themes: rotate to the one you are wearing, star the ones you like
Four changes for 200+ themes, and one mistake worth recording. ORDERING IS A ROTATION, not a sort. The registry order is the list's only structure — families sit together in it — so lifting the selected theme to the top answers "which am I on" by destroying "what is next to it". Rotating keeps every neighbour and moves the starting point. Both lists use the same `ordered` array, which is the point: "the one below the one I have on" has to mean the same thing in the dropdown and in the ctrl+shift+space browser, or one teaches an order the other contradicts. FAVOURITES are a table, not a JSON column. theme_favorites is a row per star, so a toggle is an INSERT or a DELETE and cannot race with itself; an array in user_settings would be read-modify-written and two tabs would lose one. No foreign key to a theme, because themes are not rows — most are compiled in, the rest are directories discovered at request time — so a star can outlive its theme and the reader intersects with the live registry rather than trusting the table. Favourites-first is a second rotation-preserving pass rather than a filter, so the list can still answer "what else is there". Filtering to favourites only is a separate, explicit toggle. THE INSTRUCTIONS NO LONGER SCROLL AWAY. DropdownMenuContent carried overflow-y-auto itself, so the one line telling you the shortcuts exist was visible for half a second and then gone under two hundred entries — which is the same as not having written it. Header and footer are now siblings of a scroll box instead of passengers in it, and the header names alt+space too. THE MISTAKE: the routes went on /themes first, and that prefix is deliberately UNAUTHENTICATED — the sign-in screen paints in the chosen theme, before any account exists to ask. An anonymous GET answered 500, which was the consequence arriving politely. They now live on /theme-favorites, claimed by the `account` permission, which is core and already owns /user, /dock and /api-keys: a starred theme is the same shape as a dock preference. I then mounted it one line off, in the unprotected block beside the thing I was moving it away from, and caught that by reading rather than by testing. Verified after: /api/theme-favorites is 401 unauthenticated on both verbs, and /api/themes still answers 200 so the login screen keeps its colours. 10 tests on the pure ordering — including the property that makes a rotation a rotation: every adjacency in the original survives it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Check, Star } from 'lucide-react';
|
||||
import { favouritesFirst, groupByFamily, rotateToSelected } from 'theme';
|
||||
import * as Dropdown from '@/components/ui/dropdown-menu';
|
||||
import type { Theme } from '@/components/ui/ThemeProvider';
|
||||
import { useTheme, useThemeKeys } from '@/components/ui/ThemeProvider';
|
||||
import { useThemeFavorites } from '@/state/useThemeFavorites';
|
||||
|
||||
const {
|
||||
DropdownMenu,
|
||||
@@ -31,13 +33,28 @@ const {
|
||||
export const ThemeSwitcher = () => {
|
||||
const { theme, themeId, setTheme, themes } = useTheme();
|
||||
const { open, setOpen, focused, setFocused } = useThemeKeys();
|
||||
const { favorites, isFavorite, toggle } = useThemeFavorites();
|
||||
const [onlyFavorites, setOnlyFavorites] = useState(false);
|
||||
|
||||
// Grouped by family, so `Duck Light`/`Duck Dark` and the two Catppuccins sit together. The registry is
|
||||
// readonly, so this builds mutable arrays rather than pushing into its own type.
|
||||
const families = themes.reduce<Record<string, Theme[]>>((acc, t) => {
|
||||
(acc[t.family] ??= []).push(t);
|
||||
return acc;
|
||||
}, {});
|
||||
/*
|
||||
One ordering, used by both lists.
|
||||
|
||||
ROTATED to the theme you are wearing rather than sorted: with 200+ installed, the list's only structure
|
||||
is the registry order — families sit together in it — and lifting the selected theme out of its family
|
||||
would answer "which am I on" by destroying "what is next to it". A rotation answers both. See
|
||||
`theme/rotate.ts`.
|
||||
|
||||
Then favourites first, which is a second rotation-preserving pass rather than a filter: each half keeps
|
||||
the order it was given, so the theme you are wearing still leads.
|
||||
*/
|
||||
const ordered = useMemo(() => {
|
||||
const rotated = rotateToSelected(themes, themeId);
|
||||
const listed = onlyFavorites ? rotated.filter((t) => favorites.has(t.id)) : rotated;
|
||||
return favouritesFirst(listed, favorites);
|
||||
// `favorites` is a fresh Set each render; its CONTENTS are what matter, so key on those.
|
||||
}, [themes, themeId, onlyFavorites, [...favorites].sort().join(',')]);
|
||||
|
||||
const families = useMemo(() => groupByFamily(ordered), [ordered]);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -55,21 +72,69 @@ export const ThemeSwitcher = () => {
|
||||
{theme.name}
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="z-50 max-h-[70vh] w-56 overflow-y-auto">
|
||||
<DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
|
||||
ctrl+shift+←/→ · ctrl+shift+space
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{Object.entries(families).map(([family, entries]) => (
|
||||
<div key={family}>
|
||||
{entries.map((t) => (
|
||||
<DropdownMenuItem key={t.id} onClick={() => setTheme(t.id)} className="cursor-pointer">
|
||||
<Check className={`mr-2 h-4 w-4 ${t.id === themeId ? 'opacity-100' : 'opacity-0'}`} />
|
||||
{t.name}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
{/*
|
||||
The CONTENT does not scroll — the list inside it does.
|
||||
|
||||
It used to carry `overflow-y-auto` itself, which scrolled the instruction line away with the
|
||||
themes. Two hundred entries meant the one line telling you the keyboard shortcuts existed was
|
||||
visible for the first half-second and then gone for good, which is the same as not having written
|
||||
it. Header and footer are now siblings of a scroll box rather than passengers in one.
|
||||
*/}
|
||||
<DropdownMenuContent align="end" className="z-50 flex max-h-[70vh] w-64 flex-col overflow-hidden p-0">
|
||||
<div className="shrink-0 border-b border-border px-2 py-1.5">
|
||||
<DropdownMenuLabel className="px-0 py-0 text-xs font-normal leading-relaxed text-muted-foreground">
|
||||
<span className="block">ctrl+shift+←/→ cycle · ctrl+shift+space browse</span>
|
||||
<span className="block">alt+space to search every theme by name</span>
|
||||
</DropdownMenuLabel>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(ev) => {
|
||||
// The dropdown closes on any item activation, and this is a filter rather than a choice.
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
setOnlyFavorites((was) => !was);
|
||||
}}
|
||||
className={`mt-1 inline-flex cursor-pointer items-center gap-1.5 rounded px-1.5 py-0.5 text-xs font-medium transition-colors ${
|
||||
onlyFavorites ? 'bg-primary/15 text-primary' : 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
<Star className={`h-3.5 w-3.5 ${onlyFavorites ? 'fill-current' : ''}`} />
|
||||
{onlyFavorites ? `Favourites only (${favorites.size})` : `Favourites (${favorites.size})`}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-1">
|
||||
{ordered.length === 0 ? (
|
||||
<p className="px-2 py-6 text-center text-xs text-muted-foreground">
|
||||
No favourites yet — star one with the button on its row.
|
||||
</p>
|
||||
) : (
|
||||
families.map(([family, entries]) => (
|
||||
<div key={family}>
|
||||
{entries.map((t) => (
|
||||
<DropdownMenuItem key={t.id} onClick={() => setTheme(t.id)} className="cursor-pointer pr-1">
|
||||
<Check className={`mr-2 h-4 w-4 shrink-0 ${t.id === themeId ? 'opacity-100' : 'opacity-0'}`} />
|
||||
<span className="min-w-0 flex-1 truncate">{t.name}</span>
|
||||
{/* A sibling of the row's action, never nested inside it — starring is not choosing. */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={isFavorite(t.id) ? `Unstar ${t.name}` : `Star ${t.name}`}
|
||||
title={isFavorite(t.id) ? 'Remove from favourites' : 'Add to favourites'}
|
||||
onClick={(ev) => {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
toggle(t.id);
|
||||
}}
|
||||
className="ml-1 shrink-0 rounded p-1 text-muted-foreground hover:text-primary"
|
||||
>
|
||||
<Star className={`h-3.5 w-3.5 ${isFavorite(t.id) ? 'fill-current text-primary' : ''}`} />
|
||||
</button>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -90,8 +155,11 @@ export const ThemeSwitcher = () => {
|
||||
}}
|
||||
onClick={(ev) => ev.stopPropagation()}
|
||||
>
|
||||
<ul className="flex flex-col gap-1">
|
||||
{themes.map((t) => {
|
||||
{/* The SAME `ordered` list as the dropdown — rotated to what you are wearing, favourites
|
||||
first. Both lists agreeing is the point: "the one below the one I have on" has to mean the
|
||||
same thing in both, or the browse teaches you an order the menu then contradicts. */}
|
||||
<ul className="flex max-h-[70vh] flex-col gap-1 overflow-y-auto">
|
||||
{ordered.map((t) => {
|
||||
const isFocused = t.id === focused;
|
||||
return (
|
||||
<li key={t.id}>
|
||||
@@ -106,12 +174,17 @@ export const ThemeSwitcher = () => {
|
||||
}`}
|
||||
>
|
||||
{t.name}
|
||||
{isFavorite(t.id) && (
|
||||
<Star className="ml-2 inline h-3 w-3 fill-current align-middle opacity-70" />
|
||||
)}
|
||||
{t.id === themeId && <span className="ml-2 align-middle text-xs opacity-70">active</span>}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{/* Always visible: it sits outside the scroll box above, for the same reason the dropdown's
|
||||
header does. */}
|
||||
<p className="mt-6 text-center text-xs opacity-60">
|
||||
j/k or ↑/↓ move · l or → preview · h or ← reset · enter keep · esc cancel
|
||||
</p>
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useClient } from 'hooks/useClient';
|
||||
|
||||
/*
|
||||
Starred themes, per account.
|
||||
|
||||
With 200+ installed, "which of these did I like" is a question the list cannot answer by itself, and the
|
||||
answer belongs to the account rather than to the browser — the same taste follows you to the phone.
|
||||
|
||||
Optimistic, and that is not a nicety here: the star sits in a dropdown you are about to close, so a
|
||||
round trip before the icon fills means the confirmation arrives after the thing it confirms has gone.
|
||||
*/
|
||||
|
||||
const KEY = ['themes', 'favorites'];
|
||||
|
||||
export function useThemeFavorites() {
|
||||
const client = useClient();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const query = useQuery<{ favorites: string[] }>({
|
||||
queryKey: KEY,
|
||||
queryFn: () => client.get<{ favorites: string[] }>('/theme-favorites'),
|
||||
// Taste does not change while you look at it, and the mutation below keeps the cache honest.
|
||||
staleTime: 5 * 60_000,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const toggle = useMutation({
|
||||
mutationFn: ({ themeId, favorite }: { themeId: string; favorite: boolean }) =>
|
||||
client.put<{ themeId: string; favorite: boolean }>(`/theme-favorites/${themeId}`, { favorite }),
|
||||
onMutate: async ({ themeId, favorite }) => {
|
||||
await queryClient.cancelQueries({ queryKey: KEY });
|
||||
const previous = queryClient.getQueryData<{ favorites: string[] }>(KEY);
|
||||
const current = previous?.favorites ?? [];
|
||||
queryClient.setQueryData(KEY, {
|
||||
favorites: favorite ? [...new Set([...current, themeId])] : current.filter((id) => id !== themeId),
|
||||
});
|
||||
return { previous };
|
||||
},
|
||||
// Put it back on failure. A star that stayed filled after the write was refused is worse than one that
|
||||
// never filled: it reports a preference the server does not hold.
|
||||
onError: (_err, _vars, context) => {
|
||||
if (context?.previous) queryClient.setQueryData(KEY, context.previous);
|
||||
},
|
||||
});
|
||||
|
||||
const favorites = new Set(query.data?.favorites ?? []);
|
||||
|
||||
return {
|
||||
favorites,
|
||||
isFavorite: (themeId: string) => favorites.has(themeId),
|
||||
toggle: (themeId: string) => toggle.mutate({ themeId, favorite: !favorites.has(themeId) }),
|
||||
};
|
||||
}
|
||||
@@ -38,6 +38,7 @@ export * from './chat-notification-prefs';
|
||||
export * from './nudges';
|
||||
export * from './ai-provider-usage';
|
||||
export * from './anthropic-accounts';
|
||||
export * from './theme-favorites';
|
||||
export * from './command-hq';
|
||||
export * from './dashboards';
|
||||
export * from './integrations';
|
||||
|
||||
@@ -35,6 +35,7 @@ export * from './chat-session-models/schema'; // chat_session_models
|
||||
export * from './chat-notification-prefs/schema'; // chat_notification_prefs
|
||||
export * from './ai-provider-usage/schema'; // ai_provider_usage — last usage reading per AI account
|
||||
export * from './anthropic-accounts/schema'; // anthropic_accounts — switchable OAuth credentials
|
||||
export * from './theme-favorites/schema'; // theme_favorites — starred themes, per account
|
||||
export * from './command-hq/schema'; // command_hq_categories, command_hq_sessions, command_hq_tags, command_hq_session_tags
|
||||
export * from './agent-panels/schema'; // agent_panels
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './schema';
|
||||
export * from './queries';
|
||||
@@ -0,0 +1,28 @@
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
import { db } from '../db';
|
||||
import { themeFavorites } from './schema';
|
||||
|
||||
/** The theme ids this account has starred. Order is not meaningful — the caller owns the ordering. */
|
||||
export async function listThemeFavorites(userId: number): Promise<string[]> {
|
||||
const rows = await db
|
||||
.select({ themeId: themeFavorites.themeId })
|
||||
.from(themeFavorites)
|
||||
.where(eq(themeFavorites.userId, userId));
|
||||
return rows.map((r) => r.themeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Star or unstar, returning the state it ended in.
|
||||
*
|
||||
* Idempotent in both directions on purpose: a double-tap, or two tabs racing, must not end with the star
|
||||
* in a state neither of them asked for. `onConflictDoNothing` makes the insert safe to repeat, and the
|
||||
* delete is naturally so.
|
||||
*/
|
||||
export async function setThemeFavorite(userId: number, themeId: string, favorite: boolean): Promise<boolean> {
|
||||
if (favorite) {
|
||||
await db.insert(themeFavorites).values({ userId, themeId }).onConflictDoNothing();
|
||||
return true;
|
||||
}
|
||||
await db.delete(themeFavorites).where(and(eq(themeFavorites.userId, userId), eq(themeFavorites.themeId, themeId)));
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { integer, pgTable, serial, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core';
|
||||
import { users } from '../auth/schema';
|
||||
|
||||
/**
|
||||
* Which themes an account has starred.
|
||||
*
|
||||
* ── Why a table, when a preference could be one JSON column ──
|
||||
*
|
||||
* Because it is per account and unbounded. `user_settings` would hold an array that grows with taste and
|
||||
* has to be read-modify-written by whoever toggles a star, and two tabs doing that at once lose one of the
|
||||
* stars. A row per favourite makes a toggle an INSERT or a DELETE, which cannot race with itself.
|
||||
*
|
||||
* ── Why the theme id is text with no foreign key ──
|
||||
*
|
||||
* Themes are not database rows. Most are compiled into the bundle; the rest are directories under
|
||||
* `platform/themes/` discovered at request time, so a theme can appear or vanish without anything writing
|
||||
* SQL. A foreign key would either be unenforceable or would make installing a theme a migration.
|
||||
*
|
||||
* The consequence is deliberate: a star can outlive its theme. That is why the reader intersects with the
|
||||
* live registry rather than trusting the table — a favourite naming a theme nobody has installed is
|
||||
* ignored, not shown as a broken entry, and it costs one row until the account unstars something.
|
||||
*/
|
||||
export const themeFavorites = pgTable(
|
||||
'theme_favorites',
|
||||
{
|
||||
id: serial('id').primaryKey(),
|
||||
userId: integer('user_id')
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
/** The theme's registry id — `duck-dark`, `catppuccin`. Not a foreign key; see above. */
|
||||
themeId: text('theme_id').notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
// uniqueIndex, never unique().on() — drizzle-kit re-creates named composite constraints on every push.
|
||||
// See src/databases/CLAUDE.md → "Composite keys".
|
||||
(table) => [uniqueIndex('uq_theme_favorites_user_theme').on(table.userId, table.themeId)],
|
||||
);
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { Context } from 'hono';
|
||||
import { listThemeFavorites, setThemeFavorite } from 'officerdb';
|
||||
import { createRouter } from '../../create-router';
|
||||
|
||||
/*
|
||||
Starred themes, per account.
|
||||
|
||||
── Why this is not on `/themes` ──
|
||||
|
||||
Because that prefix is deliberately UNAUTHENTICATED: the sign-in screen renders in the chosen theme, so
|
||||
the list and the stylesheets have to be readable before anyone has an account. A per-account preference on
|
||||
an anonymous prefix has no caller to attribute it to — the first version of this lived there and answered
|
||||
500 to an anonymous GET, which was the honest consequence arriving early.
|
||||
|
||||
── Why the `account` permission ──
|
||||
|
||||
It is `core`, so every account holds it and it cannot be denied, and it already owns `/user`, `/dock` and
|
||||
`/api-keys` — preferences and credentials belonging to the caller themselves. A theme favourite is the
|
||||
same shape as a dock preference: it grants nothing, it is about this account's own eyes, and denying it
|
||||
would only mean an account that can choose a theme cannot remember which ones it liked.
|
||||
|
||||
Every route here reads `user.id` from the token. None of them names an account, so there is nothing to get
|
||||
wrong about whose stars these are.
|
||||
*/
|
||||
export const themeFavoritesRouter = createRouter();
|
||||
|
||||
// GET /theme-favorites — this account's starred theme ids.
|
||||
themeFavoritesRouter.get('/', async (ctx: Context) => {
|
||||
const user = ctx.get('user');
|
||||
return ctx.json({ favorites: await listThemeFavorites(user.id) });
|
||||
});
|
||||
|
||||
// PUT /theme-favorites/:id — star or unstar one.
|
||||
//
|
||||
// PUT rather than POST because it SETS a state rather than appending: sending `{favorite:true}` twice ends
|
||||
// where sending it once does, which is what a double-tap and two racing tabs both need. The store is
|
||||
// idempotent in both directions for the same reason.
|
||||
themeFavoritesRouter.put('/:id', async (ctx: Context) => {
|
||||
const user = ctx.get('user');
|
||||
const themeId = ctx.req.param('id');
|
||||
const body = await ctx.req.json().catch(() => ({}) as Record<string, unknown>);
|
||||
const favorite = body.favorite !== false;
|
||||
return ctx.json({ themeId, favorite: await setThemeFavorite(user.id, themeId, favorite) });
|
||||
});
|
||||
@@ -5,6 +5,12 @@ import { discoverThemes, readThemeCss } from '../../themes/discover';
|
||||
/**
|
||||
* Installed themes — the ones in `platform/themes/`, not the ones the platform ships.
|
||||
*
|
||||
* **This prefix is UNAUTHENTICATED** (`UNPROTECTED_API_PREFIXES` in hono.ts) and must stay that way: the
|
||||
* sign-in screen paints in the chosen theme, before any account exists to ask. So nothing per-account can
|
||||
* live here — theme FAVOURITES are on `/theme-favorites`, behind the `account` permission, for exactly that
|
||||
* reason. Adding them here returned 500 on an anonymous request, which was the polite version of the
|
||||
* problem.
|
||||
*
|
||||
* The shipped themes are compiled into the bundle and need no server. These are read off disk at request
|
||||
* time, so dropping a directory in makes a theme appear on the next page load. No install step, no
|
||||
* rebuild, no restart — a theme is CSS custom properties, and none of that needs compiling.
|
||||
|
||||
@@ -6,6 +6,7 @@ import { authRouter } from './api/auth';
|
||||
import { serverSettingsRouter } from './api/server-settings/server-settings';
|
||||
import { landingPageDataRouter } from './api/landing-page-data/landing-page-data';
|
||||
import { themesRouter } from './api/themes/themes';
|
||||
import { themeFavoritesRouter } from './api/themes/favorites';
|
||||
import { waitlistRouter } from './api/waitlist/waitlist';
|
||||
import { usersRouter } from './api/users/users-router';
|
||||
import { apiKeysRouter } from './api/api-keys/router';
|
||||
@@ -122,6 +123,8 @@ const isDavPath = (path: string) =>
|
||||
// disambiguate. `/pipeline-jobs` and `/jobs` deliberately share one router.
|
||||
const PROTECTED_MOUNTS: [prefix: string, router: ReturnType<typeof createRouter>][] = [
|
||||
['/server-settings', serverSettingsRouter],
|
||||
// Protected, unlike `/themes` beside it — see api/themes/favorites.ts for why they are separate mounts.
|
||||
['/theme-favorites', themeFavoritesRouter],
|
||||
['/users', usersRouter],
|
||||
['/skills', skillsRouter],
|
||||
['/tasks', tasksRouter],
|
||||
|
||||
@@ -147,7 +147,10 @@ const CORE_REGISTRY: Permission[] = [
|
||||
// to present the authority the account already has, so denying it would only force the holder to keep
|
||||
// using a password in places a password should not go. What a key can then DO is decided by the same
|
||||
// permission checks as any other request from that user; nothing here widens them.
|
||||
api: ['/user', '/dock', '/api-keys'],
|
||||
// `/theme-favorites` sits here rather than on `/themes`, which is unauthenticated so the sign-in screen
|
||||
// can paint. A starred theme is the same shape as a dock preference: the caller's own taste, granting
|
||||
// nothing, and not a sensible thing to deny an account that can already choose a theme.
|
||||
api: ['/user', '/dock', '/api-keys', '/theme-favorites'],
|
||||
routes: ['/settings/profile'],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -9,3 +9,5 @@ export { useThemeAsset } from './useThemeAsset';
|
||||
export { useThemeKeys } from './useThemeKeys';
|
||||
export { THEMES, DEFAULT_THEME, findTheme, isKnownTheme, isDarkTheme, themeFromLegacyColorMode } from './themes';
|
||||
export type { Theme, ThemeId } from './themes';
|
||||
// Ordering helpers for the pickers — pure, and tested in rotate.test.ts.
|
||||
export { rotateToSelected, favouritesFirst, groupByFamily } from './rotate';
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { favouritesFirst, groupByFamily, rotateToSelected } from './rotate';
|
||||
|
||||
const ids = (list: Array<{ id: string }>) => list.map((t) => t.id);
|
||||
const list = [{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }];
|
||||
|
||||
describe('rotating to the selected theme', () => {
|
||||
test('puts the selected one first and wraps the rest behind it', () => {
|
||||
expect(ids(rotateToSelected(list, 'c'))).toEqual(['c', 'd', 'a', 'b']);
|
||||
});
|
||||
|
||||
// The property that makes this a rotation rather than a sort: nobody loses a neighbour.
|
||||
test('every adjacency survives, only the starting point moves', () => {
|
||||
const rotated = ids(rotateToSelected(list, 'c'));
|
||||
const doubled = [...ids(list), ...ids(list)].join(',');
|
||||
expect(doubled).toContain(rotated.join(','));
|
||||
});
|
||||
|
||||
test('leaves the order alone when the selected one is already first', () => {
|
||||
expect(ids(rotateToSelected(list, 'a'))).toEqual(['a', 'b', 'c', 'd']);
|
||||
});
|
||||
|
||||
// An id from an uninstalled theme, or none chosen yet. Rotating by a guess would be worse than not.
|
||||
test('leaves the order alone for an unknown or missing id', () => {
|
||||
expect(ids(rotateToSelected(list, 'gone'))).toEqual(['a', 'b', 'c', 'd']);
|
||||
expect(ids(rotateToSelected(list, undefined))).toEqual(['a', 'b', 'c', 'd']);
|
||||
});
|
||||
|
||||
test('does not mutate the input', () => {
|
||||
const original = [...ids(list)];
|
||||
rotateToSelected(list, 'd');
|
||||
expect(ids(list)).toEqual(original);
|
||||
});
|
||||
});
|
||||
|
||||
describe('favourites first', () => {
|
||||
test('lifts favourites, keeping the order within each half', () => {
|
||||
expect(ids(favouritesFirst(list, new Set(['d', 'b'])))).toEqual(['b', 'd', 'a', 'c']);
|
||||
});
|
||||
|
||||
test('changes nothing when there are none', () => {
|
||||
expect(ids(favouritesFirst(list, new Set()))).toEqual(['a', 'b', 'c', 'd']);
|
||||
});
|
||||
|
||||
// Composed with the rotation: the theme you are wearing leads its half.
|
||||
test('composes with the rotation', () => {
|
||||
expect(ids(favouritesFirst(rotateToSelected(list, 'c'), new Set(['c', 'a'])))).toEqual(['c', 'a', 'd', 'b']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('grouping by family', () => {
|
||||
const themed = [
|
||||
{ id: 'duck-dark', name: 'Duck Dark', family: 'Duck' },
|
||||
{ id: 'cat', name: 'Catppuccin', family: 'Catppuccin' },
|
||||
{ id: 'duck-light', name: 'Duck Light', family: 'Duck' },
|
||||
] as never as Parameters<typeof groupByFamily>[0];
|
||||
|
||||
test('keeps families in first-seen order, so a rotation decides them', () => {
|
||||
expect(groupByFamily(themed).map(([family]) => family)).toEqual(['Duck', 'Catppuccin']);
|
||||
});
|
||||
|
||||
// Members of a family separated by the rotation still collect together — the alternative is the same
|
||||
// family heading appearing twice.
|
||||
test('collects a family split by the rotation', () => {
|
||||
const groups = groupByFamily(themed);
|
||||
expect(groups[0]![1].map((t) => t.id)).toEqual(['duck-dark', 'duck-light']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Theme, ThemeId } from './themes';
|
||||
|
||||
/**
|
||||
* The theme list, rotated so the one you are wearing is first.
|
||||
*
|
||||
* With 200+ themes the list is far taller than any container, and the theme you have on is the anchor for
|
||||
* every decision you are about to make — "what did I just come from", "what is next to this". Sorting the
|
||||
* selected one to the top would answer the first question and destroy the second, because it takes that
|
||||
* theme out of its family and leaves a hole where it was.
|
||||
*
|
||||
* A ROTATION keeps every neighbour: the order is unchanged, the starting point moves. Duck Dark's
|
||||
* neighbours are still Duck Light and whatever followed it; they have simply wrapped around behind you.
|
||||
*
|
||||
* The registry order is the ordering to preserve — families sit together in it, and that grouping is the
|
||||
* only structure a list of two hundred names has.
|
||||
*/
|
||||
export function rotateToSelected<T extends { id: ThemeId }>(list: readonly T[], selected: ThemeId | undefined): T[] {
|
||||
if (!selected) return [...list];
|
||||
const at = list.findIndex((entry) => entry.id === selected);
|
||||
// Not present: an id from a theme that has been uninstalled, or none set yet. Leave the order alone
|
||||
// rather than rotate by a guess.
|
||||
if (at <= 0) return [...list];
|
||||
return [...list.slice(at), ...list.slice(0, at)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Favourites first, then everything else — each half keeping the rotation it was given.
|
||||
*
|
||||
* Two-tier rather than a filter, because hiding the rest makes the list unable to answer "what else is
|
||||
* there". A filter is a separate, explicit act; this is the default shape.
|
||||
*/
|
||||
export function favouritesFirst<T extends { id: ThemeId }>(list: readonly T[], favourites: ReadonlySet<ThemeId>): T[] {
|
||||
if (favourites.size === 0) return [...list];
|
||||
const starred: T[] = [];
|
||||
const rest: T[] = [];
|
||||
for (const entry of list) (favourites.has(entry.id) ? starred : rest).push(entry);
|
||||
return [...starred, ...rest];
|
||||
}
|
||||
|
||||
/** Grouped by family for the dropdown, over an already-ordered list. Families appear in first-seen order. */
|
||||
export function groupByFamily(list: readonly Theme[]): Array<[string, Theme[]]> {
|
||||
const groups = new Map<string, Theme[]>();
|
||||
for (const theme of list) {
|
||||
const existing = groups.get(theme.family);
|
||||
if (existing) existing.push(theme);
|
||||
else groups.set(theme.family, [theme]);
|
||||
}
|
||||
return [...groups.entries()];
|
||||
}
|
||||
Reference in New Issue
Block a user