[ML] Add new storeInHashQuery and replaceUrlQuery (#74955)

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
This commit is contained in:
Quynh Nguyen 2020-08-14 10:34:08 -05:00 committed by GitHub
parent 344e1de7e1
commit f1ad1f1b7b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 3 deletions

View file

@ -22,6 +22,23 @@ import { stringify, ParsedQuery } from 'query-string';
import { parseUrl, parseUrlHash } from './parse';
import { url as urlUtils } from '../../../common';
export function replaceUrlQuery(
rawUrl: string,
queryReplacer: (query: ParsedQuery) => ParsedQuery
) {
const url = parseUrl(rawUrl);
const newQuery = queryReplacer(url.query || {});
const searchQueryString = stringify(urlUtils.encodeQuery(newQuery), {
sort: false,
encode: false,
});
if (!url.search && !searchQueryString) return rawUrl; // nothing to change. return original url
return formatUrl({
...url,
search: searchQueryString,
});
}
export function replaceUrlHashQuery(
rawUrl: string,
queryReplacer: (query: ParsedQuery) => ParsedQuery

View file

@ -78,6 +78,27 @@ describe('kbn_url_storage', () => {
const retrievedState2 = getStateFromKbnUrl('_s', newUrl);
expect(retrievedState2).toEqual(state2);
});
it('should set query to url with storeInHashQuery: false', () => {
let newUrl = setStateToKbnUrl(
'_a',
{ tab: 'other' },
{ useHash: false, storeInHashQuery: false },
'http://localhost:5601/oxf/app/kibana/yourApp'
);
expect(newUrl).toMatchInlineSnapshot(
`"http://localhost:5601/oxf/app/kibana/yourApp?_a=(tab:other)"`
);
newUrl = setStateToKbnUrl(
'_b',
{ f: 'test', i: '', l: '' },
{ useHash: false, storeInHashQuery: false },
newUrl
);
expect(newUrl).toMatchInlineSnapshot(
`"http://localhost:5601/oxf/app/kibana/yourApp?_a=(tab:other)&_b=(f:test,i:'',l:'')"`
);
});
});
describe('urlControls', () => {

View file

@ -22,7 +22,7 @@ import { stringify } from 'query-string';
import { createBrowserHistory, History } from 'history';
import { decodeState, encodeState } from '../state_encoder';
import { getCurrentUrl, parseUrl, parseUrlHash } from './parse';
import { replaceUrlHashQuery } from './format';
import { replaceUrlHashQuery, replaceUrlQuery } from './format';
import { url as urlUtils } from '../../../common';
/**
@ -84,10 +84,14 @@ export function getStateFromKbnUrl<State>(
export function setStateToKbnUrl<State>(
key: string,
state: State,
{ useHash = false }: { useHash: boolean } = { useHash: false },
{ useHash = false, storeInHashQuery = true }: { useHash: boolean; storeInHashQuery?: boolean } = {
useHash: false,
storeInHashQuery: true,
},
rawUrl = window.location.href
): string {
return replaceUrlHashQuery(rawUrl, (query) => {
const replacer = storeInHashQuery ? replaceUrlHashQuery : replaceUrlQuery;
return replacer(rawUrl, (query) => {
const encoded = encodeState(state, useHash);
return {
...query,