refactor: 翻页方向改 sessionStorage+data-vt 纯 CSS,蓄力层收敛气泡+进度条 (#44)
Build Tutorial / Build @stack/tutorial (kaniko) (push) Successful in 5m10s

## 背景

翻页方案(#41)的方向登记依赖模块脚本 `page-flip.ts` 在 pageswap/pagereveal 里做 URL 章号比较,再写 `viewTransition.types` 让 CSS 的 `:active-view-transition-type()` 选关键帧。两个问题:模块脚本晚于首帧,方向读取时机不可靠;页面标题(英雄区 `ch-N` morph+蓄力探头卡)参与了过渡,动画层级复杂。参考 `idealjs/packages/home/page-one.html` 的极简做法重构:方向定义纯 CSS、传递靠 head 内联脚本+sessionStorage,进场动画完全交给浏览器。

## 变更内容

- **方向握手**:ch1–ch7.html head 增加内联经典脚本(解析阻塞、早于首帧)——读 `sessionStorage['vt']` 写 `<html data-vt>`、读后即清(consume-once)、全局 click 监听 `a[data-dir]` 写方向;`scrollRestoration='manual'` 一并移交到这里
- **方向选帧**:tokens.css 的 `:active-view-transition-type()` 全部换成 `html[data-vt="next|prev"]::view-transition-*`;`--page-flip-spring`、三个 keyframes、520ms 时长不变
- **删除 types 机制**:`page-flip.ts` 与 7 个 `main.tsx` 的 `setupPageFlip()` 移除;翻页意图统一落方向——手势/键盘/气泡点击在 `PageFlipZone` 的 `flip()` 里写 sessionStorage,页底 prev/next 链接加 `data-dir`
- **蓄力符号层收敛**:只留「气泡(章色胶囊按钮,随蓄力升起 24px)+进度条」,删 FlipPeekCard 章标题探头卡;**蓄力不再位移页面**——`[data-flip-surface]` 整页 translateY 弹簧移除,蓄力全程页面静止;英雄区 `ch-N` morph 与 `--vt-hero-name` 抑制机制一并移除(标题随整页滑动),`site-header` morph 保留
- **内联 VT opt-in**:Chrome 只采信初始 HTML 内联 `<style>@view-transition { navigation: auto; }</style>` 的跨文档 opt-in,外链 CSS 里的不算——过渡全程被 abort(`InvalidStateError: ViewTransition opt-in disabled`),动画从未真正播放。24 个入口 HTML head 各加一行内联 opt-in(与 home 做法一致),报错清零、`page-flip-rise-in/recede` 确认真实运行
- **ssg 独立插件(dev/build 均预渲染)**:跨文档 VT 的新页画面取自「过渡激活时刻」的渲染状态,客户端挂载(~110ms)落后激活(~55ms)导致定格空壳——「背景滑上来、内容事后出现」。把 `renderPages` 从 tutorialBuild 抽成独立 WatchHook `ssg()`(监听 `tutorial-build` 产出、登记 `ssg` 产出),dev 与 build 无条件预渲染填充 `#root`;常驻工作区 `node_modules/.stack-ssg`(不再 mkdtemp+rm,根治 dev watcher ENOENT 崩溃)+源码子树 mtime 指纹缓存(watch 重建只重渲染变更页,实测改一页 1/24、重建 1s);`STACK_SSG=1` 门控移除;引擎新增产出级联场景测试
- **读后即清的红利**:浏览器返回、抽屉跳章、刷新等非翻页导航读不到方向,走浏览器默认 crossfade,无残留状态
- e2e:peek 断言改气泡;新增方向握手断言(翻到 ch2 后 `data-vt=next` 且 storage 已清,翻回后 `data-vt=prev`);`docs/page-flip-research.md` 补重构记录

## 自测结果

- `tsc --noEmit` / biome `format:check` / `strip-comments` 全过
- e2e:**page-flip 10/10 通过**(含新增 data-vt 与 consume-once 断言);playground-config / playground-embed 的 15 例失败为存量问题(stash 本次改动后在纯 main 上复跑同样失败)
- 真 Chromium 探针:修复后整链(ch1→ch2→ch3→后退×2)VT abort 错误 0 次;过渡期间 `document.getAnimations` 捕获到 `page-flip-rise-in:520ms`+`page-flip-recede:520ms` 真实运行
- SSG 后:构建 24/24 页预渲染(总 3.7s);dev 伺服填充页面;watch 改一页只重渲染 1/24;过渡中间帧带完整内容(见下方第三图);e2e 复跑 15/15(page-flip 10+视觉基线 5,hydrate 无回归);引擎场景测试 24/24(含新增产出级联)
- e2e 复跑 15/15(page-flip 10+视觉基线 5)
- 蓄力态 before/after 截图:见下方附件

![before-重构前蓄力态:探头卡+标题](https://gitea.idealjs.com/attachments/95f8f443-69cd-40fb-bb72-852ce37ba999)

![after-重构后蓄力态:仅气泡+进度条,页面静止](https://gitea.idealjs.com/attachments/e19e15aa-9c86-4430-bc4c-ce5be5fc3456)

![SSG 后过渡中间帧:新页带完整内容滑入](https://gitea.idealjs.com/attachments/2a638fa6-a7f3-47df-af2d-effd793a8138)

---------

Co-authored-by: cqh963852 <cqh963852@hotmail.com>
Reviewed-on: #44
Co-authored-by: arnold.cui agent (bot) <arnold.cui-agent@idealjs.com>
This commit was merged in pull request #44.
This commit is contained in:
arnold.cui-agentandcqh963852 authored and arnold.cui committed 2026-11-14 03:42:53 +00:00
1 parent 30389ee2cb
commit f33d0730be
44 files changed
+362 -264

No files matched your search

+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>博客 · 2025-07</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>博客 · 2026-08</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>gorzil:面向多人协作的 AI 原生工具开发自述</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>sapling_transformer 近半月开发自述</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>博客 · idealjs stack 教程</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+11
View File
@@ -4,6 +4,17 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>第 1 章 · 快速开始</title>
<style>@view-transition { navigation: auto; }</style>
<script>
if ("scrollRestoration" in history) history.scrollRestoration = "manual"
var vt = sessionStorage.getItem("vt")
if (vt) document.documentElement.dataset.vt = vt
sessionStorage.removeItem("vt")
document.addEventListener("click", function (e) {
var a = e.target.closest("a[data-dir]")
if (a) sessionStorage.setItem("vt", a.dataset.dir)
})
</script>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+11
View File
@@ -4,6 +4,17 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>第 2 章 · React</title>
<style>@view-transition { navigation: auto; }</style>
<script>
if ("scrollRestoration" in history) history.scrollRestoration = "manual"
var vt = sessionStorage.getItem("vt")
if (vt) document.documentElement.dataset.vt = vt
sessionStorage.removeItem("vt")
document.addEventListener("click", function (e) {
var a = e.target.closest("a[data-dir]")
if (a) sessionStorage.setItem("vt", a.dataset.dir)
})
</script>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+11
View File
@@ -4,6 +4,17 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>第 3 章 · 更多示例</title>
<style>@view-transition { navigation: auto; }</style>
<script>
if ("scrollRestoration" in history) history.scrollRestoration = "manual"
var vt = sessionStorage.getItem("vt")
if (vt) document.documentElement.dataset.vt = vt
sessionStorage.removeItem("vt")
document.addEventListener("click", function (e) {
var a = e.target.closest("a[data-dir]")
if (a) sessionStorage.setItem("vt", a.dataset.dir)
})
</script>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+11
View File
@@ -4,6 +4,17 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>第 4 章 · 更多 · 构建</title>
<style>@view-transition { navigation: auto; }</style>
<script>
if ("scrollRestoration" in history) history.scrollRestoration = "manual"
var vt = sessionStorage.getItem("vt")
if (vt) document.documentElement.dataset.vt = vt
sessionStorage.removeItem("vt")
document.addEventListener("click", function (e) {
var a = e.target.closest("a[data-dir]")
if (a) sessionStorage.setItem("vt", a.dataset.dir)
})
</script>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+11
View File
@@ -4,6 +4,17 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>第 5 章 · 全栈基础</title>
<style>@view-transition { navigation: auto; }</style>
<script>
if ("scrollRestoration" in history) history.scrollRestoration = "manual"
var vt = sessionStorage.getItem("vt")
if (vt) document.documentElement.dataset.vt = vt
sessionStorage.removeItem("vt")
document.addEventListener("click", function (e) {
var a = e.target.closest("a[data-dir]")
if (a) sessionStorage.setItem("vt", a.dataset.dir)
})
</script>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+11
View File
@@ -4,6 +4,17 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>第 6 章 · 高级教程</title>
<style>@view-transition { navigation: auto; }</style>
<script>
if ("scrollRestoration" in history) history.scrollRestoration = "manual"
var vt = sessionStorage.getItem("vt")
if (vt) document.documentElement.dataset.vt = vt
sessionStorage.removeItem("vt")
document.addEventListener("click", function (e) {
var a = e.target.closest("a[data-dir]")
if (a) sessionStorage.setItem("vt", a.dataset.dir)
})
</script>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+11
View File
@@ -4,6 +4,17 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>第 7 章 · MPA 入口</title>
<style>@view-transition { navigation: auto; }</style>
<script>
if ("scrollRestoration" in history) history.scrollRestoration = "manual"
var vt = sessionStorage.getItem("vt")
if (vt) document.documentElement.dataset.vt = vt
sessionStorage.removeItem("vt")
document.addEventListener("click", function (e) {
var a = e.target.closest("a[data-dir]")
if (a) sessionStorage.setItem("vt", a.dataset.dir)
})
</script>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSS · 技能熟悉 · idealjs stack</title>
<style>@view-transition { navigation: auto; }</style>
<meta name="description" content="技能熟悉 · CSS:用选择器与布局控制页面样式。专项教程逐步补充中。" />
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>设计系统 · 颜色 · 鲜艳与碰撞</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>设计系统 · 组件 · 入口载体与学习工作台</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>设计系统 · 阴影 · 硬投影与拿起</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>设计系统 · 符号、形状 · 装饰即语义</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>设计系统 · 字体 · 一套字阶,两种强调</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>设计系统 · idealjs stack 教程</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+14 -16
View File
@@ -11,11 +11,6 @@ const chargeByWheel = async (page: Page, deltaY: number, steps = 20) => {
const isAtBottom = () =>
window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 1
const surfaceSettled = () => {
const surface = document.querySelector('[data-flip-surface]')
return surface instanceof HTMLElement && surface.style.transform === ''
}
const edgeProgress = (side: 'next' | 'prev') => {
const edge = document.querySelector(`[data-flip-edge="${side}"]`)
return edge instanceof HTMLElement ? Number(edge.style.getPropertyValue('--flip-progress')) : -1
@@ -30,19 +25,21 @@ const edgeSettled = (side: 'next' | 'prev') => {
test('charge past threshold at bottom flips to next chapter', async ({ page }) => {
await page.goto('./ch1.html')
await expect(page.locator('[data-flip-surface]')).toHaveCount(1)
await expect(page.locator('[data-flip-edge="next"]')).toHaveCount(1)
await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight))
await page.waitForTimeout(200)
await page.mouse.move(640, 450)
await chargeByWheel(page, 250)
await page.waitForURL('**/ch2.html')
await expect(page.locator('html')).toHaveAttribute('data-vt', 'next')
expect(await page.evaluate(() => sessionStorage.getItem('vt'))).toBeNull()
})
test('arrival momentum never flips; charge holds after wheel stops; reverse wheel clears it', async ({
page,
}) => {
await page.goto('./ch1.html')
await expect(page.locator('[data-flip-surface]')).toHaveCount(1)
await expect(page.locator('[data-flip-edge="next"]')).toHaveCount(1)
await page.mouse.move(640, 450)
await page.mouse.wheel(0, 6000)
await page.waitForFunction(isAtBottom)
@@ -67,15 +64,16 @@ test('arrival momentum never flips; charge holds after wheel stops; reverse whee
test('charge upward at top flips to previous chapter', async ({ page }) => {
await page.goto('./ch2.html')
await expect(page.locator('[data-flip-surface]')).toHaveCount(1)
await expect(page.locator('[data-flip-edge="next"]')).toHaveCount(1)
await page.mouse.move(640, 450)
await chargeByWheel(page, -250)
await page.waitForURL('**/ch1.html')
await expect(page.locator('html')).toHaveAttribute('data-vt', 'prev')
})
test('mid-page wheel keeps scrolling without flipping', async ({ page }) => {
await page.goto('./ch3.html')
await expect(page.locator('[data-flip-surface]')).toHaveCount(1)
await expect(page.locator('[data-flip-edge="next"]')).toHaveCount(1)
await page.mouse.move(640, 450)
await page.mouse.wheel(0, 1500)
await page.waitForTimeout(600)
@@ -84,7 +82,7 @@ test('mid-page wheel keeps scrolling without flipping', async ({ page }) => {
test('PageDown at bottom flips to next chapter', async ({ page }) => {
await page.goto('./ch1.html')
await expect(page.locator('[data-flip-surface]')).toHaveCount(1)
await expect(page.locator('[data-flip-edge="next"]')).toHaveCount(1)
await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight))
await page.keyboard.press('PageDown')
await page.waitForURL('**/ch2.html')
@@ -92,7 +90,7 @@ test('PageDown at bottom flips to next chapter', async ({ page }) => {
test('clicking the next-chapter badge jumps directly to the next chapter', async ({ page }) => {
await page.goto('./ch1.html')
await expect(page.locator('[data-flip-surface]')).toHaveCount(1)
await expect(page.locator('[data-flip-edge="next"]')).toHaveCount(1)
await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight))
await page.waitForTimeout(200)
await page.mouse.move(640, 450)
@@ -113,7 +111,7 @@ test('reload returns to chapter top', async ({ page }) => {
test('after flip the next chapter lands at top and first wheel scrolls', async ({ page }) => {
await page.goto('./ch1.html')
await expect(page.locator('[data-flip-surface]')).toHaveCount(1)
await expect(page.locator('[data-flip-edge="next"]')).toHaveCount(1)
await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight))
await page.waitForTimeout(200)
await page.mouse.move(640, 450)
@@ -136,7 +134,7 @@ test('weak bottom charge holds next edge symbols on screen, reverse wheel spring
page,
}) => {
await page.goto('./ch1.html')
await expect(page.locator('[data-flip-surface]')).toHaveCount(1)
await expect(page.locator('[data-flip-edge="next"]')).toHaveCount(1)
await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight))
await page.waitForTimeout(300)
expect(await page.evaluate(edgeProgress, 'next')).toBe(0)
@@ -144,7 +142,7 @@ test('weak bottom charge holds next edge symbols on screen, reverse wheel spring
await page.mouse.move(640, 450)
await page.mouse.wheel(0, 200)
await page.waitForFunction(edgeProgress, 'next')
await expect(page.locator('[data-flip-edge="next"] [data-flip-peek]')).toBeVisible()
await expect(page.locator('[data-flip-edge="next"] button')).toBeVisible()
await page.waitForTimeout(400)
expect(await page.evaluate(edgeProgress, 'next')).toBeGreaterThan(0)
@@ -159,11 +157,11 @@ test('weak top charge holds prev edge symbols on screen, reverse wheel springs t
page,
}) => {
await page.goto('./ch2.html')
await expect(page.locator('[data-flip-surface]')).toHaveCount(1)
await expect(page.locator('[data-flip-edge="next"]')).toHaveCount(1)
await page.mouse.move(640, 450)
await page.mouse.wheel(0, -200)
await page.waitForFunction(edgeProgress, 'prev')
await expect(page.locator('[data-flip-edge="prev"] [data-flip-peek]')).toBeVisible()
await expect(page.locator('[data-flip-edge="prev"] button')).toBeVisible()
await page.waitForTimeout(400)
expect(await page.evaluate(edgeProgress, 'prev')).toBeGreaterThan(0)
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML · 技能熟悉 · idealjs stack</title>
<style>@view-transition { navigation: auto; }</style>
<meta name="description" content="技能熟悉 · HTML:用标记描述网页结构。专项教程逐步补充中。" />
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>idealjs stack · 全栈教程与开发实践</title>
<style>@view-transition { navigation: auto; }</style>
<meta
name="description"
content="从第一个网页,到完整的应用。idealjs stack 提供全栈工程师教程,分享开发经验与工程实践,并提供跑在浏览器里的在线 Agent 练习场。"
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript · 技能熟悉 · idealjs stack</title>
<style>@view-transition { navigation: auto; }</style>
<meta name="description" content="技能熟悉 · JavaScript:让页面响应操作、管理数据。专项教程逐步补充中。" />
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>全栈教程 · 做一个自己的待办清单 · idealjs stack</title>
<style>@view-transition { navigation: auto; }</style>
<meta name="description" content="从页面、交互到 API 和数据库,逐步完成一个单人版 TodoList。了解技术积木、浏览器内运行时与 Agent 练习环境、预计学习时间,以及贯穿全栈的数据控制。" />
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
+1 -1
View File
@@ -4,7 +4,7 @@
"version": "0.1.0",
"type": "module",
"scripts": {
"build": "STACK_SSG=1 stack",
"build": "stack",
"dev": "stack dev",
"dev:proxy": "VITE_STACK_RUNTIME_ORIGIN=https://code.idealjs.com/absproxy/8911 stack dev --base /absproxy/9911 --port 9911",
"preview": "stack preview",
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>在线练习 · idealjs stack 教程</title>
<style>@view-transition { navigation: auto; }</style>
<link rel="stylesheet" href="./src/design-system/styles/tokens.css" />
<link rel="stylesheet" href="./src/design-system/styles/learning.css" />
</head>
+3 -7
View File
@@ -20,13 +20,7 @@ export function ChapterPage({ id, children }: { id: ChapterId; children?: ReactN
>
<div
className="relative flex items-center gap-4 overflow-hidden rounded-2xl border-2 border-ink p-5 shadow-ink"
data-chapter-hero
style={
{
background: ch.color,
viewTransitionName: `var(--vt-hero-name, ch-${id})`,
} as CSSProperties
}
style={{ background: ch.color } as CSSProperties}
>
<span
className="t-display pointer-events-none absolute right-4 top-1/2 -translate-y-1/2 select-none"
@@ -123,6 +117,7 @@ export function ChapterPage({ id, children }: { id: ChapterId; children?: ReactN
{prev ? (
<a
href={`./ch${prev}.html`}
data-dir="prev"
className="rounded-xl border-2 border-ink bg-paper px-4 py-2 text-[12.5px] font-bold text-ink no-underline shadow-ink"
>
← 第 {prev} 章 · {CHAPTERS[prev].title}
@@ -139,6 +134,7 @@ export function ChapterPage({ id, children }: { id: ChapterId; children?: ReactN
{next ? (
<a
href={`./ch${next}.html`}
data-dir="next"
className="rounded-xl border-2 border-ink bg-paper px-4 py-2 text-[12.5px] font-bold text-ink no-underline shadow-ink"
>
第 {next} 章 · {CHAPTERS[next].title} →
@@ -1,32 +0,0 @@
import type { CSSProperties } from 'react'
import type { Chapter } from '../lib/types'
export interface FlipPeekCardProps {
chapter: Chapter
side: 'prev' | 'next'
}
export function FlipPeekCard({ chapter, side }: FlipPeekCardProps) {
const label = side === 'next' ? '下一章预览' : '上一章预览'
return (
<div
data-flip-peek
className="relative flex items-center gap-4 overflow-hidden rounded-2xl border-2 border-ink p-5 shadow-ink"
style={{ background: chapter.color } as CSSProperties}
>
<span
className="t-display pointer-events-none absolute right-4 top-1/2 -translate-y-1/2 select-none"
aria-hidden
>
0{chapter.id}
</span>
<span className="text-[44px] leading-none">{chapter.emoji}</span>
<div className="flex-1">
<div className="t-small-strong text-ink/70">{label}</div>
<div className="mt-0.5 text-t1 font-extrabold text-ink">
第 {chapter.id} 章 · {chapter.title}
</div>
</div>
</div>
)
}
@@ -1,16 +1,14 @@
import type { CSSProperties, ReactNode, RefObject } from 'react'
import { useEffect, useRef } from 'react'
import type { Chapter } from '../lib/types'
import { FlipPeekCard } from './FlipPeekCard'
const CHARGE_DAMPING = 0.12
const CHARGE_RATE_CAP = 220
const FLIP_THRESHOLD = 110
const FLIP_THRESHOLD = 55
const QUIET_MS = 250
const GESTURE_GAP_MS = 100
const SPRING_STIFFNESS = 170
const SPRING_DAMPING = 18
const PEEK_TRAVEL_PERCENT = 170
export interface FlipTarget {
href: string
@@ -29,22 +27,20 @@ const edgeStyle = {
'--flip-pointer': 'none',
} as CSSProperties
const cardTransform = (side: 'prev' | 'next') =>
const bubbleTransform = (side: 'prev' | 'next') =>
side === 'next'
? `translateY(calc((1 - var(--flip-progress)) * ${PEEK_TRAVEL_PERCENT}%))`
: `translateY(calc((var(--flip-progress) - 1) * ${PEEK_TRAVEL_PERCENT}%))`
? 'translateY(calc((1 - var(--flip-progress)) * 24px))'
: 'translateY(calc((var(--flip-progress) - 1) * 24px))'
const EDGE_ANCHOR = {
next: {
container: 'bottom-0',
card: 'bottom-12',
badge: 'bottom-2',
bar: 'bottom-0',
label: '▼ 继续滚动 · 翻到下一章',
},
prev: {
container: 'top-0',
card: 'top-12',
badge: 'top-2',
bar: 'top-0',
label: '▲ 继续滚动 · 翻到上一章',
@@ -67,23 +63,12 @@ function FlipEdge({ side, target, edgeRef, onFlip }: FlipEdgeProps) {
className={`pointer-events-none fixed inset-x-0 ${anchor.container} z-40`}
style={edgeStyle}
>
<div aria-hidden className={`absolute inset-x-0 ${anchor.card}`}>
<div className="mx-auto max-w-[1200px] px-6">
<div
className="cursor-pointer will-change-transform [pointer-events:var(--flip-pointer)]"
style={{ transform: cardTransform(side) }}
onClick={onFlip}
>
<FlipPeekCard chapter={target.chapter} side={side} />
</div>
</div>
</div>
<div className={`absolute inset-x-0 ${anchor.badge} flex justify-center`}>
<button
type="button"
onClick={onFlip}
className="cursor-pointer rounded-full border-2 border-ink px-3 py-1 text-[12px] font-bold text-ink shadow-ink transition-[translate,box-shadow] duration-150 [pointer-events:var(--flip-pointer)] hover:-translate-y-0.5 hover:shadow-ink-lift active:translate-x-[2px] active:translate-y-[2px] active:shadow-[1px_1px_0_var(--color-ink)]"
style={{ background: target.chapter.color }}
style={{ background: target.chapter.color, transform: bubbleTransform(side) }}
>
{anchor.label}
</button>
@@ -99,7 +84,6 @@ function FlipEdge({ side, target, edgeRef, onFlip }: FlipEdgeProps) {
}
export function PageFlipZone({ prev, next, children }: PageFlipZoneProps) {
const surfaceRef = useRef<HTMLDivElement>(null)
const nextEdgeRef = useRef<HTMLDivElement>(null)
const prevEdgeRef = useRef<HTMLDivElement>(null)
const edgesRef = useRef({ prev, next })
@@ -107,9 +91,6 @@ export function PageFlipZone({ prev, next, children }: PageFlipZoneProps) {
edgesRef.current = { prev, next }
useEffect(() => {
const surface = surfaceRef.current
if (!surface) return
let target = 0
let position = 0
let velocity = 0
@@ -142,8 +123,6 @@ export function PageFlipZone({ prev, next, children }: PageFlipZoneProps) {
}
const paint = () => {
const offset = direction < 0 ? position : -position
surface.style.transform = offset === 0 ? '' : `translateY(${offset}px)`
const progress = Math.max(0, Math.min(position / FLIP_THRESHOLD, 1))
setProgress(1, direction > 0 ? progress : 0)
setProgress(-1, direction < 0 ? progress : 0)
@@ -190,6 +169,7 @@ export function PageFlipZone({ prev, next, children }: PageFlipZoneProps) {
direction = side
flipping = true
if (targetEdge) {
sessionStorage.setItem('vt', side > 0 ? 'next' : 'prev')
window.location.assign(targetEdge.href)
} else {
flipping = false
@@ -274,9 +254,7 @@ export function PageFlipZone({ prev, next, children }: PageFlipZoneProps) {
return (
<>
<div ref={surfaceRef} data-flip-surface>
{children}
</div>
{children}
{next && (
<FlipEdge
side="next"
-2
View File
@@ -10,8 +10,6 @@ export { DockSheet } from './components/dock/DockSheet'
export type { DropdownProps } from './components/dock/Dropdown'
export { Dropdown } from './components/dock/Dropdown'
export { EntryGuide } from './components/EntryGuide'
export type { FlipPeekCardProps } from './components/FlipPeekCard'
export { FlipPeekCard } from './components/FlipPeekCard'
export type { BookmarkProps } from './components/learning/Bookmark'
export { Bookmark } from './components/learning/Bookmark'
export type { BrickToolboxProps, ToolboxBrick } from './components/learning/BrickToolbox'
@@ -176,14 +176,6 @@
navigation: auto;
}
@media (prefers-reduced-motion: reduce) {
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation-duration: 0.01ms;
}
}
:root {
--page-flip-spring: linear(
0,
@@ -199,11 +191,6 @@
);
}
:root:active-view-transition-type(page-flip-next) [data-chapter-hero],
:root:active-view-transition-type(page-flip-prev) [data-chapter-hero] {
--vt-hero-name: none;
}
@keyframes page-flip-rise-in {
from {
transform: translateY(100%);
@@ -233,23 +220,19 @@
}
}
@media (prefers-reduced-motion: no-preference) {
:root:active-view-transition-type(page-flip-next)::view-transition-new(root),
:root:active-view-transition-type(page-flip-prev)::view-transition-new(root) {
animation-duration: 520ms;
animation-timing-function: var(--page-flip-spring);
animation-fill-mode: both;
}
:root:active-view-transition-type(page-flip-next)::view-transition-new(root) {
animation-name: page-flip-rise-in;
}
:root:active-view-transition-type(page-flip-prev)::view-transition-new(root) {
animation-name: page-flip-drop-in;
}
:root:active-view-transition-type(page-flip-next)::view-transition-old(root),
:root:active-view-transition-type(page-flip-prev)::view-transition-old(root) {
animation: 520ms var(--page-flip-spring) both page-flip-recede;
}
html[data-vt]::view-transition-new(root) {
animation-duration: 520ms;
animation-timing-function: var(--page-flip-spring);
animation-fill-mode: both;
}
html[data-vt="next"]::view-transition-new(root) {
animation-name: page-flip-rise-in;
}
html[data-vt="prev"]::view-transition-new(root) {
animation-name: page-flip-drop-in;
}
html[data-vt]::view-transition-old(root) {
animation: 520ms var(--page-flip-spring) both page-flip-recede;
}
@theme {
-45
View File
@@ -1,45 +0,0 @@
const NEXT_TYPE = 'page-flip-next'
const PREV_TYPE = 'page-flip-prev'
interface FlipActivation {
from: { url: string }
entry: { url: string }
}
interface FlipViewTransition {
types: Set<string>
}
type FlipEvent = Event & {
activation?: FlipActivation
viewTransition?: FlipViewTransition
}
const chapterOf = (url: string) => {
const match = /\/ch(\d+)\.html(?:$|[?#])/.exec(url)
return match ? Number(match[1]) : null
}
const flipType = (fromUrl: string, toUrl: string) => {
const from = chapterOf(fromUrl)
const to = chapterOf(toUrl)
if (from === null || to === null || from === to) return null
return to > from ? NEXT_TYPE : PREV_TYPE
}
export function setupPageFlip() {
if (typeof window === 'undefined') return
if ('scrollRestoration' in history) history.scrollRestoration = 'manual'
window.addEventListener('pageswap', (event) => {
const flip = event as FlipEvent
if (!flip.viewTransition || !flip.activation) return
const type = flipType(flip.activation.from.url, flip.activation.entry.url)
if (type) flip.viewTransition.types.add(type)
})
window.addEventListener('pagereveal', (event) => {
const flip = event as FlipEvent
if (!flip.viewTransition || !flip.activation) return
const type = flipType(flip.activation.from.url, window.location.href)
if (type) flip.viewTransition.types.add(type)
})
}
-2
View File
@@ -1,10 +1,8 @@
import { ChapterPage } from '../../components/ChapterPage'
import { mountPage } from '../../lib/mount'
import { setupPageFlip } from '../../lib/page-flip'
const page = <ChapterPage id={1} />
export default page
setupPageFlip()
mountPage(page)
-2
View File
@@ -1,10 +1,8 @@
import { ChapterPage } from '../../components/ChapterPage'
import { mountPage } from '../../lib/mount'
import { setupPageFlip } from '../../lib/page-flip'
const page = <ChapterPage id={2} />
export default page
setupPageFlip()
mountPage(page)
-2
View File
@@ -1,10 +1,8 @@
import { ChapterPage } from '../../components/ChapterPage'
import { mountPage } from '../../lib/mount'
import { setupPageFlip } from '../../lib/page-flip'
const page = <ChapterPage id={3} />
export default page
setupPageFlip()
mountPage(page)
-2
View File
@@ -1,10 +1,8 @@
import { ChapterPage } from '../../components/ChapterPage'
import { mountPage } from '../../lib/mount'
import { setupPageFlip } from '../../lib/page-flip'
const page = <ChapterPage id={4} />
export default page
setupPageFlip()
mountPage(page)
-2
View File
@@ -1,10 +1,8 @@
import { ChapterPage } from '../../components/ChapterPage'
import { mountPage } from '../../lib/mount'
import { setupPageFlip } from '../../lib/page-flip'
const page = <ChapterPage id={5} />
export default page
setupPageFlip()
mountPage(page)
-2
View File
@@ -1,10 +1,8 @@
import { ChapterPage } from '../../components/ChapterPage'
import { mountPage } from '../../lib/mount'
import { setupPageFlip } from '../../lib/page-flip'
const page = <ChapterPage id={6} />
export default page
setupPageFlip()
mountPage(page)
-2
View File
@@ -1,6 +1,5 @@
import { ChapterPage } from '../../components/ChapterPage'
import { mountPage } from '../../lib/mount'
import { setupPageFlip } from '../../lib/page-flip'
import { TemplateLab } from './TemplateLab'
const page = (
@@ -11,5 +10,4 @@ const page = (
export default page
setupPageFlip()
mountPage(page)
+1 -87
View File
@@ -1,21 +1,16 @@
import { statSync } from 'node:fs'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { readFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { pathToFileURL } from 'node:url'
import type { StackHook, WatchHook } from '@idealjs/stack'
import { compile } from '@tailwindcss/node'
import { Scanner } from '@tailwindcss/oxide'
import { build as esbuild, type Plugin as esbuildWasmPlugin } from 'esbuild-wasm'
import { renderToString } from 'react-dom/server'
export interface TutorialBuildOptions {
root: string
ssg?: boolean
}
const TOKENS_PATH = 'src/design-system/styles/tokens.css'
const PAGE_ENTRY = /main\.[jt]sx$/
export function tutorialBuild(options: TutorialBuildOptions): StackHook {
const hook: WatchHook = {
@@ -25,7 +20,6 @@ export function tutorialBuild(options: TutorialBuildOptions): StackHook {
const files = watched.files.map((file) => ({ ...file }))
const byPath = new Map(files.map((file) => [file.path, file]))
await compileTailwind(byPath, options.root)
if (options.ssg === true) await renderPages(ctx, byPath, options.root)
ctx.output({ name: 'tutorial-build', dir: watched.dir, files })
},
}
@@ -64,83 +58,3 @@ const compileTailwind = async (
const candidates = new Set(scanner.scan())
target.code = compiler.build([...candidates])
}
interface OutputContextLike {
inputs: { name: string; id: string }[]
modules: { id: string; deps: string[] }[]
}
const RAW_SUFFIX = '?raw'
const RUNTIME_DOC_FALLBACK =
'<!doctype html><html lang="zh-CN"><body><!-- web-runner 产物缺失:先跑 yarn workspace @stack/web-runner build:runtime --></body></html>'
const tutorialSsrPlugin = (root: string): esbuildWasmPlugin => ({
name: 'tutorial-ssr',
setup(build) {
build.onResolve({ filter: /\?raw$/ }, (args) => ({
path: join(dirname(args.importer), args.path.slice(0, -RAW_SUFFIX.length)) + RAW_SUFFIX,
}))
build.onLoad({ filter: /\?raw$/ }, async (args) => ({
contents: await readFile(args.path.slice(0, -RAW_SUFFIX.length), 'utf8'),
loader: 'text',
}))
build.onResolve({ filter: /^virtual:/ }, (args) => ({ path: args.path, namespace: 'virtual' }))
build.onLoad({ filter: /.*/, namespace: 'virtual' }, async (args) => {
if (args.path === 'virtual:web-runner-doc') {
let doc: string
try {
doc = await readFile(join(root, '../web-runner/dist-runtime/index.html'), 'utf8')
} catch {
doc = RUNTIME_DOC_FALLBACK
}
return { contents: `export default ${JSON.stringify(doc)}`, loader: 'js' }
}
return {
contents: `export default ${JSON.stringify(process.env.VITE_STACK_RUNTIME_ORIGIN ?? '')}`,
loader: 'js',
}
})
},
})
const renderPages = async (
ctx: OutputContextLike,
byPath: Map<string, { path: string; code: string }>,
root: string,
): Promise<void> => {
const workspace = await mkdtemp(join(root, 'node_modules', '.stack-ssg-'))
try {
for (const input of ctx.inputs) {
if (!input.id.endsWith('.html')) continue
const htmlFile = byPath.get(`${input.name}.html`)
if (htmlFile === undefined) continue
const htmlModule = ctx.modules.find((module) => module.id === input.id)
const entryId = htmlModule?.deps.find((dep) => PAGE_ENTRY.test(dep))
if (entryId === undefined) {
throw new Error(`[tutorial-build] ${input.name}.html 找不到 main 入口模块`)
}
const outfile = join(workspace, `${input.name}.mjs`)
await esbuild({
entryPoints: [entryId],
bundle: true,
format: 'esm',
platform: 'node',
jsx: 'automatic',
external: ['react', 'react-dom', 'react-joyride', '@idealjs/stack', 'esbuild-wasm'],
plugins: [tutorialSsrPlugin(root)],
outfile,
logLevel: 'silent',
})
const module = await import(pathToFileURL(outfile).href)
const html = renderToString(module.default)
const marker = '<div id="root"></div>'
if (!htmlFile.code.includes(marker)) {
throw new Error(`[tutorial-build] ${input.name}.html 缺少 #root 挂载点`)
}
htmlFile.code = htmlFile.code.replace(marker, `<div id="root">${html}</div>`)
}
} finally {
await rm(workspace, { recursive: true, force: true })
}
}
+167
View File
@@ -0,0 +1,167 @@
import { createHash } from 'node:crypto'
import { mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { pathToFileURL } from 'node:url'
import type { StackHook, WatchHook } from '@idealjs/stack'
import { build as esbuild, type Plugin as esbuildWasmPlugin } from 'esbuild-wasm'
import { renderToString } from 'react-dom/server'
export interface SsgOptions {
root: string
}
interface OutputContextLike {
inputs: { name: string; id: string }[]
modules: { id: string; deps: string[] }[]
}
const PAGE_ENTRY = /main\.[jt]sx$/
const RAW_SUFFIX = '?raw'
const WORKSPACE_DIR = 'node_modules/.stack-ssg'
const RUNTIME_DOC = '../web-runner/dist-runtime/index.html'
const RUNTIME_DOC_FALLBACK =
'<!doctype html><html lang="zh-CN"><body><!-- web-runner 产物缺失:先跑 yarn workspace @stack/web-runner build:runtime --></body></html>'
const cache = new Map<string, { fingerprint: string; html: string }>()
const tutorialSsrPlugin = (root: string): esbuildWasmPlugin => ({
name: 'tutorial-ssr',
setup(build) {
build.onResolve({ filter: /\?raw$/ }, (args) => ({
path: join(dirname(args.importer), args.path.slice(0, -RAW_SUFFIX.length)) + RAW_SUFFIX,
}))
build.onLoad({ filter: /\?raw$/ }, async (args) => ({
contents: await readFile(args.path.slice(0, -RAW_SUFFIX.length), 'utf8'),
loader: 'text',
}))
build.onResolve({ filter: /^virtual:/ }, (args) => ({ path: args.path, namespace: 'virtual' }))
build.onLoad({ filter: /.*/, namespace: 'virtual' }, async (args) => {
if (args.path === 'virtual:web-runner-doc') {
let doc: string
try {
doc = await readFile(join(root, RUNTIME_DOC), 'utf8')
} catch {
doc = RUNTIME_DOC_FALLBACK
}
return { contents: `export default ${JSON.stringify(doc)}`, loader: 'js' }
}
return {
contents: `export default ${JSON.stringify(process.env.VITE_STACK_RUNTIME_ORIGIN ?? '')}`,
loader: 'js',
}
})
},
})
const mtimeOf = (path: string): string => {
try {
return statSync(path).mtimeMs.toString()
} catch {
return 'missing'
}
}
const realPathOf = (id: string): string | null => {
if (id.endsWith('.raw.js')) return id.slice(0, -'.raw.js'.length)
if (id.startsWith('virtual:')) return null
return id
}
const fingerprintOf = (entryId: string, ctx: OutputContextLike, root: string): string => {
const byId = new Map(ctx.modules.map((module) => [module.id, module]))
const seen = new Set<string>()
const queue = [entryId]
const parts: string[] = []
while (queue.length > 0) {
const id = queue.shift()
if (id === undefined || seen.has(id)) continue
seen.add(id)
const real = realPathOf(id)
parts.push(real === null ? id : `${id}@${mtimeOf(real)}`)
for (const dep of byId.get(id)?.deps ?? []) queue.push(dep)
}
parts.push(`runtime-doc@${mtimeOf(join(root, RUNTIME_DOC))}`)
return createHash('sha1').update(parts.sort().join('\n')).digest('hex')
}
const renderPage = async (
name: string,
entryId: string,
fingerprint: string,
workspace: string,
root: string,
): Promise<string> => {
for (const stale of readdirSync(workspace)) {
if (stale.startsWith(`${name}-`) && stale.endsWith('.mjs')) {
rmSync(join(workspace, stale))
}
}
const outfile = join(workspace, `${name}-${fingerprint}.mjs`)
await esbuild({
entryPoints: [entryId],
bundle: true,
format: 'esm',
platform: 'node',
jsx: 'automatic',
external: ['react', 'react-dom', 'react-joyride', '@idealjs/stack', 'esbuild-wasm'],
plugins: [tutorialSsrPlugin(root)],
outfile,
logLevel: 'silent',
})
const module = await import(pathToFileURL(outfile).href)
return renderToString(module.default)
}
const renderPages = async (
ctx: OutputContextLike,
byPath: Map<string, { path: string; code: string }>,
root: string,
): Promise<void> => {
const workspace = join(root, WORKSPACE_DIR)
mkdirSync(workspace, { recursive: true })
let rendered = 0
let pages = 0
for (const input of ctx.inputs) {
if (!input.id.endsWith('.html')) continue
const htmlFile = byPath.get(`${input.name}.html`)
if (htmlFile === undefined) continue
const htmlModule = ctx.modules.find((module) => module.id === input.id)
const entryId = htmlModule?.deps.find((dep) => PAGE_ENTRY.test(dep))
if (entryId === undefined) {
throw new Error(`[ssg] ${input.name}.html 找不到 main 入口模块`)
}
pages += 1
const fingerprint = fingerprintOf(entryId, ctx, root)
let entry = cache.get(input.name)
if (entry === undefined || entry.fingerprint !== fingerprint) {
entry = {
fingerprint,
html: await renderPage(input.name, entryId, fingerprint, workspace, root),
}
cache.set(input.name, entry)
rendered += 1
}
const marker = '<div id="root"></div>'
if (!htmlFile.code.includes(marker)) {
throw new Error(`[ssg] ${input.name}.html 缺少 #root 挂载点`)
}
htmlFile.code = htmlFile.code.replace(marker, `<div id="root">${entry.html}</div>`)
}
console.log(`[ssg] ${rendered}/${pages} 页预渲染`)
}
export function ssg(options: SsgOptions): StackHook {
const hook: WatchHook = {
name: 'ssg',
watch: ['tutorial-build'],
lower: async (ctx, watched) => {
const files = watched.files.map((file) => ({ ...file }))
const byPath = new Map(files.map((file) => [file.path, file]))
await renderPages(ctx, byPath, options.root)
ctx.output({ name: 'ssg', dir: watched.dir, files })
},
}
return hook
}
+3 -1
View File
@@ -7,6 +7,7 @@ import { imports, vendor } from '@idealjs/stack/builtins'
import { nodeFs } from '@idealjs/stack/node'
import { transform } from 'esbuild-wasm'
import { tutorialBuild } from './stack-plugins/build.ts'
import { ssg } from './stack-plugins/ssg.ts'
const appDir = dirname(fileURLToPath(import.meta.url))
try {
@@ -75,6 +76,7 @@ export default defineConfig({
},
},
imports(),
tutorialBuild({ root: appDir, ssg: process.env.STACK_SSG === '1' }),
tutorialBuild({ root: appDir }),
ssg({ root: appDir }),
],
})
+11
View File
@@ -102,6 +102,17 @@ apps/tutorial/src/
1. **P0(桌面全量)**:`PageFlipZone` 手势层(wheel + 键盘,到底蓄力/释放判定)+ `tokens.css` 方向关键帧(`linear()` 弹簧、next/prev types、named 元素白名单)+ `page-flip.ts` 方向登记。Firefox/旧浏览器自动降级为现状。
2. **P1(打磨)**:下一章 prefetch、触屏 overscroll 蓄力。(已落地:蓄力符号层——底缘进度条+继续滚动文案+上/下章英雄卡探头;e2e 手势用例)
### 方向机制重构(2026-11)
参考 `idealjs/packages/home/page-one.html` 的做法,方向登记从 JS types 机制换成 sessionStorage 握手+CSS 属性选择器,进场动画完全交给浏览器:
- **写**:翻页意图产生时落 `sessionStorage['vt']`——页底 `data-dir` 链接由 ch1–ch7.html head 内联脚本的全局 click 监听写入;手势/键盘/气泡点击统一在 `PageFlipZone` 的 `flip()` 里写。
- **读**:ch1–ch7.html head 内联经典脚本(解析阻塞,早于首帧)读出并写到 `<html data-vt>`,**读后即清**(consume-once,不设默认方向)。
- **选**:`tokens.css` 用 `html[data-vt="next"]::view-transition-new(root)`(rise-in)/ `[data-vt="prev"]`(drop-in)/ `html[data-vt]::view-transition-old(root)`(recede)选关键帧,`:active-view-transition-type()` 与 `page-flip.ts` 的 pageswap/pagereveal URL 章号比较整体废弃。
- **读后即清的红利**:浏览器返回、抽屉跳章、刷新等非翻页导航读不到方向,走浏览器默认 crossfade,无残留状态、不会拿旧方向误判返回动画。
- **蓄力符号层收敛**:只留「气泡(章色胶囊按钮)+进度条」,探头卡 FlipPeekCard(章标题预览)删除;英雄区 `ch-N` 命名与 `--vt-hero-name` 抑制机制一并移除,标题随整页滑动(`data-vt` 是常驻属性,morph 抑制无法只作用于过渡窗口)。`site-header` morph 保留。
- `scrollRestoration = 'manual'` 移入内联脚本(原模块脚本晚于首帧,时机不可靠)。
落地后机制说明按仓库约定补进 design-* 册,PR 附 before/after 实拍(`docs/assets/page-flip/`)。
## 参考
+48
View File
@@ -234,6 +234,54 @@ export const SCENARIOS: Scenario[] = [
],
},
},
{
name: '产出级联:watch 订阅者登记的产出继续派发下游钩子',
files: { 'src/main.ts': 'console.log(1)\n' },
config: {
inputs: [{ name: 'main', path: 'src/main.ts' }],
hooks: [
{
name: 'mid-producer',
watch: ['default'],
lower: (ctx, output) => {
ctx.output({
name: 'mid',
dir: output.dir,
files: output.files.map((file) => ({
path: file.path,
code: `${file.code}\nmidMark()\n`,
})),
})
},
} satisfies WatchHook,
{
name: 'final-producer',
watch: ['mid'],
lower: (ctx, output) => {
ctx.output({
name: 'final',
dir: output.dir,
files: output.files.map((file) => ({
path: file.path,
code: `${file.code}\nfinalMark()\n`,
})),
})
},
} satisfies WatchHook,
],
},
expected: {
outputs: [
{ name: 'default', dir: 'dist' },
{ name: 'mid', dir: 'dist', files: [{ path: 'main.js', includes: ['midMark()'] }] },
{
name: 'final',
dir: 'dist',
files: [{ path: 'main.js', includes: ['midMark()', 'finalMark()'] }],
},
],
},
},
{
name: '未解析的相对导入使构建失败',
files: {