skip to content

In a music-streaming web app's search box serving 30 locales, including Japanese and Korean typed through an input method, when should a query fire, and how would you highlight matches safely?

level: seniorimportance: nice to knowfreq 36%

answer

  1. half-formed text mid-composition
  2. compositionend is the trigger
  3. Enter belongs to the input method
  4. the server knows what matched
  5. ranges rendered as text, never markup

basics

~20 s

Hold remote queries while an input method is composing and trigger from compositionend, leaving Enter and arrows to the input method. Highlight from server-supplied match ranges, rendered as text nodes or with the CSS Custom Highlight API, never as markup.

solid answer

~50 s

Japanese and Korean users type through an input method, passing through romaji, kana or a half-built syllable, so the input's value changes before the user means it. So while a composition session is active I send no remote queries and do not start the delay; `compositionend` triggers the normal delay itself, without counting on a later input event, and Enter or arrow keys during composition belong to the input method, not the combobox. For highlighting, the server decides what matched, because kana can match a kanji title and accents are folded, so the API returns match ranges in UTF-16 code units, the same units as JavaScript string indices. The page renders titles as text with the matched part wrapped in an element built by DOM calls, or paints ranges with the CSS Custom Highlight API. User-made playlist names make markup from the API an injection risk.

code

javascript · 14 lines
javascript
// ranges: [[start, end], ...] sorted, in UTF-16 code units, from the suggestions API
function renderLabel(el, text, ranges) {
  el.replaceChildren();
  let pos = 0;
  for (const [start, end] of ranges) {
    if (start < pos || start >= end || end > text.length) continue; // skip bad ranges
    el.append(text.slice(pos, start));          // plain text node
    const mark = document.createElement("mark");
    mark.textContent = text.slice(start, end);  // set as text, never parsed
    el.append(mark);
    pos = end;
  }
  el.append(text.slice(pos));
}

go deeper

for a junior

Remember that input-method users build characters in several steps, so the box waits for composition to end, and that highlights are built as text, not HTML.

for a middle

Explain the composition events, which one triggers the query, and why match ranges come from the server rather than a client-side string search.

for a senior

Show the bugs you would catch in testing: Enter confirming a conversion opens a suggestion, ranges shifted by surrogate pairs, user-made playlist names injected as markup.

for a principal

Set the contract across teams: what the suggestions API returns for highlights, which normalisation both sides share, and how 30 locales are tested before release.

## How input-method typing reaches the box Users of Japanese, Korean and Chinese type through an **input method editor (IME)**. In Japanese, typed romaji turns into underlined kana, the user converts it to kanji, and confirms with Enter. In Korean, letters combine into a syllable block in place. Throughout, the input's value changes on every keystroke, but the text is not yet what the user means. The browser marks this with **composition events**: `compositionstart` when a session begins, `compositionupdate` as it changes, and `compositionend` when the input method **completes or cancels** the session. A query sent mid-composition searches a half-formed word. ## When a query should fire | State of the input | What the box does | |---|---| | Not composing | the normal rule: a short pause and the minimum length | | Composing | no remote queries; the delay does not start; the current list stays | | `compositionend` | treated as an edit of its own: start the normal delay from here | | Enter or arrows while composing | left to the input method's candidate window: no commit, no move of the active option | Two details trip implementations: - **Trigger from `compositionend` itself.** Do not rely on an input event arriving after it; let the end of composition start the delay directly. - **Enter is ambiguous.** For a Japanese user, Enter often confirms a conversion. A handler that treats every Enter as "open the active suggestion" sends them somewhere they did not choose. A product whose index holds kana readings could deliberately search the uncommitted kana for Japanese users; that is a product choice with its own request budget, not the default. ## Per-locale details that feed the budget - **Minimum length per script.** One kanji or Hangul syllable can be meaningful; a Latin-tuned minimum of two or three hides useful queries. - **Normalisation agreed with the server.** Full-width and half-width forms, case rules that differ by locale, accents. The client's cache key must use the same normalisation, or the same query misses its cache. ## Highlighting the match: the server knows what matched In a 30-locale catalogue the typed text often does not appear literally in the title: - kana typed, kanji shown in the title; - "cafe" typed, a title with "Café"; - a romanised spelling matching a title in another script. A client that searches the title for the typed string highlights nothing, or the wrong letters. So the **API returns match ranges** per field, and the page highlights exactly those. The ranges need units both sides agree on. JavaScript string indices count **UTF-16 code units**; an emoji or a rare CJK character takes two. A server counting code points shifts every later range by one per such character. Ranges should also never split a character built from several code points, such as a letter with a combining accent. ## Rendering the highlight safely Titles come from catalogue metadata and from **playlist names users type themselves**. If the API returns `<em>Rad</em>io Lanterns` and the page parses that as HTML, a playlist named with markup in it becomes markup on every viewer's screen. Which DOM properties parse strings as HTML, and how sanitisers work, is a separate security subject; the design answer is to **never need HTML at all**: 1. **Segments as text.** Split the title at the ranges, append the plain parts as text nodes, and wrap each match in a `<mark>` element whose content is set as text. The title is never parsed. This works in every browser. 2. **The CSS Custom Highlight API.** Keep the title as one text node, create `Range` objects over the matched offsets, register them as a `Highlight`, and style them with `::highlight()`. The DOM is not changed at all. It has only recently become available across current major browsers, so older ones fall back to option 1. 3. **If the API can only return markup**, treat that as a contract defect to fix, not something to render. ## Summary - Hold remote queries during composition; let `compositionend` start the delay, and let the input method keep its Enter and arrow keys. - Set the minimum length per script and share normalisation with the server. - Ask the server for match ranges in agreed units, and render them as text or as highlights, never as markup.

  • Should local matches, like recent searches, also wait for compositionend?
    Filtering local data is cheap, so it may run on the uncommitted text, but it rarely helps: romaji or a half-built syllable matches little that the user means. Most products keep the current list steady during composition and refresh both local and remote matches when it ends, so the list does not flicker through intermediate states.
  • Why not have the client compute match ranges itself with a normalised search?
    Because the client would have to reproduce the server's matching exactly: locale case rules, accent folding, kana and kanji readings, transliteration. Any difference highlights the wrong letters. The server already knows why each result matched, so returning the ranges with the result is cheaper and stays correct when matching rules change.
  • Does wrapping the match in a mark element change what a screen reader says for the option?
    The option's name is still its text content, read as one string, so the words do not change. Whether a screen reader also signals the highlight varies, so the highlight is a visual aid; the meaning should never depend on it.

  • Send a query on every input event, including those fired mid-composition.
  • Treat every Enter keydown as committing the active suggestion.
  • The client can find the match by searching the title for the typed text.
  • Render the API's highlighted HTML with innerHTML; the catalogue is trusted.
  • Match ranges can be counted in code points while the page indexes UTF-16.