fix(blocksAntd): Maintain cursor position for input blocks. Closes #344

This commit is contained in:
Gervwyk 2021-02-05 10:56:01 +02:00
parent f0afafb4ff
commit 7e90fed8c6
3 changed files with 30 additions and 0 deletions

View File

@ -19,6 +19,7 @@ import { type } from '@lowdefy/helpers';
import { blockDefaultProps } from '@lowdefy/block-tools';
import { Input } from 'antd';
import Label from '../Label/Label';
import useRunAfterUpdate from '../../useRunAfterUpdate';
const TextAreaComp = Input.TextArea;
@ -43,6 +44,7 @@ const TextAreaBlock = ({
methods={methods}
content={{
content: () => {
const runAfterUpdate = useRunAfterUpdate();
return (
<TextAreaComp
id={`${blockId}_input`}
@ -52,6 +54,11 @@ const TextAreaBlock = ({
onChange={(event) => {
methods.setValue(event.target.value);
methods.triggerEvent({ name: 'onChange' });
const cStart = event.target.selectionStart;
const cEnd = event.target.selectionEnd;
runAfterUpdate(() => {
event.target.setSelectionRange(cStart, cEnd);
});
}}
onPressEnter={() => {
methods.triggerEvent({ name: 'onPressEnter' });

View File

@ -20,6 +20,7 @@ import { blockDefaultProps } from '@lowdefy/block-tools';
import Label from '../Label/Label';
import Icon from '../Icon/Icon';
import useRunAfterUpdate from '../../useRunAfterUpdate';
const TextInput = ({
blockId,
@ -42,6 +43,7 @@ const TextInput = ({
validation={validation}
content={{
content: () => {
const runAfterUpdate = useRunAfterUpdate();
return (
<Input
id={`${blockId}_input`}
@ -51,6 +53,11 @@ const TextInput = ({
onChange={(event) => {
methods.setValue(event.target.value);
methods.triggerEvent({ name: 'onChange' });
const cStart = event.target.selectionStart;
const cEnd = event.target.selectionEnd;
runAfterUpdate(() => {
event.target.setSelectionRange(cStart, cEnd);
});
}}
onPressEnter={() => {
methods.triggerEvent({ name: 'onPressEnter' });

View File

@ -0,0 +1,16 @@
import React from 'react';
const useRunAfterUpdate = () => {
const afterPaintRef = React.useRef(null);
React.useLayoutEffect(() => {
if (afterPaintRef.current) {
afterPaintRef.current();
afterPaintRef.current = null;
}
});
return (fn) => {
afterPaintRef.current = fn;
};
};
export default useRunAfterUpdate;