PageRegistration / PageMenuRegistration fixes & more simplification (#1386)

* PageRegistration & PageMenuRegistration fixes & more simplification, fix #1383

Signed-off-by: Roman <ixrock@gmail.com>

* clean up test, deprecate page.routePath

Signed-off-by: Roman <ixrock@gmail.com>

* fix: proper `isActive` state matching for page-menu-target to page considering current document location

Signed-off-by: Roman <ixrock@gmail.com>
This commit is contained in:
Roman authored and GitHub committed 2020-11-16 15:18:53 +02:00
1 parent 596e60a6f3
commit 13dbdac2f2
12 files changed
+147 -93

No files matched your search

+71 -34
View File
@@ -1,59 +1,96 @@
// Extensions-api -> Custom page registration
import React from "react";
import type { PageMenuTarget } from "./page-menu-registry";
import type React from "react";
import path from "path";
import { action } from "mobx";
import { compile } from "path-to-regexp";
import { BaseRegistry } from "./base-registry";
import { LensExtension } from "../lens-extension"
import type { PageMenuTarget } from "./page-menu-registry";
import { LensExtension } from "../lens-extension";
import logger from "../../main/logger";
export interface PageRegistration {
id: string; // will be automatically prefixed with extension name
routePath?: string; // additional (suffix) route path to base extension's route: "/extension/:name"
exact?: boolean; // route matching flag, see: https://reactrouter.com/web/api/NavLink/exact-bool
/**
* Page ID or additional route path to indicate uniqueness within current extension registered pages
* Might contain special url placeholders, e.g. "/users/:userId?" (? - marks as optional param)
* When not provided, first registered page without "id" would be used for page-menus without target.pageId for same extension
*/
id?: string;
/**
* Alias to page ID which assume to be used as path with possible :param placeholders
* @deprecated
*/
routePath?: string;
/**
* Strict route matching to provided page-id, read also: https://reactrouter.com/web/api/NavLink/exact-bool
* In case when more than one page registered at same extension "pageId" is required to identify different pages,
* It might be useful to provide `exact: true` in some cases to avoid overlapping routes.
* Without {exact:true} second page never matches since first page-id/route already includes partial route.
* @example const pages = [
* {id: "/users", exact: true},
* {id: "/users/:userId?"}
* ]
* Pro-tip: registering pages in opposite order will make same effect without "exact".
*/
exact?: boolean;
components: PageComponents;
}
export interface RegisteredPage extends PageRegistration {
extensionId: string; // required for compiling registered page to url with page-menu-target to compare
routePath: string; // full route-path to registered extension page
}
export interface PageComponents {
Page: React.ComponentType<any>;
}
const routePrefix = "/extension/:name"
export function sanitizeExtensioName(name: string) {
export function sanitizeExtensionName(name: string) {
return name.replace("@", "").replace("/", "-")
}
export function getPageUrl(ext: LensExtension, baseUrl = "") {
if (baseUrl !== "" && !baseUrl.startsWith("/")) {
baseUrl = "/" + baseUrl
export function getExtensionPageUrl<P extends object>({ extensionId, pageId = "", params }: PageMenuTarget<P>): string {
const extensionBaseUrl = compile(`/extension/:name`)({
name: sanitizeExtensionName(extensionId), // compile only with extension-id first and define base path
});
const extPageRoutePath = path.join(extensionBaseUrl, pageId); // page-id might contain route :param-s, so don't compile yet
if (params) {
return compile(extPageRoutePath)(params); // might throw error when required params not passed
}
const validUrlName = sanitizeExtensioName(ext.name);
return compile(routePrefix)({ name: validUrlName }) + baseUrl;
return extPageRoutePath;
}
export class PageRegistry<T extends PageRegistration> extends BaseRegistry<T> {
export class PageRegistry extends BaseRegistry<PageRegistration, RegisteredPage> {
@action
add(items: T[], ext?: LensExtension) {
const normalizedItems = items.map((page) => {
if (!page.routePath) {
page.routePath = `/${page.id}`
}
page.routePath = getPageUrl(ext, page.routePath)
return page
})
return super.add(normalizedItems);
add(items: PageRegistration[], ext: LensExtension) {
let registeredPages: RegisteredPage[] = [];
try {
registeredPages = items.map(page => ({
...page,
extensionId: ext.name,
routePath: getExtensionPageUrl({ extensionId: ext.name, pageId: page.id ?? page.routePath }),
}))
} catch (err) {
logger.error(`[EXTENSION]: page-registration failed`, {
items,
extension: ext,
error: String(err),
})
}
return super.add(registeredPages);
}
getByPageMenuTarget(target: PageMenuTarget) {
if (!target) {
return null
}
const routePath = `/extension/${sanitizeExtensioName(target.extensionId)}/`
return this.getItems().find((page) => page.routePath.startsWith(routePath) && page.id === target.pageId) || null
getUrl<P extends object>({ extensionId, id: pageId }: RegisteredPage, params?: P) {
return getExtensionPageUrl({ extensionId, pageId, params });
}
getByPageMenuTarget(target: PageMenuTarget = {}): RegisteredPage | null {
const targetUrl = getExtensionPageUrl(target);
return this.getItems().find(({ id: pageId, extensionId }) => {
const pageUrl = getExtensionPageUrl({ extensionId, pageId, params: target.params }); // compiled with provided params
return targetUrl === pageUrl;
}) || null;
}
}
export const globalPageRegistry = new PageRegistry<PageRegistration>();
export const clusterPageRegistry = new PageRegistry<PageRegistration>();
export const globalPageRegistry = new PageRegistry();
export const clusterPageRegistry = new PageRegistry();