Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(theme): Night Shift sign-in art, and Halloween that removes cleanly

naveenkashbb53b488e25a
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 33e7fb8509..68fc992aa8 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -4029,3 +4029,13 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Rule:** When a posting must ignore a line, filter it where every per-line collection is built, not only in the loop that writes the ledger. List every map or array derived from the lines and check each. Pin the skipped line's absence in a test: assert the side effects did not happen, not only that the ledger row is missing.
**Applies to:** `postReceipt` / `postShipment` and every posting in `inventory.service.ts` that builds update maps before its write loop.
+
+## A temporary override lives in the thing it overrides, not in its callers
+
+**Context:** Halloween had to be the theme for everyone while in season (2026-10). The first cut replaced the cookie read in all three apps' `getTheme` (`services/theme.server.ts`) with `resolveTheme(halloweenTheme.name)`.
+
+**Problem:** Undoing it meant rewriting three deleted cookie reads from memory, and nothing pointed at them: deleting `halloween-theme.ts` would just break the imports. The mesh colors in `MeshGradientBackground.tsx` (a `Record<string, …>`, so no compile error) and a test that imported the theme directly had the same shape. The removal checklist went stale twice as pieces were added.
+
+**Rule:** Put a seasonal or temporary behaviour on the removable unit itself (`forced`, `mesh` on the `SeasonalTheme`, read by the shared resolver) and keep callers generic, so deleting the unit turns the behaviour off. Test the mechanism on a fixture, not on the instance. Keep ONE removal checklist, next to the code, and make every other comment point to it.
+
+**Applies to:** `packages/utils/src/themes.ts` seasonal themes, `packages/react/src/Halloween/`, any feature flag, promo or seasonal UI.
diff --git a/.claude/rules/coding-conventions.md b/.claude/rules/coding-conventions.md
index 9c5c62a2f6..085c6f47b0 100644
--- a/.claude/rules/coding-conventions.md
+++ b/.claude/rules/coding-conventions.md
@@ -226,10 +226,10 @@ variables (`--primary`, `--background`, `--foreground`, `--card`, `--popover`,
The choice is a `theme` cookie per browser, never a database column. Each app's
`getTheme` (`services/theme.server.ts`) resolves through `resolveTheme`, which
returns the default for a name no longer in `themes`, so removing a theme
-needs no migration and breaks no browser that still holds it. **For now
-`getTheme` ignores the cookie** and renders `halloween` for everyone while it
-is in season (the default outside its window); the pickers still write the
-cookie, which takes effect again once `getTheme` reads it.
+needs no migration and breaks no browser that still holds it. A seasonal
+theme marked `forced` wins over any stored name while in season, so every
+browser renders it; the pickers still write the cookie, and it takes effect
+again once the season ends.
A seasonal theme lives in `seasonalThemes`, not `themes`, and carries an
`available` window (`ThemeWindow`, month and day, inside one calendar year).
@@ -241,8 +241,12 @@ Account settings → Appearance lists `selectableThemes()`, the everyday themes
plus any seasonal one in its window. Outside the window `themeColorValidator`
refuses it and `resolveTheme` (which every app's `Document` renders from)
falls back to the default. A seasonal theme lives in its own file
-(`halloween-theme.ts`) so removing it is that file, its `seasonalThemes`
-entry, its `index.ts` export and its `MeshGradientBackground` colors.
+(`halloween-theme.ts`) and declares everything about itself on the
+`SeasonalTheme` object (`forced`, its `mesh` colors, read through
+`seasonalMeshColors`), so no other code names it: removing it is that file,
+its `seasonalThemes` entry and its `index.ts` export. `themes.test.ts` tests
+the window on a fixture and loops over `seasonalThemes`, so it survives the
+removal unchanged.
The Halloween decorations (spider, bats, fog, witch on the loading bar, hat,
Oct 31 date marker, the "boo" ghost) live in `packages/react/src/Halloween/`,
@@ -252,4 +256,22 @@ exported as `@carbon/react/Halloween` and mounted once in each shell
`halloween` — so nothing renders, styles or listens for anyone else. The
stylesheet hangs off `data-user-menu` (ERP avatar trigger), `data-date`
(calendar cells) and `data-app-card` (MES page card); those attributes do
-nothing on their own and may stay when the folder is deleted.
+nothing on their own and may stay when the folder is deleted. **The removal
+checklist** (theme plus decorations) is the header of
+`packages/react/src/Halloween/HalloweenLayer.tsx`: the folder and its
+export, three mounts, the theme file with its two registrations, then
+`lingui:extract`.
+
+The sign-in page's left panel (`_public+/_layout.tsx`) shows the Night Shift
+while in season: `<HalloweenLoginArt />`, an ASCII story on a canvas
+(`packages/react/src/Halloween/night-shift/`), lazy-loaded behind
+`useHalloween`. It brings its own headline scrim and forces the panel it
+fills `dark` from an effect, so the layout holds one line. A haunted plant works one
+90-second shift (`ACTS` in `story.ts`) making a jack-o'-lantern; each shift
+is seeded (`planShift`: face, weather, visitor, moon phase, a rare event),
+shipped lanterns stay on the hill, and thirteen rise as the Carbon mark. The
+shift index lives in sessionStorage (`carbon:night-shift`) so a revisit
+continues the story. Everything a frame shows is a pure function of the
+moment (`renderFrame`), pinned by `frame.test.ts` across panel sizes; the
+cast reacts to the form (focus, secret fields, submit, error toasts) through
+DOM events only.
diff --git a/apps/erp/app/components/MeshGradientBackground.tsx b/apps/erp/app/components/MeshGradientBackground.tsx
index 047a073bae..2f8a9e688f 100644
--- a/apps/erp/app/components/MeshGradientBackground.tsx
+++ b/apps/erp/app/components/MeshGradientBackground.tsx
@@ -3,6 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { cn, useMode } from "@carbon/react";
+import { seasonalMeshColors } from "@carbon/utils";
import { MeshGradient } from "@paper-design/shaders-react";
import { useEffect, useState } from "react";
import { useTheme } from "~/hooks/useTheme";
@@ -47,17 +48,16 @@ const meshColorsByTheme: Record<
violet: {
light: ["#f3f0fe", "#f7f5fe", "#fbfaff", "#f5f2fe"],
dark: ["#1e0a2d", "#000000", "#0D0D0D", "#050505"]
- },
- // Seasonal: remove with packages/utils/src/halloween-theme.ts.
- halloween: {
- light: ["#fdf0e4", "#f6f0fa", "#fffaf5", "#fbefe6"],
- dark: ["#2d1205", "#14081f", "#0D0D0D", "#050505"]
}
};
-export function getMeshColors(theme: string, mode: string) {
- const colors = meshColorsByTheme[theme] ?? meshColorsByTheme.blue;
- return mode === "light" ? colors.light : colors.dark;
+export function getMeshColors(theme: string, mode: string): string[] {
+ // A seasonal theme carries its own colors (`seasonalMeshColors`).
+ const colors =
+ meshColorsByTheme[theme] ??
+ seasonalMeshColors(theme) ??
+ meshColorsByTheme.blue;
+ return [...(mode === "light" ? colors.light : colors.dark)];
}
export function getMeshBackgroundGradient(theme: string, mode: string) {
diff --git a/apps/erp/app/routes/_public+/_layout.tsx b/apps/erp/app/routes/_public+/_layout.tsx
index eae56da50e..f5afe409bc 100644
--- a/apps/erp/app/routes/_public+/_layout.tsx
+++ b/apps/erp/app/routes/_public+/_layout.tsx
@@ -4,6 +4,7 @@
import { CONTROLLED_ENVIRONMENT } from "@carbon/auth";
import { cn, Heading, TooltipProvider } from "@carbon/react";
+import { HalloweenLoginArt } from "@carbon/react/Halloween";
import { Trans } from "@lingui/react/macro";
import { Outlet } from "react-router";
@@ -12,11 +13,13 @@ export default function PublicRoute() {
<TooltipProvider>
<div className="container relative h-full flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0 bg-card">
<div className="relative hidden h-full flex-col bg-muted p-10 lg:flex dark:border-r dark:bg-zinc-900 bg-zinc-100">
+ {/* Seasonal: shows only with the Halloween theme. */}
+ <HalloweenLoginArt />
<img
src="/carbon-word-light.svg"
alt="Carbon Logo"
className={cn(
- "max-w-[200px] mb-3 dark:hidden z-50",
+ "relative max-w-[200px] mb-3 dark:hidden z-50",
CONTROLLED_ENVIRONMENT && "grayscale"
)}
/>
@@ -24,7 +27,7 @@ export default function PublicRoute() {
src="/carbon-word-dark.svg"
alt="Carbon Logo"
className={cn(
- "max-w-[200px] mb-3 dark:block hidden z-50",
+ "relative max-w-[200px] mb-3 dark:block hidden z-50",
CONTROLLED_ENVIRONMENT && "grayscale"
)}
/>
diff --git a/apps/erp/app/services/theme.server.ts b/apps/erp/app/services/theme.server.ts
index be28525550..a4264e7a37 100644
--- a/apps/erp/app/services/theme.server.ts
+++ b/apps/erp/app/services/theme.server.ts
@@ -4,17 +4,19 @@
import { DOMAIN, getCookieDomain } from "@carbon/auth";
import type { ThemeName } from "@carbon/utils";
-import { halloweenTheme, resolveTheme } from "@carbon/utils";
+import { resolveTheme } from "@carbon/utils";
import * as cookie from "cookie";
const cookieName = "theme";
/**
- * The theme to render: Halloween for everyone while it is in season, whatever
- * the cookie holds; the default outside its window.
+ * The theme to render: the cookie's, unless a seasonal theme is forced, or
+ * the default when it names none we offer now (`resolveTheme`).
*/
-export function getTheme(_request: Request): ThemeName {
- return resolveTheme(halloweenTheme.name).name;
+export function getTheme(request: Request): ThemeName {
+ const cookieHeader = request.headers.get("cookie");
+ const stored = cookieHeader ? cookie.parse(cookieHeader)[cookieName] : null;
+ return resolveTheme(stored).name;
}
export function setTheme(theme: string) {
diff --git a/apps/mes/app/services/theme.server.ts b/apps/mes/app/services/theme.server.ts
index 38122bcdce..93840d7ad8 100644
--- a/apps/mes/app/services/theme.server.ts
+++ b/apps/mes/app/services/theme.server.ts
@@ -4,17 +4,19 @@
import { DOMAIN, getCookieDomain } from "@carbon/auth";
import type { ThemeName } from "@carbon/utils";
-import { halloweenTheme, resolveTheme } from "@carbon/utils";
+import { resolveTheme } from "@carbon/utils";
import * as cookie from "cookie";
const cookieName = "theme";
/**
- * The theme to render: Halloween for everyone while it is in season, whatever
- * the cookie holds; the default outside its window.
+ * The theme to render: the cookie's, unless a seasonal theme is forced, or
+ * the default when it names none we offer now (`resolveTheme`).
*/
-export function getTheme(_request: Request): ThemeName {
- return resolveTheme(halloweenTheme.name).name;
+export function getTheme(request: Request): ThemeName {
+ const cookieHeader = request.headers.get("cookie");
+ const stored = cookieHeader ? cookie.parse(cookieHeader)[cookieName] : null;
+ return resolveTheme(stored).name;
}
export function setTheme(theme: string) {
diff --git a/apps/starter/app/services/theme.server.ts b/apps/starter/app/services/theme.server.ts
index 3a3f9c54ea..a78da01919 100644
--- a/apps/starter/app/services/theme.server.ts
+++ b/apps/starter/app/services/theme.server.ts
@@ -3,17 +3,19 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import type { ThemeName } from "@carbon/utils";
-import { halloweenTheme, resolveTheme } from "@carbon/utils";
+import { resolveTheme } from "@carbon/utils";
import * as cookie from "cookie";
const cookieName = "theme";
/**
- * The theme to render: Halloween for everyone while it is in season, whatever
- * the cookie holds; the default outside its window.
+ * The theme to render: the cookie's, unless a seasonal theme is forced, or
+ * the default when it names none we offer now (`resolveTheme`).
*/
-export function getTheme(_request: Request): ThemeName {
- return resolveTheme(halloweenTheme.name).name;
+export function getTheme(request: Request): ThemeName {
+ const cookieHeader = request.headers.get("cookie");
+ const stored = cookieHeader ? cookie.parse(cookieHeader)[cookieName] : null;
+ return resolveTheme(stored).name;
}
export function setTheme(theme: string) {
diff --git a/packages/account/AGENTS.md b/packages/account/AGENTS.md
index 38a37a4d19..01445f4770 100644
--- a/packages/account/AGENTS.md
+++ b/packages/account/AGENTS.md
@@ -28,6 +28,8 @@ and the starter. Each app mounts it once in its shell; it opens over any page.
root action (`/`), which every app's `root.tsx` handles (`modeValidator` /
`themeColorValidator` from `@carbon/utils`). `useOptimisticMode` only counts a `/`
submission carrying `mode`, so the two never read each other's in-flight value.
+ The theme grid lists `selectableThemes()`: the everyday themes plus any seasonal one in its
+ window. While a `forced` seasonal theme is in season it renders whatever is picked here.
- Panes read with `useLoaderQuery` (`@carbon/query`), so the host app needs a
`QueryClientProvider`, `window.clientCache` and `createInvalidationMiddleware` in its root.
Strings use Lingui macros, so it also needs a `LocaleProvider`; the package is in the erp
diff --git a/packages/react/AGENTS.md b/packages/react/AGENTS.md
index 80ddbcde91..38c15f4f27 100644
--- a/packages/react/AGENTS.md
+++ b/packages/react/AGENTS.md
@@ -51,6 +51,7 @@ import { Button, Card, HStack, VStack, IconButton, cn } from "@carbon/react";
- **Error boundary**: `@carbon/react/ErrorBoundary` — `RouteErrorBoundary` (exported as `ErrorBoundary` from a module layout so a failed loader shows inside the app shell; it shows the status code and, for a 4xx, the message the server threw — `routeErrorCopy` — so throw a `Response` whose body says what was wrong. A 5xx or thrown `Error` gets generic copy) and `RootErrorBoundary` (drop-in root `ErrorBoundary` for RR v7 that maps 404 / 503 (the maintenance screen) / other HTTP / thrown `Error` to a styled screen) plus its parts (`ErrorScreen`, `GlitchHeading`, `StatusReadout`, `MagneticLink`, `NoiseOverlay`). Both read a request that got no response (`isNetworkError`: a `TypeError` with one of the browsers' fetch-failure messages) as a lost connection, not a fault, and `useNetworkRetry` revalidates when the browser is back online or the tab is shown again, which clears the error. Wrap it in the app's `Document` and pass `env` so `window.env` is set (the client crashes hydration otherwise). Copy is intentionally hardcoded English, not i18n.
- **Avatar**: `src` may be a URL or a generated-avatar value from `user.avatarUrl` (`dicebear:<style>:<seed>[:<rrggbb>]`; the styles and value helpers are in `@carbon/utils` `avatar.ts`). A generated value renders as a plain `<img>` of `generatedAvatarUrl(value)` (`utils/generatedAvatarImage.ts`, which `Avatar` imports instead of the renderer so no bundle that shows an avatar carries DiceBear) — `/file/avatar/:value?v=<GENERATED_AVATAR_RENDER_VERSION>` — so it is in the server-rendered HTML and needs no client JavaScript. Every app (ERP, MES, academy) serves that path with a one-line route re-exporting `generatedAvatarLoader` from `@carbon/react/GeneratedAvatar`: it draws the SVG on the server with DiceBear 10 and answers `Cache-Control: public, max-age=31536000, immutable`, so a refresh reads it from the browser cache. **Bump `GENERATED_AVATAR_RENDER_VERSION` whenever the same value would draw differently** (a DiceBear upgrade, a change to the rendering options), or browsers keep the old image. The avatar picker draws in the browser instead (`GeneratedAvatarPreview`, `useGeneratedAvatar`), because a color drag makes a new value per step; there the DiceBear core and each style's JSON load with `import()` (`STYLE_LOADERS`, typed `Record<GeneratedAvatarStyle, …>`), never with a `with: { type: "json" }` attribute (Vite passes it to the browser, which rejects the JSON Vite serves as JavaScript, and the picker stays grey); the server side instead bundles `@dicebear/styles` through `ssrNoExternal` in each app's `vite.config.ts`, because Node refuses a package's JSON without the attribute. `generatedAvatarClassName(style)` picks the image classes: line-art styles on white (`bg-white`) in both themes, color styles on `bg-muted`. A value's optional background goes to DiceBear as `backgroundColor`; on a dark one (`isDarkBackground`, WCAG contrast) the styles that draw lines straight onto the background (`INK_OPTIONS`) get white ink. The app `Avatar` wrappers turn a stored value into `src` with `avatarSrc` (`@carbon/utils`); a new user has no avatar (initials) until they choose one
- **Announcement**: `AnnouncementBar` is the one-line bar both shells render above their page area for the deployment's announcement. It remembers a dismissal in localStorage per user and announcement id, and while shown sets `--announcement-height` on `<html>`; the ERP's `--content-inset` includes it, and a page sized from `100dvh` outside that variable must subtract it
+- **Seasonal decorations**: `@carbon/react/Halloween` exports `HalloweenLayer` (mounted once in each app shell) and `HalloweenLoginArt` (the ERP sign-in panel's ASCII story, `src/Halloween/night-shift/`). Both render nothing unless the root loader's theme is `halloween`. Keep everything seasonal inside that folder: the removal checklist is the header of `src/Halloween/HalloweenLayer.tsx`
- **Polish**: shadows over borders, `tabular-nums` for dynamic numbers, `active:scale-[0.98]` on pressables, `text-balance`/`text-pretty` for text wrapping
## Cross-References
diff --git a/packages/react/src/Halloween/HalloweenLayer.tsx b/packages/react/src/Halloween/HalloweenLayer.tsx
index 10b3a8c619..0429f74fa9 100644
--- a/packages/react/src/Halloween/HalloweenLayer.tsx
+++ b/packages/react/src/Halloween/HalloweenLayer.tsx
@@ -3,7 +3,14 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { AnimatePresence } from "motion/react";
-import { lazy, Suspense, useCallback, useState } from "react";
+import {
+ lazy,
+ Suspense,
+ useCallback,
+ useEffect,
+ useRef,
+ useState
+} from "react";
import { createPortal } from "react-dom";
import { BarSpider } from "./BarSpider";
import { BooGhost } from "./Ghost";
@@ -12,16 +19,26 @@ import { useHalloween } from "./season";
import { BatFlyby, SuccessBats } from "./Visitors";
// Seasonal decoration, shared by the ERP and the MES (`@carbon/react/Halloween`).
-// Everything renders only while the user has the Halloween theme on
-// (`useHalloween`, season.ts); for everyone else this returns nothing.
+// Everything renders only while the Halloween theme is on (`useHalloween`,
+// season.ts); for everyone else this returns nothing.
//
-// To remove it: delete this folder, the `./Halloween` export in
-// packages/react/package.json and the `<HalloweenLayer />` mount in each app
-// shell (ERP routes/x+/_layout.tsx, MES routes/x+/_layout.tsx). The
-// `data-user-menu` and `data-date` attributes it styles do nothing on their
-// own and can stay.
+// To remove Halloween, the theme and every decoration:
+// 1. Delete this folder and the `./Halloween` export in
+// packages/react/package.json.
+// 2. Delete the three mounts and their imports: `<HalloweenLayer />` in the
+// ERP's and the MES's routes/x+/_layout.tsx, `<HalloweenLoginArt />` in
+// the ERP's routes/_public+/_layout.tsx.
+// 3. Delete packages/utils/src/halloween-theme.ts, its export in
+// packages/utils/src/index.ts and its entry in `seasonalThemes`
+// (packages/utils/src/themes.ts). The theme carries everything else
+// (forced for everyone, its mesh colors), so nothing reads it by name.
+// 4. Run `pnpm run lingui:extract` to drop its strings from the catalogs.
+// Typecheck flags any mount or import left behind. The `data-user-menu`,
+// `data-date` and `data-app-card` attributes the styles hang off, and
+// `relative` on the sign-in logos, do nothing on their own and can stay.
const loadReveal = () => import("./HalloweenReveal");
+const NightShift = lazy(() => import("./night-shift/NightShift"));
const HalloweenReveal = lazy(loadReveal);
function preloadReveal() {
@@ -34,6 +51,43 @@ export function HalloweenLayer() {
return <Decorations />;
}
+/**
+ * The Night Shift, the ASCII story on the sign-in page's left panel. Fills
+ * its positioned parent; the engine loads only while the theme is on.
+ */
+export function HalloweenLoginArt() {
+ const on = useHalloween();
+ if (!on) return null;
+ return <LoginArt />;
+}
+
+function LoginArt() {
+ const ref = useRef<HTMLDivElement>(null);
+
+ // The scene is night in either mode, so the panel it fills goes dark: its
+ // logo and headline take their dark variants. Undone on unmount.
+ useEffect(() => {
+ const panel = ref.current?.parentElement;
+ if (!panel || panel.classList.contains("dark")) return;
+ panel.classList.add("dark");
+ return () => panel.classList.remove("dark");
+ }, []);
+
+ return (
+ <div
+ ref={ref}
+ aria-hidden
+ className="pointer-events-none absolute inset-0 overflow-hidden"
+ >
+ <Suspense fallback={null}>
+ <NightShift />
+ </Suspense>
+ {/* Keeps the panel's headline readable over the fog. */}
+ <div className="absolute inset-x-0 bottom-0 z-10 h-64 bg-gradient-to-t from-black/75 via-black/40 to-transparent" />
+ </div>
+ );
+}
+
function Decorations() {
const [revealOpen, setRevealOpen] = useState(false);
const open = useCallback(() => setRevealOpen(true), []);
diff --git a/packages/react/src/Halloween/night-shift/NightShift.tsx b/packages/react/src/Halloween/night-shift/NightShift.tsx
new file mode 100644
index 0000000000..21d1fdc97a
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/NightShift.tsx
@@ -0,0 +1,261 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The Night Shift on a canvas: fills its positioned parent, runs at 24 fps,
+// pauses with the tab, and watches the sign-in form so the cast can react.
+// The story resumes from the next shift on the next visit in the same
+// browser session, so the hill keeps the lanterns it has earned.
+
+import { useEffect, useRef } from "react";
+import type { Buffers } from "./frame";
+import { makeBuffers, renderFrame } from "./frame";
+import type { Layout } from "./layout";
+import { makeLayout } from "./layout";
+import type { Metrics } from "./paint";
+import { paint } from "./paint";
+import type { Watcher } from "./scene";
+import { IDLE_WATCHER } from "./scene";
+import type { Moment, ShiftPlan } from "./story";
+import { actStart, momentAt, planShift } from "./story";
+
+const FONT_FAMILY =
+ '"Geist Mono Variable", "Geist Mono", ui-monospace, SFMono-Regular, Menlo, monospace';
+/** Glyph size grows with the panel, so the scene fills it at any width. */
+function fontFor(width: number) {
+ const px = Math.max(12, Math.min(16, width / 52));
+ return { px, line: Math.trunc(px * 1.17 + 0.5) };
+}
+const FPS = 24;
+const SESSION_KEY = "carbon:night-shift";
+
+type Saved = { seed: number; shift: number };
+
+function readSaved(): Saved {
+ try {
+ const raw = window.sessionStorage.getItem(SESSION_KEY);
+ if (raw) {
+ const value: unknown = JSON.parse(raw);
+ if (
+ value &&
+ typeof value === "object" &&
+ "seed" in value &&
+ "shift" in value &&
+ typeof value.seed === "number" &&
+ typeof value.shift === "number"
+ ) {
+ return { seed: value.seed, shift: value.shift };
+ }
+ }
+ } catch {
+ // Storage can be off (private mode); the story just starts over.
+ }
+ const seed = window.crypto.getRandomValues(new Uint32Array(1))[0] ?? 1;
+ return { seed, shift: 0 };
+}
+
+function writeSaved(saved: Saved) {
+ try {
+ window.sessionStorage.setItem(SESSION_KEY, JSON.stringify(saved));
+ } catch {
+ // Not saved: the next visit starts a new story.
+ }
+}
+
+/** The one frame shown to someone who prefers reduced motion. */
+function stillMoment(shift: number): Moment {
+ // Late in Shipping: the procession lit, the ghost out, the door open.
+ return momentAt(actStart("shipping") + 14, shift);
+}
+
+function fade(sinceSeconds: number, lasts: number) {
+ if (sinceSeconds < 0 || sinceSeconds > lasts) return 0;
+ return 1 - sinceSeconds / lasts;
+}
+
+function readFocus(watcher: Watcher) {
+ const active = document.activeElement;
+ watcher.field = false;
+ watcher.secret = false;
+ watcher.peek = false;
+ if (
+ !(
+ active instanceof HTMLInputElement ||
+ active instanceof HTMLTextAreaElement
+ )
+ )
+ return;
+ const hidden =
+ active instanceof HTMLInputElement && active.type === "password";
+ const named =
+ /\b(password|otp|code|pin)\b/i.test(active.name) ||
+ active.autocomplete === "one-time-code";
+ watcher.secret = hidden || named;
+ watcher.peek =
+ !hidden &&
+ active instanceof HTMLInputElement &&
+ active.type === "text" &&
+ /password/i.test(active.name);
+ watcher.field = !watcher.secret;
+}
+
+const ERROR_TOAST = '[data-sonner-toast][data-type="error"]';
+
+export default function NightShift() {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ const ctx = canvas?.getContext("2d");
+ const host = canvas?.parentElement;
+ if (!canvas || !ctx || !host) return;
+
+ const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+ const saved = readSaved();
+ writeSaved({ seed: saved.seed, shift: saved.shift + 1 });
+ const plans = new Map<number, ShiftPlan>();
+ const planFor = (index: number) => {
+ let plan = plans.get(index);
+ if (!plan) {
+ plan = planShift(saved.seed, index);
+ plans.set(index, plan);
+ }
+ return plan;
+ };
+
+ const watcher: Watcher = { ...IDLE_WATCHER };
+ let layout: Layout | null = null;
+ let buffers: Buffers | null = null;
+ let metrics: Metrics | null = null;
+ let clock = 0;
+ let last = performance.now();
+ let lastShift = saved.shift;
+ let flareAt = Number.NEGATIVE_INFINITY;
+ let alarmAt = Number.NEGATIVE_INFINITY;
+ let disposed = false;
+ let frameId = 0;
+
+ const measure = () => {
+ const { width, height } = host.getBoundingClientRect();
+ if (width <= 0 || height <= 0) return;
+ const ratio = Math.min(2, window.devicePixelRatio || 1);
+ canvas.width = Math.trunc(width * ratio);
+ canvas.height = Math.trunc(height * ratio);
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ const size = fontFor(width);
+ const font = `${size.px}px ${FONT_FAMILY}`;
+ ctx.font = font;
+ const cellWidth = ctx.measureText("M".repeat(100)).width / 100;
+ const cols = Math.trunc(width / cellWidth);
+ const rows = Math.trunc(height / size.line);
+ layout = makeLayout(cols, rows, size.line / cellWidth);
+ buffers = makeBuffers(cols, rows);
+ metrics = {
+ cellWidth,
+ cellHeight: size.line,
+ offsetX: (width - cols * cellWidth) / 2,
+ offsetY: (height - rows * size.line) / 2,
+ font,
+ width,
+ height,
+ horizonRow: layout.horizon
+ };
+ };
+
+ const draw = () => {
+ if (!layout || !buffers || !metrics) return;
+ const moment = still
+ ? stillMoment(saved.shift)
+ : momentAt(clock, saved.shift);
+ if (moment.shift !== lastShift) {
+ lastShift = moment.shift;
+ writeSaved({ seed: saved.seed, shift: moment.shift + 1 });
+ }
+ readFocus(watcher);
+ watcher.flare = fade(clock - flareAt, 1.4);
+ watcher.alarm = fade(clock - alarmAt, 2.4);
+ const frame = renderFrame(
+ buffers,
+ layout,
+ planFor(moment.shift),
+ moment,
+ clock,
+ watcher
+ );
+ paint(ctx, buffers.main, frame, metrics);
+ };
+
+ const tick = (now: number) => {
+ if (disposed) return;
+ frameId = window.requestAnimationFrame(tick);
+ const delta = now - last;
+ if (delta < 1000 / FPS - 2) return;
+ last = now;
+ // A hidden tab gets no frames; pick the story up where it was.
+ clock += Math.min(delta, 250) / 1000;
+ draw();
+ };
+
+ const redraw = () => {
+ measure();
+ draw();
+ };
+ redraw();
+ void document.fonts?.load(`14px ${FONT_FAMILY}`).then(() => {
+ if (!disposed) redraw();
+ });
+ const resize = new ResizeObserver(redraw);
+ resize.observe(host);
+ if (!still) frameId = window.requestAnimationFrame(tick);
+
+ const onPointer = (event: PointerEvent) => {
+ if (!metrics) return;
+ const rect = canvas.getBoundingClientRect();
+ watcher.pointer = {
+ x: (event.clientX - rect.left - metrics.offsetX) / metrics.cellWidth,
+ y: (event.clientY - rect.top - metrics.offsetY) / metrics.cellHeight
+ };
+ };
+ const onLeave = () => {
+ watcher.pointer = null;
+ };
+ const onSubmit = () => {
+ flareAt = clock;
+ };
+ const toasts = new MutationObserver((records) => {
+ for (const record of records) {
+ for (const node of record.addedNodes) {
+ if (
+ node instanceof Element &&
+ (node.matches(ERROR_TOAST) || node.querySelector(ERROR_TOAST))
+ ) {
+ alarmAt = clock;
+ return;
+ }
+ }
+ }
+ });
+ toasts.observe(document.body, { childList: true, subtree: true });
+ window.addEventListener("pointermove", onPointer, { passive: true });
+ document.documentElement.addEventListener("pointerleave", onLeave);
+ document.addEventListener("submit", onSubmit, true);
+
+ return () => {
+ disposed = true;
+ window.cancelAnimationFrame(frameId);
+ resize.disconnect();
+ toasts.disconnect();
+ window.removeEventListener("pointermove", onPointer);
+ document.documentElement.removeEventListener("pointerleave", onLeave);
+ document.removeEventListener("submit", onSubmit, true);
+ };
+ }, []);
+
+ return (
+ <canvas
+ ref={canvasRef}
+ aria-hidden
+ className="absolute inset-0 h-full w-full"
+ />
+ );
+}
diff --git a/packages/react/src/Halloween/night-shift/exterior.ts b/packages/react/src/Halloween/night-shift/exterior.ts
new file mode 100644
index 0000000000..5646a478ff
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/exterior.ts
@@ -0,0 +1,1097 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The hill at night: sky, moon, the plant with its clock tower and crane, the
+// graveyard, the fence with its cat and crow, the lantern procession and the
+// pumpkin patch, plus whoever visits this shift. Everything here is drawn
+// from the moment alone, so any instant of the story can be rendered cold.
+
+import { GROUND, HILL, NIGHT, SILHOUETTE } from "../scene-palette";
+import type { Face } from "./faces";
+import type { Color } from "./grid";
+import { hex, mix, NO_BG, scale, spriteWidth } from "./grid";
+import { lanternSlot, pointAlong } from "./layout";
+import { fbm2, flicker, noise2 } from "./noise";
+import { drawLantern, drawPumpkin } from "./pumpkin";
+import type { Scene } from "./scene";
+import {
+ clamp01,
+ ease,
+ fraction,
+ hash01,
+ lerp,
+ nearest,
+ segment
+} from "./scene";
+import {
+ BAT,
+ BOO,
+ CAT,
+ CLOCK,
+ CROW,
+ GHOST,
+ HORSEMAN,
+ MARK_EDGES,
+ MARK_STARS,
+ SHIP,
+ SKELETON,
+ SPIDER,
+ STONES,
+ WITCH
+} from "./sprites";
+import { ACTS, actStart, LANTERNS_FOR_LIGHTING } from "./story";
+
+export const SKY_TOP = hex(NIGHT);
+export const SKY_HORIZON = hex("#1d1233");
+export const DAWN_TOP = hex("#191628");
+export const DAWN_HORIZON = hex("#5d4a68");
+const SILHOUETTE_BG = hex(SILHOUETTE);
+const GROUND_BG = hex(GROUND);
+const HILL_BG = hex(HILL);
+const RIM_EDGE = hex("#5b4a8a");
+const DAWN_EDGE = hex("#8a7a96");
+const STAR_DIM = hex("#3a3460");
+const STAR_BRIGHT = hex("#ece6ff");
+const MOON_DARK = hex("#3a3352");
+const MOON_LIT = hex("#f4ecd6");
+const EARTHSHINE = hex("#211b33");
+const BAT_DARK = hex("#0b0711");
+const BAT_RIM = hex("#5d4d86");
+const GRASS = hex("#2e2440");
+const GRASS_LIT = hex("#4d3d6a");
+const TEXTURE = hex("#241a33");
+const PATH = hex("#4a3a5c");
+const STONE = hex("#6f6890");
+const STONE_RIM = hex("#a49cc8");
+const STONE_BG = hex("#17111f");
+const RIP = hex("#3d3656");
+const FACTORY_TEXTURE = hex("#1a1226");
+const ROOF = hex("#4b3b70");
+const WINDOW_OFF = hex("#2a2140");
+const WINDOW_DIM = hex("#7a3a10");
+const WINDOW_LIT = hex("#ffb347");
+const DOOR_WOOD = hex("#1d120e");
+const DOOR_OPEN = hex("#8a4a12");
+const CHIMNEY = hex("#3d2f52");
+const SMOKE = hex("#6a6088");
+const CLOCK_RIM = hex("#a89a6a");
+const CLOCK_FACE = hex("#3a2f18");
+const CLOCK_HAND = hex("#fff1c4");
+const STEEL = hex("#5f5874");
+const CABLE = hex("#8a83a0");
+const VINE = hex("#33502a");
+const LEAF = hex("#4c7034");
+const PUMPKIN_SHELL = hex("#9a420c");
+const PUMPKIN_MARK = hex("#cf6a1c");
+const FENCE = hex("#4f3d4e");
+const CAT_LINE = hex("#3e3058");
+const CAT_BG = hex("#07040b");
+const CAT_EYES = hex("#d4ff5a");
+const CROW_LINE = hex("#3a304e");
+const CROW_EYE = hex("#ffcc33");
+const CAW = hex("#efe8ff");
+const LANTERN_LIGHT = hex("#ff8a2a");
+const ALARM = hex("#ff2d2d");
+const GHOST_GLOW = hex("#ddd8f6");
+const GHOST_BG = hex("#272238");
+const BONE = hex("#ece4cf");
+const VISITOR_RIM = hex("#4f4074");
+const SHIP_GLOW = hex("#8fd6b8");
+const SPIDER_EYES = hex("#ff3b3b");
+const HEAD_GLOW = hex("#ffb347");
+const RAIN = hex("#5d5585");
+const BOLT = hex("#f3eeff");
+const RING = hex("#d9c98e");
+const STAR_GOLD = hex("#ffe6a8");
+
+/** How far into the dawn: the sky pales, then the clock spins back. */
+export function dawnAt(scene: Scene) {
+ return scene.moment.act === "dawn" ? ease(segment(scene.moment.t, 0, 6)) : 0;
+}
+
+/** Seconds into the Great Lighting (the witching hour, then the dawn). */
+function lightingTime(scene: Scene) {
+ const { moment } = scene;
+ if (moment.act === "witching") return moment.t;
+ if (moment.act === "dawn") return 14 + moment.t;
+ return -1;
+}
+
+/**
+ * Where the moon is. On the shift of the Great Lighting it sets behind the
+ * hills as the lanterns rise, and leaves them the sky.
+ */
+function moonAt(scene: Scene) {
+ const { moon, horizon } = scene.layout;
+ if (!scene.plan.greatLighting) return moon;
+ const T = lightingTime(scene);
+ if (T < 0) return moon;
+ const set = ease(segment(T, 0.5, 7));
+ return { ...moon, y: lerp(moon.y, horizon + moon.r + 2, set) };
+}
+
+function overMoon(scene: Scene, x: number, y: number) {
+ const { aspect } = scene.layout;
+ const moon = moonAt(scene);
+ const dx = (x + 0.5 - moon.x) / (moon.r * aspect);
+ const dy = (y + 0.5 - moon.y) / moon.r;
+ return dx * dx + dy * dy <= 1;
+}
+
+/** A silhouette's glyph colour: black against the moon, rim-lit elsewhere. */
+function silhouette(scene: Scene, dark: Color, rim: Color) {
+ return (x: number, y: number) => (overMoon(scene, x, y) ? dark : rim);
+}
+
+function drawStars(scene: Scene, dawn: number) {
+ const { grid, layout, seconds } = scene;
+ for (const star of layout.stars) {
+ const v = noise2(seconds * 0.7 + star.seed * 0.013, star.seed % 97);
+ const shine = (0.3 + 0.7 * v) * (1 - dawn);
+ if (shine < 0.14) continue;
+ const char = v > 0.8 ? "*" : v > 0.64 ? "+" : v > 0.4 ? "." : "'";
+ grid.put(star.x, star.y, char, mix(STAR_DIM, STAR_BRIGHT, shine));
+ }
+}
+
+const MOON_RAMP = " .:-=+*#%@";
+
+function drawMoon(scene: Scene, dawn: number) {
+ const { grid, layout, plan, lights } = scene;
+ const { aspect } = layout;
+ const moon = moonAt(scene);
+ const angle = plan.moonPhase * Math.PI * 2;
+ const lx = Math.sin(angle);
+ const lz = Math.cos(angle);
+ const rx = moon.r * aspect;
+ for (
+ let row = Math.trunc(moon.y - moon.r) - 1;
+ row <= moon.y + moon.r + 1;
+ row++
+ ) {
+ for (let col = Math.trunc(moon.x - rx) - 1; col <= moon.x + rx + 1; col++) {
+ const nx = (col + 0.5 - moon.x) / rx;
+ const ny = (row + 0.5 - moon.y) / moon.r;
+ const d2 = nx * nx + ny * ny;
+ if (d2 > 1) continue;
+ const nz = Math.sqrt(1 - d2);
+ const facing = nx * lx + nz * lz;
+ const lit = clamp01((facing + 0.06) / 0.2);
+ const maria = clamp01(
+ (fbm2(nx * 2.4 + 3, ny * 2.4 + 1, 3, 5) - 0.5) / 0.16
+ );
+ const crater = noise2(nx * 9 + 1, ny * 9 + 4, 9) > 0.78 ? 0.75 : 1;
+ const brightness = lit * (0.7 + 0.3 * nz) * (1 - 0.35 * maria) * crater;
+ if (brightness < 0.07) {
+ if ((col + row) % 2 === 0) grid.put(col, row, ".", EARTHSHINE);
+ continue;
+ }
+ const index = Math.min(
+ MOON_RAMP.length - 1,
+ Math.trunc(brightness * MOON_RAMP.length)
+ );
+ grid.put(
+ col,
+ row,
+ MOON_RAMP[index] ?? "@",
+ mix(MOON_DARK, mix(MOON_LIT, DAWN_EDGE, dawn * 0.5), brightness)
+ );
+ }
+ }
+ const illumination = (1 + lz) / 2;
+ lights.push({
+ x: moon.x,
+ y: moon.y,
+ radius: moon.r * 3,
+ color: hex("#b9b0e0"),
+ power: 0,
+ halo: (0.08 + 0.14 * illumination) * (1 - dawn * 0.6)
+ });
+}
+
+function batTargets(scene: Scene) {
+ const { cols, rows } = scene.layout;
+ const targets: { x: number; y: number }[] = [];
+ const spacingX = 2;
+ const spacingY = 1;
+ const letterWidth = spacingX * 5 + 4;
+ const left = cols * 0.4 - (letterWidth * BOO.length) / 2;
+ BOO.forEach((letter, k) => {
+ letter.forEach((line, row) => {
+ for (let col = 0; col < line.length; col++) {
+ if (line[col] !== "#") continue;
+ targets.push({
+ x: left + k * letterWidth + col * spacingX,
+ y: rows * 0.13 + row * spacingY
+ });
+ }
+ });
+ });
+ return targets;
+}
+
+function drawBats(scene: Scene) {
+ const { grid, layout, plan, moment, seconds } = scene;
+ const t = moment.shiftT;
+ if (t > 16) return;
+ const boo = plan.event === "boo";
+ const targets = boo ? batTargets(scene) : [];
+ const count = boo ? targets.length : 12;
+ const belfry = { x: layout.factory.tower, y: layout.factory.towerTop + 2 };
+ const shade = silhouette(scene, BAT_DARK, BAT_RIM);
+ for (let i = 0; i < count; i++) {
+ const start = 1 + i * (boo ? 0.06 : 0.13);
+ const u = (t - start) / (boo ? 11 : 8.5);
+ if (u < 0 || u > 1) continue;
+ const r1 = hash01(i * 7 + plan.index * 131);
+ const r2 = hash01(i * 13 + 5);
+ const control = {
+ x: layout.moon.x + (r1 - 0.5) * layout.moon.r * layout.aspect * 2.6,
+ y: layout.moon.y + (r2 - 0.5) * layout.moon.r * 2.2
+ };
+ const exit = {
+ x: layout.cols + 6 + r1 * 10,
+ y: layout.rows * (0.02 + hash01(i * 31 + 2) * 0.16)
+ };
+ const a = (1 - u) * (1 - u);
+ const b = 2 * (1 - u) * u;
+ const c = u * u;
+ let x = a * belfry.x + b * control.x + c * exit.x;
+ let y =
+ a * belfry.y +
+ b * control.y +
+ c * exit.y +
+ Math.sin(seconds * 9 + i) * 0.5;
+ const target = targets[i];
+ let folded = false;
+ if (target) {
+ const w = ease(segment(t, 3.4, 4.8)) * (1 - ease(segment(t, 7.4, 8.4)));
+ x = lerp(x, target.x, w);
+ y = lerp(y, target.y, w);
+ // In formation each bat hangs as one glyph, so the letters read.
+ folded = w > 0.85;
+ }
+ if (folded) {
+ grid.put(x, y, "v", shade(x, y));
+ continue;
+ }
+ const frame =
+ BAT[Math.trunc(seconds * 11 + i * 0.37) % BAT.length] ?? "-v-";
+ for (let k = 0; k < frame.length; k++) {
+ grid.put(x - 1 + k, y, frame[k] ?? " ", shade(x - 1 + k, y));
+ }
+ }
+}
+
+function drawHills(scene: Scene, dawn: number) {
+ const { grid, layout } = scene;
+ const edge = mix(RIM_EDGE, DAWN_EDGE, dawn);
+ for (let c = 0; c < layout.cols; c++) {
+ const top = layout.ridge[c] ?? layout.horizon;
+ const r0 = Math.trunc(top);
+ for (let r = r0 + 1; r <= layout.horizon + 1; r++) {
+ grid.blank(c, r);
+ grid.fill(c, r, mix(HILL_BG, hex("#2a2236"), dawn * 0.5));
+ if (hash01(c * 131 + r * 71) < 0.045) grid.put(c, r, ".", hex("#2b1f3e"));
+ }
+ const slope = (layout.ridge[c + 1] ?? top) - (layout.ridge[c - 1] ?? top);
+ const char = slope < -0.45 ? "/" : slope > 0.45 ? "\\" : "_";
+ grid.put(c, r0, char, edge);
+ }
+}
+
+function drawGround(scene: Scene, dawn: number) {
+ const { grid, layout, seconds } = scene;
+ for (let c = 0; c < layout.cols; c++) {
+ const top = layout.ground[c] ?? layout.horizon;
+ const r0 = Math.trunc(top);
+ for (let r = r0 + 1; r < layout.rows; r++) {
+ grid.fill(c, r, GROUND_BG);
+ grid.blank(c, r);
+ const h = hash01(c * 977 + r * 131);
+ if (h < 0.07)
+ grid.put(c, r, h < 0.025 ? "," : h < 0.05 ? "." : "`", TEXTURE);
+ }
+ const tall = hash01(c * 17 + 3) < 0.4;
+ const sway = noise2(c * 0.25 + seconds * 0.6, 1.3, 2);
+ const blade = tall
+ ? sway < 0.4
+ ? "/"
+ : sway > 0.6
+ ? "\\"
+ : "|"
+ : hash01(c) < 0.5
+ ? ","
+ : "'";
+ grid.put(
+ c,
+ r0,
+ blade,
+ mix(GRASS, mix(GRASS_LIT, DAWN_EDGE, dawn * 0.4), hash01(c * 3))
+ );
+ }
+}
+
+function drawPath(scene: Scene) {
+ const { grid, layout } = scene;
+ const steps = 110;
+ for (let k = 0; k <= steps; k++) {
+ if (hash01(k * 29) > 0.7) continue;
+ const p = pointAlong(layout.path, k / steps, layout.aspect);
+ grid.put(p.x, p.y + 0.4, k % 3 === 0 ? "," : ".", PATH);
+ }
+}
+
+function drawStones(scene: Scene) {
+ const { grid, layout } = scene;
+ for (const stone of layout.stones) {
+ const art = STONES[stone.kind];
+ const width = spriteWidth(art);
+ const left = stone.x - Math.trunc(width / 2);
+ const top = stone.base - art.length + 1;
+ grid.sprite(
+ left,
+ top,
+ art,
+ (char, col, row) =>
+ char === "R" || char === "I" || char === "P"
+ ? RIP
+ : row === 0 || col >= width - 2
+ ? STONE_RIM
+ : STONE,
+ STONE_BG
+ );
+ }
+}
+
+const RUN_START = ACTS[0].seconds;
+
+/** The tower clock: 12 at midnight, about half past five at dawn, then back. */
+export function clockHours(scene: Scene) {
+ const { moment } = scene;
+ const runEnd = actStart("dawn") + 6;
+ const run = (s: number) =>
+ 5.6 * clamp01((s - RUN_START) / (runEnd - RUN_START));
+ if (moment.act !== "dawn") return run(moment.shiftT);
+ if (moment.t < 6) return run(moment.shiftT);
+ return run(runEnd) * (1 - ease(segment(moment.t, 6, 8.5)));
+}
+
+function handChar(angle: number) {
+ const a = ((angle % Math.PI) + Math.PI) % Math.PI;
+ if (a < Math.PI / 8 || a > (7 * Math.PI) / 8) return "|";
+ if (a < (3 * Math.PI) / 8) return "/";
+ if (a < (5 * Math.PI) / 8) return "-";
+ return "\\";
+}
+
+function strikeGlow(scene: Scene) {
+ if (scene.moment.act !== "midnight") return 0;
+ let glow = 0;
+ for (let k = 0; k < 12; k++) {
+ const age = scene.moment.t - (0.6 + k * 0.55);
+ if (age >= 0 && age < 0.5) glow = Math.max(glow, 1 - age / 0.5);
+ }
+ return glow;
+}
+
+function drawFactory(scene: Scene, dawn: number) {
+ const { grid, layout, seconds, lights, moment, plan } = scene;
+ const f = layout.factory;
+ for (let r = f.roof; r < f.base + 1; r++) {
+ for (let c = f.left; c <= f.right; c++) {
+ grid.fill(c, r, SILHOUETTE_BG);
+ grid.blank(c, r);
+ if (hash01(c * 61 + r * 17) < 0.04) grid.put(c, r, ".", FACTORY_TEXTURE);
+ }
+ }
+ for (let c = f.left; c + 2 <= f.right; c += 3) {
+ grid.sprite(c, f.roof - 2, [" /|", "/$|"], ROOF, SILHOUETTE_BG);
+ }
+ for (const row of [f.roof + 2, f.roof + 5]) {
+ if (row > f.base - 3) continue;
+ for (let x = f.left + 2; x + 1 < f.right - 1; x += 4) {
+ if (Math.abs(x - f.door) < 3) continue;
+ const h = hash01(x * 13 + row * 7);
+ if (h > 0.28) {
+ const b = (0.6 + 0.4 * flicker(seconds + h * 10, x)) * (1 - dawn * 0.7);
+ grid.text(x, row, "[]", mix(WINDOW_DIM, WINDOW_LIT, b));
+ lights.push({
+ x: x + 1,
+ y: row + 0.5,
+ radius: 2.2,
+ color: WINDOW_LIT,
+ power: 0.32 * b,
+ halo: 0.05 * b
+ });
+ } else {
+ grid.text(x, row, "[]", WINDOW_OFF);
+ }
+ }
+ }
+ const open =
+ moment.act === "shipping" &&
+ moment.t > 1.5 &&
+ moment.t < (plan.event === "reject" ? 10 : 12.5);
+ grid.sprite(
+ f.door - 1,
+ f.base - 3,
+ [" _ ", "|$|", "|$|"],
+ ROOF,
+ open ? DOOR_OPEN : DOOR_WOOD
+ );
+ if (open) {
+ lights.push({
+ x: f.door,
+ y: f.base - 1.5,
+ radius: 4.5,
+ color: WINDOW_LIT,
+ power: 0.75,
+ halo: 0.22
+ });
+ }
+
+ for (let r = f.chimneyTop + 1; r < f.roof; r++) {
+ grid.sprite(f.chimney - 1, r, ["|$|"], CHIMNEY, SILHOUETTE_BG);
+ }
+ grid.text(f.chimney - 1, f.chimneyTop, "===", ROOF);
+ for (let k = 0; k < 16; k++) {
+ const age = fraction(seconds * 0.11 + k / 16);
+ const x =
+ f.chimney + age * age * 18 + Math.sin(seconds * 0.7 + k) * age * 2;
+ const y = f.chimneyTop - 1 - age * 12;
+ const char =
+ age < 0.18
+ ? "o"
+ : age < 0.5
+ ? k % 2
+ ? "("
+ : ")"
+ : age < 0.8
+ ? "~"
+ : ".";
+ if (grid.isBlank(x, y)) grid.put(x, y, char, scale(SMOKE, 1 - age * 0.75));
+ }
+
+ grid.put(f.tower, f.towerTop - 1, "+", ROOF);
+ grid.put(f.tower, f.towerTop, "^", ROOF);
+ for (let k = 1; k <= 4; k++) {
+ const y = f.towerTop + k;
+ grid.put(f.tower - k - 1, y, "/", ROOF);
+ grid.put(f.tower + k + 1, y, "\\", ROOF);
+ for (let c = f.tower - k; c <= f.tower + k; c++) {
+ grid.fill(c, y, SILHOUETTE_BG);
+ grid.blank(c, y);
+ }
+ }
+ for (let y = f.towerTop + 5; y < f.roof; y++) {
+ grid.put(f.tower - 5, y, "|", ROOF);
+ grid.put(f.tower + 5, y, "|", ROOF);
+ for (let c = f.tower - 4; c <= f.tower + 4; c++) {
+ grid.fill(c, y, SILHOUETTE_BG);
+ grid.blank(c, y);
+ }
+ }
+ const strike = strikeGlow(scene);
+ const face = mix(CLOCK_FACE, hex("#7a6430"), strike * 0.6);
+ grid.sprite(f.tower - 3, f.towerTop + 5, CLOCK, CLOCK_RIM, face);
+ const center = { x: f.tower, y: f.towerTop + 7 };
+ const hours = clockHours(scene);
+ const minute = fraction(hours) * Math.PI * 2;
+ const hour = (hours / 12) * Math.PI * 2;
+ for (const k of [1, 2]) {
+ grid.put(
+ center.x + nearest(Math.sin(minute) * k),
+ center.y + nearest(-Math.cos(minute) * k * 0.5),
+ handChar(minute),
+ CLOCK_HAND
+ );
+ }
+ const hx = center.x + nearest(Math.sin(hour) * 1.2);
+ const hy = center.y + nearest(-Math.cos(hour) * 0.6);
+ if (hx !== center.x || hy !== center.y)
+ grid.put(hx, hy, handChar(hour), scale(CLOCK_HAND, 0.85));
+ grid.put(center.x, center.y, "o", CLOCK_HAND);
+ lights.push({
+ x: center.x,
+ y: center.y,
+ radius: 3 + strike * 5,
+ color: hex("#ffd98a"),
+ power: 0.25 + strike * 0.8,
+ halo: 0.1 + strike * 0.3
+ });
+}
+
+/** The crane on the roof, and the hero pumpkin while it hangs from it. */
+function drawCraneAndHero(scene: Scene) {
+ const { grid, layout, moment, seconds } = scene;
+ const f = layout.factory;
+ const stub = 4;
+ const reach = Math.max(stub, Math.trunc(layout.hero.x - f.mast));
+ const heroRadius =
+ moment.act === "midnight"
+ ? 1.05
+ : 1.05 +
+ 1.15 * ease(segment(moment.t, 2.5, 6.5)) +
+ 0.05 * Math.sin(seconds * 3);
+ const heroTop = layout.hero.y - heroRadius;
+ const t = moment.act === "harvest" ? moment.t : -1;
+
+ let length = stub;
+ let hookY = f.jib + 2;
+ let carried = false;
+ if (t >= 0) {
+ if (t < 8) length = lerp(stub, reach, ease(segment(t, 6, 8)));
+ else if (t < 11.5) length = reach;
+ else length = lerp(reach, stub, ease(segment(t, 11.5, 13.2)));
+ if (t >= 8 && t < 9.5)
+ hookY = lerp(f.jib + 2, heroTop - 1, ease(segment(t, 8, 9.5)));
+ else if (t >= 9.5 && t < 10) hookY = heroTop - 1;
+ else if (t >= 10 && t < 13.2)
+ hookY = lerp(heroTop - 1, f.jib + 3, ease(segment(t, 10, 11.5)));
+ else if (t >= 13.2)
+ hookY = lerp(f.jib + 3, f.roof + 2, ease(segment(t, 13.2, 14)));
+ carried = t >= 10;
+ }
+ const L = Math.trunc(length);
+ for (let y = f.jib; y < f.roof; y++) grid.put(f.mast, y, "H", STEEL);
+ for (let k = 1; k <= L; k++) {
+ grid.put(f.mast + k, f.jib, k === L ? ">" : "=", STEEL);
+ if (k < L)
+ grid.put(f.mast + k, f.jib + 1, k % 2 ? "\\" : "/", scale(STEEL, 0.7));
+ }
+ const hookX = f.mast + L - 1;
+ for (let y = f.jib + 1; y < hookY; y++) grid.put(hookX, y, "|", CABLE);
+ grid.put(hookX, hookY, "J", CABLE);
+
+ // Lowered through the roof hatch at the end of the harvest: gone inside.
+ const sunk = t >= 13.2 && hookY + 1 > f.roof - 1;
+ const showHero =
+ moment.act === "midnight" || (moment.act === "harvest" && !sunk);
+ if (!showHero) return;
+ const center = carried
+ ? { x: hookX + 0.5, y: hookY + 1 + heroRadius }
+ : { x: layout.hero.x, y: layout.hero.y };
+ drawPumpkin(grid, {
+ x: center.x,
+ y: center.y,
+ radius: heroRadius,
+ aspect: layout.aspect,
+ spin: seconds * 0.4,
+ seconds
+ });
+}
+
+function drawPatch(scene: Scene) {
+ const { grid, layout, moment } = scene;
+ const { patch } = layout;
+ const grown =
+ moment.act === "midnight"
+ ? 0.15
+ : moment.act === "harvest"
+ ? ease(segment(moment.t, 0, 5))
+ : 1;
+ const end = patch.left + (patch.right - patch.left) * grown;
+ for (let x = patch.left; x <= end; x++) {
+ const wave = Math.sin(x * 0.42);
+ const y = patch.y + 1 + nearest(wave * 0.8);
+ const slope = Math.cos(x * 0.42);
+ const char = slope > 0.5 ? "\\" : slope < -0.5 ? "/" : "~";
+ grid.put(x, y, char, VINE);
+ if (hash01(x * 41) < 0.22)
+ grid.put(x, y - 1, hash01(x) < 0.5 ? "&" : "%", LEAF);
+ if (hash01(x * 7 + 1) < 0.12) grid.put(x, y + 1, "@", scale(VINE, 0.8));
+ }
+ const spots = 6;
+ for (let k = 0; k < spots; k++) {
+ const x =
+ patch.left + 2 + ((k + 0.5) * (patch.right - patch.left - 4)) / spots;
+ if (Math.abs(x - layout.hero.x) < 7) continue;
+ if (x > end) continue;
+ const y = patch.y + (k % 2) - 0.2;
+ const art = k % 3 === 0 ? "(@)" : k % 3 === 1 ? "(o)" : "(O)";
+ grid.text(x - 1, y, art, PUMPKIN_SHELL);
+ grid.put(x, y, art[1] ?? "@", PUMPKIN_MARK);
+ grid.put(x, y - 1, "'", VINE);
+ }
+}
+
+function drawFence(scene: Scene) {
+ const { grid, layout, seconds, watcher } = scene;
+ const { fence } = layout;
+ for (let c = fence.left; c <= fence.right; c++) {
+ const post = (c - fence.left) % 3 === 0;
+ if (post) grid.put(c, fence.top, "^", FENCE);
+ grid.put(c, fence.top + 1, post ? "|" : "-", FENCE);
+ if (post) grid.put(c, fence.top + 2, "|", scale(FENCE, 0.8));
+ }
+
+ const { cat } = layout;
+ let look: keyof typeof CAT.eyes = "ahead";
+ if (watcher.secret) look = "left";
+ else if (watcher.field) look = "right";
+ else if (watcher.pointer) {
+ const dx = watcher.pointer.x - cat.x;
+ look = dx < -5 ? "left" : dx > 5 ? "right" : "ahead";
+ } else {
+ const idle = noise2(seconds * 0.18, 9, 4);
+ look = idle < 0.36 ? "left" : idle > 0.64 ? "right" : "ahead";
+ }
+ if (fraction(seconds / 4.7) < 0.035) look = "blink";
+ const art = [CAT.ears, CAT.eyes[look], ...CAT.body];
+ grid.sprite(
+ cat.x - 3,
+ cat.y,
+ art,
+ (char) => (char === "o" ? CAT_EYES : CAT_LINE),
+ CAT_BG
+ );
+ if (look !== "blink") {
+ scene.lights.push({
+ x: cat.x,
+ y: cat.y + 1.5,
+ radius: 1.4,
+ color: CAT_EYES,
+ power: 0.2,
+ halo: 0.06
+ });
+ }
+
+ const { crow } = layout;
+ grid.sprite(
+ crow.x,
+ crow.y,
+ CROW,
+ (char) =>
+ char === "o" ? CROW_EYE : char === ">" ? hex("#c9a227") : CROW_LINE,
+ CAT_BG
+ );
+ if (watcher.alarm > 0)
+ grid.text(
+ crow.x + 4,
+ crow.y - 1,
+ "caw.",
+ mix(CROW_LINE, CAW, watcher.alarm)
+ );
+}
+
+function lanternLight(
+ scene: Scene,
+ x: number,
+ y: number,
+ lit: number,
+ away: boolean
+) {
+ const flare = scene.watcher.flare;
+ scene.lights.push({
+ x,
+ y,
+ radius: 2.8 + flare * 2,
+ color:
+ scene.watcher.alarm > 0
+ ? mix(LANTERN_LIGHT, ALARM, scene.watcher.alarm)
+ : LANTERN_LIGHT,
+ power: 0.55 * lit * (away ? 0.45 : 1) * (1 + flare * 1.6),
+ halo: 0.2 * lit * (away ? 0.5 : 1) * (1 + flare * 1.6)
+ });
+}
+
+function lanternTint(scene: Scene, lit: number) {
+ const { alarm } = scene.watcher;
+ if (alarm <= 0) return undefined;
+ const on = fraction(scene.seconds * 7) < 0.6;
+ return mix(hex("#ffd36a"), ALARM, on ? alarm : alarm * 0.4 * lit);
+}
+
+/** The lanterns on the hill, the newest still hopping down from the door. */
+function drawProcession(scene: Scene) {
+ const { grid, layout, plan, moment, seconds, watcher } = scene;
+ if (
+ plan.greatLighting &&
+ (moment.act === "witching" || moment.act === "dawn")
+ )
+ return;
+ const shipped =
+ (moment.act === "witching" || moment.act === "dawn") &&
+ plan.event !== "reject";
+ const lanterns: Face[] = shipped
+ ? [...plan.procession, plan.face]
+ : plan.procession;
+ const peek = lanterns.length - 1;
+ lanterns.forEach((face, i) => {
+ const s = lanternSlot(i, LANTERNS_FOR_LIGHTING);
+ const p = pointAlong(layout.path, s, layout.aspect);
+ const bob = noise2(seconds * 1.1 + i * 3.1, i, 6) > 0.64 ? -1 : 0;
+ const lit = flicker(seconds + i * 1.7, i);
+ const away = watcher.secret && !(watcher.peek && i === peek);
+ drawLantern(grid, p.x, p.y - 0.6 + bob, face, {
+ lit,
+ away,
+ tint: lanternTint(scene, lit)
+ });
+ lanternLight(scene, p.x, p.y - 0.6 + bob, lit, away);
+ });
+
+ if (moment.act !== "shipping") return;
+ const t = moment.t;
+ if (plan.event === "reject") {
+ const s = segment(t, 2, 8.5) * 1.15;
+ if (t > 2 && s <= 1) {
+ const p = pointAlong(layout.path, s, layout.aspect);
+ const roll =
+ ["(@)", "(o)", "(@)", "(O)"][Math.trunc(seconds * 10) % 4] ?? "(@)";
+ grid.text(p.x - 1, p.y - 0.6, roll, PUMPKIN_MARK);
+ }
+ const chase = segment(t, 2.7, 9.8) * 1.15;
+ if (t > 2.7 && chase <= 1) {
+ const p = pointAlong(layout.path, chase, layout.aspect);
+ const frame =
+ Math.trunc(seconds * 8) % 2 === 0 ? SKELETON.runA : SKELETON.runB;
+ grid.sprite(p.x - 3, p.y - 4.6, frame, BONE);
+ }
+ return;
+ }
+ if (t < 2.5) return;
+ const u = segment(t, 2.5, 11.5);
+ const slot = lanternSlot(plan.procession.length, LANTERNS_FOR_LIGHTING);
+ const p = pointAlong(layout.path, slot * u, layout.aspect);
+ const hop = u < 1 ? Math.sin(fraction((t - 2.5) / 0.5) * Math.PI) * 1.2 : 0;
+ const lit = flicker(seconds, 99);
+ const away = watcher.secret && !watcher.peek;
+ drawLantern(grid, p.x, p.y - 0.6 - hop, plan.face, {
+ lit,
+ away,
+ tint: lanternTint(scene, lit)
+ });
+ lanternLight(scene, p.x, p.y - 0.6 - hop, lit, away);
+}
+
+function drawGhost(scene: Scene) {
+ const { grid, layout, moment, seconds, watcher, lights } = scene;
+ let alpha = 0;
+ if (moment.act === "shipping") alpha = ease(segment(moment.t, 1.5, 4));
+ else if (moment.act === "witching") alpha = 1;
+ else if (moment.act === "dawn") alpha = 1 - ease(segment(moment.t, 6, 9));
+ if (alpha <= 0) return;
+ const first = layout.stones[0];
+ const last = layout.stones[layout.stones.length - 1];
+ const mid = first && last ? (first.x + last.x) / 2 : layout.cols * 0.45;
+ const base = first?.base ?? layout.horizon + 2;
+ const x = mid + Math.sin(seconds * 0.23) * layout.cols * 0.07;
+ const y = base - 6.5 + Math.sin(seconds * 1.2) * 0.7;
+ const body = watcher.secret
+ ? watcher.peek
+ ? GHOST.peek
+ : GHOST.shut
+ : GHOST.open;
+ const hem = GHOST.hem[Math.trunc(seconds * 2.5) % 2] ?? GHOST.hem[0] ?? "";
+ const color = mix(GROUND_BG, GHOST_GLOW, alpha * 0.9);
+ grid.sprite(x - 4, y, [...body, hem], color, mix(GROUND_BG, GHOST_BG, alpha));
+ lights.push({
+ x,
+ y: y + 2,
+ radius: 3.4,
+ color: hex("#b8b0ff"),
+ power: 0.18 * alpha,
+ halo: 0.1 * alpha
+ });
+}
+
+function drawDance(scene: Scene) {
+ const { grid, layout, moment, plan, seconds } = scene;
+ if (plan.event !== "dance" || moment.act !== "witching" || plan.greatLighting)
+ return;
+ const f = layout.factory;
+ const x = f.door + 3;
+ const y = f.base - 4;
+ const step = Math.trunc(seconds / 0.4) % 2 === 0;
+ grid.sprite(x, y, step ? SKELETON.danceA : SKELETON.danceB, BONE);
+ grid.text(x + (step ? 7 : 6), y + (step ? 0 : 2), "c[_]", hex("#c8a27a"));
+ for (let k = 0; k < 3; k++) {
+ const age = fraction(seconds * 0.5 + k / 3);
+ grid.put(
+ x + 3 + Math.sin(age * 6 + k) * 2,
+ y - 1 - age * 5,
+ k % 2 ? "♪" : "♫",
+ scale(BONE, 1 - age)
+ );
+ }
+}
+
+function constellationPoint(scene: Scene, index: number) {
+ const { cols, rows, aspect, factory } = scene.layout;
+ const star = MARK_STARS[index] ?? MARK_STARS[0] ?? { x: 212, y: 240 };
+ // Right of the chimney's smoke, as large as fits: the moon has set.
+ const left = factory.chimney + 4;
+ const right = cols - 3;
+ const sy = Math.min((rows * 0.3) / 480, (right - left) / 2 / (212 * aspect));
+ return {
+ x: (left + right) / 2 + (star.x - 212) * sy * aspect,
+ y: rows * 0.26 + (star.y - 240) * sy
+ };
+}
+
+/** Thirteen lanterns rise and become the Carbon mark, then the stars. */
+function drawGreatLighting(scene: Scene) {
+ const { grid, layout, plan, moment, seconds, lights } = scene;
+ if (!plan.greatLighting) return;
+ if (moment.act !== "witching" && moment.act !== "dawn") return;
+ const T = lightingTime(scene);
+ const lanterns = [...plan.procession, plan.face];
+ const fade = 1 - ease(segment(T, 20, 24.5));
+ const positions = lanterns.map((face, i) => {
+ const slot = pointAlong(
+ layout.path,
+ lanternSlot(i, LANTERNS_FOR_LIGHTING),
+ layout.aspect
+ );
+ const lift = ease(segment(T, 0.3 + i * 0.25, 3.8 + i * 0.25));
+ const risen = {
+ x: slot.x + Math.sin(seconds * 1.3 + i) * 2 * lift,
+ y: slot.y - 0.6 - lift * 7
+ };
+ const glide = ease(segment(T, 5, 9));
+ const target = constellationPoint(scene, i);
+ return {
+ face,
+ x: lerp(risen.x, target.x, glide),
+ y:
+ lerp(risen.y, target.y, glide) +
+ Math.sin(seconds * 2 + i) * 0.15 * (1 - glide),
+ star: glide
+ };
+ });
+
+ MARK_EDGES.forEach(([a, b], k) => {
+ const from = positions[a];
+ const to = positions[b];
+ if (!from || !to) return;
+ const shown = segment(T, 9 + k * 0.22, 9.6 + k * 0.22) * fade;
+ if (shown <= 0) return;
+ const steps = Math.trunc(
+ Math.hypot((to.x - from.x) / layout.aspect, to.y - from.y) * 1.6
+ );
+ const dx = (to.x - from.x) / layout.aspect;
+ const dy = to.y - from.y;
+ const edge =
+ Math.abs(dx) > 2 * Math.abs(dy)
+ ? "-"
+ : Math.abs(dy) > 2 * Math.abs(dx)
+ ? "|"
+ : dx * dy > 0
+ ? "\\"
+ : "/";
+ for (let s = 1; s < steps; s++) {
+ if (s / steps > shown) break;
+ const x = lerp(from.x, to.x, s / steps);
+ const y = lerp(from.y, to.y, s / steps);
+ if (grid.isBlank(x, y))
+ grid.put(x, y, edge, scale(STAR_GOLD, 0.7 * fade));
+ }
+ });
+
+ positions.forEach((p, i) => {
+ const lit = flicker(seconds + i, i);
+ if (p.star < 0.5) {
+ drawLantern(grid, p.x, p.y, p.face, { lit });
+ } else {
+ const twinkle = 0.7 + 0.3 * noise2(seconds * 3 + i, i, 8);
+ const char = fade > 0.66 ? "*" : fade > 0.33 ? "+" : ".";
+ grid.put(
+ p.x,
+ p.y,
+ char,
+ scale(
+ mix(LANTERN_LIGHT, STAR_GOLD, p.star),
+ twinkle * (0.4 + 0.6 * fade)
+ )
+ );
+ }
+ lights.push({
+ x: p.x,
+ y: p.y,
+ radius: 2.6,
+ color: mix(LANTERN_LIGHT, STAR_GOLD, p.star),
+ power: 0.5 * lit * fade,
+ halo: (0.18 + 0.12 * p.star) * fade
+ });
+ });
+}
+
+function drawSkyVisitor(scene: Scene) {
+ const { grid, layout, plan, moment, seconds, lights } = scene;
+ if (moment.act !== "witching" || plan.greatLighting) return;
+ const t = moment.t;
+ const { moon, cols } = layout;
+ const shade = silhouette(scene, BAT_DARK, VISITOR_RIM);
+ if (plan.visitor === "witch") {
+ const u = segment(t, 2, 12);
+ if (u <= 0 || u >= 1) return;
+ const x = lerp(cols + 4, -22, u);
+ const y = moon.y - 3 + Math.sin(t * 1.3) * 1.4;
+ const cape = WITCH.cape[Math.trunc(seconds * 5) % 2] ?? "";
+ const art = [...WITCH.body.slice(0, 4), cape, WITCH.broom];
+ grid.sprite(x, y, art, (_char, col, row) => shade(x + col, y + row));
+ return;
+ }
+ if (plan.visitor === "ship") {
+ const u = segment(t, 1.5, 13);
+ if (u <= 0 || u >= 1) return;
+ const x = lerp(-30, cols + 2, u);
+ const y = moon.y - 2 + Math.sin(t * 0.9) * 0.6;
+ grid.sprite(x, y, SHIP, (_char, col, row) =>
+ overMoon(scene, x + col, y + row) ? hex("#163a30") : SHIP_GLOW
+ );
+ lights.push({
+ x: x + 13,
+ y: y + 3,
+ radius: 6,
+ color: SHIP_GLOW,
+ power: 0.15,
+ halo: 0.12
+ });
+ return;
+ }
+ if (plan.visitor === "spider") {
+ const down = ease(segment(t, 1.5, 5));
+ const up = ease(segment(t, 10, 13));
+ const drop = down * (1 - up);
+ if (drop <= 0) return;
+ const x = moon.x - 6;
+ const y = lerp(-6, moon.y - 1, drop) + Math.sin(seconds * 1.6) * 0.4 * drop;
+ for (let r = 0; r < y; r++) grid.put(x + 6, r, "|", scale(CABLE, 0.7));
+ grid.sprite(x, y, SPIDER, (char, col, row) =>
+ char === "o" ? SPIDER_EYES : shade(x + col, y + row)
+ );
+ lights.push({
+ x: x + 6,
+ y: y + 1,
+ radius: 1.6,
+ color: SPIDER_EYES,
+ power: 0.3,
+ halo: 0.08
+ });
+ }
+}
+
+function drawHorseman(scene: Scene) {
+ const { grid, layout, plan, moment, seconds, lights } = scene;
+ if (
+ moment.act !== "witching" ||
+ plan.greatLighting ||
+ plan.visitor !== "horseman"
+ )
+ return;
+ const u = segment(moment.t, 2, 11);
+ if (u <= 0 || u >= 1) return;
+ const x = lerp(-22, layout.cols + 2, u);
+ const column = Math.trunc(x + 10);
+ const ground =
+ layout.ridge[Math.max(0, Math.min(layout.cols - 1, column))] ??
+ layout.horizon;
+ const gallop = Math.trunc(seconds * 8) % 2;
+ const y = ground - 4.6 - (gallop ? 0.4 : 0);
+ const legs = HORSEMAN.legs[gallop] ?? "";
+ grid.sprite(x, y, [...HORSEMAN.body, legs], (char) =>
+ char === "@" || char === "(" || char === ")" ? HEAD_GLOW : VISITOR_RIM
+ );
+ lights.push({
+ x: x + 12,
+ y,
+ radius: 2.5,
+ color: HEAD_GLOW,
+ power: 0.5,
+ halo: 0.2
+ });
+}
+
+function drawBong(scene: Scene) {
+ const { grid, layout, moment } = scene;
+ if (moment.act !== "midnight") return;
+ const origin = { x: layout.factory.tower, y: layout.factory.towerTop + 7 };
+ for (let k = 0; k < 12; k++) {
+ const age = moment.t - (0.6 + k * 0.55);
+ if (age < 0 || age > 1.8) continue;
+ const radius = age * 15;
+ const strength = 1 - age / 1.8;
+ const samples = Math.max(12, Math.trunc(radius * layout.aspect * 6));
+ for (let s = 0; s < samples; s++) {
+ const a = (s / samples) * Math.PI * 2;
+ const x = origin.x + Math.cos(a) * radius * layout.aspect;
+ const y = origin.y + Math.sin(a) * radius;
+ if (!grid.isBlank(x, y) || grid.bg[grid.index(x, y)] !== NO_BG) continue;
+ const char = strength > 0.66 ? "*" : strength > 0.33 ? ":" : ".";
+ grid.put(x, y, char, scale(RING, strength * 0.8));
+ }
+ }
+}
+
+function drawRain(scene: Scene) {
+ const { grid, layout, plan, moment, seconds } = scene;
+ if (plan.weather !== "drizzle") return;
+ const heavy = moment.act === "witching" ? 1.7 : 1;
+ const count = Math.trunc(layout.cols * 0.45 * heavy);
+ for (let k = 0; k < count; k++) {
+ const speed = 22 + hash01(k * 3) * 10;
+ const y =
+ fraction((seconds * speed) / (layout.rows + 6) + hash01(k * 11)) *
+ (layout.rows + 6) -
+ 3;
+ const x = hash01(k * 17) * (layout.cols + 10) - 5 + y * 0.3;
+ grid.put(x, y, k % 3 === 0 ? "," : "'", RAIN);
+ }
+}
+
+/** Lightning in the witching hour: draws the bolt, returns the flash. */
+function drawLightning(scene: Scene) {
+ const { grid, layout, plan, moment } = scene;
+ if (moment.act !== "witching" || plan.greatLighting) return 0;
+ let flash = 0;
+ const strikes = [
+ 3.2 + hash01(plan.index * 3) * 1.5,
+ 8.7 + hash01(plan.index * 5) * 1.8
+ ];
+ strikes.forEach((at, k) => {
+ const age = moment.t - at;
+ if (age < 0 || age > 0.6) return;
+ flash = Math.max(
+ flash,
+ age < 0.08 ? 1 : age < 0.18 ? 0.35 : age < 0.26 ? 0.7 : 0
+ );
+ let x = layout.cols * (0.15 + hash01(plan.index * 7 + k) * 0.75);
+ const bright = scale(BOLT, 1 - age / 0.6);
+ for (let y = 0; y < (layout.ridge[Math.trunc(x)] ?? layout.horizon); y++) {
+ const step = hash01(plan.index * 97 + k * 31 + y) * 3;
+ const dx = step < 1 ? -1 : step < 2 ? 0 : 1;
+ grid.put(x, y, dx < 0 ? "/" : dx > 0 ? "\\" : "|", bright);
+ x += dx;
+ }
+ });
+ return flash;
+}
+
+export function drawExterior(scene: Scene) {
+ const dawn = dawnAt(scene);
+ drawStars(scene, dawn);
+ drawMoon(scene, dawn);
+ drawSkyVisitor(scene);
+ drawBats(scene);
+ drawHills(scene, dawn);
+ drawHorseman(scene);
+ drawGround(scene, dawn);
+ drawPath(scene);
+ drawStones(scene);
+ drawFactory(scene, dawn);
+ drawCraneAndHero(scene);
+ drawFence(scene);
+ drawPatch(scene);
+ drawProcession(scene);
+ drawGhost(scene);
+ drawDance(scene);
+ drawGreatLighting(scene);
+ drawBong(scene);
+ drawRain(scene);
+ const flash = drawLightning(scene);
+ return { dawn, flash };
+}
diff --git a/packages/react/src/Halloween/night-shift/faces.test.ts b/packages/react/src/Halloween/night-shift/faces.test.ts
new file mode 100644
index 0000000000..21708e3c0a
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/faces.test.ts
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Every one of the 192 faces must fit inside the smallest pumpkin the Line
+// draws, or the blade would cut air; and every face has a one-line version.
+
+import { describe, expect, it } from "vitest";
+import { carvedCells, FACE_COUNT, HERO_MIN_RADIUS, miniFace } from "./faces";
+
+const ASPECT = 1.9;
+
+function allFaces() {
+ const faces = [];
+ for (let eyes = 0; eyes < 6; eyes++) {
+ for (let nose = 0; nose < 4; nose++) {
+ for (let mouth = 0; mouth < 8; mouth++) faces.push({ eyes, nose, mouth });
+ }
+ }
+ return faces;
+}
+
+describe("faces", () => {
+ it("has 192 of them", () => {
+ expect(FACE_COUNT).toBe(192);
+ expect(allFaces()).toHaveLength(FACE_COUNT);
+ });
+
+ it("fits every face inside the smallest hero pumpkin", () => {
+ const rx = HERO_MIN_RADIUS * ASPECT * 1.18;
+ const ry = HERO_MIN_RADIUS;
+ for (const face of allFaces()) {
+ const cells = carvedCells(face);
+ expect(cells.length).toBeGreaterThan(0);
+ for (const cell of cells) {
+ // The pumpkin's centre can sit anywhere inside its cell.
+ for (const offset of [0, 0.99]) {
+ const nx = (cell.x + 0.5 - offset) / rx;
+ const ny = (cell.y + 0.5 - offset) / ry;
+ expect(nx * nx + ny * ny).toBeLessThanOrEqual(1);
+ }
+ }
+ }
+ });
+
+ it("cuts the left eye first and the mouth last", () => {
+ const cells = carvedCells({ eyes: 0, nose: 0, mouth: 0 });
+ expect(cells[0]?.x).toBeLessThan(0);
+ expect(cells.at(-1)?.y).toBeGreaterThan(0);
+ });
+
+ it("puts every face on one line, five characters wide", () => {
+ for (const face of allFaces()) {
+ const mini = miniFace(face);
+ expect(mini).toHaveLength(5);
+ expect(mini.startsWith("(")).toBe(true);
+ expect(mini.endsWith(")")).toBe(true);
+ }
+ expect(miniFace({ eyes: 2, nose: 0, mouth: 0 })).toBe("(>w<)");
+ });
+});
diff --git a/packages/react/src/Halloween/night-shift/faces.ts b/packages/react/src/Halloween/night-shift/faces.ts
new file mode 100644
index 0000000000..b5ff37c2a3
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/faces.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Jack-o'-lantern faces, built from parts: 6 eyes × 4 noses × 8 mouths, 192
+// faces. A part is a mask of the cells the blade cuts out (`#`), placed
+// relative to the pumpkin's centre. Every lantern also has a one-line
+// version, `(^w^)`, for the procession on the hill.
+
+import type { Random } from "./random";
+import { floorOf } from "./random";
+
+type Part = { mask: readonly string[]; mini: string };
+
+const EYES: readonly (Part & { miniRight?: string })[] = [
+ { mask: [" # ", " ### ", "#####"], mini: "^" },
+ { mask: [" ### ", "#####", " ### "], mini: "o" },
+ { mask: ["# ", "### ", "#####"], mini: ">", miniRight: "<" },
+ { mask: [" # ", " ### ", " # "], mini: "*" },
+ { mask: [" ", "#####", " ### "], mini: "-" },
+ { mask: [" ### ", "# #", " "], mini: "n" }
+];
+
+const NOSES: readonly Part[] = [
+ { mask: [" # ", "###"], mini: "" },
+ { mask: [" ", " # "], mini: "" },
+ { mask: ["###", " # "], mini: "" },
+ { mask: [], mini: "" }
+];
+
+const MOUTHS: readonly Part[] = [
+ {
+ mask: ["# #", " ############# ", " ######### "],
+ mini: "w"
+ },
+ {
+ mask: ["###############", "## ## ### ## ##", " ############# "],
+ mini: "m"
+ },
+ {
+ mask: [" ##### ", " ####### ", " ##### "],
+ mini: "o"
+ },
+ { mask: ["## ## ## ##", " ## ### ## "], mini: "v" },
+ {
+ mask: ["# #", " ## ## ", " ######### "],
+ mini: "u"
+ },
+ {
+ mask: ["###############", "###############", " ############# "],
+ mini: "D"
+ },
+ { mask: [" ", "###############"], mini: "_" },
+ { mask: ["###############", " ### ##### ### ", " # # # "], mini: "W" }
+];
+
+export const FACE_COUNT = EYES.length * NOSES.length * MOUTHS.length;
+
+export type Face = { eyes: number; nose: number; mouth: number };
+
+export function drawFace(random: Random): Face {
+ return {
+ eyes: floorOf(random() * EYES.length),
+ nose: floorOf(random() * NOSES.length),
+ mouth: floorOf(random() * MOUTHS.length)
+ };
+}
+
+export type Cell = { x: number; y: number };
+
+/** The smallest pumpkin, in rows, that holds every face (faces.test.ts). */
+export const HERO_MIN_RADIUS = 5.6;
+
+function maskCells(mask: readonly string[], left: number, top: number) {
+ const cells: Cell[] = [];
+ mask.forEach((line, row) => {
+ for (let col = 0; col < line.length; col++) {
+ if (line[col] === "#") cells.push({ x: left + col, y: top + row });
+ }
+ });
+ return cells;
+}
+
+function mirrored(mask: readonly string[]) {
+ return mask.map((line) => line.split("").reverse().join(""));
+}
+
+function width(mask: readonly string[]) {
+ return mask.reduce((widest, line) => Math.max(widest, line.length), 0);
+}
+
+/**
+ * The cells a face cuts out of a hero-sized pumpkin, relative to its centre,
+ * in the order the blade cuts them: left eye, right eye, nose, mouth.
+ */
+export function carvedCells(face: Face): Cell[] {
+ const eyes = EYES[face.eyes] ?? EYES[0];
+ const nose = NOSES[face.nose] ?? NOSES[0];
+ const mouth = MOUTHS[face.mouth] ?? MOUTHS[0];
+ if (!eyes || !nose || !mouth) return [];
+ const eyeWidth = width(eyes.mask);
+ const half = floorOf(eyeWidth / 2);
+ const right = eyes.miniRight ? mirrored(eyes.mask) : eyes.mask;
+ return [
+ ...maskCells(eyes.mask, -5 - half, -4),
+ ...maskCells(right, 5 - half, -4),
+ ...maskCells(nose.mask, -floorOf(width(nose.mask) / 2), -1),
+ ...maskCells(mouth.mask, -floorOf(width(mouth.mask) / 2), 1)
+ ];
+}
+
+/** The face on one line, as a lantern in the procession shows it. */
+export function miniFace(face: Face): string {
+ const eyes = EYES[face.eyes] ?? EYES[0];
+ const mouth = MOUTHS[face.mouth] ?? MOUTHS[0];
+ const left = eyes?.mini ?? "o";
+ return `(${left}${mouth?.mini ?? "w"}${eyes?.miniRight ?? left})`;
+}
+
+/** A key for a carved cell, so a renderer can look cells up in a Set. */
+export function cellKey(x: number, y: number) {
+ return (x + 64) * 256 + (y + 64);
+}
diff --git a/packages/react/src/Halloween/night-shift/frame.test.ts b/packages/react/src/Halloween/night-shift/frame.test.ts
new file mode 100644
index 0000000000..c2f79caa6c
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/frame.test.ts
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Any instant of the story renders, on any panel size: every act, every
+// visitor, every rare event and the Great Lighting. Plus the few things
+// a reader of the frame should be able to count on.
+
+import { describe, expect, it } from "vitest";
+import { miniFace } from "./faces";
+import { makeBuffers, renderFrame } from "./frame";
+import type { Grid } from "./grid";
+import { makeLayout } from "./layout";
+import { IDLE_WATCHER } from "./scene";
+import type { ShiftPlan } from "./story";
+import { actStart, LANTERNS_FOR_LIGHTING, momentAt, planShift } from "./story";
+
+const SIZES = [
+ [70, 40],
+ [100, 60],
+ [135, 76]
+] as const;
+
+function text(grid: Grid) {
+ let out = "";
+ for (let r = 0; r < grid.rows; r++) {
+ for (let c = 0; c < grid.cols; c++)
+ out += String.fromCharCode(grid.ch[r * grid.cols + c] ?? 32);
+ out += "\n";
+ }
+ return out;
+}
+
+function render(
+ plan: ShiftPlan,
+ seconds: number,
+ cols = 100,
+ rows = 60,
+ watcher = IDLE_WATCHER
+) {
+ const layout = makeLayout(cols, rows, 1.93);
+ const buffers = makeBuffers(cols, rows);
+ const moment = momentAt(seconds, plan.index);
+ const frame = renderFrame(buffers, layout, plan, moment, seconds, watcher);
+ return { frame, grid: buffers.main, layout };
+}
+
+function withPlan(overrides: Partial<ShiftPlan>): ShiftPlan {
+ return { ...planShift(7, 2), ...overrides };
+}
+
+describe("renderFrame", () => {
+ it("draws every act, at every panel size, without leaving the grid blank", () => {
+ for (const [cols, rows] of SIZES) {
+ for (let s = 0; s < 90; s += 1.5) {
+ const { grid, frame } = render(planShift(7, 2), s, cols, rows);
+ const glyphs = grid.ch.reduce(
+ (n, code) => n + (code === 32 ? 0 : 1),
+ 0
+ );
+ expect(glyphs).toBeGreaterThan(cols * rows * 0.05);
+ expect(frame.flash).toBeGreaterThanOrEqual(0);
+ expect(frame.flash).toBeLessThanOrEqual(1);
+ }
+ }
+ });
+
+ it("draws every visitor, rare event and weather", () => {
+ for (const visitor of ["witch", "horseman", "spider", "ship"] as const) {
+ for (const event of ["none", "reject", "boo", "dance"] as const) {
+ for (const weather of ["clear", "drizzle", "fog"] as const) {
+ const plan = withPlan({ visitor, event, weather });
+ for (const s of [3, 5, 20, 35, 45, 52, 70, 75, 85]) {
+ expect(() => render(plan, s)).not.toThrow();
+ }
+ }
+ }
+ }
+ });
+
+ it("shows the Line's work order, ticking to Complete after QC", () => {
+ const plan = planShift(7, 2);
+ const during = text(render(plan, actStart("line") + 10).grid);
+ expect(during).toContain(plan.job);
+ expect(during).toContain("In Progress");
+ const after = text(render(plan, actStart("line") + 23).grid);
+ expect(after).toContain("Complete");
+ expect(after).toContain("QC PASSED");
+ });
+
+ it("scraps a rejected pumpkin", () => {
+ const plan = withPlan({ event: "reject" });
+ const after = text(render(plan, actStart("line") + 22).grid);
+ expect(after).toContain("Scrapped");
+ expect(after).toContain("REJECTED");
+ });
+
+ it("stands the procession on the hill, the shipped lantern among them", () => {
+ const plan = planShift(7, 2);
+ const before = text(render(plan, actStart("harvest") + 2).grid);
+ for (const face of plan.procession)
+ expect(before).toContain(miniFace(face));
+ const after = text(render(plan, actStart("witching") + 1).grid);
+ expect(after).toContain(miniFace(plan.face));
+ });
+
+ it("turns every lantern away while a secret is typed", () => {
+ const plan = planShift(7, 2);
+ const watcher = { ...IDLE_WATCHER, secret: true };
+ const frame = text(
+ render(plan, actStart("harvest") + 2, 100, 60, watcher).grid
+ );
+ for (const face of plan.procession)
+ expect(frame).not.toContain(miniFace(face));
+ expect(frame).toContain("(:|:)");
+ });
+
+ it("lights thirteen stars for the Great Lighting", () => {
+ let index = 0;
+ while (!planShift(7, index).greatLighting) index++;
+ const plan = planShift(7, index);
+ const { frame } = render(plan, actStart("dawn") + 2);
+ const stars = frame.lights.filter((light) => (light.halo ?? 0) > 0.2);
+ expect(stars.length).toBeGreaterThanOrEqual(LANTERNS_FOR_LIGHTING);
+ });
+
+ it("wipes between the hill and the Line with a curtain of glyphs", () => {
+ const plan = planShift(7, 2);
+ const half = render(plan, actStart("line") + 0.75);
+ const glyphs = text(half.grid);
+ expect(glyphs).toMatch(/[*+x%#@&?!]/);
+ });
+});
diff --git a/packages/react/src/Halloween/night-shift/frame.ts b/packages/react/src/Halloween/night-shift/frame.ts
new file mode 100644
index 0000000000..e7736bdd02
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/frame.ts
@@ -0,0 +1,295 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// One frame of the Night Shift: picks the scene for the moment (the hill or
+// the Line), wipes between them with a curtain of falling glyphs, rolls the
+// fog in, and lights every glyph near a lantern, a window or a candle.
+
+import {
+ DAWN_HORIZON,
+ DAWN_TOP,
+ drawExterior,
+ SKY_HORIZON,
+ SKY_TOP
+} from "./exterior";
+import type { Color } from "./grid";
+import { blue, Grid, green, hex, mix, NO_BG, red, rgb } from "./grid";
+import { drawInterior } from "./interior";
+import type { Layout } from "./layout";
+import { fbm2 } from "./noise";
+import type { Light, Scene, Watcher } from "./scene";
+import { ease, hash01, lerp, segment } from "./scene";
+import type { Moment, ShiftPlan } from "./story";
+
+export type Sky = { top: Color; horizon: Color };
+
+export type FrameOut = {
+ sky: Sky;
+ lights: Light[];
+ /** A white flash over everything, 0 to 1 (lightning). */
+ flash: number;
+};
+
+export type Buffers = { main: Grid; from: Grid; to: Grid; light: Float32Array };
+
+export function makeBuffers(cols: number, rows: number): Buffers {
+ return {
+ main: new Grid(cols, rows),
+ from: new Grid(cols, rows),
+ to: new Grid(cols, rows),
+ light: new Float32Array(cols * rows * 3)
+ };
+}
+
+const WIPE_SECONDS = 1.5;
+const FOG_RAMP = ".,-~~=";
+const FOG_DIM = hex("#352d4d");
+const FOG_BRIGHT = hex("#a79ecb");
+const WIPE_HEAD = hex("#ffe2b0");
+const WIPE_TAIL = hex("#ff8a2a");
+const WIPE_GLYPHS = "*+x%#@&?!/\\";
+
+const BASE_FOG = { clear: 0.62, drizzle: 0.74, fog: 0.95 } as const;
+
+/** How thick the fog is and how high it reaches, for this moment. */
+export function fogAt(plan: ShiftPlan, moment: Moment, layout: Layout) {
+ const base = BASE_FOG[plan.weather];
+ const low = layout.rows * 0.68;
+ if (moment.act === "midnight") {
+ const clear = ease(segment(moment.t, 0, 2.6));
+ return { density: lerp(1.6, base, clear), top: lerp(0, low, clear) };
+ }
+ if (moment.act === "witching") {
+ return {
+ density: base + 0.25 * ease(moment.progress),
+ top: low - 3 * ease(moment.progress)
+ };
+ }
+ if (moment.act === "dawn") {
+ const swallow = ease(segment(moment.t, 7, 11));
+ return {
+ density: lerp(base + 0.25, 1.6, swallow),
+ top: lerp(low - 3, 0, swallow)
+ };
+ }
+ return { density: base, top: low };
+}
+
+function rollFog(scene: Scene, density: number, top: number) {
+ const { grid, layout, seconds } = scene;
+ const start = Math.max(0, Math.trunc(top) - 6);
+ for (let r = start; r < layout.rows; r++) {
+ const rise = (r - top + 6) / 10;
+ if (rise <= 0) continue;
+ const height = rise >= 1 ? 1 : rise;
+ for (let c = 0; c < layout.cols; c++) {
+ const n = fbm2(
+ c * 0.055 + seconds * 0.16,
+ r * 0.2 - seconds * 0.03,
+ 3,
+ 31
+ );
+ const v = n * height * density;
+ if (v < 0.3) continue;
+ const k = Math.min(1, (v - 0.3) / 0.7);
+ const i = r * layout.cols + c;
+ const color = mix(FOG_DIM, FOG_BRIGHT, k);
+ if (grid.ch[i] === 32 || k > 0.62) {
+ grid.ch[i] = (
+ FOG_RAMP[
+ Math.min(FOG_RAMP.length - 1, Math.trunc(k * FOG_RAMP.length))
+ ] ?? "~"
+ ).charCodeAt(0);
+ grid.fg[i] = color;
+ } else {
+ grid.fg[i] = mix(grid.fg[i] ?? 0, color, k * 0.6);
+ }
+ const bg = grid.bg[i] ?? NO_BG;
+ if (bg !== NO_BG) grid.bg[i] = mix(bg, FOG_DIM, k * 0.45);
+ }
+ }
+}
+
+/** Lights every glyph near a light source: warm near lanterns, cool at lamps. */
+function applyLights(
+ grid: Grid,
+ layout: Layout,
+ lights: Light[],
+ buffer: Float32Array
+) {
+ buffer.fill(0);
+ const { cols, rows, aspect } = layout;
+ for (const light of lights) {
+ if (light.power <= 0) continue;
+ const reachX = light.radius * aspect;
+ const r0 = Math.max(0, Math.trunc(light.y - light.radius));
+ const r1 = Math.min(rows - 1, Math.trunc(light.y + light.radius) + 1);
+ const c0 = Math.max(0, Math.trunc(light.x - reachX));
+ const c1 = Math.min(cols - 1, Math.trunc(light.x + reachX) + 1);
+ const lr = (red(light.color) / 255) * light.power;
+ const lg = (green(light.color) / 255) * light.power;
+ const lb = (blue(light.color) / 255) * light.power;
+ for (let r = r0; r <= r1; r++) {
+ for (let c = c0; c <= c1; c++) {
+ const d =
+ Math.hypot((c + 0.5 - light.x) / aspect, r + 0.5 - light.y) /
+ light.radius;
+ if (d >= 1) continue;
+ const f = (1 - d) * (1 - d);
+ const i = (r * cols + c) * 3;
+ buffer[i] = (buffer[i] ?? 0) + lr * f;
+ buffer[i + 1] = (buffer[i + 1] ?? 0) + lg * f;
+ buffer[i + 2] = (buffer[i + 2] ?? 0) + lb * f;
+ }
+ }
+ }
+ for (let i = 0; i < cols * rows; i++) {
+ const lr = buffer[i * 3] ?? 0;
+ const lg = buffer[i * 3 + 1] ?? 0;
+ const lb = buffer[i * 3 + 2] ?? 0;
+ if (lr + lg + lb < 0.01) continue;
+ if (grid.ch[i] !== 32) {
+ const fg = grid.fg[i] ?? 0;
+ grid.fg[i] = rgb(
+ red(fg) + lr * 230,
+ green(fg) + lg * 230,
+ blue(fg) + lb * 230
+ );
+ }
+ const bg = grid.bg[i] ?? NO_BG;
+ if (bg !== NO_BG)
+ grid.bg[i] = rgb(
+ red(bg) + lr * 40,
+ green(bg) + lg * 40,
+ blue(bg) + lb * 40
+ );
+ }
+}
+
+/** The curtain between scenes: falling glyphs, the new scene above them. */
+function wipe(
+ target: Grid,
+ from: Grid,
+ to: Grid,
+ progress: number,
+ seconds: number
+) {
+ const { cols, rows } = target;
+ const spread = 0.45;
+ for (let c = 0; c < cols; c++) {
+ const lag = hash01(c * 53 + 7) * spread;
+ const front = (progress * (1 + spread) - lag) * (rows + 4);
+ for (let r = 0; r < rows; r++) {
+ const i = r * cols + c;
+ const source = r < front - 2 ? to : from;
+ target.ch[i] = source.ch[i] ?? 32;
+ target.fg[i] = source.fg[i] ?? 0;
+ target.bg[i] = source.bg[i] ?? NO_BG;
+ const behind = front - r;
+ if (behind >= 0 && behind < 3) {
+ const glyph =
+ WIPE_GLYPHS[
+ Math.trunc(
+ hash01(c * 7 + r * 3 + Math.trunc(seconds * 20)) *
+ WIPE_GLYPHS.length
+ )
+ ] ?? "*";
+ target.ch[i] = glyph.charCodeAt(0);
+ target.fg[i] =
+ behind < 1 ? WIPE_HEAD : mix(WIPE_TAIL, WIPE_HEAD, 1 - behind / 3);
+ }
+ }
+ }
+}
+
+function sceneFor(
+ grid: Grid,
+ layout: Layout,
+ plan: ShiftPlan,
+ moment: Moment,
+ seconds: number,
+ watcher: Watcher
+): Scene {
+ return { grid, layout, plan, moment, seconds, watcher, lights: [] };
+}
+
+export function renderFrame(
+ buffers: Buffers,
+ layout: Layout,
+ plan: ShiftPlan,
+ moment: Moment,
+ seconds: number,
+ watcher: Watcher
+): FrameOut {
+ const { main, from, to } = buffers;
+ main.clear();
+ let lights: Light[] = [];
+ let flash = 0;
+ let dawn = 0;
+ let exterior = true;
+
+ const inWipe =
+ (moment.act === "line" || moment.act === "shipping") &&
+ moment.t < WIPE_SECONDS;
+
+ if (inWipe) {
+ const progress = moment.t / WIPE_SECONDS;
+ from.clear();
+ to.clear();
+ const toLine = moment.act === "line";
+ const before: Moment = toLine
+ ? { ...moment, act: "harvest", t: 14, progress: 1 }
+ : { ...moment, act: "line", t: 24, progress: 1 };
+ const fromScene = sceneFor(from, layout, plan, before, seconds, watcher);
+ const toScene = sceneFor(to, layout, plan, moment, seconds, watcher);
+ if (toLine) {
+ drawExterior(fromScene);
+ drawInterior(toScene);
+ const fog = fogAt(plan, before, layout);
+ rollFog(fromScene, fog.density, fog.top);
+ } else {
+ drawInterior(fromScene);
+ drawExterior(toScene);
+ const fog = fogAt(plan, moment, layout);
+ rollFog(toScene, fog.density, fog.top);
+ }
+ wipe(main, from, to, progress, seconds);
+ lights = [
+ ...fromScene.lights.map((light) => ({
+ ...light,
+ power: light.power * (1 - progress),
+ halo: (light.halo ?? 0) * (1 - progress)
+ })),
+ ...toScene.lights.map((light) => ({
+ ...light,
+ power: light.power * progress,
+ halo: (light.halo ?? 0) * progress
+ }))
+ ];
+ exterior = !toLine;
+ } else if (moment.act === "line") {
+ const scene = sceneFor(main, layout, plan, moment, seconds, watcher);
+ drawInterior(scene);
+ lights = scene.lights;
+ exterior = false;
+ } else {
+ const scene = sceneFor(main, layout, plan, moment, seconds, watcher);
+ const out = drawExterior(scene);
+ flash = out.flash;
+ dawn = out.dawn;
+ const fog = fogAt(plan, moment, layout);
+ rollFog(scene, fog.density, fog.top);
+ lights = scene.lights;
+ }
+
+ applyLights(main, layout, lights, buffers.light);
+
+ const sky: Sky = exterior
+ ? {
+ top: mix(SKY_TOP, DAWN_TOP, dawn),
+ horizon: mix(SKY_HORIZON, DAWN_HORIZON, dawn)
+ }
+ : { top: hex("#120c18"), horizon: hex("#120c18") };
+ return { sky, lights, flash };
+}
diff --git a/packages/react/src/Halloween/night-shift/grid.ts b/packages/react/src/Halloween/night-shift/grid.ts
new file mode 100644
index 0000000000..6a670fc058
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/grid.ts
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The character grid every frame is drawn into before it is painted: one
+// glyph, one text colour and an optional cell background per cell. Colours
+// are packed 0xRRGGBB numbers so a frame allocates nothing.
+
+import { floorOf } from "./random";
+
+export type Color = number;
+
+/** No background: the canvas behind the cell shows through. */
+export const NO_BG = -1;
+
+/** A sprite cell that hides whatever is behind it without drawing a glyph. */
+export const OPAQUE = "$";
+
+function clamp255(value: number) {
+ if (value <= 0) return 0;
+ if (value >= 255) return 255;
+ return value | 0;
+}
+
+export function rgb(r: number, g: number, b: number): Color {
+ return (clamp255(r) << 16) | (clamp255(g) << 8) | clamp255(b);
+}
+
+export function hex(value: string): Color {
+ return Number.parseInt(value.replace("#", ""), 16);
+}
+
+export function red(color: Color) {
+ return (color >> 16) & 255;
+}
+
+export function green(color: Color) {
+ return (color >> 8) & 255;
+}
+
+export function blue(color: Color) {
+ return color & 255;
+}
+
+/** `a` at t = 0, `b` at t = 1. */
+export function mix(a: Color, b: Color, t: number): Color {
+ const k = t <= 0 ? 0 : t >= 1 ? 1 : t;
+ return rgb(
+ red(a) + (red(b) - red(a)) * k,
+ green(a) + (green(b) - green(a)) * k,
+ blue(a) + (blue(b) - blue(a)) * k
+ );
+}
+
+export function scale(color: Color, k: number): Color {
+ return rgb(red(color) * k, green(color) * k, blue(color) * k);
+}
+
+export function css(color: Color) {
+ return `#${color.toString(16).padStart(6, "0")}`;
+}
+
+export class Grid {
+ readonly cols: number;
+ readonly rows: number;
+ readonly ch: Uint16Array;
+ readonly fg: Uint32Array;
+ readonly bg: Int32Array;
+
+ constructor(cols: number, rows: number) {
+ this.cols = cols;
+ this.rows = rows;
+ this.ch = new Uint16Array(cols * rows);
+ this.fg = new Uint32Array(cols * rows);
+ this.bg = new Int32Array(cols * rows);
+ this.clear();
+ }
+
+ clear() {
+ this.ch.fill(32);
+ this.fg.fill(0);
+ this.bg.fill(NO_BG);
+ }
+
+ /** The cell index under a point, or -1 off the grid. */
+ index(x: number, y: number) {
+ const c = floorOf(x);
+ const r = floorOf(y);
+ if (c < 0 || r < 0 || c >= this.cols || r >= this.rows) return -1;
+ return r * this.cols + c;
+ }
+
+ put(x: number, y: number, char: string, color: Color) {
+ const i = this.index(x, y);
+ if (i < 0) return;
+ this.ch[i] = char.charCodeAt(0);
+ this.fg[i] = color;
+ }
+
+ /** Clears the glyph so nothing behind shows, optionally filling the cell. */
+ blank(x: number, y: number, background: Color = NO_BG) {
+ const i = this.index(x, y);
+ if (i < 0) return;
+ this.ch[i] = 32;
+ if (background !== NO_BG) this.bg[i] = background;
+ }
+
+ fill(x: number, y: number, background: Color) {
+ const i = this.index(x, y);
+ if (i < 0) return;
+ this.bg[i] = background;
+ }
+
+ charAt(x: number, y: number) {
+ const i = this.index(x, y);
+ return i < 0 ? " " : String.fromCharCode(this.ch[i] ?? 32);
+ }
+
+ isBlank(x: number, y: number) {
+ const i = this.index(x, y);
+ return i < 0 || this.ch[i] === 32;
+ }
+
+ /** Writes a string left to right; spaces leave what is behind. */
+ text(x: number, y: number, value: string, color: Color) {
+ for (let k = 0; k < value.length; k++) {
+ const char = value[k] ?? " ";
+ if (char !== " ") this.put(x + k, y, char, color);
+ }
+ }
+
+ /**
+ * Draws ASCII art with its top-left at (x, y). Spaces are transparent,
+ * `$` hides what is behind. `color` may vary per glyph; returning null
+ * skips that glyph.
+ */
+ sprite(
+ x: number,
+ y: number,
+ lines: readonly string[],
+ color: Color | ((char: string, col: number, row: number) => Color | null),
+ background: Color = NO_BG
+ ) {
+ for (let row = 0; row < lines.length; row++) {
+ const line = lines[row] ?? "";
+ for (let col = 0; col < line.length; col++) {
+ const char = line[col] ?? " ";
+ if (char === " ") continue;
+ if (char === OPAQUE) {
+ this.blank(x + col, y + row, background);
+ continue;
+ }
+ const tint = typeof color === "number" ? color : color(char, col, row);
+ if (tint === null) continue;
+ this.put(x + col, y + row, char, tint);
+ if (background !== NO_BG) this.fill(x + col, y + row, background);
+ }
+ }
+ }
+}
+
+/** Width of the widest line: a sprite's footprint in cells. */
+export function spriteWidth(lines: readonly string[]) {
+ return lines.reduce((widest, line) => Math.max(widest, line.length), 0);
+}
diff --git a/packages/react/src/Halloween/night-shift/interior.ts b/packages/react/src/Halloween/night-shift/interior.ts
new file mode 100644
index 0000000000..9f52917bb0
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/interior.ts
@@ -0,0 +1,379 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The Line: inside the plant, the pumpkin rides a conveyor through four
+// stations (wash, carve, light, QC) while a work order in the corner ticks
+// along, the way a Carbon job does. Once the candle catches, the whole floor
+// turns from cold purple to warm orange.
+
+import { carvedCells, cellKey, HERO_MIN_RADIUS } from "./faces";
+import type { Color } from "./grid";
+import { hex, mix, scale } from "./grid";
+import { flicker, noise2 } from "./noise";
+import { drawPumpkin } from "./pumpkin";
+import type { Scene } from "./scene";
+import { clamp01, ease, fraction, hash01, lerp, segment } from "./scene";
+import { CANDLE, LAMP, NOZZLE, SKELETON } from "./sprites";
+
+const WALL_COLD = hex("#120c18");
+const WALL_WARM = hex("#1f120b");
+const BRICK = hex("#1e1628");
+const FLOOR = hex("#0b070e");
+const FLOOR_LINE = hex("#3a2f4a");
+const BELT = hex("#6a6380");
+const ROLLER = hex("#9a93b0");
+const LEG = hex("#3e3852");
+const SIGN = hex("#8a80a8");
+const SIGN_BG = hex("#1b1424");
+const LAMP_COLD = hex("#b8c4ff");
+const LAMP_WARM = hex("#ffd9a0");
+const WATER = hex("#6aa8ff");
+const BUBBLE = hex("#a8d4ff");
+const CHIP = hex("#f2b26e");
+const STEEL = hex("#7d7694");
+const BLADE = hex("#e6e3f2");
+const WAX = hex("#ece2c6");
+const FLAME = hex("#ffd36a");
+const BONE = hex("#ece4cf");
+const PASS = hex("#6ee7a0");
+const FAIL = hex("#ff5a5a");
+const TICKET_LINE = hex("#5d5378");
+const TICKET_TEXT = hex("#d9d1ee");
+const TICKET_JOB = hex("#ffb347");
+const TICKET_BG = hex("#140f1c");
+const AMBER = hex("#f5b544");
+const PENDING = hex("#5a5270");
+const PUMPKIN_GLOW = hex("#ff8a2a");
+
+const STATIONS = ["Wash", "Carve", "Light", "QC"] as const;
+
+/** Where the pumpkin is along the line, seconds into the act. */
+function travel(t: number, stops: number[], start: number, exit: number) {
+ const [wash = 0, carve = 0, light = 0, qc = 0] = stops;
+ if (t < 1.5) return start;
+ if (t < 3.5) return lerp(start, wash, ease(segment(t, 1.5, 3.5)));
+ if (t < 6.5) return wash;
+ if (t < 8) return lerp(wash, carve, ease(segment(t, 6.5, 8)));
+ if (t < 14.5) return carve;
+ if (t < 16) return lerp(carve, light, ease(segment(t, 14.5, 16)));
+ if (t < 19.5) return light;
+ if (t < 20.5) return lerp(light, qc, ease(segment(t, 19.5, 20.5)));
+ if (t < 22.5) return qc;
+ return lerp(qc, exit, ease(segment(t, 22.5, 24)));
+}
+
+/** Which stations are done, seconds into the act; QC needs the stamp. */
+function stationsDone(t: number) {
+ return [t >= 6.5, t >= 14.5, t >= 19.5, t >= 21.3];
+}
+
+/** How warm the floor is: 0 until the candle catches, then 1. */
+export function warmthAt(t: number) {
+ return ease(segment(t, 17.4, 18.6));
+}
+
+function drawTicket(
+ scene: Scene,
+ done: boolean[],
+ rejected: boolean,
+ active: number
+) {
+ const { grid, layout, plan } = scene;
+ const width = Math.min(layout.cols - 4, 48);
+ const left = Math.trunc((layout.cols - width) / 2);
+ const top = Math.max(7, Math.trunc(layout.rows * 0.12));
+ const inner = width - 2;
+ const border = `+${"-".repeat(inner)}+`;
+ for (let r = top; r <= top + 3; r++) {
+ for (let c = left; c <= left + width - 1; c++) grid.blank(c, r, TICKET_BG);
+ }
+ grid.text(left, top, border, TICKET_LINE);
+ grid.text(left, top + 3, border, TICKET_LINE);
+ grid.put(left, top + 1, "|", TICKET_LINE);
+ grid.put(left, top + 2, "|", TICKET_LINE);
+ grid.put(left + width - 1, top + 1, "|", TICKET_LINE);
+ grid.put(left + width - 1, top + 2, "|", TICKET_LINE);
+
+ grid.text(left + 2, top + 1, plan.job, TICKET_JOB);
+ grid.text(
+ left + 3 + plan.job.length,
+ top + 1,
+ "· Jack-o'-lantern",
+ TICKET_TEXT
+ );
+ const finished = done.every(Boolean);
+ const status =
+ rejected && done[3] ? "Scrapped" : finished ? "Complete" : "In Progress";
+ const statusColor = rejected && done[3] ? FAIL : finished ? PASS : AMBER;
+ const statusLeft = left + width - 3 - status.length - 2;
+ grid.put(statusLeft, top + 1, "●", statusColor);
+ grid.text(statusLeft + 2, top + 1, status, statusColor);
+
+ let x = left + 2;
+ STATIONS.forEach((name, k) => {
+ const isDone = done[k] ?? false;
+ const failed = rejected && k === 3 && isDone;
+ const mark = failed ? "✗" : isDone ? "✓" : k === active ? "●" : "○";
+ const color = failed
+ ? FAIL
+ : isDone
+ ? PASS
+ : k === active
+ ? AMBER
+ : PENDING;
+ grid.put(x, top + 2, mark, color);
+ grid.text(
+ x + 2,
+ top + 2,
+ name,
+ isDone || k === active ? TICKET_TEXT : PENDING
+ );
+ x += name.length + 6;
+ });
+}
+
+export function drawInterior(scene: Scene) {
+ const { grid, layout, plan, moment, seconds, lights } = scene;
+ const { cols, rows, aspect } = layout;
+ const t = moment.act === "line" ? moment.t : 24;
+ const warmth = warmthAt(t);
+ const rejected = plan.event === "reject";
+
+ // Laid out from the belt up: the pumpkin on it, the station signs just
+ // above the pumpkin, the lamps above the signs. So a short panel only
+ // loses wall, never a sign behind the pumpkin.
+ const beltY = Math.trunc(rows * 0.68);
+ const floorY = beltY + Math.max(4, Math.trunc(rows * 0.09));
+ const radius = Math.min(6.2, Math.max(HERO_MIN_RADIUS, rows * 0.09));
+ const signY = Math.trunc(beltY - radius * 2 - 0.2) - 2;
+ const lampY = signY - 4;
+ const wall = mix(WALL_COLD, WALL_WARM, warmth);
+ for (let r = 0; r < rows; r++) {
+ for (let c = 0; c < cols; c++) {
+ if (r < floorY) {
+ grid.fill(c, r, wall);
+ // Running bond: a mortar course every third row, the joints of
+ // each course offset by half a brick. Barely above the wall until
+ // a lamp lights it.
+ const course = Math.trunc(r / 3);
+ const joint = (c + (course % 2) * 5) % 10 === 0;
+ if (r % 3 === 2) grid.put(c, r, "_", BRICK);
+ else if (joint) grid.put(c, r, "|", BRICK);
+ } else {
+ grid.fill(c, r, FLOOR);
+ if (r === floorY) grid.put(c, r, "_", FLOOR_LINE);
+ else if (hash01(c * 31 + r * 7) < 0.05)
+ grid.put(c, r, ".", scale(FLOOR_LINE, 0.7));
+ }
+ }
+ }
+
+ const stops = [0.17, 0.37, 0.57, 0.76].map((k) => cols * k);
+ const halfWidth = radius * aspect * 1.18;
+ const start = -halfWidth - 4;
+ const exit = cols + halfWidth + 6;
+ let x = travel(t, stops, start, exit);
+ let y = beltY - radius - 0.2;
+ let spin = Math.sin(seconds * 0.5) * 0.12;
+ if (rejected && t > 22.5) {
+ const fall = segment(t, 22.6, 24);
+ y += fall * fall * rows * 0.5;
+ spin += fall * 9;
+ }
+
+ stops.forEach((stop, k) => {
+ for (let r = 0; r < lampY; r++) grid.put(stop, r, "|", scale(STEEL, 0.6));
+ grid.sprite(stop - 1, lampY, LAMP, STEEL);
+ const buzz = k === 2 && noise2(seconds * 3, 1, 7) > 0.8 ? 0.4 : 1;
+ const color = mix(LAMP_COLD, LAMP_WARM, warmth);
+ grid.put(stop, lampY + 2, "o", scale(color, buzz));
+ lights.push({
+ x: stop,
+ y: lampY + 3,
+ radius: 11,
+ color,
+ power: 0.28 * buzz,
+ halo: 0.16 * buzz
+ });
+ });
+
+ const beltShift = Math.trunc(x);
+ for (let c = 1; c < cols - 1; c++) {
+ const pattern = "=o==";
+ const char = pattern[(((c - beltShift) % 4) + 4) % 4] ?? "=";
+ grid.put(c, beltY, char, char === "o" ? ROLLER : BELT);
+ grid.put(c, beltY + 1, "-", scale(BELT, 0.6));
+ if (c % 10 === 3)
+ for (let r = beltY + 2; r < floorY; r++) grid.put(c, r, "|", LEG);
+ }
+
+ const [wash = 0, carve = 0, light = 0, qc = 0] = stops;
+ const top = y - radius;
+
+ if (t >= 3.2 && t < 6.9) {
+ for (let r = 0; r < top - 7; r++)
+ grid.text(wash - 1, r, "||", scale(STEEL, 0.6));
+ grid.sprite(wash - 1, top - 7, NOZZLE, STEEL);
+ for (let k = 0; k < 6; k++) {
+ const age = fraction(seconds * 1.8 + k / 6);
+ grid.put(
+ wash + (k % 2 ? 0 : -0.6),
+ top - 4 + age * 4,
+ age < 0.5 ? "'" : "|",
+ WATER
+ );
+ }
+ for (let k = 0; k < 16; k++) {
+ const phase = fraction(seconds * 0.45 + k / 16);
+ const bx = wash + (hash01(k * 5) - 0.5) * halfWidth * 2.4;
+ const by = beltY - 1 - phase * radius * 2.6;
+ const char = phase < 0.3 ? "." : phase < 0.65 ? "o" : "O";
+ if (
+ grid.isBlank(bx, by) ||
+ grid.charAt(bx, by) === "_" ||
+ grid.charAt(bx, by) === "|"
+ ) {
+ grid.put(bx, by, char, scale(BUBBLE, 1 - phase * 0.7));
+ }
+ }
+ }
+
+ const cells = carvedCells(plan.face);
+ const carving = clamp01(segment(t, 8.6, 14));
+ const revealed = t < 8.6 ? 0 : Math.trunc(cells.length * carving);
+ const carved = new Set<number>();
+ for (let k = 0; k < revealed; k++) {
+ const cell = cells[k];
+ if (cell) carved.add(cellKey(cell.x, cell.y));
+ }
+ const ignition = ease(segment(t, 17.4, 18.2));
+ const glow =
+ ignition * flicker(seconds, 21) * (1 + 0.4 * (1 - segment(t, 18.2, 19)));
+
+ if (x > -halfWidth - 2 && x < cols + halfWidth + 2 && y < rows + radius) {
+ drawPumpkin(grid, {
+ x,
+ y,
+ radius,
+ aspect,
+ spin,
+ carved,
+ glow: clamp01(glow),
+ seconds,
+ fill: 0.32
+ });
+ if (ignition > 0) {
+ lights.push({
+ x,
+ y,
+ radius: 10,
+ color: PUMPKIN_GLOW,
+ power: 0.12 * ignition,
+ halo: 0.34 * ignition
+ });
+ }
+ }
+
+ const armUp = t < 8.3 || t > 14.2;
+ if (!armUp) {
+ const last = cells[Math.max(0, revealed - 1)];
+ const bladeX = carve + (last?.x ?? 0);
+ const bladeY = Math.trunc(y) + (last?.y ?? -3) - 1;
+ // A laser cutter: the arm stops above the pumpkin and the beam's
+ // spark sits on the cell being cut.
+ const armTop = Math.trunc(rows * 0.12);
+ const head = Math.trunc(y - radius) - 1;
+ for (let r = armTop; r < head; r++)
+ grid.put(bladeX, r, r === head - 2 ? "o" : "|", STEEL);
+ grid.put(bladeX, head, "V", BLADE);
+ const sparks = ["*", "+", "x"];
+ grid.put(
+ bladeX,
+ bladeY,
+ sparks[Math.trunc(seconds * 14) % 3] ?? "*",
+ BLADE
+ );
+ scene.lights.push({
+ x: bladeX,
+ y: bladeY,
+ radius: 2.5,
+ color: BLADE,
+ power: 0.4,
+ halo: 0.18
+ });
+ for (let k = 0; k < 10; k++) {
+ const age = fraction(seconds * 2.2 + k / 10) * 0.9;
+ const vx = (hash01(k * 9 + 1) - 0.5) * 16;
+ grid.put(
+ bladeX + vx * age,
+ bladeY - 3 * age + 7 * age * age,
+ k % 3 === 0 ? "," : k % 3 === 1 ? "'" : ".",
+ scale(CHIP, 1 - age)
+ );
+ }
+ } else {
+ const armTop = Math.trunc(rows * 0.12);
+ for (let r = armTop; r < armTop + 4; r++)
+ grid.put(carve + 9, r, "|", scale(STEEL, 0.7));
+ grid.put(carve + 9, armTop + 4, "v", scale(BLADE, 0.6));
+ }
+
+ if (t >= 15.6 && t < 17.5) {
+ const cy = lerp(-3, top - 2.2, ease(segment(t, 15.6, 17.4)));
+ for (let r = 0; r < cy; r++) grid.put(light, r, "|", scale(STEEL, 0.6));
+ grid.sprite(light - 1, cy, CANDLE, (char) => (char === "^" ? FLAME : WAX));
+ grid.put(light, cy, Math.trunc(seconds * 12) % 2 ? "^" : "'", FLAME);
+ lights.push({
+ x: light,
+ y: cy,
+ radius: 3.5,
+ color: FLAME,
+ power: 0.6,
+ halo: 0.22
+ });
+ }
+
+ const inspector = { x: Math.min(qc + halfWidth + 1, cols - 8), y: beltY - 5 };
+ let pose = SKELETON.stand;
+ if (t >= 20.5 && t < 21.2) pose = SKELETON.stampUp;
+ else if (t >= 21.2 && t < 21.6) pose = SKELETON.stampDown;
+ if (rejected && t > 22.8) {
+ const run = segment(t, 22.8, 24);
+ inspector.x = lerp(inspector.x, cols + 4, run);
+ pose = Math.trunc(seconds * 8) % 2 === 0 ? SKELETON.runA : SKELETON.runB;
+ }
+ grid.sprite(inspector.x, inspector.y, pose, BONE);
+
+ if (t >= 21.3) {
+ // `$` keeps the wall out of the gaps between words.
+ const stamp = rejected ? "[$REJECTED$]" : "[$QC$PASSED$]";
+ const pop = 1 - ease(segment(t, 21.3, 21.6)) * 0.4;
+ const color: Color = rejected ? FAIL : PASS;
+ grid.sprite(
+ qc - Math.trunc(stamp.length / 2),
+ beltY - radius * 2 - 3.5,
+ [stamp],
+ scale(color, pop + 0.4),
+ TICKET_BG
+ );
+ }
+
+ // Signs last, so the wash pipe and the carving arm pass behind them.
+ stops.forEach((stop, k) => {
+ const label = `[$${(STATIONS[k] ?? "").toUpperCase()}$]`;
+ grid.sprite(
+ stop - Math.trunc(label.length / 2),
+ signY,
+ [label],
+ SIGN,
+ SIGN_BG
+ );
+ });
+
+ const done = stationsDone(t);
+ const active = done.indexOf(false);
+ drawTicket(scene, done, rejected, active);
+
+ return { warmth };
+}
diff --git a/packages/react/src/Halloween/night-shift/layout.ts b/packages/react/src/Halloween/night-shift/layout.ts
new file mode 100644
index 0000000000..171e5f112c
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/layout.ts
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Where everything stands on the hill, in cells, for a grid of a given size.
+// Recomputed only when the panel resizes. The upper left stays clear for the
+// Carbon logo and the lower band is fog, behind the panel's headline.
+
+import { fbm2, noise2 } from "./noise";
+import { floorOf, hashSeed, seeded } from "./random";
+
+export type Point = { x: number; y: number };
+
+export type StoneKind = "rip" | "small" | "cross" | "round";
+
+export type Layout = {
+ cols: number;
+ rows: number;
+ /** Cell height over cell width: how many columns make one row of distance. */
+ aspect: number;
+ /** Top row of the far hills, per column. */
+ ridge: Float32Array;
+ /** Top row of the near ground, per column. */
+ ground: Float32Array;
+ horizon: number;
+ moon: { x: number; y: number; r: number };
+ factory: {
+ left: number;
+ right: number;
+ roof: number;
+ base: number;
+ tower: number;
+ towerTop: number;
+ chimney: number;
+ chimneyTop: number;
+ door: number;
+ mast: number;
+ jib: number;
+ };
+ /** The lantern path, from the factory door into the fog. */
+ path: Point[];
+ stones: { x: number; base: number; kind: StoneKind }[];
+ fence: { left: number; right: number; top: number };
+ cat: Point;
+ crow: Point;
+ patch: { left: number; right: number; y: number };
+ hero: Point;
+ stars: { x: number; y: number; seed: number }[];
+};
+
+export function makeLayout(cols: number, rows: number, aspect: number): Layout {
+ const horizon = floorOf(rows * 0.585);
+ const factoryLeft = Math.max(2, floorOf(cols * 0.05));
+ const factoryRight = factoryLeft + Math.max(24, floorOf(cols * 0.25));
+ const roof = horizon - Math.max(7, floorOf(rows * 0.1));
+
+ const ridge = new Float32Array(cols);
+ const ground = new Float32Array(cols);
+ for (let c = 0; c < cols; c++) {
+ ridge[c] = rows * 0.505 + rows * 0.13 * (fbm2(c * 0.03, 2.3, 4, 7) - 0.5);
+ const flat = c >= factoryLeft - 2 && c <= factoryRight + 2;
+ ground[c] = flat
+ ? horizon
+ : horizon +
+ 1.6 * (noise2(c * 0.06, 0.7, 11) - 0.5) +
+ (c > cols * 0.6 ? 1 : 0);
+ }
+
+ const moonR = Math.max(4.5, rows * 0.095);
+ const moon = {
+ x: cols * 0.7,
+ y: Math.max(moonR + 3, rows * 0.24),
+ r: moonR
+ };
+
+ const door = factoryLeft + floorOf((factoryRight - factoryLeft) * 0.55);
+ const path: Point[] = [
+ { x: door + 1, y: horizon + 0.5 },
+ { x: cols * 0.34, y: rows * 0.628 },
+ { x: cols * 0.46, y: rows * 0.668 },
+ { x: cols * 0.58, y: rows * 0.652 },
+ { x: cols * 0.7, y: rows * 0.684 },
+ { x: cols * 0.83, y: rows * 0.668 },
+ { x: cols * 0.99, y: rows * 0.694 }
+ ];
+
+ const kinds: StoneKind[] = ["rip", "cross", "small", "round", "rip"];
+ const stones = kinds.map((kind, i) => ({
+ kind,
+ x: floorOf(cols * (0.355 + i * 0.05)),
+ base: floorOf(rows * 0.622 + (i % 2) * 1.2)
+ }));
+
+ const fence = {
+ left: floorOf(cols * 0.62),
+ right: floorOf(cols * 0.88),
+ top: floorOf(rows * 0.6)
+ };
+
+ const random = seeded(hashSeed(cols, rows));
+ const stars: Layout["stars"] = [];
+ const count = floorOf(cols * rows * 0.014);
+ for (let i = 0; i < count * 3 && stars.length < count; i++) {
+ const x = random() * cols;
+ const y = random() * rows * 0.5;
+ const dx = (x - moon.x) / aspect;
+ const dy = y - moon.y;
+ const inMoon = Math.hypot(dx, dy) < moon.r + 2;
+ const column = ridge[floorOf(x)] ?? rows;
+ if (inMoon || y > column - 2) continue;
+ stars.push({ x, y, seed: floorOf(random() * 1e6) });
+ }
+
+ return {
+ cols,
+ rows,
+ aspect,
+ ridge,
+ ground,
+ horizon,
+ moon,
+ factory: {
+ left: factoryLeft,
+ right: factoryRight,
+ roof,
+ base: horizon,
+ tower: factoryLeft + 6,
+ towerTop: roof - 11,
+ chimney: factoryRight - 5,
+ chimneyTop: roof - 8,
+ door,
+ mast: factoryRight - 1,
+ jib: roof - 6
+ },
+ path,
+ stones,
+ fence,
+ cat: { x: floorOf(cols * 0.7), y: fence.top - 4 },
+ crow: { x: fence.right - 4, y: fence.top - 3 },
+ patch: {
+ left: floorOf(cols * 0.56),
+ right: floorOf(cols * 0.96),
+ y: floorOf(rows * 0.745)
+ },
+ hero: { x: cols * 0.77, y: rows * 0.745 },
+ stars
+ };
+}
+
+function segmentLengths(path: Point[], aspect: number) {
+ const lengths: number[] = [];
+ for (let i = 1; i < path.length; i++) {
+ const a = path[i - 1];
+ const b = path[i];
+ if (!a || !b) continue;
+ lengths.push(Math.hypot((b.x - a.x) / aspect, b.y - a.y));
+ }
+ return lengths;
+}
+
+/** The point a fraction `s` (0 to 1) of the way along a path. */
+export function pointAlong(path: Point[], s: number, aspect: number): Point {
+ const lengths = segmentLengths(path, aspect);
+ const total = lengths.reduce((sum, length) => sum + length, 0);
+ let rest = Math.max(0, Math.min(1, s)) * total;
+ for (let i = 0; i < lengths.length; i++) {
+ const length = lengths[i] ?? 0;
+ const a = path[i];
+ const b = path[i + 1];
+ if (!a || !b) break;
+ if (rest <= length || i === lengths.length - 1) {
+ const k = length === 0 ? 0 : Math.min(1, rest / length);
+ return { x: a.x + (b.x - a.x) * k, y: a.y + (b.y - a.y) * k };
+ }
+ rest -= length;
+ }
+ return path[0] ?? { x: 0, y: 0 };
+}
+
+/**
+ * Where lantern `index` of `count` stands: the oldest furthest along the
+ * path, into the fog; the newest nearest the factory door.
+ */
+export function lanternSlot(index: number, capacity: number) {
+ const spacing = 0.86 / capacity;
+ return 0.97 - index * spacing;
+}
diff --git a/packages/react/src/Halloween/night-shift/noise.ts b/packages/react/src/Halloween/night-shift/noise.ts
new file mode 100644
index 0000000000..d0cc55aa52
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/noise.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Smooth value noise for fog, moon craters, ridges and candle flicker.
+
+import { floorOf } from "./random";
+
+function lattice(x: number, y: number, seed: number) {
+ let h =
+ Math.imul(x, 374761393) +
+ Math.imul(y, 668265263) +
+ Math.imul(seed, 1442695041);
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
+}
+
+function smooth(t: number) {
+ return t * t * (3 - 2 * t);
+}
+
+/** Value noise in [0, 1], continuous in x and y. */
+export function noise2(x: number, y: number, seed = 0) {
+ const x0 = floorOf(x);
+ const y0 = floorOf(y);
+ const fx = smooth(x - x0);
+ const fy = smooth(y - y0);
+ const a = lattice(x0, y0, seed);
+ const b = lattice(x0 + 1, y0, seed);
+ const c = lattice(x0, y0 + 1, seed);
+ const d = lattice(x0 + 1, y0 + 1, seed);
+ const top = a + (b - a) * fx;
+ const bottom = c + (d - c) * fx;
+ return top + (bottom - top) * fy;
+}
+
+/** Fractal noise: `octaves` layers of `noise2`, each finer and fainter. */
+export function fbm2(x: number, y: number, octaves = 3, seed = 0) {
+ let sum = 0;
+ let amplitude = 0.5;
+ let frequency = 1;
+ let norm = 0;
+ for (let i = 0; i < octaves; i++) {
+ sum += amplitude * noise2(x * frequency, y * frequency, seed + i * 17);
+ norm += amplitude;
+ amplitude *= 0.5;
+ frequency *= 2.03;
+ }
+ return sum / norm;
+}
+
+/** A candle's flicker over time, in [0, 1]; mostly bright, now and then a dip. */
+export function flicker(seconds: number, seed = 0) {
+ const slow = noise2(seconds * 1.7, 0.5, seed);
+ const fast = noise2(seconds * 9.3, 3.5, seed + 5);
+ return Math.min(1, 0.55 + 0.35 * slow + 0.2 * fast);
+}
diff --git a/packages/react/src/Halloween/night-shift/paint.ts b/packages/react/src/Halloween/night-shift/paint.ts
new file mode 100644
index 0000000000..b34479152c
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/paint.ts
@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Paints a frame onto a canvas: the sky, the cell backgrounds, the soft
+// halos of every light, then the glyphs. Glyphs of one colour that sit side
+// by side go out as one fillText, so a frame costs a few hundred calls, not
+// one per cell. Non-ASCII glyphs (✓ ● ♪) are drawn alone and centred, since
+// a fallback font need not share the monospace advance.
+
+import type { FrameOut } from "./frame";
+import type { Grid } from "./grid";
+import { blue, css, green, NO_BG, red } from "./grid";
+
+export type Metrics = {
+ /** Cell size in CSS pixels. */
+ cellWidth: number;
+ cellHeight: number;
+ /** Where the grid starts, to centre it in the canvas. */
+ offsetX: number;
+ offsetY: number;
+ font: string;
+ width: number;
+ height: number;
+ horizonRow: number;
+};
+
+const styles = new Map<number, string>();
+
+function style(color: number) {
+ let value = styles.get(color);
+ if (!value) {
+ value = css(color);
+ styles.set(color, value);
+ }
+ return value;
+}
+
+function rgba(color: number, alpha: number) {
+ return `rgba(${red(color)},${green(color)},${blue(color)},${alpha})`;
+}
+
+/** Drops the lowest bits so neighbouring glyphs share a colour and a run. */
+function quantize(color: number) {
+ return color & 0xf8f8f8;
+}
+
+export function paint(
+ ctx: CanvasRenderingContext2D,
+ grid: Grid,
+ frame: FrameOut,
+ m: Metrics
+) {
+ const { cellWidth: cw, cellHeight: ch, offsetX: ox, offsetY: oy } = m;
+
+ const sky = ctx.createLinearGradient(0, 0, 0, oy + m.horizonRow * ch);
+ sky.addColorStop(0, style(frame.sky.top));
+ sky.addColorStop(1, style(frame.sky.horizon));
+ ctx.globalCompositeOperation = "source-over";
+ ctx.fillStyle = sky;
+ ctx.fillRect(0, 0, m.width, m.height);
+
+ for (let r = 0; r < grid.rows; r++) {
+ let runStart = -1;
+ let runColor = NO_BG;
+ const flush = (end: number) => {
+ if (runStart < 0 || runColor === NO_BG) return;
+ ctx.fillStyle = style(runColor);
+ ctx.fillRect(
+ ox + runStart * cw,
+ oy + r * ch,
+ (end - runStart) * cw + 0.6,
+ ch + 0.6
+ );
+ };
+ for (let c = 0; c < grid.cols; c++) {
+ const bg = grid.bg[r * grid.cols + c] ?? NO_BG;
+ const color = bg === NO_BG ? NO_BG : quantize(bg);
+ if (color !== runColor) {
+ flush(c);
+ runStart = c;
+ runColor = color;
+ }
+ }
+ flush(grid.cols);
+ }
+
+ ctx.globalCompositeOperation = "lighter";
+ for (const light of frame.lights) {
+ const halo = light.halo ?? 0;
+ if (halo <= 0.005) continue;
+ const x = ox + light.x * cw;
+ const y = oy + light.y * ch;
+ const radius = light.radius * ch * 1.7;
+ const gradient = ctx.createRadialGradient(x, y, 0, x, y, radius);
+ gradient.addColorStop(0, rgba(light.color, Math.min(0.6, halo)));
+ gradient.addColorStop(0.4, rgba(light.color, Math.min(0.6, halo) * 0.35));
+ gradient.addColorStop(1, rgba(light.color, 0));
+ ctx.fillStyle = gradient;
+ ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
+ }
+ ctx.globalCompositeOperation = "source-over";
+
+ ctx.font = m.font;
+ ctx.textBaseline = "middle";
+ for (let r = 0; r < grid.rows; r++) {
+ const y = oy + r * ch + ch / 2;
+ let run = "";
+ let runStart = 0;
+ let runColor = -1;
+ let pendingSpaces = 0;
+ const flush = () => {
+ if (run.length > 0) {
+ ctx.textAlign = "left";
+ ctx.fillStyle = style(runColor);
+ ctx.fillText(run, ox + runStart * cw, y);
+ }
+ run = "";
+ runColor = -1;
+ pendingSpaces = 0;
+ };
+ for (let c = 0; c < grid.cols; c++) {
+ const i = r * grid.cols + c;
+ const code = grid.ch[i] ?? 32;
+ if (code === 32) {
+ if (run.length > 0) pendingSpaces++;
+ continue;
+ }
+ const color = quantize(grid.fg[i] ?? 0);
+ if (code > 126) {
+ flush();
+ ctx.textAlign = "center";
+ ctx.fillStyle = style(color);
+ ctx.fillText(String.fromCharCode(code), ox + c * cw + cw / 2, y);
+ continue;
+ }
+ if (run.length > 0 && color === runColor && pendingSpaces < 6) {
+ run += " ".repeat(pendingSpaces) + String.fromCharCode(code);
+ pendingSpaces = 0;
+ continue;
+ }
+ flush();
+ run = String.fromCharCode(code);
+ runStart = c;
+ runColor = color;
+ }
+ flush();
+ }
+
+ if (frame.flash > 0) {
+ ctx.fillStyle = `rgba(232,228,255,${frame.flash * 0.45})`;
+ ctx.fillRect(0, 0, m.width, m.height);
+ }
+}
diff --git a/packages/react/src/Halloween/night-shift/pumpkin.ts b/packages/react/src/Halloween/night-shift/pumpkin.ts
new file mode 100644
index 0000000000..9a2b38ce24
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/pumpkin.ts
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Pumpkins, shaded as solids: each cell inside the outline gets a surface
+// normal, the moon lights it from the upper right, and the ribs darken it in
+// grooves that turn as the pumpkin turns. Carved cells show the candle
+// inside, flickering.
+
+import type { Face } from "./faces";
+import { cellKey, miniFace } from "./faces";
+import type { Color, Grid } from "./grid";
+import { hex, mix, scale } from "./grid";
+import { noise2 } from "./noise";
+
+const RIND_RAMP = ".:-=+*#%@";
+const GLOW_RAMP = "+*%#@";
+
+const RIND_DARK = hex("#2a0e04");
+const RIND_LIT = hex("#ff8c22");
+const RIM = hex("#9b8cd0");
+const GLOW_DIM = hex("#c2410c");
+const GLOW_HOT = hex("#fff4cc");
+const HOLE = hex("#0b0405");
+const STEM = hex("#6b7a2e");
+
+// The moon, up and to the right, a little towards the viewer.
+const LIGHT = { x: 0.55, y: -0.55, z: 0.63 };
+
+export type PumpkinLook = {
+ x: number;
+ y: number;
+ /** Half the height in rows; the width follows from the cell aspect. */
+ radius: number;
+ aspect: number;
+ /** Turns the ribs, in radians. */
+ spin?: number;
+ /** Carved cells, keyed with `cellKey`, relative to the centre. */
+ carved?: ReadonlySet<number>;
+ /** How brightly the candle inside burns, 0 to 1. */
+ glow?: number;
+ seconds: number;
+ /** Overall light, so a pumpkin in deep fog or shadow can sit back. */
+ ambient?: number;
+ /** Light that reaches the side away from the moon, 0 to 1. */
+ fill?: number;
+};
+
+/** Draws a pumpkin and returns the cells its carved face covers. */
+export function drawPumpkin(grid: Grid, look: PumpkinLook) {
+ const { x, y, radius, aspect, seconds } = look;
+ const rx = radius * aspect * 1.18;
+ const ry = radius;
+ const spin = look.spin ?? 0;
+ const glow = look.glow ?? 0;
+ const ambient = look.ambient ?? 1;
+ const fill = look.fill ?? 0.12;
+ const top = Math.trunc(y - ry) - 1;
+ const bottom = Math.trunc(y + ry) + 1;
+ const left = Math.trunc(x - rx) - 1;
+ const right = Math.trunc(x + rx) + 1;
+ for (let row = top; row <= bottom; row++) {
+ for (let col = left; col <= right; col++) {
+ const nx = (col + 0.5 - x) / rx;
+ const ny = (row + 0.5 - y) / ry;
+ const d2 = nx * nx + ny * ny;
+ if (d2 > 1) continue;
+ const nz = Math.sqrt(1 - d2);
+ const dx = col - Math.trunc(x);
+ const dy = row - Math.trunc(y);
+ if (look.carved?.has(cellKey(dx, dy))) {
+ if (glow > 0) {
+ const heat =
+ glow * (0.72 + 0.28 * noise2(seconds * 8 + dx * 0.4, dy * 0.6, 3));
+ const char =
+ GLOW_RAMP[
+ Math.min(
+ GLOW_RAMP.length - 1,
+ Math.trunc(heat * GLOW_RAMP.length)
+ )
+ ] ?? "@";
+ grid.put(col, row, char, mix(GLOW_DIM, GLOW_HOT, heat));
+ grid.fill(col, row, mix(HOLE, hex("#5a1a00"), heat));
+ } else {
+ grid.blank(col, row, HOLE);
+ }
+ continue;
+ }
+ const lambert = Math.max(0, nx * LIGHT.x + ny * LIGHT.y + nz * LIGHT.z);
+ const longitude = Math.atan2(nx, nz);
+ const rib = 0.5 + 0.5 * Math.cos((longitude + spin) * 6);
+ const groove = 0.62 + 0.38 * Math.sqrt(rib);
+ // A lit lantern's rind sits back so its carved face reads.
+ const brightness = Math.min(
+ 1,
+ (fill + (1 - fill) * lambert) * groove * ambient * (1 - 0.45 * glow)
+ );
+ const char =
+ RIND_RAMP[
+ Math.min(
+ RIND_RAMP.length - 1,
+ Math.trunc(brightness * RIND_RAMP.length)
+ )
+ ] ?? ".";
+ let color = mix(RIND_DARK, RIND_LIT, brightness);
+ if (d2 > 0.7 && nx > 0.15 && ny < 0.1) color = mix(color, RIM, 0.35);
+ grid.put(col, row, char, color);
+ grid.fill(col, row, scale(RIND_DARK, 0.6));
+ }
+ }
+ grid.put(x, y - ry - 0.6, ")", STEM);
+ grid.put(x + 1, y - ry - 0.6, "~", scale(STEM, 0.8));
+}
+
+const LANTERN_RIND = hex("#b4500f");
+const LANTERN_FACE = hex("#ffd36a");
+
+/** A lantern in the procession: `(^w^)`, or its back while it looks away. */
+export function drawLantern(
+ grid: Grid,
+ x: number,
+ y: number,
+ face: Face,
+ options: { lit: number; away?: boolean; tint?: Color }
+) {
+ const text = options.away ? "(:|:)" : miniFace(face);
+ const left = x - 2;
+ const lit = options.lit;
+ const faceColor = options.tint ?? mix(GLOW_DIM, LANTERN_FACE, lit);
+ for (let k = 0; k < text.length; k++) {
+ const char = text[k] ?? " ";
+ const isShell = k === 0 || k === text.length - 1 || options.away;
+ grid.put(
+ left + k,
+ y,
+ char,
+ isShell ? mix(scale(LANTERN_RIND, 0.6), LANTERN_RIND, lit) : faceColor
+ );
+ }
+ grid.put(x, y - 1, "'", STEM);
+}
diff --git a/packages/react/src/Halloween/night-shift/random.ts b/packages/react/src/Halloween/night-shift/random.ts
new file mode 100644
index 0000000000..84f3bd7038
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/random.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Seeded randomness for the Night Shift. Every shift is drawn from its own
+// seed, so a shift looks the same however often it is rendered, and the
+// story can be replayed (and tested) from the seed alone.
+
+export type Random = () => number;
+
+/** Mulberry32: small, fast and good enough for picking pumpkin faces. */
+export function seeded(seed: number): Random {
+ let state = seed >>> 0;
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let t = state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** Folds numbers into one 32-bit seed (FNV-1a over their bits). */
+export function hashSeed(...parts: number[]): number {
+ let hash = 2166136261;
+ for (const part of parts) {
+ hash ^= part >>> 0;
+ hash = Math.imul(hash, 16777619);
+ hash ^= hash >>> 13;
+ }
+ return hash >>> 0;
+}
+
+/** The whole-number part, rounded towards minus infinity. */
+export function floorOf(value: number): number {
+ const whole = Math.trunc(value);
+ return value < whole ? whole - 1 : whole;
+}
+
+/** Picks by weight: `[["a", 3], ["b", 1]]` gives "a" three times in four. */
+export function pickWeighted<T>(
+ random: Random,
+ weighted: readonly (readonly [T, number])[]
+): T {
+ const total = weighted.reduce((sum, [, weight]) => sum + weight, 0);
+ let roll = random() * total;
+ for (const [item, weight] of weighted) {
+ roll -= weight;
+ if (roll < 0) return item;
+ }
+ const last = weighted.at(-1);
+ if (!last) throw new Error("pickWeighted: empty list");
+ return last[0];
+}
diff --git a/packages/react/src/Halloween/night-shift/scene.ts b/packages/react/src/Halloween/night-shift/scene.ts
new file mode 100644
index 0000000000..700851665f
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/scene.ts
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// What every scene of the Night Shift draws with: the grid, the hill's
+// layout, the shift's plan, where the story is, and what the person at the
+// login form is doing.
+
+import type { Color, Grid } from "./grid";
+import type { Layout, Point } from "./layout";
+import type { Moment, ShiftPlan } from "./story";
+
+/** A light: tints the glyphs around it and, with `halo`, glows on the canvas. */
+export type Light = {
+ x: number;
+ y: number;
+ /** Reach, in rows. */
+ radius: number;
+ color: Color;
+ /** How strongly it tints glyphs, 0 to about 1. */
+ power: number;
+ /** Opacity of the soft halo painted under the glyphs. */
+ halo?: number;
+};
+
+/** The login form, as the scene reacts to it. */
+export type Watcher = {
+ /** The pointer, in cells, while it is over the page. */
+ pointer: Point | null;
+ /** A field has focus: the cat looks at the form. */
+ field: boolean;
+ /** A secret field (password, one-time code) has focus: nobody looks. */
+ secret: boolean;
+ /** The secret is shown in clear: one lantern peeks. */
+ peek: boolean;
+ /** 1 just after a submit, fading to 0: every lantern flares. */
+ flare: number;
+ /** 1 just after an error, fading to 0: the lanterns flicker red. */
+ alarm: number;
+};
+
+export const IDLE_WATCHER: Watcher = {
+ pointer: null,
+ field: false,
+ secret: false,
+ peek: false,
+ flare: 0,
+ alarm: 0
+};
+
+export type Scene = {
+ grid: Grid;
+ layout: Layout;
+ plan: ShiftPlan;
+ moment: Moment;
+ /** Seconds since the story started: drives flicker and drift. */
+ seconds: number;
+ watcher: Watcher;
+ lights: Light[];
+};
+
+export function clamp01(value: number) {
+ return value <= 0 ? 0 : value >= 1 ? 1 : value;
+}
+
+/** 0 before `from`, 1 after `to`, linear between. */
+export function segment(t: number, from: number, to: number) {
+ return clamp01((t - from) / (to - from));
+}
+
+export function ease(t: number) {
+ const k = clamp01(t);
+ return k * k * (3 - 2 * k);
+}
+
+export function lerp(a: number, b: number, t: number) {
+ return a + (b - a) * t;
+}
+
+/** The nearest whole number, halves away from zero. */
+export function nearest(value: number) {
+ return value >= 0 ? Math.trunc(value + 0.5) : -Math.trunc(-value + 0.5);
+}
+
+/** The fractional part, always in [0, 1). */
+export function fraction(value: number) {
+ return (
+ value -
+ Math.trunc(value) +
+ (value < 0 && value !== Math.trunc(value) ? 1 : 0)
+ );
+}
+
+/** A stable pseudo-random number in [0, 1) for an integer. */
+export function hash01(n: number) {
+ let h = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b);
+ h ^= h >>> 13;
+ h = Math.imul(h, 0xc2b2ae35);
+ h ^= h >>> 16;
+ return (h >>> 0) / 4294967296;
+}
diff --git a/packages/react/src/Halloween/night-shift/sprites.ts b/packages/react/src/Halloween/night-shift/sprites.ts
new file mode 100644
index 0000000000..75a339e143
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/sprites.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The cast, in ASCII. Spaces are transparent; `$` hides what is behind
+// without drawing a glyph, so a ghost in front of a gravestone covers it.
+// String.raw keeps the backslashes as drawn.
+
+const r = String.raw;
+
+export const GHOST = {
+ open: [r` .---. `, r` /$o$o$\ `, r` |$$O$$| `, r` |$$$$$| `],
+ shut: [r` .---. `, r` /$=$=$\ `, r` |$$~$$| `, r` |$$$$$| `],
+ peek: [r` .---. `, r` /$o$=$\ `, r` |$$o$$| `, r` |$$$$$| `],
+ hem: [r` '^v^v^' `, r` 'v^v^v' `]
+};
+
+export const SKELETON = {
+ stand: [r` .-. `, r` (o.o) `, r` |=| `, r` /|=|\ `, r` / \ `],
+ stampUp: [r` .-. _`, r` (o.o)|`, r` |=|/ `, r` /|=| `, r` / \ `],
+ stampDown: [r` .-. `, r` (o.o) `, r` |=|__`, r` /|=| #`, r` / \ `],
+ runA: [r` .-. `, r` (o.o) `, r` |=|\ `, r` /|=| `, r` / > `],
+ runB: [r` .-. `, r` (o.o) `, r` /|=| `, r` |=|\ `, r` |\ `],
+ danceA: [r`\ .-. /`, r` (o.o) `, r` |=| `, r` |=| `, r` / \ `],
+ danceB: [r` .-. `, r` (^.^) `, r` /|=|\ `, r` |=| `, r` | \_`]
+};
+
+export const CAT = {
+ ears: r` /\_/\ `,
+ eyes: {
+ left: r`(o o ) `,
+ ahead: r`( o o ) `,
+ right: r`( o o) `,
+ blink: r`( - - ) `
+ },
+ body: [r` = ^ = `, r`/$$$$$\ `, r`(_)_(_)~`]
+};
+
+export const CROW = [r` _ `, r` (o> `, r`/)_) `, r` '' `];
+
+export const STONES = {
+ rip: [r` .-. `, r`|RIP|`, r`|$$$|`],
+ small: [r` __ `, r`|$$|`],
+ cross: [r` | `, r`-+-`, r` | `],
+ round: [r` .--. `, r`/$$$$\ `, r`|$$$$|`]
+};
+
+export const BAT = [r`\v/`, r`-v-`, r`/v\ `];
+
+export const WITCH = {
+ body: [
+ r` /\ `,
+ r` / \ `,
+ r` _/____\_ `,
+ r` (o ) `,
+ r` /|$$|\ `
+ ],
+ cape: [r` /|$$|\~ `, r` /|$$|\~~ `],
+ broom: r` ===|==|===}}}} `
+};
+
+export const HORSEMAN = {
+ body: [
+ r` (@) `,
+ r` _/| `,
+ r` __,--'$$|__ `,
+ r` /$$_____$$$_\_ `
+ ],
+ legs: [r` / / \ \/ \/ `, r` \ \ / /\ /\ `]
+};
+
+export const SPIDER = [
+ r` \ || / `,
+ r` \ \(oo)/ / `,
+ r` -=($$)=- `,
+ r` / /(__)\ \ `,
+ r` / \ `
+];
+
+export const SHIP = [
+ r` | | | `,
+ r` )_) )_) )_) `,
+ r` )___))___))___)\ `,
+ r` )____)____)_____)\\ `,
+ r` _____|____|____|____\\\__`,
+ r` \$$$$$$$$$$$$$$$$$$$/ `
+];
+
+export const CANDLE = [r` ^ `, r`|$|`, r`|_|`];
+
+export const LAMP = [r` | `, r`/~\ `];
+
+export const NOZZLE = [r`||`, r`||`, r`\/`];
+
+export const CLOCK = [
+ r` .---. `,
+ r`/$$$$$\ `,
+ r`|$$$$$|`,
+ r`\$$$$$/`,
+ r` '---' `
+];
+
+/** Dot-matrix letters for the bats' "BOO", one '#' per bat: 52 bats. */
+export const BOO = [
+ ["####.", "#...#", "#...#", "####.", "#...#", "#...#", "####."],
+ [".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###."],
+ [".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###."]
+];
+
+/**
+ * The Carbon mark as thirteen stars, on the logo's own 424 × 480 canvas:
+ * the hexagon, then the inner shape. `MARK_EDGES` joins them.
+ */
+export const MARK_STARS = [
+ { x: 212, y: 0 },
+ { x: 424, y: 120 },
+ { x: 424, y: 360 },
+ { x: 212, y: 480 },
+ { x: 0, y: 360 },
+ { x: 0, y: 120 },
+ { x: 212, y: 110 },
+ { x: 112, y: 177 },
+ { x: 204, y: 240 },
+ { x: 204, y: 350 },
+ { x: 320, y: 300 },
+ { x: 320, y: 240 },
+ { x: 320, y: 180 }
+];
+
+export const MARK_EDGES: readonly (readonly [number, number])[] = [
+ [0, 1],
+ [1, 2],
+ [2, 3],
+ [3, 4],
+ [4, 5],
+ [5, 0],
+ [6, 7],
+ [7, 8],
+ [8, 9],
+ [9, 10],
+ [10, 11],
+ [11, 12],
+ [12, 6]
+];
diff --git a/packages/react/src/Halloween/night-shift/story.test.ts b/packages/react/src/Halloween/night-shift/story.test.ts
new file mode 100644
index 0000000000..3047d11f0a
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/story.test.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The story's rules: one shift is ninety seconds of six acts, a shift is
+// the same however often it is drawn, the hill keeps every lantern it ships
+// (but a rejected one), and a full hill rises and starts over.
+
+import { describe, expect, it } from "vitest";
+import {
+ ACTS,
+ actStart,
+ LANTERNS_FOR_LIGHTING,
+ momentAt,
+ planShift,
+ processionAfter,
+ SHIFT_SECONDS
+} from "./story";
+
+describe("momentAt", () => {
+ it("plays the six acts in order, ninety seconds a shift", () => {
+ expect(SHIFT_SECONDS).toBe(90);
+ expect(ACTS.map((act) => act.id)).toEqual([
+ "midnight",
+ "harvest",
+ "line",
+ "shipping",
+ "witching",
+ "dawn"
+ ]);
+ for (const act of ACTS) {
+ const moment = momentAt(actStart(act.id) + 0.5);
+ expect(moment.act).toBe(act.id);
+ expect(moment.t).toBeCloseTo(0.5);
+ }
+ });
+
+ it("starts the next shift at midnight, counting from the first", () => {
+ const moment = momentAt(SHIFT_SECONDS * 2 + 1, 5);
+ expect(moment.shift).toBe(7);
+ expect(moment.act).toBe("midnight");
+ expect(moment.shiftT).toBeCloseTo(1);
+ });
+});
+
+describe("planShift", () => {
+ it("is the same shift however often it is drawn", () => {
+ expect(planShift(42, 6)).toEqual(planShift(42, 6));
+ });
+
+ it("differs from shift to shift", () => {
+ const faces = new Set(
+ Array.from({ length: 12 }, (_, i) =>
+ JSON.stringify(planShift(42, i).face)
+ )
+ );
+ expect(faces.size).toBeGreaterThan(6);
+ });
+
+ it("walks the moon through its phases, one step of eight per shift", () => {
+ expect(planShift(1, 0).moonPhase).toBe(0);
+ expect(planShift(1, 4).moonPhase).toBe(0.5);
+ expect(planShift(1, 8).moonPhase).toBe(0);
+ });
+
+ it("keeps every lantern it ships, until thirteen rise and the hill is empty", () => {
+ for (const seed of [1, 2, 3, 7, 99]) {
+ let lightings = 0;
+ for (let i = 0; i < 40; i++) {
+ const plan = planShift(seed, i);
+ const next = planShift(seed, i + 1);
+ expect(next.procession).toEqual(processionAfter(plan));
+ expect(plan.procession.length).toBeLessThan(LANTERNS_FOR_LIGHTING);
+ if (plan.event === "reject") {
+ expect(next.procession).toHaveLength(plan.procession.length);
+ } else if (plan.greatLighting) {
+ lightings++;
+ expect(plan.procession.length + 1).toBe(LANTERNS_FOR_LIGHTING);
+ expect(next.procession).toHaveLength(0);
+ } else {
+ expect(next.procession).toEqual([...plan.procession, plan.face]);
+ }
+ }
+ expect(lightings).toBeGreaterThan(0);
+ }
+ });
+
+ it("numbers the work order by shift", () => {
+ expect(planShift(1, 0).job).toBe("JOB-1031");
+ expect(planShift(1, 3).job).toBe("JOB-1034");
+ });
+
+ it("brings every rare event and every visitor sooner or later", () => {
+ const events = new Set<string>();
+ const visitors = new Set<string>();
+ for (let seed = 1; seed < 60; seed++) {
+ for (let i = 0; i < 6; i++) {
+ const plan = planShift(seed, i);
+ events.add(plan.event);
+ visitors.add(plan.visitor);
+ }
+ }
+ expect([...events].sort()).toEqual(["boo", "dance", "none", "reject"]);
+ expect([...visitors].sort()).toEqual([
+ "horseman",
+ "ship",
+ "spider",
+ "witch"
+ ]);
+ });
+});
diff --git a/packages/react/src/Halloween/night-shift/story.ts b/packages/react/src/Halloween/night-shift/story.ts
new file mode 100644
index 0000000000..22812cd4d8
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/story.ts
@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The Night Shift: a haunted plant on a hill works one shift, midnight to a
+// dawn that never comes, making one jack-o'-lantern. Every shift is seeded,
+// so it differs from the last (face, weather, visitor, moon phase, now and
+// then a rare event), and the lanterns it ships stay on the hill. When the
+// hill holds thirteen, they all rise and become the Carbon mark in the sky.
+
+import type { Face } from "./faces";
+import { drawFace } from "./faces";
+import { hashSeed, pickWeighted, seeded } from "./random";
+
+export const ACTS = [
+ { id: "midnight", seconds: 9 },
+ { id: "harvest", seconds: 14 },
+ { id: "line", seconds: 24 },
+ { id: "shipping", seconds: 18 },
+ { id: "witching", seconds: 14 },
+ { id: "dawn", seconds: 11 }
+] as const;
+
+export type ActId = (typeof ACTS)[number]["id"];
+
+export const SHIFT_SECONDS = ACTS.reduce((sum, act) => sum + act.seconds, 0);
+
+/** Where the story is: which shift, which act, how far into it. */
+export type Moment = {
+ shift: number;
+ act: ActId;
+ /** Seconds into the act. */
+ t: number;
+ /** 0 to 1 through the act. */
+ progress: number;
+ /** Seconds into the shift. */
+ shiftT: number;
+};
+
+export function actStart(id: ActId) {
+ let start = 0;
+ for (const act of ACTS) {
+ if (act.id === id) return start;
+ start += act.seconds;
+ }
+ return start;
+}
+
+export function momentAt(seconds: number, firstShift = 0): Moment {
+ const elapsed = Math.max(0, seconds);
+ const shifts = Math.trunc(elapsed / SHIFT_SECONDS);
+ const shiftT = elapsed - shifts * SHIFT_SECONDS;
+ let start = 0;
+ for (const act of ACTS) {
+ if (shiftT < start + act.seconds) {
+ const t = shiftT - start;
+ return {
+ shift: firstShift + shifts,
+ act: act.id,
+ t,
+ progress: t / act.seconds,
+ shiftT
+ };
+ }
+ start += act.seconds;
+ }
+ const last = ACTS[ACTS.length - 1];
+ return {
+ shift: firstShift + shifts,
+ act: last?.id ?? "dawn",
+ t: last?.seconds ?? 0,
+ progress: 1,
+ shiftT
+ };
+}
+
+export type Weather = "clear" | "drizzle" | "fog";
+export type Visitor = "witch" | "horseman" | "spider" | "ship";
+export type RareEvent = "none" | "reject" | "boo" | "dance";
+
+export const LANTERNS_FOR_LIGHTING = 13;
+const OPENING_LANTERNS = 4;
+
+export type ShiftPlan = {
+ index: number;
+ /** The work order on the line's ticket, e.g. "JOB-1031". */
+ job: string;
+ face: Face;
+ weather: Weather;
+ visitor: Visitor;
+ event: RareEvent;
+ /** 0 full, 0.5 new, back to full at 1; one step of eight per shift. */
+ moonPhase: number;
+ /** The lanterns already on the hill when the shift starts, oldest first. */
+ procession: Face[];
+ /** This shift's lantern fills the hill: they rise instead of a visitor. */
+ greatLighting: boolean;
+};
+
+function drawShift(seed: number, index: number, procession: Face[]): ShiftPlan {
+ const random = seeded(hashSeed(seed, index));
+ const face = drawFace(random);
+ const weather = pickWeighted<Weather>(random, [
+ ["clear", 9],
+ ["drizzle", 5],
+ ["fog", 6]
+ ]);
+ const visitor = pickWeighted<Visitor>(random, [
+ ["witch", 1],
+ ["horseman", 1],
+ ["spider", 1],
+ ["ship", 1]
+ ]);
+ const event = pickWeighted<RareEvent>(random, [
+ ["none", 17],
+ ["reject", 1],
+ ["boo", 1],
+ ["dance", 1]
+ ]);
+ const greatLighting =
+ event !== "reject" && procession.length + 1 >= LANTERNS_FOR_LIGHTING;
+ return {
+ index,
+ job: `JOB-${1031 + index}`,
+ face,
+ weather,
+ visitor,
+ event,
+ moonPhase: (((index % 8) + 8) % 8) / 8,
+ procession,
+ greatLighting
+ };
+}
+
+/** The lanterns on the hill once a shift is over. */
+export function processionAfter(plan: ShiftPlan): Face[] {
+ if (plan.event === "reject") return plan.procession;
+ if (plan.greatLighting) return [];
+ return [...plan.procession, plan.face];
+}
+
+function openingProcession(seed: number) {
+ const random = seeded(hashSeed(seed, 0x0bad5eed));
+ return Array.from({ length: OPENING_LANTERNS }, () => drawFace(random));
+}
+
+/** Plays the story from the first shift to `index` and returns that shift. */
+export function planShift(seed: number, index: number): ShiftPlan {
+ let procession = openingProcession(seed);
+ for (let k = 0; k < index; k++) {
+ procession = processionAfter(drawShift(seed, k, procession));
+ }
+ return drawShift(seed, index, procession);
+}
diff --git a/packages/react/src/Halloween/season.ts b/packages/react/src/Halloween/season.ts
index a401af3915..e25c4e7ec1 100644
--- a/packages/react/src/Halloween/season.ts
+++ b/packages/react/src/Halloween/season.ts
@@ -7,10 +7,11 @@ import { useSyncExternalStore } from "react";
import { useFetchers } from "react-router";
import { useRouteData } from "../hooks/useRouteData";
-// The one check every Halloween decoration sits behind: the user picked the
-// Halloween theme in Account settings → Appearance. Nobody else gets anything
-// rendered, styled or listened to. Out of season the server renders the
-// default theme instead (`resolveTheme`), so it switches itself off on time.
+// The one check every Halloween decoration sits behind: the root loader's
+// theme is Halloween. While it is in season the theme is forced for everyone
+// (`forced` on `halloweenTheme`); out of season the server renders the
+// stored or default theme instead (`resolveTheme`), so everything switches
+// itself off on time and nothing is rendered, styled or listened to.
// Hydration never reverses, so there is nothing to listen to.
function subscribe() {
diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.md
index b0d2306a33..783af810f1 100644
--- a/packages/utils/AGENTS.md
+++ b/packages/utils/AGENTS.md
@@ -64,6 +64,7 @@ pnpm --filter @carbon/utils typecheck
| `planning-sizing` | `computePlanningOrders` — reorder-quantity sizing for the four reordering policies (`ComputePlanningOrdersInput` — `{ reorderingPolicy, periods, projections, todayDate, params: PlanningSizingParams }` — in, `PlanningOrderSuggestion[]` out). Pure and clock-free (`todayDate` is injected). Also `orderSizingRules(policyName, params)` — how ONE order of a policy is sized (per-order quantity, daily vs spread, maximum, minimum, multiples) — shared by MRP's change actions and the planning pages: `splitIntoOrders` (a week's summed action back into its orders; `lotSizeBatches` is the batch case) and `reducedOrderQuantity` (a Decrease's floor and multiples). Shared by the MRP engine and the item planning tab's `ItemReorderPolicy`, so both size an order the same way; `planning-sizing.test.ts` pins it against hand-computed results of the SQL `calculate_quantity_to_order` |
| `precision` | The whole numeric-precision API (re-exported from `@carbon/database/precision`): `SCALE`, `EPSILON`, `RoundingMode`, `round`, `distributeRoundingResidual`, `scrapAllowance`, `applyRate`, `deriveRate`, `isBalanced`, `assertBalanced` |
| `format` | The ONLY place display/input digit counts are chosen: `moneyFormatOptions` (settlement — the currency's decimals are floor AND ceiling), `rateFormatOptions` (per-unit RATE — those decimals are only the floor, ceiling is `SCALE`), the `PERCENT_FORMAT` / `PERCENT_POINTS_FORMAT` / `SCALE_FORMAT` constants, `cldrCurrencyDecimals`, their `format*` helpers, and `INPUT_FORMAT` / `INPUT_STEP` for editable fields. Call sites pick a KIND, never a digit count |
+| `themes` | The everyday `themes` (every picker lists them) and `seasonalThemes` (each in its own file, e.g. `halloween-theme.ts`, typed `SeasonalTheme`: an `available` window, optionally `forced` for everyone in season and its own `mesh` colors). `resolveTheme` (what to render for a stored name, falling back to `DEFAULT_THEME_NAME`), `selectableThemes` (the Appearance pane), `isThemeAvailable`, `seasonalMeshColors`. A seasonal theme declares everything about itself, so removing it touches no caller |
| `string` | Slugify, truncate, camelCase/titleCase conversions |
| `items` | Item lookups and `getReadableIdWithRevision` (`readableId.revision`) |
| `revalidate` | `shouldRevalidate` predicates: `isSearchParamOnlyNavigation` (the root loader only; layouts do not skip their loaders, see `coding-conventions.md` → Routes) |
diff --git a/packages/utils/src/halloween-theme.ts b/packages/utils/src/halloween-theme.ts
index 4a9b771255..9f06bcd0ec 100644
--- a/packages/utils/src/halloween-theme.ts
+++ b/packages/utils/src/halloween-theme.ts
@@ -2,12 +2,12 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import type { ThemeWindow } from "./themes";
+import type { SeasonalTheme } from "./themes";
-// Seasonal theme. To remove it, delete this file, its entry in `themes`
-// (themes.ts), its export in index.ts and its mesh colors in the ERP's
-// MeshGradientBackground.tsx. A browser still holding the cookie falls back
-// to the default theme, as it already does outside the window.
+// Seasonal theme, forced for everyone while in season. It goes together with
+// its decorations: the removal checklist is at the top of
+// packages/react/src/Halloween/HalloweenLayer.tsx. A browser still holding
+// its cookie falls back to the default theme, as it does out of season.
export const halloweenTheme = {
name: "halloween",
@@ -15,7 +15,12 @@ export const halloweenTheme = {
available: {
from: { month: 10, day: 20 },
to: { month: 11, day: 1 }
- } satisfies ThemeWindow,
+ },
+ forced: true,
+ mesh: {
+ light: ["#fdf0e4", "#f6f0fa", "#fffaf5", "#fbefe6"],
+ dark: ["#2d1205", "#14081f", "#0D0D0D", "#050505"]
+ },
activeColor: {
light: "25 95% 50%",
dark: "25 95% 53%"
@@ -72,4 +77,4 @@ export const halloweenTheme = {
"success-foreground": "0 0% 98%"
}
}
-} as const;
+} as const satisfies SeasonalTheme;
diff --git a/packages/utils/src/themes.test.ts b/packages/utils/src/themes.test.ts
index a5403fafcc..a1ce5dcfec 100644
--- a/packages/utils/src/themes.test.ts
+++ b/packages/utils/src/themes.test.ts
@@ -2,38 +2,49 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+// The season window is tested on a fixture, and the registry on whatever
+// seasonal themes exist, so removing one (Halloween) leaves this file as is.
+
import { CalendarDate } from "@internationalized/date";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { halloweenTheme } from "./halloween-theme";
import {
DEFAULT_THEME_NAME,
isThemeAvailable,
resolveTheme,
+ type SeasonalTheme,
+ seasonalMeshColors,
+ seasonalThemes,
selectableThemes,
+ type ThemeWindow,
themes
} from "./themes";
-const inSeason = new CalendarDate(2026, 10, 31);
-const firstDay = new CalendarDate(2026, 10, 20);
-const lastDay = new CalendarDate(2026, 11, 1);
-const dayBefore = new CalendarDate(2026, 10, 19);
-const dayAfter = new CalendarDate(2026, 11, 2);
+// Typed by what a seasonal theme may declare, so it compiles when empty.
+const seasonal: readonly SeasonalTheme[] = seasonalThemes;
+
+const spooky: { name: string; available: ThemeWindow } = {
+ name: "spooky",
+ available: { from: { month: 10, day: 20 }, to: { month: 11, day: 1 } }
+};
describe("isThemeAvailable", () => {
it("always offers a theme with no window", () => {
- const zinc = resolveTheme("zinc", dayAfter);
- expect(isThemeAvailable(zinc, dayAfter)).toBe(true);
+ expect(isThemeAvailable(themes[0], new CalendarDate(2026, 3, 15))).toBe(
+ true
+ );
});
it("offers a seasonal theme inside its window, both ends included", () => {
- expect(isThemeAvailable(halloweenTheme, firstDay)).toBe(true);
- expect(isThemeAvailable(halloweenTheme, inSeason)).toBe(true);
- expect(isThemeAvailable(halloweenTheme, lastDay)).toBe(true);
+ expect(isThemeAvailable(spooky, new CalendarDate(2026, 10, 20))).toBe(true);
+ expect(isThemeAvailable(spooky, new CalendarDate(2026, 10, 31))).toBe(true);
+ expect(isThemeAvailable(spooky, new CalendarDate(2026, 11, 1))).toBe(true);
});
it("withholds a seasonal theme outside its window", () => {
- expect(isThemeAvailable(halloweenTheme, dayBefore)).toBe(false);
- expect(isThemeAvailable(halloweenTheme, dayAfter)).toBe(false);
+ expect(isThemeAvailable(spooky, new CalendarDate(2026, 10, 19))).toBe(
+ false
+ );
+ expect(isThemeAvailable(spooky, new CalendarDate(2026, 11, 2))).toBe(false);
});
});
@@ -45,7 +56,7 @@ describe("isThemeAvailable with no date", () => {
const availableAt = (instant: string) => {
vi.useFakeTimers();
vi.setSystemTime(instant);
- return isThemeAvailable(halloweenTheme);
+ return isThemeAvailable(spooky);
};
it("opens once the first time zone reaches the first day", () => {
@@ -63,36 +74,66 @@ describe("isThemeAvailable with no date", () => {
});
});
-describe("selectableThemes", () => {
- it("adds the seasonal theme to the everyday ones only in season", () => {
- expect(selectableThemes(inSeason)).toHaveLength(themes.length + 1);
- expect(selectableThemes(dayAfter)).toHaveLength(themes.length);
- });
+// A day no seasonal theme is in season.
+const ordinaryDay = new CalendarDate(2026, 3, 15);
- it("never puts a seasonal theme in the everyday list", () => {
- expect(themes.map((t) => t.name)).not.toContain(halloweenTheme.name);
+describe("resolveTheme on an ordinary day", () => {
+ it("is a day with no theme in season", () => {
+ for (const theme of seasonal) {
+ expect(isThemeAvailable(theme, ordinaryDay)).toBe(false);
+ }
});
-});
-describe("resolveTheme", () => {
it("returns the stored theme when it is offered", () => {
- expect(resolveTheme("violet", dayAfter).name).toBe("violet");
- expect(resolveTheme(halloweenTheme.name, inSeason).name).toBe(
- halloweenTheme.name
- );
+ expect(resolveTheme("violet", ordinaryDay).name).toBe("violet");
});
- it("falls back to the default for a seasonal theme out of season", () => {
- expect(resolveTheme(halloweenTheme.name, dayAfter).name).toBe(
+ it("falls back to the default for a removed or missing theme", () => {
+ expect(resolveTheme("pumpkin-spice", ordinaryDay).name).toBe(
DEFAULT_THEME_NAME
);
+ expect(resolveTheme(undefined, ordinaryDay).name).toBe(DEFAULT_THEME_NAME);
+ expect(resolveTheme(null, ordinaryDay).name).toBe(DEFAULT_THEME_NAME);
});
- it("falls back to the default for a removed or missing theme", () => {
- expect(resolveTheme("pumpkin-spice", inSeason).name).toBe(
- DEFAULT_THEME_NAME
- );
- expect(resolveTheme(undefined).name).toBe(DEFAULT_THEME_NAME);
- expect(resolveTheme(null).name).toBe(DEFAULT_THEME_NAME);
+ it("offers only the everyday themes", () => {
+ expect(selectableThemes(ordinaryDay)).toEqual([...themes]);
});
});
+
+for (const theme of seasonal) {
+ const { from, to } = theme.available;
+ const firstDay = new CalendarDate(2026, from.month, from.day);
+ const dayAfter = new CalendarDate(2026, to.month, to.day).add({ days: 1 });
+
+ describe(`seasonal theme "${theme.name}"`, () => {
+ it("is never one of the everyday themes", () => {
+ expect(themes.map((t) => t.name)).not.toContain(theme.name);
+ });
+
+ it("is offered in season and withdrawn after it", () => {
+ expect(selectableThemes(firstDay).map((t) => t.name)).toContain(
+ theme.name
+ );
+ expect(selectableThemes(dayAfter).map((t) => t.name)).not.toContain(
+ theme.name
+ );
+ });
+
+ it("renders in season, for everyone when forced", () => {
+ expect(resolveTheme(theme.name, firstDay).name).toBe(theme.name);
+ expect(resolveTheme("violet", firstDay).name).toBe(
+ theme.forced ? theme.name : "violet"
+ );
+ });
+
+ it("gives way after its season, to the stored theme or the default", () => {
+ expect(resolveTheme(theme.name, dayAfter).name).toBe(DEFAULT_THEME_NAME);
+ expect(resolveTheme("violet", dayAfter).name).toBe("violet");
+ });
+
+ it("brings its own mesh colors", () => {
+ expect(seasonalMeshColors(theme.name)).toEqual(theme.mesh);
+ });
+ });
+}
diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.ts
index 3db2112543..169501ee88 100644
--- a/packages/utils/src/themes.ts
+++ b/packages/utils/src/themes.ts
@@ -502,6 +502,28 @@ type MonthDay = { month: number; day: number };
*/
export type ThemeWindow = { from: MonthDay; to: MonthDay };
+/** Four mesh-gradient stops per mode, for the ERP's onboarding backdrop. */
+export type MeshColors = {
+ light: readonly [string, string, string, string];
+ dark: readonly [string, string, string, string];
+};
+
+/**
+ * What a seasonal theme declares. Everything about it lives on the theme, so
+ * removing one is deleting its file and its `seasonalThemes` entry.
+ */
+export type SeasonalTheme = {
+ name: string;
+ label: string;
+ available: ThemeWindow;
+ /** While in season, every browser renders it, whatever theme it picked. */
+ forced?: boolean;
+ /** Its mesh-gradient colors (`seasonalMeshColors`). */
+ mesh?: MeshColors;
+ activeColor: { light: string; dark: string };
+ cssVars: { light: Record<string, string>; dark: Record<string, string> };
+};
+
/**
* Themes offered only for a while each year, and only in Account settings →
* Appearance (`selectableThemes`). Every other picker lists `themes`, so it
@@ -509,6 +531,10 @@ export type ThemeWindow = { from: MonthDay; to: MonthDay };
*/
export const seasonalThemes = [halloweenTheme] as const;
+// The same list, typed by what a seasonal theme may declare; still compiles
+// when the list is empty.
+const seasonal: readonly SeasonalTheme[] = seasonalThemes;
+
const allThemes = [...themes, ...seasonalThemes] as const;
export type Theme = (typeof allThemes)[number];
@@ -521,10 +547,6 @@ const defaultTheme: Theme = themes[0] satisfies {
name: typeof DEFAULT_THEME_NAME;
};
-function themeWindow(theme: Theme): ThemeWindow | undefined {
- return "available" in theme ? theme.available : undefined;
-}
-
function dayOfYear({ month, day }: MonthDay) {
return month * 100 + day;
}
@@ -542,8 +564,11 @@ const LATEST_TIME_ZONE = "Etc/GMT+12";
* half hours late in India. This way the server and the browser agree, and a
* user sees the theme at most a day before or after their own dates.
*/
-export function isThemeAvailable(theme: Theme, date?: CalendarDate) {
- const window = themeWindow(theme);
+export function isThemeAvailable(
+ theme: { name: string; available?: ThemeWindow },
+ date?: CalendarDate
+) {
+ const window = theme.available;
if (!window) return true;
const from = dayOfYear(window.from);
const to = dayOfYear(window.to);
@@ -565,20 +590,36 @@ export function selectableThemes(date?: CalendarDate): Theme[] {
return allThemes.filter((theme) => isThemeAvailable(theme, date));
}
+/** The seasonal theme every browser renders now, if one is forced and in season. */
+function forcedTheme(date?: CalendarDate): Theme | undefined {
+ const forced = seasonal.find(
+ (theme) => theme.forced && isThemeAvailable(theme, date)
+ );
+ return forced && allThemes.find((theme) => theme.name === forced.name);
+}
+
/**
- * The theme to render for a stored name. An unknown name (a theme since
- * removed) or a seasonal theme out of season falls back to the default, so
- * removing a theme never breaks a browser that still holds its cookie.
+ * The theme to render for a stored name. A forced seasonal theme in season
+ * wins over any stored name. An unknown name (a theme since removed) or a
+ * seasonal theme out of season falls back to the default, so removing a
+ * theme never breaks a browser that still holds its cookie.
*/
export function resolveTheme(
name: string | null | undefined,
date?: CalendarDate
): Theme {
+ const forced = forcedTheme(date);
+ if (forced) return forced;
const theme = allThemes.find((candidate) => candidate.name === name);
if (theme && isThemeAvailable(theme, date)) return theme;
return defaultTheme;
}
+/** A seasonal theme's mesh-gradient colors, if it declares them. */
+export function seasonalMeshColors(name: string): MeshColors | undefined {
+ return seasonal.find((theme) => theme.name === name)?.mesh;
+}
+
export const BASE_THEME_WITH_VARIABLES = `
:root {
--background: <%- colors.light["background"] %>;