diff --git a/.changeset/experimental-theme-host-keeps-own-states.md b/.changeset/experimental-theme-host-keeps-own-states.md new file mode 100644 index 0000000000000..117a59e362657 --- /dev/null +++ b/.changeset/experimental-theme-host-keeps-own-states.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[experimental] `astryx experimental theme editor`: a part drawn on another part's element keeps its states to itself. A Button that a pagination cell is drawn on no longer takes the cell's `selected` state, so the button family reads the Button again and a selected look on a list row no longer reaches every Button; a part that always rides another (a list item on its Item) still takes that one's states. + +@josephfarina diff --git a/.changeset/experimental-theme-pictures-agents-open-overlays.md b/.changeset/experimental-theme-pictures-agents-open-overlays.md index aca2b761f0d82..32ca86e89b8e3 100644 --- a/.changeset/experimental-theme-pictures-agents-open-overlays.md +++ b/.changeset/experimental-theme-pictures-agents-open-overlays.md @@ -5,7 +5,7 @@ [experimental] The pictures an agent opens show the overlays, and the output keeps what was missed where a cut output still shows it: - `preview.png` (the sample page) ends with a strip of a tooltip, a popover, a menu and a select list drawn open, from the overlays the sheet draws. -- `sheet-overlays.png` shows the small overlays first, five to a row, each cell at most 300px tall, and no part of an overlay alone, so it stays under about 1600px. +- `sheet-overlays.png` shows the small overlays first, about five to a row, a panel over the page cropped to its top, and no part of an overlay alone. - A change without `--png` names `show --png` and the two pictures it writes to open. - A change counts, near its top, the parts the theme's changes did not reach; `show` lists them, with their lines, last before its closing look line. diff --git a/.changeset/experimental-theme-sheet-cells-b.md b/.changeset/experimental-theme-sheet-cells-b.md index fcdebe889fffe..46d49a12818e1 100644 --- a/.changeset/experimental-theme-sheet-cells-b.md +++ b/.changeset/experimental-theme-sheet-cells-b.md @@ -2,6 +2,6 @@ '@astryxdesign/cli': patch --- -[experimental] `astryx experimental theme editor show --png` cuts a family's picture taller than 1600px into pictures of at most that height, in order (`sheet-inputs-1.png`, `-2` …), each cut between parts, so a reader takes each in whole. The pictures show a looping animation (a skeleton, a pulsing dot) at a frame a person sees, a status dot in its color, a vertical divider at a height, each table, code and app shell variant on a row of its own, and a section's sample text; a deprecated part, and a closed overlay the open states draw open (the mobile navigation drawer), are no longer drawn as empty cells. +[experimental] `astryx experimental theme editor show --png` cuts a family's picture taller than 1600px between rows of parts into pictures of about that height (a row taller than that is a picture of its own), in order (`sheet-inputs-1.png`, `-2` …), each cut between parts, so a reader takes each in whole. The pictures show a looping animation (a skeleton, a pulsing dot) at a frame a person sees, a status dot in its color, a vertical divider at a height, each table, code and app shell variant on a row of its own, and a section's sample text; a deprecated part, and a closed overlay the open states draw open (the mobile navigation drawer), are no longer drawn as empty cells. @josephfarina diff --git a/.changeset/theme-round15-part-02.md b/.changeset/theme-round15-part-02.md new file mode 100644 index 0000000000000..5cea3e425ae3a --- /dev/null +++ b/.changeset/theme-round15-part-02.md @@ -0,0 +1,34 @@ +--- +'@astryxdesign/cli': patch +--- + +[experimental] `astryx experimental theme editor`: a border asked of a part that draws none goes to the pieces inside it only where those pieces draw borders of their own (a date and time field's two boxes), so "top nav with a 1px bottom border" writes the border on the top nav, not under each nav item, and "sidebar with a 1px right border" on the sidebar, not beside each link. + +- `astryx experimental theme editor` keeps what a change reports to what it did: a border set for light alone no longer reports the dark frame it left as the theme draws it. + +- `astryx experimental theme editor how`: "the active nav item should be a #e8def8 pill" again gives pill corners on the selected item only. There is now a single reader for a color and shape, so the item's state is kept. + +- `astryx experimental theme editor how` now gives a text color for every variant of a part whose variants each take a color of their own ("buttons with white text", "badges with dark text") to each variant only in the modes where it reads; text a part's variants read from shared tokens (a card's) is not measured this way unless the same answer gives them a fill. It measures against the variant's own fill, see-through fills over the page, or the fill the same answer gives it. Variants it can't read on keep their own text, and the answer says which. + +Other fixes: + +- "tinted " fills with the color at a low strength over what's beneath, not the solid color. A text color asked with the tint, on any part it fills (a button variant, a card, a selected nav item), deepens the tint along its own hue until that text reads (to 95% for white on blue); only when no strength of that hue reads is the text kept to the modes it reads in, with a readable ink named. +- A rule with its own verb said after a part's clause ("3px corners on cards, never use pure black for text") now applies to the whole theme. + +- `astryx experimental theme editor set … --only` always works as an escape from a group: on a member of a group that spreads it keeps the change to that member, and on a part that is styled on its own already (a sub-part, a card) it is taken and said, in place of a refusal; only a group itself, which has no one member to keep to, refuses it. A menu's radio is kept apart from every other radio: "square corners but keep menu radios round" says its circle is left as it is, and a round ask on a menu radio the theme squared offers the undo that gives the circle back. + +- `astryx experimental theme editor`: a part Core marks open is drawn open, so `--state expanded` reaches a dropdown menu's submenu row (open while its flyout is, though it is highlighted too) and a top nav's menu trigger (a control on the page, now kept as drawn open). + +- `astryx experimental theme editor`: the states Core marks on a part's own element are the part's to set. A list item (and so a checkbox list's row) takes `--state selected`, written as the attribute Core marks; a checkbox's or radio's box takes `--state hover` and the other moment states, shown from the part holding its invisible input instead of refused; a state asked of a container names the part inside it that has it, so `--on pagination --state selected` points to the selected page's item (`--on pagination-item --state selected`); and a part the drawing shows open in an overlay records its open state for `--state expanded`. + +- `astryx experimental theme editor show` draws a doc sample's plain HTML text field as the theme's own text input, a submenu's flyout once beside the menu it opens from instead of a second time below it, a control drawn pressed at the moment of its press (a press flash no longer fades back to rest), a command palette with an item highlighted on the open states page, and the mobile navigation drawer's panel inside its cell. + +- The pictures of `astryx experimental theme editor show --png` show their whole page: a page laid out wider than the picture window is pictured to its own width instead of cut at the window's edge; the mobile navigation drawer, which draws nothing closed, has no empty cell on the navigation pictures either; an overlay drawn open after its part (a toolbar's menu) sits under the control that opens it; and a step name cut by less than a pixel is shown whole too. + +- `astryx experimental theme editor how`: rows said of a part that holds no table rows are that part's own rows, the items it draws, so "menus with 32px rows" sizes the menu items and never every table row; and a part word right before a noun the editor knows as nothing ("a radio station", "a button factory", "a card game") begins a compound subject, never the part: it is named and nothing is written for it, and the rest of the ask is read as before. + +- `astryx experimental theme editor` measures a state's fill against the text that state draws, in its own variant: a part that draws no text (a switch's track, a tab's underline) gets no text problem, and a primary button's hover fill is measured against the primary button's own text, not another variant's. A page change that leaves the loading placeholder as faint as the base drew it no longer reports it as a new problem. + +- In a light-only or dark-only theme, a text color set on a part whose own background is an image (a gradient button face) is written for both modes. Inside a lightbox or overlay, which Core draws in the other scheme, the text stays on that face: it no longer turns white on a light gel button. The contrast check measures it the same way. + +@josephfarina diff --git a/packages/cli/api/theme-edit/_catalog.mjs b/packages/cli/api/theme-edit/_catalog.mjs index 11b506b4fc3a1..c022bc565fb86 100644 --- a/packages/cli/api/theme-edit/_catalog.mjs +++ b/packages/cli/api/theme-edit/_catalog.mjs @@ -191,6 +191,21 @@ export const SAMPLE_PAGE = h( ), ); +/** + * The few fixed items of the sample search source a page hands a part that + * requires one (a typeahead): the editor's pages and the catalog the part + * data is read from use these same items. + */ +export const SAMPLE_SEARCH_ITEMS = Object.freeze([ + {id: 'design', label: 'Design'}, + {id: 'engineering', label: 'Engineering'}, + {id: 'research', label: 'Research'}, + {id: 'marketing', label: 'Marketing'}, +]); + +/** The prop value that stands for the page's sample search source. */ +export const SAMPLE_SOURCE = Object.freeze({__code: 'SAMPLE_SOURCE'}); + /** * Overlays the overlays section draws open in a deeper state than their docs * show: a menu with its submenu open, a popover that holds a form, a date and @@ -280,6 +295,19 @@ export const OPEN_SCENES = Object.freeze([ }, }), }, + { + name: 'CommandPalette', + label: 'highlighted', + // Its picker highlights the chosen item once its first results come, + // so it is drawn as the browser shows it after mounting. + mounted: true, + tree: h('CommandPalette', { + isOpen: true, + isInline: true, + searchSource: SAMPLE_SOURCE, + value: SAMPLE_SEARCH_ITEMS[1].id, + }), + }, { name: 'MobileNav', label: 'open', @@ -398,21 +426,6 @@ export function elementNames(v, out = new Set()) { /** The module a binding imports. @param {Binding} b */ export const bindingFrom = b => (typeof b === 'string' ? b : b.from); -/** - * The few fixed items of the sample search source a page hands a part that - * requires one (a typeahead): the editor's pages and the catalog the part - * data is read from use these same items. - */ -export const SAMPLE_SEARCH_ITEMS = Object.freeze([ - {id: 'design', label: 'Design'}, - {id: 'engineering', label: 'Engineering'}, - {id: 'research', label: 'Research'}, - {id: 'marketing', label: 'Marketing'}, -]); - -/** The prop value that stands for the page's sample search source. */ -export const SAMPLE_SOURCE = Object.freeze({__code: 'SAMPLE_SOURCE'}); - /** * The page module source for a list of items. Each item renders on its own, * so one component that throws leaves the rest of the page. With a theme, @@ -755,6 +768,9 @@ export const SHEET_CSS = [ // An overlay shown in place keeps its own width (a popover that holds a // form, a date input's calendar): its cell grows to hold it. '.cs-cell [popover][data-astryx-layer-root]{display:block!important;position:relative!important;inset:auto!important;margin:8px 0 0!important;translate:none!important;transform:none!important;box-sizing:border-box!important}', + // A layer opened from inside another (a submenu's flyout) sits beside it. + '.cs-cell [data-astryx-layer-nest]{display:flex;align-items:flex-start;gap:4px}', + '.cs-cell [data-astryx-layer-nest] > [data-astryx-layer-root]{margin-top:8px!important}', // A part shown for its open look that opened nothing has no cell. '.cs-cell:has(.cs-open):not(:has(.cs-open [data-astryx-layer-root])){display:none}', // The overlays section's own page (sheet-overlays.png): five to a row, @@ -768,6 +784,9 @@ export const SHEET_CSS = [ '.cs-states-cell{min-width:0;overflow:clip;overflow-clip-margin:8px;padding:6px}', // A panel wider than its cell (a narrow screen's navigation drawer) is // drawn from its start, never cut at the start. - '.cs-cell dialog > *{max-width:100%!important}', + // A dialog drawn in place holds its panel in place too: a panel placed + // over the window (a navigation drawer at the window's edge) would leave + // the dialog with no height, and the cell empty. + '.cs-cell dialog > *{max-width:100%!important;position:relative!important;inset:auto!important}', '.cs-cell dialog{display:block!important;position:relative!important;inset:auto!important;margin:0!important;max-width:100%!important;max-height:300px!important;translate:none!important;transform:none!important}', ].join(''); diff --git a/packages/cli/api/theme-edit/_check.mjs b/packages/cli/api/theme-edit/_check.mjs index b3f758a3a04d4..603ee34e42e74 100644 --- a/packages/cli/api/theme-edit/_check.mjs +++ b/packages/cli/api/theme-edit/_check.mjs @@ -4781,22 +4781,25 @@ function checkOne( }); // --only is checked on a part this Core has; a part in other letters or // misspelt gets the part's own refusal first, with --only kept. + // --only keeps a change to the part named. On a group itself, or with no + // part, it names nothing to keep to, and is refused. On a part that is + // styled on its own already (a part in no group that spreads, such as a + // sub-part or a member of a group that spreads only when named), it asks + // for what the change does anyway: the change is made, without it, and + // said, so the escape always works. if (s.only && (!s.on || TARGET.has(s.on) || FAMILIES[s.on])) { const fam = s.on ? familyOf(s.on) : null; - if (!fam || FAMILIES[/** @type {string} */ (s.on)]) + if (!s.on || FAMILIES[s.on]) refuse( E.ERR_INVALID_ARGUMENT, '--only is for one member of a group, such as text-input (how --list groups).', {run: [`${HOW} --list groups`]}, ); - if (!AUTO_SPREAD.includes(/** @type {string} */ (fam))) - refuse( - E.ERR_INVALID_ARGUMENT, - `${s.on} is styled on its own already: only ${AUTO_SPREAD.join(' and ')} spread to their group, so drop --only.`, - // The same command with only --only dropped: every other scope - // (a variant, a state, a mode) kept, never a wider write. - {run: [setLine(slug, thing, v, {...s, only: undefined}, unset)]}, - ); + if (!fam || !AUTO_SPREAD.includes(fam)) { + s.only = undefined; + if (!unset) + s.note = `${s.on} is styled on its own already (only the ${AUTO_SPREAD.join(' and ')} groups spread), so --only changes nothing: it is saved without it`; + } } // A font role in other letters (Body, CODE) is that role. if ( @@ -5102,16 +5105,23 @@ function checkOne( ); if (s.state && !statesHold(states, s.state)) { // A part drawn inside this one that has the state (a calendar's day - // is today; the calendar is not): that part's line, with the state. + // is today; the calendar is not; a pagination's page button is the + // current one): that part's line, with the state. Its own pieces + // first, then the parts the census finds drawn inside it. const state = String(s.state); + const holds = (/** @type {string} */ k) => + statesHold(partStates(ctx, k), state); const inner = meant ? [] - : [...ctx.project.target.keys()] - .filter( - k => - k.startsWith(`${s.on}-`) && - statesHold(partStates(ctx, k), state), - ) + : [ + ...new Set([ + ...[...ctx.project.target.keys()].filter(k => + k.startsWith(`${s.on}-`), + ), + ...(ctx.C.MAP[String(s.on)]?.contains ?? []), + ]), + ] + .filter(k => ctx.project.target.has(k) && holds(k)) .slice(0, 3); refuse( E.ERR_THEME_UNKNOWN_STATE, @@ -5182,7 +5192,10 @@ function checkOne( /^(hover|active|focus|focus-visible|focus-within)$/.test(String(s.state)) ) { const all = partsOf(ctx, s); - const under = all.filter(t => ctx.C.MAP[t]?.underInput != null); + // (A part whose input sits in a part the theme names takes the state + // from that part, and the build writes it so; only one whose input no + // themed part holds is refused.) + const under = all.filter(t => ctx.C.MAP[t]?.underInput === ''); if (under.length && under.length === all.length) { const holders = [ ...new Set(under.map(t => ctx.C.MAP[t]?.underInput).filter(Boolean)), @@ -5901,7 +5914,7 @@ function checkOne( if (thing === 'corners') { if (s.on) { refuseInvisibleCorners(ctx, slug, s, data); - refuseRadioCorners(ctx, slug, s); + refuseRadioCorners(ctx, slug, s, data); } // With no corners setting yet, a step starts from the base theme's // own radius. @@ -7940,21 +7953,39 @@ function checkOne( * @param {import('./_settings.mjs').Ctx} ctx * @param {string} slug * @param {import('./_settings.mjs').Setting} s + * @param {import('./_settings.mjs').ThemeData} data */ -function refuseRadioCorners(ctx, slug, s) { +function refuseRadioCorners(ctx, slug, s, data) { if (ctx.unchecked) return; const parts = partsOf(ctx, s); if (!parts.length || !parts.every(t => radioCircle(ctx.C, t))) return; // A radius set on the part itself overrides the circle: a square radio - // is asked of this component, by name. + // is asked of this component, by name. A fully round ask (pill, round) + // is the circle it has: with a radius the theme set on it, the undo of + // that radius gives the circle back. const px = cornerPxOf(String(s.value)); - const own = - Number.isFinite(px) && px < 9999 - ? setLine(slug, 'border-radius', px === 0 ? '0' : `${px}px`, s) - : null; + const saved = (data?.settings ?? []).find( + (/** @type {any} */ x) => + x.thing === 'border-radius' && + x.on === s.on && + !x.when && + !x.state && + !x.mode, + ); + // (A step, "rounder" or "sharper", is no length: only "more" is round, + // and "less" gets no line, since a circle has no corner to sharpen.) + const step = Number.isFinite(px) ? null : String(s.value); + const round = step ? step === 'more' : px >= 9999; + const own = round + ? saved + ? `${P} undo ${slug} border-radius --on ${s.on}` + : null + : step + ? null + : setLine(slug, 'border-radius', px === 0 ? '0' : `${px}px`, s); refuse( E.ERR_THEME_NO_EFFECT, - `${s.on} is a radio's circle (border-radius 50%), not a corner, so the corners dial leaves it and changes nothing you see.${own ? ` A border-radius on it sets its shape: ${own.replace(`${P} `, '')}.` : ''}`, + `${s.on} is a radio's circle (border-radius 50%), not a corner, so the corners dial leaves it and changes nothing you see.${round ? (saved ? ` ${slug} sets border-radius ${saved.value} on it; undoing that gives the circle back: ${String(own).replace(`${P} `, '')}.` : ` It is fully round already.`) : own ? ` A border-radius on it sets its shape: ${own.replace(`${P} `, '')}.` : ''}`, {run: own ? [own] : [`${HOW} ${s.on}`]}, ); } diff --git a/packages/cli/api/theme-edit/_context.mjs b/packages/cli/api/theme-edit/_context.mjs index e50579d3f8185..efd831ae6713c 100644 --- a/packages/cli/api/theme-edit/_context.mjs +++ b/packages/cli/api/theme-edit/_context.mjs @@ -43,7 +43,7 @@ import { } from './_tables.mjs'; import {makeCompiler} from './_compiler.mjs'; import {openProject, installLine} from './_project.mjs'; -import {partData} from './_parts.mjs'; +import {addCensusStates, partData} from './_parts.mjs'; import {writeWhole} from './_palette.mjs'; import { assetRef, @@ -146,6 +146,7 @@ export async function context(cwd) { let uncheckedCode = null; try { parts = await partData(project); + addCensusStates(project, parts); } catch (e) { if (!isRenderFailure(e)) throw e; unchecked = renderCause(project, /** @type {Error} */ (e).message); diff --git a/packages/cli/api/theme-edit/_edit.mjs b/packages/cli/api/theme-edit/_edit.mjs index 086c1400fd930..95d887921dd80 100644 --- a/packages/cli/api/theme-edit/_edit.mjs +++ b/packages/cli/api/theme-edit/_edit.mjs @@ -6970,36 +6970,78 @@ async function changeOnce( !s.state && !s.when && /^background(-color)?$/.test(s.thing) - ) + ) { + // One note for each cause: the parts of a group whose fill covers the + // same paints (every input's status and disabled fills) are said + // together, with lines on the group, not once for each part. + /** @type {Map, flags: Set}>} */ + const causes = new Map(); for (const t of parts) { const {rest, covered} = coveredPaints(ctx, t, s.thing); if (!covered.length) continue; - const all = [...new Set(covered.map(c => `${c.cond} (${c.token})`))]; + // (The cause is what the fill covers, by kind: the props and states + // Core paints a fill for, whatever their order or count on a part.) + const kinds = [ + ...new Set(covered.map(c => String(c.cond).split('=')[0])), + ].sort(); + const key = JSON.stringify([kinds, rest ?? null]); + const cause = causes.get(key) ?? { + members: [], + rest: rest ?? null, + all: new Set(), + flags: new Set(), + }; + cause.members.push(t); + for (const c of covered) { + cause.all.add(`${c.cond} (${c.token})`); + if (c.flags) cause.flags.add(String(c.flags)); + } + causes.set(key, cause); + } + // Each chain starts with the undo of the fill just set: while it + // stays, every variant and state keeps it. + const undo = `${P} undo ${slug} ${undoArgs(s)}`; + const modeFlag = s.mode ? ` --mode ${s.mode}` : ''; + for (const { + members, + rest, + all: allSet, + flags: flagSet, + } of causes.values()) { + const all = [...allSet].sort(); const named = [ ...all.slice(0, 4), ...(all.length > 4 ? [`${all.length - 4} more`] : []), ]; + const flags = [...flagSet]; + // Lines go on the part as set when the cause is every part it + // styles (its group); else on each part the cause is. + const targets = + members.length === parts.length && s.on ? [s.on] : members; const lines = [ ...new Set( - covered - .filter(c => c.flags) - .map( - c => - `${P} set ${slug} background-color ${quoteCommandArgument(String(s.value))} --on ${t} ${c.flags}${s.mode ? ` --mode ${s.mode}` : ''}`, + targets.flatMap(on => + flags.map( + f => + `${P} set ${slug} background-color ${quoteCommandArgument(String(s.value))} --on ${on} ${f}${modeFlag}`, ), + ), ), ]; - // Each chain starts with the undo of the fill just set: while it - // stays, every variant and state keeps it. - const undo = `${P} undo ${slug} ${undoArgs(s)}`; + const who = + members.length > 3 + ? `${members.slice(0, 3).join(', ')} and ${members.length - 3} more` + : members.join(', '); + const own = members.length > 1 ? 'their' : 'its'; notes.push( - `${s.mode ? `in ${s.mode} mode, ` : ''}${t}'s fill now covers the fill Core gives it ${named.length > 1 ? 'in each of' : 'in'} ${named.join(', ')}, so ${named.length > 1 ? 'those no longer differ' : 'that no longer shows'}${ + `${s.mode ? `in ${s.mode} mode, ` : ''}${who}${members.length > 1 ? "'s fills now cover" : "'s fill now covers"} the fill Core gives ${members.length > 1 ? 'them' : 'it'} ${named.length > 1 ? 'in each of' : 'in'} ${named.join(', ')}, so ${named.length > 1 ? 'those no longer differ' : 'that no longer shows'}${ rest - ? `; to change only its fill at rest: ${undo}, then ${P} set ${slug} ${rest} ${quoteCommandArgument(String(s.value))} --on ${t}${s.mode ? ` --mode ${s.mode}` : ''}` + ? `; to change only ${own} fill at rest: ${undo}, then ${targets.map(on => `${P} set ${slug} ${rest} ${quoteCommandArgument(String(s.value))} --on ${on}${modeFlag}`).join('; ')}` : '' }${lines.length ? `; to fill only one of them: ${undo}, then ${lines.slice(0, 3).join('; or ')}` : ''}`, ); } + } // A color dial or token that a plain part's own fill covers no longer // reaches that part where Core paints with it: said. if (sub === 'set' && !s.on) { diff --git a/packages/cli/api/theme-edit/_how-question.mjs b/packages/cli/api/theme-edit/_how-question.mjs index f9a5c445a4a93..01bda3368c7f9 100644 --- a/packages/cli/api/theme-edit/_how-question.mjs +++ b/packages/cli/api/theme-edit/_how-question.mjs @@ -51,6 +51,7 @@ import {isColorToken} from './_compiler.mjs'; import { radioCircle, DIAL_RADII, + borderParts, cornerParts, focusStateOf, paddedParts, @@ -548,6 +549,35 @@ function colorsIn(c) { .map(([, v]) => v); } +/** + * The colors a tint word modifies in a clause: the color right after + * "tinted", "tint" or "washed" ("cards tinted blue"), or right before + * "tint" ("a green tint"), as RGB. + * @param {string} c a clause, lower-case + * @returns {number[][]} + */ +function tintedColors(c) { + const found = colorsFound(c); + /** @type {number[][]} */ + const out = []; + for (const m of c.matchAll(/\b(?:tint(?:ed|s)?|wash(?:ed)?)\b/g)) { + const at = m.index ?? 0; + const end = at + m[0].length; + const after = found.find( + ([i]) => i >= end && !/[,;.]|\bwith\b|\band\b/.test(c.slice(end, i)), + ); + // (The color word, with a shade word before it, then the tint word.) + const before = [...found] + .reverse() + .find(([i]) => i < at && /^\S+(?:\s+\S+)?\s+$/.test(c.slice(i, at))); + const pick = + /^tints?$/.test(m[0]) && before && !after ? before : (after ?? before); + const rgb = pick ? parseColor(pick[1]) : null; + if (rgb) out.push(rgb); + } + return out; +} + /** * A clause that forbids a change ("don't make buttons rounder", "inputs * shouldn't be round"): it changes nothing and says what stays. @@ -2505,6 +2535,7 @@ const STATE_WORDS = /** @type {Array<[RegExp, string]>} */ ([ * @property {{prop: string, value: string, bad?: string} | null} named - a CSS property the clause names, with its value as typed * @property {string} [colorRef] - a part whose color the clause names as a value ("the sidebar the page color"): read, never changed * @property {boolean} [unknownSubject] - an elided clause whose subject is no part ("and the gizmo red") + * @property {string} [compound] - a compound subject a part word begins, which names no part ("radio station") * @property {[number, number]} [colorRefSpan] - where the clause names its reference, with its own word ("the muted card") * @property {{holder: string, part: string}} [placeStrict] - an element named in a place it cannot be kept to: answered only when the answer holds there (a token on the place) * @property {{owner: string, child: string}} [possMiss] - a possessive owner's element it does not have ("the date picker's days") @@ -2997,13 +3028,42 @@ function namedLists(q, partWords, isVariant) { ); } +/** A mark the clause split reads as no word, taken out of each clause. */ +const JOINED = '\u2060'; + +/** + * A question whose fill word is followed by its color before a "with": that + * "with" starts an ask of its own ("cards tinted blue with a navy header": + * the header's navy). The clause split keeps a "with" after a fill word in the + * fill's ask ("rows tinted with the accent"); a mark after the color lets this + * one split. + * @param {string} q lower-case + */ +function markFillColorWith(q) { + return q.replace( + /\b((?:tint(?:ed|s)?|paint(?:ed|s)?|wash(?:ed|es)?)(?:\s+[a-z-]+){0,3})(\s+with\b)/gi, + (m, head, rest) => + colorsIn(head.replace(/^\S+/, '').toLowerCase()).length + ? `${head}${JOINED}${rest}` + : m, + ); +} + /** * Read a question into clauses. * @param {string} q lower-case, translated, corrected * @param {Array<[RegExp, PartRef]>} partWords + * @param {{known: (w: string) => boolean, ask: (w: string) => boolean} | null} [words] + * `known`: whether the editor knows a word as anything (a property, + * state, part, value or joining word); `ask`: whether a word asks for a + * change or joins one (an aspect, a color, an amount, a direction, a + * joining word). A part word right before a word it does not know, with + * no asking word after it in the clause, is one half of a compound + * subject * @returns {Clause[]} */ -function clausesOf(q, partWords) { +function clausesOf(q, partWords, words = null) { + q = markFillColorWith(q); // "except primary and ghost buttons", "except hover or disabled": one // except list, never an except and a new clause (unless an ask follows: // "… except cards and make buttons bigger"). @@ -3072,7 +3132,7 @@ function clausesOf(q, partWords) { joint += piece; continue; } - const text = piece.trim(); + const text = piece.replaceAll(JOINED, '').trim(); if (!text) continue; pieces.push({text, joint}); joint = ''; @@ -3081,6 +3141,8 @@ function clausesOf(q, partWords) { return pieces.map(({text, joint}) => { /** @type {Clause['parts']} */ const parts = []; + /** A compound subject a part word begins ("radio station"). @type {string | undefined} */ + let compound; // A property name is not a part: "backdrop-filter" names no backdrop. let rest = ` ${text} ` // "3 steps rounder": a count, never the stepper part. @@ -3122,6 +3184,19 @@ function clausesOf(q, partWords) { break; } if (!m) continue; + // ("the calendar range band": a part word that begins a longer part + // name is that longer part's, read when its own words come.) + const at = /** @type {number} */ (m.index); + const len = m[0].length; + if ( + partWords.some(([re2]) => { + const x = new RegExp(re2.source, re2.flags.replace('g', '')).exec( + rest.slice(at), + ); + return x != null && x.index === 0 && x[0].length > len; + }) + ) + continue; // ("a medical records table view", "the card page": a screen named // by what it shows, never that part.) if ( @@ -3132,6 +3207,38 @@ function clausesOf(q, partWords) { rest = rest.replace(re, ' '); continue; } + // ("a radio station", "a button factory", "a card game": a part word + // right before a noun the editor knows as nothing, no property, + // state, part, value or joining word, is one half of a compound + // subject, never that part. The clause keeps the compound, which the + // unknown-subject guard names. A word the clause asks for something + // after, before its next stop, is the ask's verb or a word between the part and what + // changes, "links turn red", "the card zorp border", "secondary text + // fails contrast on white", never a compound.) + // (Only as the subject of more: words after it before the stop, or + // an ask after the stop, "radio station site: heavy headings"; a + // part with one unknown word, "buttons chunky", keeps the part.) + const tail = rest.slice((m.index ?? 0) + m[0].length); + const after = /^ ([a-z]+)\b(?!['’(-])/.exec(tail); + const [own = '', ...later] = tail + .slice(after?.[0].length ?? 0) + .split(/[:;,.!?]/); + if ( + after && + after[1].length >= 3 && + words && + !words.known(after[1]) && + !own.split(/\s+/).some(w => w && words.ask(w)) && + (own.trim() !== '' || + later + .join(' ') + .split(/\s+/) + .some(w => w && words.ask(w))) + ) { + compound ??= `${m[0].trim()} ${after[1]}`; + rest = `${rest.slice(0, m.index)} ${rest.slice((m.index ?? 0) + m[0].length + after[0].length)}`; + continue; + } const p = {...part}; if (p.on === 'heading' && /^h[1-6]$/.test(m[0])) p.level = m[1]; // "the error banner": one status of the banner. @@ -3621,6 +3728,7 @@ function clausesOf(q, partWords) { text, joint, parts, + ...(compound ? {compound} : {}), ...(colorRef ? {colorRef} : {}), ...(refSpan ? {colorRefSpan: refSpan} : {}), ...(colorRefWhen ? {colorRefWhen} : {}), @@ -4369,14 +4477,6 @@ export function draftAnswer(ctx, env, question) { // ("divided by 1px lines", "separated by thin lines": lines between, // never an amount.) .replace(/\b(?:divided|separated)\s+by\s+/gi, 'with ') - // ("be a #e8def8 pill": a fill of that color, pill-shaped.) - .replace( - /\b(?:(?:should|must|to)\s+)?(?:be\s+)?an?\s+(#[0-9a-f]{3,8}|[a-z]+)\s+(pill|capsule)\b/gi, - (m, color) => - colorsIn(String(color).toLowerCase()).length - ? `with a ${color} background and pill corners` - : m, - ) // ("big touch targets": the controls a finger presses.) .replace( /\b(?:big|bigger|large|larger)\s+touch\s+targets?\b/gi, @@ -6460,7 +6560,7 @@ export function draftAnswer(ctx, env, question) { .join(' and '), ); } - const clauses0 = clausesOf(q, lex.parts); + const clauses0 = clausesOf(q, lex.parts, {known: knownWord, ask: askWord}); // "cream background, terracotta accent, serif headings": a list whose // items each ask their own thing is each of them, never the first one's // part taking the rest. @@ -6504,7 +6604,9 @@ export function draftAnswer(ctx, env, question) { ) ) return [c]; - const each = pieces.map(x => clausesOf(x, lex.parts)); + const each = pieces.map(x => + clausesOf(x, lex.parts, {known: knownWord, ask: askWord}), + ); const asks = each.map( cs => cs.length === 1 && @@ -6639,6 +6741,16 @@ export function draftAnswer(ctx, env, question) { // show a thick outline", "only in dark mode and only on cards, darker // background", "buttons only, a bit rounder"). if (c.state) return 'inherit'; + // ("…, never use pure black for text": a rule of its own, said with + // its own verb, about no part: the theme's; "never make them bold" + // points back.) + if ( + /^(?:never|don'?t|do not|avoid)\s+(?:use|using|make|give|have|go)\b/.test( + c.text, + ) && + !/\b(?:it|its|them|they|their|those|these)\b/.test(c.text) + ) + return 'theme'; if ( clauses[clauses.indexOf(c) - 1] === before && !before.colors.length && @@ -6760,14 +6872,20 @@ export function draftAnswer(ctx, env, question) { `${c.text.slice(0, m.index)} ${c.text.slice(m.index + m[0].length)}` .replace(/\s+/g, ' ') .trim(); - const restClauses = clausesOf(rest, lex.parts); + const restClauses = clausesOf(rest, lex.parts, { + known: knownWord, + ask: askWord, + }); if ( !restClauses.some( x => x.aspects.length || x.colors.length || x.parts.length, ) ) continue; - const piece = clausesOf(m[0], lex.parts); + const piece = clausesOf(m[0], lex.parts, { + known: knownWord, + ask: askWord, + }); clauses.splice(i, 1, ...piece, ...restClauses); break; } @@ -7251,7 +7369,10 @@ export function draftAnswer(ctx, env, question) { ) .replace(/\s+/g, ' ') .trim(); - const again = clausesOf(text, lex.parts); + const again = clausesOf(text, lex.parts, { + known: knownWord, + ask: askWord, + }); if (again.length === 1) { if (!again[0].parts.length) again[0].parts = c.parts; clauses[i] = again[0]; @@ -7747,7 +7868,7 @@ export function draftAnswer(ctx, env, question) { if (!hasAsk) continue; // (A clause whose subject is a word how knows as no part, "and the // gizmo red", takes no part from the one before: it is said.) - if (!c.parts.length && unknownSlot(c.text, true)) { + if (!c.parts.length && (c.compound || unknownSlot(c.text, true))) { c.unknownSubject = true; continue; } @@ -9445,15 +9566,59 @@ export function draftAnswer(ctx, env, question) { !/\bunderline|indicator\b/.test(c.text) ) p.on = 'tab'; + // "menus with 32px rows", "lists with tight rows": rows said of a part + // that holds no table rows are that part's own rows, the parts inside it + // that ride an Item (the element Core draws every list and menu row with), + // never every table's rows. A part with no such rows keeps the ask. + { + const itemProps = ctx.project.target.get('item')?.props ?? []; + /** @param {string} k */ + const ridesItem = k => + k !== 'item' && + itemProps.length > 0 && + Object.values(C.MAP[k]?.at ?? {}).some(byCond => + Object.keys(byCond ?? {}).some(cond => + itemProps.every(pr => + cond + .split(/\s/)[0] + .split(',') + .some(x => x.startsWith(`${pr}=`)), + ), + ), + ); + for (const c of clauses) { + if (!c.parts.some(p => p.on === 'table-row')) continue; + if (/\btables?\b/.test(c.text)) continue; + const holders = c.parts.filter( + p => p.on !== 'table-row' && p.on !== 'table-cell', + ); + if (!holders.length) continue; + const members = holders.flatMap(h => FAMILIES[h.on] ?? [h.on]); + if (members.some(m => (C.MAP[m]?.contains ?? []).includes('table-row'))) + continue; + const rows = [ + ...new Set( + members.flatMap(m => + [...(C.MAP[m]?.contains ?? [])].filter(ridesItem), + ), + ), + ]; + if (rows.length) c.parts = rows.map(on => ({on})); + } + } // A border or corners on a part that draws no edge of its own, whose // edges are parts of its own inside it (a date-time input's date and time - // boxes): those parts. + // boxes): those parts (for a border, only pieces that draw one). for (const c of clauses) if (c.aspects.some(a => a === 'border' || a === 'corners')) c.parts = c.parts.flatMap(p => { if (FAMILIES[p.on]) return [p]; const own = C.MAP[p.on]?.own ?? {}; - const inner = cornerParts(ctx, p.on).filter(t => t !== p.on); + const inner = ( + c.aspects.includes('corners') + ? cornerParts(ctx, p.on) + : borderParts(ctx, p.on) + ).filter(t => t !== p.on); return inner.length && !Object.keys(own).some(k => /^border/.test(k)) ? inner.map(on => ({...p, on})) : [p]; @@ -11651,9 +11816,13 @@ export function draftAnswer(ctx, env, question) { // knows as no part ("from widgets") is never answered for the whole // theme or dropped; it says so. { + // (A compound subject a part word begins, "the radio station": that + // subject, named, never the part.) const slot = (!c.parts.length || c.unknownSubject) && !c.except && c.text - ? unknownSlot(c.text, Boolean(c.unknownSubject)) + ? c.compound && !c.parts.length + ? {word: c.compound} + : unknownSlot(c.text, Boolean(c.unknownSubject)) : null; if (slot) { push({ @@ -12459,6 +12628,27 @@ export function draftAnswer(ctx, env, question) { ); continue; } + // A radio's circle the theme leaves as it is: the corners change + // leaves it too (the dial never rounds a circle), so it is kept. + if ( + (FAMILIES[p.on] ?? [p.on]).every(m => radioCircle(C, m)) && + !(env.data?.settings ?? []).some( + (/** @type {any} */ x) => + /^(corners|border-radius)$/.test(x.thing) && + (FAMILIES[p.on] ?? [p.on]).includes(x.on), + ) && + priorSteps.every( + (st, i) => + keep[i] != null || + !/^(corners|border-radius|--radius-)/.test(st.thing) || + st.thing === 'corners', + ) + ) { + said.push( + `${name} is a radio's circle, which the corners change leaves as it is`, + ); + continue; + } if ( priorSteps.some( (st, i) => @@ -19594,7 +19784,8 @@ export function draftAnswer(ctx, env, question) { parts: inner.map(x => x.k), from: inner[0].tok, to: down.t, - by: 2 * (now - Number(down.v)), + // (Rounded as a length is said: no float tail.) + by: Math.round(2 * (now - Number(down.v)) * 100) / 100, } : null; })() @@ -23071,6 +23262,85 @@ export function draftAnswer(ctx, env, question) { }; } + /** + * Whether the editor knows a word as anything: a design word, part, + * aspect, dial, color, role, state, value, mode or joining word. A word it + * does not know, right after a part word, makes a compound subject + * ("radio station"); in a part slot, a part it cannot name. + * @param {string} w + */ + function knownWord(w) { + const word = singular(w); + return Boolean( + lex.vocab.includes(w) || + lex.vocab.includes(word) || + corrected(w, lex.vocab) !== w || + lex.parts.some(([re]) => re.test(` ${w} `)) || + aspectsOf(w).length || + aspectsOf(word).length || + stateWord(w) != null || + KEEP.has(w) || + Object.hasOwn(DIALS, w) || + Object.hasOwn(HUES, w) || + // (A role color, "the brand color", and what the browser draws, + // which how answers by name, "the scrollbar".) + ROLE_WORDS.test(w) || + /^(?:scrollbars?|scroll|carets?|cursors?|selections?)$/.test(w) || + parseColor(w) || + /^(?:dark|light|darker|lighter|bigger|smaller|more|less|least|most|much|very|bit|lot|whole|entire|whole|entire|overall|main|page|app|site|everything|everywhere|default|global|general|base|theme|themes|screen|screens|current|other|same|top|bottom|left|right|inner|outer|side|sides|plus|thus|always|sometimes|its|this|that|these|those|them|they|was|has|does|yes|minus|options|things|thing|ones|one|edges|tokens|settings|variables|parts|part|modes|mode|pixels|steps|step|levels|level|times|default|normal|regular|primary|secondary|small|large|medium|big|tiny|huge|little|subtle|strong|soft|hard|new|old|nice|good|bad|ugly|pretty|heavy|thin|thick|bold|round|rounded|square|flat|clean|modern|fancy|simple|minimal|same|their|your|mine|ours|any|some|every|each|first|last|second|third|letter|letters|word|words|line|lines|link|links|title|titles|label|labels|heading|headings|body|copy|content|everything)$/.test( + w, + ) || + // (A property's own name, "cards transform", and a word that is no + // noun by its ending: a way or amount, "buttons fully", "ring + // easier", "cards used", "corners rounded".) + cssProperties().has(w) || + cssProperties().has(word) || + // (What a part has, "the h3 size", "the header bar", and a word + // some part's own name or look holds, "the checkbox check mark", + // "the card surface".) + /^(?:padding|spacing|shadows?|borders?|corners?|radius|background|fill|text|font|colou?r|outline|gap|size|height|width|titles?|headings?|headers?|footers?|bar|area|section|region|panel|box|element|component|container|part|piece|block|wrapper|surface|min|max|half|twice|double|triple|quarter|third|up|down|out|off|back|away)$/.test( + w, + ) || + [...TARGET.keys()].some(k => k.split('-').includes(word)) || + Object.values(C.MAP).some(m => + Object.values(m.attrs ?? {}).some( + vals => Array.isArray(vals) && vals.includes(w), + ), + ) || + /(?:ly|er|est|ed|ing)$/.test(w) || + // (A pronoun or a chat word: "button it", "cards thx", "plz".) + /^(?:it|its|me|my|you|your|ur|we|us|our|they|them|their|this|that|these|those|thx|thanks|thank|plz|pls|please|lol|okay|ok|yeah|yes|hey|hi)$/.test( + w, + ) || + // (A joining or helping word: "buttons with", "cards should".) + /^(?:and|or|nor|but|so|yet|with|without|in|on|of|for|to|at|by|from|into|onto|over|under|below|above|between|inside|outside|within|around|near|after|before|across|like|than|then|as|if|when|while|the|a|an|is|are|was|were|be|been|being|should|must|can|could|would|will|shall|may|might|do|did|look|looks|feel|feels|have|had|get|gets|need|needs|use|uses|stand|stands|appear|appears|seem|seems|that|which|who|only|also|too|all|not|no|just|please|pls|now|still|again|instead|both|either|neither|here|there)$/.test( + w, + ), + ); + } + + /** + * Whether a word asks for a change (an aspect, a color, an amount, a + * direction, a state): one after a part word's unknown neighbor makes the + * neighbor the ask's verb or a word between, never a compound ("links + * turn red", "the card zorp border"). + * @param {string} w + */ + function askWord(w) { + return Boolean( + aspectsOf(w).length || + parseColor(w) || + /^[#\d]/.test(w) || + Object.hasOwn(HUES, w) || + Object.hasOwn(DIALS, w) || + stateWord(w) != null || + /(?:er|est)$/.test(w) || + /^(?:up|down|more|less|half|twice|double|triple|contrast|visible|invisible|hidden|none|no)$/.test( + w, + ), + ); + } + /** * A part word how cannot name: the clause starts with a word a component * doc lists as a keyword, or a near catalog name, and asks for a shape @@ -23209,20 +23479,8 @@ export function draftAnswer(ctx, env, question) { const without = aspectsOf(text.replace(new RegExp(`\\b${w}\\b`), ' ')); const withIt = aspectsOf(text); if ( - lex.vocab.includes(w) || - lex.vocab.includes(word) || - corrected(w, lex.vocab) !== w || - lex.parts.some(([re]) => re.test(` ${w} `)) || - aspectsOf(w).length || - aspectsOf(word).length || + knownWord(w) || withIt.some(x => !without.includes(x)) || - KEEP.has(w) || - Object.hasOwn(DIALS, w) || - Object.hasOwn(HUES, w) || - // (A role color, "the brand color", and what the browser draws, - // which how answers by name, "the scrollbar".) - ROLE_WORDS.test(w) || - /^(?:scrollbars?|scroll|carets?|cursors?|selections?)$/.test(w) || (between && (/^(?:own|outer|inner|whole|main|full|bottom|top|left|right|side|each|every|default|plain|base)$/.test( w, @@ -23231,11 +23489,7 @@ export function draftAnswer(ctx, env, question) { Object.values(m.attrs ?? {}).some( vals => Array.isArray(vals) && vals.includes(w), ), - ))) || - parseColor(w) || - /^(?:dark|light|darker|lighter|bigger|smaller|more|less|least|most|much|very|bit|lot|whole|entire|whole|entire|overall|main|page|app|site|everything|everywhere|default|global|general|base|theme|themes|screen|screens|current|other|same|top|bottom|left|right|inner|outer|side|sides|plus|thus|always|sometimes|its|this|that|these|those|them|they|was|has|does|yes|minus|options|things|thing|ones|one|edges|tokens|settings|variables|parts|part|modes|mode|pixels|steps|step|levels|level|times|default|normal|regular|primary|secondary|small|large|medium|big|tiny|huge|little|subtle|strong|soft|hard|new|old|nice|good|bad|ugly|pretty|heavy|thin|thick|bold|round|rounded|square|flat|clean|modern|fancy|simple|minimal|same|their|your|mine|ours|any|some|every|each|first|last|second|third|letter|letters|word|words|line|lines|link|links|title|titles|label|labels|heading|headings|body|copy|content|everything)$/.test( - w, - ) + ))) ) continue; return {word, parts: /** @type {string[]} */ ([])}; @@ -25224,45 +25478,181 @@ export function draftAnswer(ctx, env, question) { continue; const ink = parseColor(String(st.value ?? '')); if (!ink || alphaOf(String(st.value)) < 1) continue; - // (A resting fill in the same answer is the look the text sits on; - // a fill in another state, "filled blue on hover", is not.) - if ( - o.some( + // (A resting fill in the same answer is the look the text sits on, + // for the variants it reaches; a fill in another state, "filled + // blue on hover", is not.) + /** The fill this answer gives a variant at rest, if any. @param {string} v */ + const givenFill = v => + o.find( x => x !== st && x.on === st.on && !x.state && - /^background/.test(x.thing), - ) - ) - continue; + /^background/.test(x.thing) && + (!x.when || x.when === `variant:${v}`), + ) ?? null; const variants = C.variantValues(one(st.on)).variant ?? []; - if (variants.length < 2 || !variants.includes('primary')) continue; + if (variants.length < 2) continue; + // ("badges #26272b with #d0d6e0 text": the text asked with a fill + // goes where that fill goes, its pair, never to the variants the + // fill keeps apart.) + // (Each pair keeps its fill's mode: "a navy background in dark mode + // and white text" is white text in dark mode only.) + const pairedTo = o.filter( + x => + x !== st && + x.on === st.on && + !x.state && + /^background/.test(x.thing) && + /^variant:/.test(String(x.when ?? '')), + ); + if (pairedTo.length) { + /** @type {Map} */ + const pairs = new Map(); + for (const x of pairedTo) { + const mode = st.mode ?? x.mode; + pairs.set(`${x.when}\0${mode ?? ''}`, { + ...st, + when: String(x.when), + ...(mode ? {mode} : {}), + }); + } + o.splice(i, 1, ...pairs.values()); + continue; + } const fills = (C.partReads(one(st.on), 'background') ?? []).filter( r => /^--color-/.test(r.token) && !/overlay|tint/.test(r.token), ); - const mode = /** @type {'light' | 'dark'} */ (st.mode ?? 'light'); - const lost = variants.filter(v => { + // (Each mode the theme draws: a text color that reads on a + // variant's fill in one mode only is that mode's; text needs 4.5:1.) + const modes = /** @type {Array<'light' | 'dark'>} */ ( + st.mode + ? [st.mode] + : modal + ? ['light', 'dark'] + : [env.data.mode === 'dark-only' ? 'dark' : 'light'] + ); + /** The modes a variant's text reads in. @param {string} v */ + const readsIn = v => { const r = fills.find(x => x.when.some(w => w.trim() === `variant=${v}`), ); - const f = parseColor( - String(current(r?.token ?? '--color-background-body', mode) ?? ''), - ); - return !!f && ratio(ink, f) < 3; - }); - if (!lost.length || lost.length === variants.length) continue; + const asked = givenFill(v); + return modes.filter(m => { + // (A fill given for one mode is that mode's look; in the other + // mode the text sits on the variant's own fill there.) + const given = + asked && (!asked.mode || asked.mode === m) ? asked : null; + // (A see-through fill is read over the page it sits on.) + const raw = given + ? String(given.value) + : String(current(r?.token ?? '--color-background-body', m) ?? ''); + const f0 = parseColor(raw); + const page = parseColor( + String(current('--color-background-body', m) ?? ''), + ); + const f = + f0 && page && alphaOf(raw) < 1 + ? compositeOver(f0, alphaOf(raw), page) + : f0; + return !f || ratio(ink, f) >= 4.5; + }); + }; + const ok = new Map(variants.map(v => [v, readsIn(v)])); + const lost = variants.filter(v => !ok.get(v)?.length); + const partial = variants.filter( + v => + (ok.get(v)?.length ?? 0) > 0 && + (ok.get(v)?.length ?? 0) < modes.length, + ); + if ( + (!lost.length && !partial.length) || + lost.length === variants.length + ) + continue; o.splice( i, 1, ...variants .filter(v => !lost.includes(v)) - .map(v => ({...st, when: `variant:${v}`})), + .flatMap(v => + partial.includes(v) + ? (ok.get(v) ?? []).map(m => ({ + ...st, + when: `variant:${v}`, + mode: m, + })) + : [{...st, when: `variant:${v}`}], + ), ); - if (!/keep their own text|keeps its own text/.test(d.text)) - d.text += ` (${lost.join(', ')} ${lost.length > 1 ? 'keep their own text' : 'keeps its own text'}: ${st.value} would barely show on ${lost.length > 1 ? 'their' : 'its'} fill; give ${lost.length > 1 ? 'them' : 'it'} a fill too to change ${lost.length > 1 ? 'them' : 'it'})`; + if ( + lost.length && + !/keep their own text|keeps its own text/.test(d.text) + ) + d.text += ` (${lost.join(', ')} ${lost.length > 1 ? 'keep their own text' : 'keeps its own text'}: ${st.value} would not read on ${lost.length > 1 ? 'their' : 'its'} fill; give ${lost.length > 1 ? 'them' : 'it'} a fill too to change ${lost.length > 1 ? 'them' : 'it'})`; + if (partial.length && !/only in the mode it reads in/.test(d.text)) + d.text += ` (${partial.join(', ')}: only in the mode it reads in)`; } } + // ("selected nav items tinted forest green", "a green tint on hover"): + // a tint is the color at a low strength over what is beneath, never the + // solid color, as the accent's tint is. + // Only the color the tint word modifies is tinted, on the parts named + // before it ("cards tinted blue with a navy header": the cards' blue, + // never the header), on every line of the answer that writes it (the + // card variants' own lines too). + /** @type {Array<{parts: Set, colors: number[][]}>} */ + const tints = []; + for (const d of result) { + const c = draftClause.get(d); + if (!c || !/\b(?:tint(?:ed|s)?|wash(?:ed)?)\b/.test(c.text)) continue; + const text = c.text.toLowerCase(); + const colors = tintedColors(text); + const at = text.search(/\b(?:tint(?:ed|s)?|wash(?:ed)?)\b/); + // (A part is named before the tint word when its own word is: the + // last word of its name, "card" for card, "header" for + // app-shell-header.) + const parts = new Set( + c.parts + .map(p => p.on) + .filter(on => { + const word = on.split('-').pop() ?? on; + return new RegExp(`\\b${word}`).test(text.slice(0, at)); + }), + ); + // (A clause that names no part before the tint word, "secondary + // button hover, in dark mode only: a slightly blue tint", takes the + // part its own lines are on.) + if (parts.size === 0) + for (const p of c.parts.length + ? c.parts.map(x => x.on) + : d.options.flat().map(st => st.on)) + if (p) parts.add(p); + if (colors.length && parts.size) tints.push({parts, colors}); + } + for (const d of tints.length ? result : []) + for (const o of d.options) + for (const [k, st] of o.entries()) { + const v = parseColor(String(st.value ?? '')); + if ( + !st.on || + !/^background(?:-color)?$/.test(st.thing) || + !v || + alphaOf(String(st.value)) < 1 || + !tints.some( + t => + t.parts.has(String(st.on)) && + t.colors.some(c => c.every((n, x) => Math.abs(n - v[x]) < 1)), + ) + ) + continue; + o[k] = { + ...st, + value: `color-mix(in srgb, ${st.value} 15%, transparent)`, + }; + if (!/a tint: /.test(d.text)) + d.text += ` (a tint: ${st.value} at 15% over what is beneath)`; + } // A fill given to a part that holds others ("a navy header"): a part // inside it whose own resting fill would sit at nearly the same color // (a primary button navy on navy) is named, so the answer never hides @@ -25307,6 +25697,183 @@ export function draftAnswer(ctx, env, question) { if (lost.length && !/nearly the same color/.test(d.text)) d.text += ` (note: ${[...new Set(lost)].slice(0, 4).join(', ')} inside ${st.on} ${lost.length > 1 ? 'have' : 'has'} nearly the same color as ${st.value}${st.mode ? ` in ${st.mode} mode` : ''}, so ${lost.length > 1 ? 'they' : 'it'} would barely show; give ${lost.length > 1 ? 'them' : 'it'} a fill of ${lost.length > 1 ? 'their' : 'its'} own too)`; } + // A text color written where the same answer gives the part a fill, in + // a variant, a state or at rest ("buttons tinted blue with white text", + // "cards tinted blue with white text", "selected nav items tinted green + // with white text") is measured on that fill as it + // draws, a see-through tint over the page, in each mode it applies to: + // text needs 4.5:1. Both words were asked, so a tint the text does not + // read on is deepened along its own hue, in steps of 5%, until the text + // reads in every mode, and said. Only when no strength of that hue reads + // is the text kept to the modes it reads in, or not written where it + // reads in none, said with the ink that reads there. + /** A tint as the tint pass writes it: its color, then its strength. */ + const TINT_MIX = + /^color-mix\(in srgb,\s*(.+?)\s+(\d+(?:\.\d+)?)%,\s*transparent\)$/; + /** A fill as it draws over the page in a mode, or null. @param {string} value @param {'light' | 'dark'} mode */ + const drawnFill = (value, mode) => { + const mix = TINT_MIX.exec(value.trim()); + const raw = mix ? mix[1] : value; + const c = parseColor(raw); + if (!c) return null; + const a = mix ? Number(mix[2]) / 100 : alphaOf(raw); + if (a >= 1) return c; + const page = parseColor( + String(current('--color-background-body', mode) ?? ''), + ); + return page ? compositeOver(c, a, page) : null; + }; + // Text said for every variant of a part whose fill the answer gives + // only some variants ("cards tinted blue with white text": the coloured + // card variants keep their own fills) goes to those variants alone, each + // measured on its own fill below; the rest keep their text, and it is + // said. + for (const d of result) + for (const o of d.options) + for (let i = o.length - 1; i >= 0; i--) { + const st = o[i]; + if ( + !st.on || + st.when || + (st.thing !== 'color' && !/^--color-text-/.test(st.thing)) + ) + continue; + const fills = o.filter( + x => + x.on === st.on && + (x.state ?? null) === (st.state ?? null) && + /^background(?:-color)?$/.test(x.thing), + ); + const variants = C.variantValues(one(st.on)).variant ?? []; + const given = [ + ...new Set( + fills + .map(x => /^variant:(.+)$/.exec(String(x.when ?? ''))?.[1]) + .filter(Boolean), + ), + ]; + if ( + !given.length || + fills.some(x => !x.when) || + given.length >= variants.length + ) + continue; + o.splice(i, 1, ...given.map(v => ({...st, when: `variant:${v}`}))); + const kept = variants.filter(v => !given.includes(v)); + const said = `${st.value} text goes to the ${given.join(', ')} ${st.on}`; + if (!d.text.includes(said)) + d.text += ` (${said}, the variants this fill reaches; the ${kept.join(', ')} ${st.on} keep their own text)`; + } + for (const d of result) + for (const o of d.options) + for (let i = o.length - 1; i >= 0; i--) { + const st = o[i]; + // (Any text the part draws there: its color, or a text token on it, + // in a variant, a state, or at rest.) + if ( + !st.on || + (st.thing !== 'color' && !/^--color-text-/.test(st.thing)) + ) + continue; + const ink = parseColor(String(st.value ?? '')); + if (!ink || alphaOf(String(st.value)) < 1) continue; + const fills = o.filter( + x => + x !== st && + x.on === st.on && + (x.state ?? null) === (st.state ?? null) && + /^background(?:-color)?$/.test(x.thing) && + (!x.mode || !st.mode || x.mode === st.mode), + ); + // (The variant's own fill first, "transparent on ghost buttons"; + // else a fill for the whole part, which text said for every + // variant, "--color-text-primary on card", sits on too.) + const fill = + fills.find(x => x.when === st.when) ?? + fills.find(x => !x.when || !st.when); + if (!fill) continue; + const modes = /** @type {Array<'light' | 'dark'>} */ ( + st.mode + ? [st.mode] + : fill.mode + ? [fill.mode] + : modal + ? ['light', 'dark'] + : [env.data.mode === 'dark-only' ? 'dark' : 'light'] + ); + /** @type {Array<{mode: 'light' | 'dark', ratio: number, under: number[]}>} */ + const measured = []; + for (const m of modes) { + const under = drawnFill(String(fill.value ?? ''), m); + if (under) measured.push({mode: m, ratio: ratio(ink, under), under}); + } + const fails = measured.filter(x => x.ratio < 4.5); + if (!fails.length) continue; + const mixed = TINT_MIX.exec(String(fill.value ?? '').trim()); + if (mixed) { + /** The weakest ratio across the modes at a strength. @param {number} pct */ + const weakest = pct => + Math.min( + ...modes.map(m => { + const under = drawnFill( + pct >= 100 + ? mixed[1] + : `color-mix(in srgb, ${mixed[1]} ${pct}%, transparent)`, + m, + ); + return under ? ratio(ink, under) : 0; + }), + ); + let pct = Math.ceil(Number(mixed[2]) / 5) * 5; + while (pct < 100 && weakest(pct) < 4.5) pct += 5; + if (weakest(pct) >= 4.5) { + const value = + pct >= 100 + ? mixed[1] + : `color-mix(in srgb, ${mixed[1]} ${pct}%, transparent)`; + for (const [k, x] of o.entries()) + if (x === fill || (x.value === fill.value && x.on === fill.on)) + o[k] = {...x, value}; + const said = `deepened to ${pct >= 100 ? 'solid' : `${pct}%`} so ${st.value} text`; + // (The tint said at its first strength is said at this one.) + d.text = d.text.replace( + ` (a tint: ${mixed[1]} at ${mixed[2]}% over what is beneath)`, + '', + ); + if (!d.text.includes(said)) + d.text += ` (the ${mixed[1]} tint is ${said} reads at ${weakest(pct).toFixed(1)}:1${modes.length > 1 ? ' in light and dark mode' : ''})`; + continue; + } + } + const reads = modes.filter(m => !fails.some(x => x.mode === m)); + o.splice( + i, + 1, + ...reads.map(m => + st.mode || fill.mode || reads.length === modes.length + ? st + : {...st, mode: m}, + ), + ); + const where = [ + String(st.when ?? '').replace(/^[a-z]+:/, ''), + st.state ?? '', + st.on, + ] + .filter(Boolean) + .join(' '); + for (const x of fails) { + const dark = [0x11, 0x18, 0x27]; + const light = [0xff, 0xff, 0xff]; + const better = + ratio(dark, x.under) >= ratio(light, x.under) + ? '#111827' + : '#ffffff'; + const said = `${st.value} text on the ${where}`; + if (!d.text.includes(said)) + d.text += ` (${said} would not read on ${fill.value}${modes.length > 1 || st.mode || fill.mode ? ` in ${x.mode} mode` : ''}: ${x.ratio.toFixed(2)}:1, under the 4.5:1 text needs, so it is ${reads.length ? `kept to ${reads.join(' and ')} mode` : 'not written'}; ${better} reads there at ${ratio(better === '#ffffff' ? light : dark, x.under).toFixed(1)}:1)`; + } + } for (const n of placeNotes) if (!keptInPlace.has(n.c)) result.push({text: n.text, options: []}); // (The other reading of states said together, said last.) diff --git a/packages/cli/api/theme-edit/_parts.mjs b/packages/cli/api/theme-edit/_parts.mjs index 48a9faa17aa29..9e127efacc64c 100644 --- a/packages/cli/api/theme-edit/_parts.mjs +++ b/packages/cli/api/theme-edit/_parts.mjs @@ -759,6 +759,36 @@ function deepFreeze(value) { return value; } +/** + * The runtime states the census finds a part's own element marked with + * that its doc does not list (a list item rides an Item, whose + * `data-selected` marks it selected): each `name=name` condition the part + * reads under, less its visual props. Added to the part's states, so set + * names them and the build writes them as the data attribute Core marks. + * @param {{target: Map}} project + * @param {PartData} parts + */ +export function addCensusStates(project, parts) { + for (const [part, rec] of Object.entries(parts.map)) { + const t = project.target.get(part); + if (!t) continue; + const props = new Set(t.props); + /** @type {Set} */ + const found = new Set(); + for (const byCond of Object.values(rec.at ?? {})) + for (const cond of Object.keys(byCond ?? {})) + for (const pair of cond.split(/\s/)[0].split(',')) + if (/^([a-z][\w-]*)=\1$/.test(pair)) { + const name = pair.slice(0, pair.indexOf('=')); + // (A state of a part drawn on this part's element is that + // part's: only the part's own marks count, see walkMarkup.) + if (!props.has(name) && Object.hasOwn(rec.attrs ?? {}, name)) + found.add(name); + } + for (const name of found) if (!t.states.includes(name)) t.states.push(name); + } +} + /** * The part data for the installed Core, from the cache or built now. * @param {import('./_project.mjs').ThemeProject} project @@ -984,6 +1014,19 @@ async function buildPartData(project) { const layers = walkMarkup(markup.slice(at), decls, tokens, project.target); const added = Object.keys(layers.map).filter(k => !(k in result.map)); for (const k of added) result.map[k] = layers.map[k]; + // A part the page draws too keeps its page record, and takes from the + // opened overlays only the open state the page never shows (a menu's + // submenu row, open while its flyout is): its conditions under the open + // attribute. + for (const [k, rec] of Object.entries(layers.map)) { + if (added.includes(k)) continue; + const page = result.map[k]; + if (!page) continue; + for (const [prop, byCond] of Object.entries(rec.at ?? {})) + for (const [cond, v] of Object.entries(byCond ?? {})) + if (/(?:^|,)aria-expanded=true\b/.test(cond.split(' ')[0])) + ((page.at ??= {})[prop] ??= {})[cond] ??= v; + } const seen = new Set(result.pairs.map(x => JSON.stringify(x))); for (const x of layers.pairs) if ( @@ -1299,7 +1342,7 @@ function resolvePrivate(v, env, tokens, depth = 0) { * @returns {{map: Record, pairs: TextPair[]}} */ export function walkMarkup(html, decls, tokens, targets = new Map()) { - /** @type {Record>, values: Set}>, at: Record>, inside: Record>, attrs: Record>, contains: Set, repeats: Set, holdsVariants?: Record>, tags: Set, innerCorners: Set, media: boolean, mediaSides?: Set, line?: Set, lineAdded?: Array<[string, string, Set, boolean?]>, held?: Record>, underInput?: string}>} */ + /** @type {Record>, values: Set}>, at: Record>, inside: Record>, attrs: Record>, contains: Set, repeats: Set, holdsVariants?: Record>, tags: Set, innerCorners: Set, media: boolean, mediaSides?: Set, line?: Set, lineAdded?: Array<[string, string, Set, boolean?]>, held?: Record>, alone?: boolean, borrowed?: Record>, underInput?: string}>} */ const map = {}; /** @type {Array<{env: Record, target: string | null, all?: string[], fg: PaintSide | null, bg: PaintSide | null, cond: string, kids?: string[], input?: boolean, owns?: boolean, seenParts?: Record}>} */ const stack = [{env: {}, target: null, fg: null, bg: null, cond: ''}]; @@ -1379,11 +1422,19 @@ export function walkMarkup(html, decls, tokens, targets = new Map()) { // that marks the place with a runtime state of its own (a selected tab) // is conditioned by that state already. const ownState = Object.keys(dataAttrs).some(k => states.has(k)); - const context = ownState - ? [] - : [...attrs.matchAll(/\b(aria-(?:current|pressed))="([^"]*)"/g)] - .filter(x => x[2] !== 'false') - .map(x => `${x[1]}=${x[2]}`); + // (Open is the part's own state, never a place another component puts + // it: a submenu's row is highlighted while its flyout is open, and open + // too.) + const context = [ + ...attrs.matchAll( + ownState + ? /\b(aria-expanded)="([^"]*)"/g + : /\b(aria-(?:current|pressed|expanded))="([^"]*)"/g, + ), + ] + .filter(x => x[2] !== 'false') + .map(x => `${x[1]}=${x[2]}`); + const open = context.includes('aria-expanded=true'); const env = {...parent.env}; const own = cls.flatMap(c => decls.get(c) ?? []); for (const d of own) @@ -1441,9 +1492,20 @@ export function walkMarkup(html, decls, tokens, targets = new Map()) { innerCorners: new Set(), media: false, }); - if (ownsTarget) + // A data attribute another target on the element declares is this + // part's only when the part rides on that one: a part always drawn + // together with another (a list item on its Item) takes that one's + // states; a part also drawn on its own (a Button) never takes the + // states of a part drawn on it (a pagination cell's selected). Which + // is which is known once the whole census is read. + if (ownsTarget) { + const mine = targets.get(t); + if (named.length === 1) T.alone = true; for (const [k, v] of Object.entries(dataAttrs)) - (T.attrs[k] ??= new Set()).add(v); + if (!mine || mine.props.includes(k) || mine.states.includes(k)) + (T.attrs[k] ??= new Set()).add(v); + else ((T.borrowed ??= {})[k] ??= new Set()).add(v); + } // Core's media surface inside the part (a toast's inverted surface): // it sets the text tokens of what it holds from the on-dark color // where it is dark and the on-light color where it is light (Core's @@ -1463,6 +1525,10 @@ export function walkMarkup(html, decls, tokens, targets = new Map()) { : parent.cond; for (const d of own) { if (d.prop.startsWith('--')) continue; + // (An element drawn open is never disabled: what opens it is + // enabled. Its disabled rules are recorded where Core draws it + // closed, never as open and disabled at once.) + if (open && d.cond && /disabled/.test(d.cond)) continue; // (An inherited background paints nothing of its own: it reads no // token, and what shows is its parent's.) const toks = expand(d.value, env, tokens); @@ -1672,7 +1738,19 @@ export function walkMarkup(html, decls, tokens, targets = new Map()) { Object.entries(v.inside).map(([k, s]) => [k, [...s]]), ), attrs: Object.fromEntries( - Object.entries(v.attrs).map(([k, s]) => [k, [...s]]), + Object.entries( + v.alone + ? v.attrs + : { + ...Object.fromEntries( + Object.entries(v.borrowed ?? {}).map(([k, s]) => [ + k, + new Set([...s, ...(v.attrs[k] ?? [])]), + ]), + ), + ...v.attrs, + }, + ).map(([k, s]) => [k, [...s]]), ), contains: [...v.contains], ...(v.repeats?.size ? {repeats: [...v.repeats]} : {}), diff --git a/packages/cli/api/theme-edit/_preview.mjs b/packages/cli/api/theme-edit/_preview.mjs index 3db71708e97af..7b6639e1c66e0 100644 --- a/packages/cli/api/theme-edit/_preview.mjs +++ b/packages/cli/api/theme-edit/_preview.mjs @@ -191,6 +191,71 @@ export function touchedFamilies(project, data) { return [...out]; } +/** The Astryx control each plain HTML text control is drawn as. */ +const ASTRYX_CONTROLS = Object.freeze({ + input: 'TextInput', + textarea: 'TextArea', +}); + +/** The input types a text input draws. */ +const TEXT_TYPES = new Set([ + '', + 'text', + 'email', + 'search', + 'url', + 'tel', + 'password', +]); + +/** + * A value with each plain HTML text control in a doc's sample (a field's + * ``) drawn as the Astryx control for it, its label hidden, so the + * sheet shows the theme's own control where an app would use one: a bare + * browser control shows nothing of the theme. Every other value is the same + * object. + * @param {import('./_project.mjs').ThemeProject} project + * @param {unknown} v + * @returns {unknown} + */ +function withAstryxControls(project, v) { + if (Array.isArray(v)) { + const out = v.map(x => withAstryxControls(project, x)); + return out.every((x, i) => x === v[i]) ? v : out; + } + if (!v || typeof v !== 'object') return v; + if (isElement(v)) { + const own = /** @type {Record} */ (ASTRYX_CONTROLS)[ + v.__element + ]; + const p = /** @type {Record} */ (v.props ?? {}); + if ( + own && + project.components[own] && + (v.__element !== 'input' || TEXT_TYPES.has(String(p.type ?? ''))) + ) + return { + __element: own, + props: { + label: String(p['aria-label'] ?? p.placeholder ?? 'Text'), + isLabelHidden: true, + ...(p.placeholder != null ? {placeholder: p.placeholder} : {}), + ...(p.id != null ? {id: p.id} : {}), + }, + }; + const props = withAstryxControls(project, v.props); + const children = withAstryxControls(project, v.children); + return props === v.props && children === v.children + ? v + : {...v, props, children}; + } + const entries = Object.entries(v); + const out = entries.map(([k, x]) => [k, withAstryxControls(project, x)]); + return out.every(([, x], i) => x === entries[i][1]) + ? v + : {...v, ...Object.fromEntries(out)}; +} + /** * What the cached component items are built by ({@link codeFingerprint}): * this file and every file it imports, read the first time it is needed. @@ -301,14 +366,9 @@ function componentItems(project, group) { // A deprecated part is not drawn: a theme styles the part that replaces // it. An overlay whose playground opens it over the page draws nothing // closed (a phone's navigation drawer, slid out of the window): where - // the open states draw it open (below), that is its only cell. + // the open states draw it open, that is its only cell, on every page. if (info?.deprecated) continue; - if ( - (!group || group === 'overlays') && - info?.overlay && - OPEN_SCENES.some(s => s.name === name) - ) - continue; + if (info?.overlay && OPEN_SCENES.some(s => s.name === name)) continue; catalogVariants(project, name, 12, {shown: true}).forEach((v, i) => items.push({ group: g, @@ -319,7 +379,13 @@ function componentItems(project, group) { // A doc's sample children may name a part by an older name (a // stack, a heading): each is drawn by the name Core exports. props: /** @type {Record} */ ( - withCoreAliases(project, withSampleContent(project, name, v.props)) + withAstryxControls( + project, + withCoreAliases( + project, + withSampleContent(project, name, v.props), + ), + ) ), }), // An overlay shown open is drawn open: Core places a popover, diff --git a/packages/cli/api/theme-edit/_settings.mjs b/packages/cli/api/theme-edit/_settings.mjs index bb9211bf9cccb..4c2802e6b9257 100644 --- a/packages/cli/api/theme-edit/_settings.mjs +++ b/packages/cli/api/theme-edit/_settings.mjs @@ -4410,7 +4410,9 @@ function drawnAlike(ctx, s, member) { /** * The parts that draw a part's border: the part itself, or, when it draws * none of its own and its edges are the borders of parts inside it (a date - * and time field's date and time boxes), those parts. + * and time field's date and time boxes), those parts. Only pieces that draw + * a border of their own are its edges: a top nav's items are rounded but + * draw none, so the top nav's border is the bar's own. * @param {Ctx} ctx * @param {string} part * @returns {string[]} @@ -4418,10 +4420,28 @@ function drawnAlike(ctx, s, member) { export function borderParts(ctx, part) { const own = ctx.C.MAP[part]?.own ?? {}; if (Object.keys(own).some(k => /^border(?!.*radius)/.test(k))) return [part]; - const inner = cornerParts(ctx, part).filter(t => t !== part); + const inner = cornerParts(ctx, part).filter( + t => t !== part && drawsBorder(ctx, t), + ); return inner.length ? inner : [part]; } +/** + * Whether a part's own element draws a border: a border style or width + * that is not none or zero. + * @param {Ctx} ctx + * @param {string} part + */ +function drawsBorder(ctx, part) { + return Object.entries(ctx.C.MAP[part]?.own ?? {}).some( + ([k, r]) => + /^border(?:-(?:top|right|bottom|left))?-(?:style|width)$/.test(k) && + [.../** @type {Iterable} */ (r?.values ?? [])].some( + v => !/^(?:none|hidden|0(?:px)?)$/.test(String(v).trim()), + ), + ); +} + /** * The parts that paint a part's box (a text input itself; a date and time * field's two boxes, where the row around them paints none). @@ -5294,7 +5314,7 @@ export function compileTheme(ctx, data, base) { ctx.project.target.get(target)?.states ?? [], s.state, s.when, - wrapsOneControl(ctx, target), + controlOf(ctx, target), ctx.project.target.get(target)?.stateValues, ); const b = (t[key] ??= {}); @@ -5313,7 +5333,7 @@ export function compileTheme(ctx, data, base) { ctx.project.target.get(target)?.states ?? [], s.state, s.when, - wrapsOneControl(ctx, target), + controlOf(ctx, target), ctx.project.target.get(target)?.stateValues, ); const rule = (t[key] ??= {}); @@ -5988,7 +6008,7 @@ export function compileTheme(ctx, data, base) { tg?.states ?? [], s.state, s.when, - wrapsOneControl(ctx, target), + controlOf(ctx, target), tg?.stateValues, ); if (s.state && slot.key !== (s.when ?? 'base')) return null; @@ -6087,7 +6107,7 @@ export function compileTheme(ctx, data, base) { tg?.states ?? [], s.state, s.when, - wrapsOneControl(ctx, target), + controlOf(ctx, target), tg?.stateValues, ); if (!slot.pseudo) return [block(s, target), dir]; @@ -6202,12 +6222,20 @@ export function compileTheme(ctx, data, base) { if (color) mb.backgroundColor = color; return; } - // A color set in a one-mode theme fills its mode's half only (as a - // setting for that mode does), so a region Core draws in the other mode - // reads the other half. - const mode = - s.mode ?? - (modeOnly && parseColor(String(v).trim()) ? modeOnly : undefined); + const onWholeFill = colorOnWholeFill( + ctx, + data, + {...s, thing: prop}, + target, + ); + if (onWholeFill && s.mode) + (ctx.compileNotes ??= []).push( + `${target}'s own background is the same in both modes, so its ${s.mode} text color is written for both: a region drawn in the other mode (a lightbox, an overlay) keeps the text on that background`, + ); + const mode = onWholeFill + ? undefined + : (s.mode ?? + (modeOnly && parseColor(String(v).trim()) ? modeOnly : undefined)); if (mode && !s.when && variantsReading(ctx, target, prop, s.state).length) { // A color for one mode on a part whose variants each have their own: // each variant's rule (in the state, for a state setting) gets the @@ -9069,6 +9097,38 @@ async function buildThemeSteps(ctx, slug, data) { return {warnings, lifted, notes, removedPictures}; } +/** + * Whether a text color in a one-mode theme is written for both modes. It is + * when it sits on a rule whose own fill is an image (a gradient), which is + * written whole: a region Core draws in the other mode (a lightbox, an + * overlay) keeps that fill, so it keeps the text on it too. + * @param {Ctx} ctx + * @param {ThemeData} data + * @param {Setting} x + * @param {string | null} target the part the color is written on + * @returns {boolean} + */ +function colorOnWholeFill(ctx, data, x, target) { + const own = + data.mode === 'light-only' + ? 'light' + : data.mode === 'dark-only' + ? 'dark' + : null; + if (!own || !target || x.source !== 'property') return false; + if (kebab(x.thing) !== 'color' || (x.mode && x.mode !== own)) return false; + return data.settings.some( + y => + y.source === 'property' && + /^background(-image)?$/.test(kebab(y.thing)) && + !y.mode && + !parseColor(String(y.value).trim()) && + (y.when ?? null) === (x.when ?? null) && + (y.state ?? null) === (x.state ?? null) && + partsOf(ctx, y).includes(target), + ); +} + /** * The one color mode of a light-only or dark-only theme, from its settings, * for the build to write into the built module (`colorModes`); null for a @@ -9889,7 +9949,9 @@ export async function contrastProblems(ctx, data, res) { x => (!x.state || (inState != null && x.state === inState)) && (!x.when || x.when === w) && - (!x.mode || x.mode === m) && + (!x.mode || + x.mode === m || + colorOnWholeFill(ctx, data, x, p.fg.target)) && test(x), ) ?? null; /** @param {Setting} x @param {string | null} t */ @@ -10427,17 +10489,17 @@ export async function contrastProblems(ctx, data, res) { // state.) const pairIn = pairState(pair); const stateFlag = pairIn ? ` --state ${pairIn}` : ''; - // Secondary text (a placeholder, a caption) stays secondary: its - // own color moved toward black or white just far enough to read at - // 4.5:1, not the plain black or white of primary text. + // Text with a role of its own (secondary text, a placeholder, a + // link's accent, a status color) keeps it: its own color moved + // toward black or white just far enough to read at 4.5:1, not the + // plain black or white of primary text, which would make it read + // as body text. // (It reads on every ground that text sits on there: a token set on // a part reaches its text on each of the part's grounds.) const fgNow = parseColor(String(value(pair, 'fg', x.mode) ?? '')); - const secondary = + const ownRole = fgNow && - /^--color-text-(secondary|placeholder)/.test( - String(pair.fg.tokens?.[0]), - ); + /^--color-text-(?!primary$)[\w-]+$/.test(String(pair.fg.tokens?.[0])); const page = parseColor( String( res[/** @type {'light' | 'dark'} */ (x.mode)][ @@ -10445,7 +10507,7 @@ export async function contrastProblems(ctx, data, res) { ], ), ); - const groundsThere = secondary + const groundsThere = ownRole ? [ x.ground, .../** @type {TextPair[]} */ ( @@ -10466,7 +10528,7 @@ export async function contrastProblems(ctx, data, res) { ] : []; const color = `'${ - secondary + ownRole ? nearestReading( /** @type {[number, number, number]} */ (fgNow), /** @type {Array<[number, number, number]>} */ (groundsThere), @@ -11028,7 +11090,21 @@ function borderContrastProblems(ctx, data, res, base) { : basePage, basePage, ); - if (now != null && now < 3 && (was == null || was > now)) { + // What the theme drew there without this setting, on the same + // ground: a mode the setting leaves as the theme's own (a light-only + // border's dark half, the theme's border token) makes nothing + // fainter there, whatever the theme's dials did to that token. + const themeWas = measure( + inMode(`var(${bRead.token})`, mode, res[mode]), + ground || page, + page, + ); + if ( + now != null && + now < 3 && + (was == null || was > now) && + (themeWas == null || themeWas > now + 0.005) + ) { const color = fixOn(ground || page, page, border); add( `border|${x.thing}|${t}|${mode}`, @@ -11610,7 +11686,7 @@ function placeholderProblems(ctx, data, res, base) { const what = `the loading placeholder (${parts.slice(0, 3).join(', ')}, ${TOKEN} ${v}) is ${r.toFixed(2)}:1 on the page${surface ? ' or a surface' : ''} in ${m} at its brightest`; if (same) { out.push({ - key: `placeholder|base|${m}`, + key: `placeholder|${m}`, text: `the base theme's ${what.slice(4)}, so it barely shows; the base theme draws it so`, fix: null, }); @@ -11649,6 +11725,8 @@ function placeholderProblems(ctx, data, res, base) { if (worst(c) >= PLACEHOLDER_SHOWS) fix = shade; } out.push({ + // (The key the base's own note has: a change that leaves the + // placeholder as faint as the base drew it makes no new problem.) key: `placeholder|${m}`, text: `${what}; a placeholder needs ${PLACEHOLDER_SHOWS}:1 to show`, fix: fix @@ -11814,7 +11892,9 @@ function scopedTextProblems(ctx, data, res) { const done = new Set(); for (const x of data.settings.filter(scopedColor)) { const st = x.state ? String(x.state) : null; - const when = st ? null : String(x.when); + // (A state within a variant, a primary button's hover, is both: the + // variant's own text on the state's fill.) + const when = x.when ? String(x.when) : null; for (const t of partsOf(ctx, x)) { const scopeKey = `${t}|${st ?? ''}|${when ?? ''}`; if (done.has(scopeKey)) continue; @@ -11822,16 +11902,20 @@ function scopedTextProblems(ctx, data, res) { /** A part-data condition is this scope. @param {string} w */ const inScope = w => { const terms = w.split(' ')[0].split(','); - return st - ? new RegExp(`(^|[\\s,])${st}=`).test(w) - : terms.includes(String(when).replace(':', '=')); + return ( + (!st || new RegExp(`(^|[\\s,])${st}=`).test(w)) && + (!when || + String(when) + .split('+') + .every(c => terms.includes(c.replace(':', '=')))) + ); }; /** A setting is on this part in this scope (or at rest), in a mode. @param {Setting} y @param {string} m @param {boolean} scoped */ const here = (y, m, scoped) => Boolean(y.on) && (!y.mode || y.mode === m) && (scoped - ? (y.state ?? null) === st && (st ? true : y.when === when) + ? (y.state ?? null) === st && (y.when ?? null) === when : !y.state && !y.when) && partsOf(ctx, y).includes(t); /** The latest setting matching, scoped first, then at rest. @param {(y: Setting) => boolean} test @param {string} m */ @@ -11847,14 +11931,26 @@ function scopedTextProblems(ctx, data, res) { /** The part-data read for a group in this scope, else at rest. @param {string} group */ const readOf = group => { const reads = ctx.C.partReads(t, group) ?? []; + /** The variant alone, its state left out. @param {string} w */ + const inVariant = w => { + const terms = w.split(' ')[0].split(','); + return String(when) + .split('+') + .every(c => terms.includes(c.replace(':', '='))); + }; return ( reads.find(r => r.when.some(inScope)) ?? + (when && st ? reads.find(r => r.when.some(inVariant)) : null) ?? reads.find(r => r.when.includes('')) ?? null ); }; for (const m0 of modes) { const m = /** @type {'light' | 'dark'} */ (m0); + // (A mode no write for this scope reaches, a light-only hover + // fill's dark, is drawn as the base draws it: nothing to measure.) + if (!data.settings.some(y => scopedColor(y) && here(y, m, true))) + continue; const page = parseColor(String(res[m]['--color-background-body'])); if (!page) continue; const fillSet = latest( @@ -11872,6 +11968,21 @@ function scopedTextProblems(ctx, data, res) { m, ); const textRead = readOf('text'); + // A part that draws no text, nor holds a part that does (a + // switch's track, a tab's underline), has none to measure, unless + // the theme gives it a color. (A table row's text is its cells'.) + const drawsText = (/** @type {string} */ q) => + (ctx.C.partReads(q, 'text') ?? []).length > 0; + if ( + !textRead && + !colorSet && + !( + /** @type {string[]} */ ( + /** @type {any} */ (ctx.C.MAP[t])?.contains ?? [] + ).some(drawsText) + ) + ) + continue; const textToken = textRead?.token ?? '--color-text-primary'; const textValue = colorSet ? inMode(colorSet.value, m) @@ -11890,8 +12001,16 @@ function scopedTextProblems(ctx, data, res) { const fg = compositeOver(fg0, alphaOf(textValue), ground); const r = ratio(fg, ground); if (r >= 4.5) continue; - const scope = st ? `--state ${st}` : `--when ${when}`; - const label = st ? st : String(when).replace(':', ' '); + const scope = [ + ...(when ? [`--when ${when}`] : []), + ...(st ? [`--state ${st}`] : []), + ].join(' '); + const label = [ + ...(when + ? [String(when).replace(/:/g, ' ').replace(/\+/g, ', ')] + : []), + ...(st ? [st] : []), + ].join(', '); const fix = nearestReading(fg, [ground], 4.5); // What draws the text: a color set there, else the token the text // reads, set on the part in that state or condition. @@ -12321,7 +12440,7 @@ export function baseComponent(base, ctx, target, prop, s) { states, s.state, s.when, - wrapsOneControl(ctx, target), + controlOf(ctx, target), ctx.project.target.get(target)?.stateValues, ); b = slot.pseudo @@ -12557,19 +12676,72 @@ export function clearNewMarker(dir) { * control inside it (never a list row); an action part that holds * children (a button group, a segmented control) never does, so one * disabled child never makes the whole part look disabled. + * A moment state on a part drawn under an invisible input lands on the + * part holding that input, and the part shows it from there. * @param {string} state - * @param {boolean} [wrapsControl] + * @param {boolean | Control} [control] whether it wraps one control, or + * its control (`controlOf`) * @returns {string} */ -export function stateKey(state, wrapsControl = false) { +export function stateKey(state, control = false) { + const {wraps: wrapsControl, under} = controlParts(control); const aria = ARIA_STATES[/** @type {keyof typeof ARIA_STATES} */ (state)]; if (aria) return `:is(${aria.selector})`; + // A part drawn under an invisible input (a checkbox's box): the input + // takes the pointer and the focus, so a moment state lands on the part + // that holds the input, and the part shows it from there. + const held = under ? HELD_STATES[state] : undefined; + if (held) return `:where(.astryx-${under}${held} *)`; if (state !== 'disabled') return `:${state}`; return wrapsControl ? ':is(:disabled,[aria-disabled="true"],:has(:is(input,button,select,textarea):is(:disabled,[aria-disabled="true"])))' : ':is(:disabled,[aria-disabled="true"])'; } +/** + * A moment state as the part holding an invisible input shows it, for a + * part drawn under that input. + * @type {Record} + */ +const HELD_STATES = { + hover: ':hover', + active: ':active', + focus: ':has(:is(input,button,select,textarea):focus)', + 'focus-visible': ':has(:is(input,button,select,textarea):focus-visible)', + 'focus-within': ':focus-within', +}; + +/** + * A part's control: whether it wraps one control (its disabled state is + * the control's too), and the part holding the invisible input it is drawn + * under, if any. + * @typedef {{wraps: boolean, under: string | null}} Control + */ + +/** + * @param {boolean | Control} control + * @returns {Control} + */ +function controlParts(control) { + return typeof control === 'object' && control + ? control + : {wraps: Boolean(control), under: null}; +} + +/** + * A part's control, as `stateSlot` takes it. + * @param {Ctx} ctx + * @param {string} target + * @returns {Control} + */ +export function controlOf(ctx, target) { + const under = ctx.C.MAP[target]?.underInput; + return { + wraps: wrapsOneControl(ctx, target), + under: typeof under === 'string' && under ? under : null, + }; +} + /** * The states Core paints from an ARIA attribute rather than a data * attribute of its own (a pagination's current page, a pressed or open @@ -12765,7 +12937,8 @@ function loadedForm(data) { * @param {string[]} own the states Core writes as keys on the part * @param {string | undefined} state * @param {string | undefined} when - * @param {boolean} [wrapsControl] + * @param {boolean | Control} [wrapsControl] whether it wraps one control, + * or its control (`controlOf`) * @param {Record} [values] the value Core writes for each * own state: a state that names a boolean prop is written `state:true` * @returns {{key: string, pseudo: string | null}} diff --git a/packages/cli/api/theme-edit/theme-bar-border.test.mjs b/packages/cli/api/theme-edit/theme-bar-border.test.mjs new file mode 100644 index 0000000000000..a6a56dd47cc30 --- /dev/null +++ b/packages/cli/api/theme-edit/theme-bar-border.test.mjs @@ -0,0 +1,87 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * A border asked of a bar is the bar's own, unless its edges are pieces + * that draw borders of their own: a top nav's bottom border goes on the top + * nav, never under each of its rounded items; a date and time field's + * border still goes on its two boxes; a sidebar's right border is the + * sidebar's, never one beside each link. Against real bundled base themes. + */ + +import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest'; +import {themeEditHow, themeEditNew} from './theme-edit.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import {FIXTURE_PACKAGES} from '../../test-utils/base-theme-fixture.mjs'; +import {installRealBaseThemes} from '../../test-utils/real-base-themes.mjs'; + +vi.mock('./_preview.mjs', async importOriginal => + (await import('../../test-utils/theme-render-stub.mjs')).stubRenders( + await importOriginal(), + ), +); + +/** @type {string} */ +let cwd; + +/** Why a bundled theme could not be built here, when it could not. */ +let unbuilt = ''; + +beforeAll(async () => { + cwd = makeLinkedFixture('astryx-theme-bar-border-', FIXTURE_PACKAGES); + unbuilt = await installRealBaseThemes(cwd, ['neutral']); +}, 300_000); + +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +/** @param {import('vitest').TestContext} ctx */ +const needBases = ctx => { + if (!unbuilt) return false; + console.warn(`skipped: ${unbuilt}`); + ctx.skip(); + return true; +}; + +/** @param {string} q @param {string} theme */ +const answer = async (q, theme) => { + const {data} = await themeEditHow(q, {cwd, theme}); + return { + parts: data.understood?.parts ?? [], + writes: (data.results ?? []) + .flatMap((/** @type {any} */ r) => r.commands) + .filter((/** @type {string} */ c) => / editor set /.test(c)) + .map((/** @type {string} */ c) => c.replace(/^.*? editor /, '')), + text: (data.results ?? []).map((/** @type {any} */ r) => r.text).join('\n'), + }; +}; + +describe('a border on a bar', () => { + it('goes on the bar, unless its pieces draw the borders', async ctx => { + if (needBases(ctx)) return; + await themeEditNew('b', {cwd, like: 'neutral'}); + expect( + (await answer('top nav with a 1px bottom border', 'b')).writes, + ).toEqual([ + "set b border-bottom '1px solid var(--color-border)' --on top-nav", + ]); + expect( + (await answer('sidebar with a 1px right border', 'b')).writes, + ).toEqual([ + "set b border-right '1px solid var(--color-border)' --on side-nav", + ]); + // (Its items, named, are still its items.) + expect( + (await answer('nav items with a bottom border', 'b')).writes[0], + ).toMatch(/--on top-nav-item$/); + // (A part whose pieces draw its border hands it to them.) + const field = await answer('date time input with a red border', 'b'); + expect(field.parts).toEqual([ + 'date-time-input-date-segment', + 'date-time-input-time-segment', + ]); + }, 240_000); +}); diff --git a/packages/cli/api/theme-edit/theme-edit-only-escape-and-light-only-mode.test.mjs b/packages/cli/api/theme-edit/theme-edit-only-escape-and-light-only-mode.test.mjs new file mode 100644 index 0000000000000..dc8c791852730 --- /dev/null +++ b/packages/cli/api/theme-edit/theme-edit-only-escape-and-light-only-mode.test.mjs @@ -0,0 +1,284 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file --only always works as an escape from a group: on a member of a + * group that spreads it keeps the change to that member, and on a part that + * is styled on its own already it is taken and said. A menu's radio is kept + * apart from every other radio: a square corners ask leaves its circle, and + * a round ask on a menu radio the theme squared offers the undo that gives + * the circle back. A one-mode theme reads its own mode named with --mode as + * no --mode, light-only as dark-only. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest'; +import {themeEditNew} from './theme-edit.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import { + FIXTURE_PACKAGES, + writeFixtureBaseTheme, +} from '../../test-utils/base-theme-fixture.mjs'; +import {runCli} from '../../test-utils/run-cli.mjs'; + +vi.mock('./_preview.mjs', async importOriginal => + (await import('../../test-utils/theme-render-stub.mjs')).stubRenders( + await importOriginal(), + ), +); + +const T = 240_000; +const ED = ['experimental', 'theme', 'editor']; + +/** @type {string} */ +let cwd; +/** @type {string} */ +let fresh; + +const file = () => path.join(cwd, 'themes/t/t.settings.json'); +const saved = () => JSON.parse(fs.readFileSync(file(), 'utf8')).settings; + +beforeAll(async () => { + cwd = makeLinkedFixture('astryx-theme-only-escape-', FIXTURE_PACKAGES); + writeFixtureBaseTheme(cwd, 'neutral'); + await themeEditNew('t', {cwd, like: 'neutral'}); + fresh = fs.readFileSync(file(), 'utf8'); +}, T); + +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +/** @param {string[]} args */ +const cli = async args => + JSON.parse((await runCli([...args, '--json'], cwd)).stdout); + +/** @param {any} r */ +const names = r => + (r.suggestions ?? []).map((/** @type {any} */ x) => + x.name.replace(/^.*? editor /, ''), + ); + +/** @param {string} ask */ +const how = async ask => { + const r = await cli([...ED, 'how', ask, '--theme', 't']); + /** @type {Array<{text: string, commands?: string[]}>} */ + const results = r.data?.results ?? []; + return { + texts: results.map(x => x.text), + commands: results + .flatMap(x => x.commands ?? []) + .map(c => c.replace(/^.*? editor /, '')), + }; +}; + +describe('--only', () => { + it( + 'keeps a change on a member of a group that spreads to that member', + async () => { + fs.writeFileSync(file(), fresh); + const all = await cli([ + ...ED, + 'set', + 't', + 'box-shadow', + 'none', + '--on', + 'date-time-input', + ]); + expect(all.data.parts.length).toBeGreaterThan(1); + fs.writeFileSync(file(), fresh); + const one = await cli([ + ...ED, + 'set', + 't', + 'box-shadow', + 'none', + '--on', + 'date-time-input', + '--only', + ]); + expect(one.data.parts).toEqual(['date-time-input']); + }, + T, + ); + + for (const part of ['date-time-input-date-segment', 'card']) + it( + `is taken on ${part}, styled on its own already, and said`, + async () => { + fs.writeFileSync(file(), fresh); + const r = await cli([ + ...ED, + 'set', + 't', + 'border-radius', + '2px', + '--on', + part, + '--only', + ]); + expect(r.error).toBeUndefined(); + expect(r.data.parts).toEqual([part]); + expect(r.data.notes.join(' ')).toMatch( + new RegExp( + `${part} is styled on its own already .* so --only changes nothing`, + ), + ); + // Saved as the plain change, which an undo with --only also removes. + expect( + saved().find((/** @type {any} */ x) => x.on === part).only, + ).toBeUndefined(); + const back = await cli([ + ...ED, + 'undo', + 't', + 'border-radius', + '--on', + part, + '--only', + ]); + expect(back.error).toBeUndefined(); + }, + T, + ); + + it( + 'is refused on a group itself, which has no one member to keep to', + async () => { + fs.writeFileSync(file(), fresh); + const r = await cli([ + ...ED, + 'set', + 't', + 'border-radius', + '4px', + '--on', + 'inputs', + '--only', + ]); + expect(r.error).toMatch(/--only is for one member of a group/); + }, + T, + ); +}); + +describe("a menu's radio", () => { + it( + 'keeps its circle under a square corners ask, and says so', + async () => { + fs.writeFileSync(file(), fresh); + const a = await how('square corners but keep menu radios round'); + expect(a.texts.join(' ')).toMatch( + /dropdown-menu-radio is a radio's circle, which the corners change leaves as it is/, + ); + expect(a.texts.join(' ')).not.toMatch(/cannot be kept apart/); + expect(a.commands).toContain('set t corners square'); + }, + T, + ); + + it( + 'offers the undo that gives the circle back when the theme squared it', + async () => { + fs.writeFileSync(file(), fresh); + await cli([ + ...ED, + 'set', + 't', + 'border-radius', + '0', + '--on', + 'dropdown-menu-radio', + ]); + const r = await cli([ + ...ED, + 'set', + 't', + 'corners', + 'pill', + '--on', + 'dropdown-menu-radio', + ]); + expect(r.error).toMatch(/undoing that gives the circle back/); + expect(names(r)[0]).toBe('undo t border-radius --on dropdown-menu-radio'); + expect( + (await cli([...ED, ...names(r)[0].split(' ')])).error, + ).toBeUndefined(); + }, + T, + ); + + it( + 'offers no rounding line to a sharper ask, squared or not', + async () => { + fs.writeFileSync(file(), fresh); + await cli([ + ...ED, + 'set', + 't', + 'border-radius', + '0', + '--on', + 'dropdown-menu-radio', + ]); + const squared = await cli([ + ...ED, + 'set', + 't', + 'corners', + 'sharper', + '--on', + 'dropdown-menu-radio', + ]); + expect(squared.error).toMatch(/is a radio's circle/); + expect(squared.error).not.toMatch(/gives the circle back|fully round/); + expect(names(squared).some(n => /undo t border-radius/.test(n))).toBe( + false, + ); + }, + T, + ); +}); + +describe("a one-mode theme's own --mode", () => { + for (const [mode, own] of [ + ['light-only', 'light'], + ['dark-only', 'dark'], + ]) + it( + `on a ${mode} theme is the same as no --mode`, + async () => { + fs.writeFileSync(file(), fresh); + await cli([...ED, 'set', 't', 'mode', mode]); + const r = await cli([ + ...ED, + 'set', + 't', + '--color-border', + '#888888', + '--mode', + own, + ]); + expect(r.error).toBeUndefined(); + expect(r.data.notes.join(' ')).toMatch( + new RegExp( + `t is ${mode}: --mode ${own} is its own mode, the same as no --mode`, + ), + ); + const back = await cli([ + ...ED, + 'undo', + 't', + '--color-border', + '--mode', + own, + ]); + expect(back.error).toBeUndefined(); + }, + T, + ); +}); diff --git a/packages/cli/api/theme-edit/theme-edit.test.mjs b/packages/cli/api/theme-edit/theme-edit.test.mjs index 85385cd91b6c2..1d9c7c62b1fb1 100644 --- a/packages/cli/api/theme-edit/theme-edit.test.mjs +++ b/packages/cli/api/theme-edit/theme-edit.test.mjs @@ -469,14 +469,17 @@ describe('groups', () => { await themeEditUndo('t', {thing: 'box-shadow', cwd, on: 'containers'}); }); - it('--only is refused for a group that does not spread', async () => { - const r = await refusal(() => - themeEditSet('t', 'box-shadow', 'none', {cwd, on: 'card', only: true}), + it('--only on a part of a group that does not spread is taken, and said', async () => { + const r = await themeEditSet('t', 'box-shadow', 'none', { + cwd, + on: 'card', + only: true, + }); + expect(r.data.notes.join(' ')).toMatch( + /card is styled on its own already .* so --only changes nothing/, ); - expect(r.code).toBe('ERR_INVALID_ARGUMENT'); - expect(r.run).toEqual([ - 'astryx experimental theme editor set t box-shadow none --on card', - ]); + // Taken back, so the settings stay as the other cases expect them. + await themeEditUndo('t', {cwd}); }); }); diff --git a/packages/cli/api/theme-edit/theme-fix-lines-keep-role.test.mjs b/packages/cli/api/theme-edit/theme-fix-lines-keep-role.test.mjs new file mode 100644 index 0000000000000..ee6bf44975b41 --- /dev/null +++ b/packages/cli/api/theme-edit/theme-fix-lines-keep-role.test.mjs @@ -0,0 +1,102 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file What a change reports keeps to what it did: a link color too faint + * is fixed with the nearest shade of its own color that reads, never the + * plain black or white of body text; a light-only border reports nothing + * about the dark frame it left as the theme draws it; and one fill on a + * group of parts says what it covers once for each kind of cover, not + * once for each part. + */ + +import {afterAll, beforeAll, describe, expect, it} from 'vitest'; +import {themeEditNew, themeEditSet} from './theme-edit.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import { + FIXTURE_PACKAGES, + writeFixtureBaseTheme, +} from '../../test-utils/base-theme-fixture.mjs'; + +const T = 400_000; +/** @type {string} */ +let cwd; +beforeAll(() => { + cwd = makeLinkedFixture( + 'astryx-theme-fix-lines-keep-role-', + FIXTURE_PACKAGES, + ); + writeFixtureBaseTheme(cwd, 'neutral'); +}); +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +describe('what a change reports', () => { + it( + 'fixes a faint link color with a shade of its own color, not black or white', + async () => { + await themeEditNew('l', {cwd, like: 'neutral'}); + await themeEditSet('l', '--color-background-body', '#000000', { + cwd, + mode: 'dark', + }); + const r = /** @type {any} */ ( + await themeEditSet('l', '--color-text-accent', '#0070f3', {cwd}) + ).data; + const fixes = r.newProblems + .map((/** @type {any} */ p) => String(p.fix ?? '')) + .filter((/** @type {string} */ f) => / --color-text-accent /.test(f)); + expect(fixes.length).toBeGreaterThan(0); + for (const f of fixes) expect(f).not.toMatch(/'#(000000|ffffff)'/); + }, + T, + ); + + it( + 'reports no dark problem for a border set for light alone', + async () => { + await themeEditNew('b', { + cwd, + like: 'neutral', + settings: {neutral: '#64748d'}, + }); + const r = /** @type {any} */ ( + await themeEditSet( + 'b', + 'border', + '1px solid light-dark(#d5dbe1, var(--color-border-emphasized))', + {cwd, on: 'inputs'}, + ) + ).data; + expect( + r.newProblems.filter((/** @type {any} */ p) => + /^the border on .* in dark;/.test(p.problem), + ), + ).toEqual([]); + }, + T, + ); + + it( + 'says what one fill on a group covers once for each kind of cover', + async () => { + await themeEditNew('i', {cwd, like: 'neutral'}); + const r = /** @type {any} */ ( + await themeEditSet('i', 'background-color', '#ffffff', { + cwd, + on: 'inputs', + mode: 'light', + }) + ).data; + const covers = /** @type {string[]} */ (r.notes).filter(n => + / now covers? the fill Core gives/.test(n), + ); + expect(covers.length).toBeGreaterThan(0); + expect(covers.length).toBeLessThan(r.parts.length); + }, + T, + ); +}); diff --git a/packages/cli/api/theme-edit/theme-how-clause-scope.test.mjs b/packages/cli/api/theme-edit/theme-how-clause-scope.test.mjs index 60f4524d1653d..65b247e81f301 100644 --- a/packages/cli/api/theme-edit/theme-how-clause-scope.test.mjs +++ b/packages/cli/api/theme-edit/theme-how-clause-scope.test.mjs @@ -212,7 +212,9 @@ const PART = [ "background-color '#2563eb' --on button --when variant:primary", "background-color '#2563eb' --on button --when variant:secondary", "background-color '#2563eb' --on button --when variant:ghost", - "color '#ffffff' --on button", + "color '#ffffff' --on button --when variant:primary", + "color '#ffffff' --on button --when variant:secondary", + "color '#ffffff' --on button --when variant:ghost", ], }, ], @@ -430,7 +432,8 @@ const LATER_ASKS = [ "the part's text in its with-list", { q: 'badges with a subtle colored background and dark text', - lead: "color '#111827' --on badge", + // (Each badge variant, in the modes the text reads in there.) + has: ["color '#111827' --on badge --when variant:warning"], never: /^--color-text-primary/, }, ], diff --git a/packages/cli/api/theme-edit/theme-how-draws-modes-clearly-light.test.mjs b/packages/cli/api/theme-edit/theme-how-draws-modes-clearly-light.test.mjs index 91ac9d93c4489..89efb0f3ae117 100644 --- a/packages/cli/api/theme-edit/theme-how-draws-modes-clearly-light.test.mjs +++ b/packages/cli/api/theme-edit/theme-how-draws-modes-clearly-light.test.mjs @@ -206,7 +206,9 @@ describe('clone and blind asks', () => { "background-color '#2563eb' --on button --when variant:primary", "background-color '#2563eb' --on button --when variant:secondary", "background-color '#2563eb' --on button --when variant:ghost", - "color '#ffffff' --on button", + "color '#ffffff' --on button --when variant:primary", + "color '#ffffff' --on button --when variant:secondary", + "color '#ffffff' --on button --when variant:ghost", ]); }, T, diff --git a/packages/cli/api/theme-edit/theme-how-list-items.test.mjs b/packages/cli/api/theme-edit/theme-how-list-items.test.mjs index b5b6d3808fd11..3e8bc4c1952ec 100644 --- a/packages/cli/api/theme-edit/theme-how-list-items.test.mjs +++ b/packages/cli/api/theme-edit/theme-how-list-items.test.mjs @@ -198,12 +198,33 @@ describe('corners on some sides', () => { ); }); +describe('a rule and a tint', () => { + it( + 'a rule with its own verb after a part clause is the theme’s; a tint is the color at a low strength', + async test => { + needsBases(test); + const r = await answer( + '3px corners on cards, never use pure black for text', + ); + expect(r.first).toContain("--color-text-primary '#1f2937' --mode light"); + expect(r.text).not.toMatch(/nothing changes/); + expect( + (await answer('selected nav items tinted forest green')).first, + ).toEqual([ + "background-color 'color-mix(in srgb, #228b22 15%, transparent)' --on top-nav-item --state selected", + ]); + }, + T, + ); +}); + describe('other readings', () => { it( 'a color with a shape is its fill; "divided by" is no amount; shadow-sm is small; "stable" is no table', async test => { needsBases(test); const pill = await answer('the active nav item should be a #e8def8 pill'); + expect(pill.all.join('\n')).toMatch(/corners pill --on top-nav-item/); expect(pill.text).not.toMatch(/but not "#e8def8"/); expect( (await answer('table rows divided by 1px lines')).text, diff --git a/packages/cli/api/theme-edit/theme-how-plain-words.test.mjs b/packages/cli/api/theme-edit/theme-how-plain-words.test.mjs index d1b77d9d3200e..e53324f5108eb 100644 --- a/packages/cli/api/theme-edit/theme-how-plain-words.test.mjs +++ b/packages/cli/api/theme-edit/theme-how-plain-words.test.mjs @@ -131,11 +131,12 @@ describe('plain words for looks', () => { expect(writes(await how('q0', '32px rows in the menu'))[0]).toBe( 'set q0 min-height 32px --on dropdown-menu-item', ); - const pill = top( + // (One reader for a color with a shape: the item's state is kept.) + const pill = writes( await how('q0', 'the active nav item should be a #e8def8 pill'), - ); - expect(pill).toContain('set q0 corners pill --on top-nav-item'); - expect(pill[0]).toMatch( + ).join(' '); + expect(pill).toMatch(/corners pill --on top-nav-item --state selected/); + expect(pill).toMatch( /background-color '#e8def8' --on top-nav-item --state selected/, ); expect( diff --git a/packages/cli/api/theme-edit/theme-how-tint-and-mode-pairs.test.mjs b/packages/cli/api/theme-edit/theme-how-tint-and-mode-pairs.test.mjs new file mode 100644 index 0000000000000..f82bc26e18b9c --- /dev/null +++ b/packages/cli/api/theme-edit/theme-how-tint-and-mode-pairs.test.mjs @@ -0,0 +1,240 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file `editor how`: a text color asked with a fill given for one mode is + * that mode's on every variant the fill reaches; a tint word tints only the + * color it modifies, on every line that writes it. + * + * @position api/theme-edit — tests + */ + +import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest'; +import {themeEditHow, themeEditNew} from './theme-edit.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import {FIXTURE_PACKAGES} from '../../test-utils/base-theme-fixture.mjs'; +import {installRealBaseThemes} from '../../test-utils/real-base-themes.mjs'; + +vi.mock('./_preview.mjs', async importOriginal => + (await import('../../test-utils/theme-render-stub.mjs')).stubRenders( + await importOriginal(), + ), +); + +/** @type {string} */ +let cwd; +/** Why a bundled base could not be installed here, when one could not. */ +let unbuilt = ''; + +beforeAll(async () => { + cwd = makeLinkedFixture('astryx-theme-how-tint-mode-', FIXTURE_PACKAGES); + unbuilt = await installRealBaseThemes(cwd, ['neutral']); + if (unbuilt) return; + await themeEditNew('n', {cwd, like: 'neutral'}); +}, 600_000); + +afterAll(() => { + removeLinkedFixture(cwd); +}); + +/** Every set command an answer gives, after the theme name. @param {string} q */ +const sets = async q => { + const {data} = await themeEditHow(q, {cwd, theme: 'n'}); + return (data.results ?? []) + .flatMap(r => r.commands) + .filter(c => / editor set /.test(c)) + .map(c => c.replace(/^.* editor set \S+ /, '')); +}; + +/** @param {import('vitest').TestContext} test */ +const needsBases = test => { + if (unbuilt) { + console.warn(`skipped: ${unbuilt}`); + test.skip(); + } +}; + +const T = 300_000; + +describe('a text color asked with a fill for one mode', () => { + it( + 'is that mode only, on every variant the fill reaches', + async test => { + needsBases(test); + const all = await sets( + 'buttons with a navy background in dark mode and white text', + ); + // (On the variants the dark fill reaches, the white is dark mode's; + // light mode keeps the secondary and ghost text that reads on their + // light fills.) + const white = all.filter(c => + /^color '#ffffff' .*variant:(?:secondary|ghost)/.test(c), + ); + expect(white.length).toBeGreaterThan(0); + for (const c of white) expect(c).toMatch(/ --mode dark$/); + }, + T, + ); +}); + +describe('a tint word', () => { + it( + 'tints a part named before the clause the tint word is in', + async test => { + needsBases(test); + const all = await sets( + 'Secondary button hover, in dark mode only: a slightly blue tint. Light mode untouched.', + ); + const hover = all.filter(c => + /^background(?:-color)? .*--on button .*--state hover/.test(c), + ); + expect(hover.length).toBeGreaterThan(0); + for (const c of hover) + expect(c).toMatch(/color-mix\(in srgb, #2563eb 15%/); + }, + T, + ); + + it( + 'tints the color it modifies on every line, and leaves another color solid', + async test => { + needsBases(test); + const all = await sets('cards tinted blue with a navy header'); + const fills = all.filter(c => /^background(?:-color)? /.test(c)); + const blue = fills.filter(c => /#2563eb/.test(c)); + const cards = fills.filter(c => / --on card\b/.test(c)); + expect(cards.length).toBeGreaterThan(0); + for (const c of cards) + expect(c).toMatch(/color-mix\(in srgb, #2563eb 15%, transparent\)/); + // (The header the tint does not name is its own navy, never tinted.) + const header = fills.filter(c => / --on app-shell-header\b/.test(c)); + expect(header.length).toBeGreaterThan(0); + for (const c of header) + expect(c).toBe("background-color '#1e3a8a' --on app-shell-header"); + // (Said without the tint, the header is navy too.) + const plain = (await sets('cards blue with a navy header')).filter(c => + / --on app-shell-header\b/.test(c), + ); + expect(plain.length).toBeGreaterThan(0); + for (const c of plain) + expect(c).toBe("background-color '#1e3a8a' --on app-shell-header"); + }, + T, + ); + + it( + 'deepens a tint until the text asked with it reads in every mode', + async test => { + needsBases(test); + const {data} = await themeEditHow('buttons tinted blue with white text', { + cwd, + theme: 'n', + }); + // (The answer that runs the whole ask: white on a 15% blue tint over + // the light page is 1.4:1.) + const whole = (data.results ?? []).find(r => /^all of it/.test(r.text)); + expect(whole).toBeDefined(); + const all = (whole?.commands ?? []) + .filter(c => / editor set /.test(c)) + .map(c => c.replace(/^.* editor set \S+ /, '')); + expect(all.some(c => /#2563eb 15%/.test(c))).toBe(false); + expect(whole?.text).not.toMatch(/at 15% over/); + const fills = all.filter(c => + /^background(?:-color)? .*#2563eb.* --on button --when variant:/.test( + c, + ), + ); + expect(fills.length).toBeGreaterThan(0); + for (const fill of fills) { + const when = /--when (\S+)/.exec(fill)?.[1]; + const text = all.filter( + x => + x.startsWith("color '#ffffff' --on button") && + x.includes(`--when ${when}`), + ); + expect(text.length).toBeGreaterThan(0); + for (const c of text) expect(c).not.toMatch(/--mode/); + } + expect(whole?.text).toMatch( + /the #2563eb tint is deepened to (?:\d+%|solid) so #ffffff text reads at \d+\.\d:1/, + ); + }, + T, + ); + + it( + 'keeps a text color no strength of the tint reads on to the modes it reads in, and names a readable ink', + async test => { + needsBases(test); + // (Yellow at any strength never takes white text to 4.5:1 on the + // light page; over the dark page a light tint of it does.) + const {data} = await themeEditHow( + 'buttons tinted #facc15 with white text', + {cwd, theme: 'n'}, + ); + const whole = (data.results ?? []).find(r => /^all of it/.test(r.text)); + expect(whole).toBeDefined(); + const all = (whole?.commands ?? []) + .filter(c => / editor set /.test(c)) + .map(c => c.replace(/^.* editor set \S+ /, '')); + const text = all.filter(c => c.startsWith("color '#ffffff' --on button")); + expect(text.length).toBeGreaterThan(0); + for (const c of text) expect(c).toMatch(/--mode dark/); + expect(whole?.text).toMatch( + /#ffffff text on the \S+ button would not read on color-mix\(in srgb, #facc15 15%, transparent\) in light mode: \d\.\d\d:1, under the 4\.5:1 text needs, so it is kept to dark mode; #111827 reads there/, + ); + }, + T, + ); + + for (const [q, part, state] of [ + ['cards tinted blue with white text', 'card', ''], + [ + 'selected nav items tinted forest green with white text', + 'top-nav-item', + '--state selected', + ], + ]) + it( + `measures white text on ${q}`, + async test => { + needsBases(test); + const {data} = await themeEditHow(q, {cwd, theme: 'n'}); + const whole = (data.results ?? []).find(r => /^all of it/.test(r.text)); + expect(whole).toBeDefined(); + const all = (whole?.commands ?? []) + .filter(c => / editor set /.test(c)) + .map(c => c.replace(/^.* editor set \S+ /, '')); + const fills = all.filter(c => + new RegExp( + `^background(?:-color)? .* --on ${part}\\b${state ? `.*${state}` : ''}`, + ).test(c), + ); + expect(fills.length).toBeGreaterThan(0); + // (White over a 15% tint on the light page is under 1.5:1: the + // tint is deepened, or the text kept to the modes it reads in.) + const text = all.filter( + c => /'#ffffff'/.test(c) && new RegExp(`--on ${part}\\b`).test(c), + ); + expect(text.length).toBeGreaterThan(0); + // (Each text line sits on a fill this answer gives: the variants + // that keep their own fill, the coloured cards, keep their text.) + for (const c of text) { + const when = /--when (\S+)/.exec(c)?.[1]; + expect( + fills.some(f => + when ? f.includes(`--when ${when}`) : !/--when/.test(f), + ), + ).toBe(true); + } + const deepened = fills.every(c => !/ 15%, transparent/.test(c)); + if (!deepened) for (const c of text) expect(c).toMatch(/--mode dark/); + expect(whole?.text).toMatch( + /deepened to (?:\d+%|solid) so #ffffff text reads|#ffffff text on the .* would not read/, + ); + }, + T, + ); +}); diff --git a/packages/cli/api/theme-edit/theme-how-variant-looks.test.mjs b/packages/cli/api/theme-edit/theme-how-variant-looks.test.mjs index 82b565484f500..6b6c5653effc3 100644 --- a/packages/cli/api/theme-edit/theme-how-variant-looks.test.mjs +++ b/packages/cli/api/theme-edit/theme-how-variant-looks.test.mjs @@ -91,15 +91,33 @@ describe('a color asked of every variant', () => { T, ); it( - 'a text color skips the variants it would vanish on', + 'a text color goes to each variant only in the modes it reads in there', async test => { needsBases(test); const r = await answer('buttons with white text'); + // (White reads on the primary fill in light mode, and on the ghost's + // page in dark mode only.) expect(r.first).toContain( - "color '#ffffff' --on button --when variant:primary", + "color '#ffffff' --on button --when variant:primary --mode light", ); - for (const c of r.first) expect(c).not.toMatch(/variant:ghost/); - expect(r.texts[0]).toMatch(/ghost keeps its own text/); + expect(r.first).toContain( + "color '#ffffff' --on button --when variant:ghost --mode dark", + ); + for (const c of r.first) expect(c).toMatch(/ --mode (?:light|dark)$/); + expect(r.texts[0]).toMatch(/only in the mode it reads in/); + // (Its own fill given beside it, the text is measured on that fill; + // a variant kept out of the fill keeps its own.) + const gold = await answer('gold buttons with black text'); + expect(gold.first).toContain( + "color '#000000' --on button --when variant:primary", + ); + expect(gold.first).not.toContain("color '#000000' --on button"); + expect(gold.first.join('\n')).not.toMatch( + /color '#000000' --on button --when variant:destructive --mode light/, + ); + // (A badge's see-through fill is read over the page.) + for (const c of (await answer('badges with dark text')).first) + expect(c).toMatch(/--when variant:/); }, T, ); diff --git a/packages/cli/api/theme-edit/theme-list-end-corners-scale.test.mjs b/packages/cli/api/theme-edit/theme-list-end-corners-scale.test.mjs index dcd9571c6d3f7..8928ce641fee0 100644 --- a/packages/cli/api/theme-edit/theme-list-end-corners-scale.test.mjs +++ b/packages/cli/api/theme-edit/theme-list-end-corners-scale.test.mjs @@ -86,12 +86,20 @@ describe('list end corners scale', () => { const r = await refusal(() => themeEditSet('t', 'background-color', '#ff0000', { cwd, - on: 'switch', + on: 'progress-bar', state: 'focus-within', }), ); expect(r.code).toBe('ERR_THEME_NO_EFFECT'); expect(r.message).not.toMatch(/focus-within does/); + // (A switch's track is drawn under the input its field holds: focus + // within lands on the field, where the input takes focus, and the + // track shows it from there.) + await themeEditSet('t', 'background-color', '#ff0000', { + cwd, + on: 'switch', + state: 'focus-within', + }); }); }); diff --git a/packages/cli/api/theme-edit/theme-open-state-drawn.test.mjs b/packages/cli/api/theme-edit/theme-open-state-drawn.test.mjs new file mode 100644 index 0000000000000..68cc358f7cf57 --- /dev/null +++ b/packages/cli/api/theme-edit/theme-open-state-drawn.test.mjs @@ -0,0 +1,82 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * A part Core marks open (aria-expanded) is drawn open, so its open state + * is one set names: a dropdown menu's submenu row while its flyout is + * open, and a top nav's menu trigger while its menu is. Against real + * bundled base themes. + */ + +import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import {themeEditHow, themeEditNew, themeEditSet} from './theme-edit.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import {FIXTURE_PACKAGES} from '../../test-utils/base-theme-fixture.mjs'; +import {installRealBaseThemes} from '../../test-utils/real-base-themes.mjs'; + +vi.mock('./_preview.mjs', async importOriginal => + (await import('../../test-utils/theme-render-stub.mjs')).stubRenders( + await importOriginal(), + ), +); + +/** @type {string} */ +let cwd; + +/** Why a bundled theme could not be built here, when it could not. */ +let unbuilt = ''; + +beforeAll(async () => { + cwd = makeLinkedFixture('astryx-theme-open-state-drawn-', FIXTURE_PACKAGES); + unbuilt = await installRealBaseThemes(cwd, ['neutral']); +}, 300_000); + +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +/** @param {import('vitest').TestContext} ctx */ +const needBases = ctx => { + if (!unbuilt) return false; + console.warn(`skipped: ${unbuilt}`); + ctx.skip(); + return true; +}; + +/** @param {string} q @param {string} theme */ +const answer = async (q, theme) => { + const {data} = await themeEditHow(q, {cwd, theme}); + return { + parts: data.understood?.parts ?? [], + writes: (data.results ?? []) + .flatMap((/** @type {any} */ r) => r.commands) + .filter((/** @type {string} */ c) => / editor set /.test(c)) + .map((/** @type {string} */ c) => c.replace(/^.*? editor /, '')), + text: (data.results ?? []).map((/** @type {any} */ r) => r.text).join('\n'), + }; +}; + +describe('a part drawn open', () => { + it('takes --state expanded on a submenu row and a top nav menu', async ctx => { + if (needBases(ctx)) return; + await themeEditNew('o', {cwd, like: 'neutral'}); + expect( + (await answer('make the open top nav menu blue', 'o')).writes, + ).toContain( + "set o background-color '#2563eb' --on top-nav-menu --state expanded", + ); + for (const on of ['dropdown-menu-item', 'top-nav-menu']) + await themeEditSet('o', 'background-color', '#2563eb', { + cwd, + on, + state: 'expanded', + }); + const css = fs.readFileSync(path.join(cwd, 'themes', 'o', 'o.css'), 'utf8'); + for (const on of ['dropdown-menu-item', 'top-nav-menu']) + expect(css).toContain(`.astryx-${on}:is([aria-expanded="true"])`); + }, 240_000); +}); diff --git a/packages/cli/api/theme-edit/theme-options-written-loosely-words.test.mjs b/packages/cli/api/theme-edit/theme-options-written-loosely-words.test.mjs index 01d53a47d4967..4c31a2a325ff1 100644 --- a/packages/cli/api/theme-edit/theme-options-written-loosely-words.test.mjs +++ b/packages/cli/api/theme-edit/theme-options-written-loosely-words.test.mjs @@ -229,8 +229,8 @@ describe('options written loosely', () => { expect(r.suggestions[0].name, args.join(' ')).toMatch(want); expect((await follow(r.suggestions[0].name)).error).toBeUndefined(); } - // The undo line is checked as undo checks it: --only does not fit - // card, so the line that works leaves it out. + // The undo line is checked as undo checks it: --only on card, a part + // styled on its own already, is taken, so the line keeps it. const u = await cli([ ...ED, 'undo', @@ -241,7 +241,9 @@ describe('options written loosely', () => { '--olny', ]); expect(u.error).toContain('did you mean --only?'); - expect(u.suggestions[0].name).toMatch(/ editor undo t border --on card$/); + expect(u.suggestions[0].name).toMatch( + / editor undo t border --on card --only$/, + ); }, T, ); diff --git a/packages/cli/api/theme-edit/theme-part-states-marked.test.mjs b/packages/cli/api/theme-edit/theme-part-states-marked.test.mjs new file mode 100644 index 0000000000000..2bfe8be299812 --- /dev/null +++ b/packages/cli/api/theme-edit/theme-part-states-marked.test.mjs @@ -0,0 +1,120 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * The states Core marks on a part's own element are the part's to set: a + * list item's selected state (its rows ride an Item), a checkbox's or + * radio's hover shown from the part holding its input, and a container's + * state named on the part inside it that has it (a pagination's current + * page). Against real bundled base themes. + */ + +import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import {themeEditHow, themeEditNew, themeEditSet} from './theme-edit.mjs'; +import {refusal} from '../../test-utils/theme-edit-fixture.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import {FIXTURE_PACKAGES} from '../../test-utils/base-theme-fixture.mjs'; +import {installRealBaseThemes} from '../../test-utils/real-base-themes.mjs'; + +vi.mock('./_preview.mjs', async importOriginal => + (await import('../../test-utils/theme-render-stub.mjs')).stubRenders( + await importOriginal(), + ), +); + +/** @type {string} */ +let cwd; + +/** Why a bundled theme could not be built here, when it could not. */ +let unbuilt = ''; + +beforeAll(async () => { + cwd = makeLinkedFixture('astryx-theme-part-states-marked-', FIXTURE_PACKAGES); + unbuilt = await installRealBaseThemes(cwd, ['neutral']); +}, 300_000); + +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +/** @param {import('vitest').TestContext} ctx */ +const needBases = ctx => { + if (!unbuilt) return false; + console.warn(`skipped: ${unbuilt}`); + ctx.skip(); + return true; +}; + +/** @param {string} q @param {string} theme */ +const answer = async (q, theme) => { + const {data} = await themeEditHow(q, {cwd, theme}); + return { + parts: data.understood?.parts ?? [], + writes: (data.results ?? []) + .flatMap((/** @type {any} */ r) => r.commands) + .filter((/** @type {string} */ c) => / editor set /.test(c)) + .map((/** @type {string} */ c) => c.replace(/^.*? editor /, '')), + text: (data.results ?? []).map((/** @type {any} */ r) => r.text).join('\n'), + }; +}; + +describe('states Core marks on a part', () => { + it("takes a list item's selected state", async ctx => { + if (needBases(ctx)) return; + await themeEditNew('l', {cwd, like: 'neutral'}); + expect((await answer('selected list items blue', 'l')).writes).toContain( + "set l background-color '#2563eb' --on list-item --state selected", + ); + await themeEditSet('l', 'background-color', '#2563eb', { + cwd, + on: 'list-item', + state: 'selected', + }); + const css = fs.readFileSync(path.join(cwd, 'themes', 'l', 'l.css'), 'utf8'); + expect(css).toMatch(/\.astryx-list-item\[data-selected="selected"\]/); + }, 240_000); + + it("shows a checkbox's or radio's hover from the part holding its input", async ctx => { + if (needBases(ctx)) return; + await themeEditNew('h', {cwd, like: 'neutral'}); + await themeEditSet('h', 'background-color', '#dc2626', { + cwd, + on: 'checkbox-indicator', + state: 'hover', + only: true, + }); + await themeEditSet('h', 'background-color', '#dc2626', { + cwd, + on: 'radio-indicator', + state: 'hover', + only: true, + }); + const css = fs.readFileSync(path.join(cwd, 'themes', 'h', 'h.css'), 'utf8'); + expect(css).toMatch( + /\.astryx-checkbox-indicator:where\(\.astryx-checkbox-input:hover \*\)/, + ); + expect(css).toMatch( + /\.astryx-radio-indicator:where\(\.astryx-[\w-]+:hover \*\)/, + ); + }, 240_000); + + it("names a container's state on the part inside it that has it", async ctx => { + if (needBases(ctx)) return; + await themeEditNew('p', {cwd, like: 'neutral'}); + const r = await refusal(() => + themeEditSet('p', 'background-color', '#2563eb', { + cwd, + on: 'pagination', + state: 'selected', + }), + ); + expect(r.code).toBe('ERR_THEME_UNKNOWN_STATE'); + // (Its own cell first; the Button the cell is drawn on has it too.) + expect(r.message).toMatch(/ pagination-item(?:, [a-z-]+)* ha(?:s|ve) it\./); + expect(r.run[0]).toMatch(/ --on pagination-item --state selected$/); + }, 240_000); +}); diff --git a/packages/cli/api/theme-edit/theme-pictures-fit-cut-text.test.mjs b/packages/cli/api/theme-edit/theme-pictures-fit-cut-text.test.mjs index 2cf5205d8e702..6110a3715bd4e 100644 --- a/packages/cli/api/theme-edit/theme-pictures-fit-cut-text.test.mjs +++ b/packages/cli/api/theme-edit/theme-pictures-fit-cut-text.test.mjs @@ -70,7 +70,7 @@ describe('text a part cuts when narrow', () => { const clipped = item(240, [{scroll: 400, client: 100, ellipsis: false}]); const whole = item(240, [{scroll: 80, client: 80, ellipsis: true}]); run([stepper, wide, clipped, whole]); - expect(stepper.style.minWidth).toBe('280px'); + expect(stepper.style.minWidth).toBe('281px'); // Never past the sheet's content box: the cell's padding and border fit // inside it. expect(wide.style.minWidth).toBe('1150px'); diff --git a/packages/cli/api/theme-edit/theme-pictures-open-layers-samples.test.mjs b/packages/cli/api/theme-edit/theme-pictures-open-layers-samples.test.mjs new file mode 100644 index 0000000000000..396784bb19af4 --- /dev/null +++ b/packages/cli/api/theme-edit/theme-pictures-open-layers-samples.test.mjs @@ -0,0 +1,134 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file What the pictures draw: a doc sample's plain HTML text control as + * the Astryx control for it; a submenu's flyout once, beside the menu it + * opens from; a part drawn pressed at the moment of its press; a command + * palette with an item highlighted; and a navigation drawer's panel held + * in its cell. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import {afterAll, beforeAll, describe, expect, it} from 'vitest'; +import {themeEditNew, themeEditShow} from './theme-edit.mjs'; +import {context} from './_context.mjs'; +import {showcaseItems} from './_preview.mjs'; +import {OPEN_SCENES, SHEET_CSS} from './_catalog.mjs'; +import {SETTLE_ANIMATIONS} from '../../foundation/render/picture-window.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import { + FIXTURE_PACKAGES, + writeFixtureBaseTheme, +} from '../../test-utils/base-theme-fixture.mjs'; +import {realRenders} from '../../test-utils/theme-render-stub.mjs'; + +// Its assertions read the drawn open states page. +realRenders(true); + +const T = 300_000; + +/** @type {string} */ +let cwd; + +beforeAll(async () => { + cwd = makeLinkedFixture( + 'astryx-theme-open-layers-samples-', + FIXTURE_PACKAGES, + ); + writeFixtureBaseTheme(cwd, 'neutral'); + await themeEditNew('t', {cwd, like: 'neutral'}); +}, T); + +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +/** + * The cell of a part on a sheet page, light mode only. + * @param {string} html + * @param {string} name + */ +function cell(html, name) { + const at = html.indexOf(`
${name}
`); + if (at < 0) return ''; + const end = html.indexOf('
{ + it('draws a plain HTML text control as the Astryx control for it', async () => { + const {project} = await context(cwd); + const field = showcaseItems(project, 'inputs').items.find( + it => it.name === 'Field', + ); + const tree = JSON.stringify(field?.tree); + expect(tree).toContain('"__element":"TextInput"'); + expect(tree).toContain('"isLabelHidden":true'); + expect(tree).not.toContain('"__element":"input"'); + }); +}); + +describe('a part drawn pressed', () => { + it('holds its press animation at the start, and finishes every other', () => { + class CSSAnimation { + /** @param {boolean} pressed */ + constructor(pressed) { + this.pressed = pressed; + this.currentTime = 0; + this.state = 'running'; + this.effect = { + getComputedTiming: () => ({iterations: 1, duration: 200}), + getTiming: () => ({delay: 0}), + target: {closest: () => (pressed ? {} : null)}, + }; + } + pause() { + this.state = 'paused'; + } + finish() { + this.state = 'finished'; + } + } + const press = new CSSAnimation(true); + const fade = new CSSAnimation(false); + const document = {getAnimations: () => [press, fade]}; + new Function('document', 'CSSAnimation', SETTLE_ANIMATIONS)( + document, + CSSAnimation, + ); + expect(press.state).toBe('paused'); + expect(press.currentTime).toBe(0); + expect(fade.state).toBe('finished'); + }); +}); + +describe('the open states page', () => { + it( + 'draws a flyout once beside its menu, a highlighted palette item, and a drawer held in its cell', + async () => { + expect(OPEN_SCENES.some(s => s.name === 'CommandPalette')).toBe(true); + expect(SHEET_CSS).toContain( + '.cs-cell dialog > *{max-width:100%!important;position:relative!important;inset:auto!important}', + ); + await themeEditShow('t', {cwd, section: 'overlays'}); + const html = fs.readFileSync( + path.join(cwd, 'themes/t/sheet-overlays.html'), + 'utf8', + ); + const sub = cell(html, 'DropdownMenu submenu'); + expect(sub.match(/data-astryx-layer-nest=""/g)).toHaveLength(1); + // The parent menu and its flyout, each once. + expect(sub.match(/role="menu"/g)).toHaveLength(2); + expect(cell(html, 'CommandPalette highlighted')).toContain( + 'data-highlighted="highlighted"', + ); + }, + T, + ); +}); diff --git a/packages/cli/api/theme-edit/theme-pictures-whole-page.test.mjs b/packages/cli/api/theme-edit/theme-pictures-whole-page.test.mjs new file mode 100644 index 0000000000000..ffc91b3ebe5b1 --- /dev/null +++ b/packages/cli/api/theme-edit/theme-pictures-whole-page.test.mjs @@ -0,0 +1,135 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file Each picture shows its whole page: a page laid out wider than the + * window is pictured to its width; a navigation drawer that draws nothing + * closed has no cell on any page; an overlay drawn after its part sits + * under the control that opens it; and text cut by less than a pixel gets + * its room too. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import {afterAll, beforeAll, describe, expect, it} from 'vitest'; +import {themeEditNew} from './theme-edit.mjs'; +import {context} from './_context.mjs'; +import {showcaseItems} from './_preview.mjs'; +import { + FIT_CELLS, + PLACE_LAYERS, +} from '../../foundation/render/picture-window.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import { + FIXTURE_PACKAGES, + writeFixtureBaseTheme, +} from '../../test-utils/base-theme-fixture.mjs'; + +const T = 240_000; +const render = path.resolve(import.meta.dirname, '../../foundation/render'); + +/** @type {string} */ +let cwd; + +beforeAll(async () => { + cwd = makeLinkedFixture( + 'astryx-theme-pictures-whole-page-', + FIXTURE_PACKAGES, + ); + writeFixtureBaseTheme(cwd, 'neutral'); + await themeEditNew('t', {cwd, like: 'neutral'}); +}, T); + +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +describe('a picture', () => { + it('takes the page to its own width when it is wider than the window', () => { + expect( + fs.readFileSync(path.join(render, 'picture-chrome.mjs'), 'utf8'), + ).toContain('width: Math.max(PICTURE_WINDOW.width, Math.ceil(size.width))'); + expect( + fs.readFileSync(path.join(render, 'picture-playwright.mjs'), 'utf8'), + ).toContain('fullPage: true'); + }); +}); + +describe('a navigation drawer', () => { + it( + 'has no closed cell on its own family page either', + async () => { + const {project} = await context(cwd); + const names = showcaseItems(project, 'navigation').items.map(i => i.name); + expect(names).not.toContain('MobileNav'); + expect(names.length).toBeGreaterThan(0); + }, + T, + ); +}); + +describe('an overlay drawn after its part', () => { + it('moves under its opener, as far as its item has room', () => { + const rect = (/** @type {number} */ left, /** @type {number} */ right) => ({ + left, + right, + }); + /** @type {Record} */ + const set = {}; + const opener = { + getAttribute: () => 'menu-1', + closest: () => null, + getBoundingClientRect: () => rect(300, 360), + }; + const item = { + querySelectorAll: () => [opener], + getBoundingClientRect: () => rect(0, 500), + }; + const layer = { + id: '', + parentElement: {closest: () => null}, + closest: () => item, + contains: () => false, + querySelectorAll: () => [{id: 'menu-1'}], + getBoundingClientRect: () => rect(0, 260), + style: { + setProperty: (/** @type {string} */ k, /** @type {string} */ v) => + (set[k] = v), + }, + }; + const document = {querySelectorAll: () => [layer]}; + new Function('document', PLACE_LAYERS)(document); + // Under the opener would be 300px along; the item has 240px of room. + expect(set['margin-inline-start']).toBe('240px'); + }); +}); + +describe('text cut by less than a pixel', () => { + it('gets its room too', () => { + const self = { + style: /** @type {Record} */ ({}), + getBoundingClientRect: () => ({ + width: Math.max(240, parseFloat(self.style.minWidth ?? '0') || 0), + }), + closest: () => ({clientWidth: 1200}), + querySelectorAll: () => [ + { + scrollWidth: 101, + get clientWidth() { + return Math.min( + 101, + 100 + (self.getBoundingClientRect().width - 240), + ); + }, + }, + ], + }; + new Function('document', 'getComputedStyle', FIT_CELLS)( + {querySelectorAll: () => [self]}, + () => ({textOverflow: 'ellipsis'}), + ); + expect(self.style.minWidth).toBe('242px'); + }); +}); diff --git a/packages/cli/api/theme-edit/theme-refusal-runs-label-swapped.test.mjs b/packages/cli/api/theme-edit/theme-refusal-runs-label-swapped.test.mjs index 05a8cf9ff5b53..4223eabaae79e 100644 --- a/packages/cli/api/theme-edit/theme-refusal-runs-label-swapped.test.mjs +++ b/packages/cli/api/theme-edit/theme-refusal-runs-label-swapped.test.mjs @@ -362,9 +362,9 @@ describe('pasted lines', () => { ); }); -describe('dropping --only', () => { +describe('--only on a part styled on its own already', () => { it( - 'keeps every other scope flag', + 'is taken with every other scope flag', async () => { const r = await editor([ 'set', @@ -379,9 +379,15 @@ describe('dropping --only', () => { 'dark', '--only', ]); - expect(lines(r.env)[0]).toBe( - 'set t background-color red --on card --when variant:muted --mode dark', - ); + // --only on a part styled on its own already is taken, and every + // other scope flag with it. + expect(r.env.error).toBeUndefined(); + expect(r.env.data.setting).toMatchObject({ + on: 'card', + when: 'variant:muted', + mode: 'dark', + }); + expect(r.env.data.setting.only).toBeUndefined(); }, T, ); diff --git a/packages/cli/api/theme-edit/theme-rows-and-product-words.test.mjs b/packages/cli/api/theme-edit/theme-rows-and-product-words.test.mjs new file mode 100644 index 0000000000000..1a1a9859a541a --- /dev/null +++ b/packages/cli/api/theme-edit/theme-rows-and-product-words.test.mjs @@ -0,0 +1,124 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * Rows said of a part that holds no table rows are that part's own rows + * ("menus with 32px rows" sizes the menu items, never the table rows), and + * a part word right before a noun the editor knows as nothing begins a + * compound subject ("a radio station", "a card game"), which is named and + * never written as the part. Against real bundled base themes. + */ + +import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest'; +import {themeEditHow, themeEditNew} from './theme-edit.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import {FIXTURE_PACKAGES} from '../../test-utils/base-theme-fixture.mjs'; +import {installRealBaseThemes} from '../../test-utils/real-base-themes.mjs'; + +vi.mock('./_preview.mjs', async importOriginal => + (await import('../../test-utils/theme-render-stub.mjs')).stubRenders( + await importOriginal(), + ), +); + +/** @type {string} */ +let cwd; + +/** Why a bundled theme could not be built here, when it could not. */ +let unbuilt = ''; + +beforeAll(async () => { + cwd = makeLinkedFixture( + 'astryx-theme-rows-and-product-words-', + FIXTURE_PACKAGES, + ); + unbuilt = await installRealBaseThemes(cwd, ['neutral']); +}, 300_000); + +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +/** @param {import('vitest').TestContext} ctx */ +const needBases = ctx => { + if (!unbuilt) return false; + console.warn(`skipped: ${unbuilt}`); + ctx.skip(); + return true; +}; + +/** @param {string} q @param {string} theme */ +const answer = async (q, theme) => { + const {data} = await themeEditHow(q, {cwd, theme}); + return { + parts: data.understood?.parts ?? [], + writes: (data.results ?? []) + .flatMap((/** @type {any} */ r) => r.commands) + .filter((/** @type {string} */ c) => / editor set /.test(c)) + .map((/** @type {string} */ c) => c.replace(/^.*? editor /, '')), + text: (data.results ?? []).map((/** @type {any} */ r) => r.text).join('\n'), + }; +}; + +describe("a part's rows and a product's words", () => { + it('reads rows as the rows of the part named', async ctx => { + if (needBases(ctx)) return; + await themeEditNew('r', {cwd, like: 'neutral'}); + const menus = await answer('menus with 32px rows', 'r'); + expect(menus.parts).toContain('dropdown-menu-item'); + expect(menus.parts).not.toContain('table-row'); + expect(menus.writes.join('\n')).not.toMatch(/--on table-row/); + // (Rows alone, or a table's, are still the table's.) + expect((await answer('make the table rows 40px tall', 'r')).parts).toEqual([ + 'table-row', + ]); + }, 240_000); + + it('reads a part word before an unknown noun as a compound subject', async ctx => { + if (needBases(ctx)) return; + await themeEditNew('s', {cwd, like: 'neutral'}); + const site = await answer( + 'podcast and radio station site: heavy headings, accent #c2410c, cream page', + 's', + ); + expect(site.parts).not.toContain('radio-indicator'); + expect(site.writes.join('\n')).not.toMatch(/radio-indicator/); + // (The part named as a part is still that part.) + expect((await answer('make the radio buttons bold', 's')).parts).toEqual([ + 'radio-indicator', + ]); + }, 240_000); + + it.each([ + // [ask, the parts read, a compound named, if any] + ['make the radio buttons bold', ['radio-indicator'], null], + ['make the button text bigger', ['button'], null], + ['make the card border red', ['card'], null], + ['radio station app: rounder corners', [], 'radio station'], + ['button factory app: rounder corners', [], 'button factory'], + ['card game app: rounded corners', [], 'card game'], + // (A part with one unknown word after it, and nothing more, keeps the + // part: the word is no compound's noun.) + ['buttons chunky', ['button'], null], + ['header sticky', ['app-shell-header'], null], + ])('%s', async (ask, parts, compound) => { + // (The bundled theme the cases above made; skipped with them.) + if (unbuilt) return; + const {data} = await themeEditHow(ask, {cwd, theme: 's'}); + expect(data.understood?.parts ?? []).toEqual(parts); + const text = (data.results ?? []) + .map((/** @type {any} */ r) => r.text) + .join('\n'); + const writes = (data.results ?? []) + .flatMap((/** @type {any} */ r) => r.commands) + .filter((/** @type {string} */ c) => / editor set /.test(c)); + if (compound) { + expect(text).toContain(`no part is called "${compound}"`); + expect(writes).toEqual([]); + } else if (ask.split(' ').length > 2) + expect(writes.length).toBeGreaterThan(0); + else expect(text).not.toMatch(/no part is called/); + }); +}); diff --git a/packages/cli/api/theme-edit/theme-state-fill-text-scope.test.mjs b/packages/cli/api/theme-edit/theme-state-fill-text-scope.test.mjs new file mode 100644 index 0000000000000..10ccd6cdce54a --- /dev/null +++ b/packages/cli/api/theme-edit/theme-state-fill-text-scope.test.mjs @@ -0,0 +1,101 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file A fill set for a state is measured against the text that state + * draws, in its own variant: a part that draws no text (a switch's track, + * a tab's underline) has none to measure, and a primary button's hover + * fill is measured against the primary button's own text, not another + * variant's. A page change that leaves the loading placeholder as faint as + * the base drew it makes no new problem of it. + */ + +import {afterAll, beforeAll, describe, expect, it} from 'vitest'; +import {themeEditNew, themeEditSet} from './theme-edit.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import { + FIXTURE_PACKAGES, + writeFixtureBaseTheme, +} from '../../test-utils/base-theme-fixture.mjs'; +import {installRealBaseThemes} from '../../test-utils/real-base-themes.mjs'; + +const T = 400_000; +/** @type {string} */ +let cwd; +/** Why the real neutral could not be installed here, or ''. */ +let unbuilt = ''; +beforeAll(async () => { + cwd = makeLinkedFixture('astryx-theme-state-fill-text-', FIXTURE_PACKAGES); + writeFixtureBaseTheme(cwd, 'neutral'); + unbuilt = await installRealBaseThemes(cwd, ['neutral']); + await themeEditNew('t', {cwd, like: 'neutral'}); +}, T); +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +/** @param {any} r @param {RegExp} re */ +const newOf = (r, re) => + r.data.newProblems.filter((/** @type {any} */ p) => re.test(p.problem)); + +describe('a state fill', () => { + it( + 'on a part that draws no text makes no text problem', + async () => { + const sw = await themeEditSet( + 't', + 'background-color', + 'var(--color-accent)', + { + cwd, + on: 'switch', + state: 'checked', + }, + ); + expect(newOf(sw, /^text in switch\b/)).toEqual([]); + const tab = await themeEditSet('t', 'background-color', '#fd8c73', { + cwd, + on: 'tab-indicator', + state: 'selected', + }); + expect(newOf(tab, /^text in tab-indicator\b/)).toEqual([]); + }, + T, + ); + + it( + "for one variant is measured against that variant's own text", + async () => { + const r = /** @type {any} */ ( + await themeEditSet('t', 'background-color', '#0b5ed7', { + cwd, + on: 'button', + when: 'variant:primary', + state: 'hover', + mode: 'light', + }) + ); + // The primary button's text in light is white on the blue: it reads. + expect(newOf(r, /^text in button\b/)).toEqual([]); + }, + T, + ); +}); + +describe('the loading placeholder', () => { + it( + 'as faint as the base drew it is no new problem after a page change', + async () => { + if (unbuilt) return; + await themeEditNew('p', {cwd, like: 'neutral'}); + const r = await themeEditSet('p', '--color-background-body', '#f2f9ec', { + cwd, + mode: 'light', + }); + expect(newOf(r, /loading placeholder/)).toEqual([]); + }, + T, + ); +}); diff --git a/packages/cli/api/theme-edit/theme-under-input.test.mjs b/packages/cli/api/theme-edit/theme-under-input.test.mjs index 70ff2c7ce38cb..41d475c2b31bc 100644 --- a/packages/cli/api/theme-edit/theme-under-input.test.mjs +++ b/packages/cli/api/theme-edit/theme-under-input.test.mjs @@ -3,13 +3,14 @@ /** * A part drawn under an invisible native input (a checkbox's or radio's * box, a switch) never takes the pointer or the focus: the part data - * records it, and set refuses those states there. Against real bundled - * base themes. + * records it, and set writes those states as the part holding the input + * shows them. Against real bundled base themes. */ +import fs from 'node:fs'; +import path from 'node:path'; import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest'; import {themeEditNew, themeEditSet} from './theme-edit.mjs'; -import {refusal} from '../../test-utils/theme-edit-fixture.mjs'; import { makeLinkedFixture, removeLinkedFixture, @@ -47,7 +48,7 @@ const needBases = ctx => { }; describe('a part under an input', () => { - it('refuses a pointer or focus state there, never on a menu item', async ctx => { + it('takes a pointer or focus state there from the part holding the input', async ctx => { if (needBases(ctx)) return; await themeEditNew('u', {cwd, like: 'neutral'}); for (const [on, state] of [ @@ -55,18 +56,20 @@ describe('a part under an input', () => { ['radio-indicator', 'hover'], ['radio-indicator', 'focus-within'], ['switch', 'hover'], - ]) { - const r = await refusal(() => - themeEditSet('u', 'background-color', '#dc2626', { - cwd, - on, - state, - ...(on === 'switch' ? {} : {only: true}), - }), - ); - expect(r.code, `${on} ${state}`).toBe('ERR_THEME_NO_EFFECT'); - expect(r.message, `${on} ${state}`).toMatch(/invisible input/); - } + ]) + await themeEditSet('u', 'background-color', '#dc2626', { + cwd, + on, + state, + ...(on === 'switch' ? {} : {only: true}), + }); + const css = fs.readFileSync(path.join(cwd, 'themes', 'u', 'u.css'), 'utf8'); + expect(css).toMatch( + /\.astryx-checkbox-indicator:where\(\.astryx-checkbox-input:hover \*\)/, + ); + expect(css).toMatch( + /\.astryx-radio-indicator:where\(\.astryx-[\w-]+:focus-within \*\)/, + ); // (A part with no input over it keeps its hover.) await themeEditSet('u', 'background-color', '#dc2626', { cwd, diff --git a/packages/cli/api/theme-edit/theme-whole-fill-text.test.mjs b/packages/cli/api/theme-edit/theme-whole-fill-text.test.mjs new file mode 100644 index 0000000000000..c30d578518762 --- /dev/null +++ b/packages/cli/api/theme-edit/theme-whole-fill-text.test.mjs @@ -0,0 +1,117 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file A one-mode theme's text color on a part whose own fill is an image + * (a gradient button face) is written for both modes. A region Core draws + * in the other mode (a lightbox, an overlay) keeps that face, so it keeps + * the text on it, and the contrast check measures it that way. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest'; +import {themeEditNew, themeEditSet} from './theme-edit.mjs'; +import { + makeLinkedFixture, + removeLinkedFixture, +} from '../../test-utils/linked-fixture.mjs'; +import { + FIXTURE_PACKAGES, + writeFixtureBaseTheme, +} from '../../test-utils/base-theme-fixture.mjs'; + +vi.mock('./_preview.mjs', async importOriginal => + (await import('../../test-utils/theme-render-stub.mjs')).stubRenders( + await importOriginal(), + ), +); + +/** @type {string} */ +let cwd; + +beforeAll(() => { + cwd = makeLinkedFixture('astryx-theme-whole-fill-', FIXTURE_PACKAGES); + writeFixtureBaseTheme(cwd, 'neutral'); +}, 240_000); + +afterAll(() => { + if (cwd) removeLinkedFixture(cwd); +}); + +const GEL = 'linear-gradient(to bottom, #ffffff, #dedede)'; + +/** @param {string} slug */ +const secondaryRule = slug => { + const src = fs.readFileSync( + path.join(cwd, 'themes', slug, `${slug}.settings.ts`), + 'utf8', + ); + const at = src.indexOf('"variant:secondary"'); + return src.slice(at, src.indexOf('}', src.indexOf('"color"', at)) + 1); +}; + +describe('a text color on an image fill in a one-mode theme', () => { + it('is written for both modes, so a dark media region keeps it', async () => { + await themeEditNew('gel', {cwd, like: 'neutral'}); + await themeEditSet('gel', 'mode', 'light-only', {cwd}); + await themeEditSet('gel', 'background', GEL, { + cwd, + on: 'button', + when: 'variant:secondary', + }); + const r = await themeEditSet('gel', 'color', '#000000', { + cwd, + on: 'button', + when: 'variant:secondary', + mode: 'light', + }); + expect(secondaryRule('gel')).toMatch(/"color": "#000000"/); + expect(secondaryRule('gel')).not.toMatch(/"@light"/); + expect((r.data.problems ?? []).some(p => /lightbox/.test(String(p)))).toBe( + false, + ); + expect(r.data.notes.join(' ')).toMatch( + /own background is the same in both modes, so its light text color is written for both/, + ); + }, 240_000); + + it('keeps the fill-only problem, and its offered line fixes it', async () => { + await themeEditNew('gel2', {cwd, like: 'neutral'}); + await themeEditSet('gel2', 'mode', 'light-only', {cwd}); + const r = await themeEditSet('gel2', 'background', GEL, { + cwd, + on: 'button', + when: 'variant:secondary', + }); + const media = (r.data.newProblems ?? []).find(p => + /lightbox/.test(p.problem), + ); + expect(media?.fix).toMatch( + /set gel2 color '#000000' --on button --when variant:secondary$/, + ); + const fixed = await themeEditSet('gel2', 'color', '#000000', { + cwd, + on: 'button', + when: 'variant:secondary', + }); + expect( + (fixed.data.problems ?? []).some(p => /lightbox/.test(String(p))), + ).toBe(false); + }, 240_000); + + it('leaves a two-mode theme writing the color for its mode only', async () => { + await themeEditNew('two', {cwd, like: 'neutral'}); + await themeEditSet('two', 'background', GEL, { + cwd, + on: 'button', + when: 'variant:secondary', + }); + await themeEditSet('two', 'color', '#000000', { + cwd, + on: 'button', + when: 'variant:secondary', + mode: 'light', + }); + expect(secondaryRule('two')).toMatch(/"@light": \{\s*"color": "#000000"/); + }, 240_000); +}); diff --git a/packages/cli/clients/cli/commands/experimental-theme-editor-show.doc.mjs b/packages/cli/clients/cli/commands/experimental-theme-editor-show.doc.mjs index d174a73b25691..7339db19c9088 100644 --- a/packages/cli/clients/cli/commands/experimental-theme-editor-show.doc.mjs +++ b/packages/cli/clients/cli/commands/experimental-theme-editor-show.doc.mjs @@ -32,7 +32,7 @@ export const doc = { flag: '--png', param: 'options.png', description: - "Also take PNG pictures of the previews (light and dark): preview.png, the sample page, and sheet-overlays.png, each control at rest, hovered, focused and pressed at its top, then every menu, tooltip, popover and list drawn open (from sheet-overlays.html, which it writes too; a file of yours by that name is left alone and the picture not taken) (show adds a picture of each family of components the theme sets a part of with --on, or of the buttons when it sets none: sheet-.png, from the sheet-.html it writes beside the full sheet; the families are actions, inputs, selection, navigation, feedback, data and containers, and a family taller than 1600px is cut into pictures of at most that height, in order (sheet--1.png, -2 …), so each reads whole. With --section, that section's picture is taken in their place, so --section --png pictures any other family. sheet.html, every component, is written but not pictured; the open states are taken with a section too), with no dev server running: it needs a Playwright installed in the project or a Chrome or Chromium found on the machine, and adds a few seconds while the browser starts (a browser that takes longer than 60 seconds, plus 20 seconds for each picture after the first, is stopped, and the result says so); without one, the result says how to get it. Each picture carries the editor stamp and is recorded, by name and content, in themes//.pictures.json; a file of yours named like a picture (preview.png, sheet-overlays.png) is never written over: no picture is taken, and the result names the file. Taking pictures changes nothing in the app, except that show first brings the app copy (src/themes//) and an in-app preview up to date after a hand edit to .theme.ts", + "Also take PNG pictures of the previews (light and dark): preview.png, the sample page, and sheet-overlays.png, each control at rest, hovered, focused and pressed at its top, then every menu, tooltip, popover and list drawn open (from sheet-overlays.html, which it writes too; a file of yours by that name is left alone and the picture not taken) (show adds a picture of each family of components the theme sets a part of with --on, or of the buttons when it sets none: sheet-.png, from the sheet-.html it writes beside the full sheet; the families are actions, inputs, selection, navigation, feedback, data and containers, and a family taller than 1600px is cut between rows of parts into pictures of about that height (a row taller than that is a picture of its own), in order (sheet--1.png, -2 …), so each reads whole. With --section, that section's picture is taken in their place, so --section --png pictures any other family. sheet.html, every component, is written but not pictured; the open states are taken with a section too), with no dev server running: it needs a Playwright installed in the project or a Chrome or Chromium found on the machine, and adds a few seconds while the browser starts (a browser that takes longer than 60 seconds, plus 20 seconds for each picture after the first, is stopped, and the result says so); without one, the result says how to get it. Each picture carries the editor stamp and is recorded, by name and content, in themes//.pictures.json; a file of yours named like a picture (preview.png, sheet-overlays.png) is never written over: no picture is taken, and the result names the file. Taking pictures changes nothing in the app, except that show first brings the app copy (src/themes//) and an in-app preview up to date after a hand edit to .theme.ts", }, ], examples: [ diff --git a/packages/cli/foundation/render/layers.mjs b/packages/cli/foundation/render/layers.mjs index b134f43976b96..503475091eed6 100644 --- a/packages/cli/foundation/render/layers.mjs +++ b/packages/cli/foundation/render/layers.mjs @@ -151,7 +151,8 @@ export {desktopMatches} from './picture-window.mjs'; * on each one an opened overlay holds (a submenu's row), and a typed letter * in each combobox field that a press leaves closed. A drawing that opened * nothing and holds a layer is right-clicked (a context menu). Each overlay - * is kept once, as it was when it opened. + * is kept once, as it was when it opened; a control on the page that opens + * keeps the drawn part with it open, without its overlays. * @param {any} host the element the page was drawn in * @param {(fn: () => void) => void} flushSync * @returns {Promise} @@ -243,6 +244,26 @@ export async function openLayerMarkup(host, flushSync) { } await tick(); keep(); + // A control the page itself draws (a top nav's menu trigger, outside + // every overlay) shows its open state only on the page: the part as + // drawn now, with that control open and without its overlays, is kept + // too. + if ( + control.getAttribute('aria-expanded') === 'true' && + !control.closest('[data-astryx-layer-root]') + ) { + const part = host.cloneNode(true); + for (const layer of part.querySelectorAll('[data-astryx-layer-root]')) + layer.remove(); + const html = String(part.innerHTML).replace( + /