@okjt/dashboard 0.3.0 → 0.5.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.
@@ -1,5 +1,8 @@
1
1
  import { jsx, jsxs } from "react/jsx-runtime";
2
2
  import { motion } from "framer-motion";
3
+ import { Minus, TrendingDown, TrendingUp } from "lucide-react";
4
+ import DashboardIcon from "./DashboardIcon.js";
5
+ import { useComponentDefaults } from "./DashboardProvider.js";
3
6
  const gridColumns = {
4
7
  1: "md:grid-cols-1",
5
8
  2: "md:grid-cols-2",
@@ -8,7 +11,11 @@ const gridColumns = {
8
11
  5: "md:grid-cols-3 xl:grid-cols-5",
9
12
  6: "md:grid-cols-3 xl:grid-cols-6"
10
13
  };
11
- function AdminSummaryCards({ cards = [], columns = 4 }) {
14
+ function AdminSummaryCards(ownProps) {
15
+ const { variant = "plain", ...props } = useComponentDefaults("SummaryCards", ownProps);
16
+ return variant === "bold" ? /* @__PURE__ */ jsx(BoldSummaryCards, { ...props }) : /* @__PURE__ */ jsx(PlainSummaryCards, { ...props });
17
+ }
18
+ function PlainSummaryCards({ cards = [], columns = 4 }) {
12
19
  if (!cards.length) return null;
13
20
  const gridCols = gridColumns[columns] || gridColumns[4];
14
21
  const iconVisibility = columns >= 5 ? "flex xl:hidden 2xl:flex" : "flex";
@@ -46,6 +53,62 @@ function AdminSummaryCards({ cards = [], columns = 4 }) {
46
53
  );
47
54
  }) });
48
55
  }
56
+ const boldColumns = {
57
+ 1: "grid-cols-1",
58
+ 2: "grid-cols-2",
59
+ 3: "grid-cols-2 md:grid-cols-3",
60
+ 4: "grid-cols-2 xl:grid-cols-4",
61
+ 5: "grid-cols-2 md:grid-cols-3 xl:grid-cols-5",
62
+ 6: "grid-cols-2 md:grid-cols-3 xl:grid-cols-6"
63
+ };
64
+ function BoldSummaryCards({ cards = [], columns, stackOnPhones = false }) {
65
+ if (!cards.length) return null;
66
+ let cols = boldColumns[columns ?? Math.min(cards.length, 4)] || boldColumns[4];
67
+ const compact = (columns ?? cards.length) >= 5;
68
+ if (stackOnPhones) cols = cols.replace(/^grid-cols-2\b/, "grid-cols-1 sm:grid-cols-2");
69
+ return /* @__PURE__ */ jsx("div", { className: `grid gap-3 lg:gap-4 ${cols}`, children: cards.map((card) => /* @__PURE__ */ jsx(BoldStatCard, { compact, ...card }, card.label)) });
70
+ }
71
+ function BoldStatCard({ icon, label, value, trend, hint, onClick, active = false, compact = false }) {
72
+ const up = trend > 0;
73
+ const down = trend < 0;
74
+ const trendColor = up ? "text-emerald-300" : down ? "text-accent-dark" : "text-tone-500";
75
+ const Tag = onClick ? "button" : "div";
76
+ const interactive = onClick ? "w-full text-left transition hover:border-accent-dark/30 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent-strong/60" : "";
77
+ const pressed = active ? "border-accent-strong/50 ring-1 ring-accent-strong/40" : "";
78
+ return /* @__PURE__ */ jsx(
79
+ Tag,
80
+ {
81
+ type: onClick ? "button" : void 0,
82
+ onClick,
83
+ "aria-pressed": onClick ? active : void 0,
84
+ className: `block rounded-2xl border border-tone-100 bg-surface backdrop-blur-xl ${compact ? "p-4 2xl:p-5" : "p-5 sm:p-6"} ${interactive} ${pressed}`,
85
+ children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
86
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
87
+ /* @__PURE__ */ jsx("p", { className: "mb-2 text-sm text-tone-500", children: label }),
88
+ /* @__PURE__ */ jsx("p", { className: `truncate font-semibold tracking-tight text-ink ${compact ? "text-xl 2xl:text-2xl" : "text-2xl sm:text-3xl"}`, title: typeof value === "string" ? value : void 0, children: value }),
89
+ hint && /* @__PURE__ */ jsx("p", { className: "mt-1 truncate text-xs text-tone-400", title: hint, children: hint }),
90
+ trend !== void 0 && trend !== null && /* @__PURE__ */ jsxs("div", { className: "mt-3 flex items-center gap-1.5", children: [
91
+ /* @__PURE__ */ jsx(
92
+ DashboardIcon,
93
+ {
94
+ icon: up ? "trend-up" : down ? "trend-down" : "trend-flat",
95
+ fallback: up ? TrendingUp : down ? TrendingDown : Minus,
96
+ className: `${trendColor} text-[10px]`
97
+ }
98
+ ),
99
+ /* @__PURE__ */ jsxs("span", { className: `text-xs font-medium ${trendColor}`, children: [
100
+ Math.abs(trend),
101
+ "%"
102
+ ] }),
103
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-contrast/35", children: "vs. last month" })
104
+ ] })
105
+ ] }),
106
+ /* @__PURE__ */ jsx("div", { className: `h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-accent-soft/10 bg-action/30 ${compact ? "flex xl:hidden 2xl:flex" : "flex"}`, children: /* @__PURE__ */ jsx(DashboardIcon, { icon, className: "text-base text-accent-soft" }) })
107
+ ] })
108
+ }
109
+ );
110
+ }
49
111
  export {
112
+ BoldStatCard,
50
113
  AdminSummaryCards as default
51
114
  };
@@ -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
@@ -2,73 +2,116 @@ import { jsx } from "react/jsx-runtime";
2
2
  import { createContext, useContext, useState, useEffect } from "react";
3
3
  import { useQueryClient } from "@tanstack/react-query";
4
4
  const AuthContext = createContext(null);
5
- function AuthProvider({ api, extend, children }) {
5
+ function AuthProvider({ api, extend, mode = "token", initialUser, children }) {
6
+ const session = mode === "session";
6
7
  const queryClient = useQueryClient();
7
8
  const [user, setUser] = useState(null);
8
9
  const [loading, setLoading] = useState(true);
9
10
  const [isAuthenticated, setIsAuthenticated] = useState(false);
10
11
  const [signedOut, setSignedOut] = useState(false);
11
12
  useEffect(() => {
13
+ if (initialUser !== void 0) {
14
+ setUser(initialUser);
15
+ setIsAuthenticated(!!initialUser);
16
+ setLoading(false);
17
+ return;
18
+ }
12
19
  checkAuth();
13
20
  }, []);
21
+ const keepToken = (token) => {
22
+ if (!session && token) localStorage.setItem("auth_token", token);
23
+ };
24
+ const forgetToken = () => {
25
+ if (!session) localStorage.removeItem("auth_token");
26
+ };
14
27
  const checkAuth = async () => {
15
- const token = localStorage.getItem("auth_token");
16
- if (token) {
28
+ if (session || localStorage.getItem("auth_token")) {
17
29
  try {
18
30
  const response = await api.get("/user");
19
31
  setUser(response.data);
20
32
  setIsAuthenticated(true);
21
33
  } catch {
22
- localStorage.removeItem("auth_token");
34
+ forgetToken();
23
35
  setUser(null);
24
36
  setIsAuthenticated(false);
25
37
  }
26
38
  }
27
39
  setLoading(false);
28
40
  };
29
- const login = async (email, password) => {
30
- try {
31
- const response = await api.post("/login", { email, password });
32
- if (response.data.requires_verification) {
33
- return {
34
- success: false,
35
- requires_verification: true,
36
- email: response.data.email,
37
- message: response.data.message || "Please verify your email before signing in."
38
- };
39
- }
40
- if (response.data.requires_2fa) {
41
- return {
42
- success: true,
43
- requires_2fa: true,
44
- email: response.data.email
45
- };
46
- }
47
- const { token, user: user2, ...extra } = response.data;
48
- localStorage.setItem("auth_token", token);
49
- setUser({ ...user2, ...extra });
50
- setIsAuthenticated(true);
51
- return { success: true, ...extra };
52
- } catch (error) {
41
+ const answer = (response) => {
42
+ const data = response.data ?? {};
43
+ if (data.requires_verification) {
53
44
  return {
54
45
  success: false,
55
- message: error.response?.data?.message || "Login failed"
46
+ requires_verification: true,
47
+ email: data.email,
48
+ message: data.message || response.message || "Please verify your email before signing in."
56
49
  };
57
50
  }
51
+ if (data.requires_2fa) {
52
+ return { success: true, requires_2fa: true, email: data.email, challenge: data.challenge };
53
+ }
54
+ return signedIn(data);
58
55
  };
59
- const verify2fa = async (email, code) => {
56
+ const failure = (error, fallback) => ({
57
+ success: false,
58
+ message: error.response?.data?.message || fallback,
59
+ errors: error.response?.data?.errors || {}
60
+ });
61
+ const login = async (email, password, options = {}) => {
60
62
  try {
61
- const response = await api.post("/verify-2fa", { email, code });
62
- const { token, user: user2, ...extra } = response.data;
63
- localStorage.setItem("auth_token", token);
64
- setUser({ ...user2, ...extra });
65
- setIsAuthenticated(true);
66
- return { success: true, ...extra };
63
+ const response = await api.post("/login", { email, password, ...options.remember ? { remember: true } : {} });
64
+ return answer(response);
67
65
  } catch (error) {
68
- return {
69
- success: false,
70
- message: error.response?.data?.message || "Invalid 2FA code"
71
- };
66
+ return failure(error, "Login failed");
67
+ }
68
+ };
69
+ const verify2fa = async (challenge, code) => {
70
+ try {
71
+ const response = await api.post("/verify-2fa", { challenge, code });
72
+ return answer(response);
73
+ } catch (error) {
74
+ return failure(error, "Invalid 2FA code");
75
+ }
76
+ };
77
+ const requestLoginCode = async (email) => {
78
+ try {
79
+ const response = await api.post("/login-code", { email });
80
+ return { success: true, message: response.message ?? response.data?.message };
81
+ } catch (error) {
82
+ return failure(error, "Could not send a code \u2014 try again.");
83
+ }
84
+ };
85
+ const verifyLoginCode = async (email, code) => {
86
+ try {
87
+ const response = await api.post("/login-code/verify", { email, code });
88
+ return answer(response);
89
+ } catch (error) {
90
+ return failure(error, "That sign-in code is invalid or expired.");
91
+ }
92
+ };
93
+ const forgotPassword = async (email) => {
94
+ try {
95
+ const response = await api.post("/forgot-password", { email });
96
+ return { success: true, message: response.message ?? response.data?.message };
97
+ } catch (error) {
98
+ return failure(error, "Could not send the link \u2014 try again.");
99
+ }
100
+ };
101
+ const resetPassword = async (data) => {
102
+ try {
103
+ const response = await api.post("/reset-password", data);
104
+ return { success: true, message: response.message ?? response.data?.message };
105
+ } catch (error) {
106
+ return failure(error, "Could not reset the password \u2014 try again.");
107
+ }
108
+ };
109
+ const confirmPassword = async (password) => {
110
+ try {
111
+ await api.post("/confirm-password", { password });
112
+ return { success: true };
113
+ } catch (error) {
114
+ return failure(error, "That password is incorrect.");
72
115
  }
73
116
  };
74
117
  const register = async (data) => {
@@ -83,10 +126,7 @@ function AuthProvider({ api, extend, children }) {
83
126
  message: payload.message
84
127
  };
85
128
  }
86
- const { token, user: user2, ...extra } = payload;
87
- localStorage.setItem("auth_token", token);
88
- setUser({ ...user2, ...extra });
89
- setIsAuthenticated(true);
129
+ signedIn(payload);
90
130
  return { success: true };
91
131
  } catch (error) {
92
132
  return {
@@ -108,8 +148,8 @@ function AuthProvider({ api, extend, children }) {
108
148
  try {
109
149
  const response = await api.post("/email/verify", { id, hash, expires, signature });
110
150
  const { token, user: user2, message: _message, email_verified: _verified, ...extra } = response.data;
111
- if (token) {
112
- localStorage.setItem("auth_token", token);
151
+ if (token || session && user2) {
152
+ keepToken(token);
113
153
  setUser({ ...user2, ...extra });
114
154
  setIsAuthenticated(true);
115
155
  } else {
@@ -123,14 +163,7 @@ function AuthProvider({ api, extend, children }) {
123
163
  const loginWithGoogle = async (code) => {
124
164
  try {
125
165
  const response = await api.post("/auth/google", { code });
126
- if (response.data.requires_2fa) {
127
- return { success: true, requires_2fa: true, email: response.data.email };
128
- }
129
- const { token, user: user2, ...extra } = response.data;
130
- localStorage.setItem("auth_token", token);
131
- setUser({ ...user2, ...extra });
132
- setIsAuthenticated(true);
133
- return { success: true, ...extra };
166
+ return answer(response);
134
167
  } catch (error) {
135
168
  return {
136
169
  success: false,
@@ -139,7 +172,7 @@ function AuthProvider({ api, extend, children }) {
139
172
  }
140
173
  };
141
174
  const loginWithToken = (token, authUser, extra = {}) => {
142
- localStorage.setItem("auth_token", token);
175
+ keepToken(token);
143
176
  setUser({ ...authUser, ...extra });
144
177
  setIsAuthenticated(true);
145
178
  };
@@ -153,7 +186,7 @@ function AuthProvider({ api, extend, children }) {
153
186
  } catch (error) {
154
187
  console.error("Logout error:", error);
155
188
  } finally {
156
- localStorage.removeItem("auth_token");
189
+ forgetToken();
157
190
  queryClient.clear();
158
191
  setUser(null);
159
192
  setIsAuthenticated(false);
@@ -168,6 +201,12 @@ function AuthProvider({ api, extend, children }) {
168
201
  login,
169
202
  register,
170
203
  verify2fa,
204
+ requestLoginCode,
205
+ verifyLoginCode,
206
+ forgotPassword,
207
+ resetPassword,
208
+ confirmPassword,
209
+ mode,
171
210
  loginWithToken,
172
211
  signedIn,
173
212
  loginWithGoogle,
@@ -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";