fix(editor): match the whole word under the cursor in autocomplete

This commit is contained in:
Erwan Leboucher committed 2026-08-08 10:50:52 +02:00
1 parent f680623113
commit 12922a31cc
2 files changed
+52 -7

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
import { createEditor, Editor, Transforms } from 'slate';
import { describe, expect, it } from 'vitest';
import { getPrevWorldRange } from './utils';
import { BlockType } from './types';
const createTestEditor = (text: string) => {
const editor = createEditor();
editor.children = [{ type: BlockType.Paragraph, children: [{ text }] }];
return editor;
};
const selectAt = (editor: Editor, offset: number) => {
Transforms.select(editor, { path: [0, 0], offset });
};
describe('getPrevWorldRange', () => {
it('returns the word before the cursor', () => {
const editor = createTestEditor('hello :smile world');
selectAt(editor, 12);
const range = getPrevWorldRange(editor);
expect(range && Editor.string(editor, range)).toBe(':smile');
});
it('returns the whole word when the cursor sits inside it', () => {
const editor = createTestEditor('hello :smile world');
selectAt(editor, 9);
const range = getPrevWorldRange(editor);
expect(range && Editor.string(editor, range)).toBe(':smile');
});
it('returns the whole word when the cursor sits inside the last word', () => {
const editor = createTestEditor('hello :smile');
selectAt(editor, 9);
const range = getPrevWorldRange(editor);
expect(range && Editor.string(editor, range)).toBe(':smile');
});
});
+12 -7
View File
@@ -181,11 +181,11 @@ const getPointUntilChar = (
let prevPoint: BasePoint | undefined;
let char: string | undefined;
const startPoint = Editor.point(editor, cursorPoint, { edge: 'start' });
const pointItr = Editor.positions(editor, {
at: {
anchor: Editor.start(editor, []),
focus: Editor.point(editor, cursorPoint, { edge: 'start' }),
},
at: options.reverse
? { anchor: Editor.start(editor, []), focus: startPoint }
: { anchor: startPoint, focus: Editor.end(editor, []) },
unit: 'character',
reverse: options.reverse,
});
@@ -202,16 +202,21 @@ const getPointUntilChar = (
return targetPoint;
};
// line breaks produce empty chars, not \n
const isWorldBoundary = (char: string) => /\s|^$/.test(char);
export const getPrevWorldRange = (editor: Editor): BaseRange | undefined => {
const { selection } = editor;
if (!selection || !Range.isCollapsed(selection)) return undefined;
const [cursorPoint] = Range.edges(selection);
const worldStartPoint = getPointUntilChar(editor, cursorPoint, {
reverse: true,
// line breaks produce empty chars, not \n
match: (char) => /\s|^$/.test(char),
match: isWorldBoundary,
});
return worldStartPoint && Editor.range(editor, worldStartPoint, cursorPoint);
if (!worldStartPoint) return undefined;
const worldEndPoint =
getPointUntilChar(editor, cursorPoint, { match: isWorldBoundary }) ?? cursorPoint;
return Editor.range(editor, worldStartPoint, worldEndPoint);
};
export const isEmptyEditor = (editor: Editor): boolean => {