import { createEffect, createMemo, createSignal, For, Show, type JSX } from 'solid-js'; import { LayoutLab as Engine, type LayoutSettingKey } from '../engines/layout-engine'; import { layoutShape, type LayoutShape } from '../dsl/layout-edits'; import { ENGINES, FITS, type Fit } from '../dsl/syntax'; import { count } from '../model/candidates'; import { selectionRoots } from '../model/graph'; import type { AspectSetting, Diagram, LayoutAlgorithmId, RoutingSettings } from '../model/types'; import { commandEnabled, commands, runCommand, type Command, type CommandId, } from '../state/commands'; import { ROUTE_PRESETS, type RoutePreset } from '../state/session/routing'; import { Checkbox, RangeField, SelectField, tip } from './controls'; import { IntentSummary } from './Inspector'; import { useDiagramSession } from './session-context'; import type { DiagramSession } from '../state/session'; type NumericKey = { [K in keyof Diagram['settings']]: Diagram['settings'][K] extends number ? K : never; }[keyof Diagram['settings']]; function Slider(props: { label: string; key: NumericKey; min: number; max: number; step?: number; hint?: string; }) { const s = useDiagramSession(); return ( s.updateLayoutSettings({ [props.key]: value })} /> ); } /** * Settings a rebuild reads, by layout approach. `ordering` is left out: a rebuild always orders * ranks to reduce crossings, so the choice only matters to a small pass. */ const ENGINE_CONTROLS: Partial JSX.Element>> = { boundaryPull: () => ( ), hierarchySweeps: () => , groupGap: () => , rankGap: () => , edgeLength: () => , repulsion: () => , flowStrength: () => ( ), alignment: () => , compactness: () => , gridStrength: () => ( ), fold: () => , rootId: () => , }; function FoldField() { const s = useDiagramSession(); return ( s.updateLayoutSettings({ fold })} /> ); } function RootField() { const s = useDiagramSession(); return ( [n.id, n.title] as const)]} onChange={rootId => s.updateLayoutSettings({ rootId })} /> ); } /** A browser diagram has no `layout` line. Its format is the engine's target aspect instead. */ const ASPECTS: Partial> = { wide: '2', slide: '1.6', square: '1', page: '0.75', }; type Direction = LayoutShape['direction']; /** How the diagram is arranged: direction, format and connections, with the exact values below. */ export function ArrangePanel() { const s = useDiagramSession(); const scope = () => (s.fileMode() ? s.arrangeScope() : 'root'); const loose = () => s.currentScope().scope === 'selection' && s.labScope() === 'auto'; // The scene changes with every saved revision; read it so the panel follows the file. const shape = createMemo(() => { s.fileScene(); const id = scope(); return id && s.fileMode() ? layoutShape(s.layoutPreview()?.file?.source ?? s.currentSource(), id) : null; }); const direction = (): Direction => shape()?.direction ?? (s.doc.settings.direction === 'DOWN' ? 'down' : 'right'); const fit = (): Fit | null => s.fileMode() ? (shape()?.fit ?? null) : ((Object.keys(ASPECTS) as Fit[]).find(f => ASPECTS[f] === s.doc.settings.aspect) ?? null); const setDirection = (next: Direction) => { if (s.fileMode()) return void s.previewShape({ direction: next }); void s.previewSettings({ direction: next === 'down' ? 'DOWN' : 'RIGHT' }); }; const setFit = (next: Fit | null) => { if (s.fileMode()) return void s.previewShape({ fit: next }); void s.previewSettings({ aspect: next ? ASPECTS[next] : 'canvas' }); }; const canReshape = () => !!scope() && !loose(); const axisOnly = () => ['row', 'column'].includes(shape()?.recipe ?? ''); const hasFormat = () => (!s.fileMode() || scope() === 'root') && !s.rebuildBlocked(); return (
{s.movesBlocked()}

}> Direction and format apply to the whole diagram or to one group. Select a group, or clear the selection.

} >

Direction

label="Direction" value={direction()} options={[ ...(s.fileMode() && !axisOnly() ? [['auto', 'Auto'] as const] : []), ['right', 'Right'], ['down', 'Down'], ]} onChange={setDirection} hints={{ auto: 'Reads whichever way fits best.' }} />

Format

Exact layout
Exact routing
Local tools
); } /** The scope's line as the file says it now, or as a preview would save it. */ function recipeLine(s: DiagramSession, scope: string | null, shape: LayoutShape | null) { if (!scope || !shape) return null; const line = (s.layoutPreview()?.file?.source ?? s.currentSource()) .split('\n') .find(l => new RegExp(`^layout ${scope}\\b`).test(l)); return line?.split(' #')[0].trim() ?? `Built-in ${shape.recipe} recipe`; } /** What the panel acts on: it follows the selection, so there is no scope to set. */ function Subject(props: { line: string | null }) { const s = useDiagramSession(); const name = () => { const roots = selectionRoots(s.doc, s.selection()); const id = s.currentScope().containerId; if (id) return s.doc.graph.groups.find(g => g.id === id)?.title ?? id; if (roots.length) return `${roots.length} ${roots.length === 1 ? 'shape' : 'shapes'}`; return 'Whole diagram'; }; return (
{name()} {line => {line()}}
); } function ActionButton(props: { command: CommandId; label: string; primary?: boolean }) { const command = (): Command => commands[props.command]; return ( ); } /** * The choice being compiled, so a click answers at once on a drawing that takes a while. It ends * when the drawing catches up. */ function useAsked(value: () => T) { const s = useDiagramSession(); const [asked, setAsked] = createSignal(); createEffect(() => { value(); if (!s.layoutBusy()) setAsked(undefined); }); const shown = (option: T) => (asked() === undefined ? value() : asked()) === option; return { asked, setAsked, shown }; } /** A segmented choice whose active button is what the drawing is now. */ function Choices(props: { label: string; value: T | null; options: ReadonlyArray; onChange: (value: T) => void; hints?: Partial>; }) { const { asked, setAsked, shown } = useAsked(() => props.value); return (
{([value, text]) => ( )}
); } /** Each format drawn to its own proportions, so the shape is the label. */ function FormatPicker(props: { value: Fit | null; onChange: (fit: Fit | null) => void }) { const s = useDiagramSession(); const { asked, setAsked, shown } = useAsked(() => props.value ?? 'auto'); const choose = (next: Fit | 'auto') => { if (shown(next)) return; setAsked(() => next); props.onChange(next === 'auto' ? null : next); }; const options = () => (Object.keys(FITS) as Fit[]).filter(f => s.fileMode() || ASPECTS[f] !== undefined); const glyph = (ratio: number) => ({ width: `${ratio >= 1 ? 18 : 18 * ratio}px`, height: `${ratio >= 1 ? 18 / ratio : 18}px`, }); return (
{fit => ( )}
); } function Connections() { const s = useDiagramSession(); const report = () => s.routingReport(); return (

Connections

label="Connection routing" value={s.activeRoutePreset()} options={(Object.keys(ROUTE_PRESETS) as RoutePreset[]).map(p => [p, p] as const)} onChange={s.applyRoutePreset} />

Custom values are set. A preset replaces them.

{count(report().crossings, 'crossing')} · {count(report().bends, 'bend')} · {count(report().lanePairs, 'close line')}

); } /** Every setting by what it changes: the rebuild, then the small moves of Tidy. */ function ExactLayout() { const s = useDiagramSession(); const rebuildEngine = () => s.fileMode() ? (s.labEngine() ?? (engineOf() as LayoutAlgorithmId | null)) : s.doc.settings.algorithm; const engineOf = () => { const id = s.arrangeScope(); if (!id) return null; s.fileScene(); const shape = layoutShape(s.layoutPreview()?.file?.source ?? s.currentSource(), id); return shape.engine ? shape.recipe : null; }; const algorithm = () => Engine.algorithms.find(a => a.id === rebuildEngine()); const engines = () => Engine.algorithms.filter(a => !s.fileMode() || ENGINES.includes(a.id)).map(a => [a.id, a.name]); const writes = () => { const id = s.arrangeScope(), engine = rebuildEngine(); if (!id || !engine || !s.labEngine()) return null; return s.changedLine(s.sourceWithRecipe(id, { ...s.doc.settings, algorithm: engine }).source); }; const improver = () => Engine.algorithms.find(a => a.id === s.doc.settings.algorithm)!; return (

Rebuild

label="Rebuild with" value={rebuildEngine() ?? ''} options={[ ...(s.fileMode() ? [['', 'Built-in recipe'] as const] : []), ...(engines() as Array<[string, string]>), ]} onChange={value => { if (!s.fileMode()) return s.updateLayoutSettings({ algorithm: value as LayoutAlgorithmId }); const leavesEngine = !value && engineOf(); s.setLabEngine((value || null) as LayoutAlgorithmId | null); if (leavesEngine) void s.previewShape({ builtin: true }); }} /> {a => ( <>

{a().short}

{key => ENGINE_CONTROLS[key]?.()} )}
{line => {line()}}

Tidy

label="Tidy with" value={s.doc.settings.algorithm} options={Engine.algorithms.map(a => [a.id, a.name] as const)} onChange={value => s.updateLayoutSettings({ algorithm: value })} />

{improver().short}

s.updateLayoutSettings({ ordering })} /> s.setLabScope(on ? 'neighbourhood' : 'auto')} /> s.updateLayoutSettings({ respectDirection })} /> s.updateLayoutSettings({ respectManual })} /> s.updateLayoutSettings({ growContainers })} />
); } /** The recipe's own settings. Each change previews, like Direction and Format. */ function RecipeControls() { const s = useDiagramSession(); const shape = () => { s.fileScene(); const id = s.arrangeScope(); return id ? layoutShape(s.layoutPreview()?.file?.source ?? s.currentSource(), id) : null; }; return ( {current => ( <> void s.previewShape({ gap })} /> void s.previewShape({ fold })} /> )} ); } type RouteField = [keyof RoutingSettings, string, number, number, string?]; const ROUTE_SPACING: RouteField[] = [ ['clearance', 'Around shapes', 4, 30], ['standoff', 'Before the first bend', 0, 40], ['portGap', 'At endpoints', 6, 28], ['edgeGap', 'Between lines', 4, 48], ]; const ROUTE_COSTS: RouteField[] = [ ['crossingPenalty', 'Crossing', 0, 1200, 'Higher values prefer detours over crossings.'], ['bendPenalty', 'Bend', 0, 100], ['parallelPenalty', 'Close lines', 0, 60], ['sharedPenalty', 'Shared path', 0, 20], ['fanoutPenalty', 'Fan-out', 0, 160, 'Prefer different sides for separate branches.'], ['portStability', 'Changing sides', 0, 150], ]; function ExactRouting() { const s = useDiagramSession(); const field = ([key, label, min, max, hint]: RouteField) => ( s.setRouting({ [key]: value }, 'Change routing settings')} /> ); return (

Spacing

{field}

Costs

{field} {field(['passes', 'Passes', 1, 5])}
); } function LocalTools() { const s = useDiagramSession(); return (
); }