Skip to content
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

Introduce <FilterLiveForm> #10344

Merged
merged 33 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
55555fd
wip: first working version
slax57 Nov 12, 2024
8c3bec7
wip: own story and defaultValues
slax57 Nov 12, 2024
8acaf9e
wip: more stories and fix per input validation
slax57 Nov 12, 2024
612ebc1
wip: story with ReferenceInput
slax57 Nov 12, 2024
c68e047
wip: add resettable everywhere
slax57 Nov 12, 2024
8c8d011
wip: add AsListActions story
slax57 Nov 12, 2024
ae9faa0
introduce FilterListWrapper and make stories more beautiful
slax57 Nov 12, 2024
af34890
move AutoSubmitFilterForm to ra-core
slax57 Nov 12, 2024
41780ed
trigger debounce bug in stories
slax57 Nov 14, 2024
e1342d4
fix and debug code
slax57 Nov 14, 2024
159cfd8
fix fix
slax57 Nov 14, 2024
3b0cb94
remove useless useListParams stories
slax57 Nov 14, 2024
8164dfb
apply fix to AutoSubmitFilterForm and remove tech debt from FilterForm
slax57 Nov 14, 2024
1512a1d
fix unit test
slax57 Nov 14, 2024
0c136e3
add missing FormGroupsProvider
slax57 Nov 14, 2024
719fc75
refactor FilterLiveSearch to use AutoSubmitFilterForm + fix AutoSubmi…
slax57 Nov 14, 2024
762b687
add FilterLiveSearch FullApp story
slax57 Nov 15, 2024
5362261
add filterlivesearch reapply old value bug unit test
slax57 Nov 15, 2024
47384c8
use AutoSubmitFilterForm in FilterForm
slax57 Nov 15, 2024
5b58e7e
improve AutoSubmitFilterForm component prop default value
slax57 Nov 15, 2024
b6b8eaf
add tests for AutoSubmitFilterForm
slax57 Nov 15, 2024
01c5429
add test for race condition bug
slax57 Nov 15, 2024
e8005b1
remove debug code
slax57 Nov 15, 2024
fbb3837
add docs for AutoSubmitFilterForm
slax57 Nov 15, 2024
482e83d
improve discoverability
slax57 Nov 15, 2024
0946f6e
fix Liquid syntax error
slax57 Nov 15, 2024
e34fa24
code review
slax57 Nov 20, 2024
36d5a45
move AutoSubmitFilterForm in form folder
slax57 Nov 20, 2024
eeee44f
reintroduce unset
slax57 Nov 20, 2024
fc30c5a
rename component to formComponent
slax57 Nov 20, 2024
9f0ef08
rename FilterListWrapper to FilterListSection
slax57 Nov 20, 2024
05e926f
rename AutoSubmitFilterForm to FilterLiveForm
slax57 Nov 20, 2024
7fd23c6
rename assets
slax57 Nov 20, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import * as React from 'react';

import { AutoSubmitFilterForm, AutoSubmitFilterFormProps } from '.';
import { useInput, required } from '../../../form';
import { ListContextProvider } from '../ListContextProvider';
import { useList } from '../useList';
import { useListContext } from '../useListContext';

export default { title: 'ra-core/controller/list/filter/AutoSubmitFilterForm' };

const TextInput = props => {
const { field, fieldState } = useInput(props);
const { error } = fieldState;

return (
<div
style={{
margin: '1em',
display: 'flex',
flexDirection: 'column',
gap: '5px',
}}
>
<label htmlFor={field.name}>{props.label || field.name}</label>
<input {...field} />
{error && (
<div style={{ color: 'red' }}>
{/* @ts-ignore */}
{error.message?.message || error.message}
</div>
)}
</div>
);
};

export const Basic = (props: Partial<AutoSubmitFilterFormProps>) => {
const listContext = useList({
data: [
{ id: 1, title: 'Hello', has_newsletter: true },
{ id: 2, title: 'World', has_newsletter: false },
],
filter: {
category: 'deals',
},
});
return (
<ListContextProvider value={listContext}>
<AutoSubmitFilterForm {...props}>
<TextInput source="title" />
</AutoSubmitFilterForm>
<FilterValue />
</ListContextProvider>
);
};

export const NoDebounce = () => <Basic debounce={false} />;

export const MultipleInput = () => {
const listContext = useList({
data: [
{ id: 1, title: 'Hello', has_newsletter: true },
{ id: 2, title: 'World', has_newsletter: false },
],
filter: {
category: 'deals',
},
});
return (
<ListContextProvider value={listContext}>
<AutoSubmitFilterForm>
<TextInput source="title" />
<TextInput source="author" />
</AutoSubmitFilterForm>
<FilterValue />
</ListContextProvider>
);
};

export const MultipleAutoSubmitFilterForm = () => {
const listContext = useList({
data: [
{ id: 1, title: 'Hello', has_newsletter: true },
{ id: 2, title: 'World', has_newsletter: false },
],
filter: {
category: 'deals',
},
});
return (
<ListContextProvider value={listContext}>
<AutoSubmitFilterForm>
<TextInput source="title" />
</AutoSubmitFilterForm>
<AutoSubmitFilterForm>
<TextInput source="author" />
</AutoSubmitFilterForm>
<FilterValue />
</ListContextProvider>
);
};

export const PerInputValidation = () => {
const listContext = useList({
data: [
{ id: 1, title: 'Hello', has_newsletter: true },
{ id: 2, title: 'World', has_newsletter: false },
],
filter: {
category: 'deals',
author: 'Leo Tolstoy',
},
});
return (
<ListContextProvider value={listContext}>
<AutoSubmitFilterForm>
<TextInput source="title" />
<TextInput source="author" validate={required()} />
</AutoSubmitFilterForm>
<FilterValue />
</ListContextProvider>
);
};

const validateFilters = values => {
const errors: any = {};
if (!values.author) {
errors.author = 'The author is required';
}
return errors;
};
export const GlobalValidation = () => {
const listContext = useList({
data: [
{ id: 1, title: 'Hello', has_newsletter: true },
{ id: 2, title: 'World', has_newsletter: false },
],
filter: {
category: 'deals',
author: 'Leo Tolstoy',
},
});
return (
<ListContextProvider value={listContext}>
<AutoSubmitFilterForm validate={validateFilters}>
<TextInput source="title" />
<TextInput source="author" isRequired />
</AutoSubmitFilterForm>
<FilterValue />
</ListContextProvider>
);
};

const FilterValue = () => {
const { filterValues } = useListContext();
return (
<div style={{ margin: '1em' }}>
<p>Filter values:</p>
<pre>{JSON.stringify(filterValues, null, 2)}</pre>
<pre style={{ display: 'none' }} data-testid="filter-values">
{JSON.stringify(filterValues)}
</pre>
</div>
);
};
183 changes: 183 additions & 0 deletions packages/ra-core/src/controller/list/filter/AutoSubmitFilterForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import isEqual from 'lodash/isEqual';
import cloneDeep from 'lodash/cloneDeep';
import get from 'lodash/get';
import * as React from 'react';
import { ReactNode, useEffect } from 'react';
import { FormProvider, useForm, UseFormProps } from 'react-hook-form';
import {
SourceContextProvider,
SourceContextValue,
useResourceContext,
} from '../../../core';
import {
FormGroupsProvider,
getSimpleValidationResolver,
ValidateForm,
} from '../../../form';
import { useDebouncedEvent, useEvent } from '../../../util';
import { useListFilterContext } from '../useListFilterContext';

/**
* TODO
*/
export const AutoSubmitFilterForm = (props: AutoSubmitFilterFormProps) => {
const { filterValues, setFilters } = useListFilterContext();
const resource = useResourceContext(props);

const { debounce = 500, resolver, validate, children, ...rest } = props;

const finalResolver = resolver
? resolver
: validate
? getSimpleValidationResolver(validate)
: undefined;

const form = useForm({
mode: 'onChange',
defaultValues: filterValues,
resolver: finalResolver,
...rest,
});
const { handleSubmit, getValues, reset, watch, formState } = form;
const { isValid } = formState;

// Ref tracking if there are internal changes pending, i.e. changes that
// should not trigger a reset
const formChangesPending = React.useRef(false);

// Reapply filterValues when they change externally
useEffect(() => {
const newValues = getFilterFormValues(getValues(), filterValues);
const previousValues = getValues();
console.log('AutoSubmitFilterForm useEffect', {
formChangesPending: formChangesPending.current,
newValues,
previousValues,
filterValues,
});
if (formChangesPending.current) {
// The effect was triggered by a form change (i.e. internal change),
// so we don't need to reset the form
formChangesPending.current = false;
return;
}
if (!isEqual(newValues, previousValues)) {
console.log('AutoSubmitFilterForm called reset !', {
newValues,
});
reset(newValues);
}
// The reference to the filterValues object is not updated when it changes,
// so we must stringify it to compare it by value.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [JSON.stringify(filterValues), getValues, reset]);

const onSubmit = useEvent((values: any): void => {
// Do not call setFilters if the form is invalid
if (!isValid) {
return;
}
console.log('calling setFilters with', {
...filterValues,
...values,
});
formChangesPending.current = true;
setFilters({
...filterValues,
...values,
});
});
const debouncedOnSubmit = useDebouncedEvent(onSubmit, debounce || 0);

// Submit the form on values change
useEffect(() => {
const { unsubscribe } = watch((values, { name }) => {
// Check that the name is present to avoid setting filters when
// watch was triggered by a reset
if (name) {
debouncedOnSubmit(values);
}
});
return () => unsubscribe();
}, [watch, debouncedOnSubmit]);

const sourceContext = React.useMemo<SourceContextValue>(
() => ({
getSource: (source: string) => source,
getLabel: (source: string) =>
`resources.${resource}.fields.${source}`,
}),
[resource]
);

return (
<FormProvider {...form}>
<FormGroupsProvider>
<SourceContextProvider value={sourceContext}>
<form onSubmit={handleSubmit(onSubmit)}>{children}</form>
</SourceContextProvider>
</FormGroupsProvider>
</FormProvider>
);
};

export interface AutoSubmitFilterFormProps
extends Omit<UseFormProps, 'onSubmit' | 'defaultValues'> {
children: ReactNode;
validate?: ValidateForm;
debounce?: number | false;
resource?: string;
}

/**
* Because we are using controlled inputs with react-hook-form, we must provide a default value
* for each input when resetting the form. (see https://react-hook-form.com/docs/useform/reset).
* To ensure we don't provide undefined which will result to the current input value being reapplied
* and due to the dynamic nature of the filter form, we rebuild the filter form values from its current
* values and make sure to pass at least an empty string for each input.
*/
const getFilterFormValues = (
formValues: Record<string, any>,
filterValues: Record<string, any>
) => {
return Object.keys(formValues).reduce(
(acc, key) => {
acc[key] = getInputValue(formValues, key, filterValues);
return acc;
},
cloneDeep(filterValues) ?? {}
);
};

const getInputValue = (
formValues: Record<string, any>,
key: string,
filterValues: Record<string, any>
) => {
if (formValues[key] === undefined || formValues[key] === null) {
return get(filterValues, key, '');
}
if (Array.isArray(formValues[key])) {
return get(filterValues, key, '');
}
if (formValues[key] instanceof Date) {
return get(filterValues, key, '');
}
if (typeof formValues[key] === 'object') {
const inputValues = Object.keys(formValues[key]).reduce(
(acc, innerKey) => {
const nestedInputValue = getInputValue(
formValues[key],
innerKey,
(filterValues || {})[key] ?? {}
);
acc[innerKey] = nestedInputValue;
return acc;
},
{}
);
if (!Object.keys(inputValues).length) return '';
return inputValues;
}
return get(filterValues, key, '');
};
1 change: 1 addition & 0 deletions packages/ra-core/src/controller/list/filter/index.ts
fzaninotto marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './AutoSubmitFilterForm';
1 change: 1 addition & 0 deletions packages/ra-core/src/controller/list/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ export * from './useRecordSelection';
export * from './useUnselect';
export * from './useUnselectAll';
export * from './WithListContext';
export * from './filter';
1 change: 1 addition & 0 deletions packages/ra-core/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { getMutationMode } from './getMutationMode';
export * from './getFieldLabelTranslationArgs';
export * from './mergeRefs';
export * from './useEvent';
export * from './useDebouncedEvent';
export * from './useFieldValue';

export {
Expand Down
21 changes: 21 additions & 0 deletions packages/ra-core/src/util/useDebouncedEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useCallback, useRef, useEffect } from 'react';
import debounce from 'lodash/debounce';

// TODO: create BL cards to deprecate the one in EE and use this one instead

// Hook somewhat equivalent to useEvent, but with a debounce
// Returns a debounced callback which will not change across re-renders unless the
// callback or delay changes
export const useDebouncedEvent = (callback, delay: number) => {
// Create a ref that stores the debounced callback
const debouncedCallbackRef = useRef(debounce(callback, delay));

// Whenever callback or delay changes, we need to update the debounced callback
useEffect(() => {
debouncedCallbackRef.current = debounce(callback, delay);
}, [callback, delay]);

// The function returned by useCallback will invoke the debounced callback
// Its dependencies array is empty, so it never changes across re-renders
return useCallback((...args) => debouncedCallbackRef.current(...args), []);
};
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't have the checks we do in useEvent to prevent calling the callback inside a render. I'm not really sure of the consequences but the react team has made it a strong limitation of useEvent (see its code in our repo)

Loading
Loading