Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions docs/demo/getFormattedSelection.md
Original file line number Diff line number Diff line change
@@ -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.
67 changes: 67 additions & 0 deletions src/getFormattedSelection.ts
Original file line number Diff line number Diff line change
@@ -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<string>();
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) };

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replacing useCursor with getFormattedSelection can change where the caret lands when text is selected. In this example, [bc] marks the selected text and | marks the caret.

Before formatting            a[bc]d
Formatted text               Xd
With useCursor               X|d
With getFormattedSelection   Xd|

Could we clarify in the PR description that the two behave the same when no text is selected?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the description: with no text selected the two give the same caret. With a selection they can differ, as in your example, because useCursor always restores a caret while getFormattedSelection places each edge on its own ([1234] formatted as 1,234 stays fully selected). In rc-input-number the selection is read after the edit (onChange and onCompositionEnd), so it is a caret after typing, pasting or deleting.

}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
76 changes: 76 additions & 0 deletions tests/getFormattedSelection.test.ts
Original file line number Diff line number Diff line change
@@ -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));
});
});