decentralizing page url-params management -- PoC / tsc 4.1 random fixes

Signed-off-by: Roman <ixrock@gmail.com>
This commit is contained in:
Roman committed 2020-12-03 17:17:02 +02:00
1 parent b8e190e8fd
commit b7be386e6b
59 files changed
+498 -472

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
// Navigation helpers
import { matchPath, RouteProps } from "react-router";
import { LocationDescriptor } from "history";
import { clusterViewRoute, IClusterViewRouteParams } from "../components/cluster-manager/cluster-view.route";
import { navigation } from "./index";
export function navigate(location: LocationDescriptor) {
const currentLocation = navigation.getPath();
navigation.push(location);
if (currentLocation === navigation.getPath()) {
navigation.goBack(); // prevent sequences of same url in history
}
}
export function matchParams<P>(route: string | string[] | RouteProps) {
return matchPath<P>(navigation.location.pathname, route);
}
export function isActiveRoute(route: string | string[] | RouteProps): boolean {
return !!matchParams(route);
}
export function getMatchedClusterId(): string {
const matched = matchPath<IClusterViewRouteParams>(navigation.location.pathname, {
exact: true,
path: clusterViewRoute.path
});
return matched?.params.clusterId;
}
+47
View File
@@ -0,0 +1,47 @@
// Navigation helpers
import { ipcRenderer } from "electron";
import logger from "../../main/logger";
import { reaction } from "mobx";
import { createObservableHistory } from "mobx-observable-history";
import { createBrowserHistory, createMemoryHistory } from "history";
import { broadcastMessage, subscribeToBroadcast } from "../../common/ipc";
import { getMatchedClusterId, navigate } from "./helpers";
import { UrlParam, UrlParamInit } from "./url-param";
export let history = ipcRenderer ? createBrowserHistory() : createMemoryHistory();
export let navigation = createObservableHistory(history);
export function createUrlParam<V = string>(init: UrlParamInit<V>) {
return new UrlParam<V>(init, navigation);
}
if (ipcRenderer) {
history = createBrowserHistory();
navigation = createObservableHistory(history);
if (process.isMainFrame) {
// Keep track of active cluster-id for handling IPC/menus/etc.
reaction(() => getMatchedClusterId(), clusterId => {
broadcastMessage("cluster-view:current-id", clusterId);
}, {
fireImmediately: true
});
}
// Handle navigation via IPC (e.g. from top menu)
subscribeToBroadcast("renderer:navigate", (event, url: string) => {
logger.info(`[IPC]: ${event.type} ${JSON.stringify(url)}`, event);
navigate(url);
});
// Reload dashboard window
subscribeToBroadcast("renderer:reload", () => {
location.reload();
});
}
// Re-exports from sub-modules
export * from "./helpers";
export * from "./url-param";
+101
View File
@@ -0,0 +1,101 @@
// Manage observable URL-param via location.search
import { IObservableHistory } from "mobx-observable-history";
export interface UrlParamInit<V = any> {
name: string;
isSystem?: boolean;
defaultValue?: V;
multiValues?: boolean; // false == by default
multiValueSep?: string; // joining multiple values with separator, default: ","
skipEmpty?: boolean; // skip empty value(s), e.g. "?param=", default: true
parse?(values: string[]): V; // deserialize from URL
stringify?(values: V): string | string[]; // serialize params to URL
}
export class UrlParam<V = any | any[]> {
static SYSTEM_PREFIX = "lens-";
public name: string;
public urlName: string;
constructor(private init: UrlParamInit<V>, private history: IObservableHistory) {
const { isSystem, name, skipEmpty = true } = init;
this.name = name;
this.init.skipEmpty = skipEmpty;
// prefixing to avoid collisions with extensions
this.urlName = `${isSystem ? UrlParam.SYSTEM_PREFIX : ""}${name}`;
}
isEmpty(value: V) {
return [value].flat().every(value => value == "" || value == null);
}
parse(values: string[]): V {
const { parse, multiValues } = this.init;
if (!multiValues) values.splice(1); // reduce values to single item
const parsedValues = [parse ? parse(values) : values].flat();
return multiValues ? parsedValues : parsedValues[0] as any;
}
stringify(value: V = this.get()): string {
const { stringify, multiValues, multiValueSep, skipEmpty } = this.init;
if (skipEmpty && this.isEmpty(value)) {
return "";
}
if (multiValues) {
const values = [value].flat();
const stringValues = [stringify ? stringify(value) : values.map(String)].flat();
return stringValues.join(multiValueSep);
}
return [stringify ? stringify(value) : String(value)].flat()[0];
}
get(): V {
const { history, urlName } = this;
const { multiValueSep, multiValues, defaultValue, skipEmpty } = this.init;
const value = this.parse(history.searchParams.getAsArray(urlName, multiValueSep));
if (skipEmpty && this.isEmpty(value)) {
return defaultValue;
}
return value;
}
set(value: V, { mergeGlobals = true, replaceHistory = false } = {}) {
const search = this.toSearchString(value, { mergeGlobals });
this.history.merge({ search }, replaceHistory);
}
isDefault() {
return this.get() === this.init.defaultValue;
}
clear() {
this.history.searchParams.delete(this.urlName);
}
toSearchString(value = this.get(), { withPrefix = true, mergeGlobals = true } = {}): string {
const { history, urlName, init: { skipEmpty } } = this;
const searchParams = new URLSearchParams(mergeGlobals ? history.location.search : "");
searchParams.set(urlName, this.stringify(value));
if (skipEmpty) {
searchParams.forEach((value: any, paramName) => {
if (this.isEmpty(value)) searchParams.delete(paramName);
})
}
if (Array.from(searchParams).length > 0) {
return `${withPrefix ? "?" : ""}${searchParams}`;
}
return "";
}
toObjectParam(value = this.get()): Record<string, V> {
return {
[this.urlName]: value,
};
}
}