diff --git a/.gitignore b/.gitignore index c48be44d1..64107a310 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ playwright-report/ blob-report/ coverage/ .playwright/ + +# SSR 预览生成产物(scripts/ssr-preview.mjs 输出) +ssr-preview.html diff --git a/components/__tests__/ssr-smoke.runner.mjs b/components/__tests__/ssr-smoke.runner.mjs new file mode 100644 index 000000000..cc0c90d98 --- /dev/null +++ b/components/__tests__/ssr-smoke.runner.mjs @@ -0,0 +1,235 @@ +/** + * SSR 渲染 runner:由 ssr-smoke.spec.ts 以独立子进程启动。 + * 用 vite 的 SSR 模式加载 .vue/.tsx 源码(与库的真实发布形态一致的 ESM 链路), + * 在无任何 DOM 全局的环境里 renderToString,打印标记 + 退出码。 + * + * 参数:node ssr-smoke.runner.mjs button|form|overlay|data|selfcheck + */ +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const root = path.resolve(__dirname, '../..'); + +const groups = process.argv.slice(2); + +// selfcheck 不需要 vite,在任何重初始化之前抢先执行并退出 +if (groups.includes('selfcheck')) { + if (typeof globalThis.document !== 'undefined' + || typeof globalThis.window !== 'undefined') { + console.error('SELFCHECK_FAIL: DOM globals exist in this process'); + process.exit(1); + } + console.log('SELFCHECK_OK'); + if (groups.length === 1) process.exit(0); +} + +// vite 以编程方式做 SSR transform(jsdom 不参与本进程) +const { createServer } = await import( + pathToFileURL(path.join(root, 'node_modules/vite/dist/node/index.js')).href +); + +// 与 vitest.config.ts 相同的插件链:vue + jsx(tsx 组件源码需要) +// pnpm 目录导入不可用,按包 exports 字段直指 dist 文件 +const modPath = (p) => + pathToFileURL(path.join(root, 'node_modules', p)).href; +const vuePlugin = (await import(modPath('@vitejs/plugin-vue/dist/index.mjs'))).default; +const vueJsxPlugin = (await import(modPath('@vitejs/plugin-vue-jsx/dist/index.mjs'))).default; + +const vite = await createServer({ + root, + logLevel: 'error', + plugins: [vuePlugin(), vueJsxPlugin()], + server: { middlewareMode: true }, + appType: 'custom', + optimizeDeps: { noDiscovery: true }, +}); + +const load = async (spec) => { + const url = pathToFileURL(path.resolve(root, spec)).href; + return vite.ssrLoadModule(url); +}; + +const { createSSRApp, h } = await import('vue'); +const { renderToString } = await import('vue/server-renderer'); + +const render = async (node) => { + const app = createSSRApp({ render: () => node }); + return renderToString(app); +}; + +let failed = false; +try { + if (groups.includes('button')) { + const mod = await load('components/button/button.tsx'); + const html = await render( + h(mod.default, { type: 'primary' }, { default: () => '按钮' }), + ); + if (!html.includes('按钮')) { + throw new Error(`button html missing text: ${html.slice(0, 120)}`); + } + console.log('BUTTON_OK'); + } + + if (groups.includes('form')) { + const form = await load('components/form/form.vue'); + const item = await load('components/form/formItem.vue'); + const input = await load('components/input/input.vue'); + const select = await load('components/select/select.vue'); + const html = await render( + h(form.default, { model: {} }, { + default: () => [ + h(item.default, { label: '名称', prop: 'name' }, { + default: () => h(input.default), + }), + h(item.default, { label: '城市', prop: 'city' }, { + default: () => h(select.default, null, { default: () => '选项' }), + }), + ], + }), + ); + if (!html.includes('名称') || !html.includes('城市')) { + throw new Error(`form html missing labels: ${html.slice(0, 200)}`); + } + console.log('FORM_OK'); + } + + if (groups.includes('overlay')) { + const tooltip = await load('components/tooltip/tooltip.tsx'); + const dropdown = await load('components/dropdown/dropdown.tsx'); + const modal = await load('components/modal/modal.tsx'); + const html = await render( + h('div', [ + // FTooltip 的 trigger 插槽是 default(slots.default) + h(tooltip.default, null, { + default: () => h('span', '悬停我'), + content: () => '提示内容', + }), + h(dropdown.default, { options: [] }, { + // FDropdown 的 trigger 插槽同样是 default(经 slots.default 透传给 Popper) + default: () => h('button', '菜单'), + }), + h(modal.default, { show: false }, { default: () => '模态' }), + ]), + ); + if (!html.includes('悬停我') || !html.includes('菜单')) { + throw new Error(`overlay html missing trigger: ${html.slice(0, 300)}`); + } + console.log('OVERLAY_OK'); + } + + if (groups.includes('data')) { + const table = await load('components/table/table.tsx'); + const datePicker = await load('components/date-picker/datePicker.vue'); + const timePicker = await load('components/time-picker/time-picker.vue'); + const html = await render( + h('div', [ + // columns prop + 声明宽度:验证 SSR 静态列宽兜底 + // (模板 用法经 onBeforeMount 注册,服务端 + // 不执行钩子,SSR 下不适用——此为既有设计约束) + h(table.default, { + data: [{ id: 1, name: '行一' }], + columns: [ + { prop: 'id', label: 'ID', width: 120 }, + { prop: 'name', label: '名称', minWidth: 200 }, + ], + }), + h(datePicker.default), + h(timePicker.default), + ]), + ); + if (typeof html !== 'string') { + throw new Error('data render not string'); + } + if (!html.includes('width:120px')) { + throw new Error(`table ssr col width missing: ${html.slice(0, 300)}`); + } + console.log('DATA_OK'); + } + + // review 补充组:FImage(immediate watch 里 new Image 的 P0 崩点) + if (groups.includes('image')) { + const image = await load('components/image/image.vue'); + const imgHtml = await render( + h('div', [ + h(image.default, { src: 'https://example.com/a.png' }), + h(image.default, { + src: 'https://example.com/b.png', + lazy: true, + scrollContainer: '.scroll-area', + }), + ]), + ); + if (!imgHtml.includes('fes-img')) { + throw new Error(`image html missing wrapper: ${imgHtml.slice(0, 300)}`); + } + // 服务端不预加载(loading 保持 true → 输出占位态), + // 客户端激活后 src watch 才触发真实加载 + if (!imgHtml.includes('fes-img__placeholder')) { + throw new Error(`image should render placeholder on server: ${imgHtml.slice(0, 300)}`); + } + console.log('IMAGE_OK'); + } + + // review 补充组:FFloatPane(getStorage/useDrag 守卫的回归守护) + if (groups.includes('floatpane')) { + const floatPane = await load('components/float-pane/float-pane.tsx'); + const html = await render( + h(floatPane.default, { + visible: true, + displayDirective: 'show', + // cachePosition 默认 'local':覆盖 getStorage 守卫路径 + }, { default: () => '浮窗内容' }), + ); + if (typeof html !== 'string') { + throw new Error('floatpane render not string'); + } + // to=null 时服务端 Teleport 渲染为空(Vue 上游行为), + // 断言"不崩 + 退出正常"即为本组目的,内容断言留空 + console.log('FLOATPANE_OK'); + } + + // review 补充组:命令式 API 在服务端调用必须抛可捕获的明确错误 + // (而非 ReferenceError 半路崩溃 / 静默 unhandled rejection) + if (groups.includes('imperative')) { + const modalApi = await load('components/modal/modalApi.tsx'); + let modalThrew = false; + try { + modalApi.default.info({ content: 'x' }); + } catch (e) { + modalThrew = String(e.message).includes('服务端'); + } + if (!modalThrew) { + throw new Error('FModal.info on server should throw catchable Error'); + } + const messageMod = await load('components/message/index.tsx'); + // FMessage.info 同步返回;服务端调用时 createManager reject, + // 由 .catch 输出明确错误(不再 unhandled rejection) + let messageErrored = false; + const origError = console.error; + console.error = (...args) => { + if (String(args[0]).includes('[FMessage]')) { + messageErrored = true; + } + origError(...args); + }; + try { + messageMod.default.info('hello'); + // 让 Promise 链走完 + await new Promise((r) => setTimeout(r, 50)); + } finally { + console.error = origError; + } + if (!messageErrored) { + throw new Error('FMessage.info on server should log explicit error'); + } + console.log('IMPERATIVE_OK'); + } +} catch (e) { + failed = true; + console.error(`SSR_FAIL: ${e && (e.stack || e.message)}`); +} finally { + await vite.close().catch(() => {}); +} + +process.exit(failed ? 1 : 0); diff --git a/components/__tests__/ssr-smoke.spec.ts b/components/__tests__/ssr-smoke.spec.ts new file mode 100644 index 000000000..79bc84101 --- /dev/null +++ b/components/__tests__/ssr-smoke.spec.ts @@ -0,0 +1,117 @@ +/** + * SSR 冒烟测试(独立进程方案): + * + * 背景(架构审查 P0):修复前 useTheme 的 immediate watch 在 setup 期同步访问 + * document.body,任何组件 SSR 即抛 ReferenceError。 + * + * 为什么用独立进程:vitest 的 jsdom 环境给所有用例兜底了 document/window, + * 在同进程内"删全局"会污染同 worker 的其它用例;而 node 环境又与 + * plugin-vue-jsx 的 SSR 虚拟模块存在解析兼容问题。独立子进程跑真实 + * renderToString(无任何 DOM 全局),主进程仅断言退出码与输出—— + * 语义最真实(等价于用户的 Nuxt/SSR 应用进程),且零污染。 + */ +import { execFileSync } from 'node:child_process'; +import path from 'node:path'; +import { describe, expect, test } from 'vitest'; + +const RUNNER = path.resolve(__dirname, 'ssr-smoke.runner.mjs'); + +const runSSR = (groups: string[]) => { + try { + const out = execFileSync( + process.execPath, + [RUNNER, ...groups], + { + encoding: 'utf8', + timeout: 180_000, + env: { ...process.env, NODE_ENV: 'test' }, + }, + ); + return { ok: true, out }; + } catch (e: any) { + return { ok: false, out: `${e.stdout || ''}${e.stderr || ''}` }; + } +}; + +describe('SSR 冒烟(独立进程,无任何 DOM 全局)', () => { + // runner 每次冷启动一个 vite SSR 实例(约 40~50s),默认 5s 超时不够 + const SLOW = 180_000; + + test( + '基础组件:FButton(useTheme 生命周期推迟的直接证明)', + () => { + const r = runSSR(['button']); + expect(r.ok, r.out.slice(-800)).toBe(true); + expect(r.out).toContain('BUTTON_OK'); + }, + SLOW, + ); + + test( + '表单链路:FForm + FFormItem + FInput + FSelect', + () => { + const r = runSSR(['form']); + expect(r.ok, r.out.slice(-800)).toBe(true); + expect(r.out).toContain('FORM_OK'); + }, + SLOW, + ); + + test( + '弹层家族(初始关闭):FTooltip / FDropdown / FModal', + () => { + const r = runSSR(['overlay']); + expect(r.ok, r.out.slice(-800)).toBe(true); + expect(r.out).toContain('OVERLAY_OK'); + }, + SLOW, + ); + + test( + '数据组件:FTable / FDatePicker / FTimePicker', + () => { + const r = runSSR(['data']); + expect(r.ok, r.out.slice(-800)).toBe(true); + expect(r.out).toContain('DATA_OK'); + }, + SLOW, + ); + + test( + '图片:FImage 服务端不预加载(review 补充,P0 崩点回归守护)', + () => { + const r = runSSR(['image']); + expect(r.ok, r.out.slice(-800)).toBe(true); + expect(r.out).toContain('IMAGE_OK'); + }, + SLOW, + ); + + test( + '浮窗:FFloatPane 服务端不崩(getStorage/useDrag 守卫回归守护)', + () => { + const r = runSSR(['floatpane']); + expect(r.ok, r.out.slice(-800)).toBe(true); + expect(r.out).toContain('FLOATPANE_OK'); + }, + SLOW, + ); + + test( + '命令式 API:服务端调用抛可捕获错误而非 ReferenceError', + () => { + const r = runSSR(['imperative']); + expect(r.ok, r.out.slice(-800)).toBe(true); + expect(r.out).toContain('IMPERATIVE_OK'); + }, + SLOW, + ); + + test('回归守护:本进程无任何 DOM 全局(selfcheck,秒回)', () => { + // 直接验证"无 DOM 全局"语义本身:裸 document 访问必须抛错。 + // 若未来有人把 runner 挪回 jsdom 同进程跑,这条会立刻红。 + const r = runSSR(['selfcheck']); + expect(r.ok).toBe(true); + expect(r.out).toContain('SELFCHECK_OK'); + }); +}); diff --git a/components/__tests__/theme-ssr-inject.spec.ts b/components/__tests__/theme-ssr-inject.spec.ts new file mode 100644 index 000000000..a08b1b7ae --- /dev/null +++ b/components/__tests__/theme-ssr-inject.spec.ts @@ -0,0 +1,71 @@ +import { describe, expect, test } from 'vitest'; +import { baseTheme } from '../_theme/base'; +import { applyTheme, getThemeStyleTag, getThemeVarsCss } from '../_theme/applyTheme'; +import type { Theme } from '../_theme/interface'; + +const CSS_VAR_RE = /^--f-[a-z0-9-]+:.+$/; + +describe('SSR 主题变量注入(getThemeVarsCss / getThemeStyleTag)', () => { + test('输出形如 --f-xxx:value; 的声明序列,覆盖全部基础变量', () => { + const css = getThemeVarsCss(); + const entries = css.split(';').filter(Boolean); + expect(entries.length).toBe(Object.keys(baseTheme()).length); + entries.forEach((entry) => { + expect(entry).toMatch(CSS_VAR_RE); + }); + }); + + test('包含关键主题变量且值正确', () => { + const css = getThemeVarsCss(); + expect(css).toContain('--f-primary-color:#5384ff'); + expect(css).toContain('--f-white:#fff'); + expect(css).toContain('--f-border-radius-base:4px'); + }); + + test('getThemeStyleTag 输出完整可用的 ')).toBe(true); + // 内容与 getThemeVarsCss 一致 + expect(tag).toBe(``); + }); + + test('与 applyTheme 的 DOM 写入完全一致(同一数据源同一规则)', () => { + const div = document.createElement('div'); + document.body.appendChild(div); + applyTheme(div); + + const domVars = new Map(); + for (let i = 0; i < div.style.length; i++) { + const name = div.style.item(i); + domVars.set(name, div.style.getPropertyValue(name)); + } + + const cssVars = new Map(); + getThemeVarsCss() + .split(';') + .filter(Boolean) + .forEach((entry) => { + const idx = entry.indexOf(':'); + cssVars.set(entry.slice(0, idx), entry.slice(idx + 1)); + }); + + expect(cssVars.size).toBe(domVars.size); + cssVars.forEach((value, name) => { + expect(domVars.get(name)).toBe(value); + }); + div.remove(); + }); + + test('支持 themeOverrides 定制(与 applyTheme 定制路径一致)', () => { + const overrides: Theme = { common: { primaryColor: '#ff0000' } }; + const css = getThemeVarsCss(overrides); + expect(css).toContain('--f-primary-color:#ff0000'); + + const div = document.createElement('div'); + document.body.appendChild(div); + applyTheme(div, undefined, overrides); + expect(div.style.getPropertyValue('--f-primary-color')).toBe('#ff0000'); + div.remove(); + }); +}); diff --git a/components/_theme/applyTheme.ts b/components/_theme/applyTheme.ts index 68a839723..57c869369 100644 --- a/components/_theme/applyTheme.ts +++ b/components/_theme/applyTheme.ts @@ -3,22 +3,71 @@ import { baseTheme } from './base'; import type { Theme } from './interface'; const CSS_VAR_PREFIX = '--f-'; + +// 变量声明文本("--f-primary-color:#5384ff"),applyTheme 的 DOM 写入与 +// getThemeVarsCss 的 SSR 注入共用同一生成逻辑,确保两条路径值完全一致 +const themeVarsEntries = (vars: ReturnType) => + Object.keys(vars).map((key) => ({ + name: `${CSS_VAR_PREFIX}${kebabCase(key)}`, + value: vars[key as keyof typeof vars], + })); + export function applyTheme( container: HTMLElement, theme?: string, themeOverrides?: Theme, ) { - // TODO 逻辑优化 const _theme = baseTheme(themeOverrides); + const entries = themeVarsEntries(_theme); const _container = container || document.body; - Object.keys(_theme).forEach((key) => { - _container.style.setProperty( - `${CSS_VAR_PREFIX}${kebabCase(key)}`, - _theme[key as keyof typeof _theme], - ); + entries.forEach(({ name, value }) => { + _container.style.setProperty(name, value); }); return { themeVars: _theme, }; } + +/** + * 生成主题 CSS 变量的声明文本(不含选择器与花括号),如: + * `--f-primary-color:#5384ff;--f-white:#fff;...` + * + * 服务端渲染场景使用:fes-design 的主题变量默认值由运行时 applyTheme + * 写入 DOM(非编译期 CSS),纯 SSR 首帧 JS 未执行时 var(--f-*) 解析 + * 不到值,页面呈无主题色的素颜状态(FOUC)。在 SSR 模板里把本函数 + * 输出注入 可让首帧即带主题: + * + * ```html + * + * ``` + * + * Nuxt(app.vue 或 layout): + * ```vue + * + * + * ``` + */ +export function getThemeVarsCss(themeOverrides?: Theme) { + return themeVarsEntries(baseTheme(themeOverrides)) + .map(({ name, value }) => `${name}:${value};`) + .join(''); +} + +/** + * 生成完整的 `; +} diff --git a/components/_theme/useTheme.ts b/components/_theme/useTheme.ts index 457e79b78..dae1410a6 100644 --- a/components/_theme/useTheme.ts +++ b/components/_theme/useTheme.ts @@ -1,4 +1,4 @@ -import { type Ref, ref, watch } from 'vue'; +import { type Ref, onBeforeMount, ref, watch } from 'vue'; import { createSharedComposable } from '@vueuse/core'; import { useConfig } from '../config-provider'; @@ -11,27 +11,30 @@ function _useTheme() { const config = useConfig(); const themeVars: Ref = ref(baseTheme()); - watch( - [ - () => config.getContainer?.value, - () => config.theme?.value, - () => config.themeOverrides?.value, - ], - ([getContainer, theme, themeOverrides]) => { - if (!getContainer) { - return; - } - const { themeVars: currentThemeVars } = applyTheme( - getContainer(), - theme, - themeOverrides, - ); - themeVars.value = currentThemeVars; - }, - { - immediate: true, - }, - ); + // 参考 naive-ui src/_mixins/use-theme.ts 的 SSR 处理: + // DOM 写入不在 setup 期 immediate watch 里同步执行,而是挪进 + // onBeforeMount——服务端渲染不执行生命周期钩子,结构性避免崩溃。 + onBeforeMount(() => { + watch( + [ + () => config.getContainer?.value, + () => config.theme?.value, + () => config.themeOverrides?.value, + ], + ([getContainer, theme, themeOverrides]) => { + if (!getContainer) { + return; + } + const { themeVars: currentThemeVars } = applyTheme( + getContainer(), + theme, + themeOverrides, + ); + themeVars.value = currentThemeVars; + }, + { immediate: true }, + ); + }); return { config, diff --git a/components/_util/interface.ts b/components/_util/interface.ts index d4873ca1a..ad037c48f 100644 --- a/components/_util/interface.ts +++ b/components/_util/interface.ts @@ -31,7 +31,8 @@ export type ComponentInstall = DefineComponent & { [key: string]: DefineComponent; }; -export type GetContainer = () => HTMLElement; +// 服务端渲染下 defaultContainer 返回 null(无 DOM),消费方需兼容 +export type GetContainer = () => HTMLElement | null; export type SFCWithInstall = T & Plugin; diff --git a/components/_util/isServer.ts b/components/_util/isServer.ts new file mode 100644 index 000000000..89814be20 --- /dev/null +++ b/components/_util/isServer.ts @@ -0,0 +1,10 @@ +// 参考: +// - naive-ui src/_utils/env/is-browser.ts —— typeof 判定环境 +// - element-plus packages/utils/browser.ts —— 直接复用 @vueuse/core 的 isClient +// +// fes-design 已依赖 @vueuse/core,故取 Element Plus 的做法:单一真源, +// 不自创判定。注意:isServer 在此文件作为模块级常量求值一次, +// 语义为“当前进程是否存在 DOM 全局”。 +import { isClient } from '@vueuse/core'; + +export const isServer = !isClient; diff --git a/components/_util/noticeManager.tsx b/components/_util/noticeManager.tsx index e2be6eb80..1fd14f657 100644 --- a/components/_util/noticeManager.tsx +++ b/components/_util/noticeManager.tsx @@ -18,6 +18,7 @@ import { InfoCircleFilled, } from '../icon'; import { useTheme } from '../_theme/useTheme'; +import { isServer } from './isServer'; import { getFirstValidNode } from './vnode'; let seed = 0; @@ -121,7 +122,21 @@ export function createManager(opt: { getContainer?: () => HTMLElement; [key: string]: any; }): Promise { - return new Promise((resolve) => { + return new Promise((resolve, reject) => { + // SSR:通知类命令式 API 依赖 DOM 挂载,服务端调用属于用法错误。 + // reject 而非抛裸 ReferenceError:调用方(FMessage 等)的 async + // 链路可捕获;未捕获时也会以明确的错误信息呈现, + // 不会静默丢失或半路崩溃。 + if (isServer) { + reject( + new Error( + '[NoticeManager]: 通知类命令式 API(FMessage 等)' + + ' 依赖 DOM,不能在服务端调用;请在客户端生命周期' + + '(onMounted/事件回调)中使用', + ), + ); + return; + } const { getContainer, ...props } = opt; const div = document.createElement('div'); if (getContainer) { diff --git a/components/_util/storage.ts b/components/_util/storage.ts index 9673d6038..12ba24dbb 100644 --- a/components/_util/storage.ts +++ b/components/_util/storage.ts @@ -1,3 +1,5 @@ +import { isServer } from './isServer'; + const prefixStorage = '__fesd-storage'; export function getPrefixStorage(suffix: string) { @@ -6,6 +8,11 @@ export function getPrefixStorage(suffix: string) { export type StorageType = 'local' | 'session'; -export function getStorage(type: StorageType) { +export function getStorage(type: StorageType): Storage | undefined { + // SSR:无 localStorage/sessionStorage,返回 undefined + // (调用方 useStorage 已对 undefined 做读取保护;写入仅在客户端发生) + if (isServer) { + return undefined; + } return type === 'local' ? localStorage : sessionStorage; } diff --git a/components/_util/use/useClickOutSide.ts b/components/_util/use/useClickOutSide.ts index 128861b38..ec8d33d32 100644 --- a/components/_util/use/useClickOutSide.ts +++ b/components/_util/use/useClickOutSide.ts @@ -1,5 +1,6 @@ import { type Ref, onBeforeUnmount, ref, unref, watch } from 'vue'; import getElementFromVueInstance from '../getElementFromVueInstance'; +import { isServer } from '../isServer'; export default function useClickOutSide( watchList: @@ -35,6 +36,11 @@ export default function useClickOutSide( } }; + // SSR:无 window,跳过监听注册(客户端激活后 watch 变化会重新注册) + if (isServer) { + return destroy; + } + watch( disabledRef, () => { diff --git a/components/_util/use/useEsc.ts b/components/_util/use/useEsc.ts index 975c90d31..e87de4207 100644 --- a/components/_util/use/useEsc.ts +++ b/components/_util/use/useEsc.ts @@ -1,4 +1,5 @@ import { type Ref, isRef, onBeforeUnmount, ref, watch } from 'vue'; +import { isServer } from '../isServer'; export default function useEsc( action: (event: KeyboardEvent) => void, @@ -11,6 +12,11 @@ export default function useEsc( } }; + // SSR:无 window,跳过监听注册(客户端激活后 watch 变化会重新注册) + if (isServer) { + return; + } + // 性能优化,减少事件触发次数 if (isRef(open)) { watch(open, () => { diff --git a/components/_util/use/useLockScreen.ts b/components/_util/use/useLockScreen.ts index e8d9e687a..c050dad1f 100644 --- a/components/_util/use/useLockScreen.ts +++ b/components/_util/use/useLockScreen.ts @@ -7,6 +7,7 @@ import { removeClass, } from '../dom'; import getPrefixCls from '../getPrefixCls'; +import { isServer } from '../isServer'; const cls = getPrefixCls('popup-hidden'); @@ -28,9 +29,19 @@ export default function useLockScreen(trigger: Ref) { }; onUnmounted(() => { + // SSR:无 document(钩子本身服务端不执行,此处为双保险) + if (isServer) { + return; + } cleanup(); }); + // SSR:无 document,跳过锁屏逻辑(首帧可见的弹窗由样式 v-show 控制, + // 客户端水合后本 watch 正常接管) + if (isServer) { + return; + } + watch(trigger, (val) => { if (val) { withoutHiddenClass = !hasClass(document.body, cls); diff --git a/components/_util/utils.ts b/components/_util/utils.ts index 0b174c442..d750b1013 100644 --- a/components/_util/utils.ts +++ b/components/_util/utils.ts @@ -1,10 +1,14 @@ import { nextTick } from 'vue'; import { isFinite, isNull, isString, isUndefined } from 'lodash-es'; +import { isServer } from './isServer'; export const noop = () => {}; export const noopInNoop = () => noop; -export const defaultContainer = () => document.body; +// SSR 下无 document.body,返回 null(消费方 Teleport to=null 安全跳过; +// 主题写入等 DOM 副作用各自有 isServer 守卫) +export const defaultContainer = () => + isServer ? null : document.body; export async function sleep(ms: number): Promise { return new Promise((resolve) => { diff --git a/components/collapse/common.ts b/components/collapse/common.ts index 9580cd407..8d2268aed 100644 --- a/components/collapse/common.ts +++ b/components/collapse/common.ts @@ -1,10 +1,13 @@ -import type { ComputedRef, InjectionKey, PropType, Ref } from 'vue'; +import { type ComputedRef, type InjectionKey, type PropType, type Ref, useId } from 'vue'; export const COMPONENT_NAME = 'FCollapse'; export const definePropType = (val: any): PropType => val; -export const generateId = (): number => Math.floor(Math.random() * 10000); +// 确定性 ID:useId() 基于组件树位置,SSR 与客户端水合产出相同值。 +// (旧实现 Math.random() 导致服务端/客户端两次渲染 id 不同 → +// id/aria-* 属性水合不一致告警) +export const generateId = (): string => useId(); export type CollapseActiveName = string | number; diff --git a/components/components.ts b/components/components.ts index 900752cd7..195c1c046 100644 --- a/components/components.ts +++ b/components/components.ts @@ -6,6 +6,8 @@ export * from './cascader'; export * from './checkbox'; export * from './checkbox-group'; export * from './collapse'; +// SSR 首帧主题变量注入(getThemeVarsCss / getThemeStyleTag) +export { getThemeVarsCss, getThemeStyleTag } from './_theme/applyTheme'; export * from './config-provider'; export * from './date-picker'; export * from './descriptions'; diff --git a/components/drawer/drawer.tsx b/components/drawer/drawer.tsx index 946a2e1a3..492f311a6 100644 --- a/components/drawer/drawer.tsx +++ b/components/drawer/drawer.tsx @@ -6,6 +6,7 @@ import { computed, defineComponent, nextTick, + onMounted, ref, watch, } from 'vue'; @@ -47,12 +48,29 @@ const Drawer = defineComponent({ const zIndex = ref(PopupManager.nextZIndex()); const visible = ref(false); useLockScreen(visible); + // Teleport 挂载后才激活(见 render 注释),保证 SSR 与水合首帧 + // 的 DOM 结构对称 + const teleportReady = ref(false); + onMounted(() => { + teleportReady.value = true; + }); + // 首帧同步置值(含 SSR):nextTick 推迟会在服务端单趟渲染下 + // 输出空内容(visible 永远为 false)。首帧本无过渡动画, + // 同步置值无视觉损失;后续切换仍走 nextTick 保证动画时序 + let isFirstRender = true; watch( () => props.show, () => { if (props.show) { zIndex.value = PopupManager.nextZIndex(); } + + if (isFirstRender) { + visible.value = props.show; + isFirstRender = false; + return; + } + nextTick(() => { visible.value = props.show; }); @@ -183,11 +201,18 @@ const Drawer = defineComponent({ ].filter(Boolean); }); - return () => ( - + return () => { + // Teleport 延迟激活(LazyTeleport 思路):SSR 与水合首帧 + // 就地渲染(两端对称,避免水合不匹配;且 server-renderer + // 对无 target 的 Teleport 会直接丢弃内容),挂载后激活 + // 传送,恢复正常挂载到 body 的行为。displayDirective 默认 + // 'show'(v-show 控制),首帧内容可见 + const container = getContainer.value?.(); + return ( +
{props.mask && showDom.value && ( @@ -256,7 +281,8 @@ const Drawer = defineComponent({
- ); + ); + }; }, }); diff --git a/components/empty/imgEmpty.vue b/components/empty/imgEmpty.vue index cf4fd7374..fe98b33ea 100644 --- a/components/empty/imgEmpty.vue +++ b/components/empty/imgEmpty.vue @@ -215,25 +215,15 @@