Skip to content

Commit 9548be2

Browse files
feat(lint): warn when a select option colour renders neutral on the option badge (#37986)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoAoNwrZVJoUEFfvMURpRPKJ)_ Fixes #37435 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:搭建者(人或 AI)给下拉选项写了 teal、amber、大写的 Red 这类界面画不出来的颜色时,校验命令和保存时都会收到一条提示,说明这个颜色会显示成灰色、该怎么改;写九个色系名或十六进制色的不受影响。 - 为什么做:上一张卡已经定下"选项颜色只认作者声明、没配就灰",但写错的颜色也会静默变灰,作者不知道自己写错了。 - 出错会怎样:只是提示、从不拒绝保存,误报最多多一条警告;平台和示例里现有的选项颜色没有一条会触发,可直接撤回。 - 要你做的:无。 ## What changes - New advisory rule `field/option-color-renders-neutral` (`lintOptionColors` in `packages/lint/src/data-model-rules.ts`). It warns on a select option `color` the option badge does not paint: anything that is not one of the nine palette families (`gray red orange yellow green blue indigo purple pink`, lowercase, as `BADGE_COLOR_MAP` matches them) and not `#` + 3 or 6 hex digits. The warning names the option; the fix line names the spelling the value already points at (lowercase family, the hex with its `#`, the hex without alpha digits), otherwise the families and the hex form. It never maps a colour name to a family. - Route (a) as a warning, not (b) a name-to-family map: (b) is consumer-side tolerance that invents a colour the author did not pick, close to the value-derived colour ruling A on #36882 removed (「A 全部去掉,没配就灰」). Not a refusal: `SelectOption.color` stays `z.string()`, and charts and gantt bars paint a CSS colour name. - Registered in `AUTHORING_RULES` as `tier: 'advisory'`, on `os validate` / `os build` / `os lint`, and on the runtime publish gate for `object` and `object_extension` writes, where findings ride back as 2xx `advisories` (the save door Studio, REST `/meta` and MCP authors share). Judges object fields, object-extension fields, picklists and picklist extensions; picklists are CLI-only because `picklist` is not runtime-creatable. - `os explain field/option-color-renders-neutral` entry in `rule-explanations.ts`, with the measured per-surface reading. - Root barrel publishes `FIELD_OPTION_COLOR_RENDERS_NEUTRAL`, `OPTION_COLOR_FAMILIES`, `isBadgePaintableOptionColor`, `lintOptionColors`, type `OptionColorPicklist`. - Object and object-extension door roster pins gain the rule (three test files), and the four docs CLI transcripts print 87 author-time rules (`check:docs-transcript-drift`). ## Tests - New pin `packages/lint/src/data-model-rules.option-color-37435.test.ts`: `teal` warned (rule, severity, path, where, fix names all nine families) and `amber`, `Red`, bare hex, alpha hex, `rgb()`, `hsl()`, leading-space hex all warned; every declared family and `#abc` / `#14b8a6` not warned; blank colour not judged; extension and picklist paths; all three commands; at the save door `teal` comes back as an advisory with zero errors, and `red` / a hex with none. ## Acceptance notes - Door crossing: this is an advisory-tier rule at the object door. The five fenced advisory rules (#4716 adjudication, `RUNTIME_OBJECT_ADVISORY_VOLUME`) stay fenced and untouched; that fence prices advisory VOLUME. Measured volume for this rule: 0 firings. Census of option-level colour literals: objectstack at 6e11ff2 (`*.object.ts`, picklists, extensions; non-test) is every one a family name or a 6-digit hex; the only out-of-family names (`teal`, `amber`, 9 sites) are OBJECT-level `color`, which this rule does not read. hotcrm at 08a7451: 170 colour literals, all 6-digit hex. The one out-of-family option colour in the tree is a test fixture (`ui/e2e/list-condition-row-35549.spec.ts:87`, `amber`). - Single source of the family list: `@objectstack/lint` cannot import `@object-ui/fields` (lint depends on spec only and runs in the kernel's save door), and a lint test reading the renderer source would need a `scripts/cross-package-test-inputs.mjs` + `turbo.json` declaration outside this claim's file surface. The list is therefore spelled once in lint (`OPTION_COLOR_FAMILIES`) with a comment naming `BADGE_COLOR_MAP`; the shared home both sides could read is `@objectstack/spec`, left as an open question in the report rather than taken here. - Not judged: a form view's own option list, and an object extension's `fieldPatches`. - The runtime advisory has no localized `userMessage` (no `.user-text.ts` catalog); Studio renders the English `message`. ## Verification - Two-minute check: `pnpm --filter @objectstack/lint exec vitest run src/data-model-rules.option-color-37435.test.ts` → 9 passed. - Read first: `packages/lint/src/data-model-rules.ts` (`isBadgePaintableOptionColor`, must match the renderer's reading), `packages/lint/src/authoring-rules.ts` (the `lintOptionColors` entry and its door comment), `packages/lint/src/rule-explanations.ts` (the per-surface paragraph). <details><summary>Local readings (HEAD after the docs commit)</summary> - `pnpm --filter @objectstack/lint test` → Test Files 244 passed (244), Tests 9816 passed, 5 skipped; `pnpm --filter @objectstack/lint typecheck` (tsc + test layer) green. - Ablation: `isBadgePaintableOptionColor` forced to `true` on disk → 5 of 9 pins red (the out-of-family pin included); restored with `git checkout HEAD`. - `node scripts/pm/overlap-check.mjs --branch=claude/project-thread-ciejge` → `VERDICT clean exit 0`, #37929 (shares `rule-explanations.ts`) merges cleanly. - Derived gate families run locally; `check:dual-build-cjs-loads` and `check-plugin-teardown-shape --self-test` are NOT MEASURED here (no full build; shallow clone) and are left to CI. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibx7DSQZnugnuX8CpCM)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 9d111a7 commit 9548be2

13 files changed

Lines changed: 385 additions & 10 deletions
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/lint': patch
3+
---
4+
5+
feat(lint): warn when a select option `color` renders neutral on the option badge
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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`.

‎content/docs/deployment/cli.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines
937937
→ Normalizing stack definition...
938938
→ Lowering inline handlers...
939939
→ Validating protocol compliance...
940-
→ Running author-time rules (87)...
940+
→ Running author-time rules (88)...
941941
→ Checking that every required capability has a provider installable in this edition...
942942
→ Collecting package docs (ADR-0046)... 0 collected
943943
→ Writing artifact...

‎content/docs/deployment/validating-metadata.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -870,7 +870,7 @@ A clean run walks the registry and reports timing:
870870
Config: /path/to/support-desk/objectstack.config.ts
871871
Load time: 21ms
872872
→ Validating against ObjectStack Protocol...
873-
→ Running author-time rules (87)...
873+
→ Running author-time rules (88)...
874874
→ Checking that every required capability has a provider installable in this edition...
875875
→ Checking package docs (ADR-0046)...
876876

‎content/docs/getting-started/build-with-claude-code.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ visible: 'status != "resolved"'
318318
◆ Validate
319319
────────────────────────────────────────
320320
→ Validating against ObjectStack Protocol...
321-
→ Running author-time rules (87)...
321+
→ Running author-time rules (88)...
322322
323323
✗ Author-time rules failed (1 issue)
324324
• stack · action 'resolve_ticket' visible: bare reference `status` — a

‎content/docs/ui/react-pages.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ objectstack validate
404404
────────────────────────────────────────
405405
→ Loading configuration...
406406
→ Validating against ObjectStack Protocol...
407-
→ Running author-time rules (87)...
407+
→ Running author-time rules (88)...
408408
→ Checking that every required capability has a provider installable in this edition...
409409
→ Checking package docs (ADR-0046)...
410410

‎packages/lint/src/authoring-rules.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,9 @@ import {
186186
lintLegacyOrganizationComposites,
187187
lintInlineEditBulk,
188188
lintFieldReferenceShapes,
189+
lintOptionColors,
189190
summaryRollupFindings,
191+
type OptionColorPicklist,
190192
} from './data-model-rules.js';
191193
import { objectExtensionsByTarget, objectsAsServed } from './object-graph.js';
192194

@@ -2783,6 +2785,62 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [
27832785
);
27842786
},
27852787
},
2788+
// A select option `color` the option badge renders neutral
2789+
// (`field/option-color-renders-neutral`): since the ruling on
2790+
// objectstack#36882 (option A) an option is coloured only by its declared
2791+
// colour, and a declared colour outside the nine palette families and the
2792+
// `#rgb` / `#rrggbb` hex paints the same neutral grey as no colour at all.
2793+
// ADVISORY: `SelectOption.color` stays a free string (charts and gantt hand
2794+
// it to the browser as a CSS colour), so nothing is refused.
2795+
//
2796+
// On the runtime publish gate's `object` and `object_extension` writes,
2797+
// where the written entry's own options are the whole input, so the
2798+
// differential charges a write only with a colour it declares. This is an
2799+
// advisory-tier rule at the object door, and that is this rule's own card's
2800+
// crossing, not one of the fenced rules': the fence
2801+
// (`RUNTIME_OBJECT_ADVISORY_VOLUME`) prices advisory VOLUME, and this rule
2802+
// fires on 0 of the platform's and the examples' declared option colours
2803+
// (every one is a family name or a 6-digit hex), so a save hears it only
2804+
// when its author wrote a colour that will not paint. `picklist` is not a
2805+
// runtime-creatable type, so picklists are judged on the CLI alone.
2806+
{
2807+
name: 'lintOptionColors',
2808+
tier: 'advisory',
2809+
input: 'parsed',
2810+
commands: ALL,
2811+
source: 'packages/lint/src/data-model-rules.ts',
2812+
surfaces: CLI_AND_RUNTIME,
2813+
runtimeTypes: ['object', 'object_extension'],
2814+
run: (stack) => {
2815+
const extensions = [...objectExtensionsByTarget(stack).entries()].flatMap(([target, list]) =>
2816+
list.map((ext) => ({ target, path: ext.path, fields: ext.fields })),
2817+
);
2818+
const picklists: OptionColorPicklist[] = [];
2819+
const collect = (key: 'picklists' | 'picklistExtensions', nameKey: 'name' | 'extend', noun: string) => {
2820+
const entries = (stack as AnyRec)[key];
2821+
if (!Array.isArray(entries)) return;
2822+
entries.forEach((entry: AnyRec, i: number) => {
2823+
const name = typeof entry?.[nameKey] === 'string' ? (entry[nameKey] as string) : '';
2824+
if (!name) return;
2825+
picklists.push({ name, path: `${key}[${i}]`, where: `${noun} "${name}"`, options: entry.options });
2826+
});
2827+
};
2828+
collect('picklists', 'name', 'picklist');
2829+
collect('picklistExtensions', 'extend', 'picklist extension of');
2830+
return lintOptionColors(
2831+
Array.isArray(stack.objects) ? (stack.objects as unknown[]) : [],
2832+
extensions,
2833+
picklists,
2834+
).map((f) => ({
2835+
severity: f.severity === 'suggestion' ? ('info' as const) : f.severity,
2836+
rule: f.rule,
2837+
where: f.where,
2838+
path: f.path,
2839+
message: f.message,
2840+
hint: f.fix ?? '',
2841+
}));
2842+
},
2843+
},
27862844
// Two visible fields of one object served under one label
27872845
// (`field-label-duplicate`): the platform's `owner_id` and an author's
27882846
// `assignee`, both read as "负责人" by a zh-CN reader, are two columns of one
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
// `field/option-color-renders-neutral`: a select option `color` the option
4+
// badge does not paint (outside the nine palette families and the `#rgb` /
5+
// `#rrggbb` hex) is warned at author time and at the save door, instead of
6+
// rendering neutral grey with no signal. A declared family name and a hex are
7+
// not warned. Advisory only: nothing is refused.
8+
9+
import { describe, expect, it } from 'vitest';
10+
11+
import { authoringRulesFor } from './authoring-rules.js';
12+
import {
13+
FIELD_OPTION_COLOR_RENDERS_NEUTRAL,
14+
OPTION_COLOR_FAMILIES,
15+
isBadgePaintableOptionColor,
16+
lintOptionColors,
17+
} from './data-model-rules.js';
18+
import * as indexBarrel from './index.js';
19+
import { explainRule } from './rule-explanations.js';
20+
import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js';
21+
22+
const stageField = (colors: readonly (string | undefined)[]) => ({
23+
type: 'select',
24+
options: colors.map((color, i) => ({ label: `S${i}`, value: `s${i}`, ...(color === undefined ? {} : { color }) })),
25+
});
26+
27+
const objectWith = (colors: readonly (string | undefined)[]) => [
28+
{ name: 'acme_deal', fields: { stage: stageField(colors) } },
29+
];
30+
31+
const hits = (colors: readonly (string | undefined)[]) =>
32+
lintOptionColors(objectWith(colors)).filter((i) => i.rule === FIELD_OPTION_COLOR_RENDERS_NEUTRAL);
33+
34+
describe('field/option-color-renders-neutral', () => {
35+
it('is published from the root barrel under its constant, with an `os explain` entry', () => {
36+
expect(FIELD_OPTION_COLOR_RENDERS_NEUTRAL).toBe('field/option-color-renders-neutral');
37+
expect(indexBarrel.FIELD_OPTION_COLOR_RENDERS_NEUTRAL).toBe(FIELD_OPTION_COLOR_RENDERS_NEUTRAL);
38+
expect(explainRule(FIELD_OPTION_COLOR_RENDERS_NEUTRAL)?.rule).toBe(FIELD_OPTION_COLOR_RENDERS_NEUTRAL);
39+
});
40+
41+
it('an out-of-family colour name is warned, located at the option, and the fix names the families', () => {
42+
const found = hits(['teal']);
43+
expect(found).toHaveLength(1);
44+
const [issue] = found;
45+
expect(issue).toMatchObject({
46+
severity: 'warning',
47+
rule: FIELD_OPTION_COLOR_RENDERS_NEUTRAL,
48+
path: 'objects[0].fields.stage.options[0].color',
49+
where: `object "acme_deal" · field 'stage' · option 's0'`,
50+
});
51+
expect(issue!.message).toContain("color: 'teal'");
52+
for (const family of OPTION_COLOR_FAMILIES) expect(issue!.fix).toContain(family);
53+
});
54+
55+
it('a declared family name is not warned, nor is a #rgb / #rrggbb hex', () => {
56+
expect(OPTION_COLOR_FAMILIES).toHaveLength(9);
57+
expect(hits([...OPTION_COLOR_FAMILIES])).toEqual([]);
58+
expect(hits(['#14b8a6', '#ABC', '#14B8A6'])).toEqual([]);
59+
});
60+
61+
it('an option with no colour, or an empty one, declares nothing and is not judged', () => {
62+
expect(hits([undefined, '', ' '])).toEqual([]);
63+
});
64+
65+
it('every spelling the badge renders neutral is warned, each with the fix its value points at', () => {
66+
const fixOf = (color: string) => hits([color])[0]?.fix;
67+
expect(fixOf('Red')).toBe("Write the family in lowercase: color: 'red'.");
68+
expect(fixOf('14b8a6')).toBe("Write the hex with a leading #: color: '#14b8a6'.");
69+
expect(fixOf('#14b8a6cc')).toContain("color: '#14b8a6'");
70+
for (const color of ['amber', 'rgb(20, 184, 166)', 'hsl(173 80% 40%)', ' #14b8a6', '#14b8a']) {
71+
expect(isBadgePaintableOptionColor(color), color).toBe(false);
72+
expect(hits([color]), color).toHaveLength(1);
73+
}
74+
});
75+
76+
it('judges object-extension fields and picklists where they are written', () => {
77+
const issues = lintOptionColors(
78+
[],
79+
[{ target: 'acme_deal', path: 'objectExtensions[0]', fields: [{ name: 'tier', ...stageField(['amber']) }] }],
80+
[{ name: 'deal_stage', path: 'picklists[0]', where: 'picklist "deal_stage"', options: [{ label: 'A', value: 'a', color: 'teal' }, { label: 'B', value: 'b', color: 'blue' }] }],
81+
);
82+
expect(issues.map((i) => i.path)).toEqual([
83+
'objectExtensions[0].fields.tier.options[0].color',
84+
'picklists[0].options[0].color',
85+
]);
86+
});
87+
88+
it('runs on all three commands, picklists included, from the registry', () => {
89+
for (const command of ['validate', 'build', 'lint'] as const) {
90+
expect(authoringRulesFor(command).map((r) => r.name), command).toContain('lintOptionColors');
91+
}
92+
const entry = authoringRulesFor('validate').find((r) => r.name === 'lintOptionColors')!;
93+
const findings = entry.run(
94+
{
95+
objects: objectWith(['teal']),
96+
picklists: [{ name: 'deal_stage', label: 'Stage', options: [{ label: 'A', value: 'a', color: 'amber' }] }],
97+
picklistExtensions: [{ extend: 'deal_stage', options: [{ label: 'C', value: 'c', color: 'Red' }] }],
98+
},
99+
{},
100+
);
101+
expect(findings.map((f) => [f.severity, f.path])).toEqual([
102+
['warning', 'objects[0].fields.stage.options[0].color'],
103+
['warning', 'picklists[0].options[0].color'],
104+
['warning', 'picklistExtensions[0].options[0].color'],
105+
]);
106+
});
107+
108+
describe('at the save door (object writes)', () => {
109+
const write = (color: string) => ({
110+
name: 'acme_deal',
111+
label: 'Deal',
112+
sharingModel: 'private',
113+
fields: { stage: stageField([color]) },
114+
});
115+
116+
it('an out-of-family colour name rides back as an advisory and refuses nothing', () => {
117+
expect(runtimeAuthoringRulesFor('object').map((r) => r.name)).toContain('lintOptionColors');
118+
const result = runRuntimeAuthoringRules({ type: 'object', item: write('teal'), context: { objects: [] } });
119+
expect(result.errors).toEqual([]);
120+
const advisories = result.advisories.filter((f) => f.rule === FIELD_OPTION_COLOR_RENDERS_NEUTRAL);
121+
expect(advisories).toHaveLength(1);
122+
expect(advisories[0]).toMatchObject({ severity: 'warning' });
123+
expect(advisories[0]!.hint.length).toBeGreaterThan(0);
124+
});
125+
126+
it('a declared family name and a hex ride back with no advisory', () => {
127+
for (const color of ['red', '#14b8a6']) {
128+
const result = runRuntimeAuthoringRules({ type: 'object', item: write(color), context: { objects: [] } });
129+
expect(result.advisories.filter((f) => f.rule === FIELD_OPTION_COLOR_RENDERS_NEUTRAL), color).toEqual([]);
130+
}
131+
});
132+
});
133+
});

‎packages/lint/src/data-model-rules.ts‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1236,6 +1236,132 @@ export function lintFieldReferenceShapes(
12361236
return issues;
12371237
}
12381238

1239+
// ─── Option colours the badge cannot paint ───────────────────────────
1240+
1241+
/** The rule id an option `color` the option badge renders neutral reports under. */
1242+
export const FIELD_OPTION_COLOR_RENDERS_NEUTRAL = 'field/option-color-renders-neutral';
1243+
1244+
/**
1245+
* The palette families an option badge paints by name, exactly as the badge
1246+
* renderer spells them (`BADGE_COLOR_MAP` in `ui/packages/fields/src/index.tsx`;
1247+
* matched case-sensitively there). This package cannot import the renderer
1248+
* (`@objectstack/lint` depends on `@objectstack/spec` alone and runs at the
1249+
* kernel's save door), so the list is spelled here: a family added to that map
1250+
* is added here in the same change, or this rule warns on a colour that paints.
1251+
*/
1252+
export const OPTION_COLOR_FAMILIES: readonly string[] = Object.freeze([
1253+
'gray', 'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'pink',
1254+
]);
1255+
1256+
const OPTION_COLOR_FAMILY_SET: ReadonlySet<string> = new Set(OPTION_COLOR_FAMILIES);
1257+
1258+
/** The hex the badge paints: `#` first, then 3 or 6 hex digits (trailing space tolerated, as the renderer trims). */
1259+
const BADGE_HEX_RE = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
1260+
1261+
/** Does the option badge paint this declared colour (a family name, or a `#rgb` / `#rrggbb` hex)? */
1262+
export function isBadgePaintableOptionColor(color: string): boolean {
1263+
return OPTION_COLOR_FAMILY_SET.has(color) || (color.charAt(0) === '#' && BADGE_HEX_RE.test(color.trim()));
1264+
}
1265+
1266+
/** The fix line for one unpainted colour: the nearest spelling the author meant, when the value says it. */
1267+
function optionColorFix(color: string): string {
1268+
const trimmed = color.trim();
1269+
const lower = trimmed.toLowerCase();
1270+
const families = OPTION_COLOR_FAMILIES.join(', ');
1271+
if (OPTION_COLOR_FAMILY_SET.has(lower)) return `Write the family in lowercase: color: '${lower}'.`;
1272+
if (/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(trimmed)) {
1273+
return `Write the hex with a leading #: color: '#${trimmed.replace(/^#/, '')}'.`;
1274+
}
1275+
if (/^#[0-9a-f]{8}$/i.test(trimmed)) {
1276+
return `Drop the alpha digits: color: '${trimmed.slice(0, 7)}' (the badge paints #rgb and #rrggbb only).`;
1277+
}
1278+
return `Declare one of the families (${families}) or a #rgb / #rrggbb hex; remove color for a neutral badge.`;
1279+
}
1280+
1281+
/** One picklist (or picklist extension) as {@link lintOptionColors} reads it. */
1282+
export interface OptionColorPicklist {
1283+
/** The picklist it declares or extends. */
1284+
readonly name: string;
1285+
/** Its config path, e.g. `picklists[0]` or `picklistExtensions[1]`. */
1286+
readonly path: string;
1287+
/** Human-readable location, e.g. `picklist "deal_stage"`. */
1288+
readonly where: string;
1289+
/** Its declared options. */
1290+
readonly options: unknown;
1291+
}
1292+
1293+
/**
1294+
* A select option `color` the option badge renders neutral
1295+
* ({@link FIELD_OPTION_COLOR_RENDERS_NEUTRAL}, `warning`).
1296+
*
1297+
* An option is coloured if and only if its author declared a colour, and no
1298+
* colour is derived from its value (the ruling on objectstack#36882, option
1299+
* A). The badge paints a declared colour only when it is one of
1300+
* {@link OPTION_COLOR_FAMILIES} or a `#rgb` / `#rrggbb` hex; anything else —
1301+
* `teal`, `amber`, `Red`, `rgb(…)`, `#rrggbbaa` — reaches the renderer and
1302+
* paints the same neutral grey as an option with no colour, with no signal.
1303+
* This rule is that signal, at save. It never refuses: `SelectOption.color`
1304+
* stays a free string, and other surfaces (charts, gantt) hand the string to
1305+
* the browser as a CSS colour. `os explain field/option-color-renders-neutral`
1306+
* gives the per-surface reading.
1307+
*
1308+
* Reads the inline options of the objects' fields, of the fields object
1309+
* extensions add, and of picklists and picklist extensions, each located where
1310+
* it is written. An empty or blank `color` declares nothing and is not judged.
1311+
*/
1312+
export function lintOptionColors(
1313+
objects: any[],
1314+
extensions: readonly FieldShapeExtension[] = [],
1315+
picklists: readonly OptionColorPicklist[] = [],
1316+
): LocatedLintIssue[] {
1317+
const issues: LocatedLintIssue[] = [];
1318+
const judge = (options: unknown, owner: string, optionsPath: string, where: string) => {
1319+
if (!Array.isArray(options)) return;
1320+
options.forEach((opt: any, j: number) => {
1321+
if (!opt || typeof opt !== 'object') return;
1322+
const color = opt.color;
1323+
if (typeof color !== 'string' || color.trim() === '' || isBadgePaintableOptionColor(color)) return;
1324+
const value = typeof opt.value === 'string' || typeof opt.value === 'number' ? String(opt.value) : `#${j}`;
1325+
issues.push({
1326+
severity: 'warning',
1327+
rule: FIELD_OPTION_COLOR_RENDERS_NEUTRAL,
1328+
where: `${where} · option '${value}'`,
1329+
message:
1330+
`${owner} option '${value}' declares color: '${color}', which the option badge does not paint: ` +
1331+
'it renders neutral grey, the same as an option with no colour',
1332+
path: `${optionsPath}[${j}].color`,
1333+
fix: optionColorFix(color),
1334+
});
1335+
});
1336+
};
1337+
1338+
if (Array.isArray(objects)) {
1339+
objects.forEach((obj, i) => {
1340+
if (!obj?.name) return;
1341+
for (const { name, def } of fieldEntries(obj.fields)) {
1342+
if (!def || typeof def !== 'object') continue;
1343+
judge(def.options, `field "${obj.name}.${name}"`, `objects[${i}].fields.${name}.options`, fieldWhere(obj, name));
1344+
}
1345+
});
1346+
}
1347+
for (const ext of extensions) {
1348+
for (const def of ext.fields) {
1349+
const name = typeof def?.name === 'string' ? def.name : '';
1350+
if (!name) continue;
1351+
judge(
1352+
def.options,
1353+
`field "${ext.target}.${name}"`,
1354+
`${ext.path}.fields.${name}.options`,
1355+
`object extension of "${ext.target}" · field '${name}'`,
1356+
);
1357+
}
1358+
}
1359+
for (const list of picklists) {
1360+
judge(list.options, `picklist "${list.name}"`, `${list.path}.options`, list.where);
1361+
}
1362+
return issues;
1363+
}
1364+
12391365
// ─── Rule engine ────────────────────────────────────────────────────
12401366

12411367
/**

0 commit comments

Comments
 (0)