feat(ui): standardize inspector spacing and compact level geometry

This commit is contained in:
Codex
2026-11-04 18:18:10 +03:00
parent 8ff33a6a17
commit be929f9d8e
10 changed files with 74 additions and 9 deletions
+3 -1
View File
@@ -1508,6 +1508,8 @@ export function CatalogApp() {
<LevelButton label="Заряд аккумулятора" value={null} freshness="unknown" disabled/>
<LevelButton label="Белая заливка" value={.82} fillColor="#ffffff"/>
<LevelButton label="Чёрная заливка" value={.82} fillColor="#000000"/>
<LevelButton label="Минимальный индикатор" value={1} valueText="100%" fillColor="#ffffff" geometry={{width:32,height:12,radius:4}}/>
<LevelButton label="Широкий индикатор" value={.82} geometry={{width:160,height:24,radius:8}}/>
</Preview>
<Preview title="Линейный прогресс" note="измеренный / неизвестный / завершённый">
<ProgressBar label="Подготовка" value={0.6} valueText="Три этапа из пяти" />
@@ -2357,7 +2359,7 @@ export function CatalogApp() {
draggable
onClose={() => setInspectorOpen(false)}
>
<Inspector sections={environmentSections} defaultOpen={["application-material"]} />
<Inspector header={<Description>Поля и секции разделены единым шагом 12 px.</Description>} footer={<Button variant="primary" tone="neutral" onClick={()=>setInspectorOpen(false)}>Готово</Button>} sections={environmentSections} defaultOpen={["application-material"]} />
</Window>
<Window
+5
View File
@@ -356,6 +356,11 @@ Sortable-строки ограничены вертикальной осью: г
Единая accordion-панель для settings и definition controls. Источник — только новый Environment Settings и NDC Agent Inspector.
Inspector принимает `header` для полей перед секциями и `footer` для действий после них.
Поля header и соседние секции разделяет `--nodedc-space-3` (12 px); footer
центрирует действия. Вложенные Inspector сохраняют тот же шаг. Это общий контракт,
а не локальные margin-правки потребителя. Вариант `panel` сохраняет компактные строки.
Inspector владеет:
- заголовками разделов;
+6
View File
@@ -20,3 +20,9 @@ label. WCAG luminance chooses black/white text independently over the filled
part, while the unfilled part keeps the normal theme text. Unknown has no fill;
stale retains the chosen colour and its accessible stale label. Colour-range
configuration belongs to the domain profile, not the visual component.
`geometry={{width, height, radius}}` задаёт операторские размеры с минимумом
32 × 12 px. Ниже 64 × 24 текст и padding уменьшаются пропорционально
ограничивающему размеру; длинная подпись также учитывается. Оба слоя текста
наследуют одинаковые размеры. Без geometry сохраняется прежний размер Button.
Внешний отступ от соседних действий остаётся ответственностью композиции шапки.
+6 -3
View File
@@ -3551,18 +3551,21 @@ textarea.nodedc-field__control {
.nodedc-inspector {
display: grid;
width: min(var(--nodedc-inspector-inner-width), 100%);
gap: 1px;
gap: var(--nodedc-space-3);
}
.nodedc-inspector__header { display: grid; min-width: 0; gap: var(--nodedc-space-3); }
.nodedc-inspector__footer { display: flex; justify-content: center; align-items: center; flex-wrap: wrap; gap: var(--nodedc-space-3); }
.nodedc-inspector__group {
display: grid;
gap: 1px;
gap: var(--nodedc-space-3);
}
.nodedc-inspector__section {
display: grid;
min-width: 0;
gap: 1px;
gap: 0;
}
.nodedc-inspector__section-trigger {
+7
View File
@@ -19,6 +19,9 @@ export interface InspectorSectionSpec {
export interface InspectorProps {
sections: InspectorSectionSpec[];
/** Spaced form fields above sections and centered actions below them. */
header?: ReactNode;
footer?: ReactNode;
defaultOpen?: string[];
openSections?: string[];
activeId?: string;
@@ -31,6 +34,8 @@ export interface InspectorProps {
export function Inspector({
sections,
header,
footer,
defaultOpen = [],
openSections,
activeId,
@@ -70,6 +75,7 @@ export function Inspector({
return (
<InspectorSelectPolicyContext.Provider value>
<div className={cn("nodedc-inspector", className)} data-variant={variant === "default" ? undefined : variant}>
{header ? <div className="nodedc-inspector__header">{header}</div> : null}
{groups.map((group, groupIndex) => (
<div className="nodedc-inspector__group" key={`${group.label ?? "root"}-${groupIndex}`}>
{group.sections.map((section) => {
@@ -107,6 +113,7 @@ export function Inspector({
})}
</div>
))}
{footer ? <div className="nodedc-inspector__footer">{footer}</div> : null}
</div>
</InspectorSelectPolicyContext.Provider>
);
+6 -2
View File
@@ -1,9 +1,13 @@
import {levelButtonGeometry,type LevelButtonGeometry} from './levelButtonGeometry.js';
export type {LevelButtonGeometry} from './levelButtonGeometry.js';
import type {CSSProperties} from 'react';
import {Button,type ButtonProps} from './Button.js';
import {cn} from './cn.js';
export interface LevelButtonProps extends Omit<ButtonProps,'children'|'shape'|'value'> {
label:string;
/** Optional operator geometry; text and padding shrink together below 64 × 24. */
geometry?:LevelButtonGeometry;
/** Measured fraction. Missing is unknown, never zero or animated progress. */
value?:number|null;
valueText?:string;
@@ -13,7 +17,7 @@ export interface LevelButtonProps extends Omit<ButtonProps,'children'|'shape'|'v
fillColor?:string;
}
/** Compact measured resource level which opens details, with native button semantics. */
export function LevelButton({label,value,valueText,freshness='live',levelTone='neutral',fillColor,className,style,...props}:LevelButtonProps){
export function LevelButton({label,value,valueText,freshness='live',levelTone='neutral',fillColor,geometry,className,style,...props}:LevelButtonProps){
const fraction=typeof value==='number'&&Number.isFinite(value)?Math.max(0,Math.min(1,value)):null;
const custom=typeof fillColor==='string'&&/^#[0-9a-f]{6}$/i.test(fillColor)?fillColor:null;
const channels=custom?.slice(1).match(/../g)?.map(v=>{const c=parseInt(v,16)/255;return c<=.04045?c/12.92:((c+.055)/1.055)**2.4;});
@@ -22,5 +26,5 @@ export function LevelButton({label,value,valueText,freshness='live',levelTone='n
return <Button {...props} shape="pill" className={cn('nodedc-level-button',className)}
aria-label={`${label}: ${text}${freshness==='stale'?' · последние показания':''}`}
data-level-tone={levelTone} data-freshness={freshness} data-custom-fill={custom?true:undefined}
style={{...style,'--nodedc-level-percent':`${(fraction??0)*100}%`,...(custom?{'--nodedc-level-custom':custom,'--nodedc-level-ink':ink}:{})} as CSSProperties}><span aria-hidden="true">{text}</span>{custom&&fraction!==null&&<span aria-hidden="true" className="nodedc-level-button__fill">{text}</span>}</Button>;
style={{...style,...levelButtonGeometry(geometry,text.length),'--nodedc-level-percent':`${(fraction??0)*100}%`,...(custom?{'--nodedc-level-custom':custom,'--nodedc-level-ink':ink}:{})} as CSSProperties}><span aria-hidden="true">{text}</span>{custom&&fraction!==null&&<span aria-hidden="true" className="nodedc-level-button__fill">{text}</span>}</Button>;
}
@@ -0,0 +1,10 @@
import type {CSSProperties} from 'react';
export type LevelButtonGeometry={width:number;height:number;radius?:number};
/** Keep type and padding proportional when the operator chooses a tiny indicator. */
export function levelButtonGeometry(value:LevelButtonGeometry|undefined,characters:number):CSSProperties{
if(!value)return {};
const bounded=(n:number|undefined,fallback:number,min:number,max:number)=>typeof n==='number'&&Number.isFinite(n)?Math.max(min,Math.min(max,n)):fallback;
const width=bounded(value.width,115,32,4096),height=bounded(value.height,46,12,1024),radius=bounded(value.radius,999,0,4096);
const scale=Math.min(1,height/24,width/Math.max(64,(characters+2)*8));
return {width,minWidth:width,height,minHeight:height,borderRadius:radius,flexShrink:0,fontSize:`calc(var(--nodedc-font-size-md) * ${scale})`,lineHeight:1,padding:`calc(0.25rem * ${scale}) calc(var(--nodedc-space-2) * ${scale})`};
}
+6 -3
View File
@@ -1096,7 +1096,8 @@
"Inspector selection fields use InspectorSelectField only: a stacked visible label and the 276/8/46 px split control; integrated pills are prohibited.",
"The panel variant reuses AdminNavigationPanel pill, icon and theme tokens while retaining the same controlled accordion state and domain-owned content.",
"A section action is a sibling IconButton before the disclosure chevron, never nested in the trigger. It does not toggle the section. Panel chevrons point down when collapsed and up when expanded.",
"Accent-filled section headers belong to Environment Settings; neutral headers remain available for other approved inspector contexts."
"Accent-filled section headers belong to Environment Settings; neutral headers remain available for other approved inspector contexts.",
"Default sections and optional header fields use the canonical 12 px spacing token; footer actions are centered with the same gap. Nested Inspectors retain this rhythm; the panel variant retains its compact row geometry."
]
},
{
@@ -1368,7 +1369,8 @@
"package": "@nodedc/ui-react",
"exports": [
"LevelButton",
"LevelButtonProps"
"LevelButtonProps",
"LevelButtonGeometry"
],
"domContract": [
"nodedc-level-button"
@@ -1377,7 +1379,8 @@
"rules": [
"Consumer supplies a measured fraction and freshness; unknown is not zero.",
"Stale retains the last number and accessible stale text; explicit user fill colours are retained.",
"Keyboard, focus, disabled and pointer behavior come from Button. Explicit fillColor uses contrast-correct text on the filled portion."
"Keyboard, focus, disabled and pointer behavior come from Button. Explicit fillColor uses contrast-correct text on the filled portion.",
"Optional geometry sets width, height and radius with a 32 × 12 px minimum. At small dimensions the text and padding shrink proportionally; both contrast layers share the same type geometry. Consumer owns header-group offset."
],
"documentation": "../docs/LEVEL_BUTTON.md"
}
+16
View File
@@ -47,3 +47,19 @@ test("viewport controls share one scale without scaling nested controls twice",
assert.match(styles, /\.nodedc-segmented\) :is\([^}]+zoom: 1;/);
assert.ok(JSON.parse(registrySource).components.find(c=>c.id==='button').domContract.includes('nodedc-viewport-controls'));
});
import { LevelButton } from "../packages/ui-react/dist/index.js";
import { levelButtonGeometry } from "../packages/ui-react/dist/levelButtonGeometry.js";
test("compact level indicators fit both contrast layers with proportional text and padding", () => {
const tiny=levelButtonGeometry({width:32,height:12,radius:4},4);
const normal=levelButtonGeometry({width:64,height:24,radius:8},4);
assert.equal(tiny.fontSize,'calc(var(--nodedc-font-size-md) * 0.5)');
assert.equal(tiny.padding,'calc(0.25rem * 0.5) calc(var(--nodedc-space-2) * 0.5)');
assert.equal(normal.fontSize,'calc(var(--nodedc-font-size-md) * 1)');
assert.equal(levelButtonGeometry({width:-1,height:NaN},4).width,32);
assert.equal(levelButtonGeometry({width:-1,height:NaN},4).height,46);
const markup=renderToStaticMarkup(createElement(LevelButton,{value:1,label:'Battery',fillColor:'#ffffff',geometry:{width:32,height:12,radius:4}}));
assert.match(markup,/width:32px/);assert.match(markup,/height:12px/);
assert.match(markup,/nodedc-level-button__fill/);
assert.match(markup,/100/);assert.match(markup,/aria-label="Battery: 100%"/);
});
@@ -59,3 +59,12 @@ test("Foundry Inspector screens consume the semantic selection field", async ()
assert.equal((catalog.match(/<InspectorSelectField/g) ?? []).length, 2);
assert.match(coreStyles, /\.nodedc-inspector \.nodedc-control-row:has\(\.nodedc-select-anchor\)/);
});
test("Inspector owns form header and centered action footer around its sections",async()=>{
const markup=renderToStaticMarkup(createElement(Inspector,{header:'Form fields',footer:'Action',sections:[{id:'surface',label:'Surface',content:'Controls'},{id:'textures',label:'Textures',content:'Slots'}]}));
assert.ok(markup.indexOf('nodedc-inspector__header')<markup.indexOf('nodedc-inspector__group'));
assert.ok(markup.indexOf('nodedc-inspector__footer')>markup.lastIndexOf('nodedc-inspector__section'));
const css=await readFile(new URL('../packages/ui-core/styles.css',import.meta.url),'utf8');
assert.match(css,/\.nodedc-inspector__group\s*\{[^}]*gap: var\(--nodedc-space-3\)/);
assert.match(css,/\.nodedc-inspector__footer\s*\{[^}]*justify-content: center/);
});