feat(sidebar): add server-persisted section reorder with customize mode
- preferences.display.sidebarOrder json field on Users + named migration add_sidebar_order_preference + regenerated types - New pure helper src/lib/sidebar/order.ts (section ids, labels, default order, normalizeSidebarOrder) modeled on lib/dashboard/layout.ts, with tests/int/sidebar-order.int.spec.ts covering fallback/dupes/missing ids - AppSidebar renders sections from the normalized order; feature-flagged-off sections skip their slot and keep stored positions - Customize mode: dnd-kit sortable grips on group headers, save-on-drop via new updateSidebarOrder action, Reset clears the preference, Done exits; hidden while the sidebar is collapsed - updateSidebarOrder sanitizes server-side and rewrites full preferences - Fix sibling clobbering: saveDashboardLayout now preserves sidebarOrder, and updatePreferences now preserves both sidebarOrder and dashboard.layout
This commit is contained in:
parent
8fb97fdd1c
commit
0ca35ec251
10 changed files with 40625 additions and 14 deletions
|
|
@ -222,6 +222,16 @@ export async function updatePreferences(input: {
|
||||||
(MUTEABLE_NOTIFICATION_VALUES as readonly string[]).includes(t),
|
(MUTEABLE_NOTIFICATION_VALUES as readonly string[]).includes(t),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Read the stored user first so preference groups this form does not own
|
||||||
|
// (sidebar order, dashboard layout) survive the full-preferences write.
|
||||||
|
const fullUser = await payload.findByID({
|
||||||
|
collection: "users",
|
||||||
|
id: userId,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
const stored = fullUser.preferences ?? {};
|
||||||
|
|
||||||
await payload.update({
|
await payload.update({
|
||||||
collection: "users",
|
collection: "users",
|
||||||
id: userId,
|
id: userId,
|
||||||
|
|
@ -234,11 +244,15 @@ export async function updatePreferences(input: {
|
||||||
showBackgroundTexture: input.showBackgroundTexture,
|
showBackgroundTexture: input.showBackgroundTexture,
|
||||||
leadOrActual: input.leadOrActual,
|
leadOrActual: input.leadOrActual,
|
||||||
xpDisplayMini: input.xpDisplayMini,
|
xpDisplayMini: input.xpDisplayMini,
|
||||||
|
sidebarOrder: stored.display?.sidebarOrder ?? null,
|
||||||
},
|
},
|
||||||
discord: {
|
discord: {
|
||||||
enabled: input.discordEnabled,
|
enabled: input.discordEnabled,
|
||||||
mutedTypes: discordMutedTypes,
|
mutedTypes: discordMutedTypes,
|
||||||
},
|
},
|
||||||
|
dashboard: {
|
||||||
|
layout: stored.dashboard?.layout ?? null,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
overrideAccess: true,
|
overrideAccess: true,
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import config from "@payload-config";
|
||||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||||
import { getPayload } from "payload";
|
import { getPayload } from "payload";
|
||||||
import { normalizeDashboardLayout } from "@/lib/dashboard/layout";
|
import { normalizeDashboardLayout } from "@/lib/dashboard/layout";
|
||||||
|
import { normalizeSidebarOrder } from "@/lib/sidebar/order";
|
||||||
|
|
||||||
export interface ActionResult<T = undefined> {
|
export interface ActionResult<T = undefined> {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
|
|
@ -60,6 +61,7 @@ export async function saveDashboardLayout(
|
||||||
showBackgroundTexture: preferences.display?.showBackgroundTexture ?? true,
|
showBackgroundTexture: preferences.display?.showBackgroundTexture ?? true,
|
||||||
leadOrActual: preferences.display?.leadOrActual ?? "lead",
|
leadOrActual: preferences.display?.leadOrActual ?? "lead",
|
||||||
xpDisplayMini: preferences.display?.xpDisplayMini ?? false,
|
xpDisplayMini: preferences.display?.xpDisplayMini ?? false,
|
||||||
|
sidebarOrder: preferences.display?.sidebarOrder ?? null,
|
||||||
},
|
},
|
||||||
discord: {
|
discord: {
|
||||||
enabled: preferences.discord?.enabled ?? false,
|
enabled: preferences.discord?.enabled ?? false,
|
||||||
|
|
@ -80,3 +82,62 @@ export async function saveDashboardLayout(
|
||||||
return { success: false, error: message };
|
return { success: false, error: message };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persists the sidebar section order. Pass `null` to reset back to the
|
||||||
|
* default order (clears the stored preference). Like saveDashboardLayout,
|
||||||
|
* the full preferences object is rewritten so sibling groups survive, and
|
||||||
|
* the order itself is sanitized server-side.
|
||||||
|
*/
|
||||||
|
export async function updateSidebarOrder(order: unknown): Promise<ActionResult<boolean>> {
|
||||||
|
try {
|
||||||
|
const { payload, user } = await authenticate();
|
||||||
|
const userId = user.id as number;
|
||||||
|
|
||||||
|
const normalized = order === null || order === undefined ? null : normalizeSidebarOrder(order);
|
||||||
|
const fullUser = await payload.findByID({
|
||||||
|
collection: "users",
|
||||||
|
id: userId,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
const preferences = fullUser.preferences ?? {};
|
||||||
|
|
||||||
|
await payload.update({
|
||||||
|
collection: "users",
|
||||||
|
id: userId,
|
||||||
|
data: {
|
||||||
|
preferences: {
|
||||||
|
notifications: {
|
||||||
|
mutedAll: preferences.notifications?.mutedAll ?? false,
|
||||||
|
mutedTypes: preferences.notifications?.mutedTypes ?? [],
|
||||||
|
},
|
||||||
|
display: {
|
||||||
|
showCallsign: preferences.display?.showCallsign ?? false,
|
||||||
|
showVersionOverlay: preferences.display?.showVersionOverlay ?? true,
|
||||||
|
showBackgroundTexture: preferences.display?.showBackgroundTexture ?? true,
|
||||||
|
leadOrActual: preferences.display?.leadOrActual ?? "lead",
|
||||||
|
xpDisplayMini: preferences.display?.xpDisplayMini ?? false,
|
||||||
|
sidebarOrder: normalized,
|
||||||
|
},
|
||||||
|
discord: {
|
||||||
|
enabled: preferences.discord?.enabled ?? false,
|
||||||
|
mutedTypes: preferences.discord?.mutedTypes ?? [],
|
||||||
|
},
|
||||||
|
dashboard: {
|
||||||
|
layout: preferences.dashboard?.layout ?? null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: true, data: true };
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : "Unknown error";
|
||||||
|
if (message === "Unauthorized") {
|
||||||
|
return { success: false, error: "You must be logged in." };
|
||||||
|
}
|
||||||
|
return { success: false, error: message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -312,6 +312,14 @@ export const Users: CollectionConfig = {
|
||||||
type: "checkbox",
|
type: "checkbox",
|
||||||
defaultValue: true,
|
defaultValue: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "sidebarOrder",
|
||||||
|
label: "Sidebar section order (managed by the sidebar)",
|
||||||
|
type: "json",
|
||||||
|
admin: {
|
||||||
|
description: "Ordered sidebar section ids, saved by the sidebar customize mode",
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,30 @@ import {
|
||||||
Minimize,
|
Minimize,
|
||||||
ScrollText,
|
ScrollText,
|
||||||
SparkleIcon,
|
SparkleIcon,
|
||||||
|
CheckIcon,
|
||||||
|
GripVerticalIcon,
|
||||||
|
RotateCcwIcon,
|
||||||
|
SlidersHorizontalIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import {
|
||||||
|
DndContext,
|
||||||
|
KeyboardSensor,
|
||||||
|
PointerSensor,
|
||||||
|
closestCenter,
|
||||||
|
useSensor,
|
||||||
|
useSensors,
|
||||||
|
} from "@dnd-kit/core";
|
||||||
|
import type { DragEndEvent } from "@dnd-kit/core";
|
||||||
|
import {
|
||||||
|
SortableContext,
|
||||||
|
arrayMove,
|
||||||
|
sortableKeyboardCoordinates,
|
||||||
|
useSortable,
|
||||||
|
verticalListSortingStrategy,
|
||||||
|
} from "@dnd-kit/sortable";
|
||||||
|
import { CSS } from "@dnd-kit/utilities";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
import { NavCore } from "@/components/frontend/blocks/NavCore";
|
import { NavCore } from "@/components/frontend/blocks/NavCore";
|
||||||
import { NavMinigames } from "@/components/frontend/blocks/NavMinigames";
|
import { NavMinigames } from "@/components/frontend/blocks/NavMinigames";
|
||||||
|
|
@ -24,7 +47,9 @@ import {
|
||||||
SidebarMenu,
|
SidebarMenu,
|
||||||
SidebarMenuButton,
|
SidebarMenuButton,
|
||||||
SidebarMenuItem,
|
SidebarMenuItem,
|
||||||
|
useSidebar,
|
||||||
} from "@/components/ui/sidebar";
|
} from "@/components/ui/sidebar";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import XPDisplay from "@/components/frontend/blocks/XPDisplay";
|
import XPDisplay from "@/components/frontend/blocks/XPDisplay";
|
||||||
|
|
@ -33,8 +58,16 @@ import type { User } from "@/payload-types";
|
||||||
import { Progress } from "@/components/ui/progress";
|
import { Progress } from "@/components/ui/progress";
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
import { updatePreferences } from "@/app/(frontend)/account/actions";
|
import { updatePreferences } from "@/app/(frontend)/account/actions";
|
||||||
|
import { updateSidebarOrder } from "@/app/(frontend)/actions";
|
||||||
import { sidebarData } from "@/components/frontend/blocks/sidebarData";
|
import { sidebarData } from "@/components/frontend/blocks/sidebarData";
|
||||||
import type { RegistryGame } from "@/lib/minigames/registry";
|
import type { RegistryGame } from "@/lib/minigames/registry";
|
||||||
|
import {
|
||||||
|
DEFAULT_SIDEBAR_ORDER,
|
||||||
|
SIDEBAR_SECTION_LABELS,
|
||||||
|
normalizeSidebarOrder,
|
||||||
|
type SidebarSectionId,
|
||||||
|
} from "@/lib/sidebar/order";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
const data = {
|
const data = {
|
||||||
navMain: [
|
navMain: [
|
||||||
|
|
@ -97,6 +130,8 @@ export function AppSidebar({
|
||||||
preferences?: NonNullable<User["preferences"]>;
|
preferences?: NonNullable<User["preferences"]>;
|
||||||
minigameNav?: RegistryGame[];
|
minigameNav?: RegistryGame[];
|
||||||
} & React.ComponentProps<typeof Sidebar>) {
|
} & React.ComponentProps<typeof Sidebar>) {
|
||||||
|
const router = useRouter();
|
||||||
|
const { state: sidebarState } = useSidebar();
|
||||||
const [isMiniMode, setIsMiniMode] = React.useState<boolean>(
|
const [isMiniMode, setIsMiniMode] = React.useState<boolean>(
|
||||||
preferences?.display?.xpDisplayMini ?? false,
|
preferences?.display?.xpDisplayMini ?? false,
|
||||||
);
|
);
|
||||||
|
|
@ -107,6 +142,25 @@ export function AppSidebar({
|
||||||
setIsMiniMode(savedXpDisplayMini);
|
setIsMiniMode(savedXpDisplayMini);
|
||||||
}, [savedXpDisplayMini]);
|
}, [savedXpDisplayMini]);
|
||||||
|
|
||||||
|
// Section order: normalized from the stored preference, kept in local state
|
||||||
|
// while dragging and persisted on every drop (same flow as the dashboard).
|
||||||
|
const savedSidebarOrder = React.useMemo(
|
||||||
|
() => normalizeSidebarOrder(preferences?.display?.sidebarOrder),
|
||||||
|
[preferences],
|
||||||
|
);
|
||||||
|
const [sectionOrder, setSectionOrder] =
|
||||||
|
React.useState<SidebarSectionId[]>(savedSidebarOrder);
|
||||||
|
const [isReordering, setIsReordering] = React.useState(false);
|
||||||
|
const [savingOrder, setSavingOrder] = React.useState(false);
|
||||||
|
React.useEffect(() => {
|
||||||
|
setSectionOrder(savedSidebarOrder);
|
||||||
|
}, [savedSidebarOrder]);
|
||||||
|
|
||||||
|
const sensors = useSensors(
|
||||||
|
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
|
||||||
|
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||||
|
);
|
||||||
|
|
||||||
const handleToggleXPMode = React.useCallback(async () => {
|
const handleToggleXPMode = React.useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
await updatePreferences({
|
await updatePreferences({
|
||||||
|
|
@ -139,6 +193,72 @@ export function AppSidebar({
|
||||||
);
|
);
|
||||||
const filteredNavHelpdesk = helpdeskEnabled ? data.navHelpdesk : [];
|
const filteredNavHelpdesk = helpdeskEnabled ? data.navHelpdesk : [];
|
||||||
|
|
||||||
|
const sectionNodes: Record<SidebarSectionId, React.ReactNode> = {
|
||||||
|
platform: <NavCore label={SIDEBAR_SECTION_LABELS.platform} items={data.navMain} />,
|
||||||
|
map: <NavCore label={SIDEBAR_SECTION_LABELS.map} items={data.navMap} />,
|
||||||
|
intelligence: hasIntelligence ? (
|
||||||
|
<NavCore label={SIDEBAR_SECTION_LABELS.intelligence} items={data.navIntelligence} />
|
||||||
|
) : null,
|
||||||
|
operations: <NavCore label={SIDEBAR_SECTION_LABELS.operations} items={data.navOperations} />,
|
||||||
|
infrastructure: hasLogistics ? (
|
||||||
|
<NavCore
|
||||||
|
label={SIDEBAR_SECTION_LABELS.infrastructure}
|
||||||
|
items={filteredNavLogistics}
|
||||||
|
expandDefaultOpen={hasLogistics}
|
||||||
|
/>
|
||||||
|
) : null,
|
||||||
|
chronicle: <NavCore label={SIDEBAR_SECTION_LABELS.chronicle} items={data.navStory} />,
|
||||||
|
surveys: <NavCore label={SIDEBAR_SECTION_LABELS.surveys} items={data.navSurveys} />,
|
||||||
|
helpdesk: <NavCore label={SIDEBAR_SECTION_LABELS.helpdesk} items={filteredNavHelpdesk} />,
|
||||||
|
commerce: <NavCore label={SIDEBAR_SECTION_LABELS.commerce} items={data.navCommerce} />,
|
||||||
|
personal: <NavCore label={SIDEBAR_SECTION_LABELS.personal} items={data.navPersonal} />,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Feature-flagged-off sections skip their slot entirely; hidden ids keep
|
||||||
|
// their stored positions so re-enabling a flag restores the user's layout.
|
||||||
|
const visibleOrder = sectionOrder.filter((id) => sectionNodes[id] !== null);
|
||||||
|
|
||||||
|
const persistOrder = React.useCallback(
|
||||||
|
async (order: SidebarSectionId[] | null) => {
|
||||||
|
setSavingOrder(true);
|
||||||
|
const result = await updateSidebarOrder(order);
|
||||||
|
setSavingOrder(false);
|
||||||
|
if (!result.success) {
|
||||||
|
toast.error(result.error ?? "Failed to save sidebar order");
|
||||||
|
}
|
||||||
|
router.refresh();
|
||||||
|
},
|
||||||
|
[router],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleDragEnd = React.useCallback(
|
||||||
|
(event: DragEndEvent) => {
|
||||||
|
const { active, over } = event;
|
||||||
|
if (!over || active.id === over.id) return;
|
||||||
|
const from = visibleOrder.indexOf(active.id as SidebarSectionId);
|
||||||
|
const to = visibleOrder.indexOf(over.id as SidebarSectionId);
|
||||||
|
if (from < 0 || to < 0) return;
|
||||||
|
|
||||||
|
const reorderedVisible = arrayMove(visibleOrder, from, to);
|
||||||
|
// Re-insert hidden (feature-flagged) sections at their original indices.
|
||||||
|
const merged = [...reorderedVisible];
|
||||||
|
const hiddenIds = sectionOrder.filter((id) => !visibleOrder.includes(id));
|
||||||
|
hiddenIds.forEach((id) => {
|
||||||
|
const originalIndex = sectionOrder.indexOf(id);
|
||||||
|
merged.splice(Math.min(originalIndex, merged.length), 0, id);
|
||||||
|
});
|
||||||
|
|
||||||
|
setSectionOrder(merged);
|
||||||
|
void persistOrder(merged);
|
||||||
|
},
|
||||||
|
[persistOrder, sectionOrder, visibleOrder],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleResetOrder = React.useCallback(() => {
|
||||||
|
setSectionOrder([...DEFAULT_SIDEBAR_ORDER]);
|
||||||
|
void persistOrder(null);
|
||||||
|
}, [persistOrder]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sidebar variant="inset" {...props}>
|
<Sidebar variant="inset" {...props}>
|
||||||
<SidebarHeader>
|
<SidebarHeader>
|
||||||
|
|
@ -167,21 +287,62 @@ export function AppSidebar({
|
||||||
</SidebarMenu>
|
</SidebarMenu>
|
||||||
</SidebarHeader>
|
</SidebarHeader>
|
||||||
<SidebarContent className="overflow-hidden">
|
<SidebarContent className="overflow-hidden">
|
||||||
|
<div className="flex items-center justify-end gap-1 px-3 pt-1 group-data-[collapsible=icon]:hidden">
|
||||||
|
{isReordering ? (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-7 gap-1 px-2 text-xs text-muted-foreground"
|
||||||
|
disabled={savingOrder}
|
||||||
|
onClick={handleResetOrder}
|
||||||
|
>
|
||||||
|
<RotateCcwIcon className="size-3.5" />
|
||||||
|
Reset
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-7 gap-1 px-2 text-xs"
|
||||||
|
disabled={savingOrder}
|
||||||
|
onClick={() => setIsReordering(false)}
|
||||||
|
>
|
||||||
|
<CheckIcon className="size-3.5" />
|
||||||
|
Done
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
sidebarState !== "collapsed" && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-7 gap-1 px-2 text-xs text-muted-foreground"
|
||||||
|
onClick={() => setIsReordering(true)}
|
||||||
|
>
|
||||||
|
<SlidersHorizontalIcon className="size-3.5" />
|
||||||
|
Customize
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto group-data-[collapsible=icon]:overflow-hidden">
|
<div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto group-data-[collapsible=icon]:overflow-hidden">
|
||||||
<NavCore label="Platform" items={data.navMain} />
|
{isReordering ? (
|
||||||
<NavCore label="Map" items={data.navMap} />
|
<DndContext
|
||||||
{hasIntelligence && (
|
sensors={sensors}
|
||||||
<NavCore label="Intelligence" items={data.navIntelligence} />
|
collisionDetection={closestCenter}
|
||||||
|
onDragEnd={handleDragEnd}
|
||||||
|
>
|
||||||
|
<SortableContext items={visibleOrder} strategy={verticalListSortingStrategy}>
|
||||||
|
{visibleOrder.map((id) => (
|
||||||
|
<SortableSection key={id} id={id}>
|
||||||
|
{sectionNodes[id]}
|
||||||
|
</SortableSection>
|
||||||
|
))}
|
||||||
|
</SortableContext>
|
||||||
|
</DndContext>
|
||||||
|
) : (
|
||||||
|
visibleOrder.map((id) => <React.Fragment key={id}>{sectionNodes[id]}</React.Fragment>)
|
||||||
)}
|
)}
|
||||||
<NavCore label="Operations" items={data.navOperations} />
|
|
||||||
{hasLogistics && (
|
|
||||||
<NavCore label="Infrastructure" items={filteredNavLogistics} expandDefaultOpen={hasLogistics} />
|
|
||||||
)}
|
|
||||||
<NavCore label="Chronicle" items={data.navStory} />
|
|
||||||
<NavCore label="Surveys" items={data.navSurveys} />
|
|
||||||
<NavCore label="Helpdesk" items={filteredNavHelpdesk} />
|
|
||||||
<NavCore label="Commerce" items={data.navCommerce} />
|
|
||||||
<NavCore label="Personal" items={data.navPersonal} />
|
|
||||||
{/*<NavProjects projects={data.projects} />*/}
|
{/*<NavProjects projects={data.projects} />*/}
|
||||||
</div>
|
</div>
|
||||||
<hr />
|
<hr />
|
||||||
|
|
@ -247,3 +408,32 @@ export function AppSidebar({
|
||||||
</Sidebar>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drag wrapper for one sidebar section in customize mode. The grip floats
|
||||||
|
* over the group label row; sections stay expanded so labels guide placement.
|
||||||
|
*/
|
||||||
|
function SortableSection({ id, children }: { id: SidebarSectionId; children: React.ReactNode }) {
|
||||||
|
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } =
|
||||||
|
useSortable({ id });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={setNodeRef}
|
||||||
|
style={{ transform: CSS.Transform.toString(transform), transition }}
|
||||||
|
className={cn("relative", isDragging && "z-20 opacity-80")}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
ref={setActivatorNodeRef}
|
||||||
|
type="button"
|
||||||
|
aria-label={`Reorder ${SIDEBAR_SECTION_LABELS[id]} section`}
|
||||||
|
{...attributes}
|
||||||
|
{...listeners}
|
||||||
|
className="absolute right-1 top-0 z-30 flex size-6 cursor-grab touch-none items-center justify-center rounded-sm text-muted-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:cursor-grabbing"
|
||||||
|
>
|
||||||
|
<GripVerticalIcon className="size-4" />
|
||||||
|
</button>
|
||||||
|
<div className={cn(isDragging && "rounded-md bg-sidebar-accent/40")}>{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
|
||||||
68
src/lib/sidebar/order.ts
Normal file
68
src/lib/sidebar/order.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
/**
|
||||||
|
* Sidebar section registry and order vocabulary. Pure module (no React, no
|
||||||
|
* Payload import) so both the sidebar client component and server actions can
|
||||||
|
* use it. Modeled on src/lib/dashboard/layout.ts.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const SIDEBAR_SECTION_IDS = [
|
||||||
|
"platform",
|
||||||
|
"map",
|
||||||
|
"intelligence",
|
||||||
|
"operations",
|
||||||
|
"infrastructure",
|
||||||
|
"chronicle",
|
||||||
|
"surveys",
|
||||||
|
"helpdesk",
|
||||||
|
"commerce",
|
||||||
|
"personal",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type SidebarSectionId = (typeof SIDEBAR_SECTION_IDS)[number];
|
||||||
|
|
||||||
|
export const DEFAULT_SIDEBAR_ORDER: readonly SidebarSectionId[] = [...SIDEBAR_SECTION_IDS];
|
||||||
|
|
||||||
|
export const SIDEBAR_SECTION_LABELS: Record<SidebarSectionId, string> = {
|
||||||
|
platform: "Platform",
|
||||||
|
map: "Map",
|
||||||
|
intelligence: "Intelligence",
|
||||||
|
operations: "Operations",
|
||||||
|
infrastructure: "Infrastructure",
|
||||||
|
chronicle: "Chronicle",
|
||||||
|
surveys: "Surveys",
|
||||||
|
helpdesk: "Helpdesk",
|
||||||
|
commerce: "Commerce",
|
||||||
|
personal: "Personal",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isSidebarSectionId(value: unknown): value is SidebarSectionId {
|
||||||
|
return (
|
||||||
|
typeof value === "string" && (SIDEBAR_SECTION_IDS as readonly string[]).includes(value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitizes an arbitrary stored order into a valid full section list: drops
|
||||||
|
* unknown/duplicate ids, keeps known ones in the user's order, and appends any
|
||||||
|
* missing sections at the end in default order. Non-array input falls back to
|
||||||
|
* the default order.
|
||||||
|
*/
|
||||||
|
export function normalizeSidebarOrder(raw: unknown): SidebarSectionId[] {
|
||||||
|
if (!Array.isArray(raw)) {
|
||||||
|
return [...DEFAULT_SIDEBAR_ORDER];
|
||||||
|
}
|
||||||
|
|
||||||
|
const seen = new Set<SidebarSectionId>();
|
||||||
|
const ordered: SidebarSectionId[] = [];
|
||||||
|
for (const entry of raw) {
|
||||||
|
if (isSidebarSectionId(entry) && !seen.has(entry)) {
|
||||||
|
seen.add(entry);
|
||||||
|
ordered.push(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const id of DEFAULT_SIDEBAR_ORDER) {
|
||||||
|
if (!seen.has(id)) {
|
||||||
|
ordered.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ordered;
|
||||||
|
}
|
||||||
40165
src/migrations/20261012_173511_add_sidebar_order_preference.json
Normal file
40165
src/migrations/20261012_173511_add_sidebar_order_preference.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||||
|
|
||||||
|
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
ALTER TABLE "users" ADD COLUMN "preferences_display_sidebar_order" jsonb;`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
ALTER TABLE "users" DROP COLUMN "preferences_display_sidebar_order";`)
|
||||||
|
}
|
||||||
|
|
@ -128,6 +128,7 @@ import * as migration_20261012_014741_add_call_for_fire_versus from './20261012_
|
||||||
import * as migration_20261012_015000_seed_call_for_fire_versus_registry from './20261012_015000_seed_call_for_fire_versus_registry';
|
import * as migration_20261012_015000_seed_call_for_fire_versus_registry from './20261012_015000_seed_call_for_fire_versus_registry';
|
||||||
import * as migration_20261012_030000_update_call_for_fire_versus_wording from './20261012_030000_update_call_for_fire_versus_wording';
|
import * as migration_20261012_030000_update_call_for_fire_versus_wording from './20261012_030000_update_call_for_fire_versus_wording';
|
||||||
import * as migration_20261012_134242_add_discord_presence_global from './20261012_134242_add_discord_presence_global';
|
import * as migration_20261012_134242_add_discord_presence_global from './20261012_134242_add_discord_presence_global';
|
||||||
|
import * as migration_20261012_173511_add_sidebar_order_preference from './20261012_173511_add_sidebar_order_preference';
|
||||||
|
|
||||||
export const migrations = [
|
export const migrations = [
|
||||||
{
|
{
|
||||||
|
|
@ -778,6 +779,11 @@ export const migrations = [
|
||||||
{
|
{
|
||||||
up: migration_20261012_134242_add_discord_presence_global.up,
|
up: migration_20261012_134242_add_discord_presence_global.up,
|
||||||
down: migration_20261012_134242_add_discord_presence_global.down,
|
down: migration_20261012_134242_add_discord_presence_global.down,
|
||||||
name: '20261012_134242_add_discord_presence_global'
|
name: '20261012_134242_add_discord_presence_global',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
up: migration_20261012_173511_add_sidebar_order_preference.up,
|
||||||
|
down: migration_20261012_173511_add_sidebar_order_preference.down,
|
||||||
|
name: '20261012_173511_add_sidebar_order_preference'
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -504,6 +504,18 @@ export interface User {
|
||||||
showVersionOverlay?: boolean | null;
|
showVersionOverlay?: boolean | null;
|
||||||
xpDisplayMini?: boolean | null;
|
xpDisplayMini?: boolean | null;
|
||||||
showBackgroundTexture?: boolean | null;
|
showBackgroundTexture?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Ordered sidebar section ids, saved by the sidebar customize mode
|
||||||
|
*/
|
||||||
|
sidebarOrder?:
|
||||||
|
| {
|
||||||
|
[k: string]: unknown;
|
||||||
|
}
|
||||||
|
| unknown[]
|
||||||
|
| string
|
||||||
|
| number
|
||||||
|
| boolean
|
||||||
|
| null;
|
||||||
};
|
};
|
||||||
discord?: {
|
discord?: {
|
||||||
enabled?: boolean | null;
|
enabled?: boolean | null;
|
||||||
|
|
@ -8814,6 +8826,7 @@ export interface UsersSelect<T extends boolean = true> {
|
||||||
showVersionOverlay?: T;
|
showVersionOverlay?: T;
|
||||||
xpDisplayMini?: T;
|
xpDisplayMini?: T;
|
||||||
showBackgroundTexture?: T;
|
showBackgroundTexture?: T;
|
||||||
|
sidebarOrder?: T;
|
||||||
};
|
};
|
||||||
discord?:
|
discord?:
|
||||||
| T
|
| T
|
||||||
|
|
|
||||||
75
tests/int/sidebar-order.int.spec.ts
Normal file
75
tests/int/sidebar-order.int.spec.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
||||||
|
/**
|
||||||
|
* Sidebar order preference tests. Pure module (src/lib/sidebar/order.ts),
|
||||||
|
* no database access needed; lives under tests/int per repo convention for
|
||||||
|
* vitest specs.
|
||||||
|
*/
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
DEFAULT_SIDEBAR_ORDER,
|
||||||
|
SIDEBAR_SECTION_IDS,
|
||||||
|
isSidebarSectionId,
|
||||||
|
normalizeSidebarOrder,
|
||||||
|
} from "@/lib/sidebar/order";
|
||||||
|
|
||||||
|
describe("normalizeSidebarOrder", () => {
|
||||||
|
it("falls back to the default order for non-array input", () => {
|
||||||
|
expect(normalizeSidebarOrder(undefined)).toEqual([...DEFAULT_SIDEBAR_ORDER]);
|
||||||
|
expect(normalizeSidebarOrder(null)).toEqual([...DEFAULT_SIDEBAR_ORDER]);
|
||||||
|
expect(normalizeSidebarOrder("platform")).toEqual([...DEFAULT_SIDEBAR_ORDER]);
|
||||||
|
expect(normalizeSidebarOrder({ 0: "platform" })).toEqual([...DEFAULT_SIDEBAR_ORDER]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps known ids in the user's order", () => {
|
||||||
|
const custom = ["personal", "platform", "map"];
|
||||||
|
const result = normalizeSidebarOrder(custom);
|
||||||
|
expect(result.slice(0, 3)).toEqual(["personal", "platform", "map"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops unknown and duplicate ids", () => {
|
||||||
|
const result = normalizeSidebarOrder([
|
||||||
|
"platform",
|
||||||
|
"not-a-section",
|
||||||
|
42,
|
||||||
|
null,
|
||||||
|
"platform",
|
||||||
|
"map",
|
||||||
|
]);
|
||||||
|
expect(result.filter((id) => id === "platform")).toEqual(["platform"]);
|
||||||
|
expect(result).toContain("map");
|
||||||
|
expect(result).not.toContain("not-a-section");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("appends missing sections in default order so the list is always complete", () => {
|
||||||
|
const result = normalizeSidebarOrder(["personal"]);
|
||||||
|
expect(result[0]).toBe("personal");
|
||||||
|
expect(result.slice(1)).toEqual(DEFAULT_SIDEBAR_ORDER.filter((id) => id !== "personal"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("always returns every section id exactly once", () => {
|
||||||
|
const inputs: unknown[] = [
|
||||||
|
[],
|
||||||
|
["commerce", "commerce"],
|
||||||
|
[...SIDEBAR_SECTION_IDS].reverse(),
|
||||||
|
["bogus", ...SIDEBAR_SECTION_IDS, "bogus"],
|
||||||
|
];
|
||||||
|
for (const input of inputs) {
|
||||||
|
const result = normalizeSidebarOrder(input);
|
||||||
|
expect(result).toHaveLength(SIDEBAR_SECTION_IDS.length);
|
||||||
|
expect(new Set(result).size).toBe(SIDEBAR_SECTION_IDS.length);
|
||||||
|
for (const id of SIDEBAR_SECTION_IDS) {
|
||||||
|
expect(result).toContain(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("isSidebarSectionId", () => {
|
||||||
|
it("accepts only known section ids", () => {
|
||||||
|
expect(isSidebarSectionId("platform")).toBe(true);
|
||||||
|
expect(isSidebarSectionId("personal")).toBe(true);
|
||||||
|
expect(isSidebarSectionId("Platform")).toBe(false);
|
||||||
|
expect(isSidebarSectionId(undefined)).toBe(false);
|
||||||
|
expect(isSidebarSectionId(7)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue