From 15fe1b3098a8558b73a13e77f3d16cb43680e4e3 Mon Sep 17 00:00:00 2001 From: gntrs <239629917+gntrs@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:38:49 +0200 Subject: [PATCH] 1.2.0: /palette, four colors from one by the golden ratio --- AGENTS.md | 3 +- CHANGELOG.md | 4 + README.md | 4 + SETUP.md | 2 +- VERSION | 2 +- install.ps1 | 2 +- install.sh | 2 +- llms.txt | 1 + package-lock.json | 4 +- package.json | 4 +- skills/cook/SKILL.md | 1 + skills/palette/SKILL.md | 53 +++++++++ skills/palette/palette.mjs | 230 +++++++++++++++++++++++++++++++++++++ 13 files changed, 303 insertions(+), 9 deletions(-) create mode 100644 skills/palette/SKILL.md create mode 100644 skills/palette/palette.mjs diff --git a/AGENTS.md b/AGENTS.md index 8ff1ef6..4dd9426 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,7 @@ git clone --depth 1 https://github.com/gntrs/workflow.git ~/.claude/workflow ## you are working on this repo itself -markdown skills, one rules file, two installers and six scripts (the size probe, its runner, the brand check, the ref reader, the ref check, the recorder). no build. +markdown skills, one rules file, two installers and seven scripts (the size probe, its runner, the brand check, the ref reader, the ref check, the recorder, the palette maker). no build. - skills live in `skills//SKILL.md`, depth in `skills//references/`. frontmatter `name` matches the folder. - `rules/RULES.md` is always on. a skill never contradicts it. nothing tells the reader to edit an installed file: what is personal goes in `~/.claude/RULES.local.md` (template in `setup/RULES.local.md`). @@ -26,6 +26,7 @@ markdown skills, one rules file, two installers and six scripts (the size probe, - after changing `tools/responsive-probe.js`, run `node tools/probe-test.mjs` (needs playwright with chromium: `npx playwright install chromium`, or point `PLAYWRIGHT_MODULE` at an installed copy) and show it still catches the planted cases. - after changing `tools/brand-check.mjs`, run `node tools/brand-check.mjs --self-test` and show every line passes. - after changing `tools/ref-read.mjs` or `tools/ref-check.mjs`, run their `--self-test` and show every line passes. ref-read's needs playwright like the probe runner. +- after changing `skills/palette/palette.mjs`, run `node skills/palette/palette.mjs --self-test` and show every line passes. node only. - after changing `tools/record.mjs`, run `node tools/record.mjs --self-test` and show every line passes. it needs playwright like the probe runner, and ffmpeg for the mp4 lines (without it, those check the webm fallback). - after changing an installer, run `bash scripts/test-install.sh` (and `bash scripts/test-install.sh ps1` where `pwsh` exists). it installs into throwaway homes: fresh, an upgrade from old commits, with edits, uninstall. a new behavior gets a case there. keep `install.sh` and `install.ps1` doing the same thing. - `npm ci && npm test` runs the check, the installer cases and every tool self test. playwright is pinned in `package.json`. diff --git a/CHANGELOG.md b/CHANGELOG.md index d5f68aa..f3a2183 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ newest first. the installer prints the version it had and the one it wrote. +## 1.2.0 + +- **`/palette`, four colors from one.** give it a hex and it returns an accent, a soft tint and a dark, each step made with the golden ratio: the hue turned by 137.5 degrees, the saturation cut by 61.8%, the brightness multiplied by 0.382. `skills/palette/palette.mjs` does the math and prints the text color for each one and the contrast between every pair, so you see which ones can carry text. the result is a proposal you pick from. `--css` and `--json` for the output. + ## 1.1.1 - the readme says what this is in one line under the hero, so the page has words before "install". diff --git a/README.md b/README.md index acfd7c1..e879311 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,10 @@ once per repo. private notes in `.claude/` that never get committed. [skills/ini optional. one notes vault every repo writes to, tidied while you're away. [skills/brain](skills/brain/SKILL.md) ยท [skills/dream](skills/dream/SKILL.md) +### /palette <hex> + +one color in, four out: an accent, a soft tint and a dark, each made with the golden ratio. it prints the contrast between every pair, so you see which can carry text. [skills/palette](skills/palette/SKILL.md) + ### house rules these load on their own: diff --git a/SETUP.md b/SETUP.md index 40a8854..0a286bf 100644 --- a/SETUP.md +++ b/SETUP.md @@ -21,7 +21,7 @@ check these yourself and say what you found, in one short block. do not ask abou - os and shell, total ram, free disk. - whether `git`, `gh`, `node`, `docker` (and whether a docker vm is running), `python3`, `bun` and the `claude` cli exist. - `git config --global user.name` and `user.email`. none set: add a question for the name and email their commits go out as. -- what is already in `~/.claude/`: `CLAUDE.md`, `RULES.md`, `RULES.local.md`, `settings.json`, any skill folder with the same name as one of ours (`cook`, `bbq`, `deep`, `ship`, `status`, `review`, `initiate`, `design`, `write`, `playbook`, `brain`, `dream`), and whether pstack is already installed (`claude plugin list`). +- what is already in `~/.claude/`: `CLAUDE.md`, `RULES.md`, `RULES.local.md`, `settings.json`, any skill folder with the same name as one of ours (`cook`, `bbq`, `deep`, `ship`, `status`, `review`, `initiate`, `design`, `palette`, `write`, `playbook`, `brain`, `dream`), and whether pstack is already installed (`claude plugin list`). - an earlier install: `bash ~/.claude/workflow/install.sh --status` says which version is there and which files they edited. then one message, numbered, each question with the default you will use if they say "you decide": diff --git a/VERSION b/VERSION index 524cb55..26aaba0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.1.1 +1.2.0 diff --git a/install.ps1 b/install.ps1 index 9b62330..f355f04 100644 --- a/install.ps1 +++ b/install.ps1 @@ -57,7 +57,7 @@ $Stamp = Get-Date -Format 'yyyyMMdd-HHmmss' $Backup = Join-Path (Join-Path $Claude 'workflow-backups') $Stamp $VersionFile = Join-Path $Src 'VERSION' $Version = if (Test-Path $VersionFile) { (Get-Content $VersionFile -TotalCount 1 -Encoding UTF8).Trim() } else { 'unknown' } -$Ours = 'bbq','brain','cook','deep','design','dream','initiate','playbook','review','ship','status','write' +$Ours = 'bbq','brain','cook','deep','design','dream','initiate','palette','playbook','review','ship','status','write' $script:Did = @(); $script:Skipped = @(); $script:Moved = @() $script:NewMan = [ordered]@{} diff --git a/install.sh b/install.sh index 9bfd80c..286cbd8 100644 --- a/install.sh +++ b/install.sh @@ -72,7 +72,7 @@ MANIFEST="$CLAUDE_DIR/workflow-manifest" STAMP="$(date +%Y%m%d-%H%M%S)" BACKUP="$CLAUDE_DIR/workflow-backups/$STAMP" VERSION="$(cat "$SRC/VERSION" 2>/dev/null || echo unknown)" -OURS="bbq brain cook deep design dream initiate playbook review ship status write" +OURS="bbq brain cook deep design dream initiate palette playbook review ship status write" did=() skipped=() moved=() NEWMAN="$(mktemp)"; trap 'rm -f "$NEWMAN"' EXIT diff --git a/llms.txt b/llms.txt index 1e74f40..f76e0cb 100644 --- a/llms.txt +++ b/llms.txt @@ -22,6 +22,7 @@ to install it for someone: `git clone --depth 1 https://github.com/gntrs/workflo - [status](skills/status/SKILL.md): done, pushed, merged, in five lines - [initiate](skills/initiate/SKILL.md): prepare a repo for agents - [design](skills/design/SKILL.md): front end method: only brand elements and real products, the element kit, the right or wrong board, the review loop, the size sweep +- [palette](skills/palette/SKILL.md): four colors from one by the golden ratio, with the contrast between each pair measured - [write](skills/write/SKILL.md): prose for humans - [playbook](skills/playbook/SKILL.md): swarm shapes, debugging, research, mistake ledger - [brain](skills/brain/SKILL.md), [dream](skills/dream/SKILL.md): optional notes vault diff --git a/package-lock.json b/package-lock.json index 4b33f55..992276d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workflow", - "version": "1.1.1", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workflow", - "version": "1.1.1", + "version": "1.2.0", "license": "MIT", "devDependencies": { "playwright": "1.62.1" diff --git a/package.json b/package.json index 2db1af3..8d4adc1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workflow", - "version": "1.1.1", + "version": "1.2.0", "private": true, "description": "let him /cook: agent skills, rules and tools for Claude Code", "license": "MIT", @@ -8,7 +8,7 @@ "scripts": { "check": "bash scripts/check.sh", "test:install": "bash scripts/test-install.sh", - "test:tools": "node tools/brand-check.mjs --self-test && node tools/ref-check.mjs --self-test && node tools/probe-test.mjs --self-test && node tools/ref-read.mjs --self-test && node tools/record.mjs --self-test", + "test:tools": "node tools/brand-check.mjs --self-test && node skills/palette/palette.mjs --self-test && node tools/ref-check.mjs --self-test && node tools/probe-test.mjs --self-test && node tools/ref-read.mjs --self-test && node tools/record.mjs --self-test", "test": "npm run check && npm run test:install && npm run test:tools" }, "devDependencies": { diff --git a/skills/cook/SKILL.md b/skills/cook/SKILL.md index 91b248e..19322f5 100644 --- a/skills/cook/SKILL.md +++ b/skills/cook/SKILL.md @@ -131,3 +131,4 @@ never commit, push, open a pr, merge or deploy without the user's yes that speci | after a push they approved | any post push step the repo's `.claude/CLAUDE.md` names (a rebuild, a restart), from the pushed tree | | "is this the best outcome" | `/review` | | "hack it together", "quick prototype", a hackathon | `/bbq` | +| "build a palette", "what goes with this color" | `/palette` | diff --git a/skills/palette/SKILL.md b/skills/palette/SKILL.md new file mode 100644 index 0000000..444d971 --- /dev/null +++ b/skills/palette/SKILL.md @@ -0,0 +1,53 @@ +--- +name: palette +description: Four colors from one, by the golden ratio. A main color in, an accent, a soft tint and a dark out, with the text color for each and the contrast between every pair measured. A proposal for the user to pick from. Invoke on "/palette ", "build a palette", "what goes with this color", "i only have one color". +--- + +# palette + +one color in, four out. every step uses one number, the golden ratio (1.618), so there is little to tune. it is a starting point the user picks from, never a decision made for them. + +a brand that already names its colors wins. this is for when the user has one color and asks what goes with it. it does not replace `design`'s way of finding a look: with no brand, `design` still asks and shows real looks first, and these four colors are one thing to put in front of the user there. + +## the method + +work in hsb (hue, saturation, brightness), the model every color picker shows. + +1. **main.** the one color you have. read its hue on the wheel. `#00B2A9` is hue 177, saturation 100, brightness 70. +2. **accent.** turn the hue back by the golden angle, 137.5 degrees. `360 / 1.618 = 222.5`, `360 - 222.5 = 137.5`, so `177 - 137.5 = 39.5`. under zero, add 360. keep the saturation. +3. **complementary.** the main hue again, the saturation cut by 61.8% (multiply it by 0.382), the brightness set to 81. a soft tint for large areas. +4. **contrast.** the main hue and saturation, the brightness multiplied by 0.382. `70 x 0.382 = 27`. a dark for type and for shapes that sit on the tint. + +from `#00B2A9` that gives complementary `#80CFCB` and contrast `#004541`. the accent is hue 39.5: `#F29F00` once its brightness is lifted to 95, `#B37600` at the main color's 70. see below. + +where the numbers come from: 1.618 is the ratio, 0.618 and 0.382 are the two parts it cuts a whole into, and 137.5 is the same cut made on a circle. 81 is given by the method with no rule behind it. 50 x 1.618 happens to land there. + +## run it + +``` +node ~/.claude/skills/palette/palette.mjs '#00B2A9' +node ~/.claude/skills/palette/palette.mjs '#00B2A9' --accent-brightness 95 +node ~/.claude/skills/palette/palette.mjs '#00B2A9' --css +node ~/.claude/skills/palette/palette.mjs '#00B2A9' --json +``` + +it prints the four colors with their hue, saturation and brightness, the text color to use on each, then the contrast ratio between every pair and whether that pair can carry text. `--css` prints four custom properties named after the four roles, `--json` the same data for a script. node only, no install. + +text on each: the palette's own dark or tint if it reaches 4.5 on that color, else whichever of white and black measures higher. + +values are rounded the way a picker shows them, hue to half a degree, saturation and brightness to a whole percent, so the output matches the method done by hand. the main color is never changed. + +## what the method does not decide + +- **how bright the accent is.** the method fixes its hue and nothing else. the script keeps the main color's brightness. the worked example above lifts the accent to 95 by eye, which is what `--accent-brightness 95` reproduces. pick it looking at the two colors side by side. +- **whether text is readable.** the golden ratio says nothing about that, so the script measures it. read the lines it prints: 4.5 or more carries text, 3 to 4.5 carries large text only, under 3 carries none. main and accent side by side are usually under 3: use them as shapes next to each other, never as text on each other. +- **a gray, a near black or a white main.** it has no hue to speak of, so the wheel has nothing to turn and the four colors come out as one. the script refuses a saturation under 5 or a brightness under 10 and says so. pick a color. +- **which contrast brightness.** the method multiplies the main color's brightness, not the tint's. a very dark main gives a contrast near black, which is fine for type and useless as a second surface. +- **the name.** complementary here means the soft partner of the main color. it is not the opposite side of the wheel. + +## using the result + +- it is a proposal. show the user the four swatches side by side on a real surface before any of it goes into a token file. they say yes, or they move one. in a brand file it goes in as proposed, not chosen, until they do. +- main and accent are two hues. `design` holds to one accent and gives a second hue a job or drops it. so the user picks which of the two is the accent, and the other gets a job (a surface, a data series, an illustration) or is left out. +- the four names are this method's, not a token vocabulary. mapped to the roles `design` uses: the complementary is a ground or a surface, the contrast is ink, one of main and accent is the accent, and the "text on each" line for it is its accent ink. rename them when they go into the project's tokens. +- once picked, the colors live where the project keeps them. the script is not run again on every build. diff --git a/skills/palette/palette.mjs b/skills/palette/palette.mjs new file mode 100644 index 0000000..a0ded58 --- /dev/null +++ b/skills/palette/palette.mjs @@ -0,0 +1,230 @@ +#!/usr/bin/env node +// four colors from one, by the golden ratio. no dependencies. +// node palette.mjs [--accent-brightness N] [--css | --json] +// node palette.mjs --self-test +// values are rounded the way a color picker shows them (hue to half a degree, +// saturation and brightness to a whole percent) so the output matches what +// someone gets doing the same steps by hand. + +const PHI = (1 + Math.sqrt(5)) / 2; // 1.618 +const GOLDEN_ANGLE = 360 - 360 / PHI; // 137.5 degrees +const SMALL = 2 - PHI; // 0.382 +const SOFT_BRIGHTNESS = 81; // fixed by the method +const MIN_SATURATION = 5; // under these the four colors come out as one gray or one black +const MIN_BRIGHTNESS = 10; + +export function parseHex(input) { + if (typeof input !== 'string') throw new Error('give one hex color, like #00B2A9'); + let h = input.trim().replace(/^#/, ''); + if (/^[0-9a-f]{3}$/i.test(h)) h = h.replace(/./g, (c) => c + c); + if (!/^[0-9a-f]{6}$/i.test(h)) throw new Error(`not a hex color: ${input}`); + return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); +} + +export function toHex([r, g, b]) { + return '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('').toUpperCase(); +} + +export function rgbToHsb([r, g, b]) { + const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min; + let h = 0; + if (d !== 0) { + if (max === r) h = ((g - b) / d) % 6; + else if (max === g) h = (b - r) / d + 2; + else h = (r - g) / d + 4; + h = (h * 60 + 360) % 360; + } + return { + h: (Math.round(h * 2) / 2) % 360, + s: max === 0 ? 0 : Math.round((d / max) * 100), + b: Math.round((max / 255) * 100), + }; +} + +export function hsbToRgb({ h, s, b }) { + const v = (b / 100) * 255, c = v * (s / 100), m = v - c; + const x = c * (1 - Math.abs(((h / 60) % 2) - 1)); + const [r1, g1, b1] = [[c, x, 0], [x, c, 0], [0, c, x], [0, x, c], [x, 0, c], [c, 0, x]][Math.floor(h / 60) % 6]; + return [r1, g1, b1].map((n) => Math.round(n + m)); +} + +function luminance(rgb) { + const [r, g, b] = rgb.map((v) => { + const c = v / 255; + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +export function contrastRatio(a, b) { + const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (hi + 0.05) / (lo + 0.05); +} + +export function palette(hex, opts = {}) { + const main = rgbToHsb(parseHex(hex)); + if (main.s < MIN_SATURATION || main.b < MIN_BRIGHTNESS) throw new Error(`${hex} has no hue to work with (a gray, a near black or a white: saturation ${main.s}, brightness ${main.b}). turning the wheel does nothing to it. pick a color.`); + const ab = opts.accentBrightness; + if (ab !== undefined && !(Number.isFinite(ab) && ab >= 0 && ab <= 100)) throw new Error('--accent-brightness takes a number from 0 to 100'); + const roles = { + main, + accent: { h: (Math.round((main.h - GOLDEN_ANGLE + 360) * 2) / 2) % 360, s: main.s, b: ab === undefined ? main.b : Math.round(ab) }, + complementary: { h: main.h, s: Math.round(main.s * SMALL), b: SOFT_BRIGHTNESS }, + contrast: { h: main.h, s: main.s, b: Math.round(main.b * SMALL) }, + }; + const out = {}; + for (const [name, hsb] of Object.entries(roles)) { + const rgb = name === 'main' ? parseHex(hex) : hsbToRgb(hsb); // the main color is never rewritten by rounding + out[name] = { hex: toHex(rgb), ...hsb, rgb }; + } + const inks = [['contrast', out.contrast.rgb], ['complementary', out.complementary.rgb], ['white', [255, 255, 255]], ['black', [0, 0, 0]]]; + for (const [name, c] of Object.entries(out)) { + const scored = inks.filter(([n]) => n !== name).map(([n, rgb]) => ({ name: n, hex: toHex(rgb), ratio: Math.round(contrastRatio(c.rgb, rgb) * 100) / 100 })); + // a palette color that carries text wins. else whichever of white and black reads best. + c.ink = scored.find((k) => k.ratio >= 4.5 && (k.name === 'contrast' || k.name === 'complementary')) || scored.filter((k) => k.name === 'white' || k.name === 'black').sort((a, b) => b.ratio - a.ratio)[0]; + } + const names = Object.keys(out); + const pairs = []; + for (let i = 0; i < names.length; i++) for (let j = i + 1; j < names.length; j++) { + const ratio = contrastRatio(out[names[i]].rgb, out[names[j]].rgb); + pairs.push({ a: names[i], b: names[j], ratio: Math.round(ratio * 100) / 100, text: ratio >= 4.5 ? 'text' : ratio >= 3 ? 'large text only' : 'no text' }); + } + return { colors: out, pairs }; +} + +function render(p, mode) { + if (mode === 'json') { + const colors = Object.fromEntries(Object.entries(p.colors).map(([k, { hex, h, s, b, ink }]) => [k, { hex, h, s, b, ink }])); + return JSON.stringify({ colors, pairs: p.pairs }, null, 2); + } + if (mode === 'css') { + return [':root {', ...Object.entries(p.colors).map(([k, c]) => ` --${k}: ${c.hex};`), '}'].join('\n'); + } + const lines = Object.entries(p.colors).map(([k, c]) => `${k.padEnd(14)} ${c.hex} h ${String(c.h).padStart(5)} s ${String(c.s).padStart(3)} b ${String(c.b).padStart(3)}`); + lines.push('', 'text on each:'); + for (const [k, c] of Object.entries(p.colors)) lines.push(`${k.padEnd(14)} ${c.ink.hex} (${c.ink.name}) ${c.ink.ratio.toFixed(2)}`); + lines.push('', 'contrast between each pair (4.5 for text, 3 for large text):'); + for (const q of p.pairs) lines.push(`${(q.a + ' / ' + q.b).padEnd(28)} ${q.ratio.toFixed(2).padStart(5)} ${q.text}`); + return lines.join('\n'); +} + +function selfTest() { + let failed = 0; + const check = (label, got, want) => { + const ok = JSON.stringify(got) === JSON.stringify(want); + if (!ok) failed++; + console.log(`${ok ? 'pass' : 'FAIL'} ${label}${ok ? '' : `: got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`}`); + }; + const throws = (label, fn, part) => { + let msg = null; + try { fn(); } catch (e) { msg = e.message; } + check(label, msg !== null && msg.includes(part), true); + }; + + // the worked example the method comes from + const ref = palette('#00B2A9', { accentBrightness: 95 }); + check('main reads as h 177 s 100 b 70', [ref.colors.main.h, ref.colors.main.s, ref.colors.main.b], [177, 100, 70]); + check('accent lands on 39.5 degrees', ref.colors.accent.h, 39.5); + check('accent at brightness 95 is #F29F00', ref.colors.accent.hex, '#F29F00'); + check('complementary is #80CFCB', ref.colors.complementary.hex, '#80CFCB'); + check('contrast is #004541', ref.colors.contrast.hex, '#004541'); + check('main comes back as itself', ref.colors.main.hex, '#00B2A9'); + check('an odd main comes back as itself', palette('#3b5bdb').colors.main.hex, '#3B5BDB'); + + check('accent keeps the main brightness by default', palette('#00B2A9').colors.accent.b, 70); + check('hue wraps below zero', palette('#FF0000').colors.accent.h, 222.5); + check('three digit hex, no hash, lowercase', palette('f00').colors.main.hex, '#FF0000'); + check('six pairs for four colors', ref.pairs.length, 6); + check('black on white is 21', Math.round(contrastRatio([0, 0, 0], [255, 255, 255])), 21); + check('a color against itself is 1', contrastRatio([10, 20, 30], [10, 20, 30]), 1); + const cc = ref.pairs.find((q) => q.a === 'complementary' && q.b === 'contrast'); + check('contrast on complementary carries text', cc.text, 'text'); + const ma = ref.pairs.find((q) => q.a === 'main' && q.b === 'accent'); + check('main on accent is flagged no text', ma.text, 'no text'); + + // every rgb value survives the round trip through whole rgb -> hex -> rgb + check('hex round trip', toHex(parseHex('#0a1B2c')), '#0A1B2C'); + const primaries = { 0: '#FF0000', 60: '#FFFF00', 120: '#00FF00', 180: '#00FFFF', 240: '#0000FF', 300: '#FF00FF' }; + for (const [h, want] of Object.entries(primaries)) { + check(`full color at hue ${h} is ${want}`, toHex(hsbToRgb({ h: Number(h), s: 100, b: 100 })), want); + check(`${want} reads back as hue ${h}`, rgbToHsb(parseHex(want)).h, Number(h)); + } + check('a hue that rounds up to 360 reads as 0', rgbToHsb(parseHex('#FF0001')).h, 0); + check('and its accent still lands on 222.5', palette('#FF0001').colors.accent.h, 222.5); + check('half a degree survives', rgbToHsb(hsbToRgb({ h: 39.5, s: 100, b: 95 })).h, 39.5); + check('accent brightness 0 is black', palette('#00B2A9', { accentBrightness: 0 }).colors.accent.hex, '#000000'); + check('accent brightness 100 is the full color', palette('#00B2A9', { accentBrightness: 100 }).colors.accent.hex, '#FFA800'); + check('text on the tint is the contrast color', ref.colors.complementary.ink.name, 'contrast'); + check('text on the dark is the tint', ref.colors.contrast.ink.name, 'complementary'); + check('text on the bright accent is the contrast color', [ref.colors.accent.ink.name, ref.colors.accent.ink.ratio >= 4.5], ['contrast', true]); + check('a color never names itself as its text', Object.entries(ref.colors).every(([k, c]) => c.ink.name !== k), true); + const lowAccent = palette('#00B2A9').colors.accent; + check('an accent the dark cannot sit on falls back to white or black', [lowAccent.ink.name, lowAccent.ink.ratio >= 4.5], ['black', true]); + + throws('gray is refused', () => palette('#808080'), 'no hue'); + throws('white is refused', () => palette('#FFFFFF'), 'no hue'); + throws('black is refused', () => palette('#000'), 'no hue'); + throws('a near gray is refused', () => palette('#7F8080'), 'no hue'); + throws('a near black is refused', () => palette('#010000'), 'no hue'); + check('a dim, barely colored main at the floor is let through', palette('#1A1818').colors.main.hex, '#1A1818'); + throws('empty input is refused', () => palette(''), 'not a hex color'); + throws('a word is refused', () => palette('teal'), 'not a hex color'); + throws('five digits is refused', () => palette('#12345'), 'not a hex color'); + throws('eight digits is refused', () => palette('#00B2A9FF'), 'not a hex color'); + throws('a missing argument is refused', () => palette(undefined), 'give one hex'); + throws('accent brightness over 100 is refused', () => palette('#00B2A9', { accentBrightness: 101 }), '0 to 100'); + throws('accent brightness that is not a number is refused', () => palette('#00B2A9', { accentBrightness: NaN }), '0 to 100'); + + const css = render(ref, 'css'); + check('css output has the four properties', ['--main: #00B2A9;', '--accent: #F29F00;', '--complementary: #80CFCB;', '--contrast: #004541;'].every((l) => css.includes(l)), true); + check('json output parses back', JSON.parse(render(ref, 'json')).colors.contrast.hex, '#004541'); + + // the command line: every exit code and which stream it writes to + const run = (...argv) => { const io = { out: [], err: [], log(m) { this.out.push(m); }, error(m) { this.err.push(m); } }; const code = main(argv, io); return { code, out: io.out.join('\n'), err: io.err.join('\n') }; }; + check('a color alone exits 0 with a table', [run('#00B2A9').code, run('#00B2A9').out.includes('text on each:')], [0, true]); + check('the flag before the color works', run('--accent-brightness', '95', '#00B2A9', '--css').out.includes('--accent: #F29F00;'), true); + check('no arguments prints usage and exits 2', [run().code, run().err.startsWith('usage:')], [2, true]); + check('--css with --json is refused', [run('#00B2A9', '--css', '--json').code, run('#00B2A9', '--json', '--css').code], [2, 2]); + check('two colors are refused', run('#00B2A9', '#FF0000').code, 2); + check('an unknown flag is refused', [run('#00B2A9', '--scss').code, run('#00B2A9', '--scss').err], [2, 'unknown option --scss']); + for (const v of ['', '0x5f', '1e1', '-5', 'abc', '101', undefined]) { + const r = v === undefined ? run('#00B2A9', '--accent-brightness') : run('#00B2A9', '--accent-brightness', v); + check(`--accent-brightness ${v === undefined ? 'with nothing after it' : JSON.stringify(v)} is refused`, [r.code, r.out], [2, '']); + } + check('--accent-brightness 62.5 is taken', run('#00B2A9', '--accent-brightness', '62.5').code, 0); + check('a bad color exits 2 and prints nothing to stdout', [run('teal').code, run('teal').out], [2, '']); + + console.log(failed ? `${failed} failed` : 'all passed'); + return failed ? 1 : 0; +} + +function main(argv, io = console) { + if (argv.includes('--self-test')) return selfTest(); + const usage = 'usage: node palette.mjs [--accent-brightness N] [--css | --json]\n node palette.mjs --self-test'; + let hex, accentBrightness, mode; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--css' || a === '--json') { + if (mode) { io.error('--css or --json, not both'); return 2; } + mode = a.slice(2); + } else if (a === '--accent-brightness') { + const v = argv[++i]; + if (v === undefined || !/^\d{1,3}(\.\d+)?$/.test(v)) { io.error('--accent-brightness takes a number from 0 to 100'); return 2; } + accentBrightness = Number(v); + } else if (a.startsWith('--')) { io.error(`unknown option ${a}`); return 2; } + else if (hex === undefined) hex = a; + else { io.error('one color at a time'); return 2; } + } + if (hex === undefined) { io.error(usage); return 2; } + try { + io.log(render(palette(hex, { accentBrightness }), mode || 'table')); + return 0; + } catch (e) { + io.error(e.message); + return 2; + } +} + +import { fileURLToPath } from 'node:url'; +import { realpathSync } from 'node:fs'; +if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) process.exit(main(process.argv.slice(2)));