Files
SupplierSystem/src/utils/deliveryTemplateLayout.test.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

407 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest';
import { applyLayoutTargets, canSwapTitleNodes, fitPreviewScale, resolveEditorFontState, setLayoutNodePositions, toggleNodeSelection, toFlowOffsetsFromRects } from './deliveryTemplateLayout';
import type { DeliveryHtmlTemplateLayout } from './deliveryHtmlTemplates';
/**
* 换算成「跟随内容」语义(2026-10-07)。
*
* 事故:唯一节点原本存**绝对目标位置**(渲染时 `位移 = 目标 − 自然位置`),元素被钉死在页面上;
* 编辑器预览是样例 8 行,真实单据行数一变,「合计」这类该跟着表格走的元素就错位。
* 新语义:坐标 = **相对自然位置的偏移**;换算原则 = 保持用户当前看到的样子
* (`偏移 = 当前渲染位置 − 自然位置`)。
*/
const CONTENT_W = 800; // px
const CONTENT_H = 1000; // px
const offsetLayout: DeliveryHtmlTemplateLayout = {
nodes: { '3': { xPercent: 10, yPercent: 5, fontSize: 14 } },
additions: [],
};
/** 造一个「自然位置 + 当前渲染位置」的假测量器 */
function rects(map: Record<string, { natural: [number, number]; rendered: [number, number] }>) {
return (id: string) => {
const row = map[id];
if (!row) return null;
return {
natural: { left: row.natural[0], top: row.natural[1] },
rendered: { left: row.rendered[0], top: row.rendered[1] },
};
};
}
describe('toFlowOffsetsFromRects', () => {
it('把绝对目标换算成偏移:偏移 = 渲染位置 − 自然位置,并标记 anchoring=flow', () => {
// 自然位置 (40,300)、渲染位置 (120,350) → 偏移 (80,50)px = (10%,5%)
const next = toFlowOffsetsFromRects(offsetLayout, rects({ '3': { natural: [40, 300], rendered: [120, 350] } }), CONTENT_W, CONTENT_H);
expect(next).not.toBe(offsetLayout);
expect(next.anchoring).toBe('flow');
expect(next.nodes['3'].xPercent).toBeCloseTo(10, 4);
expect(next.nodes['3'].yPercent).toBeCloseTo(5, 4);
expect(next.nodes['3'].fontSize).toBe(14); // 其它属性保留
expect(next.nodes['3'].x).toBeUndefined();
expect(next.nodes['3'].y).toBeUndefined();
});
it('已是 flow 语义(渲染 = 自然 + 偏移)→ no-op:返回同一引用', () => {
const flow: DeliveryHtmlTemplateLayout = {
anchoring: 'flow',
nodes: { '3': { xPercent: 10, yPercent: 5 } },
additions: [],
};
// 自然 (40,300) + 偏移 (80,50) = 渲染 (120,350) → 再算仍是 (10%,5%)
expect(toFlowOffsetsFromRects(flow, rects({ '3': { natural: [40, 300], rendered: [120, 350] } }), CONTENT_W, CONTENT_H)).toBe(flow);
});
it('只处理带坐标的节点:没坐标的、量不到的、legacy px 字段的都按预期处理', () => {
const layout: DeliveryHtmlTemplateLayout = {
nodes: {
'1': { fontSize: 12 }, // 无坐标 → 不动
'2': { xPercent: 5, yPercent: 5 }, // 量不到 → 不动
'4': { x: 37.79527559, y: 37.79527559 }, // legacy px 字段 → 用测量换算成偏移
},
additions: [],
};
const next = toFlowOffsetsFromRects(
layout,
rects({ '4': { natural: [100, 300], rendered: [200, 400] } }),
CONTENT_W,
CONTENT_H
);
expect(next.nodes['1']).toEqual({ fontSize: 12 });
expect(next.nodes['2']).toEqual({ xPercent: 5, yPercent: 5 });
expect(next.nodes['4'].xPercent).toBeCloseTo(12.5, 4); // (200-100)/800
expect(next.nodes['4'].yPercent).toBeCloseTo(10, 4); // (400-300)/1000
});
it('内容框尺寸非法时不动(避免除零)', () => {
expect(toFlowOffsetsFromRects(offsetLayout, rects({ '3': { natural: [0, 0], rendered: [1, 1] } }), 0, 0)).toBe(offsetLayout);
});
/**
* 重复节点(明细循环体 / {{#categories}} 组内,例如每个分类的「金额小计」行)本来就是偏移语义,
* 换算时原样保留,只补上 anchoring 标记。
*/
it('重复节点的坐标原样保留(本来就是偏移语义)', () => {
const layout: DeliveryHtmlTemplateLayout = {
nodes: { '3': { xPercent: 10, yPercent: 5, fontSize: 14, textAlign: 'center', hidden: true } },
additions: [],
};
const next = toFlowOffsetsFromRects(
layout,
rects({ '3': { natural: [0, 0], rendered: [100, 200] } }),
CONTENT_W,
CONTENT_H,
{ isRepeated: (id) => id === '3' }
);
expect(next.nodes['3']).toEqual({ xPercent: 10, yPercent: 5, fontSize: 14, textAlign: 'center', hidden: true });
expect(next.anchoring).toBe('flow');
});
it('同一偏移在「8 行样例」与「真实 2 行」下换算结果一致(不会把位置钉死在样例行数上)', () => {
// 情景:合计节点的自然位置随行数变(8 行时 600、2 行时 300),用户始终只想让它「就在原地」→ 偏移 0
const layout: DeliveryHtmlTemplateLayout = {
nodes: { '9': { xPercent: 50, yPercent: 60 } }, // 8 行样例里它渲染在 60% 处
additions: [],
};
const eightRows = toFlowOffsetsFromRects(layout, rects({ '9': { natural: [400, 600], rendered: [400, 600] } }), CONTENT_W, CONTENT_H);
const twoRows = toFlowOffsetsFromRects(layout, rects({ '9': { natural: [400, 300], rendered: [400, 600] } }), CONTENT_W, CONTENT_H);
expect(eightRows.nodes['9'].yPercent).toBeCloseTo(0, 4); // 样例行数下:原地 → 偏移 0
expect(twoRows.nodes['9'].yPercent).toBeCloseTo(30, 4); // 真实 2 行:为保持同样观感把偏移算成 +30%
});
});
/**
* 写入节点新坐标(编辑器「拖到另一个元素上交换位置」用;测量与位移计算留在调用方)。
* 两种节点的存储语义不同,但都由调用方按「自己的基准 + (对方位置 − 自己位置)」算好后写入:
* 唯一节点存绝对位置、重复节点(明细行/分组内的小计行)存统一偏移。
*/
describe('setLayoutNodePositions', () => {
it('写入两个节点的新坐标,其余属性各自保留,并清掉遗留 mm 字段', () => {
const layout: DeliveryHtmlTemplateLayout = {
nodes: {
'0': { xPercent: 10, yPercent: 2, fontSize: 26, textAlign: 'center' },
'7': { x: 37.79527559, y: 37.79527559, hidden: true },
},
additions: [],
};
const next = setLayoutNodePositions(layout, [
{ id: '0', xPercent: 40, yPercent: 30 },
{ id: '7', xPercent: 10, yPercent: 2 },
]);
expect(next.nodes['0']).toEqual({ xPercent: 40, yPercent: 30, fontSize: 26, textAlign: 'center' });
expect(next.nodes['7']).toEqual({ xPercent: 10, yPercent: 2, hidden: true, x: undefined, y: undefined });
// 不改原对象
expect(layout.nodes['0'].xPercent).toBe(10);
});
it('原本没有条目的节点也能写入(首次移动)', () => {
const layout: DeliveryHtmlTemplateLayout = { nodes: {}, additions: [] };
const next = setLayoutNodePositions(layout, [{ id: '3', xPercent: 5, yPercent: 1 }]);
expect(next.nodes['3']).toEqual({ xPercent: 5, yPercent: 1, x: undefined, y: undefined });
expect(next.additions).toEqual([]);
});
it('空数组等于不改(返回新对象但内容一致)', () => {
const layout: DeliveryHtmlTemplateLayout = { nodes: { '1': { xPercent: 1, yPercent: 1 } }, additions: [] };
const next = setLayoutNodePositions(layout, []);
expect(next.nodes).toEqual(layout.nodes);
});
});
/**
* 方案 B(2026-10-06):元素保持文档流,只把「目标坐标」换算成 transform 位移。
* 起因:绝对定位会让元素脱离文档流 —— 把标题换到别处后,原位空出来、下方内容整体上移。
* jsdom 没有排版引擎,这里用可控的假 rect 驱动:自然位置与目标坐标都在测试里给定。
*/
describe('applyLayoutTargets', () => {
const MM = 96 / 25.4;
function build(attrs: { x?: number; y?: number }, natural: { left: number; top: number }) {
document.body.innerHTML =
'<div class="delivery-html-template-root"><p id="n">x</p></div>';
const root = document.querySelector<HTMLElement>('.delivery-html-template-root')!;
const el = document.getElementById('n') as HTMLElement;
if (attrs.x !== undefined) el.dataset.dhtX = String(attrs.x);
if (attrs.y !== undefined) el.dataset.dhtY = String(attrs.y);
root.getBoundingClientRect = () =>
({ left: 0, top: 0, width: 800, height: 1000, right: 800, bottom: 1000, x: 0, y: 0, toJSON: () => ({}) }) as DOMRect;
el.getBoundingClientRect = () =>
({
left: natural.left,
top: natural.top,
width: 100,
height: 20,
right: natural.left + 100,
bottom: natural.top + 20,
x: natural.left,
y: natural.top,
toJSON: () => ({}),
}) as DOMRect;
return { root, el };
}
it('把目标坐标换算成位移(目标 − 自然位置)', () => {
const { el } = build({ x: 20, y: 10 }, { left: 40, top: 300 });
applyLayoutTargets(document);
const match = /translate\(([-0-9.]+)px, ([-0-9.]+)px\)/.exec(el.style.transform);
expect(match).not.toBeNull();
expect(Number(match![1])).toBeCloseTo(20 * MM - 40, 6);
expect(Number(match![2])).toBeCloseTo(10 * MM - 300, 6);
expect(el.style.getPropertyPriority('transform')).toBe('important');
});
it('目标与自然位置一致时不写 transform(不产生无谓样式)', () => {
const { el } = build({ x: 20, y: 10 }, { left: 20 * MM, top: 10 * MM });
applyLayoutTargets(document);
expect(el.style.transform).toBe('');
});
it('幂等:重复执行结果一致(每次先清掉旧位移再量)', () => {
const { el } = build({ x: 20, y: 10 }, { left: 40, top: 300 });
applyLayoutTargets(document);
const first = el.style.transform;
applyLayoutTargets(document);
expect(el.style.transform).toBe(first);
});
it('没有 data 目标的元素(重复节点走相对平移)不动', () => {
const { el } = build({}, { left: 40, top: 300 });
applyLayoutTargets(document);
expect(el.style.transform).toBe('');
});
it('没有 .delivery-html-template-root 时直接返回,不报错', () => {
document.body.innerHTML = '<div><p id="n">x</p></div>';
expect(() => applyLayoutTargets(document)).not.toThrow();
});
});
/**
* 手动编辑预览的等比缩放(2026-10-06):窄窗口里不再横向滚动。
* 只缩放 iframe 元素本身,iframe 内部坐标系不变 → 拖拽坐标计算不受影响。
*/
describe('fitPreviewScale', () => {
it('容器够宽时不放大(上限 1)', () => {
expect(fitPreviewScale(1200, 900)).toBe(1);
expect(fitPreviewScale(900, 900)).toBe(1);
});
it('容器更窄时按比例缩小', () => {
expect(fitPreviewScale(450, 900)).toBeCloseTo(0.5, 6);
expect(fitPreviewScale(720, 900)).toBeCloseTo(0.8, 6);
});
it('尺寸非法时返回 1(不影响渲染)', () => {
expect(fitPreviewScale(0, 900)).toBe(1);
expect(fitPreviewScale(-10, 900)).toBe(1);
expect(fitPreviewScale(800, 0)).toBe(1);
});
});
/**
* 事故(2026-10-06 再次):编辑器 onLoad 里「把目标坐标应用成位移」与「按渲染位置换算语义」
* 这两步的**顺序**不能颠倒,必须**先应用、后换算**。
*
* 方案 B 的位置不写在 CSS 里,而是加载后由 applyLayoutTargets() 现写 transform。
* 若先换算,rectOf 量到的是**还没应用位移的自然位置**,换算就把每个唯一节点改写成自然位置
* ⇒ 用户每次拖完、预览重载时坐标被抹掉,症状 = 「拖上去不动 / 位置存不下来」。
* 重复节点({{#categories}} / {{#items}} 组内)按 isRepeated 跳过换算,所以一直能拖 ——
* 用户看到的正是「分组里的行能拖,页眉的收货商户 / 配送时间 / 仓号拖不动」。
*/
describe('编辑器加载管线:必须先应用位移,再把渲染位置换算成语义坐标', () => {
const MM = 96 / 25.4;
const CONTENT_W_PX = 800;
const CONTENT_H_PX = 1000;
// 两个节点互换:[0] 自然在 x=40px,目标 x=200px(25%);[1] 自然在 x=200px,目标 x=40px(5%)
const swapped: DeliveryHtmlTemplateLayout = {
nodes: { '0': { xPercent: 25, yPercent: 30 }, '1': { xPercent: 5, yPercent: 30 } },
additions: [],
};
/** 假排版引擎:渲染位置 = 自然位置 + 行内 transform 的位移(正是浏览器的 translate 语义) */
function buildPipelineDocument() {
document.body.innerHTML = '<div class="delivery-html-template-root">'
+ '<span class="dht-edit-node-0">A</span><span class="dht-edit-node-1">B</span></div>';
const root = document.querySelector<HTMLElement>('.delivery-html-template-root')!;
const natural: Record<string, { left: number; top: number }> = {
'0': { left: 40, top: 300 },
'1': { left: 200, top: 300 },
};
const rect = (left: number, top: number, width: number, height: number) =>
({ left, top, width, height, right: left + width, bottom: top + height, x: left, y: top, toJSON: () => ({}) }) as DOMRect;
root.getBoundingClientRect = () => rect(0, 0, CONTENT_W_PX, CONTENT_H_PX);
document.querySelectorAll<HTMLElement>('.dht-edit-node-0, .dht-edit-node-1').forEach((el) => {
const id = el.className.match(/dht-edit-node-(\d+)/)![1];
// 老语义(绝对目标):渲染器把目标坐标写进 data 属性,由 applyLayoutTargets 换算成位移
const target = swapped.nodes[id]!;
el.dataset.dhtX = String(CONTENT_W_PX * Number(target.xPercent) / 100 / MM);
el.dataset.dhtY = String(CONTENT_H_PX * Number(target.yPercent) / 100 / MM);
el.getBoundingClientRect = () => {
const match = /translate\(([-0-9.]+)px,\s*([-0-9.]+)px\)/.exec(el.style.transform || '');
return rect(natural[id].left + (match ? Number(match[1]) : 0), natural[id].top + (match ? Number(match[2]) : 0), 100, 20);
};
});
const rectsOf = (id: string) => {
const el = document.querySelector<HTMLElement>(`.dht-edit-node-${id}`);
if (!el) return null;
const rendered = el.getBoundingClientRect();
const nat = natural[id];
return {
natural: { left: nat.left, top: nat.top },
rendered: { left: rendered.left, top: rendered.top },
};
};
return { rectsOf };
}
const noRepeats = { isRepeated: () => false };
it('先应用位移再换算:偏移 = 渲染位置 − 自然位置(用户调好的样子被保住,并从此跟着内容走)', () => {
const { rectsOf } = buildPipelineDocument();
applyLayoutTargets(document); // 老语义的位移是加载后现写的 —— 必须先跑,量到的才是「用户看到的位置」
const converted = toFlowOffsetsFromRects(swapped, rectsOf, CONTENT_W_PX, CONTENT_H_PX, noRepeats);
expect(converted).not.toBe(swapped);
expect(converted.anchoring).toBe('flow');
expect(converted.nodes['0']!.xPercent).toBeCloseTo(20, 4); // (200-40)/800
expect(converted.nodes['1']!.xPercent).toBeCloseTo(-20, 4); // (40-200)/800
});
it('先换算再应用位移:量到的是自然位置 → 偏移被抹成 0(顺序不能反,这就是「位置被抹平」的成因)', () => {
const { rectsOf } = buildPipelineDocument();
const converted = toFlowOffsetsFromRects(swapped, rectsOf, CONTENT_W_PX, CONTENT_H_PX, noRepeats);
expect(converted.nodes['0']!.xPercent).toBeCloseTo(0, 6);
expect(converted.nodes['1']!.xPercent).toBeCloseTo(0, 6);
});
it('重复节点(分组内的行)本来就是偏移语义,不参与换算', () => {
const { rectsOf } = buildPipelineDocument();
applyLayoutTargets(document);
const converted = toFlowOffsetsFromRects(swapped, rectsOf, CONTENT_W_PX, CONTENT_H_PX, { isRepeated: () => true });
expect(converted.nodes).toEqual(swapped.nodes); // 坐标未被改写
});
});
/**
* 面板字号/加粗的取值(2026-10-07):模板 CSS 定的字号/字重也要能在面板里看到,
* 否则输入框空着,看着像「没设置字号」。
*/
describe('resolveEditorFontState', () => {
it('没有布局覆盖时用浏览器算出来的实际字号', () => {
expect(resolveEditorFontState({ computedFontSizePx: '36px', computedFontWeight: '700' })).toEqual({ fontSize: 36, bold: true });
});
it('有覆盖值时覆盖值优先', () => {
expect(resolveEditorFontState({ storedFontSize: 18, storedFontWeight: 400, computedFontSizePx: '36px', computedFontWeight: 'bold' }))
.toEqual({ fontSize: 18, bold: false });
});
it('加粗判定:bold / bolder / ≥600 算加粗,400 / normal 不算', () => {
expect(resolveEditorFontState({ computedFontWeight: 'bold' }).bold).toBe(true);
expect(resolveEditorFontState({ computedFontWeight: 'bolder' }).bold).toBe(true);
expect(resolveEditorFontState({ computedFontWeight: '600' }).bold).toBe(true);
expect(resolveEditorFontState({ computedFontWeight: '400' }).bold).toBe(false);
expect(resolveEditorFontState({ computedFontWeight: 'normal' }).bold).toBe(false);
});
it('取值缺失/非法时不抛错、字号为 undefined', () => {
expect(resolveEditorFontState({})).toEqual({ fontSize: undefined, bold: false });
expect(resolveEditorFontState({ computedFontSizePx: '', storedFontSize: 0 }).fontSize).toBeUndefined();
expect(resolveEditorFontState({ computedFontSizePx: 'auto' }).fontSize).toBeUndefined();
});
});
/**
* 标题互换的合法落点(2026-10-07 事故修正):只有「标题 ↔ 标题」且同为重复/唯一节点才允许互换,
* 否则把表头换到表格容器位置会导致整张表跑位。
*/
describe('canSwapTitleNodes', () => {
it('标题 ↔ 标题、且同为唯一节点 ⇒ 允许', () => {
expect(canSwapTitleNodes({ targetTitleLike: true, sourceRepeated: false, targetRepeated: false })).toBe(true);
});
it('标题 ↔ 标题、且同为循环体节点 ⇒ 允许', () => {
expect(canSwapTitleNodes({ targetTitleLike: true, sourceRepeated: true, targetRepeated: true })).toBe(true);
});
it('目标是字段值/容器(非标题)⇒ 不允许(否则会把表格也写坐标)', () => {
expect(canSwapTitleNodes({ targetTitleLike: false, sourceRepeated: false, targetRepeated: false })).toBe(false);
});
it('跨类型(唯一 ↔ 循环体)⇒ 不允许(坐标语义不同:绝对位置 vs 统一偏移)', () => {
expect(canSwapTitleNodes({ targetTitleLike: true, sourceRepeated: false, targetRepeated: true })).toBe(false);
expect(canSwapTitleNodes({ targetTitleLike: true, sourceRepeated: true, targetRepeated: false })).toBe(false);
});
it('标签名不同 ⇒ 不允许(表头只和表头换、标签只和标签换,避免页眉标签换进表格)', () => {
expect(canSwapTitleNodes({ targetTitleLike: true, sourceRepeated: false, targetRepeated: false, sameTag: false })).toBe(false);
expect(canSwapTitleNodes({ targetTitleLike: true, sourceRepeated: false, targetRepeated: false, sameTag: true })).toBe(true);
});
});
/**
* 多选集合(2026-10-07):按住 Ctrl/⌘ 点选批量改字号/加粗。
*/
describe('toggleNodeSelection', () => {
it('普通点击 = 只选它', () => {
expect(toggleNodeSelection([3, 5], 8, false)).toEqual([8]);
});
it('Ctrl 点击 = 加入集合(最后点的在末尾)', () => {
expect(toggleNodeSelection([3, 5], 8, true)).toEqual([3, 5, 8]);
});
it('Ctrl 再点同一元素 = 从集合移出', () => {
expect(toggleNodeSelection([3, 5, 8], 5, true)).toEqual([3, 8]);
});
it('空集合上 Ctrl 点击 = 只选它', () => {
expect(toggleNodeSelection([], 4, true)).toEqual([4]);
});
});