Skip to content

Commit

Permalink
#760 Fix input caret jumping to end when typing
Browse files Browse the repository at this point in the history
  • Loading branch information
Polleps committed Feb 14, 2024
1 parent e88696c commit 9c2e61a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ export function PropertyForm({
category,
}: PropertyFormProps): JSX.Element {
const [nameError, setNameError, onNameBlur] = useValidation('Required');

const valueOptions = useMemo(
() => ({
handleValidationError(e: Error | undefined) {
Expand Down
32 changes: 15 additions & 17 deletions browser/react/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,8 @@ type useValueOptions = {
* // Simple usage:
* const resource = useResource('https://atomicdata.dev/classes/Agent');
* const [shortname, setShortname] = useValue(
* 'https://atomicdata.dev/properties/shortname',
* resource,
* 'https://atomicdata.dev/properties/shortname',
* );
* ```
*
Expand All @@ -198,8 +198,8 @@ type useValueOptions = {
* const resource = useResource('https://atomicdata.dev/classes/Agent');
* const [error, setError] = useState(null);
* const [shortname, setShortname] = useValue(
* 'https://atomicdata.dev/properties/shortname',
* resource,
* 'https://atomicdata.dev/properties/shortname',
* {
* commit: true,
* validate: true,
Expand All @@ -220,10 +220,12 @@ export function useValue(
commitDebounce = 100,
handleValidationError,
} = opts;
const [val, set] = useState<JSONValue>(undefined);
const [val, set] = useState<JSONValue>(resource.get(propertyURL));
const [prevResourceReference, setPrevResourceReference] = useState(resource);

const store = useStore();

const [saveResource, isWaitingForDebounce] = useDebouncedCallback(
const [saveResource] = useDebouncedCallback(
() => {
if (!commit) {
return;
Expand Down Expand Up @@ -269,22 +271,18 @@ export function useValue(
[resource, handleValidationError, store, validate, saveResource],
);

// If the hook is waiting to commit the changes return the current local value so the component using this hook shows the most recent value.
if (isWaitingForDebounce) {
return [val, validateAndSet];
}

// Value hasn't been set in state yet, so get the value
let value: JSONValue = undefined;
// Update value when resource changes.
if (resource !== prevResourceReference) {
try {
set(resource.get(propertyURL));
} catch (e) {
store.notifyError(e);
}

// Try to actually get the value, log any error
try {
value = resource.get(propertyURL);
} catch (e) {
store.notifyError(e);
setPrevResourceReference(resource);
}

return [value, validateAndSet];
return [val, validateAndSet];
}

/**
Expand Down

0 comments on commit 9c2e61a

Please sign in to comment.