spellchecker.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import { addMisspelledWords, misspelledWordsField } from './misspelled-words'
  2. import { ignoredWordsField, resetSpellChecker } from './ignored-words'
  3. import { cacheField, addWordToCache, WordCacheValue } from './cache'
  4. import { WORD_REGEX } from './helpers'
  5. import OError from '@overleaf/o-error'
  6. import { spellCheckRequest } from './backend'
  7. import { EditorView, ViewUpdate } from '@codemirror/view'
  8. import { ChangeSet, Line, Range, RangeValue } from '@codemirror/state'
  9. import { IgnoredWords } from '../../../dictionary/ignored-words'
  10. import { getNormalTextSpansFromLine } from '../../utils/tree-query'
  11. import { waitForParser } from '../wait-for-parser'
  12. import { debugConsole } from '@/utils/debugging'
  13. import type { HunspellManager } from '../../hunspell/HunspellManager'
  14. import { captureException } from '@/infrastructure/error-reporter'
  15. /*
  16. * Spellchecker, handles updates, schedules spelling checks
  17. */
  18. export class SpellChecker {
  19. private abortController?: AbortController | null = null
  20. private timeout: number | null = null
  21. private firstCheck = true
  22. private waitingForParser = false
  23. private firstCheckPending = false
  24. private trackedChanges: ChangeSet
  25. private readonly segmenter?: Intl.Segmenter
  26. // eslint-disable-next-line no-useless-constructor
  27. constructor(
  28. private readonly language: string,
  29. private hunspellManager?: HunspellManager
  30. ) {
  31. debugConsole.log('SpellChecker', language, hunspellManager)
  32. this.trackedChanges = ChangeSet.empty(0)
  33. const locale = language.replace(/_/, '-')
  34. try {
  35. if (Intl.Segmenter) {
  36. const supportedLocales = Intl.Segmenter.supportedLocalesOf([locale], {
  37. localeMatcher: 'lookup',
  38. })
  39. if (supportedLocales.includes(locale)) {
  40. this.segmenter = new Intl.Segmenter(locale, {
  41. localeMatcher: 'lookup',
  42. granularity: 'word',
  43. })
  44. }
  45. }
  46. } catch (error) {
  47. // ignore, not supported for some reason
  48. debugConsole.error(error)
  49. }
  50. if (this.segmenter) {
  51. debugConsole.log(`Using Intl.Segmenter for ${locale}`)
  52. } else {
  53. debugConsole.warn(`Not using Intl.Segmenter for ${locale}`)
  54. }
  55. }
  56. destroy() {
  57. this._clearPendingSpellCheck()
  58. // this.hunspellManager?.destroy()
  59. }
  60. _abortRequest() {
  61. if (this.abortController) {
  62. this.abortController.abort()
  63. this.abortController = null
  64. }
  65. }
  66. handleUpdate(update: ViewUpdate) {
  67. if (update.docChanged) {
  68. this.trackedChanges = this.trackedChanges.compose(update.changes)
  69. this.scheduleSpellCheck(update.view)
  70. } else if (update.viewportChanged) {
  71. this.trackedChanges = ChangeSet.empty(0)
  72. this.scheduleSpellCheck(update.view)
  73. } else if (
  74. update.transactions.some(tr => {
  75. return tr.effects.some(effect => effect.is(resetSpellChecker))
  76. })
  77. ) {
  78. // for tests
  79. this.trackedChanges = ChangeSet.empty(0)
  80. this.spellCheckAsap(update.view)
  81. }
  82. // At the point that the spellchecker is initialized, the editor may not
  83. // yet be editable, and the parser may not be ready. Therefore, to do the
  84. // initial spellcheck, watch for changes in the editability of the editor
  85. // and kick off the process that performs a spellcheck once the parser is
  86. // ready. CM6 dispatches a transaction after every chunk of parser work and
  87. // when the editability changes, which means the spell checker is
  88. // initialized as soon as possible.
  89. else if (
  90. this.firstCheck &&
  91. !this.firstCheckPending &&
  92. update.state.facet(EditorView.editable)
  93. ) {
  94. this.firstCheckPending = true
  95. this.spellCheckAsap(update.view)
  96. }
  97. }
  98. _performSpellCheck(view: EditorView) {
  99. const wordsToCheck = this.getWordsToCheck(view)
  100. if (wordsToCheck.length === 0) {
  101. return
  102. }
  103. const cache = view.state.field(cacheField)
  104. const { knownMisspelledWords, unknownWords } = cache.checkWords(
  105. this.language,
  106. wordsToCheck
  107. )
  108. const processResult = (
  109. misspellings: { index: number; suggestions?: string[] }[]
  110. ) => {
  111. this.trackedChanges = ChangeSet.empty(0)
  112. if (this.firstCheck) {
  113. this.firstCheck = false
  114. this.firstCheckPending = false
  115. }
  116. const result = buildSpellCheckResult(
  117. knownMisspelledWords,
  118. unknownWords,
  119. misspellings
  120. )
  121. view.dispatch({
  122. effects: compileEffects(result),
  123. })
  124. }
  125. if (unknownWords.length === 0) {
  126. processResult([])
  127. } else {
  128. this._abortRequest()
  129. this.abortController = new AbortController()
  130. if (this.hunspellManager) {
  131. const signal = this.abortController.signal
  132. this.hunspellManager.send(
  133. {
  134. type: 'spell',
  135. words: unknownWords.map(word => word.text),
  136. },
  137. result => {
  138. if (!signal.aborted) {
  139. if ('error' in result) {
  140. debugConsole.error(result.error)
  141. captureException(
  142. new Error('Error running spellcheck for word'),
  143. { tags: { ol_spell_check_language: this.language } }
  144. )
  145. } else {
  146. processResult(result.misspellings)
  147. }
  148. }
  149. }
  150. )
  151. } else {
  152. spellCheckRequest(this.language, unknownWords, this.abortController)
  153. .then(result => {
  154. this.abortController = null
  155. return processResult(result.misspellings)
  156. })
  157. .catch(error => {
  158. this.abortController = null
  159. debugConsole.error(error)
  160. })
  161. }
  162. }
  163. }
  164. suggest(word: string) {
  165. return new Promise<{ suggestions: string[] }>((resolve, reject) => {
  166. if (this.hunspellManager) {
  167. this.hunspellManager.send({ type: 'suggest', word }, result => {
  168. if ('error' in result) {
  169. reject(new Error('Error finding spelling suggestions for word'))
  170. } else {
  171. resolve(result)
  172. }
  173. })
  174. }
  175. })
  176. }
  177. addWord(word: string) {
  178. return new Promise<void>((resolve, reject) => {
  179. if (this.hunspellManager) {
  180. this.hunspellManager.send({ type: 'add_word', word }, result => {
  181. if ('error' in result) {
  182. reject(new Error('Error adding word to spellcheck'))
  183. } else {
  184. resolve()
  185. }
  186. })
  187. }
  188. })
  189. }
  190. removeWord(word: string) {
  191. return new Promise<void>((resolve, reject) => {
  192. if (this.hunspellManager) {
  193. this.hunspellManager.send({ type: 'remove_word', word }, result => {
  194. if ('error' in result) {
  195. reject(new Error('Error removing word from spellcheck'))
  196. } else {
  197. resolve()
  198. }
  199. })
  200. }
  201. })
  202. }
  203. _spellCheckWhenParserReady(view: EditorView) {
  204. if (this.waitingForParser) {
  205. return
  206. }
  207. this.waitingForParser = true
  208. waitForParser(view, view => view.viewport.to).then(() => {
  209. this.waitingForParser = false
  210. this._performSpellCheck(view)
  211. })
  212. }
  213. _clearPendingSpellCheck() {
  214. if (this.timeout) {
  215. window.clearTimeout(this.timeout)
  216. this.timeout = null
  217. }
  218. this._abortRequest()
  219. }
  220. _asyncSpellCheck(view: EditorView, delay: number) {
  221. this._clearPendingSpellCheck()
  222. this.timeout = window.setTimeout(() => {
  223. this._spellCheckWhenParserReady(view)
  224. this.timeout = null
  225. }, delay)
  226. }
  227. spellCheckAsap(view: EditorView) {
  228. this._asyncSpellCheck(view, 0)
  229. }
  230. scheduleSpellCheck(view: EditorView) {
  231. this._asyncSpellCheck(view, 1000)
  232. }
  233. getWordsToCheck(view: EditorView) {
  234. const wordsToCheck: Word[] = []
  235. const { from, to } = view.viewport
  236. const changedLineNumbers = new Set<number>()
  237. if (this.trackedChanges.length > 0) {
  238. this.trackedChanges.iterChangedRanges((_fromA, _toA, fromB, toB) => {
  239. if (fromB <= to && toB >= from) {
  240. const fromLine = view.state.doc.lineAt(fromB).number
  241. const toLine = view.state.doc.lineAt(toB).number
  242. for (let i = fromLine; i <= toLine; i++) {
  243. changedLineNumbers.add(i)
  244. }
  245. }
  246. })
  247. } else {
  248. const fromLine = view.state.doc.lineAt(from).number
  249. const toLine = view.state.doc.lineAt(to).number
  250. for (let i = fromLine; i <= toLine; i++) {
  251. changedLineNumbers.add(i)
  252. }
  253. }
  254. const ignoredWords = this.hunspellManager
  255. ? null
  256. : view.state.field(ignoredWordsField)
  257. for (const i of changedLineNumbers) {
  258. const line = view.state.doc.line(i)
  259. wordsToCheck.push(
  260. ...getWordsFromLine(
  261. view,
  262. line,
  263. ignoredWords,
  264. this.language,
  265. this.segmenter
  266. )
  267. )
  268. }
  269. return wordsToCheck
  270. }
  271. }
  272. export class Word {
  273. public text: string
  274. public from: number
  275. public to: number
  276. public lineNumber: number
  277. public lang: string
  278. public suggestions?: WordCacheValue
  279. constructor(options: {
  280. text: string
  281. from: number
  282. to: number
  283. lineNumber: number
  284. lang: string
  285. }) {
  286. const { text, from, to, lineNumber, lang } = options
  287. if (
  288. text == null ||
  289. from == null ||
  290. to == null ||
  291. lineNumber == null ||
  292. lang == null
  293. ) {
  294. throw new OError('Spellcheck: invalid word').withInfo({ options })
  295. }
  296. this.text = text
  297. this.from = from
  298. this.to = to
  299. this.lineNumber = lineNumber
  300. this.lang = lang
  301. }
  302. }
  303. export const buildSpellCheckResult = (
  304. knownMisspelledWords: Word[],
  305. unknownWords: Word[],
  306. misspellings: { index: number; suggestions?: string[] }[]
  307. ) => {
  308. const cacheAdditions: [Word, string[] | boolean][] = []
  309. // Put known misspellings into cache
  310. const misspelledWords = misspellings.map(item => {
  311. const word = {
  312. ...unknownWords[item.index],
  313. }
  314. word.suggestions = item.suggestions
  315. if (word.suggestions) {
  316. cacheAdditions.push([word, word.suggestions])
  317. }
  318. return word
  319. })
  320. // if word was not misspelled, put it in the cache
  321. for (const word of unknownWords) {
  322. if (!misspelledWords.find(mw => mw.text === word.text)) {
  323. cacheAdditions.push([word, true])
  324. }
  325. }
  326. return {
  327. cacheAdditions,
  328. misspelledWords: misspelledWords.concat(knownMisspelledWords),
  329. }
  330. }
  331. export const compileEffects = (results: {
  332. cacheAdditions: [Word, string[] | boolean][]
  333. misspelledWords: Word[]
  334. }) => {
  335. const { cacheAdditions, misspelledWords } = results
  336. return [
  337. addMisspelledWords.of(misspelledWords),
  338. ...cacheAdditions.map(([word, value]) => {
  339. return addWordToCache.of({
  340. lang: word.lang,
  341. wordText: word.text,
  342. value,
  343. })
  344. }),
  345. ]
  346. }
  347. export function* getWordsFromLine(
  348. view: EditorView,
  349. line: Line,
  350. ignoredWords: IgnoredWords | null,
  351. lang: string,
  352. segmenter?: Intl.Segmenter
  353. ) {
  354. for (const span of getNormalTextSpansFromLine(view, line)) {
  355. if (segmenter) {
  356. for (const value of segmenter.segment(span.text)) {
  357. if (value.isWordLike && !ignoredWords?.has(value.segment)) {
  358. const word = value.segment
  359. const from = span.from + value.index
  360. yield new Word({
  361. text: word,
  362. from,
  363. to: from + word.length,
  364. lineNumber: line.number,
  365. lang,
  366. })
  367. }
  368. }
  369. } else {
  370. for (const match of span.text.matchAll(WORD_REGEX)) {
  371. let word = match[0].replace(/'+$/, '')
  372. let from = span.from + match.index
  373. while (word.startsWith("'")) {
  374. word = word.slice(1)
  375. from++
  376. }
  377. if (!ignoredWords?.has(word)) {
  378. yield new Word({
  379. text: word,
  380. from,
  381. to: from + word.length,
  382. lineNumber: line.number,
  383. lang,
  384. })
  385. }
  386. }
  387. }
  388. }
  389. }
  390. export type Mark = Range<RangeValue & { spec: { word: Word } }>
  391. export const getMarkAtPosition = (
  392. view: EditorView,
  393. position: number
  394. ): Mark | null => {
  395. const marks = view.state.field(misspelledWordsField)
  396. let targetMark: Mark | null = null
  397. marks.between(view.viewport.from, view.viewport.to, (from, to, value) => {
  398. if (position >= from && position <= to) {
  399. targetMark = { from, to, value }
  400. return false
  401. }
  402. })
  403. return targetMark
  404. }