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

[ML] Improvements for urlState hook. #70576

Merged
merged 16 commits into from
Jul 8, 2020
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
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
4 changes: 2 additions & 2 deletions x-pack/plugins/ml/public/application/util/url_state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { renderHook, act } from '@testing-library/react-hooks';
import { getUrlState, useUrlState } from './url_state';
import { parseUrlState, useUrlState } from './url_state';

const mockHistoryPush = jest.fn();

Expand All @@ -22,7 +22,7 @@ jest.mock('react-router-dom', () => ({
describe('getUrlState', () => {
test('properly decode url with _g and _a', () => {
expect(
getUrlState(
parseUrlState(
"?_a=(mlExplorerFilter:(),mlExplorerSwimlane:(viewByFieldName:action),query:(query_string:(analyze_wildcard:!t,query:'*')))&_g=(ml:(jobIds:!(dec-2)),refreshInterval:(display:Off,pause:!f,value:0),time:(from:'2019-01-01T00:03:40.000Z',mode:absolute,to:'2019-08-30T11:55:07.000Z'))&savedSearchId=571aaf70-4c88-11e8-b3d7-01146121b73d"
)
).toEqual({
Expand Down
109 changes: 71 additions & 38 deletions x-pack/plugins/ml/public/application/util/url_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { parse, stringify } from 'query-string';
import { useCallback } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { isEqual } from 'lodash';
import { decode, encode } from 'rison-node';
import { useHistory, useLocation } from 'react-router-dom';
Expand All @@ -30,7 +30,7 @@ function isRisonSerializationRequired(queryParam: string): boolean {
return risonSerializedParams.has(queryParam);
}

export function getUrlState(search: string): Dictionary<any> {
export function parseUrlState(search: string): Dictionary<any> {
const urlState: Dictionary<any> = {};
const parsedQueryString = parse(search, { sort: false });

Expand Down Expand Up @@ -58,54 +58,87 @@ export function getUrlState(search: string): Dictionary<any> {
// different urlStates(e.g. `_a` / `_g`) don't overwrite each other.
export const useUrlState = (accessor: string): UrlState => {
const history = useHistory();
const { search } = useLocation();
const { search: locationSearchString } = useLocation();

// We maintain a local state of useLocation's search.
// This allows us to use the callback variant of setSearch()
// later on so we can make sure we always act on the
// latest url state.
const [searchString, setSearchString] = useState(locationSearchString);

useEffect(() => {
setSearchString(locationSearchString);
}, [locationSearchString]);

useEffect(() => {
// Only push to history if something related to the accessor of this
// url state instance is affected (e.g. a change in '_g' should not trigger
// a push in the '_a' instance).
if (
!isEqual(parseUrlState(locationSearchString)[accessor], parseUrlState(searchString)[accessor])
Copy link
Contributor

Choose a reason for hiding this comment

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

looks like this effect should depend on two variables, you are missing locationSearchString

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added more comments in 3500f11 to explain why locationSearchString isn't necessary for comparison in this case.

) {
history.push({ search: searchString });
}
}, [searchString]);

const setUrlState = useCallback(
(attribute: string | Dictionary<any>, value?: any) => {
const urlState = getUrlState(search);
const parsedQueryString = parse(search, { sort: false });
setSearchString((prevSearchString) => {
const urlState = parseUrlState(prevSearchString);
const parsedQueryString = parse(prevSearchString, { sort: false });

if (!Object.prototype.hasOwnProperty.call(urlState, accessor)) {
urlState[accessor] = {};
}

if (typeof attribute === 'string') {
if (isEqual(getNestedProperty(urlState, `${accessor}.${attribute}`), value)) {
return;
if (!Object.prototype.hasOwnProperty.call(urlState, accessor)) {
urlState[accessor] = {};
}

urlState[accessor][attribute] = value;
} else {
const attributes = attribute;
Object.keys(attributes).forEach((a) => {
urlState[accessor][a] = attributes[a];
});
}
if (typeof attribute === 'string') {
if (isEqual(getNestedProperty(urlState, `${accessor}.${attribute}`), value)) {
return prevSearchString;
}

try {
const oldLocationSearch = stringify(parsedQueryString, { sort: false, encode: false });
urlState[accessor][attribute] = value;
} else {
const attributes = attribute;
Object.keys(attributes).forEach((a) => {
urlState[accessor][a] = attributes[a];
});
}

Object.keys(urlState).forEach((a) => {
if (isRisonSerializationRequired(a)) {
parsedQueryString[a] = encode(urlState[a]);
} else {
parsedQueryString[a] = urlState[a];
}
});
const newLocationSearch = stringify(parsedQueryString, { sort: false, encode: false });
try {
const oldLocationSearchString = stringify(parsedQueryString, {
sort: false,
encode: false,
});

if (oldLocationSearch !== newLocationSearch) {
history.push({
search: stringify(parsedQueryString, { sort: false }),
Object.keys(urlState).forEach((a) => {
if (isRisonSerializationRequired(a)) {
parsedQueryString[a] = encode(urlState[a]);
} else {
parsedQueryString[a] = urlState[a];
}
});
const newLocationSearchString = stringify(parsedQueryString, {
sort: false,
encode: false,
});

if (oldLocationSearchString !== newLocationSearchString) {
return stringify(parsedQueryString, { sort: false });
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Could not save url state', error);
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Could not save url state', error);
}

// as a fallback and to satisfy the hooks callback requirements
// return the previous state if we didn't need or were not able to update.
return prevSearchString;
});
},
[search]
[searchString]
);

return [getUrlState(search)[accessor], setUrlState];
const urlState = useMemo(() => parseUrlState(searchString)[accessor], [searchString]);
Copy link
Contributor

Choose a reason for hiding this comment

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

I think it worth to mention in a comment for this hook that it does not react on the accessor parameter update

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good point, the accessor should never be changed, I updated the code to enforce that so it only ever considers the value passed on first call: 3500f11#diff-42f8ed66c3f1b64589d16f1b4c9d1aa2R63-R65


return [urlState, setUrlState];
};