feat(tasks): 画布动效改为布局坐标补间 + 错峰入场,FLIP 库只留流式布局
维护者第二轮反馈「还是突然直接出现」。上一版把 FLIP 库从画布摘掉后只留了 150ms 淡入 —— 太弱,看不出是「入场」。而且这个面本身需要的是**位置**动效, 不是入场动效,于是补上画布自己的补间: - tasks-layout-tween.ts:rAF 逐帧插值每张卡在**画布坐标**里的 x / y / 高度。 为什么必须是坐标而不是 transform:卡片层带 fit 的 scale(k),left/top 是画布 单位,缩放对它和对终点位置一样生效;量 rect 再播未缩放 translate 的 FLIP 在 这里恒差 k 倍,auto-animate 还会把离场卡片钉上无法表达的绝对 left/top。 fromRef 跟着「已绘制」状态走 —— 中途再次变布局时接着当前位置走,不弹回。 - 连线路径与相位框改为读补间后的盒子(它们本就是盒子的纯函数),于是线跟着 卡片走,不再在卡片还在飞的时候先瞬移到终点。 - 入场改为 300ms 上浮 + 0.88→1 缩放 + 淡入(轻微过冲),按节点页序错峰 26ms, fill-mode: backwards 让等待中的卡片先隐形;reduced-motion 下补间与入场都关。 修掉首版的一帧空档:新入场的节点在引入它的那一帧就带目标盒子渲染。 - 读者一碰折叠即接管视图(聚合卡 / 卡片 chevron / 控制条开关 → markTouched), 此后画布不再随布局自动重框;切会话重置并重新适配(顺带修掉换会话不适配的旧账)。 - FLIP 库保留在树视图与任务抽屉(那里离场是原地淡出 + 兄弟滑位的流式语义)。 守护:tests/tasks-layout-tween.spec.tsx(插值 / 缓动 / 中途位置 / 画布尺寸不中途 变化 / 入口盒子不缺席)与 tests/tasks-motion.spec.ts 扩到 5 条(画布不得 import FLIP 库、必须在画布坐标补间、入场必须错峰、折叠必须接管视图)。 全套 2248 passed / 17 skipped(193 文件)、tsc 与 eslint 0 错误、构建通过; 新构建已装进 sidebar-test,:3080 挂载正常(0 pageerror)。
This commit is contained in:
1 parent
34671dcb34
commit
e6f9eda60f
7 files changed
+428
-24
No files matched your search
+3
-1
@@ -12,7 +12,9 @@
|
||||
- 🏷 **模式词搬进徽标行**:子代理卡片此前每个都有一行 mono 元信息写着「一次性」——同一句话在每张卡上重复一次、还占一行高。现在模式(一次性 / 可持续)是**徽标旁的 chip**,智能体卡因此不再有元信息行、卡片高度预算同步收窄(只有工作流 run 卡还保留那行状态 / 成员元信息,行距按模型里有没有 run 取)。
|
||||
- 📊 **节点详情多两项事实**:新增 **Token 用量**(宿主 `tokenUsage` projection 的四个互斥桶求和,悬停给出未缓存输入 / 缓存读取 / 缓存写入 / 输出明细)与 **耗时**(宿主 `subagentTiming`:已结算回合 + 正在跑的那一轮,按页面轮询刷新)。两项都按宿主投影的**存在性**渲染——没有测量就不显示这一行,绝不打印一个说不清的 0;`SidebarProjectionSnapshot.values` 的镜像类型同步补上这两个键。
|
||||
- 🪟 **「查看转录」改为在原生右侧栏打开**(这是宿主自带能力):`dsh-resource://subagentchat/session/<childId>?parent=&mode=` + `ctx.sidebarRight.openResource(..., { kind: 'subagentchat', preferNewPane: true })`——与宿主自己的子代理列表(点行 = 主窗、点 chevron = 侧栏)同一套 tab 类型,主列保持不动;右侧新增小下拉按钮,菜单里可**在主窗中打开**(走原有的 `uiWorkspace.openSession` + 页签重挂)。宿主没有该 tab 类型 / 没有右栏 / 没有挂载会话时逐项降级回主窗并保持单按钮。
|
||||
- ✨ **动效**:接入 `@formkit/auto-animate`(`useAutoAnimateRef`,包一层 WAAPI 守卫,jsdom 与非 WAAPI 环境自动空转、并尊重 `prefers-reduced-motion`)——**树模式行**与**后台任务行**在折叠 / 新增 / 结算时滑入滑出而不是硬闪;详情卡与画布卡片各自加入场关键帧(140–150ms,reduced-motion 下关闭)。**画布刻意不跑 FLIP 库**:它的卡片层带着 fit 的 `transform: scale(k)`,而该库给离场元素钉的是 `getBoundingClientRect()` 换算出来的绝对 `left/top`(在缩放层里根本无法表达 → 元素跳位),移动项又按未缩放单位平移(行程差 k 倍)——真机上就是「折叠展开的动效都特别怪」。因此画布改为纯 CSS 入场(离场即时,与不动的连线一致),库只留给流式布局的面。
|
||||
- ✨ **动效:画布在自己的坐标系里补间**(`tasks-layout-tween.ts`)。卡片层带着 fit 的 `transform: scale(k)`,所以任何「量 rect、播 transform」的 FLIP 库在这里都是错的——`@formkit/auto-animate` 更会把离场卡片钉上由 rect 换算的绝对 `left/top`(缩放层里根本表达不出来 → 跳位)。改为**直接补间布局坐标**(每张卡的 `x`/`y`/高度):`left`/`top` 就是画布自己的单位,缩放对它和对终点位置一样生效;而连线路径与相位框都是「盒子的纯函数」,于是**跟着卡片逐帧走**,不再在卡片还在飞的时候先瞬移到终点。入场另有 CSS 关键帧(300ms:上浮 + 0.88→1 缩放 + 淡入,带轻微过冲),并按节点顺序**错峰 26ms**(一次展开多张时是瀑布而不是一下全冒),`backwards` 填充让等待中的卡片先隐形而不是先冒再动。
|
||||
- 🧭 **读者一碰折叠,视图就归他**:点聚合 / 点卡片 chevron / 控制条折叠开关都会把视图标记为「已接管」(与拖拽、缩放同一条规则),此后画布不再随布局变化自动重框——折叠时不会再把整棵树从读者眼皮底下抽走;⌂ 按钮交还自动适配。切会话时重置并重新适配(新的树 = 新的画布),顺带修掉「拖过一次之后换会话就不再适配」的旧账。
|
||||
- 🪶 **FLIP 库只留给流式布局**:树模式行与后台任务行的离场是「原地淡出 + 兄弟滑位」,那正是 FLIP 的语义且不受缩放影响;画布则明确排除(`tests/tasks-motion.spec.ts` 钉死:画布不得 import 它、树与抽屉必须有)。
|
||||
- 🧪 测试:新增 `tests/session-metrics.spec.ts`(5 条:四桶求和、空投影、运行中耗时按渲染时钟、0 不算工作、时钟回拨不显示负数)与 `tests/activity-icons.spec.ts`(3 条:13 个类别全覆盖、读 / 命令 / 搜索 / 网页互不同型、`undefined` 走思考图标);`tests/tasks-page.spec.tsx` 补 6 条(原生状态取代状态词、无数据回退、根卡真实状态、浮窗活动块位置、一次只开一组 + 判据极性的判别性用例、展开后成员仍可手工折回、Token / 耗时两行、侧栏打开地址 + 下拉在主窗打开 + 无宿主能力时单按钮、模式 chip 在徽标行);`tests/tasks-graph-layout.spec.ts` 的高度 / 行距断言跟随新的卡片预算。[设计文档](docs/plans/2026-10-11-tasks-status-and-group-fold.md)。
|
||||
|
||||
- 🃏 **任务卡小条只说原生状态**:运行中小条不再是「● 运行中 正在读取文件」这样把状态念两遍,而是**活动行取代状态词**——`正在分析请求` / `正在读取文件 · main.ts` / `正在准备读取文件` / `正在运行命令 · npm run build` 等措辞全部来自宿主 `chat` 命名空间,与主对话逐字一致;已结算小条同理(只留 `已读取文件、执行了命令`,不重复「已完成」)。**`空闲` 与 `出错` 保留状态词**(「待命」「失败」不被任何活动措辞蕴含),**完全没有活动数据时回退状态词**,小条永不空着。状态点、执行扫光与折叠 chevron 不变,小条仍是 22px——画布几何与卡片高度预算零改动。
|
||||
|
||||
@@ -127,7 +127,20 @@ state === 'running' → liveActivityLabel(summary) // 宿主 mess
|
||||
|
||||
### 第二轮的实施偏差与未验证项
|
||||
|
||||
1. **画布跑 FLIP 库是错的——已回退为 CSS 入场**(维护者真机反馈「折叠展开的动效都特别怪」,比预期的严重)。读源码后确认两处几何错误都不可修:`remove(el)` 会把离场元素重新插入 DOM 并钉上 **绝对 `left/top`/`width`/`height`(由 `getBoundingClientRect` 换算)**,而卡片层带 `transform: scale(k)` —— 这个钉位在缩放层里根本无法表达,离场卡片会跳位;移动项用 `el.animate` 播未缩放的 `translate`,而量测是缩放过的,行程差 k 倍。加上连线(SVG path)与相位框本来就不同步,观感必然崩。**处置**:画布改为 `.node` 上的纯 CSS 入场(150ms,mount-only,离场即时——与不动的连线一致),auto-animate 只保留在**流式布局**的树视图与任务抽屉(那两处的 FLIP 语义正确:离场元素原地淡出、兄弟滑位)。新增 `tests/tasks-motion.spec.ts` 把这条边界钉死:画布不得 import `use-auto-animate`,树与抽屉必须有。
|
||||
1. **画布动效:FLIP 库 → 布局坐标补间**(维护者两轮真机反馈:「折叠展开的动效都特别怪」→「还是突然直接出现」)。
|
||||
读 `@formkit/auto-animate` 源码确认它在缩放层里两处几何都不可修:`remove(el)` 把离场元素重新插入 DOM 并钉上
|
||||
由 `getBoundingClientRect` 换算的绝对 `left/top/width/height`(卡片层带 `transform: scale(k)`,这个钉位无法表达
|
||||
→ 跳位);移动项用 `el.animate` 播未缩放的 `translate`,而量测是缩放过的(行程差 k 倍)。于是分两步收口:
|
||||
- **画布改用自己的补间** `tasks-layout-tween.ts`:rAF 逐帧插值每张卡在**画布坐标**里的 `x`/`y`/高度(`left`/`top`
|
||||
是画布单位,缩放对它和对终点位置一样生效),并把 `fromRef` 跟着**已绘制**状态走(中途再来一次布局变化时接着当前位置走,
|
||||
不会弹回上一个目标)。连线路径与相位框改为读**补间后的盒子**,所以线跟着卡片走;新入场的卡片在引入它的那一帧就带着
|
||||
目标盒子渲染(否则会有「先消失一帧再出现」的闪烁,首版实测就踩到了)。
|
||||
- **入场用 CSS 关键帧**:300ms 上浮 + `scale(0.88→1)` + 淡入(轻微过冲),按节点页序**错峰 26ms**,`fill-mode: backwards`
|
||||
让等待中的卡片先隐形。`prefers-reduced-motion` 下补间与入场都关闭。
|
||||
- **读者碰折叠即接管视图**:`markTouched` 挂在三个折叠入口上(聚合卡、卡片 chevron、控制条开关),此后不再随布局自动重框;
|
||||
切会话重置并重新适配(顺带修掉「拖过一次后换会话不再适配」)。
|
||||
- **FLIP 库保留在流式布局**(树视图、任务抽屉);`tests/tasks-motion.spec.ts` 把「画布不得 import 它」写进守护,
|
||||
`tests/tasks-layout-tween.spec.tsx` 钉住插值 / 缓动 / 中途位置 / 画布尺寸不中途变化 / 入场盒子不缺席。
|
||||
2. **真机只跑通到「插件挂载 + 零 pageerror」**:新构建已装进 `sidebar-test` profile 并在 http://127.0.0.1:3080 提供服务(`[data-dsh-better-sidebar]` 挂载、`/sidebar/api/*` 200、无 pageerror / console error)。但**动效与观感的逐帧复核没做成**:宿主右栏在无头上下文里以 `transform` 平移到视口外,我的合成点击无法稳定地把任务页调出来(多次尝试后放弃)。这一条由维护者自己在实例上看。
|
||||
3. **实机数据的两个新行未在真机核验**:Token / 耗时两行通过夹具断言(25.5K / 2 分 42 秒)与 `session-metrics` 单测覆盖,但没有在真实子代理会话上截图确认数值口径(真实会话的 `tokenUsage` 是整段日志累计,包含 fork 继承前缀这一点已写进 `context-types.ts` 的注释)。
|
||||
4. **`uses` 依赖新增**:`@formkit/auto-animate@^0.10.0` 进 `dependencies`(无 `cordis`、无安装脚本,市场约束满足)。本 worktree 的 `node_modules` 因此从符号链接物化为独立副本(源仓库未被触碰,见仓库规则)。
|
||||
|
||||
+74
-14
@@ -40,6 +40,7 @@ import {
|
||||
GRAPH_FIT_MIN_SCALE, GRAPH_NODE_H, GRAPH_NODE_W, GRAPH_PAD, layoutTasksGraphForWidth,
|
||||
type GraphBox,
|
||||
} from './tasks-graph-layout.ts'
|
||||
import { useTweenedLayout } from './tasks-layout-tween.ts'
|
||||
import {
|
||||
activityLine, agentChip, agentMeta, foldErrorTally, foldPreviews, FoldGlyph, foldTally,
|
||||
TaskLine, WorkflowGlyph, workflowMeta,
|
||||
@@ -211,6 +212,14 @@ export function TasksGraph(props: TasksGraphProps): ReactNode {
|
||||
() => layoutTasksGraphForWidth(nodes, width, GRAPH_FIT_MIN_SCALE),
|
||||
[nodes, width],
|
||||
)
|
||||
/**
|
||||
* What is actually drawn: the layout tweened towards, frame by frame, in the
|
||||
* canvas's OWN coordinates (see tasks-layout-tween.ts — a screen-space FLIP
|
||||
* library cannot work under the fit's scale). Cards, connectors and phase
|
||||
* frames all read it, so the lines travel WITH the cards instead of snapping
|
||||
* to the new geometry.
|
||||
*/
|
||||
const drawn = useTweenedLayout(layout)
|
||||
const edges = useMemo(() => tasksEdges(nodes), [nodes])
|
||||
const nodeById = useMemo(() => new Map(nodes.map(node => [node.id, node])), [nodes])
|
||||
|
||||
@@ -272,11 +281,23 @@ export function TasksGraph(props: TasksGraphProps): ReactNode {
|
||||
fit()
|
||||
}, [fit])
|
||||
|
||||
// Auto-fit on mount, on layout growth and on container resize — but never
|
||||
// over a view the reader has panned/zoomed themselves.
|
||||
/** The newest `fit`, so the effects below can depend on WHAT changed. */
|
||||
const fitRef = useRef(fit)
|
||||
fitRef.current = fit
|
||||
|
||||
// A different tree is a different canvas: re-fit AND hand the view back to the
|
||||
// auto-fit, whatever the reader did to the previous one.
|
||||
useEffect(() => {
|
||||
if (!touchedRef.current) fit()
|
||||
}, [fit, rootId])
|
||||
touchedRef.current = false
|
||||
fitRef.current()
|
||||
}, [rootId])
|
||||
|
||||
// Auto-fit on layout growth — but never over a view the reader has taken over
|
||||
// (a pan, a zoom, or a fold: see markTouched). The container's own resize
|
||||
// path below fits under the same rule.
|
||||
useEffect(() => {
|
||||
if (!touchedRef.current) fitRef.current()
|
||||
}, [layout.width, layout.height])
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current
|
||||
@@ -379,6 +400,32 @@ export function TasksGraph(props: TasksGraphProps): ReactNode {
|
||||
/** Suppress node clicks that ended a drag gesture. */
|
||||
const clickAllowed = useCallback((): boolean => travelRef.current <= CLICK_TOLERANCE_PX, [])
|
||||
|
||||
/**
|
||||
* The reader driving the FOLD state takes the view over, exactly like a pan
|
||||
* or a zoom does: from then on the canvas stops re-framing itself when the
|
||||
* layout changes, so folding a group never yanks the tree out from under the
|
||||
* cards the reader is watching. The ⌂ button hands the view back.
|
||||
*/
|
||||
const markTouched = useCallback((): void => { touchedRef.current = true }, [])
|
||||
|
||||
/** The aggregate's click: reveal its group, with the view under the reader. */
|
||||
const expandGroupTouched = useCallback((node: TasksFoldNode): void => {
|
||||
markTouched()
|
||||
onExpandGroup(node)
|
||||
}, [markTouched, onExpandGroup])
|
||||
|
||||
/** The card's own chevron: fold that node, with the view under the reader. */
|
||||
const foldNodeTouched = useCallback((node: TasksAgentNode): void => {
|
||||
markTouched()
|
||||
onFoldNode?.(node)
|
||||
}, [markTouched, onFoldNode])
|
||||
|
||||
/** The cluster's page-level switch: the same claim on the view. */
|
||||
const toggleFoldTouched = useCallback((): void => {
|
||||
markTouched()
|
||||
onToggleFold()
|
||||
}, [markTouched, onToggleFold])
|
||||
|
||||
// Phase frames: group each run's members by phase and box them.
|
||||
const phaseFrames = useMemo((): PhaseFrame[] => {
|
||||
const frames: PhaseFrame[] = []
|
||||
@@ -389,7 +436,7 @@ export function TasksGraph(props: TasksGraphProps): ReactNode {
|
||||
const boxes: GraphBox[] = []
|
||||
for (const member of phase.members) {
|
||||
const id = member.childId !== '' ? member.childId : `wfmember:${runNode.run.runId}:${member.seq}`
|
||||
const box = layout.boxes.get(id)
|
||||
const box = drawn.boxes.get(id)
|
||||
if (box !== undefined) boxes.push(box)
|
||||
}
|
||||
if (boxes.length === 0) return
|
||||
@@ -409,7 +456,7 @@ export function TasksGraph(props: TasksGraphProps): ReactNode {
|
||||
})
|
||||
}
|
||||
return frames
|
||||
}, [nodes, layout])
|
||||
}, [nodes, drawn])
|
||||
|
||||
/**
|
||||
* The connector between two boxes: a straight PERPENDICULAR stub out of the
|
||||
@@ -461,8 +508,8 @@ export function TasksGraph(props: TasksGraphProps): ReactNode {
|
||||
>
|
||||
<svg className={css.edges} width={layout.width} height={layout.height} aria-hidden="true">
|
||||
{edges.map((edge) => {
|
||||
const from = layout.boxes.get(edge.from)
|
||||
const to = layout.boxes.get(edge.to)
|
||||
const from = drawn.boxes.get(edge.from)
|
||||
const to = drawn.boxes.get(edge.to)
|
||||
if (from === undefined || to === undefined) return null
|
||||
const target = nodeById.get(edge.to)
|
||||
return (
|
||||
@@ -497,20 +544,33 @@ export function TasksGraph(props: TasksGraphProps): ReactNode {
|
||||
activatable), and tree mode provides the full Arrow/Home/End/Enter
|
||||
navigation over the same nodes (see TasksTree). Do NOT "fix" the
|
||||
nodes' tabIndex without fixing the tab-stop flood. */}
|
||||
{nodes.map((node) => {
|
||||
const box = layout.boxes.get(node.id)
|
||||
{nodes.map((node, index) => {
|
||||
const box = drawn.boxes.get(node.id)
|
||||
if (box === undefined) return null
|
||||
const style = { left: box.x, top: box.y, width: GRAPH_NODE_W, minHeight: box.h }
|
||||
if (node.kind === 'fold') return renderFoldNode(node, style, onExpandGroup, clickAllowed)
|
||||
const style = {
|
||||
left: box.x,
|
||||
top: box.y,
|
||||
width: GRAPH_NODE_W,
|
||||
minHeight: box.h,
|
||||
/*
|
||||
* The entrance is STAGGERED by the node's page order: a group that
|
||||
* reveals several cards at once (or a page that loads a tree)
|
||||
* cascades instead of popping in one frame. Capped, so a big tree
|
||||
* settles quickly, and inert for cards that were already mounted
|
||||
* (their entrance ran when they arrived).
|
||||
*/
|
||||
animationDelay: `${Math.min(index, 9) * 26}ms`,
|
||||
}
|
||||
if (node.kind === 'fold') return renderFoldNode(node, style, expandGroupTouched, clickAllowed)
|
||||
if (node.kind === 'workflow') {
|
||||
return renderWorkflowNode(node, style, onWorkflowInfo, clickAllowed)
|
||||
}
|
||||
return renderAgentNode(node, style, onNodeInfo, onOpenTask, clickAllowed, onFoldNode)
|
||||
return renderAgentNode(node, style, onNodeInfo, onOpenTask, clickAllowed, foldNodeTouched)
|
||||
})}
|
||||
</div>
|
||||
<div className={css.controls} data-graph-controls>
|
||||
<ViewModeToggle mode={mode} onModeChange={onModeChange} />
|
||||
<FoldToggleButton folded={folded} onToggleFold={onToggleFold} />
|
||||
<FoldToggleButton folded={folded} onToggleFold={toggleFoldTouched} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
|
||||
@@ -142,11 +142,15 @@
|
||||
activity. The layout in tasks-graph-layout.ts reserves those rows, so the
|
||||
box handed to a card is exactly its height. */
|
||||
.node {
|
||||
/* Cards ARRIVE with a short entrance and leave instantly: the leaving side
|
||||
is what a FLIP library would animate, and it is exactly what a scaled
|
||||
canvas layer cannot express (see TasksGraph). Mount-only, so the page's
|
||||
poll never re-plays it, and the edges they hang from stay honest. */
|
||||
animation: dsh-card-in 150ms cubic-bezier(0.2, 0.8, 0.3, 1);
|
||||
/* Cards ARRIVE with a real entrance — a rise, a scale-up and a fade, with a
|
||||
slight overshoot so the arrival reads as motion rather than a repaint. The
|
||||
per-card `animation-delay` the graph sets inline staggers a group that
|
||||
reveals several cards at once; `backwards` keeps a staggered card invisible
|
||||
during its wait instead of popping and then animating. Mount-only, so the
|
||||
page's poll never re-plays it. Position changes are NOT animated here: the
|
||||
graph tweens the layout coordinates instead (tasks-layout-tween.ts), which
|
||||
is the only space the fit's scale cannot distort. */
|
||||
animation: dsh-card-in 300ms cubic-bezier(0.2, 0.9, 0.25, 1.06) backwards;
|
||||
position: absolute;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
@@ -819,8 +823,9 @@
|
||||
}
|
||||
|
||||
@keyframes dsh-card-in {
|
||||
from { opacity: 0; transform: translateY(2px); }
|
||||
to { opacity: 1; transform: none; }
|
||||
0% { opacity: 0; transform: translateY(10px) scale(0.88); }
|
||||
60% { opacity: 1; }
|
||||
100% { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
@keyframes dsh-pop-in {
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* The Tasks graph's layout TWEEN: the canvas animates in ITS OWN coordinate
|
||||
* space (each card's `x` / `y` / height), not with screen-space transforms.
|
||||
*
|
||||
* Why not a FLIP library: the card layer carries the fit's
|
||||
* `transform: scale(k)`, so a library that measures `getBoundingClientRect()`
|
||||
* and replays `translate()` in unscaled units is off by k on every move — and
|
||||
* `@formkit/auto-animate` additionally pins a leaving card with absolute
|
||||
* `left/top` derived from those rects, a box the scaled layer cannot express at
|
||||
* all (the card jumps). Measured live, both read as "折叠展开的动效都特别怪".
|
||||
*
|
||||
* Animating the layout coordinates has neither problem: `left`/`top` are the
|
||||
* canvas's own units, so the fit's scale applies to the tween exactly as it
|
||||
* applies to the final positions. And because every derived surface — the
|
||||
* connector paths, the phase frames — is a pure function of the boxes, they
|
||||
* follow the cards frame by frame instead of snapping to the new geometry while
|
||||
* the cards are still travelling.
|
||||
*
|
||||
* Scope: this animates POSITION only (x / y / height). A card that ENTERS gets
|
||||
* its CSS entrance (see tasks-graph.module.css) and a card that LEAVES is
|
||||
* removed at once — a ghost layer for exits is not worth its bookkeeping here,
|
||||
* and the aggregate that replaces the members is itself an entering card.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { GraphBox, GraphLayout } from './tasks-graph-layout.ts'
|
||||
|
||||
/** How long one layout change takes to settle (ms). */
|
||||
export const TWEEN_MS = 220
|
||||
|
||||
/** The tween's easing: fast out of the gate, gently into place (ease-out cubic). */
|
||||
export function easeOut(progress: number): number {
|
||||
const t = Math.min(1, Math.max(0, progress))
|
||||
return 1 - (1 - t) ** 3
|
||||
}
|
||||
|
||||
/** One box's geometry, the part a tween interpolates. */
|
||||
interface BoxGeometry {
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
}
|
||||
|
||||
/** Geometry of one box, or undefined when the tween has no previous slot for it. */
|
||||
function geometryOf(box: GraphBox | undefined): BoxGeometry | undefined {
|
||||
return box === undefined ? undefined : { x: box.x, y: box.y, w: box.w, h: box.h }
|
||||
}
|
||||
|
||||
/**
|
||||
* Interpolate one box between two geometries. A box with no `from` (it just
|
||||
* entered) stays at its target — the entrance animation owns that moment, and
|
||||
* sliding it in from a slot it never had would be a lie.
|
||||
*
|
||||
* @param from - the previously displayed geometry (undefined = just entered).
|
||||
* @param to - the target box.
|
||||
* @param progress - 0…1, already eased by the caller.
|
||||
*/
|
||||
export function tweenBox(from: BoxGeometry | undefined, to: GraphBox, progress: number): GraphBox {
|
||||
if (from === undefined) return to
|
||||
const mix = (a: number, b: number): number => a + (b - a) * progress
|
||||
return {
|
||||
id: to.id,
|
||||
x: mix(from.x, to.x),
|
||||
y: mix(from.y, to.y),
|
||||
w: mix(from.w, to.w),
|
||||
h: mix(from.h, to.h),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The layout as it should be DRAWN right now: the target for a first render and
|
||||
* for a reader who asked for less motion, a tweened copy after that.
|
||||
*
|
||||
* @param layout - the freshly computed layout (the tween's target).
|
||||
* @returns boxes to render, plus the target canvas extent (the canvas never
|
||||
* resizes mid-flight: the tween only moves the cards inside it).
|
||||
*/
|
||||
export function useTweenedLayout(layout: GraphLayout): GraphLayout {
|
||||
/** The geometry the current animation starts from (the last drawn state). */
|
||||
const fromRef = useRef<ReadonlyMap<string, GraphBox> | undefined>(undefined)
|
||||
const [drawnBoxes, setDrawnBoxes] = useState<ReadonlyMap<string, GraphBox>>(layout.boxes)
|
||||
|
||||
useEffect(() => {
|
||||
const from = fromRef.current
|
||||
// First paint, or a reader who opted out of motion: snap to the target.
|
||||
if (from === undefined || prefersReducedMotion()) {
|
||||
fromRef.current = layout.boxes
|
||||
setDrawnBoxes(layout.boxes)
|
||||
return
|
||||
}
|
||||
// Nothing moved (a poll that changed only labels/state): keep the boxes we
|
||||
// have, so React does not re-render every card for an identical Map.
|
||||
if (sameGeometry(from, layout.boxes)) {
|
||||
fromRef.current = layout.boxes
|
||||
return
|
||||
}
|
||||
let frame = 0
|
||||
const started = performance.now()
|
||||
const step = (): void => {
|
||||
const progress = easeOut((performance.now() - started) / TWEEN_MS)
|
||||
const next = interpolate(from, layout.boxes, progress)
|
||||
// The ref follows the DRAWN state, not the target: a layout change that
|
||||
// interrupts a running tween then resumes from where the cards actually
|
||||
// are instead of snapping them back to the previous target.
|
||||
fromRef.current = progress < 1 ? next : layout.boxes
|
||||
setDrawnBoxes(next)
|
||||
if (progress < 1) frame = requestAnimationFrame(step)
|
||||
}
|
||||
frame = requestAnimationFrame(step)
|
||||
return () => { cancelAnimationFrame(frame) }
|
||||
}, [layout])
|
||||
|
||||
useEffect(() => () => { fromRef.current = undefined }, [])
|
||||
|
||||
/**
|
||||
* What to draw. The tween's boxes are completed with the TARGET geometry for
|
||||
* any node they do not carry yet: a node that just entered has no previous
|
||||
* slot to travel from, and the render that introduces it must already have a
|
||||
* box for it (its CSS entrance is that moment — leaving it out for the one
|
||||
* render before the effect runs would blink the whole node away).
|
||||
*/
|
||||
const boxes = useMemo(() => {
|
||||
for (const id of layout.boxes.keys()) if (!drawnBoxes.has(id)) {
|
||||
const merged = new Map(drawnBoxes)
|
||||
for (const [targetId, box] of layout.boxes) if (!merged.has(targetId)) merged.set(targetId, box)
|
||||
return merged
|
||||
}
|
||||
return drawnBoxes
|
||||
}, [drawnBoxes, layout])
|
||||
|
||||
// The extent is always the target's: a canvas that resized while the cards
|
||||
// were still travelling would move the reader's frame under them.
|
||||
return useMemo(
|
||||
() => ({ boxes, width: layout.width, height: layout.height }),
|
||||
[boxes, layout.width, layout.height],
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether the reader asked the platform for less motion. */
|
||||
function prefersReducedMotion(): boolean {
|
||||
return typeof window !== 'undefined'
|
||||
&& typeof window.matchMedia === 'function'
|
||||
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
}
|
||||
|
||||
/** Whether two box maps already agree on every geometry. */
|
||||
function sameGeometry(
|
||||
a: ReadonlyMap<string, GraphBox>,
|
||||
b: ReadonlyMap<string, GraphBox>,
|
||||
): boolean {
|
||||
if (a.size !== b.size) return false
|
||||
for (const [id, box] of b) {
|
||||
const previous = a.get(id)
|
||||
if (previous === undefined) return false
|
||||
if (previous.x !== box.x || previous.y !== box.y || previous.w !== box.w || previous.h !== box.h) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** One tweened copy of `to`, using `from` for the boxes that were on screen. */
|
||||
function interpolate(
|
||||
from: ReadonlyMap<string, GraphBox>,
|
||||
to: ReadonlyMap<string, GraphBox>,
|
||||
progress: number,
|
||||
): ReadonlyMap<string, GraphBox> {
|
||||
const out = new Map<string, GraphBox>()
|
||||
for (const [id, box] of to) {
|
||||
out.set(id, tweenBox(geometryOf(from.get(id)), box, progress))
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Unit tests for the canvas layout tween: the geometry interpolation, the
|
||||
* easing, and the hook that hides every screen-space FLIP problem by animating
|
||||
* in the canvas's OWN coordinates.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement, useState, type ReactNode } from 'react'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { renderRoot } from './test-utils.ts'
|
||||
import { TWEEN_MS, easeOut, tweenBox, useTweenedLayout } from '../src/client/tasks-layout-tween.ts'
|
||||
import type { GraphBox, GraphLayout } from '../src/client/tasks-graph-layout.ts'
|
||||
|
||||
/** One box. */
|
||||
function box(id: string, x: number, y: number, h = 87): GraphBox {
|
||||
return { id, x, y, w: 190, h }
|
||||
}
|
||||
|
||||
/** One layout. */
|
||||
function layout(boxes: GraphBox[]): GraphLayout {
|
||||
return { boxes: new Map(boxes.map(entry => [entry.id, entry])), width: 400, height: 300 }
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
for (const el of document.querySelectorAll('body > div')) el.remove()
|
||||
})
|
||||
|
||||
describe('tweenBox', () => {
|
||||
it('interpolates every geometry channel', () => {
|
||||
const from = box('a', 0, 0, 80)
|
||||
const to = box('a', 100, 40, 120)
|
||||
expect(tweenBox(from, to, 0)).toMatchObject({ x: 0, y: 0, h: 80 })
|
||||
expect(tweenBox(from, to, 1)).toMatchObject({ x: 100, y: 40, h: 120 })
|
||||
expect(tweenBox(from, to, 0.5)).toMatchObject({ x: 50, y: 20, h: 100 })
|
||||
})
|
||||
|
||||
it('leaves an ENTERING box at its target (the entrance animation owns that moment)', () => {
|
||||
const to = box('fresh', 42, 7)
|
||||
expect(tweenBox(undefined, to, 0.3)).toBe(to)
|
||||
})
|
||||
})
|
||||
|
||||
describe('easeOut', () => {
|
||||
it('runs fast out of the gate and settles exactly at the ends', () => {
|
||||
expect(easeOut(0)).toBe(0)
|
||||
expect(easeOut(1)).toBe(1)
|
||||
// Ease-out: past the halfway position halfway through the time.
|
||||
expect(easeOut(0.5)).toBeGreaterThan(0.5)
|
||||
expect(easeOut(0.9)).toBeGreaterThan(easeOut(0.8))
|
||||
// Out-of-range progress is clamped (a late frame cannot overshoot).
|
||||
expect(easeOut(1.4)).toBe(1)
|
||||
expect(easeOut(-1)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
/** Renders the tweened layout and lets a test swap the target layout. */
|
||||
function Harness(props: { initial: GraphLayout; onDrawn?: (layout: GraphLayout) => void }): ReactNode {
|
||||
const [target, setTarget] = useState(props.initial)
|
||||
const drawn = useTweenedLayout(target)
|
||||
props.onDrawn?.(drawn)
|
||||
swap = setTarget
|
||||
return createElement('span', null, `${drawn.boxes.size}`)
|
||||
}
|
||||
|
||||
/** The harness's setter, captured by the render above (one instance per test). */
|
||||
let swap: (next: GraphLayout) => void = () => {}
|
||||
|
||||
describe('useTweenedLayout', () => {
|
||||
it('shows the target on the first paint, then travels to the next layout', async () => {
|
||||
vi.useFakeTimers()
|
||||
let drawn: GraphLayout = layout([])
|
||||
const { unmount } = renderRoot(
|
||||
createElement(Harness, {
|
||||
initial: layout([box('a', 0, 0)]),
|
||||
onDrawn: (value) => { drawn = value },
|
||||
}),
|
||||
)
|
||||
// First paint: no animation, the cards are where the layout put them.
|
||||
expect(drawn.boxes.get('a')?.x).toBe(0)
|
||||
|
||||
await act(async () => { swap(layout([box('a', 100, 0)])) })
|
||||
// One frame in, the card is on its way — not teleported, not waiting.
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(16) })
|
||||
const midway = drawn.boxes.get('a')?.x ?? 0
|
||||
expect(midway).toBeGreaterThan(0)
|
||||
expect(midway).toBeLessThan(100)
|
||||
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(TWEEN_MS) })
|
||||
expect(drawn.boxes.get('a')?.x).toBe(100)
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('keeps the canvas extent at the target while the cards travel', async () => {
|
||||
vi.useFakeTimers()
|
||||
let drawn: GraphLayout = layout([])
|
||||
const { unmount } = renderRoot(
|
||||
createElement(Harness, {
|
||||
initial: layout([box('a', 0, 0)]),
|
||||
onDrawn: (value) => { drawn = value },
|
||||
}),
|
||||
)
|
||||
const next = layout([box('a', 0, 0)])
|
||||
next.width = 900
|
||||
next.height = 700
|
||||
await act(async () => { swap(next) })
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(16) })
|
||||
// The frame must not resize mid-flight (that would move the reader's view
|
||||
// under a tween that is still running).
|
||||
expect(drawn.width).toBe(900)
|
||||
expect(drawn.height).toBe(700)
|
||||
expect(drawn.boxes.get('a')?.x).toBe(0)
|
||||
unmount()
|
||||
})
|
||||
})
|
||||
@@ -22,9 +22,21 @@ function source(relative: string): string {
|
||||
return readFileSync(resolve(ROOT, relative), 'utf8')
|
||||
}
|
||||
|
||||
/**
|
||||
* A source file with its comments removed. The NEGATIVE assertions below are
|
||||
* about what the code does, and these files deliberately DOCUMENT the library
|
||||
* they avoid ("measures `getBoundingClientRect()`…"), so matching raw text
|
||||
* would fail on the very explanation we want to keep.
|
||||
*/
|
||||
function code(relative: string): string {
|
||||
return source(relative)
|
||||
.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
.replace(/^\s*\/\/.*$/gm, '')
|
||||
}
|
||||
|
||||
describe('Tasks page motion', () => {
|
||||
it('keeps the FLIP library off the scaled canvas, and on the flow surfaces', () => {
|
||||
expect(source('src/client/TasksGraph.tsx')).not.toContain('use-auto-animate')
|
||||
expect(code('src/client/TasksGraph.tsx')).not.toContain('use-auto-animate')
|
||||
expect(source('src/client/TasksTree.tsx')).toContain('useAutoAnimateRef')
|
||||
expect(source('src/client/JobsDrawer.tsx')).toContain('useAutoAnimateRef')
|
||||
})
|
||||
@@ -45,6 +57,30 @@ describe('Tasks page motion', () => {
|
||||
expect(reduced).toContain('.node')
|
||||
})
|
||||
|
||||
it('animates the canvas in LAYOUT coordinates, never with screen-space transforms', () => {
|
||||
// The canvas's own tween: `left`/`top` are canvas units, so the fit's scale
|
||||
// applies to the tween exactly as it applies to the final positions — and
|
||||
// the connectors (pure functions of the boxes) travel with the cards.
|
||||
expect(source('src/client/TasksGraph.tsx')).toContain('useTweenedLayout')
|
||||
const tween = code('src/client/tasks-layout-tween.ts')
|
||||
expect(tween).toContain('requestAnimationFrame')
|
||||
// No rect measuring in the CODE: that is exactly what makes a scaled layer
|
||||
// unrepresentable for a FLIP library.
|
||||
expect(tween).not.toContain('getBoundingClientRect')
|
||||
// The card entrance is staggered, so a revealed group cascades.
|
||||
expect(source('src/client/TasksGraph.tsx')).toContain('animationDelay')
|
||||
})
|
||||
|
||||
it('stops the auto-fit once the reader drives the fold state', () => {
|
||||
const graph = source('src/client/TasksGraph.tsx')
|
||||
// Pan/zoom already claim the view; folding claims it too, so the canvas
|
||||
// never re-frames itself under the cards the reader is watching.
|
||||
expect(graph).toContain('markTouched')
|
||||
expect(graph).toContain('expandGroupTouched')
|
||||
expect(graph).toContain('foldNodeTouched')
|
||||
expect(graph).toContain('toggleFoldTouched')
|
||||
})
|
||||
|
||||
it('parks the motion host behind a WAAPI guard so tests and old hosts stay inert', () => {
|
||||
const hook = source('src/client/use-auto-animate.ts')
|
||||
expect(hook).toContain("typeof Element.prototype.animate === 'function'")
|
||||
|
||||
Reference in new issue
Block a user