Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

chore(examples): sync demo artifacts and reorganize demo entries (#6657)

白熱6d678ba08143
diff --git a/eslint.config.ts b/eslint.config.ts
index 4a369b4ad9..8cd137ae1a 100644
--- a/eslint.config.ts
+++ b/eslint.config.ts
@@ -17,6 +17,7 @@ export default antfu(
ignores: [
'mockdata/**/*.json',
'pnpm-lock.yaml',
+ 'examples/src/demos.ts',
],
stylistic: {
indent: 4,
diff --git a/examples/.gitignore b/examples/.gitignore
index bc2e208629..9a0f6625c0 100644
--- a/examples/.gitignore
+++ b/examples/.gitignore
@@ -1,3 +1,4 @@
public
!public/index.html
!public/favicon.svg
+src/demos.ts
diff --git a/examples/esbuild.config.ts b/examples/esbuild.config.ts
index 11dd0de5cc..a02280e123 100644
--- a/examples/esbuild.config.ts
+++ b/examples/esbuild.config.ts
@@ -30,6 +30,7 @@ import stylePlugin from 'esbuild-style-plugin';
import minimist from 'minimist';
import * as React from 'react';
import tailwindcss from 'tailwindcss';
+import { syncDemoArtifacts } from './scripts/sync-demos';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -100,41 +101,7 @@ if (!args.watch) {
define['process.env.BUILD_TIME'] = `"${new Date().toISOString()}"`;
}
-const entryPoints = [
- // homepage
- './src/main.tsx',
-
- // sheets
- './src/sheets/main.ts',
- './src/sheets/worker.ts',
-
- './src/sheets-no-worker/main.ts',
-
- // sheets-multi
- './src/sheets-multi/main.tsx',
-
- // sheets-multi-units
- './src/sheets-multi-units/main.ts',
-
- // sheets-uniscript
- './src/sheets-uniscript/main.ts',
-
- // sheets-webcomponent
- './src/sheets-webcomponent/main.tsx',
-
- // docs
- './src/docs/main.ts',
-
- // docs-uniscript
- './src/docs-uniscript/main.ts',
-
- // slides
- './src/slides/main.ts',
-
- // mobile sheet
- './src/mobile-s/main.ts',
- './src/mobile-s/worker.ts',
-];
+const { entryPoints } = syncDemoArtifacts();
const config: SameShape<BuildOptions, BuildOptions> = {
bundle: true,
diff --git a/examples/package.json b/examples/package.json
index 42390dac70..6ff8e6bdf9 100644
--- a/examples/package.json
+++ b/examples/package.json
@@ -8,7 +8,7 @@
"./*": "./src/*"
},
"scripts": {
- "prepare": "tsx ./scripts/generate-html.ts",
+ "prepare": "tsx ./scripts/sync-demos.ts",
"build:demo": "tsx ./esbuild.config.ts",
"dev:demo": "tsx ./esbuild.config.ts --watch",
"dev:e2e": "tsx ./esbuild.config.ts --watch --e2e",
diff --git a/examples/scripts/generate-html.ts b/examples/scripts/generate-html.ts
deleted file mode 100644
index 48c3a876c8..0000000000
--- a/examples/scripts/generate-html.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import fs from 'fs-extra';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-// eslint-disable-next-line node/prefer-global/process
-export const IS_CI = !!process.env.CI;
-
-const ESBUILD_SCRIPT = IS_CI
- ? '' :
- `
- <script>
- new EventSource('/esbuild').addEventListener('change', () => {
- console.info('reload--');
- location.reload();
- });
- </script>`;
-
-const indexTemplate = `<!doctype html>
-<html lang="en">
- <head>
- <meta charset="utf-8" />
- <meta content="width=device-width, initial-scale=1" name="viewport" />
- <title>Univer</title>
-
- <link rel="icon" type="image/x-icon" href="../favicon.svg" />
- <link rel="stylesheet" href="./main.css" />
- <style>
- html,
- body {
- height: 100%;
- margin: 0;
- font-family: Arial;
- }
- </style>${ESBUILD_SCRIPT}
- </head>
-
- <body style="overflow: hidden">
- <div id="app" style="height: 100%"></div>
-
- <script type="module" src="./main.js"></script>
- </body>
-</html>
-`;
-
-/**
- * Generate html files
- */
-async function generateHtml() {
- const __src = path.resolve(__dirname, '../src');
- fs.readdirSync(__src).forEach((dir) => {
- const __example = path.resolve(__src, dir);
- if (fs.statSync(__example).isDirectory()) {
- const __target = path.resolve(__dirname, `../public/${dir}`);
- fs.ensureDirSync(__target);
- fs.writeFileSync(path.resolve(__target, 'index.html'), indexTemplate);
- }
- });
-}
-
-generateHtml();
diff --git a/examples/scripts/sync-demos.ts b/examples/scripts/sync-demos.ts
new file mode 100644
index 0000000000..74c8fbab9e
--- /dev/null
+++ b/examples/scripts/sync-demos.ts
@@ -0,0 +1,209 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable node/prefer-global/process */
+
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import fs from 'fs-extra';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+const EXAMPLES_ROOT = path.resolve(__dirname, '..');
+const SRC_DIR = path.resolve(EXAMPLES_ROOT, 'src');
+const PUBLIC_DIR = path.resolve(EXAMPLES_ROOT, 'public');
+const GENERATED_DEMOS_FILE = path.resolve(SRC_DIR, 'demos.ts');
+
+const DEMO_MAIN_ENTRY_NAMES = ['main.ts', 'main.tsx'] as const;
+const DEMO_EXTRA_ENTRY_NAMES = ['worker.ts', 'worker.tsx'] as const;
+const IGNORED_PUBLIC_ENTRIES = new Set(['favicon.svg', 'index.html']);
+
+export const IS_CI = !!process.env.CI;
+
+const ESBUILD_SCRIPT = IS_CI
+ ? ''
+ : `
+ <script>
+ new EventSource('/esbuild').addEventListener('change', () => {
+ console.info('reload--');
+ location.reload();
+ });
+ </script>`;
+
+const indexTemplate = `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta content="width=device-width, initial-scale=1" name="viewport" />
+ <title>Univer</title>
+
+ <link rel="icon" type="image/x-icon" href="../favicon.svg" />
+ <link rel="stylesheet" href="./main.css" />
+ <style>
+ html,
+ body {
+ height: 100%;
+ margin: 0;
+ font-family: Arial;
+ }
+ </style>${ESBUILD_SCRIPT}
+ </head>
+
+ <body style="overflow: hidden">
+ <div id="app" style="height: 100%"></div>
+
+ <script type="module" src="./main.js"></script>
+ </body>
+</html>
+`;
+
+export interface DemoDefinition {
+ dir: string;
+ entryPoints: string[];
+ href: `./${string}/`;
+ title: string;
+}
+
+function formatDemoTitle(dir: string) {
+ const wordOverrides: Record<string, string> = {
+ docs: 'Docs',
+ s: 'S',
+ ui: 'UI',
+ webcomponent: 'Web Component',
+ };
+
+ return dir
+ .split('-')
+ .filter(Boolean)
+ .map((segment) => wordOverrides[segment] ?? `${segment[0].toUpperCase()}${segment.slice(1)}`)
+ .join(' ');
+}
+
+function getDemoEntryFiles(exampleDir: string) {
+ const entries: string[] = [];
+
+ for (const entryName of DEMO_MAIN_ENTRY_NAMES) {
+ if (fs.existsSync(path.resolve(exampleDir, entryName))) {
+ entries.push(entryName);
+ break;
+ }
+ }
+
+ if (!entries.length) {
+ return entries;
+ }
+
+ for (const entryName of DEMO_EXTRA_ENTRY_NAMES) {
+ if (fs.existsSync(path.resolve(exampleDir, entryName))) {
+ entries.push(entryName);
+ }
+ }
+
+ return entries;
+}
+
+export function discoverDemos() {
+ return fs.readdirSync(SRC_DIR)
+ .sort((left, right) => left.localeCompare(right))
+ .map((dir): DemoDefinition | null => {
+ const exampleDir = path.resolve(SRC_DIR, dir);
+
+ if (!fs.statSync(exampleDir).isDirectory()) {
+ return null;
+ }
+
+ const entryFiles = getDemoEntryFiles(exampleDir);
+
+ if (!entryFiles.length) {
+ return null;
+ }
+
+ return {
+ dir,
+ title: formatDemoTitle(dir),
+ href: `./${dir}/`,
+ entryPoints: entryFiles.map((entryFile) => `./src/${dir}/${entryFile}`),
+ };
+ })
+ .filter((demo): demo is DemoDefinition => demo !== null);
+}
+
+function syncDemoHtml(demos: DemoDefinition[]) {
+ fs.ensureDirSync(PUBLIC_DIR);
+
+ const activeDemoDirs = new Set(demos.map((demo) => demo.dir));
+
+ fs.readdirSync(PUBLIC_DIR).forEach((entry) => {
+ if (IGNORED_PUBLIC_ENTRIES.has(entry)) {
+ return;
+ }
+
+ const entryPath = path.resolve(PUBLIC_DIR, entry);
+
+ if (!fs.statSync(entryPath).isDirectory()) {
+ return;
+ }
+
+ if (activeDemoDirs.has(entry)) {
+ return;
+ }
+
+ if (fs.existsSync(path.resolve(entryPath, 'index.html'))) {
+ fs.removeSync(entryPath);
+ }
+ });
+
+ demos.forEach((demo) => {
+ const targetDir = path.resolve(PUBLIC_DIR, demo.dir);
+ fs.ensureDirSync(targetDir);
+ fs.writeFileSync(path.resolve(targetDir, 'index.html'), indexTemplate);
+ });
+}
+
+function syncDemosModule(demos: DemoDefinition[]) {
+ const demoImports = demos.map(({ dir, href, title }) => ({ dir, href, title }));
+
+ const content = `${[
+ '/**',
+ ' * This file is auto-generated by `./scripts/sync-demos.ts`.',
+ ' */',
+ `export const demos = ${JSON.stringify(demoImports, null, 4)} as const;`,
+ '',
+ 'export type Demo = (typeof demos)[number];',
+ '',
+ ].join('\n')}`;
+
+ fs.writeFileSync(GENERATED_DEMOS_FILE, content);
+}
+
+export function getDemoEntryPoints() {
+ return ['./src/main.tsx', ...discoverDemos().flatMap((demo) => demo.entryPoints)];
+}
+
+export function syncDemoArtifacts() {
+ const demos = discoverDemos();
+ syncDemoHtml(demos);
+ syncDemosModule(demos);
+
+ return {
+ demos,
+ entryPoints: ['./src/main.tsx', ...demos.flatMap((demo) => demo.entryPoints)],
+ };
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ syncDemoArtifacts();
+}
diff --git a/examples/src/main.tsx b/examples/src/main.tsx
index 0dc24cafb3..4a1cdae08d 100644
--- a/examples/src/main.tsx
+++ b/examples/src/main.tsx
@@ -14,13 +14,55 @@
* limitations under the License.
*/
-import { render } from '@univerjs/design';
+import { clsx, render } from '@univerjs/design';
import { defaultTheme } from '@univerjs/themes';
import { ThemeSwitcherService } from '@univerjs/ui';
+import { useState } from 'react';
import pkg from '../../package.json';
+import { demos } from './demos';
import './global.css';
+type DemoCategoryKey = 'sheets' | 'docs' | 'slides' | 'others';
+
+const CATEGORY_ORDER: DemoCategoryKey[] = ['sheets', 'docs', 'slides', 'others'];
+const PRIMARY_CATEGORY_ORDER: DemoCategoryKey[] = ['sheets', 'docs', 'slides'];
+
+const CATEGORY_TITLES: Record<DemoCategoryKey, string> = {
+ sheets: 'Sheets',
+ docs: 'Docs',
+ slides: 'Slides',
+ others: 'Others',
+};
+
+function getDemoCategory(dir: string): DemoCategoryKey {
+ if (dir.startsWith('sheets') || dir.includes('sheets')) {
+ return 'sheets';
+ }
+
+ if (dir.startsWith('docs') || dir.includes('docs')) {
+ return 'docs';
+ }
+
+ if (dir.startsWith('slides') || dir.includes('slides')) {
+ return 'slides';
+ }
+
+ return 'others';
+}
+
+const groupedDemos = CATEGORY_ORDER.map((category) => ({
+ category,
+ title: CATEGORY_TITLES[category],
+ items: demos.filter((demo) => getDemoCategory(demo.dir) === category),
+})).filter((group) => group.items.length > 0);
+
+const primaryGroups = PRIMARY_CATEGORY_ORDER.map((category) => groupedDemos.find((group) => group.category === category)).filter(
+ (group): group is (typeof groupedDemos)[number] => Boolean(group)
+);
+
+const defaultCategory = primaryGroups[0]?.category ?? groupedDemos[0]?.category ?? 'sheets';
+
// package info
// eslint-disable-next-line node/prefer-global/process
if (process.env.NODE_ENV === 'production') {
@@ -37,84 +79,118 @@ if (process.env.NODE_ENV === 'production') {
});
}
+function DemoList({ items }: { items: (typeof demos)[number][] }) {
+ return (
+ <ul>
+ {items.map((demo) => (
+ <li
+ key={demo.dir}
+ >
+ <a
+ className="
+ univer-flex univer-items-center univer-rounded-lg univer-px-4 univer-py-3 univer-no-underline
+ hover:univer-bg-slate-50
+ "
+ href={demo.href}
+ >
+ <span
+ className="
+ univer-min-w-0 univer-shrink univer-truncate univer-font-medium univer-text-slate-900
+ "
+ >
+ {demo.title}
+ </span>
+ <span
+ aria-hidden="true"
+ className="
+ univer-mx-3 univer-min-w-4 univer-flex-1 univer-border-b univer-border-dotted
+ univer-border-slate-300
+ "
+ />
+ <span className="univer-shrink-0 univer-text-sm univer-text-slate-500">{demo.dir}</span>
+ </a>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
function Examples() {
new ThemeSwitcherService().injectThemeToHead(defaultTheme);
- const demos = [{
- title: '📊 Sheets',
- href: './sheets/',
- }, {
- title: '📝 Docs',
- href: './docs/',
- }, {
- title: '📽️ Slides',
- href: './slides/',
- }, {
- title: '🗂️ Sheets No Worker',
- href: './sheets-no-worker/',
- }, {
- title: '🗂️ Sheets Multi Instance',
- href: './sheets-multi/',
- }, {
- title: '🗂️ Sheets With Webcomponent',
- href: './sheets-webcomponent/',
- }, {
- title: '🏡 Sheets Multi Units',
- href: './sheets-multi-units/',
- }, {
- title: '📄 Sheets Uniscript',
- href: './sheets-uniscript/',
- }, {
- title: '📚 Docs Uniscript',
- href: './docs-uniscript/',
- }, {
- title: '📱 Mobile',
- href: './mobile-s/',
- }];
+ const [activeCategory, setActiveCategory] = useState<DemoCategoryKey>(defaultCategory);
+ const activeGroup = primaryGroups.find((group) => group.category === activeCategory) ?? primaryGroups[0];
+ const otherGroup = groupedDemos.find((group) => group.category === 'others');
return (
- <section
- className="univer-flex univer-h-full univer-flex-col univer-items-center univer-justify-center univer-gap-6"
+ <main
+ className="
+ univer-h-screen univer-overflow-y-auto univer-bg-white univer-px-6 univer-py-10 univer-text-slate-800
+ "
>
- <header className="univer-flex univer-items-center">
- <img className="univer-w-24" src="/favicon.svg" alt="Univer" draggable={false} />
- <h1 className="univer-text-slate-700">
- <span
- className={`
- univer-bg-[linear-gradient(121deg,#0048ff_18.89%,#0c81ed_39.58%,#029dce_59.87%,#00bbb0_74.37%,#00c5a8_79.64%)]
- univer-bg-clip-text univer-text-4xl univer-text-transparent
- `}
- >
- Univer
- </span>
- <sup
- className={`
- univer-relative -univer-top-1 univer-left-2 univer-rounded-xl univer-border
- univer-border-solid univer-border-current univer-px-2 univer-py-0.5 univer-text-xs
- `}
- >
- {pkg.version}
- </sup>
- </h1>
- </header>
+ <section className="univer-mx-auto univer-max-w-3xl">
+ <header className="univer-mb-8 univer-flex univer-items-center univer-gap-4">
+ <img className="univer-w-12" src="/favicon.svg" alt="Univer" draggable={false} />
+ <div>
+ <h1 className="univer-text-3xl univer-font-semibold univer-text-slate-900">
+ Univer
+ <sup className="univer-ml-2 univer-text-sm univer-font-normal univer-text-slate-500">
+ v
+ {pkg.version}
+ </sup>
+ </h1>
+ </div>
+ </header>
- <section className="univer-container univer-flex univer-flex-wrap univer-justify-center univer-gap-6">
- {demos.map((demo) => (
- <a
- key={demo.title}
- className={`
- univer-rounded-lg univer-bg-primary-500 univer-px-6 univer-py-2.5 univer-font-medium
- univer-text-white univer-no-underline univer-shadow-sm univer-transition-all
- univer-duration-300 univer-ease-in-out
- hover:univer-scale-105 hover:univer-bg-emerald-500
- `}
- href={demo.href}
- >
- <span>{demo.title}</span>
- </a>
- ))}
+ <section className="univer-mb-8">
+ <div className="univer-mb-4 univer-flex univer-gap-2">
+ {primaryGroups.map((group) => {
+ const isActive = group.category === activeCategory;
+
+ return (
+ <button
+ key={group.category}
+ className={clsx(`
+ univer-cursor-pointer univer-rounded-full univer-border-none univer-px-4
+ univer-py-2 univer-text-sm univer-font-medium
+ `, isActive
+ ? 'univer-bg-slate-900 univer-text-white'
+ : `
+ univer-bg-white univer-font-medium univer-text-slate-700
+ hover:univer-bg-slate-50
+ `)}
+ type="button"
+ onClick={() => setActiveCategory(group.category)}
+ >
+ {group.title}
+ (
+ {group.items.length}
+ )
+ </button>
+ );
+ })}
+ </div>
+
+ {activeGroup && (
+ <section>
+ <h2 className="univer-mb-3 univer-text-lg univer-font-semibold univer-text-slate-900">
+ {activeGroup.title}
+ </h2>
+ <DemoList items={activeGroup.items} />
+ </section>
+ )}
+ </section>
+
+ {otherGroup && (
+ <section>
+ <h2 className="univer-mb-3 univer-text-lg univer-font-semibold univer-text-slate-900">
+ {otherGroup.title}
+ </h2>
+ <DemoList items={otherGroup.items} />
+ </section>
+ )}
</section>
- </section>
+ </main>
);
}
diff --git a/examples/src/mobile-s/lazy.ts b/examples/src/sheets-mobile/lazy.ts
similarity index 100%
rename from examples/src/mobile-s/lazy.ts
rename to examples/src/sheets-mobile/lazy.ts
diff --git a/examples/src/mobile-s/main.ts b/examples/src/sheets-mobile/main.ts
similarity index 100%
rename from examples/src/mobile-s/main.ts
rename to examples/src/sheets-mobile/main.ts
diff --git a/examples/src/mobile-s/worker.ts b/examples/src/sheets-mobile/worker.ts
similarity index 100%
rename from examples/src/mobile-s/worker.ts
rename to examples/src/sheets-mobile/worker.ts