diff --git a/docs/demo/getFormattedSelection.md b/docs/demo/getFormattedSelection.md new file mode 100644 index 00000000..465a388b --- /dev/null +++ b/docs/demo/getFormattedSelection.md @@ -0,0 +1,40 @@ +# getFormattedSelection + +Adjust an input selection after its text is formatted, for example when a formatter adds a prefix or separators, or changes letter case. + +```tsx | pure +import { getFormattedSelection } from '@rc-component/util'; + +// When the input changes, before formatting +const originStr = input.value; +const selection = { start: input.selectionStart, end: input.selectionEnd }; +const targetStr = format(originStr); + +// After rendering `targetStr` +const { start, end } = getFormattedSelection(originStr, selection, targetStr); +input.setSelectionRange(start, end); +``` + +```ts +interface SelectionRange { + start: number; + end: number; +} + +function getFormattedSelection( + originStr: string, + selection: SelectionRange, + targetStr: string, +): SelectionRange; +``` + +Each edge of the selection is placed by the first rule that applies: + +| Rule | `originStr` | Caret | `targetStr` | Result | +| ------------------------------------------------------------------------------------- | ----------- | ----- | ----------- | ------ | +| Keep it after the same text before it | `5` | 1 | `5%` | 1 | +| Keep it before the same text after it | `12,34` | 3 | `1,234` | 3 | +| Place it after the characters before it, found in order and skipping the removed ones | `ABc-DE` | 3 | `AB-CD-E` | 4 | +| Move it to the start when none of them is left | `abc` | 1 | `xyz` | 0 | + +Characters are compared ignoring case, since formatters often change it. Offsets outside `originStr` are clamped, and the returned end is never before the start. The selection is not modified. diff --git a/src/getFormattedSelection.ts b/src/getFormattedSelection.ts new file mode 100644 index 00000000..dfe43a5f --- /dev/null +++ b/src/getFormattedSelection.ts @@ -0,0 +1,67 @@ +export interface SelectionRange { + start: number; + end: number; +} + +// Compare characters ignoring case, since formatters often change it +function toChars(str: string) { + return str.split('').map(char => char.toLowerCase()); +} + +function getFormattedOffset( + originChars: string[], + offset: number, + targetChars: string[], +) { + const position = Math.min(Math.max(offset, 0), originChars.length); + const beforeChars = originChars.slice(0, position); + const afterChars = originChars.slice(position); + const afterStart = targetChars.length - afterChars.length; + + if (beforeChars.every((char, index) => char === targetChars[index])) { + return position; + } + if ( + afterStart >= 0 && + afterChars.every((char, index) => char === targetChars[afterStart + index]) + ) { + return afterStart; + } + + // Both sides changed, e.g. `ABc-DE` formatted as `AB-CD-E`: find the + // characters before the caret in order, skipping the ones that were removed. + // A character that is missing is also missing further on, so it is skipped + // without searching again. + const missingChars = new Set(); + let targetIndex = 0; + beforeChars.forEach(char => { + if (missingChars.has(char)) { + return; + } + const index = targetChars.indexOf(char, targetIndex); + if (index === -1) { + missingChars.add(char); + } else { + targetIndex = index + 1; + } + }); + return targetIndex; +} + +/** + * Adjust a selection of `originStr` after it is formatted as `targetStr`. + * Each edge stays after the same text before it, or before the same text after + * it. Otherwise it goes after the characters before it that are still in the + * text, or to the start. Characters are compared ignoring case. + */ +export default function getFormattedSelection( + originStr: string, + selection: SelectionRange, + targetStr: string, +): SelectionRange { + const originChars = toChars(originStr); + const targetChars = toChars(targetStr); + const start = getFormattedOffset(originChars, selection.start, targetChars); + const end = getFormattedOffset(originChars, selection.end, targetChars); + return { start, end: Math.max(start, end) }; +} diff --git a/src/index.ts b/src/index.ts index fd0a01f3..a840cebe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -40,6 +40,8 @@ export { getShadowRoot } from './Dom/shadow'; export { isStyleSupport } from './Dom/styleChecker'; export { default as KeyCode } from './KeyCode'; +export { default as getFormattedSelection } from './getFormattedSelection'; +export type { SelectionRange } from './getFormattedSelection'; export { default as getScrollBarSize, getTargetScrollBarSize, diff --git a/tests/getFormattedSelection.test.ts b/tests/getFormattedSelection.test.ts new file mode 100644 index 00000000..9635b9e0 --- /dev/null +++ b/tests/getFormattedSelection.test.ts @@ -0,0 +1,76 @@ +import { getFormattedSelection } from '../src'; +import type { SelectionRange } from '../src'; + +const caret = (position: number): SelectionRange => ({ + start: position, + end: position, +}); + +describe('getFormattedSelection', () => { + it.each<[string, string, number, string, number]>([ + ['unchanged text', '12', 1, '12', 1], + ['an appended suffix', '5', 1, '5%', 1], + ['an uppercase character typed in the middle', 'AbC', 2, 'ABC', 2], + ['an uppercase character typed at the end', 'Ab', 2, 'AB', 2], + ['a prepended prefix', '1', 1, '$ 1', 3], + ['a prefix and thousands separators', '123456', 3, '$ 123,456', 6], + ['a removed separator', '12,34', 3, '1,234', 3], + ['a caret at the start', '1', 0, '$ 1', 0], + ['an empty origin', '', 0, '$ ', 0], + ])('keeps the caret with %s', (_, originStr, position, targetStr, result) => { + expect( + getFormattedSelection(originStr, caret(position), targetStr), + ).toEqual(caret(result)); + }); + + it.each<[string, string, number, string, number]>([ + // `$ ` typed `9` before the prefix + ['a character typed before a prefix', '9$ ', 1, '$ 9', 3], + // `AB-DE` typed `c` after `B` + ['uppercase characters regrouped in pairs', 'ABc-DE', 3, 'AB-CD-E', 4], + // `AA-AA` typed `a` after the second `A` + ['repeated characters', 'AAa-AA', 3, 'AA-AA-A', 4], + ])( + 'finds the characters before the caret in order when both sides change with %s', + (_, originStr, position, targetStr, result) => { + expect( + getFormattedSelection(originStr, caret(position), targetStr), + ).toEqual(caret(result)); + }, + ); + + it('skips characters removed by the formatter', () => { + expect(getFormattedSelection('AB11c-DE', caret(5), 'AB-CD-E')).toEqual( + caret(4), + ); + }); + + it('moves the caret to the start when no character before it is left', () => { + expect(getFormattedSelection('abc', caret(1), 'xyz')).toEqual(caret(0)); + }); + + it('adjusts each edge of a selection', () => { + expect( + getFormattedSelection('1234', { start: 1, end: 3 }, '1,234'), + ).toEqual({ start: 1, end: 4 }); + }); + + it('does not return a selection that ends before it starts', () => { + expect(getFormattedSelection('a-b', { start: 1, end: 2 }, 'b-a')).toEqual( + caret(3), + ); + }); + + it('clamps offsets outside the original text', () => { + expect(getFormattedSelection('ab', { start: -1, end: 10 }, 'AB')).toEqual({ + start: 0, + end: 2, + }); + }); + + it('does not modify the selection', () => { + const selection = Object.freeze(caret(1)); + getFormattedSelection('9$ ', selection, '$ 9'); + expect(selection).toEqual(caret(1)); + }); +});