« get me outta code hell

transformContent.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/transformContent.js
blob: ddf82391357a66bd7f42fdb0a377001b67fa97ba (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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
import {bindFind} from '#find';
import {parseInput} from '#replacer';

import {Marked} from 'marked';

export const replacerSpec = {
  'album': {
    find: 'album',
    link: 'linkAlbum',
  },

  'album-commentary': {
    find: 'album',
    link: 'linkAlbumCommentary',
  },

  'album-gallery': {
    find: 'album',
    link: 'linkAlbumGallery',
  },

  'artist': {
    find: 'artist',
    link: 'linkArtist',
  },

  'artist-gallery': {
    find: 'artist',
    link: 'linkArtistGallery',
  },

  'commentary-index': {
    find: null,
    link: 'linkCommentaryIndex',
  },

  'date': {
    find: null,
    value: (ref) => new Date(ref),
    html: (date, {html, language}) =>
      html.tag('time',
        {datetime: date.toUTCString()},
        language.formatDate(date)),
  },

  'flash-index': {
    find: null,
    link: 'linkFlashIndex',
  },

  'flash': {
    find: 'flash',
    link: 'linkFlash',
    transformName(name, node, input) {
      const nextCharacter = input[node.iEnd];
      const lastCharacter = name[name.length - 1];
      if (![' ', '\n', '<'].includes(nextCharacter) && lastCharacter === '.') {
        return name.slice(0, -1);
      } else {
        return name;
      }
    },
  },

  'flash-act': {
    find: 'flashAct',
    link: 'linkFlashAct',
  },

  'group': {
    find: 'group',
    link: 'linkGroup',
  },

  'group-gallery': {
    find: 'group',
    link: 'linkGroupGallery',
  },

  'home': {
    find: null,
    link: 'linkWikiHome',
  },

  'listing-index': {
    find: null,
    link: 'linkListingIndex',
  },

  'listing': {
    find: 'listing',
    link: 'linkListing',
  },

  'media': {
    find: null,
    link: 'linkPathFromMedia',
  },

  'news-index': {
    find: null,
    link: 'linkNewsIndex',
  },

  'news-entry': {
    find: 'newsEntry',
    link: 'linkNewsEntry',
  },

  'root': {
    find: null,
    link: 'linkPathFromRoot',
  },

  'site': {
    find: null,
    link: 'linkPathFromSite',
  },

  'static': {
    find: 'staticPage',
    link: 'linkStaticPage',
  },

  'string': {
    find: null,
    value: (ref) => ref,
    html: (ref, {language, args}) => language.$(ref, args),
  },

  'tag': {
    find: 'artTag',
    link: 'linkArtTag',
  },

  'track': {
    find: 'track',
    link: 'linkTrackDynamically',
  },
};

const commonMarkedOptions = {
  headerIds: false,
  mangle: false,
};

const multilineMarked = new Marked({
  ...commonMarkedOptions,
});

const inlineMarked = new Marked({
  ...commonMarkedOptions,

  renderer: {
    paragraph(text) {
      return text;
    },
  },
});

const lyricsMarked = new Marked({
  ...commonMarkedOptions,
});

function getPlaceholder(node, content) {
  return {type: 'text', data: content.slice(node.i, node.iEnd)};
}

export default {
  contentDependencies: [
    ...(
      Object.values(replacerSpec)
        .map(description => description.link)
        .filter(Boolean)),
    'image',
  ],

  extraDependencies: ['html', 'language', 'to', 'wikiData'],

  sprawl(wikiData, content) {
    const find = bindFind(wikiData);

    const parsedNodes = parseInput(content);

    return {
      nodes: parsedNodes
        .map(node => {
          if (node.type !== 'tag') {
            return node;
          }

          const placeholder = getPlaceholder(node, content);

          const replacerKeyImplied = !node.data.replacerKey;
          const replacerKey = replacerKeyImplied ? 'track' : node.data.replacerKey.data;

          // TODO: We don't support recursive nodes like before, at the moment. Sorry!
          // const replacerValue = transformNodes(node.data.replacerValue, opts);
          const replacerValue = node.data.replacerValue[0].data;

          const spec = replacerSpec[replacerKey];

          if (!spec) {
            return placeholder;
          }

          if (spec.link) {
            let data = {link: spec.link};

            determineData: {
              // No value at all: this is an index link.
              if (!replacerValue || replacerValue === '-') {
                break determineData;
              }

              // Nothing to find: the link operates on a path or string, not a data object.
              if (!spec.find) {
                data.value = replacerValue;
                break determineData;
              }

              const thing =
                find[spec.find](
                  (replacerKeyImplied
                    ? replacerValue
                    : replacerKey + `:` + replacerValue),
                  wikiData);

              // Nothing was found: this is unexpected, so return placeholder.
              if (!thing) {
                return placeholder;
              }

              // Something was found: the link operates on that thing.
              data.thing = thing;
            }

            const {transformName} = spec;

            // TODO: Again, no recursive nodes. Sorry!
            // const enteredLabel = node.data.label && transformNode(node.data.label, opts);
            const enteredLabel = node.data.label?.data;
            const enteredHash = node.data.hash?.data;

            data.label =
              enteredLabel ??
                (transformName && data.thing.name
                  ? transformName(data.thing.name, node, content)
                  : null);

            data.hash = enteredHash ?? null;

            return {i: node.i, iEnd: node.iEnd, type: 'link', data};
          }

          // This will be another {type: 'tag'} node which gets processed in
          // generate. Extract replacerKey and replacerValue now, since it'd
          // be a pain to deal with later.
          return {
            ...node,
            data: {
              ...node.data,
              replacerKey: node.data.replacerKey.data,
              replacerValue: node.data.replacerValue[0].data,
            },
          };
        }),
    };
  },

  data(sprawl, content) {
    return {
      content,

      nodes:
        sprawl.nodes
          .map(node => {
            switch (node.type) {
              // Replace link nodes with a stub. It'll be replaced (by position)
              // with an item from relations.
              case 'link':
                return {type: 'link'};

              // Other nodes will get processed in generate.
              default:
                return node;
            }
          }),
    };
  },

  relations(relation, sprawl, content) {
    const {nodes} = sprawl;

    const relationOrPlaceholder =
      (node, name, arg) =>
        (name
          ? {
              link: relation(name, arg),
              label: node.data.label,
              hash: node.data.hash,
            }
          : getPlaceholder(node, content));

    return {
      links:
        nodes
          .filter(({type}) => type === 'link')
          .map(node => {
            const {link, thing, value} = node.data;

            if (thing) {
              return relationOrPlaceholder(node, link, thing);
            } else if (value && value !== '-') {
              return relationOrPlaceholder(node, link, value);
            } else {
              return relationOrPlaceholder(node, link);
            }
          }),

      images:
        nodes
          .filter(({type}) => type === 'image')
          .filter(({inline}) => !inline)
          .map(() => relation('image')),
    };
  },

  slots: {
    mode: {
      validate: v => v.is('inline', 'multiline', 'lyrics', 'single-link'),
      default: 'multiline',
    },

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

    thumb: {
      validate: v => v.is('small', 'medium', 'large'),
      default: 'large',
    },
  },

  generate(data, relations, slots, {html, language, to}) {
    let linkIndex = 0;
    let imageIndex = 0;

    // This array contains only straight text and link nodes, which are directly
    // representable in html (so no further processing is needed on the level of
    // individual nodes).
    const contentFromNodes =
      data.nodes.map(node => {
        switch (node.type) {
          case 'text':
            return {type: 'text', data: node.data};

          case 'image': {
            const src =
              (node.src.startsWith('media/')
                ? to('media.path', node.src.slice('media/'.length))
                : node.src);

            const {inline, link, width, height, pixelate} = node;

            if (inline) {
              return {
                type: 'image',
                inline: true,
                data:
                  html.tag('img',
                    src && {src},
                    width && {width},
                    height && {height},

                    pixelate &&
                      {class: 'pixelate'}),
              };
            }

            const image = relations.images[imageIndex++];

            return {
              type: 'image',
              inline: false,
              data:
                html.tag('div', {class: 'content-image-container'},
                  image.slots({
                    src,

                    link: link ?? true,
                    width: width ?? null,
                    height: height ?? null,
                    thumb: slots.thumb,

                    attributes: [
                      {class: 'content-image'},

                      pixelate &&
                        {class: 'pixelate'},
                    ],
                  })),
            };
          }

          case 'link': {
            const linkNode = relations.links[linkIndex++];
            if (linkNode.type === 'text') {
              return {type: 'text', data: linkNode.data};
            }

            const {link, label, hash} = linkNode;

            // These are removed from the typical combined slots({})-style
            // because we don't want to override slots that were already set
            // by something that's wrapping the linkTemplate or linkThing
            // template.
            if (label) link.setSlot('content', label);
            if (hash) link.setSlot('hash', hash);

            // TODO: This is obviously hacky.
            let hasPreferShortNameSlot;
            try {
              link.getSlotDescription('preferShortName');
              hasPreferShortNameSlot = true;
            } catch (error) {
              hasPreferShortNameSlot = false;
            }

            if (hasPreferShortNameSlot) {
              link.setSlot('preferShortName', slots.preferShortLinkNames);
            }

            return {type: 'link', data: link};
          }

          case 'tag': {
            const {replacerKey, replacerValue} = node.data;

            const spec = replacerSpec[replacerKey];

            if (!spec) {
              return getPlaceholder(node, data.content);
            }

            const {value: valueFn, html: htmlFn} = spec;

            const value =
              (valueFn
                ? valueFn(replacerValue)
                : replacerValue);

            const contents =
              (htmlFn
                ? htmlFn(value, {html, language})
                : value);

            return {type: 'text', data: contents.toString()};
          }

          default:
            return getPlaceholder(node, data.content);
        }
      });

    // In single-link mode, return the link node exactly as is - exposing
    // access to its slots.

    if (slots.mode === 'single-link') {
      const link = contentFromNodes.find(node => node.type === 'link');

      if (!link) {
        return html.blank();
      }

      return link.data;
    }

    // Content always goes through marked (i.e. parsing as Markdown).
    // This does require some attention to detail, mostly to do with line
    // breaks (in multiline mode) and extracting/re-inserting non-text nodes.

    // The content of non-text nodes can end up getting mangled by marked.
    // To avoid this, we replace them with mundane placeholders, then
    // reinsert the content in the correct positions. This also avoids
    // having to stringify tag content within this generate() function.

    const extractNonTextNodes = ({
      getTextNodeContents = node => node.data,
    } = {}) =>
      contentFromNodes
        .map((node, index) => {
          if (node.type === 'text') {
            return getTextNodeContents(node, index);
          }

          const attributes = html.attributes({
            class: 'INSERT-NON-TEXT',
            'data-type': node.type,
          });

          if (node.type === 'image') {
            attributes.set('data-inline', node.inline);
          }

          return `<span ${attributes}>${index}</span>`;
        })
        .join('');

    const reinsertNonTextNodes = (markedOutput) => {
      markedOutput = markedOutput.trim();

      const tags = [];
      const regexp = /<span class="INSERT-NON-TEXT" (.*?)>([0-9]+?)<\/span>/g;

      let deleteParagraph = false;

      const addText = (text) => {
        if (deleteParagraph) {
          text = text.replace(/^<\/p>/, '');
          deleteParagraph = false;
        }

        tags.push(text);
      };

      let match = null, parseFrom = 0;
      while (match = regexp.exec(markedOutput)) {
        addText(markedOutput.slice(parseFrom, match.index));
        parseFrom = match.index + match[0].length;

        const attributes = html.parseAttributes(match[1]);

        // Images that were all on their own line need to be removed from
        // the surrounding <p> tag that marked generates. The HTML parser
        // treats a <div> that starts inside a <p> as a Crocker-class
        // misgiving, and will treat you very badly if you feed it that.
        if (attributes.get('data-type') === 'image') {
          if (!attributes.get('data-inline')) {
            tags[tags.length - 1] = tags[tags.length - 1].replace(/<p>$/, '');
            deleteParagraph = true;
          }
        }

        const nonTextNodeIndex = match[2];
        tags.push(contentFromNodes[nonTextNodeIndex].data);
      }

      if (parseFrom !== markedOutput.length) {
        addText(markedOutput.slice(parseFrom));
      }

      return html.tags(tags, {[html.joinChildren]: ''});
    };

    if (slots.mode === 'inline') {
      const markedInput =
        extractNonTextNodes();

      const markedOutput =
        inlineMarked.parse(markedInput);

      return reinsertNonTextNodes(markedOutput);
    }

    // This is separated into its own function just since we're gonna reuse
    // it in a minute if everything goes to heck in lyrics mode.
    const transformMultiline = () => {
      const markedInput =
        extractNonTextNodes()
          // Compress multiple line breaks into single line breaks,
          // except when they're preceding or following indented
          // text (by at least two spaces).
          .replace(/(?<!  .*)\n{2,}(?!^  )/gm, '\n') /* eslint-disable-line no-regex-spaces */
          // Expand line breaks which don't follow a list, quote,
          // or <br> / "  ", and which don't precede or follow
          // indented text (by at least two spaces).
          .replace(/(?<!^ *-.*|^>.*|^  .*\n*|  $|<br>$)\n+(?!  |\n)/gm, '\n\n') /* eslint-disable-line no-regex-spaces */
          // Expand line breaks which are at the end of a list.
          .replace(/(?<=^ *-.*)\n+(?!^ *-)/gm, '\n\n')
          // Expand line breaks which are at the end of a quote.
          .replace(/(?<=^>.*)\n+(?!^>)/gm, '\n\n');

      const markedOutput =
        multilineMarked.parse(markedInput);

      return reinsertNonTextNodes(markedOutput);
    }

    if (slots.mode === 'multiline') {
      return transformMultiline();
    }

    // Lyrics mode goes through marked too, but line breaks are processed
    // differently. Instead of having each line get its own paragraph,
    // "adjacent" lines are joined together (with blank lines separating
    // each verse/paragraph).

    if (slots.mode === 'lyrics') {
      // If it looks like old data, using <br> instead of bunched together
      // lines... then oh god... just use transformMultiline. Perishes.
      if (
        contentFromNodes.some(node =>
          node.type === 'text' &&
          node.data.includes('<br'))
      ) {
        return transformMultiline();
      }

      const markedInput =
        extractNonTextNodes({
          getTextNodeContents(node, index) {
            // First, replace line breaks that follow text content with
            // <br> tags.
            let content = node.data.replace(/(?!^)\n/gm, '<br>\n');

            // Scrap line breaks that are at the end of a verse.
            content = content.replace(/<br>$(?=\n\n)/gm, '');

            // If the node started with a line break, and it's not the
            // very first node, then whatever came before it was inline.
            // (This is an assumption based on text links being basically
            // the only tag that shows up in lyrics.) Since this text is
            // following content that was already inline, restore that
            // initial line break.
            if (node.data[0] === '\n' && index !== 0) {
              content = '<br>' + content;
            }

            return content;
          },
        });

      const markedOutput =
        lyricsMarked.parse(markedInput);

      return reinsertNonTextNodes(markedOutput);
    }
  },
}