@cfp-studio/plugin-svelte 0.0.0-stage → 11.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +53 -2
- package/dist/index.d.mts +125 -0
- package/dist/index.mjs +1 -0
- package/package.json +47 -3
- package/preview/index.ts +154 -0
- package/preview/tsconfig.json +7 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Zenc Labs Pty Ltd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cfp-studio/plugin-svelte
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Svelte 框架的 CFP Studio 插件,支持 Svelte 组件/Story 静态分析、属性/类型提取、预览渲染、CSF/Storybook 兼容等。
|
|
4
|
+
|
|
5
|
+
## 特性
|
|
6
|
+
|
|
7
|
+
- 自动检测 Svelte 3.x / 4.x / 5.x 项目;**预览渲染目前只支持 3.x / 4.x**,Svelte 5 组件挂不上(renderer 仍是 Svelte ≤4 的 `new Component()` API),Svelte 5 支持已立项(方案与任务见 [`docs/spec-svelte5-support.md`](docs/spec-svelte5-support.md);缺陷档案见 `docs/bugfix/svelte-preview-polyfill-and-svelte5.md`)
|
|
8
|
+
- 支持 Svelte 组件/Story 的批量静态分析与属性/类型提取
|
|
9
|
+
- 兼容 CSF/Storybook 规范,支持 args/参数提取
|
|
10
|
+
- 支持 preview 目录下自定义 Wrapper、错误边界
|
|
11
|
+
- E2E 用例:`pnpm e2e-test`(先自动安装 `tests/apps/svelte4` fixture)
|
|
12
|
+
|
|
13
|
+
## 架构与工作原理
|
|
14
|
+
|
|
15
|
+
- 通过 `FrameworkPluginFactory` 实现插件注册与兼容性检测
|
|
16
|
+
- 使用 `createTypeAnalyzer` 进行 TS/JSX 类型分析,支持 Svelte 特殊类型适配
|
|
17
|
+
- `crawlFile` 支持单文件批量组件/Story 爬取,自动生成可预览 ID
|
|
18
|
+
- `preview/` 目录下为前端渲染入口,支持自定义 Wrapper、错误边界
|
|
19
|
+
- 支持多种 Svelte 工程模板(apps/ 下有多种测试工程)
|
|
20
|
+
|
|
21
|
+
## 主要 API/模块
|
|
22
|
+
|
|
23
|
+
- `src/index.ts`:插件主入口,注册工厂与分析器
|
|
24
|
+
- `src/crawl-file.ts`:单文件批量组件/Story 爬取
|
|
25
|
+
- `src/analyze.ts`:属性/类型/JSX 结构分析
|
|
26
|
+
- `preview/index.ts`:前端渲染入口
|
|
27
|
+
- `tests/`、`apps/`:丰富的测试与模板
|
|
28
|
+
|
|
29
|
+
## 用法示例
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { svelteFrameworkPlugin } from "@cfp-studio/plugin-svelte";
|
|
33
|
+
// 传入 core/Previewer 或 createChromelessWorkspace 等集成
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## 依赖
|
|
37
|
+
|
|
38
|
+
- `svelte`、`@sveltejs/vite-plugin-svelte`、`@cfp-studio/*`、`typescript`、`vite`
|
|
39
|
+
- 测试:`vitest`、`@playwright/test`
|
|
40
|
+
|
|
41
|
+
## 构建
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
pnpm build
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## 文档
|
|
48
|
+
|
|
49
|
+
- [`docs/README.md`](docs/README.md) — 本包文档索引
|
|
50
|
+
- [`docs/spec-svelte5-support.md`](docs/spec-svelte5-support.md) — Svelte 5 支持:renderer 双路径 + runes 静态分析(Draft)
|
|
51
|
+
|
|
52
|
+
## 许可证
|
|
53
|
+
|
|
54
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { Analyzer } from "@cfp-studio/analyzer-api";
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
import { Reader } from "@cfp-studio/vfs";
|
|
4
|
+
import * as vite from "vite";
|
|
5
|
+
|
|
6
|
+
//#region ../../engine/api/dist/index.d.mts
|
|
7
|
+
/**
|
|
8
|
+
* 定义一个框架插件信息的类型,包含插件名称和 API 版本。
|
|
9
|
+
*/
|
|
10
|
+
type FrameworkPluginInfo = {
|
|
11
|
+
name: string;
|
|
12
|
+
apiVersion: number;
|
|
13
|
+
}; //#endregion
|
|
14
|
+
//#region src/axios-api.d.ts
|
|
15
|
+
/**
|
|
16
|
+
* 创建一个基于 Axios 的 API 实例
|
|
17
|
+
* @param url - API 基础 URL
|
|
18
|
+
* @returns 实现了 Api 接口的 AxiosApi 实例
|
|
19
|
+
*/
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region ../../engine/core/dist/index.d.mts
|
|
22
|
+
//#region src/plugins/dependencies.d.ts
|
|
23
|
+
/**
|
|
24
|
+
* 定义包依赖项的类型,它是一个记录类型,键为包名,值为包含主要版本号和读取已安装版本方法的对象
|
|
25
|
+
* @typedef {Object} PackageDependencies
|
|
26
|
+
* @property {number} majorVersion - 包的主要版本号(已弃用)
|
|
27
|
+
* @property {function} readInstalledVersion - 异步读取已安装包版本的函数,返回一个 Promise,解析为字符串或 null
|
|
28
|
+
*/
|
|
29
|
+
type PackageDependencies = Record<string, {
|
|
30
|
+
/** @deprecated */majorVersion: number;
|
|
31
|
+
/**
|
|
32
|
+
* 异步读取已安装包的版本号
|
|
33
|
+
* @returns {Promise<string | null>} - 一个 Promise,解析为已安装包的版本号字符串,如果读取失败则为 null
|
|
34
|
+
*/
|
|
35
|
+
readInstalledVersion(): Promise<string | null>;
|
|
36
|
+
}>; //#endregion
|
|
37
|
+
//#region src/plugins/framework.d.ts
|
|
38
|
+
/**
|
|
39
|
+
* 定义框架插件工厂的接口。
|
|
40
|
+
* 该工厂用于创建框架插件实例,并提供检查兼容性的方法。
|
|
41
|
+
*/
|
|
42
|
+
interface FrameworkPluginFactory {
|
|
43
|
+
/**
|
|
44
|
+
* 框架插件的信息,包含插件的基本描述和元数据。
|
|
45
|
+
*/
|
|
46
|
+
info: FrameworkPluginInfo;
|
|
47
|
+
/**
|
|
48
|
+
* 检查当前项目的依赖是否与该框架插件兼容。
|
|
49
|
+
*
|
|
50
|
+
* @param dependencies - 项目的依赖包信息。**只含工程 `package.json` 里显式声明的包**
|
|
51
|
+
* (`dependencies` / `devDependencies` / `peerDependencies` 的并集),
|
|
52
|
+
* 不含传递依赖。
|
|
53
|
+
* @param rootDir - 工程根目录(可选,向后兼容)。
|
|
54
|
+
* 有些框架(如 Umi 4)**不显式声明 `react`**,而由框架包作为传递依赖带入 ——
|
|
55
|
+
* 那种情况下 `dependencies.react` 是 `undefined`,插件需要靠 `rootDir` 自行解析。
|
|
56
|
+
* 见 `docs/spec-umijs-support.md` §15。
|
|
57
|
+
* @returns 一个 Promise,解析为布尔值,表示是否兼容。
|
|
58
|
+
*/
|
|
59
|
+
isCompatible(dependencies: PackageDependencies, rootDir?: string): Promise<boolean>;
|
|
60
|
+
/**
|
|
61
|
+
* 创建框架插件实例。
|
|
62
|
+
*
|
|
63
|
+
* @param options - 创建插件所需的选项。
|
|
64
|
+
* @param options.rootDir - 项目的根目录。
|
|
65
|
+
* @param options.reader - 用于读取文件的读取器。
|
|
66
|
+
* @param options.logger - 日志记录器,用于记录插件运行时的信息。
|
|
67
|
+
* @param options.dependencies - 项目的依赖包信息。
|
|
68
|
+
* @returns 一个 Promise,解析为创建的框架插件实例。
|
|
69
|
+
*/
|
|
70
|
+
create(options: {
|
|
71
|
+
rootDir: string;
|
|
72
|
+
reader: Reader;
|
|
73
|
+
logger: Logger;
|
|
74
|
+
dependencies: PackageDependencies;
|
|
75
|
+
}): Promise<FrameworkPlugin>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* 定义框架插件的接口。
|
|
79
|
+
* 该插件继承自 Analyzer 接口,并提供了一些额外的配置和方法。
|
|
80
|
+
*/
|
|
81
|
+
interface FrameworkPlugin extends Analyzer {
|
|
82
|
+
/**
|
|
83
|
+
* 默认包装器的文件路径。
|
|
84
|
+
*/
|
|
85
|
+
defaultWrapperPath: string;
|
|
86
|
+
/**
|
|
87
|
+
* 预览目录的文件路径。
|
|
88
|
+
*/
|
|
89
|
+
previewDirPath: string;
|
|
90
|
+
/**
|
|
91
|
+
* 生成 Vite 配置的函数。
|
|
92
|
+
*
|
|
93
|
+
* @param configuredPlugins - 已配置的 Vite 插件列表。
|
|
94
|
+
* @returns Vite 用户配置对象。
|
|
95
|
+
*/
|
|
96
|
+
viteConfig: (configuredPlugins: vite.Plugin[]) => vite.UserConfig;
|
|
97
|
+
/**
|
|
98
|
+
* 该框架的**生成目录** glob,供文件爬取排除(可选)。
|
|
99
|
+
*
|
|
100
|
+
* 用于框架把代码生成到工程内的场景 —— 例如 Umi 4 的 `src/.umi`,
|
|
101
|
+
* dev server 一跑就是几万行。不排除的话它们会进组件树,
|
|
102
|
+
* 既慢又干扰(`docs/spec-umijs-support.md` G2)。
|
|
103
|
+
*
|
|
104
|
+
* 语义边界:**只是"不扫这些路径"**,不是 gitignore,也不影响文件读取
|
|
105
|
+
* (`@cfp-studio/reader` 仍能读到)。不实现该字段即保持现状。
|
|
106
|
+
*/
|
|
107
|
+
ignoredPaths?: string[];
|
|
108
|
+
/**
|
|
109
|
+
* 清理插件资源的方法。
|
|
110
|
+
* 当插件不再使用时,调用此方法释放资源。
|
|
111
|
+
*/
|
|
112
|
+
dispose(): void;
|
|
113
|
+
} //#endregion
|
|
114
|
+
//#region src/router.d.ts
|
|
115
|
+
/**
|
|
116
|
+
* 定义注册 RPC 端点的函数类型。
|
|
117
|
+
* @template E - RPC 端点的类型。
|
|
118
|
+
* @param endpoint - RPC 端点对象。
|
|
119
|
+
* @param handler - 处理该端点请求的函数。
|
|
120
|
+
*/
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/index.d.ts
|
|
123
|
+
declare const svelteFrameworkPlugin: FrameworkPluginFactory;
|
|
124
|
+
//#endregion
|
|
125
|
+
export { svelteFrameworkPlugin as default };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"path";import t from"url";import{decodePreviewableId as n,generatePreviewableId as r,wrapperPathFor as i}from"@cfp-studio/analyzer-api";import{createAnalyzer as a}from"@cfp-studio/analyzer-api/analyzer";import{svelte as o}from"@sveltejs/vite-plugin-svelte";import{polyfillNode as s}from"esbuild-plugin-polyfill-node";import c from"fs-extra";import{extractCsf3Stories as l}from"@cfp-studio/storybook-helpers";import{STRING_TYPE as u,UNKNOWN_TYPE as d,intersectionType as f,maybeOptionalType as p,objectType as m}from"@cfp-studio/type-analyzer";import h from"typescript";import{ReaderListeners as g}from"@cfp-studio/vfs";import{preprocess as _}from"svelte/compiler";function v(e,t){let n=e.sourceFile(t),r={},i={},a=[];for(let t of n?.statements||[])if(h.isVariableStatement(t)&&t.modifiers?.find(e=>e.kind===h.SyntaxKind.ExportKeyword)&&t.declarationList.flags^h.NodeFlags.Const)for(let n of t.declarationList.declarations){if(!h.isIdentifier(n.name))continue;let{type:t,collected:a}=e.resolveType(e.checker.getTypeAtLocation(n.name));r[n.name.text]=p(t,!!n.initializer),i={...i,...a}}else if(h.isTypeAliasDeclaration(t)&&t.name.text===`PJS_Slots`){let n=e.checker.getTypeAtLocation(t),r=e.resolveType(n);if(r.type.kind===`name`){let e=r.collected[r.type.name];if(e?.type.kind===`tuple`)for(let t of e.type.items)t.kind===`literal`&&typeof t.value==`string`&&a.push(t.value)}}return{props:f([m(r),m(Object.fromEntries(a.map(e=>[`slot:${e}`,u])))]),types:i}}function y(t){return e.basename(t,e.extname(t))}async function b(t,i,a,o){if(o.endsWith(`.svelte`)){let n=await t.read(o);return n?.kind===`file`?[{id:r({filePath:e.relative(a,o),name:y(o)}),sourcePosition:{start:0,end:(await n.read()).length},exported:!0,analyze:async()=>v(i,o+`.ts`)}]:[]}else{let s=i.sourceFile(o);return s?(await l(a,i,s,async r=>{let{filePath:o}=n(r),s=(await b(t,i,a,e.join(a,o))).find(e=>e.id===r);return!s||!(`exported`in s)?{props:d,types:{}}:s.analyze()})).map(e=>{if(!e.associatedComponent?.id.includes(`.svelte.ts:`))return e;let{filePath:t}=n(e.associatedComponent.id),i=x(t);return{...e,associatedComponent:{...e.associatedComponent,id:r({filePath:i,name:y(i)})}}}):[]}}function x(e){return e.substring(0,e.length-3)}function S(e){return new C(e)}var C=class{constructor(e){this.reader=e,this.listeners=new g,e.listeners.add({onChange:(e,t)=>{this.listeners.notify(e,t)}}),this.observe=e.observe?.bind(e)}async read(t){if(t.endsWith(`.svelte.ts`)){let n=await this.reader.read(t.substr(0,t.length-3));return n?.kind===`file`?{kind:`file`,name:e.basename(t),realPath:async()=>null,lastModifiedMillis:()=>n.lastModifiedMillis(),read:async()=>w(await n.read()),size:()=>n.size()}:null}let n=await this.reader.read(t);return n?.kind===`directory`?{...n,entries:async()=>{let r=await n.entries();return Promise.all([...r.map(n=>this.read(e.join(t,n.name))),...r.filter(e=>e.name.endsWith(`.svelte`)).map(n=>this.read(e.join(t,n.name+`.ts`)))]).then(e=>e.filter(Boolean))}}:n}readSync(t){if(t.endsWith(`.svelte.ts`)){let n=this.reader.readSync(t.substr(0,t.length-3));return n?.kind===`file`?{kind:`file`,name:e.basename(t),realPath:()=>null,lastModifiedMillis:()=>n.lastModifiedMillis(),read:()=>w(n.read()),size:()=>n.size()}:null}let n=this.reader.readSync(t);return n?.kind===`directory`?{...n,entries:()=>{let r=n.entries();return[...r.map(n=>this.readSync(e.join(t,n.name))),...r.filter(e=>e.name.endsWith(`.svelte`)).map(n=>this.readSync(e.join(t,n.name+`.ts`)))].filter(Boolean)}}:n}};function w(e){let t=``;_(e,[{script:({content:e})=>{t=e}}]);let n=[],r=-1;for(;r=e.indexOf(`<slot`,r+1),r!==-1;){let t=e.indexOf(`</slot>`,r);t===-1&&(t=e.indexOf(`/>`,r));let i=e.substring(r,t).match(/\sname="(.*)"/);i?n.push(i[1]):n.push(`default`)}let i=`type PJS_Slots = [${n.map(e=>JSON.stringify(e)).join(`, `)}];`;return`${t}\n${i}`}const T={info:{apiVersion:5,name:`@cfp-studio/plugin-svelte`},isCompatible:async e=>{let t=await e.svelte?.readInstalledVersion();return t?parseInt(t)>=3:!1},async create({rootDir:n,reader:r,logger:l}){let u=t.fileURLToPath(new URL(`.`,import.meta.url)),d=e.resolve(u,`..`,`preview`),f=e.join(n,`svelte.config.js`),p={},m=!1;if(await c.pathExists(f)){let e=(await import(`${t.pathToFileURL(f).href}?ts=${Date.now()}`)).default;p=e.kit?.alias||{},m=!!e.kit}return{...a({typeAnalyzerOptions:({reader:e})=>({reader:S(e)}),toTypeScriptPath:e=>e.endsWith(`.svelte`)?`${e}.ts`:e,crawlFile:({reader:e,resolver:t,rootDir:n,absoluteFilePath:r})=>b(e,t,n,r)})({rootDir:n,reader:r,logger:l}),defaultWrapperPath:i(`svelte`),previewDirPath:d,viteConfig:e=>({...m?{optimizeDeps:{esbuildOptions:{plugins:[s()]}},define:{__SVELTEKIT_DEV__:`false`,__SVELTEKIT_APP_VERSION_POLL_INTERVAL__:`0`},resolve:{alias:{$app:`node_modules/@sveltejs/kit/src/runtime/app`,...p}},publicDir:`static`}:{},plugins:[...e.filter(e=>e.name!==`vite-plugin-svelte-kit`&&e.name!==`vite-plugin-sveltekit-build`&&e.name!==`vite-plugin-sveltekit-middleware`&&e.name!==`vite-plugin-sveltekit-setup`&&e.name!==`vite-plugin-sveltekit-compile`),e.find(e=>e.name.includes(`svelte`))?null:o(),m?{name:`previewjs:fake-sveltekit-client`,transform(e,t){return t.includes(`@sveltejs/kit/src/runtime/client/singletons.js`)?e.replace(`export let client`,`export let client = {}`).replace(`url: notifiable_store({})`,`url: notifiable_store(document.location)`).replace(`page: notifiable_store({})`,`page: notifiable_store({ url: document.location })`):null}}:null,{name:`previewjs:disable-svelte-hmr`,async transform(e,t){return t.endsWith(`.svelte`)?e.replace(/import\.meta\.hot/g,`false`):null}}]})}}};export{T as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cfp-studio/plugin-svelte",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "11.1.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist",
|
|
7
|
+
"preview"
|
|
8
|
+
],
|
|
9
|
+
"type": "module",
|
|
10
|
+
"sideEffects": false,
|
|
11
|
+
"main": "./dist/index.mjs",
|
|
12
|
+
"types": "./dist/index.d.mts",
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"@sveltejs/vite-plugin-svelte": "5.0.3",
|
|
15
|
+
"esbuild-plugin-polyfill-node": "0.3.0",
|
|
16
|
+
"fs-extra": "11.3.0",
|
|
17
|
+
"svelte": "5.21.0",
|
|
18
|
+
"typescript": "5.9.3",
|
|
19
|
+
"vite": "6.4.5",
|
|
20
|
+
"@cfp-studio/analyzer-api": "0.1.14",
|
|
21
|
+
"@cfp-studio/storybook-helpers": "6.0.2",
|
|
22
|
+
"@cfp-studio/type-analyzer": "10.1.8",
|
|
23
|
+
"@cfp-studio/vfs": "2.1.8"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@playwright/test": "1.64.1",
|
|
27
|
+
"@sveltejs/kit": "2.17.3",
|
|
28
|
+
"@types/fs-extra": "11.0.4",
|
|
29
|
+
"pino": "9.11.0",
|
|
30
|
+
"pino-pretty": "11.3.0",
|
|
31
|
+
"vitest": "5.0.5",
|
|
32
|
+
"@cfp-studio/core": "1.0.9",
|
|
33
|
+
"@cfp-studio/iframe": "18.4.4",
|
|
34
|
+
"@cfp-studio/testing": "14.0.1"
|
|
35
|
+
},
|
|
36
|
+
"cfp": {
|
|
37
|
+
"domain": "web-preview",
|
|
38
|
+
"layer": "analysis"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "tsdown",
|
|
42
|
+
"release": "tsdown --minify",
|
|
43
|
+
"typecheck": "tsc --noEmit && tsc -p preview/tsconfig.json",
|
|
44
|
+
"test": "vitest run",
|
|
45
|
+
"test:watch": "vitest watch",
|
|
46
|
+
"e2e-test": "pnpm --dir tests/apps/svelte4 install --ignore-workspace --ignore-scripts && playwright test",
|
|
47
|
+
"lint": "oxlint",
|
|
48
|
+
"format": "oxfmt --write ."
|
|
49
|
+
}
|
|
6
50
|
}
|
package/preview/index.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { renderErrorPanel } from "@cfp-studio/analyzer-api";
|
|
2
|
+
import type { GetPropsFn, RendererLoader } from "@cfp-studio/iframe";
|
|
3
|
+
import { SvelteComponent } from "svelte";
|
|
4
|
+
// @ts-ignore
|
|
5
|
+
import * as si from "svelte/internal";
|
|
6
|
+
|
|
7
|
+
const root = document.getElementById("root")!;
|
|
8
|
+
let currentElement: any = null;
|
|
9
|
+
|
|
10
|
+
type Component = any;
|
|
11
|
+
|
|
12
|
+
export const loadRenderer: RendererLoader = async ({
|
|
13
|
+
wrapperModule,
|
|
14
|
+
wrapperName,
|
|
15
|
+
previewableModule,
|
|
16
|
+
previewableName,
|
|
17
|
+
shouldAbortRender,
|
|
18
|
+
}) => {
|
|
19
|
+
const isStoryModule = !!previewableModule.default?.component;
|
|
20
|
+
const Wrapper = wrapperModule?.[wrapperName || "default"] || null;
|
|
21
|
+
const Previewable = previewableModule[isStoryModule ? previewableName : "default"];
|
|
22
|
+
if (!Previewable) {
|
|
23
|
+
throw new Error(`No component or story named '${previewableName}'`);
|
|
24
|
+
}
|
|
25
|
+
const RenderComponent = isStoryModule ? Previewable.component || previewableModule.default?.component : Previewable;
|
|
26
|
+
const decorators = [...(Previewable.decorators || []), ...(previewableModule.default?.decorators || [])];
|
|
27
|
+
return {
|
|
28
|
+
render: async (getProps: GetPropsFn) => {
|
|
29
|
+
if (shouldAbortRender()) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (currentElement) {
|
|
33
|
+
currentElement.$destroy();
|
|
34
|
+
currentElement = null;
|
|
35
|
+
}
|
|
36
|
+
root.innerHTML = "";
|
|
37
|
+
const props = wrapSlotProps(
|
|
38
|
+
getProps({
|
|
39
|
+
presetGlobalProps: previewableModule.default?.args || {},
|
|
40
|
+
presetProps: Previewable.args || {},
|
|
41
|
+
}),
|
|
42
|
+
);
|
|
43
|
+
const [Decorated, decoratedProps] = decorate(RenderComponent, props, decorators.reverse());
|
|
44
|
+
// Svelte 5 有 `<svelte:boundary>`,但那是模板语法,用不了在这里;
|
|
45
|
+
// 用 try/catch 包住实例化 —— 抛错时把错误面板画进 root(`docs/todo/39`),
|
|
46
|
+
// 而不是让整片白屏(旧行为:错误冒到 runNewRender,root.innerHTML 被回滚成空)。
|
|
47
|
+
try {
|
|
48
|
+
currentElement = Wrapper
|
|
49
|
+
? new Wrapper({
|
|
50
|
+
target: root,
|
|
51
|
+
props: {
|
|
52
|
+
$$slots: createSlots({
|
|
53
|
+
default: [Decorated, decoratedProps],
|
|
54
|
+
}),
|
|
55
|
+
$$scope: {},
|
|
56
|
+
},
|
|
57
|
+
})
|
|
58
|
+
: new Decorated({
|
|
59
|
+
target: root,
|
|
60
|
+
props: decoratedProps,
|
|
61
|
+
});
|
|
62
|
+
} catch (error) {
|
|
63
|
+
renderErrorPanel(root, { error, previewableName });
|
|
64
|
+
}
|
|
65
|
+
if (Previewable.play) {
|
|
66
|
+
try {
|
|
67
|
+
await Previewable.play({ canvasElement: root });
|
|
68
|
+
} catch (e: any) {
|
|
69
|
+
// For some reason, Storybook expects to throw exceptions that should be ignored.
|
|
70
|
+
if (!e.message?.startsWith("ignoredException")) {
|
|
71
|
+
throw e;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
jsxFactory: null,
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
function wrapSlotProps(props: Record<string, any>) {
|
|
81
|
+
const result: Record<string, any> = {};
|
|
82
|
+
const slots: Record<string, any> = {};
|
|
83
|
+
for (const [key, value] of Object.entries(props)) {
|
|
84
|
+
if (key.startsWith("slot:")) {
|
|
85
|
+
const element = document.createElement("span");
|
|
86
|
+
element.innerText = value;
|
|
87
|
+
slots[key.substring(5)] = [element];
|
|
88
|
+
} else {
|
|
89
|
+
result[key] = value;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (Object.keys(slots).length > 0) {
|
|
93
|
+
result.$$slots = createSlots(slots);
|
|
94
|
+
result.$$scope = {};
|
|
95
|
+
}
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// https://storybook.js.org/docs/svelte/writing-stories/decorators
|
|
100
|
+
function decorate(Component: Component, props: any, decorators: Array<() => Component>): [Component, any] {
|
|
101
|
+
if (decorators.length === 0) {
|
|
102
|
+
return [Component, props];
|
|
103
|
+
}
|
|
104
|
+
const [rootDecoratorFn, ...remainingDecorators] = decorators;
|
|
105
|
+
const RootDecorator = rootDecoratorFn?.();
|
|
106
|
+
return [
|
|
107
|
+
RootDecorator,
|
|
108
|
+
{
|
|
109
|
+
$$slots: createSlots({
|
|
110
|
+
default: decorate(Component, props, remainingDecorators),
|
|
111
|
+
}),
|
|
112
|
+
$$scope: {},
|
|
113
|
+
},
|
|
114
|
+
];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Source: https://github.com/sveltejs/svelte/issues/2588#issuecomment-828578980
|
|
118
|
+
const createSlots = (slots: Record<string, any>) => {
|
|
119
|
+
const svelteSlots: Record<string, any> = {};
|
|
120
|
+
|
|
121
|
+
for (const slotName in slots) {
|
|
122
|
+
svelteSlots[slotName] = [createSlotFn(slots[slotName])];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function createSlotFn([ele, props = {}]: any) {
|
|
126
|
+
if (si.is_function(ele) && ele.prototype instanceof SvelteComponent) {
|
|
127
|
+
let component: any;
|
|
128
|
+
return () => ({
|
|
129
|
+
c: si.noop,
|
|
130
|
+
m(target: any, anchor: any) {
|
|
131
|
+
component = new ele({ target, props });
|
|
132
|
+
si.mount_component(component, target, anchor, null);
|
|
133
|
+
},
|
|
134
|
+
d(detaching: any) {
|
|
135
|
+
si.destroy_component(component, detaching);
|
|
136
|
+
},
|
|
137
|
+
l: si.noop,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return () => ({
|
|
141
|
+
c: si.noop,
|
|
142
|
+
m: function mount(target: any, anchor: any) {
|
|
143
|
+
si.insert(target, ele, anchor);
|
|
144
|
+
},
|
|
145
|
+
d: function destroy(detaching: any) {
|
|
146
|
+
if (detaching) {
|
|
147
|
+
si.detach(ele);
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
l: si.noop,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
return svelteSlots;
|
|
154
|
+
};
|