farscrl / tiptap-extension-spellchecker

TipTap extension to integrate a spellchecker
MIT License
8 stars 1 forks source link

Add a basic local proofreader #1

Closed asontha closed 3 months ago

asontha commented 7 months ago

Interface looks good, but adding a basic local proofreader that can be overridden would make this package immediately useful on install.

bryanjtc commented 6 months ago

@asontha Do you have an example using a local proofreader?

asontha commented 6 months ago

nope

bryanjtc commented 6 months ago

I created a local proofreader. Any suggestions or fixes are welcomed. Here is the word list I used. https://github.com/dwyl/english-words/blob/master/words_dictionary.json

interface WordList {
  [word: string]: number;
}

class Proofreader implements IProofreaderInterface {
  private wordList: WordList;

  constructor(wordListJson: WordList) {
      this.wordList = wordListJson;
  }

  async proofreadText(sentence: string): Promise<ITextWithPosition[]> {
      const wordsWithPosition: ITextWithPosition[] = [];
      let currentOffset = 0;

      const words = sentence.split(/\W+/);
      for (const word of words) {
          const lowerWord = word.toLowerCase().trim();
          const length = word.length;
          if (!this.wordList[lowerWord] && lowerWord !== "") {
              wordsWithPosition.push({
                  offset: currentOffset,
                  length,
                  word,
              });
          }
          currentOffset += length + 1; // +1 for the space after each word
      }

      return wordsWithPosition;
  }

  async getSuggestions(word: string): Promise<string[]> {
      // Example: just return similar words by replacing one character
      const suggestions: string[] = [];
      const alphabet = 'abcdefghijklmnopqrstuvwxyz';

      for (let i = 0; i < word.length; i++) {
          for (const char of alphabet) {
              const newWord = word.slice(0, i) + char + word.slice(i + 1);
              if (this.wordList[newWord]) {
                  suggestions.push(newWord);
              }
          }
      }

      return suggestions;
  }

  normalizeTextForLanguage(text: string): string {
      // You can implement language-specific text normalization here
      // For simplicity, let's just convert to lowercase
      return text.toLowerCase();
  }
}
SpellcheckerExtension.configure({
    proofreader: new Proofreader(wordListJson as WordList),
    uiStrings: {
      noSuggestions: "No suggestions found",
    },
  }),
gion-andri commented 3 months ago

I added two demo implementations in the demo folder. One of them is yours, @bryanjtc. Thank you for providing it.