From 138da4652ada77ff3a6096143ae866f50d874346 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Zandarin?= Date: Sat, 31 Oct 2026 08:37:44 +0100 Subject: [PATCH 1/4] feat: add getFormattedSelection to keep the caret after formatting --- docs/demo/getFormattedSelection.md | 40 +++++++++++++++++++ src/getFormattedSelection.ts | 41 ++++++++++++++++++++ src/index.ts | 2 + tests/getFormattedSelection.test.ts | 59 +++++++++++++++++++++++++++++ 4 files changed, 142 insertions(+) create mode 100644 docs/demo/getFormattedSelection.md create mode 100644 src/getFormattedSelection.ts create mode 100644 tests/getFormattedSelection.test.ts diff --git a/docs/demo/getFormattedSelection.md b/docs/demo/getFormattedSelection.md new file mode 100644 index 00000000..1d264883 --- /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 | `AbC` | 2 | `ABC` | 2 | +| Place it after the character before it, searched from its previous position | `9$ ` | 1 | `$ 9` | 3 | +| Move it to the end when that character is gone | `abc` | 1 | `xyz` | 3 | + +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..ba8d3226 --- /dev/null +++ b/src/getFormattedSelection.ts @@ -0,0 +1,41 @@ +export interface SelectionRange { + start: number; + end: number; +} + +function getFormattedOffset( + originStr: string, + offset: number, + targetStr: string, +) { + const position = Math.min(Math.max(offset, 0), originStr.length); + const beforeStr = originStr.slice(0, position); + const afterStr = originStr.slice(position); + + if (targetStr.startsWith(beforeStr)) { + return position; + } + if (targetStr.endsWith(afterStr)) { + return targetStr.length - afterStr.length; + } + + // Both sides changed, e.g. `9$ ` formatted as `$ 9`: follow the character + // before the caret, searching from its previous position. + const index = targetStr.indexOf(originStr[position - 1], position - 1); + return index === -1 ? targetStr.length : index + 1; +} + +/** + * 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 follows the character before it, or moves to the end. + */ +export default function getFormattedSelection( + originStr: string, + selection: SelectionRange, + targetStr: string, +): SelectionRange { + const start = getFormattedOffset(originStr, selection.start, targetStr); + const end = getFormattedOffset(originStr, selection.end, targetStr); + 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..f47ccf7c --- /dev/null +++ b/tests/getFormattedSelection.test.ts @@ -0,0 +1,59 @@ +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('follows the character before the caret when both sides change', () => { + // `$ ` typed `9` before the prefix, then formatted as `$ 9`. + expect(getFormattedSelection('9$ ', caret(1), '$ 9')).toEqual(caret(3)); + }); + + it('moves the caret to the end when the character before it is gone', () => { + expect(getFormattedSelection('abc', caret(1), 'xyz')).toEqual(caret(3)); + }); + + 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)); + }); +}); From 264fd40186298c34818c74b8874d55d1a3da3894 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Zandarin?= Date: Sat, 31 Oct 2026 08:51:21 +0100 Subject: [PATCH 2/4] test: cover where the fallback search starts --- tests/getFormattedSelection.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/getFormattedSelection.test.ts b/tests/getFormattedSelection.test.ts index f47ccf7c..86cc3e97 100644 --- a/tests/getFormattedSelection.test.ts +++ b/tests/getFormattedSelection.test.ts @@ -28,6 +28,11 @@ describe('getFormattedSelection', () => { expect(getFormattedSelection('9$ ', caret(1), '$ 9')).toEqual(caret(3)); }); + it('searches for the character before the caret from its previous position', () => { + // `$` is at index 0, before the search starts at index 1, so it is not found. + expect(getFormattedSelection('9$ ', caret(2), '$ 9')).toEqual(caret(3)); + }); + it('moves the caret to the end when the character before it is gone', () => { expect(getFormattedSelection('abc', caret(1), 'xyz')).toEqual(caret(3)); }); From 6d0c5c38ed2ee612b94d493b004330977c3b38b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Zandarin?= Date: Sat, 31 Oct 2026 11:52:18 +0100 Subject: [PATCH 3/4] test: cover both sides of the fallback search start --- tests/getFormattedSelection.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/getFormattedSelection.test.ts b/tests/getFormattedSelection.test.ts index 86cc3e97..5d3a4ac8 100644 --- a/tests/getFormattedSelection.test.ts +++ b/tests/getFormattedSelection.test.ts @@ -31,6 +31,8 @@ describe('getFormattedSelection', () => { it('searches for the character before the caret from its previous position', () => { // `$` is at index 0, before the search starts at index 1, so it is not found. expect(getFormattedSelection('9$ ', caret(2), '$ 9')).toEqual(caret(3)); + // `b` is still at index 1, where the search starts, so it is found. + expect(getFormattedSelection('abX', caret(2), 'ZbY')).toEqual(caret(2)); }); it('moves the caret to the end when the character before it is gone', () => { From db41d9a490523b0f70a6e4ae12829063d95f7605 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Zandarin?= Date: Tue, 1 Dec 2026 09:08:08 +0100 Subject: [PATCH 4/4] fix: match the characters before the caret ignoring case --- docs/demo/getFormattedSelection.md | 16 ++++----- src/getFormattedSelection.ts | 56 +++++++++++++++++++++-------- tests/getFormattedSelection.test.ts | 32 +++++++++++------ 3 files changed, 70 insertions(+), 34 deletions(-) diff --git a/docs/demo/getFormattedSelection.md b/docs/demo/getFormattedSelection.md index 1d264883..465a388b 100644 --- a/docs/demo/getFormattedSelection.md +++ b/docs/demo/getFormattedSelection.md @@ -30,11 +30,11 @@ function getFormattedSelection( 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 | `AbC` | 2 | `ABC` | 2 | -| Place it after the character before it, searched from its previous position | `9$ ` | 1 | `$ 9` | 3 | -| Move it to the end when that character is gone | `abc` | 1 | `xyz` | 3 | - -Offsets outside `originStr` are clamped, and the returned end is never before the start. The selection is not modified. +| 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 index ba8d3226..dfe43a5f 100644 --- a/src/getFormattedSelection.ts +++ b/src/getFormattedSelection.ts @@ -3,39 +3,65 @@ export interface SelectionRange { end: number; } +// Compare characters ignoring case, since formatters often change it +function toChars(str: string) { + return str.split('').map(char => char.toLowerCase()); +} + function getFormattedOffset( - originStr: string, + originChars: string[], offset: number, - targetStr: string, + targetChars: string[], ) { - const position = Math.min(Math.max(offset, 0), originStr.length); - const beforeStr = originStr.slice(0, position); - const afterStr = originStr.slice(position); + 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 (targetStr.startsWith(beforeStr)) { + if (beforeChars.every((char, index) => char === targetChars[index])) { return position; } - if (targetStr.endsWith(afterStr)) { - return targetStr.length - afterStr.length; + if ( + afterStart >= 0 && + afterChars.every((char, index) => char === targetChars[afterStart + index]) + ) { + return afterStart; } - // Both sides changed, e.g. `9$ ` formatted as `$ 9`: follow the character - // before the caret, searching from its previous position. - const index = targetStr.indexOf(originStr[position - 1], position - 1); - return index === -1 ? targetStr.length : index + 1; + // 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 follows the character before it, or moves to the end. + * 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 start = getFormattedOffset(originStr, selection.start, targetStr); - const end = getFormattedOffset(originStr, selection.end, targetStr); + 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/tests/getFormattedSelection.test.ts b/tests/getFormattedSelection.test.ts index 5d3a4ac8..9635b9e0 100644 --- a/tests/getFormattedSelection.test.ts +++ b/tests/getFormattedSelection.test.ts @@ -23,20 +23,30 @@ describe('getFormattedSelection', () => { ).toEqual(caret(result)); }); - it('follows the character before the caret when both sides change', () => { - // `$ ` typed `9` before the prefix, then formatted as `$ 9`. - expect(getFormattedSelection('9$ ', caret(1), '$ 9')).toEqual(caret(3)); - }); + 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('searches for the character before the caret from its previous position', () => { - // `$` is at index 0, before the search starts at index 1, so it is not found. - expect(getFormattedSelection('9$ ', caret(2), '$ 9')).toEqual(caret(3)); - // `b` is still at index 1, where the search starts, so it is found. - expect(getFormattedSelection('abX', caret(2), 'ZbY')).toEqual(caret(2)); + 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 end when the character before it is gone', () => { - expect(getFormattedSelection('abc', caret(1), 'xyz')).toEqual(caret(3)); + 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', () => {