1
0
Fork 0

feat(awards): render ribbon devices as vectors with tier-driven auto-layout

Introduce RibbonArt, a single shared SVG renderer used by both the production viewer and admin/studio preview so they can no longer diverge. Devices are now vector glyphs (star/oak leaf/campaign clasp/arrow up) instead of Unicode text, laid out as one centered cluster that shrinks to fit. Device count derives from advancement tier using the service-star convention (tier N shows N-1, cap 6; bare ribbon at tier 1 or for non-tiered awards). Legacy per-device x/y positions are stored but ignored, so no schema change. Designers add/remove/reorder device types and preview tiers.
This commit is contained in:
Jason Fraley 2026-10-26 22:21:10 -04:00
parent f32afc6421
commit 7430251adf
10 changed files with 485 additions and 148 deletions

View file

@ -52,7 +52,7 @@ export default function RibbonDesigner() {
Configure the ribbon colors, stripes, and device attachments for this award.
</p>
<RibbonPreview design={design} />
<RibbonPreview design={design} allowTierPreview />
<button
type="button"

View file

@ -0,0 +1,211 @@
/**
* THE single ribbon renderer, shared by production (`RibbonViewer`), the admin
* `RibbonDesigner`, and the member-facing `RibbonStudio`. Drawing stripes,
* the fabric overlay, and the devices lives here so an author's preview is
* pixel-identical to what grantees see.
*
* Devices are inline vector shapes (no Unicode glyphs, no font dependency) and
* their count and placement are derived, never positioned by hand:
*
* - `resolveDisplayedDeviceTypes(design, tier)` maps an advancement tier to a
* device count using the service-star convention: tier 1 is the bare award,
* each higher tier adds one device (capped at `MAX_TIER_DEVICES`). Non-tiered
* ribbons keep the device set authored in the designer.
* - `computeDeviceSlots(...)` lays the devices out as one centered cluster on
* the ribbon face, evenly spaced and shrunk to fit narrow ribbons.
*/
import { RIBBON_CONSTANTS, DEFAULT_RIBBON } from "./constants";
import type { DeviceType, RibbonDesign } from "./types";
export const MAX_TIER_DEVICES = 6;
const DEFAULT_DEVICE_TYPE: DeviceType = "star";
// ─── Tier-driven device resolution ──────────────────────────────────
/**
* Resolve which device glyphs to display for a design at a given advancement
* tier. Pass `tier >= 2` to use the tier mapping (tier N shows N - 1 devices,
* cycling through the authored device types, defaulting to star when none are
* authored). Pass `undefined`/`null`/`1` to render exactly what was authored.
*/
export function resolveDisplayedDeviceTypes(
design: RibbonDesign | null | undefined,
tier?: number | null,
): DeviceType[] {
const authored = Array.isArray(design?.devices) ? design.devices.map((d) => d.type) : [];
// Derive from tier only for genuine upgrades (tier >= 2). Missing, invalid,
// or base tiers render exactly what was authored.
const effectiveTier = typeof tier === "number" && Number.isFinite(tier) ? Math.floor(tier) : null;
if (effectiveTier === null || effectiveTier < 2) return authored;
// Service-star convention: the base tier carries no devices; each upgrade
// adds one. The first award of a series is therefore a bare ribbon and tier
// N reads as "awarded N times". Capped at MAX_TIER_DEVICES clusters.
const slots = Math.min(effectiveTier - 1, MAX_TIER_DEVICES);
return Array.from({ length: slots }, (_, i) => authored[i % authored.length] ?? DEFAULT_DEVICE_TYPE);
}
// ─── Centered auto-layout ───────────────────────────────────────────
export interface DeviceSlot {
cx: number;
cy: number;
size: number;
}
/**
* Lay out `count` devices as a single centered cluster on a `width x height`
* SVG canvas. Devices are evenly spaced and vertically centered; the whole
* cluster shrinks to fit within 80% of the ribbon width for high counts.
*/
export function computeDeviceSlots(
count: number,
width: number,
height: number,
): DeviceSlot[] {
if (count <= 0) return [];
const maxGroupWidth = width * 0.8;
const idealSize = Math.min(height * 0.34, 30);
// Pitch is 1.55 device-sizes center-to-center (size + a half-size gap), so
// the cluster spans `1 + 1.55 * (count - 1)` sizes (center-to-center gaps
// plus one device width); shrink uniformly when that exceeds the face.
const GAP_RATIO = 0.55;
const PITCH_RATIO = 1 + GAP_RATIO;
const spanInSizes = 1 + PITCH_RATIO * (count - 1);
const size = Math.max(6, Math.min(idealSize, maxGroupWidth / spanInSizes));
const spacing = size * PITCH_RATIO;
const total = (count - 1) * spacing;
const startX = width / 2 - total / 2;
const cy = height / 2;
return Array.from({ length: count }, (_, i) => ({ cx: startX + i * spacing, cy, size }));
}
// ─── Vector device shapes (authored in a 0..100 unit space) ─────────
const DEVICE_SHAPES: Record<DeviceType, string> = {
star: "M50 2 L60.6 35.4 L95.7 35.2 L67.1 55.6 L78.2 88.8 L50 68 L21.8 88.8 L32.9 55.6 L4.3 35.2 L39.4 35.4 Z",
oakLeaf:
"M50 94 C36 84 28 70 28 54 C28 40 34 26 50 6 C66 26 72 40 72 54 C72 70 64 84 50 94 Z M50 18 L50 84",
arrowUp: "M50 4 L88 44 L66 44 L66 96 L34 96 L34 44 L12 44 Z",
campaignClasp: "M12 32 L88 32 L88 68 L12 68 Z",
};
function DeviceShape({ type }: { type: DeviceType }) {
const d = DEVICE_SHAPES[type];
if (type === "oakLeaf") {
// Filled silhouette plus a central vein stroke for readability.
return (
<g transform="translate(-50 -50)">
<path d={d} fill="currentColor" stroke="currentColor" strokeWidth={6} strokeLinecap="round" />
</g>
);
}
return <path d={d} fill="currentColor" transform="translate(-50 -50)" />;
}
/**
* A device icon at `px` size, usable outside the ribbon SVG (editors, chips).
* Shapes are authored around the origin (see `DeviceShape`).
*/
export function DeviceGlyph({
type,
px = 14,
className,
}: {
type: DeviceType;
px?: number;
className?: string;
}) {
return (
<svg
viewBox="-56 -56 112 112"
width={px}
height={px}
aria-hidden="true"
className={className}
style={{ display: "inline-block", verticalAlign: "-2px" }}
>
<DeviceShape type={type} />
</svg>
);
}
// ─── Shared renderer ────────────────────────────────────────────────
export interface RibbonArtProps {
design: RibbonDesign | null | undefined;
/** Advancement tier of the award being rendered; drives device count. */
tier?: number | null;
/** Fabric texture overlay (present in both preview and production). */
showOverlay?: boolean;
/** Additional class names on the <svg> root (sizing, borders). */
className?: string;
maxHeight?: number;
}
/**
* Render a ribbon (stripes + overlay + vector devices) at the canonical
* `RIBBON_WIDTH x PREVIEW_HEIGHT` viewBox, scaled responsively by CSS. The
* devices shown come from `resolveDisplayedDeviceTypes(design, tier)` and are
* auto-laid-out by `computeDeviceSlots`, so this component owns all layout.
*/
export function RibbonArt({
design,
tier,
showOverlay = true,
className,
maxHeight,
}: RibbonArtProps) {
const resolved: RibbonDesign =
design && typeof design === "object" && Array.isArray(design.stripes) ? design : DEFAULT_RIBBON;
const { stripes, mirrored } = resolved;
if (stripes.length === 0) return null;
const displayStripes = mirrored ? [...stripes, ...stripes.slice(0, -1).reverse()] : stripes;
const totalWeight = displayStripes.reduce((sum, s) => sum + s.width, 0);
const viewWidth = RIBBON_CONSTANTS.RIBBON_WIDTH;
const viewHeight = RIBBON_CONSTANTS.PREVIEW_HEIGHT;
const deviceTypes = resolveDisplayedDeviceTypes(resolved, tier);
const slots = computeDeviceSlots(deviceTypes.length, viewWidth, viewHeight);
let stripeX = 0;
const stripeRects = displayStripes.map((stripe, i) => {
const w = (stripe.width / totalWeight) * viewWidth;
const el = <rect key={i} x={stripeX} y={0} width={w} height={viewHeight} fill={stripe.color} />;
stripeX += w;
return el;
});
return (
<svg
viewBox={`0 0 ${viewWidth} ${viewHeight}`}
className={className}
style={maxHeight ? { maxHeight } : undefined}
>
<rect x={0} y={0} width={viewWidth} height={viewHeight} rx={2} fill="#18181b" />
{stripeRects}
{showOverlay && (
<image href="/images/ribbon-overlay.png" className="mix-blend-multiply w-full" />
)}
{slots.map((slot, i) => (
<g
key={i}
data-device={deviceTypes[i]}
transform={`translate(${slot.cx} ${slot.cy}) scale(${slot.size / 100})`}
>
{/* Emboss: offset dark drop-shadow beneath the gold shape */}
<g style={{ pointerEvents: "none", color: "rgba(12, 10, 4, 0.55)" }} transform="translate(3 4)">
<DeviceShape type={deviceTypes[i]} />
</g>
<g style={{ pointerEvents: "none" }} color="#facc15">
<DeviceShape type={deviceTypes[i]} />
</g>
</g>
))}
</svg>
);
}

View file

@ -1,61 +1,59 @@
"use client";
import { RIBBON_CONSTANTS, RIBBON_DEVICE_INFO } from "./constants";
import { useState } from "react";
import { RIBBON_DEVICE_INFO } from "./constants";
import { DeviceGlyph, MAX_TIER_DEVICES, RibbonArt } from "./RibbonArt";
import type { Device, DeviceType, RibbonDesign, Stripe } from "./types";
const { RIBBON_ASPECT, RIBBON_WIDTH, PREVIEW_HEIGHT } = RIBBON_CONSTANTS;
// ─── Preview ────────────────────────────────────────────────────────
export function RibbonPreview({ design }: { design: RibbonDesign }) {
const { stripes, devices, mirrored } = design;
if (stripes.length === 0) return null;
const displayStripes = mirrored ? [...stripes, ...stripes.slice(0, -1).reverse()] : stripes;
const totalWeight = displayStripes.reduce((sum, s) => sum + s.width, 0);
const viewWidth = RIBBON_WIDTH;
const viewHeight = PREVIEW_HEIGHT;
/**
* Design-time ribbon preview: the same `RibbonArt` used on the live site, so
* authors see exactly what grantees get (devices included, auto-laid-out).
* Pass `tier` to preview one fixed tier. With `allowTierPreview`, a small
* selector simulates tiers 1..MAX+1: tier 1 renders the authored device set,
* each higher tier derives its cluster count (N - 1 devices), matching the
* service-star convention applied at render time.
*/
export function RibbonPreview({
design,
tier,
allowTierPreview,
}: {
design: RibbonDesign;
tier?: number | null;
allowTierPreview?: boolean;
}) {
const [simulatedTier, setSimulatedTier] = useState(1);
const effectiveTier = allowTierPreview ? simulatedTier : tier;
return (
<svg
viewBox={`0 0 ${viewWidth} ${viewHeight}`}
className="w-full h-auto rounded border border-zinc-700 bg-zinc-950"
style={{ maxHeight: 140 }}
>
<rect x={0} y={0} width={viewWidth} height={viewHeight} rx={2} fill="#18181b" />
{(() => {
let x = 0;
return displayStripes.map((stripe, i) => {
const w = (stripe.width / totalWeight) * viewWidth;
const el = <rect key={i} x={x} y={0} width={w} height={viewHeight} fill={stripe.color} />;
x += w;
return el;
});
})()}
{devices.map((device) => {
const info = RIBBON_DEVICE_INFO[device.type];
const cx = (device.position / 100) * viewWidth;
const cy = (device.positionY / 100) * viewHeight;
const fontSize = Math.min(viewHeight * 0.45, 24);
return (
<text
key={device.id}
x={cx}
y={cy}
textAnchor="middle"
dominantBaseline="central"
fill="#facc15"
fontSize={fontSize}
fontFamily="serif"
style={{ pointerEvents: "none" }}
>
{info.symbol}
</text>
);
})}
</svg>
<div className="flex flex-col gap-2">
<RibbonArt
design={design}
tier={effectiveTier}
className="w-full h-auto rounded border border-zinc-700 bg-zinc-950"
maxHeight={140}
/>
{allowTierPreview && (
<label className="flex items-center gap-2 text-[11px] text-zinc-400">
<span className="uppercase tracking-wider">Preview tier</span>
<input
type="range"
min={1}
max={MAX_TIER_DEVICES + 1}
value={simulatedTier}
onChange={(e) => setSimulatedTier(Number(e.target.value))}
className="flex-1 h-1 accent-amber-500"
/>
<span className="font-mono w-16 text-right">
{simulatedTier === 1
? "as authored"
: `${Math.min(simulatedTier - 1, MAX_TIER_DEVICES)} devices`}
</span>
</label>
)}
</div>
);
}
@ -123,7 +121,7 @@ export function StripeEditor({
onClick={() => removeStripe(idx)}
className="py-1 text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
>
\u00D7
{"\u00D7"}
</button>
</div>
))}
@ -133,6 +131,12 @@ export function StripeEditor({
// ─── Device Editor ──────────────────────────────────────────────────
/**
* Devices are added/removed as an ordered set; their placement on the ribbon
* is computed automatically (centered cluster, tier-driven count when the
* award belongs to an advancement series). The legacy per-device X/Y sliders
* are gone because layout is derived, and stored positions are ignored.
*/
export function DeviceEditor({
devices,
onChange,
@ -143,12 +147,21 @@ export function DeviceEditor({
const addDevice = (type: DeviceType) =>
onChange([...devices, { id: crypto.randomUUID(), type, position: 50, positionY: 50 }]);
const removeDevice = (id: string) => onChange(devices.filter((d) => d.id !== id));
const updateDevice = (id: string, patch: Partial<Device>) =>
onChange(devices.map((d) => (d.id === id ? { ...d, ...patch } : d)));
const moveDevice = (idx: number, delta: number) => {
const next = [...devices];
const target = idx + delta;
if (target < 0 || target >= next.length) return;
[next[idx], next[target]] = [next[target], next[idx]];
onChange(next);
};
return (
<div className="flex flex-col gap-2">
<span className="text-xs font-medium text-zinc-400 uppercase tracking-wider">Devices</span>
<p className="text-[10px] text-zinc-500">
Devices arrange themselves centered on the ribbon. For awards in an
advancement series, the tier sets how many show (tier N displays N&nbsp;-&nbsp;1).
</p>
<div className="flex flex-wrap gap-1.5">
{(Object.keys(RIBBON_DEVICE_INFO) as DeviceType[]).map((type) => {
const info = RIBBON_DEVICE_INFO[type];
@ -157,58 +170,51 @@ export function DeviceEditor({
key={type}
type="button"
onClick={() => addDevice(type)}
className="text-[11px] px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-zinc-300 hover:bg-zinc-700 transition-colors cursor-pointer"
className="text-[11px] px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-zinc-300 hover:bg-zinc-700 transition-colors cursor-pointer inline-flex items-center gap-1.5 text-yellow-400 [&_span]:text-zinc-300"
>
{info.symbol} {info.label}
<DeviceGlyph type={type} px={12} /> <span>{info.label}</span>
</button>
);
})}
</div>
{devices.length > 0 && (
<div className="flex flex-col gap-1.5">
{devices.map((device) => {
{devices.map((device, idx) => {
const info = RIBBON_DEVICE_INFO[device.type];
return (
<div
key={device.id}
className="flex items-center gap-2 bg-zinc-900 rounded px-2 py-1.5"
className="flex items-center gap-2 bg-zinc-900 rounded px-2 py-1.5 text-yellow-400"
>
<span className="text-sm">{info.symbol}</span>
<span className="font-mono text-[10px] text-zinc-500 w-4">{idx + 1}</span>
<DeviceGlyph type={device.type} px={14} />
<span className="text-[11px] text-zinc-400">{info.label}</span>
<div className="flex items-center gap-1.5 flex-1">
<label className="text-[10px] text-zinc-500 shrink-0">X</label>
<input
type="range"
min={0}
max={100}
value={device.position}
onChange={(e) => updateDevice(device.id, { position: Number(e.target.value) })}
className="flex-1 h-1 accent-zinc-400"
/>
<span className="text-[10px] text-zinc-500 font-mono w-5 text-right">
{device.position}
</span>
</div>
<div className="flex items-center gap-1.5 flex-1">
<label className="text-[10px] text-zinc-500 shrink-0">Y</label>
<input
type="range"
min={0}
max={100}
value={device.positionY}
onChange={(e) => updateDevice(device.id, { positionY: Number(e.target.value) })}
className="flex-1 h-1 accent-zinc-400"
/>
<span className="text-[10px] text-zinc-500 font-mono w-5 text-right">
{device.positionY}
</span>
</div>
<div className="flex-1" />
<button
type="button"
onClick={() => removeDevice(device.id)}
className="py-1 text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
aria-label={`Move ${info.label} earlier`}
onClick={() => moveDevice(idx, -1)}
disabled={idx === 0}
className="px-1 text-zinc-500 hover:text-zinc-200 disabled:opacity-30 cursor-pointer"
>
\u00D7
↑
</button>
<button
type="button"
aria-label={`Move ${info.label} later`}
onClick={() => moveDevice(idx, 1)}
disabled={idx === devices.length - 1}
className="px-1 text-zinc-500 hover:text-zinc-200 disabled:opacity-30 cursor-pointer"
>
↓
</button>
<button
type="button"
aria-label={`Remove ${info.label}`}
onClick={() => removeDevice(device.id)}
className="px-1 py-1 text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
>
{"\u00D7"}
</button>
</div>
);

View file

@ -71,6 +71,7 @@ export default function AwardCard(props: {
<RibbonViewer
ribbonDesign={props.award.ribbonDesign as RibbonDesign}
showRibbonOnly={true}
tier={props.award.advancement?.tier ?? null}
/>
)}
<div className="flex items-center gap-2.5">

View file

@ -87,6 +87,7 @@ export function AwardListingCard({
<RibbonViewer
ribbonDesign={award.ribbonDesign as RibbonDesign}
showRibbonOnly={false}
tier={award.advancement?.tier ?? null}
/>
</div>
) : awardImage?.url ? (

View file

@ -75,7 +75,11 @@ export function AwardPickerDialog({
{award.type === "ribbon" && award.ribbonDesign ? (
<div className="flex h-16 w-full items-center justify-center">
<div className="w-32 max-w-full">
<RibbonViewer ribbonDesign={award.ribbonDesign as RibbonDesign} showRibbonOnly />
<RibbonViewer
ribbonDesign={award.ribbonDesign as RibbonDesign}
showRibbonOnly
tier={award.advancement?.tier ?? null}
/>
</div>
</div>
) : (

View file

@ -63,7 +63,7 @@ export const RibbonRack = ({ awards }: { awards: Award[] }) => {
return (
<Tooltip key={key}>
<TooltipTrigger className="w-[6.375rem] max-w-full h-[1.6875rem] hover:scale-110 shadow-black shadow-xs hover:shadow-xl transition-transform">
<RibbonViewer ribbonDesign={ribbon} showRibbonOnly />
<RibbonViewer ribbonDesign={ribbon} showRibbonOnly tier={award.advancement?.tier ?? null} />
</TooltipTrigger>
<TooltipContent>
<div className="flex flex-col gap-1">

View file

@ -1,15 +1,26 @@
"use client";
import {
RIBBON_DEVICE_INFO,
RIBBON_CONSTANTS,
DEFAULT_RIBBON,
} from "@/components/awards/ribbonDesign/constants";
import { DEFAULT_RIBBON } from "@/components/awards/ribbonDesign/constants";
import { RibbonArt } from "@/components/awards/ribbonDesign/RibbonArt";
import type { RibbonDesign } from "@/components/awards/ribbonDesign/types";
import { useState } from "react";
import { cn } from "@/lib/utils";
export const RibbonViewer = ({ ribbonDesign, showRibbonOnly }: { ribbonDesign: RibbonDesign, showRibbonOnly?: boolean }) => {
/**
* Production ribbon renderer. Thin wrapper around the shared `RibbonArt` so
* the live site and the admin/studio previews cannot drift apart. Pass an
* award's `advancement.tier` to let the device cluster derive its count from
* the tier (service-star convention); omit it to show the authored devices.
*/
export const RibbonViewer = ({
ribbonDesign,
showRibbonOnly,
tier,
}: {
ribbonDesign: RibbonDesign;
showRibbonOnly?: boolean;
tier?: number | null;
}) => {
const initial: RibbonDesign =
ribbonDesign && typeof ribbonDesign === "object" && Array.isArray((ribbonDesign as RibbonDesign).stripes)
? (ribbonDesign as RibbonDesign)
@ -17,57 +28,13 @@ export const RibbonViewer = ({ ribbonDesign, showRibbonOnly }: { ribbonDesign: R
const [design] = useState<RibbonDesign>(initial);
const { stripes, devices, mirrored } = design;
if (stripes.length === 0) return null;
const displayStripes = mirrored ? [...stripes, ...stripes.slice(0, -1).reverse()] : stripes;
const totalWeight = displayStripes.reduce((sum, s) => sum + s.width, 0);
const viewWidth = RIBBON_CONSTANTS.RIBBON_WIDTH;
const viewHeight = RIBBON_CONSTANTS.PREVIEW_HEIGHT;
return (
<svg
viewBox={`0 0 ${viewWidth} ${viewHeight}`}
<RibbonArt
design={design}
tier={tier}
className={cn("h-auto max-h-20", {
"w-full rounded border border-zinc-700 bg-zinc-950": !showRibbonOnly
} )}
>
<rect x={0} y={0} width={viewWidth} height={viewHeight} rx={2} fill="#18181b" />
{(() => {
let x = 0;
return displayStripes.map((stripe, i) => {
const w = (stripe.width / totalWeight) * viewWidth;
const el = <rect key={i} x={x} y={0} width={w} height={viewHeight} fill={stripe.color} />;
x += w;
return el;
});
})()}
<image href="/images/ribbon-overlay.png" className="mix-blend-multiply w-full" />
{devices.map((device) => {
const info = RIBBON_DEVICE_INFO[device.type];
const cx = (device.position / 100) * viewWidth;
const cy = (device.positionY / 100) * viewHeight;
const fontSize = Math.min(viewHeight * 0.45, 24);
return (
<text
key={device.id}
x={cx}
y={cy}
textAnchor="middle"
dominantBaseline="central"
fill="#facc15"
fontSize={fontSize}
fontFamily="serif"
style={{ pointerEvents: "none" }}
className="text-shadow-sm text-shadow-black"
>
{info.symbol}
</text>
);
"w-full rounded border border-zinc-700 bg-zinc-950": !showRibbonOnly,
})}
</svg>
/>
);
};

View file

@ -114,7 +114,7 @@ export function RibbonStudio() {
<div className="flex min-w-0 flex-col gap-5">
<div className="flex flex-col gap-2">
<Label>Preview</Label>
<RibbonPreview design={design} />
<RibbonPreview design={design} allowTierPreview />
</div>
<StripeEditor
stripes={design.stripes}

View file

@ -0,0 +1,147 @@
// @vitest-environment jsdom
import { createElement as h } from "react";
import { afterEach, describe, expect, it } from "vitest";
import { cleanup, render } from "@testing-library/react";
import {
RibbonArt,
computeDeviceSlots,
resolveDisplayedDeviceTypes,
MAX_TIER_DEVICES,
} from "@/components/awards/ribbonDesign/RibbonArt";
import type { RibbonDesign } from "@/components/awards/ribbonDesign/types";
afterEach(cleanup);
const design = (deviceTypes: string[]): RibbonDesign => ({
stripes: [
{ color: "#b91c1c", width: 50 },
{ color: "#1e3a5f", width: 50 },
],
devices: deviceTypes.map((type, i) => ({
id: `dev-${i}`,
// Cast to satisfy the union; tests only use valid types or assert fallback.
type: type as RibbonDesign["devices"][number]["type"],
position: 17 + i * 11,
positionY: 83,
})),
mirrored: false,
});
describe("resolveDisplayedDeviceTypes (tier-driven count)", () => {
const authored = ["star", "oakLeaf"] as const;
it("shows exactly the authored set for base, missing, and invalid tiers", () => {
for (const tier of [undefined, null, 1, 0, -2, Number.NaN]) {
expect(resolveDisplayedDeviceTypes(design([...authored]), tier)).toEqual(["star", "oakLeaf"]);
}
});
it("maps tier N to N-1 devices using the service-star convention", () => {
const d = design([...authored]);
expect(resolveDisplayedDeviceTypes(d, 2)).toEqual(["star"]);
expect(resolveDisplayedDeviceTypes(d, 3)).toEqual(["star", "oakLeaf"]);
expect(resolveDisplayedDeviceTypes(d, 4)).toEqual(["star", "oakLeaf", "star"]);
});
it("caps the derived cluster at MAX_TIER_DEVICES", () => {
const result = resolveDisplayedDeviceTypes(design([...authored]), 99);
expect(result).toHaveLength(MAX_TIER_DEVICES);
});
it("defaults to stars when a tiered series authored no devices", () => {
const result = resolveDisplayedDeviceTypes(design([]), 3);
expect(result).toEqual(["star", "star"]);
});
});
describe("computeDeviceSlots (centered auto-layout)", () => {
const W = 366;
const H = 80;
it("returns no slots for zero/negative counts", () => {
expect(computeDeviceSlots(0, W, H)).toEqual([]);
expect(computeDeviceSlots(-3, W, H)).toEqual([]);
});
it("centers a single device on the ribbon face", () => {
const [slot] = computeDeviceSlots(1, W, H);
expect(slot.cx).toBeCloseTo(W / 2, 6);
expect(slot.cy).toBeCloseTo(H / 2, 6);
expect(slot.size).toBeGreaterThan(0);
});
it("places N devices as an evenly spaced, centered cluster", () => {
const slots = computeDeviceSlots(4, W, H);
expect(slots).toHaveLength(4);
const spacings = slots.slice(1).map((s, i) => s.cx - slots[i].cx);
spacings.forEach((gap) => expect(gap).toBeCloseTo(spacings[0], 6));
// Symmetric about the centerline.
const meanCx = slots.reduce((sum, s) => sum + s.cx, 0) / slots.length;
expect(meanCx).toBeCloseTo(W / 2, 6);
// All vertically centered.
for (const slot of slots) expect(slot.cy).toBeCloseTo(H / 2, 6);
});
it("shrinks and keeps the cluster inside the face when crowded", () => {
// A tall, narrow canvas makes ideal sizing overflow at high counts, which
// exercises the uniform shrink path (compare like-for-like canvas).
const NARROW_W = 100;
const TALL_H = 200;
const few = computeDeviceSlots(1, NARROW_W, TALL_H);
const many = computeDeviceSlots(MAX_TIER_DEVICES, NARROW_W, TALL_H);
expect(many[many.length - 1].size).toBeLessThan(few[0].size);
const span =
many[many.length - 1].cx + many[many.length - 1].size / 2 - (many[0].cx - many[0].size / 2);
expect(span).toBeLessThanOrEqual(NARROW_W * 0.8 + 1e-6);
});
});
describe("RibbonArt rendering", () => {
it("renders vector device groups (no Unicode text elements) with tier counts", () => {
const { container } = render(h(RibbonArt, { design: design(["star", "oakLeaf"]), tier: 3 }));
const devices = container.querySelectorAll("[data-device]");
expect(devices).toHaveLength(2);
expect(Array.from(devices).map((d) => d.getAttribute("data-device"))).toEqual([
"star",
"oakLeaf",
]);
// Glyphs are inline paths now; no <text> nodes and no emoji fallbacks.
expect(container.querySelectorAll("text")).toHaveLength(0);
expect(container.querySelectorAll("path").length).toBeGreaterThan(0);
});
it("keeps preview identical to production by drawing the fabric overlay once", () => {
const { container } = render(h(RibbonArt, { design: design([]), tier: 1 }));
expect(container.querySelectorAll("image[href='/images/ribbon-overlay.png']")).toHaveLength(1);
});
it("drops the overlay when showOverlay is false", () => {
const { container } = render(h(RibbonArt, { design: design([]), showOverlay: false }));
expect(container.querySelector("image")).toBeNull();
});
it("renders mirrored designs with stripes doubled", () => {
const mirrored: RibbonDesign = { ...design(["star"]), mirrored: true };
const { container } = render(h(RibbonArt, { design: mirrored }));
// mirrored doubles every stripe band; two colors -> four rects over base bg
const rects = container.querySelectorAll("rect");
expect(rects.length).toBeGreaterThanOrEqual(4);
});
it("returns null for an explicitly stripe-less design and falls back for an absent one", () => {
// Matches legacy RibbonViewer/RibbonPreview behavior: a valid object with
// no stripes draws nothing...
const { container: empty } = render(
h(RibbonArt, { design: { stripes: [], devices: [], mirrored: false } }),
);
expect(empty.querySelector("svg")).toBeNull();
// ...while an unusable value falls back to DEFAULT_RIBBON and still renders.
const { container: fallback } = render(h(RibbonArt, { design: undefined }));
expect(fallback.querySelector("svg")).not.toBeNull();
});
});