-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathSidebar.tsx
More file actions
486 lines (448 loc) · 15.2 KB
/
Copy pathSidebar.tsx
File metadata and controls
486 lines (448 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import { Sidebar as KumoSidebar, useSidebar } from "@cloudflare/kumo";
import { useLingui } from "@lingui/react/macro";
import { Gear, Palette, Storefront, Users } from "@phosphor-icons/react";
import { useQuery } from "@tanstack/react-query";
import { Link, useLocation } from "@tanstack/react-router";
import * as React from "react";
import { fetchCommentCounts } from "../lib/api/comments";
import { useCurrentUser } from "../lib/api/current-user";
import { resolvePluginPagePath, usePluginAdmins } from "../lib/plugin-context";
import {
resolveTaxonomyDefinitions,
type LocalizedTaxonomyDefinition,
} from "../lib/taxonomy-definitions.js";
import {
ADMIN_NAV_ICONS,
getCollectionNavIcon,
getTaxonomyNavIcon,
resolveNavIcon,
toPhosphorIconName,
} from "./admin-navigation-icons.js";
import { BrandIcon } from "./Logo.js";
// Re-export for Shell.tsx and Header.tsx
export { KumoSidebar as Sidebar, useSidebar };
export { resolveNavIcon, toPhosphorIconName };
// Role levels (matching @emdash-cms/auth)
const ROLE_ADMIN = 50;
const ROLE_EDITOR = 40;
/**
* Static invariants for nav entries that have AC-level visibility
* requirements (Phase 5 of Discussion #1174: "Admin sees the 'Byline
* Schema' entry; Editor does not").
*
* Exported as plain data so a unit test can assert the route + role
* pairing without mounting Kumo's Sidebar primitive — which portals
* its rendered content to `document.body` and applies collapse-state
* CSS (`display:none` on labels at narrow viewports), making
* full-DOM tests of role filtering brittle. The runtime `adminItems`
* array below references these constants directly so the test
* effectively guards the production list.
*/
export const BYLINE_SCHEMA_NAV_ITEM = {
to: "/byline-schema" as const,
minRole: ROLE_ADMIN,
icon: ADMIN_NAV_ICONS.bylineSchema,
} as const;
/**
* Filter a nav-items list by user role. Pure function — exported so
* tests can verify the role gate without rendering the sidebar. An
* item passes when it has no `minRole` (public) or the user is at
* least the required level.
*/
export function filterNavItemsByRole<T extends { minRole?: number }>(
items: T[],
userRole: number,
): T[] {
return items.filter((item) => !item.minRole || userRole >= item.minRole);
}
/**
* Manifest collections that get an auto-generated sidebar entry, in manifest
* order. Pure function — exported so tests can pin the `hidden` contract
* without rendering the sidebar.
*
* A hidden collection is still shipped in the manifest and stays fully
* routable at `/content/:collection`; it only loses its nav link, so a plugin
* that owns the collection end to end can steer editors to its own admin UI.
*/
export function visibleCollectionEntries<T extends { hidden?: boolean }>(
collections: Record<string, T>,
): Array<[string, T]> {
return Object.entries(collections).filter(([, config]) => !config.hidden);
}
export interface SidebarNavProps {
manifest: {
collections: Record<string, { label: string; hidden?: boolean }>;
plugins: Record<
string,
{
package?: string;
enabled?: boolean;
adminMode?: "react" | "blocks" | "none";
adminPages?: Array<{
path: string;
label?: string;
icon?: string;
}>;
dashboardWidgets?: Array<{ id: string; title?: string }>;
version?: string;
}
>;
taxonomies: Array<{
id?: string;
name: string;
label: string;
locale?: string;
translationGroup?: string | null;
}>;
i18n?: { defaultLocale: string; locales: string[] };
version?: string;
commit?: string;
marketplace?: string;
registry?: {
aggregatorUrl: string;
};
admin?: {
logo?: string;
siteName?: string;
favicon?: string;
};
};
}
/** Locale-normalized taxonomy rows used by the global Manage navigation. */
export function getSidebarTaxonomies<T extends LocalizedTaxonomyDefinition>(
taxonomies: readonly T[],
activeLocale?: string,
defaultLocale?: string,
): T[] {
return resolveTaxonomyDefinitions(taxonomies, activeLocale, defaultLocale);
}
interface NavItem {
to: string;
label: string;
icon: React.ElementType;
params?: Record<string, string>;
search?: Record<string, string>;
/** Minimum role level required to see this item */
minRole?: number;
/** Optional badge count (e.g., pending comments) */
badge?: number;
}
/**
* Navigation item rendered with Kumo's native Sidebar.MenuButton. Kumo's
* LinkProvider maps the href to TanStack Router for client-side navigation.
*/
function NavMenuLink({ item, isActive }: { item: NavItem; isActive: boolean }) {
const { state } = useSidebar();
const Icon = item.icon;
function IconComponent({ className }: { className?: string }) {
return <NavIcon icon={Icon} className={className} isActive={isActive} />;
}
return (
<KumoSidebar.MenuButton
href={resolveItemPath(item)}
active={isActive}
tooltip={state === "collapsed" ? item.label : undefined}
icon={IconComponent}
>
{item.label}
{item.badge != null && item.badge > 0 && (
<KumoSidebar.MenuBadge>{item.badge}</KumoSidebar.MenuBadge>
)}
</KumoSidebar.MenuButton>
);
}
export function NavIcon({
icon: Icon,
className,
isActive,
}: {
icon: React.ElementType;
className?: string;
isActive: boolean;
}) {
const weight = isActive ? "fill" : "regular";
return (
<React.Suspense
fallback={
<ADMIN_NAV_ICONS.plugins className={className} weight={weight} aria-hidden="true" />
}
>
<Icon className={className} weight={weight} aria-hidden="true" />
</React.Suspense>
);
}
/**
* Resolve the display label for a plugin admin page (sidebar + command
* palette). Declared labels are run through the shared Lingui instance:
* plugins that load their own catalog — with the English label as msgid —
* get localized nav items. The catalog is shared with the admin, so common
* labels like "Settings" pick up the admin's own translations even without
* a plugin catalog (deliberate: a localized admin shouldn't show stray
* English nav items). Labels with no catalog entry anywhere fall back to
* the literal string. Pages without a label prettify the plugin id
* ("my-shop" → "My Shop").
*/
export function resolvePluginPageLabel(
label: string | undefined,
pluginId: string,
translate: (id: string) => string,
): string {
if (label) return translate(label);
return pluginId
.split("-")
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" ");
}
/** Resolves a nav item's route path by substituting $param placeholders. */
export function resolveItemPath(item: NavItem): string {
let path = item.to;
if (item.params) {
for (const [key, value] of Object.entries(item.params)) {
path = path.replace(`$${key}`, value);
}
}
if (item.search && Object.keys(item.search).length > 0) {
path += `?${new URLSearchParams(item.search).toString()}`;
}
return path;
}
const TRAILING_SLASHES = /\/+$/;
/**
* Drop trailing slashes so a target and the router's path compare equal.
* "/" keeps its meaning: it is the admin root, not an empty path.
*/
function stripTrailingSlash(value: string): string {
return value.length > 1 ? value.replace(TRAILING_SLASHES, "") : value;
}
/**
* Checks if a nav item is active based on the current router path.
*
* Both sides are normalized because a plugin page declared with `path: "/"`
* makes the target `/plugins/<id>/`, while the router navigates to the same
* URL without the trailing slash — an exact compare would never match.
*/
export function isItemActive(itemPath: string, currentPath: string): boolean {
const queryIndex = itemPath.indexOf("?");
const raw = queryIndex === -1 ? itemPath : itemPath.slice(0, queryIndex);
const path = stripTrailingSlash(raw);
const current = stripTrailingSlash(currentPath);
return path === "/"
? current === "/"
: current === path || current.startsWith(`${path}/`);
}
/**
* Admin sidebar navigation using kumo's Sidebar compound component.
*/
export function SidebarNav({ manifest }: SidebarNavProps) {
const { t, i18n } = useLingui();
const location = useLocation();
const currentPath = location.pathname;
const routeLocale =
new URL(location.href, "http://emdash.local").searchParams.get("locale") ?? undefined;
const pluginAdmins = usePluginAdmins();
const { data: user } = useCurrentUser();
const userRole = user?.role ?? 0;
// Fetch pending comment count for badge
const { data: commentCounts } = useQuery({
queryKey: ["commentCounts"],
queryFn: fetchCommentCounts,
staleTime: 60 * 1000,
retry: false,
enabled: userRole >= ROLE_EDITOR,
});
// --- Build nav item groups ---
const contentItems: NavItem[] = [
{ to: "/", label: t`Dashboard`, icon: ADMIN_NAV_ICONS.dashboard },
];
for (const [name, config] of visibleCollectionEntries(manifest.collections)) {
contentItems.push({
to: "/content/$collection",
label: config.label,
icon: getCollectionNavIcon(name),
params: { collection: name },
});
}
contentItems.push({ to: "/media", label: t`Media`, icon: ADMIN_NAV_ICONS.media });
const manageItems: NavItem[] = [
{
to: "/comments",
label: t`Comments`,
icon: ADMIN_NAV_ICONS.comments,
minRole: ROLE_EDITOR,
badge: commentCounts?.pending,
},
{ to: "/menus", label: t`Menus`, icon: ADMIN_NAV_ICONS.menus, minRole: ROLE_EDITOR },
{
to: "/redirects",
label: t`Redirects`,
icon: ADMIN_NAV_ICONS.redirects,
minRole: ROLE_ADMIN,
},
{ to: "/widgets", label: t`Widgets`, icon: ADMIN_NAV_ICONS.widgets, minRole: ROLE_EDITOR },
{ to: "/sections", label: t`Sections`, icon: ADMIN_NAV_ICONS.sections, minRole: ROLE_EDITOR },
...getSidebarTaxonomies(manifest.taxonomies, routeLocale, manifest.i18n?.defaultLocale).map(
(tax) => ({
to: "/taxonomies/$taxonomy" as const,
label: tax.label,
icon: getTaxonomyNavIcon(tax.name),
params: { taxonomy: tax.name },
search: routeLocale ? { locale: routeLocale } : undefined,
minRole: ROLE_EDITOR,
}),
),
{ to: "/bylines", label: t`Bylines`, icon: ADMIN_NAV_ICONS.bylines, minRole: ROLE_EDITOR },
];
const adminItems: NavItem[] = [
{
to: "/content-types",
label: t`Content Types`,
icon: ADMIN_NAV_ICONS.contentTypes,
minRole: ROLE_ADMIN,
},
{ ...BYLINE_SCHEMA_NAV_ITEM, label: t`Byline Schema` },
{ to: "/users", label: t`Users`, icon: Users, minRole: ROLE_ADMIN },
{
to: "/plugins-manager",
label: t`Plugins`,
icon: ADMIN_NAV_ICONS.plugins,
minRole: ROLE_ADMIN,
},
];
if (manifest.registry) {
adminItems.push({
to: "/plugins/marketplace",
label: t`Registry`,
icon: Storefront,
minRole: ROLE_ADMIN,
});
} else if (manifest.marketplace) {
adminItems.push({
to: "/plugins/marketplace",
label: t`Marketplace`,
icon: Storefront,
minRole: ROLE_ADMIN,
});
}
if (manifest.marketplace) {
adminItems.push({
to: "/themes/marketplace",
label: t`Themes`,
icon: Palette,
minRole: ROLE_ADMIN,
});
}
adminItems.push(
{
to: "/import/wordpress",
label: t`Import`,
icon: ADMIN_NAV_ICONS.import,
minRole: ROLE_ADMIN,
},
{ to: "/settings", label: t`Settings`, icon: Gear, minRole: ROLE_ADMIN },
);
const pluginItems: NavItem[] = [];
for (const [pluginId, config] of Object.entries(manifest.plugins)) {
if (config.enabled === false) continue;
if (config.adminPages && config.adminPages.length > 0) {
const pluginPages = pluginAdmins[pluginId]?.pages;
const isBlocksMode = config.adminMode === "blocks";
for (const page of config.adminPages) {
if (!isBlocksMode && !resolvePluginPagePath(pluginPages, page.path)) continue;
const label = resolvePluginPageLabel(page.label, pluginId, (id) => i18n._(id));
pluginItems.push({
to: `/plugins/${pluginId}${page.path}`,
label,
icon: resolveNavIcon(page.icon),
});
}
}
}
const visibleContent = filterNavItemsByRole(contentItems, userRole);
const visibleManage = filterNavItemsByRole(manageItems, userRole);
const visibleAdmin = filterNavItemsByRole(adminItems, userRole);
const visiblePlugins = filterNavItemsByRole(pluginItems, userRole);
function renderNavItems(items: NavItem[]) {
return items.map((item, index) => {
const itemPath = resolveItemPath(item);
const active = isItemActive(itemPath, currentPath);
return <NavMenuLink key={`${item.to}-${index}`} item={item} isActive={active} />;
});
}
return (
<KumoSidebar className="emdash-sidebar" aria-label={t`Admin navigation`}>
<KumoSidebar.Header className="px-[11px] transition-[padding] duration-(--sidebar-animation-duration) motion-reduce:transition-none group-not-data-[state=collapsed]/sidebar:px-3.5">
<Link
to="/"
className="flex w-[calc(var(--sidebar-width)-1.75rem)] shrink-0 items-center gap-2 overflow-hidden py-1 ps-2.5 group-data-[state=collapsed]/sidebar:-translate-x-[3px] rtl:group-data-[state=collapsed]/sidebar:translate-x-[3px]"
>
<BrandIcon
logoUrl={manifest.admin?.logo}
siteName={manifest.admin?.siteName}
className="size-5 shrink-0"
aria-hidden="true"
/>
<span className="grid min-w-0 flex-1 grid-cols-[1fr] transition-[grid-template-columns] duration-(--sidebar-animation-duration) ease-(--sidebar-easing) motion-reduce:transition-none group-data-[state=collapsed]/sidebar:grid-cols-[0fr]">
<span className="min-w-0 overflow-hidden">
<span className="block w-[calc(var(--sidebar-width)-4.5rem)] truncate font-semibold">
{manifest.admin?.siteName || "EmDash"}
</span>
</span>
</span>
</Link>
</KumoSidebar.Header>
<KumoSidebar.Content>
{/* Dashboard — standalone */}
<KumoSidebar.Group className="mt-2 md:mt-1.5">
<KumoSidebar.Menu>
<NavMenuLink
item={{ to: "/", label: t`Dashboard`, icon: ADMIN_NAV_ICONS.dashboard }}
isActive={isItemActive("/", currentPath)}
/>
</KumoSidebar.Menu>
</KumoSidebar.Group>
{/* Content — collections + media */}
{visibleContent.length > 1 && (
<KumoSidebar.Group>
<KumoSidebar.GroupLabel>{t`Content`}</KumoSidebar.GroupLabel>
<KumoSidebar.Menu>
{renderNavItems(visibleContent.filter((i) => i.to !== "/"))}
</KumoSidebar.Menu>
</KumoSidebar.Group>
)}
{/* Manage — comments, menus, taxonomies, etc. */}
{visibleManage.length > 0 && (
<KumoSidebar.Group>
<KumoSidebar.GroupLabel>{t`Manage`}</KumoSidebar.GroupLabel>
<KumoSidebar.Menu>{renderNavItems(visibleManage)}</KumoSidebar.Menu>
</KumoSidebar.Group>
)}
{/* Admin — content types, users, plugins, import */}
{visibleAdmin.length > 0 && (
<KumoSidebar.Group>
<KumoSidebar.GroupLabel>{t`Admin`}</KumoSidebar.GroupLabel>
<KumoSidebar.Menu>{renderNavItems(visibleAdmin)}</KumoSidebar.Menu>
</KumoSidebar.Group>
)}
{/* Plugin pages */}
{visiblePlugins.length > 0 && (
<KumoSidebar.Group>
<KumoSidebar.GroupLabel>{t`Plugins`}</KumoSidebar.GroupLabel>
<KumoSidebar.Menu>{renderNavItems(visiblePlugins)}</KumoSidebar.Menu>
</KumoSidebar.Group>
)}
</KumoSidebar.Content>
<KumoSidebar.Footer className="gap-0">
<KumoSidebar.Trigger className="rtl:rotate-180" />
<div className="min-w-0 flex-1 overflow-hidden">
<p
data-testid="admin-version"
className="w-40 overflow-hidden truncate ps-2 text-[11px] text-kumo-subtle"
>
{manifest.admin?.siteName || "EmDash CMS"} v{manifest.version || "0.0.0"}
{manifest.commit && ` (${manifest.commit})`}
</p>
</div>
</KumoSidebar.Footer>
</KumoSidebar>
);
}