Repository navigation
feat: add getFormattedSelection to keep the caret after formatting #825
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nikzanda
wants to merge
4
commits into
react-component:master
Choose a base branch
from
nikzanda:feat/formatted-selection
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
138da46
feat: add getFormattedSelection to keep the caret after formatting
nikzanda 264fd40
test: cover where the fallback search starts
nikzanda 6d0c5c3
test: cover both sides of the fallback search start
nikzanda db41d9a
fix: match the characters before the caret ignoring case
nikzanda File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | ||
| }); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Replacing
useCursorwithgetFormattedSelectioncan change where the caret lands when text is selected. In this example,[bc]marks the selected text and|marks the caret.Could we clarify in the PR description that the two behave the same when no text is selected?
There was a problem hiding this comment.
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
useCursoralways restores a caret whilegetFormattedSelectionplaces each edge on its own ([1234]formatted as1,234stays fully selected). In rc-input-number the selection is read after the edit (onChangeandonCompositionEnd), so it is a caret after typing, pasting or deleting.