-
Notifications
You must be signed in to change notification settings - Fork 118
SD-2505 - fix: avoid UI stalls with on Typo.js example #2765
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
caio-pizzol
merged 7 commits into
main
from
gabriel/sd-2505-bug-spellcheck-significant-lag-on-load-and-when-typing
Apr 15, 2026
+254
−42
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7993596
fix: avoid UI stalls with on Typo.js example
chittolina 02dbe3d
chore: small code tweaks
chittolina 806e054
fix: cancel worker task when proofing times out
chittolina e398727
Merge branch 'main' into gabriel/sd-2505-bug-spellcheck-significant-l…
chittolinag 31d7557
fix(spell-check): use matchAll to isolate regex state across concurre…
caio-pizzol 3dc53fe
refactor(spell-check): simplify cancel tracking and tighten provider …
caio-pizzol a9874b0
Merge branch 'main' into gabriel/sd-2505-bug-spellcheck-significant-l…
caio-pizzol File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
114 changes: 114 additions & 0 deletions
114
examples/features/spell-check/typo-js/src/typoWorker.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| /// <reference lib="webworker" /> | ||
|
|
||
| import Typo from 'typo-js'; | ||
| import affUrl from 'typo-js/dictionaries/en_US/en_US.aff?url'; | ||
| import dicUrl from 'typo-js/dictionaries/en_US/en_US.dic?url'; | ||
| import type { | ||
| TypoWorkerIssue, | ||
| TypoWorkerRequest, | ||
| TypoWorkerResponse, | ||
| TypoWorkerIncomingMessage, | ||
| } from './typoWorkerMessages'; | ||
|
|
||
| const ctx: DedicatedWorkerGlobalScope = self as unknown as DedicatedWorkerGlobalScope; | ||
| const WORD_PATTERN = /[a-zA-Z'\u2019]+/g; | ||
|
|
||
| /** Yields to the worker event loop so `cancel` messages can be processed mid-check. */ | ||
| const YIELD_EVERY_WORDS = 25; | ||
|
|
||
| let dictionaryPromise: Promise<Typo> | null = null; | ||
|
|
||
| /** Cancelled request ids (added by `cancel` messages from the main thread). */ | ||
| const cancelledIds = new Set<number>(); | ||
|
|
||
| async function loadDictionary(): Promise<Typo> { | ||
| if (!dictionaryPromise) { | ||
| dictionaryPromise = Promise.all([ | ||
| fetch(affUrl).then((r) => r.text()), | ||
| fetch(dicUrl).then((r) => r.text()), | ||
| ]).then(([affData, dicData]) => new Typo('en_US', affData, dicData)); | ||
| } | ||
|
|
||
| return dictionaryPromise; | ||
| } | ||
|
|
||
| /** | ||
| * Returns issues, or `null` if the request was cancelled (caller must not post a result). | ||
| * Yields periodically so abort can be observed while Typo runs synchronously per word. | ||
| */ | ||
| async function collectIssues( | ||
| payload: TypoWorkerRequest['payload'], | ||
| dictionary: Typo, | ||
| isAborted: () => boolean, | ||
| ): Promise<TypoWorkerIssue[] | null> { | ||
| const issues: TypoWorkerIssue[] = []; | ||
| const maxSuggestions = payload.maxSuggestions ?? 5; | ||
| let wordCount = 0; | ||
|
|
||
| for (const segment of payload.segments) { | ||
| for (const match of segment.text.matchAll(WORD_PATTERN)) { | ||
| if (isAborted()) return null; | ||
|
|
||
| const word = match[0]; | ||
| if (word.replace(/['\u2019]/g, '').length < 2) continue; | ||
|
|
||
| if (!dictionary.check(word)) { | ||
| issues.push({ | ||
| segmentId: segment.id, | ||
| start: match.index, | ||
| end: match.index + word.length, | ||
| kind: 'spelling', | ||
| message: `Unknown word: "${word}"`, | ||
| replacements: maxSuggestions > 0 ? dictionary.suggest(word).slice(0, maxSuggestions) : [], | ||
| }); | ||
| } | ||
|
|
||
| wordCount++; | ||
| if (wordCount % YIELD_EVERY_WORDS === 0) { | ||
| // Yield to the event loop so abort can be observed mid-check. | ||
| await new Promise<void>((resolve) => setTimeout(resolve, 0)); | ||
| if (isAborted()) return null; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return issues; | ||
| } | ||
|
|
||
| function toErrorMessage(error: unknown): string { | ||
| if (error instanceof Error && error.message) return error.message; | ||
| return 'Typo worker failed'; | ||
| } | ||
|
|
||
| async function handleCheck(data: TypoWorkerRequest): Promise<void> { | ||
| const id = data.id; | ||
|
|
||
| try { | ||
| if (cancelledIds.has(id)) return; | ||
|
|
||
| const dictionary = await loadDictionary(); | ||
| if (cancelledIds.has(id)) return; | ||
|
|
||
| const collected = await collectIssues(data.payload, dictionary, () => cancelledIds.has(id)); | ||
| if (collected === null) return; | ||
|
|
||
| ctx.postMessage({ id, type: 'result', issues: collected } satisfies TypoWorkerResponse); | ||
| } catch (error) { | ||
| ctx.postMessage({ id, type: 'error', error: toErrorMessage(error) } satisfies TypoWorkerResponse); | ||
| } finally { | ||
| cancelledIds.delete(id); | ||
| } | ||
| } | ||
|
|
||
| ctx.addEventListener('message', (event: MessageEvent<TypoWorkerIncomingMessage>) => { | ||
| const { data } = event; | ||
|
|
||
| if (data.type === 'cancel') { | ||
| cancelledIds.add(data.id); | ||
| return; | ||
| } | ||
|
|
||
| if (data.type !== 'check') return; | ||
|
|
||
| handleCheck(data); | ||
| }); |
41 changes: 41 additions & 0 deletions
41
examples/features/spell-check/typo-js/src/typoWorkerMessages.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| export type TypoWorkerIssue = { | ||
| segmentId: string; | ||
| start: number; | ||
| end: number; | ||
| kind: 'spelling'; | ||
| message: string; | ||
| replacements: string[]; | ||
| }; | ||
|
|
||
| export type TypoWorkerPayload = { | ||
| segments: { id: string; text: string }[]; | ||
| maxSuggestions: number; | ||
| }; | ||
|
|
||
| export type TypoWorkerRequest = { | ||
| id: number; | ||
| type: 'check'; | ||
| payload: TypoWorkerPayload; | ||
| }; | ||
|
|
||
| /** Tells the worker to stop work for a timed-out or aborted check (id matches the check request). */ | ||
| export type TypoWorkerCancelMessage = { | ||
| type: 'cancel'; | ||
| id: number; | ||
| }; | ||
|
|
||
| export type TypoWorkerIncomingMessage = TypoWorkerRequest | TypoWorkerCancelMessage; | ||
|
|
||
| type TypoWorkerResultMessage = { | ||
| id: number; | ||
| type: 'result'; | ||
| issues: TypoWorkerIssue[]; | ||
| }; | ||
|
|
||
| type TypoWorkerErrorMessage = { | ||
| id: number; | ||
| type: 'error'; | ||
| error: string; | ||
| }; | ||
|
|
||
| export type TypoWorkerResponse = TypoWorkerResultMessage | TypoWorkerErrorMessage; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.