Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat: Add user script loading and Add Component popup

esenginea91cc617bf20
diff --git a/editor/package.json b/editor/package.json
index f525e9887..f36fc3f6f 100644
--- a/editor/package.json
+++ b/editor/package.json
@@ -21,6 +21,7 @@
"clean": "rimraf dist"
},
"dependencies": {
+ "esbuild-wasm": "^0.27.2",
"esengine": "workspace:*",
"lucide": "^0.563.0"
},
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 77da42883..006dc91d7 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -14,6 +14,7 @@ import { registerBuiltinEditors } from './property/editors';
import { registerBuiltinSchemas } from './schemas/ComponentSchemas';
import { saveSceneToFile, loadSceneFromFile, loadSceneFromPath } from './io/SceneSerializer';
import { icons } from './utils/icons';
+import { ScriptLoader } from './scripting';
// =============================================================================
// Types
@@ -38,6 +39,7 @@ export class Editor {
private inspectorPanel_: InspectorPanel | null = null;
private sceneViewPanel_: SceneViewPanel | null = null;
private contentBrowserPanel_: ContentBrowserPanel | null = null;
+ private scriptLoader_: ScriptLoader | null = null;
private assetsPanelVisible_: boolean = true;
private outputPanelVisible_: boolean = false;
@@ -51,6 +53,10 @@ export class Editor {
this.setupLayout();
this.setupKeyboardShortcuts();
+
+ if (this.projectPath_) {
+ this.initializeScripts();
+ }
}
get projectPath(): string | null {
@@ -98,6 +104,42 @@ export class Editor {
}
}
+ // =========================================================================
+ // Script Operations
+ // =========================================================================
+
+ private async initializeScripts(): Promise<void> {
+ if (!this.projectPath_) return;
+
+ this.scriptLoader_ = new ScriptLoader({
+ projectPath: this.projectPath_,
+ onCompileError: (errors) => {
+ console.error('Script compilation errors:', errors);
+ },
+ onCompileSuccess: () => {
+ console.log('Scripts compiled successfully');
+ },
+ });
+
+ try {
+ await this.scriptLoader_.initialize();
+ await this.scriptLoader_.compileAndExecute();
+ } catch (err) {
+ console.error('Failed to initialize scripts:', err);
+ }
+ }
+
+ async reloadScripts(): Promise<boolean> {
+ if (!this.scriptLoader_) {
+ if (this.projectPath_) {
+ await this.initializeScripts();
+ return true;
+ }
+ return false;
+ }
+ return this.scriptLoader_.reload();
+ }
+
// =========================================================================
// Private Methods
// =========================================================================
diff --git a/editor/src/panels/AddComponentPopup.ts b/editor/src/panels/AddComponentPopup.ts
new file mode 100644
index 000000000..5a7f90a91
--- /dev/null
+++ b/editor/src/panels/AddComponentPopup.ts
@@ -0,0 +1,222 @@
+/**
+ * @file AddComponentPopup.ts
+ * @brief Popup for adding components to entities
+ */
+
+import { icons } from '../utils/icons';
+import {
+ getComponentsByCategory,
+ type ComponentSchema,
+ type ComponentCategory,
+} from '../schemas/ComponentSchemas';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface AddComponentPopupOptions {
+ existingComponents: string[];
+ onSelect: (componentName: string) => void;
+ onClose: () => void;
+}
+
+interface CategoryState {
+ expanded: boolean;
+}
+
+// =============================================================================
+// AddComponentPopup
+// =============================================================================
+
+export class AddComponentPopup {
+ private container_: HTMLElement;
+ private options_: AddComponentPopupOptions;
+ private searchInput_: HTMLInputElement | null = null;
+ private listContainer_: HTMLElement | null = null;
+ private categoryStates_: Map<ComponentCategory, CategoryState> = new Map([
+ ['builtin', { expanded: true }],
+ ['script', { expanded: true }],
+ ['tag', { expanded: true }],
+ ]);
+
+ constructor(container: HTMLElement, options: AddComponentPopupOptions) {
+ this.container_ = container;
+ this.options_ = options;
+ this.render();
+ this.setupEvents();
+ }
+
+ private render(): void {
+ this.container_.innerHTML = `
+ <div class="es-add-component-popup">
+ <div class="es-add-component-header">
+ <span class="es-add-component-title">Add Component</span>
+ <button class="es-btn-icon es-add-component-close" title="Close">
+ ${icons.x(14)}
+ </button>
+ </div>
+ <div class="es-add-component-search">
+ <span class="es-search-icon">${icons.search(12)}</span>
+ <input type="text" class="es-input es-search-input" placeholder="Search components..." />
+ </div>
+ <div class="es-add-component-list"></div>
+ </div>
+ `;
+
+ this.searchInput_ = this.container_.querySelector('.es-search-input');
+ this.listContainer_ = this.container_.querySelector('.es-add-component-list');
+ this.renderList();
+ }
+
+ private renderList(filter: string = ''): void {
+ if (!this.listContainer_) return;
+
+ const components = getComponentsByCategory();
+ const filterLower = filter.toLowerCase();
+ const existing = new Set(this.options_.existingComponents);
+
+ let html = '';
+
+ const renderCategory = (
+ category: ComponentCategory,
+ label: string,
+ schemas: ComponentSchema[],
+ iconFn: () => string
+ ) => {
+ const filtered = schemas.filter(s =>
+ !existing.has(s.name) &&
+ s.name.toLowerCase().includes(filterLower)
+ );
+
+ if (filtered.length === 0 && filter) return '';
+
+ const state = this.categoryStates_.get(category)!;
+ const chevron = state.expanded ? icons.chevronDown(12) : icons.chevronRight(12);
+ const itemsClass = state.expanded ? '' : 'es-hidden';
+
+ let categoryHtml = `
+ <div class="es-component-category" data-category="${category}">
+ <div class="es-category-header">
+ <span class="es-category-chevron">${chevron}</span>
+ <span class="es-category-label">${label}</span>
+ <span class="es-category-count">${filtered.length}</span>
+ </div>
+ <div class="es-category-items ${itemsClass}">
+ `;
+
+ for (const schema of filtered) {
+ categoryHtml += `
+ <div class="es-component-item" data-component="${schema.name}">
+ <span class="es-component-icon">${iconFn()}</span>
+ <span class="es-component-name">${schema.name}</span>
+ </div>
+ `;
+ }
+
+ categoryHtml += `
+ </div>
+ </div>
+ `;
+
+ return categoryHtml;
+ };
+
+ html += renderCategory('builtin', 'Built-in', components.builtin, () => icons.box(14));
+ html += renderCategory('script', 'Scripts', components.script, () => icons.cog(14));
+ html += renderCategory('tag', 'Tags', components.tag, () => icons.tag(14));
+
+ if (!html.trim()) {
+ html = '<div class="es-no-components">No components available</div>';
+ }
+
+ this.listContainer_.innerHTML = html;
+ }
+
+ private setupEvents(): void {
+ this.searchInput_?.addEventListener('input', () => {
+ this.renderList(this.searchInput_?.value ?? '');
+ });
+
+ this.container_.querySelector('.es-add-component-close')?.addEventListener('click', () => {
+ this.options_.onClose();
+ });
+
+ this.listContainer_?.addEventListener('click', (e) => {
+ const target = e.target as HTMLElement;
+
+ const categoryHeader = target.closest('.es-category-header');
+ if (categoryHeader) {
+ const category = categoryHeader.closest('.es-component-category')?.getAttribute('data-category') as ComponentCategory;
+ if (category) {
+ this.toggleCategory(category);
+ }
+ return;
+ }
+
+ const componentItem = target.closest('.es-component-item') as HTMLElement;
+ if (componentItem) {
+ const name = componentItem.dataset.component;
+ if (name) {
+ this.options_.onSelect(name);
+ this.options_.onClose();
+ }
+ }
+ });
+
+ document.addEventListener('keydown', this.handleKeyDown);
+ setTimeout(() => this.searchInput_?.focus(), 0);
+ }
+
+ private handleKeyDown = (e: KeyboardEvent): void => {
+ if (e.key === 'Escape') {
+ this.options_.onClose();
+ }
+ };
+
+ private toggleCategory(category: ComponentCategory): void {
+ const state = this.categoryStates_.get(category);
+ if (state) {
+ state.expanded = !state.expanded;
+ this.renderList(this.searchInput_?.value ?? '');
+ }
+ }
+
+ dispose(): void {
+ document.removeEventListener('keydown', this.handleKeyDown);
+ this.container_.innerHTML = '';
+ }
+}
+
+// =============================================================================
+// Overlay Helper
+// =============================================================================
+
+export function showAddComponentPopup(
+ existingComponents: string[],
+ onSelect: (componentName: string) => void
+): void {
+ const overlay = document.createElement('div');
+ overlay.className = 'es-popup-overlay';
+
+ const container = document.createElement('div');
+ container.className = 'es-popup-container';
+ overlay.appendChild(container);
+ document.body.appendChild(overlay);
+
+ const close = () => {
+ popup.dispose();
+ overlay.remove();
+ };
+
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) {
+ close();
+ }
+ });
+
+ const popup = new AddComponentPopup(container, {
+ existingComponents,
+ onSelect,
+ onClose: close,
+ });
+}
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index 996dc077d..8e9903694 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -10,8 +10,9 @@ import {
createPropertyEditor,
type PropertyEditorInstance,
} from '../property/PropertyEditor';
-import { getComponentSchema, getAllComponentSchemas } from '../schemas/ComponentSchemas';
+import { getComponentSchema } from '../schemas/ComponentSchemas';
import { icons } from '../utils/icons';
+import { showAddComponentPopup } from './AddComponentPopup';
// =============================================================================
// Types
@@ -442,49 +443,16 @@ export class InspectorPanel {
}
private showAddComponentMenu(
- anchor: HTMLElement,
+ _anchor: HTMLElement,
entity: Entity,
existingComponents: ComponentData[]
): void {
- const existingTypes = new Set(existingComponents.map(c => c.type));
- const availableSchemas = getAllComponentSchemas().filter(
- s => !existingTypes.has(s.name)
- );
-
- if (availableSchemas.length === 0) return;
-
- const existingMenu = document.querySelector('.es-context-menu');
- existingMenu?.remove();
-
- const rect = anchor.getBoundingClientRect();
- const menu = document.createElement('div');
- menu.className = 'es-context-menu';
- menu.style.left = `${rect.left}px`;
- menu.style.top = `${rect.bottom}px`;
-
- availableSchemas.forEach(schema => {
- const item = document.createElement('div');
- item.className = 'es-context-menu-item';
- item.textContent = schema.name;
-
- item.addEventListener('click', () => {
- const defaultData = this.createDefaultComponentData(schema.name);
- this.store_.addComponent(entity, schema.name, defaultData);
- menu.remove();
- });
+ const existingTypes = existingComponents.map(c => c.type);
- menu.appendChild(item);
+ showAddComponentPopup(existingTypes, (componentName: string) => {
+ const defaultData = this.createDefaultComponentData(componentName);
+ this.store_.addComponent(entity, componentName, defaultData);
});
-
- document.body.appendChild(menu);
-
- const closeMenu = (e: MouseEvent) => {
- if (!menu.contains(e.target as Node)) {
- menu.remove();
- document.removeEventListener('click', closeMenu);
- }
- };
- setTimeout(() => document.addEventListener('click', closeMenu), 0);
}
private createDefaultComponentData(type: string): Record<string, unknown> {
@@ -609,7 +577,7 @@ export class InspectorPanel {
const ext = getFileExtension(path);
const mimeType = getMimeType(ext);
- const blob = new Blob([data], { type: mimeType });
+ const blob = new Blob([new Uint8Array(data).buffer], { type: mimeType });
const url = URL.createObjectURL(blob);
this.currentImageUrl_ = url;
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.ts
index c759a6b6e..b4d11c6fa 100644
--- a/editor/src/schemas/ComponentSchemas.ts
+++ b/editor/src/schemas/ComponentSchemas.ts
@@ -9,17 +9,50 @@ import type { PropertyMeta } from '../property/PropertyEditor';
// Types
// =============================================================================
+export type ComponentCategory = 'builtin' | 'script' | 'tag';
+
export interface ComponentSchema {
name: string;
+ category: ComponentCategory;
properties: PropertyMeta[];
}
+// =============================================================================
+// Type Inference
+// =============================================================================
+
+function isVec2(v: unknown): boolean {
+ return typeof v === 'object' && v !== null &&
+ 'x' in v && 'y' in v && !('z' in v);
+}
+
+function isVec3(v: unknown): boolean {
+ return typeof v === 'object' && v !== null &&
+ 'x' in v && 'y' in v && 'z' in v && !('w' in v);
+}
+
+function isVec4OrColor(v: unknown): boolean {
+ return typeof v === 'object' && v !== null &&
+ 'x' in v && 'y' in v && 'z' in v && 'w' in v;
+}
+
+function inferPropertyType(value: unknown): string {
+ if (typeof value === 'number') return 'number';
+ if (typeof value === 'string') return 'string';
+ if (typeof value === 'boolean') return 'boolean';
+ if (isVec2(value)) return 'vec2';
+ if (isVec3(value)) return 'vec3';
+ if (isVec4OrColor(value)) return 'vec4';
+ return 'string';
+}
+
// =============================================================================
// Built-in Schemas
// =============================================================================
export const LocalTransformSchema: ComponentSchema = {
name: 'LocalTransform',
+ category: 'builtin',
properties: [
{ name: 'position', type: 'vec3' },
{ name: 'rotation', type: 'euler' },
@@ -29,6 +62,7 @@ export const LocalTransformSchema: ComponentSchema = {
export const SpriteSchema: ComponentSchema = {
name: 'Sprite',
+ category: 'builtin',
properties: [
{ name: 'texture', type: 'number' },
{ name: 'color', type: 'color' },
@@ -43,6 +77,7 @@ export const SpriteSchema: ComponentSchema = {
export const CameraSchema: ComponentSchema = {
name: 'Camera',
+ category: 'builtin',
properties: [
{ name: 'isActive', type: 'boolean' },
{
@@ -62,6 +97,7 @@ export const CameraSchema: ComponentSchema = {
export const TextSchema: ComponentSchema = {
name: 'Text',
+ category: 'builtin',
properties: [
{ name: 'content', type: 'string' },
{ name: 'fontSize', type: 'number', min: 8, max: 200 },
@@ -106,9 +142,65 @@ export function getAllComponentSchemas(): ComponentSchema[] {
return Array.from(schemaRegistry.values());
}
+export interface ComponentsByCategory {
+ builtin: ComponentSchema[];
+ script: ComponentSchema[];
+ tag: ComponentSchema[];
+}
+
+export function getComponentsByCategory(): ComponentsByCategory {
+ const result: ComponentsByCategory = { builtin: [], script: [], tag: [] };
+ for (const schema of schemaRegistry.values()) {
+ result[schema.category].push(schema);
+ }
+ result.builtin.sort((a, b) => a.name.localeCompare(b.name));
+ result.script.sort((a, b) => a.name.localeCompare(b.name));
+ result.tag.sort((a, b) => a.name.localeCompare(b.name));
+ return result;
+}
+
+export function clearScriptComponents(): void {
+ for (const [name, schema] of schemaRegistry.entries()) {
+ if (schema.category === 'script' || schema.category === 'tag') {
+ schemaRegistry.delete(name);
+ }
+ }
+}
+
+// =============================================================================
+// User Component Registration
+// =============================================================================
+
+function registerUserComponent(
+ name: string,
+ defaults: Record<string, unknown>,
+ isTag: boolean
+): void {
+ const schema: ComponentSchema = {
+ name,
+ category: isTag ? 'tag' : 'script',
+ properties: isTag ? [] : Object.entries(defaults).map(([key, value]) => ({
+ name: key,
+ type: inferPropertyType(value),
+ })),
+ };
+ schemaRegistry.set(name, schema);
+}
+
+function exposeRegistrationAPI(): void {
+ if (typeof window !== 'undefined') {
+ (window as any).__esengine_registerComponent = registerUserComponent;
+ }
+}
+
+// =============================================================================
+// Initialization
+// =============================================================================
+
export function registerBuiltinSchemas(): void {
registerComponentSchema(LocalTransformSchema);
registerComponentSchema(SpriteSchema);
registerComponentSchema(CameraSchema);
registerComponentSchema(TextSchema);
+ exposeRegistrationAPI();
}
diff --git a/editor/src/scripting/ScriptLoader.ts b/editor/src/scripting/ScriptLoader.ts
new file mode 100644
index 000000000..07d7327c9
--- /dev/null
+++ b/editor/src/scripting/ScriptLoader.ts
@@ -0,0 +1,186 @@
+/**
+ * @file ScriptLoader.ts
+ * @brief Load and compile user TypeScript scripts
+ */
+
+import * as esbuild from 'esbuild-wasm/esm/browser';
+import { virtualFsPlugin } from './esbuildPlugins';
+import type { NativeFS, ScriptLoaderOptions, CompileError } from './types';
+import { clearScriptComponents } from '../schemas/ComponentSchemas';
+
+// =============================================================================
+// Path Utilities
+// =============================================================================
+
+function normalizePath(path: string): string {
+ return path.replace(/\\/g, '/');
+}
+
+function joinPath(...parts: string[]): string {
+ return normalizePath(parts.join('/').replace(/\/+/g, '/'));
+}
+
+function getProjectDir(projectPath: string): string {
+ const normalized = normalizePath(projectPath);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+}
+
+// =============================================================================
+// Native FS Access
+// =============================================================================
+
+function getNativeFS(): NativeFS | null {
+ return (window as any).__esengine_fs ?? null;
+}
+
+// =============================================================================
+// Script Loader
+// =============================================================================
+
+export class ScriptLoader {
+ private projectPath_: string;
+ private projectDir_: string;
+ private initialized_ = false;
+ private onCompileError_?: (errors: CompileError[]) => void;
+ private onCompileSuccess_?: () => void;
+
+ constructor(options: ScriptLoaderOptions) {
+ this.projectPath_ = normalizePath(options.projectPath);
+ this.projectDir_ = getProjectDir(this.projectPath_);
+ this.onCompileError_ = options.onCompileError;
+ this.onCompileSuccess_ = options.onCompileSuccess;
+ }
+
+ async initialize(): Promise<void> {
+ if (this.initialized_) return;
+
+ try {
+ await esbuild.initialize({
+ wasmURL: 'https://cdn.jsdelivr.net/npm/[email protected]/esbuild.wasm',
+ });
+ this.initialized_ = true;
+ } catch (err) {
+ if (String(err).includes('Cannot call "initialize" more than once')) {
+ this.initialized_ = true;
+ } else {
+ throw err;
+ }
+ }
+ }
+
+ async discoverScripts(): Promise<string[]> {
+ const fs = getNativeFS();
+ if (!fs) {
+ console.warn('ScriptLoader: NativeFS not available');
+ return [];
+ }
+
+ const scriptsPath = joinPath(this.projectDir_, 'assets/scripts');
+
+ try {
+ const exists = await fs.exists(scriptsPath);
+ if (!exists) {
+ return [];
+ }
+
+ const entries = await fs.listDirectoryDetailed(scriptsPath);
+ return entries
+ .filter(e => !e.isDirectory && e.name.endsWith('.ts'))
+ .map(e => joinPath(scriptsPath, e.name));
+ } catch (err) {
+ console.error('ScriptLoader: Failed to discover scripts:', err);
+ return [];
+ }
+ }
+
+ async compileAndExecute(): Promise<boolean> {
+ const fs = getNativeFS();
+ if (!fs) {
+ console.warn('ScriptLoader: NativeFS not available');
+ return false;
+ }
+
+ const scripts = await this.discoverScripts();
+ if (scripts.length === 0) {
+ console.log('ScriptLoader: No scripts found');
+ return true;
+ }
+
+ console.log('ScriptLoader: Compiling scripts:', scripts);
+
+ clearScriptComponents();
+
+ try {
+ const entryContent = scripts
+ .map(p => `import "${p}";`)
+ .join('\n');
+
+ const result = await esbuild.build({
+ stdin: {
+ contents: entryContent,
+ loader: 'ts',
+ resolveDir: joinPath(this.projectDir_, 'assets/scripts'),
+ },
+ bundle: true,
+ format: 'iife',
+ write: false,
+ platform: 'browser',
+ target: 'es2020',
+ plugins: [
+ virtualFsPlugin({
+ fs,
+ projectDir: this.projectDir_,
+ }),
+ ],
+ });
+
+ if (result.errors.length > 0) {
+ const errors: CompileError[] = result.errors.map(e => ({
+ file: e.location?.file || 'unknown',
+ line: e.location?.line || 0,
+ column: e.location?.column || 0,
+ message: e.text,
+ }));
+ console.error('ScriptLoader: Compilation errors:', errors);
+ this.onCompileError_?.(errors);
+ return false;
+ }
+
+ const code = result.outputFiles?.[0]?.text;
+ if (!code) {
+ console.error('ScriptLoader: No output generated');
+ return false;
+ }
+
+ this.executeScript(code);
+ console.log('ScriptLoader: Scripts loaded successfully');
+ this.onCompileSuccess_?.();
+ return true;
+ } catch (err) {
+ console.error('ScriptLoader: Compilation failed:', err);
+ const errors: CompileError[] = [{
+ file: 'unknown',
+ line: 0,
+ column: 0,
+ message: String(err),
+ }];
+ this.onCompileError_?.(errors);
+ return false;
+ }
+ }
+
+ private executeScript(code: string): void {
+ try {
+ const fn = new Function(code);
+ fn();
+ } catch (err) {
+ console.error('ScriptLoader: Script execution error:', err);
+ throw err;
+ }
+ }
+
+ async reload(): Promise<boolean> {
+ return this.compileAndExecute();
+ }
+}
diff --git a/editor/src/scripting/esbuildPlugins.ts b/editor/src/scripting/esbuildPlugins.ts
new file mode 100644
index 000000000..e9690258a
--- /dev/null
+++ b/editor/src/scripting/esbuildPlugins.ts
@@ -0,0 +1,151 @@
+/**
+ * @file esbuildPlugins.ts
+ * @brief esbuild plugins for virtual file system and SDK shim
+ */
+
+import type * as esbuild from 'esbuild-wasm';
+import type { NativeFS } from './types';
+
+// =============================================================================
+// Path Utilities
+// =============================================================================
+
+function normalizePath(path: string): string {
+ return path.replace(/\\/g, '/');
+}
+
+function joinPath(...parts: string[]): string {
+ return normalizePath(parts.join('/').replace(/\/+/g, '/'));
+}
+
+function dirname(path: string): string {
+ const normalized = normalizePath(path);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+}
+
+function resolvePath(from: string, to: string): string {
+ if (!to.startsWith('.')) {
+ return to;
+ }
+
+ const fromDir = dirname(from);
+ const parts = fromDir.split('/');
+ const toParts = to.split('/');
+
+ for (const part of toParts) {
+ if (part === '..') {
+ parts.pop();
+ } else if (part !== '.') {
+ parts.push(part);
+ }
+ }
+
+ return parts.join('/');
+}
+
+// =============================================================================
+// Virtual FS Plugin
+// =============================================================================
+
+export interface VirtualFsPluginOptions {
+ fs: NativeFS;
+ projectDir: string;
+}
+
+export function virtualFsPlugin(options: VirtualFsPluginOptions): esbuild.Plugin {
+ const { fs, projectDir } = options;
+ const nodeModulesPath = joinPath(projectDir, 'node_modules');
+ const NS = 'virtual';
+
+ return {
+ name: 'virtual-fs',
+ setup(build) {
+ // Absolute paths must be resolved before npm packages filter matches them
+ build.onResolve({ filter: /^\// }, (args) => {
+ return { path: args.path, namespace: NS };
+ });
+
+ build.onResolve({ filter: /^[A-Za-z]:/ }, (args) => {
+ return { path: normalizePath(args.path), namespace: NS };
+ });
+
+ build.onResolve({ filter: /^[^./]/ }, async (args) => {
+ if (/^[A-Za-z]:/.test(args.path)) return undefined;
+
+ const pkgName = args.path.startsWith('@')
+ ? args.path.split('/').slice(0, 2).join('/')
+ : args.path.split('/')[0];
+
+ const subpath = args.path.startsWith('@')
+ ? args.path.split('/').slice(2).join('/')
+ : args.path.split('/').slice(1).join('/');
+
+ const pkgJsonPath = joinPath(nodeModulesPath, pkgName, 'package.json');
+
+ try {
+ const pkgJsonContent = await fs.readFile(pkgJsonPath);
+ if (!pkgJsonContent) {
+ return { errors: [{ text: `Package not found: ${pkgName}` }] };
+ }
+
+ const pkgJson = JSON.parse(pkgJsonContent);
+ const entryFile = subpath || pkgJson.module || pkgJson.main || 'index.js';
+ const entryPath = joinPath(nodeModulesPath, pkgName, entryFile);
+ return { path: entryPath, namespace: NS };
+ } catch {
+ return { errors: [{ text: `Cannot resolve package: ${args.path}` }] };
+ }
+ });
+
+ build.onResolve({ filter: /^\./, namespace: NS }, async (args) => {
+ let resolved = resolvePath(args.importer || args.resolveDir, args.path);
+
+ if (!resolved.match(/\.(ts|tsx|js|jsx|json|mjs|cjs)$/)) {
+ const tsPath = resolved + '.ts';
+ if (await fs.exists(tsPath)) {
+ resolved = tsPath;
+ } else {
+ const jsPath = resolved + '.js';
+ if (await fs.exists(jsPath)) {
+ resolved = jsPath;
+ } else {
+ const indexTsPath = joinPath(resolved, 'index.ts');
+ if (await fs.exists(indexTsPath)) {
+ resolved = indexTsPath;
+ } else {
+ resolved = resolved + '.ts';
+ }
+ }
+ }
+ }
+
+ return { path: resolved, namespace: NS };
+ });
+
+ build.onLoad({ filter: /.*/, namespace: NS }, async (args) => {
+ const content = await fs.readFile(args.path);
+ if (content === null) {
+ return { errors: [{ text: `File not found: ${args.path}` }] };
+ }
+
+ let loader: esbuild.Loader = 'js';
+ if (args.path.endsWith('.ts') || args.path.endsWith('.tsx')) {
+ loader = 'ts';
+ } else if (args.path.endsWith('.json')) {
+ loader = 'json';
+ } else if (args.path.endsWith('.jsx')) {
+ loader = 'jsx';
+ } else if (args.path.endsWith('.css')) {
+ loader = 'css';
+ }
+
+ return {
+ contents: content,
+ loader,
+ resolveDir: dirname(args.path),
+ };
+ });
+ },
+ };
+}
diff --git a/editor/src/scripting/index.ts b/editor/src/scripting/index.ts
new file mode 100644
index 000000000..47cac6af2
--- /dev/null
+++ b/editor/src/scripting/index.ts
@@ -0,0 +1,7 @@
+/**
+ * @file index.ts
+ * @brief Scripting module exports
+ */
+
+export { ScriptLoader } from './ScriptLoader';
+export type { ScriptLoaderOptions, CompileError, CompileResult } from './types';
diff --git a/editor/src/scripting/types.ts b/editor/src/scripting/types.ts
new file mode 100644
index 000000000..8f27233a8
--- /dev/null
+++ b/editor/src/scripting/types.ts
@@ -0,0 +1,43 @@
+/**
+ * @file types.ts
+ * @brief Script loader type definitions
+ */
+
+// =============================================================================
+// Native FS Interface
+// =============================================================================
+
+export interface DirectoryEntry {
+ name: string;
+ isDirectory: boolean;
+ isFile: boolean;
+}
+
+export interface NativeFS {
+ readFile(path: string): Promise<string | null>;
+ listDirectoryDetailed(path: string): Promise<DirectoryEntry[]>;
+ exists(path: string): Promise<boolean>;
+}
+
+// =============================================================================
+// Script Loader Types
+// =============================================================================
+
+export interface CompileResult {
+ success: boolean;
+ code?: string;
+ errors?: CompileError[];
+}
+
+export interface CompileError {
+ file: string;
+ line: number;
+ column: number;
+ message: string;
+}
+
+export interface ScriptLoaderOptions {
+ projectPath: string;
+ onCompileError?: (errors: CompileError[]) => void;
+ onCompileSuccess?: () => void;
+}
diff --git a/editor/src/styles/editor.css b/editor/src/styles/editor.css
index 8e9623d0d..0c6328dc8 100644
--- a/editor/src/styles/editor.css
+++ b/editor/src/styles/editor.css
@@ -1766,3 +1766,186 @@ svg {
background: #e5c07b;
border-color: #e5c07b;
}
+
+/* =============================================================================
+ * Add Component Popup
+ * ============================================================================= */
+
+.es-popup-overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ background: rgba(0, 0, 0, 0.5);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 10000;
+}
+
+.es-popup-container {
+ max-width: 400px;
+ width: 90%;
+ max-height: 80vh;
+}
+
+.es-add-component-popup {
+ background: var(--es-bg-secondary);
+ border: 1px solid var(--es-border);
+ border-radius: 6px;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ max-height: 80vh;
+}
+
+.es-add-component-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 16px;
+ border-bottom: 1px solid var(--es-border);
+ background: var(--es-bg-tertiary);
+}
+
+.es-add-component-title {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--es-text-primary);
+}
+
+.es-add-component-close {
+ background: none;
+ border: none;
+ cursor: pointer;
+ padding: 4px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 4px;
+}
+
+.es-add-component-close:hover {
+ background: var(--es-bg-hover);
+}
+
+.es-add-component-close svg {
+ stroke: var(--es-text-secondary);
+}
+
+.es-add-component-close:hover svg {
+ stroke: var(--es-text-primary);
+}
+
+.es-add-component-search {
+ display: flex;
+ align-items: center;
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--es-border);
+ gap: 8px;
+}
+
+.es-search-icon svg {
+ stroke: var(--es-text-secondary);
+}
+
+.es-add-component-search .es-search-input {
+ flex: 1;
+ background: transparent;
+ border: none;
+ color: var(--es-text-primary);
+ font-size: 13px;
+ outline: none;
+}
+
+.es-add-component-search .es-search-input::placeholder {
+ color: var(--es-text-secondary);
+}
+
+.es-add-component-list {
+ overflow-y: auto;
+ max-height: 400px;
+ padding: 8px 0;
+}
+
+.es-component-category {
+ margin-bottom: 4px;
+}
+
+.es-category-header {
+ display: flex;
+ align-items: center;
+ padding: 6px 12px;
+ cursor: pointer;
+ user-select: none;
+ gap: 6px;
+}
+
+.es-category-header:hover {
+ background: var(--es-bg-hover);
+}
+
+.es-category-chevron svg {
+ stroke: var(--es-text-secondary);
+}
+
+.es-category-label {
+ flex: 1;
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ color: var(--es-text-secondary);
+}
+
+.es-category-count {
+ font-size: 11px;
+ color: var(--es-text-secondary);
+ background: var(--es-bg-tertiary);
+ padding: 1px 6px;
+ border-radius: 10px;
+}
+
+.es-category-items {
+ padding-left: 12px;
+}
+
+.es-category-items.es-hidden {
+ display: none;
+}
+
+.es-component-item {
+ display: flex;
+ align-items: center;
+ padding: 6px 12px;
+ cursor: pointer;
+ gap: 8px;
+ border-radius: 4px;
+ margin: 2px 8px;
+}
+
+.es-component-item:hover {
+ background: var(--es-bg-hover);
+}
+
+.es-component-icon svg {
+ stroke: var(--es-text-secondary);
+}
+
+.es-component-item:hover .es-component-icon svg {
+ stroke: var(--es-accent);
+}
+
+.es-component-name {
+ font-size: 13px;
+ color: var(--es-text-primary);
+}
+
+.es-no-components {
+ padding: 24px;
+ text-align: center;
+ color: var(--es-text-secondary);
+ font-size: 13px;
+}
diff --git a/editor/src/utils/icons.ts b/editor/src/utils/icons.ts
index 8b54b1d1f..801b52814 100644
--- a/editor/src/utils/icons.ts
+++ b/editor/src/utils/icons.ts
@@ -40,6 +40,8 @@ import {
Volume2,
Braces,
MousePointer2,
+ Tag,
+ Cog,
} from 'lucide';
// =============================================================================
@@ -110,6 +112,8 @@ export const icons = {
pointer: (size?: number) => renderIcon(MousePointer2 as IconNode, size),
rotateCw: (size?: number) => renderIcon(RotateCw as IconNode, size),
maximize: (size?: number) => renderIcon(Maximize as IconNode, size),
+ tag: (size?: number) => renderIcon(Tag as IconNode, size),
+ cog: (size?: number) => renderIcon(Cog as IconNode, size),
};
export type IconName = keyof typeof icons;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 75d1aa26b..b28f6e57a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -39,6 +39,9 @@ importers:
editor:
dependencies:
+ esbuild-wasm:
+ specifier: ^0.27.2
+ version: 0.27.2
esengine:
specifier: workspace:*
version: link:../sdk
@@ -551,6 +554,11 @@ packages:
resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}
+ resolution: {integrity: sha512-eUTnl8eh+v8UZIZh4MrMOKDAc8Lm7+NqP3pyuTORGFY1s/o9WoiJgKnwXy+te2J3hX7iRbFSHEyig7GsPeeJyw==}
+ engines: {node: '>=18'}
+ hasBin: true
+
resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==}
engines: {node: '>=12'}
@@ -1057,6 +1065,8 @@ snapshots:
+
optionalDependencies:
'@esbuild/aix-ppc64': 0.21.5
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index a3ed16ef9..0da916c48 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -19,7 +19,7 @@ export interface ComponentDef<T> {
let componentCounter = 0;
-export function defineComponent<T extends object>(
+function createComponentDef<T extends object>(
name: string,
defaults: T
): ComponentDef<T> {
@@ -28,15 +28,36 @@ export function defineComponent<T extends object>(
_id: Symbol(`Component_${id}_${name}`),
_name: name,
_default: defaults,
- _builtin: false,
+ _builtin: false as const,
create(data?: Partial<T>): T {
return { ...defaults, ...data };
}
};
}
+export function defineComponent<T extends object>(
+ name: string,
+ defaults: T
+): ComponentDef<T> {
+ const def = createComponentDef(name, defaults);
+ registerToEditor(name, defaults as Record<string, unknown>, false);
+ return def;
+}
+
export function defineTag(name: string): ComponentDef<{}> {
- return defineComponent(name, {});
+ const def = createComponentDef(name, {});
+ registerToEditor(name, {}, true);
+ return def;
+}
+
+function registerToEditor(
+ name: string,
+ defaults: Record<string, unknown>,
+ isTag: boolean
+): void {
+ if (typeof window !== 'undefined' && (window as any).__esengine_registerComponent) {
+ (window as any).__esengine_registerComponent(name, defaults, isTag);
+ }
}
// =============================================================================