@protobase/ui 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/app/app.d.ts +3 -0
  2. package/dist/app/app.js +84 -39
  3. package/dist/app/bottom-bar-from-meta.js +9 -2
  4. package/dist/app/breadcrumb-for.js +18 -9
  5. package/dist/app/create/create-page.js +12 -6
  6. package/dist/app/current-address.d.ts +26 -0
  7. package/dist/app/current-address.js +41 -0
  8. package/dist/app/custom-section.js +41 -0
  9. package/dist/app/displays/cards-display.js +76 -0
  10. package/dist/app/displays/custom-display.js +32 -0
  11. package/dist/app/displays/display-context.d.ts +21 -0
  12. package/dist/app/displays/display-context.js +21 -0
  13. package/dist/app/displays/display-controls.js +55 -0
  14. package/dist/app/displays/display-frame.js +30 -0
  15. package/dist/app/displays/list-displays.d.ts +11 -0
  16. package/dist/app/displays/list-displays.js +62 -0
  17. package/dist/app/displays/record-link.d.ts +19 -0
  18. package/dist/app/displays/record-link.js +25 -0
  19. package/dist/app/displays/use-display-rows.js +28 -0
  20. package/dist/app/field-editor.js +4 -4
  21. package/dist/app/list-page.js +87 -37
  22. package/dist/app/main.js +3 -2
  23. package/dist/app/nav-from-meta.js +9 -2
  24. package/dist/app/nav-recent.js +6 -2
  25. package/dist/app/pages/action-href.js +1 -3
  26. package/dist/app/pages/blocks/card-row.js +1 -1
  27. package/dist/app/pages/blocks/link.js +20 -11
  28. package/dist/app/pages/blocks/modal-form.js +1 -1
  29. package/dist/app/pages/blocks/record-card.js +1 -1
  30. package/dist/app/pages/blocks/stat.js +7 -4
  31. package/dist/app/pages/blocks/table.js +1 -1
  32. package/dist/app/pages/custom-boundary.js +17 -0
  33. package/dist/app/pages/field-value.js +8 -4
  34. package/dist/app/pages/merge-ui.js +9 -3
  35. package/dist/app/pages/problem.js +10 -0
  36. package/dist/app/pages/project-ui.d.ts +18 -4
  37. package/dist/app/pages/project-ui.js +8 -2
  38. package/dist/app/pages/record-actions.js +6 -3
  39. package/dist/app/pages/record-table.js +7 -3
  40. package/dist/app/pages/render-node.js +10 -9
  41. package/dist/app/pages/ui-from-module.d.ts +9 -0
  42. package/dist/app/pages/ui-from-module.js +23 -0
  43. package/dist/app/pages/use-run-action.js +7 -7
  44. package/dist/app/record-page.js +45 -22
  45. package/dist/app/related-section.js +1 -1
  46. package/dist/app/router.js +4 -20
  47. package/dist/app/search/search-model.js +6 -2
  48. package/dist/app/search/use-global-search.js +1 -1
  49. package/dist/app/use-app-address.d.ts +24 -0
  50. package/dist/app/use-app-address.js +47 -0
  51. package/dist/app/use-related-records.js +8 -2
  52. package/dist/app/user-menu-from-meta.js +9 -2
  53. package/dist/data/meta-data.d.ts +3 -1
  54. package/dist/data/use-meta.js +2 -1
  55. package/dist/index.d.ts +10 -2
  56. package/dist/index.js +8 -2
  57. package/dist/live/use-live-rows.js +7 -2
  58. package/dist/package.js +5 -0
  59. package/dist/plugins/load-plugin.d.ts +16 -0
  60. package/dist/plugins/load-plugin.js +73 -0
  61. package/dist/plugins/merge-plugins.js +36 -0
  62. package/dist/plugins/plugin-api.d.ts +10 -0
  63. package/dist/plugins/plugin-api.js +12 -0
  64. package/dist/plugins/plugin-context.d.ts +14 -0
  65. package/dist/plugins/plugin-context.js +12 -0
  66. package/dist/plugins/plugin-gate.js +35 -0
  67. package/dist/plugins/plugin-manifest.js +23 -0
  68. package/dist/plugins/plugin-notice.js +45 -0
  69. package/dist/plugins/plugin-ui.js +37 -0
  70. package/dist/plugins/use-plugin-loads.js +57 -0
  71. package/dist/primitives/segmented.js +8 -5
  72. package/dist/styles.css +1 -35
  73. package/dist/theme.css +39 -0
  74. package/package.json +9 -5
  75. package/dist/app/pages/project-ui-provider.js +0 -15
@@ -0,0 +1,47 @@
1
+ import { changedList, currentAddress, listDefaults } from "./current-address.js";
2
+ import { useAdminMeta } from "./meta-gate.js";
3
+ import { Link, useRouter } from "./router.js";
4
+ import { useCallback, useMemo } from "react";
5
+ import { jsx } from "react/jsx-runtime";
6
+ import { appPath, readAppPath } from "@protobase/schema";
7
+ //#region src/app/use-app-address.tsx
8
+ /**
9
+ * The app's address as logical values, and the ways to change it: `set` changes the list in place, `go` moves to
10
+ * another address, `href` is an address for an `<a href>` and `open` follows such an href. Every component reads and
11
+ * writes the address through this hook, never the query string or a path of its own.
12
+ */
13
+ const useAppAddress = () => {
14
+ const { path, params, basePath, navigate } = useRouter();
15
+ const { pages, resources, views } = useAdminMeta();
16
+ const pageNames = useMemo(() => new Set(Object.keys(pages)), [pages]);
17
+ const query = params.toString();
18
+ const read = useMemo(() => readAppPath(query ? `${path}?${query}` : path, pageNames), [
19
+ path,
20
+ query,
21
+ pageNames
22
+ ]);
23
+ const defaults = useCallback((resource) => listDefaults(resources[resource], views[resource]), [resources, views]);
24
+ const address = useMemo(() => currentAddress(read, defaults), [read, defaults]);
25
+ const go = useCallback((to, options) => navigate(appPath(to), options), [navigate]);
26
+ return {
27
+ address,
28
+ set: useCallback((change) => {
29
+ if (read?.kind !== "list") throw new Error("set changes the list the app shows; use go to move to another address");
30
+ go(changedList(read, change, defaults(read.resource)), { replace: true });
31
+ }, [
32
+ read,
33
+ defaults,
34
+ go
35
+ ]),
36
+ go,
37
+ href: useCallback((to) => appPath(to, basePath), [basePath]),
38
+ open: useCallback((target) => navigate(target.startsWith(`${basePath}/`) ? target.slice(basePath.length) : target), [basePath, navigate])
39
+ };
40
+ };
41
+ /** A link to an address in the app: an ordinary anchor that the router follows without reloading the page. */
42
+ const AppLink = ({ to, ...rest }) => /* @__PURE__ */ jsx(Link, {
43
+ to: appPath(to),
44
+ ...rest
45
+ });
46
+ //#endregion
47
+ export { AppLink, useAppAddress };
@@ -3,6 +3,7 @@ import { useClient } from "../data/api-provider.js";
3
3
  import { humanize } from "../live/naming.js";
4
4
  import { fetchLabels } from "../live/relation-labels.js";
5
5
  import { useQueries, useQueryClient } from "@tanstack/react-query";
6
+ import { appPath } from "@protobase/schema";
6
7
  //#region src/app/use-related-records.ts
7
8
  /** One entry per relation the record holds, named by the record it points at. The tenant is left out. */
8
9
  const useRelatedRecords = (model, view, resources, views, record, basePath) => {
@@ -17,13 +18,18 @@ const useRelatedRecords = (model, view, resources, views, record, basePath) => {
17
18
  queryFn: async () => (await fetchLabels(queryClient, client, target, [id], views[target.name])).get(id) ?? id
18
19
  };
19
20
  }) });
21
+ const addresses = relations.map((field) => ({
22
+ kind: "record",
23
+ resource: field.relation.resource,
24
+ key: String(record[field.name])
25
+ }));
20
26
  return {
21
- hrefs: Object.fromEntries(relations.map((field) => [field.name, `/${field.relation.resource}/${encodeURIComponent(String(record[field.name]))}`])),
27
+ addresses: Object.fromEntries(relations.map((field, index) => [field.name, addresses[index]])),
22
28
  labels: Object.fromEntries(relations.map((field, index) => [field.name, labels[index]?.data])),
23
29
  records: relations.map((field, index) => ({
24
30
  kind: view?.fields[field.name]?.label ?? humanize(field.name),
25
31
  label: labels[index]?.data ?? String(record[field.name]),
26
- href: `${basePath}/${field.relation.resource}/${encodeURIComponent(String(record[field.name]))}`
32
+ href: appPath(addresses[index], basePath)
27
33
  }))
28
34
  };
29
35
  };
@@ -2,6 +2,7 @@ import { humanize } from "../live/naming.js";
2
2
  import { iconFor } from "./icons.js";
3
3
  import { menuIcon } from "./menu-icons.js";
4
4
  import { ExternalLink, LayoutDashboard } from "lucide-react";
5
+ import { appPath } from "@protobase/schema";
5
6
  //#region src/app/user-menu-from-meta.ts
6
7
  /** The resources and pages the user menu holds; the sidebar leaves them out. */
7
8
  const userMenuResources = (meta) => new Set((meta.userMenu?.items ?? []).flatMap((item) => item.kind === "resource" ? [item.resource] : item.kind === "page" ? [item.page] : []));
@@ -20,7 +21,10 @@ const userMenuFromMeta = (meta, basePath, activeResource) => (meta.userMenu?.ite
20
21
  id: item.page,
21
22
  label: item.label ?? page?.title ?? humanize(item.page),
22
23
  icon: menuIcon(item.icon ?? page?.icon, LayoutDashboard),
23
- href: `${basePath}/${item.page}`,
24
+ href: appPath({
25
+ kind: "page",
26
+ page: item.page
27
+ }, basePath),
24
28
  active: item.page === activeResource
25
29
  };
26
30
  }
@@ -28,7 +32,10 @@ const userMenuFromMeta = (meta, basePath, activeResource) => (meta.userMenu?.ite
28
32
  id: item.resource,
29
33
  label: item.label ?? meta.views[item.resource]?.names?.plural ?? humanize(item.resource),
30
34
  icon: menuIcon(item.icon, iconFor(item.resource)),
31
- href: `${basePath}/${item.resource}`,
35
+ href: appPath({
36
+ kind: "list",
37
+ resource: item.resource
38
+ }, basePath),
32
39
  active: item.resource === activeResource
33
40
  };
34
41
  });
@@ -1,4 +1,4 @@
1
- import { ResourcePermissions } from "@protobase/client";
1
+ import { PluginRef, ResourcePermissions } from "@protobase/client";
2
2
  import { BottomBarModel, ResourceModel, UserMenuModel, ViewModel } from "@protobase/schema";
3
3
  import { PageModel } from "@protobase/layout";
4
4
  //#region src/data/meta-data.d.ts
@@ -20,5 +20,7 @@ export type MetaData = {
20
20
  runtime?: {
21
21
  url: string;
22
22
  };
23
+ /** The plugins the app loads for the user (see `PluginGate`). */
24
+ plugins?: PluginRef[];
23
25
  };
24
26
  //#endregion
@@ -29,7 +29,8 @@ const useMeta = () => {
29
29
  ...result.meta.userMenu && { userMenu: result.meta.userMenu },
30
30
  ...result.meta.bottomBar && { bottomBar: result.meta.bottomBar },
31
31
  ...result.meta.assistant && { assistant: result.meta.assistant },
32
- ...result.meta.runtime && { runtime: result.meta.runtime }
32
+ ...result.meta.runtime && { runtime: result.meta.runtime },
33
+ ...result.meta.plugins && { plugins: result.meta.plugins }
33
34
  };
34
35
  }
35
36
  });
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { ActionContext, ActionHandler, ProjectUi, defineUi } from "./app/pages/project-ui.js";
1
+ import { ActionContext, ActionHandler, ProjectUi, definePlugin, defineUi } from "./app/pages/project-ui.js";
2
+ import { PluginInfo, usePlugin } from "./plugins/plugin-context.js";
2
3
  import { App, AppProps } from "./app/app.js";
3
4
  import "./app/index.js";
4
5
  import { ApiProvider, ApiProviderProps, useClient } from "./data/api-provider.js";
@@ -8,8 +9,15 @@ import { useList } from "./data/use-list.js";
8
9
  import { useRecord } from "./data/use-record.js";
9
10
  import { useFacets, useHistogram, useSeries } from "./data/use-aggregates.js";
10
11
  import { isConflict, useUpdateRecord } from "./data/use-update-record.js";
12
+ import { pluginApi, protobaseVersion } from "./plugins/plugin-api.js";
11
13
  import { mergeUi } from "./app/pages/merge-ui.js";
14
+ import { uiFromModule } from "./app/pages/ui-from-module.js";
12
15
  import { LayoutRecord, useLayoutRecord } from "./app/pages/record-scope.js";
16
+ import { CurrentAddress, ListAddress, ListChange } from "./app/current-address.js";
17
+ import { AppLink, useAppAddress } from "./app/use-app-address.js";
18
+ import { ListDisplayRow } from "./app/displays/list-displays.js";
19
+ import { ListDisplay, useListDisplay } from "./app/displays/display-context.js";
20
+ import { RecordLink } from "./app/displays/record-link.js";
13
21
  import { useApiToken } from "./auth/use-api-token.js";
14
22
  import { AssistantDock, AssistantDockProps } from "./assistant-dock/assistant-dock.js";
15
23
  import { PartView } from "./assistant-dock/part-view.js";
@@ -30,4 +38,4 @@ import { Step, StepList, StepState } from "./step-list/step-list.js";
30
38
  import { DiffView, DiffViewProps } from "./diff-view/diff-view.js";
31
39
  import { DiffLine, diffStats, parseDiff } from "./diff-view/diff.js";
32
40
  import { CompactTable, CompactTableProps } from "./compact-table/compact-table.js";
33
- export { ActionCard, type ActionCardProps, type ActionContext, type ActionHandler, ApiProvider, type ApiProviderProps, App, type AppProps, AssistantDock, type AssistantDockProps, type BackendData, type BackendRefresh, type CardAction, type CardTone, ChatMessage, ChatThread, type ChatThreadProps, CompactTable, type CompactTableProps, Composer, type ComposerProps, type DiffLine, DiffView, type DiffViewProps, FieldList, type LayoutRecord, type MetaData, PartView, type ProjectUi, SidePanel, type SidePanelProps, type Step, StepList, type StepState, defineUi, diffStats, isConflict, mergeUi, parseDiff, useApiToken, useAssistant, useAssistantClient, useBackendData, useClient, useFacets, useHistogram, useLayoutRecord, useList, useMeta, useRecord, useSeries, useUpdateRecord };
41
+ export { ActionCard, type ActionCardProps, type ActionContext, type ActionHandler, ApiProvider, type ApiProviderProps, App, AppLink, type AppProps, AssistantDock, type AssistantDockProps, type BackendData, type BackendRefresh, type CardAction, type CardTone, ChatMessage, ChatThread, type ChatThreadProps, CompactTable, type CompactTableProps, Composer, type ComposerProps, type CurrentAddress, type DiffLine, DiffView, type DiffViewProps, FieldList, type LayoutRecord, type ListAddress, type ListChange, type ListDisplay, type ListDisplayRow, type MetaData, PartView, type PluginInfo, type ProjectUi, RecordLink, SidePanel, type SidePanelProps, type Step, StepList, type StepState, definePlugin, defineUi, diffStats, isConflict, mergeUi, parseDiff, pluginApi, protobaseVersion, uiFromModule, useApiToken, useAppAddress, useAssistant, useAssistantClient, useBackendData, useClient, useFacets, useHistogram, useLayoutRecord, useList, useListDisplay, useMeta, usePlugin, useRecord, useSeries, useUpdateRecord };
package/dist/index.js CHANGED
@@ -11,17 +11,23 @@ import { CompactTable } from "./compact-table/compact-table.js";
11
11
  import { diffStats, parseDiff } from "./diff-view/diff.js";
12
12
  import { DiffView } from "./diff-view/diff-view.js";
13
13
  import { StepList } from "./step-list/step-list.js";
14
- import { defineUi } from "./app/pages/project-ui.js";
14
+ import { definePlugin, defineUi } from "./app/pages/project-ui.js";
15
15
  import { PartView } from "./assistant-dock/part-view.js";
16
16
  import { useBackendData } from "./assistant-dock/use-backend-data.js";
17
17
  import { AssistantDock } from "./assistant-dock/assistant-dock.js";
18
18
  import { useAssistant } from "./assistant-dock/use-assistant.js";
19
19
  import { useAssistantClient } from "./assistant-dock/use-assistant-client.js";
20
20
  import { useMeta } from "./data/use-meta.js";
21
+ import { AppLink, useAppAddress } from "./app/use-app-address.js";
21
22
  import { useFacets, useHistogram, useSeries } from "./data/use-aggregates.js";
23
+ import { useListDisplay } from "./app/displays/display-context.js";
22
24
  import { useLayoutRecord } from "./app/pages/record-scope.js";
25
+ import { uiFromModule } from "./app/pages/ui-from-module.js";
23
26
  import { mergeUi } from "./app/pages/merge-ui.js";
27
+ import { usePlugin } from "./plugins/plugin-context.js";
28
+ import { pluginApi, protobaseVersion } from "./plugins/plugin-api.js";
24
29
  import { useList } from "./data/use-list.js";
25
30
  import { isConflict, useUpdateRecord } from "./data/use-update-record.js";
26
31
  import { App } from "./app/app.js";
27
- export { ActionCard, ApiProvider, App, AssistantDock, ChatMessage, ChatThread, CompactTable, Composer, DiffView, FieldList, PartView, SidePanel, StepList, defineUi, diffStats, isConflict, mergeUi, parseDiff, useApiToken, useAssistant, useAssistantClient, useBackendData, useClient, useFacets, useHistogram, useLayoutRecord, useList, useMeta, useRecord, useSeries, useUpdateRecord };
32
+ import { RecordLink } from "./app/displays/record-link.js";
33
+ export { ActionCard, ApiProvider, App, AppLink, AssistantDock, ChatMessage, ChatThread, CompactTable, Composer, DiffView, FieldList, PartView, RecordLink, SidePanel, StepList, definePlugin, defineUi, diffStats, isConflict, mergeUi, parseDiff, pluginApi, protobaseVersion, uiFromModule, useApiToken, useAppAddress, useAssistant, useAssistantClient, useBackendData, useClient, useFacets, useHistogram, useLayoutRecord, useList, useListDisplay, useMeta, usePlugin, useRecord, useSeries, useUpdateRecord };
@@ -4,7 +4,10 @@ import { createGridLoader } from "./grid-loader.js";
4
4
  import { useMemo } from "react";
5
5
  import { useQuery, useQueryClient } from "@tanstack/react-query";
6
6
  //#region src/live/use-live-rows.ts
7
- /** A grid row source backed by the API; `total` is the server's estimate from the first page. */
7
+ /**
8
+ * A grid row source backed by the API; `total` is the server's estimate from the first page. `page` loads one page of
9
+ * the same rows by number, and `key` names them in the query cache, for list displays that page through them.
10
+ */
8
11
  const useLiveRows = ({ resources, views, model, columns, filter, orderBy }) => {
9
12
  const client = useClient();
10
13
  const queryClient = useQueryClient();
@@ -38,7 +41,9 @@ const useLiveRows = ({ resources, views, model, columns, filter, orderBy }) => {
38
41
  loadRows: loader.loadRows
39
42
  } : void 0, [first.data, loader]),
40
43
  error: first.error,
41
- isLoading: first.isLoading
44
+ isLoading: first.isLoading,
45
+ page: loader.page,
46
+ key: [...keys.first(model.name, filter, orderBy), columnKey]
42
47
  };
43
48
  };
44
49
  //#endregion
@@ -0,0 +1,5 @@
1
+ //#region package.json
2
+ var version = "0.11.1";
3
+ var protobase = { "pluginApi": 1 };
4
+ //#endregion
5
+ export { protobase, version };
@@ -0,0 +1,16 @@
1
+ import "../app/pages/project-ui.js";
2
+ import { PluginRef } from "@protobase/client";
3
+ import "@protobase/schema";
4
+ //#region src/plugins/load-plugin.d.ts
5
+ /** What loading a plugin needs from the page: reading its plugin.json, adding its stylesheet and importing its module. */
6
+ export type PluginLoader = {
7
+ /** The JSON at `url`, or the HTTP status it answered with. */
8
+ readJson: (url: string) => Promise<{
9
+ json: unknown;
10
+ } | {
11
+ status: number;
12
+ }>;
13
+ addStylesheet: (url: string) => void;
14
+ importModule: (url: string) => Promise<Record<string, unknown>>;
15
+ };
16
+ //#endregion
@@ -0,0 +1,73 @@
1
+ import { parseManifest } from "./plugin-manifest.js";
2
+ import { pluginUi } from "./plugin-ui.js";
3
+ import { pluginApi, protobaseVersion } from "./plugin-api.js";
4
+ import { pluginProblem } from "@protobase/schema";
5
+ //#region src/plugins/load-plugin.ts
6
+ /** The page's own: `fetch` without a cached copy, a `<link>` per stylesheet, and `import()`. */
7
+ const browserLoader = {
8
+ readJson: async (url) => {
9
+ const response = await fetch(url, {
10
+ cache: "no-cache",
11
+ credentials: "same-origin"
12
+ });
13
+ return response.ok ? { json: await response.json() } : { status: response.status };
14
+ },
15
+ addStylesheet: (url) => {
16
+ if ([...document.querySelectorAll("link[rel=\"stylesheet\"]")].some((link) => link.href === url)) return;
17
+ const link = document.createElement("link");
18
+ link.rel = "stylesheet";
19
+ link.href = url;
20
+ document.head.append(link);
21
+ },
22
+ importModule: (url) => import(
23
+ /* @vite-ignore */
24
+ url
25
+ )
26
+ };
27
+ /** This app, as a plugin's plugin.json is checked against. */
28
+ const thisApp = {
29
+ api: pluginApi,
30
+ version: protobaseVersion
31
+ };
32
+ const describe = (error) => error instanceof Error ? error.message : String(error);
33
+ /**
34
+ * Loads the plugin `ref` names: its plugin.json, then, when this app may load it (see `pluginProblem`), its stylesheet
35
+ * and module. Every way a plugin can fail ends in `off` with the reason, never in a broken app.
36
+ */
37
+ const loadPlugin = async (ref, loader, base, host = thisApp) => {
38
+ const url = new URL(ref.url, base).href;
39
+ const off = (reason, name) => ({
40
+ kind: "off",
41
+ url,
42
+ ...name && { name },
43
+ reason
44
+ });
45
+ let name;
46
+ try {
47
+ const read = await loader.readJson(url);
48
+ if ("status" in read) return off(`its plugin.json answered ${read.status}`);
49
+ const parsed = parseManifest(read.json);
50
+ if ("problem" in parsed) return off(parsed.problem);
51
+ const { manifest } = parsed;
52
+ name = manifest.name;
53
+ const problem = pluginProblem(manifest, host);
54
+ if (problem) return off(problem, name);
55
+ if (manifest.css) loader.addStylesheet(new URL(manifest.css, url).href);
56
+ const module = await loader.importModule(new URL(manifest.entry, url).href);
57
+ const plugin = {
58
+ name,
59
+ ...manifest.version && { version: manifest.version },
60
+ url,
61
+ settings: ref.settings ?? {}
62
+ };
63
+ return {
64
+ kind: "loaded",
65
+ plugin,
66
+ ui: pluginUi(plugin, module)
67
+ };
68
+ } catch (error) {
69
+ return off(`it could not be loaded: ${describe(error)}`, name);
70
+ }
71
+ };
72
+ //#endregion
73
+ export { browserLoader, loadPlugin };
@@ -0,0 +1,36 @@
1
+ import { UiConflictError, mergeUi } from "../app/pages/merge-ui.js";
2
+ //#region src/plugins/merge-plugins.ts
3
+ /**
4
+ * The app's UI config with the loaded plugins' merged before it, in their order, and the plugins that are off: those
5
+ * that did not load, and those that define a component or action handler the app or an earlier plugin defines, which
6
+ * the app's or the earlier one keeps. A conflict within the app's own configs throws, as it does without plugins.
7
+ */
8
+ const mergePlugins = (project, loads) => {
9
+ const own = mergeUi(project ?? {});
10
+ const kept = [];
11
+ const off = [];
12
+ for (const load of loads) {
13
+ if (load.kind === "off") {
14
+ off.push(load);
15
+ continue;
16
+ }
17
+ try {
18
+ mergeUi(...kept, load.ui, own);
19
+ kept.push(load.ui);
20
+ } catch (error) {
21
+ if (!(error instanceof UiConflictError)) throw error;
22
+ off.push({
23
+ kind: "off",
24
+ url: load.plugin.url,
25
+ name: load.plugin.name,
26
+ reason: error.message
27
+ });
28
+ }
29
+ }
30
+ return {
31
+ ui: kept.length === 0 ? own : mergeUi(...kept, own),
32
+ off
33
+ };
34
+ };
35
+ //#endregion
36
+ export { mergePlugins };
@@ -0,0 +1,10 @@
1
+ //#region src/plugins/plugin-api.d.ts
2
+ /**
3
+ * The plugin API this @protobase/ui provides. A plugin built for another one is not loaded. It changes only when a
4
+ * plugin built for the previous one could break: an export of @protobase/ui removed or changed, a module shared with
5
+ * plugins added or removed, or a new major version of React. Its exports are pinned by plugin-api.test.ts.
6
+ */
7
+ export declare const pluginApi: number;
8
+ /** The Protobase version this @protobase/ui is: the app's, since plugins share the app's copy. */
9
+ export declare const protobaseVersion: string;
10
+ //#endregion
@@ -0,0 +1,12 @@
1
+ import { protobase, version } from "../package.js";
2
+ //#region src/plugins/plugin-api.ts
3
+ /**
4
+ * The plugin API this @protobase/ui provides. A plugin built for another one is not loaded. It changes only when a
5
+ * plugin built for the previous one could break: an export of @protobase/ui removed or changed, a module shared with
6
+ * plugins added or removed, or a new major version of React. Its exports are pinned by plugin-api.test.ts.
7
+ */
8
+ const pluginApi = protobase.pluginApi;
9
+ /** The Protobase version this @protobase/ui is: the app's, since plugins share the app's copy. */
10
+ const protobaseVersion = version;
11
+ //#endregion
12
+ export { pluginApi, protobaseVersion };
@@ -0,0 +1,14 @@
1
+ //#region src/plugins/plugin-context.d.ts
2
+ /** A loaded plugin, as its components see it with `usePlugin()`. */
3
+ export type PluginInfo = {
4
+ name: string;
5
+ /** Its own version, from its package.json, when it has one. */
6
+ version?: string;
7
+ /** Its plugin.json, from which its own files are found: `new URL('./data.json', url)`. */
8
+ url: string;
9
+ /** What the app gives it in `options.plugins`. */
10
+ settings: Record<string, unknown>;
11
+ };
12
+ /** The plugin the calling component belongs to: its name, version, URL and settings. Only a plugin's components may call it. */
13
+ export declare const usePlugin: () => PluginInfo;
14
+ //#endregion
@@ -0,0 +1,12 @@
1
+ import { createContext, useContext } from "react";
2
+ //#region src/plugins/plugin-context.tsx
3
+ const PluginContext = createContext(null);
4
+ const PluginProvider = PluginContext.Provider;
5
+ /** The plugin the calling component belongs to: its name, version, URL and settings. Only a plugin's components may call it. */
6
+ const usePlugin = () => {
7
+ const plugin = useContext(PluginContext);
8
+ if (!plugin) throw new Error("usePlugin is for the components of a plugin the app loaded");
9
+ return plugin;
10
+ };
11
+ //#endregion
12
+ export { PluginProvider, usePlugin };
@@ -0,0 +1,35 @@
1
+ import { Spinner } from "../primitives/spinner.js";
2
+ import { ProjectUiContext } from "../app/pages/project-ui.js";
3
+ import { useAdminMeta } from "../app/meta-gate.js";
4
+ import { browserLoader } from "./load-plugin.js";
5
+ import { mergePlugins } from "./merge-plugins.js";
6
+ import { usePluginLoads } from "./use-plugin-loads.js";
7
+ import { createContext, useContext, useMemo } from "react";
8
+ import { jsx, jsxs } from "react/jsx-runtime";
9
+ //#region src/plugins/plugin-gate.tsx
10
+ const PluginsOffContext = createContext([]);
11
+ /** The plugins `/meta` names that the app did not load, and why. */
12
+ const usePluginsOff = () => useContext(PluginsOffContext);
13
+ /**
14
+ * Loads the plugins `/meta` names and provides the project's UI config with theirs merged in. It draws its children
15
+ * once they have loaded, or failed, or after a wait (see `usePluginLoads`); a plugin that fails is left out, and its
16
+ * components draw what any missing component draws.
17
+ */
18
+ const PluginGate = ({ ui, loader = browserLoader, children }) => {
19
+ const { plugins = [] } = useAdminMeta();
20
+ const { loads, settled } = usePluginLoads(plugins, loader);
21
+ const merged = useMemo(() => mergePlugins(ui, loads), [ui, loads]);
22
+ if (!settled) return /* @__PURE__ */ jsxs("div", {
23
+ className: "flex h-full min-h-48 items-center justify-center gap-2 text-[13px] text-muted-foreground",
24
+ children: [/* @__PURE__ */ jsx(Spinner, {}), " Loading"]
25
+ });
26
+ return /* @__PURE__ */ jsx(ProjectUiContext.Provider, {
27
+ value: merged.ui,
28
+ children: /* @__PURE__ */ jsx(PluginsOffContext.Provider, {
29
+ value: merged.off,
30
+ children
31
+ })
32
+ });
33
+ };
34
+ //#endregion
35
+ export { PluginGate, usePluginsOff };
@@ -0,0 +1,23 @@
1
+ //#region src/plugins/plugin-manifest.ts
2
+ const isText = (value) => typeof value === "string" && value.trim() !== "";
3
+ /** The manifest in `value`, or what is wrong with it. */
4
+ const parseManifest = (value) => {
5
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return { problem: "its plugin.json is not an object" };
6
+ const { name, version, api, protobase, entry, css } = value;
7
+ if (!isText(name)) return { problem: "its plugin.json names no plugin" };
8
+ if (!Number.isInteger(api)) return { problem: "its plugin.json names no plugin API" };
9
+ if (!isText(protobase)) return { problem: "its plugin.json names no Protobase versions" };
10
+ if (!isText(entry)) return { problem: "its plugin.json names no module" };
11
+ if (css !== void 0 && !isText(css)) return { problem: "its plugin.json names a stylesheet that is no URL" };
12
+ if (version !== void 0 && !isText(version)) return { problem: "its plugin.json has a version that is no text" };
13
+ return { manifest: {
14
+ name,
15
+ api,
16
+ protobase,
17
+ entry,
18
+ ...version !== void 0 && { version },
19
+ ...css !== void 0 && { css }
20
+ } };
21
+ };
22
+ //#endregion
23
+ export { parseManifest };
@@ -0,0 +1,45 @@
1
+ import { useState } from "react";
2
+ import { Puzzle, X } from "lucide-react";
3
+ import { jsx, jsxs } from "react/jsx-runtime";
4
+ //#region src/plugins/plugin-notice.tsx
5
+ /** Across the top of the app for its admins while plugins it should load are off: which, and why. */
6
+ const PluginNotice = ({ off }) => {
7
+ const [dismissed, setDismissed] = useState(false);
8
+ if (dismissed || off.length === 0) return null;
9
+ return /* @__PURE__ */ jsxs("div", {
10
+ role: "region",
11
+ "aria-label": "Plugins off",
12
+ className: "flex items-start gap-3 border-b border-warning/40 bg-warning-soft px-4 py-2 text-[13px] text-warning-text",
13
+ children: [
14
+ /* @__PURE__ */ jsx(Puzzle, {
15
+ "aria-hidden": true,
16
+ className: "mt-0.5 size-4 shrink-0"
17
+ }),
18
+ /* @__PURE__ */ jsx("ul", {
19
+ className: "min-w-0 flex-1 space-y-0.5 break-words",
20
+ children: off.map((plugin) => /* @__PURE__ */ jsxs("li", { children: [
21
+ "The plugin ",
22
+ /* @__PURE__ */ jsx("span", {
23
+ className: "font-semibold",
24
+ children: plugin.name ?? plugin.url
25
+ }),
26
+ " is off: ",
27
+ plugin.reason,
28
+ "."
29
+ ] }, plugin.url))
30
+ }),
31
+ /* @__PURE__ */ jsx("button", {
32
+ type: "button",
33
+ "aria-label": "Dismiss",
34
+ className: "rounded p-0.5 hover:bg-warning/10",
35
+ onClick: () => setDismissed(true),
36
+ children: /* @__PURE__ */ jsx(X, {
37
+ "aria-hidden": true,
38
+ className: "size-4"
39
+ })
40
+ })
41
+ ]
42
+ });
43
+ };
44
+ //#endregion
45
+ export { PluginNotice };
@@ -0,0 +1,37 @@
1
+ import { uiFromModule } from "../app/pages/ui-from-module.js";
2
+ import { mergeUi } from "../app/pages/merge-ui.js";
3
+ import { PluginProvider } from "./plugin-context.js";
4
+ import { jsx } from "react/jsx-runtime";
5
+ //#region src/plugins/plugin-ui.tsx
6
+ const within = (plugin, Component, name) => {
7
+ const Within = (props) => /* @__PURE__ */ jsx(PluginProvider, {
8
+ value: plugin,
9
+ children: /* @__PURE__ */ jsx(Component, { ...props })
10
+ });
11
+ Within.displayName = `${plugin.name}:${name}`;
12
+ return Within;
13
+ };
14
+ /**
15
+ * A plugin's UI config from its module, read as a `protobase.ui.tsx` module and merged with the configs it extends,
16
+ * named after the plugin: its components and shell slots draw inside the plugin. Throws `UiConflictError` when the
17
+ * configs it merges define a name twice.
18
+ */
19
+ const pluginUi = (plugin, module) => {
20
+ const ui = mergeUi({
21
+ ...uiFromModule(module),
22
+ name: plugin.name
23
+ });
24
+ const components = Object.fromEntries(Object.entries(ui.components ?? {}).map(([name, Component]) => [name, within(plugin, Component, name)]));
25
+ const shell = ui.shell && {
26
+ ...ui.shell.actions && { actions: within(plugin, ui.shell.actions, "shell.actions") },
27
+ ...ui.shell.rightPanel && { rightPanel: within(plugin, ui.shell.rightPanel, "shell.rightPanel") }
28
+ };
29
+ return {
30
+ name: plugin.name,
31
+ components,
32
+ ...ui.actions && { actions: ui.actions },
33
+ ...shell && { shell }
34
+ };
35
+ };
36
+ //#endregion
37
+ export { pluginUi };
@@ -0,0 +1,57 @@
1
+ import { loadPlugin } from "./load-plugin.js";
2
+ import { useEffect, useState } from "react";
3
+ //#region src/plugins/use-plugin-loads.ts
4
+ /** How long the app waits for its plugins before it draws without the ones still loading, which arrive later. */
5
+ const pluginWaitMs = 1e4;
6
+ const none = [];
7
+ /**
8
+ * The plugins `refs` names, in their order, as they load. `settled` once every one has loaded or failed, or after
9
+ * `pluginWaitMs`, so a slow plugin delays the app only that long. Without plugins it is settled at once.
10
+ */
11
+ const usePluginLoads = (refs, loader) => {
12
+ const key = JSON.stringify(refs);
13
+ const [state, setState] = useState({
14
+ key: "[]",
15
+ loads: none,
16
+ settled: true
17
+ });
18
+ useEffect(() => {
19
+ if (refs.length === 0) return;
20
+ let active = true;
21
+ let waited = false;
22
+ const results = refs.map(() => void 0);
23
+ const publish = () => {
24
+ if (!active) return;
25
+ const loads = results.filter((load) => load !== void 0);
26
+ setState({
27
+ key,
28
+ loads,
29
+ settled: waited || loads.length === refs.length
30
+ });
31
+ };
32
+ const timer = setTimeout(() => {
33
+ waited = true;
34
+ publish();
35
+ }, pluginWaitMs);
36
+ refs.forEach((ref, index) => {
37
+ loadPlugin(ref, loader, window.location.href).then((load) => {
38
+ results[index] = load;
39
+ publish();
40
+ });
41
+ });
42
+ return () => {
43
+ active = false;
44
+ clearTimeout(timer);
45
+ };
46
+ }, [key, loader]);
47
+ if (refs.length === 0) return {
48
+ loads: none,
49
+ settled: true
50
+ };
51
+ return state.key === key ? state : {
52
+ loads: none,
53
+ settled: false
54
+ };
55
+ };
56
+ //#endregion
57
+ export { pluginWaitMs, usePluginLoads };
@@ -1,13 +1,16 @@
1
1
  import { cn } from "../lib/cn.js";
2
- import { jsx } from "react/jsx-runtime";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
3
  //#region src/primitives/segmented.tsx
4
- const Segmented = ({ value, options, onChange }) => /* @__PURE__ */ jsx("span", {
4
+ const Segmented = ({ value, options, onChange, label }) => /* @__PURE__ */ jsx("span", {
5
+ role: "group",
6
+ "aria-label": label,
5
7
  className: "inline-flex h-7 rounded-md bg-muted p-0.5",
6
- children: options.map((option) => /* @__PURE__ */ jsx("button", {
8
+ children: options.map((option) => /* @__PURE__ */ jsxs("button", {
7
9
  type: "button",
10
+ "aria-pressed": option.value === value,
8
11
  onClick: () => onChange(option.value),
9
- className: cn("rounded px-2.5 text-xs font-medium transition-colors", option.value === value ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"),
10
- children: option.label
12
+ className: cn("inline-flex items-center gap-1.5 rounded px-2.5 text-xs font-medium transition-colors", option.value === value ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"),
13
+ children: [option.icon && /* @__PURE__ */ jsx(option.icon, { className: "size-3.5" }), option.label]
11
14
  }, option.value))
12
15
  });
13
16
  //#endregion