feat: edit road parameters by number as well as by drag
The map had one input device. A drag projects a pointer onto the manifest's axis; there was no way to state a value, read one, or withdraw one. Both channels now meet at the same three exits in App.tsx — draftValue() previews, settleValue() commits one undoable command, abandonGesture() puts the settled state back — so nothing about the constraint, the debounce or the previewSeq arbitration is implemented twice. EditSession is untouched: focus and blur land on the gesture boundary that pointerdown and pointerup already used, which is why typing 1.53 is one undo step rather than four. Three rules the two devices do not share: - Live drag values bypass React and write the input's value directly, per direct-edit-client.md §7. A layout effect re-applies them after a mid-drag preview replaces the manifest, and drops the override once the manifest reports the value the drag asked for. - Typed values out of range are refused, not clamped. A pointer cannot state an intent it never reached, so a drag clamps; typed text is an intent, and a clamped typo reads as a plausible value that can go unnoticed. The offered extremes round inward — a real max of 2.925 renders as 2.93 under nearest-rounding, which the range it came from would then reject. - Reset disables the constraint rather than deleting it: validateEditDocument() rejects an operation naming a constraint that is not in the document. This is the one edit a drag cannot express, since a drag can set a value but never withdraw one. Interval editing stays behind intervalEditingSupported, which is still false — compileGeometry() does not read profile.interval, and a control that changes nothing is worse than no control. The conversions are implemented and tested so the row appears when the flag flips. Probing a live manifest turned up a defect that is not from this change and is not fixed here: an edge offset advertises ±2.925 while the solver rejects past about ±1. Evidence is in the task's research/, and the requirement moved to 08-31-constraint-range-validation. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
5e4e42c46f
commit
1c27501534
17 files changed
+1335
-15
No files matched your search
@@ -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<Extract<SemanticAnchor, { type: 'road-interval' }>> = {}): 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);
|
||||
});
|
||||
});
|
||||
@@ -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<ConstraintKind, string> = {
|
||||
'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);
|
||||
}
|
||||
Reference in new issue
Block a user