@frigear-nu/dashboard 0.0.0-stage → 0.0.0

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 (67) hide show
  1. package/README.md +4 -2
  2. package/dist/module.d.mts +81 -0
  3. package/dist/module.json +12 -0
  4. package/dist/module.mjs +128 -0
  5. package/dist/runtime/access.d.ts +1 -0
  6. package/dist/runtime/access.js +12 -0
  7. package/dist/runtime/app/components/ActionCard.d.vue.ts +19 -0
  8. package/dist/runtime/app/components/ActionCard.vue +54 -0
  9. package/dist/runtime/app/components/ActionCard.vue.d.ts +19 -0
  10. package/dist/runtime/app/components/ChartCard.d.vue.ts +28 -0
  11. package/dist/runtime/app/components/ChartCard.vue +53 -0
  12. package/dist/runtime/app/components/ChartCard.vue.d.ts +28 -0
  13. package/dist/runtime/app/components/Dashboard.d.vue.ts +27 -0
  14. package/dist/runtime/app/components/Dashboard.vue +156 -0
  15. package/dist/runtime/app/components/Dashboard.vue.d.ts +27 -0
  16. package/dist/runtime/app/components/DashboardGrid.d.vue.ts +15 -0
  17. package/dist/runtime/app/components/DashboardGrid.vue +9 -0
  18. package/dist/runtime/app/components/DashboardGrid.vue.d.ts +15 -0
  19. package/dist/runtime/app/components/DashboardItem.d.vue.ts +26 -0
  20. package/dist/runtime/app/components/DashboardItem.vue +153 -0
  21. package/dist/runtime/app/components/DashboardItem.vue.d.ts +26 -0
  22. package/dist/runtime/app/components/EmptyCard.d.vue.ts +18 -0
  23. package/dist/runtime/app/components/EmptyCard.vue +25 -0
  24. package/dist/runtime/app/components/EmptyCard.vue.d.ts +18 -0
  25. package/dist/runtime/app/composables/useDashboard.d.ts +46 -0
  26. package/dist/runtime/app/composables/useDashboard.js +59 -0
  27. package/dist/runtime/app/composables/useDashboardItem.d.ts +34 -0
  28. package/dist/runtime/app/composables/useDashboardItem.js +28 -0
  29. package/dist/runtime/app/composables/useDashboardLayout.d.ts +24 -0
  30. package/dist/runtime/app/composables/useDashboardLayout.js +67 -0
  31. package/dist/runtime/app/composables/useDashboardPlatform.d.ts +10 -0
  32. package/dist/runtime/app/composables/useDashboardPlatform.js +17 -0
  33. package/dist/runtime/app/composables/useSavedDashboardLayouts.d.ts +20 -0
  34. package/dist/runtime/app/composables/useSavedDashboardLayouts.js +35 -0
  35. package/dist/runtime/app/pages/home.d.vue.ts +3 -0
  36. package/dist/runtime/app/pages/home.vue +16 -0
  37. package/dist/runtime/app/pages/home.vue.d.ts +3 -0
  38. package/dist/runtime/app/utils/components.d.ts +8 -0
  39. package/dist/runtime/app/utils/components.js +19 -0
  40. package/dist/runtime/app/utils/span.d.ts +1 -0
  41. package/dist/runtime/app/utils/span.js +10 -0
  42. package/dist/runtime/i18n/lang/da.json +49 -0
  43. package/dist/runtime/i18n/lang/en.json +49 -0
  44. package/dist/runtime/preferences.d.ts +37 -0
  45. package/dist/runtime/preferences.js +25 -0
  46. package/dist/runtime/server/layouts.d.ts +9 -0
  47. package/dist/runtime/server/layouts.js +25 -0
  48. package/dist/runtime/server/routes/me/layouts.get.d.ts +2 -0
  49. package/dist/runtime/server/routes/me/layouts.get.js +6 -0
  50. package/dist/runtime/server/routes/me/layouts.patch.d.ts +2 -0
  51. package/dist/runtime/server/routes/me/layouts.patch.js +10 -0
  52. package/dist/runtime/shared/home-tab.d.ts +31 -0
  53. package/dist/runtime/shared/home-tab.js +21 -0
  54. package/dist/runtime/shared/layout.d.ts +62 -0
  55. package/dist/runtime/shared/layout.js +110 -0
  56. package/dist/runtime/shared/registry.d.ts +11 -0
  57. package/dist/runtime/shared/registry.js +15 -0
  58. package/dist/runtime/shared/stored-layouts.d.ts +12 -0
  59. package/dist/runtime/shared/stored-layouts.js +16 -0
  60. package/dist/runtime/utils/api.d.ts +11 -0
  61. package/dist/runtime/utils/api.js +11 -0
  62. package/dist/runtime/utils/dashboard.d.ts +22 -0
  63. package/dist/runtime/utils/dashboard.js +32 -0
  64. package/dist/runtime/utils/index.d.ts +4 -0
  65. package/dist/runtime/utils/index.js +18 -0
  66. package/dist/types.d.mts +3 -0
  67. package/package.json +110 -3
@@ -0,0 +1,35 @@
1
+ import { computed } from "vue";
2
+ import { dashboardApi } from "../../utils/api.js";
3
+ import { $fetch, useRequestFetch, useState } from "#imports";
4
+ export function useSavedDashboardLayouts() {
5
+ const state = useState("dashboard:saved", () => ({ owner: null, layouts: {} }));
6
+ const requestFetch = import.meta.server ? useRequestFetch() : $fetch;
7
+ const loading = /* @__PURE__ */ new Map();
8
+ async function load(owner) {
9
+ if (state.value.owner === owner) return;
10
+ const running = loading.get(owner);
11
+ if (running) return running;
12
+ const promise = (async () => {
13
+ try {
14
+ const answer = await requestFetch(dashboardApi.me.layouts);
15
+ state.value = { owner, layouts: answer?.layouts ?? {} };
16
+ } catch {
17
+ state.value = { owner, layouts: {} };
18
+ } finally {
19
+ loading.delete(owner);
20
+ }
21
+ })();
22
+ loading.set(owner, promise);
23
+ return promise;
24
+ }
25
+ async function save(owner, change) {
26
+ const answer = await $fetch(dashboardApi.me.layouts, { method: "PATCH", body: { layouts: change } });
27
+ state.value = { owner, layouts: answer?.layouts ?? {} };
28
+ }
29
+ return {
30
+ layouts: (owner) => state.value.owner === owner ? state.value.layouts : {},
31
+ load,
32
+ save,
33
+ owner: computed(() => state.value.owner)
34
+ };
35
+ }
@@ -0,0 +1,3 @@
1
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
2
+ declare const _default: typeof __VLS_export;
3
+ export default _default;
@@ -0,0 +1,16 @@
1
+ <script setup>
2
+ import { useModuleT, useRuntimeConfig } from "#imports";
3
+ defineOptions({ name: "DashboardHomePage" });
4
+ const t = useModuleT("dashboard");
5
+ const name = useRuntimeConfig().public.dashboard?.home || "crew.home";
6
+ </script>
7
+
8
+ <template>
9
+ <div class="flex flex-col gap-4">
10
+ <!-- The mobile navbar shows the tab label; the page still has one heading for screen readers. -->
11
+ <h1 class="sr-only">
12
+ {{ t("home.label", "Home") }}
13
+ </h1>
14
+ <Dashboard :name="name" />
15
+ </div>
16
+ </template>
@@ -0,0 +1,3 @@
1
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
2
+ declare const _default: typeof __VLS_export;
3
+ export default _default;
@@ -0,0 +1,8 @@
1
+ import { type Component } from 'vue';
2
+ /** The lazily loaded component of a dashboard item. */
3
+ export declare function getDashboardComponent(name: string, id: string): Component | undefined;
4
+ /**
5
+ * Every item id of a dashboard in this build, in registered order: the items of every platform and permission, so a
6
+ * layout change never drops or reorders items the current viewer does not see.
7
+ */
8
+ export declare function getDashboardItemIds(name: string): string[];
@@ -0,0 +1,19 @@
1
+ import { defineAsyncComponent, markRaw } from "vue";
2
+ import { widgets as registry } from "#widgets/registry";
3
+ import { dashboards } from "#dashboard/registry";
4
+ import { dashboardArea } from "../../shared/registry.js";
5
+ const cache = /* @__PURE__ */ new Map();
6
+ export function getDashboardComponent(name, id) {
7
+ const area = dashboardArea(name);
8
+ const key = `${area}::${id}`;
9
+ if (!cache.has(key)) {
10
+ const widget = (registry[area] ?? []).find((item) => item.id === id);
11
+ if (!widget) return void 0;
12
+ cache.set(key, markRaw(defineAsyncComponent(widget.component)));
13
+ }
14
+ return cache.get(key);
15
+ }
16
+ export function getDashboardItemIds(name) {
17
+ const entries = dashboards[name] ?? {};
18
+ return (registry[dashboardArea(name)] ?? []).map((item) => item.id).filter((id) => id in entries);
19
+ }
@@ -0,0 +1 @@
1
+ export declare function dashboardSpanClass(span?: number): string;
@@ -0,0 +1,10 @@
1
+ const spans = {
2
+ 1: "",
3
+ 2: "md:col-span-2",
4
+ 3: "md:col-span-2 xl:col-span-3",
5
+ 4: "md:col-span-2 xl:col-span-4"
6
+ };
7
+ export function dashboardSpanClass(span) {
8
+ const key = Math.min(4, Math.max(1, Math.trunc(span ?? 1)));
9
+ return spans[key];
10
+ }
@@ -0,0 +1,49 @@
1
+ {
2
+ "dashboard": {
3
+ "home": {
4
+ "label": "Hjem"
5
+ },
6
+ "edit": {
7
+ "start": "Tilpas oversigt",
8
+ "done": "Færdig",
9
+ "sessionOnly": "Ændringer gælder, indtil du genindlæser siden."
10
+ },
11
+ "reset": {
12
+ "button": "Nulstil layout",
13
+ "title": "Nulstil layout?",
14
+ "description": "Gendanner standardrækkefølgen og viser alle skjulte elementer. Sammenklappede elementer åbnes igen.",
15
+ "confirm": "Nulstil layout"
16
+ },
17
+ "item": {
18
+ "expand": "Udvid {title}",
19
+ "collapse": "Klap {title} sammen",
20
+ "moveUp": "Flyt {title} op",
21
+ "moveDown": "Flyt {title} ned",
22
+ "hide": "Skjul {title}",
23
+ "error": "{title} kunne ikke indlæses.",
24
+ "errorHint": "Noget gik galt. Prøv igen om lidt.",
25
+ "retry": "Prøv igen"
26
+ },
27
+ "hidden": {
28
+ "title": "Skjulte elementer",
29
+ "show": "Vis {title}"
30
+ },
31
+ "allHidden": {
32
+ "title": "Alle elementer er skjult",
33
+ "description": "Vis de elementer, du vil se igen."
34
+ },
35
+ "empty": {
36
+ "title": "Her er intet endnu",
37
+ "description": "Elementer vises her, når de moduler, der tilføjer dem, er installeret."
38
+ },
39
+ "error": "Oversigten kunne ikke indlæses.",
40
+ "save": {
41
+ "error": "Dit oversigtslayout kunne ikke gemmes."
42
+ },
43
+ "retry": "Prøv igen",
44
+ "permissions": {
45
+ "layouts": "Dine oversigter",
46
+ "layoutsDescription": "Se og ændr rækkefølgen og de skjulte og sammenklappede elementer på dine oversigter."
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,49 @@
1
+ {
2
+ "dashboard": {
3
+ "home": {
4
+ "label": "Home"
5
+ },
6
+ "edit": {
7
+ "start": "Customise dashboard",
8
+ "done": "Done",
9
+ "sessionOnly": "Changes last until you reload the page."
10
+ },
11
+ "reset": {
12
+ "button": "Reset layout",
13
+ "title": "Reset layout?",
14
+ "description": "Restores the default order and shows every hidden item. Collapsed items open again.",
15
+ "confirm": "Reset layout"
16
+ },
17
+ "item": {
18
+ "expand": "Expand {title}",
19
+ "collapse": "Collapse {title}",
20
+ "moveUp": "Move {title} up",
21
+ "moveDown": "Move {title} down",
22
+ "hide": "Hide {title}",
23
+ "error": "{title} could not be loaded.",
24
+ "errorHint": "Something went wrong. Try again in a moment.",
25
+ "retry": "Try again"
26
+ },
27
+ "hidden": {
28
+ "title": "Hidden items",
29
+ "show": "Show {title}"
30
+ },
31
+ "allHidden": {
32
+ "title": "Every item is hidden",
33
+ "description": "Show the items you want to see again."
34
+ },
35
+ "empty": {
36
+ "title": "Nothing here yet",
37
+ "description": "Items appear here when the modules that add them are installed."
38
+ },
39
+ "error": "The dashboard could not be loaded.",
40
+ "save": {
41
+ "error": "Your dashboard layout could not be saved."
42
+ },
43
+ "retry": "Try again",
44
+ "permissions": {
45
+ "layouts": "Your dashboard layouts",
46
+ "layoutsDescription": "See and change the order, hidden and collapsed items of your dashboards."
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,37 @@
1
+ import { z } from 'zod';
2
+ /** The preference key the layouts are stored under. */
3
+ export declare const DASHBOARD_LAYOUTS_KEY = "dashboardLayouts";
4
+ export declare const DASHBOARD_LIMITS: {
5
+ readonly dashboards: 20;
6
+ readonly idsPerList: 200;
7
+ readonly idLength: 100;
8
+ readonly settingsBytes: 1024;
9
+ };
10
+ /** One user's layout of one dashboard. */
11
+ export declare const dashboardLayoutSchema: z.ZodObject<{
12
+ order: z.ZodArray<z.ZodString>;
13
+ hidden: z.ZodArray<z.ZodString>;
14
+ collapsed: z.ZodArray<z.ZodString>;
15
+ settings: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
16
+ }, z.core.$strip>;
17
+ /** Every dashboard's layout of one user, by dashboard name (`crew.home`). */
18
+ export declare const dashboardLayoutsSchema: z.ZodRecord<z.ZodString, z.ZodObject<{
19
+ order: z.ZodArray<z.ZodString>;
20
+ hidden: z.ZodArray<z.ZodString>;
21
+ collapsed: z.ZodArray<z.ZodString>;
22
+ settings: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
23
+ }, z.core.$strip>>;
24
+ /** A dashboard name: the key of a layout. */
25
+ export declare const dashboardNameSchema: z.ZodString;
26
+ declare const _default: {
27
+ dashboardLayouts: {
28
+ schema: z.ZodRecord<z.ZodString, z.ZodObject<{
29
+ order: z.ZodArray<z.ZodString>;
30
+ hidden: z.ZodArray<z.ZodString>;
31
+ collapsed: z.ZodArray<z.ZodString>;
32
+ settings: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
33
+ }, z.core.$strip>>;
34
+ managed: true;
35
+ };
36
+ };
37
+ export default _default;
@@ -0,0 +1,25 @@
1
+ import { z } from "zod";
2
+ export const DASHBOARD_LAYOUTS_KEY = "dashboardLayouts";
3
+ export const DASHBOARD_LIMITS = {
4
+ dashboards: 20,
5
+ idsPerList: 200,
6
+ idLength: 100,
7
+ settingsBytes: 1024
8
+ };
9
+ const id = z.string().min(1).max(DASHBOARD_LIMITS.idLength);
10
+ const ids = z.array(id).max(DASHBOARD_LIMITS.idsPerList);
11
+ export const dashboardLayoutSchema = z.object({
12
+ order: ids,
13
+ hidden: ids,
14
+ collapsed: ids,
15
+ settings: z.record(id, z.record(z.string(), z.unknown())).refine((value) => new TextEncoder().encode(JSON.stringify(value)).length <= DASHBOARD_LIMITS.settingsBytes, {
16
+ message: `Item settings take at most ${DASHBOARD_LIMITS.settingsBytes} bytes per dashboard.`
17
+ }).optional()
18
+ });
19
+ export const dashboardLayoutsSchema = z.record(id, dashboardLayoutSchema).refine((value) => Object.keys(value).length <= DASHBOARD_LIMITS.dashboards, {
20
+ message: `At most ${DASHBOARD_LIMITS.dashboards} dashboard layouts.`
21
+ });
22
+ export const dashboardNameSchema = id;
23
+ export default {
24
+ dashboardLayouts: { schema: dashboardLayoutsSchema, managed: true }
25
+ };
@@ -0,0 +1,9 @@
1
+ import type { DashboardLayouts } from '../shared/stored-layouts.js';
2
+ import type { DashboardLayout } from '../../types.js';
3
+ /** A user's valid layouts; an invalid stored layout is left out. */
4
+ export declare function readDashboardLayouts(userId: number): Promise<DashboardLayouts>;
5
+ /**
6
+ * Replaces (or removes, with `null`) the named layouts of a user and keeps the others, merged against a read made right
7
+ * before the write. Invalid stored layouts are dropped, never written back. Answers the stored layouts.
8
+ */
9
+ export declare function saveDashboardLayouts(userId: number, change: Record<string, DashboardLayout | null>): Promise<DashboardLayouts>;
@@ -0,0 +1,25 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { eq } from "drizzle-orm";
3
+ import { notFound, validationError } from "@frigear-nu/module-kit/server";
4
+ import { DASHBOARD_LAYOUTS_KEY, DASHBOARD_LIMITS } from "../preferences.js";
5
+ import { mergeDashboardLayouts, validDashboardLayouts } from "../shared/stored-layouts.js";
6
+ async function storedPreferences(userId) {
7
+ const [row] = await db.select({ preferences: schema.users.preferences }).from(schema.users).where(eq(schema.users.id, userId)).limit(1);
8
+ return row;
9
+ }
10
+ export async function readDashboardLayouts(userId) {
11
+ const row = await storedPreferences(userId);
12
+ return validDashboardLayouts(row?.preferences?.[DASHBOARD_LAYOUTS_KEY]);
13
+ }
14
+ export async function saveDashboardLayouts(userId, change) {
15
+ const row = await storedPreferences(userId);
16
+ if (!row) throw notFound("User not found.");
17
+ const next = mergeDashboardLayouts(validDashboardLayouts(row.preferences?.[DASHBOARD_LAYOUTS_KEY]), change);
18
+ if (!next) {
19
+ throw validationError([{ code: "custom", path: ["layouts"], message: `At most ${DASHBOARD_LIMITS.dashboards} dashboard layouts.` }]);
20
+ }
21
+ const { [DASHBOARD_LAYOUTS_KEY]: _old, ...rest } = row.preferences ?? {};
22
+ const preferences = Object.keys(next).length ? { ...rest, [DASHBOARD_LAYOUTS_KEY]: next } : rest;
23
+ await db.update(schema.users).set({ preferences }).where(eq(schema.users.id, userId));
24
+ return next;
25
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,6 @@
1
+ import { dashboardAccess } from "../../../access.js";
2
+ import { readDashboardLayouts } from "../../layouts.js";
3
+ export default defineEventHandler(async (event) => {
4
+ const { user } = await authorize(event, dashboardAccess.permissions.layouts);
5
+ return { layouts: await readDashboardLayouts(Number(user.id)) };
6
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,10 @@
1
+ import { z } from "zod";
2
+ import { dashboardAccess } from "../../../access.js";
3
+ import { dashboardLayoutSchema, dashboardNameSchema } from "../../../preferences.js";
4
+ import { saveDashboardLayouts } from "../../layouts.js";
5
+ const bodySchema = z.object({ layouts: z.record(dashboardNameSchema, dashboardLayoutSchema.nullable()) }).strict();
6
+ export default defineEventHandler(async (event) => {
7
+ const { user } = await authorize(event, dashboardAccess.permissions.layouts);
8
+ const { layouts } = await readValidatedBody(event, bodySchema.parse);
9
+ return { layouts: await saveDashboardLayouts(Number(user.id), layouts) };
10
+ });
@@ -0,0 +1,31 @@
1
+ import type { DashboardHomeTabOptions } from '../../types.js';
2
+ export declare const HOME_TAB_DEFAULTS: {
3
+ readonly dashboard: "crew.home";
4
+ readonly path: "/crew";
5
+ readonly label: "Home";
6
+ readonly icon: "i-lucide-house";
7
+ };
8
+ /** The Home tab, in the shape of `@frigear-nu/mobile`'s `MobileTabDefinition`. */
9
+ export interface HomeTab {
10
+ id: 'home';
11
+ to: string;
12
+ label: string;
13
+ /** Set only for the default label, so a host's own `label` is not translated away. */
14
+ labelKey?: string;
15
+ icon: string;
16
+ sfSymbol: string;
17
+ requiresAuth: boolean;
18
+ order: number;
19
+ }
20
+ export interface ResolvedHomeTab {
21
+ dashboard: string;
22
+ path: string;
23
+ tab: HomeTab;
24
+ }
25
+ /**
26
+ * The Home tab to register, or `undefined` when there is none: without `@frigear-nu/mobile`, or with
27
+ * `homeTab: false`. A web app places `<Dashboard>` on a page itself.
28
+ */
29
+ export declare function resolveHomeTab(option: DashboardHomeTabOptions | false | undefined, { mobile }: {
30
+ mobile: boolean;
31
+ }): ResolvedHomeTab | undefined;
@@ -0,0 +1,21 @@
1
+ export const HOME_TAB_DEFAULTS = { dashboard: "crew.home", path: "/crew", label: "Home", icon: "i-lucide-house" };
2
+ export function resolveHomeTab(option, { mobile }) {
3
+ if (!mobile || option === false) return void 0;
4
+ const dashboard = option?.dashboard || HOME_TAB_DEFAULTS.dashboard;
5
+ const raw = option?.path || HOME_TAB_DEFAULTS.path;
6
+ const path = raw.startsWith("/") ? raw : `/${raw}`;
7
+ return {
8
+ dashboard,
9
+ path,
10
+ tab: {
11
+ id: "home",
12
+ to: path,
13
+ label: option?.label || HOME_TAB_DEFAULTS.label,
14
+ ...option?.label ? {} : { labelKey: "dashboard.home.label" },
15
+ icon: option?.icon || HOME_TAB_DEFAULTS.icon,
16
+ sfSymbol: "house",
17
+ requiresAuth: true,
18
+ order: 0
19
+ }
20
+ };
21
+ }
@@ -0,0 +1,62 @@
1
+ import type { DashboardItemCondition, DashboardLayout, DashboardPlatform } from '../../types.js';
2
+ type Identified = {
3
+ id: string;
4
+ };
5
+ /** A layout with every list present (stored layouts may lack keys). */
6
+ export declare function normalizeLayout(layout?: Partial<DashboardLayout> | null): DashboardLayout;
7
+ /** The default layout: the registered order, nothing hidden or collapsed. */
8
+ export declare const emptyLayout: () => DashboardLayout;
9
+ /**
10
+ * The items in the user's order. Ids in `order` come first, in that order; an item missing from it (added by a module
11
+ * after the user saved) keeps its registered place: right after the registered item before it.
12
+ */
13
+ export declare function orderItems<T extends Identified>(items: T[], order: string[]): T[];
14
+ export interface AppliedLayout<T> {
15
+ /** The items to render, in the user's order. */
16
+ items: T[];
17
+ /** The hidden items, in the user's order. */
18
+ hidden: T[];
19
+ /** Ids of the collapsed items. */
20
+ collapsed: string[];
21
+ }
22
+ /**
23
+ * Orders the items and splits off the hidden ones. With `all` (every item id of the dashboard in registered order,
24
+ * `getDashboardItemIds`), the order is worked out over every item first and then narrowed to `items`, so an item
25
+ * filtered out here (another platform, a permission) still anchors the items registered after it. A layout that
26
+ * stores only the moved ids (`moveItem`) needs it to give the same order on every platform.
27
+ */
28
+ export declare function applyLayout<T extends Identified>(items: T[], layout?: Partial<DashboardLayout> | null, all?: readonly string[]): AppliedLayout<T>;
29
+ /**
30
+ * The fewest ids to store so that `orderItems` over `registered` gives `full` (a reordering of `registered`): an item
31
+ * is left out when it comes right after its registered predecessor (or first, for the first registered item), since
32
+ * `orderItems` puts it there by itself. So a layout holds only the items the user moved, however many items the
33
+ * dashboard has.
34
+ */
35
+ export declare function minimalOrder(registered: readonly string[], full: readonly string[]): string[];
36
+ /**
37
+ * Moves an item to `toIndex` among the shown items (`shown`, in their current order). The move happens inside the
38
+ * full order of every item of the dashboard (`all`, registered order, including items hidden or filtered out by
39
+ * platform or permission): the item lands right before or after the shown item now at `toIndex`, and every other
40
+ * item keeps its position relative to the rest. So moving an item on the web never reorders the mobile-only items.
41
+ * Only the moved ids are stored (`minimalOrder`); apply the layout with `all` (`applyLayout`).
42
+ */
43
+ export declare function moveItem(layout: Partial<DashboardLayout> | null | undefined, all: string[], shown: string[], id: string, toIndex: number): DashboardLayout;
44
+ /** The layout without ids that are not items of the dashboard (`ids`): removed or renamed items. */
45
+ export declare function pruneLayout(layout: Partial<DashboardLayout> | null | undefined, ids: Iterable<string>): DashboardLayout;
46
+ export declare function hideItem(layout: Partial<DashboardLayout> | null | undefined, id: string): DashboardLayout;
47
+ export declare function showItem(layout: Partial<DashboardLayout> | null | undefined, id: string): DashboardLayout;
48
+ export declare function toggleCollapsed(layout: Partial<DashboardLayout> | null | undefined, id: string): DashboardLayout;
49
+ /** Replaces one item's settings; an empty object removes them. */
50
+ export declare function setItemSettings(layout: Partial<DashboardLayout> | null | undefined, id: string, value: Record<string, unknown>): DashboardLayout;
51
+ /** Back to the registered default: order, hidden, collapsed and settings cleared. */
52
+ export declare const resetLayout: () => DashboardLayout;
53
+ /** Whether an item shows on `platform`: its `platforms` (default both) and its `when.platform`. */
54
+ export declare function isOnPlatform(item: {
55
+ platforms?: DashboardPlatform[];
56
+ when?: DashboardItemCondition;
57
+ }, platform: DashboardPlatform): boolean;
58
+ export declare function filterByPlatform<T extends {
59
+ platforms?: DashboardPlatform[];
60
+ when?: DashboardItemCondition;
61
+ }>(items: T[], platform: DashboardPlatform): T[];
62
+ export {};
@@ -0,0 +1,110 @@
1
+ export function normalizeLayout(layout) {
2
+ return {
3
+ order: [...layout?.order ?? []],
4
+ hidden: [...layout?.hidden ?? []],
5
+ collapsed: [...layout?.collapsed ?? []],
6
+ ...layout?.settings ? { settings: { ...layout.settings } } : {}
7
+ };
8
+ }
9
+ export const emptyLayout = () => normalizeLayout();
10
+ export function orderItems(items, order) {
11
+ const byId = new Map(items.map((item) => [item.id, item]));
12
+ const result = [...new Set(order)].filter((id) => byId.has(id)).map((id) => byId.get(id));
13
+ const placed = new Set(result.map((item) => item.id));
14
+ items.forEach((item, index) => {
15
+ if (placed.has(item.id)) return;
16
+ let at = 0;
17
+ for (let previous = index - 1; previous >= 0; previous--) {
18
+ const found = result.findIndex((entry) => entry.id === items[previous].id);
19
+ if (found !== -1) {
20
+ at = found + 1;
21
+ break;
22
+ }
23
+ }
24
+ result.splice(at, 0, item);
25
+ placed.add(item.id);
26
+ });
27
+ return result;
28
+ }
29
+ export function applyLayout(items, layout, all) {
30
+ const normalized = normalizeLayout(layout);
31
+ const ordered = all ? orderWithin(items, all, normalized.order) : orderItems(items, normalized.order);
32
+ const hidden = new Set(normalized.hidden);
33
+ const ids = new Set(items.map((item) => item.id));
34
+ return {
35
+ items: ordered.filter((item) => !hidden.has(item.id)),
36
+ hidden: ordered.filter((item) => hidden.has(item.id)),
37
+ collapsed: normalized.collapsed.filter((id) => ids.has(id))
38
+ };
39
+ }
40
+ function orderWithin(items, all, order) {
41
+ const ids = [.../* @__PURE__ */ new Set([...all, ...items.map((item) => item.id)])];
42
+ const position = new Map(orderItems(ids.map((id) => ({ id })), order).map((entry, index) => [entry.id, index]));
43
+ return [...items].sort((a, b) => position.get(a.id) - position.get(b.id));
44
+ }
45
+ export function minimalOrder(registered, full) {
46
+ const position = new Map(full.map((id, index2) => [id, index2]));
47
+ const index = new Map(registered.map((id, at) => [id, at]));
48
+ return full.filter((id) => {
49
+ const at = index.get(id);
50
+ if (at === void 0) return true;
51
+ if (at === 0) return position.get(id) !== 0;
52
+ const before = position.get(registered[at - 1]);
53
+ return before === void 0 || position.get(id) !== before + 1;
54
+ });
55
+ }
56
+ export function moveItem(layout, all, shown, id, toIndex) {
57
+ const normalized = normalizeLayout(layout);
58
+ const from = shown.indexOf(id);
59
+ if (from === -1) return normalized;
60
+ const target = shown[Math.max(0, Math.min(Math.trunc(toIndex), shown.length - 1))];
61
+ const registered = [.../* @__PURE__ */ new Set([...all, ...shown])];
62
+ const full = orderItems(registered.map((entry) => ({ id: entry })), normalized.order).map((entry) => entry.id);
63
+ if (target === id) return { ...normalized, order: minimalOrder(registered, full) };
64
+ const order = full.filter((entry) => entry !== id);
65
+ const at = order.indexOf(target);
66
+ order.splice(toIndex > from ? at + 1 : at, 0, id);
67
+ return { ...normalized, order: minimalOrder(registered, order) };
68
+ }
69
+ export function pruneLayout(layout, ids) {
70
+ const known = new Set(ids);
71
+ const normalized = normalizeLayout(layout);
72
+ const keep = (list) => [...new Set(list)].filter((id) => known.has(id));
73
+ const settings = Object.fromEntries(Object.entries(normalized.settings ?? {}).filter(([id]) => known.has(id)));
74
+ return {
75
+ order: keep(normalized.order),
76
+ hidden: keep(normalized.hidden),
77
+ collapsed: keep(normalized.collapsed),
78
+ ...Object.keys(settings).length ? { settings } : {}
79
+ };
80
+ }
81
+ const without = (list, id) => list.filter((entry) => entry !== id);
82
+ export function hideItem(layout, id) {
83
+ const normalized = normalizeLayout(layout);
84
+ return { ...normalized, hidden: [...without(normalized.hidden, id), id] };
85
+ }
86
+ export function showItem(layout, id) {
87
+ const normalized = normalizeLayout(layout);
88
+ return { ...normalized, hidden: without(normalized.hidden, id) };
89
+ }
90
+ export function toggleCollapsed(layout, id) {
91
+ const normalized = normalizeLayout(layout);
92
+ const collapsed = normalized.collapsed.includes(id) ? without(normalized.collapsed, id) : [...normalized.collapsed, id];
93
+ return { ...normalized, collapsed };
94
+ }
95
+ export function setItemSettings(layout, id, value) {
96
+ const normalized = normalizeLayout(layout);
97
+ const settings = Object.fromEntries(Object.entries(normalized.settings ?? {}).filter(([key]) => key !== id));
98
+ if (Object.keys(value).length) settings[id] = { ...value };
99
+ const { settings: _old, ...rest } = normalized;
100
+ return Object.keys(settings).length ? { ...rest, settings } : rest;
101
+ }
102
+ export const resetLayout = () => emptyLayout();
103
+ export function isOnPlatform(item, platform) {
104
+ if (item.platforms && !item.platforms.includes(platform)) return false;
105
+ if (item.when?.platform && item.when.platform !== platform) return false;
106
+ return true;
107
+ }
108
+ export function filterByPlatform(items, platform) {
109
+ return items.filter((item) => isOnPlatform(item, platform));
110
+ }
@@ -0,0 +1,11 @@
1
+ import type { DashboardRegistryEntry } from '../../types.js';
2
+ /** The widget area a dashboard's items are registered in. */
3
+ export declare const dashboardArea: (name: string) => string;
4
+ /** The dashboard name of a widget area, or `undefined` for an area that is not a dashboard's. */
5
+ export declare function dashboardOfArea(area: string): string | undefined;
6
+ /** Whether an item's `when.module` holds. `when.platform` is decided at runtime. */
7
+ export declare function isModuleConditionMet(entry: Pick<DashboardRegistryEntry, 'when'>, hasModule: (name: string) => boolean): boolean;
8
+ /** The registry without the items whose `when.module` is not installed. */
9
+ export declare function resolveDashboardRegistry(dashboards: Record<string, DashboardRegistryEntry[]>, hasModule: (name: string) => boolean): Record<string, DashboardRegistryEntry[]>;
10
+ /** The `#dashboard/registry` module: plain data, keyed by dashboard name, then item id. */
11
+ export declare function dashboardRegistryTemplate(dashboards: Record<string, DashboardRegistryEntry[]>): string;
@@ -0,0 +1,15 @@
1
+ export const dashboardArea = (name) => `dashboard.${name}`;
2
+ export function dashboardOfArea(area) {
3
+ return area.startsWith("dashboard.") ? area.slice("dashboard.".length) : void 0;
4
+ }
5
+ export function isModuleConditionMet(entry, hasModule) {
6
+ return !entry.when?.module || hasModule(entry.when.module);
7
+ }
8
+ export function resolveDashboardRegistry(dashboards, hasModule) {
9
+ return Object.fromEntries(Object.entries(dashboards).map(([name, entries]) => [name, entries.filter((entry) => isModuleConditionMet(entry, hasModule))]));
10
+ }
11
+ export function dashboardRegistryTemplate(dashboards) {
12
+ const byId = Object.fromEntries(Object.entries(dashboards).map(([name, entries]) => [name, Object.fromEntries(entries.map((entry) => [entry.id, entry]))]));
13
+ return `export const dashboards = ${JSON.stringify(byId)}
14
+ `;
15
+ }
@@ -0,0 +1,12 @@
1
+ import type { DashboardLayout } from '../../types.js';
2
+ export type DashboardLayouts = Record<string, DashboardLayout>;
3
+ /**
4
+ * The valid layouts of a stored value, by dashboard name. A layout that no longer parses (a limit changed, a row edited
5
+ * by hand) is dropped on its own, so it never fails the others or every later save. At most `DASHBOARD_LIMITS.dashboards`.
6
+ */
7
+ export declare function validDashboardLayouts(stored: unknown): DashboardLayouts;
8
+ /**
9
+ * The layouts after a change: each named dashboard replaced, or removed with `null`; the others kept. `null` when the
10
+ * result would hold more than `DASHBOARD_LIMITS.dashboards` layouts.
11
+ */
12
+ export declare function mergeDashboardLayouts(current: DashboardLayouts, change: Record<string, DashboardLayout | null>): DashboardLayouts | null;
@@ -0,0 +1,16 @@
1
+ import { DASHBOARD_LIMITS, dashboardLayoutSchema, dashboardNameSchema } from "../preferences.js";
2
+ export function validDashboardLayouts(stored) {
3
+ if (!stored || typeof stored !== "object" || Array.isArray(stored)) return {};
4
+ const layouts = {};
5
+ for (const [name, value] of Object.entries(stored)) {
6
+ if (Object.keys(layouts).length >= DASHBOARD_LIMITS.dashboards) break;
7
+ if (!dashboardNameSchema.safeParse(name).success) continue;
8
+ const parsed = dashboardLayoutSchema.safeParse(value);
9
+ if (parsed.success) layouts[name] = parsed.data;
10
+ }
11
+ return layouts;
12
+ }
13
+ export function mergeDashboardLayouts(current, change) {
14
+ const next = Object.fromEntries(Object.entries({ ...current, ...change }).filter((entry) => entry[1] !== null));
15
+ return Object.keys(next).length > DASHBOARD_LIMITS.dashboards ? null : next;
16
+ }
@@ -0,0 +1,11 @@
1
+ /** The dashboard API (with `@frigear-nu/preferences` and `@frigear-nu/auth` installed). */
2
+ export declare const dashboardApi: {
3
+ readonly me: {
4
+ /**
5
+ * `GET` the caller's layouts (`{ layouts: { [dashboard]: DashboardLayout } }`); `PATCH { layouts: { [dashboard]:
6
+ * DashboardLayout | null } }` replaces (or with `null` removes) the layouts it names, keeps the others, and answers
7
+ * like the `GET`. `dashboard:layouts`: a session, or a token given it. Only ever the caller's own.
8
+ */
9
+ readonly layouts: "/api/dashboard/me/layouts";
10
+ };
11
+ };