diff --git a/docs/UI_CONTRACT.md b/docs/UI_CONTRACT.md index cc249cd8d..c061ad522 100644 --- a/docs/UI_CONTRACT.md +++ b/docs/UI_CONTRACT.md @@ -67,7 +67,7 @@ This contract preserves the approved MVP concept and prevents feature ownership - The Files viewer renders Markdown (`.md`, `.markdown`, `.mdown`, `.mkd`) as formatted GitHub-Flavored Markdown with fenced code blocks syntax-highlighted, and syntax-highlights recognized code files by the language detected from their extension while unknown languages stay plain monospaced text. All rendered output is sanitized: raw HTML and scripts never render and event-handler attributes and dangerous link schemes such as `javascript:` are neutralized. Activating an `http(s)` link opens it in the built-in browser while other schemes are inert, only embedded `data:` images render while remote or relative sources fall back to alt text or a placeholder without a network request, and text or code above the rich-rendering size threshold falls back to plain text with a notice. - An authenticated connection or heartbeat alone never shows agent presence. A branded badge appears only after that agent actually issues a browser command, and its cursor appears only after a real pointer position exists. Claude uses `#D97757`, Codex `#10A37F`, Qwen `#6D44E8`, Kimi `#7C5CFC`, OpenCode `#5A5858`, Hermes `#D6A700`, and an unknown provider `#7A8291`. Browser Settings separately controls indicator visibility without revoking browser access; the agent-access kill switch revokes the connection itself. - With window snapping enabled, drag and resize use a hidden `10px` grid and a `10px` magnetic threshold for neighboring edges, centers, and a consistent `20px` gap. -- The empty-canvas context menu also lists Files and a **Tools** submenu between Browser and Settings. **Tools** holds a single **Auto-sort** action whose criteria (by task, i.e. subagents to the right of the session that spawned them; by status; by project folder; grid) are radio rows in that submenu; there is no separate layouts surface, toolbar, or saved preset. Auto-sort moves the windows of the current multi-selection when it holds at least two, or else every terminal, plugin, and Browser window that is not completely inside a region (companion mascots move only when selected); sticky notes, materials, and Files cards never move. The sorted block keeps the snapping grid and `20px` gap when snapping is on, and shifts right or down until it is clear of HOME, regions, notes, materials, Files cards, and windows it does not move. The moved windows show the existing selection outline for a few seconds or until the next press; it is presentation-only and does not select them. They glide into place unless reduced motion is requested, and **Undo auto-sort** stays in the same submenu while any of them is still where the sort put it. Undo restores only those untouched windows; there is no global undo shortcut, so terminal and text inputs keep their keys. The criterion is remembered only for the running session. +- The empty-canvas context menu also lists Files and a **Tools** submenu between Browser and Settings. **Tools** holds a single **Auto-sort** action whose criteria (by task, i.e. subagents to the right of the session that spawned them; by status; by project folder; grid) are radio rows in that submenu; there is no separate layouts surface, toolbar, or saved preset. Auto-sort moves the windows of the current multi-selection when it holds at least two, or else every terminal, plugin, and Browser window that is not completely inside a region (companion mascots move only when selected); sticky notes, materials, and Files cards never move. The sorted block keeps the snapping grid and `20px` gap when snapping is on, and shifts right or down until it is clear of HOME, regions, notes, materials, Files cards, and windows it does not move. The moved windows show the existing selection outline for a few seconds or until the next press; it is presentation-only and does not select them. They glide into place unless reduced motion is requested, and **Undo auto-sort** stays in the same submenu while any of them is still where the sort put it. Undo restores only those untouched windows; there is no global undo shortcut, so terminal and text inputs keep their keys. The criterion is remembered only for the running session. A region's Tools submenu sorts only the windows inside that region and keeps them there: the arrangement goes to the region's center, or to the clear place nearest it when something is in the way; if the near-square grid does not fit, the nearest column count that fits is used (the task tree keeps its shape), and the sort is refused only when no shape fits anywhere in the region. - One trusted context dispatcher owns right-clicks on the canvas. Truly empty canvas offers region creation, a sticky note, the Settings-configured launcher submenu, Browser, and Settings. Holding RMB on empty canvas also opens the configurable radial quick launcher: moving toward an action and releasing activates it, while a stationary right-click continues to open the standard empty-canvas menu. Region and note right-clicks remain context-specific. A region offers rename, color, a note at the pressed point, and region-only deletion. A note frame offers edit, bring-to-front, and deletion. Terminal, Browser, plugin, textarea/input, and contenteditable surfaces keep their native context menus; middle-button panning is unchanged. `Cmd/Ctrl+K` opens a searchable palette over live sessions and the same global creation/launch actions. Regions persist independently of terminal restore, render behind HOME and windows, resize from every edge/corner, and move every terminal, plugin, Browser, or note whose complete bounds were inside the region at drag start. Attached contents follow the region continuously during the gesture and persist once at pointer release; deleting a region never deletes its contents. Sticky notes persist bounded text and geometry, snap like other windows, and resize from every edge/corner. General Settings exposes independent **Save colored regions after exit** and **Save notes after exit** controls. Both default on to preserve existing profiles. Turning either off removes only that collection from disk persistence without deleting its live canvas objects; turning it back on saves the current collection, while leaving it off starts the next launch with that collection empty. - Context menus, region editors, the radial launcher, and the command palette use official Lucide/provider assets and shared application color tokens. Their dimensions follow root `--ui-scale`. Appearance owns the `0.85–1.25` scale in `0.05` steps and the sage/lilac/night system palette; the scale changes UI chrome rather than canvas zoom or terminal font size. Agents owns the independent context-menu and radial-launcher subsets and their safe reset defaults. - Settings uses the approved two-pane modal grammar: a persistent icon-labelled sidebar for all seven sections, a separate current-section header, and a scrollable content pane. Settings must not fall back to the legacy light slide-over with one horizontal segmented tab strip. Simple settings use compact copy/control rows; all Settings chrome reads the active system tokens, official Lucide assets, and root `--ui-scale`. diff --git a/docs/UI_CONTRACT.ru.md b/docs/UI_CONTRACT.ru.md index 28339d575..51998905a 100644 --- a/docs/UI_CONTRACT.ru.md +++ b/docs/UI_CONTRACT.ru.md @@ -58,7 +58,7 @@ - Drag по пустому canvas всегда выполняет pan. В свежем профиле обычный scroll над пустым canvas перемещает его по обеим осям, а pinch и `Cmd/Ctrl + scroll` масштабируют вокруг указателя. **Зум обычным скроллом** возвращает исторический wheel zoom и автоматически включается при миграции существующего профиля. Только focused input-виджет прерывает canvas wheel/pinch; над unfocused или нефокусируемым виджетом события остаются канвасу. **Перехват wheel/pinch над виджетами** имеет режимы Off, On и Key: Off сохраняет владение focused-виджета, On постоянно передаёт канвасу только wheel/pinch, а Key делает это при удержании комбинации. Поэтому focused live Browser page прокручивается обычным scroll в Off или при отпущенном Key; unfocused Browser, On, активный Key binding, полный override, pinch и `Cmd/Ctrl + scroll` принадлежат канвасу. Выбранный в начале Browser wheel-sequence владелец сохраняется до 250 мс без wheel-событий. Browser summary и placeholder всегда принадлежат канвасу. Свежий профиль использует Key с `Command` на macOS или `Ctrl` на остальных платформах. Отдельный **Перехват навигации канвасом** (по умолчанию `Option` на macOS и `Alt` на остальных платформах) передаёт wheel/pinch и drag; одиночный Command/Ctrl разрешён. При удержании полного override все canvas-поверхности показывают `grab`, а начатый pan — `grabbing` до pointer up/cancel даже после отпускания комбинации. - Мини-карта центрирует камеру по нажатию без изменения масштаба. В Controls выбирается **Клик** (по умолчанию, движение указателя игнорируется) или **Перетаскивание** (мини-карта захватывает указатель и непрерывно двигает камеру); клавиши-стрелки работают в обоих режимах. - Canvas двигается RTS-style, пока указатель находится в пределах `56px` от viewport edge над пустым canvas; скорость линейно возрастает до `900px/s` на самой границе. Edge panning выключен по умолчанию и включается в Settings. Motion останавливается над interactive surfaces и во время drag-pan. -- Контекстное меню пустого канваса содержит подменю **Инструменты** с одним действием **Автосортировка**. Критерии (по задачам — субагенты справа от запустившей их сессии; по статусу; по папке проекта; сеткой) — пункты-переключатели в том же подменю, без отдельной панели, тулбара или сохранённых раскладок. Сортируются окна текущего множественного выделения, если их хотя бы два, а иначе — все окна терминалов, плагинов и браузера, которые не лежат целиком внутри региона (маскоты — только если выделены); заметки, материалы и карточки Files не двигаются. При включённой привязке блок держит сетку и зазор `20px`, и сдвигается вправо или вниз, пока не перестанет задевать HOME, регионы, заметки, материалы, карточки Files и неперемещаемые окна. Перемещённые окна на несколько секунд (или до следующего нажатия) получают обычную обводку выделения — только визуально, без выделения — и плавно переезжают, если не включено уменьшение движения. Пункт **Отменить автосортировку** остаётся в подменю, пока хотя бы одно окно стоит там, куда его поставила сортировка, и возвращает только нетронутые окна. Глобального сочетания отмены нет: клавиши остаются у терминалов и полей ввода. Выбранный критерий помнится только до перезапуска. +- Контекстное меню пустого канваса содержит подменю **Инструменты** с одним действием **Автосортировка**. Критерии (по задачам — субагенты справа от запустившей их сессии; по статусу; по папке проекта; сеткой) — пункты-переключатели в том же подменю, без отдельной панели, тулбара или сохранённых раскладок. Сортируются окна текущего множественного выделения, если их хотя бы два, а иначе — все окна терминалов, плагинов и браузера, которые не лежат целиком внутри региона (маскоты — только если выделены); заметки, материалы и карточки Files не двигаются. При включённой привязке блок держит сетку и зазор `20px`, и сдвигается вправо или вниз, пока не перестанет задевать HOME, регионы, заметки, материалы, карточки Files и неперемещаемые окна. Перемещённые окна на несколько секунд (или до следующего нажатия) получают обычную обводку выделения — только визуально, без выделения — и плавно переезжают, если не включено уменьшение движения. Пункт **Отменить автосортировку** остаётся в подменю, пока хотя бы одно окно стоит там, куда его поставила сортировка, и возвращает только нетронутые окна. Глобального сочетания отмены нет: клавиши остаются у терминалов и полей ввода. Выбранный критерий помнится только до перезапуска. Подменю **Инструменты** региона сортирует только окна внутри этого региона и оставляет их в нём: раскладка встаёт в центр региона, а если там что-то мешает — в ближайшее к центру свободное место; если почти квадратная сетка не помещается, берётся ближайшее подходящее число колонок (дерево задач сохраняет свою форму), и сортировка отказывает, только когда ни одна форма нигде в регионе не помещается. - Dialog close actions остаются внутри своей header/control row с одинаковым inset и не перекрывают field, outline или panel boundary. ## Приёмочные проверки diff --git a/docs/UI_CONTRACT.zh-CN.md b/docs/UI_CONTRACT.zh-CN.md index 99618b3e3..a42d6c30c 100644 --- a/docs/UI_CONTRACT.zh-CN.md +++ b/docs/UI_CONTRACT.zh-CN.md @@ -57,7 +57,7 @@ - Window snapping 开启时,drag/resize 使用隐藏 `10px` grid、相邻 edge/center 的 `10px` magnetic threshold,以及一致的 `20px` gap。 - 在空白 canvas 上 drag 始终执行 pan。新配置中,空白 canvas 上的普通 scroll 会沿两个轴移动,pinch 与 `Cmd/Ctrl + scroll` 会以指针为中心缩放。**Use scroll wheel to zoom** 恢复历史 wheel zoom,并在迁移现有配置时自动启用。只有 focused input widget 会中断 canvas wheel/pinch;在 unfocused 或不可聚焦 widget 上,事件仍归 canvas。**Wheel/pinch capture over widgets** 有 Off、On、Key 三种模式:Off 保留 focused-widget ownership,On 始终只交给 canvas,Key 仅在按住绑定键时交给 canvas。因此,focused live Browser page 在 Off 或 Key 未按下时会由普通 scroll 原生滚动;unfocused Browser、On、激活的 Key binding、完整 override、pinch 与 `Cmd/Ctrl + scroll` 都归 canvas。Browser wheel sequence 开始时选定的 owner 会保持到 250 ms 没有 wheel event。Browser summary 与 placeholder 始终归 canvas。新配置默认使用 Key,在 macOS 为 `Command`,其他平台为 `Ctrl`。独立的 **Canvas navigation override**(macOS 默认 `Option`,其他平台默认 `Alt`)接管 wheel/pinch 与 drag,也允许单独 Command/Ctrl。按住完整 override 时所有 canvas surface 显示 `grab`;已开始的 pan 会显示 `grabbing`,并由 canvas 持有到 pointer up/cancel。 - 指针停在空白 canvas 的 viewport edge `56px` 范围内时,canvas 以 RTS 风格 edge-pan;速度线性增加,到边缘达到 `900px/s`。Edge panning 默认关闭,在 Settings 启用。指针位于 interactive surface 或正在 drag-pan 时暂停。 -- 空白画布的右键菜单包含 **Tools** 子菜单,其中只有一个 **Auto-sort** 操作。排序条件(按任务:子代理放在启动它的会话右侧;按状态;按项目文件夹;网格)是同一子菜单中的单选行,不提供单独的面板、工具栏或保存的布局。当前多选中至少有两个窗口时,Auto-sort 只移动这些窗口;否则,移动所有未完全位于区域内的终端、插件与 Browser 窗口(吉祥物仅在被选中时移动);便签、素材与 Files 卡片从不移动。开启吸附时排列保持 10px 网格与 `20px` 间距,并向右或向下移动,直到不再覆盖 HOME、区域、便签、素材、Files 卡片和未参与排序的窗口。被移动的窗口在几秒内(或直到下一次按下)显示现有的选中轮廓,这只是视觉提示,不会选中它们;在未要求减少动态效果时平滑移动。只要仍有窗口停在排序放置的位置,**Undo auto-sort** 就保留在同一子菜单中,并且只恢复这些未被改动的窗口。没有全局撤销快捷键,终端与文本输入保留自己的按键。所选条件只在本次运行期间记住。 +- 空白画布的右键菜单包含 **Tools** 子菜单,其中只有一个 **Auto-sort** 操作。排序条件(按任务:子代理放在启动它的会话右侧;按状态;按项目文件夹;网格)是同一子菜单中的单选行,不提供单独的面板、工具栏或保存的布局。当前多选中至少有两个窗口时,Auto-sort 只移动这些窗口;否则,移动所有未完全位于区域内的终端、插件与 Browser 窗口(吉祥物仅在被选中时移动);便签、素材与 Files 卡片从不移动。开启吸附时排列保持 10px 网格与 `20px` 间距,并向右或向下移动,直到不再覆盖 HOME、区域、便签、素材、Files 卡片和未参与排序的窗口。被移动的窗口在几秒内(或直到下一次按下)显示现有的选中轮廓,这只是视觉提示,不会选中它们;在未要求减少动态效果时平滑移动。只要仍有窗口停在排序放置的位置,**Undo auto-sort** 就保留在同一子菜单中,并且只恢复这些未被改动的窗口。没有全局撤销快捷键,终端与文本输入保留自己的按键。所选条件只在本次运行期间记住。区域的 **Tools** 子菜单只整理该区域内的窗口,并让它们留在区域内:排列放在区域中央;若中央有遮挡,则放在离中央最近的空位;若近似正方形的网格放不下,则改用最接近且能放下的列数(任务树保持原有形状);只有任何形状都无法放入区域时才拒绝排序。 - Dialog close action 留在自己的 header/control row 内,使用一致 inset,不覆盖 field、outline 或 panel boundary。 ## 验收检查 diff --git a/src/renderer/src/features/workspace/canvasAutoSort.ts b/src/renderer/src/features/workspace/canvasAutoSort.ts index 981d59948..ce5395695 100644 --- a/src/renderer/src/features/workspace/canvasAutoSort.ts +++ b/src/renderer/src/features/workspace/canvasAutoSort.ts @@ -37,7 +37,7 @@ export interface CanvasAutoSortOptions { /** Fixed areas the block may not cover, e.g. HOME and canvas regions. */ avoid?: readonly SessionBounds[]; snapToGrid?: boolean; - /** For a region plan: center the existing arrangement inside it, or refuse the whole step. */ + /** For a region plan: the region the arrangement must fit into (see `placeInRegion`). */ within?: SessionBounds; } @@ -76,8 +76,16 @@ export function planCanvasAutoSort( if (items.length < 2) return null; const sorted = new Set(items.map((item) => item.id)); const obstacles = [...options.avoid ?? [], ...[...bounds].filter(([id]) => !sorted.has(id)).map(([, value]) => value)]; - const arranged = arrangeCanvasAutoSort(items, mode, { avoid: options.within ? [] : obstacles, snapToGrid: options.snapToGrid }); - const after = options.within ? centerInRegion(arranged, options.within, obstacles, options.snapToGrid === true) : arranged; + const snapToGrid = options.snapToGrid === true; + const region = options.within; + let after: Map | null = null; + if (!region) after = arrangeCanvasAutoSort(items, mode, { avoid: obstacles, snapToGrid }); + else { + for (const columns of regionShapes(items, mode)) { + after = placeInRegion(arrangeWith(items, mode, [], snapToGrid, columns), region, obstacles, snapToGrid); + if (after) break; + } + } if (!after) return null; return { before: new Map(items.map((item) => [item.id, item.bounds])), @@ -90,27 +98,72 @@ const GAP = 20; const GROUP_GAP = 2 * GAP; const GRID = 10; -function centerInRegion( +/** How many columns a grid of `count` windows gets; the default is a near-square grid. */ +type Columns = (count: number) => number; +const nearSquare: Columns = (count) => Math.max(1, Math.ceil(Math.sqrt(count))); + +/** + * The grid shapes a region sort tries, in order: the usual near-square grid first, so a layout that + * fits keeps it, then every other column limit, nearest to the usual count first and fewer columns + * before more on a tie. The limit applies to the whole grid, or to each criterion group. The task + * tree has only its own shape. + */ +function regionShapes(items: readonly CanvasAutoSortItem[], mode: CanvasAutoSortMode): Columns[] { + if (mode === "task") return [nearSquare]; + const largest = Math.max(...(mode === "grid" ? [items.length] : [...criterionGroups(items, mode).values()].map((group) => group.length))); + const usual = nearSquare(largest); + const limits = Array.from({ length: largest }, (_, index) => index + 1) + .filter((limit) => limit !== usual || mode !== "grid") + .sort((left, right) => Math.abs(left - usual) - Math.abs(right - usual) || left - right); + return [nearSquare, ...limits.map((limit): Columns => (count) => Math.min(count, limit))]; +} + +/** + * Where the arranged block goes inside a region, or null when no place there holds it. The block + * keeps 20px from the region edges and 60px below its top for the title, and the gap from every + * obstacle. It goes to the center when that is clear; otherwise to the clear place nearest the + * center (topmost, then leftmost, on a tie). With snapping every window stays on the grid. + */ +function placeInRegion( arranged: ReadonlyMap, region: SessionBounds, obstacles: readonly SessionBounds[], snap: boolean ): Map | null { - // Keep 20px at the edges and 60px above the content for the existing region title. const content = { position: { x: region.position.x + GAP, y: region.position.y + 3 * GAP }, size: { width: region.size.width - 2 * GAP, height: region.size.height - 4 * GAP } }; const block = boundingBox([...arranged.values()]); + const up = (value: number): number => snap ? Math.ceil(value / GRID) * GRID : Math.ceil(value); + const down = (value: number): number => snap ? Math.floor(value / GRID) * GRID : Math.floor(value); const round = (value: number): number => snap ? Math.round(value / GRID) * GRID : Math.round(value); - const x = round(content.position.x + (content.size.width - block.size.width) / 2); - const y = round(content.position.y + (content.size.height - block.size.height) / 2); - if (x < content.position.x || y < content.position.y - || x + block.size.width > content.position.x + content.size.width - || y + block.size.height > content.position.y + content.size.height) return null; - const margin = { position: { x: x - GAP, y: y - GAP }, size: { width: block.size.width + 2 * GAP, height: block.size.height + 2 * GAP } }; - // shortcut: reject an obstructed centered block; add bounded placement search only if requested. - if (obstacles.some((obstacle) => overlaps(margin, obstacle))) return null; + const inside = obstacles.filter((obstacle) => overlaps(region, obstacle)); + // Every free place can slide up and left until an edge or an obstacle stops it, so the region + // edges and the obstacles' edges (plus the center) are the only places worth checking. + const spots = (axis: "x" | "y"): { center: number; values: number[] } => { + const length = axis === "x" ? block.size.width : block.size.height; + const far = (bounds: SessionBounds): number => bounds.position[axis] + (axis === "x" ? bounds.size.width : bounds.size.height); + const low = up(content.position[axis]); + const high = down(far(content) - length); + const center = Math.min(high, Math.max(low, round(content.position[axis] + (far(content) - content.position[axis] - length) / 2))); + const values = [low, high, center, ...inside.flatMap((obstacle) => [up(far(obstacle) + GAP), down(obstacle.position[axis] - GAP - length)])] + .filter((value) => value >= low && value <= high); + return { center, values: [...new Set(values)].sort((left, right) => left - right) }; + }; + const xs = spots("x"); + const ys = spots("y"); + let best: (Point & { distance: number }) | null = null; + for (const y of ys.values) { + for (const x of xs.values) { + const distance = (x - xs.center) ** 2 + (y - ys.center) ** 2; + if (best && distance >= best.distance) continue; + const margin = { position: { x: x - GAP, y: y - GAP }, size: { width: block.size.width + 2 * GAP, height: block.size.height + 2 * GAP } }; + if (!inside.some((obstacle) => overlaps(margin, obstacle))) best = { x, y, distance }; + } + } + if (!best) return null; + const { x, y } = best; return new Map([...arranged].map(([id, bounds]) => [id, at(x + bounds.position.x - block.position.x, y + bounds.position.y - block.position.y, bounds) ])); @@ -130,17 +183,26 @@ export function arrangeCanvasAutoSort( items: readonly CanvasAutoSortItem[], mode: CanvasAutoSortMode, options: CanvasAutoSortOptions = {} +): Map { + return arrangeWith(items, mode, options.avoid ?? [], options.snapToGrid === true, nearSquare); +} + +function arrangeWith( + items: readonly CanvasAutoSortItem[], + mode: CanvasAutoSortMode, + avoid: readonly SessionBounds[], + snap: boolean, + columns: Columns ): Map { if (items.length === 0) return new Map(); - const snap = options.snapToGrid === true; const step: Step = (edge, gap = GAP) => (snap ? Math.ceil((edge + gap) / GRID) * GRID : edge + gap); - const local = arrangeAt(items, mode, step); + const local = arrangeAt(items, mode, step, columns); const extent = boundingBox([...local.values()]).size; const current = boundingBox(items.map((item) => item.bounds)).position; const start = snap ? { x: Math.round(current.x / GRID) * GRID, y: Math.round(current.y / GRID) * GRID } : { x: Math.round(current.x), y: Math.round(current.y) }; - const origin = clearSpot(start, extent, options.avoid ?? [], step); + const origin = clearSpot(start, extent, avoid, step); const result = new Map(); for (const [id, bounds] of local) result.set(id, at(bounds.position.x + origin.x, bounds.position.y + origin.y, bounds)); return result; @@ -167,22 +229,16 @@ function clearSpot(start: Point, size: SessionBounds["size"], obstacles: readonl return down.y - start.y < right.x - start.x ? down : right; } -function arrangeAt(items: readonly CanvasAutoSortItem[], mode: CanvasAutoSortMode, step: Step): Map { +function arrangeAt(items: readonly CanvasAutoSortItem[], mode: CanvasAutoSortMode, step: Step, columns: Columns): Map { const ordered = [...items].sort(readingOrder); if (mode === "task") return arrangeTaskTree(ordered, step); - if (mode === "grid") return arrangeGrid(ordered, 0, step); - const groups = new Map(); - for (const item of ordered) { - const key = mode === "status" ? statusGroup(item.status) : projectGroup(item.project); - const group = groups.get(key) ?? []; - group.push(item); - groups.set(key, group); - } + if (mode === "grid") return arrangeGrid(ordered, 0, step, columns); + const groups = criterionGroups(ordered, mode); const result = new Map(); let x = 0; for (const key of [...groups.keys()].sort(compareText)) { let right = x; - for (const [id, bounds] of arrangeGrid(groups.get(key)!, x, step)) { + for (const [id, bounds] of arrangeGrid(groups.get(key)!, x, step, columns)) { result.set(id, bounds); right = Math.max(right, bounds.position.x + bounds.size.width); } @@ -191,6 +247,18 @@ function arrangeAt(items: readonly CanvasAutoSortItem[], mode: CanvasAutoSortMod return result; } +/** The status or project groups, each in the order of `items`. */ +function criterionGroups(items: readonly CanvasAutoSortItem[], mode: "status" | "project"): Map { + const groups = new Map(); + for (const item of items) { + const key = mode === "status" ? statusGroup(item.status) : projectGroup(item.project); + const group = groups.get(key) ?? []; + group.push(item); + groups.set(key, group); + } + return groups; +} + /** Orchestrators in a column, each subagent to the right of the session that spawned it. */ function arrangeTaskTree(ordered: readonly CanvasAutoSortItem[], step: Step): Map { const byId = new Map(ordered.map((item) => [item.id, item])); @@ -265,9 +333,9 @@ function arrangeTaskTree(ordered: readonly CanvasAutoSortItem[], step: Step): Ma return result; } -/** A near-square grid; each column is as wide as its widest window and each row as tall as its tallest. */ -function arrangeGrid(ordered: readonly CanvasAutoSortItem[], left: number, step: Step): Map { - const columns = Math.max(1, Math.ceil(Math.sqrt(ordered.length))); +/** A grid filled row by row; each column is as wide as its widest window and each row as tall as its tallest. */ +function arrangeGrid(ordered: readonly CanvasAutoSortItem[], left: number, step: Step, columnsFor: Columns): Map { + const columns = Math.max(1, Math.min(ordered.length, columnsFor(ordered.length))); const rows = Math.ceil(ordered.length / columns); const columnWidths = Array.from({ length: columns }, () => 0); const rowHeights = Array.from({ length: rows }, () => 0); diff --git a/tests/canvas-auto-sort.test.mjs b/tests/canvas-auto-sort.test.mjs index 369bacb3f..fab0c8142 100644 --- a/tests/canvas-auto-sort.test.mjs +++ b/tests/canvas-auto-sort.test.mjs @@ -419,13 +419,111 @@ test("every region criterion centers the existing layout, keeps grid and sizes, assert.ok(placed.position.y + placed.size.height <= region.position.y + region.size.height - 20); } assert.deepEqual(planCanvasAutoSort([...bounds.keys()], plan.after, sessions, (id) => `terminal:${id}`, mode, options).after, plan.after); + // An obstacle on the centered spot moves the block to the nearest clear place; one covering the region refuses. const obstructed = new Map([...bounds, ["note:fixed", block]]); - assert.equal(planCanvasAutoSort([...bounds.keys()], obstructed, sessions, (id) => `terminal:${id}`, mode, options), null); - assert.equal(planCanvasAutoSort([...bounds.keys()], bounds, sessions, (id) => `terminal:${id}`, mode, { ...options, avoid: [block] }), null); + const moved = planCanvasAutoSort([...bounds.keys()], obstructed, sessions, (id) => `terminal:${id}`, mode, options); + assert.ok(moved, `${mode} finds a clear place beside the obstacle`); + assertRegionPlacement(moved.after, region, [block], true); + const covered = card(region.position.x + 20, region.position.y + 60, region.size.width - 40, region.size.height - 80); + assert.equal(planCanvasAutoSort([...bounds.keys()], bounds, sessions, (id) => `terminal:${id}`, mode, { ...options, avoid: [covered] }), null); assert.equal(planCanvasAutoSort([...bounds.keys()], bounds, sessions, (id) => `terminal:${id}`, mode, { within: card(3_000, 0, 800, 600) }), null); } }); +/** A valid region placement: inside the region's content area, gap-clear of each other and of every obstacle. */ +function assertRegionPlacement(placements, region, obstacles, snap) { + for (const [id, placed] of placements) { + assert.ok(placed.position.x >= region.position.x + 20 && placed.position.y >= region.position.y + 60, `${id} inside`); + assert.ok(placed.position.x + placed.size.width <= region.position.x + region.size.width - 20, `${id} inside right`); + assert.ok(placed.position.y + placed.size.height <= region.position.y + region.size.height - 20, `${id} inside bottom`); + if (snap) assert.ok(placed.position.x % 10 === 0 && placed.position.y % 10 === 0, `${id} on grid`); + for (const obstacle of obstacles) assert.equal(overlaps(grown(placed, GAP), obstacle), false, `${id} clear of obstacle`); + for (const [other, bounds] of placements) { + if (other !== id) assert.equal(overlaps(grown(placed, GAP), bounds), false, `${id} and ${other} keep the gap`); + } + } +} + +test("a region sort uses another column count when the near-square grid does not fit but another one does", () => { + // Content area 2160 x 480: three 700 x 430 windows fit in one row (2140 wide) but not as a 2 x 2 grid (880 tall). + const region = card(3_000, 0, 2_200, 560); + const bounds = new Map([["a", card(3_100, 100)], ["b", card(3_900, 100)], ["c", card(3_100, 600)]]); + const feasible = new Map([["a", card(3_030, 90)], ["b", card(3_750, 90)], ["c", card(4_470, 90)]]); + assertRegionPlacement(feasible, region, [], true); + const plan = planCanvasAutoSort([...bounds.keys()], bounds, [], (id) => id, "grid", { within: region, snapToGrid: true }); + assert.ok(plan, "three windows in one row fit the region"); + assert.deepEqual(plan.after, feasible); + assert.deepEqual(planCanvasAutoSort([...bounds.keys()], plan.after, [], (id) => id, "grid", { within: region, snapToGrid: true }).after, + plan.after, "sorting again keeps the row"); + + // By status: one waiting and three working windows are 2160 wide side by side in the usual shape; content is 1460 x 1420. + // One column per group is 1440 x 1330 and fits. + const tall = card(3_000, 0, 1_500, 1_500); + const windows = [ + terminal("w1", 3_100, 100, { status: "working" }), terminal("w2", 3_900, 100, { status: "working" }), + terminal("w3", 3_100, 600, { status: "working" }), terminal("n", 3_900, 600, { status: "needs_approval" }) + ]; + const statusBounds = new Map(windows.map(([id, value]) => [id, value])); + const sessions = windows.map(([, , session]) => session); + const columns = new Map([ + ["terminal:n", card(3_030, 110)], + ["terminal:w1", card(3_770, 110)], ["terminal:w2", card(3_770, 560)], ["terminal:w3", card(3_770, 1_010)] + ]); + assertRegionPlacement(columns, tall, [], true); + const byStatus = planCanvasAutoSort([...statusBounds.keys()], statusBounds, sessions, (id) => `terminal:${id}`, "status", { within: tall, snapToGrid: true }); + assert.ok(byStatus, "one column per status group fits the region"); + assert.deepEqual(byStatus.after, columns); + + // The usual shape is kept whenever it fits, so roomy regions sort exactly as before. + const roomy = planCanvasAutoSort([...bounds.keys()], bounds, [], (id) => id, "grid", { within: card(3_000, 0, 3_000, 2_400), snapToGrid: true }); + assert.equal(new Set([...roomy.after.values()].map((value) => value.position.y)).size, 2, "a 2 x 2 grid in a roomy region"); +}); + +test("a region sort places the block beside an obstacle near the center instead of refusing", () => { + // Content area 2960 x 2320 with a 400 x 300 note in the middle. The centered 1420 x 430 block would cover it, + // but the block fits 20px below it (y 1370..1800) or above it (y ..600); below is nearer the center. + const region = card(3_000, 0, 3_000, 2_400); + const note = card(4_300, 1_050, 400, 300); + const bounds = new Map([["a", card(3_100, 100)], ["b", card(3_100, 600)], ["note:n", note]]); + const feasible = new Map([["a", card(3_790, 1_370)], ["b", card(4_510, 1_370)]]); + assertRegionPlacement(feasible, region, [note], true); + const plan = planCanvasAutoSort(["a", "b"], bounds, [], (id) => id, "grid", { within: region, snapToGrid: true }); + assert.ok(plan, "the region has room around the note"); + assert.deepEqual(plan.after, feasible); + const again = new Map([...bounds, ...plan.after]); + assert.deepEqual(planCanvasAutoSort(["a", "b"], again, [], (id) => id, "grid", { within: region, snapToGrid: true }).after, plan.after); + + // A region that overlaps this one: its part inside is an obstacle, the free part still holds the block. + const other = card(4_000, 0, 3_000, 1_000); + const shared = planCanvasAutoSort(["a", "b"], new Map([["a", card(3_100, 1_100)], ["b", card(3_100, 1_600)]]), [], (id) => id, "grid", + { within: region, avoid: [other], snapToGrid: true }); + assert.ok(shared, "the region's free lower part holds the block"); + assertRegionPlacement(shared.after, region, [other], true); +}); + +test("region placements are always inside, gap-clear and independent of list order", () => { + let seed = 7; + const next = (limit) => (seed = (seed * 1_103_515_245 + 12_345) % 2_147_483_648) % limit; + let placed = 0; + for (let round = 0; round < 300; round += 1) { + const region = card(3_000 + next(9), next(9), 900 + next(2_400), 700 + next(2_000)); + const items = mixedItems(2 + next(7)).map((item) => ({ ...item, bounds: card(region.position.x + next(800), region.position.y + next(600), item.bounds.size.width, item.bounds.size.height) })); + const notes = Array.from({ length: next(4) }, (_, index) => [`note:${index}`, card(region.position.x + next(region.size.width), region.position.y + next(region.size.height), 100 + next(400), 100 + next(300))]); + const bounds = new Map([...items.map((item) => [item.id, item.bounds]), ...notes]); + const sessions = items.map((item) => ({ id: item.id, status: item.status, cwd: item.project, startedAt: item.startedAt })); + const snapToGrid = round % 2 === 0; + for (const mode of CANVAS_AUTO_SORT_MODES) { + const ids = items.map((item) => item.id); + const plan = planCanvasAutoSort(ids, bounds, sessions, (id) => id, mode, { within: region, snapToGrid }); + assert.deepEqual(planCanvasAutoSort([...ids].reverse(), bounds, sessions, (id) => id, mode, { within: region, snapToGrid }), plan); + if (!plan) continue; + placed += 1; + assertRegionPlacement(plan.after, region, notes.map(([, value]) => value), snapToGrid); + } + } + assert.ok(placed > 100, `enough placements were checked (${placed})`); +}); + test("nested or identical zones cannot sort windows shared with the other zone", () => { const outer = card(3_000, 0, 3_000, 2_400); const inner = card(3_100, 100, 2_000, 1_600);