Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/37435-option-color-renders-neutral.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/lint': patch
---

feat(lint): warn when a select option `color` renders neutral on the option badge

Clause-②: no
Metadata-protocol: none

A new warning, `field/option-color-renders-neutral`. An option is coloured only by the colour its author declares, and the option badge paints exactly two spellings: one of the nine palette families (`gray`, `red`, `orange`, `yellow`, `green`, `blue`, `indigo`, `purple`, `pink`, lowercase) or a `#rgb` / `#rrggbb` hex. Any other declared colour (`teal`, `amber`, `Red`, `rgb(…)`, `#rrggbbaa`, a hex with no `#`) rendered neutral grey with no signal. It now draws a warning naming the option and a fix line: the lowercase family or the `#`-prefixed / alpha-free hex when the value points at one, otherwise the families and the hex form.

It runs on `os validate`, `os build` and `os lint` over object fields, object-extension fields, picklists and picklist extensions, and at the metadata save door on `object` and `object_extension` writes, where it rides back as an advisory. Nothing is refused: `SelectOption.color` still accepts any string, and charts and gantt bars still paint a CSS colour name. `os lint --strict` fails on it, as on every warning. `os explain field/option-color-renders-neutral` gives the per-surface reading. Published from the root entry: `FIELD_OPTION_COLOR_RENDERS_NEUTRAL`, `OPTION_COLOR_FAMILIES`, `isBadgePaintableOptionColor`, `lintOptionColors` and the type `OptionColorPicklist`.
2 changes: 1 addition & 1 deletion content/docs/deployment/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines
→ Normalizing stack definition...
→ Lowering inline handlers...
→ Validating protocol compliance...
→ Running author-time rules (86)...
→ Running author-time rules (87)...
→ Checking that every required capability has a provider installable in this edition...
→ Collecting package docs (ADR-0046)... 0 collected
→ Writing artifact...
Expand Down
2 changes: 1 addition & 1 deletion content/docs/deployment/validating-metadata.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -870,7 +870,7 @@ A clean run walks the registry and reports timing:
Config: /path/to/support-desk/objectstack.config.ts
Load time: 21ms
→ Validating against ObjectStack Protocol...
→ Running author-time rules (86)...
→ Running author-time rules (87)...
→ Checking that every required capability has a provider installable in this edition...
→ Checking package docs (ADR-0046)...

Expand Down
2 changes: 1 addition & 1 deletion content/docs/getting-started/build-with-claude-code.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ visible: 'status != "resolved"'
◆ Validate
────────────────────────────────────────
→ Validating against ObjectStack Protocol...
→ Running author-time rules (86)...
→ Running author-time rules (87)...

✗ Author-time rules failed (1 issue)
• stack · action 'resolve_ticket' visible: bare reference `status` — a
Expand Down
2 changes: 1 addition & 1 deletion content/docs/ui/react-pages.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ objectstack validate
────────────────────────────────────────
→ Loading configuration...
→ Validating against ObjectStack Protocol...
→ Running author-time rules (86)...
→ Running author-time rules (87)...
→ Checking that every required capability has a provider installable in this edition...
→ Checking package docs (ADR-0046)...

Expand Down
58 changes: 58 additions & 0 deletions packages/lint/src/authoring-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,9 @@ import {
lintLegacyOrganizationComposites,
lintInlineEditBulk,
lintFieldReferenceShapes,
lintOptionColors,
summaryRollupFindings,
type OptionColorPicklist,
} from './data-model-rules.js';
import { objectExtensionsByTarget, objectsAsServed } from './object-graph.js';

Expand Down Expand Up @@ -2742,6 +2744,62 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [
);
},
},
// A select option `color` the option badge renders neutral
// (`field/option-color-renders-neutral`): since the ruling on
// objectstack#36882 (option A) an option is coloured only by its declared
// colour, and a declared colour outside the nine palette families and the
// `#rgb` / `#rrggbb` hex paints the same neutral grey as no colour at all.
// ADVISORY: `SelectOption.color` stays a free string (charts and gantt hand
// it to the browser as a CSS colour), so nothing is refused.
//
// On the runtime publish gate's `object` and `object_extension` writes,
// where the written entry's own options are the whole input, so the
// differential charges a write only with a colour it declares. This is an
// advisory-tier rule at the object door, and that is this rule's own card's
// crossing, not one of the fenced rules': the fence
// (`RUNTIME_OBJECT_ADVISORY_VOLUME`) prices advisory VOLUME, and this rule
// fires on 0 of the platform's and the examples' declared option colours
// (every one is a family name or a 6-digit hex), so a save hears it only
// when its author wrote a colour that will not paint. `picklist` is not a
// runtime-creatable type, so picklists are judged on the CLI alone.
{
name: 'lintOptionColors',
tier: 'advisory',
input: 'parsed',
commands: ALL,
source: 'packages/lint/src/data-model-rules.ts',
surfaces: CLI_AND_RUNTIME,
runtimeTypes: ['object', 'object_extension'],
run: (stack) => {
const extensions = [...objectExtensionsByTarget(stack).entries()].flatMap(([target, list]) =>
list.map((ext) => ({ target, path: ext.path, fields: ext.fields })),
);
const picklists: OptionColorPicklist[] = [];
const collect = (key: 'picklists' | 'picklistExtensions', nameKey: 'name' | 'extend', noun: string) => {
const entries = (stack as AnyRec)[key];
if (!Array.isArray(entries)) return;
entries.forEach((entry: AnyRec, i: number) => {
const name = typeof entry?.[nameKey] === 'string' ? (entry[nameKey] as string) : '';
if (!name) return;
picklists.push({ name, path: `${key}[${i}]`, where: `${noun} "${name}"`, options: entry.options });
});
};
collect('picklists', 'name', 'picklist');
collect('picklistExtensions', 'extend', 'picklist extension of');
return lintOptionColors(
Array.isArray(stack.objects) ? (stack.objects as unknown[]) : [],
extensions,
picklists,
).map((f) => ({
severity: f.severity === 'suggestion' ? ('info' as const) : f.severity,
rule: f.rule,
where: f.where,
path: f.path,
message: f.message,
hint: f.fix ?? '',
}));
},
},
// Two visible fields of one object served under one label
// (`field-label-duplicate`): the platform's `owner_id` and an author's
// `assignee`, both read as "负责人" by a zh-CN reader, are two columns of one
Expand Down
133 changes: 133 additions & 0 deletions packages/lint/src/data-model-rules.option-color-37435.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

// `field/option-color-renders-neutral`: a select option `color` the option
// badge does not paint (outside the nine palette families and the `#rgb` /
// `#rrggbb` hex) is warned at author time and at the save door, instead of
// rendering neutral grey with no signal. A declared family name and a hex are
// not warned. Advisory only: nothing is refused.

import { describe, expect, it } from 'vitest';

import { authoringRulesFor } from './authoring-rules.js';
import {
FIELD_OPTION_COLOR_RENDERS_NEUTRAL,
OPTION_COLOR_FAMILIES,
isBadgePaintableOptionColor,
lintOptionColors,
} from './data-model-rules.js';
import * as indexBarrel from './index.js';
import { explainRule } from './rule-explanations.js';
import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js';

const stageField = (colors: readonly (string | undefined)[]) => ({
type: 'select',
options: colors.map((color, i) => ({ label: `S${i}`, value: `s${i}`, ...(color === undefined ? {} : { color }) })),
});

const objectWith = (colors: readonly (string | undefined)[]) => [
{ name: 'acme_deal', fields: { stage: stageField(colors) } },
];

const hits = (colors: readonly (string | undefined)[]) =>
lintOptionColors(objectWith(colors)).filter((i) => i.rule === FIELD_OPTION_COLOR_RENDERS_NEUTRAL);

describe('field/option-color-renders-neutral', () => {
it('is published from the root barrel under its constant, with an `os explain` entry', () => {
expect(FIELD_OPTION_COLOR_RENDERS_NEUTRAL).toBe('field/option-color-renders-neutral');
expect(indexBarrel.FIELD_OPTION_COLOR_RENDERS_NEUTRAL).toBe(FIELD_OPTION_COLOR_RENDERS_NEUTRAL);
expect(explainRule(FIELD_OPTION_COLOR_RENDERS_NEUTRAL)?.rule).toBe(FIELD_OPTION_COLOR_RENDERS_NEUTRAL);
});

it('an out-of-family colour name is warned, located at the option, and the fix names the families', () => {
const found = hits(['teal']);
expect(found).toHaveLength(1);
const [issue] = found;
expect(issue).toMatchObject({
severity: 'warning',
rule: FIELD_OPTION_COLOR_RENDERS_NEUTRAL,
path: 'objects[0].fields.stage.options[0].color',
where: `object "acme_deal" · field 'stage' · option 's0'`,
});
expect(issue!.message).toContain("color: 'teal'");
for (const family of OPTION_COLOR_FAMILIES) expect(issue!.fix).toContain(family);
});

it('a declared family name is not warned, nor is a #rgb / #rrggbb hex', () => {
expect(OPTION_COLOR_FAMILIES).toHaveLength(9);
expect(hits([...OPTION_COLOR_FAMILIES])).toEqual([]);
expect(hits(['#14b8a6', '#ABC', '#14B8A6'])).toEqual([]);
});

it('an option with no colour, or an empty one, declares nothing and is not judged', () => {
expect(hits([undefined, '', ' '])).toEqual([]);
});

it('every spelling the badge renders neutral is warned, each with the fix its value points at', () => {
const fixOf = (color: string) => hits([color])[0]?.fix;
expect(fixOf('Red')).toBe("Write the family in lowercase: color: 'red'.");
expect(fixOf('14b8a6')).toBe("Write the hex with a leading #: color: '#14b8a6'.");
expect(fixOf('#14b8a6cc')).toContain("color: '#14b8a6'");
for (const color of ['amber', 'rgb(20, 184, 166)', 'hsl(173 80% 40%)', ' #14b8a6', '#14b8a']) {
expect(isBadgePaintableOptionColor(color), color).toBe(false);
expect(hits([color]), color).toHaveLength(1);
}
});

it('judges object-extension fields and picklists where they are written', () => {
const issues = lintOptionColors(
[],
[{ target: 'acme_deal', path: 'objectExtensions[0]', fields: [{ name: 'tier', ...stageField(['amber']) }] }],
[{ name: 'deal_stage', path: 'picklists[0]', where: 'picklist "deal_stage"', options: [{ label: 'A', value: 'a', color: 'teal' }, { label: 'B', value: 'b', color: 'blue' }] }],
);
expect(issues.map((i) => i.path)).toEqual([
'objectExtensions[0].fields.tier.options[0].color',
'picklists[0].options[0].color',
]);
});

it('runs on all three commands, picklists included, from the registry', () => {
for (const command of ['validate', 'build', 'lint'] as const) {
expect(authoringRulesFor(command).map((r) => r.name), command).toContain('lintOptionColors');
}
const entry = authoringRulesFor('validate').find((r) => r.name === 'lintOptionColors')!;
const findings = entry.run(
{
objects: objectWith(['teal']),
picklists: [{ name: 'deal_stage', label: 'Stage', options: [{ label: 'A', value: 'a', color: 'amber' }] }],
picklistExtensions: [{ extend: 'deal_stage', options: [{ label: 'C', value: 'c', color: 'Red' }] }],
},
{},
);
expect(findings.map((f) => [f.severity, f.path])).toEqual([
['warning', 'objects[0].fields.stage.options[0].color'],
['warning', 'picklists[0].options[0].color'],
['warning', 'picklistExtensions[0].options[0].color'],
]);
});

describe('at the save door (object writes)', () => {
const write = (color: string) => ({
name: 'acme_deal',
label: 'Deal',
sharingModel: 'private',
fields: { stage: stageField([color]) },
});

it('an out-of-family colour name rides back as an advisory and refuses nothing', () => {
expect(runtimeAuthoringRulesFor('object').map((r) => r.name)).toContain('lintOptionColors');
const result = runRuntimeAuthoringRules({ type: 'object', item: write('teal'), context: { objects: [] } });
expect(result.errors).toEqual([]);
const advisories = result.advisories.filter((f) => f.rule === FIELD_OPTION_COLOR_RENDERS_NEUTRAL);
expect(advisories).toHaveLength(1);
expect(advisories[0]).toMatchObject({ severity: 'warning' });
expect(advisories[0]!.hint.length).toBeGreaterThan(0);
});

it('a declared family name and a hex ride back with no advisory', () => {
for (const color of ['red', '#14b8a6']) {
const result = runRuntimeAuthoringRules({ type: 'object', item: write(color), context: { objects: [] } });
expect(result.advisories.filter((f) => f.rule === FIELD_OPTION_COLOR_RENDERS_NEUTRAL), color).toEqual([]);
}
});
});
});
126 changes: 126 additions & 0 deletions packages/lint/src/data-model-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1236,6 +1236,132 @@ export function lintFieldReferenceShapes(
return issues;
}

// ─── Option colours the badge cannot paint ───────────────────────────

/** The rule id an option `color` the option badge renders neutral reports under. */
export const FIELD_OPTION_COLOR_RENDERS_NEUTRAL = 'field/option-color-renders-neutral';

/**
* The palette families an option badge paints by name, exactly as the badge
* renderer spells them (`BADGE_COLOR_MAP` in `ui/packages/fields/src/index.tsx`;
* matched case-sensitively there). This package cannot import the renderer
* (`@objectstack/lint` depends on `@objectstack/spec` alone and runs at the
* kernel's save door), so the list is spelled here: a family added to that map
* is added here in the same change, or this rule warns on a colour that paints.
*/
export const OPTION_COLOR_FAMILIES: readonly string[] = Object.freeze([
'gray', 'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'pink',
]);

const OPTION_COLOR_FAMILY_SET: ReadonlySet<string> = new Set(OPTION_COLOR_FAMILIES);

/** The hex the badge paints: `#` first, then 3 or 6 hex digits (trailing space tolerated, as the renderer trims). */
const BADGE_HEX_RE = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;

/** Does the option badge paint this declared colour (a family name, or a `#rgb` / `#rrggbb` hex)? */
export function isBadgePaintableOptionColor(color: string): boolean {
return OPTION_COLOR_FAMILY_SET.has(color) || (color.charAt(0) === '#' && BADGE_HEX_RE.test(color.trim()));
}

/** The fix line for one unpainted colour: the nearest spelling the author meant, when the value says it. */
function optionColorFix(color: string): string {
const trimmed = color.trim();
const lower = trimmed.toLowerCase();
const families = OPTION_COLOR_FAMILIES.join(', ');
if (OPTION_COLOR_FAMILY_SET.has(lower)) return `Write the family in lowercase: color: '${lower}'.`;
if (/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(trimmed)) {
return `Write the hex with a leading #: color: '#${trimmed.replace(/^#/, '')}'.`;
}
if (/^#[0-9a-f]{8}$/i.test(trimmed)) {
return `Drop the alpha digits: color: '${trimmed.slice(0, 7)}' (the badge paints #rgb and #rrggbb only).`;
}
return `Declare one of the families (${families}) or a #rgb / #rrggbb hex; remove color for a neutral badge.`;
}

/** One picklist (or picklist extension) as {@link lintOptionColors} reads it. */
export interface OptionColorPicklist {
/** The picklist it declares or extends. */
readonly name: string;
/** Its config path, e.g. `picklists[0]` or `picklistExtensions[1]`. */
readonly path: string;
/** Human-readable location, e.g. `picklist "deal_stage"`. */
readonly where: string;
/** Its declared options. */
readonly options: unknown;
}

/**
* A select option `color` the option badge renders neutral
* ({@link FIELD_OPTION_COLOR_RENDERS_NEUTRAL}, `warning`).
*
* An option is coloured if and only if its author declared a colour, and no
* colour is derived from its value (the ruling on objectstack#36882, option
* A). The badge paints a declared colour only when it is one of
* {@link OPTION_COLOR_FAMILIES} or a `#rgb` / `#rrggbb` hex; anything else —
* `teal`, `amber`, `Red`, `rgb(…)`, `#rrggbbaa` — reaches the renderer and
* paints the same neutral grey as an option with no colour, with no signal.
* This rule is that signal, at save. It never refuses: `SelectOption.color`
* stays a free string, and other surfaces (charts, gantt) hand the string to
* the browser as a CSS colour. `os explain field/option-color-renders-neutral`
* gives the per-surface reading.
*
* Reads the inline options of the objects' fields, of the fields object
* extensions add, and of picklists and picklist extensions, each located where
* it is written. An empty or blank `color` declares nothing and is not judged.
*/
export function lintOptionColors(
objects: any[],
extensions: readonly FieldShapeExtension[] = [],
picklists: readonly OptionColorPicklist[] = [],
): LocatedLintIssue[] {
const issues: LocatedLintIssue[] = [];
const judge = (options: unknown, owner: string, optionsPath: string, where: string) => {
if (!Array.isArray(options)) return;
options.forEach((opt: any, j: number) => {
if (!opt || typeof opt !== 'object') return;
const color = opt.color;
if (typeof color !== 'string' || color.trim() === '' || isBadgePaintableOptionColor(color)) return;
const value = typeof opt.value === 'string' || typeof opt.value === 'number' ? String(opt.value) : `#${j}`;
issues.push({
severity: 'warning',
rule: FIELD_OPTION_COLOR_RENDERS_NEUTRAL,
where: `${where} · option '${value}'`,
message:
`${owner} option '${value}' declares color: '${color}', which the option badge does not paint: ` +
'it renders neutral grey, the same as an option with no colour',
path: `${optionsPath}[${j}].color`,
fix: optionColorFix(color),
});
});
};

if (Array.isArray(objects)) {
objects.forEach((obj, i) => {
if (!obj?.name) return;
for (const { name, def } of fieldEntries(obj.fields)) {
if (!def || typeof def !== 'object') continue;
judge(def.options, `field "${obj.name}.${name}"`, `objects[${i}].fields.${name}.options`, fieldWhere(obj, name));
}
});
}
for (const ext of extensions) {
for (const def of ext.fields) {
const name = typeof def?.name === 'string' ? def.name : '';
if (!name) continue;
judge(
def.options,
`field "${ext.target}.${name}"`,
`${ext.path}.fields.${name}.options`,
`object extension of "${ext.target}" · field '${name}'`,
);
}
}
for (const list of picklists) {
judge(list.options, `picklist "${list.name}"`, `${list.path}.options`, list.where);
}
return issues;
}

// ─── Rule engine ────────────────────────────────────────────────────

/**
Expand Down
Loading
Loading