Skip to content

Commit

Permalink
fix: defer change update for number input (storybookjs#291)
Browse files Browse the repository at this point in the history
  • Loading branch information
raychanks committed Jan 12, 2022
1 parent ce5fb5a commit 1f97003
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
10 changes: 8 additions & 2 deletions addons/ondevice-controls/src/PropForm.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React from 'react';
import React, { memo } from 'react';
import { View } from 'react-native';
import deepEqual from 'deep-equal';

import { ArgTypes } from './ControlsPanel';
import PropField from './PropField';

Expand All @@ -25,4 +27,8 @@ const PropForm = ({ args, onFieldChange }: FormProps) => {
);
};

export default PropForm;
const deepStrictEqual = (a: any, b: any): boolean => {
return deepEqual(a, b, { strict: true });
};

export default memo(PropForm, deepStrictEqual);
33 changes: 28 additions & 5 deletions addons/ondevice-controls/src/types/Number.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useState, useEffect, useRef } from 'react';
import { StyleSheet, View } from 'react-native';
import Slider from '@react-native-community/slider';
import styled from '@emotion/native';
Expand Down Expand Up @@ -26,18 +26,35 @@ export interface NumberProps {
onChange: (value: any) => void;
}

const replaceComma = (value: number | string): string => {
return typeof value === 'string' ? value.trim().replace(/,/, '.') : value.toString();
};

const NumberType = ({ arg, onChange = (value) => value }: NumberProps) => {
const allowComma = typeof arg.value === 'string' ? arg.value.trim().replace(/,/, '.') : arg.value;
const showError = Number.isNaN(Number(allowComma));
const allowComma = replaceComma(arg.value);
const [numStr, setNumStr] = useState(allowComma);
const numStrRef = useRef(numStr);
const showError = Number.isNaN(Number(numStr));

const commitChange = () => {
onChange(numStr);
};

const renderNormal = () => {
return (
<Input
autoCapitalize="none"
underlineColorAndroid="transparent"
value={arg.value.toString()}
value={numStr}
keyboardType="numeric"
onChangeText={onChange}
onChangeText={(text) => {
const commaReplaced = replaceComma(text);

setNumStr(commaReplaced);
numStrRef.current = commaReplaced;
}}
onSubmitEditing={commitChange}
onEndEditing={commitChange}
style={showError && styles.errorBorder}
/>
);
Expand All @@ -55,6 +72,12 @@ const NumberType = ({ arg, onChange = (value) => value }: NumberProps) => {
);
};

useEffect(() => {
return () => {
onChange(numStrRef.current);
};
}, [onChange]);

return <View style={styles.spacing}>{arg.range ? renderRange() : renderNormal()}</View>;
};

Expand Down

0 comments on commit 1f97003

Please sign in to comment.