diff --git a/AGENTS.md b/AGENTS.md index 4af0f2e9..8cbf1287 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. @@ -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' diff --git a/docs/content/3.rendering/7.angular.md b/docs/content/3.rendering/7.angular.md index 52a88da5..3cddf893 100644 --- a/docs/content/3.rendering/7.angular.md +++ b/docs/content/3.rendering/7.angular.md @@ -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' @@ -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' @@ -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: ``, +}) +export class PageComponent { + content = '# Hello\n\n$E = mc^2$' +} +``` + +The same applies to ``: 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) { }`, +}) +export class PageComponent implements OnInit { + readonly document = signal(undefined) + + async ngOnInit(): Promise { + 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`. + --- diff --git a/docs/content/5.reference/3.reference.md b/docs/content/5.reference/3.reference.md index 0be0e498..8146dbdb 100644 --- a/docs/content/5.reference/3.reference.md +++ b/docs/content/5.reference/3.reference.md @@ -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. diff --git a/docs/skills/comark/references/rendering-angular.md b/docs/skills/comark/references/rendering-angular.md index 3fa55117..c5320294 100644 --- a/docs/skills/comark/references/rendering-angular.md +++ b/docs/skills/comark/references/rendering-angular.md @@ -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: ``, +}) +export class DocsComponent { + content = '# Math: $E = mc^2$' +} +``` + +The same applies to ``: 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) { }`, +}) +export class DocsComponent implements OnInit { + readonly document = signal(undefined) + + async ngOnInit(): Promise { + 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 diff --git a/examples/2.vite/angular/src/app/pages/syntax.component.ts b/examples/2.vite/angular/src/app/pages/syntax.component.ts index f94f93a0..aa6a844a 100644 --- a/examples/2.vite/angular/src/app/pages/syntax.component.ts +++ b/examples/2.vite/angular/src/app/pages/syntax.component.ts @@ -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' @@ -10,23 +10,20 @@ import python from '@shikijs/langs/python' selector: 'app-syntax', standalone: true, imports: [Markdown], - template: ` - - `, + providers: [ + provideMarkdown({ + plugins: [ + shiki({ + languages: [python], + }), + alert(), + ], + components: { alert: AlertComponent, 'feature-card': FeatureCardComponent }, + }), + ], + template: ``, }) export class SyntaxComponent { - components = { alert: AlertComponent, 'feature-card': FeatureCardComponent } - plugins = [ - shiki({ - languages: [python], - }), - alert(), - ] - markdown = ` # Comark Syntax Showcase diff --git a/packages/comark-angular/src/components/markdown-document.component.ts b/packages/comark-angular/src/components/markdown-document.component.ts index 89acb4f5..8ae6566d 100644 --- a/packages/comark-angular/src/components/markdown-document.component.ts +++ b/packages/comark-angular/src/components/markdown-document.component.ts @@ -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' @@ -31,20 +35,25 @@ const EMPTY_DOCUMENT: MarkdownDocumentType = { nodes: [], frontmatter: {}, meta: standalone: true, imports: [MarkdownNode], changeDetection: ChangeDetectionStrategy.OnPush, + host: { + '[class]': 'config?.class ?? ""', + }, template: `
@for (node of renderedNodes; track $index) { }
`, }) 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() @@ -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() + /** 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. diff --git a/packages/comark-angular/src/components/markdown.component.ts b/packages/comark-angular/src/components/markdown.component.ts index 13446531..d55aab98 100644 --- a/packages/comark-angular/src/components/markdown.component.ts +++ b/packages/comark-angular/src/components/markdown.component.ts @@ -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' /** @@ -28,20 +30,25 @@ import { MarkdownDocument } from './markdown-document.component' standalone: true, imports: [MarkdownDocument], changeDetection: ChangeDetectionStrategy.OnPush, + host: { + '[class]': 'config?.class ?? ""', + }, template: ` @if (document) { } `, }) 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() @@ -56,7 +63,7 @@ export class Markdown { * `options.unwrap`. `true` unwraps `

`; a space-separated string or array * unwraps the listed tags. */ - readonly unwrap = input(false) + readonly unwrap = input() /** Custom component mappings for element tags */ readonly components = input>>({}) @@ -76,6 +83,14 @@ export class Markdown { /** Change the tag or props of element nodes just before they render */ readonly transformNode = input() + /** 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) @@ -83,14 +98,18 @@ export class Markdown { /** * 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 ?? {}), ...this.options(), - ...(this.unwrap() ? { unwrap: this.unwrap() } : {}), - plugins: this.plugins(), + ...(unwrap === undefined ? {} : { unwrap }), + plugins: mergeConfigPlugins(this.config?.plugins, this.plugins()), } } diff --git a/packages/comark-angular/src/config.ts b/packages/comark-angular/src/config.ts new file mode 100644 index 00000000..c669e2d3 --- /dev/null +++ b/packages/comark-angular/src/config.ts @@ -0,0 +1,50 @@ +import { InjectionToken } from '@angular/core' +import type { Type } from '@angular/core' +import type { NodeTransform, ParserOptions } from 'comark' + +export interface MarkdownConfig { + /** Parser options, excluding plugins. */ + options?: Omit + /** Parser plugins. */ + plugins?: ParserOptions['plugins'] + /** Pre-configured component mappings. */ + components?: Record> + /** Node transforms that run before the instance's own `transformNode`. */ + transformNode?: NodeTransform | readonly NodeTransform[] + /** Additional CSS class for the wrapper. */ + class?: string +} + +export interface MarkdownDocumentConfig { + /** Pre-configured component mappings. */ + components?: Record> + /** Node transforms that run before the instance's own `transformNode`. */ + transformNode?: NodeTransform | readonly NodeTransform[] + /** Additional CSS class for the wrapper. */ + class?: string +} + +export const MARKDOWN_CONFIG = new InjectionToken('comark.MARKDOWN_CONFIG') +export const MARKDOWN_DOCUMENT_CONFIG = new InjectionToken('comark.MARKDOWN_DOCUMENT_CONFIG') + +type ConfigPlugin = NonNullable[number] + +/** Keep the first plugin per name in each list, then let instance plugins replace config plugins. */ +export function mergeConfigPlugins( + configPlugins: ParserOptions['plugins'], + instancePlugins: ParserOptions['plugins'] +): ConfigPlugin[] { + const plugins = new Map() + + for (const list of [configPlugins, instancePlugins]) { + const seen = new Set() + for (const plugin of list ?? []) { + if (seen.has(plugin.name)) continue + seen.add(plugin.name) + plugins.delete(plugin.name) + plugins.set(plugin.name, plugin) + } + } + + return [...plugins.values()] +} diff --git a/packages/comark-angular/src/define.ts b/packages/comark-angular/src/define.ts index 79a2c18a..ef091f78 100644 --- a/packages/comark-angular/src/define.ts +++ b/packages/comark-angular/src/define.ts @@ -3,6 +3,7 @@ import type { NodeTransform, ParserOptions } from 'comark' import { mergeNodeTransforms } from 'comark/utils' import { Markdown } from './components/markdown.component' import { MarkdownDocument } from './components/markdown-document.component' +import { mergeConfigPlugins } from './config' export interface DefineMarkdownComponentOptions extends ParserOptions { /** Pre-configured component mappings. */ @@ -28,6 +29,10 @@ export interface DefineMarkdownDocumentOptions { * The returned class extends `Markdown` and merges the config-level * defaults with any per-instance `@Input()` values at runtime. * + * Angular AOT cannot statically resolve a component class produced by a factory + * in `imports` (ngtsc error -991010 / NG1010). Prefer `provideMarkdown` + * in AOT builds; this factory remains for JIT applications. + * * @example * ```typescript * import { defineMarkdownComponent } from '@comark/angular' @@ -74,38 +79,28 @@ export function defineMarkdownComponent(config: DefineMarkdownComponentOptions = /** Instance-level components that are merged with config-level components. */ override readonly components = input>>({}) - protected readonly mergedComponents = computed(() => ({ ...configComponents, ...this.components() })) + protected override readonly mergedComponents = computed(() => ({ ...configComponents, ...this.components() })) - protected readonly mergedTransforms = computed(() => mergeNodeTransforms(configTransforms, this.transformNode())) + protected override readonly mergedTransforms = computed(() => + mergeNodeTransforms(configTransforms, this.transformNode()) + ) get hostClass(): string { return configClass || '' } - /** - * Effective plugins: config-level plugins first, then instance plugins, - * deduplicated by plugin name so a plugin supplied by both runs once. - */ - private readonly effectivePlugins = computed(() => { - const names = new Set() - return [...configPlugins, ...(this.plugins() ?? [])].filter((plugin) => { - if (names.has(plugin.name)) return false - names.add(plugin.name) - return true - }) - }) - /** * Merge config-level parse options under the instance `options` input so * instance values override config defaults, without writing back to the * input signal (the parser consumes the derived value instead). */ protected override getParserOptions(): ParserOptions { + const unwrap = this.unwrap() return { ...parseOptions, ...this.options(), - ...(this.unwrap() ? { unwrap: this.unwrap() } : {}), - plugins: this.effectivePlugins(), + ...(unwrap === undefined ? {} : { unwrap }), + plugins: mergeConfigPlugins(configPlugins, this.plugins()), } } } @@ -116,6 +111,10 @@ export function defineMarkdownComponent(config: DefineMarkdownComponentOptions = /** * Create a pre-configured MarkdownDocument component with default component mappings. * + * Angular AOT cannot statically resolve a component class produced by a factory + * in `imports` (ngtsc error -991010 / NG1010). Prefer `provideMarkdownDocument` + * in AOT builds; this factory remains for JIT applications. + * * @example * ```typescript * import { defineMarkdownDocumentComponent } from '@comark/angular' @@ -152,9 +151,9 @@ export function defineMarkdownDocumentComponent(config: DefineMarkdownDocumentOp /** Instance-level components that are merged with config-level components. */ override readonly components = input>>({}) - protected readonly mergedComponents = computed(() => ({ ...configComponents, ...this.components() })) + protected override readonly mergedComponents = computed(() => ({ ...configComponents, ...this.components() })) - protected readonly mergedTransforms = computed(() => + protected override readonly mergedTransforms = computed(() => mergeNodeTransforms(config.transformNode, this.transformNode()) ) diff --git a/packages/comark-angular/src/index.ts b/packages/comark-angular/src/index.ts index 8761a72b..f2523de1 100644 --- a/packages/comark-angular/src/index.ts +++ b/packages/comark-angular/src/index.ts @@ -3,5 +3,9 @@ export { MarkdownDocument } from './components/markdown-document.component' export { MarkdownNode } from './components/markdown-node.component' export { defineMarkdownComponent, defineMarkdownDocumentComponent } from './define' export type { DefineMarkdownComponentOptions, DefineMarkdownDocumentOptions } from './define' +export { provideMarkdown, provideMarkdownDocument } from './provider' +export type { MarkdownProviderOptions, MarkdownDocumentProviderOptions } from './provider' +export { MARKDOWN_CONFIG, MARKDOWN_DOCUMENT_CONFIG } from './config' +export type { MarkdownConfig, MarkdownDocumentConfig } from './config' export type * from 'comark' diff --git a/packages/comark-angular/src/provider.ts b/packages/comark-angular/src/provider.ts new file mode 100644 index 00000000..44af2299 --- /dev/null +++ b/packages/comark-angular/src/provider.ts @@ -0,0 +1,109 @@ +import type { Provider } from '@angular/core' +import { MARKDOWN_CONFIG, MARKDOWN_DOCUMENT_CONFIG } from './config' +import type { MarkdownConfig, MarkdownDocumentConfig } from './config' +import type { DefineMarkdownComponentOptions, DefineMarkdownDocumentOptions } from './define' + +/** Options for {@link provideMarkdown}. */ +export type MarkdownProviderOptions = DefineMarkdownComponentOptions + +/** Options for {@link provideMarkdownDocument}. */ +export type MarkdownDocumentProviderOptions = DefineMarkdownDocumentOptions + +/** + * Configure the static `Markdown` component through Angular DI. + * + * Returns a config Provider for `MARKDOWN_CONFIG`. The `Markdown` component is + * declared statically, so it stays analyzable by the Angular AOT compiler and + * can be used in `imports`. AOT cannot statically resolve a component class + * created by a factory function (ngtsc error -991010 / NG1010). + * + * @example + * ```typescript + * import { Component } from '@angular/core' + * import { Markdown, provideMarkdown } from '@comark/angular' + * import { math, Math } from '@comark/angular/plugins/math' + * + * @Component({ + * selector: 'app-docs', + * standalone: true, + * imports: [Markdown], + * providers: [ + * provideMarkdown({ + * plugins: [math()], + * components: { Math }, + * class: 'prose dark:prose-invert', + * }), + * ], + * template: ``, + * }) + * export class DocsComponent { + * content = '# Hello' + * } + * ``` + */ +export function provideMarkdown(config: MarkdownProviderOptions = {}): Provider { + const { + components: configComponents = {}, + class: configClass, + plugins: configPlugins = [], + transformNode: configTransforms, + ...parseOptions + } = config + + return { + provide: MARKDOWN_CONFIG, + useValue: { + options: parseOptions, + plugins: configPlugins, + components: configComponents, + transformNode: configTransforms, + class: configClass, + } satisfies MarkdownConfig, + } +} + +/** + * Configure the static `MarkdownDocument` component through Angular DI. + * + * Returns a config Provider for `MARKDOWN_DOCUMENT_CONFIG`, which the static + * `MarkdownDocument` component reads to pre-configure components and styling. + * + * @example + * ```typescript + * import { Component, OnInit } from '@angular/core' + * import { parseMarkdown, type MarkdownDocument as MarkdownDocumentType } from 'comark' + * import { MarkdownDocument, provideMarkdownDocument } from '@comark/angular' + * import { Math } from '@comark/angular/plugins/math' + * + * @Component({ + * selector: 'app-docs', + * standalone: true, + * imports: [MarkdownDocument], + * providers: [ + * provideMarkdownDocument({ + * components: { Math }, + * }), + * ], + * template: `@if (document) { }`, + * }) + * export class DocsComponent implements OnInit { + * document?: MarkdownDocumentType + * + * async ngOnInit(): Promise { + * this.document = await parseMarkdown('# Hello') + * } + * } + * ``` + */ +export function provideMarkdownDocument(config: MarkdownDocumentProviderOptions = {}): Provider { + const { components: configComponents = {}, class: configClass, transformNode: configTransforms } = config + + return { + provide: MARKDOWN_DOCUMENT_CONFIG, + useValue: { + components: configComponents, + transformNode: configTransforms, + class: configClass, + } satisfies MarkdownDocumentConfig, + } +} diff --git a/packages/comark-angular/test/aot.test.ts b/packages/comark-angular/test/aot.test.ts new file mode 100644 index 00000000..2b6f278b --- /dev/null +++ b/packages/comark-angular/test/aot.test.ts @@ -0,0 +1,40 @@ +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { dirname, join } from 'node:path' +import { describe, expect, it } from 'vitest' + +const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..') +const ngc = join(packageRoot, 'node_modules', '.bin', 'ngc') + +function compile(project: string): { status: number; output: string } { + try { + const output = execFileSync(ngc, ['-p', join(packageRoot, 'test', 'fixtures', 'aot', project)], { + cwd: packageRoot, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }) + return { status: 0, output } + } catch (error) { + const failure = error as { status?: number; stdout?: string; stderr?: string } + return { + status: failure.status ?? 1, + output: `${failure.stdout ?? ''}${failure.stderr ?? ''}`, + } + } +} + +describe('Angular AOT compilation', () => { + it('compiles a consumer that imports the static components and registers providers', () => { + const { status, output } = compile('tsconfig.json') + + expect(output).toBe('') + expect(status).toBe(0) + }) + + it('rejects a factory-created component class in imports', () => { + const { status, output } = compile('tsconfig.factory.json') + + expect(status).not.toBe(0) + expect(output).toContain('NG1010') + }) +}) diff --git a/packages/comark-angular/test/define-component.test.ts b/packages/comark-angular/test/define-component.test.ts index 8ef18c54..ac676bbd 100644 --- a/packages/comark-angular/test/define-component.test.ts +++ b/packages/comark-angular/test/define-component.test.ts @@ -1,75 +1,112 @@ -import { describe, expect, it } from 'vitest' +import '@angular/compiler' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { TestBed } from '@angular/core/testing' +import type { NodeTransform } from 'comark' +import { parseMarkdown } from 'comark' +import emoji from 'comark/plugins/emoji' import { defineMarkdownComponent, defineMarkdownDocumentComponent } from '../src/define.ts' +import { ConfiguredMarkdown, ConfiguredMarkdownDocument, InstanceAlert } from './fixtures/defined/defined.ts' describe('defineMarkdownComponent', () => { - it('returns a component class', () => { - const Defined = defineMarkdownComponent({}) - expect(Defined).toBeDefined() - expect(typeof Defined).toBe('function') - }) + beforeEach(() => TestBed.resetTestingModule()) - it('returns a component class with default config', () => { + it('returns a component class', () => { const Defined = defineMarkdownComponent() - expect(Defined).toBeDefined() expect(typeof Defined).toBe('function') }) - it('accepts plugins in config', () => { - const fakePlugin = { name: 'test', setup: () => {} } + it('accepts plugins, components, class, and parse options', () => { + const plugin = { name: 'test', setup: () => {} } + const transformNode: NodeTransform = () => undefined + class FakeComponent {} const Defined = defineMarkdownComponent({ - plugins: [fakePlugin as any], + plugins: [plugin as any], + components: { alert: FakeComponent }, + class: 'prose', + autoClose: true, + transformNode, }) - expect(Defined).toBeDefined() + + expect(typeof Defined).toBe('function') }) - it('accepts components in config', () => { - class FakeComponent {} - const Defined = defineMarkdownComponent({ - components: { alert: FakeComponent as any }, + it('renders an imported factory component with its config', async () => { + await TestBed.configureTestingModule({ imports: [ConfiguredMarkdown] }).compileComponents() + const fixture = TestBed.createComponent(ConfiguredMarkdown) + fixture.componentRef.setInput('value', '::alert\n:smile:\n::') + fixture.detectChanges() + + await vi.waitFor(() => { + fixture.detectChanges() + expect(fixture.nativeElement.textContent).toContain('😄') }) - expect(Defined).toBeDefined() + + const html = fixture.nativeElement.outerHTML as string + expect(html).toContain('factory-class') + expect(html).toContain('config-alert') }) - it('accepts class in config', () => { - const Defined = defineMarkdownComponent({ - class: 'prose dark:prose-invert', + it('keeps the first duplicate plugin from the factory config', async () => { + const Defined = defineMarkdownComponent({ plugins: [emoji({ extend: { project: '🚀' } }), emoji()] }) + await TestBed.configureTestingModule({ imports: [Defined] }).compileComponents() + const fixture = TestBed.createComponent(Defined) + fixture.componentRef.setInput('value', ':project:') + fixture.detectChanges() + + await vi.waitFor(() => { + fixture.detectChanges() + expect(fixture.nativeElement.textContent).toContain('🚀') }) - expect(Defined).toBeDefined() }) - it('accepts parse options in config', () => { - const Defined = defineMarkdownComponent({ - autoClose: true, - autoUnwrap: false, + it('lets instance components override the factory config', async () => { + await TestBed.configureTestingModule({ imports: [ConfiguredMarkdown] }).compileComponents() + const fixture = TestBed.createComponent(ConfiguredMarkdown) + fixture.componentRef.setInput('value', '::alert\nHello\n::') + fixture.componentRef.setInput('components', { alert: InstanceAlert }) + fixture.detectChanges() + + await vi.waitFor(() => { + fixture.detectChanges() + expect(fixture.nativeElement.textContent).toContain('Hello') }) - expect(Defined).toBeDefined() + + const html = fixture.nativeElement.outerHTML as string + expect(html).toContain('instance-alert') + expect(html).not.toContain('config-alert') }) }) describe('defineMarkdownDocumentComponent', () => { - it('returns a component class', () => { - const Defined = defineMarkdownDocumentComponent({}) - expect(Defined).toBeDefined() - expect(typeof Defined).toBe('function') - }) + beforeEach(() => TestBed.resetTestingModule()) - it('returns a component class with default config', () => { + it('returns a component class', () => { const Defined = defineMarkdownDocumentComponent() - expect(Defined).toBeDefined() + expect(typeof Defined).toBe('function') }) - it('accepts components in config', () => { + it('accepts components, class, and transforms', () => { + const transformNode: NodeTransform = () => undefined class FakeComponent {} const Defined = defineMarkdownDocumentComponent({ - components: { Math: FakeComponent as any }, + components: { Math: FakeComponent }, + class: 'prose', + transformNode, }) - expect(Defined).toBeDefined() + + expect(typeof Defined).toBe('function') }) - it('accepts class in config', () => { - const Defined = defineMarkdownDocumentComponent({ - class: 'prose', - }) - expect(Defined).toBeDefined() + it('renders an imported factory component with its config', async () => { + const document = await parseMarkdown('Hello\n\n::alert\nAlert\n::') + await TestBed.configureTestingModule({ imports: [ConfiguredMarkdownDocument] }).compileComponents() + const fixture = TestBed.createComponent(ConfiguredMarkdownDocument) + fixture.componentRef.setInput('value', document) + fixture.detectChanges() + + const html = fixture.nativeElement.outerHTML as string + expect(html).toContain('factory-document-class') + expect(html).toContain('config-alert') + expect(html).toContain('

Hello
') }) }) diff --git a/packages/comark-angular/test/fixtures/aot/app.component.ts b/packages/comark-angular/test/fixtures/aot/app.component.ts new file mode 100644 index 00000000..5d2931f2 --- /dev/null +++ b/packages/comark-angular/test/fixtures/aot/app.component.ts @@ -0,0 +1,27 @@ +import { Component } from '@angular/core' +import type { MarkdownDocument as MarkdownDocumentType } from 'comark' +import { Markdown, MarkdownDocument, provideMarkdown, provideMarkdownDocument } from '../../../src/index.ts' + +@Component({ + selector: 'app-markdown', + standalone: true, + imports: [Markdown], + providers: [provideMarkdown({ class: 'prose' })], + template: ``, +}) +export class AppMarkdownComponent { + content = '# Hello' +} + +@Component({ + selector: 'app-document', + standalone: true, + imports: [MarkdownDocument], + providers: [provideMarkdownDocument({ class: 'prose' })], + template: `@if (document) { + + }`, +}) +export class AppDocumentComponent { + document?: MarkdownDocumentType +} diff --git a/packages/comark-angular/test/fixtures/aot/factory-imports.component.ts b/packages/comark-angular/test/fixtures/aot/factory-imports.component.ts new file mode 100644 index 00000000..cdbc3af8 --- /dev/null +++ b/packages/comark-angular/test/fixtures/aot/factory-imports.component.ts @@ -0,0 +1,12 @@ +import { Component } from '@angular/core' +import { defineMarkdownComponent } from '../../../src/index.ts' + +@Component({ + selector: 'app-factory-markdown', + standalone: true, + imports: [defineMarkdownComponent()], + template: ``, +}) +export class AppFactoryMarkdownComponent { + content = '# Hello' +} diff --git a/packages/comark-angular/test/fixtures/aot/tsconfig.factory.json b/packages/comark-angular/test/fixtures/aot/tsconfig.factory.json new file mode 100644 index 00000000..a8cab127 --- /dev/null +++ b/packages/comark-angular/test/fixtures/aot/tsconfig.factory.json @@ -0,0 +1,10 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "outDir": "../../../out-tsc/aot-fixture-factory", + "noEmit": true, + "types": [], + "rootDir": "../../.." + }, + "files": ["factory-imports.component.ts"] +} diff --git a/packages/comark-angular/test/fixtures/aot/tsconfig.json b/packages/comark-angular/test/fixtures/aot/tsconfig.json new file mode 100644 index 00000000..8c4eecea --- /dev/null +++ b/packages/comark-angular/test/fixtures/aot/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "outDir": "../../../out-tsc/aot-fixture", + "noEmit": true, + "types": [], + "rootDir": "../../.." + }, + "files": ["app.component.ts"] +} diff --git a/packages/comark-angular/test/fixtures/defined/defined.ts b/packages/comark-angular/test/fixtures/defined/defined.ts new file mode 100644 index 00000000..7f64079a --- /dev/null +++ b/packages/comark-angular/test/fixtures/defined/defined.ts @@ -0,0 +1,32 @@ +import { Component } from '@angular/core' +import type { NodeTransform } from 'comark' +import emoji from 'comark/plugins/emoji' +import { defineMarkdownComponent, defineMarkdownDocumentComponent } from '../../../src/define.ts' + +@Component({ + selector: 'app-config-alert', + standalone: true, + template: '', +}) +export class ConfigAlert {} + +@Component({ + selector: 'app-instance-alert', + standalone: true, + template: '', +}) +export class InstanceAlert {} + +export const ConfiguredMarkdown = defineMarkdownComponent({ + plugins: [emoji()], + components: { alert: ConfigAlert }, + class: 'factory-class', +}) + +const documentTransform: NodeTransform = ({ tag }) => (tag === 'p' ? { tag: 'section' } : undefined) + +export const ConfiguredMarkdownDocument = defineMarkdownDocumentComponent({ + components: { alert: ConfigAlert }, + class: 'factory-document-class', + transformNode: documentTransform, +}) diff --git a/packages/comark-angular/test/provider-config.test.ts b/packages/comark-angular/test/provider-config.test.ts new file mode 100644 index 00000000..c305f8e5 --- /dev/null +++ b/packages/comark-angular/test/provider-config.test.ts @@ -0,0 +1,180 @@ +import '@angular/compiler' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { Component, provideZonelessChangeDetection, type Provider, type Type } from '@angular/core' +import { TestBed } from '@angular/core/testing' +import { bootstrapApplication } from '@angular/platform-browser' +import { renderApplication } from '@angular/platform-server' +import { parseMarkdown, type NodeTransform, type ParserOptions } from 'comark' +import emoji from 'comark/plugins/emoji' +import { Markdown } from '../src/components/markdown.component.ts' +import { MarkdownDocument } from '../src/components/markdown-document.component.ts' +import { provideMarkdown, provideMarkdownDocument } from '../src/provider.ts' + +@Component({ + selector: 'app-config-alert', + standalone: true, + template: '', +}) +class ConfigAlert {} + +@Component({ + selector: 'app-instance-alert', + standalone: true, + template: '', +}) +class InstanceAlert {} + +function renderApp(App: Type): Promise { + return renderApplication( + (context) => bootstrapApplication(App, { providers: [provideZonelessChangeDetection()] }, context), + { document: '' } + ) +} + +function app(options: { imports: Type[]; providers?: Provider[]; template: string }): any { + class App {} + Component({ + selector: 'app-root', + standalone: true, + imports: options.imports, + providers: options.providers, + template: options.template, + })(App) + return App +} + +async function renderMarkdown( + value: string, + providers: Provider[], + components?: Record>, + plugins?: ParserOptions['plugins'] +): Promise { + TestBed.resetTestingModule() + await TestBed.configureTestingModule({ imports: [Markdown], providers }).compileComponents() + const fixture = TestBed.createComponent(Markdown) + fixture.componentRef.setInput('value', value) + if (components) fixture.componentRef.setInput('components', components) + if (plugins) fixture.componentRef.setInput('plugins', plugins) + fixture.detectChanges() + await vi.waitFor(() => { + expect(fixture.componentInstance.document).not.toBeNull() + fixture.detectChanges() + }) + return fixture.nativeElement.outerHTML as string +} + +describe('Markdown config providers', () => { + beforeEach(() => TestBed.resetTestingModule()) + + it('applies config plugins, components, and class to static Markdown', async () => { + const html = await renderMarkdown('::alert\n:smile:\n::', [ + provideMarkdown({ + plugins: [emoji()], + components: { alert: ConfigAlert }, + class: 'config-class', + }), + ]) + + expect(html).toContain('config-class') + expect(html).toContain('config-alert') + expect(html).toContain('😄') + }) + + it('lets instance inputs override config components', async () => { + const html = await renderMarkdown('::alert\nHello\n::', [provideMarkdown({ components: { alert: ConfigAlert } })], { + alert: InstanceAlert, + }) + + expect(html).toContain('instance-alert') + expect(html).not.toContain('config-alert') + }) + + it('lets instance plugins replace config plugins with the same name', async () => { + const provider = provideMarkdown({ plugins: [emoji()] }) + const withConfig = await renderMarkdown(':smile:', [provider]) + const withOverride = await renderMarkdown(':smile:', [provider], undefined, [{ name: 'emoji' }]) + + expect(withConfig).toContain('😄') + expect(withOverride).not.toContain('😄') + }) + + it('keeps the first duplicate in the config plugin list', async () => { + const html = await renderMarkdown(':project:', [ + provideMarkdown({ plugins: [emoji({ extend: { project: '🚀' } }), emoji()] }), + ]) + + expect(html).toContain('🚀') + }) + + it('keeps the first duplicate in the instance plugin list', async () => { + const html = await renderMarkdown(':project:', [], undefined, [emoji({ extend: { project: '🚀' } }), emoji()]) + + expect(html).toContain('🚀') + }) + + it('inherits a config unwrap default when the input is omitted', async () => { + await TestBed.configureTestingModule({ + imports: [Markdown], + providers: [provideMarkdown({ unwrap: true })], + }).compileComponents() + const fixture = TestBed.createComponent(Markdown) + fixture.componentRef.setInput('value', 'Hello') + fixture.detectChanges() + await vi.waitFor(() => { + fixture.detectChanges() + expect(fixture.componentInstance.document).not.toBeNull() + }) + + expect(fixture.nativeElement.querySelector('p')).toBeNull() + }) + + it('lets an explicit unwrap=false override a config default', async () => { + await TestBed.configureTestingModule({ + imports: [Markdown], + providers: [provideMarkdown({ unwrap: true })], + }).compileComponents() + const fixture = TestBed.createComponent(Markdown) + fixture.componentRef.setInput('value', 'Hello') + fixture.componentRef.setInput('unwrap', false) + fixture.detectChanges() + await vi.waitFor(() => { + fixture.detectChanges() + expect(fixture.componentInstance.document).not.toBeNull() + }) + + expect(fixture.nativeElement.querySelector('p')).not.toBeNull() + }) + + it('runs config transformNode before the instance transformNode', async () => { + const document = await parseMarkdown('Hello') + const App = app({ + imports: [MarkdownDocument], + providers: [ + provideMarkdownDocument({ + class: 'document-class', + transformNode: ({ tag }) => (tag === 'p' ? { tag: 'section' } : undefined), + }), + ], + template: '', + }) + const instanceTransform: NodeTransform = ({ tag }) => (tag === 'section' ? { tag: 'article' } : undefined) + App.prototype.document = document + App.prototype.transformNode = instanceTransform + + const html = await renderApp(App) + expect(html).toContain('document-class') + expect(html).toContain('
Hello
') + }) + + it('works without a provider', async () => { + const document = await parseMarkdown('Hello') + const App = app({ + imports: [MarkdownDocument], + template: '', + }) + App.prototype.document = document + + const html = await renderApp(App) + expect(html).toContain('

Hello

') + }) +}) diff --git a/packages/comark-angular/test/provider.test.ts b/packages/comark-angular/test/provider.test.ts new file mode 100644 index 00000000..b59f2647 --- /dev/null +++ b/packages/comark-angular/test/provider.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import type { ValueProvider } from '@angular/core' +import type { NodeTransform } from 'comark' +import { provideMarkdown, provideMarkdownDocument } from '../src/provider.ts' +import { MARKDOWN_CONFIG, MARKDOWN_DOCUMENT_CONFIG } from '../src/config.ts' + +describe('provideMarkdown', () => { + it('returns a MARKDOWN_CONFIG provider with defaults and overrides', () => { + const empty = provideMarkdown() as ValueProvider + expect(empty.provide).toBe(MARKDOWN_CONFIG) + expect(empty.useValue).toMatchObject({ options: {}, plugins: [], components: {} }) + + const plugin = { name: 'test', setup: () => {} } + const transformNode: NodeTransform = () => undefined + class FakeComponent {} + const provider = provideMarkdown({ + plugins: [plugin as any], + components: { alert: FakeComponent }, + class: 'prose', + autoClose: true, + transformNode, + }) as ValueProvider + + expect(provider.provide).toBe(MARKDOWN_CONFIG) + expect(provider.useValue).toEqual({ + options: { autoClose: true }, + plugins: [plugin], + components: { alert: FakeComponent }, + transformNode, + class: 'prose', + }) + }) +}) + +describe('provideMarkdownDocument', () => { + it('returns a MARKDOWN_DOCUMENT_CONFIG provider with defaults and overrides', () => { + const empty = provideMarkdownDocument() as ValueProvider + expect(empty.provide).toBe(MARKDOWN_DOCUMENT_CONFIG) + expect(empty.useValue.components).toEqual({}) + + const transformNode: NodeTransform = () => undefined + class FakeComponent {} + const provider = provideMarkdownDocument({ + components: { Math: FakeComponent }, + class: 'prose', + transformNode, + }) as ValueProvider + + expect(provider.provide).toBe(MARKDOWN_DOCUMENT_CONFIG) + expect(provider.useValue).toEqual({ + components: { Math: FakeComponent }, + class: 'prose', + transformNode, + }) + }) +}) diff --git a/packages/comark-angular/test/reparse.test.ts b/packages/comark-angular/test/reparse.test.ts index 594ee8ad..5a9c4c5d 100644 --- a/packages/comark-angular/test/reparse.test.ts +++ b/packages/comark-angular/test/reparse.test.ts @@ -1,16 +1,16 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { TestBed } from '@angular/core/testing' -import type { Type } from '@angular/core' +import type { Provider, Type } from '@angular/core' import { Markdown } from '../src/components/markdown.component.ts' -import { defineMarkdownComponent } from '../src/define.ts' +import { provideMarkdown } from '../src/provider.ts' describe('Markdown re-parses when parser inputs change', () => { beforeEach(async () => { TestBed.resetTestingModule() }) - async function render(component: Type) { - await TestBed.configureTestingModule({ imports: [component] }).compileComponents() + async function render(component: Type, providers: Provider[] = []) { + await TestBed.configureTestingModule({ imports: [component], providers }).compileComponents() const fixture = TestBed.createComponent(component) fixture.componentRef.setInput('value', 'Hello **world**') fixture.detectChanges() @@ -49,9 +49,8 @@ describe('Markdown re-parses when parser inputs change', () => { }) }) - it('re-parses a defineMarkdownComponent when `unwrap` changes', async () => { - const Defined = defineMarkdownComponent({}) - const fixture = await render(Defined) + it('re-parses with a provideMarkdown config provider when `unwrap` changes', async () => { + const fixture = await render(Markdown, [provideMarkdown({})]) expect(fixture.nativeElement.querySelector('p')).not.toBeNull() fixture.componentRef.setInput('unwrap', true) diff --git a/packages/comark-angular/tsconfig.spec.json b/packages/comark-angular/tsconfig.spec.json index 9c50ca46..156e6ae1 100644 --- a/packages/comark-angular/tsconfig.spec.json +++ b/packages/comark-angular/tsconfig.spec.json @@ -4,7 +4,7 @@ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", - "types": ["vitest/globals"] + "types": ["node", "vitest/globals"] }, "include": ["test/**/*.d.ts", "test/**/*.test.ts"] } diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 8f1c9011..32b31fd8 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -70,7 +70,7 @@ describe('package bundle size', { timeout: 60_000 }, () => { expect(report).toMatchInlineSnapshot(` { - "@comark/angular": "70.1k (63 files)", + "@comark/angular": "77.2k (63 files)", "@comark/ansi": "42.1k (109 files)", "@comark/html": "17.7k (69 files)", "@comark/nuxt": "11.0k (69 files)",