AI-native design editor. Open-source Figma alternative.
refactor: load the CanvasKit binary as a Vite asset (#1314)
Danila Poyarkov8a98e141b913
diff --git a/.gitignore b/.gitignoreindex 6a624767f..e0db665be 100644--- a/.gitignore+++ b/.gitignore@@ -65,9 +65,6 @@ storybook-static//public/demo.fig/desktop/icons/-# Copied from node_modules at build time-public/canvaskit.wasm-# Documentation build/cache outputpackages/docs/.vitepress/cache/packages/docs/.vitepress/dist/diff --git a/.storybook/preview.ts b/.storybook/preview.tsindex 8facf2576..bbdbcfc65 100644--- a/.storybook/preview.ts+++ b/.storybook/preview.ts@@ -2,11 +2,13 @@ import { withThemeByDataAttribute } from '@storybook/addon-themes'import type { Preview, Renderer } from '@storybook/vue3-vite'import { watch } from 'vue'+import { installCanvasKitBinary } from '@/app/editor/canvas/canvaskit'import { installBundledFonts } from '@/app/editor/fonts/bundled'import { useAppTheme } from '@/app/shell/theme'import '@/app.css'installBundledFonts()+installCanvasKitBinary()const preview: Preview = {decorators: [diff --git a/changes/1314/breaking.md b/changes/1314/breaking.mdnew file mode 100644index 000000000..dc1d1d923--- /dev/null+++ b/changes/1314/breaking.md@@ -0,0 +1 @@+- `getCanvasKit` from `@open-pencil/core/canvaskit` no longer reads Vite's `BASE_URL` to find `canvaskit.wasm` in a browser; it loads `/canvaskit.wasm` unless the host sets the URL with `setCanvasKitLocator` (for example `setCanvasKitLocator(() => wasmURL)` with `import wasmURL from 'canvaskit-wasm/bin/canvaskit.wasm?url'`) or passes `locateFile`.diff --git a/changes/1314/performance.md b/changes/1314/performance.mdnew file mode 100644index 000000000..c41c9e49a--- /dev/null+++ b/changes/1314/performance.md@@ -0,0 +1 @@+- The editor downloads and compiles CanvasKit once when it opens instead of twice.diff --git a/packages/core/src/canvaskit.ts b/packages/core/src/canvaskit.tsindex e0dca8357..ce92bf1e6 100644--- a/packages/core/src/canvaskit.ts+++ b/packages/core/src/canvaskit.ts@@ -1,28 +1,36 @@-/// <reference types="vite/client" />import CanvasKitInit, { type CanvasKit } from 'canvaskit-wasm'import { IS_BROWSER } from './constants'-let instance: CanvasKit | null = null+let instance: Promise<CanvasKit> | null = null++/**+ * Maps a CanvasKit file name (`canvaskit.wasm`) to the URL it loads from. Mirrors the font+ * manager's bundled-font locator: under Node the file is read beside the package, since+ * CanvasKit's Node loader reads `file:` URLs itself; in a browser the default expects the host+ * to serve it at the site root, and a bundling host sets its emitted URL instead.+ */+export type CanvasKitLocator = (file: string) => stringexport interface CanvasKitOptions {- locateFile?: (file: string) => string+ locateFile?: CanvasKitLocator}-export async function getCanvasKit(options?: CanvasKitOptions): Promise<CanvasKit> {- if (instance) return instance+let locator: CanvasKitLocator = (file) =>+ IS_BROWSER ? `/${file}` : new URL(file, import.meta.resolve('canvaskit-wasm')).href- const defaultLocate = (file: string) => {- // CanvasKit's Node loader reads `file:` URLs itself, so Windows paths need no conversion.- if (!IS_BROWSER) return new URL(file, import.meta.resolve('canvaskit-wasm')).href- const base = 'env' in import.meta ? import.meta.env.BASE_URL : '/'- const prefix = base === '/' ? '' : base.replace(/\/$/, '')- return `${prefix}/${file}`- }+/** Points CanvasKit at the host's copy of its files. Call before the first {@link getCanvasKit}. */+export function setCanvasKitLocator(locate: CanvasKitLocator): void {+ locator = locate+}- instance = await CanvasKitInit({- locateFile: options?.locateFile ?? defaultLocate+/** Loads CanvasKit once; callers that ask while it loads share the load, and a failed load is retried. */+export function getCanvasKit(options?: CanvasKitOptions): Promise<CanvasKit> {+ if (instance) return instance+ const loading = CanvasKitInit({ locateFile: options?.locateFile ?? locator })+ instance = loading+ loading.catch(() => {+ if (instance === loading) instance = null})-- return instance+ return loading}diff --git a/packages/docs/.vitepress/theme/landing/stage/engine-assets.ts b/packages/docs/.vitepress/theme/landing/stage/engine-assets.tsindex d60b19133..627b47aab 100644--- a/packages/docs/.vitepress/theme/landing/stage/engine-assets.ts+++ b/packages/docs/.vitepress/theme/landing/stage/engine-assets.ts@@ -1,14 +1,11 @@-import canvasKitWasm from 'canvaskit-wasm/bin/canvaskit.wasm?url'-import { getCanvasKit } from '@open-pencil/core/canvaskit'+import { installCanvasKitBinary } from '@/app/editor/canvas/canvaskit'import { installBundledFonts } from '@/app/editor/fonts/bundled'/**- * Core expects CanvasKit's binary at the site root, which the app arranges by copying it- * into `public/`. The landing imports it as an asset instead, and fonts come through the- * app's own `installBundledFonts()`, so Vite serves both in development and emits them with- * the build.+ * The landing installs the app's emitted CanvasKit binary and fonts, so Vite serves both in+ * development and emits them with the build.*/let ready: Promise<void> | null = null@@ -17,7 +14,8 @@ export function prepareEngine(): Promise<void> {if (ready) return readyconst request = (async () => {installBundledFonts()- await getCanvasKit({ locateFile: () => canvasKitWasm })+ installCanvasKitBinary()+ await getCanvasKit()})()// A failed download is tried again by the next stage rather than shared.request.catch(() => {diff --git a/packages/docs/AGENTS.md b/packages/docs/AGENTS.mdindex 2ab47809c..4c855c311 100644--- a/packages/docs/AGENTS.md+++ b/packages/docs/AGENTS.md@@ -12,7 +12,7 @@ Published VitePress site. `bun run docs:dev`, `bun run docs:build` for fast chec## Landing-- The landing page (`.vitepress/theme/landing/`) mounts the app's own components, so the site takes the app's aliases, icon plugins, and build constants from `appSourceConfig()` in `@open-pencil/vite-config` (`vite/`) and its design tokens from `src/theme/tokens.css`. CanvasKit and core's bundled fonts are Vite asset imports handed to core in `landing/stage/engine-assets.ts`; do not copy them into `public/`. Server-rendered sections must not import from `landing/stage/`; they reach it through the client-only `ui/StageFrame.vue`, whose imports are guarded by `import.meta.env.SSR` so the server build never compiles the editor.+- The landing page (`.vitepress/theme/landing/`) mounts the app's own components, so the site takes the app's aliases, icon plugins, and build constants from `appSourceConfig()` in `@open-pencil/vite-config` (`vite/`) and its design tokens from `src/theme/tokens.css`. CanvasKit and core's bundled fonts come from the app's asset installers (`installCanvasKitBinary`, `installBundledFonts`), called in `landing/stage/engine-assets.ts`; do not copy them into `public/`. Server-rendered sections must not import from `landing/stage/`; they reach it through the client-only `ui/StageFrame.vue`, whose imports are guarded by `import.meta.env.SSR` so the server build never compiles the editor.- The landing (`.vitepress/theme/landing/**`) is part of the root `tsconfig.json`, `bun run lint`, and `bun run format`, so it is checked with the app; its `#docs/*` imports resolve there to `.vitepress/*`, and it alone may import the app through `@/` (`oxlint.json` overrides).- Each landing stage is one document pinned with `provideTabEditorStore()` and one WebGL canvas that mounts once and is never unmounted. Browsers cap WebGL contexts per page, so do not use the app's two-canvas `EditorCanvas` there or mount and unmount stages on scroll (`landing/stage/StageCanvas.vue`).- The collaboration stage (`landing/stage/collab/`) joins two stages to one room through `createLocalRoom()`, an in-page `CollabRoomTransport`, and the app's own `openRoomSession()`; it never reaches the network or IndexedDB. It is the only stage with two canvases, so the page holds one more WebGL context than it has stages.diff --git a/packages/vue/example/src/main.ts b/packages/vue/example/src/main.tsindex 912d54f8d..620ea470b 100644--- a/packages/vue/example/src/main.ts+++ b/packages/vue/example/src/main.ts@@ -1,5 +1,11 @@+import canvasKitWasm from 'canvaskit-wasm/bin/canvaskit.wasm?url'import { createApp } from 'vue'+import { setCanvasKitLocator } from '@open-pencil/core/canvaskit'+import App from './App.vue'+// Vite serves CanvasKit's binary from the package and emits it with the build.+setCanvasKitLocator(() => canvasKitWasm)+createApp(App).mount('#app')diff --git a/packages/vue/example/vite.config.ts b/packages/vue/example/vite.config.tsindex b5faaf704..542515eb7 100644--- a/packages/vue/example/vite.config.ts+++ b/packages/vue/example/vite.config.ts@@ -1,25 +1,8 @@-import { resolve } from 'node:path'-import { copyFileSync, existsSync, mkdirSync } from 'node:fs'-import { defineConfig } from 'vite'import vue from '@vitejs/plugin-vue'export default defineConfig({- plugins: [- {- name: 'copy-canvaskit-wasm',- buildStart() {- const src = resolve(__dirname, '../../../node_modules/canvaskit-wasm/bin/canvaskit.wasm')- const destDir = resolve(__dirname, 'public')- const dest = resolve(destDir, 'canvaskit.wasm')- if (existsSync(src) && !existsSync(dest)) {- mkdirSync(destDir, { recursive: true })- copyFileSync(src, dest)- }- }- },- vue()- ],+ plugins: [vue()],server: {port: 3333}diff --git a/public/_headers b/public/_headersdeleted file mode 100644index 42f709955..000000000--- a/public/_headers+++ /dev/null@@ -1,2 +0,0 @@-/canvaskit.wasm- Content-Type: application/wasmdiff --git a/src/app/editor/canvas/canvaskit.ts b/src/app/editor/canvas/canvaskit.tsnew file mode 100644index 000000000..e27c70320--- /dev/null+++ b/src/app/editor/canvas/canvaskit.ts@@ -0,0 +1,12 @@+import canvasKitWasm from 'canvaskit-wasm/bin/canvaskit.wasm?url'++import { setCanvasKitLocator } from '@open-pencil/core/canvaskit'++/**+ * Importing CanvasKit's binary as an asset lets Vite serve it in development and emit a hashed+ * copy with the build, so no host keeps a second copy in `public/`. Kept apart from other+ * modules because `?url` imports only resolve in a Vite build, not in the Bun test runner.+ */+export function installCanvasKitBinary(): void {+ setCanvasKitLocator(() => canvasKitWasm)+}diff --git a/src/boot.ts b/src/boot.tsindex a5bd41856..1dc1a356a 100644--- a/src/boot.ts+++ b/src/boot.ts@@ -6,6 +6,7 @@ import { createRetainedScopePlugin } from '@open-pencil/vue'import './app.css'import { recordRuntimeError } from '@/app/diagnostics'+import { installCanvasKitBinary } from '@/app/editor/canvas/canvaskit'import { preloadFonts } from '@/app/editor/fonts'import { installBundledFonts } from '@/app/editor/fonts/bundled'import { observeBootErrors } from '@/app/shell/support/boot'@@ -22,6 +23,7 @@ import router from './router'*/export async function boot(): Promise<void> {installBundledFonts()+ installCanvasKitBinary()preloadFonts()const head = createHead()const app = createApp(App)diff --git a/vite.config.ts b/vite.config.tsindex 1159cde99..47e30709f 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -19,7 +19,6 @@ import {localAutomationToken,openPencilAutomationPlugin} from './vite/automation'-import { copyCanvasKitAssetsPlugin } from './vite/canvaskit-assets'import { cloudPortalBrandPlugin } from './vite/cloud-portal'import { aiIconCollection } from './vite/icons'import { openPencilPwaPlugin } from './vite/pwa'@@ -52,7 +51,6 @@ export default defineConfig(async ({ command, mode }) => {optimizeDeps: { include: ['ai/test'] },plugins: [rawMarkdownPlugin(),- cloudPortal ? undefined : copyCanvasKitAssetsPlugin(),tailwindcss(),Icons({ compiler: 'vue3', customCollections: { ai: aiIconCollection() } }),Components({ resolvers: [IconsResolver({ prefix: 'icon', customCollections: ['ai'] })] }),diff --git a/vite/canvaskit-assets.ts b/vite/canvaskit-assets.tsdeleted file mode 100644index 710c06401..000000000--- a/vite/canvaskit-assets.ts+++ /dev/null@@ -1,62 +0,0 @@-import { copyFileSync, createReadStream, existsSync, mkdirSync } from 'node:fs'-import { dirname, resolve } from 'node:path'--import type { Connect, Plugin, ResolvedConfig } from 'vite'--function syncWasmFromNodeModules(root: string, source: string, destination: string) {- const sourcePath = resolve(root, source)- const destinationPath = resolve(root, destination)- if (!existsSync(sourcePath)) {- console.warn(`[copy-canvaskit-wasm] Missing source (run \`bun install\`): ${sourcePath}`)- return- }- mkdirSync(dirname(destinationPath), { recursive: true })- copyFileSync(sourcePath, destinationPath)-}--function serveCanvasKitWasm(root: string): Connect.NextHandleFunction {- return (req, res, next) => {- const pathname = req.url?.split('?')[0] ?? ''- if (pathname !== '/canvaskit.wasm') {- next()- return- }-- const publicPath = resolve(root, pathname.slice(1))- const fallbackPath = resolve(root, 'node_modules/canvaskit-wasm/bin/canvaskit.wasm')- const file = existsSync(publicPath) ? publicPath : fallbackPath- if (!existsSync(file)) {- next()- return- }-- res.setHeader('Content-Type', 'application/wasm')- res.setHeader('Cache-Control', 'no-cache')- createReadStream(file).on('error', next).pipe(res)- }-}--export function copyCanvasKitAssetsPlugin(): Plugin {- let root = process.cwd()-- return {- name: 'copy-canvaskit-wasm',- enforce: 'pre',- configResolved(config: ResolvedConfig) {- root = config.root- },- buildStart() {- syncWasmFromNodeModules(- root,- 'node_modules/canvaskit-wasm/bin/canvaskit.wasm',- 'public/canvaskit.wasm'- )- },- configureServer(server) {- server.middlewares.use(serveCanvasKitWasm(server.config.root))- },- configurePreviewServer(server) {- server.middlewares.use(serveCanvasKitWasm(server.config.root))- }- }-}