Skip to content

Visualize Your Ideas With Code

refactor: merge runtime and editor plugins (#890)

Jacob05f0ad0af87d
diff --git a/packages/2d/src/lib/scenes/makeScene2D.ts b/packages/2d/src/lib/scenes/makeScene2D.ts
index c2adb298..78a80e9b 100644
--- a/packages/2d/src/lib/scenes/makeScene2D.ts
+++ b/packages/2d/src/lib/scenes/makeScene2D.ts
@@ -14,11 +14,6 @@ export function makeScene2D(
config: runner,
stack: new Error().stack,
meta: createSceneMetadata(),
- plugins: [
- {
- name: '@motion-canvas/2d',
- editorPlugin: '@motion-canvas/2d/editor',
- },
- ],
+ plugins: ['@motion-canvas/2d/editor'],
};
}
diff --git a/packages/core/src/app/Project.ts b/packages/core/src/app/Project.ts
index 696e7274..861c212c 100644
--- a/packages/core/src/app/Project.ts
+++ b/packages/core/src/app/Project.ts
@@ -5,19 +5,69 @@ import type {ProjectMetadata} from './ProjectMetadata';
import {SettingsMetadata} from './SettingsMetadata';
export interface ProjectSettings {
+ /**
+ * The name of the project.
+ */
name?: string;
+
+ /**
+ * A list of scene descriptions that make up the project.
+ *
+ * @remarks
+ * A full scene description can be obtained by loading a scene module with a
+ * `?scene` query parameter.
+ *
+ * @example
+ * ```ts
+ * import exampleScene from './example?scene';
+ *
+ * export default makeProject({
+ * scenes: [exampleScene],
+ * });
+ * ```
+ */
scenes: FullSceneDescription[];
- plugins?: Plugin[];
+
+ /**
+ * A list of plugins to include in the project.
+ *
+ * @remarks
+ * When a string is provided, the plugin will be imported dynamically using
+ * the string as the module specifier. This is the preferred way to include
+ * editor plugins because it makes sure that the plugin's source code gets
+ * excluded from the production build.
+ */
+ plugins?: (Plugin | string)[];
+
+ /**
+ * A custom logger instance to use.
+ */
logger?: Logger;
+
+ /**
+ * An url for the audio track to play alongside the animation.
+ *
+ * @see https://motioncanvas.io/docs/media#audio
+ */
audio?: string;
+
/**
* @deprecated Configure the offset in the Video Settings tab of th editor.
*/
audioOffset?: number;
+
+ /**
+ * Default values for project variables.
+ *
+ * @see https://motioncanvas.io/docs/project-variables
+ */
variables?: Record<string, unknown>;
+
/**
* Enable experimental features.
*
+ * @see https://motioncanvas.io/docs/experimental
+ *
* @experimental
*/
experimentalFeatures?: boolean;
diff --git a/packages/core/src/app/bootstrap.ts b/packages/core/src/app/bootstrap.ts
index db3a5290..1154a6fb 100644
--- a/packages/core/src/app/bootstrap.ts
+++ b/packages/core/src/app/bootstrap.ts
@@ -15,6 +15,7 @@ import {createSettingsMetadata} from './SettingsMetadata';
* @param config - Project settings.
* @param metaFile - The project meta file.
* @param settingsFile - The settings meta file.
+ * @param logger - An optional logger instance.
*
* @internal
*/
@@ -25,56 +26,120 @@ export function bootstrap(
config: ProjectSettings,
metaFile: MetaFile<any>,
settingsFile: MetaFile<any>,
+ logger = config.logger ?? new Logger(),
): Project {
const settings = createSettingsMetadata();
settingsFile.attach(settings);
- const defaultPlugin = DefaultPlugin();
- const pluginMap = new Map<string, Plugin>([
- [defaultPlugin.name, defaultPlugin],
- ]);
+ const project = {
+ name,
+ ...config,
+ plugins,
+ versions,
+ settings,
+ logger,
+ } as Project;
+
+ project.meta = new ProjectMetadata(project);
+ project.meta.shared.set(settings.defaults.get());
+ project.experimentalFeatures ??= false;
+ metaFile.attach(project.meta);
+
+ return project;
+}
+
+/**
+ * Bootstrap a project together with all editor plugins.
+ *
+ * @param name - The name of the project.
+ * @param versions - Package versions.
+ * @param plugins - Loaded plugins.
+ * @param config - Project settings.
+ * @param metaFile - The project meta file.
+ * @param settingsFile - The settings meta file.
+ *
+ * @internal
+ */
+export async function editorBootstrap(
+ name: string,
+ versions: Versions,
+ plugins: (Plugin | string)[],
+ config: ProjectSettings,
+ metaFile: MetaFile<any>,
+ settingsFile: MetaFile<any>,
+): Promise<Project> {
+ const logger = config.logger ?? new Logger();
+ const promises: Promise<Plugin | null>[] = [Promise.resolve(DefaultPlugin())];
if (config.plugins) {
for (const plugin of config.plugins) {
- pluginMap.set(plugin.name, plugin);
+ promises.push(parsePlugin(plugin, logger));
}
}
for (const scene of config.scenes) {
if (scene.plugins) {
for (const plugin of scene.plugins) {
- pluginMap.set(plugin.name, plugin);
+ promises.push(parsePlugin(plugin, logger));
}
}
}
for (const plugin of plugins) {
- pluginMap.set(plugin.name, plugin);
+ promises.push(parsePlugin(plugin, logger));
}
- // Make sure the default plugin is not overridden.
- pluginMap.set(defaultPlugin.name, defaultPlugin);
- plugins = [...pluginMap.values()];
+ const pluginSet = new Set<string>();
+ const resolvedPlugins = await Promise.all(promises);
+ const includedPlugins: Plugin[] = [];
+ let resolvedConfig = config;
- const reducedSettings = plugins.reduce(
- (settings, plugin) => ({
- ...settings,
- ...(plugin.settings?.(settings) ?? {}),
- }),
- {name, ...config} as ProjectSettings,
- );
+ for (const plugin of resolvedPlugins) {
+ if (!plugin || pluginSet.has(plugin.name)) {
+ continue;
+ }
- const project = {...reducedSettings} as Project;
- project.versions = versions;
- project.logger = new Logger();
- project.plugins = plugins;
- project.settings = settings;
- project.meta = new ProjectMetadata(project);
- project.meta.shared.set(settings.defaults.get());
- project.experimentalFeatures ??= false;
- metaFile.attach(project.meta);
+ pluginSet.add(plugin.name);
+ includedPlugins.push(plugin);
+
+ resolvedConfig = {
+ ...resolvedConfig,
+ ...(plugin.settings?.(resolvedConfig) ?? {}),
+ };
+ }
+
+ const project = bootstrap(
+ name,
+ versions,
+ includedPlugins,
+ resolvedConfig,
+ metaFile,
+ settingsFile,
+ );
- plugins.forEach(plugin => plugin.project?.(project));
+ includedPlugins.forEach(plugin => plugin.project?.(project));
return project;
}
+
+async function parsePlugin(
+ plugin: Plugin | string,
+ logger: Logger,
+): Promise<Plugin | null> {
+ if (typeof plugin === 'string') {
+ try {
+ plugin = (
+ await import(/* @vite-ignore */ `/@id/${plugin}`)
+ ).default() as Plugin;
+ } catch (e: any) {
+ logger.error({
+ message: `Failed to load plugin "${plugin}": ${e.message}.`,
+ stack: e.stack,
+ remarks: e.remarks,
+ });
+ return null;
+ }
+ }
+
+ return plugin;
+}
diff --git a/packages/core/src/meta/EnumMetaField.ts b/packages/core/src/meta/EnumMetaField.ts
index bd36a4ca..d5919b7e 100644
--- a/packages/core/src/meta/EnumMetaField.ts
+++ b/packages/core/src/meta/EnumMetaField.ts
@@ -13,17 +13,17 @@ export class EnumMetaField<T> extends MetaField<T> {
public constructor(
name: string,
public readonly options: MetaOption<T>[],
- initial: T = options[0].value,
+ initial: T = options[0]?.value,
) {
super(name, initial);
}
public set(value: T) {
- super.set(this.getOption(value).value);
+ super.set(this.getOption(value)?.value);
}
public parse(value: T): T {
- return this.getOption(value).value;
+ return this.getOption(value)?.value;
}
public getOption(value: T): MetaOption<T> {
diff --git a/packages/core/src/meta/ExporterMetaFile.ts b/packages/core/src/meta/ExporterMetaFile.ts
index 8751f16d..d0c925a7 100644
--- a/packages/core/src/meta/ExporterMetaFile.ts
+++ b/packages/core/src/meta/ExporterMetaFile.ts
@@ -22,7 +22,7 @@ export class ExporterMetaField extends MetaField<{
}
private readonly fields: ValueDispatcher<MetaField<any>[]>;
- public get options() {
+ public get options(): MetaField<any> | undefined {
return this.optionFields[this.current];
}
@@ -45,12 +45,12 @@ export class ExporterMetaField extends MetaField<{
value: exporter.id,
text: exporter.displayName,
})),
- exporters[current].id,
+ exporters[current]?.id,
);
super(name, {
name: exporterField.get(),
- options: optionFields[current].get(),
+ options: optionFields[current]?.get(),
});
this.exporters = exporters;
@@ -58,19 +58,23 @@ export class ExporterMetaField extends MetaField<{
this.exporterField.onChanged.subscribe(this.handleChange, false);
this.exporterField.disable(optionFields.length < 2).space();
this.optionFields = optionFields;
- this.optionFields[current].onChanged.subscribe(this.handleChange, false);
- this.fields = new ValueDispatcher([this.exporterField, this.options]);
+ this.fields = new ValueDispatcher([this.exporterField as MetaField<any>]);
+
+ if (this.options) {
+ this.options.onChanged.subscribe(this.handleChange, false);
+ this.fields.current = [this.exporterField, this.options];
+ }
}
public set(value: {name: string; options: any}) {
this.exporterField.set(value.name);
- this.options.set(value.options);
+ this.options?.set(value.options ?? {});
}
public serialize(): {name: string; options: any} {
return {
name: this.exporterField.serialize(),
- options: this.options.serialize(),
+ options: this.options?.serialize() ?? null,
};
}
@@ -86,15 +90,17 @@ export class ExporterMetaField extends MetaField<{
);
if (this.current !== index) {
- this.options.onChanged.unsubscribe(this.handleChange);
+ this.options?.onChanged.unsubscribe(this.handleChange);
this.current = index;
- this.options.onChanged.subscribe(this.handleChange, false);
- this.fields.current = [this.exporterField, this.options];
+ this.options?.onChanged.subscribe(this.handleChange, false);
+ this.fields.current = this.options
+ ? [this.exporterField, this.options]
+ : [this.exporterField];
}
this.value.current = {
name: this.exporterField.get(),
- options: this.options.get(),
+ options: this.options?.get() ?? null,
};
};
}
diff --git a/packages/core/src/plugin/DefaultPlugin.ts b/packages/core/src/plugin/DefaultPlugin.ts
index 9692eadf..a9059a6f 100644
--- a/packages/core/src/plugin/DefaultPlugin.ts
+++ b/packages/core/src/plugin/DefaultPlugin.ts
@@ -7,7 +7,7 @@ import {makePlugin} from './makePlugin';
* @internal
*/
export default makePlugin({
- name: 'mc-default-plugin',
+ name: '@motion-canvas/core/default',
exporters() {
return [ImageExporter];
},
diff --git a/packages/core/src/plugin/Plugin.ts b/packages/core/src/plugin/Plugin.ts
index 6474c519..25ec3f39 100644
--- a/packages/core/src/plugin/Plugin.ts
+++ b/packages/core/src/plugin/Plugin.ts
@@ -11,21 +11,21 @@ import type {
* Represents a runtime Motion Canvas plugin.
*/
export interface Plugin {
- name: string;
-
/**
- * A path for importing the editor plugin.
+ * A unique name of the plugin.
*
* @remarks
- * Editor plugins can extend the editor UI. They are loaded only when using
- * the editor and are ignored completely in a production build.
+ * The name should be unique across the entire ecosystem of Motion Canvas.
+ * If a plugin with the same name has already been registered, this plugin
+ * will be ignored.
*
- * The path should lead to a module containing a default export of an editor
- * plugin.
+ * If you intend to publish your plugin to npm, it is recommended to prefix
+ * this name with the name of your npm package.
*
- * @experimental
+ * Other identifiers defined by the plugin, such as a tab id, will be
+ * automatically prefixed with this name and as such don't have to be unique.
*/
- editorPlugin?: string;
+ name: string;
/**
* Modify the project settings before the project is initialized.
diff --git a/packages/core/src/scenes/Scene.ts b/packages/core/src/scenes/Scene.ts
index 0d39a13b..4e3970dc 100644
--- a/packages/core/src/scenes/Scene.ts
+++ b/packages/core/src/scenes/Scene.ts
@@ -47,7 +47,10 @@ export interface SceneDescription<T = unknown> {
* The stack trace at the moment of creation.
*/
stack?: string;
- plugins?: Plugin[];
+ /**
+ * A list of plugins to include in the project.
+ */
+ plugins?: (Plugin | string)[];
meta: SceneMetadata;
}
diff --git a/packages/docs/docs/advanced/plugins/editor.mdx b/packages/docs/docs/advanced/plugins/editor.mdx
new file mode 100644
index 00000000..7bfc21ae
--- /dev/null
+++ b/packages/docs/docs/advanced/plugins/editor.mdx
@@ -0,0 +1,130 @@
+---
+slug: /plugins/editor
+description: Extend the editor interface with Preact.
+sidebar_position: 2
+---
+
+import ExperimentalWarning from '@site/src/components/ExperimentalWarning';
+
+# Editor
+
+Editor plugins are an extension of runtime plugins that include additional hooks
+for extending the editor interface itself.
+
+<ExperimentalWarning />
+
+Let's update our plugin's entry point to export an editor plugin. The main
+difference is that we're now using the `makeEditorPlugin` function imported from
+`@motion-canvas/ui` to define it:
+
+```ts title="src/plugin.ts"
+import {makeEditorPlugin} from '@motion-canvas/ui';
+import {CustomTabConfig} from './CustomTabConfig';
+
+export default makeEditorPlugin({
+ name: 'editor-test',
+ tabs: [CustomTabConfig],
+});
+```
+
+This gives us access to some additional hooks that we can use to extend the
+interface. In the example above, we use `tabs` to declare an array of custom
+tabs that will be added to the left sidebar.
+
+The tab configuration is imported from a new file called `CustomTabConfig.tsx`
+that we have yet to create. Let's take a look at how it may look like:
+
+```tsx title="src/CustomTabConfig.tsx"
+/* @jsxImportSource preact */
+
+import {
+ Pane,
+ PhotoCamera,
+ PluginTabConfig,
+ PluginTabProps,
+ Separator,
+ Tab,
+} from '@motion-canvas/ui';
+
+function TabComponent({tab}: PluginTabProps) {
+ return (
+ <Tab title="My Tab" id="custom-tab" tab={tab}>
+ <PhotoCamera />
+ </Tab>
+ );
+}
+
+function PaneComponent() {
+ return (
+ <Pane title="My Pane" id="custom-pane">
+ <Separator size={1} />
+ Hello <strong>World</strong>!
+ </Pane>
+ );
+}
+
+export const CustomTabConfig: PluginTabConfig = {
+ name: 'inspector',
+ tabComponent: TabComponent,
+ paneComponent: PaneComponent,
+};
+```
+
+First of all, the editor is built on top of [Preact](https://preactjs.com/).
+Just like Motion Canvas, Preact uses JSX to define components. This means that
+in `tsx` files extending the editor, we need to let TypeScript know that it
+should import the `jsx` factory function from `preact` and not
+`@motion-canvas/2d`. This can be done in multiple different ways. In this simple
+example, we'll just use a comment at the top of the file:
+
+```tsx
+/* @jsxImportSource preact */
+```
+
+Next, we define a component for the tab itself. This component will be rendered
+in the navigation bar on the left. We use the `Tab` component from
+`@motion-canvas/ui` to stay consistent with the rest of the editor. We also
+borrow the `PhotoCamera` icon and put it inside:
+
+```tsx
+function TabComponent({tab}: PluginTabProps) {
+ return (
+ <Tab title="My Tab" id="custom-tab" tab={tab}>
+ <PhotoCamera />
+ </Tab>
+ );
+}
+```
+
+Similarly, we define a component for the pane that will be rendered when the tab
+is selected:
+
+```tsx
+function PaneComponent() {
+ return (
+ <Pane title="My Pane" id="custom-pane">
+ <Separator size={1} />
+ Hello <strong>World</strong>!
+ </Pane>
+ );
+}
+```
+
+Lastly, we export the configuration object:
+
+```tsx
+export const CustomTabConfig: PluginTabConfig = {
+ name: 'inspector',
+ tabComponent: TabComponent,
+ paneComponent: PaneComponent,
+};
+```
+
+Editor plugins are still experimental and the API is not yet properly documented
+but if you want to play around with some other available hooks you can take a
+look at [this editor plugin][example-plugin] provided by the `@motion-canvas/2d`
+package. It's responsible for displaying the inspector tab and drawing an
+overlay on top of the preview when clicking on different nodes.
+
+[example-plugin]:
+ https://github.com/motion-canvas/motion-canvas/blob/main/packages/2d/src/editor/index.ts
diff --git a/packages/docs/docs/advanced/plugins/index.mdx b/packages/docs/docs/advanced/plugins/index.mdx
new file mode 100644
index 00000000..6796b5a3
--- /dev/null
+++ b/packages/docs/docs/advanced/plugins/index.mdx
@@ -0,0 +1,36 @@
+---
+sidebar_position: 5
+slug: /plugins
+---
+
+import DocCardList from '@theme/DocCardList';
+import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
+
+# Authoring plugins
+
+Plugins are a way to extend the functionality of Motion Canvas.
+
+Motion Canvas consists of two parts running in separate environments: a
+[Vite](https://vitejs.dev/) development server running on Node.js and an editor
+running in the browser. Browser-related code can be split further into two
+parts:
+
+- Runtime - all the logic necessary to play the animation, such as the `Player`
+ instance, Scene definitions (including the actual source code of your
+ animation), etc.
+- Editor - the interface that lets you preview the animation, edit the settings,
+ etc.
+
+Depending on your needs, you can extend any of these parts with a plugin:
+
+<DocCardList items={useCurrentSidebarCategory().items} />
+
+# Plugin examples
+
+You can take a look at our [FFmpeg plugin][ffmpeg-plugin] for an example of a
+fully-fledged plugin. It's runtime portion provides the editor with a Video
+[exporter](/api/core/app/Exporter) that sends the rendered frames over to
+Node.js. The server portion then uses FFmpeg to convert the frames into a video.
+
+[ffmpeg-plugin]:
+ https://github.com/motion-canvas/exporters/tree/main/packages/ffmpeg
diff --git a/packages/docs/docs/advanced/plugins.mdx b/packages/docs/docs/advanced/plugins/node.mdx
similarity index 56%
rename from packages/docs/docs/advanced/plugins.mdx
rename to packages/docs/docs/advanced/plugins/node.mdx
index bec06213..537dfc31 100644
--- a/packages/docs/docs/advanced/plugins.mdx
+++ b/packages/docs/docs/advanced/plugins/node.mdx
@@ -1,93 +1,10 @@
---
-sidebar_position: 5
-slug: /plugins
+slug: /plugins/node
+description: Extend Vite and the Node.js server.
+sidebar_position: 3
---
-# Authoring plugins
-
-Plugins are a way to extend the functionality of Motion Canvas.
-
-Motion Canvas consists of two separate parts: a [Vite](https://vitejs.dev/)
-development server running on Node.js and an editor running in the browser
-(runtime). Plugins can extend both of these.
-
-## Writing a runtime plugin
-
-<div className="row margin-bottom--md">
- <div className="col col--6">
-
-Let's start by creating the entry point - a simple file that exports our plugin.
-For now, we'll put that file in the `src` directory of our Motion Canvas
-project. If you find yourself reusing the plugin across multiple projects, you
-can put it in a separate package.
-
-To define the plugin, we pass a configuration object to the
-[`makePlugin`][make-plugin] helper function and export the result. `name` is the
-only required property. `player` is an optional hook that will receive the
-[`Player`](/api/core/app/Player) instance right after it's created. Take a look
-at the [`Plugin`](/api/core/plugin/Plugin) interface for the full list of
-available hooks.
-
- </div>
- <div className="col col--6">
-
-```diff title="Project structure"
- project/
- ├── src/
- │ ├── scenes/
- │ │ └── example.tsx
-// highlight-next-line
-+ │ ├── plugin.ts
- │ └── project.ts
- ├── package.json
- └── vite.config.ts
-```
-
- </div>
-</div>
-
-```ts title="src/plugin.ts"
-import {makePlugin} from '@motion-canvas/core';
-
-export default makePlugin({
- name: 'motion-canvas-plugin-example',
- player(player) {
- player.onRecalculated.subscribe(() => {
- player.requestReset();
- player.togglePlayback(true);
- });
- },
-});
-```
-
-In this example we subscribe to the
-[`onRecalculated`](/api/core/app/Player#onRecalculated) event to play the
-animation from the beginning whenever this event occurs. Recalculation happens
-when we edit the animation either in the editor or in the code.
-
-Now we can import the plugin in our project file. Note that
-[`makePlugin`][make-plugin] returns a function that we need to call to create an
-actual plugin object. We'll see [why that's useful](#passing-options-to-runtime)
-in a moment:
-
-```ts title="src/project.ts"
-import {makeProject} from '@motion-canvas/core';
-// highlight-next-line
-import myPlugin from './plugin';
-import example from './scenes/example?scene';
-
-export default makeProject({
- scenes: [example],
- // highlight-start
- plugins: [myPlugin()],
- // ^^ we need to call the function
- // highlight-end
-});
-```
-
-That's it! Now we can run the project and see our plugin in action.
-
-## Writing a Node.js plugin
+# Node.js
<div className="row margin-bottom--md">
<div className="col col--6">
@@ -116,6 +33,7 @@ runtime plugin:
│ ├── plugin.ts
│ └── project.ts
├── package.json
+ ├── tsconfig.json
// highlight-next-line
+ ├── myVitePlugin.ts
└── vite.config.ts
@@ -239,16 +157,6 @@ export default makePlugin((options?: MyPluginOptions) => {
});
```
-## Plugin examples
-
-You can take a look at our [FFmpeg plugin][ffmpeg-plugin] for an example of a
-fully-fledged plugin. It's runtime portion provides the editor with a Video
-[exporter](/api/core/app/Exporter) that sends the rendered frames over to
-Node.js. The server portion then uses FFmpeg to convert the frames into a video.
-
[vite-plugin]: https://vitejs.dev/guide/api-plugin.html#authoring-a-plugin
[vite-configure-server]:
https://vitejs.dev/guide/api-plugin.html#configureserver
-[make-plugin]: /api/core/plugin#makePlugin
-[ffmpeg-plugin]:
- https://github.com/motion-canvas/exporters/tree/main/packages/ffmpeg
diff --git a/packages/docs/docs/advanced/plugins/runtime.mdx b/packages/docs/docs/advanced/plugins/runtime.mdx
new file mode 100644
index 00000000..a56513da
--- /dev/null
+++ b/packages/docs/docs/advanced/plugins/runtime.mdx
@@ -0,0 +1,89 @@
+---
+slug: /plugins/runtime
+description: Extend the runtime components like scenes and the player.
+sidebar_position: 1
+---
+
+# Runtime
+
+<div className="row margin-bottom--md">
+ <div className="col col--6">
+
+Runtime plugins allow you to extend the runtime components like scenes and the
+player.
+
+Let's start by creating the entry point - a simple file that exports our plugin.
+For now, we'll put that file in the `src` directory of our Motion Canvas
+project. If you find yourself reusing the plugin across multiple projects, you
+can put it in a separate package.
+
+To define the plugin, we pass a configuration object to the
+[`makePlugin`][make-plugin] helper function and export the result. `name` is the
+only required property. `player` is an optional hook that will receive the
+[`Player`](/api/core/app/Player) instance right after it's created. Take a look
+at the [`Plugin`](/api/core/plugin/Plugin) interface for the full list of
+available hooks.
+
+ </div>
+ <div className="col col--6">
+
+```diff title="Project structure"
+ project/
+ ├── src/
+ │ ├── scenes/
+ │ │ └── example.tsx
+// highlight-next-line
++ │ ├── plugin.ts
+ │ └── project.ts
+ ├── package.json
+ ├── tsconfig.json
+ └── vite.config.ts
+```
+
+ </div>
+</div>
+
+```ts title="src/plugin.ts"
+import {makePlugin} from '@motion-canvas/core';
+
+export default makePlugin({
+ name: 'motion-canvas-plugin-example',
+ player(player) {
+ player.onRecalculated.subscribe(() => {
+ player.requestReset();
+ player.togglePlayback(true);
+ });
+ },
+});
+```
+
+In this example we subscribe to the
+[`onRecalculated`](/api/core/app/Player#onRecalculated) event to play the
+animation from the beginning whenever this event occurs. Recalculation happens
+when we edit the animation either in the editor or in the code.
+
+Now we can import the plugin in our project file. Note that
+[`makePlugin`][make-plugin] returns a function that we need to call to create an
+actual plugin object (This can come in handy when
+[developing a Node.js plugin](/docs/plugins/node#passing-options-to-runtime)):
+
+```ts title="src/project.ts"
+import {makeProject} from '@motion-canvas/core';
+// highlight-next-line
+import myPlugin from './plugin';
+import example from './scenes/example?scene';
+
+export default makeProject({
+ scenes: [example],
+ // highlight-start
+ plugins: [myPlugin()],
+ // ^^ we need to call the function
+ // highlight-end
+});
+```
+
+That's it! Now we can run the project and see our plugin in action. Check out
+the [`Plugin`][plugin] interface for the full list of available hooks.
+
+[plugin]: /api/core/plugin/Plugin
+[make-plugin]: /api/core/plugin#makePlugin
diff --git a/packages/template/vite.config.ts b/packages/template/vite.config.ts
index 3a25d8e0..efc94f92 100644
--- a/packages/template/vite.config.ts
+++ b/packages/template/vite.config.ts
@@ -2,8 +2,13 @@ import motionCanvas from '@motion-canvas/vite-plugin';
import {defineConfig} from 'vite';
export default defineConfig({
- plugins: [motionCanvas()],
+ plugins: [
+ motionCanvas({
+ buildForEditor: true,
+ }),
+ ],
build: {
+ minify: false,
rollupOptions: {
output: {
entryFileNames: '[name].js',
diff --git a/packages/ui/package.json b/packages/ui/package.json
index afff8380..9566d371 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -22,7 +22,8 @@
},
"files": [
"dist",
- "types"
+ "types",
+ "tsconfig.plugin.json"
],
"dependencies": {
"@motion-canvas/core": "^3.11.0",
diff --git a/packages/ui/src/main.tsx b/packages/ui/src/main.tsx
index 371f721a..66f13c82 100644
--- a/packages/ui/src/main.tsx
+++ b/packages/ui/src/main.tsx
@@ -4,7 +4,6 @@ import {
Player,
Presenter,
Renderer,
- errorToLog,
experimentalLog,
type Project,
} from '@motion-canvas/core';
@@ -13,18 +12,24 @@ import {Editor} from './Editor';
import {ProjectData, ProjectSelection} from './ProjectSelection';
import {ApplicationProvider} from './contexts';
import {ShortcutsProvider} from './contexts/shortcuts';
-import {EditorPlugin} from './plugin';
import GridPlugin from './plugin/GridPlugin';
import {projectNameSignal} from './signals';
import {getItem, setItem} from './utils';
+const ExperimentalHooks = [
+ 'tabs',
+ 'provider',
+ 'previewOverlay',
+ 'presenterOverlay',
+] as const;
+
function renderRoot(vnode: ComponentChild) {
const root = document.createElement('main');
document.body.appendChild(root);
render(vnode, root);
}
-export async function editor(project: Project) {
+export function editor(project: Project) {
Error.stackTraceLimit = Infinity;
projectNameSignal.value = project.name;
@@ -37,26 +42,22 @@ export async function editor(project: Project) {
}
});
- const promises: Promise<EditorPlugin>[] = [];
- for (const plugin of project.plugins) {
- if (plugin.editorPlugin) {
- if (
- !project.experimentalFeatures &&
- !plugin.name.startsWith('@motion-canvas')
- ) {
+ if (!project.experimentalFeatures) {
+ for (const plugin of project.plugins) {
+ if (plugin.name.startsWith('@motion-canvas')) {
+ continue;
+ }
+
+ const experimental = ExperimentalHooks.filter(key => key in plugin);
+ if (experimental.length > 0) {
project.logger.log(
experimentalLog(
- `Plugin "${plugin.name}" tried to register an editor plugin.`,
+ `Plugin "${
+ plugin.name
+ }" uses experimental editor hooks: ${experimental.join(', ')}.`,
),
);
- continue;
}
-
- promises.push(
- import(/* @vite-ignore */ `/@id/${plugin.editorPlugin}`).then(module =>
- module.default(),
- ),
- );
}
}
@@ -119,12 +120,7 @@ export async function editor(project: Project) {
document.title = `${project.name} | Motion Canvas`;
- const plugins: EditorPlugin[] = [GridPlugin()];
- try {
- plugins.push(...(await Promise.all(promises)));
- } catch (error) {
- project.logger.error(errorToLog(error));
- }
+ const plugins = [GridPlugin(), ...project.plugins];
renderRoot(
<ApplicationProvider
diff --git a/packages/ui/src/plugin/EditorPlugin.ts b/packages/ui/src/plugin/EditorPlugin.ts
index 518b0683..3691a2cb 100644
--- a/packages/ui/src/plugin/EditorPlugin.ts
+++ b/packages/ui/src/plugin/EditorPlugin.ts
@@ -1,3 +1,4 @@
+import {Plugin} from '@motion-canvas/core';
import {FunctionComponent} from 'preact';
/**
@@ -71,12 +72,10 @@ export interface PluginOverlayConfig {
*
* @remarks
* Passed to {@link makeEditorPlugin} to create a plugin.
+ *
+ * @experimental
*/
-export interface EditorPlugin {
- /**
- * The name of the plugin.
- */
- name: string;
+export interface EditorPlugin extends Plugin {
/**
* Configuration for custom tabs displayed in the sidebar.
*/
diff --git a/packages/ui/src/plugin/makeEditorPlugin.ts b/packages/ui/src/plugin/makeEditorPlugin.ts
index ddb4aacf..7bfaa4ae 100644
--- a/packages/ui/src/plugin/makeEditorPlugin.ts
+++ b/packages/ui/src/plugin/makeEditorPlugin.ts
@@ -11,6 +11,8 @@ import type {EditorPlugin} from './EditorPlugin';
* name: 'my-custom-plugin',
* });
* ```
+ *
+ * @experimental
*/
export function makeEditorPlugin(
plugin: EditorPlugin | (() => EditorPlugin),
diff --git a/packages/ui/tsconfig.plugin.json b/packages/ui/tsconfig.plugin.json
new file mode 100644
index 00000000..1db42abb
--- /dev/null
+++ b/packages/ui/tsconfig.plugin.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "target": "esnext",
+ "module": "esnext",
+ "moduleResolution": "node",
+ "moduleDetection": "force",
+ "isolatedModules": true,
+ "esModuleInterop": false,
+ "resolveJsonModule": true,
+ "allowJs": true,
+ "sourceMap": true,
+ "declaration": true,
+ "declarationMap": true,
+ "skipLibCheck": true,
+ "lib": ["DOM", "DOM.Iterable", "ESNext"],
+ "jsx": "preserve",
+ "jsxImportSource": "preact"
+ }
+}
diff --git a/packages/vite-plugin/src/main.ts b/packages/vite-plugin/src/main.ts
index cf240368..90143bc7 100644
--- a/packages/vite-plugin/src/main.ts
+++ b/packages/vite-plugin/src/main.ts
@@ -89,6 +89,11 @@ export interface MotionCanvasPluginConfig {
* to enable it.
**/
proxy?: boolean | MotionCanvasCorsProxyOptions;
+
+ /**
+ * Build the project to run in the editor.
+ */
+ buildForEditor?: boolean;
}
export default ({
@@ -97,6 +102,7 @@ export default ({
bufferedAssets = /^$/,
editor = '@motion-canvas/ui',
proxy,
+ buildForEditor,
}: MotionCanvasPluginConfig = {}): Plugin => {
const plugins: PluginOptions[] = [];
const editorPath = path.dirname(require.resolve(editor));
@@ -252,6 +258,7 @@ export default ({
}
if (params.has('project')) {
+ const runsInEditor = buildForEditor || viteConfig.command === 'serve';
const metaFile = `${name}.meta`;
await createMeta(path.join(dir, metaFile));
@@ -283,13 +290,17 @@ export default ({
return source(
...imports,
- `import {bootstrap} from '@motion-canvas/core';`,
+ `import {${
+ runsInEditor ? 'editorBootstrap' : 'bootstrap'
+ }} from '@motion-canvas/core';`,
`import {MetaFile} from '@motion-canvas/core';`,
`import metaFile from './${metaFile}';`,
`import config from './${name}';`,
`const settings = new MetaFile('settings', '${settingsId}');`,
`settings.loadData(${JSON.stringify(parsed)});`,
- `export default bootstrap(`,
+ `export default ${
+ runsInEditor ? 'await editorBootstrap' : 'bootstrap'
+ }(`,
` '${name}',`,
` ${versions},`,
` [${pluginNames.join(', ')}],`,
@@ -488,6 +499,7 @@ export default ({
config(config) {
return {
build: {
+ target: buildForEditor ? 'esnext' : 'modules',
assetsDir: './',
rollupOptions: {
preserveEntrySignatures: 'strict',