Merge reviewed fractional nudge preservation

This commit is contained in:
haelyra committed 2026-11-19 18:58:27 -05:00
commit 863e3eee05
5 files changed
+157 -22

No files matched your search

+10 -2
View File
@@ -52,6 +52,14 @@ function clampInt(value, { min = 0, max = MAX_DIMENSION } = {}) {
return Math.min(max, Math.max(min, Math.round(number)));
}
// Dragging subtracts CSS positions, so even an integer gesture can produce
// a fractional distance. Preserve that finite effect within the same bounds.
function clampOffset(value) {
const number = typeof value === 'number' ? value : Number.parseFloat(value);
if (!Number.isFinite(number)) return null;
return Math.min(MAX_DIMENSION, Math.max(-MAX_DIMENSION, number));
}
// A dimension of zero or less is "not provided", never a 1px viewport.
function positiveInt(value) {
const number = typeof value === 'number' ? value : Number.parseFloat(value);
@@ -143,8 +151,8 @@ function normalizeEdit(raw, position) {
return edit;
}
case 'nudge': {
const dx = clampInt(raw.dx, { min: -MAX_DIMENSION });
const dy = clampInt(raw.dy, { min: -MAX_DIMENSION });
const dx = clampOffset(raw.dx);
const dy = clampOffset(raw.dy);
if (dx === null || dy === null) return null;
edit.dx = dx;
edit.dy = dy;
+8 -2
View File
@@ -29,11 +29,17 @@ function serveUiAsset(pathname, res) {
}
function requireLosslessReplay(raw) {
const edit = normalizeEdit(raw, 0);
if (!edit) return; // Preserve omission of malformed/unknown edit kinds.
const reject = field => {
throw Object.assign(new Error(`replay cannot preserve the edit's ${field}; use a supported value`), { code: 'EUI_REPLAY_LOSSY' });
};
if (raw && raw.kind === 'nudge') {
for (const value of [raw.dx, raw.dy]) {
const parsed = typeof value === 'number' ? value : Number.parseFloat(value);
if (!Number.isFinite(parsed)) reject('numeric value');
}
}
const edit = normalizeEdit(raw, 0);
if (!edit) return; // Preserve omission of unrelated malformed/unknown kinds.
if (raw.selector !== edit.selector) reject('selector');
if (typeof raw.id === 'string' && raw.id !== edit.id) reject('identity');
if (edit.kind === 'text') {
+1 -1
View File
@@ -40,7 +40,7 @@ test('normalizeEdit accepts every supported kind and clamps fields', () => {
assert.deepStrictEqual(move.to, { parent: 'div.b', index: 0 });
const nudge = feedback.normalizeEdit({ kind: 'nudge', selector: 'p', dx: -4, dy: 10.6 }, 0);
assert.deepStrictEqual([nudge.dx, nudge.dy], [-4, 11]);
assert.deepStrictEqual([nudge.dx, nudge.dy], [-4, 10.6]);
const remove = feedback.normalizeEdit({ kind: 'remove', selector: 'button.secondary', outerHTML: '<button>x</button>', from: { parent: 'div.actions', index: 1 } }, 0);
assert.strictEqual(remove.outerHTML, '<button>x</button>');
@@ -0,0 +1,121 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const vm = require('node:vm');
const { createSessionStore } = require('../../scripts/lib/plan-canvas/sessions');
const { createPlanCanvasServer } = require('../../scripts/lib/plan-canvas/server');
const { normalizeEdit } = require('../../scripts/lib/ui-canvas/feedback');
const { uiEditorJs } = require('../../scripts/lib/ui-canvas/editor');
const { editorGesturesJs } = require('../../scripts/lib/ui-canvas/editor-gestures');
let passed = 0;
let failed = 0;
async function test(name, run) {
try { await run(); passed++; console.log('PASS ' + name); }
catch (error) { failed++; console.log('FAIL ' + name + ': ' + error.stack); }
}
const section = (source, start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start)));
function style(left, top) {
return { left: left + 'px', top: top + 'px', position: 'relative',
getPropertyValue(name) { return this[name] || ''; },
setProperty(name, value) { this[name] = value; },
removeProperty(name) { delete this[name]; } };
}
function captureDrag(left, top, nextLeft, nextTop) {
let captured;
const target = { style: style(nextLeft, nextTop), isConnected: true };
const context = { document: { documentElement: { removeAttribute() {} } }, post() {}, toast() {},
px: value => Number.parseFloat(value) || 0,
newEdit: (kind, _el, detail) => ({ id: 'nudge1', kind, selector: '#a', ...detail }),
record: edit => { const { _el, _inlineBefore, ...record } = edit; captured = record; },
applyInline: (el, values) => Object.assign(el.style, values) };
vm.createContext(context);
vm.runInContext(section(editorGesturesJs(), ' function endDrag(', ' function nudgeBy('), context);
context.endDrag({ kind: 'nudge', el: target, baseLeft: left, baseTop: top,
inlineBefore: { left: left + 'px', top: top + 'px' } });
return captured;
}
function replay(edit, left, top) {
const target = { style: style(left, top), isConnected: true };
const context = { px: value => Number.parseFloat(value) || 0, getComputedStyle: () => ({ position: 'relative' }), resolveForEdit: () => target };
vm.createContext(context);
const source = uiEditorJs();
vm.runInContext(section(source, ' function applyInline(', ' function contentBoxDelta(')
+ section(source, ' function applyEdit(', ' function undo('), context);
assert.equal(context.applyEdit({ ...edit }, null), true);
return target.style;
}
async function fixture(run) {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-ui-numeric-'));
const file = path.join(directory, 'card.html');
fs.writeFileSync(file, '<html><body><div id="a"></div></body></html>');
const stateDir = path.join(directory, 'state');
const store = createSessionStore({ stateDir });
const key = store.open(file, { mode: 'ui' }).session.key;
const server = createPlanCanvasServer({ store });
const { port } = await server.listen(0);
function request(body) {
return new Promise((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, method: 'POST',
path: '/api/session/' + key + '/feedback', headers: { 'content-type': 'application/json' } }, res => {
let text = ''; res.on('data', chunk => { text += chunk; });
res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(text) }));
});
req.on('error', reject); req.end(JSON.stringify(body));
});
}
try { await run({ directory, file, stateDir, store, key, request }); }
finally { await server.close(); fs.rmSync(directory, { recursive: true, force: true }); }
}
async function main() {
for (const kind of ['edits', 'finish']) {
await test('actual fractional drag survives ' + kind + ', disk reopen, drain and generated replay', () => fixture(async ({ stateDir, store, key, request }) => {
const edit = captureDrag(0.3, -4.1, 32.3, -3.55);
assert.equal(edit.dx, 32.3 - 0.3);
assert.notEqual(edit.dx, 32, 'Exercise actual binary floating subtraction, not a rounded substitute');
assert.equal(edit.dy, -3.55 - -4.1);
const html = '<html><body><div id="a" style="position:relative;left:32.3px;top:-3.55px"></div></body></html>';
const response = await request({ deliveryId: (kind === 'edits' ? 'a' : 'b').repeat(32),
items: [{ kind, html, edits: [edit] }], endSession: kind === 'finish' });
assert.equal(response.status, 200, JSON.stringify(response.body));
assert.deepEqual(response.body.acceptedEditIds, ['nudge1']);
const accepted = store.get(key).pendingFeedback[0];
assert.equal(fs.readFileSync(accepted.exportPath, 'utf8'), html);
assert.equal(JSON.parse(fs.readFileSync(accepted.editsPath, 'utf8')).edits[0].dx, edit.dx);
const reopened = createSessionStore({ stateDir });
const drained = reopened.takeFeedback(key);
assert.equal(drained.status, 'feedback');
const saved = drained.items[0].edits[0];
assert.equal(saved.dx, edit.dx); assert.equal(saved.dy, edit.dy);
const replayed = replay(saved, 0.3, -4.1);
assert.equal(Number.parseFloat(replayed.left), 32.3);
assert.equal(Number.parseFloat(replayed.top), -3.55);
}));
}
await test('genuine subpixel offsets and bounded numeric strings remain exact', () => {
for (const [dx, dy] of [[1.5, -0.25], [-20000, 20000], ['1.125', '-0.875']]) {
const edit = normalizeEdit({ kind: 'nudge', selector: '#a', dx, dy }, 0);
assert.equal(edit.dx, Number(dx)); assert.equal(edit.dy, Number(dy));
}
});
for (const dx of [20000.25, -20000.25, 'Infinity', 'NaN']) {
await test('rejects invalid nudge ' + dx + ' before any export or queue write', () => fixture(async ({ directory, store, key, request }) => {
const before = fs.readdirSync(directory).sort(); const state = JSON.stringify(store.get(key));
const response = await request({ items: [{ kind: 'edits', html: '<html>captured</html>', edits: [{ id: 'bad', kind: 'nudge', selector: '#a', dx, dy: 0 }] }] });
assert.equal(response.status, 422, JSON.stringify(response.body));
assert.deepEqual(fs.readdirSync(directory).sort(), before);
assert.equal(JSON.stringify(store.get(key)), state);
}));
}
await test('nonfinite normalization stays unusable and other numeric contracts stay integers', () => {
for (const value of [Infinity, -Infinity, NaN]) assert.equal(normalizeEdit({ kind: 'nudge', selector: '#a', dx: value, dy: 0 }, 0), null);
assert.equal(normalizeEdit({ kind: 'resize', selector: '#a', width: 10.6 }, 0).width, 11);
assert.equal(normalizeEdit({ kind: 'move', selector: '#a', from: { parent: 'body', index: 0 }, to: { parent: 'body', index: 1.6 } }, 0).to.index, 2);
});
console.log('Passed: ' + passed + '\nFailed: ' + failed); process.exitCode = failed ? 1 : 0;
}
main().catch(error => { console.error(error); process.exitCode = 1; });
@@ -37,7 +37,7 @@ async function fixture(run) {
function item(edits, extra = {}) {
return { kind: 'edits', html: '<html><body><div id="a">Captured</div></body></html>', edits, ...extra };
}
try { await run({ directory, file, store, session, request, item }); }
try { await run({ directory, file, store, session, getSession: () => store.get(session.key), request, item }); }
finally { await server.close(); fs.rmSync(directory, { recursive: true, force: true }); }
}
@@ -50,17 +50,17 @@ async function main() {
['edit identity', nudge('e'.repeat(41))],
['resize bound', { id: 'e1', kind: 'resize', selector: '#a', width: 20001 }],
['nudge bound', { ...nudge('e1'), dx: -20001 }],
['fractional nudge', { ...nudge('e1'), dx: 1.5 }],
['fractional resize', { id: 'e1', kind: 'resize', selector: '#a', width: 1.5 }],
['move index', { id: 'e1', kind: 'move', selector: '#a', from: { parent: 'body', index: 0 }, to: { parent: 'body', index: 100001 } }],
['move parent', { id: 'e1', kind: 'move', selector: '#a', from: { parent: 'body', index: 0 }, to: { parent: '#' + 'a'.repeat(500), index: 0 } }],
]) {
await test(`rejects lossy ${label} before exports or queue mutation`, () => fixture(async ({ directory, session, request, item }) => {
await test(`rejects lossy ${label} before exports or queue mutation`, () => fixture(async ({ directory, getSession, request, item }) => {
const before = fs.readdirSync(directory).sort();
const state = JSON.stringify(session);
const state = JSON.stringify(getSession());
const response = await request([item([edit])]);
assert.equal(response.status, 422, JSON.stringify(response.body));
assert.deepEqual(fs.readdirSync(directory).sort(), before);
assert.equal(JSON.stringify(session), state);
assert.equal(JSON.stringify(getSession()), state);
}));
}
await test('a later lossy item prevents exporting an earlier valid item', () => fixture(async ({ directory, request, item }) => {
@@ -69,7 +69,7 @@ async function main() {
assert.equal(response.status, 422);
assert.deepEqual(fs.readdirSync(directory).sort(), before);
}));
await test('boundary-size text and numeric replay payloads remain complete', () => fixture(async ({ session, request, item }) => {
await test('boundary-size text and numeric replay payloads remain complete', () => fixture(async ({ getSession, request, item }) => {
const text = 'x'.repeat(20000);
const html = `<html><body><div id="a" style="width:20000px;height:1px;position:relative;left:-20000px;top:20000px">${text}</div></body></html>`;
const response = await request([item([
@@ -79,33 +79,33 @@ async function main() {
], { html })]);
assert.equal(response.status, 200);
assert.equal(response.body.batches[0].edits[0].htmlAfter, text);
assert.equal(session.uiBatches[0].edits[1].width, 20000);
assert.equal(session.uiBatches[0].edits[2].dx, -20000);
assert.equal(fs.readFileSync(session.pendingFeedback[0].exportPath, 'utf8'), html);
assert.equal(getSession().uiBatches[0].edits[1].width, 20000);
assert.equal(getSession().uiBatches[0].edits[2].dx, -20000);
assert.equal(fs.readFileSync(getSession().pendingFeedback[0].exportPath, 'utf8'), html);
}));
await test('an empty older batch is not covered by unrelated edit IDs', () => fixture(async ({ store, session, request, item }) => {
await test('an empty older batch is not covered by unrelated edit IDs', () => fixture(async ({ store, session, getSession, request, item }) => {
const empty = store.queueFeedback(session.key, [{ kind: 'edits', edits: [], snapshotHash: 'a'.repeat(64) }]).accepted[0].id;
const response = await request([item([nudge('new')], { bakedEditIds: [] })]);
assert.equal(response.status, 200);
assert.deepEqual(session.uiBatches.at(-1).includedBatches, []);
assert.ok(session.uiBatches.some(batch => batch.id === empty));
assert.deepEqual(getSession().uiBatches.at(-1).includedBatches, []);
assert.ok(getSession().uiBatches.some(batch => batch.id === empty));
}));
for (const count of [49, 50]) {
await test(`${count} covered older batches ${count === 49 ? 'fit' : 'exceed'} the acknowledgment limit`, () => fixture(async ({ directory, store, session, request, item }) => {
await test(`${count} covered older batches ${count === 49 ? 'fit' : 'exceed'} the acknowledgment limit`, () => fixture(async ({ directory, store, session, getSession, request, item }) => {
const ids = Array.from({ length: count }, (_, index) => `old-${index}`);
store.queueFeedback(session.key, ids.map(id => ({ kind: 'edits', edits: [nudge(id)], snapshotHash: 'a'.repeat(64) })));
const before = fs.readdirSync(directory).sort();
const state = JSON.stringify(session);
const state = JSON.stringify(getSession());
const response = await request([item([nudge('latest')], { bakedEditIds: ids })]);
if (count === 50) {
assert.equal(response.status, 413);
assert.equal(JSON.stringify(session), state);
assert.equal(JSON.stringify(getSession()), state);
assert.deepEqual(fs.readdirSync(directory).sort(), before);
} else {
assert.equal(response.status, 200);
const latest = session.pendingFeedback.at(-1);
const latest = getSession().pendingFeedback.at(-1);
assert.equal(latest.includedBatches.length, 49);
const hint = UI_PROFILE.nextSteps.feedback({ items: session.pendingFeedback });
const hint = UI_PROFILE.nextSteps.feedback({ items: getSession().pendingFeedback });
assert.equal(hint.match(/--ack ([^ ]+)/)[1].split(',').length, 50);
}
}));