Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,9 @@ Svelte 5 renderer (`Markdown`, `MarkdownDocument`, `MarkdownNode`) plus experime

### `@comark/angular` (`packages/comark-angular/`)

Angular 21+ renderer (peer range `>=21 <23`) with standalone components (`Markdown` selector `comark-markdown`, `MarkdownDocument`, `defineMarkdownComponent`, `defineMarkdownDocumentComponent`).
Angular 21+ renderer (peer range `>=21 <23`) with standalone components (`Markdown` selector `comark-markdown`, `MarkdownDocument`, `defineMarkdownComponent`, `defineMarkdownDocumentComponent`, `provideMarkdown`, `provideMarkdownDocument`).

- `provideMarkdown` / `provideMarkdownDocument` return config `Provider` objects for `MARKDOWN_CONFIG` / `MARKDOWN_DOCUMENT_CONFIG` (`src/config.ts`). Register them at bootstrap to configure every instance, or scope them to a route or ancestor injector. The static `Markdown` / `MarkdownDocument` components inject those tokens optionally. Use these in AOT builds: a component class returned by a factory cannot be resolved in `imports` (NG1010 / ngtsc -991010). `defineMarkdownComponent` / `defineMarkdownDocumentComponent` remain as component-class factories for JIT builds.
- Built with `ng-packagr` (`ng build`), then `scripts/strip-sourcemaps.mjs` removes emitted source maps and `scripts/sync-plugins.mjs` writes plain plugin re-exports and `./plugins/*` export map entries into `dist/package.json`.
- Plugin entry points use **named exports** because the Angular Package Format strips `export default` (`import { math, Math } from '@comark/angular/plugins/math'`, `import { security } from '@comark/angular/plugins/security'`).
- Publishes from `dist/` via `publishConfig.directory`; `test/bundle.test.ts` packs from `dist/` too.
Expand Down Expand Up @@ -217,7 +218,7 @@ import { createAnsiRenderer, createAnsiPrinter, printAnsi, renderAnsi, renderAns
import { Markdown, MarkdownDocument, defineMarkdownComponent } from '@comark/vue' // also @comark/react
import { Markdown, MarkdownDocument } from '@comark/svelte'
import { MarkdownAsync } from '@comark/svelte/async'
import { Markdown, MarkdownDocument, defineMarkdownComponent } from '@comark/angular'
import { Markdown, MarkdownDocument, defineMarkdownComponent, provideMarkdown, MARKDOWN_CONFIG } from '@comark/angular'
import math, { Math } from '@comark/vue/plugins/math' // same shape in html, react, svelte (`{ math, Math }` in angular)
import mermaid, { Mermaid } from '@comark/vue/plugins/mermaid'
import binding, { Binding, If } from '@comark/vue/plugins/binding'
Expand Down
72 changes: 70 additions & 2 deletions docs/content/3.rendering/7.angular.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ See [ComarkPlugin](/plugins) for available plugins.
```typescript [app.component.ts]
import { Component } from '@angular/core'
import { Markdown } from '@comark/angular'
import shiki from '@comark/angular/plugins/shiki'
import { shiki } from '@comark/angular/plugins/shiki'
import githubLight from '@shikijs/themes/github-light'
import githubDark from '@shikijs/themes/github-dark'

Expand Down Expand Up @@ -550,7 +550,7 @@ Use `defineMarkdownComponent` and `defineMarkdownDocumentComponent` to create pr

```typescript [components/docs-markdown.ts]
import { defineMarkdownComponent } from '@comark/angular'
import shiki from '@comark/angular/plugins/shiki'
import { shiki } from '@comark/angular/plugins/shiki'
import { math, Math } from '@comark/angular/plugins/math'
import { mermaid, Mermaid } from '@comark/angular/plugins/mermaid'

Expand Down Expand Up @@ -594,4 +594,72 @@ export const DocsMarkdownDocument = defineMarkdownDocumentComponent({
})
```

### `provideMarkdown` and `provideMarkdownDocument` (AOT-safe)

Angular AOT cannot statically resolve a component class returned by a factory in `imports` (NG1010 / ngtsc error -991010). For AOT builds, keep the static components in `imports` and register the config providers once at bootstrap. Every Markdown component in the app then uses that config.

```typescript [main.ts]
import { bootstrapApplication } from '@angular/platform-browser'
import { AppComponent } from './app.component'
import { provideMarkdown, provideMarkdownDocument } from '@comark/angular'
import { shiki } from '@comark/angular/plugins/shiki'
import { math, Math } from '@comark/angular/plugins/math'
import { mermaid, Mermaid } from '@comark/angular/plugins/mermaid'

bootstrapApplication(AppComponent, {
providers: [
provideMarkdown({
plugins: [shiki(), math(), mermaid()],
components: { Math, Mermaid },
class: 'prose dark:prose-invert',
}),
provideMarkdownDocument({
components: { Math },
class: 'prose',
}),
],
})
```

Components only import the static component. No provider or wrapper is needed in each component:

```typescript [page.component.ts]
import { Component } from '@angular/core'
import { Markdown } from '@comark/angular'

@Component({
selector: 'app-page',
standalone: true,
imports: [Markdown],
template: `<comark-markdown [value]="content" />`,
})
export class PageComponent {
content = '# Hello\n\n$E = mc^2$'
}
```

The same applies to `<comark-markdown-document>`: import `MarkdownDocument` and it picks up `provideMarkdownDocument` from the root injector. Use a signal for an asynchronously parsed document so zoneless change detection sees the update:

```typescript [page.component.ts]
import { Component, OnInit, signal } from '@angular/core'
import { parseMarkdown, type MarkdownDocument as MarkdownDocumentType } from 'comark'
import { MarkdownDocument } from '@comark/angular'

@Component({
selector: 'app-page',
standalone: true,
imports: [MarkdownDocument],
template: `@if (document(); as document) { <comark-markdown-document [value]="document" /> }`,
})
export class PageComponent implements OnInit {
readonly document = signal<MarkdownDocumentType | undefined>(undefined)

async ngOnInit(): Promise<void> {
this.document.set(await parseMarkdown('# Hello'))
}
}
```

`provideMarkdown` and `provideMarkdownDocument` return config `Provider` objects for `MARKDOWN_CONFIG` and `MARKDOWN_DOCUMENT_CONFIG`. Both tokens and their config interfaces are exported. Providers can also be scoped to a route or an ancestor component; the closest injector wins. Instance-level `[options]`, `[plugins]`, `[components]`, and `[transformNode]` inputs merge with the global config and win on conflict. Config plugins run before instance plugins; a same-name instance plugin replaces the config plugin. Config `transformNode` runs before the instance's own transform. The `defineMarkdown*` factories above still return component classes for JIT apps that disable AOT and import `@angular/compiler`.

---
2 changes: 2 additions & 0 deletions docs/content/5.reference/3.reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,8 @@ export const AppMarkdown = defineMarkdownComponent({
})
```

> In `@comark/angular`, `provideMarkdown` and `provideMarkdownDocument` are the AOT-safe alternatives. They return config `Provider` objects for `MARKDOWN_CONFIG` / `MARKDOWN_DOCUMENT_CONFIG`: register them once at bootstrap (or in a route or ancestor injector) and every static `Markdown` / `MarkdownDocument` component inherits the config. The `defineMarkdownComponent` / `defineMarkdownDocumentComponent` factories still return component classes for JIT builds. See the [Angular renderer guide](/rendering/angular#pre-configured-components).

## Transforming nodes before render

`transformNode` lets you change the tag or props of an element node right before it renders, based on its props and the render context. Use it when a value is only known at render time, such as runtime `data`, and `components` alone can't express the change.
Expand Down
64 changes: 64 additions & 0 deletions docs/skills/comark/references/rendering-angular.md
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,70 @@ export const DocsMarkdownDocument = defineMarkdownDocumentComponent({
})
```

### provideMarkdown and provideMarkdownDocument (AOT-safe)

Factory-created component classes cannot be resolved in `imports` under AOT (NG1010). For AOT builds, import the static components and register the config providers once at bootstrap. Every Markdown component in the app inherits that config:

```typescript
import { bootstrapApplication } from '@angular/platform-browser'
import { AppComponent } from './app.component'
import { provideMarkdown, provideMarkdownDocument } from '@comark/angular'
import { math, Math } from '@comark/angular/plugins/math'
import { mermaid, Mermaid } from '@comark/angular/plugins/mermaid'

bootstrapApplication(AppComponent, {
providers: [
provideMarkdown({
plugins: [math(), mermaid()],
components: { Math, Mermaid },
class: 'prose dark:prose-invert',
}),
provideMarkdownDocument({ components: { Math } }),
],
})
```

Components only import the static component. No provider or wrapper is needed in each component:

```typescript
import { Component } from '@angular/core'
import { Markdown } from '@comark/angular'

@Component({
selector: 'app-docs',
standalone: true,
imports: [Markdown],
template: `<comark-markdown [value]="content" />`,
})
export class DocsComponent {
content = '# Math: $E = mc^2$'
}
```

The same applies to `<comark-markdown-document>`: import `MarkdownDocument` and it picks up `provideMarkdownDocument` from the root injector. Use a signal for an asynchronously parsed document so zoneless change detection sees the update:

```typescript
import { Component, OnInit, signal } from '@angular/core'
import { parseMarkdown, type MarkdownDocument as MarkdownDocumentType } from 'comark'
import { MarkdownDocument } from '@comark/angular'

@Component({
selector: 'app-docs',
standalone: true,
imports: [MarkdownDocument],
template: `@if (document(); as document) { <comark-markdown-document [value]="document" /> }`,
})
export class DocsComponent implements OnInit {
readonly document = signal<MarkdownDocumentType | undefined>(undefined)

async ngOnInit(): Promise<void> {
this.document.set(await parseMarkdown('# Hello'))
}
}
```

Both helpers return config `Provider` objects for `MARKDOWN_CONFIG` and `MARKDOWN_DOCUMENT_CONFIG`. Providers can also be scoped to a route or an ancestor component; the closest injector wins. Instance-level `options`, `plugins`, `components`, and `transformNode` inputs merge with the global config and win on conflict. Config plugins run first; a same-name instance plugin replaces the config plugin. Config `transformNode` runs before the instance's own transform. The `defineMarkdown*` factories above remain for JIT apps that disable AOT and import `@angular/compiler`.

---

## Plugins
Expand Down
29 changes: 13 additions & 16 deletions examples/2.vite/angular/src/app/pages/syntax.component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Component } from '@angular/core'
import { Markdown } from '@comark/angular'
import { Markdown, provideMarkdown } from '@comark/angular'
import shiki from 'comark/plugins/shiki'
import alert from 'comark/plugins/alert'
import { AlertComponent } from '../components/alert.component'
Expand All @@ -10,23 +10,20 @@ import python from '@shikijs/langs/python'
selector: 'app-syntax',
standalone: true,
imports: [Markdown],
template: `
<comark-markdown
[value]="markdown"
[plugins]="plugins"
[components]="components"
/>
`,
providers: [
provideMarkdown({
plugins: [
shiki({
languages: [python],
}),
alert(),
],
components: { alert: AlertComponent, 'feature-card': FeatureCardComponent },
}),
],
template: `<comark-markdown [value]="markdown" />`,
})
export class SyntaxComponent {
components = { alert: AlertComponent, 'feature-card': FeatureCardComponent }
plugins = [
shiki({
languages: [python],
}),
alert(),
]

markdown = `
# Comark Syntax Showcase

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Type,
computed,
inject,
type OnInit,
type OnDestroy,
input,
} from '@angular/core'
import type { ElementNode, Node, MarkdownDocument as MarkdownDocumentType, NodeRenderData, NodeTransform } from 'comark'
import { mergeNodeTransforms } from 'comark/utils'
import { MARKDOWN_DOCUMENT_CONFIG } from '../config'
import type { MarkdownDocumentConfig } from '../config'
import { MarkdownNode } from './markdown-node.component'
import { findLastTextNodeAndAppendNode, getCaret } from '../utils/caret'

Expand All @@ -31,20 +35,25 @@ const EMPTY_DOCUMENT: MarkdownDocumentType = { nodes: [], frontmatter: {}, meta:
standalone: true,
imports: [MarkdownNode],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'[class]': 'config?.class ?? ""',
},
template: `
<div class="comark-content">
@for (node of renderedNodes; track $index) {
<comark-markdown-node
[node]="node"
[components]="components()"
[components]="mergedComponents()"
[renderData]="renderData"
[transformNode]="transformNode()"
[transformNode]="mergedTransforms()"
/>
}
</div>
`,
})
export class MarkdownDocument implements OnInit, OnDestroy {
protected readonly config: MarkdownDocumentConfig | null = inject(MARKDOWN_DOCUMENT_CONFIG, { optional: true })

/** The parsed Markdown document to render */
readonly value = input<MarkdownDocumentType>()

Expand All @@ -63,6 +72,14 @@ export class MarkdownDocument implements OnInit, OnDestroy {
/** Change the tag or props of element nodes just before they render */
readonly transformNode = input<NodeTransform | readonly NodeTransform[]>()

/** Config-level and instance-level components merged, instance wins. */
protected readonly mergedComponents = computed(() => ({ ...(this.config?.components ?? {}), ...this.components() }))

/** Config-level transforms run before the instance's own transforms. */
protected readonly mergedTransforms = computed(() =>
mergeNodeTransforms(this.config?.transformNode, this.transformNode())
)

/**
* Document key used to subscribe to live updates via `globalThis.comarkContext`.
* Falls back to the document's own `meta.key` when set by a plugin.
Expand Down
35 changes: 27 additions & 8 deletions packages/comark-angular/src/components/markdown.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import {
} from '@angular/core'
import { createSerializedMarkdownParser } from 'comark'
import type { ParserOptions, MarkdownDocument as MarkdownDocumentType, NodeTransform } from 'comark'
import { isMarkdownDocument } from 'comark/utils'
import { isMarkdownDocument, mergeNodeTransforms } from 'comark/utils'
import { MARKDOWN_CONFIG, mergeConfigPlugins } from '../config'
import type { MarkdownConfig } from '../config'
import { MarkdownDocument } from './markdown-document.component'

/**
Expand All @@ -28,20 +30,25 @@ import { MarkdownDocument } from './markdown-document.component'
standalone: true,
imports: [MarkdownDocument],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'[class]': 'config?.class ?? ""',
},
template: `
@if (document) {
<comark-markdown-document
[value]="document"
[components]="components()"
[components]="mergedComponents()"
[streaming]="streaming()"
[caret]="caret()"
[data]="data()"
[transformNode]="transformNode()"
[transformNode]="mergedTransforms()"
/>
}
`,
})
export class Markdown {
protected readonly config: MarkdownConfig | null = inject(MARKDOWN_CONFIG, { optional: true })

/** The markdown content to parse and render, or a pre-parsed MarkdownDocument */
readonly value = input<string | MarkdownDocumentType>()

Expand All @@ -56,7 +63,7 @@ export class Markdown {
* `options.unwrap`. `true` unwraps `<p>`; a space-separated string or array
* unwraps the listed tags.
*/
readonly unwrap = input<boolean | string | string[]>(false)
readonly unwrap = input<boolean | string | string[]>()

/** Custom component mappings for element tags */
readonly components = input<Record<string, Type<any>>>({})
Expand All @@ -76,21 +83,33 @@ export class Markdown {
/** Change the tag or props of element nodes just before they render */
readonly transformNode = input<NodeTransform | readonly NodeTransform[]>()

/** Config-level and instance-level components merged, instance wins. */
protected readonly mergedComponents = computed(() => ({ ...(this.config?.components ?? {}), ...this.components() }))

/** Config-level transforms run before the instance's own transforms. */
protected readonly mergedTransforms = computed(() =>
mergeNodeTransforms(this.config?.transformNode, this.transformNode())
)

document: MarkdownDocumentType | null = null

private cdr = inject(ChangeDetectorRef)

/**
* Compose the parse options consumed by the serialized parser.
*
* Subclasses (e.g. `defineMarkdownComponent`) override this to merge
* config-level defaults without mutating the `options`/`plugins` inputs.
* Config defaults are merged under the instance inputs so instance values
* win without mutating the input signals. Instance plugins replace config
* plugins with the same name. An omitted `unwrap` inherits the config
* default, while an explicit `false` overrides it.
*/
protected getParserOptions(): ParserOptions {
const unwrap = this.unwrap()
return {
...(this.config?.options ?? {}),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
...this.options(),
...(this.unwrap() ? { unwrap: this.unwrap() } : {}),
plugins: this.plugins(),
...(unwrap === undefined ? {} : { unwrap }),
plugins: mergeConfigPlugins(this.config?.plugins, this.plugins()),
}
}

Expand Down
Loading
Loading