import { useEffect, useState } from 'react' import { loadSegmenter, type Segmenter } from '../lib/segment' // Loads the Chinese word list, once per session, and only for a writer who is // going to use it. // // Modelled on useSpellChecker, and gated harder. That hook loads for everyone, // because everyone's English gets spell-checked; this one loads a megabyte for // the one direction that needs it, and an account practising English would // never ask a single question of it. The gate is the writer's own setting rather // than a guess from their text: a Mandarin native drafting English quotes // Chinese in it constantly, and none of that is what this is for. // // A failure resolves to null, which every consumer already handles as "no // segmentation" — the Chinese hover quietly does nothing rather than the editor // refusing to open. export function useSegmenter(enabled: boolean): Segmenter | null { const [segmenter, setSegmenter] = useState(null) useEffect(() => { if (!enabled) { // Turning the direction back drops it. It is a megabyte of resident map // whose only consumer just switched off, and re-loading costs one fetch // that the browser cache answers. setSegmenter(null) return } let cancelled = false loadSegmenter().then((seg) => { if (!cancelled) setSegmenter(seg) }) return () => { cancelled = true } }, [enabled]) return segmenter }