Files
arnold.cuiandcqh963852 3b9092ad40
Build Tutorial / Build @stack/tutorial (kaniko) (push) Failing after 49s
refactor: 组件三层分类拆包——token 迁 vanilla-extract,ui-kit 与 site-ui-kit 双包落地 (#62)
## 背景

design-system 混居在 `apps/tutorial/src/design-system` 一个桶里:token 的事实源是 tailwind v4 `@theme`,token/基础组件/业务组件三层没有物理边界,样式范式被 tailwind 绑死。按三层分类(token/ui-kit 基础行为件/业务组件)拆成两个 workspace 包,token 用 vanilla-extract 最小用法(theme var + style,不用 recipe/sprinkles)重建事实源,整体减少对 tailwind 的依赖。

## 变更内容

**两包结构(源码直出,`@idealjs/stack` 同款 exports 指 .ts)**
- `@idealjs/stack-ui-kit`:token 层 + 基础组件层。颜色 token 分两层(`design/colors` 规范的机器可执行形式):**色板描述层** `--palette-*`(coral/teal/mustard/violet/pink/blue/green/black/cream/sand/clay/graphite,色值唯一事实源,theme switch 只切这层)与**语义描述层** `--color-*`(clash 对槽位与中性角色,组件组成只消费这层,值全部 `var(--palette-*)`);semantic 层以 `createGlobalThemeContract` + mapFn **按原名**输出 `--color-*`/`--shadow-*`/`--text-*`(learning.css 约 166 处、app 手写 css、全部 inline `var()` 按原名消费,改名即断),业务包 `--color-ch1..7` 同样映射 palette 槽位;组件 11 件全量 ve 化(Button/ShadowButton/ShadowCard/Ticket/BrowserMockup/shapes/Scatter/dock 三件),`.hover-host` 系与 `.ticket-*` 打孔机制平移为 `globalStyle`
- `@idealjs/stack-site-ui-kit`:业务层(types/章节图谱件/Site 壳/PageFlipZone/learning 12 件/Gallery),`learning.css` 与 page-flip 动画段归位包内;本版业务件仍以 tailwind 类书写,靠桥接层消费 token(后续逐步 ve 化,见包 README「已知后续」)
- 行为/语义拆两层:ui-kit 新增 `Tabs`(tablist roving)/`FlipCard`(双面常驻 DOM)/`ToggleButton`(aria-pressed)骨架与 `useControllableState`;FolderTabs/FlashCard/Bookmark 改为骨架 + learning 皮薄封装,DOM 与类名不变;`SiteNavbar`/`SiteSidebar` 本轮不动样式(含 #61 的 nested 零投影形态,已 rebase 合入并保留 API)

**stack CLI 插件适配(零 core 侵入,全部现有 hook 先例)**
- `@idealjs/stack-ui-kit/stack-plugin`:真 esbuild + 官方 ve 插件求值 `.css.ts`,`config.load` 返回静态类名产物(发生在 import 解析前,依赖图干净);`WatchHook` 监听 default 产出向每个 html 注入 `__shared/ui-kit.css` 并超集重发,链序 default → vanilla-extract → tutorial-build → ssg;缓存按内容指纹
- ssg 插件的 esbuild-wasm 通道加 `.css.ts` onLoad(走同一编译产物)
- `stack dev/watch` 新增 `config.watchRoots` 多根监听,tutorial 挂两包源码热更(实测改包内组件触发重建)

**app 侧**
- `tokens.css` 拆解为桥接层 `src/styles/tailwind.css`(`@theme inline` 同名引用 ve 变量生成 utility + 排版工具类),app 侧 ~456 行 token 类用法零改动;token 唯一事实源移交 ve
- 消费方 import 全部改双包名(tsconfig paths 走 aliasResolve);24 个 html 的 learning.css link 改包说明符,产物落 `__shared/`
- 删除 `src/design-system/`,README 拆为两包各自文档

## 自测结果

- `yarn workspace @stack/tutorial build`:24 输入 169 模块,ve css 落 `__shared/ui-kit.css`,html link 重写正确
- `yarn workspace @stack/tutorial test:e2e`:**134 全过**(rebase 到含 #61 的 main 后,#61 重建的基线含此前 main 上既有失败的 flip-nav-overlay)
- `yarn workspace @idealjs/stack-ui-kit typecheck` / `stack-site-ui-kit typecheck` 通过;`packages/stack` 测试 74 全过;`node scripts/strip-comments.mjs` 零注释;`biome format` 收敛
- dev 模式实测:改两包源码触发热更(watchRoots 生效)
- 颜色两层拆分后 e2e 134 全过(最终计算色值不变);`design/colors` 文档页按两层重写(中性阶补齐五档),视觉基线以 `--update-snapshots=all` 刻意更新,前后对照:

颜色页(design/colors,两层结构与中性阶补齐):

![before-after design/colors](https://gitea.idealjs.com/attachments/e018ee4b-27ca-4a9b-918d-1766e7ad44e2)
- 前后对照截图(main@7b6797a vs 本分支,stack preview + playwright 1280×900,fonts.ready 后截,滚动容器展开取整页):

---------

Co-authored-by: cqh963852 <cqh963852@hotmail.com>
Reviewed-on: #62
2026-11-24 13:07:41 +00:00

218 lines
7.5 KiB
TypeScript

import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
import { resolve as resolvePath2 } from 'node:path'
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
vanillaLoad?: (id: string) => Promise<string | null | undefined>
themeClasses?: () => Record<string, 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,
vanillaLoad?: SsgOptions['vanillaLoad'],
): esbuildWasmPlugin => ({
name: 'tutorial-ssr',
setup(build) {
build.onResolve({ filter: /\.css$/ }, (args) => {
const abs = resolvePath2(args.resolveDir ?? '', args.path)
if (existsSync(`${abs}.ts`)) return { path: `${abs}.ts` }
return { path: `ssr-css-empty:${args.path}`, namespace: 'ssr-css-empty' }
})
build.onLoad({ filter: /.*/, namespace: 'ssr-css-empty' }, () => ({
contents: '',
loader: 'js',
}))
if (vanillaLoad !== undefined) {
build.onLoad({ filter: /\.css\.ts$/ }, async (args) => {
const code = await vanillaLoad(args.path)
if (code === undefined || code === null) return null
return { contents: code, loader: 'js' }
})
}
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 SSG_PLUGIN_VERSION = 'css-ts-jump-v3'
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))}`)
parts.push(SSG_PLUGIN_VERSION)
return createHash('sha1').update(parts.sort().join('\n')).digest('hex')
}
const renderPage = async (
name: string,
entryId: string,
fingerprint: string,
workspace: string,
root: string,
vanillaLoad: SsgOptions['vanillaLoad'],
): Promise<string> => {
const flat = name.replaceAll('/', '__')
for (const stale of readdirSync(workspace)) {
if (stale.startsWith(`${flat}-`) && stale.endsWith('.mjs')) {
rmSync(join(workspace, stale))
}
}
const outfile = join(workspace, `${flat}-${fingerprint}.mjs`)
await esbuild({
entryPoints: [entryId],
bundle: true,
format: 'esm',
platform: 'node',
jsx: 'automatic',
external: ['react', 'react-dom', 'react-joyride', '@idealjs/stack', 'esbuild-wasm', '*.css'],
plugins: [tutorialSsrPlugin(root, vanillaLoad)],
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,
vanillaLoad: SsgOptions['vanillaLoad'],
themeClasses: SsgOptions['themeClasses'],
): 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, vanillaLoad),
}
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>`)
htmlFile.code = applyThemeClasses(htmlFile.code, themeClasses?.())
}
console.log(`[ssg] ${rendered}/${pages} 页预渲染`)
}
const applyThemeClasses = (code: string, classes?: Record<string, string>): string => {
if (classes === undefined) return code
const htmlClasses = ['paletteClass', 'themeClass', 'siteClass']
.map((key) => classes[key])
.filter(Boolean)
let next = code
if (htmlClasses.length > 0 && !/<html[^>]*\sclass="/.test(next)) {
next = next.replace(/<html(?=[\s>])/, `<html class="${htmlClasses.join(' ')}"`)
}
const pageBase = classes.pageBase
if (pageBase !== undefined) {
if (/<body[^>]*\sclass="/.test(next)) {
next = next.replace(/(<body[^>]*\sclass=")[^"]*"/, `$1${pageBase}"`)
} else {
next = next.replace(/<body(?=[\s>])/, `<body class="${pageBase}"`)
}
}
return next
}
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, options.vanillaLoad, options.themeClasses)
ctx.output({ name: 'ssg', dir: watched.dir, files })
},
}
return hook
}