•
16 min read

Machinery Autocomplete in Pontoon

Table of Contents

Pontoon’s translation editor completes a translation as you type, using the Machinery suggestions for the current string (translation memory and machine translation). The completion is drawn in gray after the cursor. Tab accepts one word of it and Esc hides it. In the code, the gray text is called ghost text.

typed    Firefox non r▏iesce
Tab      Firefox non riesce▏ a
Tab      Firefox non riesce a▏ trovare

The suggestion in this example is Italian for “Firefox can’t find the server”. Everything after the ▏ cursor is gray.

This post walks through the code in the order it runs. Nearly all of it lives in two files:

  • ghostText.ts has the matching algorithm and the CodeMirror extension that draws the gray text and handles Tab and Esc.
  • editFieldExtensions.ts has the React hook that picks the candidate strings, and the editor’s keymap.

The snippets are copied from those files. Where comments were added for this post, the text says so.

How the pieces fit

React                                    CodeMirror

MachineryTranslations (context)
    │
    ▼
useGhostTextCandidates(fieldId)
    │  string[]
    ▼
EditField ── setGhostTextCandidates ───▶ ghostTextState (state field)
                                         { segmenter, candidates, hidden }
                                               │
                                               ▼
                                         ghostTextPlugin (view plugin)
                                           getGhostText:  show anything?
                                           findGhostText: what to show
                                               │
                                               ▼
                                         GhostTextWidget: the gray <span>

                                         keymap: Tab → acceptGhostText
                                                 Esc → dismissGhostText

The candidate strings live on the React side, and they change while the page is open because each Machinery source responds on its own schedule. The editor is CodeMirror 6, which keeps its own immutable state and only changes through transactions. The two sides meet at one point: React sends the candidates into the editor as a state effect. From there, a state field stores them, a view plugin decides on every update what gray text to show, and a widget draws it. The decision itself is findGhostText, a pure function of the text so far, the candidates and a word segmenter.

useGhostTextCandidates: where the candidates come from

export function useGhostTextCandidates(fieldId?: string): readonly string[] {
  const enabled = useAppSelector(
    (state) => state[USER].settings.machineryAutocomplete,
  );
  const { composed, translations } = useContext(MachineryTranslations);
  const { query } = useContext(SearchData);
  const { sourceView } = useContext(EditorData);
  const sourceEntry = useEntityEntry();
  return useMemo(() => {
    if (!enabled || query || sourceView) {
      return [];
    }
    if (fieldId === undefined) {
      return translations.map((tx) => tx.translation);
    }
    return composed.flatMap(({ value, properties }) => {
      const { format, id } = sourceEntry;
      const entry = createMessageEntry(format, id, value, properties);
      const field = editMessageEntry(sourceEntry, entry).find(
        (field) => field.id === fieldId,
      );
      return field?.handle.current.value ? [field.handle.current.value] : [];
    });
  }, [
    composed,
    enabled,
    fieldId,
    query,
    sourceEntry,
    sourceView,
    translations,
  ]);
}

Each editor field calls this hook and gets back the strings it can complete from.

The first if is the feature’s off switch. It returns no candidates when:

  • the user has turned the setting off (it’s on by default),
  • a Concordance search is active (query), because the Machinery panel is then showing results for other strings,
  • the editor is in Advanced FTL mode (sourceView), where the field holds raw Fluent syntax and inserting a plain-text suggestion could produce broken FTL.

A simple string has a single field with no fieldId, and every Machinery translation is a candidate. They arrive sorted by quality, which decides ties later on.

A string with several fields, like a Fluent message with attributes or plural variants, uses composed suggestions instead. A composed suggestion is a whole-message translation. createMessageEntry turns it into the same structure as the source string, editMessageEntry splits that into editor fields, and the field with this field’s id becomes the candidate. A .label field therefore only completes from .label text. In locales without Google Translate, composed suggestions come only from translation memory, which has nothing for a new string, so new plural and attribute strings currently get no candidates.

The result is wrapped in useMemo so the array only changes identity when its inputs change. That matters because the array is the dependency of the effect that sends it to the editor.

EditField: connecting the hook to the editor

const ghostTextCandidates = useGhostTextCandidates(fieldId);

// … inside initView, when the EditorView is created:
if (readOnly) {
  extensions.push(
    EditorState.readOnly.of(true),
    EditorView.editable.of(false),
  );
} else {
  extensions.push(ghostText(locale.code));
  // …
}

When a field’s EditorView is created, editable fields get the extension, configured with the locale. Read-only fields don’t, so no gray text is ever computed for them.

useEffect(() => {
  view?.dispatch({
    effects: setGhostTextCandidates.of(ghostTextCandidates),
  });
}, [view, ghostTextCandidates]);

The view is created once, when the field mounts, so later changes to props or context don’t reach it on their own. Recreating it for every new suggestion would reset the cursor and the undo history in the middle of typing. Instead, each new candidate list is dispatched as a transaction that carries only an effect and leaves the document alone.

ghostText(): setting up the extension

export function ghostText(locale: string): Extension {
  const segmenter = getWordSegmenter(locale);
  return segmenter
    ? [
        ghostTextState.init(() => ({
          segmenter,
          candidates: [],
          hidden: false,
        })),
        ghostTextPlugin,
      ]
    : [];
}

function getWordSegmenter(locale: string) {
  if (typeof Intl.Segmenter !== 'function') {
    return null;
  }
  try {
    return new Intl.Segmenter(locale, { granularity: 'word' });
  } catch {
    return new Intl.Segmenter(undefined, { granularity: 'word' });
  }
}

ghostText() returns the two parts of the extension: the state field with its starting value, and the view plugin. It builds one Intl.Segmenter for the locale up front, so the segmenter isn’t recreated on every keystroke. In browsers without Intl.Segmenter, getWordSegmenter returns null, the extension is an empty array, and the feature is simply absent. If the locale code isn’t a valid language tag, the constructor throws and the browser’s default locale is used instead.

ghostTextState: what the editor remembers

export const setGhostTextCandidates = StateEffect.define<readonly string[]>();

const dismissGhostTextEffect = StateEffect.define<null>();

type GhostTextState = {
  segmenter: Intl.Segmenter;
  candidates: readonly string[];
  hidden: boolean;
};

const ghostTextState = StateField.define<GhostTextState | null>({
  create: () => null,
  update(value, tr) {
    if (!value) {
      return value;
    }
    let next = value;
    if (tr.docChanged || tr.selection) {
      const hidden = tr.isUserEvent('delete');
      if (hidden !== next.hidden) {
        next = { ...next, hidden };
      }
    }
    for (const effect of tr.effects) {
      if (effect.is(setGhostTextCandidates)) {
        next = { ...next, candidates: effect.value };
      } else if (effect.is(dismissGhostTextEffect)) {
        next = { ...next, hidden: true };
      }
    }
    return next;
  },
});

The state field holds the segmenter, the current candidates and a hidden flag. Its default value from create is null, and ghostText() replaces it with the real starting value through ghostTextState.init().

update runs for every transaction and returns the next value:

  • When the document or the selection changed, hidden becomes tr.isUserEvent('delete'). User events are dotted names and isUserEvent matches by prefix, so this is true for Backspace (delete.backward), Delete (delete.forward) and other deletions, and false for typing, pasting or moving the cursor. Without it, deleting the last letter of a word would bring that letter straight back as gray text.
  • setGhostTextCandidates replaces the candidates.
  • dismissGhostTextEffect hides the gray text until the next change. Esc sends it.

The field only stores inputs. The gray text is computed from them when it’s needed, so there’s no cached result to keep in sync.

getGhostText: whether to show anything

function getGhostText(view: EditorView): { pos: number; text: string } | null {
  const { state } = view;
  const ghost = state.field(ghostTextState, false);
  const { main, ranges } = state.selection;
  const pos = state.doc.length;
  if (
    !ghost ||
    ghost.hidden ||
    ghost.candidates.length === 0 ||
    ranges.length > 1 ||
    !main.empty ||
    main.head !== pos ||
    currentCompletions(state).length > 0
  ) {
    return null;
  }
  const text = findGhostText(
    state.doc.toString(),
    ghost.candidates,
    ghost.segmenter,
  );
  return text ? { pos, text } : null;
}

The view plugin calls this on every update, and both key commands call it too. It returns the gray text and the position to draw it at, or null.

The condition lists the cases where there’s nowhere sensible to put gray text:

  • the field is missing, the gray text is hidden, or there are no candidates,
  • there’s more than one cursor (ranges.length > 1),
  • text is selected (!main.empty),
  • the cursor isn’t at the very end of the document (main.head !== pos),
  • the placeholder dropdown is open (currentCompletions(state).length > 0).

state.field(ghostTextState, false) passes false so that a missing field returns undefined instead of throwing. The keymap that calls this function is installed in every editor, including read-only ones that never got the field.

Requiring the cursor to be at the end means gray text never sits in the middle of existing text, where it would push words to the right or repeat text that’s already there. The dropdown check exists because the editor already had a separate autocomplete for placeholders: type { or < and a list of the source string’s placeholders appears. While that list is open, it owns Tab.

With the cursor at the end, the whole document is the text before the cursor, and that’s what goes into findGhostText.

findGhostText: what to show

const wordChar = /[\p{L}\p{M}\p{N}]/u;
const hasWordChar = /[\p{L}\p{N}]/u;

export function findGhostText(
  before: string,
  candidates: readonly string[],
  segmenter: Intl.Segmenter,
): string {
  let best = { candidate: '', length: 0 };
  for (const candidate of candidates) {
    const length = getMatchLength(before, candidate);
    if (length > best.length) {
      best = { candidate, length };
    }
  }

  const { candidate, length } = best;
  const match = before.slice(before.length - length);
  if (getMatchWeight(match) < MIN_MATCH_TO_COMPLETE_WORD) {
    return '';
  }
  const midWord = wordChar.test(before.charAt(before.length - length - 1));
  const units = getUnits(candidate, segmenter);
  for (
    let start = candidate.indexOf(match);
    start !== -1;
    start = candidate.indexOf(match, start + 1)
  ) {
    const end = start + length;
    const unit = getUnitToComplete(candidate, units, start, end, midWord);
    if (unit) {
      const text = candidate.slice(end, unit.end).split(/[\r\n]/, 1)[0];
      return text.trim() ? text : '';
    }
  }
  return '';
}

The function has four steps:

  1. For each candidate, measure the longest match at the end of the typed text, and keep the best candidate.
  2. Return nothing if that match is too weak to even finish a word.
  3. Split the candidate into units, the chunks that one Tab accepts.
  4. Go through each place the match occurs in the candidate and decide whether to finish the current unit or offer the next one. The first occurrence that produces something wins.

Two details in step 1. The comparison is >, so on a tie the earlier candidate wins, and because candidates are sorted by quality, that’s the better suggestion. And only the best candidate is ever used. If it has nothing left to add, the result is empty even when a weaker candidate could continue.

The last lines cut the result at the first line break and return nothing if it’s only whitespace. The helpers follow.

getMatchLength: the longest suffix match

function getMatchLength(before: string, candidate: string): number {
  let min = 0;
  let max = Math.min(before.length, candidate.length);
  while (min < max) {
    const mid = Math.ceil((min + max) / 2);
    if (candidate.includes(before.slice(before.length - mid))) {
      min = mid;
    } else {
      max = mid - 1;
    }
  }
  return min;
}

The match is the longest suffix of the typed text that appears anywhere in the candidate. It’s a suffix because typing happens at the end. It can be anywhere in the candidate because a translation doesn’t have to start the way a suggestion does.

Suffix of Un filIn Il file?
"l"yes
"il"yes
"fil"yes
" fil"yes (the longest, so this is the match)
"n fil"no
"Un fil"no

If a suffix appears in the candidate, every shorter suffix does too, since each shorter suffix is a substring of the longer one. So the answers are always a run of yeses followed by a run of nos, which is exactly what binary search needs. For Un fil against Il file, the loop checks lengths 3, 5 and 4, and returns 4.

The midpoint is rounded up because a successful check sets min = mid. If it were rounded down, then once max was min + 1 the midpoint would equal min and the loop would never finish.

getMatchWeight: is the match strong enough?

export const MIN_MATCH_TO_COMPLETE_WORD = 4;

export const MIN_MATCH_TO_SUGGEST_NEXT_WORD = 8;

A match needs a weight of at least 4 before the current word is finished, and at least 8 before a whole new word is offered:

TypedCandidateWeightResult
"Un fi""Il file"3nothing
"Un fil""Il file"4"e"
"Apri il""Apri il file"7nothing (il is complete, and the next word needs 8)
"Apri il ""Apri il file"8"file"

In the last row, the space after il takes the weight from 7 to 8, which is also the point where the translator has signalled that il is finished.

/**
 * Letters of the scripts where one character is a whole syllable or
 * morpheme, so a 2-character word like 接続 or 연결 says about as much as
 * a 4-character word in Latin script.
 */
const denseScript =
  /[\p{scx=Han}\p{scx=Hiragana}\p{scx=Katakana}\p{scx=Hangul}\p{scx=Bopomofo}\p{scx=Yi}]/u;

function getMatchWeight(text: string): number {
  let weight = 0;
  for (const char of text) {
    weight +=
      hasWordChar.test(char) && denseScript.test(char) ? 2 : char.length;
  }
  return weight;
}

The weight is the number of characters, except that letters in dense scripts count as two. The regex uses scx (Script_Extensions) rather than sc (Script), and the difference shows with the long vowel mark ー. Its Script is Common because hiragana and katakana both use it, but its Script_Extensions lists both, so サーバー weighs 8 rather than 6. Script_Extensions also covers CJK punctuation like 。 and 、, which is why the hasWordChar test is there: only letters and numbers count double. Thai isn’t on the list. It doesn’t put spaces between words either, but its letters stand for sounds, not syllables.

tokenize and getUnits: what one Tab accepts

/**
 * What Tab accepts: a word with any punctuation, placeholders or tags
 * attached to it.
 */
type Unit = { start: number; end: number };

Some candidates split into units:

[Salva] [il] [file,] [poi] [chiudi.]
[Fai] [clic] [su] [«Salva»] [per] [continuare]
[Elimina] [{ $count }] [file]
[Invia] [una] [e-mail]
[ファイル、] [フォルダ] [を] [開く。]

Units are built in two passes. First, tokenize produces tokens:

type Token = {
  start: number;
  end: number;
  isWord: boolean;
  isPlaceholder?: true;
};

function tokenize(text: string, segmenter: Intl.Segmenter): Token[] {
  const tokens: Token[] = [];
  const addSegments = (start: number, end: number) => {
    const segments = segmenter.segment(text.slice(start, end));
    for (const { index, segment, isWordLike } of segments) {
      const pos = start + index;
      tokens.push({
        start: pos,
        end: pos + segment.length,
        isWord: !!isWordLike,
      });
    }
  };

  let pos = 0;
  for (const match of text.matchAll(placeholder)) {
    if (hasWordChar.test(match[0])) {
      addSegments(pos, match.index);
      pos = match.index + match[0].length;
      tokens.push({
        start: match.index,
        end: pos,
        isWord: true,
        isPlaceholder: true,
      });
    }
  }
  addSegments(pos, text.length);
  return tokens;
}

Placeholders come first. placeholder is the editor’s existing regex for HTML tags, Fluent { … } expressions, printf-style %s and similar. Each match that contains a letter or digit becomes a single token flagged isPlaceholder, so { $count } and <strong> are never split. The regex also matches things like … and unusual whitespace. Those have no letters or digits, so they’re left to the segmenter.

addSegments runs Intl.Segmenter over the text between placeholders. With granularity: 'word', the segmenter knows where words start and end, including in languages written without spaces, and isWordLike tells words apart from spaces and punctuation:

const japanese = new Intl.Segmenter('ja', { granularity: 'word' });
[...japanese.segment('ファイル、フォルダを開く。')].map((s) => s.segment);
// ['ファイル', '、', 'フォルダ', 'を', '開く', '。']

Then getUnits groups the tokens. Comments added:

const breakingSpace = /[^\S\u00a0\u2007\u202f]/; // whitespace, minus no-break spaces
const joiner = /^[-\u2010\u2011/\u00a0\u2007\u202f]+$/;

function getUnits(text: string, segmenter: Intl.Segmenter): Unit[] {
  const units: Unit[] = [];
  let unit: Unit | null = null;
  let hasWord = false;
  let joined: boolean | null = null;

  for (const token of tokenize(text, segmenter)) {
    const str = text.slice(token.start, token.end);
    // Rule 1: a breaking space ends the unit.
    if (!token.isWord && breakingSpace.test(str)) {
      if (unit) {
        units.push(unit);
        unit = null;
      }
      continue;
    }

    // Rule 2: a second word starts a new unit, unless only joiners came between.
    const isText = token.isWord && !token.isPlaceholder;
    if (unit && isText && hasWord && !joined) {
      units.push(unit);
      unit = null;
    }
    if (!unit) {
      unit = { start: token.start, end: token.end };
      hasWord = false;
      joined = null;
    }
    // Rule 3: everything else sticks to the current unit.
    unit.end = token.end;
    if (isText) {
      hasWord = true;
      joined = null;
    } else {
      joined = (joined ?? true) && joiner.test(str);
    }
  }
  if (unit) {
    units.push(unit);
  }
  return units;
}

No-break spaces don’t count as breaking, so French continuer ?, written with a narrow no-break space before the ?, stays one unit. Joiners are hyphens, slashes and no-break spaces, which keeps e-mail and 100 km together. Punctuation and placeholders stick to whatever unit they’re next to.

joined is the state behind rule 2. It’s null right after a word, true while every token since that word has been a joiner, and false once anything else appears. The comma in file,poi sets it to false, so the text splits into file, and poi.

Spaces never belong to a unit. When the next unit is offered, though, the text from the end of the match to the end of that unit includes the space in front of it. That’s why, after riesce is accepted, the gray text is " a".

getUnitToComplete: finish this word or offer the next

Comments added:

function getUnitToComplete(
  candidate: string,
  units: readonly Unit[],
  start: number,
  end: number,
  midWord: boolean,
): Unit | null {
  // If the match starts partway into a word, that word isn't evidence.
  const first = units.find((u) => start < u.end);
  const alignedStart =
    first && (first.start < start || (first.start === start && midWord))
      ? first.end
      : start;

  // Case A: the match ends inside a unit. Finish it, if the evidence covers its start.
  const current = units.find((u) => u.start < end && end < u.end);
  if (current && candidate.slice(end, current.end).trim()) {
    return alignedStart <= current.start ? current : null;
  }

  // Case B: the match ends between units. Offer the next one, if the whole words weigh 8+.
  const aligned = candidate.slice(alignedStart, end);
  if (getMatchWeight(aligned) < MIN_MATCH_TO_SUGGEST_NEXT_WORD) {
    return null;
  }
  return units.find((u) => u.start >= end) ?? null;
}

start and end mark where the match sits in the candidate. Which case applies depends on end:

               start             end
                 ▼                ▼
candidate:      [Firefox] [non] [r|iesce] [a] [trovare] [il] [server]
typed:           Firefox   non   r

                                       end
                                        ▼
candidate:      [Firefox] [non] [riesce]| [a] [trovare] [il] [server]
typed:           Firefox   non   riesce
  • Case A: end is inside a unit, so the result is the rest of that unit, iesce. The weight-4 check in findGhostText already covered this case.
  • Case B: end is between units, so the result is the next unit with the space before it, " a". This needs a weight of 8.

alignedStart deals with matches that start partway through a word. Typed Aprisalv against the candidate salva il file gives the match salv. It clears the weight-4 threshold, but the typed word is Aprisalv, not salva, so finishing it would be wrong. There are two signals:

  • first.start < start: the match starts partway into a unit of the candidate.
  • midWord, computed in findGhostText: the character before the match in the typed text is a letter, mark or number. If the match covers all of the typed text, charAt(-1) returns an empty string and midWord is false.

If either is true, alignedStart moves to the end of that first unit. Case A then requires alignedStart <= current.start, so the unit being finished must be covered from its first character. Case B only counts the text from alignedStart to end toward the weight of 8.

Skipping the partial word, rather than rejecting the whole match, matters because of how a longest suffix match behaves. Typed Una pericona di sistema e against Fai clic sull'icona di sistema e poi chiudi, the match is icona di sistema e . It starts inside a word on both sides, and it keeps starting there however much more matching text is typed, since that’s as far back as the two texts agree. Rejecting such matches would turn off next-word suggestions for the rest of the line. Skipping leaves " di sistema e " as evidence, with a weight of 14, so the result is poi. This comes up often with Italian elision (dell'icona and sull'icona) and with Korean particles (서버에 and 네트워크에 share 에).

Back in findGhostText, the loop tries every occurrence of the match. Typed cerc against Ricerca o cerca nel web first matches inside Ricerca, which fails the alignment check, and then matches the word cerca, which gives a.

The widget and the view plugin: drawing the gray text

class GhostTextWidget extends WidgetType {
  constructor(readonly text: string) {
    super();
  }

  eq(other: GhostTextWidget) {
    return other.text === this.text;
  }

  toDOM() {
    const span = document.createElement('span');
    span.className = 'ghost-text';
    span.setAttribute('aria-hidden', 'true');
    span.textContent = this.text;
    return span;
  }
}

function ghostTextDecorations(view: EditorView): DecorationSet {
  const ghost = getGhostText(view);
  if (!ghost) {
    return Decoration.none;
  }
  const widget = new GhostTextWidget(ghost.text);
  return Decoration.set(
    Decoration.widget({ widget, side: 1 }).range(ghost.pos),
  );
}

const ghostTextPlugin = ViewPlugin.fromClass(
  class {
    decorations: DecorationSet;

    constructor(view: EditorView) {
      this.decorations = ghostTextDecorations(view);
    }

    update(update: ViewUpdate) {
      this.decorations = ghostTextDecorations(update.view);
    }
  },
  { decorations: (plugin) => plugin.decorations },
);

The gray text is never inserted into the document. view.state.doc still reads Firefox non r while it’s showing, so saving, copying and undo don’t see it. It’s a widget decoration: a DOM node that CodeMirror draws at a document position.

  • ghostTextPlugin recomputes its decorations on every view update, which calls getGhostText, and so findGhostText, on every keystroke and cursor move. The inputs are a few short strings, so this stays cheap.
  • Decoration.widget({ widget, side: 1 }) puts the widget at the end of the document. side: 1 draws it after the cursor. With the default side: 0, the cursor would appear after the gray text, as if it had already been typed.
  • eq lets CodeMirror reuse the existing DOM node when the text hasn’t changed.
  • aria-hidden keeps screen readers from reading the suggestion as part of the translation.
.ghost-text {
  color: var(--editor-placeholder-color);
  pointer-events: none;
}

.cm-editor:not(.cm-focused) .ghost-text {
  display: none;
}

The color is the editor’s placeholder color, which is defined for both the light and dark themes. pointer-events: none lets clicks through to the text underneath, and the gray text is hidden whenever the editor isn’t focused.

Tab and Esc

export const acceptGhostText: Command = (view) => {
  const ghost = view.composing ? null : getGhostText(view);
  if (!ghost) {
    return false;
  }
  const { pos, text } = ghost;
  view.dispatch({
    changes: { from: pos, insert: text },
    selection: { anchor: pos + text.length },
    scrollIntoView: true,
    userEvent: 'input.complete',
  });
  return true;
};

export const dismissGhostText: Command = (view) => {
  if (view.composing || !getGhostText(view)) {
    return false;
  }
  view.dispatch({ effects: dismissGhostTextEffect.of(null) });
  return true;
};

export const ghostTextKeymap: readonly KeyBinding[] = [
  { key: 'Tab', run: acceptGhostText },
  { key: 'Escape', run: dismissGhostText },
];

These bindings sit in the editor’s keymap in editFieldExtensions.ts, after the ones that need the keys first:

keymap.of([
  {
    key: 'Enter',
    run: () => ref.current.onEnter(),
    shift: insertNewlineAndIndent,
  },
  { key: 'Mod-Enter', run: insertNewlineAndIndent },
  { key: 'Escape', run: () => ref.current.onEscape() },
  { key: 'Tab', run: acceptCompletion },
  ...ghostTextKeymap,
  // …
]),

For each key, CodeMirror runs the matching bindings in order and stops at the first run that returns true. If none do, the browser gets the key.

  • Esc: onEscape closes Pontoon’s unsaved-changes or failed-checks popup if one is open, and returns true. Otherwise dismissGhostText hides the gray text.
  • Tab: acceptCompletion handles it if the placeholder dropdown is open. Otherwise acceptGhostText handles it if there’s gray text. Otherwise Tab moves focus as usual.

acceptGhostText inserts the text at the end of the document and moves the cursor after it in a single transaction, so it can be undone like any edit. Its user event is input.complete, which isn’t a deletion, so the state field keeps hidden false and the next word is computed straight away. That’s how repeated Tabs accept a suggestion word by word.

Both commands return false while view.composing is true. During IME composition, such as typing Japanese, Tab and Esc belong to the input method. The gray text still shows, but those keys pass through to the IME.

Tests

Since findGhostText is a pure function, most tests are one-liners. The find helper fixes an Italian segmenter:

const segmenter = new Intl.Segmenter('it', { granularity: 'word' });
const find = (before: string, candidates: string[]) =>
  findGhostText(before, candidates, segmenter);

const firefox = 'Firefox non riesce a trovare il server';
expect(find('Firefox non r', [firefox])).toBe('iesce');
expect(find('Un fi', ['Il file'])).toBe(''); // ' fi'
expect(find('Un fil', ['Il file'])).toBe('e'); // ' fil'
expect(find('Aprisalv', ['salva il file'])).toBe('');

const fluent = 'Elimina { $count } file';
expect(find('Elimina ', [fluent])).toBe('{ $count }');

const ja = new Intl.Segmenter('ja', { granularity: 'word' });
expect(findGhostText('このファイ', ['このファイルを開く'], ja)).toBe('ル');

The editor tests build a real EditorView in jsdom, dispatch keyboard events on view.contentDOM, and use defaultPrevented to see whether the editor handled a key:

function press(key: string) {
  const event = new KeyboardEvent('keydown', {
    key,
    bubbles: true,
    cancelable: true,
  });
  view!.contentDOM.dispatchEvent(event);
  return event.defaultPrevented;
}

expect(press('Tab')).toBe(false) means Tab went to the browser, which is what should happen when there’s no gray text. The IME tests start a composition by hand, with a compositionstart event and a direct edit of the DOM text node, and stub Range.prototype.getClientRects, which jsdom doesn’t implement.

References