@okjt/dashboard 0.4.0 → 0.6.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.
@@ -46,10 +46,11 @@ function PlainToolbar({
46
46
  children: /* @__PURE__ */ jsxs(
47
47
  "div",
48
48
  {
49
- className: "admin-floating-toolbar flex flex-wrap items-center justify-center gap-1 sm:gap-2 p-1.5 sm:p-2 rounded-2xl border border-white/40 shadow-2xl backdrop-blur-md",
49
+ className: "admin-floating-toolbar flex flex-wrap items-center justify-center gap-1 sm:gap-2 p-1.5 sm:p-2 rounded-2xl border shadow-2xl backdrop-blur-md",
50
50
  style: {
51
- background: "rgba(255, 249, 245, 0.92)",
52
- boxShadow: "0 12px 40px color-mix(in srgb, var(--color-body) 18%, transparent)"
51
+ background: "var(--okjt-toolbar-bg, rgba(255, 249, 245, 0.92))",
52
+ borderColor: "var(--okjt-toolbar-border, rgba(255, 255, 255, 0.4))",
53
+ boxShadow: "0 12px 40px color-mix(in srgb, var(--okjt-shadow, var(--color-body)) 18%, transparent)"
53
54
  },
54
55
  children: [
55
56
  searchProps && /* @__PURE__ */ jsx(AdminToolbarSearch, { ...searchProps }),
@@ -1,64 +1,39 @@
1
1
  import { jsx, jsxs } from "react/jsx-runtime";
2
- import { useId } from "react";
3
- const baseInputClasses = "w-full px-4 py-2 rounded-lg border border-tone-200 focus:outline-none focus:ring-2 focus:ring-accent/20 focus:border-accent transition-colors";
4
- function AdminInput({ label, error, className = "", id, ...props }) {
5
- const generatedId = useId();
6
- const inputId = id || generatedId;
7
- const errorId = `${inputId}-error`;
8
- return /* @__PURE__ */ jsxs("div", { children: [
9
- label && /* @__PURE__ */ jsx("label", { htmlFor: inputId, className: "block text-sm font-medium text-tone-600 mb-1", children: label }),
10
- /* @__PURE__ */ jsx(
11
- "input",
2
+ import { forwardRef, useId } from "react";
3
+ import { useComponentDefaults } from "./DashboardProvider.js";
4
+ const baseInputClasses = "w-full px-4 py-2 rounded-lg border border-tone-200 bg-[var(--okjt-field-bg,transparent)] text-[color:var(--okjt-field-text,inherit)] focus:outline-none focus:ring-2 focus:ring-accent/20 focus:border-accent transition-colors";
5
+ function makeField(Tag, extraClasses, displayName) {
6
+ const Field = forwardRef(function Field2({ label, error, bare = false, className = "", id, children, baseClassName, ...props }, ref) {
7
+ const { classNames } = useComponentDefaults("Field", {});
8
+ const base = baseClassName ?? classNames?.[Tag] ?? `${baseInputClasses}${extraClasses ? ` ${extraClasses}` : ""}`;
9
+ const generatedId = useId();
10
+ const inputId = id || generatedId;
11
+ const errorId = `${inputId}-error`;
12
+ const control = /* @__PURE__ */ jsx(
13
+ Tag,
12
14
  {
15
+ ref,
13
16
  id: inputId,
14
17
  "aria-invalid": error ? true : void 0,
15
- "aria-describedby": error ? errorId : void 0,
16
- className: `${baseInputClasses} ${error ? "border-red-400" : ""} ${className}`,
17
- ...props
18
- }
19
- ),
20
- error && /* @__PURE__ */ jsx("p", { id: errorId, className: "text-red-500 text-xs mt-1", children: error })
21
- ] });
22
- }
23
- function AdminTextarea({ label, error, className = "", id, ...props }) {
24
- const generatedId = useId();
25
- const inputId = id || generatedId;
26
- const errorId = `${inputId}-error`;
27
- return /* @__PURE__ */ jsxs("div", { children: [
28
- label && /* @__PURE__ */ jsx("label", { htmlFor: inputId, className: "block text-sm font-medium text-tone-600 mb-1", children: label }),
29
- /* @__PURE__ */ jsx(
30
- "textarea",
31
- {
32
- id: inputId,
33
- "aria-invalid": error ? true : void 0,
34
- "aria-describedby": error ? errorId : void 0,
35
- className: `${baseInputClasses} resize-none ${error ? "border-red-400" : ""} ${className}`,
36
- ...props
37
- }
38
- ),
39
- error && /* @__PURE__ */ jsx("p", { id: errorId, className: "text-red-500 text-xs mt-1", children: error })
40
- ] });
41
- }
42
- function AdminSelect({ label, error, children, className = "", id, ...props }) {
43
- const generatedId = useId();
44
- const inputId = id || generatedId;
45
- const errorId = `${inputId}-error`;
46
- return /* @__PURE__ */ jsxs("div", { children: [
47
- label && /* @__PURE__ */ jsx("label", { htmlFor: inputId, className: "block text-sm font-medium text-tone-600 mb-1", children: label }),
48
- /* @__PURE__ */ jsx(
49
- "select",
50
- {
51
- id: inputId,
52
- "aria-invalid": error ? true : void 0,
53
- "aria-describedby": error ? errorId : void 0,
54
- className: `${baseInputClasses} ${error ? "border-red-400" : ""} ${className}`,
18
+ "aria-describedby": error && !bare ? errorId : void 0,
19
+ className: `${base} ${error ? "border-red-400" : ""} ${className}`,
55
20
  ...props,
56
21
  children
57
22
  }
58
- ),
59
- error && /* @__PURE__ */ jsx("p", { id: errorId, className: "text-red-500 text-xs mt-1", children: error })
60
- ] });
23
+ );
24
+ if (bare) return control;
25
+ return /* @__PURE__ */ jsxs("div", { children: [
26
+ label && /* @__PURE__ */ jsx("label", { htmlFor: inputId, className: "block text-sm font-medium text-tone-600 mb-1", children: label }),
27
+ control,
28
+ error && /* @__PURE__ */ jsx("p", { id: errorId, className: "text-red-500 text-xs mt-1", children: error })
29
+ ] });
30
+ });
31
+ Field.displayName = displayName;
32
+ return Field;
61
33
  }
34
+ const AdminInput = makeField("input", "", "AdminInput");
35
+ const AdminTextarea = makeField("textarea", "resize-none", "AdminTextarea");
36
+ const AdminSelect = makeField("select", "", "AdminSelect");
62
37
  export {
63
38
  AdminInput,
64
39
  AdminSelect,
@@ -3,9 +3,24 @@ import React, { useState, useEffect, useLayoutEffect, useRef } from "react";
3
3
  import { motion, AnimatePresence } from "framer-motion";
4
4
  import { ChevronRight, ChevronLeft, X, Trophy, Sparkles } from "lucide-react";
5
5
  import { Button } from "@okjt/ui";
6
- function AdminTutorial({ steps, onComplete, isRestarted = false }) {
6
+ function findTarget(step) {
7
+ if (!step || typeof document === "undefined") return null;
8
+ if (step.selector) return document.querySelector(step.selector);
9
+ return step.target ? document.getElementById(step.target) : null;
10
+ }
11
+ function onScreen(step) {
12
+ if (!step.selector && !step.target) return true;
13
+ const el = findTarget(step);
14
+ if (!el) return false;
15
+ const rect = el.getBoundingClientRect();
16
+ return rect.width > 0 && rect.height > 0 && rect.right > 0 && rect.left < window.innerWidth;
17
+ }
18
+ function AdminTutorial({ steps: allSteps, onComplete, isRestarted = false, open, skipMissing = false }) {
19
+ const controlled = open !== void 0;
20
+ const steps = skipMissing && allSteps ? allSteps.filter(onScreen) : allSteps;
7
21
  const [currentStep, setCurrentStep] = useState(0);
8
- const [isVisible, setIsVisible] = useState(false);
22
+ const [ownVisible, setIsVisible] = useState(false);
23
+ const isVisible = controlled ? !!open : ownVisible;
9
24
  const [coords, setCoords] = useState(null);
10
25
  const [boxHeight, setBoxHeight] = useState(360);
11
26
  const boxRef = useRef(null);
@@ -13,17 +28,21 @@ function AdminTutorial({ steps, onComplete, isRestarted = false }) {
13
28
  if (boxRef.current) setBoxHeight(boxRef.current.offsetHeight);
14
29
  }, [currentStep, isVisible, coords]);
15
30
  useEffect(() => {
31
+ if (controlled) return void 0;
16
32
  if (!steps?.length) return void 0;
17
33
  const isCompleted = localStorage.getItem("admin-tutorial-complete");
18
34
  if (!isCompleted || isRestarted) {
19
35
  const timer = setTimeout(() => setIsVisible(true), 1e3);
20
36
  return () => clearTimeout(timer);
21
37
  }
22
- }, [isRestarted, steps?.length]);
38
+ }, [controlled, isRestarted, steps?.length]);
39
+ useEffect(() => {
40
+ if (controlled && open) setCurrentStep(0);
41
+ }, [controlled, open]);
23
42
  useEffect(() => {
24
43
  if (isVisible) {
25
44
  const step2 = steps[currentStep];
26
- const el = document.getElementById(step2.target);
45
+ const el = findTarget(step2);
27
46
  if (el) {
28
47
  el.scrollIntoView({ behavior: "auto", block: "center" });
29
48
  }
@@ -39,7 +58,7 @@ function AdminTutorial({ steps, onComplete, isRestarted = false }) {
39
58
  }, [isVisible, currentStep]);
40
59
  const updateCoords = () => {
41
60
  const step2 = steps[currentStep];
42
- const el = document.getElementById(step2.target);
61
+ const el = findTarget(step2);
43
62
  if (el) {
44
63
  const rect = el.getBoundingClientRect();
45
64
  if (!isNaN(rect.top) && !isNaN(rect.left)) {
@@ -69,10 +88,24 @@ function AdminTutorial({ steps, onComplete, isRestarted = false }) {
69
88
  }
70
89
  };
71
90
  const handleComplete = () => {
72
- setIsVisible(false);
73
- localStorage.setItem("admin-tutorial-complete", "true");
91
+ if (!controlled) {
92
+ setIsVisible(false);
93
+ localStorage.setItem("admin-tutorial-complete", "true");
94
+ }
74
95
  if (onComplete) onComplete();
75
96
  };
97
+ const keys = useRef(null);
98
+ keys.current = { next: handleNext, back: handleBack, done: handleComplete };
99
+ useEffect(() => {
100
+ if (!isVisible) return void 0;
101
+ const onKey = (e) => {
102
+ if (e.key === "Escape") keys.current.done();
103
+ else if (e.key === "ArrowRight") keys.current.next();
104
+ else if (e.key === "ArrowLeft") keys.current.back();
105
+ };
106
+ document.addEventListener("keydown", onKey);
107
+ return () => document.removeEventListener("keydown", onKey);
108
+ }, [isVisible]);
76
109
  const getBoxStyle = () => {
77
110
  if (!coords) {
78
111
  return { style: { top: "50%", left: "50%", transform: "translate(-50%, -50%)" }, placement: null };
@@ -116,7 +149,7 @@ function AdminTutorial({ steps, onComplete, isRestarted = false }) {
116
149
  return { style: { top, left, width: boxW }, placement: placement2 };
117
150
  };
118
151
  if (!isVisible || !steps?.length) return null;
119
- const step = steps[currentStep];
152
+ const step = steps[Math.min(currentStep, steps.length - 1)];
120
153
  const { style: boxStyle, placement } = getBoxStyle();
121
154
  return /* @__PURE__ */ jsxs("div", { className: "fixed inset-0 z-[100] pointer-events-none", children: [
122
155
  /* @__PURE__ */ jsx(
@@ -137,6 +170,10 @@ function AdminTutorial({ steps, onComplete, isRestarted = false }) {
137
170
  {
138
171
  layout: true,
139
172
  ref: boxRef,
173
+ role: "dialog",
174
+ "aria-modal": "true",
175
+ "aria-labelledby": "okjt-tutorial-title",
176
+ "aria-describedby": "okjt-tutorial-body",
140
177
  initial: { opacity: 0, scale: 0.95 },
141
178
  animate: { opacity: 1, scale: 1 },
142
179
  style: boxStyle,
@@ -173,11 +210,11 @@ function AdminTutorial({ steps, onComplete, isRestarted = false }) {
173
210
  exit: { opacity: 0, y: -10 },
174
211
  className: "min-h-[100px]",
175
212
  children: [
176
- /* @__PURE__ */ jsxs("h3", { className: "text-xl font-semibold text-body mb-2 flex items-center gap-2", children: [
213
+ /* @__PURE__ */ jsxs("h3", { id: "okjt-tutorial-title", className: "text-xl font-semibold text-body mb-2 flex items-center gap-2", children: [
177
214
  step.title,
178
215
  currentStep === 0 && /* @__PURE__ */ jsx(Sparkles, { className: "w-4 h-4 text-accent" })
179
216
  ] }),
180
- /* @__PURE__ */ jsx("p", { className: "text-muted text-sm leading-relaxed", children: step.content })
217
+ /* @__PURE__ */ jsx("p", { id: "okjt-tutorial-body", className: "text-muted text-sm leading-relaxed", children: step.content })
181
218
  ]
182
219
  },
183
220
  currentStep
@@ -10,7 +10,7 @@ function AuthLayout({ title, subtitle, children, footer, brand, backLabel = "Bac
10
10
  initial: { opacity: 0, y: 16 },
11
11
  animate: { opacity: 1, y: 0 },
12
12
  transition: { duration: 0.45 },
13
- className: `w-full ${aside ? "max-w-6xl grid lg:grid-cols-2" : "max-w-xl grid"} gap-3 p-3 rounded-[2rem] bg-paper border border-white shadow-[0_30px_80px_-30px_color-mix(in_srgb,var(--color-body)_35%,transparent)]`,
13
+ className: `w-full ${aside ? "max-w-6xl grid lg:grid-cols-2" : "max-w-xl grid"} gap-3 p-3 rounded-[2rem] bg-paper border border-surface shadow-[0_30px_80px_-30px_color-mix(in_srgb,var(--okjt-shadow,var(--color-body))_35%,transparent)]`,
14
14
  children: [
15
15
  /* @__PURE__ */ jsxs("section", { className: "flex flex-col px-5 py-8 sm:px-10 lg:px-14 lg:py-12", children: [
16
16
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-4", children: [
@@ -32,7 +32,7 @@ function AuthLayout({ title, subtitle, children, footer, brand, backLabel = "Bac
32
32
  }
33
33
  ) });
34
34
  }
35
- const fieldClass = "w-full h-12 px-5 rounded-full bg-white border border-line text-sm text-ink placeholder:text-[var(--okjt-auth-placeholder,var(--color-faint))] shadow-[0_1px_2px_color-mix(in_srgb,var(--color-body)_4%,transparent)] outline-none transition focus:border-[var(--okjt-auth-focus,var(--color-accent))] focus:ring-4 focus:ring-[var(--okjt-auth-focus,var(--color-accent))]/15 read-only:bg-tint read-only:text-muted";
35
+ const fieldClass = "w-full h-12 px-5 rounded-full bg-surface border border-line text-sm text-ink placeholder:text-[var(--okjt-auth-placeholder,var(--color-faint))] shadow-[0_1px_2px_color-mix(in_srgb,var(--okjt-shadow,var(--color-body))_4%,transparent)] outline-none transition focus:border-[var(--okjt-auth-focus,var(--color-accent))] focus:ring-4 focus:ring-[var(--okjt-auth-focus,var(--color-accent))]/15 read-only:bg-tint read-only:text-muted";
36
36
  function AuthField({ id, label, type = "text", error, className = "", inputClassName = "", ...props }) {
37
37
  const [visible, setVisible] = useState(false);
38
38
  const isPassword = type === "password";
@@ -35,7 +35,7 @@ function CollaborationProvider({ children }) {
35
35
  const latest = useRef({ module, pathname });
36
36
  latest.current = { module, pathname };
37
37
  const beat = useCallback(async () => {
38
- if (document.visibilityState === "hidden") return;
38
+ if (!api || document.visibilityState === "hidden") return;
39
39
  try {
40
40
  const res = await api.post("/collaboration/heartbeat", { module: latest.current.module, path: latest.current.pathname });
41
41
  setState({ presence: res.data?.presence || [], badges: res.data?.badges || {} });
@@ -4,7 +4,7 @@ function GoogleButton({ href = "/api/auth/google", label = "Continue with Google
4
4
  "a",
5
5
  {
6
6
  href,
7
- className: "flex w-full items-center justify-center gap-3 rounded-full border border-tone-200 bg-white px-4 py-3 text-sm font-semibold text-ink shadow-sm transition-colors hover:bg-tone-50",
7
+ className: "flex w-full items-center justify-center gap-3 rounded-full border border-tone-200 bg-surface px-4 py-3 text-sm font-semibold text-ink shadow-sm transition-colors hover:bg-tone-50",
8
8
  children: [
9
9
  /* @__PURE__ */ jsxs("svg", { className: "h-5 w-5", viewBox: "0 0 24 24", "aria-hidden": "true", children: [
10
10
  /* @__PURE__ */ jsx("path", { fill: "#4285F4", d: "M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" }),
@@ -31,18 +31,21 @@ function NotificationIcon({ icon }) {
31
31
  const IconComp = ICON_MAP[icon] || BellRing;
32
32
  return /* @__PURE__ */ jsx(IconComp, { className: "w-4 h-4 text-accent" });
33
33
  }
34
- function NotificationsBell() {
34
+ function NotificationsBell({ listPath = "/notifications", markAllPath = "/notifications/mark-read", map }) {
35
35
  const navigate = useNavigate();
36
36
  const { api } = useDashboard();
37
37
  const [showNotifications, setShowNotifications] = useState(false);
38
38
  const [notifications, setNotifications] = useState([]);
39
39
  const [unreadCount, setUnreadCount] = useState(0);
40
- const fetchedRef = useRef(false);
41
- const fetchNotifications = async () => {
40
+ const latest = useRef({ listPath, map });
41
+ latest.current = { listPath, map };
42
+ const fetchNotifications = async (isCancelled = () => false) => {
42
43
  try {
43
- const res = await api.get("/notifications");
44
+ const res = await api.get(latest.current.listPath);
45
+ if (isCancelled()) return;
44
46
  const payload = res.data;
45
- const items = Array.isArray(payload) ? payload : Array.isArray(payload?.data) ? payload.data : [];
47
+ const raw = Array.isArray(payload) ? payload : Array.isArray(payload?.data) ? payload.data : [];
48
+ const items = latest.current.map ? raw.map(latest.current.map) : raw;
46
49
  setNotifications(items);
47
50
  setUnreadCount(items.filter((n) => !n.read_at).length);
48
51
  } catch (e) {
@@ -51,23 +54,8 @@ function NotificationsBell() {
51
54
  };
52
55
  useEffect(() => {
53
56
  let cancelled = false;
54
- const init = async () => {
55
- if (!fetchedRef.current) {
56
- fetchedRef.current = true;
57
- try {
58
- const res = await api.get("/notifications");
59
- if (cancelled) return;
60
- const payload = res.data;
61
- const items = Array.isArray(payload) ? payload : Array.isArray(payload?.data) ? payload.data : [];
62
- setNotifications(items);
63
- setUnreadCount(items.filter((n) => !n.read_at).length);
64
- } catch (e) {
65
- console.error("Failed to fetch notifications", e);
66
- }
67
- }
68
- };
69
- init();
70
- const interval = setInterval(fetchNotifications, 3e4);
57
+ fetchNotifications(() => cancelled);
58
+ const interval = setInterval(() => fetchNotifications(() => cancelled), 3e4);
71
59
  return () => {
72
60
  cancelled = true;
73
61
  clearInterval(interval);
@@ -75,7 +63,7 @@ function NotificationsBell() {
75
63
  }, []);
76
64
  const handleMarkAllRead = async () => {
77
65
  try {
78
- await api.post("/notifications/mark-read");
66
+ await api.post(markAllPath);
79
67
  fetchNotifications();
80
68
  } catch (e) {
81
69
  console.error("Failed to mark read", e);
@@ -195,7 +195,7 @@ function SignInPage({
195
195
  type: "button",
196
196
  onClick: handlePasskey,
197
197
  disabled: loading,
198
- className: "mb-3 flex w-full items-center justify-center gap-2 rounded-full border border-tone-200 bg-white px-4 py-3 text-sm font-semibold text-ink shadow-sm transition-colors hover:bg-tone-50 disabled:opacity-50",
198
+ className: "mb-3 flex w-full items-center justify-center gap-2 rounded-full border border-tone-200 bg-surface px-4 py-3 text-sm font-semibold text-ink shadow-sm transition-colors hover:bg-tone-50 disabled:opacity-50",
199
199
  children: [
200
200
  /* @__PURE__ */ jsx("svg", { className: "h-5 w-5", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: "1.8", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15.75 5.25a3 3 0 0 1 3 3m3 0a6 6 0 0 1-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1 1 21.75 8.25Z" }) }),
201
201
  "Sign in with a passkey"
@@ -1,8 +1,10 @@
1
1
  import { jsx, jsxs } from "react/jsx-runtime";
2
2
  import { AlertCircle } from "lucide-react";
3
3
  import { AdminHeaderStatus } from "./AdminChromeContext.js";
4
+ import { useHasUnsavedChanges } from "./useUnsavedChangesGuard.js";
4
5
  function UnsavedChangesStatus({ dirty }) {
5
- if (!dirty) return null;
6
+ const anyUnsaved = useHasUnsavedChanges();
7
+ if (!(dirty ?? anyUnsaved)) return null;
6
8
  return /* @__PURE__ */ jsx(AdminHeaderStatus, { children: /* @__PURE__ */ jsxs("span", { role: "status", className: "px-3 py-1.5 rounded-full text-xs font-semibold flex items-center gap-2 bg-amber-50 text-amber-800 whitespace-nowrap", children: [
7
9
  /* @__PURE__ */ jsx(AlertCircle, { className: "w-3.5 h-3.5" }),
8
10
  " Unsaved changes"
package/dist/index.js CHANGED
@@ -26,7 +26,15 @@ import { default as default20 } from "./UnsavedChangesStatus.js";
26
26
  import { default as default21 } from "./AdminTutorial.js";
27
27
  import { default as default22, useBulkAdminAction } from "./useAdminAction.js";
28
28
  import { default as default23 } from "./useCrudHandlers.js";
29
- import { default as default24, useUnsavedChanges } from "./useUnsavedChangesGuard.js";
29
+ import {
30
+ default as default24,
31
+ useUnsavedChanges,
32
+ useHasUnsavedChanges,
33
+ hasUnsavedChanges,
34
+ confirmLeave,
35
+ useGuardedNavigate,
36
+ allowNextNavigation
37
+ } from "./useUnsavedChangesGuard.js";
30
38
  import { default as default25 } from "./useFilteredItems.js";
31
39
  import { default as default26 } from "./useSavedViews.js";
32
40
  import { useModules, moduleForPathIn, initials, collaboratorColor } from "./modules.js";
@@ -111,9 +119,12 @@ export {
111
119
  default20 as UnsavedChangesStatus,
112
120
  default41 as VerifyEmailPage,
113
121
  default30 as VersionHistoryDrawer,
122
+ allowNextNavigation,
114
123
  collaboratorColor,
124
+ confirmLeave,
115
125
  countActiveFilterLists,
116
126
  countActiveFilters,
127
+ hasUnsavedChanges,
117
128
  initials,
118
129
  loginWithPasskey,
119
130
  moduleForPathIn,
@@ -130,6 +141,8 @@ export {
130
141
  default23 as useCrudHandlers,
131
142
  useDashboard,
132
143
  default25 as useFilteredItems,
144
+ useGuardedNavigate,
145
+ useHasUnsavedChanges,
133
146
  useModules,
134
147
  default26 as useSavedViews,
135
148
  useSearch,
@@ -1,8 +1,63 @@
1
- import { useEffect, useState } from "react";
1
+ import { useCallback, useEffect, useId, useState, useSyncExternalStore } from "react";
2
2
  import { useNavigate } from "react-router-dom";
3
3
  import { confirmAction } from "@okjt/ui";
4
- function useUnsavedChangesGuard(dirty, message = "You have unsaved changes. Leave without saving?") {
4
+ const DEFAULT_MESSAGE = "You have unsaved changes. Leave without saving?";
5
+ const dirtyForms = /* @__PURE__ */ new Map();
6
+ const listeners = /* @__PURE__ */ new Set();
7
+ const notify = () => listeners.forEach((listener) => listener());
8
+ function reportUnsaved(key, dirty, message) {
9
+ const had = dirtyForms.has(key);
10
+ if (dirty) dirtyForms.set(key, message);
11
+ else dirtyForms.delete(key);
12
+ if (had !== dirty) notify();
13
+ }
14
+ const subscribe = (listener) => {
15
+ listeners.add(listener);
16
+ return () => listeners.delete(listener);
17
+ };
18
+ function hasUnsavedChanges() {
19
+ return dirtyForms.size > 0;
20
+ }
21
+ function useHasUnsavedChanges() {
22
+ return useSyncExternalStore(subscribe, hasUnsavedChanges, () => false);
23
+ }
24
+ let bypassUntil = 0;
25
+ function allowNextNavigation(ms = 1e3) {
26
+ bypassUntil = Date.now() + ms;
27
+ }
28
+ function takeBypass() {
29
+ if (Date.now() <= bypassUntil) {
30
+ bypassUntil = 0;
31
+ return true;
32
+ }
33
+ return false;
34
+ }
35
+ let asking = null;
36
+ function confirmLeave(message) {
37
+ if (!hasUnsavedChanges() || takeBypass()) return Promise.resolve(true);
38
+ if (asking) return asking;
39
+ const text = message || [...dirtyForms.values()][0] || DEFAULT_MESSAGE;
40
+ asking = confirmAction({ title: "Leave without saving?", message: text, confirmLabel: "Leave", tone: "danger" }).then((leave) => {
41
+ if (leave) allowNextNavigation();
42
+ return !!leave;
43
+ }).finally(() => {
44
+ asking = null;
45
+ });
46
+ return asking;
47
+ }
48
+ function useGuardedNavigate() {
5
49
  const navigate = useNavigate();
50
+ return useCallback(async (to, options) => {
51
+ if (typeof to === "number" || await confirmLeave()) navigate(to, options);
52
+ }, [navigate]);
53
+ }
54
+ function useUnsavedChangesGuard(dirty, message = DEFAULT_MESSAGE) {
55
+ const navigate = useNavigate();
56
+ const key = useId();
57
+ useEffect(() => {
58
+ reportUnsaved(key, !!dirty, message);
59
+ return () => reportUnsaved(key, false);
60
+ }, [key, dirty, message]);
6
61
  useEffect(() => {
7
62
  if (!dirty) return void 0;
8
63
  const onBeforeUnload = (e) => {
@@ -15,9 +70,11 @@ function useUnsavedChangesGuard(dirty, message = "You have unsaved changes. Leav
15
70
  if (!link || link.target === "_blank" || link.hasAttribute("download")) return;
16
71
  const url = new URL(link.href, window.location.href);
17
72
  if (url.origin !== window.location.origin || url.pathname === window.location.pathname) return;
73
+ if (takeBypass()) return;
18
74
  e.preventDefault();
19
75
  e.stopPropagation();
20
- if (await confirmAction({ title: "Leave without saving?", message, confirmLabel: "Leave", tone: "danger" })) {
76
+ if (await confirmLeave(message)) {
77
+ takeBypass();
21
78
  navigate(url.pathname + url.search + url.hash);
22
79
  }
23
80
  };
@@ -36,6 +93,11 @@ function useUnsavedChanges(value) {
36
93
  return { dirty, markSaved: setBaseline, baseline };
37
94
  }
38
95
  export {
96
+ allowNextNavigation,
97
+ confirmLeave,
39
98
  useUnsavedChangesGuard as default,
99
+ hasUnsavedChanges,
100
+ useGuardedNavigate,
101
+ useHasUnsavedChanges,
40
102
  useUnsavedChanges
41
103
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@okjt/dashboard",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Dashboard pages for OKJTech projects: page layout, hero, summary cards, floating toolbar with search and filters, side panel, lists, bulk actions, one way to save, and working together: presence, version history, sharing; the dashboard shell, sign-in pages and account menu",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -23,7 +23,7 @@
23
23
  "test": "node build.mjs && vitest run"
24
24
  },
25
25
  "dependencies": {
26
- "@okjt/ui": "^0.2.1"
26
+ "@okjt/ui": "^0.4.0"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "@tanstack/react-query": ">=5",