@okjt/dashboard 0.0.0-stage → 0.1.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 (46) hide show
  1. package/README.md +144 -2
  2. package/dist/ActivityPanel.js +48 -0
  3. package/dist/AdminBulkActions.js +109 -0
  4. package/dist/AdminCard.js +7 -0
  5. package/dist/AdminChromeContext.js +16 -0
  6. package/dist/AdminFloatingToolbar.js +147 -0
  7. package/dist/AdminInput.js +66 -0
  8. package/dist/AdminListPanel.js +26 -0
  9. package/dist/AdminModal.js +23 -0
  10. package/dist/AdminPageHero.js +101 -0
  11. package/dist/AdminPageLayout.js +54 -0
  12. package/dist/AdminPagination.js +92 -0
  13. package/dist/AdminSidePanel.js +479 -0
  14. package/dist/AdminSummaryCards.js +51 -0
  15. package/dist/AdminToolbarFilters.js +168 -0
  16. package/dist/AdminToolbarSearch.js +61 -0
  17. package/dist/AdminTutorial.js +221 -0
  18. package/dist/AuthContext.js +189 -0
  19. package/dist/CollaborationContext.js +84 -0
  20. package/dist/CollaboratorAvatars.js +36 -0
  21. package/dist/DashboardHeader.js +140 -0
  22. package/dist/DashboardProvider.js +45 -0
  23. package/dist/DashboardShell.js +93 -0
  24. package/dist/DashboardSidebar.js +97 -0
  25. package/dist/DeleteButton.js +21 -0
  26. package/dist/EditableFieldset.js +9 -0
  27. package/dist/EmptyState.js +22 -0
  28. package/dist/GoogleButton.js +22 -0
  29. package/dist/NotificationsBell.js +149 -0
  30. package/dist/QueryError.js +23 -0
  31. package/dist/SearchContext.js +16 -0
  32. package/dist/ShareModal.js +228 -0
  33. package/dist/StatCard.js +33 -0
  34. package/dist/ToggleButton.js +26 -0
  35. package/dist/UnsavedChangesStatus.js +13 -0
  36. package/dist/VersionHistoryDrawer.js +172 -0
  37. package/dist/index.js +110 -0
  38. package/dist/modules.js +32 -0
  39. package/dist/passkeys.js +84 -0
  40. package/dist/useActivityPanel.js +34 -0
  41. package/dist/useAdminAction.js +77 -0
  42. package/dist/useCrudHandlers.js +54 -0
  43. package/dist/useFilteredItems.js +19 -0
  44. package/dist/useSavedViews.js +30 -0
  45. package/dist/useUnsavedChangesGuard.js +41 -0
  46. package/package.json +39 -4
@@ -0,0 +1,172 @@
1
+ import { jsx, jsxs } from "react/jsx-runtime";
2
+ import { useState } from "react";
3
+ import { motion } from "framer-motion";
4
+ import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
5
+ import { format, formatDistanceToNow, isToday, isYesterday } from "date-fns";
6
+ import { History, X, RotateCcw, Globe2 } from "lucide-react";
7
+ import { Overlay, Button, Spinner, SegmentedControl, confirmAction, notifyError, notifySuccess, usePermissions } from "@okjt/ui";
8
+ import { CollaboratorAvatar } from "./CollaboratorAvatars.js";
9
+ import { useDashboard } from "./DashboardProvider.js";
10
+ import { useModules } from "./modules.js";
11
+ const ACTION_WORDS = { created: "added", updated: "edited", deleted: "deleted", restored: "restored" };
12
+ const dayLabel = (date) => isToday(date) ? "Today" : isYesterday(date) ? "Yesterday" : format(date, "EEEE, d MMM yyyy");
13
+ const fieldLabel = (field) => field.replace(/_/g, " ").replace(/^\w/, (c) => c.toUpperCase());
14
+ function Change({ change }) {
15
+ return /* @__PURE__ */ jsxs("li", { className: "text-xs text-tone-600 break-words", children: [
16
+ /* @__PURE__ */ jsxs("span", { className: "font-medium text-tone-700", children: [
17
+ fieldLabel(change.field),
18
+ ": "
19
+ ] }),
20
+ change.before !== null && /* @__PURE__ */ jsx("del", { className: "text-tone-400 decoration-red-300", children: change.before }),
21
+ change.before !== null && " \u2192 ",
22
+ /* @__PURE__ */ jsx("span", { className: "text-tone-800", children: change.after ?? "\u2014" })
23
+ ] });
24
+ }
25
+ function Entry({ revision, batchSize, showModule, onRestore, restoring, canRestore }) {
26
+ const { anonymousName } = useDashboard();
27
+ const { moduleByKey } = useModules();
28
+ const who = revision.user || { id: 0, name: anonymousName };
29
+ const when = new Date(revision.updated_at || revision.created_at);
30
+ const moduleLabel = moduleByKey(revision.module)?.label || revision.module;
31
+ return /* @__PURE__ */ jsxs("li", { className: "flex gap-3 py-3", children: [
32
+ /* @__PURE__ */ jsx(CollaboratorAvatar, { person: who, size: "sm" }),
33
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 space-y-1", children: [
34
+ /* @__PURE__ */ jsxs("p", { className: "text-sm text-tone-700 leading-snug", children: [
35
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-tone-900", children: who.name }),
36
+ " ",
37
+ ACTION_WORDS[revision.action] || revision.action,
38
+ " ",
39
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-tone-900", children: revision.subject_label || revision.subject_type })
40
+ ] }),
41
+ /* @__PURE__ */ jsxs("p", { className: "text-[11px] text-tone-500 flex flex-wrap gap-x-2", children: [
42
+ /* @__PURE__ */ jsx("span", { title: format(when, "PPpp"), children: formatDistanceToNow(when, { addSuffix: true }) }),
43
+ showModule && /* @__PURE__ */ jsx("span", { className: "px-1.5 rounded bg-tone-100 text-tone-600", children: moduleLabel })
44
+ ] }),
45
+ revision.changes?.length > 0 && /* @__PURE__ */ jsxs("ul", { className: "space-y-0.5 pt-0.5", children: [
46
+ revision.changes.slice(0, 4).map((change) => /* @__PURE__ */ jsx(Change, { change }, change.field)),
47
+ revision.changes.length > 4 && /* @__PURE__ */ jsxs("li", { className: "text-[11px] text-tone-400", children: [
48
+ "+",
49
+ revision.changes.length - 4,
50
+ " more fields"
51
+ ] })
52
+ ] }),
53
+ canRestore && revision.restorable && /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1.5 pt-1", children: [
54
+ /* @__PURE__ */ jsx(Button, { size: "sm", icon: RotateCcw, disabled: restoring, onClick: () => onRestore(revision, false), children: revision.action === "deleted" ? "Restore deleted item" : "Restore this version" }),
55
+ batchSize > 1 && /* @__PURE__ */ jsxs(Button, { size: "sm", disabled: restoring, onClick: () => onRestore(revision, true), children: [
56
+ "Restore whole save (",
57
+ batchSize,
58
+ ")"
59
+ ] })
60
+ ] })
61
+ ] })
62
+ ] });
63
+ }
64
+ function VersionHistoryDrawer({ module, onClose, onRestored }) {
65
+ const queryClient = useQueryClient();
66
+ const [scope, setScope] = useState(module ? "page" : "all");
67
+ const [restoring, setRestoring] = useState(false);
68
+ const { canEdit } = usePermissions();
69
+ const { api } = useDashboard();
70
+ const { moduleByKey } = useModules();
71
+ const filterModule = scope === "page" ? module : null;
72
+ const moduleLabel = moduleByKey(module)?.label;
73
+ const query = useInfiniteQuery({
74
+ queryKey: ["revisions", filterModule],
75
+ queryFn: async ({ pageParam }) => (await api.get("/revisions", { params: { module: filterModule || void 0, page: pageParam } })).data,
76
+ initialPageParam: 1,
77
+ getNextPageParam: (last) => last && last.current_page < last.last_page ? last.current_page + 1 : void 0,
78
+ staleTime: 0
79
+ });
80
+ const revisions = query.data?.pages.flatMap((p) => p?.data || []) || [];
81
+ const batchSizes = revisions.reduce((acc, r) => ({ ...acc, [r.batch]: (acc[r.batch] || 0) + 1 }), {});
82
+ const restore = async (revision, wholeBatch) => {
83
+ const ok = await confirmAction({
84
+ title: wholeBatch ? "Restore the whole save?" : "Restore this version?",
85
+ message: wholeBatch ? `Every change saved together with "${revision.subject_label}" goes back to how it was then. You can undo this from the history too.` : `"${revision.subject_label}" goes back to this version. Your current version stays in the history, so you can undo this.`,
86
+ confirmLabel: "Restore"
87
+ });
88
+ if (!ok) return;
89
+ setRestoring(true);
90
+ try {
91
+ const res = await api.post(`/revisions/${revision.id}/restore`, { batch: wholeBatch });
92
+ notifySuccess(res.data?.restored > 1 ? `${res.data.restored} changes restored` : "Version restored");
93
+ await queryClient.invalidateQueries();
94
+ onRestored?.();
95
+ } catch (err) {
96
+ notifyError(err, "Could not restore this version");
97
+ } finally {
98
+ setRestoring(false);
99
+ }
100
+ };
101
+ let lastDay = null;
102
+ return /* @__PURE__ */ jsx(Overlay, { onClose, className: "flex justify-end", backdropClassName: "bg-black/30", zIndex: 90, children: /* @__PURE__ */ jsxs(
103
+ motion.aside,
104
+ {
105
+ role: "dialog",
106
+ "aria-modal": "true",
107
+ "aria-label": "Version history",
108
+ initial: { x: "100%" },
109
+ animate: { x: 0 },
110
+ exit: { x: "100%" },
111
+ transition: { type: "spring", damping: 32, stiffness: 300 },
112
+ onClick: (e) => e.stopPropagation(),
113
+ className: "h-full w-full max-w-md bg-white shadow-2xl flex flex-col",
114
+ children: [
115
+ /* @__PURE__ */ jsxs("div", { className: "shrink-0 px-4 py-3 border-b border-tone-100 space-y-3", children: [
116
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
117
+ /* @__PURE__ */ jsx(History, { className: "w-5 h-5 text-accent" }),
118
+ /* @__PURE__ */ jsx("h2", { className: "text-lg font-medium text-tone-800 flex-1", children: "Version history" }),
119
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: onClose, "aria-label": "Close version history", className: "p-1.5 rounded-lg text-tone-500 hover:bg-tone-100", children: /* @__PURE__ */ jsx(X, { className: "w-5 h-5" }) })
120
+ ] }),
121
+ module && /* @__PURE__ */ jsx(
122
+ SegmentedControl,
123
+ {
124
+ size: "sm",
125
+ fullWidth: true,
126
+ "aria-label": "Show changes for",
127
+ value: scope,
128
+ onChange: setScope,
129
+ options: [
130
+ { value: "page", label: moduleLabel || "This page" },
131
+ { value: "all", label: "All pages", icon: Globe2 }
132
+ ]
133
+ }
134
+ )
135
+ ] }),
136
+ /* @__PURE__ */ jsxs("div", { className: "flex-1 min-h-0 overflow-y-auto px-4", children: [
137
+ query.isLoading ? /* @__PURE__ */ jsx("div", { className: "py-10 flex justify-center", children: /* @__PURE__ */ jsx(Spinner, {}) }) : query.isError ? /* @__PURE__ */ jsx("p", { className: "py-10 text-center text-sm text-tone-500", children: "Couldn't load the history. Try again in a moment." }) : revisions.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "py-12 text-center space-y-1", children: [
138
+ /* @__PURE__ */ jsx(History, { className: "w-10 h-10 mx-auto text-tone-200" }),
139
+ /* @__PURE__ */ jsxs("p", { className: "text-sm text-tone-500", children: [
140
+ "No changes recorded ",
141
+ scope === "page" ? "on this page " : "",
142
+ "yet."
143
+ ] }),
144
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-tone-400", children: "Every save from now on can be restored here." })
145
+ ] }) : /* @__PURE__ */ jsx("ul", { children: revisions.map((revision) => {
146
+ const day = dayLabel(new Date(revision.updated_at || revision.created_at));
147
+ const header = day !== lastDay ? day : null;
148
+ lastDay = day;
149
+ return /* @__PURE__ */ jsxs("li", { children: [
150
+ header && /* @__PURE__ */ jsx("h3", { className: "sticky top-0 z-10 bg-white/95 backdrop-blur pt-3 pb-1 text-[11px] font-bold uppercase tracking-wider text-tone-500", children: header }),
151
+ /* @__PURE__ */ jsx("ul", { className: "divide-y divide-tone-100", children: /* @__PURE__ */ jsx(
152
+ Entry,
153
+ {
154
+ revision,
155
+ batchSize: batchSizes[revision.batch] || 1,
156
+ showModule: scope === "all",
157
+ onRestore: restore,
158
+ restoring,
159
+ canRestore: canEdit
160
+ }
161
+ ) })
162
+ ] }, revision.id);
163
+ }) }),
164
+ query.hasNextPage && /* @__PURE__ */ jsx("div", { className: "py-4 flex justify-center", children: /* @__PURE__ */ jsx(Button, { size: "sm", loading: query.isFetchingNextPage, onClick: () => query.fetchNextPage(), children: "Load older changes" }) })
165
+ ] })
166
+ ]
167
+ }
168
+ ) });
169
+ }
170
+ export {
171
+ VersionHistoryDrawer as default
172
+ };
package/dist/index.js ADDED
@@ -0,0 +1,110 @@
1
+ import { DashboardProvider, useDashboard } from "./DashboardProvider.js";
2
+ import { AdminChromeProvider, useAdminChrome, AdminHeaderStatus } from "./AdminChromeContext.js";
3
+ import { SearchProvider, useSearch } from "./SearchContext.js";
4
+ import { default as default2 } from "./AdminPageLayout.js";
5
+ import { default as default3 } from "./AdminPageHero.js";
6
+ import { default as default4 } from "./AdminSummaryCards.js";
7
+ import { default as default5 } from "./StatCard.js";
8
+ import { default as default6 } from "./AdminFloatingToolbar.js";
9
+ import { default as default7 } from "./AdminToolbarSearch.js";
10
+ import { default as default8, countActiveFilters } from "./AdminToolbarFilters.js";
11
+ import { SidePanelNav, SidePanelAside, SidePanelMobileBar } from "./AdminSidePanel.js";
12
+ import { default as default9 } from "./AdminListPanel.js";
13
+ import { default as default10, pageWindow } from "./AdminPagination.js";
14
+ import { default as default11 } from "./AdminBulkActions.js";
15
+ import { default as default12 } from "./AdminCard.js";
16
+ import { AdminInput, AdminTextarea, AdminSelect } from "./AdminInput.js";
17
+ import { default as default13 } from "./AdminModal.js";
18
+ import { default as default14 } from "./EditableFieldset.js";
19
+ import { default as default15 } from "./DeleteButton.js";
20
+ import { default as default16 } from "./ToggleButton.js";
21
+ import { default as default17 } from "./EmptyState.js";
22
+ import { default as default18 } from "./QueryError.js";
23
+ import { default as default19 } from "./UnsavedChangesStatus.js";
24
+ import { default as default20 } from "./AdminTutorial.js";
25
+ import { default as default21, useBulkAdminAction } from "./useAdminAction.js";
26
+ import { default as default22 } from "./useCrudHandlers.js";
27
+ import { default as default23, useUnsavedChanges } from "./useUnsavedChangesGuard.js";
28
+ import { default as default24 } from "./useFilteredItems.js";
29
+ import { default as default25 } from "./useSavedViews.js";
30
+ import { useModules, moduleForPathIn, initials, collaboratorColor } from "./modules.js";
31
+ import { CollaborationProvider, useCollaboration, HEARTBEAT_MS } from "./CollaborationContext.js";
32
+ import { default as default26, CollaboratorAvatar } from "./CollaboratorAvatars.js";
33
+ import { default as default27 } from "./ActivityPanel.js";
34
+ import { default as default28 } from "./useActivityPanel.js";
35
+ import { default as default29 } from "./VersionHistoryDrawer.js";
36
+ import { default as default30 } from "./ShareModal.js";
37
+ import { default as default31 } from "./DashboardShell.js";
38
+ import { default as default32 } from "./DashboardSidebar.js";
39
+ import { default as default33 } from "./DashboardHeader.js";
40
+ import { AuthProvider, useAuth, default as default34 } from "./AuthContext.js";
41
+ import { default as default35 } from "./GoogleButton.js";
42
+ import { default as default36 } from "./NotificationsBell.js";
43
+ import { loginWithPasskey, registerPasskey, passkeysSupported } from "./passkeys.js";
44
+ export {
45
+ default27 as ActivityPanel,
46
+ default11 as AdminBulkActions,
47
+ default12 as AdminCard,
48
+ AdminChromeProvider,
49
+ default6 as AdminFloatingToolbar,
50
+ AdminHeaderStatus,
51
+ AdminInput,
52
+ default9 as AdminListPanel,
53
+ default13 as AdminModal,
54
+ default3 as AdminPageHero,
55
+ default2 as AdminPageLayout,
56
+ default10 as AdminPagination,
57
+ AdminSelect,
58
+ default4 as AdminSummaryCards,
59
+ AdminTextarea,
60
+ default8 as AdminToolbarFilters,
61
+ default7 as AdminToolbarSearch,
62
+ default20 as AdminTutorial,
63
+ default34 as AuthContext,
64
+ AuthProvider,
65
+ CollaborationProvider,
66
+ CollaboratorAvatar,
67
+ default26 as CollaboratorAvatars,
68
+ default33 as DashboardHeader,
69
+ DashboardProvider,
70
+ default31 as DashboardShell,
71
+ default32 as DashboardSidebar,
72
+ default15 as DeleteButton,
73
+ default14 as EditableFieldset,
74
+ default17 as EmptyState,
75
+ default35 as GoogleButton,
76
+ HEARTBEAT_MS,
77
+ default36 as NotificationsBell,
78
+ default18 as QueryError,
79
+ SearchProvider,
80
+ default30 as ShareModal,
81
+ SidePanelAside,
82
+ SidePanelMobileBar,
83
+ SidePanelNav,
84
+ default5 as StatCard,
85
+ default16 as ToggleButton,
86
+ default19 as UnsavedChangesStatus,
87
+ default29 as VersionHistoryDrawer,
88
+ collaboratorColor,
89
+ countActiveFilters,
90
+ initials,
91
+ loginWithPasskey,
92
+ moduleForPathIn,
93
+ pageWindow,
94
+ passkeysSupported,
95
+ registerPasskey,
96
+ default28 as useActivityPanel,
97
+ default21 as useAdminAction,
98
+ useAdminChrome,
99
+ useAuth,
100
+ useBulkAdminAction,
101
+ useCollaboration,
102
+ default22 as useCrudHandlers,
103
+ useDashboard,
104
+ default24 as useFilteredItems,
105
+ useModules,
106
+ default25 as useSavedViews,
107
+ useSearch,
108
+ useUnsavedChanges,
109
+ default23 as useUnsavedChangesGuard
110
+ };
@@ -0,0 +1,32 @@
1
+ import { useMemo } from "react";
2
+ import { useDashboard } from "./DashboardProvider.js";
3
+ function moduleForPathIn(modules, pathname = "") {
4
+ const path = pathname.replace(/\/+$/, "") || "/";
5
+ let best = null;
6
+ for (const m of modules) {
7
+ if ((path === m.path || path.startsWith(`${m.path}/`)) && (!best || m.path.length > best.path.length)) best = m;
8
+ }
9
+ return best;
10
+ }
11
+ function useModules() {
12
+ const { modules } = useDashboard();
13
+ return useMemo(() => {
14
+ const byKey = Object.fromEntries(modules.map((m) => [m.key, m]));
15
+ return {
16
+ modules,
17
+ moduleByKey: (key) => byKey[key] || null,
18
+ moduleForPath: (pathname) => moduleForPathIn(modules, pathname)
19
+ };
20
+ }, [modules]);
21
+ }
22
+ function initials(name = "") {
23
+ return name.trim().split(/\s+/).slice(0, 2).map((p) => p[0]?.toUpperCase() || "").join("") || "?";
24
+ }
25
+ const COLLABORATOR_COLORS = ["#A67B5B", "#6B8E7F", "#8B6FA6", "#C27C5A", "#5B7FA6", "#A65B7B", "#7F8E5B"];
26
+ const collaboratorColor = (id = 0) => COLLABORATOR_COLORS[Math.abs(Number(id) || 0) % COLLABORATOR_COLORS.length];
27
+ export {
28
+ collaboratorColor,
29
+ initials,
30
+ moduleForPathIn,
31
+ useModules
32
+ };
@@ -0,0 +1,84 @@
1
+ function b64urlToBuffer(b64url) {
2
+ const bin = atob(b64url.replace(/-/g, "+").replace(/_/g, "/"));
3
+ const bytes = new Uint8Array(bin.length);
4
+ for (let i = 0; i < bin.length; i += 1) bytes[i] = bin.charCodeAt(i);
5
+ return bytes.buffer;
6
+ }
7
+ function bufferToB64url(buffer) {
8
+ let bin = "";
9
+ new Uint8Array(buffer).forEach((b) => {
10
+ bin += String.fromCharCode(b);
11
+ });
12
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
13
+ }
14
+ function decodeOptions(options, listKey) {
15
+ return {
16
+ ...options,
17
+ challenge: b64urlToBuffer(options.challenge),
18
+ [listKey]: (options[listKey] || []).map((c) => ({ ...c, id: b64urlToBuffer(c.id) }))
19
+ };
20
+ }
21
+ function encodeCredential(credential) {
22
+ const { response } = credential;
23
+ const base = {
24
+ id: credential.id,
25
+ rawId: bufferToB64url(credential.rawId),
26
+ type: credential.type,
27
+ clientExtensionResults: credential.getClientExtensionResults?.() || {}
28
+ };
29
+ if ("attestationObject" in response) {
30
+ return {
31
+ ...base,
32
+ response: {
33
+ attestationObject: bufferToB64url(response.attestationObject),
34
+ clientDataJSON: bufferToB64url(response.clientDataJSON),
35
+ transports: response.getTransports?.() || []
36
+ }
37
+ };
38
+ }
39
+ return {
40
+ ...base,
41
+ response: {
42
+ authenticatorData: bufferToB64url(response.authenticatorData),
43
+ clientDataJSON: bufferToB64url(response.clientDataJSON),
44
+ signature: bufferToB64url(response.signature),
45
+ userHandle: response.userHandle ? bufferToB64url(response.userHandle) : null
46
+ }
47
+ };
48
+ }
49
+ async function fetchOptions(url, headers, failure) {
50
+ const res = await fetch(url, { headers: { Accept: "application/json", ...headers }, credentials: "same-origin" });
51
+ if (!res.ok) throw new Error(failure);
52
+ const payload = await res.json();
53
+ return payload.data?.options || payload.options;
54
+ }
55
+ async function send(url, headers, body, failure) {
56
+ const res = await fetch(url, {
57
+ method: "POST",
58
+ headers: { "Content-Type": "application/json", Accept: "application/json", ...headers },
59
+ credentials: "same-origin",
60
+ body: JSON.stringify(body)
61
+ });
62
+ const payload = await res.json();
63
+ if (!res.ok) throw new Error(payload.message || failure);
64
+ return payload.data || payload;
65
+ }
66
+ async function loginWithPasskey({ base = "/api" } = {}) {
67
+ const options = await fetchOptions(`${base}/passkeys/login/options`, {}, "Could not start passkey sign-in.");
68
+ const credential = await navigator.credentials.get({ publicKey: decodeOptions(options, "allowCredentials") });
69
+ return send(`${base}/passkeys/login`, {}, { credential: encodeCredential(credential) }, "Passkey sign-in failed.");
70
+ }
71
+ async function registerPasskey(name, token, { base = "/api" } = {}) {
72
+ const auth = { Authorization: `Bearer ${token}` };
73
+ const options = await fetchOptions(`${base}/passkeys/options`, auth, "Could not start passkey registration.");
74
+ const credential = await navigator.credentials.create({ publicKey: decodeOptions(options, "excludeCredentials") });
75
+ return send(`${base}/passkeys`, auth, { name, credential: encodeCredential(credential) }, "Could not save passkey.");
76
+ }
77
+ function passkeysSupported() {
78
+ return typeof window !== "undefined" && !!window.PublicKeyCredential;
79
+ }
80
+ export {
81
+ loginWithPasskey,
82
+ passkeysSupported,
83
+ registerPasskey
84
+ };
@@ -0,0 +1,34 @@
1
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
+ import { Activity, History } from "lucide-react";
3
+ import ActivityPanel from "./ActivityPanel.js";
4
+ import { CollaboratorAvatar } from "./CollaboratorAvatars.js";
5
+ import { useCollaboration } from "./CollaborationContext.js";
6
+ function useActivityPanel() {
7
+ const { othersHere, openHistory } = useCollaboration();
8
+ return {
9
+ id: "activity",
10
+ title: "Activity",
11
+ icon: Activity,
12
+ subtitle: "Who\u2019s here and what changed",
13
+ defaultCollapsed: true,
14
+ mobile: false,
15
+ content: /* @__PURE__ */ jsx(ActivityPanel, {}),
16
+ rail: /* @__PURE__ */ jsxs(Fragment, { children: [
17
+ othersHere.slice(0, 3).map((person) => /* @__PURE__ */ jsx(CollaboratorAvatar, { person, size: "xs" }, person.id)),
18
+ /* @__PURE__ */ jsx(
19
+ "button",
20
+ {
21
+ type: "button",
22
+ onClick: openHistory,
23
+ "aria-label": "Version history",
24
+ title: "Version history",
25
+ className: "p-2 rounded-lg text-tone-500 hover:bg-tone-100 hover:text-accent",
26
+ children: /* @__PURE__ */ jsx(History, { className: "w-4 h-4" })
27
+ }
28
+ )
29
+ ] })
30
+ };
31
+ }
32
+ export {
33
+ useActivityPanel as default
34
+ };
@@ -0,0 +1,77 @@
1
+ import { useCallback, useMemo, useRef, useState } from "react";
2
+ import { useQueryClient } from "@tanstack/react-query";
3
+ import { toast } from "react-hot-toast";
4
+ import { usePermissions, confirmAction, notifyError, notifySuccess } from "@okjt/ui";
5
+ import { useDashboard } from "./DashboardProvider.js";
6
+ const resolve = (value, ...args) => typeof value === "function" ? value(...args) : value;
7
+ const deniedByRole = (err) => err?.response?.status === 403 && err.response.data?.reason === "role";
8
+ function useAdminAction(fn, options = {}) {
9
+ const { canEdit, isOwner } = usePermissions();
10
+ const allowed = options.role === "owner" ? isOwner : canEdit;
11
+ const queryClient = useQueryClient();
12
+ const refreshCollaboration = useDashboard().useAfterChange();
13
+ const [pendingKeys, setPendingKeys] = useState(() => /* @__PURE__ */ new Set());
14
+ const latest = useRef({ fn, options });
15
+ latest.current = { fn, options };
16
+ const run = useCallback(async (...args) => {
17
+ const { fn: write, options: opts } = latest.current;
18
+ if (!allowed) {
19
+ toast.error(opts.role === "owner" ? "Only owners can do this." : "You have view-only access.", { id: "role-denied" });
20
+ return void 0;
21
+ }
22
+ const confirmInput = resolve(opts.confirm, ...args);
23
+ if (confirmInput && !await confirmAction(confirmInput)) return void 0;
24
+ const key = opts.key ? opts.key(...args) : args[0];
25
+ setPendingKeys((keys) => new Set(keys).add(key));
26
+ try {
27
+ const result = await write(...args);
28
+ const message = resolve(opts.success, result, ...args);
29
+ if (message) notifySuccess(message);
30
+ await Promise.all([
31
+ ...(opts.invalidate || []).map((queryKey) => queryClient.invalidateQueries({ queryKey })),
32
+ queryClient.invalidateQueries({ queryKey: ["revisions"] })
33
+ ]);
34
+ refreshCollaboration?.();
35
+ opts.onSuccess?.(result, ...args);
36
+ return result;
37
+ } catch (err) {
38
+ if (opts.error !== false && !deniedByRole(err)) notifyError(err, resolve(opts.error, err, ...args) || "Something went wrong");
39
+ opts.onError?.(err, ...args);
40
+ if (opts.rethrow) throw err;
41
+ return void 0;
42
+ } finally {
43
+ setPendingKeys((keys) => {
44
+ const next = new Set(keys);
45
+ next.delete(key);
46
+ return next;
47
+ });
48
+ }
49
+ }, [allowed, queryClient, refreshCollaboration]);
50
+ return useMemo(() => ({
51
+ run,
52
+ allowed,
53
+ pending: pendingKeys.size > 0,
54
+ isPending: (key) => pendingKeys.has(key),
55
+ isAdminAction: true
56
+ }), [run, allowed, pendingKeys]);
57
+ }
58
+ function useBulkAdminAction(fn, options = {}) {
59
+ return useAdminAction(async (ids) => {
60
+ const results = await Promise.allSettled(ids.map((id) => fn(id)));
61
+ const failed = results.filter((r) => r.status === "rejected").length;
62
+ if (failed) {
63
+ const err = new Error(`${failed} of ${ids.length} failed`);
64
+ err.failed = failed;
65
+ throw err;
66
+ }
67
+ return ids.length;
68
+ }, {
69
+ key: () => "bulk",
70
+ error: (err, ids) => err.failed ? `${err.failed} of ${ids.length} couldn't be updated` : "Something went wrong",
71
+ ...options
72
+ });
73
+ }
74
+ export {
75
+ useAdminAction as default,
76
+ useBulkAdminAction
77
+ };
@@ -0,0 +1,54 @@
1
+ import { useState, useCallback } from "react";
2
+ import useAdminAction from "./useAdminAction.js";
3
+ function useCrudHandlers({ service, onRefresh, labels = {} }) {
4
+ const [selectedItem, setSelectedItem] = useState(null);
5
+ const [modalOpen, setModalOpen] = useState(false);
6
+ const handleAdd = useCallback(() => {
7
+ setSelectedItem(null);
8
+ setModalOpen(true);
9
+ }, []);
10
+ const handleEdit = useCallback((item) => {
11
+ setSelectedItem(item);
12
+ setModalOpen(true);
13
+ }, []);
14
+ const removeAction = useAdminAction(
15
+ (id, opts = {}) => opts.deleteFn ? opts.deleteFn(id) : service?.delete?.(id),
16
+ {
17
+ confirm: (id, opts = {}) => opts.confirmMessage || "Delete this item?",
18
+ success: labels.deleted,
19
+ error: "Failed to delete",
20
+ onSuccess: () => onRefresh?.()
21
+ }
22
+ );
23
+ const saveAction = useAdminAction(
24
+ (data) => selectedItem ? service.update(selectedItem.id, data) : service.create(data),
25
+ {
26
+ key: () => "save",
27
+ success: labels.saved,
28
+ error: "Failed to save",
29
+ rethrow: true,
30
+ onSuccess: () => {
31
+ setModalOpen(false);
32
+ setSelectedItem(null);
33
+ onRefresh?.();
34
+ }
35
+ }
36
+ );
37
+ const handleDelete = removeAction.run;
38
+ const handleSave = saveAction.run;
39
+ return {
40
+ selectedItem,
41
+ modalOpen,
42
+ setModalOpen,
43
+ isProcessing: removeAction.isPending,
44
+ handleAdd,
45
+ handleEdit,
46
+ handleDelete,
47
+ handleSave,
48
+ removeAction,
49
+ saveAction
50
+ };
51
+ }
52
+ export {
53
+ useCrudHandlers as default
54
+ };
@@ -0,0 +1,19 @@
1
+ import { useMemo } from "react";
2
+ function useFilteredItems(items, searchQuery, filterFn) {
3
+ return useMemo(() => {
4
+ if (!items) return [];
5
+ const searchLower = (searchQuery || "").toLowerCase();
6
+ if (!searchLower) return items;
7
+ return items.filter((item) => {
8
+ if (filterFn) return filterFn(item, searchLower);
9
+ return Object.values(item).some((val) => {
10
+ if (typeof val === "string") return val.toLowerCase().includes(searchLower);
11
+ if (val && typeof val === "object") return JSON.stringify(val).toLowerCase().includes(searchLower);
12
+ return false;
13
+ });
14
+ });
15
+ }, [items, searchQuery, filterFn]);
16
+ }
17
+ export {
18
+ useFilteredItems as default
19
+ };
@@ -0,0 +1,30 @@
1
+ import { useCallback, useState } from "react";
2
+ const read = (key) => {
3
+ try {
4
+ const stored = JSON.parse(localStorage.getItem(key) || "[]");
5
+ return Array.isArray(stored) ? stored : [];
6
+ } catch {
7
+ return [];
8
+ }
9
+ };
10
+ function useSavedViews(storageKey) {
11
+ const [views, setViews] = useState(() => read(storageKey));
12
+ const persist = useCallback((next) => {
13
+ setViews(next);
14
+ try {
15
+ localStorage.setItem(storageKey, JSON.stringify(next));
16
+ } catch {
17
+ }
18
+ }, [storageKey]);
19
+ const saveView = useCallback((name, state) => {
20
+ const trimmed = name.trim();
21
+ if (!trimmed) return;
22
+ const others = views.filter((v) => v.name.toLowerCase() !== trimmed.toLowerCase());
23
+ persist([...others, { id: `${Date.now()}`, name: trimmed, state }]);
24
+ }, [views, persist]);
25
+ const deleteView = useCallback((id) => persist(views.filter((v) => v.id !== id)), [views, persist]);
26
+ return { views, saveView, deleteView };
27
+ }
28
+ export {
29
+ useSavedViews as default
30
+ };
@@ -0,0 +1,41 @@
1
+ import { useEffect, useState } from "react";
2
+ import { useNavigate } from "react-router-dom";
3
+ import { confirmAction } from "@okjt/ui";
4
+ function useUnsavedChangesGuard(dirty, message = "You have unsaved changes. Leave without saving?") {
5
+ const navigate = useNavigate();
6
+ useEffect(() => {
7
+ if (!dirty) return void 0;
8
+ const onBeforeUnload = (e) => {
9
+ e.preventDefault();
10
+ e.returnValue = "";
11
+ };
12
+ const onClick = async (e) => {
13
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
14
+ const link = e.target.closest?.("a[href]");
15
+ if (!link || link.target === "_blank" || link.hasAttribute("download")) return;
16
+ const url = new URL(link.href, window.location.href);
17
+ if (url.origin !== window.location.origin || url.pathname === window.location.pathname) return;
18
+ e.preventDefault();
19
+ e.stopPropagation();
20
+ if (await confirmAction({ title: "Leave without saving?", message, confirmLabel: "Leave", tone: "danger" })) {
21
+ navigate(url.pathname + url.search + url.hash);
22
+ }
23
+ };
24
+ window.addEventListener("beforeunload", onBeforeUnload);
25
+ document.addEventListener("click", onClick, true);
26
+ return () => {
27
+ window.removeEventListener("beforeunload", onBeforeUnload);
28
+ document.removeEventListener("click", onClick, true);
29
+ };
30
+ }, [dirty, message, navigate]);
31
+ }
32
+ function useUnsavedChanges(value) {
33
+ const [baseline, setBaseline] = useState(null);
34
+ const dirty = baseline !== null && JSON.stringify(value) !== JSON.stringify(baseline);
35
+ useUnsavedChangesGuard(dirty);
36
+ return { dirty, markSaved: setBaseline, baseline };
37
+ }
38
+ export {
39
+ useUnsavedChangesGuard as default,
40
+ useUnsavedChanges
41
+ };