« get me outta code hell

image.js « dependencies « content « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/content/dependencies/image.js
blob: 93e765834b0cf7cacd475087c5f8be1e9bf543a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import {logInfo, logWarn} from '#cli';
import {empty} from '#sugar';

export default {
  extraDependencies: [
    'cachebust',
    'checkIfImagePathHasCachedThumbnails',
    'getDimensionsOfImagePath',
    'getSizeOfImagePath',
    'getThumbnailEqualOrSmaller',
    'getThumbnailsAvailableForDimensions',
    'html',
    'language',
    'missingImagePaths',
    'to',
  ],

  contentDependencies: ['generateColorStyleAttribute'],

  relations: (relation) => ({
    colorStyle:
      relation('generateColorStyleAttribute'),
  }),

  data(artTags) {
    const data = {};

    if (artTags) {
      data.contentWarnings =
        artTags
          .filter(tag => tag.isContentWarning)
          .map(tag => tag.name);
    } else {
      data.contentWarnings = null;
    }

    return data;
  },

  slots: {
    src: {type: 'string'},

    path: {
      validate: v => v.validateArrayItems(v.isString),
    },

    thumb: {type: 'string'},

    link: {
      validate: v => v.anyOf(v.isBoolean, v.isString),
      default: false,
    },

    color: {
      validate: v => v.isColor,
    },

    warnings: {
      validate: v => v.looseArrayOf(v.isString),
    },

    reveal: {type: 'boolean', default: true},
    lazy: {type: 'boolean', default: false},

    square: {type: 'boolean', default: false},

    dimensions: {
      validate: v => v.isDimensions,
    },

    alt: {type: 'string'},

    attributes: {
      type: 'attributes',
      mutable: false,
    },

    missingSourceContent: {
      type: 'html',
      mutable: false,
    },
  },

  generate(data, relations, slots, {
    cachebust,
    checkIfImagePathHasCachedThumbnails,
    getDimensionsOfImagePath,
    getSizeOfImagePath,
    getThumbnailEqualOrSmaller,
    getThumbnailsAvailableForDimensions,
    html,
    language,
    missingImagePaths,
    to,
  }) {
    let originalSrc;

    if (slots.src) {
      originalSrc = slots.src;
    } else if (!empty(slots.path)) {
      originalSrc = to(...slots.path);
    } else {
      originalSrc = '';
    }

    // TODO: This feels janky. It's necessary to deal with static content that
    // includes strings like <img src="media/misc/foo.png">, but processing the
    // src string directly when a parts-formed path *is* available seems wrong.
    // It should be possible to do urls.from(slots.path[0]).to(...slots.path),
    // for example, but will require reworking the control flow here a little.
    let mediaSrc = null;
    if (originalSrc.startsWith(to('media.root'))) {
      mediaSrc =
        originalSrc
          .slice(to('media.root').length)
          .replace(/^\//, '');
    }

    const isMissingImageFile =
      missingImagePaths.includes(mediaSrc);

    if (isMissingImageFile) {
      logInfo`No image file for ${mediaSrc} - build again for list of missing images.`;
    }

    const willLink =
      !isMissingImageFile &&
      (typeof slots.link === 'string' || slots.link);

    const contentWarnings =
      slots.warnings ??
      data.contentWarnings;

    const willReveal =
      slots.reveal &&
      originalSrc &&
      !isMissingImageFile &&
      !empty(contentWarnings);

    const hasBothDimensions =
      !!(slots.dimensions &&
         slots.dimensions[0] !== null &&
         slots.dimensions[1] !== null);

    const willSquare =
      (hasBothDimensions
        ? slots.dimensions[0] === slots.dimensions[1]
        : slots.square);

    const imgAttributes = html.attributes([
      {class: 'image'},

      slots.alt && {alt: slots.alt},

      slots.dimensions?.[0] &&
        {width: slots.dimensions[0]},

      slots.dimensions?.[1] &&
        {width: slots.dimensions[1]},
    ]);

    const isPlaceholder =
      !originalSrc || isMissingImageFile;

    if (isPlaceholder) {
      return (
        prepare(
          html.tag('div', {class: 'image-text-area'},
            (html.isBlank(slots.missingSourceContent)
              ? language.$('misc.missingImage')
              : slots.missingSourceContent)),
          'visible'));
    }

    let reveal = null;
    if (willReveal) {
      reveal = [
        html.tag('img', {class: 'reveal-symbol'},
          {src: to('shared.staticFile', 'warning.svg', cachebust)}),

        html.tag('br'),

        html.tag('span', {class: 'reveal-warnings'},
          language.$('misc.contentWarnings.warnings', {
            warnings: language.formatUnitList(contentWarnings),
          })),

        html.tag('br'),

        html.tag('span', {class: 'reveal-interaction'},
          language.$('misc.contentWarnings.reveal')),
      ];
    }

    const hasThumbnails =
      mediaSrc &&
      checkIfImagePathHasCachedThumbnails(mediaSrc);

    // Warn for images that *should* have cached thumbnail information but are
    // missing from the thumbs cache.
    if (
      slots.thumb &&
      !hasThumbnails &&
      !mediaSrc.endsWith('.gif')
    ) {
      logWarn`No thumbnail info cached: ${mediaSrc} - displaying original image here (instead of ${slots.thumb})`;
    }

    let displaySrc = originalSrc;

    // This is only distinguished from displaySrc by being a thumbnail,
    // so it won't be set if thumbnails aren't available.
    let revealSrc = null;

    // If thumbnails are available *and* being used, calculate thumbSrc,
    // and provide some attributes relevant to the large image overlay.
    if (hasThumbnails && slots.thumb) {
      const selectedSize =
        getThumbnailEqualOrSmaller(slots.thumb, mediaSrc);

      const mediaSrcJpeg =
        mediaSrc.replace(/\.(png|jpg)$/, `.${selectedSize}.jpg`);

      displaySrc =
        to('thumb.path', mediaSrcJpeg);

      if (willReveal) {
        const miniSize =
          getThumbnailEqualOrSmaller('mini', mediaSrc);

        const mediaSrcJpeg =
          mediaSrc.replace(/\.(png|jpg)$/, `.${miniSize}.jpg`);

        revealSrc =
          to('thumb.path', mediaSrcJpeg);
      }

      const dimensions = getDimensionsOfImagePath(mediaSrc);
      const availableThumbs = getThumbnailsAvailableForDimensions(dimensions);

      const [width, height] = dimensions;
      const originalLength = Math.max(width, height)

      const fileSize =
        (willLink && mediaSrc
          ? getSizeOfImagePath(mediaSrc)
          : null);

      imgAttributes.add([
        fileSize &&
          {'data-original-size': fileSize},

        originalLength &&
          {'data-original-length': originalLength},

        !empty(availableThumbs) &&
          {'data-thumbs':
              availableThumbs
                .map(([name, size]) => `${name}:${size}`)
                .join(' ')},
      ]);
    }

    if (!displaySrc) {
      return (
        prepare(
          html.tag('img', imgAttributes),
          'visible'));
    }

    const images = {
      displayStatic:
        html.tag('img',
          imgAttributes,
          {src: displaySrc}),

      displayLazy:
        slots.lazy &&
          html.tag('img',
            imgAttributes,
            {class: 'lazy', 'data-original': displaySrc}),

      revealStatic:
        revealSrc &&
          html.tag('img', {class: 'reveal-thumbnail'},
            imgAttributes,
            {src: revealSrc}),

      revealLazy:
        slots.lazy &&
        revealSrc &&
          html.tag('img', {class: 'reveal-thumbnail'},
            imgAttributes,
            {class: 'lazy', 'data-original': revealSrc}),
    };

    const staticImageContent =
      html.tags([images.displayStatic, images.revealStatic]);

    if (slots.lazy) {
      const lazyImageContent =
        html.tags([images.displayLazy, images.revealLazy]);

      return html.tags([
        html.tag('noscript',
          prepare(staticImageContent, 'visible')),

        prepare(lazyImageContent, 'hidden'),
      ]);
    } else {
      return prepare(staticImageContent, 'visible');
    }

    function prepare(imageContent, visibility) {
      let wrapped = imageContent;

      if (willReveal) {
        wrapped =
          html.tags([
            wrapped,
            html.tag('span', {class: 'reveal-text-container'},
              html.tag('span', {class: 'reveal-text'},
                reveal)),
          ]);
      }

      wrapped =
        html.tag('div', {class: 'image-inner-area'},
          wrapped);

      if (willLink) {
        wrapped =
          html.tag('a', {class: 'image-link'},
            (typeof slots.link === 'string'
              ? {href: slots.link}
              : {href: originalSrc}),

            wrapped);
      }

      wrapped =
        html.tag('div', {class: 'image-outer-area'},
          willSquare &&
            {class: 'square-content'},

          wrapped);

      wrapped =
        html.tag('div', {class: 'image-container'},
          willSquare &&
            {class: 'square'},

          typeof slots.link === 'string' &&
            {class: 'no-image-preview'},

          (isPlaceholder
            ? {class: 'placeholder-image'}
            : [
                willLink &&
                  {class: 'has-link'},

                willReveal &&
                  {class: 'reveal'},

                revealSrc &&
                  {class: 'has-reveal-thumbnail'},
              ]),

          visibility === 'hidden' &&
            {class: 'js-hide'},

          slots.color &&
            relations.colorStyle.slots({
              color: slots.color,
              context: 'image-box',
            }),

          slots.attributes,

          wrapped);

      return wrapped;
    }
  },
};