summaryrefslogtreecommitdiffstats
path: root/toolkit/components/translations/content/translations.mjs
blob: 478f854bb58341b9df798a011a4b0bbf4c0c366b (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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// The following globals are injected via the AboutTranslationsChild actor.
// translations.mjs is running in an unprivileged context, and these injected functions
// allow for the page to get access to additional privileged features.

/* global AT_getSupportedLanguages, AT_log, AT_getScriptDirection,
   AT_logError, AT_createTranslationsPort, AT_isHtmlTranslation,
   AT_isTranslationEngineSupported, AT_identifyLanguage */

// Allow tests to override this value so that they can run faster.
// This is the delay in milliseconds.
window.DEBOUNCE_DELAY = 200;
// Allow tests to test the debounce behavior by counting debounce runs.
window.DEBOUNCE_RUN_COUNT = 0;

/**
 * @typedef {import("../translations").SupportedLanguages} SupportedLanguages
 */

/**
 * The model and controller for initializing about:translations.
 */
class TranslationsState {
  /**
   * This class is responsible for all UI updated.
   *
   * @type {TranslationsUI}
   */
  ui;

  /**
   * The language to translate from, in the form of a BCP 47 language tag,
   * e.g. "en" or "fr".
   *
   * @type {string}
   */
  fromLanguage = "";

  /**
   * The language to translate to, in the form of a BCP 47 language tag,
   * e.g. "en" or "fr".
   *
   * @type {string}
   */
  toLanguage = "";

  /**
   * The message to translate, cached so that it can be determined if the text
   * needs to be re-translated.
   *
   * @type {string}
   */
  messageToTranslate = "";

  /**
   * Only send one translation in at a time to the worker.
   *
   * @type {Promise<string[]>}
   */
  translationRequest = Promise.resolve([]);

  /**
   * The translator is only valid for a single language pair, and needs
   * to be recreated if the language pair changes.
   *
   * @type {null | Promise<Translator>}
   */
  translator = null;

  /**
   * @param {boolean} isSupported
   */
  constructor(isSupported) {
    /**
     * Is the engine supported by the device?
     *
     * @type {boolean}
     */
    this.isTranslationEngineSupported = isSupported;

    /**
     * @type {SupportedLanguages}
     */
    this.supportedLanguages = isSupported
      ? AT_getSupportedLanguages()
      : Promise.resolve([]);

    this.ui = new TranslationsUI(this);
    this.ui.setup();

    // Set the UI as ready after all of the state promises have settled.
    this.supportedLanguages
      .then(() => {
        this.ui.setAsReady();
      })
      .catch(error => {
        AT_logError("Failed to load the supported languages", error);
      });
  }

  /**
   * Identifies the human language in which the message is written and returns
   * the BCP 47 language tag of the language it is determined to be.
   *
   * e.g. "en" for English.
   *
   * @param {string} message
   */
  async identifyLanguage(message) {
    const start = performance.now();
    const { langTag, confidence } = await AT_identifyLanguage(message);
    const duration = performance.now() - start;
    AT_log(
      `[ ${langTag}(${(confidence * 100).toFixed(2)}%) ]`,
      `Source language identified in ${duration / 1000} seconds`
    );
    return langTag;
  }

  /**
   * Only request a translation when it's ready.
   */
  maybeRequestTranslation = debounce({
    /**
     * Debounce the translation requests so that the worker doesn't fire for every
     * single keyboard input, but instead the keyboard events are ignored until
     * there is a short break, or enough events have happened that it's worth sending
     * in a new translation request.
     */
    onDebounce: async () => {
      // The contents of "this" can change between async steps, store a local variable
      // binding of these values.
      const {
        fromLanguage,
        toLanguage,
        messageToTranslate,
        translator: translatorPromise,
      } = this;

      if (!this.isTranslationEngineSupported) {
        // Never translate when the engine isn't supported.
        return;
      }

      if (
        !fromLanguage ||
        !toLanguage ||
        !messageToTranslate ||
        !translatorPromise
      ) {
        // Not everything is set for translation.
        this.ui.updateTranslation("");
        return;
      }

      const [translator] = await Promise.all([
        // Ensure the engine is ready to go.
        translatorPromise,
        // Ensure the previous translation has finished so that only the latest
        // translation goes through.
        this.translationRequest,
      ]);

      if (
        // Check if the current configuration has changed and if this is stale. If so
        // then skip this request, as there is already a newer request with more up to
        // date information.
        this.translator !== translatorPromise ||
        this.fromLanguage !== fromLanguage ||
        this.toLanguage !== toLanguage ||
        this.messageToTranslate !== messageToTranslate
      ) {
        return;
      }

      const start = performance.now();

      this.translationRequest = translator.translate(messageToTranslate);
      const translation = await this.translationRequest;

      // The measure events will show up in the Firefox Profiler.
      performance.measure(
        `Translations: Translate "${this.fromLanguage}" to "${this.toLanguage}" with ${messageToTranslate.length} characters.`,
        {
          start,
          end: performance.now(),
        }
      );

      this.ui.updateTranslation(translation);
      const duration = performance.now() - start;
      AT_log(`Translation done in ${duration / 1000} seconds`);
    },

    // Mark the events so that they show up in the Firefox Profiler. This makes it handy
    // to visualize the debouncing behavior.
    doEveryTime: () => {
      performance.mark(
        `Translations: input changed to ${this.messageToTranslate.length} characters`
      );
    },
  });

  /**
   * Any time a language pair is changed, a new Translator needs to be created.
   */
  async maybeCreateNewTranslator() {
    // If we may need to re-building the worker, the old translation is no longer valid.
    this.ui.updateTranslation("");

    // These are cases in which it wouldn't make sense or be possible to load any translations models.
    if (
      // If fromLanguage or toLanguage are unpopulated we cannot load anything.
      !this.fromLanguage ||
      !this.toLanguage ||
      // If fromLanguage's value is "detect", rather than a BCP 47 language tag, then no language
      // has been detected yet.
      this.fromLanguage === "detect" ||
      // If fromLanguage and toLanguage are the same, this means that the detected language
      // is the same as the toLanguage, and we do not want to translate from one language to itself.
      this.fromLanguage === this.toLanguage
    ) {
      if (this.translator) {
        // The engine is no longer needed.
        this.translator.then(translator => translator.destroy());
        this.translator = null;
      }
      return;
    }

    const start = performance.now();
    AT_log(
      `Creating a new translator for "${this.fromLanguage}" to "${this.toLanguage}"`
    );

    this.translator = Translator.create(this.fromLanguage, this.toLanguage);
    this.maybeRequestTranslation();

    try {
      await this.translator;
      const duration = performance.now() - start;
      // Signal to tests that the translator was created so they can exit.
      window.postMessage("translator-ready");
      AT_log(`Created a new Translator in ${duration / 1000} seconds`);
    } catch (error) {
      this.ui.showInfo("about-translations-engine-error");
      AT_logError("Failed to get the Translations worker", error);
    }
  }

  /**
   * Updates the fromLanguage to match the detected language only if the
   * about-translations-detect option is selected in the language-from dropdown.
   *
   * If the new fromLanguage is different than the previous fromLanguage this
   * may update the UI to display the new language and may rebuild the translations
   * worker if there is a valid selected target language.
   */
  async maybeUpdateDetectedLanguage() {
    if (!this.ui.detectOptionIsSelected() || this.messageToTranslate === "") {
      // If we are not detecting languages or if the message has been cleared
      // we should ensure that the UI is not displaying a detected language
      // and there is no need to run any language detection.
      this.ui.setDetectOptionTextContent("");
      return;
    }

    const [langTag, supportedLanguages] = await Promise.all([
      this.identifyLanguage(this.messageToTranslate),
      this.supportedLanguages,
    ]);

    // Only update the language if the detected language matches
    // one of our supported languages.
    const entry = supportedLanguages.fromLanguages.find(
      ({ langTag: existingTag }) => existingTag === langTag
    );
    if (entry) {
      const { displayName } = entry;
      await this.setFromLanguage(langTag);
      this.ui.setDetectOptionTextContent(displayName);
    }
  }

  /**
   * @param {string} lang
   */
  async setFromLanguage(lang) {
    if (lang !== this.fromLanguage) {
      this.fromLanguage = lang;
      await this.maybeCreateNewTranslator();
    }
  }

  /**
   * @param {string} lang
   */
  setToLanguage(lang) {
    if (lang !== this.toLanguage) {
      this.toLanguage = lang;
      this.maybeCreateNewTranslator();
    }
  }

  /**
   * @param {string} message
   */
  async setMessageToTranslate(message) {
    if (message !== this.messageToTranslate) {
      this.messageToTranslate = message;
      await this.maybeUpdateDetectedLanguage();
      this.maybeRequestTranslation();
    }
  }
}

/**
 *
 */
class TranslationsUI {
  /** @type {HTMLSelectElement} */
  languageFrom = document.getElementById("language-from");
  /** @type {HTMLSelectElement} */
  languageTo = document.getElementById("language-to");
  /** @type {HTMLTextAreaElement} */
  translationFrom = document.getElementById("translation-from");
  /** @type {HTMLDivElement} */
  translationTo = document.getElementById("translation-to");
  /** @type {HTMLDivElement} */
  translationToBlank = document.getElementById("translation-to-blank");
  /** @type {HTMLDivElement} */
  translationInfo = document.getElementById("translation-info");
  /** @type {HTMLDivElement} */
  translationInfoMessage = document.getElementById("translation-info-message");
  /** @type {TranslationsState} */
  state;

  /**
   * The detect-language option element. We want to maintain a handle to this so that
   * we can dynamically update its display text to include the detected language.
   *
   * @type {HTMLOptionElement}
   */
  #detectOption;

  /**
   * @param {TranslationsState} state
   */
  constructor(state) {
    this.state = state;
    this.translationTo.style.visibility = "visible";
    this.#detectOption = document.querySelector('option[value="detect"]');
  }

  /**
   * Do the initial setup.
   */
  setup() {
    if (!this.state.isTranslationEngineSupported) {
      this.showInfo("about-translations-no-support");
      this.disableUI();
      return;
    }
    this.setupDropdowns();
    this.setupTextarea();
  }

  /**
   * Signals that the UI is ready, for tests.
   */
  setAsReady() {
    document.body.setAttribute("ready", "");
  }

  /**
   * Once the models have been synced from remote settings, populate them with the display
   * names of the languages.
   */
  async setupDropdowns() {
    const supportedLanguages = await this.state.supportedLanguages;

    // Update the DOM elements with the display names.
    for (const { langTag, displayName } of supportedLanguages.toLanguages) {
      const option = document.createElement("option");
      option.value = langTag;
      option.text = displayName;
      this.languageTo.add(option);
    }

    for (const { langTag, displayName } of supportedLanguages.fromLanguages) {
      const option = document.createElement("option");
      option.value = langTag;
      option.text = displayName;
      this.languageFrom.add(option);
    }

    // Enable the controls.
    this.languageFrom.disabled = false;
    this.languageTo.disabled = false;

    // Focus the language dropdowns if they are empty.
    if (this.languageFrom.value == "") {
      this.languageFrom.focus();
    } else if (this.languageTo.value == "") {
      this.languageTo.focus();
    }

    this.state.setFromLanguage(this.languageFrom.value);
    this.state.setToLanguage(this.languageTo.value);
    this.updateOnLanguageChange();

    this.languageFrom.addEventListener("input", () => {
      this.state.setFromLanguage(this.languageFrom.value);
      this.updateOnLanguageChange();
    });

    this.languageTo.addEventListener("input", () => {
      this.state.setToLanguage(this.languageTo.value);
      this.updateOnLanguageChange();
      this.translationTo.setAttribute("lang", this.languageTo.value);
    });
  }

  /**
   * Show an info message to the user.
   *
   * @param {string} l10nId
   */
  showInfo(l10nId) {
    document.l10n.setAttributes(this.translationInfoMessage, l10nId);
    this.translationInfo.style.display = "flex";
  }

  /**
   * Hides the info UI.
   */
  hideInfo() {
    this.translationInfo.style.display = "none";
  }

  /**
   * Returns true if about-translations-detect is the currently
   * selected option in the language-from dropdown, otherwise false.
   *
   * @returns {boolean}
   */
  detectOptionIsSelected() {
    return this.languageFrom.value === "detect";
  }

  /**
   * Sets the textContent of the about-translations-detect option in the
   * language-from dropdown to include the detected language's display name.
   *
   * @param {string} displayName
   */
  setDetectOptionTextContent(displayName) {
    // Set the text to the fluent value that takes an arg to display the language name.
    if (displayName) {
      document.l10n.setAttributes(
        this.#detectOption,
        "about-translations-detect-lang",
        { language: displayName }
      );
    } else {
      // Reset the text to the fluent value that does not display any language name.
      document.l10n.setAttributes(
        this.#detectOption,
        "about-translations-detect"
      );
    }
  }

  /**
   * React to language changes.
   */
  updateOnLanguageChange() {
    this.#updateDropdownLanguages();
    this.#updateMessageDirections();
  }

  /**
   * You cant translate from one language to another language. Hide the options
   * if this is the case.
   */
  #updateDropdownLanguages() {
    for (const option of this.languageFrom.options) {
      option.hidden = false;
    }
    for (const option of this.languageTo.options) {
      option.hidden = false;
    }
    if (this.state.toLanguage) {
      const option = this.languageFrom.querySelector(
        `[value=${this.state.toLanguage}]`
      );
      if (option) {
        option.hidden = true;
      }
    }
    if (this.state.fromLanguage) {
      const option = this.languageTo.querySelector(
        `[value=${this.state.fromLanguage}]`
      );
      if (option) {
        option.hidden = true;
      }
    }
    this.state.maybeUpdateDetectedLanguage();
  }

  /**
   * Define the direction of the language message text, otherwise it might not display
   * correctly. For instance English in an RTL UI would display incorrectly like so:
   *
   * LTR text in LTR UI:
   *
   * ┌──────────────────────────────────────────────┐
   * │ This is in English.                          │
   * └──────────────────────────────────────────────┘
   *
   * LTR text in RTL UI:
   * ┌──────────────────────────────────────────────┐
   * │                          .This is in English │
   * └──────────────────────────────────────────────┘
   *
   * LTR text in RTL UI, but in an LTR container:
   * ┌──────────────────────────────────────────────┐
   * │ This is in English.                          │
   * └──────────────────────────────────────────────┘
   *
   * The effects are similar, but reversed for RTL text in an LTR UI.
   */
  #updateMessageDirections() {
    if (this.state.toLanguage) {
      this.translationTo.setAttribute(
        "dir",
        AT_getScriptDirection(this.state.toLanguage)
      );
    } else {
      this.translationTo.removeAttribute("dir");
    }
    if (this.state.fromLanguage) {
      this.translationFrom.setAttribute(
        "dir",
        AT_getScriptDirection(this.state.fromLanguage)
      );
    } else {
      this.translationFrom.removeAttribute("dir");
    }
  }

  setupTextarea() {
    this.state.setMessageToTranslate(this.translationFrom.value);
    this.translationFrom.addEventListener("input", () => {
      this.state.setMessageToTranslate(this.translationFrom.value);
    });
  }

  disableUI() {
    this.translationFrom.disabled = true;
    this.languageFrom.disabled = true;
    this.languageTo.disabled = true;
  }

  /**
   * @param {string} message
   */
  updateTranslation(message) {
    this.translationTo.innerText = message;
    if (message) {
      this.translationTo.style.visibility = "visible";
      this.translationToBlank.style.visibility = "hidden";
      this.hideInfo();
    } else {
      this.translationTo.style.visibility = "hidden";
      this.translationToBlank.style.visibility = "visible";
    }
  }
}

/**
 * Listen for events coming from the AboutTranslations actor.
 */
window.addEventListener("AboutTranslationsChromeToContent", ({ detail }) => {
  switch (detail.type) {
    case "enable": {
      // While the feature is in development, hide the feature behind a pref. See the
      // "browser.translations.enable" pref in modules/libpref/init/all.js and Bug 971044
      // for the status of enabling this project.
      if (window.translationsState) {
        throw new Error("about:translations was already initialized.");
      }
      AT_isTranslationEngineSupported().then(isSupported => {
        window.translationsState = new TranslationsState(isSupported);
      });
      document.body.style.visibility = "visible";
      break;
    }
    default:
      throw new Error("Unknown AboutTranslationsChromeToContent event.");
  }
});

/**
 * Debounce a function so that it is only called after some wait time with no activity.
 * This is good for grouping text entry via keyboard.
 *
 * @param {object} settings
 * @param {Function} settings.onDebounce
 * @param {Function} settings.doEveryTime
 * @returns {Function}
 */
function debounce({ onDebounce, doEveryTime }) {
  /** @type {number | null} */
  let timeoutId = null;
  let lastDispatch = null;

  return (...args) => {
    doEveryTime(...args);

    const now = Date.now();
    if (lastDispatch === null) {
      // This is the first call to the function.
      lastDispatch = now;
    }

    const timeLeft = lastDispatch + window.DEBOUNCE_DELAY - now;

    // Always discard the old timeout, either the function will run, or a new
    // timer will be scheduled.
    clearTimeout(timeoutId);

    if (timeLeft <= 0) {
      // It's been long enough to go ahead and call the function.
      timeoutId = null;
      lastDispatch = null;
      window.DEBOUNCE_RUN_COUNT += 1;
      onDebounce(...args);
      return;
    }

    // Re-set the timeout with the current time left.
    clearTimeout(timeoutId);

    timeoutId = setTimeout(() => {
      // Timeout ended, call the function.
      timeoutId = null;
      lastDispatch = null;
      window.DEBOUNCE_RUN_COUNT += 1;
      onDebounce(...args);
    }, timeLeft);
  };
}

/**
 * Perform transalations over a `MessagePort`. This class manages the communications to
 * the translations engine.
 */
class Translator {
  /**
   * @type {MessagePort}
   */
  #port;

  /**
   * An id for each message sent. This is used to match up the request and response.
   */
  #nextMessageId = 0;

  /**
   * Tie together a message id to a resolved response.
   *
   * @type {Map<number, TranslationRequest>}
   */
  #requests = new Map();

  engineStatus = "initializing";

  /**
   * @param {MessagePort} port
   */
  constructor(port) {
    this.#port = port;

    // Create a promise that will be resolved when the engine is ready.
    let engineLoaded;
    let engineFailed;
    this.ready = new Promise((resolve, reject) => {
      engineLoaded = resolve;
      engineFailed = reject;
    });

    // Match up a response on the port to message that was sent.
    port.onmessage = ({ data }) => {
      switch (data.type) {
        case "TranslationsPort:TranslationResponse": {
          const { targetText, messageId } = data;
          // A request may not match match a messageId if there is a race during the pausing
          // and discarding of the queue.
          this.#requests.get(messageId)?.resolve(targetText);
          break;
        }
        case "TranslationsPort:GetEngineStatusResponse": {
          if (data.status === "ready") {
            engineLoaded();
          } else {
            engineFailed();
          }
          break;
        }
        default:
          AT_logError("Unknown translations port message: " + data.type);
          break;
      }
    };

    port.postMessage({ type: "TranslationsPort:GetEngineStatusRequest" });
  }

  /**
   * Opens up a port and creates a new translator.
   *
   * @param {string} fromLanguage
   * @param {string} toLanguage
   * @returns {Promise<Translator>}
   */
  static create(fromLanguage, toLanguage) {
    return new Promise((resolve, reject) => {
      AT_createTranslationsPort(fromLanguage, toLanguage);

      function getResponse({ data }) {
        if (
          data.type == "GetTranslationsPort" &&
          fromLanguage === data.fromLanguage &&
          toLanguage === data.toLanguage
        ) {
          // The response matches, resolve the port.
          const translator = new Translator(data.port);

          // Resolve the translator once it is ready, or propagate the rejection
          // if it failed.
          translator.ready.then(() => resolve(translator), reject);
          window.removeEventListener("message", getResponse);
        }
      }

      // Listen for a response for the message port.
      window.addEventListener("message", getResponse);
    });
  }

  /**
   * Send a request to translate text to the Translations Engine. If it returns `null`
   * then the request is stale. A rejection means there was an error in the translation.
   * This request may be queued.
   *
   * @param {string} sourceText
   * @returns {Promise<string>}
   */
  translate(sourceText) {
    return new Promise((resolve, reject) => {
      const messageId = this.#nextMessageId++;
      // Store the "resolve" for the promise. It will be matched back up with the
      // `messageId` in #handlePortMessage.
      const isHTML = AT_isHtmlTranslation();
      this.#requests.set(messageId, {
        sourceText,
        isHTML,
        resolve,
        reject,
      });
      this.#port.postMessage({
        type: "TranslationsPort:TranslationRequest",
        messageId,
        sourceText,
        isHTML,
      });
    });
  }

  /**
   * Close the port and remove any pending or queued requests.
   */
  destroy() {
    this.#port.close();
  }
}