@umituz/web-dashboard 8.8.1 → 8.10.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-dashboard",
3
- "version": "8.8.1",
3
+ "version": "8.10.0",
4
4
  "description": "Installable app skeleton for the fleet — layouts, analytics (dependency-free SVG charts), calendar, onboarding flow permissions/module registry; udb-* stylesheet on design-system tokens",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -47,6 +47,8 @@
47
47
  "./settings/utils": "./src/domains/settings/utils/index.ts",
48
48
  "./timing": "./src/domains/timing/index.ts",
49
49
  "./timing/hooks": "./src/domains/timing/hooks/index.ts",
50
+ "./tour": "./src/domains/tour/index.ts",
51
+ "./tour/tour.css": "./src/domains/tour/tour.css",
50
52
  "./search": "./src/domains/search/index.ts",
51
53
  "./search/utils": "./src/domains/search/searchItems.ts",
52
54
  "./styles.css": "./src/styles/dashboard.css"
@@ -76,6 +78,7 @@
76
78
  }
77
79
  },
78
80
  "dependencies": {
81
+ "driver.js": "^1.10.2",
79
82
  "lucide-react": "^0.577.0"
80
83
  },
81
84
  "devDependencies": {
@@ -15,6 +15,7 @@ import type {
15
15
  } from "../types/layout";
16
16
  import type { DashboardNotification } from "../types/notification";
17
17
  import type { DashboardUser } from "../types/user";
18
+ import { filterProfileItems } from "../utils/dashboard";
18
19
 
19
20
  interface DashboardHeaderPropsExtended extends DashboardHeaderProps {
20
21
  user?: DashboardUser;
@@ -63,7 +64,8 @@ export const DashboardHeader = ({
63
64
  const navigate = useNavigate();
64
65
 
65
66
  const unreadCount = notifications.filter((n) => !n.read).length;
66
- const customItems = profileItems ?? extraProfileItems;
67
+ const rawCustomItems = profileItems ?? extraProfileItems;
68
+ const customItems = filterProfileItems(rawCustomItems, user);
67
69
 
68
70
  const handleLogout = async () => {
69
71
  try {
@@ -41,6 +41,10 @@ export interface HeaderProfileItem {
41
41
  to?: string;
42
42
  onSelect?: () => void;
43
43
  danger?: boolean;
44
+ roles?: readonly string[];
45
+ permission?: string;
46
+ anyOf?: readonly string[];
47
+ permissions?: readonly string[];
44
48
  }
45
49
 
46
50
  export interface SidebarAction {
@@ -9,6 +9,10 @@ export interface SidebarItem {
9
9
  badge?: string | number;
10
10
  secondaryLabel?: string;
11
11
  end?: boolean;
12
+ roles?: readonly string[];
13
+ permission?: string;
14
+ anyOf?: readonly string[];
15
+ permissions?: readonly string[];
12
16
  }
13
17
 
14
18
  export interface SidebarGroup {
@@ -5,6 +5,9 @@ export interface DashboardUser {
5
5
  name?: string;
6
6
  email?: string;
7
7
  avatar?: string;
8
+ role?: string;
9
+ roles?: readonly string[];
10
+ permissions?: readonly string[];
8
11
  hasMobileApp?: boolean;
9
12
  hasWebApp?: boolean;
10
13
  }
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { getActiveSidebarItem, getPageTitle, isPathActive } from "./dashboard";
2
+ import { filterSidebarItems, getActiveSidebarItem, getPageTitle, isPathActive } from "./dashboard";
3
3
 
4
4
  describe("isPathActive", () => {
5
5
  it("matches exact paths regardless of end", () => {
@@ -63,3 +63,68 @@ describe("getPageTitle", () => {
63
63
  expect(getActiveSidebarItem("/nowhere", nested)).toBeNull();
64
64
  });
65
65
  });
66
+
67
+ describe("filterSidebarItems & filterProfileItems (Dynamic RBAC & Permission Control)", () => {
68
+ it("filters items based on generic SaaS role access", () => {
69
+ const items = [
70
+ { path: "/overview", label: "Overview" },
71
+ { path: "/editor-tools", label: "Editor Tools", roles: ["editor", "admin"] },
72
+ { path: "/admin", label: "Admin Panel", roles: ["admin"] },
73
+ ];
74
+
75
+ const viewerUser = { id: "1", role: "viewer" };
76
+ const viewerItems = filterSidebarItems(items, viewerUser);
77
+ expect(viewerItems.map((i) => i.path)).toEqual(["/overview"]);
78
+
79
+ const editorUser = { id: "2", role: "editor" };
80
+ const editorItems = filterSidebarItems(items, editorUser);
81
+ expect(editorItems.map((i) => i.path)).toEqual(["/overview", "/editor-tools"]);
82
+
83
+ const adminUser = { id: "3", role: "admin" };
84
+ const adminItems = filterSidebarItems(items, adminUser);
85
+ expect(adminItems.map((i) => i.path)).toEqual(["/overview", "/editor-tools", "/admin"]);
86
+ });
87
+
88
+ it("filters items based on dynamic permission matrix", () => {
89
+ const matrix = {
90
+ viewer: ["projects.read"],
91
+ editor: ["projects.read", "projects.write"],
92
+ admin: ["*"],
93
+ };
94
+
95
+ const items = [
96
+ { path: "/projects", label: "Projects", permission: "projects.read" },
97
+ { path: "/projects/new", label: "Create Project", permission: "projects.write" },
98
+ { path: "/billing", label: "Billing", permission: "billing.manage" },
99
+ ];
100
+
101
+ expect(filterSidebarItems(items, { role: "viewer", matrix }).map((i) => i.path)).toEqual([
102
+ "/projects",
103
+ ]);
104
+ expect(filterSidebarItems(items, { role: "editor", matrix }).map((i) => i.path)).toEqual([
105
+ "/projects",
106
+ "/projects/new",
107
+ ]);
108
+ expect(filterSidebarItems(items, { role: "admin", matrix }).map((i) => i.path)).toEqual([
109
+ "/projects",
110
+ "/projects/new",
111
+ "/billing",
112
+ ]);
113
+ });
114
+
115
+ it("filters items based on explicit permissions array", () => {
116
+ const items = [
117
+ { path: "/public", label: "Public" },
118
+ { path: "/billing", label: "Billing", permission: "billing.manage" },
119
+ ];
120
+
121
+ expect(filterSidebarItems(items, { permissions: [] }).map((i) => i.path)).toEqual(["/public"]);
122
+ expect(
123
+ filterSidebarItems(items, { permissions: ["billing.manage"] }).map((i) => i.path)
124
+ ).toEqual(["/public", "/billing"]);
125
+ expect(filterSidebarItems(items, { permissions: ["*"] }).map((i) => i.path)).toEqual([
126
+ "/public",
127
+ "/billing",
128
+ ]);
129
+ });
130
+ });
@@ -65,19 +65,88 @@ export function getPageTitle(
65
65
  return null;
66
66
  }
67
67
 
68
- export function filterSidebarItems<T extends { enabled?: boolean; requiredApp?: "mobile" | "web" }>(
68
+ import { hasAnyPermission, hasPermission } from "../../permissions/hasPermission";
69
+ import type { PermissionMatrix } from "../../permissions/types";
70
+
71
+ export interface AccessControllableItem {
72
+ enabled?: boolean;
73
+ requiredApp?: "mobile" | "web";
74
+ roles?: readonly string[];
75
+ permission?: string;
76
+ anyOf?: readonly string[];
77
+ permissions?: readonly string[];
78
+ }
79
+
80
+ export interface AccessControllableUser {
81
+ role?: string;
82
+ roles?: readonly string[];
83
+ permissions?: readonly string[];
84
+ matrix?: PermissionMatrix;
85
+ hasMobileApp?: boolean;
86
+ hasWebApp?: boolean;
87
+ }
88
+
89
+ export function isItemPermitted(
90
+ item: AccessControllableItem,
91
+ user?: AccessControllableUser
92
+ ): boolean {
93
+ if (item.enabled === false) return false;
94
+
95
+ if (item.requiredApp === "mobile" && !user?.hasMobileApp) return false;
96
+ if (item.requiredApp === "web" && !user?.hasWebApp) return false;
97
+
98
+ if (item.roles && item.roles.length > 0) {
99
+ const userRoles = [
100
+ ...(user?.role ? [user.role] : []),
101
+ ...(user?.roles ?? []),
102
+ ];
103
+ const hasRole = item.roles.some((r) => userRoles.includes(r));
104
+ if (!hasRole) return false;
105
+ }
106
+
107
+ if (item.permission) {
108
+ if (user?.matrix && user?.role) {
109
+ if (!hasPermission(user.matrix, user.role, item.permission)) {
110
+ return false;
111
+ }
112
+ } else {
113
+ const userPerms = user?.permissions ?? [];
114
+ if (!userPerms.includes("*") && !userPerms.includes(item.permission)) {
115
+ return false;
116
+ }
117
+ }
118
+ }
119
+
120
+ const anyOfList = item.anyOf ?? item.permissions;
121
+ if (anyOfList && anyOfList.length > 0) {
122
+ if (user?.matrix && user?.role) {
123
+ if (!hasAnyPermission(user.matrix, user.role, anyOfList)) {
124
+ return false;
125
+ }
126
+ } else {
127
+ const userPerms = user?.permissions ?? [];
128
+ if (!userPerms.includes("*")) {
129
+ const hasAny = anyOfList.some((p) => userPerms.includes(p));
130
+ if (!hasAny) return false;
131
+ }
132
+ }
133
+ }
134
+
135
+ return true;
136
+ }
137
+
138
+ export function filterSidebarItems<T extends AccessControllableItem>(
69
139
  items: T[],
70
- user?: { hasMobileApp?: boolean; hasWebApp?: boolean }
140
+ user?: AccessControllableUser
71
141
  ): T[] {
72
- return items.filter((item) => {
73
- if (item.enabled === false) return false;
74
-
75
- if (!item.requiredApp) return true;
76
- if (item.requiredApp === "mobile") return user?.hasMobileApp ?? false;
77
- if (item.requiredApp === "web") return user?.hasWebApp ?? false;
142
+ return items.filter((item) => isItemPermitted(item, user));
143
+ }
78
144
 
79
- return true;
80
- });
145
+ export function filterProfileItems<T extends AccessControllableItem>(
146
+ items: T[],
147
+ user?: AccessControllableUser
148
+ ): T[] {
149
+ return items.filter((item) => isItemPermitted(item, user));
81
150
  }
82
151
 
83
152
  export function generateNotificationId(): string {
@@ -0,0 +1,39 @@
1
+ import type { ReactNode } from "react";
2
+ import { ShieldAlert } from "lucide-react";
3
+ import { Button } from "@umituz/web-design-system/atoms";
4
+
5
+ export interface AccessDeniedProps {
6
+ title?: string;
7
+ description?: string;
8
+ actionLabel?: string;
9
+ onAction?: () => void;
10
+ icon?: ReactNode;
11
+ children?: ReactNode;
12
+ }
13
+
14
+ export const AccessDenied = ({
15
+ title = "Erişim Yetkisi Yok",
16
+ description = "Bu sayfayı görüntülemek veya bu işlemi gerçekleştirmek için gerekli izne sahip değilsiniz.",
17
+ actionLabel,
18
+ onAction,
19
+ icon,
20
+ children,
21
+ }: AccessDeniedProps) => {
22
+ return (
23
+ <div className="flex min-h-[320px] w-full flex-col items-center justify-center rounded-2xl border border-line bg-surface p-8 text-center shadow-xs">
24
+ <div className="mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-rose-500/10 text-rose-500">
25
+ {icon ?? <ShieldAlert className="h-7 w-7" aria-hidden="true" />}
26
+ </div>
27
+ <h2 className="mb-2 font-display text-xl font-bold tracking-tight text-ink">{title}</h2>
28
+ <p className="max-w-md text-sm text-ink-2 leading-relaxed">{description}</p>
29
+ {children && <div className="mt-4">{children}</div>}
30
+ {actionLabel && onAction && (
31
+ <div className="mt-6">
32
+ <Button variant="default" size="sm" onClick={onAction}>
33
+ {actionLabel}
34
+ </Button>
35
+ </div>
36
+ )}
37
+ </div>
38
+ );
39
+ };
@@ -4,7 +4,9 @@ import { MemoryRouter, Route, Routes } from "react-router";
4
4
  import {
5
5
  Can,
6
6
  PermissionsProvider,
7
+ ProtectedRoute,
7
8
  RequirePermission,
9
+ usePermission,
8
10
  usePermissions,
9
11
  } from "./PermissionsContext";
10
12
  import type { PermissionMatrix } from "./types";
@@ -142,3 +144,43 @@ describe("Can", () => {
142
144
  expect(screen.getByText("Orders")).not.toBeNull();
143
145
  });
144
146
  });
147
+
148
+ describe("usePermission", () => {
149
+ it("returns true when permission is granted and false otherwise", () => {
150
+ let allowed = false;
151
+ const Probe = () => {
152
+ allowed = usePermission("orders.edit");
153
+ return null;
154
+ };
155
+ mount("editor", <Probe />);
156
+ expect(allowed).toBe(true);
157
+
158
+ mount("viewer", <Probe />);
159
+ expect(allowed).toBe(false);
160
+ });
161
+ });
162
+
163
+ describe("ProtectedRoute", () => {
164
+ it("renders children when authorized", () => {
165
+ mount("editor", (
166
+ <MemoryRouter>
167
+ <ProtectedRoute permission="orders.edit">
168
+ <span>Protected Area</span>
169
+ </ProtectedRoute>
170
+ </MemoryRouter>
171
+ ));
172
+ expect(screen.getByText("Protected Area")).not.toBeNull();
173
+ });
174
+
175
+ it("renders fallback AccessDenied when unauthorized without redirect", () => {
176
+ mount("viewer", (
177
+ <MemoryRouter>
178
+ <ProtectedRoute permission="orders.edit">
179
+ <span>Protected Area</span>
180
+ </ProtectedRoute>
181
+ </MemoryRouter>
182
+ ));
183
+ expect(screen.queryByText("Protected Area")).toBeNull();
184
+ expect(screen.getByText("Erişim Yetkisi Yok")).not.toBeNull();
185
+ });
186
+ });
@@ -2,6 +2,7 @@ import { createContext, useCallback, useContext, useMemo, type ReactNode } from
2
2
  import { Navigate } from "react-router";
3
3
  import { hasAnyPermission, hasPermission } from "./hasPermission";
4
4
  import type { Permission, PermissionMatrix, RoleKey } from "./types";
5
+ import { AccessDenied } from "./AccessDenied";
5
6
 
6
7
  export interface PermissionsProviderProps {
7
8
  matrix: PermissionMatrix;
@@ -106,3 +107,47 @@ export const Can = ({
106
107
  const allowed = resolveAllowed(can, canAny, permission, anyOf);
107
108
  return allowed ? <>{children}</> : <>{fallback}</>;
108
109
  };
110
+
111
+ /**
112
+ * Convenience hook that checks whether the current user has a specific permission.
113
+ *
114
+ * Example:
115
+ * ```tsx
116
+ * const canCreateProject = usePermission("projects.create");
117
+ * ```
118
+ */
119
+ export const usePermission = (permission: Permission): boolean => {
120
+ const { can } = usePermissions();
121
+ return can(permission);
122
+ };
123
+
124
+ export interface ProtectedRouteProps {
125
+ permission?: Permission;
126
+ anyOf?: readonly Permission[];
127
+ children: ReactNode;
128
+ redirectTo?: string;
129
+ fallback?: ReactNode;
130
+ }
131
+
132
+ /**
133
+ * Route-level permission guard. If the user lacks the permission:
134
+ * - Renders `fallback` if provided
135
+ * - Redirects to `redirectTo` if provided
136
+ * - Otherwise displays the standard `<AccessDenied />` screen
137
+ */
138
+ export const ProtectedRoute = ({
139
+ permission,
140
+ anyOf,
141
+ children,
142
+ redirectTo,
143
+ fallback,
144
+ }: ProtectedRouteProps) => {
145
+ const { can, canAny } = usePermissions();
146
+ const allowed = resolveAllowed(can, canAny, permission, anyOf);
147
+ if (!allowed) {
148
+ if (fallback !== undefined) return <>{fallback}</>;
149
+ if (redirectTo !== undefined) return <Navigate to={redirectTo} replace />;
150
+ return <AccessDenied />;
151
+ }
152
+ return <>{children}</>;
153
+ };
@@ -22,7 +22,9 @@ const grantIncludes = (grant: RoleGrant, permission: Permission): boolean => {
22
22
  if (grant === PERMISSION_WILDCARD) return true;
23
23
  return grant.some(
24
24
  (entry) =>
25
- entry === permission || matchesModuleWildcard(entry, permission),
25
+ entry === PERMISSION_WILDCARD ||
26
+ entry === permission ||
27
+ matchesModuleWildcard(entry, permission),
26
28
  );
27
29
  };
28
30
 
@@ -1,12 +1,19 @@
1
1
  export {
2
2
  PermissionsProvider,
3
3
  usePermissions,
4
+ usePermission,
4
5
  RequirePermission,
6
+ ProtectedRoute,
5
7
  Can,
6
8
  type PermissionsProviderProps,
7
9
  type RequirePermissionProps,
10
+ type ProtectedRouteProps,
8
11
  type CanProps,
9
12
  } from "./PermissionsContext";
13
+ export {
14
+ AccessDenied,
15
+ type AccessDeniedProps,
16
+ } from "./AccessDenied";
10
17
  export {
11
18
  hasPermission,
12
19
  hasAnyPermission,
@@ -0,0 +1,3 @@
1
+ export * from "./types";
2
+ export * from "./tourEngine";
3
+ export * from "./useProductTour";
@@ -0,0 +1,187 @@
1
+ @import "driver.js/dist/driver.css";
2
+
3
+ /* ==========================================================================
4
+ Driver.js Popover Styling — Design System Token Integration
5
+ ========================================================================== */
6
+
7
+ .driver-popover {
8
+ background-color: var(--color-surface, #ffffff);
9
+ color: var(--color-ink, #0f172a);
10
+ border-radius: 1rem;
11
+ padding: 1.25rem;
12
+ box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04), 0 0 0 1px rgba(0, 0, 0, 0.08);
13
+ border: 1px solid var(--color-line, rgba(0, 0, 0, 0.08));
14
+ max-width: 380px;
15
+ min-width: 280px;
16
+ font-family: inherit;
17
+ z-index: 1000000000;
18
+ }
19
+
20
+ .dark .driver-popover {
21
+ background-color: var(--color-surface, #1e293b);
22
+ color: var(--color-ink, #f8fafc);
23
+ border-color: var(--color-line, rgba(255, 255, 255, 0.12));
24
+ box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 10px 10px -5px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(255, 255, 255, 0.1);
25
+ }
26
+
27
+ .driver-popover-title {
28
+ font-size: 1rem;
29
+ font-weight: 700;
30
+ line-height: 1.35;
31
+ color: var(--color-ink, #0f172a);
32
+ margin-bottom: 0.5rem;
33
+ display: flex;
34
+ align-items: center;
35
+ }
36
+
37
+ .dark .driver-popover-title {
38
+ color: var(--color-ink, #f8fafc);
39
+ }
40
+
41
+ .driver-popover-description {
42
+ font-size: 0.875rem;
43
+ line-height: 1.5;
44
+ color: var(--color-ink-2, #475569);
45
+ margin-bottom: 1.25rem;
46
+ }
47
+
48
+ .dark .driver-popover-description {
49
+ color: var(--color-ink-2, #94a3b8);
50
+ }
51
+
52
+ .driver-popover-close-btn {
53
+ top: 1rem;
54
+ right: 1rem;
55
+ color: var(--color-ink-3, #94a3b8);
56
+ font-size: 1.25rem;
57
+ width: 24px;
58
+ height: 24px;
59
+ display: flex;
60
+ align-items: center;
61
+ justify-content: center;
62
+ border-radius: 9999px;
63
+ transition: all 150ms ease;
64
+ }
65
+
66
+ .driver-popover-close-btn:hover {
67
+ color: var(--color-ink, #0f172a);
68
+ background-color: rgba(0, 0, 0, 0.05);
69
+ }
70
+
71
+ .dark .driver-popover-close-btn:hover {
72
+ color: #ffffff;
73
+ background-color: rgba(255, 255, 255, 0.1);
74
+ }
75
+
76
+ .driver-popover-footer {
77
+ display: flex;
78
+ align-items: center;
79
+ justify-content: space-between;
80
+ margin-top: 0.5rem;
81
+ padding-top: 0.75rem;
82
+ border-top: 1px solid var(--color-line, rgba(0, 0, 0, 0.06));
83
+ }
84
+
85
+ .dark .driver-popover-footer {
86
+ border-top-color: var(--color-line, rgba(255, 255, 255, 0.08));
87
+ }
88
+
89
+ .driver-popover-progress-text {
90
+ font-size: 0.75rem;
91
+ font-weight: 600;
92
+ color: var(--color-ink-3, #94a3b8);
93
+ }
94
+
95
+ .dark .driver-popover-progress-text {
96
+ color: var(--color-ink-3, #64748b);
97
+ }
98
+
99
+ .driver-popover-navigation-btns {
100
+ display: flex;
101
+ align-items: center;
102
+ gap: 0.5rem;
103
+ }
104
+
105
+ .driver-popover-footer-btn {
106
+ font-size: 0.8125rem;
107
+ font-weight: 600;
108
+ padding: 0.4rem 0.85rem;
109
+ border-radius: 9999px;
110
+ cursor: pointer;
111
+ transition: all 150ms cubic-bezier(0.4, 0, 0.2, 1);
112
+ border: 1px solid transparent;
113
+ }
114
+
115
+ .driver-popover-prev-btn {
116
+ background-color: transparent;
117
+ color: var(--color-ink-2, #475569);
118
+ border-color: var(--color-line, rgba(0, 0, 0, 0.12));
119
+ }
120
+
121
+ .driver-popover-prev-btn:hover {
122
+ background-color: rgba(0, 0, 0, 0.04);
123
+ color: var(--color-ink, #0f172a);
124
+ }
125
+
126
+ .dark .driver-popover-prev-btn {
127
+ color: var(--color-ink-2, #94a3b8);
128
+ border-color: var(--color-line, rgba(255, 255, 255, 0.15));
129
+ }
130
+
131
+ .dark .driver-popover-prev-btn:hover {
132
+ background-color: rgba(255, 255, 255, 0.06);
133
+ color: #ffffff;
134
+ }
135
+
136
+ .driver-popover-next-btn {
137
+ background-color: var(--color-primary, #3b7a5e);
138
+ color: #ffffff;
139
+ border: none;
140
+ box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
141
+ }
142
+
143
+ .driver-popover-next-btn:hover {
144
+ filter: brightness(1.08);
145
+ transform: translateY(-0.5px);
146
+ }
147
+
148
+ .dark .driver-popover-next-btn {
149
+ background-color: var(--color-primary, #448f6e);
150
+ color: #ffffff;
151
+ }
152
+
153
+ .driver-popover-arrow {
154
+ border-color: var(--color-surface, #ffffff);
155
+ }
156
+
157
+ .driver-popover-arrow-side-left {
158
+ border-left-color: var(--color-surface, #ffffff);
159
+ }
160
+
161
+ .driver-popover-arrow-side-right {
162
+ border-right-color: var(--color-surface, #ffffff);
163
+ }
164
+
165
+ .driver-popover-arrow-side-top {
166
+ border-top-color: var(--color-surface, #ffffff);
167
+ }
168
+
169
+ .driver-popover-arrow-side-bottom {
170
+ border-bottom-color: var(--color-surface, #ffffff);
171
+ }
172
+
173
+ .dark .driver-popover-arrow-side-left {
174
+ border-left-color: var(--color-surface, #1e293b);
175
+ }
176
+
177
+ .dark .driver-popover-arrow-side-right {
178
+ border-right-color: var(--color-surface, #1e293b);
179
+ }
180
+
181
+ .dark .driver-popover-arrow-side-top {
182
+ border-top-color: var(--color-surface, #1e293b);
183
+ }
184
+
185
+ .dark .driver-popover-arrow-side-bottom {
186
+ border-bottom-color: var(--color-surface, #1e293b);
187
+ }
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { isTourCompleted, markTourCompleted, resetTourCompletion } from "./tourEngine";
3
+
4
+ describe("Tour Engine & User Isolation", () => {
5
+ it("defaults to false and toggles completed state", () => {
6
+ const tourId = "onboarding_test_tour";
7
+ resetTourCompletion(tourId);
8
+ expect(isTourCompleted(tourId)).toBe(false);
9
+
10
+ markTourCompleted(tourId);
11
+ expect(isTourCompleted(tourId)).toBe(true);
12
+
13
+ resetTourCompletion(tourId);
14
+ expect(isTourCompleted(tourId)).toBe(false);
15
+ });
16
+
17
+ it("isolates tour completion per user", () => {
18
+ const tourId = "role_isolated_tour";
19
+ const userA = "user_student_123";
20
+ const userB = "user_teacher_456";
21
+
22
+ resetTourCompletion(tourId, userA);
23
+ resetTourCompletion(tourId, userB);
24
+
25
+ expect(isTourCompleted(tourId, userA)).toBe(false);
26
+ expect(isTourCompleted(tourId, userB)).toBe(false);
27
+
28
+ markTourCompleted(tourId, userA);
29
+ expect(isTourCompleted(tourId, userA)).toBe(true);
30
+ expect(isTourCompleted(tourId, userB)).toBe(false);
31
+
32
+ markTourCompleted(tourId, userB);
33
+ expect(isTourCompleted(tourId, userA)).toBe(true);
34
+ expect(isTourCompleted(tourId, userB)).toBe(true);
35
+
36
+ resetTourCompletion(tourId, userA);
37
+ expect(isTourCompleted(tourId, userA)).toBe(false);
38
+ expect(isTourCompleted(tourId, userB)).toBe(true);
39
+ });
40
+ });
@@ -0,0 +1,174 @@
1
+ import { driver } from "driver.js";
2
+ import type { Config as DriverConfig, Driver, DriveStep } from "driver.js";
3
+ import type { TourConfig, TourEngineInstance } from "./types";
4
+
5
+ const STORAGE_PREFIX = "umituz_tour_";
6
+ const memoryTourStore = new Map<string, string>();
7
+
8
+ function getStorageKey(tourId: string, userId?: string): string {
9
+ return userId ? `${STORAGE_PREFIX}${userId}_${tourId}` : `${STORAGE_PREFIX}${tourId}`;
10
+ }
11
+
12
+ /**
13
+ * Checks whether a given tour has been completed or dismissed by the user.
14
+ */
15
+ export function isTourCompleted(tourId: string, userId?: string): boolean {
16
+ const key = getStorageKey(tourId, userId);
17
+ if (typeof window === "undefined" || !window.localStorage) {
18
+ return memoryTourStore.get(key) === "completed";
19
+ }
20
+ try {
21
+ return window.localStorage.getItem(key) === "completed";
22
+ } catch {
23
+ return memoryTourStore.get(key) === "completed";
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Marks a tour as completed in localStorage (with in-memory fallback).
29
+ */
30
+ export function markTourCompleted(tourId: string, userId?: string): void {
31
+ const key = getStorageKey(tourId, userId);
32
+ memoryTourStore.set(key, "completed");
33
+ if (typeof window === "undefined" || !window.localStorage) return;
34
+ try {
35
+ window.localStorage.setItem(key, "completed");
36
+ } catch {
37
+ // ignore storage errors
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Resets the tour completion state so it can be re-run.
43
+ */
44
+ export function resetTourCompletion(tourId: string, userId?: string): void {
45
+ const key = getStorageKey(tourId, userId);
46
+ memoryTourStore.delete(key);
47
+ if (typeof window === "undefined" || !window.localStorage) return;
48
+ try {
49
+ window.localStorage.removeItem(key);
50
+ } catch {
51
+ // ignore storage errors
52
+ }
53
+ }
54
+
55
+ let activeDriverInstance: Driver | null = null;
56
+
57
+ /**
58
+ * Instantiates and returns a TourEngineInstance wrapping driver.js.
59
+ */
60
+ export function createProductTour(config: TourConfig): TourEngineInstance {
61
+ const {
62
+ tourId,
63
+ steps,
64
+ labels = {},
65
+ overlayOpacity = 0.65,
66
+ stagePadding = 8,
67
+ stageRadius = 12,
68
+ animate = true,
69
+ smoothScroll = true,
70
+ allowClose = true,
71
+ popoverClass,
72
+ onComplete,
73
+ onSkip,
74
+ onStepChange,
75
+ } = config;
76
+
77
+ const nextBtnDefault = labels.next ?? "İleri";
78
+ const prevBtnDefault = labels.prev ?? "Geri";
79
+ const doneBtnDefault = labels.done ?? "Tamamla";
80
+ const progressTextTemplate = labels.progress ?? "{{current}} / {{total}}";
81
+
82
+ let completedSuccessfully = false;
83
+
84
+ const driveSteps: DriveStep[] = steps.map((step, index) => {
85
+ const isLast = index === steps.length - 1;
86
+ const targetSelector = step.target && step.target !== "body" ? step.target : undefined;
87
+
88
+ const formattedTitle = step.badge
89
+ ? `<span style="display:inline-block;padding:2px 8px;font-size:11px;font-weight:700;border-radius:9999px;background-color:rgba(59,122,94,0.15);color:#3b7a5e;margin-right:6px;vertical-align:middle;">${step.badge}</span>${step.title}`
90
+ : step.title;
91
+
92
+ return {
93
+ element: targetSelector,
94
+ popover: {
95
+ title: formattedTitle,
96
+ description: step.description,
97
+ side: step.placement && step.placement !== "center" ? step.placement : undefined,
98
+ align: step.align ?? "center",
99
+ nextBtnText: isLast ? doneBtnDefault : nextBtnDefault,
100
+ prevBtnText: prevBtnDefault,
101
+ showProgress: true,
102
+ progressText: progressTextTemplate,
103
+ onNextClick: (_element, _step, opts) => {
104
+ if (isLast) {
105
+ completedSuccessfully = true;
106
+ markTourCompleted(tourId, config.userId);
107
+ opts.driver.destroy();
108
+ onComplete?.();
109
+ } else {
110
+ opts.driver.moveNext();
111
+ }
112
+ },
113
+ },
114
+ };
115
+ });
116
+
117
+ const driverConfig: DriverConfig = {
118
+ steps: driveSteps,
119
+ animate,
120
+ smoothScroll,
121
+ allowClose,
122
+ overlayOpacity,
123
+ stagePadding,
124
+ stageRadius,
125
+ popoverClass: popoverClass ? `driver-popover ${popoverClass}` : "driver-popover",
126
+ showProgress: true,
127
+ progressText: progressTextTemplate,
128
+ nextBtnText: nextBtnDefault,
129
+ prevBtnText: prevBtnDefault,
130
+ doneBtnText: doneBtnDefault,
131
+ onHighlightStarted: (_element, _step, opts) => {
132
+ const activeIdx = opts.state.activeIndex ?? 0;
133
+ const currentTourStep = steps[activeIdx];
134
+ if (currentTourStep) {
135
+ onStepChange?.(activeIdx, currentTourStep);
136
+ }
137
+ },
138
+ onDestroyed: () => {
139
+ activeDriverInstance = null;
140
+ if (!completedSuccessfully) {
141
+ markTourCompleted(tourId, config.userId);
142
+ onSkip?.();
143
+ }
144
+ },
145
+ };
146
+
147
+ const driverObj = driver(driverConfig);
148
+
149
+ return {
150
+ start: () => {
151
+ if (activeDriverInstance) {
152
+ try {
153
+ activeDriverInstance.destroy();
154
+ } catch {
155
+ // ignore
156
+ }
157
+ }
158
+ activeDriverInstance = driverObj;
159
+ completedSuccessfully = false;
160
+ driverObj.drive();
161
+ },
162
+ destroy: () => {
163
+ driverObj.destroy();
164
+ },
165
+ next: () => {
166
+ driverObj.moveNext();
167
+ },
168
+ previous: () => {
169
+ driverObj.movePrevious();
170
+ },
171
+ isActive: () => driverObj.isActive(),
172
+ getCurrentStepIndex: () => driverObj.getActiveIndex() ?? 0,
173
+ };
174
+ }
@@ -0,0 +1,102 @@
1
+ export type TourPlacement = "top" | "right" | "bottom" | "left" | "center";
2
+ export type TourAlign = "start" | "center" | "end";
3
+
4
+ export interface TourStep {
5
+ /**
6
+ * DOM selector to attach popover to (e.g. `[data-tour="search-bar"]` or `header`).
7
+ * When omitted or set to `'body'`, the step centers as a modal.
8
+ */
9
+ target?: string;
10
+ /**
11
+ * Step title displayed in bold in the popover header.
12
+ */
13
+ title: string;
14
+ /**
15
+ * Step description or HTML body.
16
+ */
17
+ description: string;
18
+ /**
19
+ * Optional placement side. Defaults to `'center'` if target is omitted, otherwise auto/bottom.
20
+ */
21
+ placement?: TourPlacement;
22
+ /**
23
+ * Alignment along the side (start, center, end).
24
+ */
25
+ align?: TourAlign;
26
+ /**
27
+ * Optional small badge text displayed before the title (e.g. "Yeni", "Adım 1").
28
+ */
29
+ badge?: string;
30
+ }
31
+
32
+ export interface TourLabels {
33
+ next?: string;
34
+ prev?: string;
35
+ done?: string;
36
+ skip?: string;
37
+ progress?: string; // e.g. "{{current}} / {{total}}"
38
+ }
39
+
40
+ export interface TourConfig {
41
+ tourId: string;
42
+ /**
43
+ * Optional user ID to isolate completion status per user on the same client.
44
+ */
45
+ userId?: string;
46
+ /**
47
+ * Optional external completion flag (e.g. from backend/database).
48
+ */
49
+ isCompleted?: boolean;
50
+ steps: TourStep[];
51
+ labels?: TourLabels;
52
+ overlayOpacity?: number;
53
+ stagePadding?: number;
54
+ stageRadius?: number;
55
+ animate?: boolean;
56
+ smoothScroll?: boolean;
57
+ allowClose?: boolean;
58
+ popoverClass?: string;
59
+ onComplete?: () => void;
60
+ onSkip?: () => void;
61
+ onStepChange?: (index: number, step: TourStep) => void;
62
+ }
63
+
64
+ export interface TourEngineInstance {
65
+ start: () => void;
66
+ destroy: () => void;
67
+ next: () => void;
68
+ previous: () => void;
69
+ isActive: () => boolean;
70
+ getCurrentStepIndex: () => number;
71
+ }
72
+
73
+ export interface UseProductTourOptions extends Omit<TourConfig, "onComplete" | "onSkip" | "onStepChange"> {
74
+ /**
75
+ * If true, starts the tour automatically on mount when not yet completed.
76
+ */
77
+ autoStart?: boolean;
78
+ /**
79
+ * Delay in milliseconds before auto-starting the tour (default: 600ms).
80
+ */
81
+ autoStartDelayMs?: number;
82
+ /**
83
+ * Optional callback when completed.
84
+ */
85
+ onComplete?: () => void;
86
+ /**
87
+ * Optional callback when skipped/closed.
88
+ */
89
+ onSkip?: () => void;
90
+ /**
91
+ * Optional callback when step changes.
92
+ */
93
+ onStepChange?: (index: number, step: TourStep) => void;
94
+ }
95
+
96
+ export interface UseProductTourReturn {
97
+ startTour: (options?: { force?: boolean }) => void;
98
+ restartTour: () => void;
99
+ destroyTour: () => void;
100
+ hasCompleted: boolean;
101
+ isTourActive: boolean;
102
+ }
@@ -0,0 +1,141 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import type { TourConfig, TourEngineInstance, UseProductTourOptions, UseProductTourReturn } from "./types";
3
+ import { createProductTour, isTourCompleted, resetTourCompletion } from "./tourEngine";
4
+
5
+ export function useProductTour(options: UseProductTourOptions): UseProductTourReturn {
6
+ const {
7
+ tourId,
8
+ userId,
9
+ isCompleted,
10
+ steps,
11
+ labels,
12
+ overlayOpacity,
13
+ stagePadding,
14
+ stageRadius,
15
+ animate,
16
+ smoothScroll,
17
+ allowClose,
18
+ autoStart = false,
19
+ autoStartDelayMs = 600,
20
+ onComplete,
21
+ onSkip,
22
+ onStepChange,
23
+ } = options;
24
+
25
+ const [hasCompleted, setHasCompleted] = useState<boolean>(() => {
26
+ return Boolean(isCompleted) || isTourCompleted(tourId, userId);
27
+ });
28
+ const [isTourActive, setIsTourActive] = useState<boolean>(false);
29
+ const engineRef = useRef<TourEngineInstance | null>(null);
30
+
31
+ useEffect(() => {
32
+ setHasCompleted(Boolean(isCompleted) || isTourCompleted(tourId, userId));
33
+ }, [isCompleted, tourId, userId]);
34
+
35
+ const onCompleteRef = useRef(onComplete);
36
+ onCompleteRef.current = onComplete;
37
+ const onSkipRef = useRef(onSkip);
38
+ onSkipRef.current = onSkip;
39
+ const onStepChangeRef = useRef(onStepChange);
40
+ onStepChangeRef.current = onStepChange;
41
+
42
+ const config: TourConfig = useMemo(
43
+ () => ({
44
+ tourId,
45
+ userId,
46
+ isCompleted,
47
+ steps,
48
+ labels,
49
+ overlayOpacity,
50
+ stagePadding,
51
+ stageRadius,
52
+ animate,
53
+ smoothScroll,
54
+ allowClose,
55
+ onComplete: () => {
56
+ setHasCompleted(true);
57
+ setIsTourActive(false);
58
+ onCompleteRef.current?.();
59
+ },
60
+ onSkip: () => {
61
+ setHasCompleted(true);
62
+ setIsTourActive(false);
63
+ onSkipRef.current?.();
64
+ },
65
+ onStepChange: (index, step) => {
66
+ onStepChangeRef.current?.(index, step);
67
+ },
68
+ }),
69
+ [
70
+ tourId,
71
+ userId,
72
+ isCompleted,
73
+ steps,
74
+ labels,
75
+ overlayOpacity,
76
+ stagePadding,
77
+ stageRadius,
78
+ animate,
79
+ smoothScroll,
80
+ allowClose,
81
+ ],
82
+ );
83
+
84
+ const startTour = useCallback(
85
+ (startOptions?: { force?: boolean }) => {
86
+ const force = startOptions?.force ?? false;
87
+ const alreadyDone = Boolean(isCompleted) || isTourCompleted(tourId, userId);
88
+ if (!force && alreadyDone) {
89
+ return;
90
+ }
91
+
92
+ if (engineRef.current?.isActive()) {
93
+ engineRef.current.destroy();
94
+ }
95
+
96
+ const instance = createProductTour(config);
97
+ engineRef.current = instance;
98
+ setIsTourActive(true);
99
+ instance.start();
100
+ },
101
+ [config, tourId, userId, isCompleted],
102
+ );
103
+
104
+ const restartTour = useCallback(() => {
105
+ resetTourCompletion(tourId, userId);
106
+ setHasCompleted(false);
107
+ startTour({ force: true });
108
+ }, [tourId, userId, startTour]);
109
+
110
+ const destroyTour = useCallback(() => {
111
+ if (engineRef.current) {
112
+ engineRef.current.destroy();
113
+ setIsTourActive(false);
114
+ }
115
+ }, []);
116
+
117
+ useEffect(() => {
118
+ if (!autoStart) return;
119
+ const alreadyDone = Boolean(isCompleted) || isTourCompleted(tourId, userId);
120
+ if (alreadyDone) return;
121
+
122
+ const timer = window.setTimeout(() => {
123
+ startTour();
124
+ }, autoStartDelayMs);
125
+
126
+ return () => {
127
+ window.clearTimeout(timer);
128
+ if (engineRef.current?.isActive()) {
129
+ engineRef.current.destroy();
130
+ }
131
+ };
132
+ }, [autoStart, autoStartDelayMs, tourId, userId, isCompleted, startTour]);
133
+
134
+ return {
135
+ startTour,
136
+ restartTour,
137
+ destroyTour,
138
+ hasCompleted,
139
+ isTourActive,
140
+ };
141
+ }
package/src/index.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  export * from './domains/layouts';
2
2
  export * from './domains/settings';
3
3
  export * from './domains/calendar';
4
+ export * from './domains/permissions';
5
+ export * from './domains/organization';
6
+ export * from './domains/tour';
4
7
  export {
5
8
  useAnalytics,
6
9
  MetricCard,