diff --git a/.trellis/tasks/08-26-direct-manipulation-road-editor/task.json b/.trellis/tasks/08-26-direct-manipulation-road-editor/task.json index 82505da..ce214b1 100644 --- a/.trellis/tasks/08-26-direct-manipulation-road-editor/task.json +++ b/.trellis/tasks/08-26-direct-manipulation-road-editor/task.json @@ -26,7 +26,9 @@ "08-27-junction-dominated-roads", "08-28-edit-interaction-polish", "08-28-junction-control-offsets", - "08-28-crosswalk-element-editor" + "08-28-crosswalk-element-editor", + "08-31-parameter-panel-binding", + "08-31-constraint-range-validation" ], "parent": null, "relatedFiles": [ diff --git a/.trellis/tasks/08-31-constraint-range-validation/check.jsonl b/.trellis/tasks/08-31-constraint-range-validation/check.jsonl new file mode 100644 index 0000000..9dd3234 --- /dev/null +++ b/.trellis/tasks/08-31-constraint-range-validation/check.jsonl @@ -0,0 +1 @@ +{"_example": "Fill with {\"file\": \"\", \"reason\": \"\"}. Put spec/research files only — no code paths. Run `python3 .trellis/scripts/get_context.py --mode packages` to list available specs. Delete this line once real entries are added."} diff --git a/.trellis/tasks/08-31-constraint-range-validation/implement.jsonl b/.trellis/tasks/08-31-constraint-range-validation/implement.jsonl new file mode 100644 index 0000000..9dd3234 --- /dev/null +++ b/.trellis/tasks/08-31-constraint-range-validation/implement.jsonl @@ -0,0 +1 @@ +{"_example": "Fill with {\"file\": \"\", \"reason\": \"\"}. Put spec/research files only — no code paths. Run `python3 .trellis/scripts/get_context.py --mode packages` to list available specs. Delete this line once real entries are added."} diff --git a/.trellis/tasks/08-31-constraint-range-validation/prd.md b/.trellis/tasks/08-31-constraint-range-validation/prd.md new file mode 100644 index 0000000..6265f04 --- /dev/null +++ b/.trellis/tasks/08-31-constraint-range-validation/prd.md @@ -0,0 +1,57 @@ +# 约束值范围的服务端校验与重放失效 + +## 目标 + +让 manifest 声明的取值范围与求解器实际接受的可行域一致,并让保存后因几何变化而越界的约束按既有 status 机制转 `stale`,而不是静默产出畸形几何。 + +缺口有**两个方向**,实测确认(见 `08-31-parameter-panel-binding/research/manifest-range-vs-solver.md`): + +1. **过松**——manifest 宣告的范围比求解器接受的宽。实测某 6.5m 道路的外缘偏移手柄声明 `±2.925`,但超过约 `±1` 即返回 `direct-edit-outer-edges-cross`。宣告范围约为可行域的 3 倍。 +2. **无校验**——求解器不检查 manifest 的 `min`/`max`,范围目前仅由客户端夹值实际约束。 + +方向 1 是用户可直接感知的(拖到一半几何就冻结),优先级高于方向 2。 + +## 已确认的事实 + +- `direct-edit-solver.js` 的 `applyConstraint` 分支(302、312、322 行附近)只校验 `Number.isFinite` 与非负,**未校验 manifest 声明的 `min` / `max`**。 +- 范围目前是纯客户端概念:manifest 下发它,`projection.ts:60` 的 `projectHandleValue` 夹它,仅此而已。今天没出事,只因拖拽是唯一写入通道且它必夹。 +- 部分范围是**动态的**:外缘偏移为 `±Math.max(0.1, width * 0.45)`,随道路宽度浮动;步行带固定 `0..8`;角部圆角固定 `0.5..30`。 +- 因此保存时合法的值,可能在道路几何变化后越界——重导入改变车道数、其它约束改变断面宽度均可触发。该类越界发生在保存之后的求解期,**客户端结构上无法拦截**。 +- 父 `design.md` 已为同类情形定义规则:"`boundaryIndex` ⋯ 重放时若车道数变化导致越界,该约束转 `stale`,不做近似映射。"数值范围越界属于同一类,只是未被写下。 +- `08-31-parameter-panel-binding` 引入第二条写入通道(数值输入)。该任务在客户端拦截越界输入,但那只覆盖输入当下,不覆盖本任务的场景。 + +## 范围 + +1. manifest 发布的 `min`/`max` 必须落在求解器实际接受的可行域内——宣告一个必被拒绝的极值等于骗用户。 +2. 求解器在应用约束时校验其值落在该 kind / 该锚点当前的合法范围内。 +3. 越界值产生**阻塞性诊断**,不静默夹值、不静默丢弃。 +4. 范围的计算与 manifest 中 `value.min` / `value.max` 的生成**共用同一处逻辑**,不得出现两份定义。 +5. 重放(重导入、几何版本变更)时,因范围变化而越界的约束转 `stale`,与 `boundaryIndex` 越界同等处理。 +6. rebase 响应的 status 计数与明细覆盖这一新的 `stale` 来源。 + +## 明确不做 + +- 不改变客户端拖拽的夹值行为(`projectHandleValue` 是渲染正确性的一部分)。 +- 不为越界约束做近似映射或自动修正——与父 `design.md` 的"不自动改值"一致。 +- 不新增约束 kind,不改动几何生成。 + +## 验收标准 + +- [ ] 复现 research 记录的场景:某 6.5m 道路的外缘偏移手柄,其发布的 `max` 不再是一个提交即被 `direct-edit-outer-edges-cross` 拒绝的值。 +- [ ] 对任一手柄,提交恰好等于 manifest `min` 或 `max` 的值不产生阻塞诊断(宣告即可用)。 +- [ ] 绕过客户端直接 POST 一个越界约束到 `/api/edit-preview`,返回阻塞性诊断而非畸形几何。 +- [ ] manifest 的 `min`/`max` 与求解器校验用的范围来自同一处代码,可由测试证明二者一致。 +- [ ] 构造一个"保存时合法、几何变化后越界"的场景(如缩窄道路使可行域下降),重放后该约束报 `stale`,且不参与求解。 +- [ ] `stale` 的原因在 rebase 响应中可区分于锚点丢失导致的 `stale`。 +- [ ] 既有的 `exact` 约束不因本改动被误判失效——回归现有 revision 编译结果不变。 +- [ ] `npm run format:check`、`npm run test`、`npm run test:client`、`npm run build` 全绿。 + +## 风险与门槛 + +- 范围收紧可能让**既有已保存约束**突然变 `stale`。上线前必须在真实 import 目录上跑一遍,确认影响面,并确保旧 revision 仍可打开并复现原结果(父 `design.md` 的可复现性要求)。 +- 范围的两份定义(manifest 生成处与校验处)若各写各的,会产生"手柄允许但求解器拒绝"的死区。第 3 条是硬要求。 + +## 关联 + +- 缺口由 `08-31-parameter-panel-binding` 的设计过程发现,详见该任务 `design.md` 的「已知缺口」。 +- 本任务不阻塞面板任务:面板的客户端校验独立成立。 diff --git a/.trellis/tasks/08-31-constraint-range-validation/task.json b/.trellis/tasks/08-31-constraint-range-validation/task.json new file mode 100644 index 0000000..463b361 --- /dev/null +++ b/.trellis/tasks/08-31-constraint-range-validation/task.json @@ -0,0 +1,26 @@ +{ + "id": "constraint-range-validation", + "name": "constraint-range-validation", + "title": "约束值范围的服务端校验与重放失效", + "description": "服务端补 manifest min/max 校验;保存后因几何变化导致的数值越界转 stale", + "status": "planning", + "dev_type": null, + "scope": null, + "package": null, + "priority": "P3", + "creator": "dingkang", + "assignee": "dingkang", + "createdAt": "2026-08-31", + "completedAt": null, + "branch": null, + "base_branch": "main", + "worktree_path": null, + "commit": null, + "pr_url": null, + "subtasks": [], + "children": [], + "parent": "08-26-direct-manipulation-road-editor", + "relatedFiles": [], + "notes": "", + "meta": {} +} \ No newline at end of file diff --git a/.trellis/tasks/08-31-parameter-panel-binding/check.jsonl b/.trellis/tasks/08-31-parameter-panel-binding/check.jsonl new file mode 100644 index 0000000..bd453d2 --- /dev/null +++ b/.trellis/tasks/08-31-parameter-panel-binding/check.jsonl @@ -0,0 +1,4 @@ +{"file":".trellis/spec/frontend/direct-edit-client.md","reason":"检查面板未写入 baseline source、控件值全部由 manifest 驱动、previewSeq 仲裁未被绕开。"} +{"file":".trellis/spec/frontend/state-management.md","reason":"检查聚焦/失焦的值所有权切换无第二真相来源,且中间态不被预览响应改写。"} +{"file":".trellis/spec/frontend/quality-guidelines.md","reason":"检查新增纯逻辑的单测覆盖与客户端质量门槛。"} +{"file":".trellis/spec/guides/code-reuse-thinking-guide.md","reason":"核对拖拽与输入两条通道汇合于同一个 draftFor,未出现并行实现。"} diff --git a/.trellis/tasks/08-31-parameter-panel-binding/design.md b/.trellis/tasks/08-31-parameter-panel-binding/design.md new file mode 100644 index 0000000..f331f24 --- /dev/null +++ b/.trellis/tasks/08-31-parameter-panel-binding/design.md @@ -0,0 +1,114 @@ +# 参数面板与数值双向绑定 · 设计 + +> 父任务 `08-26-direct-manipulation-road-editor/design.md` 仍是约束模型、求解边界与 API 合约的权威定义。本文只补充**第二条输入通道**引入的规则,不改变其中任何一条。 + +## 架构定位 + +本任务不触碰服务端。约束模型、求解器、handle manifest、revision 全部原样保留。改动完全落在客户端输入层: + +```text + ┌─ 拖拽(连续)──→ projectHandleValue() ─┐ +选中道路 → manifest ─┤ ├→ draftFor(handle, value) + └─ 输入框(离散)→ 解析 + 范围校验 ──────┘ ↓ + PreviewRequester + (80ms 防抖 + previewSeq 仲裁) + ↓ + EditSession.commit() +``` + +`draftFor(handle, value)`(`App.tsx:206`)本就是纯函数 `(手柄, 数字) → 草稿`。两条通道的唯一区别是**如何产生那个数字**以及**何时闭合 gesture**,汇合点之后完全一致。 + +## 不变量:取值范围 + +> **约束值永不超出 manifest 声明的 `[min, max]`。** +> +> - **连续输入**(拖拽、滑杆)在极限处**停止移动**。ghost 与手柄按夹后的值绘制,绝不跟随越界的光标。 +> - **离散输入**(数值框)**拒绝接受**越界值:标记非法、不发预览、不进 undo 栈、保留最后一个有效预览。范围提示可一键填入极值。 + +这是**一条规则的两种设备表达**,不是两套策略。 + +连续设备没有表达"拒绝"的手段——停止移动就是它的拒绝,而且是当场可见的:手柄停住、光标继续走。用户不会形成"我设成了 -24.1"这个信念。夹值理由见 `projection.ts:75` 的注释(ol-ext 探针把手柄拖到 -24.1m 而约束夹在 -5.4m,手柄指向一个不可能存在的路形)。 + +离散设备则相反:数字已经键入、Tab 已经按下,此时夹值是**事后篡改**。且失败模式不对称—— + +| 用户意图 | 夹值 | 拒绝 | +| --- | --- | --- | +| 打错(想输 2.4,输成 24) | 变成 5.4,看起来合理,可能永不被发现 | 立即可见 | +| 想拉满 | 如愿 | 多一步(或点范围提示一键填入) | + +拒绝错了只损失一次击键;夹值错了会把一个**看起来正常的错误值**送进下游编译与仿真。故取拒绝。 + +## 值的所有权 + +任一时刻,一个参数的显示值来源是**唯一**且由聚焦状态决定的: + +| 状态 | 显示值 | 理由 | +| --- | --- | --- | +| 未聚焦 | `handle.value.current` | 服务端权威回显 | +| 聚焦中 | 本地文本 draft | 保留 `1.`、`-`、空串等中间态 | + +必须如此的原因:`App.tsx:197` 在每次预览结算时 `setManifest(response.handles)` 整体替换 manifest。受控输入若直接绑定 `value.current`,键入 `1.` 触发的防抖预览返回后会把输入框冲成 `1`,小数点消失。 + +失焦即清 draft。此时 `value.current` 必然等于刚提交的值——因为 `direct-edit-solver.js:136` 的 `numericValue()` 直接回显约束里的数字,服务端不改写。**故不存在"请求值 vs 求解值"的双显示需求。** + +> 该结论依赖 solver 当前行为。若日后改为回写求解结果,本节规则失效,需同步重审。 + +## gesture 边界 + +`gestureIdentity()` 是懒创建的 operationId 单例,`commitGesture()` 释放它。它抽象的是"一段有始有终的操作",与指针无绑定关系,因此可原样承载键盘输入: + +| 阶段 | 拖拽 | 输入框 | 动作 | +| --- | --- | --- | --- | +| 开始 | `pointerdown` | `focus` | 铸 operationId | +| 进行 | `pointermove` | `onChange` | `requester.schedule()`,**不 commit** | +| 结束 | `pointerup` | `blur` / `Enter` | `requester.flush()` + `commitGesture()` | +| 放弃 | — | `Escape` | 回滚显示值 + `requester.cancel()` | + +`EditSession` 与 `gestureIdentity()` 无需改动。输入 `1.53` 产生一步 undo,而非四步。 + +滑杆(若实现)的 pointerdown/up 天然落在此表内,不引入新分支。 + +**保存路径**:`saveDirectEdits()` 必须在入口强制结算未闭合的 gesture。DOM 中 blur 先于 click 触发,直接点"保存"能赶上,但该顺序过于脆弱,不作为正确性依赖。 + +## 区间的单位分层 + +父 `design.md` 的坐标分层表规定持久化层只有米与归一化 station。显示层不受该表约束。 + +| 层 | 单位 | +| --- | --- | +| 持久化 / 传输 | `station` (0..1) | +| 面板显示与输入 | 米(`station × roadLengthMeters`) | + +**只在用户实际编辑时换算**,不在每次渲染时做 米→station→米 的往返,否则四舍五入会让数字自行漂移。`roadLengthMeters` 取自 `IntervalRangeHandle`,与 range 手柄同源。 + +区间由整条道路共享(`rangeDraftFor` 重锚该路全部约束),故在面板中**每条路一行**,不随手柄重复。 + +## 面板可表达而拖拽不能表达的操作 + +`value.current` 在无约束时回落基线(外缘偏移基线为 0),因此"未修改"与"显式设为 0"数值完全相同。`handle.constraintId` 仅在约束存在时出现,客户端据此区分。 + +由此得到一个拖拽结构上无法提供的能力:**删除约束**。拖拽只能设值,不能移除。面板每行提供"重置",删除该约束并使该行回到未修改态。 + +这是参数面板的实质增量,而非拖拽的镜像显示。 + +## 渲染性能 + +`handleDragEvent` 每次 mousemove 触发,而 `App.tsx` 是单个 974 行组件。拖拽值回流面板必须经 rAF 节流,不得直接 `setState`。 + +节流有效性需在扩大面板规模前验证——手柄当前仅 5~6 个,问题不会自行显现。 + +## 边界 + +- 面板不得成为第二套几何算法或第二个值的真相来源。范围、位置、`affects`、可编辑性一律只来自服务端 manifest。 +- 面板只呈现主地图拥有的 kind。路口 shape 三 kind 仍属 `JunctionTools`;保留区内手柄呈禁用态并显示 `disabledReason`。 +- 不新增约束 kind,不改动求解器。 + +## 已知缺口 + +服务端 `applyConstraint` 只校验 `Number.isFinite` 与非负,**不校验 manifest 的 `min`/`max`**。今日范围仅由客户端 `projectHandleValue` 的夹值实际约束。 + +外缘偏移的范围随道路宽度浮动(`±Math.max(0.1, width * 0.45)`),因此保存时合法的值可能在后续几何变化后越界。此类越界发生在保存之后的求解期,**客户端结构上无法拦截**。 + +父 `design.md` 已为 `boundaryIndex` 定义同类规则——"重放时若车道数变化导致越界,该约束转 `stale`,不做近似映射"——数值范围越界应同等处理。 + +属重放正确性,不属本任务;独立成任务。本任务的客户端校验不因该缺口存在而降级:范围在哪定义就在哪拦,并避免一次注定被拒的求解。 diff --git a/.trellis/tasks/08-31-parameter-panel-binding/implement.jsonl b/.trellis/tasks/08-31-parameter-panel-binding/implement.jsonl new file mode 100644 index 0000000..597fae5 --- /dev/null +++ b/.trellis/tasks/08-31-parameter-panel-binding/implement.jsonl @@ -0,0 +1,6 @@ +{"file":".trellis/spec/frontend/direct-edit-client.md","reason":"面板是第二条输入通道,必须继续遵守 manifest 驱动、baseline 不被写入、预览时序与图层所有权。"} +{"file":".trellis/spec/frontend/state-management.md","reason":"聚焦期本地 draft 与服务端 value.current 的所有权切换是本任务的核心状态规则,不得产生第二个值的真相来源。"} +{"file":".trellis/spec/frontend/component-guidelines.md","reason":"新增参数面板组件需符合既有组件结构与职责边界。"} +{"file":".trellis/spec/frontend/hook-guidelines.md","reason":"拖拽回流的 rAF 节流以 hook 承载,需符合既有 hook 约定。"} +{"file":".trellis/spec/guides/code-reuse-thinking-guide.md","reason":"输入通道必须复用 draftFor / PreviewRequester / EditSession,禁止复制出第二套预览与 undo 链路。"} +{"file":".trellis/tasks/08-26-direct-manipulation-road-editor/design.md","reason":"继承 v2 约束模型、坐标分层、预览时序与 handle manifest 的权威合同。"} diff --git a/.trellis/tasks/08-31-parameter-panel-binding/implement.md b/.trellis/tasks/08-31-parameter-panel-binding/implement.md new file mode 100644 index 0000000..a72744d --- /dev/null +++ b/.trellis/tasks/08-31-parameter-panel-binding/implement.md @@ -0,0 +1,84 @@ +# 实施计划 + +顺序按**风险递减**排列:每一步都有可独立验证的门禁,失败即停,不进入下一步。 + +## 0. 纯逻辑与测试夹具 + +- 在 `workbench/client/src/edit/` 新增参数值的纯逻辑:数值格式化/解析(保留 `1.`、`-`、空串中间态)、范围校验、`station ↔ 米` 换算。 +- 与现有 `meters.ts` / `projection.ts` / `selection.ts` 同侧,**不得 import OpenLayers**。 +- 失败优先的 vitest:越界判定的边界值、中间态解析不丢字符、米↔station 往返不漂移。 +- 门禁:新增模块的单测在 node 下跑通,且 `grep -r "from 'ol" ` 对新文件无命中。 + +## 1. 面板只读渲染 + +- 新增面板组件,遍历 `editHandles` 渲染:中文名、`value.current`、单位、`[min, max]`。**此步不可编辑。** +- 多个 `road-lane-divider` 按 `boundaryIndex` 分行;不可编辑手柄呈禁用态并显示 `disabledReason`。 +- 依 `handle.constraintId` 是否存在标记"已修改"。 +- 区间每条路一行,以米显示。 +- 验证:选中不同道路、选中含保留区的道路、选中多车道道路,面板结构正确。 +- 门禁:`directEdit` 开关关闭时面板不渲染、不请求 manifest,网络轨迹与 main 一致。 + +## 2. 拖拽 → 面板回流 + +- 拖拽值**直接写 DOM 节点**(ref + `textContent` / `value`),不经 React 渲染。 + `direct-edit-client.md` §7:rAF 合并是**最低要求**,"写到源头"才是生产规则;ghost 直接写 OL source,面板的等价物是直接写 DOM。 +- **禁止**在 `handleDragEvent` 中 `setState`;gesture 结束时才做一次 state 对账。 +- 禁止在 `setState` updater 内计算或读 OL 状态(§6)。 +- 验证:拖拽过程中面板数值实时跟随;用 render 计数确认**面板未新增任何渲染**。 + 注意门禁不是"拖拽期间渲染 0 次"——`onSettled` 的 `setManifest` 本就会在拖拽中随防抖预览触发渲染,那是服务端权威预览的固有代价,改动前就存在。要证明的是 `pointermove` 自身不再产生渲染。 +- 拖拽中落地的预览会把 manifest 换成滞后一个防抖周期的值,需保证数字不在两者间闪烁。 +- 门禁:节流有效性必须在此步证明。手柄当前仅 5~6 个,问题不会自行显现;跳过则后续无从归因。 + +## 3. 输入通道:预览、gesture 边界、commit + +- 输入框接入 `draftFor` → `PreviewRequester.schedule()`,复用 80ms 防抖与 `previewSeq` 仲裁。 +- gesture 边界按 `design.md` 表实现:`focus` 铸 operationId,`onChange` 只预览,`blur` / `Enter` 走 `flush()` + `commitGesture()`,`Escape` 回滚 + `cancel()`。 +- 聚焦期间显示本地文本 draft,失焦后跟随 `value.current`。 +- **`EditSession` 与 `gestureIdentity()` 不得修改**;若发现需要改,说明边界映射错了,退回重审。 +- 验证:输入框改值与拖到同一数值产出同形约束;输入 `1.53` 后一次 Ctrl+Z 回到修改前;键入 `1.` 期间到达的预览响应不改写输入框。 +- 门禁:一次非空表单编辑可在正式重编译结果中观察到几何变化。只交付 UI 不算通过。 + +## 4. 范围拒绝与极值填入 + +- 越界输入:标红、**不发预览请求**、不进 undo 栈、保留最后一个有效预览。 +- 拖拽与滑杆的夹值行为保持不变(`projectHandleValue` 不改)。 +- 范围提示中的极值可点击填入。 +- 验证:越界时网络面板无新请求;blur 后无新 undo 步骤;点击极值可正常提交;拖拽越界时手柄仍停在极限。 +- 门禁:夹值与拒绝的差异必须体现为 `design.md` 中的同一条不变量,不得实现成两条并列策略。 + +## 5. 重置与区间换算 + +- 每行"重置"删除该约束,使该行回到未修改态(`constraintId` 消失、值回落基线)。 +- 区间的米↔station 换算实现并单测;**区间行受 `intervalEditingSupported` 门控,当前为 `false` 故不渲染**。 + 理由与 range 手柄一致(`flag.ts:46`):`compileGeometry()` 不读 `profile.interval`,一个改了没效果的输入框比没有更糟。 + 换算只在用户实际编辑时进行,渲染路径不做米→station→米 往返。 +- 验证:重置后保存重编译,该参数回到基线;换算函数往返无累积漂移;开关为 `false` 时面板不出现区间行。 + +## 6. 加固与手测 + +- `saveDirectEdits()` 入口强制结算未闭合 gesture,不依赖 blur/click 顺序。 +- 手测清单: + - 输入未失焦直接点"保存",修改被正确持久化。 + - 拖拽与输入交替操作,undo/redo 序列正确。 + - 快速连续输入,乱序预览响应不覆盖较新结果。 + - 切换选中道路时未闭合的输入被正确结算或放弃。 + - OpenLayers `Map` 未被重建,仅受影响 source 被替换。 +- 门禁:交付前 `directEdit` 开关行为与改动前一致。 + +## 验证命令 + +```sh +npm run format:check +npm run test +npm run test:client +npm run test:client:unit +npm run build +``` + +## 风险文件 + +- `workbench/client/src/App.tsx`:974 行单组件。面板 state 与拖拽回流都落在此处,是重渲染风险的集中点;必要时先抽出编辑状态再加面板。 +- `workbench/client/src/edit/session.ts`:**不应修改**。若实现中需要改动,说明 gesture 边界映射有误。 +- `workbench/client/src/edit/projection.ts`:`projectHandleValue` 的夹值是拖拽正确性的一部分(见其 75 行注释),不得为"统一行为"而移除。 +- `workbench/client/src/edit/preview-request.ts`:防抖与 `previewSeq` 仲裁由两条通道共用,任何改动同时影响拖拽。 +- `src/compile/direct-edit-solver.js`:**本任务不改**。若发现必须改,先确认不是把服务端校验缺口混进了本任务范围。 diff --git a/.trellis/tasks/08-31-parameter-panel-binding/prd.md b/.trellis/tasks/08-31-parameter-panel-binding/prd.md new file mode 100644 index 0000000..63fc011 --- /dev/null +++ b/.trellis/tasks/08-31-parameter-panel-binding/prd.md @@ -0,0 +1,99 @@ +# 参数面板与数值双向绑定 + +## 目标 + +给直接编辑加一个参数面板:选中道路后,每个可编辑参数以数值形式呈现,既能读到地图拖拽的实时结果,也能直接输入数值驱动几何。两条输入通道写同一份结构化约束,共用同一条预览、保存、撤销链路。 + +地图直接操纵**保留**,不被替换。面板是第二个平等的输入通道,不是拖拽的只读显示器。 + +## 已确认的事实 + +以下均为读代码核实,不是推断: + +- `App.tsx:206` 的 `draftFor(handle, value)` 已经是纯函数 `(手柄, 数字) → 草稿`。拖拽只是产生这个数字的一种方式;输入框可以复用同一个入口。 +- `EditHandle.value` 是 `{ current, min, max, unit: 'meter' }`——**取值范围服务端早已下发**,客户端不需要新增来源。 +- `direct-edit-solver.js:136` 的 `numericValue(constraint, key, fallback)` 直接从约束读值,无约束时回落基线。**服务端从不改写用户输入的数字**;值非法时发阻塞诊断(`direct-edit-invalid-value`)拒绝,不做静默替换。因此不存在"请求值 vs 求解值"两个数字。 +- `App.tsx:197` 每次预览结算都 `setManifest(response.handles)` 整体替换 manifest,`value.current` 随之刷新。受控输入若直接绑定它,输入中间态(`1.`、`-`、空串)会被冲掉。 +- `projection.ts:60` 的 `projectHandleValue` 把拖拽值夹到 `[min, max]`,`ghost.show()` 与 `handlePositionFor()` 都按夹后的值绘制。拖拽越界时手柄停在极限、光标继续移动。 +- 服务端 `applyConstraint`(`direct-edit-solver.js:302/312/322` 附近)只校验 `Number.isFinite` 与非负,**未校验 manifest 的 `min`/`max`**。范围目前是纯客户端概念。 +- 外缘偏移的范围随道路宽度浮动(`±Math.max(0.1, width * 0.45)`);步行带固定 `0..8`;角部圆角固定 `0.5..30`。 +- `gestureIdentity()` 懒创建 operationId,`commitGesture()` 释放它。一次 gesture = `EditSession.commit()` 一次 = 一步 undo。该机制与指针无绑定关系。 +- `handle.constraintId` 仅在约束存在时出现,因此客户端能区分"未修改(基线回落)"与"显式设为该值"。 +- 区间由整条道路共享:`rangeDraftFor` 会把该路上所有约束一起重锚。`IntervalRangeHandle` 同时携带 `station` 与 `roadLengthMeters`。 +- 同一条路可有多个 `road-lane-divider` 手柄,靠 `boundaryIndex` 区分。 +- `direct-edit-solver.js` 写 `profile.interval`(290、472 行),但 `compileGeometry()` 不读它——`native-road.js` 中 `interval` 的唯一命中是方向箭头间距,与此无关。**每次直接编辑实际作用于整条道路。** 因此 `flag.ts:46` 的 `intervalEditingSupported` 为 `false`,range 手柄被隐藏。 +- 当前**没有任何参数面板**。与手柄相关的 UI 仅 `App.tsx:404` 状态栏一句 `手柄 ${n} 个`。 +- `handleDragEvent` 每次 mousemove 触发;`App.tsx` 是单个 974 行组件。 + +## 范围 + +### 1. 面板与读取 + +1. 选中道路后,面板按手柄列出可编辑参数:中文名、当前值、单位、合法范围。 +2. 多个 `road-lane-divider` 分别成行,用 `boundaryIndex` 标识,不按 kind 去重。 +3. 影响区间**每条路一行**(不是每个手柄一行),以米显示,`station` 仍是唯一存储真相。 + **受 `intervalEditingSupported` 门控**:该开关当前为 `false`,故本任务不渲染区间行。 + 换算与显示逻辑仍按第 5 节实现并单测,随开关翻转一并生效。 +4. 每行标记该参数是否已被显式修改(依据 `handle.constraintId` 是否存在)。 +5. 不可编辑手柄(落在路口保留区)在面板中呈禁用态并显示 `disabledReason`。 + +### 2. 拖拽 → 数字 + +6. 拖拽过程中面板数值实时跟随,与地图 ghost 同步。 +7. 高频更新经 rAF 节流,不得每次 mousemove 触发整个 App 重渲染。 + +### 3. 数字 → 图形 + +8. 输入框修改值时走与拖拽相同的 `draftFor` → `PreviewRequester` 链路,含 80ms 防抖与 `previewSeq` 仲裁。 +9. gesture 边界:`focus` 对应 `pointerdown`(铸 operationId),`blur` / `Enter` 对应 `pointerup`(`commitGesture`)。输入 `1.53` 只产生**一步** undo。 +10. `Escape` 回滚到上一个有效值并 `cancel()` 在途请求。 +11. 聚焦期间输入框显示本地文本,失焦后跟随 `value.current`。中间态不被预览响应冲掉。 +12. `saveDirectEdits()` 入口先强制结算未闭合的 gesture,不依赖 blur 与 click 的触发顺序。 + +### 4. 范围处理 + +13. 拖拽与滑杆维持夹值(`projectHandleValue` 不变)。 +14. 数值输入**不夹值**:越界时标记非法、不发预览、不进 undo 栈,保留最后一个有效预览。 +15. 范围提示中的极值可一键填入。 + +### 5. 重置 + +16. 每行提供"重置",删除该约束回到基线。这是拖拽无法表达的操作——拖拽只能设值,不能移除约束。 + +## 明确不做 + +- 不移除、不削弱地图上的拖拽手柄。 +- 不新增约束 kind,不改动求解器几何逻辑。 +- 不补服务端 `min`/`max` 校验(见「已知缺口」,另立任务)。 +- 不做参数的批量编辑、复制粘贴、跨道路应用。 +- 不动 `JunctionTools` 的所有权边界;面板只呈现主地图拥有的 kind。 +- 不同步遗留 `workbench/client/app.js`。 + +## 验收标准 + +- [ ] 选中道路后面板列出全部可编辑参数;多条车道分隔各自成行且可独立修改。 +- [ ] 拖拽手柄时面板数值实时跟随;拖拽期间 React 重渲染次数经 rAF 收敛(非每 mousemove 一次)。 +- [ ] 输入框改值后地图预览更新,与拖到同一数值的结果一致。 +- [ ] 输入 `1.53` 后按 Ctrl+Z **一次**即回到修改前状态。 +- [ ] 输入过程中(如已键入 `1.`)到达的预览响应不会改写输入框内容。 +- [ ] 输入越界值:字段标红、不发预览请求(可由网络面板证明)、保留上一个有效预览、blur 后不产生 undo 步骤。 +- [ ] 点击范围提示中的极值可一键填入并正常提交。 +- [ ] 拖拽越界时手柄停在极限位置,行为与改动前一致。 +- [ ] 未修改参数与显式设为基线值的参数在面板上可区分;"重置"能删除约束并使该行回到未修改态。 +- [ ] 影响区间的米↔station 换算函数经单测覆盖,往返无累积漂移。(区间行本身受 `intervalEditingSupported` 门控,当前不渲染。) +- [ ] 输入未失焦时直接点"保存",该次修改被正确持久化。 +- [ ] 路口保留区内的手柄在面板中禁用并显示原因。 +- [ ] `npm run format:check`、`npm run test`、`npm run test:client`、`npm run test:client:unit`、`npm run build` 全绿。 + +## 风险与门槛 + +- 面板不得成为第二套几何或第二个值的真相来源。所有范围、位置、影响对象仍只来自服务端 manifest。 +- `value.current` 是**请求值的回显**而非求解值。若后续 solver 改成回写求解结果,第 11 条的显示规则失效,必须同步重审。 +- 外缘偏移的 `min`/`max` 随道路宽度浮动,因此"当前合法"不等于"永远合法"。客户端校验只能覆盖输入当下。 +- 拖拽回流若实现为直接 `setState`,会逐帧重渲染 974 行的 `App`。必须先确认节流有效再扩大面板规模。 + +## 已知缺口(不在本任务内) + +服务端只校验 finite/非负,不校验 manifest 的 `min`/`max`;而外缘偏移范围随道路宽度浮动,意味着保存时合法的值可能在几何变化后越界。这类越界**客户端结构上无法拦截**——它发生在保存之后的求解期。 + +`design.md` 已为 `boundaryIndex` 定义了同类规则("重放时若车道数变化导致越界,该约束转 `stale`"),数值范围越界应当同等处理。属重放正确性,独立成任务。 diff --git a/.trellis/tasks/08-31-parameter-panel-binding/research/manifest-range-vs-solver.md b/.trellis/tasks/08-31-parameter-panel-binding/research/manifest-range-vs-solver.md new file mode 100644 index 0000000..4f9cfca --- /dev/null +++ b/.trellis/tasks/08-31-parameter-panel-binding/research/manifest-range-vs-solver.md @@ -0,0 +1,58 @@ +# manifest 范围与求解器可行域不一致 + +日期:2026-08-31 +来源:`08-31-parameter-panel-binding` 实施期间对运行中工作台(`osm-KZZP9U`)的实测。 + +## 现象 + +手柄 `handle:road-edge-offset:segment:way/-3246/0:left`,manifest 声明 +`value.min = -2.925`、`value.max = 2.925`(即 `±width * 0.45`,道路宽 6.5m)。 + +逐值探测 `POST /api/edit-preview`: + +| offsetMeters | 阻塞诊断 | +| --- | --- | +| -2.90 | `direct-edit-outer-edges-cross` | +| -2.00 | `direct-edit-outer-edges-cross` | +| -1.00 | `direct-edit-outer-edges-cross` | +| **-0.50** | **(无)** | +| **0.00** | **(无)** | +| **0.50** | **(无)** | +| **1.00** | **(无)** | +| 2.00 | `direct-edit-outer-edges-cross` | +| 2.90 | `direct-edit-outer-edges-cross` | +| 500 | `direct-edit-outer-edges-cross` | + +探针构造已排除误报:小幅值干净,说明请求本身合法。 + +## 结论 + +**manifest 宣告的范围比求解器实际接受的可行域宽约 3 倍,且双向都是。** +真实边界落在 `(-1.0, -0.5]` 与 `[1.0, 2.0)` 之间,未进一步二分。 + +失败原因未查明。`direct-edit-outer-edges-cross` 对应 design.md 的 +「同一站点左右外缘不得交叉」不变量,但仅移动**单侧**外缘 1m +(6.5m 宽的路)为何会触发交叉,需要读 `compileGeometry()` 才能确定—— +可能经由车道最小宽度 2.4m 派生,也可能诊断名不完全对应其实际判据。 + +## 与既有行为的关系 + +这不是本任务引入的。拖拽一直夹到 `±2.925`,所以用户一直能拖进被拒区间—— +拖过约 1m 后几何冻结、诊断出现,而手柄继续走到 2.925。 +按 design.md「无效草稿不替换最后一个有效预览」,这是既定行为。 + +参数面板没有改变它,但**把它变可见了**:范围以文字打印,且极值可一键填入。 +点击极值会得到一个必被服务端拒绝的值。 + +## 处理 + +未在本任务修改。理由: + +- 客户端范围校验必须用 manifest 的 `min`/`max`,用别的就是发明第二个真相来源 + (`direct-edit-client.md` §2)。 +- 收窄范围需要求解器解析地算出外缘交叉的可行区间,属求解器工作, + 本任务明确排除。 +- 点击极值的结果是一个诚实的服务端拒绝:诊断可见、最后一个有效预览保留、可撤销。 + 不是静默破坏。 + +已并入 `08-31-constraint-range-validation` 的需求。 diff --git a/.trellis/tasks/08-31-parameter-panel-binding/task.json b/.trellis/tasks/08-31-parameter-panel-binding/task.json new file mode 100644 index 0000000..5c0c8ac --- /dev/null +++ b/.trellis/tasks/08-31-parameter-panel-binding/task.json @@ -0,0 +1,26 @@ +{ + "id": "parameter-panel-binding", + "name": "parameter-panel-binding", + "title": "参数面板与数值双向绑定", + "description": "为直接编辑加参数面板:数值输入与地图拖拽双向绑定,共用同一条约束/预览/undo 链路", + "status": "in_progress", + "dev_type": null, + "scope": null, + "package": null, + "priority": "P2", + "creator": "dingkang", + "assignee": "dingkang", + "createdAt": "2026-08-31", + "completedAt": null, + "branch": null, + "base_branch": "main", + "worktree_path": null, + "commit": null, + "pr_url": null, + "subtasks": [], + "children": [], + "parent": "08-26-direct-manipulation-road-editor", + "relatedFiles": [], + "notes": "", + "meta": {} +} \ No newline at end of file diff --git a/workbench/client/src/App.tsx b/workbench/client/src/App.tsx index 1d5907e..99eefaf 100644 --- a/workbench/client/src/App.tsx +++ b/workbench/client/src/App.tsx @@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { Download, RefreshCw, Save, Upload } from 'lucide-react'; import { api, isVersionConflict } from './lib/api'; import { MapCanvas } from './components/MapCanvas'; +import { ParameterPanel, type ParameterPanelHandle } from './components/ParameterPanel'; import { directEditEnabled, intervalEditingSupported } from './edit/flag'; import { PreviewRequester, type PreviewDraft } from './edit/preview-request'; import { anchorSnapshotFor, constraintValueFor, draftConstraint, operationFor } from './edit/projection'; @@ -161,6 +162,10 @@ function App() { const [editDiagnostics, setEditDiagnostics] = useState([]); const sessionRef = useRef(null); if (directEditEnabled && !sessionRef.current) sessionRef.current = new EditSession(); + // Per-frame drag feedback reaches the panel through this rather than through + // state, for the same reason the ghost writes its own source: a setState on + // every pointermove re-renders all of App. + const panelRef = useRef(null); // The session is a mutable object in a ref, so React cannot see it change. // Bumping this after every mutation is what keeps the buttons in step with it. const [editRevision, setEditRevision] = useState(0); @@ -268,6 +273,60 @@ function App() { const fragment = session?.fragment(); if (fragment) requester?.flush(fragment); }; + /** + * A live value from either channel: preview it, do not commit. + * + * Dragging and typing differ only in how the number is made. From here down the + * two share everything — the draft, the debounce, the previewSeq arbitration — + * so there is one implementation rather than a parallel one per input device. + */ + const draftValue = (handle: EditHandle, value: number) => { + const draft = draftFor(handle, value); + if (draft) requester?.schedule(draft); + }; + /** Neither channel committed: release the id and put the settled state back. */ + const abandonGesture = () => { + gesture.current = null; + panelRef.current?.clearLive(); + previewSession(); + }; + /** A settled value from either channel: one undoable command, or nothing. */ + const settleValue = (handle: EditHandle, value: number) => { + const draft = draftFor(handle, value); + if (draft) commitGesture(draft, [`constraint:${handle.handleId}`]); + else abandonGesture(); + }; + /** + * Reset: put a parameter back on the compiler's baseline. + * + * The constraint is disabled rather than removed. `validateEditDocument()` + * rejects an operation naming a constraint that is not in the document, so a + * deletion would have to record an operation about nothing; disabling is also + * what design.md already sanctions for undoing saved work, and it keeps the + * history readable. The solver skips `enabled === false` and then publishes the + * handle without a `constraintId`, so the row reports itself unmodified again. + * + * This is the one edit dragging cannot express — a drag can set a value, never + * withdraw one. + */ + const resetHandle = (handle: EditHandle) => { + const base = session?.fragment(); + const constraintId = handle.constraintId; + if (!session || !base || !constraintId) return; + const identity = gestureIdentity(); + const operation = { + id: identity.operationId, + createdAt: identity.createdAt, + constraintIds: [constraintId], + }; + commitGesture( + { + constraints: base.constraints.map((item) => (item.id === constraintId ? { ...item, enabled: false } : item)), + operations: [...base.operations.filter((item) => item.id !== operation.id), operation], + }, + [constraintId], + ); + }; const undoEdit = () => { // A saved gesture cannot be un-applied — persisted history is append-only — so // it is reversed by an inverse operation, which needs its own identity. @@ -296,6 +355,10 @@ function App() { }; const saveDirectEdits = async () => { if (!session) return; + // A field still being typed in holds an uncommitted value. Blur fires before + // click so the button press would settle it anyway, but that ordering is not + // something to depend on for whether an edit is persisted. + panelRef.current?.settleOpenEdit(); const fragment = session.fragment(); let version: number; try { @@ -493,10 +556,12 @@ function App() { preview={preview} ghostPending={session?.degraded ?? false} onHandleDrag={(handle, value) => { - const draft = draftFor(handle, value); - if (draft) requester?.schedule(draft); + // Straight to the DOM, like the ghost writes straight to its source: + // a per-pointermove setState re-renders this whole component. + panelRef.current?.showLive(handle.handleId, value); + draftValue(handle, value); }} - onHandleDragEnd={(handle, value) => commitGesture(draftFor(handle, value), [`constraint:${handle.handleId}`])} + onHandleDragEnd={settleValue} onHandleBlocked={(_handle, reason) => setStatus(reason)} onRangeDrag={(range, anchor) => { const draft = rangeDraftFor(range, anchor); @@ -514,15 +579,28 @@ function App() { commitGesture(draft, touched); }} /> - + ); @@ -609,8 +687,10 @@ function Inspector({ }; const signalUid = typeof marking?.signal_uid === 'string' ? marking.signal_uid : ''; const signal = state.trafficSignals.assemblies.features.find((item) => item.properties?.signal_uid === signalUid); + // The `.inspector` aside now belongs to the layout in `main`, so the parameter + // panel can share the column. Same markup, one level up. return ( - + ); } function MarkingEditor({ diff --git a/workbench/client/src/components/ParameterPanel.tsx b/workbench/client/src/components/ParameterPanel.tsx new file mode 100644 index 0000000..e41e5ae --- /dev/null +++ b/workbench/client/src/components/ParameterPanel.tsx @@ -0,0 +1,281 @@ +// The parameter panel: every editable value on the selected road, as a number. +// +// This is the second input channel next to dragging. Both produce a scalar and +// hand it to the same `draftValue()` / `settleValue()` in App.tsx, so this +// component owns text and presentation only — never geometry, never a range of +// its own. Every value, bound and disabled reason shown here is read off the +// handle manifest, for the same reason handle features carry nothing but their +// id: a second constraint model on the client is the failure the cross-layer +// guide warns about. +// +// Two rules shape the rest of the file: +// +// 1. Live drag values do NOT go through React. `direct-edit-client.md` §7 makes +// rAF coalescing the floor and "write straight to the source" the rule: the +// ghost writes its OpenLayers source directly, and the panel's equivalent of a +// source is the input's `value`. `showLive()` mirrors `EditGhostLayer.show()` +// deliberately — same call site, same number, one draws the road and one the +// digits. +// +// 2. A value out of the manifest's range is refused, not clamped. Dragging clamps +// because a pointer cannot state an intent it never reached and the handle has +// to stay on a road shape that can exist (`projection.ts:75`); typed text *is* +// an intent, and a clamped typo reads as a plausible value that can go +// unnoticed. Same invariant, two devices, two honest ways to say "no". + +import { useImperativeHandle, useLayoutEffect, useRef, useState, type Ref } from 'react'; +import { + formatBoundInward, + formatParameterValue, + isModified, + labelForHandle, + parseParameterInput, + rangeVerdictOf, + rendersSame, +} from '../edit/parameter'; +import { disabledReasonOf } from '../edit/selection'; +import type { EditHandle } from '../edit/types'; + +export interface ParameterPanelHandle { + /** Live value during a drag, written straight to the DOM. */ + showLive(handleId: string, value: number): void; + /** A drag that committed nothing: drop the overrides and fall back to React. */ + clearLive(): void; + /** + * Closes a field the user is still typing in, before its value is read. + * + * Blur fires before click in the DOM, so clicking "save" would settle the field + * in time on its own — but only just, and nothing states that ordering. Saving + * calls this first so the guarantee does not rest on event order. + */ + settleOpenEdit(): void; +} + +/** Baseline text is kept on the node so a restore cannot go stale with a closure. */ +const BASELINE_ATTRIBUTE = 'data-baseline'; + +interface RowCallbacks { + /** Typing: preview, do not commit. */ + onDraft: (handle: EditHandle, value: number) => void; + /** Blur or Enter: one undoable command. */ + onSettle: (handle: EditHandle, value: number) => void; + /** Escape, or a field left holding something unusable. */ + onAbandon: () => void; + /** Withdraw the constraint and return the row to the compiler's baseline. */ + onReset: (handle: EditHandle) => void; +} + +function ParameterRow({ + handle, + register, + onDraft, + onSettle, + onAbandon, + onReset, +}: RowCallbacks & { + handle: EditHandle; + register: (handleId: string, node: HTMLInputElement | null) => void; +}) { + /** The text being typed. `null` means "not editing, follow the manifest". */ + const [text, setText] = useState(null); + /** What the field held at focus, so an untouched blur commits nothing. */ + const seeded = useRef(''); + + const reason = disabledReasonOf(handle); + const { current, min, max } = handle.value; + const baseline = formatParameterValue(current); + // Shown and filled as the same text, so the offered extreme is always typeable. + const lowest = formatBoundInward(min, 'min'); + const highest = formatBoundInward(max, 'max'); + const parsed = text === null ? null : parseParameterInput(text); + // `null` is "not a number yet" — `-` on the way to `-1.5` — and is neither + // previewable nor an error, so it must not light the field up red. + const verdict = parsed === null ? 'ok' : rangeVerdictOf(parsed, min, max); + const rejected = verdict !== 'ok'; + + const draft = (next: string) => { + setText(next); + const value = parseParameterInput(next); + if (value === null) return; + if (rangeVerdictOf(value, min, max) !== 'ok') return; + onDraft(handle, value); + }; + + const settle = () => { + const value = text === null ? null : parseParameterInput(text); + const touched = text !== null && text !== seeded.current; + setText(null); + if (!touched) return; + // Committing a value that renders the same as the stored one would turn a + // focus/blur with no typing into an edit, because the field shows a rounded + // form of what the manifest holds. + if (value !== null && rangeVerdictOf(value, min, max) === 'ok' && !rendersSame(value, current)) + onSettle(handle, value); + // Typed, then left unusable: a previously previewed keystroke may still be + // pending, so the settled state has to be put back. + else onAbandon(); + }; + + /** + * Fills an extreme, so "I want it as wide as possible" costs one click. + * + * The text comes from `formatBoundInward`, not from the raw bound: a max of + * 2.925 renders as 2.93 under nearest-rounding, and filling that would be + * rejected by the very range it came from. + */ + const fill = (text: string) => (event: React.MouseEvent) => { + // The field is focused; a plain click would blur it and settle first. + event.preventDefault(); + draft(text); + }; + + /** Drops the constraint behind this row, which no drag can do. */ + const reset = (event: React.MouseEvent) => { + // Same reason as `fill`: never let the click settle a half-typed field first. + event.preventDefault(); + setText(null); + onReset(handle); + }; + + return ( +
  • + + {labelForHandle(handle)} + {isModified(handle) ? ( + <> + + + + ) : null} + + + register(handle.handleId, node)} + onFocus={(event) => { + // Seed from what is on screen rather than from the manifest: after a + // drag the row can legitimately be ahead of the last settled preview. + seeded.current = event.currentTarget.value; + setText(event.currentTarget.value); + }} + onChange={(event) => draft(event.target.value)} + onBlur={settle} + onKeyDown={(event) => { + if (event.key === 'Enter') event.currentTarget.blur(); + if (event.key === 'Escape') { + setText(null); + onAbandon(); + event.currentTarget.blur(); + } + }} + />{' '} + m + + + {reason ?? ( + <> + {rejected ? '超出范围|' : ''} + 可取{' '} + {' '} + ~{' '} + + + )} + +
  • + ); +} + +export function ParameterPanel({ + handles, + hasSelection, + ref, + ...callbacks +}: RowCallbacks & { + handles: EditHandle[]; + hasSelection: boolean; + ref?: Ref; +}) { + const nodes = useRef(new Map()); + /** Handles under a drag, so a re-render cannot undo the live value. */ + const live = useRef(new Map()); + + const register = (handleId: string, node: HTMLInputElement | null) => { + if (node) nodes.current.set(handleId, node); + else nodes.current.delete(handleId); + }; + + useImperativeHandle(ref, () => ({ + showLive(handleId, value) { + live.current.set(handleId, value); + const node = nodes.current.get(handleId); + if (node) node.value = formatParameterValue(value); + }, + clearLive() { + // Only for a drag that committed nothing — otherwise the effect below hands + // the row back to React on its own. React does not know the value was + // mutated, so a drag that ends where it started produces no re-render and + // would leave its last number on screen; the baseline attribute is what the + // row actually rendered, so it restores. + for (const [handleId] of live.current) { + const node = nodes.current.get(handleId); + if (node) node.value = node.getAttribute(BASELINE_ATTRIBUTE) ?? ''; + } + live.current.clear(); + }, + settleOpenEdit() { + // `blur()` runs the row's onBlur synchronously, so the command is on the + // stack by the time this returns. + for (const node of nodes.current.values()) if (node === document.activeElement) node.blur(); + }, + })); + + // A debounced preview lands mid-drag and replaces the manifest, so React + // re-renders with a value one debounce behind the pointer. Re-applying the live + // value after the DOM update — before paint — keeps the number from flickering + // between the two. + // + // It is also how an override ends: once the manifest reports the value the drag + // asked for, the row is handed back to React rather than being force-written + // forever. A handle that is no longer rendered drops out with it. + useLayoutEffect(() => { + const present = new Set(handles.map((item) => item.handleId)); + for (const [handleId, value] of live.current) { + if (!present.has(handleId)) { + live.current.delete(handleId); + continue; + } + const node = nodes.current.get(handleId); + if (!node) continue; + const text = formatParameterValue(value); + if (node.getAttribute(BASELINE_ATTRIBUTE) === text) live.current.delete(handleId); + else node.value = text; + } + }); + + return ( +
    +

    道路参数

    + {handles.length ? ( +
      + {handles.map((handle) => ( + + ))} +
    + ) : ( +

    {hasSelection ? '当前道路无可编辑参数' : '选中道路以显示参数'}

    + )} +
    + ); +} diff --git a/workbench/client/src/edit/parameter.test.ts b/workbench/client/src/edit/parameter.test.ts new file mode 100644 index 0000000..84ccaa6 --- /dev/null +++ b/workbench/client/src/edit/parameter.test.ts @@ -0,0 +1,223 @@ +import { describe, expect, it } from 'vitest'; +import { + formatBoundInward, + formatParameterValue, + isModified, + labelForHandle, + metersToStation, + parseParameterInput, + rangeVerdictOf, + rendersSame, + stationToMeters, +} from './parameter'; +import type { ConstraintKind, EditHandle, SemanticAnchor } from './types'; + +function handle(kind: ConstraintKind, anchor: SemanticAnchor, constraintId?: string): EditHandle { + return { + handleId: `h:${kind}`, + kind, + anchor, + position: [116.397, 39.908], + axisAzimuth: 90, + value: { current: 1.5, min: -5, max: 5, unit: 'meter' }, + affects: [], + editable: true, + ...(constraintId ? { constraintId } : {}), + }; +} + +const interval = (extra: Partial> = {}): SemanticAnchor => ({ + type: 'road-interval', + roadId: 'road:way/1:forward', + startStation: 0.15, + endStation: 0.85, + ...extra, +}); + +describe('parseParameterInput', () => { + it('parses the forms a meters field legitimately holds', () => { + expect(parseParameterInput('1')).toBe(1); + expect(parseParameterInput('1.53')).toBe(1.53); + expect(parseParameterInput('-2.4')).toBe(-2.4); + expect(parseParameterInput('.5')).toBe(0.5); + expect(parseParameterInput('+3')).toBe(3); + }); + + it('parses a trailing dot so typing 1.53 previews at every keystroke', () => { + // `1.` is a real value mid-way through `1.53`. Previewing it is the point of + // the binding; what must not happen is the field being rewritten to `1`. + expect(parseParameterInput('1.')).toBe(1); + }); + + it('returns null for text that is not a number yet', () => { + // These are "wait", not "invalid" — the caller must not preview or flag them. + expect(parseParameterInput('')).toBeNull(); + expect(parseParameterInput('-')).toBeNull(); + expect(parseParameterInput('.')).toBeNull(); + expect(parseParameterInput('-.')).toBeNull(); + }); + + it('never turns a cleared or blank field into an explicit zero', () => { + // Number('') and Number(' ') are both 0. Using it bare would persist a zero + // the user never typed, which for an edge offset is a real geometry change. + expect(parseParameterInput('')).not.toBe(0); + expect(parseParameterInput(' ')).toBeNull(); + }); + + it('rejects text that is not a plain decimal', () => { + expect(parseParameterInput('abc')).toBeNull(); + expect(parseParameterInput('1.5.5')).toBeNull(); + expect(parseParameterInput('1,5')).toBeNull(); + // Scientific notation in a meters field is a typo, not an intent. + expect(parseParameterInput('1e5')).toBeNull(); + expect(parseParameterInput('Infinity')).toBeNull(); + }); + + it('tolerates surrounding whitespace from a paste', () => { + expect(parseParameterInput(' 2.75 ')).toBe(2.75); + }); +}); + +describe('formatParameterValue', () => { + it('drops trailing zeros rather than padding to a fixed width', () => { + expect(formatParameterValue(1.5)).toBe('1.5'); + expect(formatParameterValue(2)).toBe('2'); + expect(formatParameterValue(1.53)).toBe('1.53'); + }); + + it('rounds to centimetre precision', () => { + expect(formatParameterValue(1.234)).toBe('1.23'); + expect(formatParameterValue(1.236)).toBe('1.24'); + }); + + it('never renders a negative zero', () => { + expect(formatParameterValue(-0.001)).toBe('0'); + expect(formatParameterValue(-0)).toBe('0'); + }); + + it('renders a non-finite value as empty rather than "NaN"', () => { + expect(formatParameterValue(Number.NaN)).toBe(''); + }); +}); + +describe('rendersSame', () => { + it('treats values that display identically as the same edit', () => { + // Focusing a field showing `1.23` over a stored `1.234` and blurring without + // typing must not commit a change the user never made. + expect(rendersSame(1.23, 1.234)).toBe(true); + }); + + it('separates values the user can tell apart', () => { + expect(rendersSame(1.23, 1.24)).toBe(false); + }); +}); + +describe('formatBoundInward', () => { + it('never renders a bound outside the range it came from', () => { + // Real manifest value: an edge offset's bounds are ±width * 0.45, which lands + // on half-centimetres. Nearest-rounding turns 2.925 into 2.93 — above the max. + const max = 2.9250000000000003; + const min = -max; + expect(formatBoundInward(max, 'max')).toBe('2.92'); + expect(formatBoundInward(min, 'min')).toBe('-2.92'); + expect(rangeVerdictOf(Number(formatBoundInward(max, 'max')), min, max)).toBe('ok'); + expect(rangeVerdictOf(Number(formatBoundInward(min, 'min')), min, max)).toBe('ok'); + }); + + it('leaves a bound that already fits the precision alone', () => { + expect(formatBoundInward(8, 'max')).toBe('8'); + expect(formatBoundInward(0, 'min')).toBe('0'); + expect(formatBoundInward(0.5, 'min')).toBe('0.5'); + }); + + it('is the value a click on the extreme fills, so it must round-trip', () => { + for (const bound of [30, 0.5, 2.9250000000000003, -5.4, 7.996]) { + for (const side of ['min', 'max'] as const) { + const text = formatBoundInward(bound, side); + const parsed = parseParameterInput(text); + expect(parsed).not.toBeNull(); + // Inward means: never further from zero-crossing than the bound itself. + if (side === 'max') expect(parsed!).toBeLessThanOrEqual(bound); + else expect(parsed!).toBeGreaterThanOrEqual(bound); + } + } + }); +}); + +describe('rangeVerdictOf', () => { + it('accepts the inclusive bounds', () => { + expect(rangeVerdictOf(-5, -5, 5)).toBe('ok'); + expect(rangeVerdictOf(5, -5, 5)).toBe('ok'); + expect(rangeVerdictOf(0, -5, 5)).toBe('ok'); + }); + + it('names which bound was crossed, so the panel can offer that extreme', () => { + expect(rangeVerdictOf(-24.1, -5.4, 5.4)).toBe('below-min'); + expect(rangeVerdictOf(24.1, -5.4, 5.4)).toBe('above-max'); + }); +}); + +describe('station <-> meters', () => { + it('converts against the road length', () => { + expect(stationToMeters(0.5, 150)).toBe(75); + expect(metersToStation(75, 150)).toBe(0.5); + }); + + it('round-trips without drift', () => { + const roadLength = 137.42; + let station = 0.3; + // The panel converts only on a real edit, but the functions themselves must + // not accumulate error when they are called repeatedly. + for (let index = 0; index < 100; index += 1) { + station = metersToStation(stationToMeters(station, roadLength), roadLength); + } + expect(station).toBeCloseTo(0.3, 12); + }); + + it('returns zero rather than dividing by a zero-length road', () => { + expect(metersToStation(10, 0)).toBe(0); + expect(stationToMeters(0.5, 0)).toBe(0); + expect(Number.isFinite(metersToStation(10, 0))).toBe(true); + }); +}); + +describe('labelForHandle', () => { + it('distinguishes lane dividers by boundary index', () => { + // A road carries one handle per boundary; the kind alone cannot name a row. + const first = labelForHandle(handle('road-lane-divider', interval({ boundaryIndex: 1 }))); + const second = labelForHandle(handle('road-lane-divider', interval({ boundaryIndex: 2 }))); + expect(first).toBe('车道分隔 #1'); + expect(second).toBe('车道分隔 #2'); + expect(first).not.toBe(second); + }); + + it('names the side geographically', () => { + expect(labelForHandle(handle('road-edge-offset', interval({ side: 'left' })))).toBe('外缘偏移(左)'); + expect(labelForHandle(handle('road-edge-offset', interval({ side: 'right' })))).toBe('外缘偏移(右)'); + }); + + it('falls back to the bare kind when the anchor carries no discriminator', () => { + expect( + labelForHandle( + handle('junction-corner-radius', { + type: 'junction-corner', + nodeId: '9', + incomingRoadId: 'seg:1', + outgoingRoadId: 'seg:2', + }), + ), + ).toBe('角部圆角'); + }); +}); + +describe('isModified', () => { + it('reads the constraint link, not the value', () => { + // `value.current` falls back to a baseline when no constraint exists, so an + // untouched parameter and one explicitly set to the same number look alike. + const untouched = handle('road-edge-offset', interval()); + const edited = handle('road-edge-offset', interval(), 'constraint:1'); + expect(untouched.value.current).toBe(edited.value.current); + expect(isModified(untouched)).toBe(false); + expect(isModified(edited)).toBe(true); + }); +}); diff --git a/workbench/client/src/edit/parameter.ts b/workbench/client/src/edit/parameter.ts new file mode 100644 index 0000000..db90a02 --- /dev/null +++ b/workbench/client/src/edit/parameter.ts @@ -0,0 +1,148 @@ +// Parameter panel values: text <-> number, range verdicts, station <-> meters. +// +// The panel is the second input channel. A drag makes a number by projecting a +// pointer onto the manifest's axis (`projection.ts`); the panel makes one by +// parsing text. Both then feed the same `draftFor()` in App.tsx, so the only +// things that differ are how the number is produced and when the gesture closes. +// +// No OpenLayers import, same rule as meters.ts / projection.ts / selection.ts: +// this is the half of the panel that can be tested in node. + +import type { ConstraintKind, EditHandle } from './types'; + +/** Meters render to centimetre precision; more digits are noise on a road. */ +export const DISPLAY_DECIMALS = 2; + +/** + * Text a number field may hold, as a number — or `null` when the text is not a + * number yet. + * + * `null` means "wait", not "invalid": while typing `-1.5` the field passes + * through `-`, which is neither previewable nor an error. The caller must not + * preview, commit, or flag a `null`. + * + * `Number()` is deliberately not used on its own: `Number('')` and `Number(' ')` + * are both `0`, which would silently turn a cleared field into an explicit zero. + * + * `1.` parses to `1` and is previewed on purpose — that is the live feedback the + * two-way binding exists for. What must not happen is the field being *rewritten* + * to `1`, and that is prevented by the focused-draft rule in the panel, not here. + */ +export function parseParameterInput(text: string): number | null { + const trimmed = text.trim(); + // Digits are required somewhere: `-`, `.` and `-.` are incomplete, not zero. + // Scientific notation is excluded — in a meters field it is a typo, not intent. + if (!/^[+-]?(\d+\.?\d*|\.\d+)$/.test(trimmed)) return null; + const value = Number(trimmed); + return Number.isFinite(value) ? value : null; +} + +/** The display form of a value: fixed precision, without trailing zero noise. */ +export function formatParameterValue(value: number): string { + if (!Number.isFinite(value)) return ''; + const fixed = value.toFixed(DISPLAY_DECIMALS); + // `1.50` -> `1.5`, `2.00` -> `2`, while `-0.00` collapses to `0`. + const trimmed = fixed.replace(/\.?0+$/, ''); + return trimmed === '-0' || trimmed === '' ? '0' : trimmed; +} + +/** + * Whether two values are the same edit, judged by what the user can see. + * + * Display rounds to `DISPLAY_DECIMALS`, so focusing a field showing `1.23` over a + * stored `1.234` and blurring without typing would otherwise commit a change the + * user never made. Comparing rendered forms makes that a no-op. + */ +export function rendersSame(a: number, b: number): boolean { + return formatParameterValue(a) === formatParameterValue(b); +} + +/** + * A bound, rounded *inward* to display precision. + * + * Rounding to nearest can push a bound past itself: a real max of `2.925` renders + * as `2.93`, so offering that text as "the maximum" hands the user a value the + * range check then rejects. Observed on a live manifest, where an edge offset's + * bounds are `±width * 0.45` and land on half-centimetres routinely. + * + * The displayed range therefore understates the true one by less than a + * centimetre, which is the most the field can express anyway. + */ +export function formatBoundInward(value: number, side: 'min' | 'max'): string { + const factor = 10 ** DISPLAY_DECIMALS; + const scaled = value * factor; + const inward = side === 'min' ? Math.ceil(scaled) : Math.floor(scaled); + return formatParameterValue(inward / factor); +} + +export type RangeVerdict = 'ok' | 'below-min' | 'above-max'; + +/** + * Where a value sits relative to the manifest's declared range. + * + * The invariant is shared with dragging — a constraint value never leaves + * `[min, max]` — but the two devices express it differently. A drag clamps, + * because a pointer cannot state an intent it did not reach and the handle has to + * stay on a road shape that can exist (`projection.ts:75`). Typed text *is* an + * intent, so the panel refuses it instead of rewriting it: a clamped typo reads as + * a plausible value and can go unnoticed, while a refusal cannot. + */ +export function rangeVerdictOf(value: number, min: number, max: number): RangeVerdict { + if (value < min) return 'below-min'; + if (value > max) return 'above-max'; + return 'ok'; +} + +/** Meters from the road's start for a normalized station. */ +export function stationToMeters(station: number, roadLengthMeters: number): number { + return roadLengthMeters > 0 ? station * roadLengthMeters : 0; +} + +/** + * The inverse. Only call this when the user actually edited a distance — running + * it on every render would send the value through meters and back, and the + * rounding would let a station drift on its own. + */ +export function metersToStation(meters: number, roadLengthMeters: number): number { + return roadLengthMeters > 0 ? meters / roadLengthMeters : 0; +} + +const KIND_LABELS: Record = { + 'road-edge-offset': '外缘偏移', + 'road-sidewalk-width': '步行带宽度', + 'road-lane-divider': '车道分隔', + 'junction-approach-width': '进口宽度', + 'junction-cutback': '进口 cutback', + 'junction-corner-radius': '角部圆角', + 'junction-crosswalk-inset': '斑马线退让', + 'junction-stop-line-offset': '停止线偏移', +}; + +/** + * The row label for a handle. + * + * A road can carry several `road-lane-divider` handles at once, one per boundary, + * so the kind alone does not identify a row. Side and boundary index come off the + * anchor rather than being recomputed, keeping the manifest the only source. + */ +export function labelForHandle(handle: EditHandle): string { + const base = KIND_LABELS[handle.kind] ?? handle.kind; + const anchor = handle.anchor; + if ('boundaryIndex' in anchor && Number.isInteger(anchor.boundaryIndex)) return `${base} #${anchor.boundaryIndex}`; + if ('side' in anchor && anchor.side) return `${base}(${anchor.side === 'left' ? '左' : '右'})`; + return base; +} + +/** + * Whether this parameter has been edited, as opposed to sitting on the compiler's + * baseline. + * + * The solver fills `value.current` from the constraint when one exists and from a + * baseline default when it does not (`direct-edit-solver.js:136`), so the number + * alone cannot tell "untouched" from "explicitly set to the same number". + * `constraintId` is present only in the first case, which is also what makes a + * reset row possible — dragging can set a value but never remove a constraint. + */ +export function isModified(handle: EditHandle): boolean { + return Boolean(handle.constraintId); +} diff --git a/workbench/client/src/styles.css b/workbench/client/src/styles.css index 7715232..a0e358c 100644 --- a/workbench/client/src/styles.css +++ b/workbench/client/src/styles.css @@ -221,3 +221,113 @@ pre { padding: 2px 5px; font-size: 12px; } +.parameters { + margin-bottom: 16px; +} +.parameters ul { + display: grid; + gap: 6px; +} +.parameter { + display: grid; + grid-template-columns: 1fr auto; + gap: 2px 10px; + border: 1px solid #dce5e1; + background: #f8fbfa; + padding: 7px; +} +.parameter-label { + color: #52615b; + font-size: 12px; +} +.parameter-dot { + display: inline-block; + width: 6px; + height: 6px; + margin-left: 5px; + border-radius: 50%; + background: #2f7d5d; + vertical-align: middle; +} +.parameter-value { + font-size: 15px; + font-variant-numeric: tabular-nums; + text-align: right; +} +.parameter-value em { + color: #52615b; + font-size: 12px; + font-style: normal; +} +.parameter-range { + grid-column: 1 / -1; + color: #7b8a83; + font-size: 11px; + font-variant-numeric: tabular-nums; +} +.parameter.disabled { + background: #f2f4f3; +} +.parameter.disabled .parameter-value { + color: #9aa8a1; +} +.parameter.disabled .parameter-range { + color: #8a7a55; +} +.parameter-empty { + color: #7b8a83; + font-size: 12px; + margin: 0; +} +.parameter-input { + width: 76px; + border: 1px solid #aab8b2; + background: white; + padding: 3px 5px; + font: inherit; + font-size: 14px; + font-variant-numeric: tabular-nums; + text-align: right; +} +.parameter-input:focus { + outline: 2px solid #2f7d5d; + outline-offset: -1px; +} +.parameter-input.rejected { + border-color: #c2452f; + background: #fdf3f1; +} +.parameter-input:disabled { + background: #f2f4f3; + color: #9aa8a1; +} +.parameter-range.rejected { + color: #c2452f; +} +.parameter-extreme { + border: 0; + background: none; + padding: 0; + font: inherit; + font-variant-numeric: tabular-nums; + color: #2f7d5d; + text-decoration: underline; + cursor: pointer; +} +.parameter-range.rejected .parameter-extreme { + color: #c2452f; +} +.parameter-reset { + border: 0; + background: none; + padding: 0; + margin-left: 8px; + font: inherit; + font-size: 11px; + color: #7b8a83; + text-decoration: underline; + cursor: pointer; +} +.parameter-reset:hover { + color: #c2452f; +}