Add documentation for using Milkdown with various frameworks

- Created a new document for using components in Milkdown.
- Added a guide for using plugins in Milkdown, including toggling plugins programmatically and listing official plugins.
- Introduced a recipe for integrating Milkdown with Angular, including installation steps and component creation.
- Added a recipe for using Milkdown with Next.js, detailing installation and component setup.
- Created a guide for integrating Milkdown with NuxtJS, including installation and component creation.
- Added a comprehensive guide for using Milkdown with React, covering both Crepe and core Milkdown usage.
- Introduced a recipe for SolidJS integration with Milkdown, including installation and component creation.
- Added a guide for using Milkdown with Svelte, detailing installation and component setup.
- Created a comprehensive guide for integrating Milkdown with Vue, covering both Crepe and core Milkdown usage.
- Added a recipe for using Milkdown with Vue2, including installation and component creation.
This commit is contained in:
2026-01-17 14:18:08 +08:00
parent 4de3dfdd8d
commit d9ab341223
381 changed files with 125356 additions and 0 deletions
@@ -0,0 +1,142 @@
# Announcing Telemetry Inspector
There's a lot of questions from community asking that how can they know what plugins are enabled.
From Milkdown@7.2, we've added telemetries for milkdown, it can be available by inspectors.
With this API, you can inspect editor inner status.
You can even use visualizer to visualize the data. We create a simple example on [our playground](/playground).
![Milkdown Inspector](/blogs/announcing-telemetry-inspector/milkdown-inspector.gif)
## Get Started
Inspector will be a top-level API in Milkdown. You can use it like this:
```ts
import { Editor } from "@milkdown/core";
import { Telemetry } from "@milkdown/ctx";
const editor = await Editor.make()
// Inspector is disabled by default considering performance. You need to enable it manually.
.enableInspector()
// ...
.create();
const telemetry: Telemetry[] = editor.inspect();
```
The `Telemetry` interface will have the following fields:
```ts
interface Telemetry {
// User defined information for the plugin.
metadata: Meta;
// The slices and their current value defined by the plugin.
injectedSlices: { name: string; value: unknown }[];
// The slices and their current value consumed by the plugin.
consumedSlices: { name: string; value: unknown }[];
// The timers and their duration defined by the plugin.
recordedTimers: { name: string; duration: number; status: TimerStatus }[];
// The timers and their duration consumed by the plugin.
// Generally, the plugin will wait for them.
waitTimers: { name: string; duration: number; status: TimerStatus }[];
}
type TimerStatus = "pending" | "resolved" | "rejected";
interface Meta {
displayName: string;
description?: string;
package: string;
group?: string;
additional?: Record<string, any>;
}
```
For every plugin, it'll have a telemetry if it has metadata declared.
With the data, you'll know the sequence of the plugins loaded, the slices and timers they defined and consumed.
For example:
```ts
[
{
metadata: {
displayName: "Config",
package: "@milkdown/core",
group: "System",
},
injectedSlices: [],
consumedSlices: [
/* ... */
],
recordedTimers: [
{
name: "ConfigReady",
duration: 3,
status: "resolved",
},
],
waitTimers: [],
},
{
metadata: {
displayName: "Init",
package: "@milkdown/core",
group: "System",
},
injectedSlices: [],
consumedSlices: [
/* ... */
],
recordedTimers: [
{
name: "InitReady",
duration: 5,
status: "resolved",
},
],
waitTimers: [
{
name: "ConfigReady",
duration: 5,
status: "resolved",
},
],
},
];
```
From above information, we can know that the `Init` plugin wait for `Config` plugin to be ready.
We can build a sequence diagram from the data.
![Timer Sequence](/blogs/announcing-telemetry-inspector/timer-sequence.gif)
## Add Metadata for Plugin
For plugin maintainers, you can add metadata to your plugin to make it more friendly to the inspector.
```ts
import { MilkdownPlugin } from "@milkdown/ctx";
const yourMilkdownPlugin: MilkdownPlugin = () => {
/* your implementation */
};
yourMilkdownPlugin.metadata = {
displayName: "Your Plugin",
package: "your-plugin-package",
description: "Your plugin description",
group: "If you have a lot of plugins in your package, you can group them.",
addtitional: {
/* You can add any additional information here. */
version: "1.0.0",
authror: "Mike",
},
};
```
With metadata, your plugin will report telemetry correctly to the inspector.
@@ -0,0 +1,247 @@
# Build Your Own Milkdown Copilot
OpenAI introduced ChatGPT in 2020, which is a chatbot that can generate natural language responses to user input.
Which brings us a new way to interact with devices and applications.
Nowadays, there are more and more tools that are powered by AI. Such as Notion, GitHub and even Microsoft 365.
Since OpenAI also released the [API](https://openai.com/blog/openai-api) of it. And Milkdown is composed by plugins.
I think it's possible to build a Milkdown Copilot Plugin that can help you write documents. So I did it.
Let's see the result.
![Milkdown Copilot](/blogs/build-your-own-milkdown-copilot/milkdown-copilot.gif)
Looks cool, right? But how does it work? I'll explain it in the following sections.
## Prepare a Backend
**Before we start, you need to have a OpenAI API Key.** You'll need to get one [here](https://platform.openai.com/account/api-keys).
I'll not explain how to get it. You can find the details in their [official docs](https://platform.openai.com/).
I'll use Node.js to build the backend. You can use any language you like.
The backend is very simple. It just calls the OpenAI API and returns the result.
```ts
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
// Get your API key from env variable
apiKey: process.env.OPENAPI_KEY,
});
const openai = new OpenAIApi(configuration);
export const handler = async (req, res, next) => {
if (req.path === "/api/copilot" && req.method === "POST") {
const buffers = [];
// Get the body of the request.
const body = JSON.parse(req.body);
// Get prompt from the body.
const { prompt } = body;
const completion = await openai.createCompletion({
// Pick a model you like
model: "text-davinci-003",
prompt,
});
const hint = completion.data.choices[0].text;
return res.end(JSON.stringify({ hint }));
}
next();
return;
};
```
We watch the `/api/copilot` route and call the OpenAI API when we receive a POST request.
The post request should contain a `prompt` field which is the text that we want to complete.
To call our API, we just need one single helper in browser environment:
```ts
async function fetchAIHint(prompt: string) {
const data: Record<string, string> = { prompt };
const response = await fetch("/api/copilot", {
method: "POST",
body: JSON.stringify(data),
});
const res = (await response.json()) as { hint: string };
return res.hint;
}
```
## Build a Milkdown Plugin
Now let's focus on the Milkdown Copilot Plugin.
Basically I want to implement two things:
1. When the user types `<Enter>` or `<Space>`, they will get a hint from the copilot.
2. When the user types `<Tab>`, they will apply the content from the hint to the editor.
### Overview
To build a bridge between the copilot and the editor,
we can build a prosemirror plugin and use the `onKeyDown` hook to listen to the keydown event.
```ts
function keyDownHandler(ctx: Ctx, event: Event) {
if (event.key === "Enter" || event.code === "Space") {
getHint(ctx);
return;
}
if (event.key === "Tab") {
// prevent the browser from focusing on the next element.
event.preventDefault();
applyHint(ctx);
return;
}
hideHint(ctx);
}
```
When the user types `<Enter>` or `<Space>`, we will call the `getHint` function to get a hint from the copilot.
And when the user types `<Tab>`, we will call the `applyHint` function to apply the hint to the editor.
If user types other keys, we will hide the hint.
And we also need a component to render the hint. Here I choose to use a simple [widget decoration in prosemirror](https://prosemirror.net/docs/ref/#view.Decoration^widget).
```ts
function renderHint(message: string) {
const dom = document.createElement("pre");
dom.className = "copilot-hint";
dom.innerHTML = message;
return dom;
}
```
So our component looks like:
```ts
import { Plugin, PluginKey } from "@milkdown/prose/state";
import { Decoration, DecorationSet } from "@milkdown/prose/view";
import { $prose } from "@milkdown/utils";
const initialState = {
deco: DecorationSet.empty,
message: "",
};
export const copilotPluginKey = new PluginKey("milkdown-copilot");
export const copilotPlugin = $prose(
(ctx) =>
new Plugin({
key: copilotPluginKey,
props: {
handleKeyDwon(view, event) {
keydownHandler(ctx, event);
},
decorations(state) {
return copilotPluginKey.getState(state).deco;
},
},
state: {
init() {
return { ...initialState };
},
apply(tr, value, _prevState, state) {
const message = tr.getMeta(copilotPluginKey);
if (typeof message !== "string") return value;
if (message.length === 0) {
return { ...initialState };
}
const { to } = tr.selection;
const widget = Decoration.widget(to + 1, () => renderHint(message));
return {
deco: DecorationSet.create(state.doc, [widget]),
message,
};
},
},
}),
);
```
### Get Hint
To get a hint from the copilot, we need to get the text before the cursor.
```ts
function getHint(ctx: Ctx) {
const view = ctx.get(editorViewCtx);
const { state } = view;
const { tr, schema } = state;
const { from } = tr.selection;
const slice = tr.doc.slice(0, from);
const serializer = ctx.get(serializerCtx);
const doc = schema.topNodeType.createAndFill(undefined, slice.content);
if (!doc) return;
const markdown = serializer(doc);
fetchAIHint(markdown).then((hint) => {
const tr = view.state.tr;
view.dispatch(tr.setMeta(copilotPluginKey, hint));
});
}
```
1. First of all, we get the `selection` from the `state` of the editor.
2. Then we get a `slice` of the document from the start to the cursor.
3. Then we use the `serializer` to convert the slice to markdown.
4. After that, we call the `fetchAIHint` function to get a hint from the copilot.
5. Finally, we dispatch a transaction with the hint message we get to update the state of the editor.
### Hide Hint
To hide the hint, we just need to dispatch a transaction with an empty message.
```ts
function hideHint(ctx: Ctx) {
const view = ctx.get(editorViewCtx);
const { state } = view;
const { tr } = state;
view.dispatch(tr.setMeta(copilotPluginKey, ""));
}
```
### Apply Hint
Since we pass markdown to the OpenAI API. It may return a markdown snippet.
So, before we apply the hint to the editor, we need to convert the markdown snippet to prosemirror node.
```ts
function applyHint(ctx: Ctx) {
const view = ctx.get(editorViewCtx);
const { state } = view;
const { tr, schema } = state;
const { message } = copilotPluginKey.getState(state);
const parser = ctx.get(parserCtx);
const slice = parser(message);
const dom = DOMSerializer.fromSchema(schema).serializeFragment(slice.content);
const node = DOMParser.fromSchema(schema).parseSlice(dom);
// Reset the hint since it's applied
tr.setMeta(copilotPluginKey, "")
// Replace the selection with the hint
.replaceSelection(node);
view.dispatch(tr);
}
```
1. First of all, we get the hint message from the state of the editor.
2. Then we use the `parser` to convert the markdown snippet to prosemirror node.
3. Finally, we dispatch a transaction to replace the selection with the hint.
## Conclusion
In this article, we have built a really simple Copilot plugin for Milkdown.
The plugin is not perfect, but it's a good start to help you build your own.
The source code is available on [Milkdown/examples/vanilla-openapi](https://github.com/Milkdown/examples/tree/main/vanilla-openai).
I hope it can give you some inspiration.
@@ -0,0 +1,151 @@
# Introducing Milkdown@7
It's been almost one year since the release of [milkdown](https://milkdown.dev) V6.
It helped a lot of users to build their own markdown based applications.
It has 13k downloads per month and I feel so grateful that users like that.
However, we noticed that there're some problems cannot be resolved if we don't make a new major version.
What big changes did we made? I'll introduce them to you in this blog.
## TL;DR
- The editor becomes a first-class headless component.
- Factory plugins are fully replaced by **composable plugins**.
- Runtime plugin toggling is supported.
- Universal widget plugins.
- Better Vue and React support.
- API documentation is provided.
## Why Headless?
In the past, milkdown had a lot of internal styles to make sure the editor can work out of box and the themes are easy to create.
However, I found it limits the users to design their own editor.
Even worse, if you have an well designed application,
it is really hard to keep the style of the milkdown editor same with the rest of the application.
You'll need to override lots of styles everywhere.
It stops a log of users from using milkdown.
If we think about why users need an editor,
the most important thing is always the functionality of the editor.
Users just want a component that can provide smooth editing experience.
Style will always be the second thing.
So, why not remove all the internal styles and make the editor a headless component?
The users can easily integrate the editor into their own application.
They can use their own styles and even use their own components to render the editor.
We just care about the functionality of the editor. Make sure it works well.
## Composable Plugins
Although the composable plugins have been existed in milkdown for a long time,
we use factory plugins to create most of the official plugins in V6.
But, the problem is that factory plugins limit the possibility of the plugins.
The factory plugins handle a bunch of complex logic and it is hard to extend.
So for users who want to create a plugin in a easy way, they must follow the factory plugin's way.
```ts
const nodePlugin = createPlugin(() => ({
id: 'node',
schema: someSchema,
inputRules: someInputRules
commands: someCommands
}))
```
See? You can define a lot of things inside the factory plugin.
But if you want to use some part of them in another plugin, it's really hard to do that.
However, the milkdown's plugin system is designed to be flexible and composable.
We want to let users to control the data flow entirely.
So, we decided to remove all the factory plugins and use composable plugins to replace them.
The composable plugins can keep the atomicity of the plugins and make the plugin system more flexible.
They also make the plugin system easier to maintain.
```ts
const nodeSchema = $node("node", someSchema);
const nodeInputRules = $inputRules(someInputRules);
const nodeCommands = $commands(someCommands);
```
If you want to reuse them, it also will be very easy.
```ts
const anotherCommand = $commands(() => {
return setBlockType(nodeSchema.type());
});
```
## Runtime Plugin Toggling
In the past, once you register a plugin, you cannot remove it.
In V7, we support runtime plugin toggling by providing two new API: `editor.remove` and `editor.removeConfig`.
They can let users remove the plugins and configs at runtime.
```ts
import { Editor } from "@milkdown/core";
import { someMilkdownPlugin } from "some-milkdown-plugin";
const editor = await Editor.config(configForPlugin)
.use(someMilkdownPlugin)
.create();
// remove plugin
await editor.remove(someMilkdownPlugin);
// remove config
editor.removeConfig(configForPlugin);
// add another plugin
editor.use(anotherMilkdownPlugin);
// Recreate the editor to apply changes.
await editor.create();
```
Also, if you call the `editor.create` method after the editor is created,
it will recreate the editor and apply all the changes.
## Universal Widget Plugins
We have 4 official widget plugins in V6: _slash_, _tooltip_, _block_ and _menu_.
They are all well designed and easy to use.
But if you want to customize them, what you can do is really limited.
Also, it's hard to reuse their logic even if you want to create something similar to them.
For example, if you want to create a mention plugin which will show a list of users when you type `@`,
you need to create a new plugin from scratch.
So, in V7, we make _slash_, _tooltip_ and _block_ plugins universal.
You can use them to build you features easily.
For example, if you want to create a mention plugin, you can use the new slash plugin to do that.
Another example is that you can also create tooltips for different types of nodes.
Display a tooltip with input when you focus on an image node, or display a tooltip with buttons when you select some text.
What about the _menu_ plugin? We removed it because we think it's easy to create a menu plugin by yourself.
We've already done that in the [official playground](https://milkdown.dev/playground).
And, trust me, [it won't need much code](https://github.com/milkdown/website/blob/main/src/component/Playground/Milkdown/index.tsx#L57).
## Better Vue and React Support
Thanks to the [Saul-Mirone/prosemirror-adapter project](https://github.com/Saul-Mirone/prosemirror-adapter).
In milkdown V7. We allow users to use vue and react to render lots of parts of the editor.
For example, you can use them to render your own code block, drag handle or even small icons.
- React Example: [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/Milkdown/examples/tree/main/react-custom-component)
- Vue Example: [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/Milkdown/examples/tree/main/vue-custom-component)
## API Documentation
What's the hardest thing to do when maintaining an open source project?
Keep the documentation up to date.
Thanks to the [marijnh/builddocs project](https://github.com/marijnh/builddocs),
we can generate the API documentation automatically from the source code.
We also redesigned the documentation website, provide a more powerful playground and lots of examples.
@@ -0,0 +1,172 @@
# Understanding Headless Slash Plugin
In the old Milkdown versions. The slash plugin can be used to display a list of commands when users type `/` in the editor.
It provides a way to insert nodes and commands into the editor, and it's really easy to use.
![legacy slash plugin](/blogs/understanding-headless-slash-plugin/legacy-slash-plugin.png)
However, it's hard to extend the slash plugin to support more commands, or if you want to change the UI of the slash plugin, you have to rewrite the whole plugin.
But, write a new plugin is always a hard work. You have to understand a lot of context and APIs of both ProseMirror and Milkdown.
## User Story
So, why don't we provide the slash plugin as a headless plugin?
In most cases, developers just want to make sure that when users type a special character, a dropdown menu will be displayed.
But the trigger character and the UI of the dropdown menu are different in different cases.
For example:
- When user type `/`, the menu contains a list of **commands**.
- When user type `:`, the menu contains a list of **emoji**.
- When user type `@`, the menu contains a list of **users**.
That's the story behind the headless slash plugin. We provide the plugin to solve a single problem: **display a dropdown menu when users input satisfy a condition**.
## How to use
In the new slash plugin, you'll need to control when to display the dropdown menu by yourself.
And you'll also need to provide the UI of the dropdown menu.
So, you'll need to create a `SlashProvider` instance.
```ts
import { slashPlugin, SlashProvider } from "@milkdown/plugin-slash";
const slashProvider = new SlashProvider({
content: YourDropdownUI,
shouldShow(this: SlashProvider, view: EditorView) {
const currentText = this.getContent(view);
if (currentText === "") {
return false;
}
// Display the menu if the last character is `/`.
if (currentText.endsWith("/")) {
return true;
}
return false;
},
});
```
Then, you can use the slash provider in your plugin view.
```ts
import { EditorState } from "@milkdown/prose/state";
import { EditorView, PluginView } from "@milkdown/prose/view";
function yourSlashView(): PluginView {
return {
update: (view: EditorView, prevState: EditorState) => {
slashProvider.update(view, prevState);
},
destroy: () => {
slashProvider.destroy();
},
};
}
```
Last, you'll need to add the slash plugin to your editor.
```ts
import { Editor } from "@milkdown/core";
import { slashFactory } from "@milkdown/plugin-slash";
const slash = slashFactory("my-slash");
Editor.make()
.config((ctx) => {
ctx.set(slash.key, {
view: slashPluginView,
});
})
.use(slash)
.create();
```
## Use with Prosemirror Adapter
If you're using milkdown with UI frameworks like React,
I recommend you to use the [Prosemirror Adapter](https://github.com/Saul-Mirone/prosemirror-adapter).
It can help you build prosemirror UI components with your favorite UI framework.
For example, if you're using React:
```tsx
import { SlashProvider } from "@milkdown/plugin-slash";
import { useInstance } from "@milkdown/react";
import { usePluginViewContext } from "@prosemirror-adapter/react";
export const DropdownMenu = () => {
const { view, prevState } = usePluginViewContext();
const slashProvider = useRef<SlashProvider>();
const divRef = useRef<HTMLDivElement>(null);
const [loading] = useInstance();
useEffect(() => {
if (!ref.current || loading) return;
slashProvider.current ??= new SlashProvider({
content: divRef.current,
// ...
});
return () => {
slashProvider.current?.destroy();
slashProvider.current = undefined;
};
}, [loading, root, setOpened, setSearch, setSelected]);
useEffect(() => {
slashProvider.current?.update(view, prevState);
});
// Add a wrapper `div` to hide the dropdown menu when initializing.
return (
<div className="hidden">
<div role="tooltip" ref={divRef}>
<h1>Hi! I'm a dropdown menu.</h1>
</div>
</div>
);
};
```
And in your editor component:
```ts
import { usePluginViewFactory } from "@prosemirror-adapter/react";
export const YourEditor = () => {
const pluginViewFactory = usePluginViewFactory();
useEditor((editor) => {
return Editor.make()
.config((ctx) => {
ctx.set(slash.key, {
view: pluginViewFactory({
component: DopdownMenu,
}),
});
})
.use(slash);
});
// ...
};
```
## Real World Example
In [milkdown playground](/playground), you can type `/` to display a dropdown menu.
![command dropdown](/blogs/understanding-headless-slash-plugin/command-dropdown.png)
You can also type `:(\S)+` (for example: `:mil`) to display a list of emojis.
![emoji dropdown](/blogs/understanding-headless-slash-plugin/emoji-dropdown.png)
You can find the source code of them in [Milkdown website](https://github.com/Milkdown/website).
I hope you enjoy the new slash plugin.
@@ -0,0 +1,199 @@
# Architecture Overview
Milkdown is built with a modular, layered architecture that provides flexibility and extensibility. This document explains the core architectural concepts and how they work together.
![0.75](/guide/milkdown-architecture.png "Milkdown Architecture")
## Core Architecture Layers
Milkdown's architecture is built upon four distinct layers, each providing specific functionality and extensibility:
### 🥛 Core Layer
The foundation of Milkdown that provides:
- Plugin loading and management system
- Core editor concepts and interfaces
- Base document model integration
- Essential utilities and helpers
### 🧇 Plugin Layer
A comprehensive collection of modular plugins that extend the editor's functionality:
- Syntax plugins (Markdown parsing, GFM, etc.)
- UI plugins (toolbar, menu, etc.)
- Feature plugins (image upload, table, etc.)
- Utility plugins (history, clipboard, etc.)
### 🍮 Component Layer
Headless UI components that serve as building blocks:
- Toolbar components
- Slash menu components
- Table components
### 🍰 Editor Layer
Ready-to-use, user-friendly editors:
- Crepe editor
- Custom editor implementations
## Architecture Benefits
This layered approach provides several key benefits:
1. **Modularity**: Each layer can be used independently
2. **Flexibility**: Mix and match components as needed
3. **Extensibility**: Create custom implementations at any layer
4. **Maintainability**: Clear separation of concerns
5. **Reusability**: Components can be shared across implementations
## Markdown Transformation
![0.75](/guide/transformer.png "Transformer")
Milkdown's transformation system handles the conversion between Markdown and the editor's internal document model:
### Parsing Process
1. Markdown text → Remark AST
2. Remark AST → ProseMirror Schema
3. Schema → ProseMirror Document
### Serialization Process
1. ProseMirror Document → ProseMirror Schema
2. Schema → Remark AST
3. Remark AST → Markdown text
This transformation system ensures:
- Accurate Markdown parsing
- Consistent document structure
- Reliable serialization
- Extensible transformation pipeline
## Context System
The Context System is a powerful state management and dependency coordination system that enables plugins to work together seamlessly.
![1.00](/guide/plugin-sequence.png "Plugin Sequence")
### Core Concepts
#### 1. Context (Ctx)
The main interface for plugins to interact with the system:
```typescript
interface Ctx {
get: <T>(slice: Slice<T>) => T;
set: <T>(slice: Slice<T>, value: T) => void;
wait: (timer: Timer) => Promise<void>;
done: (timer: Timer) => void;
inject: <T>(slice: Slice<T>, value: T) => void;
remove: <T>(slice: Slice<T>) => void;
}
```
#### 2. Slices
State containers that can be shared between plugins:
```typescript
// Create a slice with initial value and name
const themeSlice = createSlice("light", "theme");
// Use in a plugin
const themePlugin: MilkdownPlugin = (ctx) => {
return () => {
// Read current theme
const theme = ctx.get(themeSlice);
// Update theme
ctx.set(themeSlice, "dark");
// React to theme changes
ctx.watch(themeSlice, (newTheme) => {
// Handle theme change
});
};
};
```
#### 3. Timers
Dependency management system for plugin coordination:
```typescript
// Define a timer
const dataReady = createTimer("DataReady");
// Use in a plugin
const dataPlugin: MilkdownPlugin = (ctx) => {
ctx.record(dataReady);
return async () => {
// Wait for dependencies
await ctx.wait(SchemaReady);
// Do work
// ...
// Mark as ready
ctx.done(dataReady);
};
};
```
### Plugin Lifecycle
Plugins follow a consistent lifecycle pattern:
```typescript
const examplePlugin: MilkdownPlugin = (ctx) => {
// 1. Setup Phase
ctx.inject(mySlice, defaultValue);
ctx.record(myTimer);
return async () => {
// 2. Initialization Phase
await ctx.wait(RequiredTimer);
// 3. Runtime Phase
const value = ctx.get(mySlice);
ctx.set(mySlice, newValue);
// 4. Cleanup Phase
return () => {
ctx.remove(mySlice);
};
};
};
```
### Best Practices
1. **State Management**
- Use slices for shared state
- Keep state minimal and focused
- Watch for state changes when needed
2. **Dependency Management**
- Use timers for coordination
- Wait for required dependencies
- Mark completion appropriately
3. **Plugin Organization**
- Follow the lifecycle pattern
- Clean up resources properly
- Document dependencies clearly
## Next Steps
- Start to [use Crepe editor](/docs/guide/using-crepe)
- Learn more about [writing plugins](/docs/plugin/plugins-101)
- Explore [available plugins](/docs/plugin/using-plugins)
+160
View File
@@ -0,0 +1,160 @@
# Code Highlighting
Milkdown supports syntax highlighting for code blocks through the `@milkdown/plugin-highlight` plugin. This plugin provides several options for highlighting code with different syntax highlighters.
## Installation
```bash
npm install @milkdown/plugin-highlight
```
## Basic Usage
The highlight plugin requires a parser to be configured. Here's a basic example using the Shiki parser:
```typescript
import { Editor } from "@milkdown/core";
import { commonmark } from "@milkdown/preset-commonmark";
import { highlight, highlightPluginConfig } from "@milkdown/plugin-highlight";
import { createParser } from "@milkdown/plugin-highlight/shiki";
const editor = Editor.make()
.config(async (ctx) => {
const parser = await createParser({
theme: "github-light",
langs: ["javascript", "typescript", "python", "html", "css"],
});
ctx.set(highlightPluginConfig.key, { parser });
})
.use(commonmark)
.use(highlight)
.create();
```
## Available Parsers
The plugin supports multiple syntax highlighting libraries:
### Shiki
Provides high-quality syntax highlighting with VS Code themes. Learn more at [Shiki](https://shiki.style/):
```typescript
import { createParser } from "@milkdown/plugin-highlight/shiki";
const parser = await createParser({
theme: "github-light",
langs: ["javascript", "typescript", "python"],
});
ctx.set(highlightPluginConfig.key, { parser });
```
### Lowlight
Based on [highlight.js](https://highlightjs.org/), supports many languages:
```typescript
import { createParser } from "@milkdown/plugin-highlight/lowlight";
import { common } from "lowlight";
const parser = createParser({ common });
ctx.set(highlightPluginConfig.key, { parser });
```
Learn more about Lowlight at [lowlight](https://github.com/wooorm/lowlight).
### Refractor
Based on [Prism.js](https://prismjs.com/):
```typescript
import { createParser } from "@milkdown/plugin-highlight/refractor";
import { refractor } from "refractor";
const parser = createParser({ refractor });
ctx.set(highlightPluginConfig.key, { parser });
```
Learn more about Refractor at [refractor](https://github.com/wooorm/refractor).
### Sugar High
A lightweight and fast syntax highlighter. Learn more at [Sugar High](https://github.com/huozhi/sugar-high):
```typescript
import { createParser } from "@milkdown/plugin-highlight/sugar-high";
const parser = createParser();
ctx.set(highlightPluginConfig.key, { parser });
```
## Styling
The highlighted code will have CSS classes applied based on the chosen parser. You'll need to include appropriate CSS to style the highlighted tokens.
### Sugar High Classes
Sugar High uses classes like:
- `sh__token--identifier`
- `sh__token--string`
- `sh__token--keyword`
- `sh__token--sign`
- `sh__token--property`
You can style these using CSS variables:
```css
.sh__token--identifier {
color: var(--sh-identifier);
}
.sh__token--string {
color: var(--sh-string);
}
.sh__token--keyword {
color: var(--sh-keyword);
}
```
### Other Parsers
For Lowlight, Refractor, and Shiki, refer to their respective documentation for styling information.
## Example
Here's a complete example with Shiki:
```typescript
import { Editor } from "@milkdown/core";
import { commonmark } from "@milkdown/preset-commonmark";
import { highlight, highlightPluginConfig } from "@milkdown/plugin-highlight";
import { createParser } from "@milkdown/plugin-highlight/shiki";
async function createHighlightedEditor() {
const parser = await createParser({
theme: "github-light",
langs: ["javascript", "typescript", "python", "html", "css", "json"],
});
const editor = Editor.make()
.config((ctx) => {
ctx.set(highlightPluginConfig.key, { parser });
})
.use(commonmark)
.use(highlight);
await editor.create();
return editor;
}
```
With this setup, your code blocks will be automatically highlighted:
````markdown
```javascript
console.log("Hello, world!");
const greeting = (name) => `Hello, ${name}!`;
```
````
The code above will render with syntax highlighting applied to keywords, strings, and other language constructs.
@@ -0,0 +1,122 @@
# Collaborative Editing
Milkdown supports collaborative editing powered by [Y.js](https://docs.yjs.dev/).
We provide the [@milkdown/plugin-collab](/docs/api/plugin-collab) plugin to help you use milkdown with yjs easily.
This plugin includes basic collaborative editing features like:
- Sync between clients.
- Remote cursor support.
- Undo/Redo support.
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/vanilla-collab"}
## Configure Plugin
First you need to install the plugin and yjs through npm:
```bash
npm install @milkdown/plugin-collab
npm install yjs y-protocols y-prosemirror
```
And you also need to choose a [provider for yjs](https://docs.yjs.dev/ecosystem/connection-provider), here we use [y-websocket](https://docs.yjs.dev/ecosystem/connection-provider/y-websocket) as an example.
After the installation, you can configure your editor:
```typescript
// ...import other plugins
import { collab, collabServiceCtx } from "@milkdown/plugin-collab";
async function setup() {
const editor = await Editor.make()
.config(nord)
.use(commonmark)
.use(collab)
.create();
const doc = new Doc();
const wsProvider = new WebsocketProvider("<YOUR_WS_HOST>", "milkdown", doc);
editor.action((ctx) => {
const collabService = ctx.get(collabServiceCtx);
collabService
// bind doc and awareness
.bindDoc(doc)
.setAwareness(wsProvider.awareness)
// connect yjs with milkdown
.connect();
});
}
```
Now your editor can support collaborative editing. Isn't it easy?
## Connect and Disconnect
You may want to control the connect status of the editor manually.
```typescript
editor.action((ctx) => {
const collabService = ctx.get(collabServiceCtx);
const doc = new Doc();
const wsProvider = new WebsocketProvider("<YOUR_WS_HOST>", "milkdown", doc);
collabService.bindDoc(doc).setAwareness(wsProvider.awareness);
document.getElementById("connect").onclick = () => {
wsProvider.connect();
collabService.connect();
};
document.getElementById("disconnect").onclick = () => {
wsProvider.disconnect();
collabService.disconnect();
};
});
```
## Default Template
By default, the editor will show a empty document. You may want to use a template to show a document.
```typescript
const template = `# Heading`;
editor.action((ctx) => {
const collabService = ctx.get(collabServiceCtx);
const doc = new Doc();
const wsProvider = new WebsocketProvider("<YOUR_WS_HOST>", "milkdown", doc);
collabService.bindDoc(doc).setAwareness(wsProvider.awareness);
wsProvider.once("synced", async (isSynced: boolean) => {
if (isSynced) {
collabService
// apply your template
.applyTemplate(markdown)
// don't forget connect
.connect();
}
});
});
```
Keep in mind that applying a template multiple times may cause some unexpected behavior, such as duplicate content.
Because of this you need to make sure **the template is applied only once**.
By default, the template will only be applied if _document get from remote server is empty_.
You can control this behavior through passing second parameter to `applyTemplate`:
```typescript
collabService
.applyTemplate(markdown, (remoteNode, templateNode) => {
// return true to apply template
})
// don't forget connect
.connect();
```
Here the nodes we get are [prosemirror nodes](https://prosemirror.net/docs/ref/#model.Node).
You should return `true` if the template should be applied, and `false` if not.
+250
View File
@@ -0,0 +1,250 @@
# Commands
Commands are a powerful way to programmatically modify editor content. The command system in Milkdown provides a flexible and type-safe way to create, manage, and execute commands.
## Command Manager
---
The command manager is the central place for handling all editor commands. It provides methods to:
- Register new commands
- Execute commands
- Chain multiple commands together
- Handle command arguments
## Run a Command
---
You can execute commands using the command manager through the editor's action system:
```typescript
import { Editor, commandsCtx } from "@milkdown/kit/core";
import {
commonmark,
toggleEmphasisCommand,
} from "@milkdown/kit/preset/commonmark";
async function setup() {
const editor = await Editor.make().use(commonmark).create();
const toggleItalic = () =>
editor.action((ctx) => {
// get command manager
const commandManager = ctx.get(commandsCtx);
// call command
commandManager.call(toggleEmphasisCommand.key);
});
// get markdown string:
$button.onClick = toggleItalic;
}
```
## Command Chaining
---
You can chain multiple commands together using the command manager's `chain` method. Commands in the chain will be executed in order until one of them returns `true`:
```typescript
import { Editor, commandsCtx } from "@milkdown/kit/core";
import {
commonmark,
toggleEmphasisCommand,
toggleStrongCommand,
} from "@milkdown/kit/preset/commonmark";
const editor = await Editor.make().use(commonmark).create();
editor.action((ctx) => {
const commandManager = ctx.get(commandsCtx);
// Chain multiple commands
commandManager
.chain()
.pipe(toggleEmphasisCommand.key) // Try to toggle emphasis
.pipe(toggleStrongCommand.key) // If emphasis fails, try to toggle strong
.run();
});
```
You can also mix inline commands with registered commands:
```typescript
import { chainCommands } from "@milkdown/prose/commands";
editor.action((ctx) => {
const commandManager = ctx.get(commandsCtx);
commandManager
.chain()
.inline(someInlineCommand) // Add an inline command
.pipe(toggleEmphasisCommand.key) // Add a registered command
.run();
});
```
## Create a Command
---
To create a command, use the `$command` utility from `@milkdown/utils`. Commands should be [prosemirror commands](https://prosemirror.net/docs/guide/#commands).
### Example: Command without argument
```typescript
import { Editor } from "@milkdown/kit/core";
import { blockquoteSchema } from "@milkdown/kit/preset/commonmark";
import { wrapIn } from "@milkdown/kit/prose/commands";
import { $command, callCommand } from "@milkdown/kit/utils";
const wrapInBlockquoteCommand = $command(
"WrapInBlockquote",
(ctx) => () => wrapIn(blockquoteSchema.type(ctx)),
);
// register the command when creating the editor
const editor = Editor().make().use(wrapInBlockquoteCommand).create();
// call command
editor.action(callCommand(wrapInBlockquoteCommand.key));
```
### Example: Command with argument
Commands can accept arguments of any type:
```typescript
import { headingSchema } from "@milkdown/kit/preset/commonmark";
import { setBlockType } from "@milkdown/kit/prose/commands";
import { $command, callCommand } from "@milkdown/kit/utils";
// use number as the type of argument
export const WrapInHeading = createCmdKey<number>();
const wrapInHeadingCommand = $command(
"WrapInHeading",
(ctx) =>
(level = 1) =>
setBlockType(headingSchema.type(ctx), { level }),
);
// call command
editor.action(callCommand(wrapInHeadingCommand.key)); // turn to h1 by default
editor.action(callCommand(wrapInHeadingCommand.key, 2)); // turn to h2
```
### Example: Command with Multiple Arguments
```typescript
interface TableConfig {
rows: number;
cols: number;
withHeader: boolean;
}
const insertTableCommand = $command(
"InsertTable",
(ctx) => (config: TableConfig) => {
// Implementation for inserting a table
return (state, dispatch) => {
// ... table insertion logic
return true;
};
},
);
// Usage
editor.action(
callCommand(insertTableCommand.key, {
rows: 3,
cols: 3,
withHeader: true,
}),
);
```
## Best Practices
---
1. **Command Naming**
- Use clear, descriptive names
- Follow the pattern: `[Action][Target]Command`
- Example: `toggleEmphasisCommand`, `insertTableCommand`
2. **Command Organization**
- Group related commands together
- Use namespaces for command keys
- Keep commands focused and single-purpose
3. **Error Handling**
- Always check if the command can be executed
- Return `false` if the command cannot be executed
- Handle edge cases gracefully
4. **Performance**
- Keep commands lightweight
- Avoid unnecessary state updates
- Use command chaining for complex operations
5. **Type Safety**
- Use TypeScript for command arguments
- Define clear interfaces for command payloads
- Use generics for type-safe command keys
## Common Patterns
---
### Toggle Commands
```typescript
const toggleCommand = $command(
"ToggleFeature",
(ctx) => () => (state, dispatch) => {
const isActive = checkIfActive(state);
return isActive
? removeFeature(state, dispatch)
: addFeature(state, dispatch);
},
);
```
### Insert Commands
```typescript
const insertCommand = $command(
"InsertContent",
(ctx) => (content: string) => (state, dispatch) => {
const { selection } = state;
if (!selection) return false;
const tr = state.tr.insertText(content, selection.from);
dispatch?.(tr);
return true;
},
);
```
### Transform Commands
```typescript
const transformCommand = $command(
"TransformContent",
(ctx) => (transform: (node: ProseNode) => ProseNode) => (state, dispatch) => {
const { selection } = state;
if (!selection) return false;
const tr = state.tr.replaceWith(
selection.from,
selection.to,
transform(state.doc.nodeAt(selection.from)!),
);
dispatch?.(tr);
return true;
},
);
```
+39
View File
@@ -0,0 +1,39 @@
# FAQ
This page lists answers of FAQ.
---
### How can I change contents programmatically?
You should use `editor.action` to change the contents.
We provide two macros for that allow you to change content in milkdown, `insert` and `replaceAll`.
```typescript
import { insert, replaceAll } from "@milkdown/kit/utils";
const editor = await Editor.make()
// .use(<All Your Plugins>)
.create();
editor.action(insert("# New Heading"));
editor.action(replaceAll("# New Document"));
```
---
### How to configure remark?
```typescript
import { remarkStringifyOptionsCtx } from "@milkdown/kit/core";
editor.config((ctx) => {
ctx.set(remarkStringifyOptionsCtx, {
// some options, for example:
bullet: "*",
fences: true,
incrementListMarker: false,
});
});
```
+165
View File
@@ -0,0 +1,165 @@
# Getting Started with Milkdown
Milkdown is a powerful WYSIWYG markdown editor that combines the simplicity of markdown with the flexibility of a modern editor. It's designed to be lightweight yet extensible, making it perfect for both simple and complex editing needs.
## Quick Start
The fastest way to get started is using `@milkdown/crepe`:
```bash
npm install @milkdown/crepe
```
```typescript
import { Crepe } from "@milkdown/crepe";
import "@milkdown/crepe/theme/common/style.css";
import "@milkdown/crepe/theme/frame.css";
const crepe = new Crepe({
root: "#app",
defaultValue: "Hello, Milkdown!",
});
crepe.create();
```
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/editor-crepe"}
## Core Concepts
Milkdown consists of two main parts:
1. **Core Package** (`@milkdown/core`)
- Plugin loader
- Internal plugins
2. **Additional Plugins**
- Syntax support
- Commands
- UI components
- Custom features
This modular architecture allows you to enable or disable features as needed, from basic markdown support to advanced features like tables, LaTeX equations, and collaborative editing.
## Key Features
- 📝 **WYSIWYG Markdown** - Write markdown in an elegant way
- 🎨 **Themable** - Create your own theme and publish it as an npm package
- 🎮 **Hackable** - Create your own plugin to support your awesome idea
- 🦾 **Reliable** - Built on top of [prosemirror](https://prosemirror.net/) and [remark](https://github.com/remarkjs/remark)
-**Slash & Tooltip** - Write faster than ever, enabled by a plugin
- 🧮 **Math** - LaTeX math equations support via math plugin
- 📊 **Table** - Table support with fluent ui, via table plugin
- 🍻 **Collaborate** - Shared editing support with [yjs](https://docs.yjs.dev/)
- 💾 **Clipboard** - Support copy and paste markdown, via clipboard plugin
- 👍 **Emoji** - Support emoji shortcut and picker, via emoji plugin
## Tech Stack
Milkdown is built on top of these powerful libraries:
- [Prosemirror](https://prosemirror.net/) - A toolkit for building rich-text editors on the web
- [Remark](https://github.com/remarkjs/remark) - Markdown parser done right
- [TypeScript](https://www.typescriptlang.org/) - For type safety and better developer experience
## Creating Your First Editor
Milkdown provides two distinct approaches to create an editor, each suited for different needs:
### 1. 🍼 Using `@milkdown/kit` (Build from Scratch)
This approach gives you complete control over your editor. Use this if you want to:
- Build a custom editor from the ground up
- Have full control over which features to include
- Create a highly customized editing experience
- Integrate with specific frameworks or requirements
First, install the required packages:
```bash
npm install @milkdown/kit
```
Create a basic editor with commonmark syntax:
```typescript
import { Editor } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
// This is the must have css for prosemirror
import "@milkdown/kit/prose/view/style/prosemirror.css";
Editor.make().use(commonmark).create();
```
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/vanilla-commonmark"}
Add undo & redo support:
```typescript
import { Editor } from "@milkdown/kit/core";
import { history } from "@milkdown/kit/plugin/history";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { nord } from "@milkdown/theme-nord";
import "@milkdown/theme-nord/style.css";
const milkdown = Editor.make()
.config(nord)
.use(commonmark)
.use(history)
.create()
.then(() => {
console.log("Editor created");
});
// To destroy the editor
milkdown.destroy();
```
> **Note**: `<Mod>` is `<Cmd>` for macOS and `<Ctrl>` for other platforms.
### 2. 🥞 Using `@milkdown/crepe` (Ready to Use)
This is the quickest way to get started with a fully-featured editor. Use this if you want to:
- Get up and running quickly
- Have a well-designed editor out of the box
- Focus on content rather than configuration
- Have a production-ready solution with minimal setup
```bash
npm install @milkdown/crepe
```
```typescript
import { Crepe } from "@milkdown/crepe";
import "@milkdown/crepe/theme/common/style.css";
/**
* Available themes:
* frame, classic, nord
* frame-dark, classic-dark, nord-dark
*/
import "@milkdown/crepe/theme/frame.css";
const crepe = new Crepe({
root: "#app",
defaultValue: "Hello, Milkdown!",
});
crepe.create().then(() => {
console.log("Editor created");
});
// To destroy the editor
crepe.destroy();
```
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/editor-crepe"}
## Next Steps
- Learn more about [overview](/guide/architecture-overview)
- Explore [available plugins](/plugins/using-plugins)
- Check out [theming](/guide/theming)
> 🍼 Fun fact: This documentation is rendered by Milkdown itself!
@@ -0,0 +1,398 @@
# Interacting with Editor
This guide covers the essential ways to interact with the Milkdown editor, including initialization, content management, and editor lifecycle.
## Using Crepe Editor
---
Crepe is a high-level wrapper around Milkdown that provides a simpler API for common editor operations. Here's how to use it:
```typescript
import { Crepe } from "@milkdown/crepe";
// Create a new editor instance
const editor = new Crepe({
// Optional: specify root element (DOM node or selector)
root: "#editor",
// Optional: set default content, supports markdown, json and dom.
defaultValue: "# Hello Crepe!",
});
// Create the editor
await editor.create();
// Get markdown content
const markdown = editor.getMarkdown();
// Set readonly mode
editor.setReadonly(true);
// Register event listeners
editor.on((listener) => {
listener.markdownUpdated((ctx, markdown) => {
console.log("Content updated:", markdown);
});
listener.focus((ctx) => {
console.log("Editor focused");
});
listener.blur((ctx) => {
console.log("Editor blurred");
});
listener.selectionUpdated((ctx, selection, prevSelection) => {
console.log("Selection updated:", selection);
});
listener.updated((ctx, doc, prevDoc) => {
console.log("Document updated:", doc);
});
});
// Destroy the editor when done
await editor.destroy();
```
## Register to DOM
---
By default, milkdown will create editor on the `document.body`. Alternatively, you can also point out which dom node you want it to load into:
```typescript
import { rootCtx } from "@milkdown/kit/core";
Editor.make().config((ctx) => {
ctx.set(rootCtx, document.querySelector("#editor"));
});
```
It's also possible to just pass a selector to `rootCtx`:
> The selector will be passed to `document.querySelector` to get the dom.
```typescript
import { rootCtx } from "@milkdown/kit/core";
Editor.make().config((ctx) => {
ctx.set(rootCtx, "#editor");
});
```
## Setting Default Value
---
We support three types of default values:
- Markdown strings
- HTML DOM
- Prosemirror documentation JSON
### Markdown
You can set a markdown string as the default value of the editor.
```typescript
import { defaultValueCtx } from "@milkdown/kit/core";
const defaultValue = "# Hello milkdown";
Editor.make().config((ctx) => {
ctx.set(defaultValueCtx, defaultValue);
});
```
### Dom
You can also use HTML as default value.
Let's assume that we have the following html snippets:
```html
<div id="pre">
<h1>Hello milkdown!</h1>
</div>
```
Then we can use it as a defaultValue with a `type` specification:
```typescript
import { defaultValueCtx } from "@milkdown/kit/core";
const defaultValue = {
type: "html",
dom: document.querySelector("#pre"),
};
Editor.make().config((ctx) => {
ctx.set(defaultValueCtx, defaultValue);
});
```
### JSON
We can also use a JSON object as a default value.
This JSON object can be obtained by a listener through the [listener-plugin](https://www.npmjs.com/package/@milkdown/plugin-listener), for example:
```typescript
import { listener, listenerCtx } from "@milkdown/kit/plugin/listener";
let jsonOutput;
Editor.make()
.config((ctx) => {
ctx.get(listenerCtx).updated((ctx, doc, prevDoc) => {
jsonOutput = doc.toJSON();
});
})
.use(listener);
```
Then we can use this `jsonOutput` as default Value:
```typescript
import { defaultValueCtx } from "@milkdown/kit/core";
const defaultValue = {
type: "json",
value: jsonOutput,
};
Editor.make().config((ctx) => {
ctx.set(defaultValueCtx, defaultValue);
});
```
## Inspecting Editor Status
---
You can inspect the editor's status through the `status` property.
```typescript
import { Editor, EditorStatus } from "@milkdown/kit/core";
const editor = Editor.make().use(/* some plugins */);
assert(editor.status === EditorStatus.Idle);
editor.create().then(() => {
assert(editor.status === EditorStatus.Created);
});
assert(editor.status === EditorStatus.OnCreate);
editor.destroy().then(() => {
assert(editor.status === EditorStatus.Destroyed);
});
assert(editor.status === EditorStatus.OnDestroyed);
```
You can also listen to the status changes:
```typescript
import { Editor, EditorStatus } from "@milkdown/kit/core";
const editor = Editor.make().use(/* some plugins */);
editor.onStatusChange((status: EditorStatus) => {
console.log(status);
});
```
### Status Lifecycle
1. `Idle`: Initial state
2. `OnCreate`: During creation
3. `Created`: Successfully created
4. `OnDestroyed`: During destruction
5. `Destroyed`: Successfully destroyed
## Adding Listeners
---
As mentioned above, you can add a listener to the editor, in order to get its value when needed.
You can add as many listeners as you want, all the listeners will be triggered at once.
### Markdown Listener
You can add markdown listener to get the editor's contents as a markdown string.
> ⚠️ Markdown listener will influence the performance for large documents, please use it carefully.
> If you have a large document, I suggest you to only `parse` and `serialize` the document when needed.
```typescript
import { listener, listenerCtx } from "@milkdown/kit/plugin/listener";
let output = "";
Editor.make()
.config((ctx) => {
ctx.get(listenerCtx).markdownUpdated((ctx, markdown, prevMarkdown) => {
output = markdown;
});
})
.use(listener);
```
### Doc Listener
You can also listen to the [raw prosemirror document node](https://prosemirror.net/docs/ref/#model.Node), and do things you want from there.
```typescript
import { listener, listenerCtx } from "@milkdown/kit/plugin/listener";
let jsonOutput;
Editor.make()
.config((ctx) => {
ctx.get(listenerCtx).updated((ctx, doc, prevDoc) => {
jsonOutput = doc.toJSON();
});
})
.use(listener);
```
### Selection Listener
You can track changes to the editor's selection using the `selectionUpdated` event. This is useful for implementing features like:
- Custom toolbars that update based on selection
- Context menus
- Selection-based formatting controls
```typescript
import { listener, listenerCtx } from "@milkdown/kit/plugin/listener";
import { Selection, TextSelection } from "@milkdown/prose/state";
Editor.make()
.config((ctx) => {
ctx.get(listenerCtx).selectionUpdated((ctx, selection, prevSelection) => {
if (selection instanceof TextSelection) {
// Get selection range
const { from, to } = selection;
// Example: Update toolbar based on selection
updateToolbar({
hasSelection: from !== to,
selectionStart: from,
selectionEnd: to,
});
}
});
})
.use(listener);
```
The selection listener will be triggered when the selection is changed.
So you don't need to compare them manually.
For more details about listeners, please check [Using Listeners](/docs/api/plugin-listener).
## Readonly Mode
---
You can set the editor to readonly mode by setting the `editable` property.
```typescript
import { editorViewOptionsCtx } from "@milkdown/kit/core";
let readonly = false;
const editable = () => !readonly;
Editor.make().config((ctx) => {
ctx.update(editorViewOptionsCtx, (prev) => ({
...prev,
editable,
}));
});
// set to readonly after 5 secs.
setTimeout(() => {
readonly = true;
}, 5000);
```
### Use Cases for Readonly Mode
- Preview mode
- Document review
- Print-friendly views
- Mobile device optimization
## Using Actions
---
You can use an action to get the context value in a running editor on demand.
For example, to get the markdown string by running an action:
```typescript
import { Editor, editorViewCtx, serializerCtx } from "@milkdown/kit/core";
async function playWithEditor() {
const editor = await Editor.make().use(commonmark).create();
const getMarkdown = () =>
editor.action((ctx) => {
const editorView = ctx.get(editorViewCtx);
const serializer = ctx.get(serializerCtx);
return serializer(editorView.state.doc);
});
// get markdown string:
getMarkdown();
}
```
We provide some macros out of the box, you can use them as actions:
```typescript
import { insert } from "@milkdown/kit/utils";
editor.action(insert("# Hello milkdown"));
```
### Common Actions
- Insert content
- Get current selection
- Apply formatting
- Execute commands
For more details about macros, please check [macros](/docs/guide/macros).
## Destroying
---
You can call `editor.destroy` to destroy an existing editor. You can create a new editor again with `editor.create`.
```typescript
await editor.destroy();
// Then create again
await editor.create();
```
If you just want to recreate the editor, you can use `editor.create`, it will **destroy the old editor and create a new one**.
```typescript
await editor.create();
// This equals to call `editor.destroy` and `editor.create` again.
await editor.create();
```
If you want to **clear the plugins and configs for the editor** when calling `editor.destroy`, you can pass `true` to `editor.destroy`.
```typescript
await editor.destroy(true);
```
+252
View File
@@ -0,0 +1,252 @@
# Keyboard Shortcuts
Keyboard shortcuts are a crucial part of the editor's user experience. Milkdown provides a flexible system for configuring keyboard shortcuts through presets and plugins.
## Default Shortcuts
---
Milkdown comes with a set of default keyboard shortcuts from both presets and plugins. Here's a comprehensive list of all internal shortcuts:
> #### 💡 Note
>
> `Mod` represents the platform-specific modifier key:
>
> - Windows/Linux: `Ctrl`
> - macOS: `Command`
### Commonmark Preset Shortcuts
#### Headings
| Shortcut | Description |
| -------------------- | ----------------------- |
| `Mod-Alt-1` | Turn block into h1 |
| `Mod-Alt-2` | Turn block into h2 |
| `Mod-Alt-3` | Turn block into h3 |
| `Mod-Alt-4` | Turn block into h4 |
| `Mod-Alt-5` | Turn block into h5 |
| `Mod-Alt-6` | Turn block into h6 |
| `Delete`/`Backspace` | Downgrade heading level |
#### Block Elements
| Shortcut | Description |
| ------------- | ---------------------------- |
| `Mod-Shift-b` | Wrap selection in blockquote |
| `Mod-Shift-8` | Wrap in bullet list |
| `Mod-Shift-7` | Wrap in ordered list |
| `Mod-Shift-c` | Wrap in code block |
| `Shift-Enter` | Insert hard break |
| `Mod-Alt-0` | Wrap in paragraph |
#### Text Formatting
| Shortcut | Description |
| -------- | ------------------ |
| `Mod-b` | Toggle bold |
| `Mod-i` | Toggle italic |
| `Mod-e` | Toggle inline code |
### GFM Preset Shortcuts
#### Text Formatting
| Shortcut | Description |
| ----------- | -------------------- |
| `Mod-Alt-x` | Toggle strikethrough |
#### Tables
| Shortcut | Description |
| ------------------- | -------------------------------- |
| `Mod-]` | Move to next cell |
| `Mod-[` | Move to previous cell |
| `Mod-Enter`/`Enter` | Exit table and break if possible |
## Configuring Shortcuts
---
You can customize keyboard shortcuts by configuring the keymap in the editor setup:
```typescript
import { blockquoteKeymap, commonmark } from "@milkdown/kit/preset/commonmark";
Editor.make()
.config((ctx) => {
ctx.set(blockquoteKeymap.key, {
WrapInBlockquote: "Mod-Shift-b",
// or you may want to bind multiple keys:
WrapInBlockquote: ["Mod-Shift-b", "Mod-b"],
});
})
.use(commonmark);
```
## Defining Keymaps
---
Keymaps in Milkdown are defined using the `$useKeymap` utility. Here's how to define keymaps for different features:
### Heading Keymap Example
```typescript
import { $useKeymap } from "@milkdown/utils";
import { commandsCtx } from "@milkdown/core";
export const headingKeymap = $useKeymap("headingKeymap", {
TurnIntoH1: {
shortcuts: "Mod-Alt-1",
command: (ctx) => {
const commands = ctx.get(commandsCtx);
return () => commands.call(wrapInHeadingCommand.key, 1);
},
},
TurnIntoH2: {
shortcuts: "Mod-Alt-2",
command: (ctx) => {
const commands = ctx.get(commandsCtx);
return () => commands.call(wrapInHeadingCommand.key, 2);
},
},
// ... more heading levels
DowngradeHeading: {
shortcuts: ["Delete", "Backspace"],
command: (ctx) => {
const commands = ctx.get(commandsCtx);
return () => commands.call(downgradeHeadingCommand.key);
},
},
});
```
### Strong (Bold) Keymap Example
```typescript
import { $useKeymap } from "@milkdown/utils";
import { commandsCtx } from "@milkdown/core";
export const strongKeymap = $useKeymap("strongKeymap", {
ToggleBold: {
shortcuts: ["Mod-b"],
command: (ctx) => {
const commands = ctx.get(commandsCtx);
return () => commands.call(toggleStrongCommand.key);
},
},
});
```
### Keymap Structure
Each keymap definition follows this structure:
```typescript
$useKeymap('keymapName', {
CommandName: {
shortcuts: string | string[], // Single shortcut or array of shortcuts
priority?: number, // (Optional) Priority of the shortcut
command: (ctx) => () => { // Command to execute
const commands = ctx.get(commandsCtx);
return () => commands.call(commandKey, ...args);
},
},
});
```
## Creating Custom Shortcuts
---
If you need to add custom shortcuts, you can create a keymap plugin:
```typescript
import { $useKeymap } from "@milkdown/utils";
import { commandsCtx } from "@milkdown/core";
const customKeymap = $useKeymap("customKeymap", {
CustomCommand: {
shortcuts: "F1",
command: (ctx) => {
const commands = ctx.get(commandsCtx);
return () => commands.call(someCommand.key);
},
},
});
// Usage
Editor.make().use(customKeymap).use(commonmark);
```
### Example: Custom Command with Shortcut
```typescript
import { $command, $useKeymap } from "@milkdown/utils";
import { commandsCtx } from "@milkdown/core";
// Create a custom command
const customCommand = $command("CustomCommand", (ctx) => () => {
return (state, dispatch) => {
// Command implementation
return true;
};
});
// Create a keymap
const customKeymap = $useKeymap("customKeymap", {
CustomCommand: {
shortcuts: ["F1", "Mod-F1"], // Multiple shortcuts
command: (ctx) => {
const commands = ctx.get(commandsCtx);
return () => commands.call(customCommand.key);
},
},
});
// Usage
Editor.make().use(customCommand).use(customKeymap);
```
## Shortcut Priority
You can control the order in which shortcuts are handled by specifying a `priority` property. Shortcuts with higher priority values are handled before those with lower values. This is useful if you want your custom shortcut to override or take precedence over other shortcuts that use the same key combination.
When multiple shortcuts are registered for the same key, they are executed in order of priority. If a shortcut command returns `false`, the next shortcut with the same key will be tried. If it returns `true`, no further commands for that key will be run. This allows you to chain or override shortcut behaviors as needed.
- The default priority is **50**.
- Normal priority values should be between **1** and **100**.
- Use higher numbers to ensure your shortcut is registered before others with the same key.
#### Example: Using Priority
```typescript
import { $useKeymap } from "@milkdown/utils";
import { commandsCtx } from "@milkdown/core";
export const customKeymap = $useKeymap("customKeymap", {
CustomBold: {
shortcuts: "Mod-b",
priority: 100, // Highest in the normal range, so this runs first
command: (ctx) => {
const commands = ctx.get(commandsCtx);
return () => {
// Custom bold logic
return true;
};
},
},
CustomAnotherBold: {
shortcuts: "Mod-b",
priority: 75, // Lower priority, will run only if CustomBold returns false
command: (ctx) => {
const commands = ctx.get(commandsCtx);
return () => {
// Custom italic logic
return true;
};
},
},
});
```
+278
View File
@@ -0,0 +1,278 @@
# Macros
Macros are helper functions that provide a convenient way to interact with the editor. They take a payload (or nothing) as parameters and return a callback function that takes the `ctx` of milkdown as a parameter. When called with `ctx`, they apply the specified action to the editor.
## Usage
There are two main ways to use macros:
```typescript
import { insert } from "@milkdown/kit/utils";
import { listenerCtx } from "@milkdown/plugin-listener";
// Method 1: Using editor.action()
editor.action(insert("# Hello Macro"));
// Method 2: Using listener
editor.config((ctx) => {
ctx.get(listenerCtx).mounted(insert("# Default Title"));
});
```
## Available Macros
### Content Manipulation
#### `insert`
Inserts content at the current cursor position. The macro accepts two parameters:
- `markdown`: The markdown string to insert
- `inline`: Optional boolean flag (default: false) that determines how the content is inserted
```typescript
import { insert } from "@milkdown/kit/utils";
// Insert as block content (default)
editor.action(insert("# Hello World"));
// Insert as inline content
editor.action(insert("inline text", true));
```
The behavior differs based on the `inline` parameter:
- When `inline` is `false` (default):
- Replaces the current selection with the parsed markdown content
- Maintains the selection's open start/end positions
- Scrolls the view to show the inserted content
- When `inline` is `true`:
- Attempts to insert the content as inline text
- If the content is text-only, replaces the selection with a text node
- Otherwise, replaces the selection with the parsed content
#### `insertPos`
Inserts markdown at a given position. The macro accepts two parameters:
- `markdown`: The markdown string to insert
- `pos`: The position to insert the content at
```typescript
import { insertPos } from "@milkdown/kit/utils";
// Insert "Hello" at the beginning of the document
editor.action(insertPos("Hello", 0));
```
#### `replaceAll`
Replaces all content in the editor. The macro accepts two parameters:
- `markdown`: The markdown string to replace the current content with
- `flush`: Optional boolean flag (default: false) that determines how the replacement is performed
```typescript
import { replaceAll } from "@milkdown/kit/utils";
// Replace content without flushing state
editor.action(replaceAll("# New Content"));
// Replace content and flush editor state
editor.action(replaceAll("# New Content", true));
```
The behavior differs based on the `flush` parameter:
- When `flush` is `false` (default):
- Replaces the entire document content with the new markdown
- Maintains the current editor state
- More efficient for simple content replacements
- When `flush` is `true`:
- Creates a new editor state with the new content
- Reinitializes all plugins
- Useful when you need a completely fresh editor state
#### `replaceRange`
Replaces the content of the given range with a markdown string.
```typescript
import { replaceRange } from "@milkdown/kit/utils";
// Replace content from position 0 to 5 with "Hello"
editor.action(replaceRange("Hello", { from: 0, to: 5 }));
```
### Content Retrieval
#### `getMarkdown`
Gets the current content as markdown. If a range is provided, it will return the markdown for that range; otherwise, it will return the markdown for the entire document.
```typescript
import { getMarkdown } from "@milkdown/kit/utils";
// Get markdown for the entire document
const markdown = editor.action(getMarkdown());
// Get markdown for a specific range
const selectionMarkdown = editor.action(getMarkdown({ from: 0, to: 5 }));
```
#### `getHTML`
Gets the current content as HTML.
```typescript
import { getHTML } from "@milkdown/kit/utils";
const html = editor.action(getHTML());
```
### Editor State
#### `forceUpdate`
Forces the editor to update its state.
```typescript
import { forceUpdate } from "@milkdown/kit/utils";
editor.action(forceUpdate());
```
#### `setAttr`
Sets attributes for a node at a specific position. The macro accepts two parameters:
- `pos`: The position of the node to update
- `update`: A function that takes the previous attributes and returns the new attributes
```typescript
import { setAttr } from "@milkdown/kit/utils";
// Update node attributes at position 10
editor.action(
setAttr(10, (prevAttrs) => ({
...prevAttrs,
class: "custom-class",
})),
);
// Example: Update heading level
editor.action(
setAttr(10, (prevAttrs) => ({
...prevAttrs,
level: 2,
})),
);
```
The macro:
- Takes a specific position in the document
- Retrieves the node at that position
- Applies the update function to modify the node's attributes
- Dispatches the changes to update the editor state
Note: The position must be valid and contain a node, otherwise the operation will be ignored.
### Navigation
#### `outline`
Gets the outline of the document.
```typescript
import { outline } from "@milkdown/kit/utils";
const docOutline = editor.action(outline());
```
### Command Execution
#### `callCommand`
Calls a registered command with optional payload. The macro has two overloads:
Examples:
```typescript
import { callCommand } from "@milkdown/kit/utils";
import { wrapInHeadingCommand } from "@milkdown/plugin-heading";
// Using command key
editor.action(callCommand(wrapInHeadingCommand.key, 1));
// With complex payload
editor.action(
callCommand("CustomCommand", {
type: "heading",
level: 1,
content: "New Heading",
}),
);
```
The macro:
- Takes a command key
- Optionally accepts a payload parameter
- Returns a boolean indicating whether the command was successful
Note: The command must be registered in the editor's command context before it can be called.
### Utility Macros
#### `markdownToSlice`
Converts a markdown string to a [slice](https://prosemirror.net/docs/ref/#model.Slice). This is useful when you need to manipulate the content before inserting it into the editor.
```typescript
import { markdownToSlice } from "@milkdown/kit/utils";
const slice = editor.action(markdownToSlice("# Hello Slice"));
```
## Examples
### Adding Content
```typescript
import { insert } from "@milkdown/kit/utils";
import { listenerCtx } from "@milkdown/plugin-listener";
editor.config((ctx) => {
ctx.get(listenerCtx).mounted(insert("# Welcome\nStart editing..."));
});
```
### Saving Content
```typescript
import { getMarkdown } from "@milkdown/kit/utils";
editor.config((ctx) => {
ctx.get(listenerCtx).updated(() => {
const content = getMarkdown()(ctx);
localStorage.setItem("editor-content", content);
});
});
```
### Custom Command with Macro
```typescript
import { callCommand } from "@milkdown/kit/utils";
editor.action(
callCommand("customCommand", {
type: "heading",
level: 1,
content: "New Heading",
}),
);
```
For more details about each macro's parameters and return types, check the [API Reference](/docs/api/utils#macros).
+38
View File
@@ -0,0 +1,38 @@
# Prosemirror API
Milkdown is built on top of prosemirror. Which means you can use the entire prosemirror API in Milkdown.
To access the prosemirror API, you can use the `@milkdown/prose` package. It re-exports all of the prosemirror API.
Using this package you can make sure that you are using the same version of prosemirror as Milkdown.
## Installation
To access a certain API in the `prosemirror-x` package, you need to import them from `@milkdown/kit/prose/x`.
For example:
```ts
// Originally in prosemirror-state
import { EditorState } from "@milkdown/kit/prose/state";
// Originally in prosemirror-view
import { EditorView } from "@milkdown/kit/prose/view";
```
## List of packages
The following is a list of all the re-exported prosemirror API.
- `@milkdown/kit/prose/changeset`
- `@milkdown/kit/prose/commands`
- `@milkdown/kit/prose/dropcursor`
- `@milkdown/kit/prose/gapcursor`
- `@milkdown/kit/prose/history`
- `@milkdown/kit/prose/inputrules`
- `@milkdown/kit/prose/keymap`
- `@milkdown/kit/prose/model`
- `@milkdown/kit/prose/schema-list`
- `@milkdown/kit/prose/state`
- `@milkdown/kit/prose/transform`
- `@milkdown/kit/prose/view`
- `@milkdown/kit/prose/tables`
You can find the documentation of the prosemirror API [here](https://prosemirror.net/docs/ref/).
+215
View File
@@ -0,0 +1,215 @@
# Styling Guide
Milkdown is a headless editor, which means it doesn't come with any default styles. This gives you complete control over the appearance of your editor. You can either use existing themes or create your own custom styling solution.
# Styling Crepe Theme
---
Crepe is a collection of themes for Milkdown that provides both light and dark variants. The theme structure is organized as follows:
```
theme/
├── common/ # Shared styles and utilities
├── crepe/ # Light theme variant
├── crepe-dark/ # Dark theme variant
├── frame/ # Frame theme (light)
├── frame-dark/ # Frame theme (dark)
├── nord/ # Nord theme (light)
└── nord-dark/ # Nord theme (dark)
```
## Using Crepe Theme
To use the Crepe theme in your project:
```ts
// Import base styles first
import "@milkdown/crepe/theme/common/style.css";
// Choose the theme you want to use
import "@milkdown/crepe/theme/crepe.css";
```
## Theme Variables
Crepe theme uses CSS variables for consistent styling. Here are all the available variables:
### Colors
```css
.milkdown {
/* Background Colors */
--crepe-color-background: #fffdfb; /* Main background color */
--crepe-color-surface: #fff8f4; /* Surface color for cards/panels */
--crepe-color-surface-low: #fff1e5; /* Lower surface color for depth */
/* Text Colors */
--crepe-color-on-background: #1f1b16; /* Text color on background */
--crepe-color-on-surface: #201b13; /* Text color on surface */
--crepe-color-on-surface-variant: #4f4539; /* Secondary text color */
/* Accent Colors */
--crepe-color-primary: #805610; /* Primary brand color */
--crepe-color-secondary: #fbdebc; /* Secondary accent color */
--crepe-color-on-secondary: #271904; /* Text color on secondary */
/* UI Colors */
--crepe-color-outline: #817567; /* Border/outline color */
--crepe-color-inverse: #362f27; /* Inverse color for contrast */
--crepe-color-on-inverse: #fcefe2; /* Text color on inverse */
--crepe-color-inline-code: #ba1a1a; /* Inline code color */
--crepe-color-error: #ba1a1a; /* Error state color */
/* Interactive Colors */
--crepe-color-hover: #f9ecdf; /* Hover state color */
--crepe-color-selected: #ede0d4; /* Selected state color */
--crepe-color-inline-area: #e4d8cc; /* Inline editing area color */
}
```
### Typography
```css
.milkdown {
/* Font Families */
--crepe-font-title: Georgia, Cambria, "Times New Roman", Times, serif;
--crepe-font-default: "Open Sans", Arial, Helvetica, sans-serif;
--crepe-font-code:
Fira Code, Menlo, Monaco, "Courier New", Courier, monospace;
}
```
### Shadows
```css
.milkdown {
/* Small Shadow */
--crepe-shadow-1:
0px 1px 3px 1px rgba(0, 0, 0, 0.15), 0px 1px 2px 0px rgba(0, 0, 0, 0.3);
/* Large Shadow */
--crepe-shadow-2:
0px 2px 6px 2px rgba(0, 0, 0, 0.15), 0px 1px 2px 0px rgba(0, 0, 0, 0.3);
}
```
## Customizing Crepe Theme
You can customize the Crepe theme by overriding its variables:
```css
/* custom-overrides.css */
.crepe .milkdown {
/* Override colors */
--crepe-color-primary: #your-primary-color;
--crepe-color-background: #your-background-color;
/* Override typography */
--crepe-font-default: "Your Font", sans-serif;
/* Override shadows */
--crepe-shadow-1: your-shadow-value;
}
```
# Styling Milkdown
---
## Basic Styling
The editor is rendered within a container that has the class `.milkdown`, and the editable content area is wrapped in a container with the class `.editor`. You can use these classes to scope your styles:
```css
/* Basic styling example */
.milkdown .editor {
max-width: 800px;
margin: 0 auto;
padding: 1rem;
}
.milkdown .editor p {
margin: 1rem 0;
line-height: 1.6;
}
```
## Node and Mark Classes
Milkdown provides default class names for each node and mark. Here are some common examples:
```css
/* Paragraph styling */
.milkdown .editor .paragraph {
margin: 1rem 0;
}
/* Heading styling */
.milkdown .editor .heading {
font-weight: 600;
margin: 1.5rem 0 1rem;
}
/* List styling */
.milkdown .editor .bullet-list {
padding-left: 1.5rem;
}
.milkdown .editor .ordered-list {
padding-left: 1.5rem;
}
```
## Custom Attributes
You can add custom attributes to nodes and marks, which is particularly useful when working with CSS frameworks like Tailwind CSS.
```typescript
import { Editor, editorViewOptionsCtx } from "@milkdown/kit/core";
import {
commonmark,
headingAttr,
paragraphAttr,
} from "@milkdown/kit/preset/commonmark";
Editor.make()
.config((ctx) => {
// Add attributes to the editor container
ctx.update(editorViewOptionsCtx, (prev) => ({
...prev,
attributes: {
class: "milkdown-editor mx-auto outline-hidden",
spellcheck: "false",
},
}));
// Add attributes to nodes and marks
ctx.set(headingAttr.key, (node) => {
const level = node.attrs.level;
return {
class: `heading-${level} font-bold`,
"data-level": level,
};
});
ctx.set(paragraphAttr.key, () => ({
class: "text-base leading-relaxed",
}));
})
.use(commonmark);
```
# Best Practices
---
1. **Use CSS Variables**: Define your theme's colors and spacing using CSS variables for easy customization.
2. **Responsive Design**: Ensure your editor styles work well on different screen sizes.
3. **Dark Mode Support**: Consider adding dark mode support using CSS variables and media queries.
4. **Accessibility**: Maintain good contrast ratios and readable font sizes.
5. **Performance**: Keep your CSS selectors specific and avoid overly complex rules.
For more examples and inspiration, check out:
- [@milkdown/theme-nord](https://github.com/Milkdown/milkdown/tree/main/packages/theme-nord)
- [@milkdown/crepe/theme](https://github.com/Milkdown/milkdown/tree/main/packages/crepe/src/theme)
+234
View File
@@ -0,0 +1,234 @@
# Using Crepe Editor
Crepe is a powerful, feature-rich Markdown editor built on top of Milkdown. It provides a complete editing experience with a beautiful UI and extensive customization options.
## Why Choose Crepe?
---
- 🚀 **Ready to Use**: Works out of the box with sensible defaults
- 🎨 **Beautiful UI**: Modern design with multiple theme options
- 🔧 **Highly Customizable**: Extensive configuration options
- 📦 **Feature Complete**: Includes all essential Markdown editing features
- 🛠️ **Extensible**: Built on Milkdown's plugin system
## Quick Start
---
### Installation
```bash
# Using npm
npm install @milkdown/crepe
# Using yarn
yarn add @milkdown/crepe
# Using pnpm
pnpm add @milkdown/crepe
```
### Basic Usage
```typescript
import { Crepe } from "@milkdown/crepe";
import "@milkdown/crepe/theme/common/style.css";
import "@milkdown/crepe/theme/frame.css";
// Choose your preferred theme
// Create editor instance
const crepe = new Crepe({
root: document.getElementById("app"),
defaultValue: "# Hello, Crepe!\n\nStart writing your markdown...",
});
// Initialize the editor
await crepe.create();
// Clean up when done
crepe.destroy();
```
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/editor-crepe"}
## Themes
---
Crepe comes with several beautiful themes out of the box:
### Light Themes
- `frame` - Modern frame-based design
- `classic` - Traditional editor look
- `nord` - Clean, minimal Nord color scheme
### Dark Themes
- `frame-dark` - Dark version of frame theme
- `classic-dark` - Dark version of classic theme
- `nord-dark` - Dark version of nord theme
To use a theme:
```typescript
// Import base styles first
import "@milkdown/crepe/theme/common/style.css";
// Then import your chosen theme
import "@milkdown/crepe/theme/frame.css";
```
### Custom Themes
You can create your own theme by extending the base styles. Check out the [existing themes](https://github.com/Milkdown/milkdown/tree/main/packages/crepe/src/theme) for reference.
## Features
---
Crepe includes a comprehensive set of features that can be enabled or disabled as needed.
### Feature Configuration
> **Note**: For any configuration that ends with `Icon` (like `boldIcon`, `linkIcon`, etc.), you can use a HTML string or a simply string. This applies to all icon configurations throughout Crepe's features.
```typescript
const crepe = new Crepe({
features: {
// Disable specific features
[Crepe.Feature.CodeMirror]: false,
[Crepe.Feature.Table]: false,
},
featureConfigs: {
// Configure feature behavior
[Crepe.Feature.LinkTooltip]: {
inputPlaceholder: "Enter URL...",
},
},
});
```
### Available Features
#### 1. Code Editor (`CodeMirror`)
Syntax highlighting and editing for code blocks with language support, theme customization, and preview capabilities.
#### 2. List Management (`ListItem`)
Support for bullet lists, ordered lists, and todo lists with customizable icons and formatting.
#### 3. Link Management (`LinkTooltip`)
Enhanced link editing and preview with customizable tooltips, edit/remove actions, and copy functionality.
#### 4. Image Handling (`ImageBlock`)
Image upload and management with resizing, captions, and support for both inline and block images.
#### 5. Block Editing (`BlockEdit`)
Drag-and-drop block management and slash commands for quick content insertion and organization.
#### 6. Table Support (`Table`)
Full-featured table editing with row/column management, alignment options, and drag-and-drop functionality.
#### 7. Toolbar (`Toolbar`)
Formatting toolbar for selected text with customizable icons and actions.
#### 8. Cursor (`Cursor`)
Enhanced cursor experience with drop cursor and gap cursor for better content placement.
#### 9. Placeholder (`Placeholder`)
Document or block level placeholders to guide users when content is empty.
#### 10. Latex (`Latex`)
Mathematical formula support with both inline and block math rendering using KaTeX.
For detailed configuration options of each feature, please refer to the [API documentation](/docs/api/crepe).
## Editor Instance Methods
---
#### `crepe.editor`
Access the underlying Milkdown editor instance.
```typescript
const editor = crepe.editor;
editor.use(customPlugin);
editor.action(insert("Hello"));
```
#### `crepe.create()`
Initialize the editor.
```typescript
await crepe.create();
```
#### `crepe.destroy()`
Clean up the editor instance.
```typescript
crepe.destroy();
```
#### `crepe.setReadonly(value: boolean)`
Toggle readonly mode.
```typescript
crepe.setReadonly(true); // Make editor read-only
crepe.setReadonly(false); // Make editor editable
```
#### `crepe.on`
Add event listeners.
```typescript
crepe.on((listener) => {
listener.markdownUpdated((markdown) => {
console.log("Markdown updated:", markdown);
});
listener.updated((doc) => {
console.log("Document updated");
});
listener.focus(() => {
console.log("Editor focused");
});
listener.blur(() => {
console.log("Editor blurred");
});
});
```
#### `crepe.getMarkdown()`
Get current markdown content.
```typescript
const markdown = crepe.getMarkdown();
```
## Next Steps
---
- Learn about [Milkdown's architecture](/docs/guide/architecture-overview)
- Explore [available plugins](/docs/plugin/using-plugins)
- Read the [API reference](/docs/api/crepe)
+37
View File
@@ -0,0 +1,37 @@
# Using @milkdown/kit
Milkdown provides a set of utilities to help you build your editor.
These utilities are re-exported from the `@milkdown/kit` package.
Thus, you don't need to install the common dependencies manually like `@milkdown/prose`, `@milkdown/core` or `@milkdown/preset-common` in your project.
## What's included
`@milkdown/kit` re-exports the following packages:
| Package | Import path | Scope |
| ---------------------------------------------------------- | ----------------------------------------- | --------- |
| [@milkdown/core](/docs/api/core) | `@milkdown/kit/core` | Framework |
| [@milkdown/ctx](/docs/api/ctx) | `@milkdown/kit/ctx` | Framework |
| [@milkdown/prose](/docs/guide/prosemirror-api) | `@milkdown/kit/prose` | Framework |
| [@milkdown/prose/\*](/docs/guide/prosemirror-api) | `@milkdown/kit/prose/*` | Framework |
| [@milkdown/transformer](/docs/api/transformer) | `@milkdown/kit/transformer` | Framework |
| [@milkdown/utils](/docs/api/utils) | `@milkdown/kit/utils` | Framework |
| [@milkdown/preset-commonmark](/docs/api/preset-commonmark) | `@milkdown/kit/preset/commonmark` | Preset |
| [@milkdown/preset-gfm](/docs/api/preset-gfm) | `@milkdown/kit/preset/gfm` | Preset |
| [@milkdown/plugin-block](/docs/api/plugin-block) | `@milkdown/kit/plugin/block` | Plugin |
| [@milkdown/plugin-clipboard](/docs/api/plugin-clipboard) | `@milkdown/kit/plugin/clipboard` | Plugin |
| [@milkdown/plugin-cursor](/docs/api/plugin-cursor) | `@milkdown/kit/plugin/cursor` | Plugin |
| [@milkdown/plugin-history](/docs/api/plugin-history) | `@milkdown/kit/plugin/history` | Plugin |
| [@milkdown/plugin-indent](/docs/api/plugin-indent) | `@milkdown/kit/plugin/indent` | Plugin |
| [@milkdown/plugin-listener](/docs/api/plugin-listener) | `@milkdown/kit/plugin/listener` | Plugin |
| [@milkdown/plugin-slash](/docs/api/plugin-slash) | `@milkdown/kit/plugin/slash` | Plugin |
| [@milkdown/plugin-tooltip](/docs/api/plugin-tooltip) | `@milkdown/kit/plugin/tooltip` | Plugin |
| [@milkdown/plugin-trailing](/docs/api/plugin-trailing) | `@milkdown/kit/plugin/trailing` | Plugin |
| [@milkdown/plugin-upload](/docs/api/plugin-upload) | `@milkdown/kit/plugin/upload` | Plugin |
| @milkdown/component | `@milkdown/kit/component` | Component |
| @milkdown/component/code-block | `@milkdown/kit/component/code-block` | Component |
| @milkdown/component/image-block | `@milkdown/kit/component/image-block` | Component |
| @milkdown/component/image-inline | `@milkdown/kit/component/image-inline` | Component |
| @milkdown/component/link-tooltip | `@milkdown/kit/component/link-tooltip` | Component |
| @milkdown/component/list-item-block | `@milkdown/kit/component/list-item-block` | Component |
| @milkdown/component/table-block | `@milkdown/kit/component/table-block` | Component |
+30
View File
@@ -0,0 +1,30 @@
# Why Milkdown
There are different kinds of markdown editors, such as [Typora](https://typora.io/), [tui](https://github.com/nhn/tui.editor) and [Bear](https://bear.app/).
They work pretty well for writing notes in markdown on different platforms. So why bother making Milkdown?
Milkdown aims to provide an **open source solution** for developers to make their editors more powerful, and attractive, it also ensures it runs everywhere.
---
## Open Source & Easy to Integrate
Different from industrial apps such as [Notion](https://notion.so) and [Typora](https://typora.io/),
Milkdown is open source and fully free. You can integrate it everywhere legally.
> If you like milkdown, please consider to fund me in order to help with the maintenance.
## Plugin Driven
Milkdown treats every feature as a plugin.
With this pattern, developers can choose what they need in an editor instead of bundling all features even they won't need.
Developers can extend their plugins to satisfy their habits such as defining a vim keymap via a custom plugin.
## Reliable
Milkdown is powered by [Prosemirror](https://prosemirror.net/) and [Remark](https://github.com/remarkjs/remark), which has a large community and stands the test of the industry.
What's more, plugins from the prosemirror and remark community can be easily reused in order to build a Milkdown plugin.
## Themable & Hackable
Themes and plugins for Milkdown can be shared and installed using npm packages. Milkdown is a headless component, which means you can fully control its style.
+90
View File
@@ -0,0 +1,90 @@
# Milkdown
👋 Welcome to Milkdown. We are so glad to see you here!
💭 You may wonder, what is Milkdown? Please write something here.
> ⚠️ **Not the right side!**
>
> Please try something on the left side.
![1.00](/polar.jpeg "Hello by a polar bear")
You're seeing this editor called **🥞Crepe**, which is an editor built on top of Milkdown.
If you want to install this editor, you can run `npm install @milkdown/crepe`. Then you can use it like this:
```js
import { Crepe } from "@milkdown/crepe";
import "@milkdown/crepe/theme/common/style.css";
// We have some themes for you to choose, ex.
import "@milkdown/crepe/theme/frame.css";
// Or you can create your own theme
import "./your-theme.css";
const crepe = new Crepe({
root: "#app",
defaultValue: "# Hello, Milkdown!",
});
crepe.create().then(() => {
console.log("Milkdown is ready!");
});
// Before unmount
crepe.destroy();
```
---
## Structure
> 🍼 [Milkdown][repo] is a WYSIWYG markdown editor framework.
>
> Which means you can build your own markdown editor with Milkdown.
In the real world, a typical milkdown editor is built on top of 3 layers:
- [x] 🥛 Core: The core of Milkdown, which provides the plugin loading system with the editor concepts.
- [x] 🧇 Plugins: A set of plugins that can be used to extend the functionalities of the editor.
- [x] 🍮 Components: Some headless components that can be used to build your own editor.
At the start, you may find it hard to understand all these concepts.
But don't worry, we have this `@milkdown/crepe` editor for you to get started quickly.
---
## You can do more with Milkdown
In Milkdown, you can extend the editor in many ways:
| Feature | Description | Example |
| ------------ | ---------------------------------------------------- | ------------------------- |
| 🎨 Theme | Create your own theme with CSS | Nord, Dracula |
| 🧩 Plugin | Create your own plugin to extend the editor | Search, Collab |
| 📦 Component | Create your own component to build your own editor | Slash Menu, Toolbar |
| 📚 Syntax | Create your own syntax to extend the markdown parser | Image with Caption, LaTex |
We have provided a lot of plugins and components, with an out-of-the-box crepe editor for you to use and learn.
---
## Open Source
- Milkdown is an open-source project under the MIT license.
- Everyone is welcome to contribute to the project, and you can use it in your own project for free.
- Please let me know what you are building with Milkdown, I would be so glad to see that!
Maintaining Milkdown is a lot of work, and we are working on it in our spare time.
If you like Milkdown, please consider supporting us by [sponsoring][sponsor] the project.
We'll be so grateful for your support.
## Who built Milkdown?
Milkdown is built by [Mirone][mirone] and designed by [Meo][meo].
[repo]: https://github.com/Milkdown/milkdown
[mirone]: https://github.com/Saul-Mirone
[meo]: https://meo.cool
[sponsor]: https://github.com/sponsors/Saul-Mirone
@@ -0,0 +1,85 @@
# Composable Plugins
In the previous section, we showed you how to create a plugin from scratch. Luckily, you don't need to do that in most cases. Milkdown provides a lot of helpers in [@milkdown/utils](/docs/api/utils) to make it easier to create plugins. The **composable** here means that you can use the plugin in other plugins. For example, you can use a command plugin in a keymap plugin. This is a very common pattern in Milkdown.
I'll show you some examples of how to use composable plugins. But I won't go into detail about the options and the usage of each plugin. You can find the details in the [API reference](/docs/api/utils#composable).
## Schema
The schema plugin is the most important plugin in Milkdown. It defines the structure of the document. A schema plugin in milkdown is a super set of the [node schema spec](https://prosemirror.net/docs/ref/#model.NodeSpec) or [mark schema spec](https://prosemirror.net/docs/ref/#model.MarkSpec) in ProseMirror.
Let's create a simple blockquote node plugin as an example:
```typescript
import { $node } from "@milkdown/kit/utils";
const blockquote = $node("blockquote", () => ({
content: "block+",
group: "block",
defining: true,
parseDOM: [{ tag: "blockquote" }],
toDOM: (node) => ["blockquote", ctx.get(blockquoteAttr.key)(node), 0],
parseMarkdown: {
match: ({ type }) => type === "blockquote",
runner: (state, node, type) => {
state.openNode(type).next(node.children).closeNode();
},
},
toMarkdown: {
match: (node) => node.type.name === "blockquote",
runner: (state, node) => {
state.openNode("blockquote").next(node.content).closeNode();
},
},
}));
```
## Input Rule
Since we have a blockquote node, we can create an input rule plugin to make it easier to create a blockquote node.
We expect that when we type `> ` at the beginning of a line, the blockquote node will be created.
```typescript
import { wrappingInputRule } from "@milkdown/kit/prose/inputrules";
import { $inputRule } from "@milkdown/kit/utils";
export const wrapInBlockquoteInputRule = $inputRule(() =>
wrappingInputRule(/^\s*>\s$/, blockquoteSchema.type()),
);
```
## Command
We can also create a command plugin to create a blockquote node.
The command is useful when we want to create a button to create a blockquote node.
```typescript
import { wrapIn } from "@milkdown/kit/prose/commands";
import { $command } from "@milkdown/kit/utils";
export const wrapInBlockquoteCommand = $command(
"WrapInBlockquote",
() => () => wrapIn(blockquoteSchema.type()),
);
```
## Shortcut
We can also create a shortcut plugin for blockquote.
Here we use `Ctrl + Shift + B` as the shortcut. When we press this shortcut, the blockquote node will be created.
And we can also use the command we created in the previous section.
```typescript
import { commandsCtx } from "@milkdown/kit/core";
import { $useKeymap } from "@milkdown/kit/utils";
export const blockquoteKeymap = $useKeymap("blockquoteKeymap", {
WrapInBlockquote: {
shortcuts: "Mod-Shift-b",
command: (ctx) => {
const commands = ctx.get(commandsCtx);
return () => commands.call(wrapInBlockquoteCommand.key);
},
},
});
```
@@ -0,0 +1,125 @@
# Example: Block Plugin
The **block plugin** adds a positional hook next to every top-level node (paragraphs, headings, lists, etc.).
It is the foundation for features such as drag handles, quick-insert buttons or block toolbars.
In Milkdown this functionality lives in `@milkdown/plugin-block` and consistent with tooltip & slash consists of:
- a **BlockProvider** that deals with DOM positioning/lifecycle
- a **blockFactory** _implemented internally_ exposed as two ctx slices: `blockSpec`, `blockPlugin`
This guide covers:
- Understanding the provider/service architecture.
- Writing a **vanilla TypeScript** drag handle that lets you reorder blocks.
- Mounting custom UIs in **React** and **Vue**.
- Studying the production-ready _Block Handle_ feature inside Crepe.
---
## 1. Anatomy of a Block Plugin
Unlike tooltip/slash, `@milkdown/plugin-block` ships its factory slices directly:
```ts
import { blockSpec, blockPlugin } from "@milkdown/plugin-block";
```
You normally interact with **BlockProvider** which talks to an internal _BlockService_: the service listens to mouse / drag events, figures out which node is **active** and sends `show` / `hide` messages to the provider.
Your job is to decide how to render a UI for that active node.
Key APIs:
- `new BlockProvider({ ctx, content, ... })` similar to Tooltip/Slash.
- `provider.active` info about the currently focused block (`node`, `pos`, `el`).
- Optional callbacks: `getOffset`, `getPlacement`, `getPosition` for fine-grained positioning.
---
## 2. Minimal Vanilla Drag Handle
Below we build a small **drag handle** that appears on hover and lets you drag-n-drop any block.
```ts
import { block, blockPlugin } from "@milkdown/plugin-block";
import { BlockProvider } from "@milkdown/plugin-block/block-provider"; // path depending on bundler
import { Editor } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
// 1️⃣ Create DOM element for the handle
const handle = document.createElement("div");
handle.className = "drag-handle";
handle.innerHTML = "≡";
handle.style.cssText = `
width:20px;height:20px;display:flex;align-items:center;justify-content:center;
cursor:grab;border-radius:4px;background:#f2f3f5;color:#555;user-select:none;
`;
// 2️⃣ Build provider show only when mouse is over a block
const provider = (ctx: Ctx) => {
const provider = new BlockProvider({
ctx,
content: handle,
getOffset: () => 8,
});
return {
update: provider.update,
destroy: provider.destroy,
};
};
// 3️⃣ Wire provider to Milkdown
const blockConfig = (ctx: Ctx) => {
ctx.set(blockSpec.key, {
view: provider(ctx),
});
};
Editor.make().config(blockConfig).use(commonmark).use(block).create();
```
Drag & Drop:
The HTML element has `cursor:grab`. The internal `BlockService` automatically sets `draggable` and wires ProseMirror's drag-events so you can reorder blocks without extra code 👉 nice!
---
## 3. Framework Examples
### React
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/react-block"}
The React demo renders a `<BlockHandle/>` component, keeps drag state in hooks and feeds the root element to `BlockProvider`.
### Vue
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/vue-block"}
Vue's `<BlockHandle>` uses `Teleport` and reactive refs exactly like the tooltip/slash examples.
---
## 4. Real-world Feature Crepe Block Handle
Crepe brings all the pieces together to create a **block edit** experience that combines a drag handle **and** a plus-button to open the slash menu:
```text
packages/crepe/src/feature/block-edit/handle/
```
Things worth exploring:
1. **Dynamic placement** via `getPlacement` (centred vs top-aligned depending on node height).
2. Filtering nodes with `blockConfig.filterNodes` so handles do not appear inside tables / math / blockquotes.
3. Programmatically showing the _slash menu_ after pressing the "+" button.
---
## 5. Summary & Next Steps
`@milkdown/plugin-block` is the Swiss-army knife for any block-level UI: drag handles, add-buttons, side toolbars…
Combine it with tooltip/slash to build sophisticated editors.
Hack on the examples, tweak positioning callbacks, and ship your own block goodies 🚀.
@@ -0,0 +1,159 @@
# Example: Iframe Plugin
This guide demonstrates how to create a custom iframe syntax plugin for Milkdown. This plugin allows you to embed iframes directly in your markdown content using a simple directive syntax.
## Overview
---
The iframe plugin enables you to embed external web content using the following syntax:
```markdown
::iframe{src="https://example.com"}
```
This will render as an embedded iframe in your document.
## Implementation Steps
---
To create a custom syntax plugin in Milkdown, we need to implement five key components:
1. **Remark Plugin**: Parse the custom syntax
2. **Schema Definition**: Define the node structure
3. **Parser**: Convert markdown to ProseMirror nodes
4. **Serializer**: Convert ProseMirror nodes back to markdown
5. **Input Rules**: Handle user input
Let's implement each component:
## 1. Remark Plugin
---
First, we use the `remark-directive` plugin to support our custom syntax. This plugin allows us to define custom directives in markdown.
```typescript
import directive from "remark-directive";
import { $remark } from "@milkdown/kit/utils";
const remarkDirective = $remark("remarkDirective", () => directive);
```
## 2. Schema Definition
---
Next, we define the schema for our iframe node. The schema specifies how the node behaves and appears in the editor.
```typescript
import { $node } from "@milkdown/kit/utils";
import { Node } from "@milkdown/kit/prose/model";
const iframeNode = $node("iframe", () => ({
group: "block", // Block-level node
atom: true, // Cannot be split
isolating: true, // Cannot be merged with adjacent nodes
marks: "", // No marks allowed
attrs: {
src: { default: null }, // URL attribute
},
parseDOM: [
{
tag: "iframe",
getAttrs: (dom) => ({
src: (dom as HTMLElement).getAttribute("src"),
}),
},
],
toDOM: (node: Node) => [
"iframe",
{ ...node.attrs, contenteditable: false }, // Prevent editing iframe content
0,
],
}));
```
## 3. Parser
---
The parser converts our markdown syntax into ProseMirror nodes. It looks for the `leafDirective` type with the name "iframe".
```typescript
parseMarkdown: {
match: (node) => node.type === 'leafDirective' && node.name === 'iframe',
runner: (state, node, type) => {
state.addNode(type, { src: (node.attributes as { src: string }).src });
},
},
```
## 4. Serializer
---
The serializer converts ProseMirror nodes back to markdown format.
```typescript
toMarkdown: {
match: (node) => node.type.name === 'iframe',
runner: (state, node) => {
state.addNode('leafDirective', undefined, undefined, {
name: 'iframe',
attributes: { src: node.attrs.src },
});
},
},
```
## 5. Input Rules
---
Input rules handle user typing and convert the syntax into an iframe node.
```typescript
import { InputRule } from "@milkdown/kit/prose";
import { $inputRule } from "@milkdown/kit/utils";
const iframeInputRule = $inputRule(
() =>
new InputRule(
/::iframe\{src\="(?<src>[^"]+)?"?\}/,
(state, match, start, end) => {
const [okay, src = ""] = match;
const { tr } = state;
if (okay) {
tr.replaceWith(start - 1, end, iframeNode.type().create({ src }));
}
return tr;
},
),
);
```
## Usage
---
To use the iframe plugin, add it to your Milkdown editor configuration:
```typescript
import { Editor } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
Editor.make()
.use([remarkDirective, iframeNode, iframeInputRule])
.use(commonmark)
.create();
```
## Example
---
Here's a complete example of the iframe plugin in action:
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/vanilla-iframe-syntax"}
@@ -0,0 +1,189 @@
# Example: Marker Plugin
This guide demonstrates how to create a custom marker syntax plugin for Milkdown. This plugin allows you to mark text with custom colors using a simple markdown syntax.
## Overview
---
The marker plugin enables you to mark text using the following syntax:
```markdown
==marked text==
=={#EE4B2B}marked text with color==
```
This will render as marked text in your document, with the option to specify custom colors.
## Implementation Steps
---
To create a custom marker syntax plugin in Milkdown, we need to implement several components:
1. **Remark Plugin**: Parse the custom syntax
2. **Schema Definition**: Define the mark structure
3. **Parser**: Convert markdown to ProseMirror marks
4. **Serializer**: Convert ProseMirror marks back to markdown
5. **Input Rules**: Handle user input
6. **Color Picker**: Add UI for color selection
Let's implement each component:
## 1. Remark Plugin
---
First, we create a remark plugin to handle our custom marker syntax:
> ⚠️ The real implementation is more complex, but we simplify it for the sake of the example.
> Under the hood, you'll need to write a [micromark extension](https://github.com/micromark/micromark) to make it works correctly.
```typescript
import { $remark } from "@milkdown/kit/utils";
const remarkMarkColor = () => {
return (tree: any) => {
visit(tree, "text", (node: any, index: number, parent: any) => {
const match = node.value.match(/==(?:{#([^}]+)})?([^=]+)==/);
if (match) {
const [_, color, text] = match;
const mark = {
type: "mark",
data: { color },
children: [{ type: "text", value: text }],
};
parent.children.splice(index, 1, mark);
}
});
};
};
const milkdownMarkColorPlugin = $remark("markColor", () => remarkMarkColor);
```
## 2. Schema Definition
---
Next, we define the schema for our marker:
```typescript
import { $markSchema } from "@milkdown/kit/utils";
import { Mark } from "mdast";
export const DEFAULT_COLOR = "#ffff00";
export const markSchema = $markSchema("mark", () => ({
attrs: {
color: {
default: DEFAULT_COLOR,
validate: "string",
},
},
parseDOM: [
{
tag: "mark",
getAttrs: (node: HTMLElement) => ({
color: node.style.backgroundColor,
}),
},
],
toDOM: (mark) => ["mark", { style: `background-color: ${mark.attrs.color}` }],
parseMarkdown: {
match: (node) => node.type === "mark",
runner: (state, node, markType) => {
const color = (node as Mark).data?.color;
state.openMark(markType, { color });
state.next(node.children);
state.closeMark(markType);
},
},
toMarkdown: {
match: (node) => node.type.name === "mark",
runner: (state, mark) => {
let color = mark.attrs.color;
if (color?.toLowerCase() === DEFAULT_COLOR.toLowerCase()) {
color = undefined;
}
state.withMark(mark, "mark", undefined, {
data: { color },
});
},
},
}));
```
## 3. Input Rules
---
We add input rules to handle user typing:
```typescript
import { $inputRule } from "@milkdown/kit/utils";
import { InputRule } from "@milkdown/kit/prose";
const markInputRule = $inputRule(
() =>
new InputRule(/==(?:{#([^}]+)})?([^=]+)==/, (state, match, start, end) => {
const [okay, color, text] = match;
const { tr } = state;
if (okay) {
tr.addMark(
start,
end,
markSchema.type().create({ color: color || DEFAULT_COLOR }),
);
}
return tr;
}),
);
```
## 4. Color Picker Tooltip
---
To enhance the user experience, we add a color picker tooltip:
```typescript
export const colorPickerTooltip = tooltipFactory("color-picker");
class TooltipPluginView {
// ... implementation
}
export const colorPickerTooltipConfig = (ctx: Ctx) => {
ctx.set(colorPickerTooltip.key, {
view: () => new TooltipPluginView(ctx),
});
};
```
## Usage
---
To use the marker plugin, add it to your Milkdown editor configuration:
```typescript
import { Editor } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
Editor.make()
.use(milkdownMarkColorPlugin)
.use(markSchema)
.use(markInputRule)
.use(colorPickerTooltip)
.use(commonmark)
.create();
```
## Example
---
Here's a complete example of the marker plugin in action:
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/vanilla-highlight-syntax"}
@@ -0,0 +1,137 @@
# Example: Slash Plugin
After reading the tooltip guide you already know how Milkdown separates **positioning logic** (provider) from **editor wiring** (ctx slices produced by a factory).
The `@milkdown/plugin-slash` package applies exactly the same idea but focuses on _command palettes_ triggered by a character familiar to `/` menus in modern editors.
This document shows you how to:
- Understand what the slash plugin gives you out-of-the-box.
- Build a **vanilla TypeScript** implementation of a basic `/` menu.
- Use the slash provider with **React** and **Vue**.
- Explore a full-blown menu feature that ships inside Milkdown's Crepe UI.
---
## 1. Anatomy of a Slash Plugin
`@milkdown/plugin-slash` exports two utilities:
1. **`SlashProvider`** Measures the caret position and manages show / hide of your menu.
2. **`slashFactory(id)`** Generates a ctx slice & ProseMirror plugin pair that plugs the provider into the editor.
```ts
import { slashFactory } from "@milkdown/plugin-slash";
export const [mySlashSpec, mySlashPlugin] = slashFactory("my");
```
Just like the tooltip factory:
- `mySlashSpec` is where you put a `PluginSpec` (what ProseMirror needs).
- `mySlashPlugin` turns that spec into a runtime plugin.
---
## 2. A Minimal Vanilla `/` Menu
Below we create a small menu that suggests two commands whenever the user types `/`.
```ts
import { SlashProvider, slashFactory } from "@milkdown/plugin-slash";
import { Editor } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
// DOM content of the menu plain HTML for the demo
const menu = document.createElement("div");
menu.className = "slash-menu";
menu.style.cssText = `
position:absolute;padding:4px 0;background:white;border:1px solid #eee;
box-shadow:0 2px 8px rgba(0,0,0,.15);border-radius:6px;font-size:14px;
`;
menu.innerHTML = `<ul style="margin:0;padding:0;list-style:none">
<li data-cmd="h1" style="padding:4px 12px;cursor:pointer">Heading 1</li>
<li data-cmd="bullet" style="padding:4px 12px;cursor:pointer">Bullet List</li>
</ul>`;
// Click handler replace with real commands
menu.addEventListener("click", (e) => {
const target = e.target as HTMLElement;
const cmd = target.dataset.cmd;
alert(`Run command: ${cmd}`);
});
// Provider positions & shows above DOM element
const provider = new SlashProvider({
content: menu,
// show the menu when the last character before caret is '/'
shouldShow(view) {
return provider.getContent(view)?.endsWith("/") ?? false;
},
offset: 8,
});
const slash = slashFactory("demo");
const slashConfig = (ctx: Ctx) => {
ctx.set(slash.key, {
view: () => ({
update: provider.update,
destroy: provider.destroy,
}),
});
};
Editor.make().config(slashConfig).use(commonmark).use(slash).create();
```
Key takeaways:
- `SlashProvider` has a helper `getContent(view)` to fetch text before the caret handy for filtering.
- You decide **when to show** the menu via the `shouldShow` callback (default: when last char is `/`).
- The provider only manipulates **position + visibility**; rendering & commands are completely yours.
---
## 3. Framework Examples
### React
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/react-slash"}
Highlights:
1. A `<SlashMenu/>` React component renders the list.
2. The component root is passed to `SlashProvider` (just like the tooltip demo).
3. React hooks manage internal focus & keyboard navigation.
### Vue
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/vue-slash"}
The Vue version uses `Teleport` to append the menu to `document.body` and `ref` / `watch` for reactivity.
---
## 4. Real-world Feature Crepe Block Menu
Milkdown's **Crepe** UI implements an extensible block-level menu on top of the slash plugin. You'll find the source code at:
```text
packages/crepe/src/feature/block-edit/menu/
```
Notable patterns to look for:
- **Context slices** (`menu` / `menuAPI`) to expose imperative `show` & `hide` methods.
- Filtering commands based on the current text after `/`.
- Preventing the menu inside `code` blocks or lists.
Studying this folder is a great next step once you master the basics.
---
## 5. Summary & Next Steps
- `@milkdown/plugin-slash` gives you caret detection + positioning nothing else.
- UI, behaviour, and commands are fully customisable.
Fork one of the examples above, add your own commands, and you'll have a modern `/` command palette in minutes ✨.
@@ -0,0 +1,140 @@
# Example: Tooltip Plugin
This guide walks you through creating and using **tooltip-based plugins** in Milkdown.
You will learn how the low-level `@milkdown/plugin-tooltip` works and how to build richer experiences on top of it in **vanilla TypeScript**, **React**, and **Vue**.
> **TL;DR** A tooltip in Milkdown is nothing more than a ProseMirror plugin created by `tooltipFactory(id)`.
> It receives position information from the editor and renders any DOM of your choice.
> Everything else (buttons, inputs, styling, framework bindings) can be composed on top of that.
## 1. Anatomy of a Tooltip
---
At its core the tooltip plugin exported from `@milkdown/plugin-tooltip` contains two helpers:
1. **`TooltipProvider`** An utility class powered by [floating-ui](https://floating-ui.com/) to calculate the tooltip position.
2. **`tooltipFactory(id)`** A factory that returns a pair of Milkdown plugin slices which wire the provider into the editor.
The factory is extremely small (≈40 lines):
```ts
import { tooltipFactory } from "@milkdown/plugin-tooltip";
// Create a tooltip identified by the string "my".
export const [myTooltipSpec, myTooltipPlugin] = tooltipFactory("my");
```
The first element (`myTooltipSpec`) is a **ctx slice** that stores a `PluginSpec`, while the second one (`myTooltipPlugin`) is the real ProseMirror plugin which consumes that spec.
## 2. A Minimal Vanilla Tooltip
---
Below is the complete code for a tooltip that shows the **length of the current selection**.
```ts
import { Editor } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { TooltipProvider, tooltipFactory } from "@milkdown/plugin-tooltip";
// 1) Prepare DOM that we will mount into the page.
const el = document.createElement("div");
el.className = "selection-length";
el.style.cssText = `
pointer-events:none;
background:#333;color:#fff;padding:2px 6px;border-radius:4px;font-size:12px;
`;
// 2) Build a provider which updates the content.
const provider = new TooltipProvider({
content: el,
shouldShow: (view) => !!view.state.selection.content().size,
});
// 3) Bridge provider & editor.
const tooltip = tooltipFactory("sel-length");
const tooltipConfig = (ctx: Ctx) => {
ctx.set(selectionTooltipSpec.key, {
view: () => ({
update: provider.update,
destroy: provider.destroy,
}),
});
};
Editor.make().config(tooltipConfig).use(commonmark).use(tooltip).create();
```
Key points:
- We **create** any DOM element we like (`el`).
- `TooltipProvider` tracks the editor position and moves the element.
- `tooltipFactory` wraps the provider into a pluggable slice.
## 3. Framework Examples
---
Sometimes building UI is easier in your favourite framework.
Because the tooltip provider only deals with **DOM elements**, you can freely render React, Vue or Svelte components and pass their root node to the provider.
### React
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/react-tooltip"}
The React example shows how to:
1. Create a React component (`<SelectionTooltip/>`).
2. Render it into a portal and give the root HTML element to `TooltipProvider`.
3. Re-use React state/hooks while Milkdown takes care of positioning.
### Vue
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/vue-tooltip"}
The Vue example follows the same pattern with `defineComponent` and `teleport`.
## 4. Real-world Examples
---
### 4-1. Link Tooltip (_@milkdown/component/link-tooltip_)
The [link tooltip](https://github.com/Milkdown/milkdown/tree/main/packages/components/src/link-tooltip) demonstrates how to:
- Maintain UI **state** (`preview` vs `edit`) in ctx slices.
- Communicate with the editor through an **API slice** (add / edit / remove links).
- Render framework-agnostic UI inside a tooltip provider.
Have a look at the files below to see those techniques in action:
```text
packages/components/src/link-tooltip/
├── slices.ts # state & API slices
├── tooltips.ts # preview & edit providers
└── component.tsx # (framework examples)
```
### 4-2. Toolbar Feature (_@milkdown/crepe/feature/toolbar_)
The toolbar in the [crepe](https://github.com/Milkdown/milkdown/tree/main/packages/crepe) package pushes the idea further by:
- Using multiple tooltip instances (one per button group).
- Rendering the UI with Vue _inside_ the provider.
- Sharing configuration via ctx slices so that every button is extensible by third-party plugins.
You can browse the implementation starting from
```text
packages/crepe/src/feature/toolbar/component.tsx
```
## 5. Summary & Next Steps
---
- `@milkdown/plugin-tooltip` offers **just enough** abstraction: positioning & lifecycle.
- Everything else **state, styling, framework integration** is totally up to you.
Try to customise one of the examples above, then ship your own tooltip-powered features 🤟.
+174
View File
@@ -0,0 +1,174 @@
# Plugins 101
In this section we will show you the basic information of the plugin.
In most cases, you will not need to write plugins without helpers.
But it can help you understand the plugin system and what happens under the hood.
## Structure Overview
Generally speaking, a plugin will have following structure:
```typescript
import { MilkdownPlugin } from "@milkdown/kit/ctx";
const myPlugin: MilkdownPlugin = (ctx) => {
// #1 prepare plugin
return async () => {
// #2 run plugin
return async () => {
// #3 clean up plugin
};
};
};
```
Each plugin is composed by three parts:
1. _Prepare_: this part will be executed when plugin is registered in milkdown by `.use` method.
2. _Run_: this part will be executed when plugin is actually loaded.
3. _Post_: this part will be executed when plugin is removed by `.remove` method or editor is destroyed.
## Timer
Timer can be used to decide when to load the current plugin and how current plugin can influence other plugin's loading status.
You can use `ctx.wait` to wait a timer to finish.
```typescript
import { MilkdownPlugin, Complete } from "@milkdown/kit/core";
const myPlugin: MilkdownPlugin = (ctx) => {
return async () => {
const start = Date.now();
await ctx.wait(Complete);
const end = Date.now();
console.log("Milkdown load duration: ", end - start);
};
};
```
You can also create your own timer and influence other plugins load time.
For example, let's create a plugin that will fetch markdown content from remote server as editor's default value.
```typescript
import {
MilkdownPlugin,
editorStateTimerCtx,
defaultValueCtx,
createTimer,
} from "@milkdown/kit/core";
const RemoteTimer = createTimer("RemoteTimer");
const remotePlugin: MilkdownPlugin = (ctx) => {
// register timer
ctx.record(RemoteTimer);
return async () => {
// the editorState plugin will wait for this timer to finish before initialize editor state.
ctx.update(editorStateTimerCtx, (timers) => timers.concat(RemoteTimer));
const defaultMarkdown = await fetchMarkdownAPI();
ctx.set(defaultValueCtx, defaultMarkdown);
// mark timer as complete
ctx.done(RemoteTimer);
return async () => {
await SomeAPI();
// remove timer when plugin is removed
ctx.clearTimer(RemoteTimer);
};
};
};
```
It has following steps:
1. We use `createTimer` to create a timer, and use `pre.record` to register it into milkdown.
2. We update `editorStateTimerCtx` to tell the internal `editorState` plugin that before initialize editor state, it should wait our remote fetch process finished.
3. After we get value from `fetchMarkdownAPI`, we set it as `defaultValue` and use `ctx.done` to mark a timer as complete.
## Ctx
We have used `ctx` several times in the above example, now we can try to understand what it is.
Ctx is a data container which is shared in the entire editor instance. It's composed by a lot of slices. Every `slice` has a unique key and a value. You can change the value of a slice by `ctx.set` and `ctx.update`. And you can get the value of a slice by `ctx.get` with the slice key or name. Last but not least, you can remove a slice by `post.remove`.
```typescript
import { MilkdownPlugin, createSlice } from "@milkdown/kit/ctx";
const counterCtx = createSlice(0, "counter");
const counterPlugin: MilkdownPlugin = (ctx) => {
ctx.inject(counterCtx);
return () => {
// count is 0
const count0 = ctx.get(counterCtx);
// set count to 1
ctx.set(counterCtx, 1);
// now count is 1
const count1 = ctx.get(counterCtx);
// set count to n + 2
ctx.update(counterCtx, (prev) => prev + 2);
// now count is 3
const count2 = ctx.get(counterCtx);
// we can also get value by the slice name
const count3 = ctx.get("counter");
return () => {
// remove the slice
ctx.remove(counterCtx);
};
};
};
```
We can use `createSlice` to create a ctx, and use `pre.inject` to inject the ctx into the editor.
And when plugin processing, `ctx.get` can get the value of a ctx, `ctx.set` can set the value of a ctx, and `ctx.update` can update a ctx using callback function.
So, we can use `ctx` combine with `timer` to decide when should a plugin be processed.
```typescript
import {
MilkdownPlugin,
SchemaReady,
Timer,
createSlice,
} from "@milkdown/kit/core";
const examplePluginTimersCtx = createSlice<Timer[]>([], "example-timer");
const examplePlugin: MilkdownPlugin = (ctx) => {
ctx.inject(examplePluginTimersCtx, [SchemaReady]);
return async () => {
await Promise.all(
ctx.get(examplePluginTimersCtx).map((timer) => ctx.wait(timer)),
);
// or we can use a simplified syntax sugar
await ctx.waitTimers(examplePluginTimersCtx);
// do something
};
};
```
With this pattern, if other plugins want to delay the process of `examplePlugin`, all they need to do is just add a timer into `examplePluginTimersCtx` with `ctx.update`.
## Summary
Now let's go back to the plugin structure. Since we have the knowledge of `timer` and `ctx`, we can understand what we should do in each part of a plugin.
1. In `prepare` stage of the plugin, we can use `ctx.record` to register a timer, and use `ctx.inject` to inject a slice.
2. In `run` stage of the plugin, we can use `ctx.wait` to wait a timer to finish, and use `ctx.get` to get the value of a slice. We can also change values of slices by `ctx.set` and `ctx.update`. And we can use `ctx.done` to mark a timer as complete.
3. In `post` stage of the plugin, we can use `ctx.clearTimer` to clear a timer, and use `ctx.remove` to remove a slice.
+28
View File
@@ -0,0 +1,28 @@
# Using Components
Components are features work out of the box that built on top of plugins.
Each component is a separate module. You can use them by importing them from `@milkdown/kit/component/*`.
All components can be used just like plugins.
```ts
import { imageBlock } from "@milkdown/kit/component/image-block";
import { Editor } from "@milkdown/kit/core";
Editor.make().use(/* some other plugins */).use(imageBlock).create();
```
Components are designed to be headless, which means they are not opinionated about the UI.
You can use them to build your own editor UI. Components are built by web components and can be used in any framework.
---
# List of Components
| Name | Description |
| ------------------------------------------------ | ---------------------------------------------------------- |
| [Code Block](/docs/api/component-code-block) | Render code by [Codemirror](https://codemirror.net/) |
| [Image Block](/docs/api/component-image-block) | Render an image as a block |
| [Image Inline](/docs/api/component-image-inline) | Provide placeholder and uploader features for inline image |
| [Link Tooltip](/docs/api/component-link-tooltip) | Provide edit and preview feature for link |
| [List Item](/docs/api/component-list-item-block) | Renderers bullet, ordered and task list by custom renderer |
| [Table Block](/docs/api/component-table-block) | Render table and provides table editing features |
+87
View File
@@ -0,0 +1,87 @@
# Using Plugins
All features in milkdown are provided by plugin.
Such as syntax, components, etc.
Now we can try more plugins:
```typescript
import { Editor } from "@milkdown/kit/core";
import { slash } from "@milkdown/kit/plugin/slash";
import { tooltip } from "@milkdown/kit/plugin/tooltip";
import { commonmark } from "@milkdown/kit/preset/commonmark";
Editor.make().use(commonmark).use(tooltip).use(slash).create();
```
---
## Toggling Plugins
You can also toggle plugins programmatically:
```typescript
import { Editor } from "@milkdown/kit/core";
import { someMilkdownPlugin } from "some-milkdown-plugin";
const editor = await Editor.config(configForPlugin)
.use(someMilkdownPlugin)
.create();
// remove plugin
await editor.remove(someMilkdownPlugin);
// remove config
editor.removeConfig(configForPlugin);
// add another plugin
editor.use(anotherMilkdownPlugin);
// Recreate the editor to apply changes.
await editor.create();
```
---
## Official Plugins
Milkdown provides the following official plugins:
### Plugins provided by `@milkdown/kit`:
> 🙋‍♀️Why not all plugins are available in `@milkdown/kit`?
>
> `@milkdown/kit` is a collection of plugins that are commonly used in the editor.
> If you want to use a plugin that is not in `@milkdown/kit`, you can install it separately.
> The plugins in `@milkdown/kit` are also stable and well-tested.
| Package Name | Description |
| -------------------------------------------------------------- | --------------------------------------------------------- |
| [@milkdown/kit/preset/commonmark](/docs/api/preset-commonmark) | Add [commonmark](https://commonmark.org/) syntax support. |
| [@milkdown/kit/preset/gfm](/docs/api/preset-gfm) | Add [gfm](https://github.github.com/gfm/) syntax support. |
| [@milkdown/kit/plugin/history](/docs/api/plugin-history) | Add undo & redo support. |
| [@milkdown/kit/plugin/clipboard](/docs/api/plugin-clipboard) | Add markdown copy & paste support. |
| [@milkdown/kit/plugin/cursor](/docs/api/plugin-cursor) | Add drop & gap cursor. |
| [@milkdown/kit/plugin/listener](/docs/api/plugin-listener) | Add listener support. |
| [@milkdown/kit/plugin/indent](/docs/api/plugin-indent) | Add tab indent support. |
| [@milkdown/kit/plugin/upload](/docs/api/plugin-upload) | Add drop and upload support. |
| [@milkdown/kit/plugin/block](/docs/api/plugin-block) | Add a drag handle for every block node. |
| [@milkdown/kit/plugin/tooltip](/docs/api/plugin-tooltip) | Add universal tooltip support. |
| [@milkdown/kit/plugin/slash](/docs/api/plugin-slash) | Add universal slash commands support. |
### Other Plugins:
- [@milkdown/plugin-collab](/docs/api/plugin-collab)
Add collaborative editing support, powered by [yjs](https://docs.yjs.dev/).
- [@milkdown/plugin-prism](/docs/api/plugin-prism)
Add [prism](https://prismjs.com/) support for code block highlight.
- [@milkdown/plugin-emoji](/docs/api/plugin-emoji)
Add emoji shortcut support (something like `:+1:`), and use [twemoji](https://twemoji.twitter.com/) to display emoji.
## Community plugins
Check out [awesome-milkdown](https://github.com/Milkdown/awesome-milkdown) to find community plugins. You can also submit a PR to list your plugins there.
+48
View File
@@ -0,0 +1,48 @@
# Angular
We don't provide Angular support out of box, but you can use the vanilla version with it easily.
## Install the Dependencies
```bash
# install with npm
npm install @milkdown/kit
npm install @milkdown/theme-nord
```
## Create a Component
Create a component is pretty easy.
```html
<!-- editor.component.html -->
<div #editorRef></div>
```
```typescript
// editor.component.ts
import { Component, ElementRef, ViewChild } from "@angular/core";
import { defaultValueCtx, Editor, rootCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { nord } from "@milkdown/theme-nord";
@Component({
templateUrl: "./editor.component.html",
})
export class AppComponent {
@ViewChild("editorRef") editorRef: ElementRef;
defaultValue = "# Milkdown x Angular";
ngAfterViewInit() {
Editor.make()
.config((ctx) => {
ctx.set(rootCtx, this.editorRef.nativeElement);
ctx.set(defaultValueCtx, this.defaultValue);
})
.config(nord)
.use(commonmark)
.create();
}
}
```
+51
View File
@@ -0,0 +1,51 @@
# Next.js
Since we provide [react](/docs/recipes/react) support out of box, we can use it directly in [Next.js](https://nextjs.org/).
## Install the Dependencies
Except the `@milkdown/kit` and theme. We need to install the `@milkdown/react`, which provide lots of abilities for react in milkdown.
```bash
# install with npm
npm install @milkdown/react
npm install @milkdown/kit
npm install @milkdown/theme-nord
```
## Create a Component
Create a component is pretty easy.
```tsx
import { Editor, rootCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { Milkdown, MilkdownProvider, useEditor } from "@milkdown/react";
import { nord } from "@milkdown/theme-nord";
import React from "react";
const MilkdownEditor: React.FC = () => {
const { editor } = useEditor((root) =>
Editor.make()
.config(nord)
.config((ctx) => {
ctx.set(rootCtx, root);
})
.use(commonmark),
);
return <Milkdown />;
};
export const MilkdownEditorWrapper: React.FC = () => {
return (
<MilkdownProvider>
<MilkdownEditor />
</MilkdownProvider>
);
};
```
## Online Demo
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/next-commonmark"}
+82
View File
@@ -0,0 +1,82 @@
# NuxtJS
Since we provide [vue](/docs/recipes/vue) support out of box, we can use it directly in [NuxtJS](https://v3.nuxtjs.org/).
> NuxtJS version should be 3.x.
## Install the Dependencies
Except the `@milkdown/kit` and theme. We need to install the `@milkdown/vue`, which provide lots of abilities for vue in milkdown.
```bash
# install with npm
npm install @milkdown/vue
npm install @milkdown/kit
npm install @milkdown/theme-nord
```
## Create a Component
Create a component is pretty easy.
First, we need to create a `MilkdownEditor` component.
```html
<!-- MilkdownEditor.vue -->
<template>
<Milkdown />
</template>
<script>
import { Editor, rootCtx, defaultValueCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { nord } from "@milkdown/theme-nord";
import { Milkdown, useEditor } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "Milkdown",
components: {
Milkdown,
},
setup: () => {
useEditor((root) =>
Editor.make()
.config((ctx) => {
ctx.set(rootCtx, root);
})
.config(nord)
.use(commonmark),
);
},
});
</script>
```
Then, we need to create a `MilkdownEditorWrapper` component.
```html
<!-- MilkdownEditorWrapper.vue -->
<template>
<MilkdownProvider>
<MilkdownEditor />
</MilkdownProvider>
</template>
<script>
import { MilkdownProvider } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "MilkdownEditorWrapper",
components: {
MilkdownProvider,
},
setup: () => {},
});
</script>
```
## Online Demo
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/nuxt-commonmark"}
+213
View File
@@ -0,0 +1,213 @@
# React Integration
Milkdown provides first-class React support with dedicated packages and hooks for seamless integration. You can choose between Crepe, our feature-rich WYSIWYG editor, or the core Milkdown editor for more customization options.
## Using Crepe
---
Crepe is a powerful, feature-rich Markdown editor built on top of Milkdown that provides a more user-friendly editing experience.
### Installation
```bash
npm install @milkdown/crepe @milkdown/react @milkdown/kit
```
### Implementation
```tsx
import { Crepe } from "@milkdown/crepe";
import { Milkdown, MilkdownProvider, useEditor } from "@milkdown/react";
const CrepeEditor: React.FC = () => {
const { get } = useEditor((root) => {
return new Crepe({ root });
});
return <Milkdown />;
};
export const MilkdownEditorWrapper: React.FC = () => {
return (
<MilkdownProvider>
<CrepeEditor />
</MilkdownProvider>
);
};
```
### Online Demo
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/react-crepe"}
## Using Milkdown
---
For more advanced use cases or when you need full control over the editor's configuration, you can use the core Milkdown editor directly.
### Install Dependencies
```bash
npm install @milkdown/react @milkdown/kit
```
### Basic Usage
Here's a minimal example to get started:
```tsx
import { Editor, rootCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { Milkdown, MilkdownProvider, useEditor } from "@milkdown/react";
import { nord } from "@milkdown/theme-nord";
const MilkdownEditor: React.FC = () => {
const { get } = useEditor((root) =>
Editor.make()
.config(nord)
.config((ctx) => {
ctx.set(rootCtx, root);
})
.use(commonmark),
);
return <Milkdown />;
};
export const MilkdownEditorWrapper: React.FC = () => {
return (
<MilkdownProvider>
<MilkdownEditor />
</MilkdownProvider>
);
};
```
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/react-commonmark"}
## Advanced Usage
---
### Accessing Editor Instance
The `useInstance()` hook can only be used within components that are children of `MilkdownProvider`. It returns a tuple containing a loading state and a getter function to access the editor instance.
```tsx
import { useInstance } from "@milkdown/react";
import { getMarkdown } from "@milkdown/utils";
// ❌ This won't work - ParentComponent is outside MilkdownProvider
const ParentComponent: React.FC = () => {
const [isLoading, getInstance] = useInstance(); // This will be [true, () => undefined]
return <MilkdownEditorWrapper />;
};
// ✅ This is the correct way - EditorControls is inside MilkdownProvider
const EditorControls: React.FC = () => {
const [isLoading, getInstance] = useInstance();
const handleSave = () => {
if (isLoading) return;
const editor = getInstance();
if (!editor) return;
const content = editor.action(getMarkdown());
// Do something with the content
};
return (
<button onClick={handleSave} disabled={isLoading}>
Save
</button>
);
};
// ✅ Proper component structure
const EditorWithControls: React.FC = () => {
return (
<MilkdownProvider>
<MilkdownEditorWrapper />
<EditorControls />
</MilkdownProvider>
);
};
```
### Best Practices
1. **Component Structure**
- Keep the editor component separate from business logic
- Wrap the editor with `MilkdownProvider` at the highest necessary level
- Use TypeScript for better type safety
2. **Performance**
- Memoize the editor configuration if it's complex
- Use React.memo for the editor component if needed
- Avoid unnecessary re-renders of the editor
### Common Use Cases
**Form Integration**
```tsx
const FormWithEditor: React.FC = () => {
const [isLoading, getInstance] = useInstance();
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (isLoading) return;
const editor = getInstance();
if (!editor) return;
const content = editor.action(getMarkdown());
// Submit form with content
};
return (
<form onSubmit={handleSubmit}>
<MilkdownEditorWrapper />
<button type="submit" disabled={isLoading}>
Submit
</button>
</form>
);
};
```
**Auto-save**
```tsx
import { Editor, rootCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { listener, listenerCtx } from "@milkdown/kit/plugin/listener";
import { Milkdown, useEditor } from "@milkdown/react";
const AutoSaveEditor: React.FC = () => {
const { get } = useEditor((root) =>
Editor.make()
.config((ctx) => {
ctx.set(rootCtx, root);
// Add markdown listener for auto-save
ctx.get(listenerCtx).markdownUpdated((ctx, markdown) => {
// Save content to your backend or storage
saveToBackend(markdown);
});
})
.use(commonmark)
.use(listener),
);
return <Milkdown />;
};
```
## More Examples
---
- [Examples Repository](https://github.com/Milkdown/examples)
+46
View File
@@ -0,0 +1,46 @@
# SolidJS
We don't provide SolidJS support out of box, but you can use the vanilla version with it easily.
## Install the Dependencies
```bash
# install with npm
npm install @milkdown/kit
npm install @milkdown/theme-nord
```
## Create a Component
Create a component is pretty easy.
```tsx
import { defaultValueCtx, Editor, rootCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { nord } from "@milkdown/theme-nord";
import { onCleanup, onMount } from "solid-js";
const Milkdown = () => {
let ref;
let editor;
onMount(async () => {
editor = await Editor.make()
.config((ctx) => {
ctx.set(rootCtx, ref);
})
.config(nord)
.use(commonmark)
.create();
});
onCleanup(() => {
editor.destroy();
});
return <div ref={ref} />;
};
```
## Online Demo
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/solid-commonmark"}
+45
View File
@@ -0,0 +1,45 @@
# Svelte
We don't provide Svelte support out of box, but you can use the vanilla version with it easily.
## Install the Dependencies
```bash
# install with npm
npm install @milkdown/kit
npm install @milkdown/theme-nord
```
## Creating a Component
Creating a component is pretty easy.
```html
<script>
import { Editor, rootCtx, defaultValueCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { nord } from "@milkdown/theme-nord";
function editor(dom) {
// to obtain the editor instance we need to store a reference of the editor.
const MakeEditor = Editor.make()
.config((ctx) => {
ctx.set(rootCtx, dom);
})
.config(nord)
.use(commonmark)
.create();
MakeEditor.then((editor) => {
// here you have access to the editor instance.
// const exampleContent = "# Hello World!";
// editor.action(replaceAll(exampleContent));
});
}
</script>
<div use:editor />
```
## Online Demo
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/svelte-commonmark"}
+294
View File
@@ -0,0 +1,294 @@
# Vue Integration
Milkdown provides first-class Vue support with dedicated packages and hooks for seamless integration. You can choose between Crepe, our feature-rich WYSIWYG editor, or the core Milkdown editor for more customization options.
> Vue version should be 3.x
## Using Crepe
---
Crepe is a powerful, feature-rich Markdown editor built on top of Milkdown that provides a more user-friendly editing experience.
### Installation
```bash
npm install @milkdown/crepe @milkdown/vue @milkdown/kit
```
### Implementation
```vue
<!-- MilkdownEditor.vue -->
<template>
<Milkdown />
</template>
<script>
import { Crepe } from "@milkdown/crepe";
import { Milkdown, MilkdownProvider, useEditor } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "MilkdownEditor",
components: {
Milkdown,
},
setup: () => {
const { get } = useEditor((root) => {
return new Crepe({ root });
});
},
});
</script>
<!-- MilkdownEditorWrapper.vue -->
<template>
<MilkdownProvider>
<MilkdownEditor />
</MilkdownProvider>
</template>
<script>
import { MilkdownProvider } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "MilkdownEditorWrapper",
components: {
MilkdownProvider,
},
});
</script>
```
### Online Demo
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/vue-crepe"}
## Using Milkdown
---
For more advanced use cases or when you need full control over the editor's configuration, you can use the core Milkdown editor directly.
### Install Dependencies
```bash
npm install @milkdown/vue @milkdown/kit @milkdown/theme-nord
```
### Basic Usage
Here's a minimal example to get started:
```vue
<!-- MilkdownEditor.vue -->
<template>
<Milkdown />
</template>
<script>
import { Editor, rootCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { nord } from "@milkdown/theme-nord";
import { Milkdown, useEditor } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "MilkdownEditor",
components: {
Milkdown,
},
setup: () => {
const { get } = useEditor((root) =>
Editor.make()
.config(nord)
.config((ctx) => {
ctx.set(rootCtx, root);
})
.use(commonmark),
);
},
});
</script>
<!-- MilkdownEditorWrapper.vue -->
<template>
<MilkdownProvider>
<MilkdownEditor />
</MilkdownProvider>
</template>
<script>
import { MilkdownProvider } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "MilkdownEditorWrapper",
components: {
MilkdownProvider,
},
});
</script>
```
::iframe{src="https://stackblitz.com/github/Milkdown/examples/tree/main/vue-commonmark"}
## Advanced Usage
---
### Accessing Editor Instance
The `useInstance()` hook can only be used within components that are children of `MilkdownProvider`. It returns a tuple containing a loading state and a getter function to access the editor instance.
```vue
<!-- EditorControls.vue -->
<template>
<button @click="handleSave" :disabled="isLoading">Save</button>
</template>
<script>
import { useInstance } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "EditorControls",
setup: () => {
const [isLoading, getInstance] = useInstance();
const handleSave = () => {
if (isLoading.value) return;
const editor = getInstance();
if (!editor) return;
const content = editor.getMarkdown();
// Do something with the content
};
return {
isLoading,
handleSave,
};
},
});
</script>
<!-- EditorWithControls.vue -->
<template>
<MilkdownProvider>
<MilkdownEditor />
<EditorControls />
</MilkdownProvider>
</template>
<script>
import { MilkdownProvider } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "EditorWithControls",
components: {
MilkdownProvider,
},
});
</script>
```
### Best Practices
1. **Component Structure**
- Keep the editor component separate from business logic
- Wrap the editor with `MilkdownProvider` at the highest necessary level
- Use TypeScript for better type safety
2. **Performance**
- Memoize the editor configuration if it's complex
- Use Vue's `shallowRef` for editor instance if needed
- Avoid unnecessary re-renders of the editor
### Common Use Cases
**Form Integration**
```vue
<template>
<form @submit.prevent="handleSubmit">
<MilkdownEditorWrapper />
<button type="submit" :disabled="isLoading">Submit</button>
</form>
</template>
<script>
import { useInstance } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "FormWithEditor",
setup: () => {
const [isLoading, getInstance] = useInstance();
const handleSubmit = () => {
if (isLoading.value) return;
const editor = getInstance();
if (!editor) return;
const content = editor.getMarkdown();
// Submit form with content
};
return {
isLoading,
handleSubmit,
};
},
});
</script>
```
**Auto-save**
```vue
<template>
<Milkdown />
</template>
<script>
import { Editor, rootCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { listener, listenerCtx } from "@milkdown/kit/plugin/listener";
import { Milkdown, useEditor } from "@milkdown/vue";
import { defineComponent } from "vue";
export default defineComponent({
name: "AutoSaveEditor",
components: {
Milkdown,
},
setup: () => {
const { get } = useEditor((root) =>
Editor.make()
.config((ctx) => {
ctx.set(rootCtx, root);
// Add markdown listener for auto-save
ctx.get(listenerCtx).markdownUpdated((ctx, markdown) => {
// Save content to your backend or storage
saveToBackend(markdown);
});
})
.use(commonmark)
.use(listener),
);
},
});
</script>
```
## More Examples
---
- [Examples Repository](https://github.com/Milkdown/examples)
+44
View File
@@ -0,0 +1,44 @@
# Vue2
We don't provide Vue2 support out of box, but you can use the vanilla version with it easily.
## Install the Dependencies
```bash
# install with npm
npm install @milkdown/kit
npm install @milkdown/theme-nord
```
## Create a Component
Create a component is pretty easy.
```html
<template>
<div ref="editor"></div>
</template>
<script>
import { defaultValueCtx, Editor, rootCtx } from "@milkdown/kit/core";
import { commonmark } from "@milkdown/kit/preset/commonmark";
import { nord } from "@milkdown/theme-nord";
export default {
name: "Editor",
props: {
msg: String,
},
mounted() {
Editor.make()
.config((ctx) => {
ctx.set(rootCtx, this.$refs.editor);
ctx.set(defaultValueCtx, this.$props.msg);
})
.config(nord)
.use(commonmark)
.create();
},
};
</script>
```