Skip to content

Commit

Permalink
fix: reset UI selection after programmatic value change (#915)
Browse files Browse the repository at this point in the history
  • Loading branch information
ph-fritsche committed Apr 11, 2022
1 parent f5049c4 commit 8bc3310
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
9 changes: 8 additions & 1 deletion src/document/interceptor.ts
Expand Up @@ -28,6 +28,7 @@ export function prepareInterceptor<
*/
applyNative?: boolean
realArgs?: ImplReturn<ElementType[PropName]>
then?: () => void
},
) {
const prototypeDescriptor = Object.getOwnPropertyDescriptor(
Expand All @@ -49,7 +50,11 @@ export function prepareInterceptor<
this: ElementType,
...args: Params<ElementType[PropName]>
) {
const {applyNative = true, realArgs} = interceptorImpl.call(this, ...args)
const {
applyNative = true,
realArgs,
then,
} = interceptorImpl.call(this, ...args)

const realFunc = ((!applyNative && objectDescriptor) ||
(prototypeDescriptor as PropertyDescriptor))[target] as (
Expand All @@ -62,6 +67,8 @@ export function prepareInterceptor<
} else {
realFunc.call(this, ...realArgs)
}

then?.()
}
;(intercept as Interceptable)[Interceptor] = Interceptor

Expand Down
3 changes: 1 addition & 2 deletions src/document/value.ts
Expand Up @@ -32,13 +32,12 @@ function valueInterceptor(
if (isUI) {
this[UIValue] = String(v)
setPreviousValue(this, String(this.value))
} else {
trackOrSetValue(this, String(v))
}

return {
applyNative: !!isUI,
realArgs: sanitizeValue(this, v),
then: isUI ? undefined : () => trackOrSetValue(this, String(v)),
}
}

Expand Down
14 changes: 14 additions & 0 deletions tests/document/index.ts
Expand Up @@ -112,6 +112,20 @@ test('maintain selection range on elements without support for selection range',
expect(element.selectionStart).toBe(null)
})

test('reset UI selection if value is programmatically set', async () => {
const {element} = render<HTMLInputElement>(`<input/>`)

prepare(element)

setUIValue(element, 'abc')
setUISelection(element, {anchorOffset: 1, focusOffset: 2})

element.value = 'abcdef'
expect(element.selectionStart).toBe(6)
expect(getUISelection(element)).toHaveProperty('focusOffset', 6)
expect(getUISelection(element)).toHaveProperty('startOffset', 6)
})

test('clear UI selection if selection is programmatically set', async () => {
const {element} = render<HTMLInputElement>(`<input/>`)

Expand Down

0 comments on commit 8bc3310

Please sign in to comment.