Compare commits

..

No commits in common. "main" and "2.0.1" have entirely different histories.
main ... 2.0.1

16 changed files with 326 additions and 503 deletions

View file

@ -1,9 +1,9 @@
root = true root = true
[*] [*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space indent_style = space
insert_final_newline = true indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true trim_trailing_whitespace = true
insert_final_newline = true

View file

@ -1,3 +1,9 @@
name: bb
on:
issues:
types: [opened, reopened, edited, closed, labeled, unlabeled]
pull_request_target:
types: [opened, reopened, edited, closed, labeled, unlabeled]
jobs: jobs:
main: main:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@ -5,9 +11,3 @@ jobs:
- uses: unifiedjs/beep-boop-beta@main - uses: unifiedjs/beep-boop-beta@main
with: with:
repo-token: ${{secrets.GITHUB_TOKEN}} repo-token: ${{secrets.GITHUB_TOKEN}}
name: bb
on:
issues:
types: [closed, edited, labeled, opened, reopened, unlabeled]
pull_request_target:
types: [closed, edited, labeled, opened, reopened, unlabeled]

View file

@ -1,21 +1,21 @@
name: main
on:
- pull_request
- push
jobs: jobs:
main: main:
name: ${{matrix.node}} name: ${{matrix.node}}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v2
- uses: actions/setup-node@v4 - uses: dcodeIO/setup-node-nvm@master
with: with:
node-version: ${{matrix.node}} node-version: ${{matrix.node}}
- run: npm install - run: npm install
- run: npm test - run: npm test
- uses: codecov/codecov-action@v5 - uses: codecov/codecov-action@v1
strategy: strategy:
matrix: matrix:
node: node:
- lts/hydrogen - lts/erbium
- node - node
name: main
on:
- pull_request
- push

9
.gitignore vendored
View file

@ -1,9 +1,6 @@
*.d.ts
*.log
*.map
*.tsbuildinfo
.DS_Store
coverage/ coverage/
node_modules/ node_modules/
.DS_Store
*.d.ts
*.log
yarn.lock yarn.lock
!/index.d.ts

1
.npmrc
View file

@ -1,2 +1 @@
ignore-scripts=true
package-lock=false package-lock=false

View file

@ -1,2 +1,3 @@
*.md
coverage/ coverage/
*.json
*.md

View file

@ -1 +0,0 @@
test/fixtures/

15
index.d.ts vendored
View file

@ -1,15 +0,0 @@
import type {ToMarkdownOptions} from 'mdast-util-directive'
export {default} from './lib/index.js'
/**
* Configuration for `remark-directive`.
*
* Currently supports
* `collapseEmptyAttributes`,
* `preferShortcut`,
* `preferUnquoted`,
* `quoteSmart`,
* and `quote` as serialization options.
*/
export interface Options extends ToMarkdownOptions {}

View file

@ -1,2 +1,36 @@
// Note: types exposed from `index.d.ts`. /**
export {default} from './lib/index.js' * @typedef {import('mdast').Root} Root
*
* @typedef {import('mdast-util-directive')} DoNotTouchAsThisImportIncludesDirectivesInTree
*/
import {directive} from 'micromark-extension-directive'
import {directiveFromMarkdown, directiveToMarkdown} from 'mdast-util-directive'
/**
* Plugin to support the generic directives proposal (`:cite[smith04]`,
* `::youtube[Video of a cat in a box]{v=01ab2cd3efg}`, and such).
*
* @type {import('unified').Plugin<void[], Root>}
*/
export default function remarkDirective() {
const data = this.data()
add('micromarkExtensions', directive())
add('fromMarkdownExtensions', directiveFromMarkdown)
add('toMarkdownExtensions', directiveToMarkdown)
/**
* @param {string} field
* @param {unknown} value
*/
function add(field, value) {
const list = /** @type {unknown[]} */ (
// Other extensions
/* c8 ignore next 2 */
data[field] ? data[field] : (data[field] = [])
)
list.push(value)
}
}

View file

@ -1,38 +0,0 @@
/**
* @import {} from 'mdast-util-directive'
* @import {Root} from 'mdast'
* @import {} from 'remark-arse'
* @import {} from 'remark-stringify'
* @import {Processor} from 'unified'
*/
import {
directiveFromMarkdown,
directiveToMarkdown,
} from "mdast-util-directive";
import { directive } from "micromark-extension-directive";
/**
* Add support for generic directives.
*
* ###### Notes
*
* Doesnt handle the directives: create your own plugin to do that.
*
* @returns {undefined}
* Nothing.
*/
export default function remarkDirective() {
const data = this.data();
const micromarkExtensions =
data.micromarkExtensions || (data.micromarkExtensions = []);
const fromMarkdownExtensions =
data.fromMarkdownExtensions || (data.fromMarkdownExtensions = []);
const toMarkdownExtensions =
data.toMarkdownExtensions || (data.toMarkdownExtensions = []);
micromarkExtensions.push(directive());
fromMarkdownExtensions.push(directiveFromMarkdown());
toMarkdownExtensions.push(directiveToMarkdown());
}

View file

@ -1,6 +1,6 @@
(The MIT License) (The MIT License)
Copyright (c) Titus Wormer <tituswormer@gmail.com> Copyright (c) 2020 Titus Wormer <tituswormer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the a copy of this software and associated documentation files (the

View file

@ -1,106 +1,85 @@
{ {
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)", "name": "remark-directive",
"bugs": "https://github.com/remarkjs/remark-directive/issues", "version": "2.0.1",
"contributors": ["Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"], "description": "remark plugin to support directives",
"dependencies": { "license": "MIT",
"@types/mdast": "^4.0.0", "keywords": [
"mdast-util-directive": "^3.0.0", "unified",
"micromark-extension-directive": "git+https://git.v-sli.me/HidemaruOwO/micromark-extension-directive.git#fix.1", "remark",
"unified": "^11.0.0" "remark-plugin",
}, "plugin",
"description": "remark plugin to support directives", "mdast",
"devDependencies": { "markdown",
"@types/node": "^22.0.0", "generic",
"c8": "^10.0.0", "directive",
"is-hidden": "^2.0.0", "container"
"prettier": "^3.0.0", ],
"remark": "^15.0.0", "repository": "remarkjs/remark-directive",
"remark-cli": "^12.0.0", "bugs": "https://github.com/remarkjs/remark-directive/issues",
"remark-preset-wooorm": "^10.0.0", "funding": {
"to-vfile": "^8.0.0", "type": "opencollective",
"type-coverage": "^2.0.0", "url": "https://opencollective.com/unified"
"typescript": "^5.0.0", },
"xo": "^0.60.0" "author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
}, "contributors": [
"exports": "./index.js", "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
"files": ["index.d.ts", "index.js", "lib/"], ],
"funding": { "sideEffects": false,
"type": "opencollective", "type": "module",
"url": "https://opencollective.com/unified" "main": "index.js",
}, "types": "index.d.ts",
"keywords": [ "files": [
"container", "index.d.ts",
"directive", "index.js"
"generic", ],
"markdown", "dependencies": {
"mdast", "@types/mdast": "^3.0.0",
"plugin", "mdast-util-directive": "^2.0.0",
"remark-plugin", "micromark-extension-directive": "^2.0.0",
"remark", "unified": "^10.0.0"
"unified" },
], "devDependencies": {
"license": "MIT", "@types/tape": "^4.0.0",
"name": "remark-directive", "c8": "^7.0.0",
"prettier": { "is-hidden": "^2.0.0",
"bracketSpacing": false, "prettier": "^2.0.0",
"singleQuote": true, "remark": "^14.0.0",
"semi": false, "remark-cli": "^10.0.0",
"tabWidth": 2, "remark-preset-wooorm": "^9.0.0",
"trailingComma": "none", "rimraf": "^3.0.0",
"useTabs": false "tape": "^5.0.0",
}, "to-vfile": "^7.0.0",
"remarkConfig": { "type-coverage": "^2.0.0",
"plugins": ["remark-preset-wooorm"] "typescript": "^4.0.0",
}, "xo": "^0.45.0"
"repository": "remarkjs/remark-directive", },
"scripts": { "scripts": {
"build": "tsc --build --clean && tsc --build && type-coverage", "build": "rimraf \"test/**/*.d.ts\" \"*.d.ts\" && tsc && type-coverage",
"format": "remark --frail --output --quiet -- . && prettier --log-level warn --write -- . && xo --fix", "format": "remark . -qfo --ignore-pattern test/ && prettier . -w --loglevel warn && xo --fix",
"prepack": "npm run build && npm run format", "test-api": "node --conditions development test/index.js",
"test-api": "node --conditions development test/index.js", "test-coverage": "c8 --check-coverage --branches 100 --functions 100 --lines 100 --statements 100 --reporter lcov npm run test-api",
"test-coverage": "c8 --100 --reporter lcov -- npm run test-api", "test": "npm run build && npm run format && npm run test-coverage"
"test": "npm run build && npm run format && npm run test-coverage" },
}, "prettier": {
"sideEffects": false, "tabWidth": 2,
"typeCoverage": { "useTabs": false,
"atLeast": 100, "singleQuote": true,
"strict": true "bracketSpacing": false,
}, "semi": false,
"type": "module", "trailingComma": "none"
"version": "3.0.1", },
"xo": { "xo": {
"overrides": [ "prettier": true
{ },
"files": ["**/*.d.ts"], "remarkConfig": {
"rules": { "plugins": [
"@typescript-eslint/array-type": [ "preset-wooorm"
"error", ]
{ },
"default": "generic" "typeCoverage": {
} "atLeast": 100,
], "detail": true,
"@typescript-eslint/ban-types": [ "strict": true,
"error", "ignoreCatch": true
{ }
"extendDefaults": true
}
],
"@typescript-eslint/consistent-type-definitions": [
"error",
"interface"
]
}
},
{
"files": ["test/**/*.js"],
"rules": {
"no-await-in-loop": "off"
}
}
],
"prettier": true,
"rules": {
"logical-assignment-operators": "off"
}
}
} }

378
readme.md
View file

@ -8,86 +8,84 @@
[![Backers][backers-badge]][collective] [![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat] [![Chat][chat-badge]][chat]
**[remark][]** plugin to support the [generic directives [**remark**][remark] plugin to support the [generic directives proposal][prop]
proposal][commonmark-prop] (`:cite[smith04]`, (`:cite[smith04]`, `::youtube[Video of a cat in a box]{v=01ab2cd3efg}`, and
`::youtube[Video of a cat in a box]{v=01ab2cd3efg}`, and such). such).
## Contents ## Contents
* [What is this?](#what-is-this) * [What is this?](#what-is-this)
* [When should I use this?](#when-should-i-use-this) * [When should I use this?](#when-should-i-use-this)
* [Install](#install) * [Install](#install)
* [Use](#use) * [Use](#use)
* [API](#api) * [API](#api)
* [`unified().use(remarkDirective[, options])`](#unifieduseremarkdirective-options) * [`unified().use(remarkDirective)`](#unifieduseremarkdirective)
* [`Options`](#options) * [Examples](#examples)
* [Examples](#examples) * [Example: YouTube](#example-youtube)
* [Example: YouTube](#example-youtube) * [Example: Styled blocks](#example-styled-blocks)
* [Example: Styled blocks](#example-styled-blocks) * [Syntax](#syntax)
* [Authoring](#authoring) * [Syntax tree](#syntax-tree)
* [HTML](#html) * [Types](#types)
* [CSS](#css) * [Compatibility](#compatibility)
* [Syntax](#syntax) * [Security](#security)
* [Syntax tree](#syntax-tree) * [Related](#related)
* [Types](#types) * [Contribute](#contribute)
* [Compatibility](#compatibility) * [License](#license)
* [Security](#security)
* [Related](#related)
* [Contribute](#contribute)
* [License](#license)
## What is this? ## What is this?
This package is a [unified][] ([remark][]) plugin to add support for directives: This package is a [unified][] ([remark][]) plugin to add support for directives:
one syntax for arbitrary extensions in markdown. one syntax for arbitrary extensions in markdown.
You can use this with some more code to match your specific needs, to allow for
anything from callouts, citations, styled blocks, forms, embeds, spoilers, etc.
unified is an AST (abstract syntax tree) based transform project.
**remark** is everything unified that relates to markdown.
The layer under remark is called mdast, which is only concerned with syntax
trees.
Another layer underneath is micromark, which is only concerned with parsing.
This package is a small wrapper to integrate all of these.
## When should I use this? ## When should I use this?
Directives are one of the four ways to extend markdown: an arbitrary extension Directives are one of the four ways to extend markdown: an arbitrary extension
syntax (see [Extending markdown][micromark-extending-markdown] in micromarks syntax (see [Extending markdown](https://github.com/micromark/micromark#extending-markdown)
docs for the alternatives and more info). in micromarks docs for the alternatives and more info).
This mechanism works well when you control the content: who authors it, what This mechanism works well when you control the content: who authors it, what
tools handle it, and where its displayed. tools handle it, and where its displayed.
When authors can read a guide on how to embed a tweet but are not expected to When authors can read a guide on how to embed a tweet but are not expected to
know the ins and outs of HTML or JavaScript. know the ins and outs of HTML or JavaScript.
Directives dont work well if you dont know who authors content, what tools Directives dont work well if you dont know who authors content, what tools
handle it, and where it ends up. handle it, and where it ends up.
Example use cases are a docs website for a project or product, or blogging Example use cases are a docs website for a project or product, or blogging tools
tools and static site generators. and static site generators.
If you *just* want to turn markdown into HTML (with maybe a few extensions such
as this one), we recommend [`micromark`][micromark] with
[`micromark-extension-directive`][micromark-extension-directive] instead.
If you dont use plugins and want to access the syntax tree, you can use
[`mdast-util-from-markdown`][mdast-util-from-markdown] with
[`mdast-util-directive`][mdast-util-directive].
## Install ## Install
This package is [ESM only][esm]. This package is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).
In Node.js (version 16+), install with [npm][]: In Node.js (12.20+, 14.14+, 16.0+), install with [npm][]:
```sh ```sh
npm install remark-directive npm install remark-directive
``` ```
In Deno with [`esm.sh`][esmsh]: In Deno with [Skypack][]:
```js ```js
import remarkDirective from 'https://esm.sh/remark-directive@3' import remarkDirective from 'https://cdn.skypack.dev/remark-directive@2?dts'
``` ```
In browsers with [`esm.sh`][esmsh]: In browsers with [Skypack][]:
```html ```html
<script type="module"> <script type="module">
import remarkDirective from 'https://esm.sh/remark-directive@3?bundle' import remarkDirective from 'https://cdn.skypack.dev/remark-directive@2?min'
</script> </script>
``` ```
## Use ## Use
Say our document `example.md` contains: Say we have the following file, `example.md`:
```markdown ```markdown
:::main{#readme} :::main{#readme}
@ -102,55 +100,48 @@ A :i[lovely] language know as :abbr[HTML]{title="HyperText Markup Language"}.
::: :::
``` ```
…and our module `example.js` contains: And our module, `example.js`, looks as follows:
```js ```js
/**
* @import {} from 'mdast-util-directive'
* @import {} from 'mdast-util-to-hast'
* @import {Root} from 'mdast'
*/
import {h} from 'hastscript'
import rehypeFormat from 'rehype-format'
import rehypeStringify from 'rehype-stringify'
import remarkDirective from 'remark-directive'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import {read} from 'to-vfile' import {read} from 'to-vfile'
import {unified} from 'unified' import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkDirective from 'remark-directive'
import remarkRehype from 'remark-rehype'
import rehypeFormat from 'rehype-format'
import rehypeStringify from 'rehype-stringify'
import {visit} from 'unist-util-visit' import {visit} from 'unist-util-visit'
import {h} from 'hastscript'
const file = await unified() main()
.use(remarkParse)
.use(remarkDirective)
.use(myRemarkPlugin)
.use(remarkRehype)
.use(rehypeFormat)
.use(rehypeStringify)
.process(await read('example.md'))
console.log(String(file)) async function main() {
const file = await unified()
.use(remarkParse)
.use(remarkDirective)
.use(myRemarkPlugin)
.use(remarkRehype)
.use(rehypeFormat)
.use(rehypeStringify)
.process(await read('example.md'))
console.log(String(file))
}
// This plugin is an example to let users write HTML with directives. // This plugin is an example to let users write HTML with directives.
// Its informative but rather useless. // Its informative but rather useless.
// See below for others examples. // See below for others examples.
/** @type {import('unified').Plugin<[], import('mdast').Root>} */
function myRemarkPlugin() { function myRemarkPlugin() {
/** return (tree) => {
* @param {Root} tree visit(tree, (node) => {
* Tree.
* @returns {undefined}
* Nothing.
*/
return function (tree) {
visit(tree, function (node) {
if ( if (
node.type === 'containerDirective' || node.type === 'textDirective' ||
node.type === 'leafDirective' || node.type === 'leafDirective' ||
node.type === 'textDirective' node.type === 'containerDirective'
) { ) {
const data = node.data || (node.data = {}) const data = node.data || (node.data = {})
const hast = h(node.name, node.attributes || {}) const hast = h(node.name, node.attributes)
data.hName = hast.tagName data.hName = hast.tagName
data.hProperties = hast.properties data.hProperties = hast.properties
@ -160,7 +151,7 @@ function myRemarkPlugin() {
} }
``` ```
…then running `node example.js` yields: Now, running `node example` yields:
```html ```html
<main id="readme"> <main id="readme">
@ -173,48 +164,13 @@ function myRemarkPlugin() {
## API ## API
This package exports no identifiers. This package exports no identifiers.
The default export is [`remarkDirective`][api-remark-directive]. The default export is `remarkDirective`.
### `unified().use(remarkDirective[, options])` ### `unified().use(remarkDirective)`
Add support for generic directives. Configures remark so that it can parse and serialize directives.
Doesnt handle the directives: [create your own plugin][create-plugin] to do
###### Parameters that.
* `options` ([`Options`][api-options], optional)
— configuration
###### Returns
Nothing (`undefined`).
###### Notes
Doesnt handle the directives:
[create your own plugin][unified-create-plugin] to do that.
### `Options`
Configuration (TypeScript type).
###### Fields
* `collapseEmptyAttributes`
(`boolean`, default: `true`)
— collapse empty attributes: get `title` instead of `title=""`
* `preferShortcut`
(`boolean`, default: `true`)
— prefer `#` and `.` shortcuts for `id` and `class`
* `preferUnquoted`
(`boolean`, default: `false`)
— leave attributes unquoted if that results in less bytes
* `quoteSmart`
(`boolean`, default: `false`)
— use the other quote if that results in less bytes
* `quote`
(`'"'` or `"'"`,
default: the [`quote`][quote] used by `remark-stringify` for titles)
— preferred quote to use around attribute values
## Examples ## Examples
@ -225,31 +181,15 @@ Its based on the example in Use above.
If `myRemarkPlugin` was replaced with this function: If `myRemarkPlugin` was replaced with this function:
```js ```js
/**
* @import {} from 'mdast-util-directive'
* @import {} from 'mdast-util-to-hast'
* @import {Root} from 'mdast'
* @import {VFile} from 'vfile'
*/
import {visit} from 'unist-util-visit'
// This plugin is an example to turn `::youtube` into iframes. // This plugin is an example to turn `::youtube` into iframes.
/** @type {import('unified').Plugin<[], import('mdast').Root>} */
function myRemarkPlugin() { function myRemarkPlugin() {
/**
* @param {Root} tree
* Tree.
* @param {VFile} file
* File.
* @returns {undefined}
* Nothing.
*/
return (tree, file) => { return (tree, file) => {
visit(tree, function (node) { visit(tree, (node) => {
if ( if (
node.type === 'containerDirective' || node.type === 'textDirective' ||
node.type === 'leafDirective' || node.type === 'leafDirective' ||
node.type === 'textDirective' node.type === 'containerDirective'
) { ) {
if (node.name !== 'youtube') return if (node.name !== 'youtube') return
@ -257,16 +197,8 @@ function myRemarkPlugin() {
const attributes = node.attributes || {} const attributes = node.attributes || {}
const id = attributes.id const id = attributes.id
if (node.type === 'textDirective') { if (node.type === 'textDirective') file.fail('Text directives for `youtube` not supported', node)
file.fail( if (!id) file.fail('Missing video id', node)
'Unexpected `:youtube` text directive, use two colons for a leaf directive',
node
)
}
if (!id) {
file.fail('Unexpected missing `id` on `youtube` directive', node)
}
data.hName = 'iframe' data.hName = 'iframe'
data.hProperties = { data.hProperties = {
@ -291,7 +223,7 @@ function myRemarkPlugin() {
::youtube[Video of a cat in a box]{#01ab2cd3efg} ::youtube[Video of a cat in a box]{#01ab2cd3efg}
``` ```
…then running `node example.js` yields: …then running `node example` yields:
```html ```html
<h1>Cat videos</h1> <h1>Cat videos</h1>
@ -300,37 +232,23 @@ function myRemarkPlugin() {
### Example: Styled blocks ### Example: Styled blocks
> 👉 **Note**: This is sometimes called admonitions, callouts, etc. Note: This is sometimes called admonitions, callouts, etc.
This example shows how directives can be used to style blocks. This example shows how directives can be used to style blocks.
Its based on the example in Use above. Its based on the example in Use above.
If `myRemarkPlugin` was replaced with this function: If `myRemarkPlugin` was replaced with this function:
```js ```js
/**
* @import {} from 'mdast-util-directive'
* @import {} from 'mdast-util-to-hast'
* @import {Root} from 'mdast'
*/
import {h} from 'hastscript'
import {visit} from 'unist-util-visit'
// This plugin is an example to turn `::note` into divs, passing arbitrary // This plugin is an example to turn `::note` into divs, passing arbitrary
// attributes. // attributes.
/** @type {import('unified').Plugin<[], import('mdast').Root>} */
function myRemarkPlugin() { function myRemarkPlugin() {
/**
* @param {Root} tree
* Tree.
* @returns {undefined}
* Nothing.
*/
return (tree) => { return (tree) => {
visit(tree, (node) => { visit(tree, (node) => {
if ( if (
node.type === 'containerDirective' || node.type === 'textDirective' ||
node.type === 'leafDirective' || node.type === 'leafDirective' ||
node.type === 'textDirective' node.type === 'containerDirective'
) { ) {
if (node.name !== 'note') return if (node.name !== 'note') return
@ -338,7 +256,7 @@ function myRemarkPlugin() {
const tagName = node.type === 'textDirective' ? 'span' : 'div' const tagName = node.type === 'textDirective' ? 'span' : 'div'
data.hName = tagName data.hName = tagName
data.hProperties = h(tagName, node.attributes || {}).properties data.hProperties = h(tagName, node.attributes).properties
} }
}) })
} }
@ -367,57 +285,36 @@ if you chose xxx, you should also use yyy somewhere…
</div> </div>
``` ```
## Authoring
When authoring markdown with directives, keep in mind that they dont work in
most places.
On your own site it can be great!
## HTML
You can define how directives are turned into HTML.
If directives are not handled, they do not emit anything.
## CSS
How to display directives is left as an exercise for the reader.
## Syntax ## Syntax
See [*Syntax* in This plugin applies a micromark extensions to parse the syntax.
`micromark-extension-directive`](https://github.com/micromark/micromark-extension-directive#syntax). See its readme for parse details:
* [`micromark-extension-directive`](https://github.com/micromark/micromark-extension-directive#syntax)
## Syntax tree ## Syntax tree
See [*Syntax tree* in This plugin applies one mdast utility to build and serialize the AST.
`mdast-util-directive`](https://github.com/syntax-tree/mdast-util-directive#syntax-tree). See its readme for the node types supported in the tree:
* [`mdast-util-directive`](https://github.com/syntax-tree/mdast-util-directive#syntax-tree)
## Types ## Types
This package is fully typed with [TypeScript][]. This package is fully typed with [TypeScript][].
It exports no additional options. If youre working with the syntax tree, make sure to import this plugin
somewhere in your types, as that registers the new node types in the tree.
If youre working with the syntax tree, you can register the new node types
with `@types/mdast` by adding a reference:
```js ```js
/** /** @typedef {import('remark-directive')} */
* @import {} from 'mdast-util-directive'
* @import {Root} from 'mdast'
*/
import {visit} from 'unist-util-visit' import {visit} from 'unist-util-visit'
function myRemarkPlugin() { /** @type {import('unified').Plugin<[], import('mdast').Root>} */
/** export default function myRemarkPlugin() => {
* @param {Root} tree
* Tree.
* @returns {undefined}
* Nothing.
*/
return (tree) => { return (tree) => {
visit(tree, function (node) { visit(tree, (node) => {
console.log(node) // `node` can now be one of the nodes for directives. // `node` can now be one of the nodes for directives.
}) })
} }
} }
@ -425,31 +322,30 @@ function myRemarkPlugin() {
## Compatibility ## Compatibility
Projects maintained by the unified collective are compatible with maintained Projects maintained by the unified collective are compatible with all maintained
versions of Node.js. versions of Node.js.
As of now, that is Node.js 12.20+, 14.14+, and 16.0+.
Our projects sometimes work with older versions, but this is not guaranteed.
When we cut a new major release, we drop support for unmaintained versions of This plugin works with unified 9+ and remark 14+.
Node.
This means we try to keep the current release line, `remark-directive@^3`,
compatible with Node.js 16.
## Security ## Security
Use of `remark-directive` does not involve **[rehype][]** ([hast][]) or user Use of `remark-directive` does not involve [**rehype**][rehype]
content so there are no openings for [cross-site scripting (XSS)][wiki-xss] ([**hast**][hast]) or user content so there are no openings for [cross-site
attacks. scripting (XSS)][xss] attacks.
## Related ## Related
* [`remark-gfm`](https://github.com/remarkjs/remark-gfm) * [`remark-gfm`](https://github.com/remarkjs/remark-gfm)
— support GFM (autolink literals, footnotes, strikethrough, tables, — support GFM (autolink literals, strikethrough, tables, tasklists)
tasklists) * [`remark-github`](https://github.com/remarkjs/remark-github)
* [`remark-frontmatter`](https://github.com/remarkjs/remark-frontmatter) — link references to commits, issues, pull-requests, and users, like on
— support frontmatter (YAML, TOML, and more) GitHub
* [`remark-math`](https://github.com/remarkjs/remark-math) * [`remark-frontmatter`](https://github.com/remarkjs/remark-frontmatter)
— support math — support frontmatter (YAML, TOML, and more)
* [`remark-mdx`](https://github.com/mdx-js/mdx/tree/main/packages/remark-mdx) * [`remark-math`](https://github.com/remarkjs/remark-math)
— support MDX (ESM, JSX, expressions) — support math
## Contribute ## Contribute
@ -479,9 +375,9 @@ abide by its terms.
[downloads]: https://www.npmjs.com/package/remark-directive [downloads]: https://www.npmjs.com/package/remark-directive
[size-badge]: https://img.shields.io/bundlejs/size/remark-directive [size-badge]: https://img.shields.io/bundlephobia/minzip/remark-directive.svg
[size]: https://bundlejs.com/?q=remark-directive [size]: https://bundlephobia.com/result?p=remark-directive
[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg [sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg
@ -495,50 +391,32 @@ abide by its terms.
[npm]: https://docs.npmjs.com/cli/install [npm]: https://docs.npmjs.com/cli/install
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c [skypack]: https://www.skypack.dev
[esmsh]: https://esm.sh
[health]: https://github.com/remarkjs/.github [health]: https://github.com/remarkjs/.github
[contributing]: https://github.com/remarkjs/.github/blob/main/contributing.md [contributing]: https://github.com/remarkjs/.github/blob/HEAD/contributing.md
[support]: https://github.com/remarkjs/.github/blob/main/support.md [support]: https://github.com/remarkjs/.github/blob/HEAD/support.md
[coc]: https://github.com/remarkjs/.github/blob/main/code-of-conduct.md [coc]: https://github.com/remarkjs/.github/blob/HEAD/code-of-conduct.md
[license]: license [license]: license
[author]: https://wooorm.com [author]: https://wooorm.com
[commonmark-prop]: https://talk.commonmark.org/t/generic-directives-plugins-syntax/444 [unified]: https://github.com/unifiedjs/unified
[hast]: https://github.com/syntax-tree/hast
[mdast-util-directive]: https://github.com/syntax-tree/mdast-util-directive
[mdast-util-from-markdown]: https://github.com/syntax-tree/mdast-util-from-markdown
[micromark]: https://github.com/micromark/micromark
[micromark-extension-directive]: https://github.com/micromark/micromark-extension-directive
[micromark-extending-markdown]: https://github.com/micromark/micromark#extending-markdown
[quote]: https://github.com/remarkjs/remark/tree/main/packages/remark-stringify#options
[rehype]: https://github.com/rehypejs/rehype
[remark]: https://github.com/remarkjs/remark [remark]: https://github.com/remarkjs/remark
[xss]: https://en.wikipedia.org/wiki/Cross-site_scripting
[typescript]: https://www.typescriptlang.org [typescript]: https://www.typescriptlang.org
[unified]: https://github.com/unifiedjs/unified [rehype]: https://github.com/rehypejs/rehype
[unified-create-plugin]: https://unifiedjs.com/learn/guide/create-a-plugin/ [hast]: https://github.com/syntax-tree/hast
[wiki-xss]: https://en.wikipedia.org/wiki/Cross-site_scripting [prop]: https://talk.commonmark.org/t/generic-directives-plugins-syntax/444
[api-remark-directive]: #unifieduseremarkdirective-options [create-plugin]: https://unifiedjs.com/learn/guide/create-a-plugin/
[api-options]: #options

View file

@ -30,7 +30,7 @@ b
d d
:::e :::e
* * f * * f
::: :::
> g h > g h

View file

@ -2,77 +2,66 @@
* @typedef {import('mdast').Root} Root * @typedef {import('mdast').Root} Root
*/ */
import assert from 'node:assert/strict' import fs from 'node:fs'
import fs from 'node:fs/promises' import path from 'node:path'
import process from 'node:process' import test from 'tape'
import test from 'node:test' import {readSync} from 'to-vfile'
import {isHidden} from 'is-hidden' import {unified} from 'unified'
import {remark} from 'remark' import {remark} from 'remark'
import remarkDirective from 'remark-directive' import {isHidden} from 'is-hidden'
import directive from '../index.js'
test('remarkDirective', async function (t) { test('directive()', (t) => {
await t.test('should expose the public api', async function () { t.doesNotThrow(() => {
assert.deepEqual(Object.keys(await import('remark-directive')).sort(), [ remark().use(directive).freeze()
'default' }, 'should not throw if not passed options')
])
})
await t.test('should not throw if not passed options', async function () { t.doesNotThrow(() => {
assert.doesNotThrow(function () { unified().use(directive).freeze()
remark().use(remarkDirective).freeze() }, 'should not throw if without parser or compiler')
})
}) t.end()
}) })
test('fixtures', async function (t) { test('fixtures', (t) => {
const base = new URL('fixtures/', import.meta.url) const base = path.join('test', 'fixtures')
const folders = await fs.readdir(base) const entries = fs.readdirSync(base).filter((d) => !isHidden(d))
t.plan(entries.length)
let index = -1 let index = -1
while (++index < entries.length) {
while (++index < folders.length) { const fixture = entries[index]
const folder = folders[index] t.test(fixture, (st) => {
const file = readSync(path.join(base, fixture, 'input.md'))
if (isHidden(folder)) continue const input = String(file)
const outputPath = path.join(base, fixture, 'output.md')
await t.test(folder, async function () { const treePath = path.join(base, fixture, 'tree.json')
const folderUrl = new URL(folder + '/', base) const proc = remark().use(directive).freeze()
const inputUrl = new URL('input.md', folderUrl) const actual = proc.parse(file)
const outputUrl = new URL('output.md', folderUrl)
const treeUrl = new URL('tree.json', folderUrl)
const input = String(await fs.readFile(inputUrl))
/** @type {Root} */
let expected
/** @type {string} */ /** @type {string} */
let output let output
/** @type {Root} */
const processor = remark().use(remarkDirective) let expected
const actual = processor.parse(input)
try { try {
output = String(await fs.readFile(outputUrl)) expected = JSON.parse(String(fs.readFileSync(treePath)))
} catch {
// New fixture.
fs.writeFileSync(treePath, JSON.stringify(actual, null, 2) + '\n')
expected = actual
}
try {
output = fs.readFileSync(outputPath, 'utf8')
} catch { } catch {
output = input output = input
} }
try { st.deepEqual(actual, expected, 'tree')
if ('UPDATE' in process.env) { st.equal(String(proc.processSync(file)), output, 'process')
throw new Error('Updating…')
}
expected = JSON.parse(String(await fs.readFile(treeUrl))) st.end()
} catch {
expected = actual
// New fixture.
await fs.writeFile(treeUrl, JSON.stringify(actual, undefined, 2) + '\n')
}
assert.deepEqual(actual, expected)
assert.equal(String(await processor.process(input)), String(output))
}) })
} }
}) })

View file

@ -1,16 +1,16 @@
{ {
"include": ["test/**/*.js", "*.js"],
"compilerOptions": { "compilerOptions": {
"target": "ES2020",
"lib": ["ES2020"],
"module": "ES2020",
"moduleResolution": "node",
"allowJs": true,
"checkJs": true, "checkJs": true,
"customConditions": ["development"],
"declarationMap": true,
"declaration": true, "declaration": true,
"emitDeclarationOnly": true, "emitDeclarationOnly": true,
"exactOptionalPropertyTypes": true, "allowSyntheticDefaultImports": true,
"lib": ["es2022"], "skipLibCheck": true,
"module": "node16", "strict": true
"strict": true, }
"target": "es2022"
},
"exclude": ["coverage/", "node_modules/"],
"include": ["**/*.js", "index.d.ts"]
} }