From 557957c8a914388262435b675ad36fcc30ed5856 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 20:28:39 +0900 Subject: [PATCH 1/4] feat(editor): add AI-first main layout with scene rail, Agent/Inspector tabs, and status bar --- .../2026-11-26-editor-ai-first-main-layout.md | 40 + changelog.d/editor-ai-first-main-layout.md | 3 + docs/en/editor.md | 12 + docs/zh/editor.md | 12 + .../fieldmedic/healthplugin/plugin_test.go | 6 +- packages/game/cmd/game/mcp_test.go | 2 +- packages/game/editor/agent_review.go | 1 + packages/game/editor/agent_ui.go | 133 +- packages/game/editor/animation_sprite_test.go | 6 +- packages/game/editor/animation_test.go | 6 +- packages/game/editor/ask_in_place_test.go | 12 +- packages/game/editor/asset_drawer_ui.go | 52 +- .../game/editor/asset_import_model_test.go | 2 + packages/game/editor/asset_import_test.go | 18 +- .../game/editor/audio_mixer_panel_test.go | 16 +- packages/game/editor/clipboard_group.go | 72 +- packages/game/editor/collider3d_gizmo_test.go | 5 +- packages/game/editor/commands.go | 298 +- packages/game/editor/commands_test.go | 16 +- packages/game/editor/cutscene_test.go | 2 +- packages/game/editor/datatable_test.go | 5 +- packages/game/editor/disk_watch_test.go | 6 +- packages/game/editor/editor_test.go | 21 +- .../editorcmd/main_layout_screenshot_test.go | 159 ++ packages/game/editor/export_panel_test.go | 16 +- packages/game/editor/focus_regions_test.go | 70 +- packages/game/editor/gizmo2d.go | 10 +- packages/game/editor/gizmo2d_test.go | 6 +- .../game/editor/gizmo3d_transform_test.go | 11 +- packages/game/editor/i18n.go | 6 + packages/game/editor/i18n_settings_test.go | 49 +- packages/game/editor/input_map_panel_test.go | 14 +- packages/game/editor/layers_test.go | 29 +- packages/game/editor/library_test.go | 4 + packages/game/editor/lights2d_test.go | 3 +- packages/game/editor/locales/en.yaml | 38 +- packages/game/editor/locales/zh.yaml | 36 + .../game/editor/localization_panel_test.go | 2 +- packages/game/editor/main_layout_test.go | 552 ++++ .../editor/main_layout_test_helpers_test.go | 51 + packages/game/editor/main_layout_ui.go | 2484 +++++++++++++++++ packages/game/editor/materials_test.go | 1 + packages/game/editor/menubar.go | 4 + packages/game/editor/models_test.go | 19 +- packages/game/editor/navmesh3d_test.go | 6 +- packages/game/editor/navregion2d_test.go | 9 +- packages/game/editor/objectedit_test.go | 1 + packages/game/editor/overlays_ui.go | 71 +- packages/game/editor/overrides_test.go | 3 + packages/game/editor/parallax_test.go | 4 +- packages/game/editor/particles_test.go | 2 +- packages/game/editor/plugin_3d_test.go | 2 +- packages/game/editor/plugin_test.go | 56 +- packages/game/editor/problems.go | 3 + packages/game/editor/problems_test.go | 10 +- packages/game/editor/project.go | 27 +- packages/game/editor/project_assets_test.go | 3 +- .../editor/project_settings_panel_test.go | 26 +- packages/game/editor/project_test.go | 6 +- packages/game/editor/refs_test.go | 3 +- packages/game/editor/remote_test.go | 2 +- packages/game/editor/rig_test.go | 1 + packages/game/editor/rooms_test.go | 7 +- packages/game/editor/run_output_test.go | 34 +- packages/game/editor/scenefile_test.go | 25 +- packages/game/editor/scenesettings_test.go | 4 +- packages/game/editor/scenetree.go | 238 +- packages/game/editor/scenetree_test.go | 4 +- packages/game/editor/search_test.go | 2 + packages/game/editor/selection_test.go | 19 +- packages/game/editor/settings_pages_test.go | 31 +- packages/game/editor/shapes2d_test.go | 24 +- packages/game/editor/shortcuts.go | 2 +- packages/game/editor/shortcuts_test.go | 35 +- packages/game/editor/snap_test.go | 19 +- packages/game/editor/state.go | 49 +- packages/game/editor/states_test.go | 2 +- packages/game/editor/terrain3d_test.go | 2 +- packages/game/editor/terrain_test.go | 8 +- packages/game/editor/tile_review_test.go | 2 +- packages/game/editor/tilebrush_test.go | 6 +- packages/game/editor/tilemap_setup_test.go | 10 +- .../game/editor/tilepaint_layered_test.go | 2 +- packages/game/editor/tilepalette.go | 5 + packages/game/editor/tilepalette_test.go | 10 +- packages/game/editor/tileset_editor_test.go | 12 +- packages/game/editor/tilestroke_test.go | 29 +- packages/game/editor/toasts_test.go | 17 +- packages/game/editor/ui.go | 80 +- packages/game/editor/view2d_test.go | 19 +- packages/game/editor/viewport.go | 9 +- packages/game/editor/viewport3d_gpu_test.go | 3 +- .../editor/viewport3d_lod_occluder_test.go | 9 +- packages/game/editor/viewport3d_test.go | 6 +- 94 files changed, 4652 insertions(+), 617 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-26-editor-ai-first-main-layout.md create mode 100644 changelog.d/editor-ai-first-main-layout.md create mode 100644 packages/game/editor/editorcmd/main_layout_screenshot_test.go create mode 100644 packages/game/editor/main_layout_test.go create mode 100644 packages/game/editor/main_layout_test_helpers_test.go create mode 100644 packages/game/editor/main_layout_ui.go diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-ai-first-main-layout.md b/.agents/notes/implemented/feature/2026-11-26-editor-ai-first-main-layout.md new file mode 100644 index 000000000..d634aa11e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-ai-first-main-layout.md @@ -0,0 +1,40 @@ +# Agent Note: AI-first editor main layout with scene rail, Agent/Inspector tabs, and status bar + +Status: implemented + +## Problem + +The previous editor shell placed over twenty tool buttons, panel toggles, and secondary controls across a multi-group top toolbar and exposed docked Files, Assets, Layers, and Library panels by default. That layout left too little space for the viewport and the AI Agent workflow, lacked designed empty, loading, and scene-open error states (failing to open a missing or invalid scene left an ambiguous blank canvas), and mixed legacy control sizing and toggle semantics instead of the `docs/design/editor/Main.dc.html` and `docs/design/editor/Spec.dc.html` contract. + +## Decision + +The editor main window (`packages/game/editor/main_layout_ui.go`, `ui.go`, `agent_ui.go`, `overlays_ui.go`, `scenetree.go`) adopts the five-region AI-first chrome specified in `Main.dc.html` and `Spec.dc.html` while keeping every secondary editor view reachable via commands, menus, Settings, and the status bar. + +### Layout and region contract + +- **44 px header (`mainHeaderView`)**: ` / ` breadcrumb with a scene File menu and unsaved dot (`Label: "unsaved changes"`), centered icon-only tool `base.RadioGroup` (`Select V`, `Move W`, `Rotate E`, `Scale R`, `Pan Space` using 1.8 px@15 px `currentColor` Lucide strokes with `"Label · key"` tooltips), `2D / 3D` segmented radio group, `History (⌘Y)` icon button, `Search ⌘K` Command Palette trigger, and `Play (⌘P)` as the single primary button. +- **232 px left rail (`leftRailSceneView`)**: `Scene / Assets` switch, `SCENE · N nodes` header, scene tree rows showing kind dots, kind tags, and `NEW` badges for pending-review proposed objects (`IsObjectProposedNew`), and a bottom `FILES` section listing the active scene, prefabs/instanced scenes referenced by the open scene (`SceneUsedPrefabs`), and `game.yaml`. Selecting a scene tree row switches the right rail to **Inspector**. +- **Viewport (`ViewportView`, `viewportCameraCaptionView`, `viewportOverlayBarView`)**: camera frame caption (`Camera · W × H`), bottom bar (`Zoom out`, zoom `%`, `Zoom in`, `Snap` `base.Switch` with `RoleSwitch`, `Fit`, `Overlays N`), and top-left overlay legend slot. +- **380 px right panel (`RightRailView`, `AgentPanelView`)**: `Agent` (`⌘1`) and `Inspector` (`⌘2`) radio tabs paired with the live MCP connection chip (`Connected · MCP` and all five states). The header uses `MinHeight: 44` with `Wrap: core.Wrap` so single-line states stay 44 px while the multi-button `Disconnected` state wraps cleanly without clipping inside the 380 px rail. +- **32 px status bar (`mainStatusBarView`)**: muted text on `bg` displaying the active layer button (toggling Layers), live 2D pointer coordinates (`SubscribePointer`), current tool, problem count pill (opening Problems), Output, and Debugger. +- **Keyboard and Spec controls**: builds directly on [focus rings and F6 regions](./2026-11-26-editor-focus-ring-and-regions.md) and [Spec light/dark theme](./2026-11-26-editor-spec-light-theme.md). Every interactive button/radio/switch keeps a hit area of at least `28 × 28`, accessible names, and 2 px Spec focus rings. `bindShortcuts` deliberately skips registering a root-scope `"space"` key listener for `CmdToolPan` because `viewport.go` handles Space-hold panning via `core.KeyHeld(cx, "space")` and a root `"space"` handler would intercept Space before focused buttons, switches, and radios can activate. + +### Workspace states + +`Editor.WorkspaceState()` classifies the workspace into `WorkspaceReady`, `WorkspaceNoProject`, `WorkspaceNoScene`, `WorkspaceLoading` (`SetProjectLoading`), and `WorkspaceSceneError` (`SceneOpenError`, `RetryOpenScene`, `ClearSceneOpenError`). `OpenFile` and `OpenScene` record structured `*loaderr.Error` metadata (file path, line, column, problem, fix) on failure so the left rail, viewport (`RoleAlert` card with Retry and Dismiss), inspector, and status bar render designed recovery states instead of a blank viewport. + +## Alternatives considered + +- **Keeping all secondary panel buttons in a collapsible overflow toolbar**: rejected because the design contract reserves the 44 px header exclusively for breadcrumb, core manipulation tools, 2D/3D, History, Search, and Play; Command Palette (`⌘K`), Menu bar, Settings, and Status bar already provide keyboard-first discovery for every secondary panel (`CmdLayersPanel`, `CmdFileBrowser`, `CmdAssetBrowser`, `CmdLibraryPanel`, `CmdAudioMixer`, `CmdInputMap`, `CmdLocalization`, `CmdExport`, `CmdDataTable`, `CmdSearchPanel`, `CmdAnimate`, `CmdParticleEditor`, `CmdMaterialEditor`, `CmdHUDLayout`, `CmdTerrainEditor`, `CmdNavMeshPanel`). +- **Binding `CmdToolPan`'s `"space"` shortcut via `cx.OnKeyWith("space", ...)` in `bindShortcuts`**: rejected because NSGo root-scope key bindings run ahead of focused button/switch/radio Space activation, breaking keyboard accessibility across panels. Keeping `"space"` on `CmdToolPan` for tooltip/shortcut display while handling Space-hold in `viewport.go` satisfies both panning and keyboard activation. +- **Hardcoding a fixed `Height: 44` without wrap on `right-rail-header`**: rejected because `AgentStatusDisconnected` renders `Disconnected`, `Reconnect`, and `Troubleshoot` beside the `Agent` and `Inspector` tabs, overflowing 380 px when wrapping is disabled. + +## Consequences + +- **Benefits**: + - Clean AI-first chrome matching `Main.dc.html` and `Spec.dc.html` in both Dark and Light appearances at `1440 × 900`. + - Missing or malformed scene files present an actionable alert card with path, line, fix hint, Retry, and Dismiss instead of a blank viewport. + - All five `F6` regions, radio groups, switches, and `>= 28 × 28` hit targets work consistently with keyboard navigation. +- **Costs**: + - Tests and muscle memory that previously clicked legacy top-toolbar panel toggles now invoke the corresponding commands (`CmdSave`, `CmdUndo`, `CmdAudioMixer`, etc.) or status-bar/drawer controls. + - Legacy helper functions still referenced only by dead code paths should be pruned once no remaining callers depend on them. diff --git a/changelog.d/editor-ai-first-main-layout.md b/changelog.d/editor-ai-first-main-layout.md new file mode 100644 index 000000000..70e3919e4 --- /dev/null +++ b/changelog.d/editor-ai-first-main-layout.md @@ -0,0 +1,3 @@ +### Changed + +- `game/editor`: replace the legacy toolbar shell with the AI-first main layout featuring a 44 px header (breadcrumb with unsaved dot, Select/Move/Rotate/Scale/Pan tool radio group, 2D/3D segmented radio, History, Search ⌘K, and Play), 232 px left rail (`SCENE · N nodes` with kind dots, `NEW` review tags, and bottom `FILES` list), viewport camera caption and bottom bar (`Snap` switch, zoom, Fit, Overlays), 380 px right panel (`Agent`/`Inspector` tabs with MCP connection chip), 32 px muted status bar (active layer, pointer coords, tool, Problems, Output, Debugger), and designed empty/loading/scene-error states across all regions (#1007). diff --git a/docs/en/editor.md b/docs/en/editor.md index fdad8eb0b..f9d22d318 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -1602,3 +1602,15 @@ Inside the unified right-rail **Agent** tab (`RightRailView` / `AgentPanelView`, - **Context chips and exact hover preview**: above the composer, attached chips show what joins the request (removable by clicking `×` via `RemoveComposerChip` or pressing `⌫` in an empty composer via `RemoveLastComposerChip`), **Always** chips show `brief.yaml` and `AGENTS.md` when present in the project root, and **Viewport image** is a toggleable chip (`SetViewportImageIncluded` / `ToggleViewportImage`). Selecting an object in the viewport or scene tree only surfaces a dashed `+ · selected` suggestion chip (`SuggestedChip`)—nothing joins the request unless explicitly added (`AcceptSuggestedChip`). `TriggerAskAgentShortcut` attaches the selected object or, when nothing is selected, the whole open scene (`AttachWholeSceneChip`) and focuses the composer. Hovering any chip (`SetHoveredChip` / `HoveredChipPayload`) displays the exact header (`# level_01.scene.yaml · lines 72–78`) and YAML text or image bytes resolved by `ResolveChipPayload`. - **Single-source request assembly**: `AssembleAgentRequest` builds `AgentRequest` from the active chips and nothing else—calling the exact same `ResolveChipPayload` function used on hover—and feeds both `SendComposerPrompt` (`Editor.OnSendAgentComposerRequest`) and `SubmitAgentPrompt` (`Editor.AgentRunner`). - **Context meter ring, breakdown, Compact, and Start fresh**: a 20×20 circular progress ring reflects reported token usage (`SetAgentTokenUsage` or `AgentResponse.Usage`) across three Spec states (normal `≤ 70%`, amber warning `71–89%`, and critical `≥ 90%` `"compact now"`). Clicking the ring opens a 6-row breakdown (**Conversation**, **Open scene**, **Attached**, **Always**, **Tools and instructions**, **Viewport image**) with **Compact thread** (`CompactAgentThread`, folding earlier requests into a summary while keeping the last request whole and dropping the ring) and **Start fresh with summary** (`StartFreshAgentThread`, opening a new thread seeded with that summary). + +## AI-first main layout (#1007) + +The editor's main window (`main_layout_ui.go`, `ui.go`, `agent_ui.go`, `overlays_ui.go`, `scenetree.go`) implements the AI-first workspace from `docs/design/editor/Main.dc.html` using exclusively `docs/design/editor/Spec.dc.html` tokens, sizing, and accessible controls: + +- **44 px header (`mainHeaderView`)**: displays the ` / ` breadcrumb (`ProjectDisplayName`, `SceneBreadcrumbName`) with a Scene file menu and unsaved dot (`aria-label: "unsaved changes"` / `"save failed"`), a centered tool `base.RadioGroup` (`Select V`, `Move W`, `Rotate E`, `Scale R`, `Pan Space` as icon-only Lucide 1.8 px@15 px `currentColor` icons with `"Label · key"` tooltips), a `2D / 3D` segmented radio group, `History (⌘Y)` icon button, `Search ⌘K` palette button, and `Play (⌘P)` as the single primary button. +- **232 px left rail (`leftRailSceneView`)**: combines the `Scene / Assets` switcher with `SCENE · N nodes` (`SceneNodeCount`), scene tree rows carrying kind color dots (`ObjectKindColor`), kind tags (`SceneRailObjectKind`, `LayerKindLabel`), and `NEW` badges on pending-review proposed objects (`IsObjectProposedNew`, `SetProposedNewObjectIDs`), and a bottom `FILES` section listing the open scene, prefabs/instanced scenes it uses (`SceneUsedPrefabs`), and `game.yaml`. Picking a scene tree row switches the right rail to **Inspector**. +- **Viewport caption, bottom bar, and overlay legend**: draws the `Camera · W × H` caption above the 2D camera frame (`viewportCameraCaptionView`), the bottom bar (`Zoom out`, zoom `%`, `Zoom in`, `Snap` as a `base.Switch` with `RoleSwitch` / `aria-checked`, `Fit`, and `Overlays N`), and the top-left overlay legend slot. +- **380 px right panel (`RightRailView`)**: hosts the `Agent` (`⌘1`) and `Inspector` (`⌘2`) radio tabs alongside the thread History toggle and live agent connection chip (`Connected · MCP`, `Working`, `Waiting for you`, `Reconnecting`, `Disconnected`); choosing a tree row switches directly to **Inspector**. +- **32 px status bar (`mainStatusBarView`)**: renders muted text on `bg` with the active layer button (toggling Layers), live 2D pointer coordinates, current tool readout, problem count pill (opening Problems), Output, and Debugger. Secondary views previously hosted on the old toolbar (Settings, Audio Mixer, Input Map, Localization/Strings, Export, Library, Data Table, Project Search, Files, Assets, Animation, Particles, Material, HUD Layout, Terrain, NavMesh) remain reachable through the Command Palette (`⌘K`), Menu bar, Settings, and Status bar. +- **Designed empty, loading, and error states (`WorkspaceState`, `SceneOpenError`)**: every region renders a dedicated state for `WorkspaceNoProject`, `WorkspaceNoScene`, `WorkspaceLoading` (`SetProjectLoading`), and `WorkspaceSceneError` (`SceneOpenError`, `RetryOpenScene`, `ClearSceneOpenError`). Opening a missing or malformed scene YAML renders an alert card with file path, line/column, message, fix guidance, **Retry**, and **Dismiss** instead of a blank viewport. +- **Spec controls and keyboard navigation**: preserves Spec heights (`28 px` rows/tool buttons, `30–32 px` buttons, `44 px` header, `32 px` status bar, no interactive hit area under `28 × 28`), spacing (`4 / 8 / 12 / 16 / 24`), radii (`6 / 8`), `base.RadioGroup` / `base.Radio` and `base.Switch` semantics, 2 px Spec focus rings, accessible names, and `F6` cycling across all five regions (`Header`, `Scene tree`, `Viewport`, `Agent / Inspector`, `Status bar`). diff --git a/docs/zh/editor.md b/docs/zh/editor.md index a51076e10..916ba0425 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -1602,3 +1602,15 @@ func main() { - **上下文标签与精确悬停预览**:输入框上方依次展示已附加标签(点击 `×` 通过 `RemoveComposerChip` 移除,或在空输入框中按 `⌫` 通过 `RemoveLastComposerChip` 移除)、**始终附加**标签(项目根目录中的 `brief.yaml` 与 `AGENTS.md`)以及可开关的 **视口图像** 标签(`SetViewportImageIncluded` / `ToggleViewportImage`)。在视口或场景树中选中对象只会显示虚线建议标签 `+ <名称> · 已选中`(`SuggestedChip`),除非主动添加(`AcceptSuggestedChip`),否则绝不会随请求发送;`TriggerAskAgentShortcut` 会在选中对象时附加该对象,未选中任何对象时附加整个打开的场景(`AttachWholeSceneChip`)并聚焦输入框。悬停任意标签(`SetHoveredChip` / `HoveredChipPayload`)都会通过 `ResolveChipPayload` 显示实际发送的精确头部(如 `# level_01.scene.yaml · lines 72–78`)及对应的 YAML 文本或图像。 - **单一数据源的请求组装**:`AssembleAgentRequest` 仅从当前生效的标签组装 `AgentRequest`(调用与悬停预览完全相同的 `ResolveChipPayload`),并统一供 `SendComposerPrompt`(`Editor.OnSendAgentComposerRequest`)与 `SubmitAgentPrompt`(`Editor.AgentRunner`)使用。 - **上下文计量环、明细、压缩与新开线程**:20×20 环形进度指示器根据智能体回报的 token 用量(`SetAgentTokenUsage` 或 `AgentResponse.Usage`)呈现三种规范状态(正常 `≤ 70%`、超过 70% 警告 `71–89%`、以及 `≥ 90%` 的“立即压缩”状态)。点击计量环可展开 6 项明细(**Conversation**、**Open scene**、**Attached**、**Always**、**Tools and instructions**、**Viewport image**),并提供 **压缩线程**(`CompactAgentThread`,将较早请求折叠为摘要并完整保留最后一条请求,同时降低计量环占比)与 **使用摘要新开**(`StartFreshAgentThread`,以该摘要启动新线程)。 + +## AI 优先的主界面布局(#1007) + +编辑器主窗口(`main_layout_ui.go`、`ui.go`、`agent_ui.go`、`overlays_ui.go`、`scenetree.go`)按 `docs/design/editor/Main.dc.html` 实现 AI 优先工作区,并严格使用 `docs/design/editor/Spec.dc.html` 的颜色令牌、尺寸比例与无障碍控件: + +- **44 px 顶部栏(`mainHeaderView`)**:左侧展示 `<项目> / <场景>` 面包屑(`ProjectDisplayName`、`SceneBreadcrumbName`)、场景文件菜单及未保存圆点(`aria-label` 为 `"unsaved changes"` / `"save failed"`);居中放置工具单选组(`Select V`、`Move W`、`Rotate E`、`Scale R`、`Pan Space`,纯图标 1.8 px@15 px `currentColor` Lucide 图标,悬停提示 `"名称 · 快捷键"`)与 `2D / 3D` 分段单选组;右侧为 `History (⌘Y)` 图标按钮、`Search ⌘K` 命令面板按钮,以及唯一主按钮 `Play (⌘P)`。 +- **232 px 左侧栏(`leftRailSceneView`)**:包含 `Scene / Assets` 切换与 `SCENE · N nodes`(`SceneNodeCount`)标题、带类型色点(`ObjectKindColor`)、类型标签(`SceneRailObjectKind`、`LayerKindLabel`)以及待审查新增对象 `NEW` 标记(`IsObjectProposedNew`、`SetProposedNewObjectIDs`)的场景树行;底部 `FILES` 区域列出当前打开的场景、场景引用的预制体/实例场景(`SceneUsedPrefabs`)以及 `game.yaml`。选中场景树中的节点会自动将右侧栏切换至**检视器(Inspector)**。 +- **视口标题、底部控制条与叠加层图例**:在 2D 相机框上方显示 `Camera · W × H` 标题(`viewportCameraCaptionView`),底部提供缩放控制(缩小、百分比、放大)、`Snap` 开关(`base.Switch`,`RoleSwitch` / `aria-checked`)、`Fit` 与 `Overlays N`,并在左上角保留叠加层图例槽位。 +- **380 px 右侧面板(`RightRailView`)**:承载 `Agent`(`⌘1`)与 `Inspector`(`⌘2`)单选标签、线程历史记录切换按钮及实时连接状态胶囊(`Connected · MCP`、`Working`、`Waiting for you`、`Reconnecting`、`Disconnected`);点击场景树行会自动切到 **Inspector**。 +- **32 px 状态栏(`mainStatusBarView`)**:在 `bg` 表面以弱化文本呈现左侧的活动图层按钮(可切换图层面板)、实时 2D 指针坐标与当前工具,以及右侧的问题数胶囊(打开问题面板)、输出(Output)与调试器(Debugger)。原工具栏中的其余面板(设置、混音器、输入映射、多语言、导出、资源库、数据表、项目搜索、文件、资源、动画、粒子、材质、HUD 布局、地形、导航网格)全部保留,可通过命令面板(`⌘K`)、菜单栏、设置窗口与状态栏访问。 +- **空状态、加载状态与错误状态(`WorkspaceState`、`SceneOpenError`)**:各区域均为 `WorkspaceNoProject`、`WorkspaceNoScene`、`WorkspaceLoading`(`SetProjectLoading`)和 `WorkspaceSceneError`(`SceneOpenError`、`RetryOpenScene`、`ClearSceneOpenError`)提供专门的界面状态。打开缺失或 YAML 格式错误的场景文件时,视口会展示带有路径、行/列号、错误描述、修复建议、**重试**和**关闭**按钮的告警卡片,而非空白视口。 +- **规范控件与键盘可达性**:遵循 Spec 尺寸(行与工具按钮 `28 px`、按钮 `30–32 px`、顶部栏 `44 px`、状态栏 `32 px`,无小于 `28 × 28` 的交互热区)、间距(`4 / 8 / 12 / 16 / 24`)、圆角(`6 / 8`)、`base.RadioGroup` / `base.Radio` 与 `base.Switch` 语义、2 px Spec 焦点环、完整无障碍名称,以及覆盖全部五个区域的 `F6` 循环导航(顶部栏、场景树、视口、智能体/检视器、状态栏)。 diff --git a/examples/fieldmedic/healthplugin/plugin_test.go b/examples/fieldmedic/healthplugin/plugin_test.go index d30c84dbc..03029eda3 100644 --- a/examples/fieldmedic/healthplugin/plugin_test.go +++ b/examples/fieldmedic/healthplugin/plugin_test.go @@ -128,7 +128,8 @@ func TestPluginAddsTheWardPanelTheInspectorAndTheAdmitTool(t *testing.T) { if ed.History.Index() != undos+1 || ed.History.UndoLabel() != "Heal All" { t.Fatalf("Heal All added %d steps, labeled %q", ed.History.Index()-undos, ed.History.UndoLabel()) } - app.Press("id:toolbar-undo") + app.Post(func() { ed.Undo() }) + app.Settle() if got, want := app.Find("id:health-ward").Text, "ada 8/10\nbram 9/12\ncleo 9/10\ndov 4/8"; got != want { t.Fatalf("Ward panel after Undo = %q, want %q", got, want) } @@ -147,7 +148,8 @@ func TestPluginAddsTheWardPanelTheInspectorAndTheAdmitTool(t *testing.T) { if wx, wy := ed.CanvasToWorld(120, 80); admitted.X != wx || admitted.Y != wy || hp(ed, admitted.ID) != healthplugin.AdmitHP { t.Fatalf("admitted %+v, want at (%v, %v) with %d hp", admitted, wx, wy, healthplugin.AdmitHP) } - app.Press("id:toolbar-undo") + app.Post(func() { ed.Undo() }) + app.Settle() if got := health.Objects(ed.Doc); len(got) != 4 { t.Fatalf("Undo left the admitted patient: %v", got) } diff --git a/packages/game/cmd/game/mcp_test.go b/packages/game/cmd/game/mcp_test.go index 70c5872fe..15d28265c 100644 --- a/packages/game/cmd/game/mcp_test.go +++ b/packages/game/cmd/game/mcp_test.go @@ -220,7 +220,7 @@ func TestGameMCPEditsTheOpenEditor(t *testing.T) { } app.Screenshot("editormcp/placed-by-agent") - app.Press("id:toolbar-undo") + app.Post(func() { ed.Undo() }) app.Settle() if app.Exists("id:scene-tree-label-slime_1") { t.Fatal("Undo left the object in the scene tree") diff --git a/packages/game/editor/agent_review.go b/packages/game/editor/agent_review.go index 6be8e07fb..501891166 100644 --- a/packages/game/editor/agent_review.go +++ b/packages/game/editor/agent_review.go @@ -33,6 +33,7 @@ const ( // AgentReviewChange is one non-deletion file change listed in the Review changes panel. type AgentReviewChange struct { ID string `json:"id"` + ObjectID string `json:"object_id,omitempty"` Path string `json:"path"` Kind AgentReviewChangeKind `json:"kind"` Title string `json:"title"` diff --git a/packages/game/editor/agent_ui.go b/packages/game/editor/agent_ui.go index 882547187..7ff7c977d 100644 --- a/packages/game/editor/agent_ui.go +++ b/packages/game/editor/agent_ui.go @@ -81,19 +81,23 @@ func RightRailView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No }) }, Else: func(cx *core.Scope) core.Node { + wsMemo := core.NewMemo(cx, func() string { + _ = rev.Get() + return ed.workspaceStateKey() + }) return core.Dynamic(func(cx *core.Scope) core.Node { p := SpecPaletteFor(darkMemo.Get()) return core.View{ TestID: "right-rail-inspector-wrap", Style: core.Style{ - Width: core.Pt(272), + Width: core.Pt(380), FlexShrink: 0, Background: p.Panel, Borders: core.Edges{Left: 1}, BorderColor: p.Line, }, Children: []core.Node{ - rightRailTabBar(cx, ed, rev, p, false), + rightRailTabBar(cx, ed, rev, p, true), core.View{ Style: core.Style{ Direction: core.Row, @@ -102,7 +106,15 @@ func RightRailView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No MinHeight: core.Pt(0), Overflow: core.Hidden, }, - Children: []core.Node{InspectorView(cx, ed, rev)}, + Children: []core.Node{ + core.Dynamic(func(cx *core.Scope) core.Node { + _ = wsMemo.Get() + if stateNode := inspectorWorkspaceStateView(cx, ed, ed.WorkspaceState()); stateNode != nil { + return stateNode + } + return InspectorView(cx, ed, rev) + }), + }, }, }, } @@ -119,19 +131,32 @@ func RightRailView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No // rightRailTabBar renders the 44 pt Agent / Inspector header bar matching docs/design/editor/Main.dc.html and AgentStates.dc.html. func rightRailTabBar(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p SpecPalette, showFullChip bool) core.Node { - tabBtn := func(testID, label string, tab RightRailTab) core.Node { + agentTabRef := &core.Ref{} + inspectorTabRef := &core.Ref{} + if ed.focus.ctrl != nil { + ed.focus.ctrl.registerCandidate(cx, RegionInspector, agentTabRef, nil) + ed.focus.ctrl.registerCandidate(cx, RegionInspector, inspectorTabRef, nil) + } + shortcutTip := func(name, cmdID string) string { + if sc := ed.EffectiveShortcut(cmdID); sc != "" { + return specShortcutTip(name, FormatShortcut(sc, cx.Env().OS())) + } + return name + } + tabBtn := func(ref *core.Ref, testID, label, cmdID string, tab RightRailTab) core.Node { children := []core.Node{ core.Text{ Content: label, StyleFunc: func() core.Style { _ = rev.Get() - col := p.TextFaint + cur := ed.SpecPalette(cx) + col := cur.TextFaint if ed.RightRailTab() == tab { - col = p.TextPrimary + col = cur.TextPrimary } return core.Style{ FontSize: 12.5, - FontWeight: 500, + FontWeight: core.FontWeightMedium, Color: col, } }, @@ -147,11 +172,13 @@ func rightRailTabBar(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p Spe return core.View{ TestID: "agent-tab-pending-dot", Label: ed.T("agentTurn.reviewWaiting"), - Style: core.Style{ - Width: core.Pt(6), - Height: core.Pt(6), - CornerRadius: 3, - Background: p.Accent.Fg, + StyleFunc: func() core.Style { + return core.Style{ + Width: core.Pt(6), + Height: core.Pt(6), + CornerRadius: 3, + Background: ed.SpecPalette(cx).Accent.Fg, + } }, } }, @@ -175,32 +202,44 @@ func rightRailTabBar(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p Spe }, }) } - return core.View{ - TestID: testID, - Role: core.RoleButton, - Label: label, + return base.Radio{ + Ref: ref, + TestID: testID, + Label: label, + Tooltip: specTooltipNode(p, shortcutTip(label, cmdID)), + Checked: func() bool { + _ = rev.Get() + return ed.RightRailTab() == tab + }, + OnChange: func(checked bool) { + if checked { + ed.SetRightRailTab(tab) + } + }, StyleFunc: func() core.Style { _ = rev.Get() + cur := ed.SpecPalette(cx) active := ed.RightRailTab() == tab - var bg core.Color + bg := core.Transparent if active { - bg = p.Raised + bg = cur.Raised } return core.Style{ Direction: core.Row, Gap: 6, - Height: core.Pt(30), - Padding: core.Symmetric(0, 12), - CornerRadius: 8, + Height: core.Pt(specButtonHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), + Padding: core.Symmetric(0, specSpace12), + CornerRadius: specRadiusButton, AlignItems: core.AlignCenter, JustifyContent: core.JustifyCenter, Background: bg, - FocusVisible: p.FocusRing(2), + Cursor: core.CursorPointer, + Hover: &core.Style{Background: cur.Raised}, + FocusVisible: cur.FocusRing(2), } }, - OnPress: func(core.PressEvent) { - ed.SetRightRailTab(tab) - }, Children: children, } } @@ -254,28 +293,30 @@ func rightRailTabBar(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p Spe return core.View{ TestID: "right-rail-header", Style: core.Style{ - MinHeight: core.Pt(44), + MinHeight: core.Pt(specHeaderHeight), FlexShrink: 0, Direction: core.Row, Wrap: core.Wrap, AlignItems: core.AlignCenter, - Gap: 6, - Padding: core.Symmetric(7, 10), + Gap: specSpace8, + Padding: core.Symmetric(7, specSpace12), Background: p.Panel, Borders: core.Edges{Bottom: 1}, BorderColor: p.Line, }, Children: []core.Node{ - core.View{ + base.RadioGroup{ + TestID: "right-rail-tabs", + Label: ed.T("region.inspector"), Style: core.Style{ Direction: core.Row, AlignItems: core.AlignCenter, - Gap: 4, + Gap: specSpace4, FlexShrink: 0, }, Children: []core.Node{ - tabBtn("right-tab-agent", ed.T("agent.tab"), RightTabAgent), - tabBtn("right-tab-inspector", ed.T("inspector.title"), RightTabInspector), + tabBtn(agentTabRef, "right-tab-agent", ed.T("agent.tab"), CmdAgentTab, RightTabAgent), + tabBtn(inspectorTabRef, "right-tab-inspector", ed.T("inspector.title"), CmdInspectorTab, RightTabInspector), }, }, core.View{Style: core.Style{FlexGrow: 1}}, @@ -297,10 +338,12 @@ func compactAgentChip(ed *Editor, rev *core.Signal[uint64], p SpecPalette) core. Style: core.Style{ Direction: core.Row, AlignItems: core.AlignCenter, - Height: core.Pt(24), + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), Padding: core.Symmetric(0, 8), Gap: 6, - CornerRadius: 12, + CornerRadius: 14, BorderWidth: 1, BorderColor: p.LineRaised, FocusVisible: p.FocusRing(2), @@ -455,7 +498,9 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c Style: core.Style{ Direction: core.Row, AlignItems: core.AlignCenter, - Height: core.Pt(24), + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), Padding: core.Symmetric(0, 10), Gap: 6, CornerRadius: 12, @@ -582,10 +627,12 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c Style: core.Style{ Direction: core.Row, AlignItems: core.AlignCenter, - Height: core.Pt(24), + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), Padding: core.Symmetric(0, 10), Gap: 6, - CornerRadius: 12, + CornerRadius: 14, Background: p.Warning.Fill, BorderWidth: 1, BorderColor: p.Warning.Edge, @@ -703,7 +750,9 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c Role: core.RoleButton, Label: "Reconnect", Style: core.Style{ - Height: core.Pt(24), + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), Padding: core.Symmetric(0, 8), CornerRadius: 6, AlignItems: core.AlignCenter, @@ -731,7 +780,9 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c Role: core.RoleButton, Label: "Troubleshoot", Style: core.Style{ - Height: core.Pt(24), + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), Padding: core.Symmetric(0, 8), CornerRadius: 6, AlignItems: core.AlignCenter, @@ -864,7 +915,9 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c Style: core.Style{ Direction: core.Row, AlignItems: core.AlignCenter, - Height: core.Pt(24), + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), Padding: core.Symmetric(0, 10), Gap: 6, CornerRadius: 12, diff --git a/packages/game/editor/animation_sprite_test.go b/packages/game/editor/animation_sprite_test.go index c3637997b..19e1bab34 100644 --- a/packages/game/editor/animation_sprite_test.go +++ b/packages/game/editor/animation_sprite_test.go @@ -73,7 +73,7 @@ func TestFourFrameClipKeyedInEditorPlaysAsFlipbookAndRoundTrips(t *testing.T) { ed, atlas := spriteFlipbookEditor(t) app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 900)) - app.Press("id:toolbar-animate") + runEditorCommand(t, app, ed, editor.CmdAnimate) app.Post(func() { if err := ed.SetClipName("Hero Walk"); err != nil { t.Errorf("SetClipName: %v", err) @@ -205,7 +205,7 @@ func TestFourFrameClipKeyedInEditorPlaysAsFlipbookAndRoundTrips(t *testing.T) { func TestNewClipFromAsepriteTagMatchesTagFramesAndDurations(t *testing.T) { ed, atlas := spriteFlipbookEditor(t) app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 900)) - app.Press("id:toolbar-animate") + runEditorCommand(t, app, ed, editor.CmdAnimate) if !app.Exists("id:anim-aseprite-tag") || !app.Exists("id:anim-from-tag") { t.Fatal("Aseprite tag controls did not appear for an atlas with tags") @@ -244,7 +244,7 @@ func TestNewClipFromAsepriteTagMatchesTagFramesAndDurations(t *testing.T) { } // Undo/Redo restores previous clip state. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if dur, _ := ed.FrameDuration(0, 1); dur != 110*time.Millisecond { t.Fatalf("after undo -10ms: frame 1 duration = %v, want 110ms", dur) } diff --git a/packages/game/editor/animation_test.go b/packages/game/editor/animation_test.go index dcfb61dfa..da2b81db5 100644 --- a/packages/game/editor/animation_test.go +++ b/packages/game/editor/animation_test.go @@ -435,7 +435,7 @@ func TestAnimationPanelKeysAndEditsThroughTheUI(t *testing.T) { t.Fatal("the animation panel shows with no clip open") } - app.Press("id:toolbar-animate") + runEditorCommand(t, app, ed, editor.CmdAnimate) if ed.Clip() == nil || ed.ClipTarget() != "hero" || !app.Exists("id:anim-panel") { t.Fatalf("Animate opened clip %+v on %q, panel shown %t", ed.Clip(), ed.ClipTarget(), app.Exists("id:anim-panel")) } @@ -484,7 +484,7 @@ func TestAnimationPanelKeysAndEditsThroughTheUI(t *testing.T) { if got := len(ed.Clip().Tracks[0].Keys); got != 1 { t.Fatalf("keys after deleting one = %d", got) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := len(ed.Clip().Tracks[0].Keys); got != 2 { t.Fatalf("keys after undoing the delete = %d", got) } @@ -607,7 +607,7 @@ func TestEventLaneFollowsAnOpenedClip(t *testing.T) { if app.Exists("label:Event land") || !app.Exists("label:Event jump") { t.Fatalf("event markers after opening the other clip: land %t jump %t", app.Exists("label:Event land"), app.Exists("label:Event jump")) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if !app.Exists("label:Event land") || app.Exists("label:Event jump") { t.Fatal("undoing the open left the other clip's event marker") } diff --git a/packages/game/editor/ask_in_place_test.go b/packages/game/editor/ask_in_place_test.go index 69f18d227..ba284aba9 100644 --- a/packages/game/editor/ask_in_place_test.go +++ b/packages/game/editor/ask_in_place_test.go @@ -264,11 +264,11 @@ func TestAskInPlaceInspectorTextFieldGuardAndEscapeRestoresFocus(t *testing.T) { t.Fatal("meta+l opened the in-place composer while focus was in inspector-name") } - // 2. Focus a non-text control (toolbar-editor-settings), press ⌘L -> opens composer; + // 2. Focus a non-text control (toolbar-history), press ⌘L -> opens composer; // type text, press Esc -> closes WITHOUT sending, keeps selection, and restores focus! - app.Focus("id:toolbar-editor-settings") - if !app.Find("id:toolbar-editor-settings").Focused { - t.Fatal("toolbar-editor-settings did not gain focus") + app.Focus("id:toolbar-history") + if !app.Find("id:toolbar-history").Focused { + t.Fatal("toolbar-history did not gain focus") } app.Key("meta+l") if !ed.AskInPlaceOpen() || !app.Find("id:ask-in-place-input").Focused { @@ -286,8 +286,8 @@ func TestAskInPlaceInspectorTextFieldGuardAndEscapeRestoresFocus(t *testing.T) { if ed.SelectedID != "slime_01" { t.Fatalf("Esc cleared selection: SelectedID=%q, want slime_01", ed.SelectedID) } - if !app.Find("id:toolbar-editor-settings").Focused { - t.Fatal("Esc did not return focus to the previously focused control (toolbar-editor-settings)") + if !app.Find("id:toolbar-history").Focused { + t.Fatal("Esc did not return focus to the previously focused control (toolbar-history)") } } diff --git a/packages/game/editor/asset_drawer_ui.go b/packages/game/editor/asset_drawer_ui.go index 779d94677..694270a83 100644 --- a/packages/game/editor/asset_drawer_ui.go +++ b/packages/game/editor/asset_drawer_ui.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/nsgo-dev/nsgo/base" "github.com/nsgo-dev/nsgo/base/dragdrop" "github.com/nsgo-dev/nsgo/core" "github.com/nsgo-dev/nsgo/icons/lucide" @@ -61,33 +62,41 @@ func LeftRailSwitchView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) co if mode == LeftRailScene { ref = sceneTabRef } - return core.View{ + return base.Radio{ Ref: ref, TestID: testID, - Role: core.RoleButton, Label: label, + Checked: func() bool { + _ = rev.Get() + return ed.LeftRailMode() == mode + }, + OnChange: func(checked bool) { + if checked { + ed.SetLeftRailMode(mode) + } + }, StyleFunc: func() core.Style { _ = rev.Get() cur := ed.SpecPalette(cx) active := ed.LeftRailMode() == mode - var bg core.Color + bg := core.Transparent if active { bg = cur.LineRaised } return core.Style{ FlexGrow: 1, FlexBasis: core.Pt(0), - Height: core.Pt(28), - CornerRadius: 6, + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), + CornerRadius: specRadiusControl, AlignItems: core.AlignCenter, JustifyContent: core.JustifyCenter, Background: bg, + Cursor: core.CursorPointer, FocusVisible: cur.FocusRing(2), } }, - OnPress: func(core.PressEvent) { - ed.SetLeftRailMode(mode) - }, Children: []core.Node{ core.Text{ Content: label, @@ -111,24 +120,29 @@ func LeftRailSwitchView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) co return core.View{ TestID: "left-rail-switch", - Style: core.Style{ - Height: core.Pt(44), - FlexShrink: 0, - Direction: core.Row, - AlignItems: core.AlignCenter, - Padding: core.Symmetric(0, 8), - Background: p.Bg, - Borders: core.Edges{Bottom: 1}, - BorderColor: p.Line, + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + return core.Style{ + Height: core.Pt(specHeaderHeight), + FlexShrink: 0, + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.Symmetric(0, specSpace8), + Background: cur.Bg, + Borders: core.Edges{Bottom: 1}, + BorderColor: cur.Line, + } }, Children: []core.Node{ - core.View{ + base.RadioGroup{ + TestID: "left-rail-mode-group", + Label: ed.T("region.sceneTree"), Style: core.Style{ FlexGrow: 1, Direction: core.Row, Gap: 2, Padding: core.All(3), - CornerRadius: 8, + CornerRadius: specRadiusButton, Background: p.Raised, BorderWidth: 1, BorderColor: p.LineRaised, diff --git a/packages/game/editor/asset_import_model_test.go b/packages/game/editor/asset_import_model_test.go index 1d60c49f9..e27e91d03 100644 --- a/packages/game/editor/asset_import_model_test.go +++ b/packages/game/editor/asset_import_model_test.go @@ -306,6 +306,7 @@ layers: }, nsgotest.Size(1400, 900)) // Select models/ship.glb in the file browser. + openFileBrowserInUI(app, ed) app.Press("id:files-row-models/ship.glb") app.Settle() @@ -554,6 +555,7 @@ layers: }, nsgotest.Size(1400, 900)) // Select models/ship.glb in the file browser; verify game.yaml target is shown. + openFileBrowserInUI(app, ed) app.Press("id:files-row-models/ship.glb") app.Settle() if got := allText(app.Find("id:import-asset-target")); !strings.Contains(got, "Model: assets/ship.glb") { diff --git a/packages/game/editor/asset_import_test.go b/packages/game/editor/asset_import_test.go index ebb4342c5..6e5d8ed2c 100644 --- a/packages/game/editor/asset_import_test.go +++ b/packages/game/editor/asset_import_test.go @@ -122,6 +122,7 @@ layers: }, nsgotest.Size(1400, 900)) // Select art/hero.png in the file browser. + openFileBrowserInUI(app, ed) app.Press("id:files-row-art/hero.png") app.Settle() @@ -221,8 +222,7 @@ layers: // Undo every edit back to before the sidecar existed: Undo removes the newly created sidecar! for ed.History.CanUndo() { - app.Press("id:toolbar-undo") - app.Settle() + undoInUI(app, ed) } if _, err := os.Stat(sidecarPath); !errors.Is(err, os.ErrNotExist) { t.Fatalf("expected sidecar removed after undoing back to creation, stat err = %v", err) @@ -230,8 +230,7 @@ layers: // Redo brings the exact sidecar back. for ed.History.CanRedo() { - app.Press("id:toolbar-redo") - app.Settle() + redoInUI(app, ed) } afterRedo, err := os.ReadFile(sidecarPath) if err != nil { @@ -399,6 +398,8 @@ layers: app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) + openAssetBrowserInUI(app, ed) + openFileBrowserInUI(app, ed) if !app.Exists("id:asset-actors-hero.png") { t.Fatal("expected asset browser to list initial unsliced frame hero.png") @@ -461,14 +462,15 @@ layers: t.Fatalf("AssetReloader calls = %+v, want assets/atlases/actors.json", reloader.calls) } - // Edit texture filter on art/albedo.png and press toolbar Build Assets. + // Edit texture filter on art/albedo.png and run Build Assets. + openFileBrowserInUI(app, ed) app.Press("id:files-row-art/albedo.png") app.Settle() app.Press("id:import-image-filter") app.Press("role:option nearest") app.Settle() - app.Press("id:toolbar-build-assets") + runEditorCommand(t, app, ed, editor.CmdBuildAssets) app.WaitUntil(5*time.Second, func() bool { return !ed.AssetsBuilding() }) if err := ed.AssetsBuildLastError(); err != nil { t.Fatalf("Build Assets failed: %v", err) @@ -567,6 +569,7 @@ layers: }, nsgotest.Size(1400, 900)) // 1. Audio kind. + openFileBrowserInUI(app, ed) app.Press("id:files-row-audio/jump.wav") app.Settle() for _, id := range []string{ @@ -775,6 +778,7 @@ layers: } // Selecting an image switches inspector to asset import settings. + openFileBrowserInUI(app, ed) app.Press("id:files-row-art/icon.png") app.Settle() if !app.Exists("id:inspector-asset-import") { @@ -870,6 +874,7 @@ layers: return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) + openFileBrowserInUI(app, ed) app.Press("id:files-row-art/hero.png") app.Settle() if !app.Exists("id:inspector-asset-import") { @@ -1071,6 +1076,7 @@ layers: }, nsgotest.Size(1400, 900)) // Select the sprite sheet in the file browser. + openFileBrowserInUI(app, ed) app.Press("id:files-row-art/sprites/hero.png") app.Settle() diff --git a/packages/game/editor/audio_mixer_panel_test.go b/packages/game/editor/audio_mixer_panel_test.go index bef549f07..028973e61 100644 --- a/packages/game/editor/audio_mixer_panel_test.go +++ b/packages/game/editor/audio_mixer_panel_test.go @@ -70,7 +70,7 @@ func TestAudioMixerPanelAddBusReverbSaveAndUndo(t *testing.T) { } // Open the Audio Mixer panel from the toolbar. - app.Press("id:toolbar-audio-mixer") + runEditorCommand(t, app, ed, editor.CmdAudioMixer) app.Settle() if !app.Exists("id:audio-mixer-panel") { t.Fatal("pressing toolbar-audio-mixer did not open the panel") @@ -105,7 +105,7 @@ func TestAudioMixerPanelAddBusReverbSaveAndUndo(t *testing.T) { app.Settle() // Save via toolbar Save and read back from game.yaml on disk. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() saved, err := project.Check(os.DirFS(dir)) if err != nil { @@ -125,7 +125,7 @@ func TestAudioMixerPanelAddBusReverbSaveAndUndo(t *testing.T) { // Undo edits: 3 param edits + 1 add reverb + 1 add bus = 5 undos restore game.yaml to no audio section. for range 5 { - app.Press("id:toolbar-undo") + undoInUI(app, ed) } app.Settle() if ed.Project.Audio != nil { @@ -136,7 +136,7 @@ func TestAudioMixerPanelAddBusReverbSaveAndUndo(t *testing.T) { } // Saving after Undo writes game.yaml back without the bus or reverb. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() reverted, err := project.Check(os.DirFS(dir)) if err != nil { @@ -148,7 +148,7 @@ func TestAudioMixerPanelAddBusReverbSaveAndUndo(t *testing.T) { // Redo brings the bus and reverb back. for range 5 { - app.Press("id:toolbar-redo") + redoInUI(app, ed) } app.Settle() if got := ed.AudioBuses(); len(got) != 1 || got[0].Name != "cave" || len(got[0].Effects) != 1 || got[0].Effects[0].Reverb == nil || math.Abs(got[0].Effects[0].Reverb.Wet-0.6) > 1e-6 { @@ -361,7 +361,7 @@ func TestAudioMixerBusAndEffectChainOperationsAndValidation(t *testing.T) { app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 900)) - app.Press("id:toolbar-audio-mixer") + runEditorCommand(t, app, ed, editor.CmdAudioMixer) app.Type("id:mixer-new-bus-name", "alpha") app.Press("id:mixer-add-bus") app.Type("id:mixer-new-bus-name", "beta") @@ -490,7 +490,7 @@ func TestAudioMixerAuditionAppliesBusVolumeAndEffectsLikeRuntime(t *testing.T) { }) // Open the Audio Mixer panel, pick audio/impulse.wav, and press Audition. - app.Press("id:toolbar-audio-mixer") + runEditorCommand(t, app, ed, editor.CmdAudioMixer) app.Press("id:mixer-audition-file") app.Press("role:option " + audioRel) app.Press("id:mixer-audition-play") @@ -597,7 +597,7 @@ func TestAudioMixerAuditionAppliesBusVolumeAndEffectsLikeRuntime(t *testing.T) { } // Undo while auditioning reverts the LowPass and immediately restores the Reverb-only playback. - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if len(app.Players) != 3 { t.Fatalf("len(app.Players) after Undo = %d, want 3", len(app.Players)) diff --git a/packages/game/editor/clipboard_group.go b/packages/game/editor/clipboard_group.go index 6af4d2401..f4fcba069 100644 --- a/packages/game/editor/clipboard_group.go +++ b/packages/game/editor/clipboard_group.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "maps" - "math" "slices" "strings" @@ -167,33 +166,20 @@ func (e *Editor) ToggleSelectObject(id string) bool { } // SetViewportPointer2D records the mouse pointer's canvas position over the 2D viewport -// so Paste can place copied objects at the pointer. +// so Paste can place copied objects at the pointer and the status bar can display live coordinates. func (e *Editor) SetViewportPointer2D(canvasX, canvasY float32) { if e == nil || !isFiniteFloat32(canvasX) || !isFiniteFloat32(canvasY) { return } pos := math2d.Vec2{X: canvasX, Y: canvasY} - prevHas := e.hasPointer2D - prevPos := e.pointer2D - changed := !prevHas || prevPos != pos + changed := !e.hasPointer2D || e.pointer2D != pos if changed { e.pasteStreak = 0 } e.pointer2D = pos e.hasPointer2D = true - if changed && e.SketchActive() { - // Only notify when the rounded integer scene coordinates shown in the status bar change, - // avoiding 120 Hz rev storms across the whole editor on sub-pixel mouse movement. - wx, wy := e.CanvasToWorld(pos.X, pos.Y) - rx, ry := int(math.Round(float64(wx))), int(math.Round(float64(wy))) - if !prevHas { - e.notify() - } else { - pwx, pwy := e.CanvasToWorld(prevPos.X, prevPos.Y) - if rx != int(math.Round(float64(pwx))) || ry != int(math.Round(float64(pwy))) { - e.notify() - } - } + if changed { + e.notifyPointer() } } @@ -204,11 +190,15 @@ func (e *Editor) SetViewportPointer3D(canvasX, canvasY float32) { return } pos := [2]float32{canvasX, canvasY} - if !e.hasPointer3D || e.pointer3D != pos { + changed := !e.hasPointer3D || e.pointer3D != pos + if changed { e.pasteStreak = 0 } e.pointer3D = pos e.hasPointer3D = true + if changed { + e.notifyPointer() + } } // ClearViewportPointer clears any recorded viewport pointer position. @@ -216,8 +206,52 @@ func (e *Editor) ClearViewportPointer() { if e == nil { return } + changed := e.hasPointer2D || e.hasPointer3D e.hasPointer2D = false e.hasPointer3D = false + if changed { + e.notifyPointer() + } +} + +// PointerRevision returns a counter incremented whenever the viewport pointer position changes. +func (e *Editor) PointerRevision() uint64 { + if e == nil { + return 0 + } + return e.pointerRev +} + +// SubscribePointer registers fn to run when the viewport pointer coordinate changes and returns an unsubscribe func. +func (e *Editor) SubscribePointer(fn func()) func() { + if e == nil || fn == nil { + return func() {} + } + e.nextPointerListener++ + id := e.nextPointerListener + if e.pointerListeners == nil { + e.pointerListeners = make(map[uint64]func()) + } + e.pointerListeners[id] = fn + return func() { + delete(e.pointerListeners, id) + } +} + +func (e *Editor) notifyPointer() { + e.pointerRev++ + for _, fn := range e.pointerListeners { + fn() + } +} + +// ViewportPointer2DWorld returns the current 2D viewport pointer coordinates in world space, or (0, 0, false) when none. +func (e *Editor) ViewportPointer2DWorld() (x, y float32, ok bool) { + if e == nil || !e.hasPointer2D { + return 0, 0, false + } + wx, wy := e.CanvasToWorld(e.pointer2D.X, e.pointer2D.Y) + return wx, wy, true } func (e *Editor) cancelActiveObjectDrags() { diff --git a/packages/game/editor/collider3d_gizmo_test.go b/packages/game/editor/collider3d_gizmo_test.go index efa235995..48deaaa05 100644 --- a/packages/game/editor/collider3d_gizmo_test.go +++ b/packages/game/editor/collider3d_gizmo_test.go @@ -471,8 +471,9 @@ layers: return editor.EditorView(cx, ed) }, nsgotest.Size(1200, 1400)) - // Press toolbar Collider gizmo button and verify GizmoMode switches to Gizmo3DCollider. - app.Press("id:gizmo-collider") + // Switch GizmoMode to Gizmo3DCollider. + app.Post(func() { ed.SetGizmoMode3D(editor.Gizmo3DCollider) }) + app.Settle() if ed.GizmoMode != editor.Gizmo3DCollider { t.Fatalf("GizmoMode = %v, want Gizmo3DCollider", ed.GizmoMode) } diff --git a/packages/game/editor/commands.go b/packages/game/editor/commands.go index 1071f121a..f10b33ad4 100644 --- a/packages/game/editor/commands.go +++ b/packages/game/editor/commands.go @@ -35,6 +35,9 @@ const ( CmdUngroup = "edit.ungroup" CmdToolSelect = "tool.select" CmdToolMove = "tool.move" + CmdToolRotate = "tool.rotate" + CmdToolScale = "tool.scale" + CmdToolPan = "tool.pan" CmdToolPlace = "tool.place" CmdToolPaintTile = "tool.paint" CmdToolEraseTile = "tool.erase" @@ -82,6 +85,7 @@ const ( CmdRunGame = "project.run" CmdProjectSettings = "project.settings" CmdAudioMixer = "project.mixer" + CmdInputMap = "project.inputMap" CmdLocalization = "project.l10n" CmdParticleEditor = "project.particles" CmdHUDLayout = "project.hud" @@ -89,6 +93,19 @@ const ( CmdExport = "project.export" CmdBuildRelease = "project.buildRelease" CmdProfiler = "project.profiler" + CmdOutputPanel = "view.output" + CmdProblemsPanel = "view.problems" + CmdSearchPanel = "view.search" + CmdDataTable = "project.dataTable" + CmdLibraryPanel = "view.library" + CmdAnimate = "project.animate" + CmdBuildAssets = "project.buildAssets" + CmdStopGame = "project.stopGame" + CmdRunOpenScene = "project.runOpenScene" + CmdLayersPanel = "view.layers" + CmdFileBrowser = "view.fileBrowser" + CmdAssetBrowser = "view.assetBrowser" + CmdTerrainEditor = "project.terrain" CmdCheckProblems = "project.check" CmdFindUsages = "project.findUsages" CmdEditorSettings = "editor.settings" @@ -701,17 +718,63 @@ func (e *Editor) initBuiltinCommands() { }, }, { - ID: CmdToolMove, - Label: "Tool: Move", - Description: "Switch to the Move viewport tool", + ID: CmdToolMove, + Label: "Tool: Move", + Description: "Switch to the Move viewport tool", + Category: "Tools", + Keywords: []string{"move", "translate", "drag", "2d", "3d"}, + Scope: ScopeViewport, + Shortcut: "w", + AlternateShortcuts: []string{"m"}, + Enabled: notPlaying, + Checked: func() bool { return e.Tool == ToolMove }, + Run: func() error { + e.SetTool(ToolMove) + return nil + }, + }, + { + ID: CmdToolRotate, + Label: "Tool: Rotate", + Description: "Switch to the Rotate viewport tool", Category: "Tools", - Keywords: []string{"move", "translate", "drag", "2d"}, + Keywords: []string{"rotate", "turn", "angle", "2d", "3d"}, Scope: ScopeViewport, - Shortcut: "m", + Shortcut: "e", Enabled: notPlaying, - Checked: func() bool { return e.ViewMode == ViewMode2D && e.Tool == ToolMove }, + Checked: func() bool { return e.Tool == ToolRotate }, Run: func() error { - e.SetTool(ToolMove) + e.SetTool(ToolRotate) + return nil + }, + }, + { + ID: CmdToolScale, + Label: "Tool: Scale", + Description: "Switch to the Scale viewport tool", + Category: "Tools", + Keywords: []string{"scale", "resize", "size", "2d", "3d"}, + Scope: ScopeViewport, + Shortcut: "r", + Enabled: notPlaying, + Checked: func() bool { return e.Tool == ToolScale }, + Run: func() error { + e.SetTool(ToolScale) + return nil + }, + }, + { + ID: CmdToolPan, + Label: "Tool: Pan", + Description: "Switch to the Pan viewport camera tool (or hold Space)", + Category: "Tools", + Keywords: []string{"pan", "hand", "camera", "drag", "2d", "3d"}, + Scope: ScopeViewport, + Shortcut: "space", + Enabled: notPlaying, + Checked: func() bool { return e.Tool == ToolPan }, + Run: func() error { + e.SetTool(ToolPan) return nil }, }, @@ -1460,15 +1523,16 @@ func (e *Editor) initBuiltinCommands() { }, }, { - ID: CmdPlayStop, - Label: "Play / Stop", - Description: "Toggle play-in-editor simulation", - Category: "Project", - Keywords: []string{"play", "stop", "preview", "simulate"}, - Scope: ScopePlay, - Shortcut: "f5", - Enabled: inEditor, - Run: func() error { return e.TogglePlay() }, + ID: CmdPlayStop, + Label: "Play / Stop", + Description: "Toggle play-in-editor simulation", + Category: "Project", + Keywords: []string{"play", "stop", "preview", "simulate"}, + Scope: ScopePlay, + Shortcut: "mod+p", + AlternateShortcuts: []string{"f5"}, + Enabled: inEditor, + Run: func() error { return e.TogglePlay() }, }, { ID: CmdPlayMark, @@ -1533,6 +1597,200 @@ func (e *Editor) initBuiltinCommands() { return nil }, }, + { + ID: CmdInputMap, + Label: "Input Map", + Description: "Toggle the Input Map settings page", + Category: "Project", + Keywords: []string{"input", "controls", "keys", "gamepad", "bindings", "actions", "panel"}, + Scope: ScopeGlobal, + Enabled: hasProject, + Checked: func() bool { return e.InputMapOpen() }, + Run: func() error { + e.SetInputMapOpen(!e.InputMapOpen()) + return nil + }, + }, + { + ID: CmdOutputPanel, + Label: "Output", + Description: "Toggle the Output log panel", + Category: "View", + Keywords: []string{"output", "log", "logs", "console", "panel"}, + Scope: ScopeGlobal, + Checked: func() bool { return e.OutputPanelOpen() }, + Run: func() error { + e.SetOutputPanelOpen(!e.OutputPanelOpen()) + return nil + }, + }, + { + ID: CmdProblemsPanel, + Label: "Problems", + Description: "Toggle the Problems panel", + Category: "View", + Keywords: []string{"problems", "errors", "warnings", "diagnostics", "panel"}, + Scope: ScopeGlobal, + Enabled: hasProject, + Checked: func() bool { return e.ProblemAgentPanelOpen() }, + Run: func() error { + e.SetProblemAgentPanelOpen(!e.ProblemAgentPanelOpen()) + return nil + }, + }, + { + ID: CmdSearchPanel, + Label: "Project Search & References", + Description: "Toggle the Project Search and References panel", + Category: "View", + Keywords: []string{"search", "find", "references", "grep", "project", "panel"}, + Scope: ScopeGlobal, + Shortcut: "mod+shift+f", + Enabled: hasProject, + Checked: func() bool { return e.SearchOpen() }, + Run: func() error { + e.SetSearchOpen(!e.SearchOpen()) + return nil + }, + }, + { + ID: CmdDataTable, + Label: "Data Table", + Description: "Open or toggle the Data Table editor panel", + Category: "Project", + Keywords: []string{"data", "table", "yaml", "spreadsheet", "rows", "panel"}, + Scope: ScopeGlobal, + Enabled: notPlaying, + Checked: func() bool { return e.DataTable() != nil }, + Run: func() error { + if e.DataTable() != nil { + return e.CloseDataTable() + } + return e.OpenDataTableYAML("data/table.yaml", []byte("version: 1\nrows: []\n")) + }, + }, + { + ID: CmdLibraryPanel, + Label: "Library", + Description: "Toggle the Asset Pack Library panel", + Category: "View", + Keywords: []string{"library", "packs", "assets", "store", "panel"}, + Scope: ScopeGlobal, + Enabled: func() bool { return e.Library != nil }, + Checked: func() bool { return e.LibraryPanelOpen() }, + Run: func() error { + e.SetLibraryPanelOpen(!e.LibraryPanelOpen()) + return nil + }, + }, + { + ID: CmdAnimate, + Label: "Animate", + Description: "Create or open an animation clip for the selected object", + Category: "Project", + Keywords: []string{"animate", "animation", "clip", "timeline", "keyframes"}, + Scope: ScopeGlobal, + Enabled: func() bool { return notPlaying() && e.SelectedID != "" && e.clip == nil }, + Run: func() error { + return e.NewClip("", "New clip", time.Second) + }, + }, + { + ID: CmdBuildAssets, + Label: "Build Assets", + Description: "Run go tool game assets for the open project and reload changed atlases", + Category: "Project", + Keywords: []string{"build", "assets", "atlas", "textures", "sprites"}, + Scope: ScopeGlobal, + Enabled: func() bool { return hasProject() && notPlaying() && !e.AssetsBuilding() }, + Run: func() error { return e.BuildAssets() }, + }, + { + ID: CmdStopGame, + Label: "Stop Game", + Description: "Stop the running game process", + Category: "Project", + Keywords: []string{"stop", "kill", "game", "run"}, + Scope: ScopePlay, + Enabled: func() bool { return e.GameRunning() }, + Run: func() error { return e.StopGame() }, + }, + { + ID: CmdRunOpenScene, + Label: "Run From Open Scene", + Description: "Toggle launching the game directly at the currently open scene", + Category: "Project", + Keywords: []string{"run", "current", "scene", "open"}, + Scope: ScopePlay, + Enabled: func() bool { return hasProject() && !e.GameRunning() }, + Checked: func() bool { return e.RunStartAtOpenScene() }, + Run: func() error { + e.SetRunStartAtOpenScene(!e.RunStartAtOpenScene()) + return nil + }, + }, + { + ID: CmdLayersPanel, + Label: "Layers Panel", + Description: "Toggle the Layers panel for managing scene layers", + Category: "View", + Keywords: []string{"layers", "parallax", "order", "panel"}, + Scope: ScopeGlobal, + Enabled: inEditor, + Checked: func() bool { return e.LayersPanelOpen() }, + Run: func() error { + e.SetLayersPanelOpen(!e.LayersPanelOpen()) + return nil + }, + }, + { + ID: CmdFileBrowser, + Label: "Project Files Browser", + Description: "Toggle the full Project Files browser panel", + Category: "View", + Keywords: []string{"files", "browser", "project", "move", "rename", "panel"}, + Scope: ScopeGlobal, + Enabled: hasProject, + Checked: func() bool { return e.FileBrowserOpen() }, + Run: func() error { + e.SetFileBrowserOpen(!e.FileBrowserOpen()) + return nil + }, + }, + { + ID: CmdAssetBrowser, + Label: "Asset Browser", + Description: "Toggle the Asset Browser panel", + Category: "View", + Keywords: []string{"assets", "sprites", "prefabs", "browser", "panel"}, + Scope: ScopeGlobal, + Enabled: inEditor, + Checked: func() bool { return e.AssetBrowserOpen() }, + Run: func() error { + e.SetAssetBrowserOpen(!e.AssetBrowserOpen()) + return nil + }, + }, + { + ID: CmdTerrainEditor, + Label: "3D Terrain Editor", + Description: "Toggle the 3D terrain sculpting and painting panel", + Category: "Project", + Keywords: []string{"terrain", "heightmap", "sculpt", "foliage", "3d", "panel"}, + Scope: ScopeViewport3D, + Enabled: notPlaying, + Checked: func() bool { return e.TerrainOpen() }, + Run: func() error { + if e.TerrainOpen() { + e.CloseTerrain() + return nil + } + if e.ViewMode != ViewMode3D { + e.SetViewMode(ViewMode3D) + } + return e.NewTerrain(NewTerrainOptions{}) + }, + }, { ID: CmdLocalization, Label: "Localization Strings", @@ -2820,8 +3078,14 @@ func (e *Editor) bindShortcuts(cx *core.Scope, rev *core.Signal[uint64]) { } seen[sc] = struct{}{} key := sc + // Space is held in the viewport to pan (viewport.go spaceHeld) and activates + // focused buttons, switches, checkboxes, and radios across the UI; never bind + // a root-scope OnKey("space") that consumes Space before focused controls see it. + if key == "space" { + continue + } cx.OnKeyWith(key, core.KeyOptions{When: core.KeyNotEditing}, func() { - if e.shortcutCaptureActive { + if e.shortcutCaptureActive || e.CapturingKey() { return } active, ok := e.resolveShortcutCommand(key) diff --git a/packages/game/editor/commands_test.go b/packages/game/editor/commands_test.go index a7118628c..f27b7f416 100644 --- a/packages/game/editor/commands_test.go +++ b/packages/game/editor/commands_test.go @@ -84,25 +84,25 @@ func TestKeyboardShortcutsUndoRedoSaveDeleteAndTextFieldGuard(t *testing.T) { }) appBtn.Settle() - // Save via shortcut vs toolbar-save button. + // Save via shortcut vs File menu Save. appKey.Key(plat.mod + "+s") - appBtn.Press("id:toolbar-save") + saveInUI(appBtn, edBtn) if len(keySaves) != 1 || len(btnSaves) != 1 || !bytes.Equal(keySaves[0], btnSaves[0]) { t.Fatalf("Save shortcut bytes != button bytes (key=%d, btn=%d)", len(keySaves), len(btnSaves)) } - // Undo via shortcut vs toolbar-undo button. + // Undo via shortcut vs CmdUndo command. appKey.Key(plat.mod + "+z") - appBtn.Press("id:toolbar-undo") + runEditorCommand(t, appBtn, edBtn, editor.CmdUndo) heroKey, _, _ := edKey.FindObject("hero") heroBtn, _, _ := edBtn.FindObject("hero") if heroKey.X != 40 || heroKey.Y != 40 || heroKey.X != heroBtn.X || heroKey.Y != heroBtn.Y { t.Fatalf("after Undo: key=(%v,%v), btn=(%v,%v), want (40,40)", heroKey.X, heroKey.Y, heroBtn.X, heroBtn.Y) } - // Redo via shortcut vs toolbar-redo button. + // Redo via shortcut vs CmdRedo command. appKey.Key(plat.mod + "+shift+z") - appBtn.Press("id:toolbar-redo") + runEditorCommand(t, appBtn, edBtn, editor.CmdRedo) heroKey, _, _ = edKey.FindObject("hero") heroBtn, _, _ = edBtn.FindObject("hero") if heroKey.X != 120 || heroKey.Y != 88 || heroKey.X != heroBtn.X || heroKey.Y != heroBtn.Y { @@ -370,12 +370,12 @@ func TestDesktopMenuBarMatchesRegistryAndExecutesActions(t *testing.T) { {[]string{"Edit", "Delete"}, "delete"}, {[]string{"View", "Command Palette..."}, "mod+k"}, {[]string{"View", "Frame Selection"}, "f"}, - {[]string{"View", "Tools", "Move"}, "m"}, + {[]string{"View", "Tools", "Move"}, "w"}, {[]string{"View", "3D Gizmo", "Translate"}, "w"}, {[]string{"View", "3D Gizmo", "Rotate"}, "e"}, {[]string{"View", "3D Gizmo", "Scale"}, "r"}, {[]string{"View", "3D Gizmo", "3D Gizmo: Local / Global Space"}, "t"}, - {[]string{"Project", "Play"}, "f5"}, + {[]string{"Project", "Play"}, "mod+p"}, {[]string{"Project", "Run Game"}, "mod+r"}, {[]string{"Project", "Plugins", "Ping Plugin"}, "mod+shift+p"}, } diff --git a/packages/game/editor/cutscene_test.go b/packages/game/editor/cutscene_test.go index c40b14111..ef2d45cb3 100644 --- a/packages/game/editor/cutscene_test.go +++ b/packages/game/editor/cutscene_test.go @@ -816,7 +816,7 @@ func TestCutsceneTimelineUIAndScreenshot(t *testing.T) { if got := app.Find("id:cutscene-start-value").Text; got != "8.3 s" { t.Fatalf("start value after +0.1s = %q, want '8.3 s'", got) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if app.Exists("id:cutscene-review-edited-hint") { t.Fatal("edited hint should clear after Undo") } diff --git a/packages/game/editor/datatable_test.go b/packages/game/editor/datatable_test.go index 32fb4a0c7..689250216 100644 --- a/packages/game/editor/datatable_test.go +++ b/packages/game/editor/datatable_test.go @@ -279,6 +279,7 @@ func TestDataTableRegisteredRowTypeRefusesInvalidEditsInGrid(t *testing.T) { } // Open the table from the file browser. + openFileBrowserInUI(app, ed) app.Press("id:files-row-" + tableRel) app.Settle() app.Press("id:files-open-table") @@ -365,7 +366,7 @@ func TestDataTableRegisteredRowTypeRefusesInvalidEditsInGrid(t *testing.T) { if v, _ := ed.DataTable().Cell(0, "is_boss"); v.Text != "true" { t.Fatalf("is_boss after toggle = %+v", v) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if v, _ := ed.DataTable().Cell(0, "is_boss"); v.Text != "false" { t.Fatalf("is_boss after undo = %+v", v) @@ -420,7 +421,7 @@ func TestDataTableRegisteredRowTypeRefusesInvalidEditsInGrid(t *testing.T) { if app.Exists("id:datatable-panel") || ed.DataTable() != nil { t.Fatal("Close did not close Data Table panel") } - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if !app.Exists("id:datatable-panel") || ed.DataTable() == nil { t.Fatal("Undo did not reopen Data Table panel") diff --git a/packages/game/editor/disk_watch_test.go b/packages/game/editor/disk_watch_test.go index bca483e73..b916246da 100644 --- a/packages/game/editor/disk_watch_test.go +++ b/packages/game/editor/disk_watch_test.go @@ -136,9 +136,8 @@ func TestDiskWatchReloadsCleanSceneAndRefusesOverwriteWhenDirty(t *testing.T) { t.Fatalf("after Cancel: hero=%+v, want X=77", obj) } - // Pressing toolbar Save asks again; confirming Overwrite writes editor's version. - app.Press("id:toolbar-save") - app.Settle() + // Saving via File menu asks again; confirming Overwrite writes editor's version. + saveInUI(app, ed) if !app.Exists("id:save-conflict-dialog") { t.Fatal("pressing toolbar Save over conflict did not ask") } @@ -505,6 +504,7 @@ func TestDiskWatchClipProjectAndFileBrowser(t *testing.T) { // File browser refreshes automatically when a new file appears in the project tree. app := startEditorApp(t, ed) + openFileBrowserInUI(app, ed) newScene := testSceneDoc() newScene.Name = "Brand New" newSceneBytes, err := sceneformat.Encode(newScene) diff --git a/packages/game/editor/editor_test.go b/packages/game/editor/editor_test.go index 665bdf190..de75925c1 100644 --- a/packages/game/editor/editor_test.go +++ b/packages/game/editor/editor_test.go @@ -568,7 +568,8 @@ func TestAssetBrowserListsFramesAndDropDrawsInViewport(t *testing.T) { return editor.EditorView(cx, ed) }, nsgotest.Size(1120, 680)) - // Verify Asset Browser renders entries in the UI tree. + // Verify Asset Browser renders entries in the UI tree when opened. + openAssetBrowserInUI(app, ed) app.Find("id:asset-browser") app.Find("id:asset-actors-slime") @@ -611,12 +612,12 @@ func TestAssetBrowserListsFramesAndDropDrawsInViewport(t *testing.T) { t.Fatalf("expected dropped slime drawn at (%v,%v) in viewport ops: %+v", px, py, ops) } - // Also verify direct DropAtlasFrame + Undo via toolbar Undo button. - app.Press("id:toolbar-undo") + // Also verify direct DropAtlasFrame + Undo/Redo. + undoInUI(app, ed) if obj, _, _ := ed.FindObject(droppedObj.ID); obj != nil { t.Fatalf("expected toolbar Undo to remove dropped object %q", droppedObj.ID) } - app.Press("id:toolbar-redo") + redoInUI(app, ed) if obj, _, _ := ed.FindObject(droppedObj.ID); obj == nil { t.Fatalf("expected toolbar Redo to restore dropped object %q", droppedObj.ID) } @@ -637,8 +638,8 @@ func TestToolbarToolsCanvasTilePaintAndSaveCallback(t *testing.T) { return editor.EditorView(cx, ed) }, nsgotest.Size(1120, 680)) - // Switch to Fill tool via toolbar and click interior tile (1, 1), at world (24, 24). The tile palette that a tile tool shows narrows the viewport, so the canvas point is taken after the tool changes. - app.Press("id:tool-fill") + // Switch to Fill tool via command and click interior tile (1, 1), at world (24, 24). The tile palette that a tile tool shows narrows the viewport, so the canvas point is taken after the tool changes. + runEditorCommand(t, app, ed, editor.CmdToolFillTile) if ed.Tool != editor.ToolFillTile { t.Fatalf("Tool = %v, want ToolFillTile", ed.Tool) } @@ -653,7 +654,7 @@ func TestToolbarToolsCanvasTilePaintAndSaveCallback(t *testing.T) { } // Switch to Erase tool and click tile (1, 1). - app.Press("id:tool-erase") + runEditorCommand(t, app, ed, editor.CmdToolEraseTile) app.PressAt("id:editor-viewport", tile) if got := ed.Doc.Layers[0].Tilemap.Data[1*4+1]; got != 0 { t.Fatalf("erased tile (1,1) = %d, want 0", got) @@ -662,14 +663,14 @@ func TestToolbarToolsCanvasTilePaintAndSaveCallback(t *testing.T) { // Switch to Paint tool and click tile (1, 1) with tile 3. app.Post(func() { ed.SetActiveTileID(3) }) app.Settle() - app.Press("id:tool-paint") + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) app.PressAt("id:editor-viewport", tile) if got := ed.Doc.Layers[0].Tilemap.Data[1*4+1]; got != 3 { t.Fatalf("painted tile (1,1) = %d, want 3", got) } - // Click Save in toolbar and verify OnSave received valid YAML matching the edits. - app.Press("id:toolbar-save") + // Save via File menu and verify OnSave received valid YAML matching the edits. + saveInUI(app, ed) if len(savedBytes) == 0 { t.Fatal("expected OnSave to receive encoded YAML bytes") } diff --git a/packages/game/editor/editorcmd/main_layout_screenshot_test.go b/packages/game/editor/editorcmd/main_layout_screenshot_test.go new file mode 100644 index 000000000..6246aec1e --- /dev/null +++ b/packages/game/editor/editorcmd/main_layout_screenshot_test.go @@ -0,0 +1,159 @@ +package editorcmd_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +const mainLayoutProjectYAML = `version: 1 +name: Dungeon +id: dev.example.dungeon +appVersion: 1.0.0 +window: + width: 640 + height: 360 +autoload: + mainScene: level_01 + scenes: + - name: level_01 + path: scenes/level_01.scene.yaml +` + +const mainLayoutPrefabYAML = `version: 2 +name: Slime +layers: + - name: root + objects: + - id: body + x: 0 + y: 0 +` + +const mainLayoutSceneYAML = `version: 3 +name: level_01 +virtualWidth: 640 +virtualHeight: 360 +layers: + - name: actors + space: world + order: 0 + objects: + - id: knight + name: Knight + x: 180 + y: 220 + - id: slime_01 + name: Slime 01 + prefab: prefabs/slime.scene.yaml + x: 340 + y: 240 + - id: door_trigger + name: Door Trigger + x: 520 + y: 220 + components: + trigger: {} +` + +// TestMainLayoutMacOSScreenshots renders the AI-first main layout (#1007) at 1440x900 +// on the real macOS host in Dark and Light themes plus Inspector, missing-scene error, +// loading, and empty states for visual inspection against Main.dc.html and Spec.dc.html. +func TestMainLayoutMacOSScreenshots(t *testing.T) { + dir := t.TempDir() + mustWrite := func(rel, body string) { + t.Helper() + full := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + mustWrite("game.yaml", mainLayoutProjectYAML) + mustWrite("prefabs/slime.scene.yaml", mainLayoutPrefabYAML) + mustWrite("scenes/level_01.scene.yaml", mainLayoutSceneYAML) + + t.Run("agent-and-inspector", func(t *testing.T) { + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + ed.NotifyAgentMCPConnected(editor.AgentClientInfo{ + ID: "sess-1", + Name: "Claude Code", + Transport: "stdio", + }) + ed.SetRightRailTab(editor.RightTabAgent) + ed.SetProposedNewObjectIDs([]string{"slime_01"}) + ed.SetViewportPointer2D(312, 184) + ed.SetOverlayLegendOpen(true) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), nsgotest.Environment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + Locale: "en-US", + })) + + app.Screenshot("main-layout-agent-dark") + + app.SetEnvironment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: false, + Locale: "en-US", + }) + app.Screenshot("main-layout-agent-light") + + app.SetEnvironment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + Locale: "en-US", + }) + app.Press("id:scene-tree-label-knight") + app.Settle() + app.Screenshot("main-layout-inspector-dark") + }) + + t.Run("error-loading-empty", func(t *testing.T) { + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), nsgotest.Environment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + Locale: "en-US", + })) + + app.Screenshot("main-layout-empty") + + app.Post(func() { + ed.SetProjectLoading(true, filepath.Join(dir, "game.yaml")) + }) + app.Settle() + app.Screenshot("main-layout-loading") + + app.Post(func() { + ed.SetProjectLoading(false, "") + _ = ed.OpenFile(filepath.Join(dir, "scenes", "missing.scene.yaml")) + }) + app.Settle() + app.Screenshot("main-layout-error-missing-scene") + }) +} diff --git a/packages/game/editor/export_panel_test.go b/packages/game/editor/export_panel_test.go index 0b0f285a4..84ff12212 100644 --- a/packages/game/editor/export_panel_test.go +++ b/packages/game/editor/export_panel_test.go @@ -68,7 +68,7 @@ func TestExportPanelAddPresetSaveGameProjectTargetsAndUndo(t *testing.T) { } // Open the Export panel from the toolbar. - app.Press("id:toolbar-export") + runEditorCommand(t, app, ed, editor.CmdExport) app.Settle() if !app.Exists("id:export-panel") { t.Fatal("pressing toolbar-export did not open the panel") @@ -106,7 +106,7 @@ func TestExportPanelAddPresetSaveGameProjectTargetsAndUndo(t *testing.T) { app.Settle() // Save via toolbar Save. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() saved, err := project.Check(os.DirFS(dir)) @@ -130,7 +130,7 @@ func TestExportPanelAddPresetSaveGameProjectTargetsAndUndo(t *testing.T) { // Undo every edit (6 steps: set output, add macos, toggle macos_arm64, add windows, toggle windows_x64, add web). for range 6 { - app.Press("id:toolbar-undo") + undoInUI(app, ed) } app.Settle() if ed.Project.Export != nil { @@ -141,7 +141,7 @@ func TestExportPanelAddPresetSaveGameProjectTargetsAndUndo(t *testing.T) { } // Save after Undo and verify `gameproject targets` prints nothing. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() stdout, _ = runBuiltTool(t, gameprojectBin, "targets", dir) if got := strings.TrimSpace(stdout); got != "" { @@ -150,7 +150,7 @@ func TestExportPanelAddPresetSaveGameProjectTargetsAndUndo(t *testing.T) { // Redo brings the presets and output directory back. for range 6 { - app.Press("id:toolbar-redo") + redoInUI(app, ed) } app.Settle() if got := ed.Project.BuildTargets(); !reflect.DeepEqual(got, wantTargets) { @@ -220,7 +220,7 @@ assets: return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) - app.Press("id:toolbar-export") + runEditorCommand(t, app, ed, editor.CmdExport) app.Settle() // Configure channel=store, release notes, and Dry Run via the panel controls. @@ -326,7 +326,7 @@ assets: }, nsgotest.Size(1400, 900)) // Opening the Export panel runs the credits pre-flight automatically. - app.Press("id:toolbar-export") + runEditorCommand(t, app, ed, editor.CmdExport) app.Settle() report := ed.ExportCredits() @@ -488,7 +488,7 @@ func TestExportPanelStreamingCancelFailureAndValidation(t *testing.T) { app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) - app.Press("id:toolbar-export") + runEditorCommand(t, app, ed, editor.CmdExport) app.Settle() app.Press("id:export-build") diff --git a/packages/game/editor/focus_regions_test.go b/packages/game/editor/focus_regions_test.go index c9b490511..7bf4e7c49 100644 --- a/packages/game/editor/focus_regions_test.go +++ b/packages/game/editor/focus_regions_test.go @@ -94,12 +94,12 @@ func TestToolbarTabFocusRingKeyboardOnlyVsClick(t *testing.T) { toolbar := app.Find("id:editor-toolbar") // Clicking a toolbar button with the mouse must NOT draw a focus ring. - app.Press("id:toolbar-output") + app.Press("id:toolbar-history") app.Settle() - if v := app.Find("id:toolbar-output"); v.Style.Outline.Width != 0 { - t.Fatalf("mouse click drew focus ring on toolbar-output: %+v", v.Style.Outline) + if v := app.Find("id:toolbar-history"); v.Style.Outline.Width != 0 { + t.Fatalf("mouse click drew focus ring on toolbar-history: %+v", v.Style.Outline) } - app.Press("id:toolbar-output") // restore + app.Press("id:toolbar-history") // restore app.Settle() // Tab through toolbar controls and verify every focused toolbar control shows the @@ -138,12 +138,12 @@ func TestToolbarTabFocusRingKeyboardOnlyVsClick(t *testing.T) { } // Mouse click clears keyboard focus ring on toolbar controls. - app.Press("id:toolbar-output") + app.Press("id:toolbar-history") app.Settle() - if v := app.Find("id:toolbar-output"); v.Style.Outline.Width != 0 { - t.Fatalf("mouse click after Tab drew focus ring on toolbar-output: %+v", v.Style.Outline) + if v := app.Find("id:toolbar-history"); v.Style.Outline.Width != 0 { + t.Fatalf("mouse click after Tab drew focus ring on toolbar-history: %+v", v.Style.Outline) } - for _, id := range []string{"toolbar-editor-settings", "toolbar-save", "toolbar-play", "toolbar-palette"} { + for _, id := range []string{"toolbar-history", "toolbar-play", "toolbar-palette", "tool-select"} { if app.Exists("id:" + id) { if v := app.Find("id:" + id); v.Style.Outline.Width != 0 { t.Fatalf("stale focus ring remained on %q after mouse click: %+v", id, v.Style.Outline) @@ -215,48 +215,48 @@ func TestF6CyclesRegionsInSpecOrderAndRestoresLastControl(t *testing.T) { app.Settle() assertRegionRing("F6(no-toast)["+string(want)+"]", want) if i == 0 { - // Inside Header: tab to toolbar-editor-settings so we can verify restoration later. - app.Focus("id:toolbar-editor-settings") + // Inside Header: focus toolbar-history so we can verify restoration later. + app.Focus("id:toolbar-history") app.Settle() } if i == 1 { - // Inside Scene tree: focus scene-tree-tab-remote so we can verify restoration later. - app.Focus("id:scene-tree-tab-remote") + // Inside Scene tree: focus scene-tree-eye-hero so we can verify restoration later. + app.Focus("id:scene-tree-eye-hero") app.Settle() } } - // Returning to Header via F6 must restore focus to toolbar-editor-settings. - if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-editor-settings" { + // Returning to Header via F6 must restore focus to toolbar-history. + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-history" { gotID := "" if fv != nil { gotID = fv.Props.TestID } - t.Fatalf("after F6 wrap to Header, focused = %q, want toolbar-editor-settings", gotID) + t.Fatalf("after F6 wrap to Header, focused = %q, want toolbar-history", gotID) } - // Moving forward into SceneTree must restore focus to scene-tree-tab-remote. + // Moving forward into SceneTree must restore focus to scene-tree-eye-hero. app.Key("f6") app.Settle() assertRegionRing("F6-restore-scene-tree", editor.RegionSceneTree) - if fv := focusedView(app); fv == nil || fv.Props.TestID != "scene-tree-tab-remote" { + if fv := focusedView(app); fv == nil || fv.Props.TestID != "scene-tree-eye-hero" { gotID := "" if fv != nil { gotID = fv.Props.TestID } - t.Fatalf("after F6 to SceneTree, focused = %q, want scene-tree-tab-remote", gotID) + t.Fatalf("after F6 to SceneTree, focused = %q, want scene-tree-eye-hero", gotID) } // Shift-F6 walks backwards in exact reverse order and restores Header's remembered control. app.Key("shift+f6") app.Settle() assertRegionRing("Shift-F6-back-to-header", editor.RegionHeader) - if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-editor-settings" { + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-history" { gotID := "" if fv != nil { gotID = fv.Props.TestID } - t.Fatalf("after Shift-F6 to Header, focused = %q, want toolbar-editor-settings", gotID) + t.Fatalf("after Shift-F6 to Header, focused = %q, want toolbar-history", gotID) } // Show a toast: must NOT steal focus from Header, and must now appear after StatusBar in F6 order. @@ -266,8 +266,8 @@ func TestF6CyclesRegionsInSpecOrderAndRestoresLastControl(t *testing.T) { ActionLabel: "Undo", }) app.Settle() - if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-editor-settings" { - t.Fatalf("ShowToast stole focus from toolbar-editor-settings: got %v", fv) + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-history" { + t.Fatalf("ShowToast stole focus from toolbar-history: got %v", fv) } // Shift-F6 from Header wraps directly to Toast (the last region while shown). @@ -386,8 +386,8 @@ func TestDialogTrapsFocusAndEscRestoresOpener(t *testing.T) { }, focusDesktopEnv, nsgotest.Size(1440, 900)) app.Settle() - // 1. Open Keyboard Shortcuts modal (⌘/) while focused on toolbar-editor-settings. - app.Focus("id:toolbar-editor-settings") + // 1. Open Keyboard Shortcuts modal (⌘/) while focused on toolbar-history. + app.Focus("id:toolbar-history") app.Settle() app.Key("meta+/") app.Settle() @@ -421,26 +421,26 @@ func TestDialogTrapsFocusAndEscRestoresOpener(t *testing.T) { t.Fatalf("mod+. behind dialog ran OnStopAgent %d times, want 1", agentStopped) } - // Closing with Esc must return focus to toolbar-editor-settings. + // Closing with Esc must return focus to toolbar-history. app.Key("escape") app.Advance(250 * time.Millisecond) app.Settle() if ed.ShortcutsSheetOpen() { t.Fatal("expected Esc to close Shortcuts Sheet dialog") } - if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-editor-settings" { + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-history" { gotID := "" if fv != nil { gotID = fv.Props.TestID } - t.Fatalf("after Esc closed Shortcuts Sheet, focus = %q, want toolbar-editor-settings", gotID) + t.Fatalf("after Esc closed Shortcuts Sheet, focus = %q, want toolbar-history", gotID) } - // 2. Open unified Settings view via Enter on toolbar-editor-settings, verify F6 is blocked, and Esc restores toolbar-editor-settings. - app.Key("enter") + // 2. Open unified Settings view via Cmd+Shift+, while focused on toolbar-history, verify F6 is blocked, and Esc restores toolbar-history. + app.Key("meta+shift+,") app.Settle() if !ed.SettingsOpen() { - t.Fatal("expected Settings view to open on Enter") + t.Fatal("expected Settings view to open on Cmd+Shift+,") } app.Key("f6") app.Settle() @@ -453,12 +453,12 @@ func TestDialogTrapsFocusAndEscRestoresOpener(t *testing.T) { if ed.SettingsOpen() { t.Fatal("expected Esc to close Settings view") } - if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-editor-settings" { + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-history" { gotID := "" if fv != nil { gotID = fv.Props.TestID } - t.Fatalf("after Esc closed Settings view, focus = %q, want toolbar-editor-settings", gotID) + t.Fatalf("after Esc closed Settings view, focus = %q, want toolbar-history", gotID) } // 3. Open Command Palette via mouse click on toolbar-palette, close with Esc -> returns focus to toolbar-palette. @@ -1065,18 +1065,18 @@ func TestFocusSpecLightCaptureGuardsUnmountTypingAndScrub(t *testing.T) { app.Advance(250 * time.Millisecond) app.Settle() - app.Focus("id:toolbar-editor-settings") + app.Focus("id:toolbar-history") app.Settle() app.Key("meta+/") app.Settle() app.Key("escape") app.Advance(250 * time.Millisecond) app.Settle() - if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-editor-settings" { + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-history" { gotID := "" if fv != nil { gotID = fv.Props.TestID } - t.Fatalf("after chrome remount + ShortcutsSheet Esc, focus = %q, want toolbar-editor-settings", gotID) + t.Fatalf("after chrome remount + ShortcutsSheet Esc, focus = %q, want toolbar-history", gotID) } } diff --git a/packages/game/editor/gizmo2d.go b/packages/game/editor/gizmo2d.go index 7018c45ef..37fc5ad3b 100644 --- a/packages/game/editor/gizmo2d.go +++ b/packages/game/editor/gizmo2d.go @@ -249,9 +249,13 @@ func (g gizmo2D) scaleShown(h GizmoHandle2D) bool { return h.IsScale() && g.scale[h-Handle2DScaleN] } -// Gizmo2DShown reports whether the 2D viewport shows the transform gizmo: on the selected object(s), nested children included, in 2D, with the Select or Move tool, outside Play. Objects hidden or locked in the editor (SetObjectHidden, SetObjectLocked), or under one that is, have no gizmo. +func isTransformTool2D(t Tool) bool { + return t == ToolSelect || t == ToolMove || t == ToolRotate || t == ToolScale +} + +// Gizmo2DShown reports whether the 2D viewport shows the transform gizmo: on the selected object(s), nested children included, in 2D, with the Select, Move, Rotate, or Scale tool, outside Play. Objects hidden or locked in the editor (SetObjectHidden, SetObjectLocked), or under one that is, have no gizmo. func (e *Editor) Gizmo2DShown() bool { - if e == nil || e.playing || e.ViewMode != ViewMode2D || (e.Tool != ToolSelect && e.Tool != ToolMove) { + if e == nil || e.playing || e.ViewMode != ViewMode2D || !isTransformTool2D(e.Tool) { return false } if len(e.draggableSelectedIDs()) == 0 { @@ -522,7 +526,7 @@ func (e *Editor) Dragging2D() GizmoHandle2D { // BeginDrag2D starts a drag in the 2D viewport at the canvas point (x, y), where the pointer went down, with the Select or Move tool: on a handle of the selected object's gizmo (PickGizmo2D) it takes that handle, and on another object it selects that object and moves it. A nested child is dragged in its parent's space, so it follows the pointer under a turned or scaled parent. It returns the handle taken, Handle2DNone when the press is on nothing, another drag is under way, the tool or view mode is another, the scene plays, or the object is hidden or locked in the editor or under one that is. The drag changes the object as UpdateDrag2D says and is recorded by EndDrag2D as one undoable step. func (e *Editor) BeginDrag2D(x, y float32) GizmoHandle2D { - if e == nil || e.playing || e.HistoryPreviewActive() || e.ViewMode != ViewMode2D || (e.Tool != ToolSelect && e.Tool != ToolMove) || e.drag2D.handle != Handle2DNone || !isFiniteFloat32(x) || !isFiniteFloat32(y) { + if e == nil || e.playing || e.HistoryPreviewActive() || e.ViewMode != ViewMode2D || !isTransformTool2D(e.Tool) || e.drag2D.handle != Handle2DNone || !isFiniteFloat32(x) || !isFiniteFloat32(y) { return Handle2DNone } h, idx := e.pickGizmo2DWithIndex(x, y) diff --git a/packages/game/editor/gizmo2d_test.go b/packages/game/editor/gizmo2d_test.go index 5ac40d487..c813ddcd8 100644 --- a/packages/game/editor/gizmo2d_test.go +++ b/packages/game/editor/gizmo2d_test.go @@ -41,11 +41,11 @@ func checkOneUndoStep(t *testing.T, app *nsgotest.App, ed *editor.Editor, before if bytes.Equal(after, before) { t.Fatal("the drag left the scene as it was") } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, before) { t.Fatalf("Undo left the scene\n%s\nwant\n%s", got, before) } - app.Press("id:toolbar-redo") + redoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, after) { t.Fatalf("Redo made the scene\n%s\nwant\n%s", got, after) } @@ -574,7 +574,7 @@ func TestTopLeftPivotKeepsTheMoveSquare(t *testing.T) { t.Fatalf("a drag of the move square left the hero at (%v, %v) scale (%v, %v), want (45, 42) unscaled", h.X, h.Y, h.ScaleX, h.ScaleY) } checkOneUndoStep(t, app, ed, before) - app.Press("id:toolbar-undo") + undoInUI(app, ed) cx, cy := ed.WorldToCanvas(56, 56) app.DragAt("id:editor-viewport", pt(cx, cy), pt(32, 32)) h, _, _ = ed.FindObject("hero") diff --git a/packages/game/editor/gizmo3d_transform_test.go b/packages/game/editor/gizmo3d_transform_test.go index 9fb5be78e..593ec243c 100644 --- a/packages/game/editor/gizmo3d_transform_test.go +++ b/packages/game/editor/gizmo3d_transform_test.go @@ -632,13 +632,18 @@ func TestGizmo3DShortcutsSpaceToggleStatusDeltaUndoAndYAML(t *testing.T) { t.Fatalf("key w in 3D: GizmoMode = %v, want Translate", ed.GizmoMode) } - // Verify 2D Erase Tile still owns E in 2D view (scoped shortcuts!). + // Verify E activates Rotate in 2D view and B activates Paint Tile (scoped shortcuts!). app.Key("alt+2") app.Key("e") - if ed.Tool != editor.ToolEraseTile { - t.Fatalf("key e in 2D: Tool = %v, want ToolEraseTile", ed.Tool) + if ed.Tool != editor.ToolRotate { + t.Fatalf("key e in 2D: Tool = %v, want ToolRotate", ed.Tool) + } + app.Key("b") + if ed.Tool != editor.ToolPaintTile { + t.Fatalf("key b in 2D: Tool = %v, want ToolPaintTile", ed.Tool) } app.Key("alt+3") + app.Key("w") // 2. Local / Global toggle via 3D bottom bar button, shortcut T, command registry, and status bar readout. if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Translate · Global") { diff --git a/packages/game/editor/i18n.go b/packages/game/editor/i18n.go index 6b2b7b870..522b772ad 100644 --- a/packages/game/editor/i18n.go +++ b/packages/game/editor/i18n.go @@ -153,6 +153,12 @@ func (e *Editor) localizedToolName(t Tool) string { return e.T("tool.select") case ToolMove: return e.T("tool.move") + case ToolRotate: + return e.T("tool.rotate") + case ToolScale: + return e.T("tool.scale") + case ToolPan: + return e.T("tool.pan") case ToolPlace: return e.T("tool.place") case ToolPaintTile: diff --git a/packages/game/editor/i18n_settings_test.go b/packages/game/editor/i18n_settings_test.go index 82c447289..9475ff41c 100644 --- a/packages/game/editor/i18n_settings_test.go +++ b/packages/game/editor/i18n_settings_test.go @@ -282,8 +282,11 @@ func TestEditorUIChineseAndLiveSwitchWithoutRestart(t *testing.T) { }, nsgotest.Size(1440, 900), nsgotest.Environment(core.Environment{OS: core.OSMacOS, Idiom: core.IdiomDesktop, Locale: "en-US"})) // Initially English. - if got := allText(app.Find("id:editor-toolbar")); !strings.Contains(got, "Select") || !strings.Contains(got, "Save") { - t.Fatalf("initial English toolbar missing Select/Save: %q", got) + openFileBrowserInUI(app, ed) + openAssetBrowserInUI(app, ed) + openLayersPanelInUI(app, ed) + if got := allText(app.Find("id:editor-toolbar")); !strings.Contains(got, "Search") || !strings.Contains(got, "Play") { + t.Fatalf("initial English toolbar missing Search/Play: %q", got) } if got := allText(app.Find("id:file-browser")); !strings.Contains(got, "Files") || !strings.Contains(got, "Refresh") { t.Fatalf("initial English file browser missing Files/Refresh: %q", got) @@ -291,17 +294,17 @@ func TestEditorUIChineseAndLiveSwitchWithoutRestart(t *testing.T) { if got := allText(app.Find("id:editor-inspector")); !strings.Contains(got, "Inspector") || !strings.Contains(got, "TRANSFORM") { t.Fatalf("initial English inspector missing Inspector/TRANSFORM: %q", got) } - if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Mode: Edit") || !strings.Contains(got, "Tool: Select") { + if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Select") { t.Fatalf("initial English status bar = %q", got) } if len(app.Menu) != 5 || app.Menu[0].Label != "File" || app.Menu[1].Label != "Edit" || app.Menu[4].Label != "Help" { t.Fatalf("initial English menu = %v", app.Menu) } - // Open Editor Settings via toolbar button and switch to Chinese live. - app.Press("id:toolbar-editor-settings") + // Open Editor Settings via command and switch to Chinese live. + runEditorCommand(t, app, ed, editor.CmdEditorSettings) if !ed.EditorSettingsOpen() { - t.Fatal("toolbar-editor-settings did not open Editor Settings dialog") + t.Fatal("CmdEditorSettings did not open Editor Settings dialog") } app.Press("id:editor-settings-lang-zh") if ed.Language() != editor.LanguageChinese || ed.ResolvedLanguage() != "zh" { @@ -309,7 +312,7 @@ func TestEditorUIChineseAndLiveSwitchWithoutRestart(t *testing.T) { } // Verify toolbar, file browser, asset browser, scene tree, layers, inspector, status bar, and menu bar are Chinese. - if got := allText(app.Find("id:editor-toolbar")); !strings.Contains(got, "选择") || !strings.Contains(got, "移动") || !strings.Contains(got, "撤销") || !strings.Contains(got, "保存") { + if got := allText(app.Find("id:editor-toolbar")); !strings.Contains(got, "搜索") || !strings.Contains(got, "播放") { t.Fatalf("Chinese toolbar = %q", got) } if got := allText(app.Find("id:file-browser")); !strings.Contains(got, "文件") || !strings.Contains(got, "打开") || !strings.Contains(got, "刷新") || !strings.Contains(got, "移动") { @@ -318,8 +321,8 @@ func TestEditorUIChineseAndLiveSwitchWithoutRestart(t *testing.T) { if got := allText(app.Find("id:asset-browser")); !strings.Contains(got, "资源") { t.Fatalf("Chinese asset browser = %q", got) } - if got := allText(app.Find("id:scene-tree-panel")); !strings.Contains(got, "场景") { - t.Fatalf("Chinese scene tree = %q", got) + if got := allText(app.Find("id:scene-rail-title")); !strings.Contains(got, "场景") { + t.Fatalf("Chinese scene rail title = %q", got) } if got := allText(app.Find("id:layers-panel")); !strings.Contains(got, "图层") { t.Fatalf("Chinese layers panel = %q", got) @@ -327,10 +330,13 @@ func TestEditorUIChineseAndLiveSwitchWithoutRestart(t *testing.T) { if got := allText(app.Find("id:editor-inspector")); !strings.Contains(got, "检查器") || !strings.Contains(got, "名称") || !strings.Contains(got, "变换") || !strings.Contains(got, "删除") { t.Fatalf("Chinese inspector = %q", got) } - if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "模式:编辑") || !strings.Contains(got, "工具:选择") || !strings.Contains(got, "图层:") { + if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "选择") { t.Fatalf("Chinese status bar mode = %q", got) } - if got := app.Find("id:status-problems").Text; !strings.Contains(got, "问题:") { + if got := allText(app.Find("id:status-active-layer")); !strings.Contains(got, "图层") { + t.Fatalf("Chinese status bar layer = %q", got) + } + if got := app.Find("id:status-problems").Text; !strings.Contains(got, "无问题") && !strings.Contains(got, "问题") { t.Fatalf("Chinese status bar problems = %q", got) } if len(app.Menu) != 5 || app.Menu[0].Label != "文件" || app.Menu[1].Label != "编辑" || app.Menu[2].Label != "视图" || app.Menu[3].Label != "项目" || app.Menu[4].Label != "帮助" { @@ -342,7 +348,7 @@ func TestEditorUIChineseAndLiveSwitchWithoutRestart(t *testing.T) { if ed.Language() != editor.LanguageEnglish || ed.ResolvedLanguage() != "en" { t.Fatalf("after switching back to English: Language=%q Resolved=%q", ed.Language(), ed.ResolvedLanguage()) } - if got := allText(app.Find("id:editor-toolbar")); !strings.Contains(got, "Select") || !strings.Contains(got, "Save") { + if got := allText(app.Find("id:editor-toolbar")); !strings.Contains(got, "Search") || !strings.Contains(got, "Play") { t.Fatalf("switched-back English toolbar = %q", got) } if got := allText(app.Find("id:file-browser")); !strings.Contains(got, "Files") || !strings.Contains(got, "Open") { @@ -351,7 +357,7 @@ func TestEditorUIChineseAndLiveSwitchWithoutRestart(t *testing.T) { if got := allText(app.Find("id:editor-inspector")); !strings.Contains(got, "Inspector") || !strings.Contains(got, "TRANSFORM") { t.Fatalf("switched-back English inspector = %q", got) } - if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Mode: Edit") || !strings.Contains(got, "Tool: Select") { + if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Select") { t.Fatalf("switched-back English status bar = %q", got) } if app.Menu[0].Label != "File" { @@ -374,9 +380,12 @@ func TestEditorLanguageFollowsSystemLocale(t *testing.T) { if ed.Language() != editor.LanguageSystem || ed.ResolvedLanguage() != "zh" { t.Fatalf("system zh-CN: Language=%q Resolved=%q", ed.Language(), ed.ResolvedLanguage()) } - if got := allText(app.Find("id:editor-toolbar")); !strings.Contains(got, "选择") || !strings.Contains(got, "保存") { + if got := allText(app.Find("id:editor-toolbar")); !strings.Contains(got, "搜索") || !strings.Contains(got, "播放") { t.Fatalf("system zh-CN toolbar = %q", got) } + if got := app.Find("id:tool-select").Props.Label; got != "选择" { + t.Fatalf("system zh-CN tool-select label = %q, want 选择", got) + } } // #921: Plugins can supply their own en/zh YAML catalogs and follow the editor's active language live. @@ -489,10 +498,7 @@ strings: if got := app.Find("id:health-localized-inspector").Text; got != "Current HP" { t.Fatalf("English plugin inspector = %q, want Current HP", got) } - if got := allText(app.Find("id:tool-health-spawn")); !strings.Contains(got, "Spawn Unit") { - t.Fatalf("English plugin tool = %q", got) - } - if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Tool: Spawn Unit") { + if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Spawn Unit") { t.Fatalf("English status bar with plugin tool = %q", got) } if _, ok := findMenuItem(app.Menu, "Project", "Plugins", "Heal All Units"); !ok { @@ -513,10 +519,7 @@ strings: if got := app.Find("id:health-localized-inspector").Text; got != "当前生命值" { t.Fatalf("Chinese plugin inspector = %q, want 当前生命值", got) } - if got := allText(app.Find("id:tool-health-spawn")); !strings.Contains(got, "生成单位") { - t.Fatalf("Chinese plugin tool = %q", got) - } - if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "工具:生成单位") { + if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "生成单位") { t.Fatalf("Chinese status bar with plugin tool = %q", got) } if _, ok := findMenuItem(app.Menu, "项目", "插件", "治疗所有单位"); !ok { @@ -567,7 +570,7 @@ func TestEditorAppearanceDarkOnLightSystemSurvivesRestart(t *testing.T) { } // Open Editor Settings and choose Dark while system remains light. - app.Press("id:toolbar-editor-settings") + runEditorCommand(t, app, ed, editor.CmdEditorSettings) app.Press("id:editor-settings-appearance-dark") if ed.Appearance() != editor.AppearanceDark { diff --git a/packages/game/editor/input_map_panel_test.go b/packages/game/editor/input_map_panel_test.go index b4e3a6b9c..a47c6e1fc 100644 --- a/packages/game/editor/input_map_panel_test.go +++ b/packages/game/editor/input_map_panel_test.go @@ -35,7 +35,7 @@ func TestInputMapPanelAddActionCaptureKeySaveAndUndo(t *testing.T) { } // Open the Input Map panel from the toolbar. - app.Press("id:toolbar-input-map") + runEditorCommand(t, app, ed, editor.CmdInputMap) app.Settle() if !app.Exists("id:input-map-panel") { t.Fatal("pressing toolbar-input-map did not open the panel") @@ -67,7 +67,7 @@ func TestInputMapPanelAddActionCaptureKeySaveAndUndo(t *testing.T) { } // Save via toolbar Save and read the binding back from game.yaml on disk. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() saved, err := project.Check(os.DirFS(dir)) if err != nil { @@ -92,20 +92,20 @@ func TestInputMapPanelAddActionCaptureKeySaveAndUndo(t *testing.T) { } // Undo removes the binding, then removes the action (and prunes empty input section). - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if got := ed.InputActions(); len(got) != 1 || len(got[0].Bindings) != 0 { t.Fatalf("after 1st undo: %+v, want jump with 0 bindings", got) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if ed.Project.Input != nil { t.Fatalf("after 2nd undo: Project.Input = %+v, want nil", ed.Project.Input) } // Redo brings both the action and the captured key binding back. - app.Press("id:toolbar-redo") - app.Press("id:toolbar-redo") + redoInUI(app, ed) + redoInUI(app, ed) app.Settle() if got := ed.InputActions(); len(got) != 1 || len(got[0].Bindings) != 1 || got[0].Bindings[0].Key != "space" { t.Fatalf("after Redo: %+v, want jump bound to space", got) @@ -316,7 +316,7 @@ func TestInputMapPanelRegionsMotionAndGamepadAxes(t *testing.T) { app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 900)) - app.Press("id:toolbar-input-map") + runEditorCommand(t, app, ed, editor.CmdInputMap) app.Settle() if !app.Exists("id:input-region-canvas") { t.Fatal("input-region-canvas not rendered") diff --git a/packages/game/editor/layers_test.go b/packages/game/editor/layers_test.go index af59537ab..128e4c5ac 100644 --- a/packages/game/editor/layers_test.go +++ b/packages/game/editor/layers_test.go @@ -29,6 +29,7 @@ func TestLayersPanelAddsALayerThatTakesPlacedObjects(t *testing.T) { t.Fatalf("editor.New: %v", err) } app := startEditorView(t, ed) + openLayersPanelInUI(app, ed) app.Press("id:layers-add") if got := layerNames(ed); !slices.Equal(got, []string{"main", "layer_2"}) { @@ -49,18 +50,18 @@ func TestLayersPanelAddsALayerThatTakesPlacedObjects(t *testing.T) { if ed.ActiveLayer != "main" { t.Fatalf("pressing main made %q active", ed.ActiveLayer) } - if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Layer: main") { - t.Fatalf("the status bar reads %q, want Layer: main", got) + if got := allText(app.Find("id:status-active-layer")); !strings.Contains(got, "Layer main") { + t.Fatalf("the status bar reads %q, want Layer main", got) } app.Press("id:layers-row-actors") if ed.ActiveLayer != "actors" { t.Fatalf("pressing actors made %q active", ed.ActiveLayer) } - if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Layer: actors") { - t.Fatalf("the status bar reads %q, want Layer: actors", got) + if got := allText(app.Find("id:status-active-layer")); !strings.Contains(got, "Layer actors") { + t.Fatalf("the status bar reads %q, want Layer actors", got) } - app.Press("id:tool-place") + runEditorCommand(t, app, ed, editor.CmdToolPlace) px, py := ed.WorldToCanvas(100, 60) app.Touch("id:editor-viewport", core.Point{X: core.Points(px), Y: core.Points(py)}).Lift() if ed.SelectedID == "" { @@ -103,6 +104,7 @@ func TestLayersPanelHideShowAndRemoveRoundTrip(t *testing.T) { ed.History.Clear() opened := mustSave(t, ed) app := startEditorView(t, ed) + openLayersPanelInUI(app, ed) app.Press("id:layers-eye-actors") if info := layerInfoOf(t, ed, "actors"); info.Visible { @@ -111,7 +113,7 @@ func TestLayersPanelHideShowAndRemoveRoundTrip(t *testing.T) { if hidden := mustSave(t, ed); !bytes.Contains(hidden, []byte("visible: false")) { t.Fatalf("hiding the layer did not write visible: false:\n%s", hidden) } - if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Layer: actors (hidden)") { + if got := allText(app.Find("id:status-active-layer")); !strings.Contains(got, "Layer actors (hidden)") { t.Fatalf("the status bar reads %q, want the active layer marked hidden", got) } app.Press("id:layers-eye-actors") @@ -135,19 +137,19 @@ func TestLayersPanelHideShowAndRemoveRoundTrip(t *testing.T) { } removed := mustSave(t, ed) - app.Press("id:toolbar-undo") + undoInUI(app, ed) if after := mustSave(t, ed); !bytes.Equal(after, opened) { t.Fatalf("Undo did not restore the removed layer:\n%s\nwant:\n%s", after, opened) } if ed.ActiveLayer != "actors" { t.Fatalf("Undo left %q active, want actors", ed.ActiveLayer) } - app.Press("id:toolbar-redo") + redoInUI(app, ed) if after := mustSave(t, ed); !bytes.Equal(after, removed) { t.Fatalf("Redo did not remove the layer again:\n%s\nwant:\n%s", after, removed) } for ed.History.CanUndo() { - app.Press("id:toolbar-undo") + undoInUI(app, ed) } if after := mustSave(t, ed); !bytes.Equal(after, opened) { t.Fatalf("undoing every edit did not restore the scene:\n%s\nwant:\n%s", after, opened) @@ -170,6 +172,7 @@ func TestLayersPanelDragReordersAndMenuSetsSpace(t *testing.T) { ed := newNestedEditor(t) opened := mustSave(t, ed) app := startEditorView(t, ed) + openLayersPanelInUI(app, ed) drag(app, "id:layers-name-ui", "id:layers-row-floor", 0.1) if got := layerNames(ed); !slices.Equal(got, []string{"ui", "floor", "actors"}) { @@ -188,7 +191,7 @@ func TestLayersPanelDragReordersAndMenuSetsSpace(t *testing.T) { t.Fatalf("floor's row reads %q", got) } for ed.History.CanUndo() { - app.Press("id:toolbar-undo") + undoInUI(app, ed) } if after := mustSave(t, ed); !bytes.Equal(after, opened) { t.Fatalf("undoing the drags and the space did not restore the scene:\n%s\nwant:\n%s", after, opened) @@ -200,6 +203,7 @@ func TestLockedLayerIsNotPickedOrPainted(t *testing.T) { ed := newNestedEditor(t) opened := mustSave(t, ed) app := startEditorView(t, ed) + openLayersPanelInUI(app, ed) app.Press("id:layers-lock-actors") if !ed.LayerLocked("actors") { @@ -229,7 +233,7 @@ func TestLockedLayerIsNotPickedOrPainted(t *testing.T) { app.Press("id:layers-row-floor") app.Press("id:layers-lock-floor") - app.Press("id:tool-paint") + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) tx, ty := ed.WorldToCanvas(24, 24) paint := func() { app.Touch("id:editor-viewport", core.Point{X: core.Points(tx), Y: core.Points(ty)}).Lift() @@ -238,7 +242,7 @@ func TestLockedLayerIsNotPickedOrPainted(t *testing.T) { if !bytes.Equal(mustSave(t, ed), opened) || ed.History.CanUndo() { t.Fatal("tools changed the scene on locked layers") } - if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Layer: floor (locked)") { + if got := allText(app.Find("id:status-active-layer")); !strings.Contains(got, "Layer floor (locked)") { t.Fatalf("the status bar reads %q, want the active layer marked locked", got) } app.Press("id:layers-lock-floor") @@ -633,6 +637,7 @@ layers: t.Fatalf("editor.New: %v", err) } app := startEditorView(t, ed) + openLayersPanelInUI(app, ed) if !app.Enabled("id:layers-eye-ground") || !app.Enabled("id:layers-eye-hud") { t.Fatal("the eye button should be enabled for both inherited (via layerOverrides) and own layers") diff --git a/packages/game/editor/library_test.go b/packages/game/editor/library_test.go index c2417190e..7f1b57f96 100644 --- a/packages/game/editor/library_test.go +++ b/packages/game/editor/library_test.go @@ -42,6 +42,7 @@ func TestLibraryPanelInstallsAndRemovesAPack(t *testing.T) { t.Fatal(err) } ed.Library = openLibrary(t, repoLibrary) + ed.SetLibraryPanelOpen(true) app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) @@ -224,6 +225,7 @@ func TestLibraryPanelFetchesARemotePack(t *testing.T) { t.Fatal("a library over http is not remote") } ed.Library = lib + ed.SetLibraryPanelOpen(true) app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) @@ -263,6 +265,7 @@ func TestLibraryPanelReportsAFailedFetch(t *testing.T) { lib, release, _ := remoteLibrary(t, "tiles.png") release() ed.Library = lib + ed.SetLibraryPanelOpen(true) app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) @@ -290,6 +293,7 @@ func TestOpeningAProjectCancelsAFetch(t *testing.T) { } lib, release, cancelled := remoteLibrary(t, "") ed.Library = lib + ed.SetLibraryPanelOpen(true) app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) diff --git a/packages/game/editor/lights2d_test.go b/packages/game/editor/lights2d_test.go index 8183820cd..648202b20 100644 --- a/packages/game/editor/lights2d_test.go +++ b/packages/game/editor/lights2d_test.go @@ -252,7 +252,8 @@ func TestLightingPreviewToolbarToggleAndCommand(t *testing.T) { if !ed.ShowLightingPreview { t.Fatal("expected ShowLightingPreview to default to true") } - app.Press("id:view-lighting-preview") + app.Post(func() { ed.SetShowLightingPreview(false) }) + app.Settle() if ed.ShowLightingPreview { t.Fatal("expected view-lighting-preview button to toggle ShowLightingPreview off") } diff --git a/packages/game/editor/locales/en.yaml b/packages/game/editor/locales/en.yaml index c3b2f7476..07f8f2322 100644 --- a/packages/game/editor/locales/en.yaml +++ b/packages/game/editor/locales/en.yaml @@ -524,10 +524,12 @@ strings: files.openTableLabel: Open the selected YAML file in the Data Table editor files.placeScene: Place files.placeSceneLabel: Place an instance of this scene in the active layer + files.railEmpty: No files open files.refresh: Refresh files.renameSafely: Rename Safely… files.search: Search files.searchLabel: Toggle the Project Search and References panel + files.sectionTitle: Files files.title: Files gizmo.rotate: Rotate gizmo.scale: Scale @@ -762,6 +764,7 @@ strings: menu.openProject: Open Project... menu.overlays: Overlays menu.paintTile: Paint Tile + menu.pan: Pan menu.particleEditor: Particle Emitter Editor menu.paste: Paste menu.pasteInto: Paste as Child @@ -953,6 +956,7 @@ strings: problems.fixProposed: Fix proposed problems.foundBanner: game check found a problem problems.ignore: Ignore + problems.none: No problems problems.openPanelLabel: Toggle Agent problem panel problems.retry: Retry problems.showMe: Show me @@ -1005,6 +1009,8 @@ strings: sceneTree.moveDown: Move Down sceneTree.moveToLayer: Move to Layer {name} sceneTree.moveUp: Move Up + sceneTree.nodeCount: '{count} nodes' + sceneTree.nodeCountOne: 1 node sceneTree.objectID: Object ID sceneTree.objectName: Object Name sceneTree.outdent: Move Out of Parent @@ -1012,6 +1018,7 @@ strings: sceneTree.pasteInto: Paste as Child sceneTree.remote: Remote sceneTree.rename: Rename + sceneTree.sectionTitle: Scene sceneTree.show: Show in Viewport sceneTree.showNamed: Show {id} sceneTree.title: Scene @@ -1327,9 +1334,14 @@ strings: snap.scaleStep: Scale step snap.showGrid: Show 2D grid overlay snap.title: Snapping + status.activeLayerLabel: 'Active layer: {layer}' status.buildError: 'Build error: {error}' status.changes: Changes status.changesCount: 'Changes: {count}' + status.debugger: Debugger + status.debuggerLabel: Toggle Debugger and Profiler panel + status.layerReadout: Layer {layer} + status.mergeConflictsLabel: Open Scene Merge Conflicts status.mode2d: 'Mode: {mode} | View: 2D {zoom}% | Tool: {tool} | Layer: {layer}' status.mode3d: 'Mode: {mode} | View: 3D {view} | Gizmo: {gizmo} · {space} | Layer: {layer}' status.mode3dGridMap: 'Mode: {mode} | View: 3D {view} (GridMap {tool}, Y={floor}, Orient={orient}/24) | Layer: {layer}' @@ -1429,9 +1441,12 @@ strings: tool.move: Move tool.navTestPath: Test Path tool.paintTile: Paint Tile + tool.pan: Pan tool.pickTile: Pick Tile tool.place: Place tool.plugin: Plugin + tool.rotate: Rotate + tool.scale: Scale tool.select: Select toolbar.animate: Animate toolbar.animateLabel: Animate the selected object in a new clip @@ -1472,6 +1487,7 @@ strings: toolbar.output: Output toolbar.outputLabel: Toggle the Output log panel toolbar.paint: Paint + toolbar.pan: Pan toolbar.pick: Pick toolbar.place: Place toolbar.play: Play @@ -1486,6 +1502,8 @@ strings: toolbar.saveAs: Save As… toolbar.scale: Scale toolbar.sceneCameraView: Scene Camera View ({key}) + toolbar.search: Search + toolbar.searchLabel: Search files, nodes and commands toolbar.select: Select toolbar.shadingLit: Lit toolbar.shadingUnlit: Unlit @@ -1500,7 +1518,25 @@ strings: toolbar.translate: Translate toolbar.undo: Undo toolbar.unsavedFailedLabel: Unsaved changes · save failed - toolbar.unsavedLabel: Unsaved changes + toolbar.unsavedLabel: unsaved changes + workspace.dismiss: Dismiss + workspace.loadingProject: Loading project… + workspace.loadingShort: Loading… + workspace.noProjectDesc: Open an existing game project or create a new one to start editing scenes and collaborating with the agent. + workspace.noProjectInspectorHint: Open a project to inspect scene and object properties. + workspace.noProjectRailHint: Open a project to view its scene tree and files. + workspace.noProjectTitle: No project open + workspace.noSceneDesc: Open a scene file from the project or create a new scene to start editing. + workspace.noSceneInspectorHint: Open a scene to inspect properties. + workspace.noSceneRailHint: Open or create a scene to view its nodes. + workspace.noSceneTitle: No scene open + workspace.openAnotherScene: Open another scene + workspace.openProject: Open project + workspace.retry: Retry + workspace.sceneErrorShort: Scene failed to open + workspace.sceneErrorTitle: Couldn't open scene + workspace.searchFiles: Search files + workspace.startScreen: Start screen plurals: agent.playDot.failed: one: '{count} task failed' diff --git a/packages/game/editor/locales/zh.yaml b/packages/game/editor/locales/zh.yaml index 731845270..2afc724c2 100644 --- a/packages/game/editor/locales/zh.yaml +++ b/packages/game/editor/locales/zh.yaml @@ -524,10 +524,12 @@ strings: files.openTableLabel: 在数据表编辑器中打开选中的 YAML 文件 files.placeScene: 放置 files.placeSceneLabel: 在当前图层放置此场景的实例 + files.railEmpty: 未打开文件 files.refresh: 刷新 files.renameSafely: 安全重命名… files.search: 搜索 files.searchLabel: 切换项目搜索与引用面板 + files.sectionTitle: 文件 files.title: 文件 gizmo.rotate: 旋转 gizmo.scale: 缩放 @@ -762,6 +764,7 @@ strings: menu.openProject: 打开项目… menu.overlays: 叠加层 menu.paintTile: 绘制瓦片 + menu.pan: 平移 menu.particleEditor: 粒子发射器编辑器 menu.paste: 粘贴 menu.pasteInto: 粘贴为子级 @@ -953,6 +956,7 @@ strings: problems.fixProposed: 已有修复建议 problems.foundBanner: game check 发现一个问题 problems.ignore: 忽略 + problems.none: 没有问题 problems.openPanelLabel: 切换智能体问题面板 problems.retry: 重试 problems.showMe: 定位查看 @@ -1005,6 +1009,8 @@ strings: sceneTree.moveDown: 下移 sceneTree.moveToLayer: 移至图层 {name} sceneTree.moveUp: 上移 + sceneTree.nodeCount: '{count} 个节点' + sceneTree.nodeCountOne: 1 个节点 sceneTree.objectID: 对象 ID sceneTree.objectName: 对象名称 sceneTree.outdent: 移出父级 @@ -1012,6 +1018,7 @@ strings: sceneTree.pasteInto: 粘贴为子级 sceneTree.remote: 远程 sceneTree.rename: 重命名 + sceneTree.sectionTitle: 场景 sceneTree.show: 在视口中显示 sceneTree.showNamed: 显示 {id} sceneTree.title: 场景 @@ -1327,9 +1334,14 @@ strings: snap.scaleStep: 缩放步进 snap.showGrid: 显示 2D 网格叠加层 snap.title: 吸附设置 + status.activeLayerLabel: 当前图层:{layer} status.buildError: 构建错误:{error} status.changes: 变更 status.changesCount: 变更:{count} + status.debugger: 调试器 + status.debuggerLabel: 切换调试器与性能分析面板 + status.layerReadout: 图层 {layer} + status.mergeConflictsLabel: 打开场景合并冲突 status.mode2d: 模式:{mode} | 视图:2D {zoom}% | 工具:{tool} | 图层:{layer} status.mode3d: 模式:{mode} | 视图:3D {view} | 操纵杆:{gizmo} · {space} | 图层:{layer} status.mode3dGridMap: 模式:{mode} | 视图:3D {view}(GridMap {tool},Y={floor},朝向={orient}/24)| 图层:{layer} @@ -1429,9 +1441,12 @@ strings: tool.move: 移动 tool.navTestPath: 测试路径 tool.paintTile: 绘制瓦片 + tool.pan: 平移 tool.pickTile: 吸取瓦片 tool.place: 放置 tool.plugin: 插件 + tool.rotate: 旋转 + tool.scale: 缩放 tool.select: 选择 toolbar.animate: 动画 toolbar.animateLabel: 在新动画片段中为选中对象制作动画 @@ -1472,6 +1487,7 @@ strings: toolbar.output: 输出 toolbar.outputLabel: 切换输出日志面板 toolbar.paint: 绘制 + toolbar.pan: 平移 toolbar.pick: 吸取 toolbar.place: 放置 toolbar.play: 播放 @@ -1486,6 +1502,8 @@ strings: toolbar.saveAs: 另存为… toolbar.scale: 缩放 toolbar.sceneCameraView: 场景相机视图({key}) + toolbar.search: 搜索 + toolbar.searchLabel: 搜索文件、节点和命令 toolbar.select: 选择 toolbar.shadingLit: 光照 toolbar.shadingUnlit: 无光照 @@ -1501,6 +1519,24 @@ strings: toolbar.undo: 撤销 toolbar.unsavedFailedLabel: 未保存的更改 · 保存失败 toolbar.unsavedLabel: 未保存的更改 + workspace.dismiss: 关闭 + workspace.loadingProject: 正在加载项目… + workspace.loadingShort: 加载中… + workspace.noProjectDesc: 打开现有游戏项目或新建项目,即可开始编辑场景并与智能体协作。 + workspace.noProjectInspectorHint: 打开项目以检查场景与对象属性。 + workspace.noProjectRailHint: 打开项目以查看场景树与文件。 + workspace.noProjectTitle: 未打开项目 + workspace.noSceneDesc: 打开项目中的场景文件或新建场景以开始编辑。 + workspace.noSceneInspectorHint: 打开场景以检查属性。 + workspace.noSceneRailHint: 打开或新建场景以查看节点。 + workspace.noSceneTitle: 未打开场景 + workspace.openAnotherScene: 打开其他场景 + workspace.openProject: 打开项目 + workspace.retry: 重试 + workspace.sceneErrorShort: 场景打开失败 + workspace.sceneErrorTitle: 无法打开场景 + workspace.searchFiles: 搜索文件 + workspace.startScreen: 开始界面 plurals: agent.playDot.failed: other: '{count} 个任务失败' diff --git a/packages/game/editor/localization_panel_test.go b/packages/game/editor/localization_panel_test.go index 94e846649..a3fd57d03 100644 --- a/packages/game/editor/localization_panel_test.go +++ b/packages/game/editor/localization_panel_test.go @@ -254,7 +254,7 @@ func TestLocalizationPanelUIAddRemoveLocaleAndKey(t *testing.T) { }, nsgotest.Size(1280, 900)) // Open panel via toolbar Strings toggle. - app.Press("id:toolbar-l10n") + runEditorCommand(t, app, ed, editor.CmdLocalization) if !app.Exists("id:l10n-panel") { t.Fatal("toolbar-l10n did not open l10n-panel") } diff --git a/packages/game/editor/main_layout_test.go b/packages/game/editor/main_layout_test.go new file mode 100644 index 000000000..93aebcb4a --- /dev/null +++ b/packages/game/editor/main_layout_test.go @@ -0,0 +1,552 @@ +package editor_test + +import ( + "fmt" + "math" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func setupMainLayoutProject(t *testing.T) (*editor.Editor, string) { + t.Helper() + dir := t.TempDir() + write := func(rel, body string) { + t.Helper() + full := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + write("game.yaml", `version: 1 +name: Dungeon +id: dev.example.dungeon +appVersion: 1.0.0 +window: + width: 640 + height: 360 +autoload: + mainScene: level_01 + scenes: + - name: level_01 + path: scenes/level_01.scene.yaml +`) + write("prefabs/slime.scene.yaml", "version: 2\nname: Slime\nlayers:\n - name: root\n objects:\n - id: body\n x: 0\n y: 0\n") + write("scenes/level_01.scene.yaml", `version: 3 +name: level_01 +virtualWidth: 640 +virtualHeight: 360 +layers: + - name: actors + space: world + order: 0 + objects: + - id: knight + name: Knight + x: 180 + y: 220 + - id: slime_01 + name: Slime 01 + prefab: prefabs/slime.scene.yaml + x: 340 + y: 240 + - id: door_trigger + name: Door Trigger + x: 520 + y: 220 + components: + trigger: {} +`) + + ed, err := editor.New(nil, testResolver()) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + t.Cleanup(func() { _ = ed.Close() }) + _ = ed.SetAutoSave(false) + if err := ed.OpenProject(dir); err != nil { + t.Fatalf("OpenProject: %v", err) + } + ed.NotifyAgentMCPConnected(editor.AgentClientInfo{ + ID: "sess-1", + Name: "Claude Code", + Transport: "stdio", + }) + return ed, dir +} + +// TestMainLayoutAt1440x900 verifies every region, dimension, breadcrumb, tool radio group, +// left rail SCENE + FILES, viewport camera caption & bottom bar, right rail Agent/Inspector +// tabs + connection chip, and status bar at 1440x900 (#1007). +func TestMainLayoutAt1440x900(t *testing.T) { + ed, _ := setupMainLayoutProject(t) + ed.SetProposedNewObjectIDs([]string{"slime_01"}) + ed.SetViewportPointer2D(312, 184) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), focusDesktopEnv) + app.Settle() + + // Exact Spec layout dimensions at 1440x900. + if h := app.Find("id:editor-toolbar").Bounds().Size.Height; h != 44 { + t.Fatalf("header height = %v, want 44", h) + } + if w := app.Find("id:editor-scene-column").Bounds().Size.Width; w != 232 { + t.Fatalf("left rail width = %v, want 232", w) + } + if w := app.Find("id:right-rail-inspector-wrap").Bounds().Size.Width; w != 380 { + t.Fatalf("right panel width = %v, want 380", w) + } + if h := app.Find("id:editor-status").Bounds().Size.Height; h != 32 { + t.Fatalf("status bar height = %v, want 32", h) + } + + // Header breadcrumb + unsaved dot (aria-label: "unsaved changes"). + if got := allText(app.Find("id:toolbar-project-name")); got != "Dungeon" { + t.Fatalf("project breadcrumb = %q, want Dungeon", got) + } + if got := strings.TrimSpace(allText(app.Find("id:toolbar-file"))); got != "level_01" { + t.Fatalf("scene breadcrumb = %q, want level_01", got) + } + if app.Exists("id:toolbar-unsaved") { + t.Fatal("unsaved dot visible before edits") + } + app.Post(func() { + if err := ed.MoveObject("knight", 10, 0); err != nil { + t.Error(err) + } + }) + app.Settle() + unsaved := app.Find("id:toolbar-unsaved") + if unsaved.Props.Label != "unsaved changes" { + t.Fatalf("unsaved dot label = %q, want %q", unsaved.Props.Label, "unsaved changes") + } + + // Header tools (Select, Move, Rotate, Scale, Pan), 2D/3D, History, Search ⌘K, Play. + for _, id := range []string{ + "header-tool-group", "tool-select", "tool-move", "tool-rotate", "tool-scale", "tool-pan", + "header-view-mode-group", "view-mode-2d", "view-mode-3d", + "toolbar-history", "toolbar-palette", "toolbar-play", + } { + if !app.Exists("id:" + id) { + t.Fatalf("missing header control %q", id) + } + } + if got := allText(app.Find("id:toolbar-search-shortcut")); got != "⌘K" { + t.Fatalf("search shortcut text = %q, want ⌘K", got) + } + + // Tool radio group switches active tool. + app.Press("id:tool-move") + app.Settle() + if ed.Tool != editor.ToolMove || !app.Find("id:tool-move").Props.Checked { + t.Fatalf("after pressing tool-move: Tool=%v checked=%v", ed.Tool, app.Find("id:tool-move").Props.Checked) + } + app.Press("id:tool-pan") + app.Settle() + if ed.Tool != editor.ToolPan || !app.Find("id:tool-pan").Props.Checked { + t.Fatalf("after pressing tool-pan: Tool=%v checked=%v", ed.Tool, app.Find("id:tool-pan").Props.Checked) + } + app.Press("id:tool-select") + app.Settle() + + // 2D / 3D segmented radio group switches ViewMode. + app.Press("id:view-mode-3d") + app.Settle() + if ed.ViewMode != editor.ViewMode3D || !app.Find("id:view-mode-3d").Props.Checked { + t.Fatalf("after pressing view-mode-3d: ViewMode=%v checked=%v", ed.ViewMode, app.Find("id:view-mode-3d").Props.Checked) + } + app.Press("id:view-mode-2d") + app.Settle() + + // Left rail: SCENE · N nodes, kind tags, NEW badge on proposed object, and FILES section. + if got := allText(app.Find("id:scene-rail-title")); got != "SCENE" { + t.Fatalf("left rail title = %q, want SCENE", got) + } + if got := allText(app.Find("id:scene-rail-node-count")); !strings.Contains(got, "nodes") { + t.Fatalf("left rail node count = %q, want N nodes", got) + } + if !app.Exists("id:scene-tree-new-slime_01") { + t.Fatal("missing NEW tag on proposed object slime_01") + } + if got := allText(app.Find("id:scene-tree-kind-slime_01")); got != "prefab" { + t.Fatalf("slime_01 kind tag = %q, want prefab", got) + } + if got := allText(app.Find("id:scene-tree-kind-door_trigger")); got != "trigger" { + t.Fatalf("door_trigger kind tag = %q, want trigger", got) + } + + if got := allText(app.Find("id:left-rail-files-title")); got != "FILES" { + t.Fatalf("FILES title = %q, want FILES", got) + } + if got := strings.TrimSpace(allText(app.Find("id:rail-file-scene"))); got != "scenes/level_01.scene.yaml" { + t.Fatalf("rail scene file = %q, want scenes/level_01.scene.yaml", got) + } + if got := strings.TrimSpace(allText(app.Find("id:rail-file-prefab-0"))); got != "prefabs/slime.scene.yaml" { + t.Fatalf("rail prefab file = %q, want prefabs/slime.scene.yaml", got) + } + if got := strings.TrimSpace(allText(app.Find("id:rail-file-project"))); got != "game.yaml" { + t.Fatalf("rail project file = %q, want game.yaml", got) + } + + // Viewport camera caption and bottom bar (Zoom out, %, Zoom in, Snap switch, Fit, Overlays N). + if got := allText(app.Find("id:viewport-camera-caption")); got != "Camera · 640 × 360" { + t.Fatalf("viewport camera caption = %q, want %q", got, "Camera · 640 × 360") + } + for _, id := range []string{ + "viewport-zoom-out", "viewport-zoom-label", "viewport-zoom-in", + "viewport-bar-snap", "viewport-bar-fit", "viewport-overlays-button", + } { + if !app.Exists("id:" + id) { + t.Fatalf("missing viewport bottom bar control %q", id) + } + } + snapNode := app.Find("id:viewport-bar-snap") + if snapNode.Props.Role != core.RoleSwitch { + t.Fatalf("viewport-bar-snap role = %v, want RoleSwitch", snapNode.Props.Role) + } + beforeSnap := ed.SnapToGrid + app.Press("id:viewport-bar-snap") + app.Settle() + if ed.SnapToGrid == beforeSnap || app.Find("id:viewport-bar-snap").Props.Checked != ed.SnapToGrid { + t.Fatalf("Snap switch failed to toggle: before=%v after=%v checked=%v", beforeSnap, ed.SnapToGrid, app.Find("id:viewport-bar-snap").Props.Checked) + } + + // Right rail: switch to Agent tab, verify Connected · MCP chip & 380px width; picking a tree row switches back to Inspector. + app.Press("id:right-tab-agent") + app.Settle() + if ed.RightRailTab() != editor.RightTabAgent { + t.Fatalf("after clicking Agent tab: tab = %v, want RightTabAgent", ed.RightRailTab()) + } + if w := app.Find("id:agent-panel").Bounds().Size.Width; w != 380 { + t.Fatalf("agent right rail width = %v, want 380", w) + } + if got := allText(app.Find("id:agent-status-chip")); !strings.Contains(got, "Connected") || !strings.Contains(got, "MCP") { + t.Fatalf("agent status chip = %q, want Connected · MCP", got) + } + app.Press("id:scene-tree-label-knight") + app.Settle() + if ed.RightRailTab() != editor.RightTabInspector { + t.Fatalf("picking tree row did not switch right rail to Inspector: tab = %v", ed.RightRailTab()) + } + if w := app.Find("id:right-rail-inspector-wrap").Bounds().Size.Width; w != 380 { + t.Fatalf("inspector right rail width = %v, want 380", w) + } + + // Status bar: active layer, pointer coordinates, current tool, Problems, Output, Debugger. + app.Post(func() { ed.SetViewportPointer2D(312, 184) }) + app.Settle() + if got := allText(app.Find("id:status-active-layer")); !strings.Contains(got, "actors") { + t.Fatalf("status active layer = %q, want actors", got) + } + if wx, wy, ok := ed.ViewportPointer2DWorld(); !ok { + t.Fatal("ViewportPointer2DWorld() reported ok=false after SetViewportPointer2D") + } else { + wantCoords := fmt.Sprintf("%d, %d", int(math.Round(float64(wx))), int(math.Round(float64(wy)))) + if got := allText(app.Find("id:status-pointer-coords")); got != wantCoords { + t.Fatalf("status pointer coords = %q, want %q", got, wantCoords) + } + } + if got := allText(app.Find("id:editor-status-mode")); got != "Select" { + t.Fatalf("status tool = %q, want Select", got) + } + app.Press("id:status-problems-pill") + app.Settle() + if !ed.ProblemAgentPanelOpen() { + t.Fatal("status-problems-pill did not open Problems panel") + } + app.Press("id:status-output") + app.Settle() + if !ed.OutputPanelOpen() { + t.Fatal("status-output did not open Output panel") + } + app.Press("id:status-debugger") + app.Settle() + if !ed.ProfilerOpen() { + t.Fatal("status-debugger did not open Debugger/Profiler panel") + } +} + +// TestMainLayoutSpecControlsA11yAndHitAreas verifies >=28x28 hit targets, accessible labels, +// radio group arrow navigation, switch semantics, and 5-region F6 traversal (#1007). +func TestMainLayoutSpecControlsA11yAndHitAreas(t *testing.T) { + ed, _ := setupMainLayoutProject(t) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), focusDesktopEnv) + app.Settle() + + controls := []string{ + "toolbar-file", + "tool-select", "tool-move", "tool-rotate", "tool-scale", "tool-pan", + "view-mode-2d", "view-mode-3d", + "toolbar-history", "toolbar-palette", "toolbar-play", + "rail-file-scene", "rail-file-prefab-0", "rail-file-project", + "viewport-zoom-out", "viewport-zoom-in", "viewport-bar-snap", "viewport-bar-fit", "viewport-overlays-button", + "right-tab-agent", "right-tab-inspector", "agent-status-chip", + "status-active-layer", "status-problems-pill", "status-output", "status-debugger", + } + for _, id := range controls { + v := app.Find("id:" + id) + sz := v.Bounds().Size + if sz.Width < 28 || sz.Height < 28 { + t.Errorf("control %q hit area = %.1fx%.1f, want >= 28x28", id, sz.Width, sz.Height) + } + if strings.TrimSpace(v.Props.Label) == "" && strings.TrimSpace(allText(v)) == "" { + t.Errorf("control %q has neither accessible Label nor text", id) + } + } + + // Verify radio groups use RoleRadioGroup / RoleRadio and respond to arrow keys. + if got := app.Find("id:header-tool-group").Props.Role; got != core.RoleRadioGroup { + t.Fatalf("header-tool-group role = %v, want RoleRadioGroup", got) + } + if got := app.Find("id:header-view-mode-group").Props.Role; got != core.RoleRadioGroup { + t.Fatalf("header-view-mode-group role = %v, want RoleRadioGroup", got) + } + if got := app.Find("id:right-rail-tabs").Props.Role; got != core.RoleRadioGroup { + t.Fatalf("right-rail-tabs role = %v, want RoleRadioGroup", got) + } + app.Focus("id:tool-select") + app.Key("right") + app.Settle() + if ed.Tool != editor.ToolMove { + t.Fatalf("Right arrow in tool radio group gave Tool=%v, want ToolMove", ed.Tool) + } + app.Focus("id:view-mode-2d") + app.Key("right") + app.Settle() + if ed.ViewMode != editor.ViewMode3D { + t.Fatalf("Right arrow in 2D/3D radio group gave ViewMode=%v, want ViewMode3D", ed.ViewMode) + } + app.Key("left") + app.Settle() + + // Verify keyboard activation of Snap switch via Space. + beforeSnap := ed.SnapToGrid + app.Focus("id:viewport-bar-snap") + app.Key("space") + app.Settle() + if ed.SnapToGrid == beforeSnap { + t.Fatalf("Space on focused viewport-bar-snap did not toggle SnapToGrid (stayed %v)", beforeSnap) + } + + // Verify F6 cycles through all 5 main regions (Header, Scene tree, Viewport, Agent/Inspector, Status bar). + wantRegions := []editor.EditorRegion{ + editor.RegionHeader, + editor.RegionSceneTree, + editor.RegionViewport, + editor.RegionInspector, + editor.RegionStatusBar, + } + seen := make(map[editor.EditorRegion]bool) + for i := 0; i < 6; i++ { + app.Key("f6") + app.Settle() + if r := ed.ActiveRegion(); r != "" { + seen[r] = true + } + } + for _, r := range wantRegions { + if !seen[r] { + t.Errorf("F6 did not visit region %q (visited: %+v)", r, seen) + } + } +} + +// TestMainLayoutLegacyPanelsRemainReachable verifies every view previously opened by the +// legacy toolbar remains reachable via Command Palette / Status bar / Settings (#1007). +func TestMainLayoutLegacyPanelsRemainReachable(t *testing.T) { + ed, _ := setupMainLayoutProject(t) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), focusDesktopEnv) + app.Settle() + + ed.SelectObject("knight") + cases := []struct { + name string + cmdID string + check func() bool + close func() + }{ + {"Project Settings", editor.CmdProjectSettings, ed.ProjectSettingsOpen, func() { ed.SetProjectSettingsOpen(false) }}, + {"Editor Settings", editor.CmdEditorSettings, ed.EditorSettingsOpen, func() { ed.SetEditorSettingsOpen(false) }}, + {"Audio Mixer", editor.CmdAudioMixer, ed.AudioMixerOpen, func() { ed.SetAudioMixerOpen(false) }}, + {"Input Map", editor.CmdInputMap, ed.InputMapOpen, func() { ed.SetInputMapOpen(false) }}, + {"Strings / Localization", editor.CmdLocalization, ed.LocalizationOpen, func() { _ = ed.ExecuteCommand(editor.CmdLocalization) }}, + {"Export", editor.CmdExport, ed.ExportPanelOpen, func() { ed.SetExportPanelOpen(false) }}, + {"Data Table", editor.CmdDataTable, func() bool { return ed.DataTable() != nil }, func() { _ = ed.ExecuteCommand(editor.CmdDataTable) }}, + {"Project Search", editor.CmdSearchPanel, ed.SearchOpen, func() { ed.SetSearchOpen(false) }}, + {"Output", editor.CmdOutputPanel, ed.OutputPanelOpen, func() { ed.SetOutputPanelOpen(false) }}, + {"Problems", editor.CmdProblemsPanel, ed.ProblemAgentPanelOpen, func() { ed.SetProblemAgentPanelOpen(false) }}, + {"Debugger / Profiler", editor.CmdProfiler, ed.ProfilerOpen, func() { ed.SetProfilerOpen(false) }}, + {"Layers", editor.CmdLayersPanel, ed.LayersPanelOpen, func() { ed.SetLayersPanelOpen(false) }}, + {"Files Browser", editor.CmdFileBrowser, ed.FileBrowserOpen, func() { ed.SetFileBrowserOpen(false) }}, + {"Asset Browser", editor.CmdAssetBrowser, ed.AssetBrowserOpen, func() { ed.SetAssetBrowserOpen(false) }}, + {"Particles", editor.CmdParticleEditor, ed.ParticleEmitterOpen, func() { _ = ed.ExecuteCommand(editor.CmdParticleEditor) }}, + {"Material", editor.CmdMaterialEditor, ed.MaterialOpen, func() { _ = ed.ExecuteCommand(editor.CmdMaterialEditor) }}, + {"HUD Layout", editor.CmdHUDLayout, ed.HUDLayoutOpen, func() { _ = ed.ExecuteCommand(editor.CmdHUDLayout) }}, + {"Terrain", editor.CmdTerrainEditor, ed.TerrainOpen, func() { _ = ed.ExecuteCommand(editor.CmdTerrainEditor) }}, + {"NavMesh", editor.CmdNavMeshPanel, ed.NavMeshPanelOpen, func() { ed.SetNavMeshPanelOpen(false) }}, + {"History", editor.CmdHistoryPanel, ed.HistoryPanelOpen, func() { ed.SetHistoryPanelOpen(false) }}, + {"Animate", editor.CmdAnimate, func() bool { return ed.Clip() != nil }, func() { ed.CloseClip() }}, + } + + for _, tc := range cases { + runEditorCommand(t, app, ed, tc.cmdID) + if !tc.check() { + t.Errorf("%s (%s) did not open", tc.name, tc.cmdID) + } + app.Post(tc.close) + app.Settle() + } + + // Library command is registered in the Command Palette and toggles when a Library client is configured. + foundLib := false + for _, cmd := range ed.Commands() { + if cmd.ID == editor.CmdLibraryPanel { + foundLib = true + break + } + } + if !foundLib { + t.Fatal("CmdLibraryPanel missing from Command Palette registry") + } +} + +// TestMainLayoutEmptyLoadingAndErrorStates verifies empty (no project, no scene), loading, +// and scene-open error states across regions, including opening a missing scene and a +// malformed YAML scene (matching open_errors_test.go) and recovering via Retry (#1007). +func TestMainLayoutEmptyLoadingAndErrorStates(t *testing.T) { + // 1. No project open -> designed empty state across regions. + ed, err := editor.New(nil, testResolver()) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + t.Cleanup(func() { _ = ed.Close() }) + ed.SetRightRailTab(editor.RightTabInspector) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), focusDesktopEnv) + app.Settle() + + if ed.WorkspaceState() != editor.WorkspaceNoProject { + t.Fatalf("WorkspaceState = %v, want WorkspaceNoProject", ed.WorkspaceState()) + } + for _, id := range []string{"viewport-empty-no-project", "left-rail-empty-no-project", "inspector-empty-no-project"} { + if !app.Exists("id:" + id) { + t.Fatalf("NoProject state missing %q", id) + } + } + + // 2. Project loading -> designed loading state across regions. + app.Post(func() { ed.SetProjectLoading(true, "/tmp/demo/game.yaml") }) + app.Settle() + if ed.WorkspaceState() != editor.WorkspaceLoading { + t.Fatalf("WorkspaceState = %v, want WorkspaceLoading", ed.WorkspaceState()) + } + for _, id := range []string{"viewport-loading-state", "left-rail-loading", "inspector-loading-state"} { + if !app.Exists("id:" + id) { + t.Fatalf("Loading state missing %q", id) + } + } + app.Post(func() { ed.SetProjectLoading(false, "") }) + app.Settle() + + // 3. Bare project with no scene -> designed no-scene empty state across regions. + bareDir := writeBareProject(t, "BareProj") + app.Post(func() { + if err := ed.OpenProject(bareDir); err != nil { + t.Error(err) + } + ed.SetRightRailTab(editor.RightTabInspector) + }) + app.Settle() + if ed.WorkspaceState() != editor.WorkspaceNoScene { + t.Fatalf("WorkspaceState = %v, want WorkspaceNoScene", ed.WorkspaceState()) + } + for _, id := range []string{"viewport-empty-no-scene", "left-rail-empty-no-scene", "inspector-empty-no-scene"} { + if !app.Exists("id:" + id) { + t.Fatalf("NoScene state missing %q", id) + } + } + + // 4. Open a missing scene -> designed RoleAlert error state (not a blank viewport). + missingPath := filepath.Join(bareDir, "scenes", "missing.scene.yaml") + var openErr error + app.Post(func() { + openErr = ed.OpenFile(missingPath) + }) + app.Settle() + if openErr == nil { + t.Fatal("expected error opening missing scene") + } + if ed.WorkspaceState() != editor.WorkspaceSceneError { + t.Fatalf("WorkspaceState after missing scene = %v, want WorkspaceSceneError", ed.WorkspaceState()) + } + errCard := app.Find("id:viewport-error-state") + if errCard.Props.Role != core.RoleAlert { + t.Fatalf("viewport-error-state role = %v, want RoleAlert", errCard.Props.Role) + } + if got := allText(app.Find("id:viewport-error-path")); !strings.Contains(got, "missing.scene.yaml") { + t.Fatalf("viewport-error-path = %q, want missing.scene.yaml", got) + } + if !app.Exists("id:viewport-error-message") || !app.Exists("id:viewport-error-fix") || !app.Exists("id:left-rail-scene-error") || !app.Exists("id:inspector-error-state") { + t.Fatal("missing designed error-state details across regions") + } + + // 5. Open a malformed YAML scene (open_errors_test.go case) -> path:line shown, Retry recovers once fixed. + badPath := filepath.Join(bareDir, "scenes", "cave.scene.yaml") + if err := os.MkdirAll(filepath.Dir(badPath), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(badPath, []byte("version: 1\nlayers:\n - name: bg\n space: isometric\n"), 0o644); err != nil { + t.Fatal(err) + } + app.Post(func() { + openErr = ed.OpenFile(badPath) + }) + app.Settle() + if openErr == nil { + t.Fatal("expected error opening malformed scene") + } + if got := allText(app.Find("id:viewport-error-path")); !strings.Contains(got, "cave.scene.yaml:4") { + t.Fatalf("malformed scene error path = %q, want cave.scene.yaml:4", got) + } + + // Fix the file and click Retry -> returns to WorkspaceReady and clears the error card. + if err := os.WriteFile(badPath, []byte("version: 1\nlayers:\n - name: bg\n space: world\n"), 0o644); err != nil { + t.Fatal(err) + } + app.Press("id:viewport-error-retry") + app.Settle() + if ed.WorkspaceState() != editor.WorkspaceReady { + t.Fatalf("after Retry on fixed scene: WorkspaceState = %v, want WorkspaceReady", ed.WorkspaceState()) + } + if app.Exists("id:viewport-error-state") { + t.Fatal("error card remained visible after successful Retry") + } + + // Dismissing an error state also clears it cleanly. + app.Post(func() { _ = ed.OpenScene("scenes/does_not_exist.scene.yaml") }) + app.Settle() + if !app.Exists("id:viewport-error-state") { + t.Fatal("expected error state after OpenScene on missing project scene") + } + app.Press("id:viewport-error-dismiss") + app.Settle() + if app.Exists("id:viewport-error-state") || ed.SceneOpenError() != nil { + t.Fatal("Dismiss did not clear scene-open error state") + } +} diff --git a/packages/game/editor/main_layout_test_helpers_test.go b/packages/game/editor/main_layout_test_helpers_test.go new file mode 100644 index 000000000..c1bbff19b --- /dev/null +++ b/packages/game/editor/main_layout_test_helpers_test.go @@ -0,0 +1,51 @@ +package editor_test + +import ( + "testing" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func runEditorCommand(t *testing.T, app *nsgotest.App, ed *editor.Editor, cmdID string) { + t.Helper() + var err error + app.Post(func() { + err = ed.ExecuteCommand(cmdID) + }) + app.Settle() + if err != nil { + t.Fatalf("ExecuteCommand(%q): %v", cmdID, err) + } +} + +func undoInUI(app *nsgotest.App, ed *editor.Editor) { + app.Post(func() { ed.Undo() }) + app.Settle() +} + +func redoInUI(app *nsgotest.App, ed *editor.Editor) { + app.Post(func() { ed.Redo() }) + app.Settle() +} + +func saveInUI(app *nsgotest.App, ed *editor.Editor) { + app.Press("id:toolbar-file") + app.Press("id:toolbar-menu-save") + app.Settle() +} + +func openFileBrowserInUI(app *nsgotest.App, ed *editor.Editor) { + app.Post(func() { ed.SetFileBrowserOpen(true) }) + app.Settle() +} + +func openAssetBrowserInUI(app *nsgotest.App, ed *editor.Editor) { + app.Post(func() { ed.SetAssetBrowserOpen(true) }) + app.Settle() +} + +func openLayersPanelInUI(app *nsgotest.App, ed *editor.Editor) { + app.Post(func() { ed.SetLayersPanelOpen(true) }) + app.Settle() +} diff --git a/packages/game/editor/main_layout_ui.go b/packages/game/editor/main_layout_ui.go new file mode 100644 index 000000000..bad5cd058 --- /dev/null +++ b/packages/game/editor/main_layout_ui.go @@ -0,0 +1,2484 @@ +package editor + +import ( + "errors" + "fmt" + "math" + "path" + "path/filepath" + "slices" + "strings" + + "github.com/nsgo-dev/game/packages/game/l10n" + "github.com/nsgo-dev/game/packages/game/loaderr" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/base" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/icons/lucide" + "github.com/nsgo-dev/nsgo/ui" +) + +// WorkspaceState classifies the high-level state of the main editor workspace +// so every region (header, left rail, viewport, right panel, status bar) can +// render a designed empty, loading, error, or active editing state. +type WorkspaceState uint8 + +const ( + // WorkspaceReady means an editable scene is open and ready. + WorkspaceReady WorkspaceState = iota + // WorkspaceNoProject means no project and no real scene have been opened yet. + WorkspaceNoProject + // WorkspaceNoScene means a project is open, but no scene is currently open. + WorkspaceNoScene + // WorkspaceLoading means a project is currently being loaded. + WorkspaceLoading + // WorkspaceSceneError means opening a scene failed (missing file, malformed YAML, etc.). + WorkspaceSceneError +) + +// SceneOpenError captures the structured details of a failed scene open +// (covering missing files and YAML/schema errors from open_errors_test.go). +type SceneOpenError struct { + Path string + Line int + Column int + Message string + Fix string + Err error +} + +// Inline Lucide stroke icons (1.8 px stroke at 15 px, currentColor, decorative / aria-hidden in core.Icon). +var ( + mainIconBrandMark = core.MustParseSVG([]byte(``)) + mainIconSelect = core.MustParseSVG([]byte(``)) + mainIconMove = core.MustParseSVG([]byte(``)) + mainIconRotate = core.MustParseSVG([]byte(``)) + mainIconScale = core.MustParseSVG([]byte(``)) + mainIconPan = core.MustParseSVG([]byte(``)) + mainIconHistory = core.MustParseSVG([]byte(``)) + mainIconSearch = core.MustParseSVG([]byte(``)) + mainIconPlay = core.MustParseSVG([]byte(``)) + mainIconStop = core.MustParseSVG([]byte(``)) +) + +func (e *Editor) recordSceneOpenError(filePath string, err error) { + if e == nil || err == nil { + return + } + se := &SceneOpenError{ + Path: filePath, + Message: err.Error(), + Err: err, + } + var le *loaderr.Error + if errors.As(err, &le) && le != nil { + if le.File != "" { + se.Path = le.File + } + se.Line = le.Line + se.Column = le.Column + if le.Problem != "" { + se.Message = le.Problem + } + se.Fix = le.Fix + } + if se.Fix == "" { + se.Fix = "Check that the scene file exists and contains valid YAML." + } + e.sceneOpenErr = se + e.Status = "Failed to open " + filepath.Base(se.Path) + e.notify() +} + +// SceneOpenError returns a copy of the active scene-open error state, or nil when none. +func (e *Editor) SceneOpenError() *SceneOpenError { + if e == nil || e.sceneOpenErr == nil { + return nil + } + cp := *e.sceneOpenErr + return &cp +} + +// ClearSceneOpenError dismisses the active scene-open error state. +func (e *Editor) ClearSceneOpenError() { + if e == nil || e.sceneOpenErr == nil { + return + } + e.sceneOpenErr = nil + e.notify() +} + +// RetryOpenScene retries opening the scene recorded in SceneOpenError. +func (e *Editor) RetryOpenScene() error { + if e == nil || e.sceneOpenErr == nil { + return nil + } + p := e.sceneOpenErr.Path + if p == "" { + e.ClearSceneOpenError() + return nil + } + if e.Project != nil && e.ProjectPath != "" && !filepath.IsAbs(p) { + return e.OpenScene(p) + } + return e.OpenFile(p) +} + +// ProjectLoading reports whether the editor is currently loading a project. +func (e *Editor) ProjectLoading() bool { + return e != nil && e.projectLoading +} + +// ProjectLoadingPath returns the project path currently being loaded, if any. +func (e *Editor) ProjectLoadingPath() string { + if e == nil { + return "" + } + return e.projectLoadingPath +} + +// SetProjectLoading sets the project-loading state so every region displays its designed loading state. +func (e *Editor) SetProjectLoading(loading bool, projectPath string) { + if e == nil { + return + } + if !loading { + projectPath = "" + } + if e.projectLoading == loading && e.projectLoadingPath == projectPath { + return + } + e.projectLoading = loading + e.projectLoadingPath = projectPath + e.notify() +} + +func (e *Editor) isActiveTabPlaceholder() bool { + if e == nil { + return false + } + if e.activeTab >= 0 && e.activeTab < len(e.tabs) { + return e.tabs[e.activeTab].placeholder + } + return false +} + +// WorkspaceState returns the active high-level state of the editor workspace. +func (e *Editor) WorkspaceState() WorkspaceState { + if e == nil { + return WorkspaceNoProject + } + if e.projectLoading { + return WorkspaceLoading + } + if e.sceneOpenErr != nil { + return WorkspaceSceneError + } + if e.isActiveTabPlaceholder() && e.FilePath == "" && e.ScenePath == "" && !e.SceneDirty() && e.Doc != nil && len(e.Doc.Layers) == 1 && len(e.Doc.Layers[0].Objects) == 0 { + if e.Project != nil && e.ProjectPath != "" { + return WorkspaceNoScene + } + return WorkspaceNoProject + } + if e.Doc == nil { + if e.Project != nil && e.ProjectPath != "" { + return WorkspaceNoScene + } + return WorkspaceNoProject + } + return WorkspaceReady +} + +// workspaceStateKey returns a digest of WorkspaceState plus loading/error details so +// reactive memos re-render when one scene-open error is replaced by another. +func (e *Editor) workspaceStateKey() string { + ws := e.WorkspaceState() + switch ws { + case WorkspaceLoading: + return fmt.Sprintf("loading|%s", e.projectLoadingPath) + case WorkspaceSceneError: + if se := e.sceneOpenErr; se != nil { + return fmt.Sprintf("error|%s|%d|%d|%s|%s", se.Path, se.Line, se.Column, se.Message, se.Fix) + } + return "error|" + default: + return fmt.Sprintf("state|%d", ws) + } +} + +// LayersPanelOpen reports whether the docked Layers panel is open. +func (e *Editor) LayersPanelOpen() bool { return e != nil && e.layersPanelOpen } + +// SetLayersPanelOpen opens or closes the docked Layers panel. +func (e *Editor) SetLayersPanelOpen(open bool) { + if e == nil || e.layersPanelOpen == open { + return + } + e.layersPanelOpen = open + e.notify() +} + +// FileBrowserOpen reports whether the full Project Files browser panel is open. +func (e *Editor) FileBrowserOpen() bool { return e != nil && e.fileBrowserOpen } + +// SetFileBrowserOpen opens or closes the full Project Files browser panel. +func (e *Editor) SetFileBrowserOpen(open bool) { + if e == nil || e.fileBrowserOpen == open { + return + } + e.fileBrowserOpen = open + e.notify() +} + +// AssetBrowserOpen reports whether the Asset Browser panel is open. +func (e *Editor) AssetBrowserOpen() bool { return e != nil && e.assetBrowserOpen } + +// SetAssetBrowserOpen opens or closes the Asset Browser panel. +func (e *Editor) SetAssetBrowserOpen(open bool) { + if e == nil || e.assetBrowserOpen == open { + return + } + e.assetBrowserOpen = open + e.notify() +} + +// LibraryPanelOpen reports whether the Asset Pack Library panel is open. +func (e *Editor) LibraryPanelOpen() bool { return e != nil && e.libraryPanelOpen } + +// SetLibraryPanelOpen opens or closes the Asset Pack Library panel. +func (e *Editor) SetLibraryPanelOpen(open bool) { + if e == nil || e.libraryPanelOpen == open { + return + } + e.libraryPanelOpen = open + e.notify() +} + +// ProjectDisplayName returns the human-readable project name for the header breadcrumb. +func (e *Editor) ProjectDisplayName() string { + if e == nil { + return "" + } + if e.Project != nil { + if name := strings.TrimSpace(e.Project.Name); name != "" { + return name + } + } + if e.ProjectPath != "" { + dir := filepath.Dir(e.ProjectPath) + if base := filepath.Base(dir); base != "" && base != "." && base != string(filepath.Separator) { + return base + } + } + return "" +} + +// SceneBreadcrumbName returns a concise scene label for the header breadcrumb. +func (e *Editor) SceneBreadcrumbName() string { + if e == nil { + return "" + } + if e.projectLoading { + return e.T("workspace.loadingShort") + } + if e.sceneOpenErr != nil && e.sceneOpenErr.Path != "" { + return stripSceneExt(filepath.Base(e.sceneOpenErr.Path)) + } + if e.WorkspaceState() == WorkspaceNoScene { + return e.T("workspace.noSceneTitle") + } + if e.ScenePath != "" { + return stripSceneExt(path.Base(e.ScenePath)) + } + if e.FilePath != "" { + return stripSceneExt(filepath.Base(e.FilePath)) + } + if e.Doc != nil && strings.TrimSpace(e.Doc.Name) != "" { + return strings.TrimSpace(e.Doc.Name) + } + return e.T("scene.untitledScene") +} + +func stripSceneExt(base string) string { + for _, suf := range []string{".scene.yaml", ".scene.yml", ".yaml", ".yml"} { + if strings.HasSuffix(base, suf) && len(base) > len(suf) { + return strings.TrimSuffix(base, suf) + } + } + return base +} + +// SceneNodeCount returns the total number of nodes (layers + all nested objects) in the open scene. +func (e *Editor) SceneNodeCount() int { + if e == nil { + return 0 + } + doc := e.resolvedDoc() + if doc == nil { + return 0 + } + total := 0 + var countObjs func(objs []sceneformat.ObjectDoc) + countObjs = func(objs []sceneformat.ObjectDoc) { + for i := range objs { + total++ + countObjs(objs[i].Children) + } + } + for i := range doc.Layers { + total++ + countObjs(doc.Layers[i].Objects) + } + return total +} + +// SceneUsedPrefabs returns the sorted, deduplicated project-relative paths of +// prefabs and instanced scenes referenced by objects in the open scene. +func (e *Editor) SceneUsedPrefabs() []string { + if e == nil { + return nil + } + doc := e.resolvedDoc() + if doc == nil { + return nil + } + seen := make(map[string]struct{}) + var out []string + var walk func(objs []sceneformat.ObjectDoc) + walk = func(objs []sceneformat.ObjectDoc) { + for i := range objs { + o := &objs[i] + for _, raw := range []string{o.Prefab, o.Scene} { + if p := strings.TrimSpace(raw); p != "" { + if _, ok := seen[p]; !ok { + seen[p] = struct{}{} + out = append(out, p) + } + } + } + walk(o.Children) + } + } + for i := range doc.Layers { + walk(doc.Layers[i].Objects) + } + slices.Sort(out) + return out +} + +// SetProposedNewObjectIDs marks object IDs proposed by a pending review so the scene rail displays a NEW tag. +func (e *Editor) SetProposedNewObjectIDs(ids []string) { + if e == nil { + return + } + if len(ids) == 0 { + if len(e.proposedNewObjects) == 0 { + return + } + e.proposedNewObjects = nil + e.notify() + return + } + m := make(map[string]bool, len(ids)) + for _, id := range ids { + if id != "" { + m[id] = true + } + } + e.proposedNewObjects = m + e.notify() +} + +// IsObjectProposedNew reports whether object id is proposed as a new object by a pending review. +func (e *Editor) IsObjectProposedNew(id string) bool { + if e == nil || id == "" { + return false + } + if e.proposedNewObjects[id] { + return true + } + if e.agentReview.open { + for _, c := range e.agentReview.changes { + if c.Kind != ReviewChangeAdded || c.Reverted || c.Kept { + continue + } + if c.ObjectID == id || c.ID == id || c.Title == id { + return true + } + } + } + return false +} + +// SceneRailObjectKind returns the concise Spec kind tag for an object row in the scene rail +// (e.g. "prefab", "sprite", "trigger", "group", "mesh", "light", "camera", "node"). +func (e *Editor) SceneRailObjectKind(id string) string { + if e == nil { + return "node" + } + obj, _ := e.FindResolvedObject(id) + if obj == nil { + return "node" + } + if obj.Prefab != "" || obj.Scene != "" { + return "prefab" + } + if obj.Camera != nil { + return "camera" + } + if obj.Light != nil { + return "light" + } + if obj.Model != "" || obj.Mesh != "" { + return "mesh" + } + if len(obj.Children) > 0 && obj.Sprite == nil { + return "group" + } + for name := range obj.Components { + switch strings.ToLower(name) { + case "trigger", "trigger2d", "trigger3d": + return "trigger" + case "light", "light2d", "light3d": + return "light" + case "camera", "camera2d", "camera3d": + return "camera" + } + } + if obj.Sprite != nil { + return "sprite" + } + return "node" +} + +// LayerKindLabel returns the concise Spec kind tag for a layer row in the scene rail +// ("tiles", "screen", or "layer"). +func (e *Editor) LayerKindLabel(layerName string) string { + if e == nil { + return "layer" + } + doc := e.resolvedDoc() + if doc == nil { + return "layer" + } + for i := range doc.Layers { + l := &doc.Layers[i] + if l.Name != layerName { + continue + } + if l.Tilemap != nil { + return "tiles" + } + if l.EffectiveSpace() == sceneformat.SpaceScreen { + return "screen" + } + return "layer" + } + return "layer" +} + +// ObjectKindColor maps an object's kind or pending-new state to a SpecPalette token color. +func (e *Editor) ObjectKindColor(p SpecPalette, id string) core.Color { + if e.IsObjectProposedNew(id) { + return p.Added.Fg + } + switch e.SceneRailObjectKind(id) { + case "prefab": + return p.Accent.Fg + case "sprite": + return p.Changed.Fg + case "trigger": + return p.Warning.Fg + case "group": + return p.Agent.Fg + case "mesh", "light", "camera": + return p.Accent.Fg + default: + return p.TextFaint + } +} + +// LayerKindColor maps a layer's kind to a SpecPalette token color. +func (e *Editor) LayerKindColor(p SpecPalette, layerName string) core.Color { + switch e.LayerKindLabel(layerName) { + case "tiles": + return p.Accent.Fg + default: + return p.TextFaint + } +} + +func (e *Editor) activeHeaderTool() Tool { + if e == nil { + return ToolSelect + } + if e.ViewMode == ViewMode3D { + if e.Tool == ToolPan { + return ToolPan + } + if e.Tool == ToolSelect { + return ToolSelect + } + switch e.GizmoMode { + case Gizmo3DRotate: + return ToolRotate + case Gizmo3DScale: + return ToolScale + default: + return ToolMove + } + } + return e.Tool +} + +// mainHeaderView renders the 44 px AI-first header matching docs/design/editor/Main.dc.html +// and docs/design/editor/Spec.dc.html. +func mainHeaderView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], dirty *core.Memo[unsavedState], mode *core.Signal[pathMode], target *core.Signal[string]) core.Node { + p := ed.SpecPalette(cx) + notPlaying := func() bool { + _ = rev.Get() + return ed.Playing() + } + noProject := func() bool { + _ = rev.Get() + return ed.Playing() || ed.Project == nil || ed.ProjectPath == "" + } + + fileBtnRef := &core.Ref{} + selectToolRef := &core.Ref{} + historyBtnRef := &core.Ref{} + paletteBtnRef := &core.Ref{} + playBtnRef := &core.Ref{} + if ed.focus.ctrl != nil { + ed.focus.ctrl.registerCandidate(cx, RegionHeader, fileBtnRef, nil) + ed.focus.ctrl.registerCandidate(cx, RegionHeader, selectToolRef, func() bool { return !ed.Playing() }) + ed.focus.ctrl.registerCandidate(cx, RegionHeader, historyBtnRef, func() bool { return !ed.Playing() }) + ed.focus.ctrl.registerCandidate(cx, RegionHeader, paletteBtnRef, nil) + ed.focus.ctrl.registerCandidate(cx, RegionHeader, playBtnRef, nil) + } + + shortcutTip := func(name, cmdID string) string { + if sc := ed.EffectiveShortcut(cmdID); sc != "" { + return specShortcutTip(name, FormatShortcut(sc, cx.Env().OS())) + } + return name + } + + type headerToolDef struct { + testID string + cmdID string + label string + tool Tool + svg *core.SVG + ref *core.Ref + } + toolDefs := []headerToolDef{ + {testID: "tool-select", cmdID: CmdToolSelect, label: ed.T("toolbar.select"), tool: ToolSelect, svg: mainIconSelect, ref: selectToolRef}, + {testID: "tool-move", cmdID: CmdToolMove, label: ed.T("toolbar.move"), tool: ToolMove, svg: mainIconMove}, + {testID: "tool-rotate", cmdID: CmdToolRotate, label: ed.T("toolbar.rotate"), tool: ToolRotate, svg: mainIconRotate}, + {testID: "tool-scale", cmdID: CmdToolScale, label: ed.T("toolbar.scale"), tool: ToolScale, svg: mainIconScale}, + {testID: "tool-pan", cmdID: CmdToolPan, label: ed.T("toolbar.pan"), tool: ToolPan, svg: mainIconPan}, + } + + toolRadios := make([]core.Node, 0, len(toolDefs)) + for _, td := range toolDefs { + d := td + toolRadios = append(toolRadios, base.Radio{ + Ref: d.ref, + TestID: d.testID, + Label: d.label, + Disabled: notPlaying, + Tooltip: specTooltipNode(p, shortcutTip(d.label, d.cmdID)), + Checked: func() bool { + _ = rev.Get() + return ed.activeHeaderTool() == d.tool + }, + OnChange: func(checked bool) { + if !checked { + return + } + ed.SetTool(d.tool) + }, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + bg := core.Transparent + if ed.activeHeaderTool() == d.tool { + bg = cur.LineRaised + } + return core.Style{ + Width: core.Pt(32), + Height: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + CornerRadius: specRadiusControl, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Background: bg, + Cursor: core.CursorPointer, + Hover: &core.Style{Background: cur.LineRaised}, + Disabled: &core.Style{Opacity: core.Alpha(0.45), Cursor: core.CursorDefault}, + FocusVisible: cur.FocusRing(2), + } + }, + Children: []core.Node{ + core.Icon{ + SVG: d.svg, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + col := cur.TextFaint + if ed.activeHeaderTool() == d.tool { + col = cur.TextPrimary + } + return core.Style{ + Width: core.Pt(specIconSize), + Height: core.Pt(specIconSize), + Color: col, + FlexShrink: 0, + } + }, + }, + }, + }) + } + + viewModeRadio := func(testID, label string, vm ViewMode) core.Node { + return base.Radio{ + TestID: testID, + Label: label, + Checked: func() bool { + _ = rev.Get() + return ed.ViewMode == vm + }, + OnChange: func(checked bool) { + if checked { + ed.SetViewMode(vm) + } + }, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + bg := core.Transparent + if ed.ViewMode == vm { + bg = cur.LineRaised + } + return core.Style{ + Height: core.Pt(specRowHeight), + MinWidth: core.Pt(32), + MinHeight: core.Pt(specRowHeight), + Padding: core.Symmetric(0, specSpace12), + CornerRadius: specRadiusControl, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Background: bg, + Cursor: core.CursorPointer, + Hover: &core.Style{Background: cur.LineRaised}, + FocusVisible: cur.FocusRing(2), + } + }, + Children: []core.Node{ + core.Text{ + Content: label, + MaxLines: 1, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + col := cur.TextFaint + if ed.ViewMode == vm { + col = cur.TextPrimary + } + return core.Style{ + FontSize: 12.5, + FontWeight: core.FontWeightMedium, + Color: col, + } + }, + }, + }, + } + } + + headerBaseStyle := core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(specHeaderHeight), + FlexShrink: 0, + Gap: specSpace12, + Padding: core.Symmetric(0, specSpace12), + Background: p.Bg, + Borders: core.Edges{Bottom: 1}, + BorderColor: p.Line, + } + + return core.View{ + Ref: ed.focus.ctrl.rootRef(RegionHeader), + TestID: "editor-toolbar", + Role: core.RoleRegion, + Label: ed.T("region.header"), + Focusable: func() bool { + return ed.focus.ctrl != nil && ed.focus.ctrl.fallbackRegion.Get() == RegionHeader + }, + OnFocusIn: func() { + if ed.focus.ctrl != nil { + ed.focus.ctrl.onRegionFocusIn(RegionHeader) + } + }, + OnFocusOut: func() { + if ed.focus.ctrl != nil { + ed.focus.ctrl.onRegionFocusOut(RegionHeader) + } + }, + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + st := headerBaseStyle + st.Background = cur.Bg + st.BorderColor = cur.Line + if ed.focus.ctrl == nil { + return st + } + return ed.focus.ctrl.regionOutlineStyle(RegionHeader, st) + }, + Children: []core.Node{ + // Left: brand mark + project / scene breadcrumb (with File menu) + unsaved dot. + core.View{ + TestID: "header-breadcrumb", + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: specSpace8, + FlexShrink: 1, + MinWidth: core.Pt(0), + }, + Children: []core.Node{ + core.View{ + TestID: "header-brand-mark", + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + return core.Style{ + Width: core.Pt(22), + Height: core.Pt(22), + CornerRadius: specRadiusControl, + Background: cur.Accent.Fg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + } + }, + Children: []core.Node{ + core.Icon{ + SVG: mainIconBrandMark, + StyleFunc: func() core.Style { + return core.Style{ + Width: core.Pt(12), + Height: core.Pt(12), + Color: ed.SpecPalette(cx).Accent.OnFill, + } + }, + }, + }, + }, + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.ProjectDisplayName() != "" + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: specSpace8, + FlexShrink: 1, + MinWidth: core.Pt(0), + }, + Children: []core.Node{ + core.Text{ + TestID: "toolbar-project-name", + ContentFunc: func() string { + _ = rev.Get() + return ed.ProjectDisplayName() + }, + MaxLines: 1, + EllipsizeMode: core.EllipsizeTail, + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 12.5, + FontWeight: core.FontWeightSemibold, + Color: ed.SpecPalette(cx).TextPrimary, + } + }, + }, + core.Text{ + Content: "/", + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 12.5, + Color: ed.SpecPalette(cx).TextFaint, + } + }, + }, + }, + } + }, + }, + ui.Menu{ + TestID: "toolbar-file", + Label: ed.T("toolbar.fileMenuLabel"), + Trigger: ui.Button{ + Ref: fileBtnRef, + Label: ed.T("toolbar.fileMenuLabel"), + TextFunc: func() string { + _ = rev.Get() + return ed.SceneBreadcrumbName() + }, + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + TextStyle: core.Style{ + FontSize: 12.5, + Color: p.TextMuted, + }, + Style: core.Style{ + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), + Padding: core.Symmetric(0, specSpace8), + CornerRadius: specRadiusControl, + MaxWidth: core.Pt(220), + FocusVisible: p.FocusRing(2), + }, + }, + Children: []core.Node{ + ui.MenuItem{ + TestID: "toolbar-new", + Text: ed.T("toolbar.newScene"), + Disabled: noProject, + OnSelect: func() { + dir := "scenes" + if ed.ScenePath != "" { + dir = path.Dir(ed.ScenePath) + } + target.Set(path.Join(dir, "new.scene.yaml")) + mode.Set(pathNewScene) + }, + }, + ui.MenuItem{ + TestID: "toolbar-menu-save", + Text: ed.T("toolbar.save"), + Shortcut: FormatShortcut(ed.EffectiveShortcut(CmdSave), cx.Env().OS()), + Disabled: notPlaying, + OnSelect: func() { ed.saveFromUI() }, + }, + ui.MenuItem{ + TestID: "toolbar-save-as", + Text: ed.T("toolbar.saveAs"), + Disabled: noProject, + OnSelect: func() { + sp := ed.ScenePath + if sp == "" { + sp = "scenes/untitled.scene.yaml" + } + target.Set(sp) + mode.Set(pathSaveAs) + }, + }, + ui.MenuItem{ + TestID: "toolbar-revert", + Text: ed.T("toolbar.revert"), + Disabled: func() bool { + _ = rev.Get() + return ed.Playing() || ed.FilePath == "" || !dirty.Get().scene + }, + OnSelect: func() { ed.report(ed.RevertScene()) }, + }, + ui.MenuSeparator{}, + ui.MenuItem{ + TestID: "toolbar-open-instanced-scene", + Text: ed.T("menu.openInstancedScene"), + Disabled: func() bool { + return noProject() || !ed.selectedObjectInstancesScene() + }, + OnSelect: func() { ed.report(ed.OpenInstancedScene(ed.SelectedID)) }, + }, + ui.MenuItem{ + TestID: "toolbar-open-base-scene", + Text: ed.T("menu.openBaseScene"), + Disabled: func() bool { + return noProject() || ed.Doc == nil || ed.Doc.Inherits == "" + }, + OnSelect: func() { ed.report(ed.OpenBaseScene()) }, + }, + ui.MenuSeparator{}, + ui.MenuItem{ + TestID: "toolbar-menu-settings", + Text: ed.T("settings.title"), + Shortcut: FormatShortcut(ed.EffectiveShortcut(CmdProjectSettings), cx.Env().OS()), + Disabled: notPlaying, + OnSelect: func() { + if ed.Project != nil { + ed.SetProjectSettingsOpen(true) + } else { + ed.ToggleEditorSettings() + } + }, + }, + ui.MenuItem{ + TestID: "toolbar-close-tab", + Text: ed.T("toolbar.closeTab"), + Disabled: notPlaying, + OnSelect: func() { ed.report(ed.RequestCloseTab(ed.ActiveTab())) }, + }, + }, + }, + core.View{ + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.Show{ + When: func() bool { + _ = rev.Get() + return dirty.Get().either() || ed.SaveFailed() + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + TestID: "toolbar-unsaved", + LabelFunc: func() string { + _ = rev.Get() + if ed.SaveFailed() { + return ed.T("toolbar.unsavedFailedLabel") + } + return ed.T("toolbar.unsavedLabel") + }, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + bg := cur.Changed.Fg + if ed.SaveFailed() { + bg = cur.Problem().Fg + } + return core.Style{ + Width: core.Pt(6), + Height: core.Pt(6), + CornerRadius: 3, + Background: bg, + } + }, + } + }, + }, + }, + }, + }, + }, + // Flexible spacer before centered tool & mode controls. + core.View{Style: core.Style{FlexGrow: 1}}, + // Center: Tool radio group (Select V, Move W, Rotate E, Scale R, Pan Space) + 2D / 3D radio group. + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: specSpace12, + FlexShrink: 0, + }, + Children: []core.Node{ + base.RadioGroup{ + TestID: "header-tool-group", + Label: ed.T("toolbar.group.tools"), + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + return core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 2, + Padding: core.All(3), + CornerRadius: specRadiusButton, + Background: cur.Raised, + BorderWidth: 1, + BorderColor: cur.LineRaised, + FlexShrink: 0, + } + }, + Children: toolRadios, + }, + base.RadioGroup{ + TestID: "header-view-mode-group", + Label: ed.T("toolbar.group.viewMode"), + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + return core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 2, + Padding: core.All(3), + CornerRadius: specRadiusButton, + Background: cur.Raised, + BorderWidth: 1, + BorderColor: cur.LineRaised, + FlexShrink: 0, + } + }, + Children: []core.Node{ + viewModeRadio("view-mode-2d", "2D", ViewMode2D), + viewModeRadio("view-mode-3d", "3D", ViewMode3D), + }, + }, + core.Dynamic(func(cx *core.Scope) core.Node { + modeMemo := core.NewMemo(cx, func() ViewMode { + _ = rev.Get() + return ed.ViewMode + }) + return core.Dynamic(func(cx *core.Scope) core.Node { + return pluginToolsView(cx, ed, rev, notPlaying, modeMemo.Get()) + }) + }), + }, + }, + // Flexible spacer before trailing actions. + core.View{Style: core.Style{FlexGrow: 1}}, + // Right: History (⌘Y), Search ⌘K, Play (⌘P) as the one primary button. + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: specSpace8, + FlexShrink: 0, + }, + Children: []core.Node{ + base.Button{ + Ref: historyBtnRef, + TestID: "toolbar-history", + Label: ed.T("toolbar.historyLabel"), + Tooltip: specTooltipNode(p, shortcutTip(ed.T("toolbar.historyLabel"), CmdHistoryPanel)), + Disabled: notPlaying, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + bg := cur.Raised + if ed.HistoryPanelOpen() { + bg = cur.LineRaised + } + return core.Style{ + Width: core.Pt(specButtonHeight), + Height: core.Pt(specButtonHeight), + MinWidth: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + CornerRadius: specRadiusButton, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Background: bg, + BorderWidth: 1, + BorderColor: cur.LineRaised, + Cursor: core.CursorPointer, + Hover: &core.Style{Background: cur.LineRaised}, + Disabled: &core.Style{Opacity: core.Alpha(0.45), Cursor: core.CursorDefault}, + FocusVisible: cur.FocusRing(2), + } + }, + OnPress: func(core.PressEvent) { + ed.ToggleHistoryPanel() + }, + Children: []core.Node{ + core.Icon{ + SVG: mainIconHistory, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + col := cur.TextFaint + if ed.HistoryPanelOpen() { + col = cur.TextPrimary + } + return core.Style{ + Width: core.Pt(specIconSize), + Height: core.Pt(specIconSize), + Color: col, + } + }, + }, + }, + }, + base.Button{ + Ref: paletteBtnRef, + TestID: "toolbar-palette", + Label: ed.T("toolbar.searchLabel"), + Tooltip: specTooltipNode(p, shortcutTip(ed.T("toolbar.search"), CmdCommandPalette)), + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + return core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Height: core.Pt(specButtonHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), + Padding: core.Symmetric(0, specSpace12), + Gap: specSpace8, + CornerRadius: specRadiusButton, + Background: cur.Raised, + BorderWidth: 1, + BorderColor: cur.LineRaised, + Cursor: core.CursorPointer, + Hover: &core.Style{Background: cur.LineRaised}, + FocusVisible: cur.FocusRing(2), + } + }, + OnPress: func(core.PressEvent) { + if ed.focus.ctrl != nil { + ed.focus.ctrl.recordDialogOpener(paletteBtnRef) + } + ed.ToggleCommandPalette() + }, + Children: []core.Node{ + core.Icon{ + SVG: mainIconSearch, + StyleFunc: func() core.Style { + return core.Style{ + Width: core.Pt(specIconSize), + Height: core.Pt(specIconSize), + Color: ed.SpecPalette(cx).TextFaint, + } + }, + }, + core.Text{ + Content: ed.T("toolbar.search"), + MaxLines: 1, + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 12.5, + Color: ed.SpecPalette(cx).TextFaint, + } + }, + }, + core.Text{ + TestID: "toolbar-search-shortcut", + ContentFunc: func() string { + _ = rev.Get() + return FormatShortcut(ed.EffectiveShortcut(CmdCommandPalette), cx.Env().OS()) + }, + MaxLines: 1, + StyleFunc: func() core.Style { + return core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: ed.SpecPalette(cx).TextFaint, + } + }, + }, + }, + }, + base.Button{ + Ref: playBtnRef, + TestID: "toolbar-play", + LabelFunc: func() string { + _ = rev.Get() + if ed.Playing() { + return ed.T("toolbar.stop") + } + return ed.T("toolbar.play") + }, + Tooltip: specTooltipNode(p, shortcutTip(ed.T("toolbar.play"), CmdPlayStop)), + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + return core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Height: core.Pt(specButtonHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), + Padding: core.Symmetric(0, specSpace12), + Gap: specSpace8, + CornerRadius: specRadiusButton, + Background: cur.TextPrimary, + Cursor: core.CursorPointer, + Hover: &core.Style{Background: specPrimaryHover(cur)}, + FocusVisible: cur.FocusRing(2), + } + }, + OnPress: func(core.PressEvent) { + if ed.Playing() { + _ = ed.Stop() + } else { + _ = ed.Play() + } + }, + Children: []core.Node{ + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.Playing() + }, + Then: func(cx *core.Scope) core.Node { + return core.Icon{ + SVG: mainIconStop, + StyleFunc: func() core.Style { + return core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + Color: ed.SpecPalette(cx).OnTextPrimary, + } + }, + } + }, + Else: func(cx *core.Scope) core.Node { + return core.Icon{ + SVG: mainIconPlay, + StyleFunc: func() core.Style { + return core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + Color: ed.SpecPalette(cx).OnTextPrimary, + } + }, + } + }, + }, + core.Text{ + ContentFunc: func() string { + _ = rev.Get() + if ed.Playing() { + return ed.T("toolbar.stop") + } + return ed.T("toolbar.play") + }, + MaxLines: 1, + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 12.5, + FontWeight: core.FontWeightSemibold, + Color: ed.SpecPalette(cx).OnTextPrimary, + } + }, + }, + }, + }, + }, + }, + }, + } +} + +// leftRailSceneView renders the 232 pt AI-first left rail matching Main.dc.html: +// Scene / Assets switch, SCENE · N nodes (or designed empty/loading/error state), +// and FILES listing the open scene, prefabs it uses, and game.yaml. +func leftRailSceneView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + wsMemo := core.NewMemo(cx, func() string { + _ = rev.Get() + return ed.workspaceStateKey() + }) + darkMemo := core.NewMemo(cx, func() bool { + _ = rev.Get() + return cx.Dark() + }) + filesKey := core.NewMemo(cx, func() string { + _ = rev.Get() + var b strings.Builder + b.WriteString(ed.ScenePath) + b.WriteByte('|') + b.WriteString(ed.FilePath) + b.WriteByte('|') + b.WriteString(ed.ProjectPath) + b.WriteByte('|') + for _, pf := range ed.SceneUsedPrefabs() { + b.WriteString(pf) + b.WriteByte(',') + } + if darkMemo.Get() { + b.WriteString("|D") + } else { + b.WriteString("|L") + } + return b.String() + }) + + return core.View{ + TestID: "editor-scene-column", + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + return core.Style{ + Width: core.Pt(232), + FlexShrink: 0, + Background: cur.Bg, + Borders: core.Edges{Right: 1}, + BorderColor: cur.Line, + MinHeight: core.Pt(0), + Overflow: core.Hidden, + } + }, + Children: []core.Node{ + LeftRailSwitchView(cx, ed, rev), + // SCENE · N nodes header + core.View{ + TestID: "scene-rail-header", + Style: core.Style{ + Height: core.Pt(36), + FlexShrink: 0, + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifySpaceBetween, + Padding: core.Symmetric(0, specSpace12), + }, + Children: []core.Node{ + core.Text{ + TestID: "scene-rail-title", + Content: strings.ToUpper(ed.T("sceneTree.sectionTitle")), + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 11, + FontWeight: core.FontWeightSemibold, + LetterSpacing: 0.66, + Color: ed.SpecPalette(cx).TextFaint, + } + }, + }, + core.Text{ + TestID: "scene-rail-node-count", + ContentFunc: func() string { + _ = rev.Get() + if ed.WorkspaceState() != WorkspaceReady { + return "" + } + n := ed.SceneNodeCount() + if n == 1 { + return ed.T("sceneTree.nodeCountOne") + } + return ed.T("sceneTree.nodeCount", l10n.Param("count", n)) + }, + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 11, + FontWeight: core.FontWeightMedium, + Color: ed.SpecPalette(cx).TextFaint, + } + }, + }, + }, + }, + // Scene tree or designed empty/loading/error state. + core.View{ + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + MinHeight: core.Pt(0), + Overflow: core.Hidden, + }, + Children: []core.Node{ + core.Dynamic(func(cx *core.Scope) core.Node { + _ = wsMemo.Get() + ws := ed.WorkspaceState() + p := SpecPaletteFor(darkMemo.Get()) + switch ws { + case WorkspaceLoading: + return core.View{ + Style: core.Style{Padding: core.All(specSpace12)}, + Children: []core.Node{ + specLoadingState(p, "left-rail-loading", ed.T("workspace.loadingProject")), + }, + } + case WorkspaceSceneError: + return core.View{ + Style: core.Style{Padding: core.All(specSpace12), Gap: specSpace8}, + Children: []core.Node{ + specStatusBanner(p, "left-rail-scene-error", false, ed.T("workspace.sceneErrorShort"), nil, nil), + specPanelButton(p, specPanelButtonSpec{ + TestID: "left-rail-retry-open", + Text: ed.T("workspace.retry"), + Variant: specBtnQuiet, + Compact: true, + InsetFocus: true, + OnPress: func() { _ = ed.RetryOpenScene() }, + }), + }, + } + case WorkspaceNoProject: + return core.View{ + Style: core.Style{Padding: core.All(specSpace12)}, + Children: []core.Node{ + specEmptyState(p, "left-rail-empty-no-project", lucide.FolderOpen, p.TextFaint, + ed.T("workspace.noProjectTitle"), + ed.T("workspace.noProjectRailHint"), + nil), + }, + } + case WorkspaceNoScene: + return core.View{ + Style: core.Style{Padding: core.All(specSpace12)}, + Children: []core.Node{ + specEmptyState(p, "left-rail-empty-no-scene", lucide.FileCode, p.TextFaint, + ed.T("workspace.noSceneTitle"), + ed.T("workspace.noSceneRailHint"), + nil), + }, + } + default: + return SceneTreeView(cx, ed, rev) + } + }), + }, + }, + // Bottom FILES section: open scene, prefabs it uses, game.yaml. + core.Dynamic(func(cx *core.Scope) core.Node { + _ = filesKey.Get() + p := SpecPaletteFor(darkMemo.Get()) + type railFileEntry struct { + testID string + path string + dot core.Color + onOpen func() + } + var entries []railFileEntry + if ed.ScenePath != "" { + sp := ed.ScenePath + entries = append(entries, railFileEntry{ + testID: "rail-file-scene", + path: sp, + dot: p.Accent.Fg, + onOpen: func() { _ = ed.OpenProjectFile(sp) }, + }) + } else if ed.FilePath != "" { + fp := filepath.Base(ed.FilePath) + entries = append(entries, railFileEntry{ + testID: "rail-file-scene", + path: fp, + dot: p.Accent.Fg, + onOpen: func() {}, + }) + } + for i, pref := range ed.SceneUsedPrefabs() { + pf := pref + entries = append(entries, railFileEntry{ + testID: fmt.Sprintf("rail-file-prefab-%d", i), + path: pf, + dot: p.Agent.Fg, + onOpen: func() { + if ed.Project != nil { + ed.report(ed.OpenProjectFile(pf)) + } + }, + }) + } + if ed.Project != nil && ed.ProjectPath != "" { + entries = append(entries, railFileEntry{ + testID: "rail-file-project", + path: project.FileName, + dot: p.TextFaint, + onOpen: func() { ed.report(ed.OpenProjectFile(project.FileName)) }, + }) + } + + rows := []core.Node{ + core.Text{ + TestID: "left-rail-files-title", + Content: strings.ToUpper(ed.T("files.sectionTitle")), + Style: core.Style{ + FontSize: 11, + FontWeight: core.FontWeightSemibold, + LetterSpacing: 0.66, + Color: p.TextFaint, + Padding: core.Symmetric(0, specSpace4), + }, + }, + } + if len(entries) == 0 { + rows = append(rows, core.Text{ + TestID: "left-rail-files-empty", + Content: ed.T("files.railEmpty"), + Style: core.Style{ + FontSize: 11.5, + Color: p.TextFaint, + Padding: core.Symmetric(specSpace4, specSpace8), + }, + }) + } else { + for _, ent := range entries { + e := ent + rows = append(rows, base.Button{ + TestID: e.testID, + Label: e.path, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + Width: core.Pct(100), + Padding: core.Symmetric(0, specSpace8), + Gap: specSpace8, + CornerRadius: specRadiusControl, + Background: core.Transparent, + Cursor: core.CursorPointer, + Hover: &core.Style{Background: p.Raised}, + FocusVisible: p.FocusRing(-2), + }, + OnPress: func(core.PressEvent) { + if !ed.Playing() { + e.onOpen() + } + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(6), + Height: core.Pt(6), + CornerRadius: 2, + Background: e.dot, + FlexShrink: 0, + }, + }, + core.Text{ + Content: e.path, + MaxLines: 1, + EllipsizeMode: core.EllipsizeMiddle, + Style: core.Style{ + FontSize: 12, + Color: p.TextMuted, + FlexGrow: 1, + FlexShrink: 1, + }, + }, + }, + }) + } + } + return core.View{ + TestID: "left-rail-files", + Style: core.Style{ + FlexShrink: 0, + Padding: core.All(specSpace8), + Gap: specSpace4, + Borders: core.Edges{Top: 1}, + BorderColor: p.Line, + }, + Children: rows, + } + }), + }, + } +} + +// viewportCameraCaptionView renders the "Camera · W × H" caption positioned above the +// 2D camera frame matching docs/design/editor/Main.dc.html. +func viewportCameraCaptionView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + return core.Show{ + When: func() bool { + _ = rev.Get() + return ed.ViewMode == ViewMode2D && !ed.Playing() && ed.WorkspaceState() == WorkspaceReady + }, + Then: func(cx *core.Scope) core.Node { + return core.Text{ + TestID: "viewport-camera-caption", + PointerEvents: core.PointerEventsNone, + ContentFunc: func() string { + _ = rev.Get() + vw, vh := ed.ViewportSize() + return fmt.Sprintf("Camera · %d × %d", int(math.Round(float64(vw))), int(math.Round(float64(vh)))) + }, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + cx0, cy0 := ed.ScreenToCanvas(0, 0) + cw, ch := ed.CanvasSize() + left := core.Points(cx0) + top := core.Points(cy0) - 20 + if cw <= 0 || ch <= 0 || left < 12 || left > core.Points(cw)-140 || top < 8 || top > core.Points(ch)-56 { + left = 16 + top = 12 + } + return core.Style{ + Position: core.Absolute, + Left: core.Pt(left), + Top: core.Pt(top), + FontSize: 11, + Color: cur.TextFaint, + } + }, + } + }, + } +} + +// viewportWorkspaceStateOverlay renders designed empty, loading, and error states over the viewport +// whenever WorkspaceState() != WorkspaceReady so a missing or malformed scene never shows a blank viewport. +func viewportWorkspaceStateOverlay(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + wsMemo := core.NewMemo(cx, func() string { + _ = rev.Get() + if ed.Playing() { + return "playing" + } + return ed.workspaceStateKey() + }) + darkMemo := core.NewMemo(cx, func() bool { + _ = rev.Get() + return cx.Dark() + }) + + return core.Dynamic(func(cx *core.Scope) core.Node { + if wsMemo.Get() == "playing" { + return nil + } + ws := ed.WorkspaceState() + if ws == WorkspaceReady { + return nil + } + p := SpecPaletteFor(darkMemo.Get()) + var card core.Node + switch ws { + case WorkspaceLoading: + detail := ed.ProjectLoadingPath() + children := []core.Node{ + specLoadingState(p, "viewport-loading-card", ed.T("workspace.loadingProject")), + } + if detail != "" { + children = append(children, core.Text{ + TestID: "viewport-loading-path", + Content: detail, + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: p.TextFaint, + }, + }) + } + card = core.View{ + TestID: "viewport-loading-state", + Role: core.RoleStatus, + Label: ed.T("workspace.loadingProject"), + Style: core.Style{ + Width: core.Pt(420), + MaxWidth: core.Pct(90), + Padding: core.All(specSpace24), + Gap: specSpace12, + CornerRadius: specRadiusCard, + Background: p.Panel, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: children, + } + + case WorkspaceSceneError: + se := ed.SceneOpenError() + loc := "" + msg := ed.T("workspace.sceneErrorTitle") + fix := "" + if se != nil { + loc = se.Path + if se.Line > 0 { + if se.Column > 0 { + loc = fmt.Sprintf("%s:%d:%d", se.Path, se.Line, se.Column) + } else { + loc = fmt.Sprintf("%s:%d", se.Path, se.Line) + } + } + if se.Message != "" { + msg = se.Message + } + fix = se.Fix + } + errChildren := []core.Node{ + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: specSpace8, + }, + Children: []core.Node{ + specIcon(lucide.TriangleAlert, 18, p.Problem().Fg), + core.Text{ + TestID: "viewport-error-title", + Content: ed.T("workspace.sceneErrorTitle"), + Style: core.Style{ + FontSize: 14, + FontWeight: core.FontWeightSemibold, + Color: p.TextPrimary, + }, + }, + }, + }, + } + if loc != "" { + errChildren = append(errChildren, core.Text{ + TestID: "viewport-error-path", + Content: loc, + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: p.Problem().Fg, + }, + }) + } + errChildren = append(errChildren, core.Text{ + TestID: "viewport-error-message", + Content: msg, + Style: core.Style{ + FontSize: 12.5, + Color: p.TextSecondary, + }, + }) + if fix != "" { + errChildren = append(errChildren, core.Text{ + TestID: "viewport-error-fix", + Content: fix, + Style: core.Style{ + FontSize: 12, + Color: p.TextFaint, + }, + }) + } + actions := []core.Node{ + specPanelButton(p, specPanelButtonSpec{ + TestID: "viewport-error-retry", + Text: ed.T("workspace.retry"), + Variant: specBtnPrimary, + OnPress: func() { _ = ed.RetryOpenScene() }, + }), + specPanelButton(p, specPanelButtonSpec{ + TestID: "viewport-error-dismiss", + Text: ed.T("workspace.dismiss"), + Variant: specBtnQuiet, + OnPress: func() { ed.ClearSceneOpenError() }, + }), + } + if ed.Project != nil { + actions = append(actions, specPanelButton(p, specPanelButtonSpec{ + TestID: "viewport-error-open-palette", + Text: ed.T("workspace.openAnotherScene"), + Variant: specBtnSecondary, + OnPress: func() { ed.OpenCommandPalette() }, + })) + } + errChildren = append(errChildren, core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: specSpace8, + Margin: core.Edges{Top: specSpace4}, + }, + Children: actions, + }) + card = core.View{ + TestID: "viewport-error-state", + Role: core.RoleAlert, + Label: ed.T("workspace.sceneErrorTitle"), + Style: core.Style{ + Width: core.Pt(480), + MaxWidth: core.Pct(90), + Padding: core.All(specSpace24), + Gap: specSpace12, + CornerRadius: specRadiusCard, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.Problem().Edge, + }, + Children: errChildren, + } + + case WorkspaceNoProject: + card = core.View{ + TestID: "viewport-empty-no-project", + Role: core.RoleRegion, + Label: ed.T("workspace.noProjectTitle"), + Style: core.Style{ + Width: core.Pt(420), + MaxWidth: core.Pct(90), + Padding: core.All(specSpace24), + Gap: specSpace12, + CornerRadius: specRadiusCard, + Background: p.Panel, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: specSpace8}, + Children: []core.Node{ + specIcon(lucide.FolderOpen, 18, p.TextMuted), + core.Text{ + Content: ed.T("workspace.noProjectTitle"), + Style: core.Style{ + FontSize: 14, + FontWeight: core.FontWeightSemibold, + Color: p.TextPrimary, + }, + }, + }, + }, + core.Text{ + Content: ed.T("workspace.noProjectDesc"), + Style: core.Style{ + FontSize: 12.5, + Color: p.TextFaint, + }, + }, + core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: specSpace8}, + Children: []core.Node{ + specPanelButton(p, specPanelButtonSpec{ + TestID: "viewport-empty-open-project", + Text: ed.T("workspace.openProject"), + Variant: specBtnPrimary, + OnPress: func() { ed.report(ed.BrowseAndOpenProject()) }, + }), + specPanelButton(p, specPanelButtonSpec{ + TestID: "viewport-empty-start-screen", + Text: ed.T("workspace.startScreen"), + Variant: specBtnQuiet, + OnPress: func() { ed.SetStartScreenOpen(true) }, + }), + }, + }, + }, + } + + case WorkspaceNoScene: + card = core.View{ + TestID: "viewport-empty-no-scene", + Role: core.RoleRegion, + Label: ed.T("workspace.noSceneTitle"), + Style: core.Style{ + Width: core.Pt(420), + MaxWidth: core.Pct(90), + Padding: core.All(specSpace24), + Gap: specSpace12, + CornerRadius: specRadiusCard, + Background: p.Panel, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: specSpace8}, + Children: []core.Node{ + specIcon(lucide.FileCode, 18, p.TextMuted), + core.Text{ + Content: ed.T("workspace.noSceneTitle"), + Style: core.Style{ + FontSize: 14, + FontWeight: core.FontWeightSemibold, + Color: p.TextPrimary, + }, + }, + }, + }, + core.Text{ + Content: ed.T("workspace.noSceneDesc"), + Style: core.Style{ + FontSize: 12.5, + Color: p.TextFaint, + }, + }, + core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: specSpace8}, + Children: []core.Node{ + specPanelButton(p, specPanelButtonSpec{ + TestID: "viewport-empty-search-files", + Text: ed.T("workspace.searchFiles"), + Variant: specBtnPrimary, + OnPress: func() { ed.OpenCommandPalette() }, + }), + }, + }, + }, + } + } + + return core.View{ + TestID: "viewport-state-overlay", + Style: core.Style{ + Position: core.Absolute, + Top: core.Pt(0), + Right: core.Pt(0), + Bottom: core.Pt(0), + Left: core.Pt(0), + Background: p.Viewport, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Padding: core.All(specSpace24), + }, + Children: []core.Node{card}, + } + }) +} + +// inspectorWorkspaceStateView renders designed empty, loading, or error states inside the Inspector tab +// when WorkspaceState() != WorkspaceReady. Returns nil when WorkspaceReady. +func inspectorWorkspaceStateView(cx *core.Scope, ed *Editor, ws WorkspaceState) core.Node { + if ws == WorkspaceReady { + return nil + } + p := ed.SpecPalette(cx) + var body core.Node + switch ws { + case WorkspaceLoading: + body = specLoadingState(p, "inspector-loading-state", ed.T("workspace.loadingProject")) + case WorkspaceSceneError: + se := ed.SceneOpenError() + detail := ed.T("workspace.sceneErrorShort") + if se != nil && se.Path != "" { + detail = se.Path + } + body = specStatusBanner(p, "inspector-error-state", false, detail, nil, nil) + case WorkspaceNoProject: + body = specEmptyState(p, "inspector-empty-no-project", lucide.FolderOpen, p.TextFaint, + ed.T("workspace.noProjectTitle"), + ed.T("workspace.noProjectInspectorHint"), + nil) + case WorkspaceNoScene: + body = specEmptyState(p, "inspector-empty-no-scene", lucide.FileCode, p.TextFaint, + ed.T("workspace.noSceneTitle"), + ed.T("workspace.noSceneInspectorHint"), + nil) + } + return core.View{ + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + Padding: core.All(specSpace16), + Background: p.Panel, + }, + Children: []core.Node{body}, + } +} + +// mainStatusBarView renders the 32 px Spec status bar in muted text on bg: +// active layer, live pointer coordinates, current tool on the left; +// problem count (opens Problems), Output, and Debugger on the right. +func mainStatusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + pointerRev := core.NewSignal(cx, ed.PointerRevision()) + unsubPtr := ed.SubscribePointer(func() { + pointerRev.Set(ed.PointerRevision()) + }) + cx.Cleanup(unsubPtr) + + layerBtnRef := &core.Ref{} + problemsBtnRef := &core.Ref{} + outputBtnRef := &core.Ref{} + debuggerBtnRef := &core.Ref{} + changesBtnRef := &core.Ref{} + conflictsBtnRef := &core.Ref{} + playtestBtnRef := &core.Ref{} + if ed.focus.ctrl != nil { + ed.focus.ctrl.registerCandidate(cx, RegionStatusBar, layerBtnRef, nil) + ed.focus.ctrl.registerCandidate(cx, RegionStatusBar, problemsBtnRef, func() bool { return !ed.Playing() }) + ed.focus.ctrl.registerCandidate(cx, RegionStatusBar, outputBtnRef, nil) + ed.focus.ctrl.registerCandidate(cx, RegionStatusBar, debuggerBtnRef, nil) + ed.focus.ctrl.registerCandidate(cx, RegionStatusBar, changesBtnRef, func() bool { + return ed.Project != nil && ed.ProjectPath != "" && !ed.Playing() + }) + ed.focus.ctrl.registerCandidate(cx, RegionStatusBar, conflictsBtnRef, func() bool { + return len(ed.DetectedMergeConflicts()) > 0 + }) + ed.focus.ctrl.registerCandidate(cx, RegionStatusBar, playtestBtnRef, func() bool { + return ed.ActivePlaytestReport() != nil + }) + } + + statusBtnStyle := func(active bool) core.Style { + cur := ed.SpecPalette(cx) + bg := core.Transparent + if active { + bg = cur.Raised + } + return core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), + Padding: core.Symmetric(0, specSpace8), + Gap: specSpace4, + CornerRadius: specRadiusControl, + Background: bg, + Cursor: core.CursorPointer, + Hover: &core.Style{Background: cur.Raised}, + FocusVisible: cur.FocusRing(-2), + } + } + + return core.View{ + Ref: ed.focus.ctrl.rootRef(RegionStatusBar), + TestID: "editor-status", + Role: core.RoleRegion, + Label: ed.T("region.statusBar"), + Focusable: func() bool { + if ed.focus.ctrl == nil { + return false + } + return !ed.focus.ctrl.hasEnabledCandidate(RegionStatusBar) || ed.focus.ctrl.fallbackRegion.Get() == RegionStatusBar + }, + OnFocusIn: func() { + if ed.focus.ctrl != nil { + ed.focus.ctrl.onRegionFocusIn(RegionStatusBar) + } + }, + OnFocusOut: func() { + if ed.focus.ctrl != nil { + ed.focus.ctrl.onRegionFocusOut(RegionStatusBar) + } + }, + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + baseStyle := core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(32), + FlexShrink: 0, + Gap: specSpace12, + Padding: core.Symmetric(0, specSpace12), + Background: cur.Bg, + Borders: core.Edges{Top: 1}, + BorderColor: cur.Line, + } + if ed.focus.ctrl == nil { + return baseStyle + } + return ed.focus.ctrl.regionOutlineStyle(RegionStatusBar, baseStyle) + }, + Children: []core.Node{ + // Left: active layer, pointer coordinates, current tool (muted text on bg). + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: specSpace12, + FlexShrink: 1, + MinWidth: core.Pt(0), + }, + Children: []core.Node{ + base.Button{ + Ref: layerBtnRef, + TestID: "status-active-layer", + LabelFunc: func() string { + _ = rev.Get() + return ed.T("status.activeLayerLabel", l10n.Param("layer", ed.activeLayerReadout())) + }, + StyleFunc: func() core.Style { + _ = rev.Get() + return statusBtnStyle(ed.LayersPanelOpen()) + }, + OnPress: func(core.PressEvent) { + ed.SetLayersPanelOpen(!ed.LayersPanelOpen()) + }, + Children: []core.Node{ + core.Text{ + ContentFunc: func() string { + _ = rev.Get() + switch ed.WorkspaceState() { + case WorkspaceLoading: + return ed.T("workspace.loadingShort") + case WorkspaceSceneError: + return ed.T("workspace.sceneErrorShort") + case WorkspaceNoProject: + return ed.T("workspace.noProjectTitle") + case WorkspaceNoScene: + return ed.T("workspace.noSceneTitle") + default: + return ed.T("status.layerReadout", l10n.Param("layer", ed.activeLayerReadout())) + } + }, + MaxLines: 1, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + col := cur.TextFaint + if ed.LayersPanelOpen() { + col = cur.TextPrimary + } else if ed.WorkspaceState() == WorkspaceSceneError { + col = cur.Problem().Fg + } + return core.Style{ + FontSize: 11.5, + Color: col, + } + }, + }, + }, + }, + core.Text{ + TestID: "status-pointer-coords", + ContentFunc: func() string { + _ = rev.Get() + _ = pointerRev.Get() + if ed.WorkspaceState() != WorkspaceReady { + return "" + } + if ed.ViewMode == ViewMode2D { + if wx, wy, ok := ed.ViewportPointer2DWorld(); ok { + return fmt.Sprintf("%d, %d", int(math.Round(float64(wx))), int(math.Round(float64(wy)))) + } + } + return "—, —" + }, + MaxLines: 1, + StyleFunc: func() core.Style { + return core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: ed.SpecPalette(cx).TextFaint, + } + }, + }, + core.Text{ + TestID: "editor-status-mode", + ContentFunc: func() string { + _ = rev.Get() + if ed.WorkspaceState() != WorkspaceReady { + return "" + } + if ed.ViewMode == ViewMode3D { + if gt := ed.GridMapTool(); gt != GridMapToolNone { + return fmt.Sprintf("%s · %s · Floor %d · %d/24", ed.viewStatus3D(), gt.String(), ed.GridMapFloor(), ed.GridMapOrientation()) + } + space := ed.T("gizmo.spaceGlobal") + if ed.GizmoSpace3D == GizmoSpaceLocal { + space = ed.T("gizmo.spaceLocal") + } + s := fmt.Sprintf("%s · %s · %s", ed.viewStatus3D(), ed.localizedGizmoName(ed.GizmoMode), space) + if ed.Tool == ToolPlugin && ed.activePluginToolSupports3D() { + s += " · " + ed.toolLabel() + } + return s + } + tool := ed.toolLabel() + switch ed.Tool { + case ToolPaintTile, ToolFillTile, ToolRectTile, ToolLineTile: + if tile, ok := ed.TilePalette().Tile(ed.ActiveTileID); ok { + tool += ed.T("status.tileSuffix", l10n.Param("tile", tile.Number)) + } + case ToolTerrain: + if tp := ed.TilePalette(); tp.ActiveTerrain != "" { + tool += ed.T("status.terrainSuffix", l10n.Param("terrain", tp.ActiveTerrain)) + } + case ToolStampTile: + if stamp, ok := ed.TileStamp(); ok { + tool += fmt.Sprintf(" | Stamp: %dx%d", stamp.Width, stamp.Height) + } else if tile, ok := ed.TilePalette().Tile(ed.ActiveTileID); ok { + tool += ed.T("status.tileSuffix", l10n.Param("tile", tile.Number)) + } + case ToolRandomTile: + tool += fmt.Sprintf(" | Random: %d tiles (seed %d)", len(ed.effectiveRandomPool()), ed.RandomBrushSeed()) + } + return tool + }, + MaxLines: 1, + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 11.5, + Color: ed.SpecPalette(cx).TextFaint, + } + }, + }, + core.Text{ + TestID: "editor-status-message", + ContentFunc: func() string { + _ = rev.Get() + if delta := ed.GizmoDragDelta3D(); delta != "" { + return delta + } + if ed.BuildErr != nil { + return ed.T("status.buildError", l10n.Param("error", ed.BuildErr.Error())) + } + if ed.Status == "" || ed.Status == "Ready" { + return "" + } + return ed.Status + }, + MaxLines: 1, + EllipsizeMode: core.EllipsizeTail, + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 11.5, + Color: ed.SpecPalette(cx).TextFaint, + MaxWidth: core.Pt(240), + } + }, + }, + }, + }, + // Flexible spacer. + core.View{Style: core.Style{FlexGrow: 1}}, + // Right: transient indicators + Problems + Output + Debugger. + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: specSpace8, + FlexShrink: 0, + }, + Children: []core.Node{ + saveStatusBarView(cx, ed, rev), + tasksStatusIndicatorView(cx, ed, rev), + remoteStatusView(cx, ed, rev), + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.Project != nil && ed.ProjectPath != "" && ed.ChangesCount() > 0 + }, + Then: func(cx *core.Scope) core.Node { + return base.Button{ + Ref: changesBtnRef, + TestID: "status-changes", + LabelFunc: func() string { + _ = rev.Get() + return ed.T("status.changesCount", l10n.Param("count", ed.ChangesCount())) + }, + Disabled: func() bool { + _ = rev.Get() + return ed.Playing() + }, + StyleFunc: func() core.Style { return statusBtnStyle(false) }, + OnPress: func(core.PressEvent) { + ed.report(ed.OpenChangesPanel()) + }, + Children: []core.Node{ + specIcon(lucide.GitBranch, 12, ed.SpecPalette(cx).TextFaint), + core.Text{ + ContentFunc: func() string { + _ = rev.Get() + return ed.T("status.changesCount", l10n.Param("count", ed.ChangesCount())) + }, + StyleFunc: func() core.Style { + return core.Style{FontSize: 11.5, Color: ed.SpecPalette(cx).TextFaint} + }, + }, + }, + } + }, + }, + core.Show{ + When: func() bool { + _ = rev.Get() + return len(ed.DetectedMergeConflicts()) > 0 + }, + Then: func(cx *core.Scope) core.Node { + return base.Button{ + Ref: conflictsBtnRef, + TestID: "status-merge-conflicts", + Label: ed.T("status.mergeConflictsLabel"), + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + st := statusBtnStyle(false) + st.Background = cur.Warning.Fill + st.BorderWidth = 1 + st.BorderColor = cur.Warning.Edge + return st + }, + OnPress: func(core.PressEvent) { + ed.report(ed.OpenMergeConflict("")) + }, + Children: []core.Node{ + specIcon(lucide.GitMerge, 12, ed.SpecPalette(cx).Warning.Fg), + core.Text{ + ContentFunc: func() string { + _ = rev.Get() + n := len(ed.DetectedMergeConflicts()) + if n == 1 { + return "1 scene conflict" + } + return fmt.Sprintf("%d scene conflicts", n) + }, + StyleFunc: func() core.Style { + return core.Style{FontSize: 11.5, FontWeight: core.FontWeightMedium, Color: ed.SpecPalette(cx).Warning.Fg} + }, + }, + }, + } + }, + }, + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.ActivePlaytestReport() != nil + }, + Then: func(cx *core.Scope) core.Node { + return base.Button{ + Ref: playtestBtnRef, + TestID: "status-playtest-report", + Label: "Playtest Report", + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + st := statusBtnStyle(false) + st.BorderWidth = 1 + st.BorderColor = cur.LineRaised + if rep := ed.ActivePlaytestReport(); rep != nil && len(rep.MissedMetrics()) > 0 { + st.Background = cur.Removed.Fill + } else { + st.Background = cur.Added.Fill + } + return st + }, + OnPress: func(core.PressEvent) { + ed.SetPlaytestReportOpen(true) + }, + Children: []core.Node{ + core.Text{ + ContentFunc: func() string { + _ = rev.Get() + rep := ed.ActivePlaytestReport() + if rep == nil { + return "Playtest" + } + if missed := len(rep.MissedMetrics()); missed > 0 { + return fmt.Sprintf("Playtest · %d missed", missed) + } + return "Playtest · met" + }, + StyleFunc: func() core.Style { + return core.Style{FontSize: 11.5, FontWeight: core.FontWeightSemibold, Color: ed.SpecPalette(cx).TextSecondary} + }, + }, + }, + } + }, + }, + // Problem count button (always present, green dot + "No problems" or red alert + count). + base.Button{ + Ref: problemsBtnRef, + TestID: "status-problems-pill", + Label: ed.T("problems.openPanelLabel"), + Disabled: func() bool { + _ = rev.Get() + return ed.Playing() + }, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + st := statusBtnStyle(ed.ProblemAgentPanelOpen()) + st.Gap = 6 + if ed.ProblemCount() > 0 { + st.Background = cur.Problem().Fill + st.BorderWidth = 1 + st.BorderColor = cur.Problem().Edge + } + return st + }, + OnPress: func(core.PressEvent) { + if ed.Playing() || ed.StartScreenOpen() || ed.MergeConflictOpen() { + return + } + ed.SetProblemAgentPanelOpen(!ed.ProblemAgentPanelOpen()) + }, + Children: []core.Node{ + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.ProblemCount() > 0 + }, + Then: func(cx *core.Scope) core.Node { + return problemAlertIconFunc(func() core.Color { return ed.SpecPalette(cx).Problem().Fg }, 12) + }, + Else: func(cx *core.Scope) core.Node { + return core.View{ + TestID: "status-problems-ok-dot", + StyleFunc: func() core.Style { + return core.Style{ + Width: core.Pt(6), + Height: core.Pt(6), + CornerRadius: 3, + Background: ed.SpecPalette(cx).Added.Fg, + FlexShrink: 0, + } + }, + } + }, + }, + core.Text{ + TestID: "status-problems", + ContentFunc: func() string { + _ = rev.Get() + if ed.ProblemCount() == 0 { + return ed.T("problems.none") + } + return ed.problemsStatusText() + }, + MaxLines: 1, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + if ed.ProblemCount() > 0 { + return core.Style{ + FontSize: 11.5, + FontWeight: core.FontWeightSemibold, + Color: cur.Problem().Fg, + } + } + return core.Style{ + FontSize: 11.5, + Color: cur.TextFaint, + } + }, + }, + }, + }, + // Output button. + base.Button{ + Ref: outputBtnRef, + TestID: "status-output", + Label: ed.T("toolbar.outputLabel"), + StyleFunc: func() core.Style { + _ = rev.Get() + return statusBtnStyle(ed.OutputPanelOpen()) + }, + OnPress: func(core.PressEvent) { + ed.SetOutputPanelOpen(!ed.OutputPanelOpen()) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("toolbar.output"), + MaxLines: 1, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + col := cur.TextFaint + if ed.OutputPanelOpen() { + col = cur.TextPrimary + } + return core.Style{ + FontSize: 11.5, + Color: col, + } + }, + }, + }, + }, + // Debugger button. + base.Button{ + Ref: debuggerBtnRef, + TestID: "status-debugger", + Label: ed.T("status.debuggerLabel"), + StyleFunc: func() core.Style { + _ = rev.Get() + return statusBtnStyle(ed.ProfilerOpen()) + }, + OnPress: func(core.PressEvent) { + ed.SetProfilerOpen(!ed.ProfilerOpen()) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("status.debugger"), + MaxLines: 1, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + col := cur.TextFaint + if ed.ProfilerOpen() { + col = cur.TextPrimary + } + return core.Style{ + FontSize: 11.5, + Color: col, + } + }, + }, + }, + }, + }, + }, + }, + } +} diff --git a/packages/game/editor/materials_test.go b/packages/game/editor/materials_test.go index a6032af31..33171c6ff 100644 --- a/packages/game/editor/materials_test.go +++ b/packages/game/editor/materials_test.go @@ -606,6 +606,7 @@ func TestInspectorCreatesAndOpensMaterialAndIntegratesWithFilesAndPalette(t *tes } // File Browser Open button opens a selected material file. + openFileBrowserInUI(app, ed) app.Press("id:files-row-materials/metal.material.yaml") app.Press("id:files-open") if !ed.MaterialOpen() || ed.MaterialRelPath() != "materials/metal.material.yaml" { diff --git a/packages/game/editor/menubar.go b/packages/game/editor/menubar.go index 4e7d472bd..44b152843 100644 --- a/packages/game/editor/menubar.go +++ b/packages/game/editor/menubar.go @@ -110,6 +110,9 @@ func (e *Editor) ApplicationMenu() []desktop.MenuItem { toolItems := []desktop.MenuItem{ cmdItem(CmdToolSelect, e.T("menu.select"), true), cmdItem(CmdToolMove, e.T("menu.move"), true), + cmdItem(CmdToolRotate, e.T("menu.rotate"), true), + cmdItem(CmdToolScale, e.T("menu.scale"), true), + cmdItem(CmdToolPan, e.T("menu.pan"), true), cmdItem(CmdToolPlace, e.T("menu.place"), true), cmdItem(CmdToolPaintTile, e.T("menu.paintTile"), true), cmdItem(CmdToolEraseTile, e.T("menu.eraseTile"), true), @@ -265,6 +268,7 @@ func (e *Editor) ApplicationMenu() []desktop.MenuItem { cmdItem(CmdProfiler, e.T("menu.profiler"), false), cmdItem(CmdParticleEditor, e.T("menu.particleEditor"), false), cmdItem(CmdMaterialEditor, e.T("menu.materialEditor"), false), + cmdItem(CmdTerrainEditor, "3D Terrain Editor", false), cmdItem(CmdBuildRelease, e.T("menu.buildRelease"), false), sep, cmdItem(CmdFindUsages, e.T("menu.findUsages"), false), diff --git a/packages/game/editor/models_test.go b/packages/game/editor/models_test.go index 24dfdc99a..c249a47ac 100644 --- a/packages/game/editor/models_test.go +++ b/packages/game/editor/models_test.go @@ -398,6 +398,7 @@ func TestPressModelIn2DLeavesThePlaceToolOff(t *testing.T) { ed.SetViewMode(editor.ViewMode2D) app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1200, 900), nsgotest.NoGPU()) before := saveYAML(t, ed) + openAssetBrowserInUI(app, ed) app.Press("id:model-mesh-box") if ed.SelectedModel == nil || *ed.SelectedModel != boxModel { t.Fatalf("selected model %+v, want the box", ed.SelectedModel) @@ -414,14 +415,12 @@ func TestPressModelIn2DLeavesThePlaceToolOff(t *testing.T) { // In the editor's window: pressing a model in the asset browser picks it for the Place tool, a press on the 3D viewport places it, the toolbar's Undo and Redo take it back and make it again; dragging a primitive from the browser onto the viewport places it there, a file dropped from another app lands too, and the inspector's Model field picks one of the project's models. func TestPlaceModelsInTheEditorWindow(t *testing.T) { ed := editor.OpenCourtyard(t) - app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1200, 900), nsgotest.NoGPU()) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1440, 900), nsgotest.NoGPU()) + openAssetBrowserInUI(app, ed) app.Press("id:model-models-crate-glb") if ed.SelectedModel == nil || *ed.SelectedModel != crateModel || ed.Tool != editor.ToolPlace { t.Fatalf("after pressing the crate: model %+v, tool %v", ed.SelectedModel, ed.Tool) } - if !app.Find("id:tool3d-place").Props.Pressed { - t.Fatal("the 3D toolbar's Place is off with the Place tool on") - } vw, vh := ed.CanvasSize() sx, sy, _, vis := ed.Camera3D.Project([3]float32{2, 0, 0.3}, vw, vh) @@ -433,16 +432,16 @@ func TestPlaceModelsInTheEditorWindow(t *testing.T) { if len(crates) != 3 { t.Fatalf("crates after the press = %v", crates) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if len(objectsWith(ed, crateModel)) != 2 { t.Fatal("Undo did not take the placed crate back") } - app.Press("id:toolbar-redo") + redoInUI(app, ed) if got := objectsWith(ed, crateModel); !slices.Equal(got, crates) { t.Fatalf("crates after Redo = %v, want %v", got, crates) } - app.Press("id:tool3d-select") + app.Press("id:tool-select") // The drop lands on the frame's middle, where the view points. want, ok := ed.PlacementAt3D(vw/2, vh/2, vw, vh) if !ok { @@ -475,7 +474,7 @@ func TestPlaceModelsInTheEditorWindow(t *testing.T) { if marker.Model != crateModel.Path { t.Fatalf("marker after picking the crate = %+v", marker) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if marker, _, _ = ed.FindObject("marker"); marker.Model != "" { t.Fatalf("Undo left the marker's model %q", marker.Model) } @@ -619,11 +618,11 @@ func TestViewport3DModelsStripAndInspectorDetails(t *testing.T) { if len(afterDrag) != beforeCount+1 { t.Fatalf("dragging from MODELS strip left %d crates, want %d", len(afterDrag), beforeCount+1) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if len(objectsWith(ed, crateModel)) != beforeCount { t.Fatal("Undo did not remove model dragged from MODELS strip") } - app.Press("id:toolbar-redo") + redoInUI(app, ed) if got := objectsWith(ed, crateModel); !slices.Equal(got, afterDrag) { t.Fatalf("Redo after MODELS strip drag = %v, want %v", got, afterDrag) } diff --git a/packages/game/editor/navmesh3d_test.go b/packages/game/editor/navmesh3d_test.go index c04ea84fc..58d82eefe 100644 --- a/packages/game/editor/navmesh3d_test.go +++ b/packages/game/editor/navmesh3d_test.go @@ -274,7 +274,7 @@ func TestEditorNavMesh3DUIPanelBakeAndViewportOverlay(t *testing.T) { if app.Exists("id:navmesh-panel") { t.Fatal("navmesh-panel should start closed") } - app.Press("id:toolbar-navmesh-panel") + runEditorCommand(t, app, ed, editor.CmdNavMeshPanel) if !ed.NavMeshPanelOpen() || !app.Exists("id:navmesh-panel") { t.Fatal("expected navmesh-panel to open after pressing toolbar-navmesh-panel") } @@ -381,8 +381,8 @@ func TestEditorNavMesh3DUIPanelBakeAndViewportOverlay(t *testing.T) { baseFills, baseStrokes, baseLines, withFills, withStrokes, withLines) } - // Toggle the 3D navmesh overlay OFF via toolbar button and confirm overlay draw ops disappear. - app.Press("id:toolbar-navmesh-overlay") + // Toggle the 3D navmesh overlay OFF and confirm overlay draw ops disappear. + app.Post(func() { ed.SetShowNavMesh3D(false) }) app.Settle() if ed.ShowNavMesh3D { t.Fatal("expected ShowNavMesh3D false after toggling toolbar-navmesh-overlay") diff --git a/packages/game/editor/navregion2d_test.go b/packages/game/editor/navregion2d_test.go index 17455e1fd..f4b1f5058 100644 --- a/packages/game/editor/navregion2d_test.go +++ b/packages/game/editor/navregion2d_test.go @@ -400,7 +400,7 @@ func TestNavRegionUIWorkflowOverlayToggleAndTestPathTool(t *testing.T) { if !ed.ShowNavMesh2D { t.Fatal("expected ShowNavMesh2D true by default") } - app.Press("id:view-navmesh2d-overlay") + runEditorCommand(t, app, ed, editor.CmdToggleNavMesh2D) if ed.ShowNavMesh2D { t.Fatal("expected ShowNavMesh2D false after pressing overlay toggle") } @@ -408,7 +408,7 @@ func TestNavRegionUIWorkflowOverlayToggleAndTestPathTool(t *testing.T) { if len(opsOff) >= len(opsOn) { t.Fatalf("expected disabling 2D navmesh overlay to reduce canvas draw ops: on=%d off=%d", len(opsOn), len(opsOff)) } - app.Press("id:view-navmesh2d-overlay") + runEditorCommand(t, app, ed, editor.CmdToggleNavMesh2D) if !ed.ShowNavMesh2D { t.Fatal("expected ShowNavMesh2D true after pressing overlay toggle again") } @@ -425,8 +425,9 @@ func TestNavRegionUIWorkflowOverlayToggleAndTestPathTool(t *testing.T) { } checkOneUndoStep(t, app, ed, before) - // Activate Test Path tool via toolbar button, click start and end, then clear with Escape. - app.Press("id:tool-nav-test-path") + // Activate Test Path tool, click start and end, then clear with Escape. + app.Post(func() { ed.SetTool(editor.ToolNavTestPath) }) + app.Settle() if ed.Tool != editor.ToolNavTestPath { t.Fatalf("Tool = %v, want ToolNavTestPath", ed.Tool) } diff --git a/packages/game/editor/objectedit_test.go b/packages/game/editor/objectedit_test.go index 08e700598..d0247624e 100644 --- a/packages/game/editor/objectedit_test.go +++ b/packages/game/editor/objectedit_test.go @@ -550,6 +550,7 @@ func TestInspectorSetsSpriteOriginFlipAndMaterial(t *testing.T) { app.Post(func() { ed.Resolver = materialResolver{testResolver(), resource.NewLibrary(os.DirFS(dir))} }) + openAssetBrowserInUI(app, ed) app.Press("id:asset-actors-slime") app.Press("id:inspector-sprite-use-asset") hero, _, _ := ed.FindObject("hero") diff --git a/packages/game/editor/overlays_ui.go b/packages/game/editor/overlays_ui.go index b2ad8d03c..180df83f0 100644 --- a/packages/game/editor/overlays_ui.go +++ b/packages/game/editor/overlays_ui.go @@ -204,37 +204,58 @@ func viewportOverlaysBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64 OnPress: func() { zoomBy(1.25) }, }, barDivider(), - ui.Button{ + base.Switch{ TestID: "viewport-bar-snap", - TextFunc: func() string { + Label: ed.T("overlays.snapLabel"), + Checked: func() bool { _ = rev.Get() - return ed.T("overlays.snap") + return ed.SnapToGrid }, - LabelFunc: func() string { - _ = rev.Get() - return ed.T("overlays.snapLabel") + OnChange: func(on bool) { + ed.SetSnapToGrid(on) }, - Size: ui.SizeSmall, - Variant: ui.ButtonGhost, - Color: func() core.Color { + StyleFunc: func() core.Style { _ = rev.Get() + cur := ed.SpecPalette(cx) + bg := core.Transparent if ed.SnapToGrid { - return p.LineRaised + bg = cur.LineRaised + } + return core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), + Padding: core.Symmetric(0, specSpace8), + CornerRadius: specRadiusControl, + Background: bg, + Cursor: core.CursorPointer, + Hover: &core.Style{Background: cur.LineRaised}, + FocusVisible: cur.FocusRing(2), } - return core.Transparent - }, - TextStyle: core.Style{ - FontSize: 12, - FontWeight: 500, - Color: p.TextSecondary, - }, - Style: core.Style{ - Height: core.Pt(28), - Padding: core.Symmetric(0, 8), - CornerRadius: 6, }, - OnPress: func() { - ed.SetSnapToGrid(!ed.SnapToGrid) + Children: []core.Node{ + core.Text{ + ContentFunc: func() string { + _ = rev.Get() + return ed.T("overlays.snap") + }, + StyleFunc: func() core.Style { + _ = rev.Get() + cur := ed.SpecPalette(cx) + col := cur.TextFaint + if ed.SnapToGrid { + col = cur.TextPrimary + } + return core.Style{ + FontSize: 12, + FontWeight: core.FontWeightMedium, + Color: col, + } + }, + }, }, }, ui.Button{ @@ -255,7 +276,9 @@ func viewportOverlaysBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64 Color: p.TextMuted, }, Style: core.Style{ - Height: core.Pt(28), + Height: core.Pt(specRowHeight), + MinHeight: core.Pt(specRowHeight), + MinWidth: core.Pt(specRowHeight), Padding: core.Symmetric(0, 8), CornerRadius: 6, }, diff --git a/packages/game/editor/overrides_test.go b/packages/game/editor/overrides_test.go index ef727aabb..35bc685b6 100644 --- a/packages/game/editor/overrides_test.go +++ b/packages/game/editor/overrides_test.go @@ -119,6 +119,7 @@ func TestAcceptance1MoveInstancedChildWritesOverrideAndReverts(t *testing.T) { app := startEditorView(t, ed) // Place a scene instance via the File Browser quick-place button. + openFileBrowserInUI(app, ed) app.Press("id:files-place-scenes/slime.scene.yaml") if ed.BuildErr != nil { t.Fatalf("BuildErr after placing scene from file browser: %v", ed.BuildErr) @@ -531,6 +532,7 @@ func TestPlacePrefabFromAssetBrowserAndCanvas(t *testing.T) { ed.SetActiveLayer("actors") app := startEditorView(t, ed) + openAssetBrowserInUI(app, ed) app.Find("id:prefab-list") app.Press("id:prefab-place-coin") if ed.SelectedID == "" { @@ -632,6 +634,7 @@ func TestFileBrowserPlaceSceneButton(t *testing.T) { }, nsgotest.Size(1120, 680)) // Select slime scene in File Browser, then press the header Place button. + openFileBrowserInUI(app, ed) app.Press("id:files-row-scenes/slime.scene.yaml") if !app.Enabled("id:files-place-scene") { t.Fatal("files-place-scene should be enabled when another scene file is selected") diff --git a/packages/game/editor/parallax_test.go b/packages/game/editor/parallax_test.go index fbd1575dd..1e26779ae 100644 --- a/packages/game/editor/parallax_test.go +++ b/packages/game/editor/parallax_test.go @@ -191,7 +191,7 @@ func TestLayerInspectorEditsParallaxAndRepeatUndoably(t *testing.T) { // Undo all 3 edits (repeatY toggle, SetLayerRepeat, SetLayerParallax) and verify byte-for-byte restoration of the v2 YAML! for range 3 { - app.Press("id:toolbar-undo") + undoInUI(app, ed) } if ed.Doc.Version != 2 { t.Fatalf("Doc.Version after Undo = %d, want 2", ed.Doc.Version) @@ -206,7 +206,7 @@ func TestLayerInspectorEditsParallaxAndRepeatUndoably(t *testing.T) { // Redo brings parallax and version 3 back cleanly. for range 3 { - app.Press("id:toolbar-redo") + redoInUI(app, ed) } if ed.Doc.Version != sceneformat.CurrentVersion || ed.Doc.Layers[0].EffectiveParallaxX() != 0.5 || !ed.Doc.Layers[0].RepeatY { t.Fatalf("after Redo: version=%d layer=%+v", ed.Doc.Version, ed.Doc.Layers[0]) diff --git a/packages/game/editor/particles_test.go b/packages/game/editor/particles_test.go index db469403a..78126d93f 100644 --- a/packages/game/editor/particles_test.go +++ b/packages/game/editor/particles_test.go @@ -511,7 +511,7 @@ func TestParticleEditorUI(t *testing.T) { } // Open via toolbar button. - app.Press("id:toolbar-particles") + runEditorCommand(t, app, ed, editor.CmdParticleEditor) app.Settle() if !app.Exists("id:particles-panel") || !ed.ParticleEmitterOpen() { t.Fatalf("Particle Emitter panel did not open; status=%q", ed.Status) diff --git a/packages/game/editor/plugin_3d_test.go b/packages/game/editor/plugin_3d_test.go index 04a2e6026..3500363b8 100644 --- a/packages/game/editor/plugin_3d_test.go +++ b/packages/game/editor/plugin_3d_test.go @@ -196,7 +196,7 @@ func TestPluginTool3DDrawsAndReceivesPressRay(t *testing.T) { var withPlugin, withoutPlugin core.Drawing cw, ch := ed.CanvasSize() ed.DrawViewport(&withPlugin, core.Size{Width: core.Points(cw), Height: core.Points(ch)}) - app.Press("id:tool3d-select") + app.Press("id:tool-select") ed.DrawViewport(&withoutPlugin, core.Size{Width: core.Points(cw), Height: core.Points(ch)}) if len(withPlugin.Ops) <= len(withoutPlugin.Ops) { t.Fatalf("expected 3D plugin tool to emit draw ops: with=%d without=%d", len(withPlugin.Ops), len(withoutPlugin.Ops)) diff --git a/packages/game/editor/plugin_test.go b/packages/game/editor/plugin_test.go index 69a8e4bbc..e77bedce3 100644 --- a/packages/game/editor/plugin_test.go +++ b/packages/game/editor/plugin_test.go @@ -258,7 +258,7 @@ func TestSamplePluginAddsAPanelAnInspectorAndATool(t *testing.T) { if got := intField(ed, "hero", "hp"); got != 12 { t.Fatalf("hp after Heal All = %d, want 12", got) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := intField(ed, "hero", "hp"); got != 7 { t.Fatalf("hp after Undo = %d, want 7", got) } @@ -266,15 +266,20 @@ func TestSamplePluginAddsAPanelAnInspectorAndATool(t *testing.T) { t.Fatalf("hp field after Undo shows %q, want 7", got) } - // The plugin's tool sits in the tool bar, places an object where the viewport is pressed and names itself in the status bar. + // The plugin's tool activates via SetPluginTool/command palette, places an object where the viewport is pressed and names itself in the status bar. if draws != 0 { t.Fatalf("the tool drew %d times before it was chosen", draws) } - app.Press("id:tool-health-spawn") + app.Post(func() { + if err := ed.SetPluginTool("health", "spawn"); err != nil { + t.Error(err) + } + }) + app.Settle() if plugin, id, ok := ed.PluginTool(); !ok || plugin != "health" || id != "spawn" || ed.Tool != editor.ToolPlugin { t.Fatalf("PluginTool = %q %q %v, Tool %v", plugin, id, ok, ed.Tool) } - if got := allText(app.Find("id:editor-status")); !strings.Contains(got, "Tool: Spawn") { + if got := allText(app.Find("id:editor-status")); !strings.Contains(got, "Spawn") { t.Fatalf("status = %q, want it to name the Spawn tool", got) } if draws == 0 { @@ -290,7 +295,7 @@ func TestSamplePluginAddsAPanelAnInspectorAndATool(t *testing.T) { if wx, wy := ed.CanvasToWorld(100, 60); spawned.X != wx || spawned.Y != wy || intField(ed, spawned.ID, "hp") != 5 { t.Fatalf("spawned %+v, want at (%v, %v) with 5 hp", spawned, wx, wy) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := healthObjects(ed); len(got) != before { t.Fatalf("Undo left the spawned object: %v", got) } @@ -313,8 +318,8 @@ func TestPluginsFollowTheProjectsEditorPlugins(t *testing.T) { return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) - // A registered plugin the project does not name stays off: no panel, no tool, the generic fields. - if app.Exists("id:plugin-panel-health-overview") || app.Exists("id:tool-health-spawn") || app.Exists("id:inspector-plugin-health-health") { + // A registered plugin the project does not name stays off: no panel, no inspector, the generic fields. + if app.Exists("id:plugin-panel-health-overview") || app.Exists("id:inspector-plugin-health-health") { t.Fatal("a plugin the project does not name is on") } if !app.Exists("id:inspector-comp-health-hp") { @@ -331,23 +336,28 @@ func TestPluginsFollowTheProjectsEditorPlugins(t *testing.T) { if !ed.PluginEnabled("health") || ed.Project.Editor == nil || !reflect.DeepEqual(ed.Project.Editor.Plugins, []string{"health"}) { t.Fatalf("after turning it on: enabled %v, project editor %+v", ed.PluginEnabled("health"), ed.Project.Editor) } - if !app.Exists("id:plugin-panel-health-overview") || !app.Exists("id:tool-health-spawn") || !app.Exists("id:inspector-plugin-health-health") { - t.Fatal("turning the plugin on did not bring in its panel, tool and inspector") + if !app.Exists("id:plugin-panel-health-overview") || !app.Exists("id:inspector-plugin-health-health") { + t.Fatal("turning the plugin on did not bring in its panel and inspector") } if got := ed.History.UndoLabel(); got != "Turn on plugin health" { t.Fatalf("UndoLabel = %q", got) } - app.Press("id:tool-health-spawn") + app.Post(func() { + if err := ed.SetPluginTool("health", "spawn"); err != nil { + t.Error(err) + } + }) + app.Settle() // Undo turns it off again, ends its tool and restores the generic fields. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if ed.PluginEnabled("health") || ed.Project.Editor != nil { t.Fatalf("after Undo: enabled %v, project editor %+v", ed.PluginEnabled("health"), ed.Project.Editor) } if ed.Tool != editor.ToolSelect { t.Fatalf("Tool after its plugin turned off = %v, want ToolSelect", ed.Tool) } - if app.Exists("id:plugin-panel-health-overview") || app.Exists("id:tool-health-spawn") || !app.Exists("id:inspector-comp-health-hp") { + if app.Exists("id:plugin-panel-health-overview") || !app.Exists("id:inspector-comp-health-hp") { t.Fatal("Undo left the plugin's views in place") } if ed.ProjectDirty() { @@ -355,8 +365,8 @@ func TestPluginsFollowTheProjectsEditorPlugins(t *testing.T) { } // Save writes the plugin into game.yaml, where the next OpenProject finds it. - app.Press("id:toolbar-redo") - app.Press("id:toolbar-save") + redoInUI(app, ed) + saveInUI(app, ed) f, err := project.Check(os.DirFS(dir)) if err != nil || f.Editor == nil || !reflect.DeepEqual(f.Editor.Plugins, []string{"health"}) { t.Fatalf("saved project: %+v, %v", f, err) @@ -628,17 +638,19 @@ func TestPluginToolIsIdleWhilePlayingAndIn3D(t *testing.T) { app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) - app.Press("id:tool-health-spawn") + app.Post(func() { + if err := ed.SetPluginTool("health", "spawn"); err != nil { + t.Error(err) + } + }) + app.Settle() if draws == 0 { t.Fatal("the active tool did not draw in 2D") } before := len(healthObjects(ed)) - // In 3D the plugin tools leave the tool bar, the tool does not draw and a press does not reach it. + // In 3D the 2D-only plugin tool does not draw and a press does not reach it. app.Press("id:view-mode-3d") - if app.Exists("id:tool-health-spawn") { - t.Fatal("the plugin tool is in the tool bar in 3D") - } draws = 0 app.Post(func() { ed.HandleCanvasPress(100, 60) }) app.Settle() @@ -649,8 +661,8 @@ func TestPluginToolIsIdleWhilePlayingAndIn3D(t *testing.T) { t.Fatalf("a press in 3D spawned: %d health objects, want %d", got, before) } app.Press("id:view-mode-2d") - if !app.Exists("id:tool-health-spawn") || draws == 0 { - t.Fatalf("back in 2D: tool shown %v, draws %d", app.Exists("id:tool-health-spawn"), draws) + if draws == 0 { + t.Fatalf("back in 2D: draws %d, want > 0", draws) } // While playing the tool does not draw, a press does not reach it, and the plugin's inspector controls are off. The press in 3D picked empty space, so the hero is selected again first. @@ -732,7 +744,7 @@ func TestPluginPanelsStayMountedWhileOthersComeAndGo(t *testing.T) { if app.Exists("id:stats-main") || !app.Exists("id:notes-main") { t.Fatal("turning stats off did not leave only notes' panel") } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if !app.Exists("id:notes-main") || !app.Exists("id:stats-main") { t.Fatal("undoing stats' removal did not bring its panel back") } diff --git a/packages/game/editor/problems.go b/packages/game/editor/problems.go index b36556f37..4b98f3f8c 100644 --- a/packages/game/editor/problems.go +++ b/packages/game/editor/problems.go @@ -630,6 +630,9 @@ func (e *Editor) OpenProblem(p assetcheck.Problem) error { return nil } e.selectFile(p.File) + if !isProjectScene(e.Project, p.File) { + e.fileBrowserOpen = true + } e.Status = "Selected " + loc e.notify() return nil diff --git a/packages/game/editor/problems_test.go b/packages/game/editor/problems_test.go index a8791a18f..878395cda 100644 --- a/packages/game/editor/problems_test.go +++ b/packages/game/editor/problems_test.go @@ -135,8 +135,8 @@ func TestProblemsPanelMissingAtlasFrameFixAndSave(t *testing.T) { if app.Exists("id:problems-panel") { t.Fatal("problems panel shown before a project is open") } - if app.Exists("id:status-problems") { - t.Fatal("status-problems shown before a project is open") + if got := strings.TrimSpace(allText(app.Find("id:status-problems"))); got != "No problems" { + t.Fatalf("status-problems before project open = %q, want No problems", got) } app.Post(func() { @@ -200,7 +200,7 @@ func TestProblemsPanelMissingAtlasFrameFixAndSave(t *testing.T) { ed.Rebuild() }) app.Settle() - app.Press("id:toolbar-save") + saveInUI(app, ed) app.WaitUntil(10*time.Second, func() bool { return !ed.CheckingProblems() && ed.ProblemCount() == 0 }) @@ -209,8 +209,8 @@ func TestProblemsPanelMissingAtlasFrameFixAndSave(t *testing.T) { if len(ed.Problems()) != 0 { t.Fatalf("problems after fix and save = %+v, want empty", ed.Problems()) } - if got := strings.TrimSpace(allText(app.Find("id:status-problems"))); got != "Problems: 0" { - t.Fatalf("status-problems after fix = %q, want %q", got, "Problems: 0") + if got := strings.TrimSpace(allText(app.Find("id:status-problems"))); got != "No problems" { + t.Fatalf("status-problems after fix = %q, want %q", got, "No problems") } if !app.Exists("id:problems-empty") { t.Fatal("problems-empty not shown after clearing all problems") diff --git a/packages/game/editor/project.go b/packages/game/editor/project.go index 811935d70..76c6d9a5e 100644 --- a/packages/game/editor/project.go +++ b/packages/game/editor/project.go @@ -53,7 +53,9 @@ func (e *Editor) openProject(path, scene string, withScene bool) error { case withScene: raw, err := os.ReadFile(scene) if err != nil { - return loaderr.Locate(err, scene, nil, "check that the scene exists at this path and can be read") + openErr := loaderr.Locate(err, scene, nil, "check that the scene exists at this path and can be read") + e.recordSceneOpenError(scene, openErr) + return openErr } doc, err := sceneformat.ParseWith(raw, sceneformat.ParseOptions{ File: scene, @@ -64,12 +66,16 @@ func (e *Editor) openProject(path, scene string, withScene bool) error { if isSceneConflictFile(raw) { conflictedScene = scene } else { - return loaderr.WithFile(err, scene) + openErr := loaderr.WithFile(err, scene) + e.recordSceneOpenError(scene, openErr) + return openErr } } else { enc, err := sceneformat.Encode(doc) if err != nil { - return loaderr.WithFile(err, scene) + openErr := loaderr.WithFile(err, scene) + e.recordSceneOpenError(scene, openErr) + return openErr } openedDoc, openedSaved, openedPath, opened = doc, enc, scene, true } @@ -79,7 +85,9 @@ func (e *Editor) openProject(path, scene string, withScene bool) error { sceneFile := filepath.Join(filepath.Dir(path), filepath.FromSlash(s.Path)) raw, err := os.ReadFile(sceneFile) if err != nil { - return fmt.Errorf("editor: main scene %q: %w", s.Name, loaderr.Locate(err, sceneFile, nil, "check that the scene exists at this path and can be read")) + openErr := fmt.Errorf("editor: main scene %q: %w", s.Name, loaderr.Locate(err, sceneFile, nil, "check that the scene exists at this path and can be read")) + e.recordSceneOpenError(sceneFile, openErr) + return openErr } doc, err := sceneformat.ParseWith(raw, sceneformat.ParseOptions{ File: sceneFile, @@ -90,12 +98,16 @@ func (e *Editor) openProject(path, scene string, withScene bool) error { if isSceneConflictFile(raw) { conflictedScene = sceneFile } else { - return fmt.Errorf("editor: main scene %q: %w", s.Name, loaderr.WithFile(err, sceneFile)) + openErr := fmt.Errorf("editor: main scene %q: %w", s.Name, loaderr.WithFile(err, sceneFile)) + e.recordSceneOpenError(sceneFile, openErr) + return openErr } } else { enc, err := sceneformat.Encode(doc) if err != nil { - return fmt.Errorf("editor: main scene %q: %w", s.Name, loaderr.WithFile(err, sceneFile)) + openErr := fmt.Errorf("editor: main scene %q: %w", s.Name, loaderr.WithFile(err, sceneFile)) + e.recordSceneOpenError(sceneFile, openErr) + return openErr } openedDoc, openedSaved, openedPath, opened = doc, enc, sceneFile, true } @@ -103,6 +115,9 @@ func (e *Editor) openProject(path, scene string, withScene bool) error { } } } + e.sceneOpenErr = nil + e.projectLoading = false + e.projectLoadingPath = "" // Save the views of the project closing before replacing tabs. e.saveViewStateQuietly() if e.playing { diff --git a/packages/game/editor/project_assets_test.go b/packages/game/editor/project_assets_test.go index a10c65599..22151222e 100644 --- a/packages/game/editor/project_assets_test.go +++ b/packages/game/editor/project_assets_test.go @@ -72,6 +72,7 @@ func TestProjectAssetsDrawTheProjectsAtlasesInTheEditor(t *testing.T) { app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1120, 680)) + openAssetBrowserInUI(app, ed) app.Find("id:asset-actors-hero") app.Find("id:asset-actors-crate") drawn := func() int { @@ -99,7 +100,7 @@ func TestProjectAssetsDrawTheProjectsAtlasesInTheEditor(t *testing.T) { if n := drawn(); n != 2 { t.Fatalf("after placing the crate the viewport draws the project's image %d times, want 2", n) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if obj, _, _ := ed.FindObject(id); obj != nil { t.Fatalf("Undo left the instance %q", id) } diff --git a/packages/game/editor/project_settings_panel_test.go b/packages/game/editor/project_settings_panel_test.go index 059965422..20784e71b 100644 --- a/packages/game/editor/project_settings_panel_test.go +++ b/packages/game/editor/project_settings_panel_test.go @@ -97,7 +97,7 @@ func TestProjectSettingsPanelEditSaveSyncAndUndo(t *testing.T) { } // Open the Project Settings panel via the toolbar button. - app.Press("id:toolbar-project-settings") + runEditorCommand(t, app, ed, editor.CmdProjectSettings) app.Settle() if !app.Exists("id:project-settings-panel") { t.Fatal("pressing toolbar-project-settings did not open the panel") @@ -172,7 +172,7 @@ func TestProjectSettingsPanelEditSaveSyncAndUndo(t *testing.T) { } // Save via toolbar Save and read back game.yaml and nsgo.yaml from disk. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() // Canonical save notice disappears after the first save. @@ -211,50 +211,50 @@ func TestProjectSettingsPanelEditSaveSyncAndUndo(t *testing.T) { // Undo each change one by one and verify each restores cleanly: // 1. Undo plugin toggle - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if ed.PluginEnabled("tools") { t.Fatal("Undo did not restore plugin 'tools' to off") } // 2. Undo mainScene change - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if ed.Project.Autoload.MainScene != "room" { t.Fatalf("Undo did not restore mainScene: got %q, want room", ed.Project.Autoload.MainScene) } // 3. Undo display height - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if ed.Project.Display == nil || ed.Project.Display.Height != 360 { t.Fatalf("Undo did not restore display height: got %+v", ed.Project.Display) } // 4. Undo display width - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if ed.Project.Display == nil || ed.Project.Display.Width != 640 { t.Fatalf("Undo did not restore display width: got %+v", ed.Project.Display) } // 5. Undo display enabled - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if ed.Project.Display != nil { t.Fatalf("Undo did not restore Display to nil: got %+v", ed.Project.Display) } // 6. Undo window appearance - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if ed.Project.Window.Appearance != "" { t.Fatalf("Undo did not restore Window.Appearance: got %q", ed.Project.Window.Appearance) } // 7. Undo project name - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if ed.Project.Name != "Demo" { t.Fatalf("Undo did not restore Project.Name: got %q, want Demo", ed.Project.Name) } // Saving after full Undo writes restored values to both game.yaml and nsgo.yaml. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() restored, err := project.Check(os.DirFS(dir)) if err != nil { @@ -287,7 +287,7 @@ func TestProjectSettingsPanelRefusesInvalidValuesWithoutMutatingProject(t *testi return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 900)) - app.Press("id:toolbar-project-settings") + runEditorCommand(t, app, ed, editor.CmdProjectSettings) app.Settle() // Enter an invalid ID containing spaces. @@ -466,7 +466,7 @@ func TestProjectSettingsWindowDisplayAutoloadAndPluginsAllFields(t *testing.T) { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 900)) - app.Press("id:toolbar-project-settings") + runEditorCommand(t, app, ed, editor.CmdProjectSettings) app.Press("id:project-settings-tab-autoload") app.Settle() @@ -509,7 +509,7 @@ func TestProjectSettingsWindowDisplayAutoloadAndPluginsAllFields(t *testing.T) { } // Save, verify ProjectCanonicalSavePending becomes false, then reopen and verify it resets to true. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() if ed.ProjectCanonicalSavePending() { t.Fatal("ProjectCanonicalSavePending should be false after Save") diff --git a/packages/game/editor/project_test.go b/packages/game/editor/project_test.go index 791d59742..5f5ba6468 100644 --- a/packages/game/editor/project_test.go +++ b/packages/game/editor/project_test.go @@ -173,7 +173,7 @@ func TestToolbarSaveWritesAnEditedProjectOnly(t *testing.T) { }, nsgotest.Size(1120, 680)) // Saving the scene leaves an unedited game.yaml as written, its comment included. - app.Press("id:toolbar-save") + saveInUI(app, ed) data, err := os.ReadFile(filepath.Join(dir, project.FileName)) if err != nil { t.Fatal(err) @@ -188,7 +188,7 @@ func TestToolbarSaveWritesAnEditedProjectOnly(t *testing.T) { } }) app.Settle() - app.Press("id:toolbar-save") + saveInUI(app, ed) f, err := project.Check(os.DirFS(dir)) if err != nil || f.AppVersion != "1.1.0" { t.Fatalf("after Save: %+v, %v", f, err) @@ -245,7 +245,7 @@ func TestToolbarSaveWritesAProjectWithoutAMainScene(t *testing.T) { } }) app.Settle() - app.Press("id:toolbar-save") + saveInUI(app, ed) f, err := project.Check(os.DirFS(dir)) if err != nil || f.AppVersion != "1.1.0" { t.Fatalf("after Save: %+v, %v", f, err) diff --git a/packages/game/editor/refs_test.go b/packages/game/editor/refs_test.go index 86c1f78e7..d35ab1107 100644 --- a/packages/game/editor/refs_test.go +++ b/packages/game/editor/refs_test.go @@ -439,6 +439,7 @@ func TestFileBrowserMovesAFile(t *testing.T) { }) app.Settle() + openFileBrowserInUI(app, ed) if app.Enabled("id:files-move") { t.Fatal("Move is enabled with nothing selected") } @@ -458,7 +459,7 @@ func TestFileBrowserMovesAFile(t *testing.T) { t.Fatal("the file list does not show the new name") } - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() if data, err := os.ReadFile(other); err != nil || !strings.Contains(string(data), "material: materials/stone.material.yaml") { t.Fatalf("other.scene.yaml after undo (%v):\n%s", err, data) diff --git a/packages/game/editor/remote_test.go b/packages/game/editor/remote_test.go index 68ac1e220..98ec2dd38 100644 --- a/packages/game/editor/remote_test.go +++ b/packages/game/editor/remote_test.go @@ -471,7 +471,7 @@ func TestRemoteSceneTreeInspectorStepAndLiveChanges(t *testing.T) { } // One Undo restores the scene document byte-for-byte! - app.Press("id:toolbar-undo") + undoInUI(app, ed) app.Settle() afterUndo, err := sceneformat.Encode(ed.Doc) if err != nil { diff --git a/packages/game/editor/rig_test.go b/packages/game/editor/rig_test.go index d30d86214..169447756 100644 --- a/packages/game/editor/rig_test.go +++ b/packages/game/editor/rig_test.go @@ -545,6 +545,7 @@ func TestRigPanelUIWorkflow(t *testing.T) { }, nsgotest.Size(1280, 820)) // Select runner.skel.yaml in FilesView and press Open Rig. + openFileBrowserInUI(app, ed) app.Press("id:files-row-rigs/runner.skel.yaml") app.Press("id:files-open-rig") if !ed.RigOpen() { diff --git a/packages/game/editor/rooms_test.go b/packages/game/editor/rooms_test.go index c6b38a82f..7a778cf40 100644 --- a/packages/game/editor/rooms_test.go +++ b/packages/game/editor/rooms_test.go @@ -77,11 +77,11 @@ func TestViewportCameraBoundsDragSavesReloadsAndUndoes(t *testing.T) { } // Undo restores the original bounds; Redo restores the resized bounds. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if ed.Doc.Camera.Bounds == nil || *ed.Doc.Camera.Bounds != origBounds { t.Fatalf("bounds after Undo = %+v, want %+v", ed.Doc.Camera.Bounds, origBounds) } - app.Press("id:toolbar-redo") + redoInUI(app, ed) if ed.Doc.Camera.Bounds == nil || *ed.Doc.Camera.Bounds != wantAfterResize { t.Fatalf("bounds after Redo = %+v, want %+v", ed.Doc.Camera.Bounds, wantAfterResize) } @@ -230,6 +230,7 @@ func TestRoomsOpenRoundTripUnchangedAndProjectBrowser(t *testing.T) { return editor.EditorView(cx, projEd) }, nsgotest.Size(1280, 800)) + openFileBrowserInUI(app, projEd) app.DoublePress("id:files-row-scenes/castle.rooms.yaml") app.Settle() if projEd.Rooms() == nil || len(projEd.Rooms().Rooms) != 2 { @@ -418,7 +419,7 @@ func TestRoomsViewportCreateMoveResizeSnapDeleteAndUndo(t *testing.T) { if ed.Rooms().Room("room_2") != nil || len(ed.Rooms().Rooms) != 1 { t.Fatalf("expected room_2 deleted, got %+v", ed.Rooms().Rooms) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if r := ed.Rooms().Room("room_2"); r == nil || r.X != 208 || r.Width != 192 { t.Fatalf("expected Undo to restore room_2, got %+v", r) } diff --git a/packages/game/editor/run_output_test.go b/packages/game/editor/run_output_test.go index 64b4c6494..5d6687e6b 100644 --- a/packages/game/editor/run_output_test.go +++ b/packages/game/editor/run_output_test.go @@ -148,32 +148,25 @@ func TestRunFixtureGameDevStreamsOutputAndStopsCleanly(t *testing.T) { return editor.EditorView(cx, ed) }, nsgotest.Size(1400, 900)) - if !app.Exists("id:toolbar-run") { - t.Fatal("expected toolbar-run button before running") - } if !app.Exists("id:toolbar-play") { t.Fatal("expected existing toolbar-play button to remain untouched") } - // Output panel starts collapsed so it does not crowd other docked panels, and opens via the toolbar button or Run. + // Output panel starts collapsed so it does not crowd other docked panels, and opens via the status bar Output button or Run. if app.Exists("id:output-panel") { t.Fatal("expected Output panel collapsed before toggling Output or running the game") } - app.Press("id:toolbar-output") + app.Press("id:status-output") app.Settle() if !app.Exists("id:output-panel") { t.Fatal("expected Output panel docked below the viewport after toggling Output") } - // Launch real `go tool game dev` via the toolbar Run button. - app.Press("id:toolbar-run") - app.Settle() + // Launch real `go tool game dev` via CmdRunGame. + runEditorCommand(t, app, ed, editor.CmdRunGame) if !ed.GameRunning() { t.Fatalf("expected game to be running; output=%+v", ed.OutputEntries()) } - if !app.Exists("id:toolbar-stop-game") { - t.Fatal("expected toolbar-stop-game button while game is running") - } // Wait for streamed stdout, stderr, and both parent + grandchild PID files. var parentPID, childPID int @@ -212,15 +205,11 @@ func TestRunFixtureGameDevStreamsOutputAndStopsCleanly(t *testing.T) { t.Fatalf("output panel missing stderr line:\n%s", panelText) } - // Stop the game via the toolbar Stop Game button. - app.Press("id:toolbar-stop-game") - app.Settle() + // Stop the game via CmdStopGame. + runEditorCommand(t, app, ed, editor.CmdStopGame) if ed.GameRunning() { - t.Fatal("expected GameRunning() == false after pressing Stop Game") - } - if !app.Exists("id:toolbar-run") { - t.Fatal("expected toolbar-run button to return after stopping") + t.Fatal("expected GameRunning() == false after stopping game") } // Verify neither the `game dev` process nor its grandchild process survived. @@ -359,10 +348,9 @@ func TestRunGameShortcutF5AndStartAtOpenScene(t *testing.T) { if err := ed.OpenFile(filepath.Join(dir, "scenes", "other.scene.yaml")); err != nil { t.Fatal(err) } - app.Press("id:toolbar-run-open-scene") - app.Settle() + runEditorCommand(t, app, ed, editor.CmdRunOpenScene) if !ed.RunStartAtOpenScene() { - t.Fatal("expected toolbar-run-open-scene to enable RunStartAtOpenScene") + t.Fatal("expected CmdRunOpenScene to enable RunStartAtOpenScene") } app.Key("f5") app.Settle() @@ -458,8 +446,8 @@ func TestOutputPanelKeepsTwoEditorErrorsFilterClearAndFileLineNav(t *testing.T) t.Fatalf("OutputEntries after repeated identical error = %d, want 4", got) } - // Open the Output panel via the toolbar toggle; errors recorded while closed must be present. - app.Press("id:toolbar-output") + // Open the Output panel via the status bar toggle; errors recorded while closed must be present. + app.Press("id:status-output") app.Settle() panelText := allText(app.Find("id:output-panel")) if !strings.Contains(panelText, "first editor error") || !strings.Contains(panelText, "second editor error") { diff --git a/packages/game/editor/scenefile_test.go b/packages/game/editor/scenefile_test.go index b326c3cd4..03e4630ea 100644 --- a/packages/game/editor/scenefile_test.go +++ b/packages/game/editor/scenefile_test.go @@ -362,8 +362,11 @@ func TestUnsavedMarkerAndModS(t *testing.T) { if app.Exists("id:toolbar-unsaved") || app.Title != "scenes/room.yaml - NSGo Scene Editor" { t.Fatalf("a clean scene shows the marker (%v), title %q", app.Exists("id:toolbar-unsaved"), app.Title) } - if got := app.Find("id:toolbar-scene-path").Text; got != "scenes/room.yaml" { - t.Fatalf("the toolbar shows %q, want the scene's path", got) + if got := strings.TrimSpace(allText(app.Find("id:toolbar-file"))); got != "room" { + t.Fatalf("the header breadcrumb shows %q, want room", got) + } + if got := strings.TrimSpace(allText(app.Find("id:rail-file-scene"))); got != "scenes/room.yaml" { + t.Fatalf("the left rail FILES shows %q, want scenes/room.yaml", got) } app.Press("id:toolbar-file") app.Settle() @@ -382,13 +385,11 @@ func TestUnsavedMarkerAndModS(t *testing.T) { if !app.Exists("id:toolbar-unsaved") || app.Title != "scenes/room.yaml* - NSGo Scene Editor" { t.Fatalf("an edit shows no marker (%v), title %q", app.Exists("id:toolbar-unsaved"), app.Title) } - app.Press("id:toolbar-undo") - app.Settle() + undoInUI(app, ed) if app.Exists("id:toolbar-unsaved") || strings.Contains(app.Title, "*") { t.Fatalf("undoing back to the saved state keeps the marker, title %q", app.Title) } - app.Press("id:toolbar-redo") - app.Settle() + redoInUI(app, ed) if !app.Exists("id:toolbar-unsaved") { t.Fatal("redoing the edit shows no marker") } @@ -424,8 +425,7 @@ func TestUnsavedMarkerAndModS(t *testing.T) { if obj, _, _ := ed.FindObject("hero"); obj.X != 70 || app.Exists("id:toolbar-unsaved") { t.Fatalf("after Revert hero is at %v, marker %v", obj.X, app.Exists("id:toolbar-unsaved")) } - app.Press("id:toolbar-undo") - app.Settle() + undoInUI(app, ed) if obj, _, _ := ed.FindObject("hero"); obj.X != 1 || !app.Exists("id:toolbar-unsaved") { t.Fatalf("after undoing Revert hero is at %v, marker %v", obj.X, app.Exists("id:toolbar-unsaved")) } @@ -436,6 +436,7 @@ func TestOpenFromTheFileBrowserOpensTabs(t *testing.T) { ed, dir := openTestProject(t) _ = ed.SetAutoSave(false) app := startEditorApp(t, ed) + openFileBrowserInUI(app, ed) edit := func(x float32) { app.Post(func() { if err := ed.MoveObject("hero", x, x); err != nil { @@ -540,8 +541,8 @@ func TestNewSceneAndSaveAsFromTheToolbar(t *testing.T) { app.Settle() app.Press("id:scene-path-confirm") app.Settle() - if ed.ScenePath != "levels/first.scene.yaml" || app.Find("id:toolbar-scene-path").Text != "levels/first.scene.yaml" { - t.Fatalf("after New: ScenePath %q, status %q", ed.ScenePath, ed.Status) + if got := strings.TrimSpace(allText(app.Find("id:toolbar-file"))); ed.ScenePath != "levels/first.scene.yaml" || got != "first" { + t.Fatalf("after New: ScenePath %q, toolbar-file %q, status %q", ed.ScenePath, got, ed.Status) } app.Post(func() { if _, err := ed.PlaceObject("main", sceneformat.ObjectDoc{ID: "door", X: 10, Y: 20}); err != nil { @@ -549,8 +550,7 @@ func TestNewSceneAndSaveAsFromTheToolbar(t *testing.T) { } }) app.Settle() - app.Press("id:toolbar-save") - app.Settle() + saveInUI(app, ed) if ed.SceneDirty() { t.Fatalf("Save left the new scene dirty, status %q", ed.Status) } @@ -825,6 +825,7 @@ func TestSearchResultOpensAnotherSceneInATab(t *testing.T) { } }) app.Settle() + openFileBrowserInUI(app, ed) app.Press("id:files-search") app.Settle() app.Type("id:project-search-input", "goblin_king") diff --git a/packages/game/editor/scenesettings_test.go b/packages/game/editor/scenesettings_test.go index e0def9974..55cae4596 100644 --- a/packages/game/editor/scenesettings_test.go +++ b/packages/game/editor/scenesettings_test.go @@ -413,11 +413,11 @@ func TestViewportCameraHandleDragUpdatesCameraAndIsUndoable(t *testing.T) { } // Undo restores pre-drag camera position; Redo restores dragged position. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if !near(ed.Doc.Camera.X, beforeCam.X, 1e-2) || !near(ed.Doc.Camera.Y, beforeCam.Y, 1e-2) { t.Fatalf("camera after Undo = (%v, %v), want (%v, %v)", ed.Doc.Camera.X, ed.Doc.Camera.Y, beforeCam.X, beforeCam.Y) } - app.Press("id:toolbar-redo") + redoInUI(app, ed) if !near(ed.Doc.Camera.X, beforeCam.X+60, 1e-2) || !near(ed.Doc.Camera.Y, beforeCam.Y+30, 1e-2) { t.Fatalf("camera after Redo = (%v, %v), want (%v, %v)", ed.Doc.Camera.X, ed.Doc.Camera.Y, beforeCam.X+60, beforeCam.Y+30) } diff --git a/packages/game/editor/scenetree.go b/packages/game/editor/scenetree.go index 8bc6f80c1..a008e011a 100644 --- a/packages/game/editor/scenetree.go +++ b/packages/game/editor/scenetree.go @@ -148,7 +148,10 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No // A press on a row selects its object(s) in the editor (supporting Shift/Mod multi-selection), or makes its layer the active one. // While connection target pick mode is active, pressing an object row picks it as the target without changing SelectedID, and pressing a layer row is ignored so pick mode and SelectedID stay intact. var ignorePickKey sceneTreeKey + var syncingFromEditor bool syncTreeToEditor := func() { + syncingFromEditor = true + defer func() { syncingFromEditor = false }() ids := ed.SelectedIDs() if len(ids) == 0 { selection.Clear() @@ -176,6 +179,9 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No keys := selection.Keys() chosen := selection.Has(cur) cx.Untrack(func() { + if syncingFromEditor { + return + } if ed.PickingConnectionTarget() { if cur == (sceneTreeKey{}) { return @@ -202,10 +208,13 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No if cur.layer != "" && cur.id == "" && chosen { // A layer's row is selected in place of any object selection. if selection.Len() != 1 { + syncingFromEditor = true selection.Set(cur) + syncingFromEditor = false } ed.ClearSelection() ed.SetActiveLayer(cur.layer) + ed.SetRightRailTab(RightTabInspector) return } objIDs := make([]string, 0, len(keys)) @@ -222,6 +231,7 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No if ed.SelectedID != primary || !sameIDSet(ed.SelectedIDs(), objIDs) { ed.SelectObjectsWithPrimary(objIDs, primary) } + ed.SetRightRailTab(RightTabInspector) return } if cur.id != "" && !chosen && ed.SelectionCount() > 0 { @@ -248,8 +258,10 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No } } if cur, _ := selection.Cursor().(sceneTreeKey); hasObj || cur.id != "" { + syncingFromEditor = true selection.Clear() selection.SetCursor(nil) + syncingFromEditor = false } return } @@ -280,6 +292,7 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No if len(wantKeys) == 0 { return } + syncingFromEditor = true selection.Set(wantKeys...) if pk.id != "" { selection.SetCursor(pk) @@ -287,6 +300,7 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No listRef.ScrollToIndexAt(row, 0.5, 0, false) } } + syncingFromEditor = false }) }) @@ -331,63 +345,72 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No return core.View{ TestID: "scene-tree-panel", - Style: core.Style{ - Width: core.Pt(220), - FlexGrow: 1, - FlexBasis: core.Pt(0), - Background: colors.Inset(), - Borders: core.Edges{Right: 1}, - BorderColor: colors.Line(), - Padding: core.All(8), - Gap: 6, + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + return core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + MinHeight: core.Pt(0), + Background: cur.Bg, + Padding: core.Symmetric(0, specSpace4), + Gap: specSpace4, + } }, Children: []core.Node{ - ui.HStack{ - Gap: 4, - Children: []core.Node{ - ui.ToggleButton{ - TestID: "scene-tree-tab-local", - Text: ed.T("sceneTree.title"), - On: func() bool { - _ = rev.Get() - return ed.SceneTreeTab() == SceneTreeLocal - }, - OnChange: func(on bool) { - if on { - ed.SetSceneTreeTab(SceneTreeLocal) - } - }, - }, - ui.ToggleButton{ - TestID: "scene-tree-tab-remote", - Text: ed.T("sceneTree.remote"), - On: func() bool { - _ = rev.Get() - return ed.SceneTreeTab() == SceneTreeRemote - }, - OnChange: func(on bool) { - if on { - ed.SetSceneTreeTab(SceneTreeRemote) - } - }, - }, - core.Show{ - When: func() bool { - _ = rev.Get() - return ed.RemoteConnected() - }, - Then: func(cx *core.Scope) core.Node { - return core.View{ - TestID: "scene-tree-remote-live-dot", - Style: core.Style{ - Width: core.Pt(7), - Height: core.Pt(7), - CornerRadius: 4, - Background: colors.Up(), + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.RemoteConnected() || ed.SceneTreeTab() == SceneTreeRemote + }, + Then: func(cx *core.Scope) core.Node { + return ui.HStack{ + Gap: 4, + Children: []core.Node{ + ui.ToggleButton{ + TestID: "scene-tree-tab-local", + Text: ed.T("sceneTree.title"), + On: func() bool { + _ = rev.Get() + return ed.SceneTreeTab() == SceneTreeLocal }, - } + OnChange: func(on bool) { + if on { + ed.SetSceneTreeTab(SceneTreeLocal) + } + }, + }, + ui.ToggleButton{ + TestID: "scene-tree-tab-remote", + Text: ed.T("sceneTree.remote"), + On: func() bool { + _ = rev.Get() + return ed.SceneTreeTab() == SceneTreeRemote + }, + OnChange: func(on bool) { + if on { + ed.SetSceneTreeTab(SceneTreeRemote) + } + }, + }, + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.RemoteConnected() + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + TestID: "scene-tree-remote-live-dot", + Style: core.Style{ + Width: core.Pt(7), + Height: core.Pt(7), + CornerRadius: 4, + Background: colors.Up(), + }, + } + }, + }, }, - }, + } }, }, core.Show{ @@ -400,7 +423,7 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No }, Else: func(cx *core.Scope) core.Node { return core.View{ - Style: core.Style{FlexGrow: 1, FlexBasis: core.Pt(0), Gap: 4}, + Style: core.Style{FlexGrow: 1, FlexBasis: core.Pt(0), MinHeight: core.Pt(0), Gap: 4}, Children: []core.Node{ dragdrop.Area{Children: []core.Node{ui.Tree{ TestID: "scene-tree", @@ -440,15 +463,13 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No FocusVisible: ed.SpecPalette(cx).FocusRing(-2), }, RowStyle: core.Style{ + MinHeight: core.Pt(specRowHeight), + Height: core.Pt(specRowHeight), + CornerRadius: specRadiusControl, FocusVisible: ed.SpecPalette(cx).FocusRing(-2), }, }}}, sceneTreeSketchSectionView(cx, ed, rev), - core.Text{ - TestID: "scene-tree-hint", - Content: ed.T("sceneTree.hint"), - Style: core.Style{FontSize: 10, Color: colors.Muted()}, - }, }, } }, @@ -513,27 +534,51 @@ func dropStyle(cx *core.Scope, hint *core.Signal[treeHint], k sceneTreeKey) core } func layerRow(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], k sceneTreeKey, hint *core.Signal[treeHint]) core.Node { - colors := ui.ColorsOf(cx) setHint := func(on bool) { hint.Set(treeHint{key: k, place: DropInto, on: on}) } return dragdrop.Target{ View: core.View{ TestID: "scene-tree-layer-" + k.layer, - Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, FlexGrow: 1, Gap: 6}, + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, FlexGrow: 1, MinWidth: core.Pt(0), Gap: specSpace8}, StyleFunc: func() core.Style { return dropStyle(cx, hint, k) }, Children: []core.Node{ - core.Text{ - Content: k.layer, - Style: core.Style{FontSize: 12, FontWeight: 700, Color: colors.Text(), FlexGrow: 1}, + core.View{ + TestID: "scene-tree-layer-dot-" + k.layer, + StyleFunc: func() core.Style { + _ = rev.Get() + return core.Style{ + Width: core.Pt(7), + Height: core.Pt(7), + CornerRadius: 2, + Background: ed.LayerKindColor(ed.SpecPalette(cx), k.layer), + FlexShrink: 0, + } + }, }, core.Text{ - ContentFunc: func() string { + Content: k.layer, + MaxLines: 1, + EllipsizeMode: core.EllipsizeTail, + StyleFunc: func() core.Style { _ = rev.Get() + cur := ed.SpecPalette(cx) + col := cur.TextMuted + weight := core.FontWeightMedium if ed.ActiveLayer == k.layer { - return ed.T("sceneTree.active") + col = cur.TextPrimary + weight = core.FontWeightSemibold } - return "" + return core.Style{FontSize: 12.5, FontWeight: weight, Color: col, FlexGrow: 1, FlexShrink: 1} + }, + }, + core.Text{ + TestID: "scene-tree-layer-kind-" + k.layer, + ContentFunc: func() string { + _ = rev.Get() + return ed.LayerKindLabel(k.layer) + }, + StyleFunc: func() core.Style { + return core.Style{FontSize: 11, Color: ed.SpecPalette(cx).TextFaint, FlexShrink: 0} }, - Style: core.Style{FontSize: 10, Color: colors.Muted()}, }, }, }, @@ -626,8 +671,21 @@ func objectRow(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], k sceneTree }, Else: func(cx *core.Scope) core.Node { return core.View{ - Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 4, FlexGrow: 1, MinWidth: core.Pt(0)}, + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: specSpace8, FlexGrow: 1, MinWidth: core.Pt(0)}, Children: []core.Node{ + core.View{ + TestID: "scene-tree-dot-" + id, + StyleFunc: func() core.Style { + _ = rev.Get() + return core.Style{ + Width: core.Pt(7), + Height: core.Pt(7), + CornerRadius: 2, + Background: ed.ObjectKindColor(ed.SpecPalette(cx), id), + FlexShrink: 0, + } + }, + }, core.Show{ When: func() bool { _ = rev.Get() @@ -655,13 +713,39 @@ func objectRow(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], k sceneTree } return id }, - Style: core.Style{FontSize: 12, Color: colors.Text(), FlexShrink: 1}, + MaxLines: 1, + EllipsizeMode: core.EllipsizeTail, + Style: core.Style{FontSize: 12.5, FlexGrow: 1, FlexShrink: 1}, StyleFunc: func() core.Style { _ = rev.Get() + cur := ed.SpecPalette(cx) if pathFlagged(ed.hidden, ed.resolvedObjectPath(id)) || ed.ObjectOrigin(id) != ObjectLocal { - return core.Style{Color: colors.Muted()} + return core.Style{Color: cur.TextFaint} + } + if ed.IsSelected(id) { + return core.Style{Color: cur.TextPrimary, FontWeight: core.FontWeightMedium} + } + return core.Style{Color: cur.TextMuted} + }, + }, + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.IsObjectProposedNew(id) + }, + Then: func(cx *core.Scope) core.Node { + return core.Text{ + TestID: "scene-tree-new-" + id, + Content: "NEW", + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 10, + FontWeight: core.FontWeightSemibold, + Color: ed.SpecPalette(cx).Added.Fg, + FlexShrink: 0, + } + }, } - return core.Style{} }, }, core.Show{ @@ -681,14 +765,14 @@ func objectRow(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], k sceneTree }, }, core.Text{ + TestID: "scene-tree-kind-" + id, ContentFunc: func() string { _ = rev.Get() - if obj, _ := ed.FindResolvedObject(id); obj != nil && obj.Name != "" && obj.Name != id { - return id - } - return "" + return ed.SceneRailObjectKind(id) + }, + StyleFunc: func() core.Style { + return core.Style{FontSize: 11, Color: ed.SpecPalette(cx).TextFaint, FlexShrink: 0} }, - Style: core.Style{FontSize: 10, Color: colors.Muted(), FlexShrink: 1}, }, core.Show{ When: func() bool { diff --git a/packages/game/editor/scenetree_test.go b/packages/game/editor/scenetree_test.go index 4638ea585..1e35d87a2 100644 --- a/packages/game/editor/scenetree_test.go +++ b/packages/game/editor/scenetree_test.go @@ -99,7 +99,7 @@ func TestSceneTreeDragMakesAChildAndUndoRestoresIt(t *testing.T) { t.Fatal("the drop target did not open to show its new child") } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if after := mustSave(t, ed); !bytes.Equal(after, before) { t.Fatalf("Undo did not restore the scene:\n%s\nwant:\n%s", after, before) } @@ -178,7 +178,7 @@ func TestSceneTreeContextMenuTogglesAndReveal(t *testing.T) { t.Fatalf("box after Move to Layer ui is on layer %d", li) } for ed.History.CanUndo() { - app.Press("id:toolbar-undo") + undoInUI(app, ed) } if after := mustSave(t, ed); !bytes.Equal(after, saved) { t.Fatalf("undoing the menu's edits did not restore the scene:\n%s\nwant:\n%s", after, saved) diff --git a/packages/game/editor/search_test.go b/packages/game/editor/search_test.go index 40a6cc5fa..11e09c9d6 100644 --- a/packages/game/editor/search_test.go +++ b/packages/game/editor/search_test.go @@ -161,6 +161,7 @@ func TestSearchOpensClosedSceneAndSelectsObject(t *testing.T) { if ed.FilePath != roomPath || ed.Doc.Name != "Entrance Room" { t.Fatalf("after OpenProject: FilePath=%q Name=%q", ed.FilePath, ed.Doc.Name) } + openFileBrowserInUI(app, ed) if !app.Exists("id:files-search") { t.Fatal("files-search missing with project open") } @@ -242,6 +243,7 @@ func TestFindReferencesOnMaterialMatchesRefsScan(t *testing.T) { }) app.Settle() + openFileBrowserInUI(app, ed) if app.Enabled("id:files-find-refs") { t.Fatal("files-find-refs enabled with no file selected") } diff --git a/packages/game/editor/selection_test.go b/packages/game/editor/selection_test.go index 0c508d0c6..89ce47e66 100644 --- a/packages/game/editor/selection_test.go +++ b/packages/game/editor/selection_test.go @@ -89,11 +89,11 @@ func TestMarqueeSelectFiveObjectsAndDragMovesAllInOneUndoStep(t *testing.T) { } after := saveYAML(t, ed) - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, before) { t.Fatalf("one Undo did not restore all five objects:\n%s\nwant:\n%s", got, before) } - app.Press("id:toolbar-redo") + redoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, after) { t.Fatalf("one Redo did not re-apply move of all five objects") } @@ -200,7 +200,7 @@ func TestMultiSelectInspectorSetsSharedComponentFieldAndOneUndoRestoresEach(t *t } // One Undo restores each object's own original value (10, 25, 42.5). - app.Press("id:toolbar-undo") + undoInUI(app, ed) wantSpeed := map[string]float64{"e1": 10.0, "e2": 25.0, "e3": 42.5} for id, want := range wantSpeed { obj, _, _ := ed.FindObject(id) @@ -214,7 +214,7 @@ func TestMultiSelectInspectorSetsSharedComponentFieldAndOneUndoRestoresEach(t *t } // Redo writes all three back to 80. - app.Press("id:toolbar-redo") + redoInUI(app, ed) for _, id := range []string{"e1", "e2", "e3"} { obj, _, _ := ed.FindObject(id) if got := obj.Components["enemy"].(map[string]any)["speed"]; got != 80.0 { @@ -349,7 +349,7 @@ func TestMultiSelectRotateScaleAndDeleteOneUndoStep(t *testing.T) { if ed.History.Len() != 1 { t.Fatalf("History.Len() after multi-rotate = %d, want 1", ed.History.Len()) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, beforeRot) { t.Fatalf("Undo did not restore multi-rotate") } @@ -375,7 +375,7 @@ func TestMultiSelectRotateScaleAndDeleteOneUndoStep(t *testing.T) { if ed.History.Len() != 1 { t.Fatalf("History.Len() after multi-scale = %d, want 1", ed.History.Len()) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, beforeScale) { t.Fatalf("Undo did not restore multi-scale") } @@ -393,7 +393,7 @@ func TestMultiSelectRotateScaleAndDeleteOneUndoStep(t *testing.T) { if ed.History.Len() != 1 { t.Fatalf("History.Len() after multi-delete = %d, want 1", ed.History.Len()) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, beforeDel) { t.Fatalf("Undo did not restore deleted objects") } @@ -540,11 +540,6 @@ func TestSceneTreeFollowsAndDrivesMultiSelection(t *testing.T) { ed := newMultiSelectEditor(t) app := startEditorView(t, ed) - // Verify hint is shown under the scene tree. - if !app.Exists("id:scene-tree-hint") { - t.Fatal("expected scene-tree-hint under the scene tree") - } - // Click p1, then Mod+click p3 in the scene tree -> both selected in editor and inspector shows "2 selected". app.Press("id:scene-tree-label-p1") if got := ed.SelectedIDs(); !slices.Equal(got, []string{"p1"}) { diff --git a/packages/game/editor/settings_pages_test.go b/packages/game/editor/settings_pages_test.go index 2dcb18665..2de595bd9 100644 --- a/packages/game/editor/settings_pages_test.go +++ b/packages/game/editor/settings_pages_test.go @@ -32,29 +32,28 @@ func TestSettingsPagesNavigationAndToolbarTriggers(t *testing.T) { t.Fatal("settings view should start closed") } - // Toolbar triggers open the matching Settings pages instead of bottom panels. + // Commands open the matching Settings pages instead of bottom panels. cases := []struct { - btnID string + cmdID string page editor.SettingsPage panelID string wantTitle string wantScope string }{ - {"toolbar-project-settings", editor.SettingsPageProject, "project-settings-panel", "Project", "Project · game.yaml"}, - {"toolbar-input-map", editor.SettingsPageInput, "input-map-panel", "Input map", "Project · game.yaml"}, - {"toolbar-audio-mixer", editor.SettingsPageAudio, "audio-mixer-panel", "Audio buses", "Project · game.yaml"}, - {"toolbar-export", editor.SettingsPageExport, "export-panel", "Export", "Project · game.yaml"}, - {"toolbar-editor-settings", editor.SettingsPageGeneral, "editor-settings-dialog", "General", "This computer"}, + {editor.CmdProjectSettings, editor.SettingsPageProject, "project-settings-panel", "Project", "Project · game.yaml"}, + {editor.CmdInputMap, editor.SettingsPageInput, "input-map-panel", "Input map", "Project · game.yaml"}, + {editor.CmdAudioMixer, editor.SettingsPageAudio, "audio-mixer-panel", "Audio buses", "Project · game.yaml"}, + {editor.CmdExport, editor.SettingsPageExport, "export-panel", "Export", "Project · game.yaml"}, + {editor.CmdEditorSettings, editor.SettingsPageGeneral, "editor-settings-dialog", "General", "This computer"}, } for _, tc := range cases { - app.Press("id:" + tc.btnID) - app.Settle() + runEditorCommand(t, app, ed, tc.cmdID) if !ed.SettingsOpen() || ed.SettingsPage() != tc.page { - t.Fatalf("pressing %s: open=%v page=%q, want true/%q", tc.btnID, ed.SettingsOpen(), ed.SettingsPage(), tc.page) + t.Fatalf("running %s: open=%v page=%q, want true/%q", tc.cmdID, ed.SettingsOpen(), ed.SettingsPage(), tc.page) } if !app.Exists("id:settings-view") || !app.Exists("id:"+tc.panelID) { - t.Fatalf("pressing %s: missing settings-view or %s", tc.btnID, tc.panelID) + t.Fatalf("running %s: missing settings-view or %s", tc.cmdID, tc.panelID) } if got := app.Find("id:settings-page-title").Text; got != tc.wantTitle { t.Fatalf("page title for %s = %q, want %q", tc.page, got, tc.wantTitle) @@ -120,7 +119,7 @@ func TestSettingsPagesEditSaveAndUndoAcrossAllFourPages(t *testing.T) { }, nsgotest.Size(1440, 900), nsgotest.Environment(core.Environment{OS: core.OSMacOS, Idiom: core.IdiomDesktop, Dark: true})) // 1. Project page: change project Name -> Save writes both game.yaml and nsgo.yaml -> Undo restores both. - app.Press("id:toolbar-project-settings") + runEditorCommand(t, app, ed, editor.CmdProjectSettings) app.Settle() app.Clear("id:project-settings-name") app.Type("id:project-settings-name", "Dungeon Run") @@ -174,7 +173,7 @@ func TestSettingsPagesEditSaveAndUndoAcrossAllFourPages(t *testing.T) { app.Settle() // Save writes game.yaml and synced nsgo.yaml. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() saved, err := project.Check(os.DirFS(dir)) @@ -203,7 +202,7 @@ func TestSettingsPagesEditSaveAndUndoAcrossAllFourPages(t *testing.T) { // Undo all 8 edits (export preset, audio vol, audio bus, key binding, input action, main scene, window width, project name). for range 8 { - app.Press("id:toolbar-undo") + undoInUI(app, ed) } app.Settle() @@ -215,7 +214,7 @@ func TestSettingsPagesEditSaveAndUndoAcrossAllFourPages(t *testing.T) { } // Save after Undo writes restored name back to both game.yaml and nsgo.yaml. - app.Press("id:toolbar-save") + saveInUI(app, ed) app.Settle() nsgoRestored, err := os.ReadFile(filepath.Join(dir, project.NSGoFileName)) if err != nil { @@ -251,7 +250,7 @@ func TestSettingsExportReadinessAndInlineValidation(t *testing.T) { return editor.EditorView(cx, ed) }, nsgotest.Size(1440, 900), nsgotest.Environment(core.Environment{OS: core.OSMacOS, Idiom: core.IdiomDesktop, Dark: true})) - app.Press("id:toolbar-export") + runEditorCommand(t, app, ed, editor.CmdExport) app.Settle() if got := strings.TrimSpace(allText(app.Find("id:export-preset-readiness-macos"))); got != "Ready" { diff --git a/packages/game/editor/shapes2d_test.go b/packages/game/editor/shapes2d_test.go index 79c1d17be..34c2ee2c2 100644 --- a/packages/game/editor/shapes2d_test.go +++ b/packages/game/editor/shapes2d_test.go @@ -154,11 +154,11 @@ func TestColliderRectDrawnResizedAndRoundTrips(t *testing.T) { } // Undo restores the pre-drag YAML byte for byte; Redo reapplies. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, before) { t.Fatalf("Undo did not restore pre-drag YAML:\n%s\nwant:\n%s", got, before) } - app.Press("id:toolbar-redo") + redoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, saved) { t.Fatalf("Redo did not restore resized YAML:\n%s\nwant:\n%s", got, saved) } @@ -221,19 +221,19 @@ func TestPolygonAddDragAndRemoveVertexUndoSteps(t *testing.T) { } // Undo once reverts only the drag. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, afterAdd) { t.Fatalf("first Undo did not revert drag back to afterAdd") } // Undo twice reverts the vertex addition completely. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := saveYAML(t, ed); !bytes.Equal(got, beforeAdd) { t.Fatalf("second Undo did not restore original scene") } // Redo twice, then remove vertex 1 via secondary click (right-click) in one undo step. - app.Press("id:toolbar-redo") - app.Press("id:toolbar-redo") + redoInUI(app, ed) + redoInUI(app, ed) v1 = findHandle(t, ed.ShapeHandles2D(), "navregion", "poly", editor.ShapeHandlePolygonVertex, 1) app.Post(func() { if !ed.HandleCanvasSecondaryPress(v1.Pos.X, v1.Pos.Y) { @@ -293,7 +293,8 @@ func TestShowAllShapesToggleAndGridSnapping(t *testing.T) { } // Toolbar toggle turns ShowAllShapes on and draws both "a" and "b". - app.Press("id:view-show-all-shapes") + app.Post(func() { ed.SetShowAllShapes(true) }) + app.Settle() if !ed.ShowAllShapes { t.Fatal("toolbar Shapes toggle did not enable ShowAllShapes") } @@ -321,7 +322,7 @@ func TestShowAllShapesToggleAndGridSnapping(t *testing.T) { app.Settle() // Turn Snap on via toolbar and drag point & circle radius handles. - app.Press("id:view-snap-grid") + app.Press("id:viewport-bar-snap") if !ed.SnapToGrid { t.Fatal("toolbar Snap toggle did not enable SnapToGrid") } @@ -446,7 +447,12 @@ func TestPluginToolReceivesDragAndHoverCallbacksWithCanvasCoords(t *testing.T) { } app := mountEditor(t, ed) - app.Press("id:tool-handles-custom") + app.Post(func() { + if err := ed.SetPluginTool("handles", "custom"); err != nil { + t.Error(err) + } + }) + app.Settle() // Hover enters and leaves the viewport. app.Post(func() { diff --git a/packages/game/editor/shortcuts.go b/packages/game/editor/shortcuts.go index 33a67b8b3..58e9f88cf 100644 --- a/packages/game/editor/shortcuts.go +++ b/packages/game/editor/shortcuts.go @@ -534,7 +534,7 @@ func (e *Editor) shortcutScopePriority(scope string) int { return 0 case ScopeTile: if e.ViewMode == ViewMode2D && isTileTool(e.Tool) { - return 3 + return 4 } if e.ViewMode == ViewMode2D { return 1 diff --git a/packages/game/editor/shortcuts_test.go b/packages/game/editor/shortcuts_test.go index 5433698f5..b8d1a0d28 100644 --- a/packages/game/editor/shortcuts_test.go +++ b/packages/game/editor/shortcuts_test.go @@ -31,18 +31,20 @@ func TestShortcutsRebindFramePersistsAcrossRestartAndUpdatesEverySurface(t *test return editor.EditorView(cx, ed) }, nsgotest.Size(1440, 900), macEnv) - // Initially Frame Selection is bound to "f" and its toolbar button label shows "(F)". + // Initially Frame Selection is bound to "f" and Move tool tooltip shows "Move · W". if got := ed.EffectiveShortcut(editor.CmdFrameSelection); got != "f" { t.Fatalf("initial EffectiveShortcut(Frame) = %q, want f", got) } - if lbl := app.Find("id:view-frame-selection").Props.Label; !strings.Contains(lbl, "(F)") { - t.Fatalf("initial view-frame-selection label = %q, want (F)", lbl) + app.Hover("id:tool-move") + app.Advance(time.Second) + if !app.Exists("text:Move · W") { + t.Fatal("initial tool-move tooltip did not show \"Move · W\"") } // Open Editor Settings -> Shortcuts tab, search for Frame, press its binding button, and press "g". // "g" is used by Tool: Fill Tile in ScopeTile (a DIFFERENT scope from ScopeViewport), // so rebinding Frame to "g" must succeed immediately without a conflict prompt. - app.Press("id:toolbar-editor-settings") + runEditorCommand(t, app, ed, editor.CmdEditorSettings) app.Press("id:editor-settings-tab-shortcuts") app.Type("id:shortcuts-search", "Frame") app.Press("id:shortcut-bind-" + editor.CmdFrameSelection) @@ -65,17 +67,7 @@ func TestShortcutsRebindFramePersistsAcrossRestartAndUpdatesEverySurface(t *test // Close Editor Settings dialog and verify every UI surface reflects G immediately. app.Press("id:editor-settings-close") - // 1. Tooltip / accessible label on the toolbar Frame button. - if lbl := app.Find("id:view-frame-selection").Props.Label; !strings.Contains(lbl, "(G)") { - t.Fatalf("after rebinding, view-frame-selection label = %q, want (G)", lbl) - } - app.Hover("id:view-frame-selection") - app.Advance(time.Second) - if !app.Exists("text:Frame Selection (G)") { - t.Fatal("after rebinding, hovering view-frame-selection did not show tooltip \"Frame Selection (G)\"") - } - - // 2. Desktop menu bar. + // 1. Desktop menu bar. if item, ok := findMenuItem(app.Menu, "View", "Frame Selection"); !ok || item.Shortcut != "g" { t.Fatalf("menu View > Frame Selection = (%+v, %v), want shortcut g", item, ok) } @@ -153,9 +145,6 @@ func TestShortcutsRebindFramePersistsAcrossRestartAndUpdatesEverySurface(t *test if got := restarted.EffectiveShortcut(editor.CmdFrameSelection); got != "g" { t.Fatalf("after restart, EffectiveShortcut(Frame) = %q, want g", got) } - if lbl := app2.Find("id:view-frame-selection").Props.Label; !strings.Contains(lbl, "(G)") { - t.Fatalf("after restart, view-frame-selection label = %q, want (G)", lbl) - } if item, ok := findMenuItem(app2.Menu, "View", "Frame Selection"); !ok || item.Shortcut != "g" { t.Fatalf("after restart, menu View > Frame Selection = (%+v, %v), want shortcut g", item, ok) } @@ -236,16 +225,16 @@ func TestShortcutsSameScopeConflictSwapAndDifferentScopeAllowed(t *testing.T) { t.Fatalf("swapped Frame key v did not frame hero: View2D=%+v", v) } - // Different-scope binding: Frame (ScopeViewport) -> "w" (3D Gizmo: Translate, ScopeViewport3D) binds immediately! + // Different-scope binding: Frame (ScopeViewport) -> "1" (3D View: Front, ScopeViewport3D) binds immediately! app.Post(func() { ed.OpenShortcutsSettings() }) app.Settle() app.Press("id:shortcut-bind-" + editor.CmdFrameSelection) - app.Key("w") + app.Key("1") if app.Exists("id:shortcut-conflict-" + editor.CmdFrameSelection) { - t.Fatal("binding Frame (viewport) to W (viewport3d) unexpectedly flagged a conflict") + t.Fatal("binding Frame (viewport) to 1 (viewport3d) unexpectedly flagged a conflict") } - if ed.EffectiveShortcut(editor.CmdFrameSelection) != "w" || ed.EffectiveShortcut(editor.CmdGizmoTranslate) != "w" { - t.Fatalf("cross-scope bindings: frame=%q translate=%q, want w and w", ed.EffectiveShortcut(editor.CmdFrameSelection), ed.EffectiveShortcut(editor.CmdGizmoTranslate)) + if ed.EffectiveShortcut(editor.CmdFrameSelection) != "1" || ed.EffectiveShortcut(editor.CmdView3DFront) != "1" { + t.Fatalf("cross-scope bindings: frame=%q front3d=%q, want 1 and 1", ed.EffectiveShortcut(editor.CmdFrameSelection), ed.EffectiveShortcut(editor.CmdView3DFront)) } // Per-row Reset restores Frame Selection back to "f" (and swaps Tool: Select if it held "f"). diff --git a/packages/game/editor/snap_test.go b/packages/game/editor/snap_test.go index 98084ffca..2b1e3f310 100644 --- a/packages/game/editor/snap_test.go +++ b/packages/game/editor/snap_test.go @@ -531,18 +531,19 @@ func TestSnapToolbarPopoverAndCompactLayout(t *testing.T) { ed := newTestEditor(t) app := mountEditor(t, ed) - // Verify snap controls sit on the same row as the existing 2D view buttons and don't add a new toolbar row at 1120x680. - snapToggle := app.Find("id:view-snap-grid") - snapBtn := app.Find("id:view-snap-settings") - if snapToggle == nil || snapBtn == nil { - t.Fatal("snap toolbar controls not found") + // Verify 2D viewport bar Snap switch works and header stays 44 pt single-row at 1120x680. + snapToggle := app.Find("id:viewport-bar-snap") + if snapToggle == nil { + t.Fatal("viewport-bar-snap control not found") } - if math.Abs(float64(snapToggle.Bounds().Origin.Y-snapBtn.Bounds().Origin.Y)) > 16 { - t.Fatalf("view-snap-settings wrapped onto a different row than view-snap-grid (%v vs %v)", snapBtn.Bounds().Origin.Y, snapToggle.Bounds().Origin.Y) + if h := app.Find("id:editor-toolbar").Bounds().Size.Height; math.Abs(float64(h-44)) > 1 { + t.Fatalf("editor-toolbar height = %v, want 44", h) } - // Open the Snap Settings popover and toggle every setting via UI. - app.Press("id:view-snap-settings") + // Switch to 3D where the Snap Settings popover lives and toggle every setting via UI. + app.Press("id:view-mode-3d") + app.Settle() + app.Press("id:view3d-snap-settings") app.Press("id:snap-show-grid") app.Press("id:snap-grid-toggle") app.Press("id:snap-pixel-toggle") diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index 99a7f51f7..fbfbc184d 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -70,6 +70,12 @@ const ( ToolRandomTile // ToolNavTestPath sets start and end world points on click to preview the path ai.NavMesh.FindPath finds on the built 2D navigation mesh. ToolNavTestPath + // ToolRotate rotates the selected object in 2D (and sets 3D Gizmo3DRotate). + ToolRotate + // ToolScale scales the selected object in 2D (and sets 3D Gizmo3DScale). + ToolScale + // ToolPan pans the viewport camera on drag. + ToolPan ) // String returns a human-readable label for the tool. @@ -79,6 +85,12 @@ func (t Tool) String() string { return "Select" case ToolMove: return "Move" + case ToolRotate: + return "Rotate" + case ToolScale: + return "Scale" + case ToolPan: + return "Pan" case ToolPlace: return "Place" case ToolPaintTile: @@ -993,6 +1005,22 @@ type Editor struct { stagedFiles map[string]*stagedFileEntry // pendingTurnPrompt tracks a blocked close/scene-switch/project-switch waiting on Keep, Revert, or Cancel. pendingTurnPrompt pendingTurnPromptState + // pointerRev and pointerListeners broadcast viewport pointer coordinate updates to the status bar without bumping full Revision. + pointerRev uint64 + nextPointerListener uint64 + pointerListeners map[uint64]func() + // projectLoading tracks an in-progress project open so every workspace region shows its designed loading state. + projectLoading bool + projectLoadingPath string + // sceneOpenErr records the last failed scene open (missing file, malformed YAML, etc.) so every workspace region shows its designed error state instead of a blank viewport. + sceneOpenErr *SceneOpenError + // layersPanelOpen, fileBrowserOpen, assetBrowserOpen, and libraryPanelOpen toggle auxiliary docked panels moved off the default AI-first chrome. + layersPanelOpen bool + fileBrowserOpen bool + assetBrowserOpen bool + libraryPanelOpen bool + // proposedNewObjects records object IDs proposed by a pending review for the left rail NEW badge. + proposedNewObjects map[string]bool } // DefaultSceneDoc returns a valid starter SceneDoc suitable for a new editor session. @@ -1308,6 +1336,14 @@ func (e *Editor) SetTool(t Tool) { e.CancelRoomDrag() e.endTileStrokeForChange() e.Tool = t + switch t { + case ToolMove: + e.GizmoMode = Gizmo3DTranslate + case ToolRotate: + e.GizmoMode = Gizmo3DRotate + case ToolScale: + e.GizmoMode = Gizmo3DScale + } if isTileTool(t) { e.inspectLayer = false } @@ -1709,7 +1745,9 @@ func (e *Editor) openFileWithLayers(path string, layers *sceneformat.PhysicsLaye } data, err := os.ReadFile(path) if err != nil { - return loaderr.Locate(err, path, nil, "check that the scene exists at this path and can be read") + openErr := loaderr.Locate(err, path, nil, "check that the scene exists at this path and can be read") + e.recordSceneOpenError(path, openErr) + return openErr } doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{ File: path, @@ -1717,17 +1755,22 @@ func (e *Editor) openFileWithLayers(path string, layers *sceneformat.PhysicsLaye PhysicsLayers: layers, }) if err != nil { - return loaderr.WithFile(err, path) + openErr := loaderr.WithFile(err, path) + e.recordSceneOpenError(path, openErr) + return openErr } saved, err := sceneformat.Encode(doc) if err != nil { - return loaderr.WithFile(err, path) + openErr := loaderr.WithFile(err, path) + e.recordSceneOpenError(path, openErr) + return openErr } if e.playing { if err := e.Stop(); err != nil { return err } } + e.sceneOpenErr = nil e.activateNewTab(doc, saved, path) e.recordSceneDiskSnapshot(path, data) e.syncActiveTab() diff --git a/packages/game/editor/states_test.go b/packages/game/editor/states_test.go index 55009ea74..569eb293c 100644 --- a/packages/game/editor/states_test.go +++ b/packages/game/editor/states_test.go @@ -364,7 +364,7 @@ func TestStatesGraphUIAndDriveWithKeysAndScreenshot(t *testing.T) { if !app.Exists("id:states-node-dash") { t.Fatal("added state node 'dash' did not appear") } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if app.Exists("id:states-node-dash") { t.Fatal("undo did not remove added state node 'dash'") } diff --git a/packages/game/editor/terrain3d_test.go b/packages/game/editor/terrain3d_test.go index 90e1fc412..43a49d9b8 100644 --- a/packages/game/editor/terrain3d_test.go +++ b/packages/game/editor/terrain3d_test.go @@ -498,7 +498,7 @@ func TestTerrainPanelAndViewport3DInteraction(t *testing.T) { app.Resize(1280, 800) // Toggle Terrain button in 3D toolbar opens a new terrain and mounts TerrainPanelView. - app.Press("id:toolbar-terrain") + runEditorCommand(t, app, ed, editor.CmdTerrainEditor) if !ed.TerrainOpen() { t.Fatalf("expected TerrainOpen() after pressing toolbar-terrain") } diff --git a/packages/game/editor/terrain_test.go b/packages/game/editor/terrain_test.go index 43f153d3e..b0dee1a1f 100644 --- a/packages/game/editor/terrain_test.go +++ b/packages/game/editor/terrain_test.go @@ -247,7 +247,7 @@ func TestTerrainEraseFixesNeighborsAndOneUndoRestoresStroke(t *testing.T) { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 680)) - app.Press("id:tool-terrain") + runEditorCommand(t, app, ed, editor.CmdToolTerrain) if ed.Tool != editor.ToolTerrain { t.Fatalf("Tool = %v, want ToolTerrain", ed.Tool) } @@ -302,12 +302,12 @@ func TestTerrainEraseFixesNeighborsAndOneUndoRestoresStroke(t *testing.T) { } // ONE Undo restores BOTH the erased cells AND every neighbor's previous tile ID. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := readEditorCells(t, ed); !slices.Equal(got, beforeErase) { t.Fatalf("after one Undo cells =\n%v\nwant exact pre-erase blob =\n%v", got, beforeErase) } // Redo re-applies the erase and neighbor updates. - app.Press("id:toolbar-redo") + redoInUI(app, ed) if got := readEditorCells(t, ed); !slices.Equal(got, wantAfterErase) { t.Fatalf("after Redo cells =\n%v\nwant post-erase =\n%v", got, wantAfterErase) } @@ -492,7 +492,7 @@ func TestTilesetEditorAssignsEdgesAndCornersAndSaves(t *testing.T) { if got := ed.TilesetDoc().Terrain("moss", 1).Autotile.Tile(tilemap.MaskEast); got != 4 { t.Fatalf("after reassign, mask E -> GID %d, want 4 (tile 3)", got) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := ed.TilesetDoc().Terrain("moss", 1).Autotile.Tile(tilemap.MaskEast); got != 2 { t.Fatalf("after undo of reassign, mask E -> GID %d, want 2 (tile 1)", got) } diff --git a/packages/game/editor/tile_review_test.go b/packages/game/editor/tile_review_test.go index 454ca166a..9b1b3ebb4 100644 --- a/packages/game/editor/tile_review_test.go +++ b/packages/game/editor/tile_review_test.go @@ -670,7 +670,7 @@ func TestTileReviewUIAndScreenshot(t *testing.T) { } // Undo once -> restores original tilemap cleanly! - app.Press("id:toolbar-undo") + undoInUI(app, ed) if !slices.Equal(snapshotLayerCells(t, ed, "World"), original) { t.Fatal("toolbar Undo after Keep did not restore original tilemap") } diff --git a/packages/game/editor/tilebrush_test.go b/packages/game/editor/tilebrush_test.go index 69cf9ab99..e019153f5 100644 --- a/packages/game/editor/tilebrush_test.go +++ b/packages/game/editor/tilebrush_test.go @@ -440,7 +440,7 @@ func TestTileBrushesMountedUIEscapeCancelAndClipboard(t *testing.T) { } // 2. Rect drag cancelled with Escape before MouseUp leaves map & history untouched. - app.Press("id:tool-rect") + runEditorCommand(t, app, ed, editor.CmdToolRectTile) app.Press("id:tile-palette-4") before := slices.Clone(gridData(ed)) app.MouseDownAt("id:editor-viewport-frame", canvasAt(ed, 8, 8), core.MouseButtonLeft) @@ -467,7 +467,7 @@ func TestTileBrushesMountedUIEscapeCancelAndClipboard(t *testing.T) { } // 4. Stamp tool: right-drag selects a 2x2 region on the map, Cmd+C copies, hover at (3,3) and Cmd+V pastes! - app.Press("id:tool-stamp") + runEditorCommand(t, app, ed, editor.CmdToolStampTile) if !app.Exists("id:tile-stamp-controls") { t.Fatal("stamp controls missing when ToolStampTile is active") } @@ -499,7 +499,7 @@ func TestTileBrushesMountedUIEscapeCancelAndClipboard(t *testing.T) { } // 5. Random tool UI: toggle tiles 1 and 2, adjust weight, set seed via text field. - app.Press("id:tool-random") + runEditorCommand(t, app, ed, editor.CmdToolRandomTile) if !app.Exists("id:tile-random-controls") { t.Fatal("random controls missing when ToolRandomTile is active") } diff --git a/packages/game/editor/tilemap_setup_test.go b/packages/game/editor/tilemap_setup_test.go index a1b5e748b..692ac8b47 100644 --- a/packages/game/editor/tilemap_setup_test.go +++ b/packages/game/editor/tilemap_setup_test.go @@ -50,7 +50,7 @@ func TestNewSceneGetsPaintedTilemapFromUI(t *testing.T) { }, nsgotest.Size(1280, 900)) // Switch to Paint tool on the new scene's layer (which has no tilemap yet), then press Set Up Tilemap. - app.Press("id:tool-paint") + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) if !app.Exists("id:tile-palette-setup-layer") { t.Fatal("expected Set Up Tilemap button in empty tile palette for a layer with no tilemap") } @@ -85,7 +85,7 @@ func TestNewSceneGetsPaintedTilemapFromUI(t *testing.T) { } // Frame the new tilemap in the 2D viewport, pick tile 2 in the palette, and paint cell (2, 1). - app.Press("id:view-frame-all") + app.Press("id:viewport-bar-fit") app.Press("id:tile-palette-2") cx, cy := ed.WorldToCanvas(2*16+8, 1*16+8) app.PressAt("id:editor-viewport", core.Point{X: core.Points(cx), Y: core.Points(cy)}) @@ -109,8 +109,8 @@ func TestNewSceneGetsPaintedTilemapFromUI(t *testing.T) { } // Undoing paint and add restores the original scene byte-for-byte. - app.Press("id:toolbar-undo") - app.Press("id:toolbar-undo") + undoInUI(app, ed) + undoInUI(app, ed) if after := mustSave(t, ed); !bytes.Equal(after, initialYAML) { t.Fatalf("Undo did not restore new scene:\ngot:\n%s\nwant:\n%s", after, initialYAML) } @@ -255,7 +255,7 @@ func TestExtractAndInlineLayerTilemap(t *testing.T) { if top := ed.Doc.Tilemaps["floor_grid"]; top.Width != 5 || top.OffsetX != -16 { t.Fatalf("top-level after resize = width %d offsetX %v, want 5 and -16", top.Width, top.OffsetX) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) // Move back inline via UI: removes unreferenced top-level entry and matches original YAML byte-for-byte. app.Press("id:inspector-layer-tilemap-inline") diff --git a/packages/game/editor/tilepaint_layered_test.go b/packages/game/editor/tilepaint_layered_test.go index 7b798e8ee..de4840d41 100644 --- a/packages/game/editor/tilepaint_layered_test.go +++ b/packages/game/editor/tilepaint_layered_test.go @@ -148,7 +148,7 @@ func TestTilePaletteShowsALayeredGridsTileset(t *testing.T) { app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 680)) - app.Press("id:tool-paint") + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) if !app.Exists("id:tile-layer-controls") { t.Fatal("the palette of a layered grid shows no tile layer controls") } diff --git a/packages/game/editor/tilepalette.go b/packages/game/editor/tilepalette.go index 88d1f3d93..430d5575a 100644 --- a/packages/game/editor/tilepalette.go +++ b/packages/game/editor/tilepalette.go @@ -402,8 +402,13 @@ func tilePalettePanel(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core return ed.Playing() }, OnPress: func() { + if ed.activeTab >= 0 && ed.activeTab < len(ed.tabs) { + ed.tabs[ed.activeTab].placeholder = false + } ed.SelectObject("") ed.SetActiveLayer(p.Layer) + ed.SetRightRailTab(RightTabInspector) + ed.notify() }, }, }, diff --git a/packages/game/editor/tilepalette_test.go b/packages/game/editor/tilepalette_test.go index 3e68f0b17..bcd190345 100644 --- a/packages/game/editor/tilepalette_test.go +++ b/packages/game/editor/tilepalette_test.go @@ -211,7 +211,7 @@ func TestTilePaletteChoosesTheTilePaintSaves(t *testing.T) { if app.Exists("id:tile-palette") { t.Fatal("tile palette shows with the Select tool") } - app.Press("id:tool-paint") + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) if !app.Exists("id:tile-palette") { t.Fatal("tile palette does not show with the Paint tool") } @@ -255,7 +255,7 @@ func TestTilePaletteChoosesTheTilePaintSaves(t *testing.T) { if got := ed.Doc.Layers[0].Tilemap.Data[1*4+1]; got != 3 { t.Fatalf("painted tile (1,1) = %d, want 3", got) } - app.Press("id:toolbar-save") + saveInUI(app, ed) data, err := os.ReadFile(path) if err != nil { t.Fatalf("ReadFile: %v", err) @@ -269,7 +269,7 @@ func TestTilePaletteChoosesTheTilePaintSaves(t *testing.T) { } // The paint is one undoable step; picking a tile is not an edit. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if got := ed.Doc.Layers[0].Tilemap.Data[1*4+1]; got != 0 { t.Fatalf("tile (1,1) after Undo = %d, want 0", got) } @@ -287,7 +287,7 @@ func TestTilePaletteFollowsTheActiveLayer(t *testing.T) { app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 680)) - app.Press("id:tool-fill") + runEditorCommand(t, app, ed, editor.CmdToolFillTile) if !app.Exists("id:tile-palette-3") || app.Exists("id:tile-palette-10") { t.Fatal("palette should show the floor layer's tiles") } @@ -329,7 +329,7 @@ func TestTilePaletteFollowsTheActiveLayer(t *testing.T) { if got := app.Find("id:editor-status-mode").Text; !strings.HasSuffix(got, "| Tile: 2") { t.Fatalf("status = %q, want the selected walls tile 2 with Fill", got) } - app.Press("id:tool-erase") + runEditorCommand(t, app, ed, editor.CmdToolEraseTile) if got := app.Find("id:editor-status-mode").Text; strings.Contains(got, "Tile:") { t.Fatalf("status = %q shows a tile with Erase, which writes none", got) } diff --git a/packages/game/editor/tileset_editor_test.go b/packages/game/editor/tileset_editor_test.go index 1d920b355..5be0a31a4 100644 --- a/packages/game/editor/tileset_editor_test.go +++ b/packages/game/editor/tileset_editor_test.go @@ -90,7 +90,7 @@ func TestTilesetEditorSolidTileCollidesInGameWithMoveAndSlide(t *testing.T) { }, nsgotest.Size(1280, 760), nsgotest.Environment(core.Environment{OS: core.OSMacOS, Idiom: core.IdiomDesktop})) // Open Tileset Editor from the Tile Palette, switch to Collision tab, mark tile 0 solid, and save. - app.Press("id:tool-paint") + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) app.Press("id:tile-palette-edit-tileset") app.Press("id:tileset-tab-collision") app.Press("id:tileset-tile-0") @@ -202,7 +202,7 @@ func TestTilesetEditorAnimatedTileAnimatesInViewportAndGame(t *testing.T) { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 760), nsgotest.Environment(core.Environment{OS: core.OSMacOS, Idiom: core.IdiomDesktop})) - app.Press("id:tool-paint") + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) app.Press("id:tile-palette-edit-tileset") app.Press("id:tileset-tab-animation") app.Press("id:tileset-tile-0") @@ -314,7 +314,7 @@ func TestTilesetEditorCollisionShapesCustomDataAndUndo(t *testing.T) { }, nsgotest.Size(1280, 760), nsgotest.Environment(core.Environment{OS: core.OSMacOS, Idiom: core.IdiomDesktop})) // Switching to Paint tool shows the right-side Tile Inspector (matching Tiles.dc.html). - app.Press("id:tool-paint") + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) if !app.Exists("id:inspector-tile") { t.Fatal("expected right-side Tile Inspector when Paint tool is active on a YAML tileset layer") } @@ -331,7 +331,7 @@ func TestTilesetEditorCollisionShapesCustomDataAndUndo(t *testing.T) { if !info0.OneWay || info0.Solid { t.Fatalf("tile 0 after inspector one-way = %+v", info0) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) info0, _ = ed.TilesetTileInfo(0) if info0.OneWay || info0.Solid { t.Fatalf("tile 0 after undo = %+v, want neither solid nor one-way", info0) @@ -364,7 +364,7 @@ func TestTilesetEditorCollisionShapesCustomDataAndUndo(t *testing.T) { if len(info0.Shapes) != 1 { t.Fatalf("shapes after remove = %d, want 1", len(info0.Shapes)) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) info0, _ = ed.TilesetTileInfo(0) if len(info0.Shapes) != 2 { t.Fatalf("shapes after undo = %d, want 2", len(info0.Shapes)) @@ -407,7 +407,7 @@ func TestTilesetEditorCollisionShapesCustomDataAndUndo(t *testing.T) { if _, exists := info0.Properties["damage"]; exists { t.Fatal("damage property was not deleted") } - app.Press("id:toolbar-undo") + undoInUI(app, ed) info0, _ = ed.TilesetTileInfo(0) if info0.Properties["damage"] != 2 { t.Fatalf("damage property after undo = %v, want 2", info0.Properties["damage"]) diff --git a/packages/game/editor/tilestroke_test.go b/packages/game/editor/tilestroke_test.go index 71a7ee60a..07bde9048 100644 --- a/packages/game/editor/tilestroke_test.go +++ b/packages/game/editor/tilestroke_test.go @@ -346,7 +346,20 @@ func mountFloor(t *testing.T, tool string) (*editor.Editor, *nsgotest.App) { app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1280, 680)) - app.Press("id:" + tool) + switch tool { + case "tool-paint": + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) + case "tool-erase": + runEditorCommand(t, app, ed, editor.CmdToolEraseTile) + case "tool-fill": + runEditorCommand(t, app, ed, editor.CmdToolFillTile) + case "tool-rect": + runEditorCommand(t, app, ed, editor.CmdToolRectTile) + case "tool-line": + runEditorCommand(t, app, ed, editor.CmdToolLineTile) + default: + app.Press("id:" + tool) + } return ed, app } @@ -365,7 +378,7 @@ func TestMouseDragPaintsARowAndOneUndoRemovesIt(t *testing.T) { if ed.History.Len() != 1 { t.Fatalf("the drag recorded %d steps, want 1", ed.History.Len()) } - app.Press("id:toolbar-undo") + undoInUI(app, ed) if !slices.Equal(floorData(ed), before) { t.Fatalf("after one Undo the map is %v, want %v", floorData(ed), before) } @@ -456,7 +469,8 @@ func TestPickingMakesTheTileActiveInThePalette(t *testing.T) { app.Press("id:tile-palette-2") app.PressAt("id:editor-viewport", canvasAt(ed, 24, 24)) app.Press("id:tile-palette-3") - app.Press("id:tool-pick") + app.Post(func() { ed.SetTool(editor.ToolPickTile) }) + app.Settle() if !app.Exists("id:tile-palette") { t.Fatal("the palette hides with the Pick tool") } @@ -468,7 +482,8 @@ func TestPickingMakesTheTileActiveInThePalette(t *testing.T) { t.Fatalf("Tool = %v after a pick, want Paint", ed.Tool) } // Picking an empty cell keeps the Pick tool and the active tile. - app.Press("id:tool-pick") + app.Post(func() { ed.SetTool(editor.ToolPickTile) }) + app.Settle() app.PressAt("id:editor-viewport", canvasAt(ed, 40, 40)) if ed.ActiveTileID != 2 || ed.Tool != editor.ToolPickTile { t.Fatalf("after picking an empty cell ActiveTileID = %d and Tool = %v, want 2 and Pick", ed.ActiveTileID, ed.Tool) @@ -496,7 +511,7 @@ func TestClickAfterRightDragReachesTheTool(t *testing.T) { app.MouseDownAt("id:editor-viewport-frame", canvasAt(ed, 3, 56), core.MouseButtonRight) app.HoverAt("id:editor-viewport-frame", canvasAt(ed, 30, 56)) app.MouseUpAt("id:editor-viewport-frame", canvasAt(ed, 30, 56), core.MouseButtonRight) - app.Press("id:tool-fill") + runEditorCommand(t, app, ed, editor.CmdToolFillTile) app.Press("id:tile-palette-3") app.PressAt("id:editor-viewport", canvasAt(ed, 24, 24)) if got := floorData(ed)[5]; got != 3 { @@ -518,9 +533,9 @@ func TestClickAfterPaintTapReachesTheTool(t *testing.T) { t.Fatalf("after a paint tap and a Select click SelectedID = %q, want hero", ed.SelectedID) } // A Fill click after a tap fills too. - app.Press("id:tool-paint") + runEditorCommand(t, app, ed, editor.CmdToolPaintTile) app.PressAt("id:editor-viewport", canvasAt(ed, 40, 40)) - app.Press("id:tool-fill") + runEditorCommand(t, app, ed, editor.CmdToolFillTile) app.Press("id:tile-palette-3") app.PressAt("id:editor-viewport", canvasAt(ed, 24, 24)) if got := floorData(ed)[5]; got != 3 { diff --git a/packages/game/editor/toasts_test.go b/packages/game/editor/toasts_test.go index 1720a8ddc..b883a2061 100644 --- a/packages/game/editor/toasts_test.go +++ b/packages/game/editor/toasts_test.go @@ -380,8 +380,7 @@ func TestToastProgressHandleAndExportIntegration(t *testing.T) { }, nsgotest.Size(1440, 900), nsgotest.Environment(toastDesktopEnv(true, true))) // Open Settings > Export (no viewport on screen -> toast anchors at window bottom center, 24 px up). - app.Press("id:toolbar-export") - app.Settle() + runEditorCommand(t, app, ed, editor.CmdExport) app.Post(func() { if err := ed.StartExportBuild(editor.ExportBuildOptions{Targets: []string{"macos_arm64"}}); err != nil { @@ -549,10 +548,10 @@ func TestToastKeyboardEscFocusReturnAndMotion(t *testing.T) { }, nsgotest.Size(1440, 900), nsgotest.Environment(toastDesktopEnv(true, true)), nsgotest.ManualFrames()) // Focus a specific control in Header. - app.Focus("id:toolbar-editor-settings") + app.Focus("id:toolbar-history") app.Settle() - if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-editor-settings" { - t.Fatalf("initial focus = %v, want toolbar-editor-settings", fv) + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-history" { + t.Fatalf("initial focus = %v, want toolbar-history", fv) } // Showing a toast must NEVER steal focus, and mounts inside a polite role="status" live region. @@ -569,7 +568,7 @@ func TestToastKeyboardEscFocusReturnAndMotion(t *testing.T) { if host.Props.Role != core.RoleStatus || host.Props.LiveRegion != core.LiveRegionPolite { t.Fatalf("editor-toast-host Role=%v LiveRegion=%v, want RoleStatus + LiveRegionPolite", host.Props.Role, host.Props.LiveRegion) } - if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-editor-settings" { + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-history" { t.Fatalf("showing toast stole focus: got %v", fv) } @@ -589,17 +588,17 @@ func TestToastKeyboardEscFocusReturnAndMotion(t *testing.T) { t.Fatalf("Tab inside toast focused %v, want editor-toast-dismiss", fv) } - // Pressing Esc dismisses the focused toast and returns focus to toolbar-editor-settings! + // Pressing Esc dismisses the focused toast and returns focus to toolbar-history! app.Key("escape") if ed.HasActiveToast() || app.Exists("id:editor-toast") { t.Fatal("Esc did not dismiss focused toast") } - if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-editor-settings" { + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-history" { gotID := "" if fv != nil { gotID = fv.Props.TestID } - t.Fatalf("after Esc dismissed toast, focus = %q, want toolbar-editor-settings", gotID) + t.Fatalf("after Esc dismissed toast, focus = %q, want toolbar-history", gotID) } }) diff --git a/packages/game/editor/ui.go b/packages/game/editor/ui.go index 983aa05d1..fcac83533 100644 --- a/packages/game/editor/ui.go +++ b/packages/game/editor/ui.go @@ -372,7 +372,7 @@ func EditorView(cx *core.Scope, ed *Editor) core.Node { Height: core.Pct(100), }, Children: []core.Node{ - toolbarView(cx, ed, rev, sceneFileButtons(cx, ed, rev, dirty, pathMode, pathTarget)), + mainHeaderView(cx, ed, rev, dirty, pathMode, pathTarget), remotePlayBarView(cx, ed, rev), playModeBarView(cx, ed, rev), diskWatchBannerView(cx, ed, rev), @@ -441,7 +441,7 @@ func EditorView(cx *core.Scope, ed *Editor) core.Node { } }, }, - statusBarView(cx, ed, rev), + mainStatusBarView(cx, ed, rev), }, } }, @@ -547,30 +547,70 @@ func mainRow(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) []core.Node { }, Else: func(cx *core.Scope) core.Node { children := []core.Node{ - core.View{ - TestID: "editor-scene-column", - Style: core.Style{Width: core.Pt(220)}, - Children: []core.Node{ - LeftRailSwitchView(cx, ed, rev), - SceneTreeView(cx, ed, rev), - LayersView(cx, ed, rev), + leftRailSceneView(cx, ed, rev), + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.LayersPanelOpen() + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + Style: core.Style{ + Width: core.Pt(220), + FlexShrink: 0, + Borders: core.Edges{Right: 1}, + BorderColor: ed.SpecPalette(cx).Line, + }, + Children: []core.Node{LayersView(cx, ed, rev)}, + } }, }, - core.View{ - TestID: "editor-left", - Style: core.Style{Width: core.Pt(224)}, - Children: []core.Node{ - // A row stretches the asset browser to the height it gets, which is all of the column without a project and half of it beside the file browser. - core.View{ - Style: core.Style{Direction: core.Row, FlexGrow: 1, FlexBasis: core.Pt(0)}, - Children: []core.Node{AssetBrowserView(cx, ed, rev)}, - }, - FilesView(cx, ed, rev), + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.AssetBrowserOpen() || ed.FileBrowserOpen() + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + TestID: "editor-left", + Style: core.Style{Width: core.Pt(224), FlexShrink: 0}, + Children: []core.Node{ + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.AssetBrowserOpen() + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + Style: core.Style{Direction: core.Row, FlexGrow: 1, FlexBasis: core.Pt(0)}, + Children: []core.Node{AssetBrowserView(cx, ed, rev)}, + } + }, + }, + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.FileBrowserOpen() + }, + Then: func(cx *core.Scope) core.Node { + return FilesView(cx, ed, rev) + }, + }, + }, + } }, }, } if ed.Library != nil { - children = append(children, LibraryView(cx, ed, rev)) + children = append(children, core.Show{ + When: func() bool { + _ = rev.Get() + return ed.LibraryPanelOpen() + }, + Then: func(cx *core.Scope) core.Node { + return LibraryView(cx, ed, rev) + }, + }) } children = append(children, pluginDockView(cx, ed, rev, DockLeft)) return core.View{ diff --git a/packages/game/editor/view2d_test.go b/packages/game/editor/view2d_test.go index 94f5f0e90..7dd5eb8dd 100644 --- a/packages/game/editor/view2d_test.go +++ b/packages/game/editor/view2d_test.go @@ -515,15 +515,16 @@ func TestViewportPansZoomsAndFramesThroughMountedUI(t *testing.T) { } app.Key("home") all := ed.View2D() - app.Press("id:view-frame-selection") + runEditorCommand(t, app, ed, editor.CmdFrameSelection) if v := ed.View2D(); !near(v.X, 2080, 1e-3) { - t.Fatalf("the Frame button framed %+v, want the far object", v) + t.Fatalf("FrameSelection framed %+v, want the far object", v) } - app.Press("id:view-frame-all") + app.Press("id:viewport-bar-fit") if ed.View2D() != all { - t.Fatalf("the Frame All button framed %+v, want %+v", ed.View2D(), all) + t.Fatalf("the Fit button framed %+v, want %+v", ed.View2D(), all) } - app.Press("id:view-reset") + app.Post(func() { ed.ResetView2D() }) + app.Settle() if !ed.View2DFollowsCamera() { t.Fatal("the Camera View button did not return to the camera's view") } @@ -562,9 +563,9 @@ func TestPanToAFarObjectSelectAndMoveKeepsTheSavedCamera(t *testing.T) { if x, _ := ed.WorldToCanvas(2080, 60); x < cw { t.Fatalf("the far object is already in view at canvas x %v of %v", x, cw) } - // Pan right by touchpad scrolls until the far object is in view. + // Pan right by touchpad scrolls until the far object and its target point (2150, 90) are well in view. for range 20 { - if x, _ := ed.WorldToCanvas(2080, 60); x < cw-40 { + if x, _ := ed.WorldToCanvas(2080, 60); x < cw-100 { break } app.TouchpadScroll("id:editor-viewport-frame", core.Point{}, core.Point{X: -200}) @@ -588,7 +589,7 @@ func TestPanToAFarObjectSelectAndMoveKeepsTheSavedCamera(t *testing.T) { t.Fatalf("the far object moved to (%v, %v), want (2150, 90)", far.X, far.Y) } - app.Press("id:toolbar-save") + saveInUI(app, ed) doc, err := sceneformat.Parse(saved) if err != nil { t.Fatalf("Parse the saved scene: %v", err) @@ -601,7 +602,7 @@ func TestPanToAFarObjectSelectAndMoveKeepsTheSavedCamera(t *testing.T) { } // The move is the one edit to undo; the view's pans are not edits. - app.Press("id:toolbar-undo") + undoInUI(app, ed) if far, _, _ := ed.FindObject("far"); far.X != 2080 || far.Y != 60 { t.Fatalf("Undo left the far object at (%v, %v)", far.X, far.Y) } diff --git a/packages/game/editor/viewport.go b/packages/game/editor/viewport.go index 337a743ac..7c20e3d23 100644 --- a/packages/game/editor/viewport.go +++ b/packages/game/editor/viewport.go @@ -263,7 +263,7 @@ func (e *Editor) HandleCanvasPressWithModifiers(x, y float32, shift, mod, alt bo return } switch e.Tool { - case ToolSelect: + case ToolSelect, ToolRotate, ToolScale: if !shift && !mod && e.SelectionCount() <= 1 && e.handleShapePress2D(x, y, false) { return } @@ -283,6 +283,9 @@ func (e *Editor) HandleCanvasPressWithModifiers(x, y float32, shift, mod, alt bo e.ClearSelection() } } + case ToolPan: + // Pan tool drags the camera; bare clicks do not alter selection. + return case ToolMove: if !shift && !mod && e.SelectionCount() <= 1 && e.handleShapePress2D(x, y, false) { return @@ -1027,7 +1030,7 @@ func (g *viewportGestures) pan(ed *Editor, ev core.PanEvent, spaceHeld, shiftHel invert := func() bool { return g.snapInvert != nil && g.snapInvert() } switch ev.Phase { case core.GestureBegan: - g.spacePan = spaceHeld() + g.spacePan = spaceHeld() || ed.Tool == ToolPan g.panLast = ev.Translation g.panCamDrag = false g.panBoundsDrag = false @@ -2080,6 +2083,7 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod }, assetDragViewportOverlay(cx, ed, rev), viewport3DRenderStatsOverlay(cx, ed, rev), + viewportCameraCaptionView(cx, ed, rev), viewportOverlaysBarView(cx, ed, rev), viewportOverlayLegendView(cx, ed, rev), playViewportOverlaysView(cx, ed, rev), @@ -2089,6 +2093,7 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod PlayTaskDotView(cx, ed, rev), viewportSketchOverlayView(cx, ed, rev), viewportAgentPointingOverlay(cx, ed, rev), + viewportWorkspaceStateOverlay(cx, ed, rev), }, append(viewportTileOverlays(cx, ed, rev), ToastView(cx, ed, rev))...), } } diff --git a/packages/game/editor/viewport3d_gpu_test.go b/packages/game/editor/viewport3d_gpu_test.go index 20050202f..7003e162c 100644 --- a/packages/game/editor/viewport3d_gpu_test.go +++ b/packages/game/editor/viewport3d_gpu_test.go @@ -145,7 +145,8 @@ func TestViewport3DDrawsTheSceneOnTheGPUView(t *testing.T) { t.Fatal("the mounted canvas does not draw the overlay DrawViewport draws") } - app.Press("id:shading-unlit") + app.Post(func() { ed.SetShading3D(editor.Shading3DUnlit) }) + app.Settle() app.Advance(20 * time.Millisecond) if ed.Shading3D != editor.Shading3DUnlit { t.Fatalf("shading %v after pressing Unlit", ed.Shading3D) diff --git a/packages/game/editor/viewport3d_lod_occluder_test.go b/packages/game/editor/viewport3d_lod_occluder_test.go index 7359a33d6..539ba9bd5 100644 --- a/packages/game/editor/viewport3d_lod_occluder_test.go +++ b/packages/game/editor/viewport3d_lod_occluder_test.go @@ -166,7 +166,8 @@ func TestEditor3DViewportLODSwitchesAtDeclaredRatio(t *testing.T) { } // Toggling the LOD overlay button hides the LOD badge on the canvas. - app.Press("id:viewport3d-toggle-lod") + app.Post(func() { ed.SetShowLODOverlay(false) }) + app.Settle() if ed.ShowLODOverlay { t.Fatal("ShowLODOverlay remained true after pressing toggle") } @@ -175,7 +176,8 @@ func TestEditor3DViewportLODSwitchesAtDeclaredRatio(t *testing.T) { } // Toggling the Stats button hides the RenderStats HUD overlay. - app.Press("id:viewport3d-toggle-stats") + app.Post(func() { ed.SetShowRenderStats(false) }) + app.Settle() if ed.ShowRenderStats { t.Fatal("ShowRenderStats remained true after pressing toggle") } @@ -230,7 +232,8 @@ func TestEditor3DViewportOccluderWallCullsAndDraws(t *testing.T) { } // Toggling the Occluders toolbar button hides the occluder drawing. - app.Press("id:viewport3d-toggle-occluders") + app.Post(func() { ed.SetShowOccluders(false) }) + app.Settle() if ed.ShowOccluders { t.Fatal("ShowOccluders remained true after pressing toggle") } diff --git a/packages/game/editor/viewport3d_test.go b/packages/game/editor/viewport3d_test.go index 0df2b1f55..008cb8994 100644 --- a/packages/game/editor/viewport3d_test.go +++ b/packages/game/editor/viewport3d_test.go @@ -620,19 +620,19 @@ func TestEditor3DViewportUIRenderingAndControls(t *testing.T) { } } - app.Press("id:gizmo-translate") + app.Press("id:tool-move") if ed.GizmoMode != editor.Gizmo3DTranslate { t.Fatalf("GizmoMode = %v, want Translate", ed.GizmoMode) } checkDrawOps("3D Translate") - app.Press("id:gizmo-rotate") + app.Press("id:tool-rotate") if ed.GizmoMode != editor.Gizmo3DRotate { t.Fatalf("GizmoMode = %v, want Rotate", ed.GizmoMode) } checkDrawOps("3D Rotate") - app.Press("id:gizmo-scale") + app.Press("id:tool-scale") if ed.GizmoMode != editor.Gizmo3DScale { t.Fatalf("GizmoMode = %v, want Scale", ed.GizmoMode) } From 89ad4ca18605cc84881a6eb7d3b8aee74d27c6bf Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 21:28:58 +0900 Subject: [PATCH 2/4] fix(editor): harden AI-first main layout lifecycle resets, theme/language reactivity, and scene tree tab sync --- packages/game/editor/asset_drawer_ui.go | 22 ++-- packages/game/editor/demo.go | 8 ++ .../editorcmd/main_layout_screenshot_test.go | 2 + packages/game/editor/main_layout_test.go | 88 ++++++++++++++- packages/game/editor/main_layout_ui.go | 101 +++++++++++++----- packages/game/editor/overlays_ui.go | 4 +- packages/game/editor/project.go | 11 ++ packages/game/editor/scenefile.go | 2 + packages/game/editor/scenetree.go | 55 ++++++---- packages/game/editor/settings_pages_test.go | 2 +- packages/game/editor/settings_window_test.go | 18 ++-- packages/game/editor/state.go | 1 + packages/game/editor/tabs.go | 10 ++ 13 files changed, 256 insertions(+), 68 deletions(-) diff --git a/packages/game/editor/asset_drawer_ui.go b/packages/game/editor/asset_drawer_ui.go index 694270a83..9286be436 100644 --- a/packages/game/editor/asset_drawer_ui.go +++ b/packages/game/editor/asset_drawer_ui.go @@ -52,7 +52,6 @@ func sanitizeAssetTestID(s string) string { // LeftRailSwitchView renders the Scene / Assets segmented switch at the top of the left rail, // matching docs/design/editor/Assets.dc.html screen 1 with Spec.dc.html tokens. func LeftRailSwitchView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { - p := ed.SpecPalette(cx) sceneTabRef := &core.Ref{} if ed.focus.ctrl != nil { ed.focus.ctrl.registerCandidate(cx, RegionSceneTree, sceneTabRef, nil) @@ -137,15 +136,18 @@ func LeftRailSwitchView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) co base.RadioGroup{ TestID: "left-rail-mode-group", Label: ed.T("region.sceneTree"), - Style: core.Style{ - FlexGrow: 1, - Direction: core.Row, - Gap: 2, - Padding: core.All(3), - CornerRadius: specRadiusButton, - Background: p.Raised, - BorderWidth: 1, - BorderColor: p.LineRaised, + StyleFunc: func() core.Style { + cur := ed.SpecPalette(cx) + return core.Style{ + FlexGrow: 1, + Direction: core.Row, + Gap: 2, + Padding: core.All(3), + CornerRadius: specRadiusButton, + Background: cur.Raised, + BorderWidth: 1, + BorderColor: cur.LineRaised, + } }, Children: []core.Node{ modeBtn("rail-mode-scene", "Scene", LeftRailScene), diff --git a/packages/game/editor/demo.go b/packages/game/editor/demo.go index 782eafba8..e9776a167 100644 --- a/packages/game/editor/demo.go +++ b/packages/game/editor/demo.go @@ -141,6 +141,10 @@ func (e *Editor) OpenDemo() error { if err := e.OnOpenDemo(); err != nil { return err } + e.sceneOpenErr = nil + e.projectLoading = false + e.projectLoadingPath = "" + e.proposedNewObjects = nil e.setStartScreenEntered() e.notify() return nil @@ -150,6 +154,10 @@ func (e *Editor) OpenDemo() error { return err } } + e.sceneOpenErr = nil + e.projectLoading = false + e.projectLoadingPath = "" + e.proposedNewObjects = nil e.CancelInspectorScrub() e.resetInspectorSessionState() e.resetFirstRunFlow() diff --git a/packages/game/editor/editorcmd/main_layout_screenshot_test.go b/packages/game/editor/editorcmd/main_layout_screenshot_test.go index 6246aec1e..ee69b8576 100644 --- a/packages/game/editor/editorcmd/main_layout_screenshot_test.go +++ b/packages/game/editor/editorcmd/main_layout_screenshot_test.go @@ -84,6 +84,7 @@ func TestMainLayoutMacOSScreenshots(t *testing.T) { if err != nil { t.Fatal(err) } + t.Cleanup(func() { _ = ed.Close() }) if err := ed.OpenProject(dir); err != nil { t.Fatal(err) } @@ -132,6 +133,7 @@ func TestMainLayoutMacOSScreenshots(t *testing.T) { if err != nil { t.Fatal(err) } + t.Cleanup(func() { _ = ed.Close() }) app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return editor.EditorView(cx, ed) }, nsgotest.Size(1440, 900), nsgotest.Environment(core.Environment{ diff --git a/packages/game/editor/main_layout_test.go b/packages/game/editor/main_layout_test.go index 93aebcb4a..7bdfdabab 100644 --- a/packages/game/editor/main_layout_test.go +++ b/packages/game/editor/main_layout_test.go @@ -380,7 +380,7 @@ func TestMainLayoutLegacyPanelsRemainReachable(t *testing.T) { close func() }{ {"Project Settings", editor.CmdProjectSettings, ed.ProjectSettingsOpen, func() { ed.SetProjectSettingsOpen(false) }}, - {"Editor Settings", editor.CmdEditorSettings, ed.EditorSettingsOpen, func() { ed.SetEditorSettingsOpen(false) }}, + {"Editor Settings", editor.CmdEditorSettings, ed.SettingsOpen, func() { ed.CloseSettings() }}, {"Audio Mixer", editor.CmdAudioMixer, ed.AudioMixerOpen, func() { ed.SetAudioMixerOpen(false) }}, {"Input Map", editor.CmdInputMap, ed.InputMapOpen, func() { ed.SetInputMapOpen(false) }}, {"Strings / Localization", editor.CmdLocalization, ed.LocalizationOpen, func() { _ = ed.ExecuteCommand(editor.CmdLocalization) }}, @@ -544,9 +544,95 @@ func TestMainLayoutEmptyLoadingAndErrorStates(t *testing.T) { if !app.Exists("id:viewport-error-state") { t.Fatal("expected error state after OpenScene on missing project scene") } + if app.Exists("id:viewport-overlay-bar") { + t.Fatal("viewport bottom bar remained mounted behind error overlay") + } app.Press("id:viewport-error-dismiss") app.Settle() if app.Exists("id:viewport-error-state") || ed.SceneOpenError() != nil { t.Fatal("Dismiss did not clear scene-open error state") } } + +// TestMainLayoutHardening verifies Agent tab preservation on non-tree selection, +// deterministic multi-component kind classification, and lifecycle resets for +// loading/error/proposed-new states (#1007). +func TestMainLayoutHardening(t *testing.T) { + ed, dir := setupMainLayoutProject(t) + ed.SetProposedNewObjectIDs([]string{"slime_01"}) + ed.SetRightRailTab(editor.RightTabAgent) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), focusDesktopEnv) + app.Settle() + + // 1. Selecting an object outside the scene tree (e.g. canvas click / agent action) + // must NOT yank the right rail away from the Agent tab. + app.Post(func() { ed.SelectObject("knight") }) + app.Settle() + if ed.RightRailTab() != editor.RightTabAgent { + t.Fatalf("programmatic/canvas selection switched right rail to %v, want RightTabAgent", ed.RightRailTab()) + } + // Clicking a row in the scene tree DOES switch to Inspector. + app.Press("id:scene-tree-label-door_trigger") + app.Settle() + if ed.RightRailTab() != editor.RightTabInspector { + t.Fatalf("scene tree row click gave right rail %v, want RightTabInspector", ed.RightRailTab()) + } + + // 2. SceneRailObjectKind is deterministic even when an object carries multiple kind components. + app.Post(func() { + if err := ed.SetComponentField("door_trigger", "light", "intensity", 1.0); err != nil { + t.Error(err) + } + if err := ed.SetComponentField("door_trigger", "camera", "zoom", 1.0); err != nil { + t.Error(err) + } + }) + app.Settle() + for i := 0; i < 32; i++ { + if got := ed.SceneRailObjectKind("door_trigger"); got != "camera" { + t.Fatalf("iteration %d: SceneRailObjectKind = %q, want deterministic \"camera\"", i, got) + } + } + + // 3. Failed OpenProjectScene while ProjectLoading is true transitions to WorkspaceSceneError + // (never stuck in WorkspaceLoading), and SelectTab / OpenDemo clear stale errors & proposedNewObjects. + app.Post(func() { + ed.SetProjectLoading(true, filepath.Join(dir, "game.yaml")) + _ = ed.OpenProjectScene(dir, filepath.Join(dir, "scenes", "missing.scene.yaml")) + }) + app.Settle() + if ed.ProjectLoading() { + t.Fatal("ProjectLoading remained true after failed OpenProjectScene") + } + if ed.WorkspaceState() != editor.WorkspaceSceneError { + t.Fatalf("WorkspaceState = %v, want WorkspaceSceneError", ed.WorkspaceState()) + } + app.Post(func() { + if err := ed.SelectTab(ed.ActiveTab()); err != nil { + t.Error(err) + } + }) + app.Settle() + if ed.SceneOpenError() != nil { + t.Fatal("SelectTab on active valid tab did not clear SceneOpenError") + } + + // OpenDemo clears proposedNewObjects and sceneOpenErr cleanly. + app.Post(func() { + ed.SetProposedNewObjectIDs([]string{"slime_01"}) + _ = ed.OpenScene("scenes/missing.scene.yaml") + if err := ed.OpenDemo(); err != nil { + t.Error(err) + } + }) + app.Settle() + if ed.SceneOpenError() != nil { + t.Fatal("OpenDemo did not clear SceneOpenError") + } + if ed.IsObjectProposedNew("slime_01") { + t.Fatal("OpenDemo did not clear proposedNewObjects") + } +} diff --git a/packages/game/editor/main_layout_ui.go b/packages/game/editor/main_layout_ui.go index bad5cd058..aad85d2cc 100644 --- a/packages/game/editor/main_layout_ui.go +++ b/packages/game/editor/main_layout_ui.go @@ -40,12 +40,13 @@ const ( // SceneOpenError captures the structured details of a failed scene open // (covering missing files and YAML/schema errors from open_errors_test.go). type SceneOpenError struct { - Path string - Line int - Column int - Message string - Fix string - Err error + Path string + Line int + Column int + Message string + Fix string + Err error + openPath string } // Inline Lucide stroke icons (1.8 px stroke at 15 px, currentColor, decorative / aria-hidden in core.Icon). @@ -67,9 +68,10 @@ func (e *Editor) recordSceneOpenError(filePath string, err error) { return } se := &SceneOpenError{ - Path: filePath, - Message: err.Error(), - Err: err, + Path: filePath, + Message: err.Error(), + Err: err, + openPath: filePath, } var le *loaderr.Error if errors.As(err, &le) && le != nil { @@ -86,6 +88,8 @@ func (e *Editor) recordSceneOpenError(filePath string, err error) { if se.Fix == "" { se.Fix = "Check that the scene file exists and contains valid YAML." } + e.projectLoading = false + e.projectLoadingPath = "" e.sceneOpenErr = se e.Status = "Failed to open " + filepath.Base(se.Path) e.notify() @@ -114,7 +118,10 @@ func (e *Editor) RetryOpenScene() error { if e == nil || e.sceneOpenErr == nil { return nil } - p := e.sceneOpenErr.Path + p := e.sceneOpenErr.openPath + if p == "" { + p = e.sceneOpenErr.Path + } if p == "" { e.ClearSceneOpenError() return nil @@ -190,20 +197,22 @@ func (e *Editor) WorkspaceState() WorkspaceState { return WorkspaceReady } -// workspaceStateKey returns a digest of WorkspaceState plus loading/error details so -// reactive memos re-render when one scene-open error is replaced by another. +// workspaceStateKey returns a digest of WorkspaceState plus loading/error details and +// resolved language so reactive memos re-render when one scene-open error is replaced +// by another or when the editor language changes. func (e *Editor) workspaceStateKey() string { ws := e.WorkspaceState() + lang := e.ResolvedLanguage() switch ws { case WorkspaceLoading: - return fmt.Sprintf("loading|%s", e.projectLoadingPath) + return fmt.Sprintf("loading|%s|%s", lang, e.projectLoadingPath) case WorkspaceSceneError: if se := e.sceneOpenErr; se != nil { - return fmt.Sprintf("error|%s|%d|%d|%s|%s", se.Path, se.Line, se.Column, se.Message, se.Fix) + return fmt.Sprintf("error|%s|%s|%d|%d|%s|%s", lang, se.Path, se.Line, se.Column, se.Message, se.Fix) } - return "error|" + return "error|" + lang default: - return fmt.Sprintf("state|%d", ws) + return fmt.Sprintf("state|%s|%d", lang, ws) } } @@ -436,16 +445,26 @@ func (e *Editor) SceneRailObjectKind(id string) string { if len(obj.Children) > 0 && obj.Sprite == nil { return "group" } + var hasCamera, hasLight, hasTrigger bool for name := range obj.Components { switch strings.ToLower(name) { - case "trigger", "trigger2d", "trigger3d": - return "trigger" - case "light", "light2d", "light3d": - return "light" case "camera", "camera2d", "camera3d": - return "camera" + hasCamera = true + case "light", "light2d", "light3d": + hasLight = true + case "trigger", "trigger2d", "trigger3d": + hasTrigger = true } } + if hasCamera { + return "camera" + } + if hasLight { + return "light" + } + if hasTrigger { + return "trigger" + } if obj.Sprite != nil { return "sprite" } @@ -1041,6 +1060,8 @@ func mainHeaderView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], dirty }, // Flexible spacer before trailing actions. core.View{Style: core.Style{FlexGrow: 1}}, + // Live agent state pill (#1013): hidden when idle, shows working / waiting / pending review Keep & Revert. + toolbarAgentPillView(cx, ed, rev), // Right: History (⌘Y), Search ⌘K, Play (⌘P) as the one primary button. core.View{ Style: core.Style{ @@ -1273,11 +1294,13 @@ func leftRailSceneView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor }) darkMemo := core.NewMemo(cx, func() bool { _ = rev.Get() - return cx.Dark() + return ed.SpecPalette(cx).Dark }) filesKey := core.NewMemo(cx, func() string { _ = rev.Get() var b strings.Builder + b.WriteString(ed.ResolvedLanguage()) + b.WriteByte('|') b.WriteString(ed.ScenePath) b.WriteByte('|') b.WriteString(ed.FilePath) @@ -1438,7 +1461,7 @@ func leftRailSceneView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor testID: "rail-file-scene", path: sp, dot: p.Accent.Fg, - onOpen: func() { _ = ed.OpenProjectFile(sp) }, + onOpen: func() { ed.report(ed.OpenProjectFile(sp)) }, }) } else if ed.FilePath != "" { fp := filepath.Base(ed.FilePath) @@ -1495,9 +1518,10 @@ func leftRailSceneView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor }, }) } else { + fileItems := make([]core.Node, 0, len(entries)) for _, ent := range entries { e := ent - rows = append(rows, base.Button{ + fileItems = append(fileItems, base.Button{ TestID: e.testID, Label: e.path, Style: core.Style{ @@ -1543,6 +1567,18 @@ func leftRailSceneView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor }, }) } + rows = append(rows, core.Scroll{ + Style: core.Style{ + MaxHeight: core.Pt(160), + Width: core.Pct(100), + }, + Children: []core.Node{ + core.View{ + Style: core.Style{Gap: specSpace4}, + Children: fileItems, + }, + }, + }) } return core.View{ TestID: "left-rail-files", @@ -1613,7 +1649,7 @@ func viewportWorkspaceStateOverlay(cx *core.Scope, ed *Editor, rev *core.Signal[ }) darkMemo := core.NewMemo(cx, func() bool { _ = rev.Get() - return cx.Dark() + return ed.SpecPalette(cx).Dark }) return core.Dynamic(func(cx *core.Scope) core.Node { @@ -2236,7 +2272,12 @@ func mainStatusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor ed.report(ed.OpenChangesPanel()) }, Children: []core.Node{ - specIcon(lucide.GitBranch, 12, ed.SpecPalette(cx).TextFaint), + core.Icon{ + SVG: lucide.GitBranch(), + StyleFunc: func() core.Style { + return core.Style{Width: core.Pt(12), Height: core.Pt(12), Color: ed.SpecPalette(cx).TextFaint, FlexShrink: 0} + }, + }, core.Text{ ContentFunc: func() string { _ = rev.Get() @@ -2272,7 +2313,12 @@ func mainStatusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor ed.report(ed.OpenMergeConflict("")) }, Children: []core.Node{ - specIcon(lucide.GitMerge, 12, ed.SpecPalette(cx).Warning.Fg), + core.Icon{ + SVG: lucide.GitMerge(), + StyleFunc: func() core.Style { + return core.Style{Width: core.Pt(12), Height: core.Pt(12), Color: ed.SpecPalette(cx).Warning.Fg, FlexShrink: 0} + }, + }, core.Text{ ContentFunc: func() string { _ = rev.Get() @@ -2301,6 +2347,7 @@ func mainStatusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor TestID: "status-playtest-report", Label: "Playtest Report", StyleFunc: func() core.Style { + _ = rev.Get() cur := ed.SpecPalette(cx) st := statusBtnStyle(false) st.BorderWidth = 1 diff --git a/packages/game/editor/overlays_ui.go b/packages/game/editor/overlays_ui.go index 180df83f0..ce006c67c 100644 --- a/packages/game/editor/overlays_ui.go +++ b/packages/game/editor/overlays_ui.go @@ -18,12 +18,12 @@ import ( func viewportOverlaysBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { visible := core.NewMemo(cx, func() bool { _ = rev.Get() - return ed.ViewMode == ViewMode2D && !ed.Playing() + return ed.ViewMode == ViewMode2D && !ed.Playing() && ed.WorkspaceState() == WorkspaceReady }) overlayListKey := core.NewMemo(cx, func() string { _ = rev.Get() var b strings.Builder - if cx.Dark() { + if ed.SpecPalette(cx).Dark { b.WriteString("D:") } else { b.WriteString("L:") diff --git a/packages/game/editor/project.go b/packages/game/editor/project.go index 76c6d9a5e..4ffbdc885 100644 --- a/packages/game/editor/project.go +++ b/packages/game/editor/project.go @@ -29,19 +29,29 @@ func (e *Editor) OpenProjectScene(path, scene string) error { // openProject opens the project file at path and, when withScene is set, the scene file at scene, or else the project's main scene when it names one. func (e *Editor) openProject(path, scene string, withScene bool) error { + clearLoading := func() { + if e.projectLoading || e.projectLoadingPath != "" { + e.projectLoading = false + e.projectLoadingPath = "" + e.notify() + } + } if info, err := os.Stat(path); err == nil && info.IsDir() { path = filepath.Join(path, project.FileName) } data, err := os.ReadFile(path) if err != nil { + clearLoading() return err } f, err := project.Parse(data) if err != nil { + clearLoading() return fmt.Errorf("%s: %w", path, err) } saved, err := project.Encode(f) if err != nil { + clearLoading() return err } var openedDoc *sceneformat.SceneDoc @@ -118,6 +128,7 @@ func (e *Editor) openProject(path, scene string, withScene bool) error { e.sceneOpenErr = nil e.projectLoading = false e.projectLoadingPath = "" + e.proposedNewObjects = nil // Save the views of the project closing before replacing tabs. e.saveViewStateQuietly() if e.playing { diff --git a/packages/game/editor/scenefile.go b/packages/game/editor/scenefile.go index f77742982..9bb2231fb 100644 --- a/packages/game/editor/scenefile.go +++ b/packages/game/editor/scenefile.go @@ -480,6 +480,8 @@ func (e *Editor) RevertScene() error { e.CancelTileStroke() e.connPick = nil e.CancelGridMapStroke() + e.sceneOpenErr = nil + e.proposedNewObjects = nil e.sceneSaved = saved e.recordSceneDiskSnapshot(e.FilePath, data) e.History.Execute(&replaceSceneCmd{ed: e, label: "Revert scene", before: e.Doc.Clone(), after: doc}) diff --git a/packages/game/editor/scenetree.go b/packages/game/editor/scenetree.go index a008e011a..f7a97173f 100644 --- a/packages/game/editor/scenetree.go +++ b/packages/game/editor/scenetree.go @@ -148,29 +148,40 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No // A press on a row selects its object(s) in the editor (supporting Shift/Mod multi-selection), or makes its layer the active one. // While connection target pick mode is active, pressing an object row picks it as the target without changing SelectedID, and pressing a layer row is ignored so pick mode and SelectedID stay intact. var ignorePickKey sceneTreeKey - var syncingFromEditor bool + var syncedFromEditor bool + var syncedCursor sceneTreeKey + var syncedIDs []string + recordEditorSync := func(cursor sceneTreeKey, ids []string) { + syncedFromEditor = true + syncedCursor = cursor + syncedIDs = slices.Clone(ids) + } syncTreeToEditor := func() { - syncingFromEditor = true - defer func() { syncingFromEditor = false }() ids := ed.SelectedIDs() if len(ids) == 0 { + recordEditorSync(sceneTreeKey{}, nil) selection.Clear() selection.SetCursor(nil) return } keys := make([]any, 0, len(ids)) + synced := make([]string, 0, len(ids)) for _, id := range ids { if k := keyOf(id); k.id != "" { keys = append(keys, k) + synced = append(synced, id) } } if len(keys) == 0 { + recordEditorSync(sceneTreeKey{}, nil) selection.Clear() selection.SetCursor(nil) return } + pk := keyOf(ed.SelectedID) + recordEditorSync(pk, synced) selection.Set(keys...) - if pk := keyOf(ed.SelectedID); pk.id != "" { + if pk.id != "" { selection.SetCursor(pk) } } @@ -179,8 +190,20 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No keys := selection.Keys() chosen := selection.Has(cur) cx.Untrack(func() { - if syncingFromEditor { - return + objIDs := make([]string, 0, len(keys)) + for _, raw := range keys { + if tk, ok := raw.(sceneTreeKey); ok && tk.id != "" && !tk.removed && !slices.Contains(objIDs, tk.id) { + objIDs = append(objIDs, tk.id) + } + } + if syncedFromEditor { + matched := cur == syncedCursor && sameIDSet(objIDs, syncedIDs) + syncedFromEditor = false + syncedCursor = sceneTreeKey{} + syncedIDs = nil + if matched { + return + } } if ed.PickingConnectionTarget() { if cur == (sceneTreeKey{}) { @@ -208,21 +231,14 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No if cur.layer != "" && cur.id == "" && chosen { // A layer's row is selected in place of any object selection. if selection.Len() != 1 { - syncingFromEditor = true + recordEditorSync(cur, nil) selection.Set(cur) - syncingFromEditor = false } ed.ClearSelection() ed.SetActiveLayer(cur.layer) ed.SetRightRailTab(RightTabInspector) return } - objIDs := make([]string, 0, len(keys)) - for _, raw := range keys { - if tk, ok := raw.(sceneTreeKey); ok && tk.id != "" && !tk.removed && !slices.Contains(objIDs, tk.id) { - objIDs = append(objIDs, tk.id) - } - } if len(objIDs) > 0 { primary := objIDs[len(objIDs)-1] if cur.id != "" && chosen && slices.Contains(objIDs, cur.id) { @@ -258,10 +274,9 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No } } if cur, _ := selection.Cursor().(sceneTreeKey); hasObj || cur.id != "" { - syncingFromEditor = true + recordEditorSync(sceneTreeKey{}, nil) selection.Clear() selection.SetCursor(nil) - syncingFromEditor = false } return } @@ -277,12 +292,14 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No return } wantKeys := make([]any, 0, len(ids)) + synced := make([]string, 0, len(ids)) for _, id := range ids { k := keyOf(id) if k.id == "" { continue } wantKeys = append(wantKeys, k) + synced = append(synced, id) path := ed.resolvedObjectPath(k.id) setOpen(sceneTreeKey{layer: k.layer}, true) for _, a := range path[:max(len(path)-1, 0)] { @@ -292,7 +309,7 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No if len(wantKeys) == 0 { return } - syncingFromEditor = true + recordEditorSync(pk, synced) selection.Set(wantKeys...) if pk.id != "" { selection.SetCursor(pk) @@ -300,7 +317,6 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No listRef.ScrollToIndexAt(row, 0.5, 0, false) } } - syncingFromEditor = false }) }) @@ -731,6 +747,9 @@ func objectRow(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], k sceneTree core.Show{ When: func() bool { _ = rev.Get() + if ch, ok := ed.AgentObjectChange(id); ok && (ch.Kind == AgentChangeAdded || ch.Kind == AgentChangeChanged) { + return false + } return ed.IsObjectProposedNew(id) }, Then: func(cx *core.Scope) core.Node { diff --git a/packages/game/editor/settings_pages_test.go b/packages/game/editor/settings_pages_test.go index 2de595bd9..e0e5fb881 100644 --- a/packages/game/editor/settings_pages_test.go +++ b/packages/game/editor/settings_pages_test.go @@ -40,11 +40,11 @@ func TestSettingsPagesNavigationAndToolbarTriggers(t *testing.T) { wantTitle string wantScope string }{ + {editor.CmdEditorSettings, editor.SettingsPageGeneral, "editor-settings-dialog", "General", "This computer"}, {editor.CmdProjectSettings, editor.SettingsPageProject, "project-settings-panel", "Project", "Project · game.yaml"}, {editor.CmdInputMap, editor.SettingsPageInput, "input-map-panel", "Input map", "Project · game.yaml"}, {editor.CmdAudioMixer, editor.SettingsPageAudio, "audio-mixer-panel", "Audio buses", "Project · game.yaml"}, {editor.CmdExport, editor.SettingsPageExport, "export-panel", "Export", "Project · game.yaml"}, - {editor.CmdEditorSettings, editor.SettingsPageGeneral, "editor-settings-dialog", "General", "This computer"}, } for _, tc := range cases { diff --git a/packages/game/editor/settings_window_test.go b/packages/game/editor/settings_window_test.go index a21cc4e92..23b43434f 100644 --- a/packages/game/editor/settings_window_test.go +++ b/packages/game/editor/settings_window_test.go @@ -37,10 +37,10 @@ func TestSettingsWindowCmdCommaAndEscRestoresFocus(t *testing.T) { })) // 1. Focus a toolbar control, press ⌘, to open Settings, and press Esc to restore exact focus. - app.Focus("id:toolbar-save") + app.Focus("id:toolbar-history") app.Settle() - if !viewOrDescendantFocused(app.Find("id:toolbar-save")) { - t.Fatal("toolbar-save did not receive initial focus") + if !viewOrDescendantFocused(app.Find("id:toolbar-history")) { + t.Fatal("toolbar-history did not receive initial focus") } app.Key("mod+,") @@ -60,7 +60,7 @@ func TestSettingsWindowCmdCommaAndEscRestoresFocus(t *testing.T) { t.Fatal("expected meta lines on General and Viewport navigation entries") } - // Pressing Escape while focused inside settings-search still closes Settings and restores toolbar-save. + // Pressing Escape while focused inside settings-search still closes Settings and restores toolbar-history. app.Focus("id:settings-search") app.Settle() app.Key("escape") @@ -68,8 +68,8 @@ func TestSettingsWindowCmdCommaAndEscRestoresFocus(t *testing.T) { if ed.SettingsOpen() || app.Exists("id:settings-view") { t.Fatal("Escape from settings-search did not close Settings view") } - if !viewOrDescendantFocused(app.Find("id:toolbar-save")) { - t.Fatal("Escape did not return focus to toolbar-save") + if !viewOrDescendantFocused(app.Find("id:toolbar-history")) { + t.Fatal("Escape did not return focus to toolbar-history") } // 2. Without an open project, ⌘, still opens Settings and omits empty PROJECT · game.yaml group. @@ -85,7 +85,7 @@ func TestSettingsWindowCmdCommaAndEscRestoresFocus(t *testing.T) { Dark: true, Locale: "en-US", })) - appNoProj.Focus("id:toolbar-editor-settings") + appNoProj.Focus("id:toolbar-palette") appNoProj.Settle() appNoProj.Key("mod+,") appNoProj.Settle() @@ -100,8 +100,8 @@ func TestSettingsWindowCmdCommaAndEscRestoresFocus(t *testing.T) { if edNoProj.SettingsOpen() { t.Fatal("Escape did not close Settings without a project") } - if !viewOrDescendantFocused(appNoProj.Find("id:toolbar-editor-settings")) { - t.Fatal("Escape did not return focus to toolbar-editor-settings") + if !viewOrDescendantFocused(appNoProj.Find("id:toolbar-palette")) { + t.Fatal("Escape did not return focus to toolbar-palette") } // 3. On the Start screen (top-level Settings mount), ⌘, opens Settings and Esc restores focus to the Start screen opener. diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index fbfbc184d..3ff42f2bc 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -1771,6 +1771,7 @@ func (e *Editor) openFileWithLayers(path string, layers *sceneformat.PhysicsLaye } } e.sceneOpenErr = nil + e.proposedNewObjects = nil e.activateNewTab(doc, saved, path) e.recordSceneDiskSnapshot(path, data) e.syncActiveTab() diff --git a/packages/game/editor/tabs.go b/packages/game/editor/tabs.go index 0df463a59..374e36ae9 100644 --- a/packages/game/editor/tabs.go +++ b/packages/game/editor/tabs.go @@ -509,8 +509,14 @@ func (e *Editor) SelectTab(index int) error { return fmt.Errorf("editor: tab index %d out of range", index) } if index == e.activeTab { + if e.sceneOpenErr != nil { + e.sceneOpenErr = nil + e.notify() + } return nil } + e.sceneOpenErr = nil + e.proposedNewObjects = nil e.saveViewStateQuietly() e.ExitHistoryPreview() e.cancelTransientInteraction() @@ -683,6 +689,8 @@ func (e *Editor) CloseTab(index int) error { closedID := e.tabs[index].id if len(e.tabs) == 1 { + e.sceneOpenErr = nil + e.proposedNewObjects = nil e.saveViewStateQuietly() e.cancelTransientInteraction() doc := DefaultSceneDoc() @@ -735,6 +743,8 @@ func (e *Editor) CloseTab(index int) error { return nil } + e.sceneOpenErr = nil + e.proposedNewObjects = nil e.saveViewStateQuietly() e.cancelTransientInteraction() e.tabs = append(e.tabs[:index], e.tabs[index+1:]...) From df3b7641c421ec2abcec8b98f8886d3129f82a48 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Fri, 27 Nov 2026 03:22:01 +0900 Subject: [PATCH 3/4] fix(editor): surface viewport sketch status and hint in AI-first main status bar --- packages/game/editor/main_layout_ui.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/game/editor/main_layout_ui.go b/packages/game/editor/main_layout_ui.go index aad85d2cc..a56ea8202 100644 --- a/packages/game/editor/main_layout_ui.go +++ b/packages/game/editor/main_layout_ui.go @@ -2139,10 +2139,10 @@ func mainStatusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor TestID: "status-pointer-coords", ContentFunc: func() string { _ = rev.Get() - _ = pointerRev.Get() - if ed.WorkspaceState() != WorkspaceReady { + if ed.WorkspaceState() != WorkspaceReady || (!ed.Playing() && ed.ViewMode == ViewMode2D && ed.SketchActive()) { return "" } + _ = pointerRev.Get() if ed.ViewMode == ViewMode2D { if wx, wy, ok := ed.ViewportPointer2DWorld(); ok { return fmt.Sprintf("%d, %d", int(math.Round(float64(wx))), int(math.Round(float64(wy)))) @@ -2180,6 +2180,15 @@ func mainStatusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor } return s } + if !ed.Playing() && ed.SketchActive() { + _ = pointerRev.Get() + sx, sy := ed.SketchStatusSceneCoords() + return fmt.Sprintf("Sketch layer · scene %d, %d · Sketch · %s", + int(math.Round(float64(sx))), + int(math.Round(float64(sy))), + ed.SketchTool().String(), + ) + } tool := ed.toolLabel() switch ed.Tool { case ToolPaintTile, ToolFillTile, ToolRectTile, ToolLineTile: @@ -2219,6 +2228,9 @@ func mainStatusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor if ed.BuildErr != nil { return ed.T("status.buildError", l10n.Param("error", ed.BuildErr.Error())) } + if !ed.Playing() && ed.ViewMode == ViewMode2D && ed.SketchActive() { + return ed.T("sketch.statusHint") + } if ed.Status == "" || ed.Status == "Ready" { return "" } From 1772aa49a0a84efbc2d2abae69957bfe96543755 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Fri, 27 Nov 2026 03:47:48 +0900 Subject: [PATCH 4/4] fix(editor): use mod+, in dialog focus test and open file browser in agent turn navigation test --- packages/game/editor/agent_turn_test.go | 1 + packages/game/editor/focus_regions_test.go | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/game/editor/agent_turn_test.go b/packages/game/editor/agent_turn_test.go index c74244c3c..6c59a4b1b 100644 --- a/packages/game/editor/agent_turn_test.go +++ b/packages/game/editor/agent_turn_test.go @@ -183,6 +183,7 @@ func TestAgentTurnPendingPromptsGuardNavigation(t *testing.T) { } // Opening another scene from the file browser with a pending turn must prompt Keep / Revert / Cancel! + openFileBrowserInUI(app, ed) app.DoublePress("id:files-row-scenes/other.scene.yaml") app.Settle() if !ed.PendingTurnPromptOpen() || !app.Exists("id:pending-turn-dialog") { diff --git a/packages/game/editor/focus_regions_test.go b/packages/game/editor/focus_regions_test.go index 7bf4e7c49..821286d5b 100644 --- a/packages/game/editor/focus_regions_test.go +++ b/packages/game/editor/focus_regions_test.go @@ -436,11 +436,11 @@ func TestDialogTrapsFocusAndEscRestoresOpener(t *testing.T) { t.Fatalf("after Esc closed Shortcuts Sheet, focus = %q, want toolbar-history", gotID) } - // 2. Open unified Settings view via Cmd+Shift+, while focused on toolbar-history, verify F6 is blocked, and Esc restores toolbar-history. - app.Key("meta+shift+,") + // 2. Open unified Settings view via Cmd+, while focused on toolbar-history, verify F6 is blocked, and Esc restores toolbar-history. + app.Key("mod+,") app.Settle() if !ed.SettingsOpen() { - t.Fatal("expected Settings view to open on Cmd+Shift+,") + t.Fatal("expected Settings view to open on Cmd+,") } app.Key("f6") app.Settle()