diff --git a/.github/assets/customization-sliders/after.png b/.github/assets/customization-sliders/after.png new file mode 100644 index 0000000..e02d594 Binary files /dev/null and b/.github/assets/customization-sliders/after.png differ diff --git a/.github/assets/customization-sliders/before.png b/.github/assets/customization-sliders/before.png new file mode 100644 index 0000000..fabd079 Binary files /dev/null and b/.github/assets/customization-sliders/before.png differ diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a8a542b..ef665b0 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -8,6 +8,10 @@ The extraction preserves the Plotter skill package originally located at `apps/u The skill’s bundled reference manifest records the source revisions of its approved SVG snapshots. Dated feedback and audits from the coss period were removed from the tree after commit `37f3464` and remain in git history. +## Component attribution + +The customization token controls adapt DialKit’s slider component (MIT, Copyright (c) 2026 Josh Puckett, [joshpuckett/dialkit](https://github.com/joshpuckett/dialkit)). `components/ui/slider.tsx` keeps DialKit’s label-and-value-in-track layout, hover-to-edit value, and decile snapping, adapted to Plotter’s theme tokens and Base UI version. + ## License record Plotter and its portable skill package use the [MIT license](LICENSE), selected by the maintainer on 2026-11-08. The notices retain the coss.com and Origin UI copyright and add Pasquale Vitiello’s copyright for Plotter. The current coss source also uses MIT. diff --git a/components/plotter/plotter-token-guide.tsx b/components/plotter/plotter-token-guide.tsx index 63357df..21ae3c6 100644 --- a/components/plotter/plotter-token-guide.tsx +++ b/components/plotter/plotter-token-guide.tsx @@ -22,7 +22,7 @@ import { FieldLabel, } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; -import { Slider, SliderValue } from "@/components/ui/slider"; +import { Slider } from "@/components/ui/slider"; import { highlightOpacity, roleCss, @@ -90,6 +90,20 @@ const groups = [ { label: "Opacity", prefix: "--plotter-opacity-" }, ]; +function buildCss(values: Values, ink: string) { + const declarations = tokens + .map((token) => ` ${token}: ${values[token]};`) + .join("\n"); + return `.illustration {\n --plotter-ink: ${ink};\n${declarations}\n}`; +} + +function getSliderConfig(token: ControlToken) { + return { + max: token.startsWith("--plotter-opacity-") ? 1 : defaults[token] * 2, + step: token === "--plotter-opacity-highlight" ? 0.005 : 0.01, + }; +} + export function PlotterTokenGuide({ children }: { children: ReactNode }) { const id = useId(); const cssRef = useRef(null); @@ -100,9 +114,7 @@ export function PlotterTokenGuide({ children }: { children: ReactNode }) { const [copyState, setCopyState] = useState<"idle" | "copied" | "manual">( "idle", ); - const css = `.illustration {\n --plotter-ink: ${ink};\n${tokens - .map((token) => ` ${token}: ${values[token]};`) - .join("\n")}\n}`; + const css = buildCss(values, ink); const previewStyle: CSSProperties & Values & { "--plotter-ink": string } = { ...values, "--plotter-ink": ink, @@ -148,8 +160,9 @@ export function PlotterTokenGuide({ children }: { children: ReactNode }) {

Adjust ink, stroke widths, and opacity without changing the drawing. - Try every token on MEC-05 and the samples below it, then copy the CSS - to a wrapper around your inline SVG. + Drag a slider, or hover a value and click to type an exact number. Try + every token on MEC-05 and the samples below it, then copy the CSS to a + wrapper around your inline SVG.

@@ -186,40 +199,24 @@ export function PlotterTokenGuide({ children }: { children: ReactNode }) { .filter((token) => token.startsWith(prefix)) .map((token) => { const { label, hint } = controls[token]; - const max = token.startsWith("--plotter-opacity-") - ? 1 - : defaults[token] * 2; + const { max, step } = getSliderConfig(token); return ( { setValues((current) => ({ ...current, - [token]: - typeof value === "number" ? value : value[0], + [token]: value, })); setCopyState("idle"); }} - step={ - token === "--plotter-opacity-highlight" - ? 0.005 - : 0.01 - } + step={step} value={values[token]} - > -
- {label} - -
-
+ /> {hint} diff --git a/components/ui/slider.tsx b/components/ui/slider.tsx index 9d22b55..75b1853 100644 --- a/components/ui/slider.tsx +++ b/components/ui/slider.tsx @@ -1,79 +1,766 @@ "use client"; +/** + * Adapted from DialKit's Slider (MIT, Copyright (c) 2026 Josh Puckett). + * https://github.com/joshpuckett/dialkit + */ + import { Slider as SliderPrimitive } from "@base-ui/react/slider"; -import { type ReactElement, useMemo } from "react"; +import * as React from "react"; import { cn } from "@/lib/utils"; -export function Slider({ - className, - getAriaLabel, - children, - defaultValue, +const LABEL_OFFSET = 10; +const VALUE_OFFSET = 12; +const HANDLE_BUFFER = 8; +const HANDLE_INSET = 7.5; +const MIN_HANDLE_CENTER = 6.5; +const HOVER_EDIT_DELAY = 800; +const DECILE_SNAP_THRESHOLD = 0.03125; + +const HANDLE_OPACITY = { + idle: 0, + dodge: 0.1, + hover: 0.5, + drag: 0.9, +} as const; + +type DodgeThresholds = { + left: number; + right: number; +}; + +const DEFAULT_DODGE_THRESHOLDS: DodgeThresholds = { + left: 30, + right: 78, +}; + +type SliderProps = Omit< + SliderPrimitive.Root.Props, + | "value" + | "defaultValue" + | "onValueChange" + | "onValueCommitted" + | "orientation" + | "thumbAlignment" +> & { + label: string; + value?: number; + defaultValue?: number; + onValueChange?: (value: number) => void; + formatValue?: (value: number) => string; + unit?: string; + snapOnClick?: boolean; + className?: string; +}; + +function clampValue(value: number, min: number, max: number) { + return Math.min(max, Math.max(min, value)); +} + +function isEndpoint(value: number, min: number, max: number) { + return value === min || value === max; +} + +function isUsableStep(step: number) { + return Number.isFinite(step) && step > 0; +} + +/** Decimal places needed by a step or range endpoint, including scientific notation. */ +function decimalsForStep(step: number, min: number, max: number) { + return Math.min( + 100, + Math.max( + ...[step, min, max].map((value) => { + const [coefficient, exponent = "0"] = String(value) + .toLowerCase() + .split("e"); + return Math.max( + 0, + (coefficient.split(".")[1]?.length ?? 0) - Number(exponent), + ); + }), + ), + ); +} + +/** Snap relative to the minimum and keep exact endpoints reachable. */ +function roundValue(value: number, step: number, min: number, max: number) { + const clamped = clampValue(value, min, max); + if (isEndpoint(clamped, min, max) || !isUsableStep(step)) return clamped; + + const snapped = min + Math.round((clamped - min) / step) * step; + return clampValue(Number(snapped.toPrecision(14)), min, max); +} + +/** Clicking a continuous slider pulls to the nearest tenth of the range. */ +function snapToDecile(value: number, min: number, max: number) { + const range = max - min; + if (range <= 0) return min; + + const normalized = (value - min) / range; + const nearest = Math.round(normalized * 10) / 10; + return Math.abs(normalized - nearest) <= DECILE_SNAP_THRESHOLD + ? min + nearest * range + : value; +} + +function hashMarkPercents(min: number, max: number, step: number) { + const range = max - min; + if (range <= 0) return []; + + const stepCount = range / step; + if (stepCount > 0 && stepCount <= 10) { + return Array.from( + { length: Math.max(0, Math.floor(stepCount) - 1) }, + (_, index) => ((index + 1) * step * 100) / range, + ); + } + + return Array.from({ length: 9 }, (_, index) => (index + 1) * 10); +} + +function resolveDodgeThresholds( + width: number, + labelWidth: number, + valueWidth: number, +): DodgeThresholds { + return { + left: ((LABEL_OFFSET + labelWidth + HANDLE_BUFFER) / width) * 100, + right: ((width - VALUE_OFFSET - valueWidth - HANDLE_BUFFER) / width) * 100, + }; +} + +function thresholdsAreEqual(a: DodgeThresholds, b: DodgeThresholds) { + return Math.abs(a.left - b.left) < 0.1 && Math.abs(a.right - b.right) < 0.1; +} + +function getElementWidth(element: HTMLElement | null) { + return element?.offsetWidth ?? 0; +} + +function getPercentage(value: number, min: number, max: number) { + const range = max - min; + return range > 0 ? ((value - min) / range) * 100 : 0; +} + +function isDodged(percentage: number, thresholds: DodgeThresholds) { + return percentage < thresholds.left || percentage > thresholds.right; +} + +/** DialKit pulls the handle slightly ahead of the fill edge. */ +function resolveHandleShift(fillEdge: number, trackWidth: number) { + if (trackWidth <= 0) return 0; + + const maxCenter = Math.max(MIN_HANDLE_CENTER, trackWidth - HANDLE_INSET); + const desiredCenter = Math.min( + Math.max(fillEdge - HANDLE_INSET, MIN_HANDLE_CENTER), + maxCenter, + ); + return desiredCenter - fillEdge; +} + +function resolveHandleOpacity( + active: boolean, + dodge: boolean, + dragging: boolean, +) { + if (!active) return HANDLE_OPACITY.idle; + if (dodge) return HANDLE_OPACITY.dodge; + return dragging ? HANDLE_OPACITY.drag : HANDLE_OPACITY.hover; +} + +function isSliderActive(state: { + hovered: boolean; + dragging: boolean; + focused: boolean; + editing: boolean; +}) { + return state.hovered || state.dragging || state.focused || state.editing; +} + +function formatSliderValue( + value: number, + decimals: number, + formatValue?: (value: number) => string, +) { + return formatValue ? formatValue(value) : value.toFixed(decimals); +} + +function resolveStep(step: number) { + return step > 0 ? step : 1; +} + +function resolveLargeStep(largeStep: number | undefined, step: number) { + return largeStep ?? step * 10; +} + +function resolveCurrentValue( + isControlled: boolean, + value: number | undefined, + uncontrolledValue: number, + min: number, + max: number, +) { + const nextValue = + isControlled && value !== undefined ? value : uncontrolledValue; + return clampValue(nextValue, min, max); +} + +function getFillTone(active: boolean, focused: boolean) { + return active || focused ? "bg-foreground/15" : "bg-foreground/[0.11]"; +} + +function getHandleTone(active: boolean, dodge: boolean) { + return cn( + "h-5 w-[3px] rounded-full bg-foreground transition-[opacity,scale] duration-200", + active ? "scale-x-100" : "scale-x-[0.25]", + dodge && "scale-y-75", + ); +} + +function getValueTone( + active: boolean, + focused: boolean, + valueEditable: boolean, +) { + return cn( + "absolute top-1/2 right-3 z-20 -translate-y-1/2 border-b border-transparent pb-px font-mono text-[13px] leading-none font-medium tabular-nums transition-colors duration-150", + active || focused ? "text-foreground" : "text-foreground/70", + valueEditable && "cursor-text border-foreground/70", + ); +} + +function resolveSnappedValue( + value: number, + reason: string, + options: { + min: number; + max: number; + step: number; + snapOnClick: boolean; + }, +) { + if (reason !== "track-press" || !options.snapOnClick) return value; + + const discreteSteps = (options.max - options.min) / options.step; + const snapped = + discreteSteps <= 10 + ? roundValue(value, options.step, options.min, options.max) + : snapToDecile(value, options.min, options.max); + + return roundValue(snapped, options.step, options.min, options.max); +} + +function commitDraft( + draft: string, + step: number, + min: number, + max: number, + onCommit: (value: number) => void, +) { + const parsed = Number.parseFloat(draft); + if (!Number.isFinite(parsed)) return; + onCommit(roundValue(parsed, step, min, max)); +} + +function hasCommandModifier(event: React.KeyboardEvent) { + return event.altKey || event.ctrlKey || event.metaKey; +} + +function isPlainEnter(event: React.KeyboardEvent) { + return event.key === "Enter" && !hasCommandModifier(event); +} + +function SliderHashMarks({ + percentages, + active, +}: { + percentages: number[]; + active: boolean; +}) { + return ( + + ); +} + +/** Measures the track and the text overlays, then keeps both in sync. */ +function useTrackMeasurements({ + rootRef, + labelRef, + valueRef, + editing, +}: { + rootRef: React.RefObject; + labelRef: React.RefObject; + valueRef: React.RefObject; + editing: boolean; +}) { + const [trackWidth, setTrackWidth] = React.useState(0); + const [dodgeThresholds, setDodgeThresholds] = React.useState( + DEFAULT_DODGE_THRESHOLDS, + ); + + // The value element is swapped while editing, so the observer must reattach. + // biome-ignore lint/correctness/useExhaustiveDependencies: editing controls which element the observer watches. + React.useLayoutEffect(() => { + const root = rootRef.current; + if (!root) return; + + const measure = () => { + const width = root.offsetWidth; + if (!width) return; + + const nextThresholds = resolveDodgeThresholds( + width, + getElementWidth(labelRef.current), + getElementWidth(valueRef.current), + ); + + setTrackWidth((previous) => + Math.abs(previous - width) < 0.1 ? previous : width, + ); + setDodgeThresholds((previous) => + thresholdsAreEqual(previous, nextThresholds) + ? previous + : nextThresholds, + ); + }; + + measure(); + const observer = new ResizeObserver(measure); + observer.observe(root); + + for (const element of [labelRef.current, valueRef.current]) { + if (element) observer.observe(element); + } + + return () => observer.disconnect(); + }, [rootRef, labelRef, valueRef, editing]); + + return { trackWidth, dodgeThresholds }; +} + +/** Handles the hover-to-edit value, its text input, and the Enter shortcut. */ +function useValueEditing({ value, + decimals, + min, + max, + step, + disabled, + onCommit, + thumbInputRef, +}: { + value: number; + decimals: number; + min: number; + max: number; + step: number; + disabled: boolean | undefined; + onCommit: (value: number) => void; + thumbInputRef: React.RefObject; +}) { + const [valueHovered, setValueHovered] = React.useState(false); + const [valueEditable, setValueEditable] = React.useState(false); + const [editing, setEditing] = React.useState(false); + const [draft, setDraft] = React.useState(""); + + const editorRef = React.useRef(null); + const editingRef = React.useRef(false); + + React.useEffect(() => { + if (!valueHovered || editing) return; + const timeout = window.setTimeout( + () => setValueEditable(true), + HOVER_EDIT_DELAY, + ); + return () => window.clearTimeout(timeout); + }, [valueHovered, editing]); + + React.useEffect(() => { + if (!editing) return; + editorRef.current?.focus(); + editorRef.current?.select(); + }, [editing]); + + const beginEditing = () => { + if (disabled) return; + editingRef.current = true; + setDraft(value.toFixed(decimals)); + setEditing(true); + }; + + const finishEditing = (commit: boolean, restoreFocus = false) => { + if (!editingRef.current) return; + editingRef.current = false; + + if (commit) commitDraft(draft, step, min, max, onCommit); + + setEditing(false); + setValueHovered(false); + setValueEditable(false); + + if (restoreFocus) { + queueMicrotask(() => + thumbInputRef.current?.focus({ preventScroll: true }), + ); + } + }; + + const handleValueClick = (event: React.MouseEvent) => { + if (!valueEditable) return; + event.preventDefault(); + event.stopPropagation(); + beginEditing(); + }; + + const handleValuePointerDown = ( + event: React.PointerEvent, + ) => { + if (valueEditable) event.stopPropagation(); + }; + + const handleValuePointerEnter = () => setValueHovered(true); + + const handleValuePointerLeave = () => { + setValueHovered(false); + setValueEditable(false); + }; + + const handleThumbKeyDown = (event: React.KeyboardEvent) => { + if (!isPlainEnter(event)) return; + event.preventDefault(); + event.stopPropagation(); + beginEditing(); + }; + + const handleDraftChange = (event: React.ChangeEvent) => { + setDraft(event.target.value); + }; + + const handleEditorKeyDown = ( + event: React.KeyboardEvent, + ) => { + event.stopPropagation(); + if (event.key === "Enter") { + event.preventDefault(); + finishEditing(true, true); + } else if (event.key === "Escape") { + event.preventDefault(); + finishEditing(false, true); + } + }; + + const handleEditorBlur = () => finishEditing(true); + + return { + editing, + draft, + editorRef, + valueEditable, + handleValueClick, + handleValuePointerDown, + handleValuePointerEnter, + handleValuePointerLeave, + handleThumbKeyDown, + handleDraftChange, + handleEditorKeyDown, + handleEditorBlur, + }; +} + +function SliderValue({ + label, + displayValue, + valueRef, + active, + focused, + editing, + draft, + editorRef, + valueEditable, + onValueClick, + onValuePointerDown, + onValuePointerEnter, + onValuePointerLeave, + onDraftChange, + onEditorKeyDown, + onEditorBlur, +}: { + label: string; + displayValue: string; + valueRef: React.RefObject; + active: boolean; + focused: boolean; + editing: boolean; + draft: string; + editorRef: React.RefObject; + valueEditable: boolean; + onValueClick: (event: React.MouseEvent) => void; + onValuePointerDown: (event: React.PointerEvent) => void; + onValuePointerEnter: () => void; + onValuePointerLeave: () => void; + onDraftChange: (event: React.ChangeEvent) => void; + onEditorKeyDown: (event: React.KeyboardEvent) => void; + onEditorBlur: () => void; +}) { + if (editing) { + return ( + event.stopPropagation()} + onClick={(event) => event.stopPropagation()} + className="absolute top-1/2 right-3 z-20 w-[5ch] min-w-[3ch] -translate-y-1/2 border-b border-foreground/70 bg-transparent pb-px text-right font-mono text-[13px] font-medium text-foreground tabular-nums outline-none" + /> + ); + } + + return ( + + ); +} + +function Slider({ + label, + value, + defaultValue, + onValueChange, + formatValue, + unit, + snapOnClick = true, min = 0, max = 100, + step = 1, + largeStep, + disabled, + className, ...props -}: SliderPrimitive.Root.Props & - Pick): ReactElement { - const _values = useMemo(() => { - if (value !== undefined) { - return Array.isArray(value) ? value : [value]; - } - if (defaultValue !== undefined) { - return Array.isArray(defaultValue) ? defaultValue : [defaultValue]; - } - return [min]; - }, [value, defaultValue, min]); +}: SliderProps) { + const safeStep = resolveStep(step); + const decimals = decimalsForStep(safeStep, min, max); + + const isControlled = value !== undefined; + const [uncontrolledValue, setUncontrolledValue] = React.useState(() => + clampValue(defaultValue ?? min, min, max), + ); + const currentValue = resolveCurrentValue( + isControlled, + value, + uncontrolledValue, + min, + max, + ); + + const [hovered, setHovered] = React.useState(false); + const [focused, setFocused] = React.useState(false); + const [dragging, setDragging] = React.useState(false); + + const rootRef = React.useRef(null); + const labelRef = React.useRef(null); + const valueRef = React.useRef(null); + const thumbInputRef = React.useRef(null); + + const setCurrentValue = (nextValue: number) => { + if (!isControlled) setUncontrolledValue(nextValue); + onValueChange?.(nextValue); + }; + + const { + editing, + draft, + editorRef, + valueEditable, + handleValueClick, + handleValuePointerDown, + handleValuePointerEnter, + handleValuePointerLeave, + handleThumbKeyDown, + handleDraftChange, + handleEditorKeyDown, + handleEditorBlur, + } = useValueEditing({ + value: currentValue, + decimals, + min, + max, + step: safeStep, + disabled, + onCommit: setCurrentValue, + thumbInputRef, + }); + const { trackWidth, dodgeThresholds } = useTrackMeasurements({ + rootRef, + labelRef, + valueRef, + editing, + }); + + const active = isSliderActive({ + hovered, + dragging, + focused, + editing, + }); + const displayValue = formatSliderValue(currentValue, decimals, formatValue); + const percentage = getPercentage(currentValue, min, max); + const fillEdge = (percentage / 100) * trackWidth; + const handleShift = resolveHandleShift(fillEdge, trackWidth); + const dodge = isDodged(percentage, dodgeThresholds); + const handleOpacity = resolveHandleOpacity(active, dodge, dragging); + const marks = hashMarkPercents(min, max, safeStep); + + const handleValueChange = ( + nextValue: number, + details: SliderPrimitive.Root.ChangeEventDetails, + ) => { + if (details.reason === "drag") setDragging(true); + setCurrentValue(nextValue); + }; + + const handleValueCommitted = ( + nextValue: number, + details: SliderPrimitive.Root.CommitEventDetails, + ) => { + setDragging(false); + const snappedValue = resolveSnappedValue(nextValue, details.reason, { + min, + max, + step: safeStep, + snapOnClick, + }); + if (snappedValue !== nextValue) setCurrentValue(snappedValue); + }; return ( setHovered(true)} + onPointerLeave={() => setHovered(false)} + onPointerUp={() => setDragging(false)} + onPointerCancel={() => setDragging(false)} > - {children} - + + + - {Array.from({ length: _values.length }, (_, index) => ( - - ))} + + label} + getAriaValueText={() => + unit ? `${displayValue} ${unit}` : displayValue + } + onFocus={(event) => + setFocused(event.currentTarget.matches(":focus-visible")) + } + onBlur={() => setFocused(false)} + onKeyDown={handleThumbKeyDown} + className="absolute flex h-5 w-5 items-center justify-center transition-[inset-inline-start] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] outline-none group-data-[dragging]:transition-none" + > + + + + {label} + + + ); } -export function SliderValue({ - className, - ...props -}: SliderPrimitive.Value.Props): ReactElement { - return ( - - ); -} - -export { SliderPrimitive }; +export type { SliderProps }; +export { Slider };