« get me outta code hell

language.js « things « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/things/language.js
blob: 5573ce28ff3077577a9013b0d8db118792987c48 (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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import { Temporal, toTemporalInstant } from '@js-temporal/polyfill';

import {withAggregate} from '#aggregate';
import CacheableObject from '#cacheable-object';
import * as html from '#html';
import {empty} from '#sugar';
import {isLanguageCode} from '#validators';
import Thing from '#thing';

import {
  getExternalLinkStringOfStyleFromDescriptors,
  getExternalLinkStringsFromDescriptors,
  isExternalLinkContext,
  isExternalLinkSpec,
  isExternalLinkStyle,
} from '#external-links';

import {externalFunction, flag, name} from '#composite/wiki-properties';

export class Language extends Thing {
  static [Thing.getPropertyDescriptors] = () => ({
    // Update & expose

    // General language code. This is used to identify the language distinctly
    // from other languages (similar to how "Directory" operates in many data
    // objects).
    code: {
      flags: {update: true, expose: true},
      update: {validate: isLanguageCode},
    },

    // Human-readable name. This should be the language's own native name, not
    // localized to any other language.
    name: name(`Unnamed Language`),

    // Language code specific to JavaScript's Internationalization (Intl) API.
    // Usually this will be the same as the language's general code, but it
    // may be overridden to provide Intl constructors an alternative value.
    intlCode: {
      flags: {update: true, expose: true},
      update: {validate: isLanguageCode},
      expose: {
        dependencies: ['code'],
        transform: (intlCode, {code}) => intlCode ?? code,
      },
    },

    // Flag which represents whether or not to hide a language from general
    // access. If a language is hidden, its portion of the website will still
    // be built (with all strings localized to the language), but it won't be
    // included in controls for switching languages or the <link rel=alternate>
    // tags used for search engine optimization. This flag is intended for use
    // with languages that are currently in development and not ready for
    // formal release, or which are just kept hidden as "experimental zones"
    // for wiki development or content testing.
    hidden: flag(false),

    // Mapping of translation keys to values (strings). Generally, don't
    // access this object directly - use methods instead.
    strings: {
      flags: {update: true, expose: true},
      update: {validate: (t) => typeof t === 'object'},
      expose: {
        dependencies: ['inheritedStrings'],
        transform(strings, {inheritedStrings}) {
          if (strings || inheritedStrings) {
            return {...(inheritedStrings ?? {}), ...(strings ?? {})};
          } else {
            return null;
          }
        },
      },
    },

    // May be provided to specify "default" strings, generally (but not
    // necessarily) inherited from another Language object.
    inheritedStrings: {
      flags: {update: true, expose: true},
      update: {validate: (t) => typeof t === 'object'},
    },

    // List of descriptors for providing to external link utilities when using
    // language.formatExternalLink - refer to util/external-links.js for info.
    externalLinkSpec: {
      flags: {update: true, expose: true},
      update: {validate: isExternalLinkSpec},
    },

    // Update only

    escapeHTML: externalFunction(),

    // Expose only

    intl_date: this.#intlHelper(Intl.DateTimeFormat, {full: true}),
    intl_number: this.#intlHelper(Intl.NumberFormat),
    intl_listConjunction: this.#intlHelper(Intl.ListFormat, {type: 'conjunction'}),
    intl_listDisjunction: this.#intlHelper(Intl.ListFormat, {type: 'disjunction'}),
    intl_listUnit: this.#intlHelper(Intl.ListFormat, {type: 'unit'}),
    intl_pluralCardinal: this.#intlHelper(Intl.PluralRules, {type: 'cardinal'}),
    intl_pluralOrdinal: this.#intlHelper(Intl.PluralRules, {type: 'ordinal'}),

    validKeys: {
      flags: {expose: true},

      expose: {
        dependencies: ['strings', 'inheritedStrings'],
        compute: ({strings, inheritedStrings}) =>
          Array.from(
            new Set([
              ...Object.keys(inheritedStrings ?? {}),
              ...Object.keys(strings ?? {}),
            ])
          ),
      },
    },

    // TODO: This currently isn't used. Is it still needed?
    strings_htmlEscaped: {
      flags: {expose: true},
      expose: {
        dependencies: ['strings', 'inheritedStrings', 'escapeHTML'],
        compute({strings, inheritedStrings, escapeHTML}) {
          if (!(strings || inheritedStrings) || !escapeHTML) return null;
          const allStrings = {...inheritedStrings, ...strings};
          return Object.fromEntries(
            Object.entries(allStrings).map(([k, v]) => [k, escapeHTML(v)])
          );
        },
      },
    },
  });

  static #intlHelper (constructor, opts) {
    return {
      flags: {expose: true},
      expose: {
        dependencies: ['code', 'intlCode'],
        compute: ({code, intlCode}) => {
          const constructCode = intlCode ?? code;
          if (!constructCode) return null;
          return Reflect.construct(constructor, [constructCode, opts]);
        },
      },
    };
  }

  $(...args) {
    return this.formatString(...args);
  }

  assertIntlAvailable(property) {
    if (!this[property]) {
      throw new Error(`Intl API ${property} unavailable`);
    }
  }

  getUnitForm(value) {
    this.assertIntlAvailable('intl_pluralCardinal');
    return this.intl_pluralCardinal.select(value);
  }

  formatString(...args) {
    const hasOptions =
      typeof args.at(-1) === 'object' &&
      args.at(-1) !== null;

    const key =
      (hasOptions ? args.slice(0, -1) : args)
        .filter(Boolean)
        .join('.');

    const options =
      (hasOptions
        ? args.at(-1)
        : {});

    if (!this.strings) {
      throw new Error(`Strings unavailable`);
    }

    if (!this.validKeys.includes(key)) {
      throw new Error(`Invalid key ${key} accessed`);
    }

    // These will be filled up as we iterate over the template, slotting in
    // each option (if it's present).
    const missingOptionNames = new Set();

    // And this will have entries deleted as they're encountered in the
    // template. Leftover entries are misplaced.
    const optionsMap =
      new Map(
        Object.entries(options).map(([name, value]) => [
          name
            .replace(/[A-Z]/g, '_$&')
            .toUpperCase(),
          value,
        ]));

    const output = this.#iterateOverTemplate({
      template: this.strings[key],

      match: /{(?<name>[A-Z0-9_]+)}/g,

      insert: ({name: optionName}, canceledForming) => {
        if (optionsMap.has(optionName)) {
          let optionValue;

          // We'll only need the option's value if we're going to use it as
          // part of the formed output (see below).
          if (!canceledForming) {
            optionValue = optionsMap.get(optionName);
          }

          // But we always have to delete expected options off the provided
          // option map, since the leftovers are what will be used to tell
          // which are misplaced.
          optionsMap.delete(optionName);

          if (canceledForming) {
            return undefined;
          } else {
            return optionValue;
          }
        } else {
          // We don't need to continue forming the output if we've hit a
          // missing option name, since the end result of this formatString
          // call will be a thrown error, and formed output won't be needed.
          missingOptionNames.add(optionName);
          return undefined;
        }
      },
    });

    const misplacedOptionNames =
      Array.from(optionsMap.keys());

    withAggregate({message: `Errors in options for string "${key}"`}, ({push}) => {
      if (!empty(missingOptionNames)) {
        const names = Array.from(missingOptionNames).join(`, `);
        push(new Error(`Missing options: ${names}`));
      }

      if (!empty(misplacedOptionNames)) {
        const names = Array.from(misplacedOptionNames).join(`, `);
        push(new Error(`Unexpected options: ${names}`));
      }
    });

    return output;
  }

  #iterateOverTemplate({
    template,
    match: regexp,
    insert: insertFn,
  }) {
    const outputParts = [];

    let canceledForming = false;

    let lastIndex = 0;
    let partInProgress = '';

    for (const match of template.matchAll(regexp)) {
      const insertion =
        insertFn(match.groups, canceledForming);

      if (insertion === undefined) {
        canceledForming = true;
      }

      // Don't proceed with forming logic if the insertion function has
      // indicated that's not needed anymore - but continue iterating over
      // the rest of the template's matches, so other iteration logic (with
      // side effects) gets to process everything.
      if (canceledForming) {
        continue;
      }

      partInProgress += template.slice(lastIndex, match.index);

      // Sanitize string arguments in particular. These are taken to come from
      // (raw) data and may include special characters that aren't meant to be
      // rendered as HTML markup.
      const sanitizedInsertion =
        this.#sanitizeValueForInsertion(insertion);

      if (typeof sanitizedInsertion === 'string') {
        // Join consecutive strings together.
        partInProgress += sanitizedInsertion;
      } else if (
        sanitizedInsertion instanceof html.Tag &&
        sanitizedInsertion.contentOnly
      ) {
        // Collapse string-only tag contents onto the current string part.
        partInProgress += sanitizedInsertion.toString();
      } else {
        // Push the string part in progress, then the insertion as-is.
        outputParts.push(partInProgress);
        outputParts.push(sanitizedInsertion);
        partInProgress = '';
      }

      lastIndex = match.index + match[0].length;
    }

    if (canceledForming) {
      return undefined;
    }

    // Tack onto the final partInProgress, which may still have a value by this
    // point, if the final inserted value was a string. (Otherwise, it'll just
    // be equal to the remaining template text.)
    if (lastIndex < template.length) {
      partInProgress += template.slice(lastIndex);
    }

    if (partInProgress) {
      outputParts.push(partInProgress);
    }

    return this.#wrapSanitized(outputParts);
  }

  // Processes a value so that it's suitable to be inserted into a template.
  // For strings, this escapes HTML special characters, displaying them as-are
  // instead of representing HTML markup. For numbers and booleans, this turns
  // them into string values, so they never accidentally get caught as falsy
  // by #html stringification. Everything else - most importantly including
  // html.Tag objects - gets left as-is, preserving the value exactly as it's
  // provided.
  #sanitizeValueForInsertion(value) {
    const escapeHTML = CacheableObject.getUpdateValue(this, 'escapeHTML');
    if (!escapeHTML) {
      throw new Error(`escapeHTML unavailable`);
    }

    switch (typeof value) {
      case 'string':
        return escapeHTML(value);

      case 'number':
      case 'boolean':
        return value.toString();

      default:
        return value;
    }
  }

  // Wraps the output of a formatting function in a no-name-nor-attributes
  // HTML tag, which will indicate to other calls to formatString that this
  // content is a string *that may contain HTML* and doesn't need to
  // sanitized any further. It'll still .toString() to just the string
  // contents, if needed.
  #wrapSanitized(content) {
    return html.tags(content, {
      [html.joinChildren]: '',
      [html.noEdgeWhitespace]: true,
    });
  }

  // Similar to the above internal methods, but this one is public.
  // It should be used when embedding content that may not have previously
  // been sanitized directly into an HTML tag or template's contents.
  // The templating engine usually handles this on its own, as does passing
  // a value (sanitized or not) directly for inserting into formatting
  // functions, but if you used a custom slot validation function (for example,
  // {validate: v => v.isHTML} instead of {type: 'string'} / {type: 'html'})
  // and are embedding the contents of the slot as a direct child of another
  // tag, you should manually sanitize those contents with this function.
  sanitize(value) {
    if (typeof value === 'string') {
      return this.#wrapSanitized(this.#sanitizeValueForInsertion(value));
    } else {
      return value;
    }
  }

  formatDate(date) {
    this.assertIntlAvailable('intl_date');
    return this.intl_date.format(date);
  }

  formatDateRange(startDate, endDate) {
    this.assertIntlAvailable('intl_date');
    return this.intl_date.formatRange(startDate, endDate);
  }

  formatDateDuration({
    years: numYears = 0,
    months: numMonths = 0,
    days: numDays = 0,
    approximate = false,
  }) {
    let basis;

    const years = this.countYears(numYears, {unit: true});
    const months = this.countMonths(numMonths, {unit: true});
    const days = this.countDays(numDays, {unit: true});

    if (numYears && numMonths && numDays)
      basis = this.formatString('count.dateDuration.yearsMonthsDays', {years, months, days});
    else if (numYears && numMonths)
      basis = this.formatString('count.dateDuration.yearsMonths', {years, months});
    else if (numYears && numDays)
      basis = this.formatString('count.dateDuration.yearsDays', {years, days});
    else if (numYears)
      basis = this.formatString('count.dateDuration.years', {years});
    else if (numMonths && numDays)
      basis = this.formatString('count.dateDuration.monthsDays', {months, days});
    else if (numMonths)
      basis = this.formatString('count.dateDuration.months', {months});
    else if (numDays)
      basis = this.formatString('count.dateDuration.days', {days});
    else
      return this.formatString('count.dateDuration.zero');

    if (approximate) {
      return this.formatString('count.dateDuration.approximate', {
        duration: basis,
      });
    } else {
      return basis;
    }
  }

  formatRelativeDate(currentDate, referenceDate, {
    considerRoundingDays = false,
    approximate = true,
    absolute = true,
  } = {}) {
    const currentInstant = toTemporalInstant.apply(currentDate);
    const referenceInstant = toTemporalInstant.apply(referenceDate);

    const comparison =
      Temporal.Instant.compare(currentInstant, referenceInstant);

    if (comparison === 0) {
      return this.formatString('count.dateDuration.same');
    }

    const currentTDZ = currentInstant.toZonedDateTimeISO('Etc/UTC');
    const referenceTDZ = referenceInstant.toZonedDateTimeISO('Etc/UTC');

    const earlierTDZ = (comparison === -1 ? currentTDZ : referenceTDZ);
    const laterTDZ = (comparison === 1 ? currentTDZ : referenceTDZ);

    const {years, months, days} =
      laterTDZ.since(earlierTDZ, {
        largestUnit: 'year',
        smallestUnit:
          (considerRoundingDays
            ? (laterTDZ.since(earlierTDZ, {
                largestUnit: 'year',
                smallestUnit: 'day',
              }).years
                ? 'month'
                : 'day')
            : 'day'),
        roundingMode: 'halfCeil',
      });

    const duration =
      this.formatDateDuration({
        years, months, days,
        approximate: false,
      });

    const relative =
      this.formatString(
        'count.dateDuration',
        (approximate && (years || months || days)
          ? (comparison === -1
              ? 'approximateEarlier'
              : 'approximateLater')
          : (comparison === -1
              ? 'earlier'
              : 'later')),
        {duration});

    if (absolute) {
      return this.formatString('count.dateDuration.relativeAbsolute', {
        relative,
        absolute: this.formatDate(currentDate),
      });
    } else {
      return relative;
    }
  }

  formatDuration(secTotal, {approximate = false, unit = false} = {}) {
    if (secTotal === 0) {
      return this.formatString('count.duration.missing');
    }

    const hour = Math.floor(secTotal / 3600);
    const min = Math.floor((secTotal - hour * 3600) / 60);
    const sec = Math.floor(secTotal - hour * 3600 - min * 60);

    const pad = (val) => val.toString().padStart(2, '0');

    const stringSubkey = unit ? '.withUnit' : '';

    const duration =
      hour > 0
        ? this.formatString('count.duration.hours' + stringSubkey, {
            hours: hour,
            minutes: pad(min),
            seconds: pad(sec),
          })
        : this.formatString('count.duration.minutes' + stringSubkey, {
            minutes: min,
            seconds: pad(sec),
          });

    return approximate
      ? this.formatString('count.duration.approximate', {duration})
      : duration;
  }

  formatExternalLink(url, {
    style = 'platform',
    context = 'generic',
  } = {}) {
    if (!this.externalLinkSpec) {
      throw new TypeError(`externalLinkSpec unavailable`);
    }

    isExternalLinkContext(context);

    if (style === 'all') {
      return getExternalLinkStringsFromDescriptors(url, this.externalLinkSpec, {
        language: this,
        context,
      });
    }

    isExternalLinkStyle(style);

    const result =
      getExternalLinkStringOfStyleFromDescriptors(url, style, this.externalLinkSpec, {
        language: this,
        context,
      });

    // It's possible for there to not actually be any string available for the
    // given URL, style, and context, and we want this to be detectable via
    // html.blank().
    return result ?? html.blank();
  }

  formatIndex(value) {
    this.assertIntlAvailable('intl_pluralOrdinal');
    return this.formatString('count.index.' + this.intl_pluralOrdinal.select(value), {index: value});
  }

  formatNumber(value) {
    this.assertIntlAvailable('intl_number');
    return this.intl_number.format(value);
  }

  formatWordCount(value) {
    const num = this.formatNumber(
      value > 1000 ? Math.floor(value / 100) / 10 : value
    );

    const words =
      value > 1000
        ? this.formatString('count.words.thousand', {words: num})
        : this.formatString('count.words', {words: num});

    return this.formatString('count.words.withUnit.' + this.getUnitForm(value), {words});
  }

  #formatListHelper(array, processFn) {
    // Operate on "insertion markers" instead of the actual contents of the
    // array, because the process function (likely an Intl operation) is taken
    // to only operate on strings. We'll insert the contents of the array back
    // at these points afterwards.

    const insertionMarkers =
      Array.from(
        {length: array.length},
        (_item, index) => `<::insertion_${index}>`);

    // Basically the same insertion logic as in formatString. Like there, we
    // can't assume that insertion markers were kept in the same order as they
    // were provided, so we'll refer to the marked index. But we don't need to
    // worry about some of the indices *not* corresponding to a provided source
    // item, like we do in formatString, so that cuts out a lot of the
    // validation logic.

    return this.#iterateOverTemplate({
      template: processFn(insertionMarkers),

      match: /<::insertion_(?<index>[0-9]+)>/g,

      insert: ({index: markerIndex}) => {
        return array[markerIndex];
      },
    });
  }

  // Conjunction list: A, B, and C
  formatConjunctionList(array) {
    this.assertIntlAvailable('intl_listConjunction');
    return this.#formatListHelper(
      array,
      array => this.intl_listConjunction.format(array));
  }

  // Disjunction lists: A, B, or C
  formatDisjunctionList(array) {
    this.assertIntlAvailable('intl_listDisjunction');
    return this.#formatListHelper(
      array,
      array => this.intl_listDisjunction.format(array));
  }

  // Unit lists: A, B, C
  formatUnitList(array) {
    this.assertIntlAvailable('intl_listUnit');
    return this.#formatListHelper(
      array,
      array => this.intl_listUnit.format(array));
  }

  // Lists without separator: A B C
  formatListWithoutSeparator(array) {
    return this.#formatListHelper(
      array,
      array => array.join(' '));
  }

  // File sizes: 42.5 kB, 127.2 MB, 4.13 GB, 998.82 TB
  formatFileSize(bytes) {
    if (!bytes) return '';

    bytes = parseInt(bytes);
    if (isNaN(bytes)) return '';

    const round = (exp) => Math.round(bytes / 10 ** (exp - 1)) / 10;

    if (bytes >= 10 ** 12) {
      return this.formatString('count.fileSize.terabytes', {
        terabytes: round(12),
      });
    } else if (bytes >= 10 ** 9) {
      return this.formatString('count.fileSize.gigabytes', {
        gigabytes: round(9),
      });
    } else if (bytes >= 10 ** 6) {
      return this.formatString('count.fileSize.megabytes', {
        megabytes: round(6),
      });
    } else if (bytes >= 10 ** 3) {
      return this.formatString('count.fileSize.kilobytes', {
        kilobytes: round(3),
      });
    } else {
      return this.formatString('count.fileSize.bytes', {bytes});
    }
  }
}

const countHelper = (stringKey, optionName = stringKey) =>
  function(value, {unit = false} = {}) {
    return this.formatString(
      unit
        ? `count.${stringKey}.withUnit.` + this.getUnitForm(value)
        : `count.${stringKey}`,
      {[optionName]: this.formatNumber(value)});
  };

// TODO: These are hard-coded. Is there a better way?
Object.assign(Language.prototype, {
  countAdditionalFiles: countHelper('additionalFiles', 'files'),
  countAlbums: countHelper('albums'),
  countArtworks: countHelper('artworks'),
  countCommentaryEntries: countHelper('commentaryEntries', 'entries'),
  countContributions: countHelper('contributions'),
  countCoverArts: countHelper('coverArts'),
  countDays: countHelper('days'),
  countFlashes: countHelper('flashes'),
  countMonths: countHelper('months'),
  countTimesReferenced: countHelper('timesReferenced'),
  countTimesUsed: countHelper('timesUsed'),
  countTracks: countHelper('tracks'),
  countWeeks: countHelper('weeks'),
  countYears: countHelper('years'),
});