From 15a899300487ce2575336f2ffe55a86b557b6d86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Wed, 18 Nov 2026 13:37:22 +0000 Subject: [PATCH 1/4] docs: clean up AI-written prose and fix stale references Amp-Thread-ID: https://ampcode.com/threads/T-01a1ee18-c0b9-71e0-ad1f-8d67e232f577 --- SECURITY.md | 33 +- docs/README.md | 214 +++------- .../1.getting-started/0.introduction.md | 54 +-- .../1.getting-started/1.installation.md | 33 +- .../1.getting-started/2.document-model.md | 6 +- docs/content/10.use-cases/1.intelligent-ui.md | 10 +- docs/content/10.use-cases/10.email-and-rss.md | 2 +- .../10.use-cases/2.ai-chat-streaming.md | 2 +- docs/content/10.use-cases/3.vue-ai-chat.md | 2 +- docs/content/10.use-cases/4.svelte-ai-chat.md | 2 +- .../content/10.use-cases/5.angular-ai-chat.md | 8 +- docs/content/10.use-cases/6.generative-ui.md | 6 +- docs/content/10.use-cases/7.docs-and-blogs.md | 2 +- .../10.use-cases/8.cms-runtime-content.md | 3 +- docs/content/10.use-cases/9.cli-and-agents.md | 2 +- docs/content/10.use-cases/index.md | 2 +- .../0.markdown-libraries-for-ai-chat.md | 2 +- docs/content/11.compare/1.comark-vs-mdx.md | 52 +-- .../10.comark-vs-svelte-markdown.md | 6 +- .../11.comark-vs-vue-markdown-render.md | 2 +- .../11.compare/2.comark-vs-react-markdown.md | 47 ++- .../11.compare/3.comark-vs-streamdown.md | 38 +- .../content/11.compare/4.comark-vs-markdoc.md | 32 +- .../11.compare/5.comark-vs-markstream.md | 12 +- docs/content/11.compare/6.comark-vs-marked.md | 2 +- .../11.compare/7.comark-vs-markdown-it.md | 2 +- docs/content/11.compare/8.comark-vs-remark.md | 4 +- .../11.compare/9.comark-vs-markdown-to-jsx.md | 10 +- docs/content/11.compare/index.md | 2 +- docs/content/2.syntax/1.markdown.md | 18 +- docs/content/2.syntax/2.components.md | 42 +- docs/content/2.syntax/3.attributes.md | 14 +- docs/content/2.syntax/4.frontmatter.md | 24 +- docs/content/3.rendering/2.html.md | 8 +- docs/content/3.rendering/3.vue.md | 63 ++- docs/content/3.rendering/5.react.md | 62 ++- docs/content/3.rendering/6.svelte.md | 51 ++- docs/content/3.rendering/7.angular.md | 39 +- docs/content/3.rendering/8.ansi.md | 31 +- docs/content/4.plugins/0.defaults/alert.md | 50 +-- .../4.plugins/0.defaults/attributes.md | 16 +- .../4.plugins/0.defaults/components.md | 18 +- .../4.plugins/0.defaults/frontmatter.md | 18 +- docs/content/4.plugins/0.defaults/html.md | 32 +- docs/content/4.plugins/0.defaults/linkify.md | 8 +- .../content/4.plugins/0.defaults/task-list.md | 6 +- docs/content/4.plugins/1.built-in/binding.md | 86 ++-- docs/content/4.plugins/1.built-in/breaks.md | 8 +- docs/content/4.plugins/1.built-in/emoji.md | 18 +- .../4.plugins/1.built-in/external-links.md | 4 +- .../content/4.plugins/1.built-in/footnotes.md | 30 +- .../4.plugins/1.built-in/heading-links.md | 8 +- .../4.plugins/1.built-in/json-render.md | 10 +- docs/content/4.plugins/1.built-in/math.md | 20 +- docs/content/4.plugins/1.built-in/mermaid.md | 36 +- .../4.plugins/1.built-in/punctuation.md | 6 +- docs/content/4.plugins/1.built-in/rangi.md | 34 +- docs/content/4.plugins/1.built-in/security.md | 91 +++-- docs/content/4.plugins/1.built-in/shiki.md | 64 +-- docs/content/4.plugins/1.built-in/summary.md | 6 +- .../4.plugins/1.built-in/title-description.md | 8 +- docs/content/4.plugins/1.built-in/toc.md | 14 +- .../4.plugins/2.custom/1.plugin-api.md | 34 +- docs/content/4.plugins/2.custom/2.ast-api.md | 8 +- .../4.plugins/2.custom/3.markdown-it.md | 12 +- docs/content/4.plugins/index.md | 72 ++-- docs/content/5.reference/0.render.md | 27 +- docs/content/5.reference/1.parse.md | 64 ++- docs/content/5.reference/2.auto-close.md | 28 +- docs/content/5.reference/3.reference.md | 63 ++- docs/content/7.kb/0.why-comark.md | 98 ++--- docs/content/7.kb/2.migration-from-mdc.md | 153 ++++--- docs/content/7.kb/3.migration-from-mdx.md | 96 ++--- docs/content/7.kb/4.twoslash.md | 66 +-- docs/content/7.kb/5.custom-code-block.md | 30 +- docs/content/8.examples/1.frameworks/astro.md | 10 +- .../content/8.examples/1.frameworks/nextjs.md | 14 +- docs/content/8.examples/1.frameworks/nuxt.md | 16 +- .../8.examples/1.frameworks/sveltekit.md | 16 +- .../8.examples/1.frameworks/vitepress.md | 12 +- docs/content/8.examples/2.vite/angular.md | 6 +- docs/content/8.examples/2.vite/html.md | 12 +- docs/content/8.examples/2.vite/react.md | 6 +- docs/content/8.examples/2.vite/svelte.md | 10 +- docs/content/8.examples/2.vite/vue.md | 8 +- .../8.examples/3.plugins/react-vite-math.md | 79 ++-- .../3.plugins/react-vite-mermaid.md | 29 +- .../8.examples/3.plugins/vue-vite-binding.md | 43 +- .../3.plugins/vue-vite-highlight.md | 202 ++++------ .../3.plugins/vue-vite-json-render.md | 36 +- .../8.examples/3.plugins/vue-vite-math.md | 88 ++-- .../8.examples/3.plugins/vue-vite-mermaid.md | 36 +- .../3.plugins/vue-vite-punctuation.md | 12 +- docs/content/8.examples/4.ai/nuxt-ai-sdk.md | 12 +- docs/content/8.examples/index.md | 44 +- docs/content/9.ecosystem.md | 19 +- docs/content/index.md | 18 +- docs/nuxt.config.ts | 2 +- docs/server/utils/llms.ts | 2 +- docs/skills/comark/AGENTS.md | 34 +- docs/skills/comark/SKILL.md | 377 +++++++----------- .../comark/references/markdown-syntax.md | 142 +++---- docs/skills/comark/references/parsing-ast.md | 94 ++--- .../comark/references/rendering-angular.md | 102 ++--- .../comark/references/rendering-react.md | 111 +++--- .../comark/references/rendering-svelte.md | 135 +++---- .../skills/comark/references/rendering-vue.md | 73 ++-- docs/skills/migrate-mdc-to-comark/SKILL.md | 82 ++-- examples/1.frameworks/astro/README.md | 41 +- .../src/content/posts/astro-integration.md | 58 +-- .../astro/src/content/posts/comark-syntax.md | 24 +- .../astro/src/content/posts/hello-world.md | 24 +- examples/1.frameworks/nextjs/README.md | 47 +-- .../nextjs/content/posts/comark-syntax.md | 28 +- .../nextjs/content/posts/hello-world.md | 20 +- .../content/posts/nextjs-integration.md | 22 +- examples/1.frameworks/nuxt/README.md | 50 +-- .../nuxt/content/posts/comark-syntax.md | 24 +- .../nuxt/content/posts/hello-world.md | 20 +- .../nuxt/content/posts/nuxt-ui-integration.md | 34 +- examples/1.frameworks/sveltekit/README.md | 44 +- examples/1.frameworks/vitepress/README.md | 42 +- examples/1.frameworks/vitepress/demo.md | 28 +- examples/1.frameworks/vitepress/index.md | 16 +- examples/2.vite/angular/README.md | 41 +- .../content/posts/angular-integration.md | 24 +- .../angular/content/posts/comark-syntax.md | 24 +- .../angular/content/posts/hello-world.md | 22 +- examples/2.vite/html/README.md | 191 +-------- examples/2.vite/react/README.md | 41 +- .../react/content/posts/comark-syntax.md | 24 +- .../2.vite/react/content/posts/hello-world.md | 20 +- .../react/content/posts/react-integration.md | 24 +- examples/2.vite/svelte/README.md | 44 +- .../svelte/content/posts/comark-syntax.md | 24 +- .../svelte/content/posts/hello-world.md | 20 +- .../content/posts/svelte-integration.md | 22 +- examples/2.vite/vue-streaming/README.md | 59 ++- examples/2.vite/vue/README.md | 44 +- .../2.vite/vue/content/posts/comark-syntax.md | 24 +- .../2.vite/vue/content/posts/hello-world.md | 22 +- .../vue/content/posts/vue-integration.md | 24 +- examples/3.cli/ansi/source.md | 51 ++- examples/3.plugins/react-vite-math/README.md | 95 ++--- .../3.plugins/react-vite-mermaid/README.md | 55 ++- examples/3.plugins/vue-vite-binding/README.md | 77 ++-- .../3.plugins/vue-vite-highlight/README.md | 131 ++---- .../3.plugins/vue-vite-json-render/README.md | 64 ++- examples/3.plugins/vue-vite-math/README.md | 107 +++-- examples/3.plugins/vue-vite-mermaid/README.md | 63 ++- .../3.plugins/vue-vite-punctuation/README.md | 42 +- examples/3.plugins/vue-vite-rangi/README.md | 90 ++--- examples/4.ai/nuxt-ai-sdk/README.md | 33 +- packages/comark-angular/README.md | 14 +- packages/comark-ansi/README.md | 14 +- packages/comark-html/README.md | 12 +- packages/comark-nuxt/README.md | 2 +- packages/comark-react/README.md | 14 +- packages/comark-svelte/README.md | 14 +- packages/comark-vue/README.md | 18 +- packages/comark/README.md | 20 +- 161 files changed, 2823 insertions(+), 3477 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 0d4f0ac82..3909c78a9 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,32 +1,28 @@ -# Security Policy +# Security policy -## Supported Versions +## Supported versions | Version | Supported | |---------|--------------------| | Latest | :white_check_mark: | -## Reporting a Vulnerability +## Reporting a vulnerability -If you discover a security vulnerability in Comark, please report it responsibly. +If you discover a security vulnerability in Comark, report it privately. -**Do not open a public issue.** Instead, please email us at: +**Do not open a public issue.** Email **security@comark.dev** with: -**security@comark.dev** - -Include the following in your report: - -- Description of the vulnerability +- A description of the vulnerability - Steps to reproduce - Potential impact -- Suggested fix (if any) +- A suggested fix, if you have one -## Response Timeline +## Response timeline -- **Acknowledgment**: Within 48 hours of receiving the report -- **Assessment**: Within 7 days we will assess the severity and impact -- **Fix**: Critical vulnerabilities will be patched as soon as possible -- **Disclosure**: We will coordinate with you on public disclosure timing +- **Acknowledgment**: within 48 hours of receiving the report +- **Assessment**: we assess severity and impact within 7 days +- **Fix**: we patch critical vulnerabilities as soon as possible +- **Disclosure**: we coordinate public disclosure timing with you ## Scope @@ -38,10 +34,11 @@ This policy applies to all packages in the Comark monorepo: - `@comark/vue` - `@comark/react` - `@comark/svelte` +- `@comark/angular` - `@comark/nuxt` (deprecated) -## Built-in Security +## Built-in security -Comark includes a built-in [security plugin](https://comark.dev/plugins/built-in/security) (`comark/plugins/security`) that provides XSS sanitization. We recommend enabling it when rendering user-generated content. +Comark includes a [security plugin](https://comark.dev/plugins/built-in/security) (`comark/plugins/security`) for XSS sanitization. Enable it when rendering untrusted or user-generated content. Thank you for helping keep Comark and its users safe. diff --git a/docs/README.md b/docs/README.md index e3e064091..fe46ef564 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,185 +1,97 @@ -# Comark Documentation +# Comark documentation -This directory contains comprehensive documentation for the Comark library, built with the [comark-docs](https://github.com/comarkdown/comark-docs) Nuxt layer. +This directory contains the [comark.dev](https://comark.dev) documentation site, built with the [`comark-docs`](https://github.com/comarkdown/comark-docs) Nuxt layer. -## Documentation Structure +## Local development -### Getting Started -- **[Documentation Home](./content/index.md)** - Start here for an overview -- **[Installation](./content/1.getting-started/1.installation.md)** - Set up Comark in your project - -### Agent skill - -To install the Comark [Agent Skill](https://agentskills.io) from the published documentation site: +From the repository root: ```bash -npx skills add https://comark.dev +pnpm docs ``` -See the [Installation guide](./content/1.getting-started/1.installation.md) (section *Agent Skill*) for more context. - -### Core API Documentation -1. **[Parse API](./content/5.api/1.parse.md)** - String parsing - - `parseMarkdown()` - Parse markdown strings - - Types and interfaces - -2. **[Auto-Close API](./content/5.api/2.auto-close.md)** - Handle incomplete syntax - - `autoCloseMarkdown()` - Auto-close unclosed syntax - - Streaming integration - - Use cases - -### Rendering -3. **[Vue Rendering](./content/3.rendering/3.vue.md)** - Render Comark content in Vue - - Component props - - Custom components - - Slots and error handling - -4. **[React Rendering](./content/3.rendering/5.react.md)** - Render Comark content in React - - Component props - - Custom components - - Props conversion - -5. **[Svelte Rendering](./content/3.rendering/6.svelte.md)** - Render Comark content in Svelte - - Snippets and streaming - - SvelteKit SSR - -6. **[Angular Rendering](./content/3.rendering/7.angular.md)** - Render Comark content in Angular - - Standalone components - - Custom components and streaming - -7. **[HTML Rendering](./content/3.rendering/2.html.md)** - Framework-free HTML strings - -8. **[ANSI Rendering](./content/3.rendering/8.ansi.md)** - Terminal output - -## Quick Navigation - -### By Use Case - -**I want to...** - -- **Install Comark** → [Installation Guide](./content/1.getting-started/1.installation.md) -- **Install the Agent Skill** → `npx skills add https://comark.dev` (see [Getting Started → Agent skill](#agent-skill-ai-assistants) above) -- **Parse markdown from a string** → [Parse API](./content/5.api/1.parse.md) -- **Handle incomplete markdown** → [Auto-Close API](./content/5.api/2.auto-close.md) -- **Render Comark in Vue** → [Vue Rendering](./content/3.rendering/3.vue.md) -- **Render Comark in React** → [React Rendering](./content/3.rendering/5.react.md) -- **Render Comark in Svelte** → [Svelte Rendering](./content/3.rendering/6.svelte.md) -- **Render Comark in Angular** → [Angular Rendering](./content/3.rendering/7.angular.md) -- **Create custom components** → [Vue - Custom Components](./content/3.rendering/3.vue.md#custom-components) - -### By Technology - -- **TypeScript** → All documentation includes TypeScript examples -- **Vue** → [Vue Rendering](./content/3.rendering/3.vue.md) -- **React** → [React Rendering](./content/3.rendering/5.react.md) -- **Svelte** → [Svelte Rendering](./content/3.rendering/6.svelte.md) -- **Angular** → [Angular Rendering](./content/3.rendering/7.angular.md) - -## Development - -### Quick Start +Or from `docs/`: ```bash -# Install dependencies -pnpm install - -# Start development server -pnpm run dev +pnpm dev # Start the dev server at http://localhost:3000 +pnpm lint # Lint Markdown and Comark component usage in content/ +pnpm build # Build the site into .output/ ``` -Your documentation site will be running at `http://localhost:3000` - -### Project Structure +## Structure ``` docs/ -├── content/ # Documentation markdown files -│ ├── index.md # Documentation home -│ ├── 1.getting-started/ # Getting started guides -│ ├── 2.syntax/ # Syntax documentation -│ ├── 3.rendering/ # Framework and string rendering -│ ├── 5.api/ # API reference docs -│ └── 8.examples.md # Examples -├── public/ # Static assets -└── package.json # Dependencies and scripts +├── app/ # Site pages and custom prose components +├── content/ # Documentation Markdown files +│ ├── index.md # Landing page +│ ├── 1.getting-started/ # Introduction, installation, and document model +│ ├── 2.syntax/ # Markdown, components, attributes, and frontmatter +│ ├── 3.rendering/ # HTML, Vue, React, Svelte, Angular, and ANSI renderers +│ ├── 4.plugins/ # Default, built-in, and custom plugins +│ ├── 5.reference/ # Render, parse, auto-close, and type reference +│ ├── 7.kb/ # Architecture notes and migration guides +│ ├── 8.examples/ # Runnable framework, Vite, plugin, and AI examples +│ ├── 9.ecosystem.md # Community packages and production sites +│ ├── 10.use-cases/ # Task-focused guides +│ └── 11.compare/ # Library comparisons +├── public/ # Static assets +├── server/ # Server routes (including /llms-*.txt endpoints) +├── skills/ # Published agent skills (comark, migrate-mdc-to-comark) +├── comark-lint.config.ts # comark-linter configuration +└── nuxt.config.ts # Nuxt configuration ``` -## API Reference - -### Parse Utilities - -| Function | Purpose | Documentation | -|----------|---------|---------------| -| `parseMarkdown()` | Parse string | [Parse API](./content/5.api/1.parse.md) | -| `autoCloseMarkdown()` | Auto-close syntax | [Auto-Close API](./content/5.api/2.auto-close.md) | - -### Framework Components +## Key pages -| Export | Type | Documentation | -|--------|------|---------------| -| `Markdown` (Vue) | Component | [Vue Rendering](./content/3.rendering/3.vue.md) | -| `Markdown` (React) | Component | [React Rendering](./content/3.rendering/5.react.md) | -| `Markdown` (Svelte) | Component | [Svelte Rendering](./content/3.rendering/6.svelte.md) | -| `Markdown` (Angular) | Component | [Angular Rendering](./content/3.rendering/7.angular.md) | +### Getting started and syntax -### Types +- [Documentation home](./content/index.md): landing page and overview +- [Introduction](./content/1.getting-started/0.introduction.md): architecture and capabilities +- [Installation](./content/1.getting-started/1.installation.md): packages, IDE extension, and browser extension +- [Document model](./content/1.getting-started/2.document-model.md): `MarkdownDocument`, node tuples, and utilities +- [Syntax](./content/2.syntax/1.markdown.md): CommonMark, GFM, [components](./content/2.syntax/2.components.md), [attributes](./content/2.syntax/3.attributes.md), and [frontmatter](./content/2.syntax/4.frontmatter.md) -| Type | Purpose | Documentation | -|------|---------|---------------| -| `MarkdownDocument` | Parse Markdown document | [API Reference](./content/5.api/3.reference.md) | -| `Node` | AST node | [API Reference](./content/5.api/3.reference.md) | +### Reference -## Contributing to Documentation +- [Render API](./content/5.reference/0.render.md): `renderMarkdown()` and string rendering options +- [Parse API](./content/5.reference/1.parse.md): `parseMarkdown()`, `createMarkdownParser()`, and parser options +- [Auto-close API](./content/5.reference/2.auto-close.md): `autoCloseMarkdown()` for incomplete Markdown streams +- [API reference](./content/5.reference/3.reference.md): `MarkdownDocument`, `Node`, utilities, and `transformNode` -When contributing documentation: +### Renderers -1. **Follow the existing structure** - Match the format of existing docs -2. **Include code examples** - Show TypeScript and framework-specific examples -3. **Add cross-references** - Link to related documentation -4. **Test all examples** - Ensure code examples actually work -5. **Use proper markdown** - Follow Comark for components +- [HTML rendering](./content/3.rendering/2.html.md): `@comark/html` +- [Vue rendering](./content/3.rendering/3.vue.md): `@comark/vue` and Nuxt module +- [React rendering](./content/3.rendering/5.react.md): `@comark/react` and Server Components +- [Svelte rendering](./content/3.rendering/6.svelte.md): `@comark/svelte` and SvelteKit SSR +- [Angular rendering](./content/3.rendering/7.angular.md): `@comark/angular` (Angular 21+) +- [ANSI rendering](./content/3.rendering/8.ansi.md): `@comark/ansi` -### Documentation Standards +## Agent skill -- **Headers**: Use sentence case (e.g., "Parse API" not "Parse api") -- **Code blocks**: Always specify language (```typescript, ```vue, etc.) -- **Links**: Use relative links within docs -- **Examples**: Include both simple and advanced examples -- **TypeScript**: Always include type annotations -- **Comments**: Explain non-obvious code - -## Built With - -This documentation site uses: - -- [Nuxt 4](https://nuxt.com) - The web framework -- [Nuxt Content](https://content.nuxt.com/) - File-based CMS -- [Nuxt UI](https://ui.nuxt.com) - UI components -- [Tailwind CSS 4](https://tailwindcss.com/) - Utility-first CSS -- [comark-docs](https://github.com/comarkdown/comark-docs) - Documentation layer - -## Deployment - -Build for production: +Install the Comark [Agent Skill](https://agentskills.io) from the published site: ```bash -pnpm run build +npx skills add https://comark.dev ``` -The built files will be in the `.output` directory, ready for deployment. +Skill sources live in [`./skills/`](./skills/). See the [Installation guide](./content/1.getting-started/1.installation.md#agent-skill) for details. + +## Writing documentation -Deploy to: -- [Vercel](https://vercel.com) -- [Netlify](https://netlify.com) -- [Cloudflare Pages](https://pages.cloudflare.com) -- Any Node.js hosting +- Use sentence case for headings, card titles, and bold labels (for example, `## Parse options`, not `## Parse Options`). +- Specify a language on every fenced code block (`ts`, `tsx`, `vue`, `svelte`, `mdc`, `bash`). +- Use root-relative links inside `content/` (for example, `/reference/parse`) and run `pnpm --filter comark-docs-site lint` to check components, unclosed blocks, and links. +- Use Comark prose components (`::code-group`, `::tabs`, `::callout`, `::note`, `::card-group`) in `content/`, and plain GitHub Flavored Markdown in `README.md` files. -## Questions or Issues? +## Built with -- **Documentation unclear?** [Open an issue](https://github.com/comarkdown/comark/issues) -- **Example doesn't work?** [Report it](https://github.com/comarkdown/comark/issues) -- **Want to contribute?** [Submit a PR](https://github.com/comarkdown/comark/pulls) +- [`comark-docs`](https://github.com/comarkdown/comark-docs): Nuxt documentation layer built on Comark +- [Nuxt 4](https://nuxt.com): application framework +- [Nuxt UI](https://ui.nuxt.com): UI and prose components +- [Tailwind CSS 4](https://tailwindcss.com): styling ## License -Documentation is under the same license as the project (ISC). +Published under the [MIT License](../LICENSE) (MIT). diff --git a/docs/content/1.getting-started/0.introduction.md b/docs/content/1.getting-started/0.introduction.md index 4b865187d..10ccfa5fb 100644 --- a/docs/content/1.getting-started/0.introduction.md +++ b/docs/content/1.getting-started/0.introduction.md @@ -1,6 +1,6 @@ --- title: 'What Is Comark? Markdown Parser and Renderer' -description: 'Comark is an open-source Markdown parser and renderer with components, attributes and plugins. It streams AI output to React, Vue, Svelte, Angular, HTML and the terminal.' +description: 'Comark is an open-source Markdown parser and renderer with components, attributes, and plugins. It streams AI output to React, Vue, Svelte, Angular, HTML, and the terminal.' navigation: title: Introduction links: @@ -17,11 +17,11 @@ links: variant: soft --- -**Comark** is an open-source Markdown parser and renderer with components, attributes and plugins. It streams AI output to React, Vue, Svelte, Angular, HTML and the terminal. Give it standard CommonMark or GitHub Flavored Markdown (GFM), and render the same source to any of these targets. +**Comark** is an open-source Markdown parser and renderer with components, attributes, and plugins. It streams AI output to React, Vue, Svelte, Angular, HTML, and the terminal. Give it CommonMark or GitHub Flavored Markdown (GFM), and render the same source to any of these targets. Parsing and rendering are decoupled through a compact, serializable [`MarkdownDocument`](/getting-started/document-model). Parse on the server, in the browser, in a worker, during a build, or as content streams in. You can then inspect, transform, cache, serialize, or render the document without tying your content to one output target. -Comark is built on [markdown-exit](https://github.com/serkodev/markdown-exit), a TypeScript rewrite of markdown-it that preserves its plugin API. It combines that foundation with streaming support, an extensible plugin system, and optional component and attribute syntax for richer content. +Comark is built on [markdown-exit](https://github.com/serkodev/markdown-exit), a TypeScript rewrite of markdown-it that preserves its plugin API. It adds streaming support, a plugin system, and optional component and attribute syntax. Start with the renderer that matches your output: @@ -97,6 +97,8 @@ Learn why we created Comark and the principles behind its design in [Why Comark] ## How it works +The following diagram shows how Comark parses Markdown once and renders the resulting document to each target: + ::div{.border .border-default .rounded .bg-muted .p-4} ```mermaid graph LR @@ -113,13 +115,13 @@ graph LR ``` :: -1. **Parse** - Comark parses Markdown into a compact [`MarkdownDocument`](/getting-started/document-model) -2. **Transform** - Inspect, transform, cache, or serialize the document -3. **Render** - Convert the document to HTML, ANSI, Markdown, Vue, React, Svelte, or Angular +1. **Parse**: Comark parses Markdown into a compact [`MarkdownDocument`](/getting-started/document-model). +2. **Transform**: inspect, transform, cache, or serialize the document. +3. **Render**: convert the document to HTML, ANSI, Markdown, Vue, React, Svelte, or Angular. ## Extend Markdown when needed -Plain Markdown works without any component syntax. When your content needs richer structure, Comark adds readable components and attributes without embedding verbose HTML or executable framework code: +Plain Markdown works without any component syntax. When your content needs custom UI, Comark adds components and attributes without embedding verbose HTML or executable framework code: ```mdc # Welcome to my blog @@ -131,25 +133,25 @@ This is an important message! :: ``` -The `::alert` block supports properties, children, and named slots. The renderer only uses components you explicitly register, so the source remains portable data rather than framework-specific code. Learn more in [Component Syntax](/syntax/components) and [Attributes](/syntax/attributes). +The `::alert` block supports properties, children, and named slots. The renderer only uses components you explicitly register, so the source remains portable data rather than framework-specific code. Learn more in [Component syntax](/syntax/components) and [Attributes](/syntax/attributes). -Editor and browser tooling when working with Comark components: -- [Comark for VS Code extension](/getting-started/installation#ide-extension) for components and attributes syntax highlighting and autocomplete -- [Comark for GitHub browser extension](/getting-started/installation#browser-extension) to visualize Comark syntax directly on GitHub Markdown pages +Editor and browser extensions for Comark syntax: +- [Comark for VS Code](/getting-started/installation#ide-extension) adds syntax highlighting and autocomplete for components and attributes. +- [Comark for GitHub](/getting-started/installation#browser-extension) renders Comark syntax on GitHub Markdown pages. ## When to use Comark -Comark is ideal for: +Use Comark when your project needs any of the following: -- **Content platforms** - Parse Markdown from files, databases, APIs, or a CMS at build time or runtime -- **Multi-target publishing** - Reuse one source for applications, static HTML, RSS, email, and terminal output -- **AI chat interfaces** - Stream and render incomplete Markdown responses in real time -- **Documentation and blogs** - Combine standard Markdown with callouts, embeds, diagrams, and interactive UI -- **Content pipelines** - Inspect, transform, cache, or serialize a compact document before rendering +- **Content platforms**: parse Markdown from files, databases, APIs, or a CMS at build time or runtime. +- **Multi-target publishing**: render one source to web apps, static HTML, RSS, email, and terminal output. +- **AI chat interfaces**: stream and render incomplete Markdown responses as tokens arrive. +- **Documentation and blogs**: combine CommonMark and GFM with callouts, embeds, diagrams, and interactive UI. +- **Content pipelines**: inspect, transform, cache, or serialize a compact document before rendering. ## Comparison with other tools -For detailed, honest comparisons, see [Comark vs MDX](/compare/comark-vs-mdx), [Comark vs react-markdown](/compare/comark-vs-react-markdown), [Comark vs Streamdown](/compare/comark-vs-streamdown), and [Comark vs Markdoc](/compare/comark-vs-markdoc). +For detailed comparisons, see [Comark vs MDX](/compare/comark-vs-mdx), [Comark vs react-markdown](/compare/comark-vs-react-markdown), [Comark vs Streamdown](/compare/comark-vs-streamdown), and [Comark vs Markdoc](/compare/comark-vs-markdoc). | Feature | Comark | Streamdown | MDX | Markdoc | |---------|--------|------------|-----|---------| @@ -170,26 +172,26 @@ For detailed, honest comparisons, see [Comark vs MDX](/compare/comark-vs-mdx), [ ::card-group #default ::card{icon="i-lucide-file-text" title="CommonMark and GFM" to="/syntax/markdown"} - Parse familiar Markdown syntax, including tables, task lists, code blocks, and more. + Parse standard Markdown syntax, including tables, task lists, and code blocks. :: - ::card{icon="i-lucide-layers" title="Parse Once, Render Anywhere" to="/getting-started/document-model"} + ::card{icon="i-lucide-layers" title="Parse once, render anywhere" to="/getting-started/document-model"} Produce a compact document you can inspect, cache, serialize, and render to every supported target. :: - ::card{icon="i-lucide-radio" title="Streaming Support" to="/rendering/vue#streaming"} - Real-time incremental parsing for AI chat interfaces and live content. + ::card{icon="i-lucide-radio" title="Streaming support" to="/rendering/vue#streaming"} + Incremental parsing and auto-close for AI chat interfaces and live content. :: - ::card{icon="i-lucide-puzzle" title="Plugin Ecosystem" to="/plugins"} + ::card{icon="i-lucide-puzzle" title="Plugin ecosystem" to="/plugins"} Extend parsing with Comark plugins or reuse plugins written for markdown-it. :: - ::card{icon="i-lucide-component" title="Component Syntax" to="/syntax/components"} - Add props, slots, and nested UI while keeping content as readable plain text. + ::card{icon="i-lucide-component" title="Component syntax" to="/syntax/components"} + Add props, slots, and nested UI while keeping content as plain text. :: - ::card{icon="i-lucide-code" title="Dedicated Renderers" to="/getting-started/installation"} + ::card{icon="i-lucide-code" title="Dedicated renderers" to="/getting-started/installation"} Render to HTML, ANSI, Vue, React, Svelte, and Angular without changing the source. :: :: diff --git a/docs/content/1.getting-started/1.installation.md b/docs/content/1.getting-started/1.installation.md index 604c5b7aa..8e11cd2cd 100644 --- a/docs/content/1.getting-started/1.installation.md +++ b/docs/content/1.getting-started/1.installation.md @@ -2,7 +2,7 @@ title: Installation description: Install Comark and choose a parser or renderer for HTML, ANSI, Vue, React, Svelte, or Angular to start working with Markdown in minutes. links: - - label: Comark Syntax + - label: Comark syntax icon: i-lucide-file-text to: /syntax/components color: neutral @@ -25,7 +25,7 @@ Choose the output you need and render your first Markdown document in minutes. :: ::card{icon="i-logos-vue" title="Vue" to="/rendering/vue"} - Use Comark in Vue 3 applications with full async component support and streaming. + Use Comark in Vue 3 applications with async component support and streaming. :: ::card{icon="i-logos-nuxt-icon" title="Nuxt" to="/rendering/vue#nuxt"} @@ -41,17 +41,17 @@ Choose the output you need and render your first Markdown document in minutes. :: ::card{icon="i-logos-angular-icon" title="Angular" to="/rendering/angular"} - Use Comark in Angular 17+ applications with standalone components and streaming. + Use Comark in Angular 21+ applications with standalone components and streaming. :: ::card{icon="i-lucide-terminal" title="ANSI" to="/rendering/ansi"} - Render Comark as styled terminal output for CLIs and developer tooling. + Render Comark as styled terminal output for CLIs and developer tools. :: :: ## Agent skill -To give coding agents the Comark skill (syntax, AST, renderers, streaming), install it from production: +To give coding agents the Comark skill (syntax, AST, renderers, and streaming), install it from comark.dev: ```bash [Terminal] npx skills add https://comark.dev @@ -59,12 +59,12 @@ npx skills add https://comark.dev ## IDE extension -Install the [Comark extension](https://marketplace.visualstudio.com/items?itemName=Nuxt.mdc) in **VS Code** or **Cursor** for syntax highlighting, bracket matching, document folding, and auto-completion in `.md` files using Comark syntax. +Install the [Comark extension](https://marketplace.visualstudio.com/items?itemName=Nuxt.mdc) in **VS Code** or **Cursor** for syntax highlighting, bracket matching, document folding, and autocomplete in `.md` files using Comark syntax. ::card-group ::card --- - title: Comark Extension + title: Comark extension icon: "i-logos-visual-studio-code" color: "neutral" variant: "subtle" @@ -82,7 +82,7 @@ ext install Nuxt.mdc ## Browser extension -Install **Comark for GitHub** to better visualize Markdown files that use Comark components and attributes syntax on GitHub. +Install **Comark for GitHub** to render Comark component and attribute syntax when viewing Markdown files on GitHub. ::card-group ::card @@ -107,7 +107,7 @@ target: "_blank" :: ::card --- -title: "View Source / Manual Install" +title: "View source and manual install" icon: "i-simple-icons-github" color: "neutral" variant: "subtle" @@ -218,7 +218,7 @@ Use these when you need to render Markdown as an interactive document in Vue, Re ### String renderers -Use these when you need a string output with no UI framework involved like server-side HTML generation, static site builds, or CLI tooling. +Use these when you need string output without a UI framework, such as server-side HTML generation, static site builds, or CLI tools. ::tabs ::tabs-item{label="HTML" icon="i-vscode-icons-file-type-html"} @@ -296,23 +296,22 @@ See the [Parse API](/reference/parse) and [Render API](/reference/render) for fu ## Learn more -Learn more about Comark features and syntax: +Explore Comark syntax and plugins: ::card-group{cols="2"} - :::card{icon="i-lucide-code" title="Markdown Syntax" to="/syntax/markdown"} - Learn the standard Markdown syntax and how to use it with Comark. + :::card{icon="i-lucide-code" title="Markdown syntax" to="/syntax/markdown"} + Read how Comark parses CommonMark and GitHub Flavored Markdown. ::: :::card{icon="i-lucide-component" title="Components" to="/syntax/components"} - Learn the component syntax for blocks, inline elements, props, and slots + Embed block and inline components with props and slots. ::: :::card{icon="i-lucide-tag" title="Attributes" to="/syntax/attributes"} - Add classes, IDs, and custom attributes to Markdown elements + Add classes, IDs, and custom attributes to Markdown elements. ::: - :::card{icon="i-lucide-plug" title="Plugins" to="/plugins"} - Add syntax highlighting, math, mermaid diagrams, and more + Add syntax highlighting, math, Mermaid diagrams, and more. ::: :: diff --git a/docs/content/1.getting-started/2.document-model.md b/docs/content/1.getting-started/2.document-model.md index dfa1b8b5c..38035be73 100644 --- a/docs/content/1.getting-started/2.document-model.md +++ b/docs/content/1.getting-started/2.document-model.md @@ -1,6 +1,6 @@ --- title: Document Model -description: Understand the serializable Markdown document returned by Comark, including its nodes, frontmatter, metadata and rendering workflow. +description: Understand the serializable Markdown document returned by Comark, including its nodes, frontmatter, metadata, and rendering workflow. navigation: title: Document links: @@ -16,7 +16,7 @@ links: variant: soft --- -`parseMarkdown()` returns a `MarkdownDocument`: a plain, serializable object containing parsed nodes, frontmatter, and plugin metadata. +`parseMarkdown()` returns a `MarkdownDocument`, a plain, serializable object containing parsed nodes, frontmatter, and plugin metadata. ```ts import { parseMarkdown } from 'comark' @@ -313,7 +313,7 @@ type ArticleDocument = MarkdownDocument Parser plugins can contribute these types automatically when you parse content directly. -Use “AST” when discussing the node representation itself. Use “document” for the root object returned by the parser and accepted by renderers. +Use "AST" when discussing the node representation itself. Use "document" for the root object returned by the parser and accepted by renderers. ```tsx const document = await parseMarkdown(markdown) diff --git a/docs/content/10.use-cases/1.intelligent-ui.md b/docs/content/10.use-cases/1.intelligent-ui.md index 71fa05723..7e63e47ce 100644 --- a/docs/content/10.use-cases/1.intelligent-ui.md +++ b/docs/content/10.use-cases/1.intelligent-ui.md @@ -32,7 +32,7 @@ You can build the same pattern in your own app. Each part has a Comark equivalen | Intelligent UI | Comark | | --- | --- | | A library of native components | Your Vue, React, Svelte, or Angular components, registered in the `components` prop | -| Streamable components | `streaming` and `autoClose`: a component renders before its closing `::` arrives | +| Streamable components | `streaming` and `autoClose` render a component before its closing `::` arrives | | A compiler that processes the interface during generation | The parser turns `::component{props}` into data, and runs no code | | The model picks the layout, or plain text | A system prompt that lists your components and when to use them | @@ -65,7 +65,7 @@ items: :: ``` -The `:` prefix gives a typed value: `guests` is the number `6`. The YAML block passes `items` as an array of objects. The list inside `::timeline` is the default slot. See [component syntax](/syntax/components) for props, slots, and nesting. +The `:` prefix parses a typed value, so `guests` is the number `6`. The YAML block passes `items` as an array of objects. The list inside `::timeline` is the default slot. See [component syntax](/syntax/components) for props, slots, and nesting. ## Write streamable components @@ -87,7 +87,7 @@ interface Item { name?: string, perGuest?: number, unit?: string } const props = defineProps<{ guests?: number, items?: Item[] }>() -// Model values are untrusted: keep only positive, finite numbers. +// Keep only positive, finite numbers from untrusted model output. const positive = (value: unknown) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined @@ -122,7 +122,7 @@ import { useState } from 'react' interface Item { name?: string, perGuest?: number, unit?: string } -// Model values are untrusted: keep only positive, finite numbers. +// Keep only positive, finite numbers from untrusted model output. const positive = (value: unknown) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined @@ -244,7 +244,7 @@ Three practices help the model choose well: - **Allow plain text.** Without the rule, a model tends to place components in every answer. - **Give one example per component.** The model copies the syntax of the example, including the `:` prefix and the YAML block. -To test the catalog, run a fixed set of questions against it, and check which components each answer uses. This docs site builds its page generator prompt from a component registry the same way: see [`docs/server/utils/prompt.ts`](https://github.com/comarkdown/comark/blob/main/docs/server/utils/prompt.ts). +To test the catalog, run a fixed set of questions against it, and check which components each answer uses. This docs site builds its page generator prompt from a component registry the same way in [`docs/server/utils/prompt.ts`](https://github.com/comarkdown/comark/blob/main/docs/server/utils/prompt.ts). ## Keep model output safe diff --git a/docs/content/10.use-cases/10.email-and-rss.md b/docs/content/10.use-cases/10.email-and-rss.md index 1175e68c8..2ccbda77a 100644 --- a/docs/content/10.use-cases/10.email-and-rss.md +++ b/docs/content/10.use-cases/10.email-and-rss.md @@ -65,7 +65,7 @@ Thanks for signing up. :button[Confirm your email]{href="https://example.com/confirm"} ``` -`@comark/html` returns only the content HTML. Put it inside your email layout. Email clients differ in their CSS support. We recommend that you inline the styles of your layout and of the Markdown elements with a separate CSS inliner tool. +`@comark/html` returns only the content HTML. Put it inside your email layout. Email clients differ in their CSS support, so we recommend inlining the CSS for your layout and Markdown elements with a CSS inliner before sending. ## Pass per-recipient data diff --git a/docs/content/10.use-cases/2.ai-chat-streaming.md b/docs/content/10.use-cases/2.ai-chat-streaming.md index a55e4e959..8cd14d66d 100644 --- a/docs/content/10.use-cases/2.ai-chat-streaming.md +++ b/docs/content/10.use-cases/2.ai-chat-streaming.md @@ -134,7 +134,7 @@ const plugins = [security({ blockedTags: ['script', 'iframe', 'embed', 'form', ' // ``` -Define `plugins` outside the component, so the reference stays stable between renders. Import the same plugin from `@comark/vue/plugins/security`, `@comark/svelte/plugins/security`, or `@comark/angular/plugins/security`. To turn off raw HTML parsing, set `registerDefaultPlugins: false` and register only the plugins you need, without `html`. +Define `plugins` outside the component, so the reference stays stable between renders. Import the same plugin from `@comark/vue/plugins/security` or `@comark/svelte/plugins/security`, or as `{ security }` from `@comark/angular/plugins/security`. To turn off raw HTML parsing, set `registerDefaultPlugins: false` and register only the plugins you need, without `html`. ## FAQ diff --git a/docs/content/10.use-cases/3.vue-ai-chat.md b/docs/content/10.use-cases/3.vue-ai-chat.md index dd6d401dc..f7c6c8bd5 100644 --- a/docs/content/10.use-cases/3.vue-ai-chat.md +++ b/docs/content/10.use-cases/3.vue-ai-chat.md @@ -93,7 +93,7 @@ function onSubmit() {
- +
``` diff --git a/docs/content/10.use-cases/4.svelte-ai-chat.md b/docs/content/10.use-cases/4.svelte-ai-chat.md index 9faeefb68..c975a1537 100644 --- a/docs/content/10.use-cases/4.svelte-ai-chat.md +++ b/docs/content/10.use-cases/4.svelte-ai-chat.md @@ -87,7 +87,7 @@ Pass `part.state === 'streaming'` to the `streaming` prop. Each part then runs i {/each}
- +
``` diff --git a/docs/content/10.use-cases/5.angular-ai-chat.md b/docs/content/10.use-cases/5.angular-ai-chat.md index fa21f4c71..43d1e2e4e 100644 --- a/docs/content/10.use-cases/5.angular-ai-chat.md +++ b/docs/content/10.use-cases/5.angular-ai-chat.md @@ -1,6 +1,6 @@ --- title: 'Stream Markdown in Angular with the AI SDK' -description: 'Build an Angular 17+ chat that streams AI SDK responses and renders each message as Markdown with Comark while it arrives.' +description: 'Build an Angular 21+ chat that streams AI SDK responses and renders each message as Markdown with Comark while it arrives.' navigation: title: Angular chat icon: i-simple-icons-angular @@ -19,7 +19,7 @@ links: Use the `Chat` class from `@ai-sdk/angular` to receive messages, and render each text part with ``. Comark closes unfinished syntax while the part streams, and runs a full parse when it is complete. -`@comark/angular` supports Angular 17 or later. See the [requirements](/rendering/angular#requirements) for the exact range. The `Chat` class from `@ai-sdk/angular` stores its state in Angular signals, so the template updates as tokens arrive. +`@comark/angular` supports Angular 21+ (`>=21.0.0 <23.0.0`). See the [requirements](/rendering/angular#requirements) for details. The `Chat` class from `@ai-sdk/angular` stores its state in Angular signals, so the template updates as tokens arrive. ## Build the chat @@ -85,7 +85,7 @@ import { Markdown } from '@comark/angular' }
- +
`, }) @@ -107,7 +107,7 @@ export class ChatComponent { Use the `components` input to map Comark tags to Angular components. Use the `plugins` input to add parser plugins, for example the [security plugin](/plugins/built-in/security) for untrusted output. This excerpt adds two properties to the component above: ```typescript [chat.component.ts] -import security from '@comark/angular/plugins/security' +import { security } from '@comark/angular/plugins/security' import { AlertComponent } from './alert.component' export class ChatComponent { diff --git a/docs/content/10.use-cases/6.generative-ui.md b/docs/content/10.use-cases/6.generative-ui.md index 64aaac3ef..4c86fd91d 100644 --- a/docs/content/10.use-cases/6.generative-ui.md +++ b/docs/content/10.use-cases/6.generative-ui.md @@ -17,7 +17,7 @@ links: variant: soft --- -The model writes component syntax, for example `::flight-card{from="CDG" to="JFK" price="342"}`, and your app maps the tag to a real component. Component syntax is data: it runs no code, and only the components that you register render as components. Raw HTML in the output is different: the default `html` plugin keeps a ` ``` @@ -389,8 +386,8 @@ import { AppMarkdown } from './markdown' |--------|------|---------|-------------| | [`extends`](#extends) | `ReturnType` | `undefined` | Inherit plugins and components from another component | | `name` | `string` | `undefined` | Component name for debugging | -| `autoUnwrap` | `boolean` | `true` | Automatically unwrap single block elements | -| `autoClose` | `boolean` | `true` | Auto-close incomplete markdown syntax | +| `autoUnwrap` | `boolean` | `true` | Unwrap single paragraph elements inside components | +| `autoClose` | `boolean` | `true` | Auto-close incomplete Markdown syntax | | `linkify` | `boolean` | `true` | **Deprecated.** Use `registerDefaultPlugins: false` and register [`linkify()`](/plugins/defaults/linkify) instead | | `registerDefaultPlugins` | `boolean` | `true` | Register default plugins (`linkify`, `frontmatter`, `html`, `alert`, `task-list`, `components`, `attributes`) | | [`plugins`](#plugins) | `ComarkPlugin[]` | `[]` | Array of plugins | @@ -411,7 +408,6 @@ import toc from '@comark/vue/plugins/toc' import math, { Math } from '@comark/vue/plugins/math' import ProsePre from './components/ProsePre.vue' -// Base: highlight + prose components, used everywhere export const BaseMarkdown = defineMarkdownComponent({ name: 'BaseMarkdown', plugins: [ @@ -420,7 +416,6 @@ export const BaseMarkdown = defineMarkdownComponent({ components: { ProsePre }, }) -// Article: extends Base, adds TOC and math export const ArticleMarkdown = defineMarkdownComponent({ name: 'ArticleMarkdown', extends: BaseMarkdown, @@ -428,7 +423,6 @@ export const ArticleMarkdown = defineMarkdownComponent({ components: { Math }, }) -// Comment: extends Base only, no TOC, no math export const CommentMarkdown = defineMarkdownComponent({ name: 'CommentMarkdown', extends: BaseMarkdown, @@ -459,7 +453,6 @@ import { readFile } from 'node:fs/promises' const parse = createMarkdownParser() -// In your server handler export async function getContentDocument(slug: string) { const markdown = await readFile(`content/${slug}.md`, 'utf-8') return parse(markdown) @@ -490,17 +483,17 @@ const document = await res.json() | Prop | Type | Default | Description | |------|------|---------|-------------| -| `value` | `MarkdownDocument` | — | **Required.** The parsed document returned by `parseMarkdown()` | +| `value` | `MarkdownDocument` | `-` | **Required.** The parsed document returned by `parseMarkdown()` | | [`components`](#components) | `Record` | `{}` | Custom Vue component mappings | | [`componentsManifest`](#componentsmanifest) | `ComponentManifest` | `undefined` | Dynamic component resolver for lazy-loaded components | | [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode | | [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append a blinking caret to the last text node | -| [`data`](#data) | `Record` | `{}` | Runtime values referenced from markdown via `:prop="data.path"` | +| [`data`](#data) | `Record` | `{}` | Runtime values referenced from Markdown via `:prop="data.path"` | | [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render | ### `defineMarkdownDocumentComponent` -Creates a pre-configured `` with baked-in component mappings. +Creates a pre-configured `` component with default component mappings. #### Setup @@ -584,7 +577,7 @@ export const CommentMarkdownDocument = defineMarkdownDocumentComponent({ ## Live documents -`MarkdownDocument` can subscribe to an ambient **context** so external sources can drive a mounted renderer: an HMR signal, a collaboration socket, an agent editing the document while you chat with it, or devtools. The listen key is the document's own `meta.key` (set by a plugin) or the `document-key` prop, so a parsed document can carry its own identity. If `globalThis.comarkContext` exists the renderer listens for updates on that key and re-renders; on unmount it cleans up. With no context, the key is ignored at zero cost. +`MarkdownDocument` can subscribe to an ambient **context** so external sources can update a mounted renderer, such as HMR, a collaboration socket, an agent, or devtools. The listen key comes from `meta.key` (set by a plugin) or the `document-key` prop. When `globalThis.comarkContext` exists, the renderer listens for updates on that key, re-renders on change, and unsubscribes on unmount. Without a context, the key is ignored. ```vue ``` -A **driver** installs the context once and pushes updates by key with `set()` (replace the whole document) or `patch()` (surgical node edits, with structural sharing so only the changed branch re-renders): +A **driver** installs the context once and pushes updates by key with `set()` to replace the whole document, or `patch()` to edit individual nodes with structural sharing so only the changed branch re-renders: ```ts import { createComarkContext, parseMarkdown } from 'comark' @@ -604,13 +597,13 @@ doc.set(await parseMarkdown('# Replaced')) doc.patch({ op: 'insert', path: [1], node: ['p', {}, 'inserted'] }) ``` -A `path` is a node-index path into `document.nodes`: the first segment indexes the top-level nodes, each later segment indexes into that element's children. Patch operations are `replace`, `insert`, `remove` (each takes a `path`), plus `meta`, `frontmatter`, and `data` merges. The same context API powers `@comark/react`, `@comark/svelte`, and `@comark/angular`: websocket handlers, agents, devtools, and HMR all drive it the same way. +A `path` indexes into `document.nodes`, where the first segment selects a top-level node and each later segment selects a child of that element. Patch operations include `replace`, `insert`, and `remove` (each taking a `path`), along with `meta`, `frontmatter`, and `data` merges. `@comark/react`, `@comark/svelte`, and `@comark/angular` share the same context API. --- ## Component bindings -Comark automatically bridges the gap between Comark syntax and your component's interface. +Comark maps component attributes and slots in Markdown to Vue props and slots. ### Prop binding @@ -701,7 +694,7 @@ Pass the component to the `components` prop: ### Resolution order -When Comark encounters a tag, it looks for a matching Vue component in this order, stopping at the first match: +Comark resolves each tag against Vue components in this order and stops at the first match: 1. **`Prose{PascalTag}`**: for example, `ProseH1` for `h1`. Follows the Nuxt Content prose component convention. 2. **`{PascalTag}`**: for example, `Alert` for `alert`. PascalCase version of the tag name. @@ -714,7 +707,7 @@ If none match, the tag renders as a native HTML element. ## Nuxt UI integration -When [`@nuxt/ui`](https://ui.nuxt.com) is installed, Comark automatically uses Nuxt UI's prose components for enhanced styling. In [Nuxt](#nuxt), the module turns them on for you. +When [`@nuxt/ui`](https://ui.nuxt.com) is installed, Comark renders Markdown elements with Nuxt UI's prose components. In [Nuxt](#nuxt), the module enables them by default. ### Vite setup @@ -746,7 +739,7 @@ export default defineConfig({ ## Streaming -Enable real-time rendering as content arrives, ideal for AI chat interfaces and live previews. +Render Markdown incrementally as chunks arrive from an AI stream or live preview. ### Setup @@ -790,7 +783,7 @@ async function askAI(prompt: string) { ``` ::callout{icon="i-lucide-info" color="info"} -`autoClose` is enabled by default: incomplete syntax like `**bold text` is automatically closed on every parse. Disable with `:options="{ autoClose: false }"`. +`autoClose` is enabled by default and closes incomplete syntax such as `**bold text` on every parse. Disable it with `:options="{ autoClose: false }"`. :: ### Caret diff --git a/docs/content/3.rendering/5.react.md b/docs/content/3.rendering/5.react.md index 6b6aeeaac..1af4d9788 100644 --- a/docs/content/3.rendering/5.react.md +++ b/docs/content/3.rendering/5.react.md @@ -17,7 +17,7 @@ links: variant: soft --- -The `@comark/react` package provides React components for rendering Comark content with full support for custom components, plugins, and streaming. +`@comark/react` renders Markdown and Comark components in React and Next.js, with plugin support, Server Components, and streaming. ## Installation @@ -43,7 +43,7 @@ bun add @comark/react ## `` -The `` component is the quickest way to render markdown in React. It handles parsing and rendering automatically. +`` parses and renders Markdown in one component. ::warning{to="#markdowndocument"} `` is an **async** component. You can also use the `` component to handle parsing yourself. @@ -64,7 +64,7 @@ export default function App() { ### Usage -Pass markdown content via `children` or the `value` prop. `value` accepts a markdown **string** or a pre-parsed [`MarkdownDocument`](/getting-started/document-model): +Pass Markdown content via `children` or the `value` prop. `value` accepts a Markdown **string** or a pre-parsed [`MarkdownDocument`](/getting-started/document-model): ::code-group @@ -94,19 +94,19 @@ Passing a document to `` skips parsing at runtime, but the **parser is | Prop | Type | Default | Description | |------|------|---------|-------------| -| `children` | `React.ReactNode` | - | Markdown content to parse and render | +| `children` | `React.ReactNode` | `-` | Markdown content to parse and render | | `value` | `string \| MarkdownDocument` | `''` | Markdown string or pre-parsed document (alternative to children) | -| [`options`](#options) | `ParserOptions` | `{}` | Parser options (autoUnwrap, autoClose, etc.) | +| [`options`](#options) | `ParserOptions` | `{}` | Parser options (`autoUnwrap`, `autoClose`, and others) | | [`plugins`](#plugins) | `ComarkPlugin[]` | `[]` | Array of plugins | -| `unwrap` | `boolean \| string \| string[]` | `false` | Strip wrapper tags (MDC `unwrap`) — `true` unwraps `

`; a comma/space-separated string or array peels tags sequentially, for example `"ul li"` | +| `unwrap` | `boolean \| string \| string[]` | `false` | Strip wrapper tags (MDC `unwrap`). `true` unwraps `

`; a comma- or space-separated string or array peels tags sequentially, for example `"ul li"` | | [`components`](#components) | `Record` | `{}` | Custom React component mappings | | [`componentsManifest`](#componentsmanifest) | `(name: string) => Promise` | `undefined` | Dynamic component resolver | | [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode | | [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append caret to last text node | -| [`data`](#data) | `Record` | `undefined` | Runtime values referenced from markdown via `:prop="data.path"` | +| [`data`](#data) | `Record` | `undefined` | Runtime values referenced from Markdown via `:prop="data.path"` | | [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render | | `className` | `string` | `undefined` | CSS class for wrapper element | -| `...attributes` | `HTMLAttributes` | — | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `

` | +| `...attributes` | `HTMLAttributes` | `-` | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `
` | #### `options` @@ -139,7 +139,7 @@ export default function App() { } ``` -For math and mermaid plugins, also pass the companion components: +For the `math` and `mermaid` plugins, also pass the companion components: ```tsx [App.tsx] import { Markdown } from '@comark/react' @@ -160,7 +160,7 @@ export default function App() { #### `components` -Use this prop to map custom React components to Comark elements and use them in your markdown. +Map custom React components to Comark elements in your Markdown. ::steps{level="4"} @@ -206,12 +206,12 @@ This is a warning message! :: ::tip -See [Component Bindings](#component-bindings) for how props and slots map to your React component, or [Component Syntax](/syntax/components) for the full Comark syntax API: nested components, inline syntax, and more. +See [Component bindings](#component-bindings) for how props and slots map to your React component, or [Component syntax](/syntax/components) for nested components, inline syntax, and attributes. :: #### `componentsManifest` -For lazy-loading components on demand. Components are resolved via `React.lazy()` and wrapped in `` automatically. Works with both `` and ``: +Pass a function to load components on demand. Comark resolves each component with `React.lazy()` and wraps it in ``, in both `` and ``: ```tsx [App.tsx] import { Markdown } from '@comark/react' @@ -227,7 +227,7 @@ export default function App() { #### `data` -Expose runtime values to markdown authors. Any prop written with a `:` prefix is resolved against the render context `{ frontmatter, meta, data, props }` when its value isn't valid JSON. See [Data Binding](/syntax/components#data-binding) for the full scope. +Expose runtime values to Markdown authors. Any prop written with a `:` prefix resolves against the render context `{ frontmatter, meta, data, props }` when its value isn't valid JSON. See [Data binding](/syntax/components#data-binding) for details. ```tsx [App.tsx] import { Markdown } from '@comark/react' @@ -251,7 +251,6 @@ import type { NodeTransform } from '@comark/react' const user = { id: 42 } const content = `::cta\nOpen your dashboard\n::` -// Render every `::cta` as a link to the user's dashboard const transformNode: NodeTransform = ({ tag, props }) => { if (tag !== 'cta') return return { tag: 'a', props: { ...props, href: `/users/${user.id}/dashboard` } } @@ -268,7 +267,7 @@ Define the function outside the component, or memoize it. A new array on every r ### `defineMarkdownComponent` -Creates a pre-configured `` component with default options, plugins, and components baked in. +Creates a pre-configured `` component with default options, plugins, and components. #### Usage @@ -315,10 +314,8 @@ import { AppMarkdown } from './markdown' export default function App() { return ( <> - {/* All configuration is already included */} {content} - {/* Can still override per-instance */} {content} @@ -335,8 +332,8 @@ export default function App() { |--------|------|---------|-------------| | [`extends`](#extends) | `ReturnType` | `undefined` | Inherit plugins and components from another component | | `name` | `string` | `undefined` | Component name for debugging | -| `autoUnwrap` | `boolean` | `true` | Automatically unwrap single block elements | -| `autoClose` | `boolean` | `true` | Auto-close incomplete markdown syntax | +| `autoUnwrap` | `boolean` | `true` | Unwrap single paragraph elements inside components | +| `autoClose` | `boolean` | `true` | Auto-close incomplete Markdown syntax | | `linkify` | `boolean` | `true` | **Deprecated.** Use `registerDefaultPlugins: false` and register [`linkify()`](/plugins/defaults/linkify) instead | | `registerDefaultPlugins` | `boolean` | `true` | Register default plugins (`linkify`, `frontmatter`, `html`, `alert`, `task-list`, `components`, `attributes`) | | [`plugins`](#plugins) | `ComarkPlugin[]` | `[]` | Array of plugins | @@ -357,14 +354,12 @@ import toc from '@comark/react/plugins/toc' import math, { Math } from '@comark/react/plugins/math' import CodeBlock from './components/CodeBlock' -// Base: highlight + shared prose overrides, used everywhere const BaseMarkdown = defineMarkdownComponent({ name: 'BaseMarkdown', plugins: [shiki({ themes: { light: githubLight, dark: githubDark } })], components: { pre: CodeBlock }, }) -// Article: extends Base, adds TOC and math export const ArticleMarkdown = defineMarkdownComponent({ name: 'ArticleMarkdown', extends: BaseMarkdown, @@ -372,7 +367,6 @@ export const ArticleMarkdown = defineMarkdownComponent({ components: { Math }, }) -// Comment: extends Base only, no TOC, no math export const CommentMarkdown = defineMarkdownComponent({ name: 'CommentMarkdown', extends: BaseMarkdown, @@ -417,7 +411,7 @@ Renders a pre-parsed `MarkdownDocument` without any parsing. Use it when you par ### Parsing -Parse your markdown content and pass the document directly in a React Server Component: +Parse your Markdown content and pass the document directly in a React Server Component: ```tsx [app/docs/[slug]/page.tsx] import { createMarkdownParser } from 'comark' @@ -440,19 +434,19 @@ export default async function DocsPage({ params }: { params: { slug: string } }) | Prop | Type | Default | Description | |------|------|---------|-------------| -| `value` | `MarkdownDocument` | — | **Required.** The parsed document returned by `parseMarkdown()` | +| `value` | `MarkdownDocument` | `-` | **Required.** The parsed document returned by `parseMarkdown()` | | [`components`](#components) | `Record` | `{}` | Custom React component mappings | | [`componentsManifest`](#componentsmanifest) | `ComponentManifest` | `undefined` | Dynamic component resolver for lazy-loaded components | | [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode | | [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append a blinking caret to the last text node | -| [`data`](#data) | `Record` | `undefined` | Runtime values referenced from markdown via `:prop="data.path"` | +| [`data`](#data) | `Record` | `undefined` | Runtime values referenced from Markdown via `:prop="data.path"` | | [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render | | `className` | `string` | `undefined` | CSS class for the wrapper `
` | -| `...attributes` | `HTMLAttributes` | — | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `
` | +| `...attributes` | `HTMLAttributes` | `-` | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `
` | ### `defineMarkdownDocumentComponent` -Creates a pre-configured `` with baked-in component mappings. +Creates a pre-configured `` component with default component mappings. #### Setup @@ -533,7 +527,7 @@ export const CommentMarkdownDocument = defineMarkdownDocumentComponent({ ## Live documents -`MarkdownLive` is a client wrapper around `MarkdownDocument` that subscribes to an ambient **context** so external sources can drive a mounted renderer: an HMR signal, a collaboration socket, an agent editing the document while you chat with it, or devtools. It accepts the same props as `MarkdownDocument` plus a `documentKey`. The listen key is the document's own `meta.key` (set by a plugin) or the `documentKey` prop; if `globalThis.comarkContext` exists the renderer listens for updates on that key and re-renders, cleaning up on unmount. `MarkdownDocument` itself stays free of client-only hooks so it can render in a React Server Component. With no context, the key is ignored at zero cost. +`MarkdownLive` is a client wrapper around `MarkdownDocument` that subscribes to an ambient **context** so external sources can update a mounted renderer, such as HMR, a collaboration socket, an agent, or devtools. It accepts the same props as `MarkdownDocument` plus `documentKey`. The listen key comes from `meta.key` (set by a plugin) or the `documentKey` prop. When `globalThis.comarkContext` exists, the renderer listens for updates on that key, re-renders on change, and unsubscribes on unmount. `MarkdownDocument` stays free of client-only hooks so it can render in a React Server Component. Without a context, the key is ignored. ```tsx import { MarkdownLive } from '@comark/react' @@ -541,7 +535,7 @@ import { MarkdownLive } from '@comark/react' ``` -A **driver** installs the context once and pushes updates by key with `set()` (replace the whole document) or `patch()` (surgical node edits, with structural sharing so only the changed branch re-renders): +A **driver** installs the context once and pushes updates by key with `set()` to replace the whole document, or `patch()` to edit individual nodes with structural sharing so only the changed branch re-renders: ```ts import { createComarkContext, parseMarkdown } from 'comark' @@ -553,17 +547,17 @@ doc.set(await parseMarkdown('# Replaced')) doc.patch({ op: 'insert', path: [1], node: ['p', {}, 'inserted'] }) ``` -A `path` is a node-index path into `document.nodes`: the first segment indexes the top-level nodes, each later segment indexes into that element's children. Patch operations are `replace`, `insert`, `remove` (each takes a `path`), plus `meta`, `frontmatter`, and `data` merges. The same context API powers `@comark/vue`, `@comark/svelte`, and `@comark/angular`: websocket handlers, agents, devtools, and HMR all drive it the same way. +A `path` indexes into `document.nodes`, where the first segment selects a top-level node and each later segment selects a child of that element. Patch operations include `replace`, `insert`, and `remove` (each taking a `path`), along with `meta`, `frontmatter`, and `data` merges. `@comark/vue`, `@comark/svelte`, and `@comark/angular` share the same context API. --- ## Component bindings -Comark automatically bridges the gap between Comark syntax and your component's interface. +Comark maps component attributes and slots in Markdown to React props. ### Prop binding -Attributes in Comark syntax are passed as props to your component. Use the `:` prefix to pass typed values. HTML attribute names are automatically converted to their React equivalents: +Attributes in Comark syntax pass as props to your component. Use the `:` prefix to pass typed values. Comark converts HTML attribute names to their React equivalents: | Markdown | React prop | |----------|------------| @@ -663,7 +657,7 @@ If no custom component matches, the tag renders as a native HTML element. ## Streaming -Enable real-time rendering as content arrives, ideal for AI chat interfaces and live previews. +Render Markdown incrementally as chunks arrive from an AI stream or live preview. ### Setup @@ -711,7 +705,7 @@ export default function AiChat() { ``` ::callout{icon="i-lucide-info" color="info"} -`autoClose` is enabled by default: incomplete syntax like `**bold text` is automatically closed on every parse. Disable with `options={{ autoClose: false }}`. +`autoClose` is enabled by default and closes incomplete syntax such as `**bold text` on every parse. Disable it with `options={{ autoClose: false }}`. :: ### Caret diff --git a/docs/content/3.rendering/6.svelte.md b/docs/content/3.rendering/6.svelte.md index c94de8eba..3a813e5e0 100644 --- a/docs/content/3.rendering/6.svelte.md +++ b/docs/content/3.rendering/6.svelte.md @@ -17,7 +17,7 @@ links: variant: soft --- -The `@comark/svelte` package provides Svelte 5 components for rendering Comark content with full support for custom components, plugins, and streaming. +`@comark/svelte` renders Markdown and Comark components in Svelte 5 and SvelteKit, with plugin support and streaming. ## Installation @@ -44,7 +44,7 @@ bun add @comark/svelte ## `` -The `` component is the quickest way to render markdown in Svelte 5. It handles parsing and rendering automatically using `$state` and `$effect`. +`` parses and renders Markdown in Svelte 5 using `$state` and `$effect`. ::warning `` uses `$effect` internally and **will not render during SSR**. For SvelteKit, parse in your `load()` function and use [``](#markdowndocument) instead. @@ -52,7 +52,7 @@ The `` component is the quickest way to render markdown in Svelte 5. I ### Usage -Pass markdown content via the `value` prop. `value` accepts a markdown **string** or a pre-parsed [`MarkdownDocument`](/getting-started/document-model): +Pass Markdown content via the `value` prop. `value` accepts a Markdown **string** or a pre-parsed [`MarkdownDocument`](/getting-started/document-model): ::code-group @@ -88,17 +88,17 @@ Passing a document to `` skips parsing at runtime, but the **parser is | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `string \| MarkdownDocument` | `''` | Markdown string or pre-parsed document | -| [`options`](#options) | `ParserOptions` | `{}` | Parser options (autoUnwrap, autoClose, etc.) | +| [`options`](#options) | `ParserOptions` | `{}` | Parser options (`autoUnwrap`, `autoClose`, and others) | | [`plugins`](#plugins) | `ComarkPlugin[]` | `[]` | Array of plugins | -| `unwrap` | `boolean \| string \| string[]` | `false` | Strip wrapper tags (MDC `unwrap`) — `true` unwraps `

`; a comma/space-separated string or array peels tags sequentially, for example `"ul li"` | +| `unwrap` | `boolean \| string \| string[]` | `false` | Strip wrapper tags (MDC `unwrap`). `true` unwraps `

`; a comma- or space-separated string or array peels tags sequentially, for example `"ul li"` | | [`components`](#components) | `Record` | `{}` | Custom Svelte component mappings | | [`componentsManifest`](#componentsmanifest) | `ComponentManifest` | `undefined` | Dynamic component resolver | | [`streaming`](#streaming) | `boolean` | `false` | Enable streaming mode | | [`caret`](#caret) | `boolean \| { class: string }` | `false` | Append caret to last text node | -| [`data`](#data) | `Record` | `undefined` | Runtime values referenced from markdown via `:prop="data.path"` | +| [`data`](#data) | `Record` | `undefined` | Runtime values referenced from Markdown via `:prop="data.path"` | | [`transformNode`](#transformnode) | `NodeTransform \| NodeTransform[]` | `undefined` | Change the tag or props of element nodes right before they render | | `class` | `string` | `''` | CSS class for wrapper element | -| `...attributes` | `HTMLAttributes` | — | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `

` | +| `...attributes` | `HTMLAttributes` | `-` | Any other HTML attribute (`id`, `style`, `role`, `data-*`, `aria-*`, ...) is set on the wrapper `
` | #### `options` @@ -124,7 +124,7 @@ See [ComarkPlugin](/plugins) for available plugins. ``` -For math and mermaid plugins, also pass the companion components: +For the `math` and `mermaid` plugins, also pass the companion components: ```svelte [App.svelte] ``` @@ -536,11 +529,11 @@ MDC's `` and the older `` attribute bot ``` :: -The `unwrap` attribute strips the specified wrapper tag(s) from the rendered children. Useful when you want to remove the auto-inserted `

` from single-paragraph slot content. +The `unwrap` attribute strips the given wrapper tags from slot children, such as the `

` around single-paragraph slot content. #### Named slots -Named slots work the same as in MDC: use `#slotName` in the markdown and `` in the component: +Named slots work the same way as in MDC. Write `#header` in Markdown and `` in the Vue component: ```vue @@ -559,7 +552,7 @@ Named slots work the same as in MDC: use `#slotName` in the markdown and `` | `ProsePre` | `ProsePre` | | `` | `ProseCode` | `ProseCode` | -The names are the same. The internal resolution mechanism changed: MDC resolved `prose-p` (kebab-case) in the renderer, then looked up the registered `ProseP` component. Comark resolves directly by `ProseP` (PascalCase). Components that follow the `Prose*.vue` naming convention work without changes once they are registered. +Internally, MDC converted tags to kebab-case (`prose-p`) before looking up `ProseP`. Comark looks up `ProseP` in PascalCase directly. Existing `Prose*.vue` components work unchanged once you register them. ::note -Custom `ProsePre` components that relied on a `code` prop (or `meta.lines`) for copy buttons or collapse thresholds need a small update: after highlighting, Comark does not expose the raw source as a prop. Declare `__node` and reconstruct the text with `textContent()` from `comark/utils`. See [Custom Pre](/kb/custom-code-block). +Comark does not pass a `code` prop (or `meta.lines`) to `ProsePre`. Declare `__node` on your component and call `textContent()` from `comark/utils` to read the raw code for copy buttons or collapse thresholds. See [Custom code block](/kb/custom-code-block). :: ### Nuxt UI If your project uses [Nuxt UI](https://ui.nuxt.com), the `@comark/vue` Nuxt module registers [Nuxt UI prose components](https://ui.nuxt.com/docs/typography) automatically. -[Nuxt UI](https://ui.nuxt.com) also exposes convenience shorthand components for common callout patterns. Instead of `::callout{icon="..." color="..."}`, you can use: +[Nuxt UI](https://ui.nuxt.com) also provides callout shorthands for `::callout{icon="..." color="..."}`: ```mdc ::note @@ -629,11 +622,11 @@ A critical warning. :: ``` -These are equivalent to `::callout` with the matching `color` and default icon. They are **only available with [Nuxt UI](https://ui.nuxt.com)**. Without it, continue using `::callout{...}` directly. +Each shorthand renders `::callout` with its matching `color` and icon. Without [Nuxt UI](https://ui.nuxt.com), use `::callout{...}` or register your own callout components. ## Component syntax -The MDC block and inline component syntax is identical. No changes needed in your markdown files. +Block and inline component syntax is unchanged from MDC: ```mdc ::alert{type="info"} @@ -651,16 +644,16 @@ Body content. ``` ::tip{to="/syntax/components"} -See the Component Syntax reference for blocks, inline elements, props, slots, and nesting. +See Component syntax for blocks, inline components, props, slots, and nesting. :: ## Binding and data passing -MDC's `{{ }}` interpolation and runtime data are supported in Comark via the [binding plugin](/plugins/built-in/binding) and the shared [data-binding](/syntax/components#data-binding) layer. The API differs in three important ways: +Comark supports `{{ }}` text interpolation and runtime data through the [binding plugin](/plugins/built-in/binding) and [data binding](/syntax/components#data-binding). Three parts work differently from MDC: -1. **Opt-in parser + renderer handler** — register `binding()` and the framework `Binding` component (not enabled by default). -2. **Namespaced paths** — use `frontmatter.`, `data.`, `meta.`, or `props.` instead of bare names from a flat parse-time bag. -3. **Data at render time** — pass runtime values with the renderer's `data` prop. Do **not** pass `{ data }` into `parseMarkdown`. +1. **Opt-in plugin and component.** Register the `binding()` parser plugin and pass the `Binding` component to your renderer. +2. **Namespaced paths.** Prefix paths with `frontmatter.`, `data.`, `meta.`, or `props.` instead of reading bare names from a flat object. +3. **Render-time data.** Pass runtime values to the renderer's `data` prop, not to `parseMarkdown()`. ### Inline `{{ }}` interpolation @@ -678,7 +671,7 @@ Welcome, {{ frontmatter.user.name || guest }}. ``` :: -Wire the plugin once (Nuxt example): +Register the plugin and component when rendering (Nuxt example): ```vue ``` @@ -215,17 +207,17 @@ const markdown = ` Welcome! :: -‎::chart{:data="metrics"} +::chart{:data="data.metrics"} :: ` export default function Page() { - return {markdown} + return {markdown} } ``` :: -For shared defaults, use `defineMarkdownComponent` to avoid passing components everywhere: +To share defaults across pages, create a configured component with `defineMarkdownComponent`: ```typescript import { defineMarkdownComponent } from '@comark/vue' // or '@comark/react' @@ -238,9 +230,7 @@ export const DocsMarkdown = defineMarkdownComponent({ }) ``` ---- - -## Exports & state +## Exports and state MDX uses `export` statements to define page-level variables: @@ -250,7 +240,7 @@ export const year = 2023 # Report for {year} ``` -Comark doesn't support inline JavaScript expressions. Instead, use frontmatter for static metadata and application state for dynamic values: +Comark doesn't run JavaScript inside Markdown. Use frontmatter (with the [binding plugin](/plugins/built-in/binding)) for static metadata and application state for dynamic values: ::code-group ```mdc [Frontmatter] @@ -258,10 +248,10 @@ Comark doesn't support inline JavaScript expressions. Instead, use frontmatter f year: 2023 --- -# Report for {{ year }} +# Report for {{ frontmatter.year }} ``` -```vue [Application State (Vue)] +```vue [Application state (Vue)] ``` -### React Rendering +### React rendering ```tsx import { Markdown } from '@comark/react' @@ -85,7 +82,7 @@ export default function App() { } ``` -### Svelte Rendering +### Svelte rendering ```svelte ``` -## API Reference Summary +## API reference summary -### Core Functions (`comark`) +### Core functions (`comark`) ```typescript -// Asynchronous parsing +// Parse Markdown to a MarkdownDocument parseMarkdown(source: string, options?: ParserOptions): Promise -// Auto-close unclosed syntax -autoCloseMarkdown(source: string): string +// Create a reusable parser instance +createMarkdownParser(options?: ParserOptions): (source: string) => Promise + +// Auto-close unfinished syntax +autoCloseMarkdown(source: string, options?: AutoCloseOptions): string ``` -### HTML Rendering Functions (`@comark/html`) +### HTML rendering functions (`@comark/html`) ```typescript -// Render markdown to HTML string (parse + render in one step) +// Parse and render Markdown to an HTML string renderHtml(markdown: string, options?: ParserOptions & RendererOptions): Promise // Render a pre-parsed document to HTML renderHtmlFromDocument(document: MarkdownDocument, options?: RendererOptions): Promise -// Create a reusable render function with shared parser instance +// Create a reusable render function with a shared parser instance createHtmlRenderer(options?: ParserOptions & RendererOptions): (markdown: string) => Promise ``` -### Vue Components (`@comark/vue`) +### Vue components (`@comark/vue`) ```vue ``` -### React Components (`@comark/react`) +### React components (`@comark/react`) ```tsx ``` -### Svelte Components (`@comark/svelte`) +### Svelte components (`@comark/svelte`) ```svelte ``` -### Angular Components (`@comark/angular`) +### Angular components (`@comark/angular`) ```html ``` -## Performance Characteristics +## Performance notes -- **Serializable document model** - compact array-based nodes -- **Lazy component loading** - only load what's needed -- **Shiki highlighter caching** - avoid re-initialization -- **Parallel processing** - batch parse multiple files efficiently +- **Serializable document model:** compact tuple-based nodes (`['tag', attrs, ...children]`) +- **Reusable parser instances:** `createMarkdownParser()` initializes plugins once across calls +- **Lazy component loading:** `componentsManifest` loads custom components on demand +- **Incremental streaming:** completed top-level blocks are reused while streaming -## TypeScript Support +## TypeScript support -Full TypeScript definitions included: +TypeScript definitions ship with `comark` and every renderer package: ```typescript import type { MarkdownDocument, Node, + ElementNode, ParserOptions, } from 'comark' ``` -## Architecture Overview - -``` -┌─────────────────────────────────────────┐ -│ Markdown Input (String) │ -└────────────────┬────────────────────────┘ - │ - ┌────────▼────────┐ - │ Auto-close │ (Optional) - │ Unclosed │ - │ Syntax │ - └────────┬────────┘ - │ - ┌────────▼────────┐ - │ Parse │ - │ Frontmatter │ (YAML) - └────────┬────────┘ - │ - ┌────────▼────────┐ - │ MarkdownIt │ - │ + Plugins │ (Comark, Tasks) - └────────┬────────┘ - │ - ┌────────▼────────┐ - │ Token │ - │ Processing │ - └────────┬────────┘ - │ - ┌────────▼────────┐ - │ Comark │ - │ AST │ - └────────┬────────┘ - │ - ┌────────▼────────┐ - │ Auto-unwrap │ (Optional) - └────────┬────────┘ - │ - ┌────────▼────────┐ - │ Generate TOC │ - └────────┬────────┘ - │ - ┌────────▼────────┐ - │ MarkdownDocument │ - │ (nodes + data │ - │ + meta) │ - └────────┬────────┘ - │ - ┌───────────┬──────┴──────┬───────────┐ - ▼ ▼ ▼ ▼ -┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ -│ Vue │ │ React │ │ Svelte │ │ Angular │ -│ Renderer│ │ Renderer│ │ Renderer│ │ Renderer│ -└─────────┘ └─────────┘ └─────────┘ └─────────┘ -``` - -## Contributing & Testing - -See the [test specifications](../../packages/comark/SPEC/) for examples of all supported syntax features. +## Architecture overview -Run tests: -```bash -pnpm test ``` - -Run specific test: -```bash -pnpm test -- tests/parse.test.ts +Markdown input (string) + -> autoCloseMarkdown (default: on) + -> frontmatter extraction (YAML -> document.frontmatter) + -> markdown-exit tokenization + plugins (components, attributes, task-list, alert, ...) + -> token processor -> compact node tuples + -> autoUnwrap + post plugins (for example shiki, toc, summary, security) + -> MarkdownDocument { nodes, frontmatter, meta } + -> renderer (@comark/vue, @comark/react, @comark/svelte, @comark/angular, @comark/html, @comark/ansi, comark/render) ``` ## Resources -- **README:** [README.md](../../README.md) - Installation and quick start -- **Specifications:** [SPEC/](../../packages/comark/SPEC/) - Complete syntax test cases - ---- - -## Summary +- **Documentation:** [comark.dev](https://comark.dev) +- **Repository:** [github.com/comarkdown/comark](https://github.com/comarkdown/comark) +- **Syntax specifications:** [`packages/comark/SPEC/`](https://github.com/comarkdown/comark/tree/main/packages/comark/SPEC) -**Comark** is a comprehensive solution for parsing and rendering markdown with component support. It excels at: - -1. **Extending Markdown** - Component syntax without breaking compatibility -2. **Streaming Support** - Real-time rendering with auto-close -3. **Serializable Documents** - Efficient `MarkdownDocument` model with compact nodes -4. **Framework Support** - First-class Vue, React, Svelte, and Angular integration -5. **Developer Experience** - Full TypeScript support and comprehensive documentation - -**Choose Comark when you need:** -- Markdown with custom components -- Streaming/incremental parsing -- Real-time markdown editors -- AI-generated content rendering -- Documentation platforms -- Static site generation with custom components - ---- +## Reference guides -**Next Steps:** -- 📝 [Learn Markdown Syntax](./references/markdown-syntax.md) -- 🔧 [Master Parsing & AST](./references/parsing-ast.md) -- ⚛️ [Explore Vue Rendering](./references/rendering-vue.md) -- ⚛️ [Explore React Rendering](./references/rendering-react.md) -- 🎡 [Explore Svelte Rendering](./references/rendering-svelte.md) -- 🅰️ [Explore Angular Rendering](./references/rendering-angular.md) -- 🤖 [Use with AI Agents](./AGENTS.md) +- [Markdown syntax](./references/markdown-syntax.md) +- [Parsing and document model](./references/parsing-ast.md) +- [Vue rendering](./references/rendering-vue.md) +- [React rendering](./references/rendering-react.md) +- [Svelte rendering](./references/rendering-svelte.md) +- [Angular rendering](./references/rendering-angular.md) +- [AI agents and LLM streaming](./AGENTS.md) diff --git a/docs/skills/comark/references/markdown-syntax.md b/docs/skills/comark/references/markdown-syntax.md index 0351df0ae..1070ee31d 100644 --- a/docs/skills/comark/references/markdown-syntax.md +++ b/docs/skills/comark/references/markdown-syntax.md @@ -1,25 +1,11 @@ -# Markdown Syntax Guide +# Markdown syntax guide -Complete guide for writing Comark (Components in Markdown) documents. - -## Table of Contents - -- [Standard Markdown](#standard-markdown) -- [Frontmatter](#frontmatter) -- [Comark Components](#comark-components) -- [Attributes](#attributes) -- [Code Blocks](#code-blocks) -- [Task Lists](#task-lists) -- [Tables](#tables) - ---- +Syntax reference for authoring Comark (Components in Markdown) documents. ## Standard Markdown Comark parses CommonMark and GitHub Flavored Markdown (GFM). A few constructs differ, for example `[text]` without a link destination is a span, not a shortcut reference link. See https://comark.dev/syntax/markdown#differences-from-commonmark-and-gfm. -The standard features: - ### Headings ```markdown @@ -31,10 +17,9 @@ The standard features: ###### Heading 6 ``` +**Note:** All headings automatically get an `id` from their visible text (for example, `# Hello World` becomes `

`). Unicode letters, marks, and numbers are kept (`## Café` -> `café`); punctuation and symbols are stripped, and a heading that slugifies to nothing gets no ID. A leading digit is prefixed with `_` (`## 1. Introduction` -> `_1-introduction`), and a duplicate anywhere in the document gets a numeric suffix (`options`, `options-1`, `options-2`). IDs are flat by default (`## Setup` / `### Install` -> `setup`, `install`); set `headingIds: 'nested'` in parse options to prefix each ID from `h3` down with the nearest `h2`+ ancestor (`setup-install`). Inline marks and link labels contribute their text; an inline component name is omitted (`:icon-star` does not appear in the slug). An explicit `{id="..."}` replaces the generated ID. Set `headingIds: false` to disable generation; a user-supplied `id` is still kept. -**Note:** All headings automatically get an `id` from their visible text (e.g., `# Hello World` becomes `

`). Unicode letters, marks, and numbers are kept (`## Café` → `café`); punctuation and symbols are stripped, and a heading that slugifies to nothing gets no id. A leading digit is prefixed with `_` (`## 1. Introduction` → `_1-introduction`), and a duplicate anywhere in the document gets a numeric suffix (`options`, `options-1`, `options-2`). Ids are flat by default (`## Setup` / `### Install` → `setup`, `install`); set `headingIds: 'nested'` in parse options to prefix each id from `h3` down with the nearest `h2`+ ancestor (`setup-install`). Inline marks and link labels contribute their text; an inline component name is omitted (`:icon-star` does not appear in the slug). An explicit `{id="..."}` replaces the generated id. Set `headingIds: false` to disable generation; a user-supplied `id` is still kept. - -### Text Formatting +### Text formatting ```markdown **Bold text** @@ -60,7 +45,7 @@ The standard features: 2. Another nested item ``` -### Links and Images +### Links and images ```markdown [Link text](https://example.com) @@ -74,10 +59,10 @@ The standard features: > This is a blockquote > It can span multiple lines > -> And contain other markdown elements +> And contain other Markdown elements ``` -### Horizontal Rules +### Horizontal rules ```markdown --- @@ -85,7 +70,7 @@ The standard features: ___ ``` -### Line Breaks +### Line breaks ```markdown Line with two trailing spaces @@ -119,13 +104,13 @@ Your markdown content here... - Must be at the very beginning of the document - Enclosed by `---` delimiters - Parsed as YAML -- Available in the `frontmatter` property of MarkdownDocument +- Stored in `document.frontmatter` on `MarkdownDocument` -### Common Fields +### Common fields -- **title**: Often used for page titles or TOC labels +- **title**: often used for page titles or TOC labels -Note: `depth` and `searchDepth` are not automatically processed from frontmatter. They must be explicitly passed to the `toc` plugin options. +Note: `depth` and `searchDepth` are not automatically read from frontmatter. Pass them explicitly to the `toc` plugin options. ### Example @@ -148,11 +133,11 @@ console.log(result.frontmatter) --- -## Comark Components +## Comark components -Comark (Components in Markdown) extends standard markdown with custom component syntax. +Comark (Components in Markdown) extends standard Markdown with custom component syntax. -### Block Components +### Block components Block components use the `::component-name` syntax: @@ -160,7 +145,7 @@ Block components use the `::component-name` syntax: ::component-name{prop1="value1" prop2="value2"} Content inside the component -Can have **markdown** and other elements +Can have **Markdown** and other elements :: ``` @@ -174,7 +159,7 @@ This is an important message! ::card{title="My Card"} -Card content with **markdown** support +Card content with **Markdown** support :: @@ -182,7 +167,7 @@ Card content with **markdown** support :: ``` -### Inline Components +### Inline components Inline components use the `:component-name` syntax: @@ -207,9 +192,9 @@ Click the :button[Submit]{type="primary"} to continue. The status is :badge[Active]{color="green"} right now. ``` -### Component Properties +### Component properties -Components support various property syntaxes: +Components support the following property syntaxes: ```markdown ::component{prop="value"} @@ -228,11 +213,11 @@ Components support various property syntaxes: :: -::component{obj='{"key": "value"}'} +::component{:obj='{"key": "value"}'} :: -::component{arr='["item1", "item2"]'} +::component{:arr='["item1", "item2"]'} :: @@ -241,7 +226,7 @@ Components support various property syntaxes: :: ``` -### Component Slots +### Component slots Block components support named slots using the `#slot-name` syntax: @@ -261,7 +246,7 @@ Default slot :: ``` -#### AST Output +#### AST output ```json { @@ -296,9 +281,9 @@ Default slot } ``` -### Default Slot +### Default slot -Content inside a component without a slot marker is the **default slot**. These two forms are equivalent in rendering but produce different ASTs: +Content inside a component without a slot marker goes to the **default slot**. These two forms render the same way: ```markdown ::component @@ -313,19 +298,19 @@ hello :: ``` -**Without `#default`**: content becomes direct children (auto-unwrapped): +**Without `#default`**, content becomes direct children (auto-unwrapped): ```json ["component", {}, "hello"] ``` -**With `#default`**: content is wrapped in an explicit template node: +**With `#default`**, content is wrapped in an explicit template node: ```json ["component", {}, ["template", { "name": "default" }, "hello"]] ``` Both serialize back to the same Markdown (without `#default`). The Vue, React, Svelte, and Angular renderers treat both forms identically: direct children and `template[name="default"]` children both become the default slot. Use `#default` explicitly when mixing named and default slots in the same component. -### Nested Components +### Nested components Components can be nested within each other: @@ -345,9 +330,9 @@ More content in outer ## Attributes -Comark allows adding custom attributes to native markdown elements using `{...}` syntax after the element. +Add custom attributes to native Markdown elements by placing `{...}` right after the element. -### Strong/Bold Attributes +### Strong/bold attributes ```markdown **bold text**{.highlight #important} @@ -355,14 +340,14 @@ Comark allows adding custom attributes to native markdown elements using `{...}` **bold text**{bool} ``` -### Italic/Emphasis Attributes +### Italic/emphasis attributes ```markdown *italic text*{.emphasized} _italic text_{#custom-id} ``` -### Link Attributes +### Link attributes ```markdown [Link text](url){target="_blank" rel="noopener"} @@ -370,41 +355,41 @@ _italic text_{#custom-id} [External](https://example.com){target="_blank" .external-link} ``` -### Image Attributes +### Image attributes ```markdown ![Alt text](image.png){.responsive width="800" height="600"} ![Logo](logo.svg){.logo #site-logo} ``` -### Inline Code Attributes +### Inline code attributes ```markdown `code snippet`{.language-js} `variable`{data-type="string"} ``` -### Span Attributes +### Span attributes ```markdown This is [highlighted text]{.highlight .yellow} in a paragraph. ``` -### Attribute Types +### Attribute types -- **Boolean:** `{bool}` → `:bool="true"` -- **ID:** `{#my-id}` → `id="my-id"` -- **Class:** `{.my-class}` → `class="my-class"` -- **Key-Value:** `{key="value"}` → `key="value"` -- **JSON Objects:** `{data='{"key": "val"}'}` → `data={"key": "val"}` +- **Boolean:** `{bool}` -> `:bool="true"` +- **ID:** `{#my-id}` -> `id="my-id"` +- **Class:** `{.my-class}` -> `class="my-class"` +- **Key-value:** `{key="value"}` -> `key="value"` +- **JSON objects:** `{:data='{"key": "val"}'}` -> `data={"key": "val"}` --- -## Code Blocks +## Code blocks -Comark provides advanced code block features with metadata support. +Fenced code blocks support a language identifier, filename, line highlights, and custom metadata. -### Basic Code Block +### Basic code block ````markdown ```javascript @@ -414,7 +399,7 @@ function hello() { ``` ```` -### Language with Syntax Highlighting +### Language with syntax highlighting ````markdown ```typescript @@ -425,7 +410,7 @@ interface User { ``` ```` -### Filename Metadata +### Filename metadata ````markdown ```javascript [server.js] @@ -434,9 +419,9 @@ const app = express() ``` ```` -**Note:** Filename is enclosed in `[...]` brackets. +Enclose the filename in `[...]` brackets. -### Line Highlighting +### Line highlighting ````markdown ```javascript {1-3,5} @@ -449,14 +434,14 @@ function example() { ``` ```` -#### Highlighting Syntax +#### Highlighting syntax - Single line: `{3}` - Range: `{1-5}` - Multiple: `{1,3,5}` - Combined: `{1-3,7,10-12}` -### Combined Metadata +### Combined metadata ````markdown ```javascript {1-3} [utils.ts] meta=value @@ -466,12 +451,11 @@ function hello() { ``` ```` -**Metadata Order:** Any order is supported: +Metadata tokens after the language can appear in any order: - `language {highlights} [filename] meta` - `language [filename] {highlights} meta` -- etc. -### Special Characters in Filename +### Special characters in filename ````markdown ```typescript [@[...slug\].ts] @@ -480,7 +464,7 @@ function hello() { ``` ```` -### No Language Specified +### No language specified ````markdown ``` @@ -489,7 +473,7 @@ No syntax highlighting ``` ```` -### AST Structure +### AST structure ```json { @@ -516,7 +500,7 @@ No syntax highlighting --- -## Task Lists +## Task lists Comark supports GitHub Flavored Markdown task lists: @@ -535,7 +519,7 @@ Comark supports GitHub Flavored Markdown task lists: - Works in both ordered and unordered lists - Supports nesting -### HTML Output +### HTML output ```html
    @@ -563,7 +547,7 @@ Comark supports GitHub Flavored Markdown tables: | Cell 4 | Cell 5 | Cell 6 | ``` -### Aligned Tables +### Aligned tables ```markdown | Left Aligned | Center Aligned | Right Aligned | @@ -572,13 +556,13 @@ Comark supports GitHub Flavored Markdown tables: | Text | Text | Text | ``` -#### Alignment Syntax +#### Alignment syntax - Left: `:---` - Center: `:---:` - Right: `---:` -### Inline Markdown in Tables +### Inline Markdown in tables ```markdown | Feature | Status | Link | @@ -587,7 +571,7 @@ Comark supports GitHub Flavored Markdown tables: | `Code` | ~~Strike~~ | ![Image](img.png) | ``` -### Varying Column Widths +### Varying column widths ```markdown | Short | Medium Column | Very Long Column Name Here | @@ -595,8 +579,6 @@ Comark supports GitHub Flavored Markdown tables: | A | B | C | ``` -**Note:** Column width is determined by the longest content in each column. - --- -[← Back to Main Skills Guide](../../SKILLS.md) +[Back to skill guide](../SKILL.md) diff --git a/docs/skills/comark/references/parsing-ast.md b/docs/skills/comark/references/parsing-ast.md index fa14e6816..560e3b8b8 100644 --- a/docs/skills/comark/references/parsing-ast.md +++ b/docs/skills/comark/references/parsing-ast.md @@ -1,19 +1,10 @@ -# Parsing & Document Model +# Parsing and document model -Complete guide for parsing Comark content and working with the serializable `MarkdownDocument` model. +Guide to parsing Comark content and working with the serializable `MarkdownDocument` model. -## Table of Contents +## String parsing -- [String Parsing](#string-parsing) -- [Async Parsing with Syntax Highlighting](#async-parsing-with-syntax-highlighting) -- [Document Structure](#document-structure) -- [Rendering Documents](#rendering-documents) - ---- - -## String Parsing - -The primary way to parse Comark content is using the `parseMarkdown()` function: +Parse Markdown strings with `parseMarkdown()`: ```typescript import { parseMarkdown } from 'comark' @@ -24,7 +15,7 @@ title: My Document # Hello World -This is **markdown** with :icon-star component. +This is **Markdown** with :icon-star component. ::alert{type="info"} Important message here @@ -34,7 +25,7 @@ Important message here const result = await parseMarkdown(content) ``` -### Result Structure +### Result structure ```typescript interface MarkdownDocument { @@ -48,13 +39,13 @@ interface MarkdownDocument { } ``` -### Parse Options +### Parse options ```typescript interface ParserOptions { - autoUnwrap?: boolean // Remove unnecessary

    wrappers (default: true) - autoClose?: boolean // Auto-close unclosed syntax (default: true) - plugins?: ComarkPlugin[] // Enable plugins (e.g., highlight, emoji, toc) + autoUnwrap?: boolean // Remove single-paragraph

    wrappers (default: true) + autoClose?: boolean // Auto-close unfinished syntax (default: true) + plugins?: ComarkPlugin[] // Enable plugins (for example, shiki, emoji, toc) } ``` @@ -77,9 +68,9 @@ const result = await parseMarkdown(content, { }) ``` -### Auto-Unwrap Feature +### Auto-unwrap feature -Auto-unwrap removes unnecessary paragraph wrappers from container components: +Auto-unwrap removes single-paragraph `

    ` wrappers from container components: **Without auto-unwrap:** ```json @@ -91,11 +82,11 @@ Auto-unwrap removes unnecessary paragraph wrappers from container components: ["alert", {}, "Text"] ``` -Auto-unwrap applies to any component whose only child is a single paragraph. +Auto-unwrap applies to any container whose only child is a single paragraph. -### Auto-Close Feature +### Auto-close feature -Auto-close automatically closes unclosed markdown syntax, essential for streaming: +Auto-close completes unfinished Markdown syntax so partial input renders cleanly during streaming: ```typescript import { autoCloseMarkdown } from 'comark' @@ -124,9 +115,9 @@ const closedProps = autoCloseMarkdown(props) --- -## Async Parsing with Syntax Highlighting +## Async parsing with syntax highlighting -For syntax highlighting support, use the `highlight` plugin: +For syntax highlighting, pass the `shiki` plugin: ```typescript import { parseMarkdown } from 'comark' @@ -161,7 +152,7 @@ const result = await parseMarkdown(content, { }) ``` -### Highlight Plugin Options +### Shiki plugin options ```typescript // Standard entry: comark/plugins/shiki @@ -177,7 +168,7 @@ interface ShikiOptions { preStyles?: boolean } -// Core entry: comark/plugins/shiki/core — no defaults / no registerDefault* +// Core entry: comark/plugins/shiki/core (no defaults, no registerDefault* options) interface ShikiCoreOptions { themes: { // required light?: ThemeRegistration @@ -189,7 +180,7 @@ interface ShikiCoreOptions { } ``` -### Dual Theme Support +### Dual theme support ```typescript import shiki from 'comark/plugins/shiki' @@ -208,11 +199,11 @@ const result = await parseMarkdown(content, { --- -## Document Structure +## Document structure -Comark returns a serializable `MarkdownDocument` with compact array-based nodes. +Comark returns a serializable `MarkdownDocument` with compact tuple-based nodes. -### MarkdownDocument Format +### MarkdownDocument format ```typescript interface MarkdownDocument { @@ -228,16 +219,17 @@ interface MarkdownDocument { type Node = | string // Text nodes | [tag: string, props?: Record, ...children: Node[]] + | [null, Record, string] // Comment nodes ``` -### Node Structure +### Node structure -**Text Node:** +**Text node:** ```json "plain text content" ``` -**Element Node:** +**Element node:** ```json ["tag", { "prop": "value" }, ...children] ``` @@ -246,7 +238,7 @@ type Node = ```json // Paragraph with text -["p", {}, "Simple paragraph"] +["p", {}, "First paragraph"] // Paragraph with bold text ["p", {}, "Text with ", ["strong", {}, "bold"], " word"] @@ -257,15 +249,15 @@ type Node = // Link with attributes ["a", { "href": "https://example.com", "target": "_blank" }, "Link"] -// Comark Component -["alert", { "type": "info" }, ["p", {}, "Message"]] +// Comark component +["alert", { "type": "info" }, "Message"] // Component with slots [ "card", {}, - ["template", { "name": "header" }, ["h2", {}, "Title"]], - ["template", { "name": "content" }, ["p", {}, "Content"]] + ["template", { "name": "header" }, ["h2", { "id": "title" }, "Title"]], + ["template", { "name": "content" }, "Content"] ] // Default slot: content without #slot-name becomes direct children @@ -275,7 +267,7 @@ type Node = ["component", {}, ["template", { "name": "default" }, "hello"]] ``` -### Complete Document Example +### Complete document example **Input:** ```markdown @@ -323,17 +315,17 @@ Warning message } ``` -### Property Conventions +### Property conventions - **Boolean props:** `:bool="true"` (props starting with `:`) - **Standard props:** `key="value"` - **ID:** `id="value"` (from `{#value}`) - **Class:** `class="value"` (from `{.value}`) -- **Custom data:** Any attribute name and value +- **Custom data:** any attribute name and value --- -## Rendering Documents +## Rendering documents ### Render to HTML @@ -341,7 +333,7 @@ Warning message import { parseMarkdown } from 'comark' import { renderHtmlFromDocument } from '@comark/html' -const content = '# Hello World\n\nThis is **markdown**.' +const content = '# Hello World\n\nThis is **Markdown**.' const doc = await parseMarkdown(content) const html = await renderHtmlFromDocument(doc) @@ -351,12 +343,12 @@ console.log(html) **Output:** ```html

    Hello World

    -

    This is markdown.

    +

    This is Markdown.

    ``` ### Render to Markdown -Convert AST back to Comark markdown: +Convert a document back to Comark Markdown: ```typescript import { parseMarkdown } from 'comark' @@ -378,13 +370,13 @@ Message :: ``` -### Use Cases +### Use cases -- Round-trip parsing (parse → modify AST → render back) +- Round-trip parsing (parse, modify nodes, render back) - AST transformation - Content normalization -- Markdown generation from programmatic AST +- Markdown generation from programmatic node trees --- -[← Back to Main Skills Guide](../../SKILLS.md) +[Back to skill guide](../SKILL.md) diff --git a/docs/skills/comark/references/rendering-angular.md b/docs/skills/comark/references/rendering-angular.md index 9a4f7c44f..3fa55117f 100644 --- a/docs/skills/comark/references/rendering-angular.md +++ b/docs/skills/comark/references/rendering-angular.md @@ -1,24 +1,10 @@ -# Angular Rendering Guide +# Angular rendering guide -Complete guide for rendering Markdown documents in Angular 21+ applications. +Guide to rendering Markdown documents in Angular 21+ applications. -## Table of Contents +## Basic usage -- [Basic Usage](#basic-usage) -- [Custom Components](#custom-components) -- [Dynamic Component Resolution](#dynamic-component-resolution) -- [Content Projection (Slots)](#content-projection-slots) -- [Streaming Mode](#streaming-mode) -- [Prose Components](#prose-components) -- [Props & Inputs](#props--inputs) -- [Data Binding](#data-binding) -- [Pre-configured Components](#pre-configured-components) - ---- - -## Basic Usage - -Use the `Markdown` standalone component to render markdown: +Use the `Markdown` standalone component to render Markdown: ```typescript // app.component.ts @@ -46,7 +32,7 @@ Important message } ``` -### With a Pre-parsed Document +### With a pre-parsed document Use `MarkdownDocument` when you already have a parsed document: @@ -77,7 +63,7 @@ export class AppComponent { --- -## Custom Components +## Custom components Map custom Angular components to Comark element tags: @@ -105,14 +91,14 @@ export class AppComponent { } ``` -### Component Resolution Order +### Component resolution order Components are resolved by checking these keys in order: -1. `Prose{PascalTag}`, e.g., `ProseH1` for `

    ` tags -2. `PascalTag`, e.g., `Alert` for `::alert` components -3. `tag`, e.g., `alert` for `::alert` components +1. `Prose{PascalTag}`, for example `ProseH1` for `

    ` tags +2. `PascalTag`, for example `Alert` for `::alert` components +3. `tag`, for example `alert` for `::alert` components -### Custom Component Example +### Custom component example Custom components receive Comark element attributes as `@Input()` properties. Children are projected via ``: @@ -148,7 +134,7 @@ export class CustomAlertComponent { } ``` -### Custom Heading Example +### Custom heading example ```typescript // custom-heading.component.ts @@ -179,11 +165,11 @@ export class CustomHeadingComponent { --- -## Dynamic Component Resolution +## Dynamic component resolution Components are resolved at runtime. The `components` input is a plain `Record>` mapping tag names to Angular component classes. -The renderer uses Angular's `createComponent` API to dynamically instantiate components, and `reflectComponentType` to discover which `@Input()` properties the component accepts. Only matching inputs are set. +The renderer uses Angular's `createComponent` API to instantiate components dynamically, and `reflectComponentType` to inspect which `@Input()` properties the component accepts. Only matching inputs are set. ```typescript import { Component, Type } from '@angular/core' @@ -216,11 +202,11 @@ export class DocsComponent { --- -## Content Projection (Slots) +## Content projection (slots) -Comark named slots map to Angular's content projection. The renderer handles slot extraction automatically. +Comark named slots map to Angular's content projection. -### Markdown with Slots +### Markdown with slots ```markdown ::card @@ -228,14 +214,14 @@ Comark named slots map to Angular's content projection. The renderer handles slo ## Card Title #content -Main content here with **markdown** support +Main content here with **Markdown** support #footer Footer text :: ``` -### Custom Component with Slots +### Custom component with slots Named slots are rendered into `
    ` elements and appended to the component's host element. Use CSS attribute selectors or `@ContentChildren` to target them: @@ -282,7 +268,7 @@ import { Component, ChangeDetectionStrategy } from '@angular/core' export class CardComponent {} ``` -### Nested Slots +### Nested slots ```markdown ::tabs @@ -298,9 +284,9 @@ Content for tab 2 --- -## Streaming Mode +## Streaming mode -Enable streaming mode for real-time rendering of content (e.g., AI-generated output): +Enable streaming mode for incremental rendering of live content (for example, AI-generated output): ```typescript import { Component } from '@angular/core' @@ -338,7 +324,7 @@ export class StreamingComponent { } ``` -### Caret Configuration +### Caret configuration The `caret` input controls the streaming cursor indicator: @@ -350,9 +336,9 @@ The `caret` input controls the streaming cursor indicator: ``` -The caret is a `` with a pulsing CSS animation, automatically appended to the last text node in the AST during streaming. +The caret is a `` with a pulsing CSS animation, appended to the last text node in the AST during streaming. -### Summary Mode +### Summary mode Render only content before ``: @@ -362,9 +348,9 @@ Render only content before ``: --- -## Prose Components +## Prose components -The `MarkdownDocument` renders standard HTML elements natively. Override them with custom components using the `Prose` prefix: +`MarkdownDocument` renders standard HTML elements natively. Override them with custom components using the `Prose` prefix: ```typescript import { Component, Type } from '@angular/core' @@ -392,9 +378,9 @@ export class DocsComponent { --- -## Props & Inputs +## Props & inputs -Custom components receive Comark element attributes as `@Input()` properties. The renderer uses `reflectComponentType` to discover accepted inputs and only sets matching ones. +Custom components receive Comark element attributes as `@Input()` properties. The renderer uses `reflectComponentType` to inspect accepted inputs and sets only matching ones. ```typescript // data-table.component.ts @@ -436,13 +422,13 @@ Table content here :: ``` -### Property Parsing Rules +### Property parsing rules -- Props starting with `:` are parsed as booleans/JSON -- Standard HTML attributes work normally -- `__node` provides access to the raw AST node (set automatically if the component declares it as an `@Input()`) +- Props starting with `:` are parsed as booleans or JSON +- Standard HTML attributes pass through as strings +- `__node` gives access to the raw AST node (set automatically if the component declares it as an `@Input()`) -### Accessing Node Structure +### Accessing node structure ```typescript @Input() __node?: any @@ -455,9 +441,9 @@ get nodeChildren() { return this.__node?.slice(2) || [] } --- -## Data Binding +## Data binding -The `data` input allows passing ambient data for `:binding` resolution in markdown: +The `data` input passes runtime values for `:prop` and `{{ }}` resolution in Markdown: ```typescript import { Component } from '@angular/core' @@ -478,7 +464,7 @@ import { binding, Binding } from '@comark/angular/plugins/binding' `, }) export class AppComponent { - content = 'Hello {{ user.name }}, you have {{ count }} messages.' + content = 'Hello {{ data.user.name }}, you have {{ data.count }} messages.' plugins = [binding()] components = { Binding } @@ -491,7 +477,7 @@ export class AppComponent { --- -## Pre-configured Components +## Pre-configured components Use `defineMarkdownComponent` or `defineMarkdownDocumentComponent` to create pre-configured components with default plugins and component mappings: @@ -592,14 +578,14 @@ export class AppComponent { } ``` -The Mermaid component includes automatic dark mode support: it watches the `` element for `.dark` class changes and re-renders diagrams accordingly. +The Mermaid component watches the `` element for `.dark` class changes and re-renders diagrams automatically. ### Binding ```typescript import { binding, Binding } from '@comark/angular/plugins/binding' -// See the "Data Binding" section above for full usage. +// See the "Data binding" section above for usage. ``` --- @@ -608,11 +594,11 @@ import { binding, Binding } from '@comark/angular/plugins/binding' All `@comark/angular` components use: -- **Standalone Components**: no `NgModule` required +- **Standalone components**: no `NgModule` required - **`ChangeDetectionStrategy.OnPush`**: minimal change detection overhead -- **Dynamic component creation** via `createComponent`: efficient runtime instantiation -- **`reflectComponentType`**: only set inputs the component actually declares +- **Dynamic component creation** via `createComponent`: runtime instantiation without wrapper modules +- **`reflectComponentType`**: sets only inputs that the component declares --- -[← Back to Main Skills Guide](../SKILL.md) +[Back to skill guide](../SKILL.md) diff --git a/docs/skills/comark/references/rendering-react.md b/docs/skills/comark/references/rendering-react.md index 32c7ace6f..bc53417e7 100644 --- a/docs/skills/comark/references/rendering-react.md +++ b/docs/skills/comark/references/rendering-react.md @@ -1,23 +1,10 @@ -# React Rendering Guide +# React rendering guide -Complete guide for rendering Markdown documents in React applications. +Guide to rendering Markdown documents in React applications. -## Table of Contents +## Basic usage -- [Basic Usage](#basic-usage) -- [Custom Components](#custom-components) -- [Dynamic Component Resolution](#dynamic-component-resolution) -- [Props Conversion](#props-conversion) -- [Streaming Mode](#streaming-mode) -- [Prose Components](#prose-components) -- [Custom Props Handling](#custom-props-handling) -- [CSS Class Name](#css-class-name) - ---- - -## Basic Usage - -Use the `Markdown` component to render markdown: +Use the `Markdown` component to render Markdown: ```tsx import { Markdown } from '@comark/react' @@ -39,7 +26,7 @@ export default function App() { --- -## Custom Components +## Custom components Map custom React components to Comark elements: @@ -65,7 +52,7 @@ export default function App({ content }) { } ``` -### Custom Component Example +### Custom component example ```tsx // CustomHeading.tsx @@ -78,7 +65,7 @@ interface Props { } export default function CustomHeading({ __node, id, children }: Props) { - const tag = __node[0] // h1, h2, etc. + const tag = __node[0] // h1 through h6 const Component = tag as keyof JSX.IntrinsicElements return ( @@ -89,7 +76,7 @@ export default function CustomHeading({ __node, id, children }: Props) { } ``` -**Styled Component:** +**Styled component:** ```tsx import styled from 'styled-components' @@ -104,7 +91,7 @@ const StyledHeading = styled.h1<{ level: number }>` export default function CustomHeading({ __node, children }: Props) { const tag = __node[0] - const level = parseInt(tag[1]) // Extract level from 'h1', 'h2', etc. + const level = parseInt(tag[1]) // Extract level from 'h1' through 'h6' return ( @@ -114,7 +101,7 @@ export default function CustomHeading({ __node, children }: Props) { } ``` -### Alert Component Example +### Alert component example ```tsx // CustomAlert.tsx @@ -127,16 +114,16 @@ interface AlertProps { } export default function CustomAlert({ type = 'info', children }: AlertProps) { - const icons = { - info: 'ℹ️', - warning: '⚠️', - error: '❌', - success: '✅', + const labels = { + info: 'Info', + warning: 'Warning', + error: 'Error', + success: 'Success', } return (
    -
    {icons[type]}
    +
    {labels[type]}
    {children}
    ) @@ -145,7 +132,7 @@ export default function CustomAlert({ type = 'info', children }: AlertProps) { --- -## Dynamic Component Resolution +## Dynamic component resolution Load components dynamically using `componentsManifest`: @@ -176,23 +163,23 @@ export default function App({ content }) { --- -## Props Conversion +## Props conversion -React renderer handles HTML attribute conversion automatically: +The React renderer converts HTML attributes to React props automatically: -### Attribute Mapping +### Attribute mapping ```tsx -// Markdown attribute → React prop -{class="foo"} → className="foo" -{tabindex="0"} → tabIndex={0} -{style="..."} → style={{...}} (converted to object) -{:bool="true"} → bool={true} (parsed from string) -{:count="5"} → count={5} (parsed as number) -{:data='{"key":"val"}'} → data={{key:"val"}} (parsed as object) +// Markdown attribute -> React prop +{class="foo"} -> className="foo" +{tabindex="0"} -> tabIndex={0} +{style="..."} -> style={{...}} (converted to object) +{:bool="true"} -> bool={true} (parsed from string) +{:count="5"} -> count={5} (parsed as number) +{:data='{"key":"val"}'} -> data={{key:"val"}} (parsed as object) ``` -### Style Conversion +### Style conversion ```tsx // Input: style="color: red; font-size: 16px" @@ -203,7 +190,7 @@ React renderer handles HTML attribute conversion automatically: // Output: style={{ '--custom-color': 'blue' }} ``` -### Boolean Props +### Boolean props ```tsx // Markdown: **text**{:disabled} @@ -213,7 +200,7 @@ React renderer handles HTML attribute conversion automatically: // React prop: external={true} ``` -### Number Props +### Number props ```tsx // Markdown: ::component{:count="5"} @@ -223,7 +210,7 @@ React renderer handles HTML attribute conversion automatically: // React prop: max={100} ``` -### Object/Array Props +### Object/array props ```tsx // Markdown: ::component{:config='{"theme":"dark"}'} @@ -235,9 +222,9 @@ React renderer handles HTML attribute conversion automatically: --- -## Streaming Mode +## Streaming mode -Use the `Markdown` component with reactive state for streaming content: +Use `Markdown` with reactive state for streaming content: ```tsx import { useState, useEffect } from 'react' @@ -276,9 +263,9 @@ export default function StreamingContent() { --- -## Prose Components +## Prose components -The `Markdown` component uses built-in prose styling automatically. You can override with custom components: +`Markdown` renders standard HTML elements by default. Override them or add custom elements through `components`: ```tsx import { Markdown } from '@comark/react' @@ -293,7 +280,7 @@ export default function App({ content }) { } ``` -### Tailwind CSS Prose +### Tailwind CSS prose ```tsx import { Markdown } from '@comark/react' @@ -309,7 +296,7 @@ export default function App({ content }) { --- -## Custom Props Handling +## Custom props handling Access props in custom components: @@ -317,7 +304,7 @@ Access props in custom components: // CustomAlert.tsx interface AlertProps { type?: string // From {type="info"} - bool?: boolean // From {bool} → :bool="true" + bool?: boolean // From {bool} -> :bool="true" count?: number // From {:count="5"} data?: object // From {:data='{"key":"val"}'} __node?: any // Original Comark node @@ -346,14 +333,14 @@ export default function CustomAlert({ } ``` -### Property Types +### Property types -- `:bool="true"` → `bool={true}` (boolean) -- `:count="5"` → `count={5}` (number) -- `:obj='{"key":"val"}'` → `obj={{key:"val"}}` (object) -- `attr="value"` → `attr="value"` (string) +- `:bool="true"` -> `bool={true}` (boolean) +- `:count="5"` -> `count={5}` (number) +- `:obj='{"key":"val"}'` -> `obj={{key:"val"}}` (object) +- `attr="value"` -> `attr="value"` (string) -### Accessing Node Structure +### Accessing node structure ```tsx interface Props { @@ -375,7 +362,7 @@ export default function Component({ __node, children }: Props) { } ``` -### Working with Complex Props +### Working with complex props ```tsx // DataTable.tsx @@ -400,7 +387,7 @@ export default function DataTable({ {columns.map((col, i) => ( {col} - {sortable && } + {sortable && } ))} @@ -422,9 +409,9 @@ Table content here --- -## CSS Class Name +## CSS class name -Add custom wrapper class: +Add a custom wrapper class: ```tsx @@ -41,7 +26,7 @@ Important message --- -## Custom Components +## Custom components Map custom Svelte components to Comark elements: @@ -63,14 +48,14 @@ Map custom Svelte components to Comark elements: ``` -### Component Resolution Order +### Component resolution order Components are resolved by checking these keys in order: -1. `Prose{PascalTag}`, e.g., `ProseH1` for `

    ` tags -2. `PascalTag`, e.g., `Alert` for `::alert` components -3. `tag`, e.g., `alert` for `::alert` components +1. `Prose{PascalTag}`, for example `ProseH1` for `

    ` tags +2. `PascalTag`, for example `Alert` for `::alert` components +3. `tag`, for example `alert` for `::alert` components -### Custom Component Example +### Custom component example Custom components receive AST node attributes as props and children as a Svelte `children` snippet: @@ -87,7 +72,7 @@ Custom components receive AST node attributes as props and children as a Svelte

    ``` -### Alert Component Example +### Alert component example ```svelte @@ -102,23 +87,23 @@ Custom components receive AST node attributes as props and children as a Svelte children?: Snippet } = $props() - const icons = { - info: '\u2139\uFE0F', - warning: '\u26A0\uFE0F', - error: '\u274C', - success: '\u2705', + const labels = { + info: 'Info', + warning: 'Warning', + error: 'Error', + success: 'Success', } ``` --- -## Dynamic Component Resolution +## Dynamic component resolution Load components dynamically using `componentsManifest`: @@ -144,9 +129,9 @@ Load components dynamically using `componentsManifest`: ``` -In SvelteKit projects, keep components rendered from Markdown in a dedicated folder such as `$lib/components/comark/`. This keeps Comark-rendered components separate from normal app UI components and makes `componentsManifest` globs easier to audit. +In SvelteKit projects, keep components rendered from Markdown in a dedicated folder such as `$lib/components/comark/`. This separates Comark-rendered components from normal app UI components and keeps `componentsManifest` globs auditable. -For SvelteKit SSR with non-eager lazy components, use `MarkdownAsync` and a manifest that returns dynamic imports. An explicit map is the easiest option to audit: +For SvelteKit SSR with non-eager lazy components, use `MarkdownAsync` and a manifest that returns dynamic imports. An explicit map keeps the allowed components clear: ```svelte
    - {@render children?.()} + {#if header} +
    {@render header()}
    + {/if} +
    {@render children?.()}
    + {#if footer} + + {/if}
    ``` -Note: Named slots from Comark (`#header`, `#content`, `#footer`) are rendered as `template` elements in the AST. The Svelte renderer passes all children (including named slot templates) as a single `children` snippet. To handle named slots individually, access the `__node` prop and filter children by template name. - --- -## Props Mapping +## Props mapping The Svelte renderer maps AST attributes to component props: -### Attribute Mapping +### Attribute mapping ``` -// Markdown attribute → Svelte prop -{class="foo"} → class="foo" (pass-through) -{className="foo"} → class="foo" (mapped) -{style="color: red"} → style="color: red" (pass-through as string) -{tabindex="0"} → tabindex="0" (pass-through) -{:bool="true"} → bool={true} (parsed from string) -{:count="5"} → count={5} (parsed as number) -{:data='{"key":"val"}'} → data={{key:"val"}} (parsed as object) +// Markdown attribute -> Svelte prop +{class="foo"} -> class="foo" (pass-through) +{className="foo"} -> class="foo" (mapped) +{style="color: red"} -> style="color: red" (pass-through as string) +{tabindex="0"} -> tabindex="0" (pass-through) +{:bool="true"} -> bool={true} (parsed from string) +{:count="5"} -> count={5} (parsed as number) +{:data='{"key":"val"}'} -> data={{key:"val"}} (parsed as object) ``` -Svelte is closer to HTML than React, so most attributes pass through unchanged. The only mapping is `className` → `class`. Colon-prefixed attributes (`:prop="value"`) are parsed as typed values (boolean, number, JSON). +Svelte is closer to HTML than React, so most attributes pass through unchanged. The only mapping is `className` to `class`. Colon-prefixed attributes (`:prop="value"`) are parsed as typed values (boolean, number, JSON). -### Boolean Props +### Boolean props ``` // Markdown: ::component{:disabled="true"} @@ -272,7 +265,7 @@ Svelte is closer to HTML than React, so most attributes pass through unchanged. // Svelte prop: visible={false} ``` -### Number Props +### Number props ``` // Markdown: ::component{:count="5"} @@ -282,7 +275,7 @@ Svelte is closer to HTML than React, so most attributes pass through unchanged. // Svelte prop: max={100} ``` -### Object/Array Props +### Object/array props ``` // Markdown: ::component{:config='{"theme":"dark"}'} @@ -294,9 +287,9 @@ Svelte is closer to HTML than React, so most attributes pass through unchanged. --- -## Streaming Mode +## Streaming mode -Use the `Markdown` component with `$state` for streaming content: +Use `Markdown` with `$state` for streaming content: ```svelte ``` -### Custom Component Example +### Custom component example ```vue @@ -95,7 +82,7 @@ const id = computed(() => props.__node[1]?.id) ``` -### Alert Component Example +### Alert component example ```vue @@ -151,7 +138,7 @@ const iconName = computed(() => { --- -## Dynamic Component Resolution +## Dynamic component resolution Load components dynamically using `componentsManifest`: @@ -182,11 +169,11 @@ async function loadComponent(name: string) { --- -## Slots Support +## Slots support -Comark components with slots work seamlessly in Vue: +Comark named slots map directly to Vue slots: -### Markdown with Slots +### Markdown with slots ```markdown ::card @@ -194,14 +181,14 @@ Comark components with slots work seamlessly in Vue: ## Card Title #content -Main content here with **markdown** support +Main content here with **Markdown** support #footer Footer text :: ``` -### Custom Component with Slots +### Custom component with slots ```vue @@ -246,7 +233,7 @@ Footer text ``` -### Nested Slots +### Nested slots ```markdown ::tabs @@ -289,9 +276,9 @@ const activeTab = ref('tab1') --- -## Streaming Mode +## Streaming mode -The `Markdown` component can be used with reactive content for streaming scenarios: +Use `Markdown` with reactive content for streaming responses: ```vue