diff --git a/packages/nc-gui-v2/utils/NcAutocompleteTree.ts b/packages/nc-gui-v2/utils/NcAutocompleteTree.ts new file mode 100644 index 0000000000..8af01f9812 --- /dev/null +++ b/packages/nc-gui-v2/utils/NcAutocompleteTree.ts @@ -0,0 +1,87 @@ +// ref : https://medium.com/weekly-webtips/js-implementing-auto-complete-f4c5a5d5c009 + +interface Node { + value: [] + isLeaf: boolean + children: Record +} + +export class NcAutocompleteTree { + trie: Record + suggestions: string[] + + constructor() { + this.trie = {} + this.suggestions = [] + } + + newNode(): Node { + return { + value: [], + isLeaf: false, + children: {}, + } + } + + add(word: Record) { + if (!this.trie) { + this.trie = this.newNode() + } + + let root = this.trie + for (const letter of word.text.toLowerCase()) { + if (!(letter in root.children)) { + root.children[letter] = this.newNode() + } + root = root.children[letter] + } + root.value = root.value || [] + root.value.push(word) + } + + find(word: string) { + let root = this.trie + for (const letter of word) { + if (letter in root.children) { + root = root.children[letter] + } else { + return null // if not found return null + } + } + + return root // return the root where it ends search + } + + traverse(root: Node) { + if (root.value && root.value.length) { + this.suggestions.push(...root.value) + } + + for (const letter in root.children) { + this.traverse(root.children[letter]) + } + } + + complete(word: string, CHILDREN = null) { + this.suggestions = [] + const root = this.find(word.toLowerCase()) + + if (!root) { + return this.suggestions + } // cannot suggest anything + + const children = root.children + + let spread = 0 + for (const letter in children) { + this.traverse(children[letter]) + spread++ + + if (CHILDREN && spread === CHILDREN) { + break + } + } + + return this.suggestions + } +} diff --git a/packages/nc-gui-v2/utils/index.ts b/packages/nc-gui-v2/utils/index.ts index 48125eb024..309388f94b 100644 --- a/packages/nc-gui-v2/utils/index.ts +++ b/packages/nc-gui-v2/utils/index.ts @@ -1,3 +1,4 @@ +export * from './NcAutocompleteTree' export * from './colorsUtils' export * from './dateTimeUtils' export * from './deepCompare'