fix(ui): constrain editor tools and add screen color sampling

This commit is contained in:
Codex
2026-11-14 23:37:36 +03:00
parent d7885fe098
commit 5f93defabf
13 changed files with 96 additions and 19 deletions
+4 -4
View File
@@ -39,7 +39,7 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
const required=dockMinimum(visibleTree,minimums),area={...bounds,width:Math.max(bounds.width,required.width),height:Math.max(bounds.height,required.height)};
const constrained=constrainDockTree(visibleTree,area,minimums)!;
const rects=dockRects(constrained,area);
const floatingRect=(id:string)=>fitWindow(value.floating[id]??tools.find(t=>t.id===id)?.initialRect??{left:Math.max(8,bounds.width-380),top:24,width:360,height:540},bounds);
const floatingRect=(id:string)=>fitWindow(value.floating[id]??tools.find(t=>t.id===id)?.initialRect??{left:Math.max(8,bounds.width-380),top:24,width:360,height:540},bounds,tools.find(t=>t.id===id)?.minimumSize);
const latest=useRef({value,onChange,rects,bounds,enabled,tools});latest.current={value,onChange,rects,bounds,enabled,tools};
const activate=(id:string)=>setOrder(v=>[...v.filter(x=>x!==id),id]);
useLayoutEffect(()=>{const v=viewport.current!;const measure=()=>setBounds({left:0,top:0,width:v.clientWidth,height:v.clientHeight});measure();const ro=new ResizeObserver(measure);ro.observe(v);return()=>ro.disconnect();},[]);
@@ -57,8 +57,8 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
const p=point(e),dx=p.x-g.x,dy=p.y-g.y;
if(!g.moved&&Math.hypot(dx,dy)<6)return;
g.moved=true;
const b=latest.current.bounds;
g.current=g.edge?resizeWindow(g.rect,g.edge,dx,dy,b):fitWindow({...g.rect,left:g.rect.left+dx,top:g.rect.top+dy},b);
const b=latest.current.bounds,minimum=latest.current.tools.find(t=>t.id===g.id)?.minimumSize;
g.current=g.edge?resizeWindow(g.rect,g.edge,dx,dy,b,minimum):fitWindow({...g.rect,left:g.rect.left+dx,top:g.rect.top+dy},b,minimum);
const visibleBounds={...b,left:viewport.current?.scrollLeft??0,top:viewport.current?.scrollTop??0};
g.target=g.edge?null:editorDockTarget(visibleBounds,latest.current.rects,primaryId,g.id,p.x,p.y);
setDrag({...g});e.preventDefault();
@@ -85,7 +85,7 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
else if(position)setKeyboard({id,target:{activeId:id,overId:keyboard.target?.overId??primaryId,position,scope:e.shiftKey||!keyboard.target?'workspace':keyboard.target.scope}});
else return;
}else if(e.key==='Enter'||e.key===' '){setKeyboard({id,target:null});activate(id);}
else if(position&&!rects[id]){const r=floatingRect(id),delta=e.altKey?1:10,dx=position==='left'?-delta:position==='right'?delta:0,dy=position==='top'?-delta:position==='bottom'?delta:0;onChange({...value,floating:{...value.floating,[id]:e.shiftKey?resizeWindow(r,'se',dx,dy,bounds):fitWindow({...r,left:r.left+dx,top:r.top+dy},bounds)}});}
else if(position&&!rects[id]){const r=floatingRect(id),delta=e.altKey?1:10,dx=position==='left'?-delta:position==='right'?delta:0,dy=position==='top'?-delta:position==='bottom'?delta:0;onChange({...value,floating:{...value.floating,[id]:e.shiftKey?resizeWindow(r,'se',dx,dy,bounds,tools.find(t=>t.id===id)?.minimumSize):fitWindow({...r,left:r.left+dx,top:r.top+dy},bounds,tools.find(t=>t.id===id)?.minimumSize)}});}
else return;
e.preventDefault();e.stopPropagation();
};
+2
View File
@@ -1,5 +1,6 @@
import {
MousePointer2,
Pipette,
createLucideIcon,
Glasses,
Cuboid,
@@ -85,6 +86,7 @@ const InformationPlain = createLucideIcon('InformationPlain', [
['path', {d:'M12 4h.01M10 9h2v11M9 20h6',key:'information'}],
]);
const icons = {
pipette: Pipette,
"add-point": CirclePlus,
ruler: DimensionLine,
section: SectionPlane,
+30
View File
@@ -3,6 +3,10 @@ import { VerticalRangeBand, type RangeBandControlProps } from "./VerticalRangeBa
export type { RangeBandControlProps } from "./VerticalRangeBand.js";
import { cn } from "./cn.js";
import { Dropdown } from "./Dropdown.js";
import { Button } from "./Button.js";
import { Icon } from "./Icon.js";
import { Description } from "./Description.js";
import { screenColorPicker } from "./screenColorPicker.js";
export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> {
label: string;
@@ -277,7 +281,27 @@ function hsvToHex({ h, s, v }: Hsv): string {
export function ColorField({ value, onChange, label = "Цвет", className, disabled = false, onBlur, onKeyDown, ...props }: ColorFieldProps) {
const [draft, setDraft] = useState(value);
const [paletteOpen, setPaletteOpen] = useState(false), [picking, setPicking] = useState(false), [pickError, setPickError] = useState(false);
const nativePicker = useRef<HTMLInputElement>(null), sampling = useRef<AbortController | null>(null);
const screenPicker = screenColorPicker();
useEffect(() => () => { sampling.current?.abort(); }, []);
useEffect(() => { if (disabled || !paletteOpen) { sampling.current?.abort(); sampling.current = null; setPicking(false); } }, [disabled, paletteOpen]);
useEffect(() => setDraft(value), [value]);
const sampleScreen = async () => {
if (disabled || sampling.current) return;
setPickError(false);
if (!screenPicker) { nativePicker.current?.click(); return; }
const controller = new AbortController(); sampling.current = controller; setPicking(true);
try {
// open() executes synchronously in this trusted click before the first await.
const result = await new screenPicker().open({ signal: controller.signal });
if (!controller.signal.aborted && parseHexColor(result.sRGBHex)) { setDraft(result.sRGBHex.toLowerCase()); onChange(result.sRGBHex.toLowerCase()); }
} catch (error) {
if (!controller.signal.aborted && !(error instanceof Error && error.name === 'AbortError')) setPickError(true);
} finally {
if (!controller.signal.aborted) { setPicking(false); sampling.current = null; }
}
};
const validColor = hexToHsv(value);
const [hsv, setHsv] = useState<Hsv>(() => validColor ?? { h: 330, s: 82, v: 100 });
const style = { "--nodedc-color-value": validColor ? hsvToHex(validColor) : hsvToHex(hsv) } as CSSProperties;
@@ -302,6 +326,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
<div className={cn("nodedc-color-field", className)} style={style}>
<Dropdown
className="nodedc-color-field__dropdown"
onOpenChange={setPaletteOpen}
placement="bottom-start"
minWidth={296}
width={296}
@@ -354,6 +379,10 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
<span>Оттенок</span>
<input type="range" min={0} max={360} value={Math.round(hsv.h)} aria-label={`${label}: оттенок`} disabled={disabled} onChange={(event) => commit({ ...hsv, h: Number(event.target.value) })} />
</label>
<Button width="full" icon={<Icon name="pipette"/>} disabled={disabled} loading={picking} onClick={() => void sampleScreen()} title={screenPicker ? 'Выбрать цвет в любой точке экрана; Escape — отменить' : 'В этом браузере выбор цвета с экрана доступен через системную палитру, если она поддерживает пипетку'}>
{screenPicker ? 'Цвет с экрана' : 'Системная палитра'}
</Button>
{pickError && <Description role="status">Не удалось включить пипетку. Повторите попытку.</Description>}
<div className="nodedc-color-palette__presets" aria-label="Быстрые цвета">
{palettePresets.map((preset) => (
<button
@@ -371,6 +400,7 @@ export function ColorField({ value, onChange, label = "Цвет", className, dis
</div>
</div>
</Dropdown>
<input ref={nativePicker} type="color" className="nodedc-color-field__native-picker" tabIndex={-1} aria-hidden="true" disabled={disabled} value={validColor ? hsvToHex(validColor) : '#000000'} onChange={event => { setDraft(event.target.value); onChange(event.target.value); }}/>
<input
className="nodedc-color-field__text"
{...props}
@@ -0,0 +1,5 @@
/** Screen sampling requires a secure context and an explicit trusted click. No screenshots are retained. */
export type ScreenColorPicker = new () => { open(options: { signal: AbortSignal }): Promise<{ sRGBHex: string }> };
export function screenColorPicker(): ScreenColorPicker | undefined {
return (globalThis as typeof globalThis & { EyeDropper?: ScreenColorPicker }).EyeDropper;
}
+7 -6
View File
@@ -3,15 +3,16 @@ export type WindowRect = { left: number; top: number; width: number; height: num
export type ResizeEdge = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';
export const windowResizeEdges: ResizeEdge[] = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'];
type Bounds = { width: number; height: number };
const defaultMinimum: Bounds = { width: 320, height: 200 };
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value));
export function fitWindow(rect: WindowRect, bounds: Bounds): WindowRect {
const width = clamp(rect.width, Math.min(320, bounds.width - 16), Math.max(1, bounds.width - 16));
const height = clamp(rect.height, Math.min(200, bounds.height - 16), Math.max(1, bounds.height - 16));
export function fitWindow(rect: WindowRect, bounds: Bounds, minimum: Bounds = defaultMinimum): WindowRect {
const width = clamp(rect.width, Math.max(1, Math.min(minimum.width, bounds.width - 16)), Math.max(1, bounds.width - 16));
const height = clamp(rect.height, Math.max(1, Math.min(minimum.height, bounds.height - 16)), Math.max(1, bounds.height - 16));
return { width, height, left: clamp(rect.left, 8, Math.max(8, bounds.width - width - 8)), top: clamp(rect.top, 8, Math.max(8, bounds.height - height - 8)) };
}
export function resizeWindow(rect: WindowRect, edge: ResizeEdge, dx: number, dy: number, bounds: Bounds): WindowRect {
const r = fitWindow(rect, bounds), right = r.left + r.width, bottom = r.top + r.height;
const minWidth = Math.min(320, bounds.width - 16), minHeight = Math.min(200, bounds.height - 16);
export function resizeWindow(rect: WindowRect, edge: ResizeEdge, dx: number, dy: number, bounds: Bounds, minimum: Bounds = defaultMinimum): WindowRect {
const r = fitWindow(rect, bounds, minimum), right = r.left + r.width, bottom = r.top + r.height;
const minWidth = Math.max(1, Math.min(minimum.width, bounds.width - 16)), minHeight = Math.max(1, Math.min(minimum.height, bounds.height - 16));
const left = edge.includes('w') ? clamp(r.left + dx, 8, right - minWidth) : r.left;
const top = edge.includes('n') ? clamp(r.top + dy, 8, bottom - minHeight) : r.top;
const endX = edge.includes('e') ? clamp(right + dx, left + minWidth, bounds.width - 8) : right;