### Install Markdoc using npm or yarn Source: https://github.com/evidence-dev/markdoc/blob/main/README.md Install the Markdoc library using either npm or yarn package managers. This is the first step to integrating Markdoc into your project. ```shell npm install @markdoc/markdoc ``` ```shell yarn add @markdoc/markdoc ``` -------------------------------- ### Install Markdoc with React dependencies Source: https://github.com/evidence-dev/markdoc/blob/main/README.md Install Markdoc along with its necessary React dependencies and types for React projects. This command ensures all required packages are available for React integration. ```shell npm install @markdoc/markdoc react @types/react ``` -------------------------------- ### Parse, Transform, and Render Markdoc Content Source: https://github.com/evidence-dev/markdoc/blob/main/README.md Example of using Markdoc to parse a Markdown string, transform the Abstract Syntax Tree (AST) into content, and render it using React. This demonstrates the core workflow of Markdoc. ```javascript const doc = "\n# Markdoc README\n\n{% image src=\"/logo.svg\" /%}\n"; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast); return Markdoc.renderers.react(content, React); ``` -------------------------------- ### Schema Definition with Slots in Markdoc Source: https://context7.com/evidence-dev/markdoc/llms.txt This snippet demonstrates how to define complex component schemas in Markdoc using slots. Slots allow for composable content patterns, enabling the creation of reusable and structured components. This example sets up a basic dialog structure with a header slot. Requires the '@markdoc/markdoc' library. ```javascript import Markdoc from '@markdoc/markdoc'; const markdown = ` {% dialog %} {% slot name="header" %} ``` -------------------------------- ### Custom Attribute Types for Validation and Transformation in Markdoc Source: https://context7.com/evidence-dev/markdoc/llms.txt This example showcases the creation of custom attribute types in Markdoc for robust validation and data transformation. It defines `ColorAttribute` and `UrlAttribute` classes with `validate` and `transform` methods. These custom types are then used within a Markdoc configuration to process tag attributes, ensuring data integrity and applying transformations like URL prefixing and color mapping. Requires the '@markdoc/markdoc' library. ```javascript import Markdoc from '@markdoc/markdoc'; // Custom color attribute type class ColorAttribute { validate(value, config) { const validColors = ['red', 'blue', 'green', 'yellow']; if (typeof value === 'string' && validColors.includes(value)) { return true; } return [{ id: 'invalid-color', level: 'error', message: `Color must be one of: ${validColors.join(', ')}` }]; } transform(value, config) { const colorMap = { 'red': '#FF0000', 'blue': '#0000FF', 'green': '#00FF00', 'yellow': '#FFFF00' }; return colorMap[value] || value; } } // Custom URL attribute type class UrlAttribute { validate(value, config) { if (typeof value !== 'string') return false; try { new URL(value); return true; } catch { return [{ id: 'invalid-url', level: 'error', message: 'Must be a valid URL' }]; } } transform(value, config) { // Ensure HTTPS return value.replace(/^http:/, 'https:'); } } const config = { tags: { highlight: { render: 'span', attributes: { color: { type: ColorAttribute }, url: { type: UrlAttribute } } } } }; const markdown = ` {% highlight color="blue" url="http://example.com" %} Highlighted text {% /highlight %} `; const ast = Markdoc.parse(markdown); // Validate with custom types const errors = Markdoc.validate(ast, config); console.log(errors); // Will validate URL and color // Transform applies custom transformations const content = Markdoc.transform(ast, config); console.log(content.children[0].attributes.color); // '#0000FF' console.log(content.children[0].attributes.url); // 'https://example.com' ``` -------------------------------- ### Render Markdoc Content to React Components Source: https://context7.com/evidence-dev/markdoc/llms.txt Demonstrates how to parse Markdown, transform it with custom components, and render the result as React elements. It includes defining custom React components and configuring Markdoc to use them. ```javascript import Markdoc from '@markdoc/markdoc'; import React from 'react'; // Custom React components const Callout = ({ type, children }) => (
{children}
); const Card = ({ title, icon, children }) => (

{icon} {title}

{children}
); const config = { tags: { callout: { render: 'Callout', attributes: { type: { type: String, default: 'info' } } }, card: { render: 'Card', attributes: { title: { type: String, required: true }, icon: { type: String } } } } }; const markdown = ` # Product Features {% callout type="warning" %} Limited time offer! {% /callout %} {% card title="Feature 1" icon="star" %} Amazing feature description. {% /card %} `; const ast = Markdoc.parse(markdown); const content = Markdoc.transform(ast, config); // Render with custom components const components = { Callout, Card }; const reactElement = Markdoc.renderers.react(content, React, { components }); // Use in your React app function App() { return
{reactElement}
; } ``` -------------------------------- ### Format AST to Markdown with Options in Markdoc Source: https://context7.com/evidence-dev/markdoc/llms.txt This JavaScript snippet illustrates how to parse Markdown into an Abstract Syntax Tree (AST) and then format that AST back into a Markdown string. It shows basic AST modification and demonstrates how to use options with the `Markdoc.format` function for controlling indentation, tag opening width, and list modes. Requires the '@markdoc/markdoc' library. ```javascript import Markdoc from '@markdoc/markdoc'; // Parse some markdown const original = ` # Title Some **bold** text and a [link](https://example.com) {% callout type="warning" title="Important" %} Custom tag content {% /callout %} `; const ast = Markdoc.parse(original); // Modify the AST programmatically ast.children[0].attributes.level = 2; // Change heading level // Format back to Markdown const formatted = Markdoc.format(ast); console.log(formatted); // Output: // ## Title // // Some **bold** text and a [link](https://example.com) // // {% callout type="warning" title="Important" %} // Custom tag content // {% /callout %} // Format with options const formattedWithOptions = Markdoc.format(ast, { allowIndentation: true, maxTagOpeningWidth: 60, orderedListMode: 'increment' }); ``` -------------------------------- ### Render Markdown with Custom Configuration in Markdoc Source: https://context7.com/evidence-dev/markdoc/llms.txt This snippet demonstrates how to parse Markdown content, define custom variables and functions for templating, and then transform and render the content into HTML. It highlights variable interpolation, conditional rendering, and function usage within the Markdoc templating system. Dependencies include the '@markdoc/markdoc' library. ```javascript import Markdoc from '@markdoc/markdoc'; const markdown = ` # Welcome {% $user.name %} Your account balance: {% $user.balance %} {% if equals($user.role, "admin") %} You have **admin** privileges. {% /if %} Uppercase name: {% uppercase($user.name) %} Total items: {% default($cart.items, 0) %} `; const config = { variables: { user: { name: 'Alice', balance: 1250.50, role: 'admin' }, cart: {} }, functions: { equals: { parameters: { 0: { required: true }, 1: { required: true } }, transform(parameters) { return parameters[0] === parameters[1]; } }, uppercase: { parameters: { 0: { type: String, required: true } }, transform(parameters) { return String(parameters[0]).toUpperCase(); } }, default: { parameters: { 0: {}, 1: { required: true } }, transform(parameters) { return parameters[0] !== undefined ? parameters[0] : parameters[1]; } } }, tags: { if: { render: null, attributes: {}, transform(node, config) { const condition = Object.values(node.attributes)[0]; const isTruthy = typeof condition === 'function' ? condition : Boolean(condition); return isTruthy ? node.transformChildren(config) : []; } } } }; const ast = Markdoc.parse(markdown); const content = Markdoc.transform(ast, config); const html = Markdoc.renderers.html(content); console.log(html); // Renders with variables interpolated and conditional content included ``` -------------------------------- ### Transform AST to Renderable Tree with Markdoc Schemas Source: https://context7.com/evidence-dev/markdoc/llms.txt Transforms a Markdoc Abstract Syntax Tree (AST) into a renderable tree structure using custom schemas, tags, and configuration. This process applies schema definitions and executes custom transform functions to produce Tag objects suitable for rendering. It allows for dynamic content injection using variables and custom functions. ```javascript import Markdoc from '@markdoc/markdoc'; const markdown = ` # Hello {% $name %} The price is {% $price %} `; const ast = Markdoc.parse(markdown); // Define a custom tag schema const config = { tags: { callout: { render: 'div', attributes: { type: { type: String, default: 'info', matches: ['info', 'warning', 'error'] } }, transform(node, config) { const attributes = node.transformAttributes(config); attributes.className = `callout callout-${node.attributes.type}`; return new Markdoc.Tag('div', attributes, node.transformChildren(config)); } } }, variables: { name: 'World', price: 99.99 }, functions: { uppercase: { transform(parameters) { return String(parameters[0]).toUpperCase(); } } } }; // Transform the AST into a renderable tree const content = Markdoc.transform(ast, config); // The result is a tree of Tag objects console.log(content.name); // 'article' (document renders as article) console.log(content.children[0].name); // 'h1' console.log(content.children[0].children); // ['Hello ', 'World'] ``` -------------------------------- ### Render Dialog Component with Slots using Markdoc Source: https://context7.com/evidence-dev/markdoc/llms.txt Demonstrates how Markdoc transforms a custom 'dialog' tag with named slots ('header', 'content', 'footer') into component props. The 'dialog' tag requires 'header' and 'content' slots and can optionally include a 'footer' slot. This enables structured content organization within Markdown. ```javascript const markdown = `{% dialog %} {% slot name="header" %} # Confirm Action {% /slot %} {% slot name="content" %} Are you sure you want to delete this item? {% /slot %} {% slot name="footer" %} [Cancel](#) | [Delete](#delete) {% /slot %} {% /dialog %}`; const config = { tags: { dialog: { render: 'Dialog', slots: { header: { render: 'header', required: true }, content: { render: 'content', required: true }, footer: { render: 'footer' } } }, slot: { render: null, attributes: { name: { type: String, required: true } } } } }; const ast = Markdoc.parse(markdown, { slots: true }); const content = Markdoc.transform(ast, config); // Slots are transformed into component props console.log(content.children[0].name); // 'Dialog' console.log(content.children[0].attributes.header); // Tag with header content console.log(content.children[0].attributes.content); // Tag with main content console.log(content.children[0].attributes.footer); // Tag with footer content ``` -------------------------------- ### Conditional Rendering and Partials with Markdoc Source: https://context7.com/evidence-dev/markdoc/llms.txt Shows how to implement conditional content rendering using 'if' tags and content reuse with 'partial' tags in Markdoc. It uses variables for dynamic content display and a configuration object to define the 'partial' tag's behavior, including loading content from external files. The output is rendered as HTML. ```javascript import Markdoc from '@markdoc/markdoc'; const markdown = `{% if $showBanner %} ## Special Offer! Get 50% off today only. {% /if %} {% if not($user.isPremium) %} [Upgrade to Premium](#upgrade) {% /if %} {% partial file="footer.md" /%}`; const partialContent = { 'footer.md': '---\n\nCopyright 2024. All rights reserved.' }; const config = { variables: { showBanner: true, user: { isPremium: false } }, tags: { partial: { render: null, attributes: { file: { type: String, required: true } }, transform(node, config) { const filename = node.attributes.file; const content = partialContent[filename]; if (!content) { return new Markdoc.Tag('div', {}, [`Error: Partial '${filename}' not found`]); } const ast = Markdoc.parse(content); return Markdoc.transform(ast, config); } } } }; const ast = Markdoc.parse(markdown); const content = Markdoc.transform(ast, config); const html = Markdoc.renderers.html(content); console.log(html); // Includes conditional content and partial content ``` -------------------------------- ### Minimal tsconfig.json for Markdoc in TypeScript Source: https://github.com/evidence-dev/markdoc/blob/main/README.md This is the minimum `tsconfig.json` configuration required to successfully use Markdoc within a TypeScript project. It ensures proper module resolution and target compatibility. ```json { "compilerOptions": { "moduleResolution": "node", "target": "esnext", "esModuleInterop": true } } ``` -------------------------------- ### Render Markdoc Content to React Components Source: https://context7.com/evidence-dev/markdoc/llms.txt Renders the transformed Markdoc content tree into React components. This process allows for custom mapping of Markdoc tags and nodes to specific React components, enabling the creation of dynamic and interactive documentation UIs. It requires the Markdoc library and React. ```javascript import React from 'react'; import Markdoc from '@markdoc/markdoc'; const markdown = ` ``` -------------------------------- ### Render Markdoc Content to HTML Source: https://context7.com/evidence-dev/markdoc/llms.txt Shows how to parse Markdown content and transform it into an HTML string. This is useful for static site generation or server-side rendering. It configures how link nodes are rendered. ```javascript import Markdoc from '@markdoc/markdoc'; const markdown = ` # Documentation Page Visit our [website](https://example.com "Example Site") for more info. ![Logo](/logo.png "Company Logo") ## Features - Feature 1 - Feature 2 - Feature 3 `; const ast = Markdoc.parse(markdown); const config = { nodes: { link: { render: 'a', attributes: { href: { type: String, required: true }, title: { type: String }, target: { type: String, default: '_blank' }, rel: { type: String, default: 'noopener noreferrer' } } } } }; const content = Markdoc.transform(ast, config); // Render to HTML string const html = Markdoc.renderers.html(content); console.log(html); // Output: //
//

Documentation Page

//

Visit our website for more info.

//

Logo

//

Features

// //
``` -------------------------------- ### Parse Markdown to AST with Markdoc Source: https://context7.com/evidence-dev/markdoc/llms.txt Parses a Markdown string into an Abstract Syntax Tree (AST) using the Markdoc library. The AST represents the content as a hierarchical node structure, including location information and error tracking for each node. This is the first step in the Markdoc processing pipeline. ```javascript import Markdoc from '@markdoc/markdoc'; const markdown = ` # Welcome to Markdoc This is a **bold** statement with a [link](https://example.com). {% callout type="warning" %} This is a custom tag with content. {% /callout %} `; // Parse the markdown into an AST const ast = Markdoc.parse(markdown); // The AST is a tree of Node objects console.log(ast.type); // 'document' console.log(ast.children.length); // Number of child nodes console.log(ast.children[0].type); // 'heading' console.log(ast.children[0].attributes.level); // 1 // Access location information console.log(ast.children[0].lines); // [1, 2] - line range console.log(ast.children[0].location); // { file, start, end } ``` -------------------------------- ### Import Markdoc in JavaScript (CommonJS and ESM) Source: https://github.com/evidence-dev/markdoc/blob/main/README.md Import the Markdoc library into your JavaScript project. Supports both CommonJS and ECMAScript Module (ESM) syntax. ```javascript const Markdoc = require('@markdoc/markdoc'); ``` ```javascript import Markdoc from '@markdoc/markdoc'; ``` -------------------------------- ### Custom Tag Transformation with Slots and Nested Content Source: https://context7.com/evidence-dev/markdoc/llms.txt Illustrates defining custom tags like 'tabs' and 'tab' with complex transformation logic. The 'tabs' tag transforms its children ('tab' tags) into a structured data format suitable for rendering. ```javascript import Markdoc from '@markdoc/markdoc'; const markdown = ` {% tabs %} {% tab label="JavaScript" %} ```javascript console.log('Hello'); ``` {% /tab %} {% tab label="Python" %} ```python print('Hello') ``` {% /tab %} {% /tabs %} `; const config = { tags: { tabs: { render: 'Tabs', transform(node, config) { const tabs = node.children .filter(child => child.tag === 'tab') .map(child => ({ label: child.attributes.label, content: child.transformChildren(config) })); return new Markdoc.Tag( 'Tabs', { tabs }, [], node.location, node.lines ); } }, tab: { render: 'Tab', attributes: { label: { type: String, required: true } } } } }; const ast = Markdoc.parse(markdown); const content = Markdoc.transform(ast, config); // Result contains structured tabs data console.log(content.children[0].name); // 'Tabs' console.log(content.children[0].attributes.tabs); // Array of tab objects console.log(content.children[0].attributes.tabs[0].label); // 'JavaScript' ``` -------------------------------- ### Validate Markdoc Content Against Schemas Source: https://context7.com/evidence-dev/markdoc/llms.txt Validates Markdoc Abstract Syntax Tree (AST) nodes against predefined schema definitions to identify potential errors before rendering. The validator checks for required attributes, type constraints, allowed values, and custom validation rules, returning an array of error objects. ```javascript import Markdoc from '@markdoc/markdoc'; const markdown = ` {% callout type="invalid" %} This has an invalid type attribute. {% /callout %} {% unknownTag %} This tag is not defined. {% /unknownTag %} `; const ast = Markdoc.parse(markdown); const config = { tags: { callout: { render: 'div', attributes: { type: { type: String, required: true, matches: ['info', 'warning', 'error'] }, title: { type: String } } } } }; // Validate the AST const errors = Markdoc.validate(ast, config); // Errors contain detailed information errors.forEach(error => { console.log(error.error.id); // 'attribute-value-invalid', 'tag-undefined' console.log(error.error.level); // 'error', 'critical', 'warning' console.log(error.error.message); // Descriptive error message console.log(error.location); // Location in source file console.log(error.lines); // [start, end] line numbers }); // Check if there are critical errors const criticalErrors = errors.filter(e => e.error.level === 'critical'); if (criticalErrors.length > 0) { throw new Error('Validation failed with critical errors'); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.