Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Collapsible heading plugin #124

Merged
merged 8 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ Any non-code changes should be prefixed with `(docs)`.
See `PUBLISH.md` for instructions on how to publish a new version.
-->

- (minor) Add Collapsible Heading plugin


## v1.14.0 - 3a842c4

Expand Down
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,40 @@ Set this property to `false` to disable this plugin.
- `className` (`string`, optional, defaults to `'table-wrapper'`): Class to use for the table wrapper.
</details>

### collapsible_heading

<details>
<summary>Wrap specific headings in detail tag and make the content collapsible</summary>

If an array of heading tags is provided, all those tags and the related content will be wrapped in a details tag, with the heading as the summary.

Nesting multiple collapsible sections is supported.

**Example Markdown input:**

# H1 header
Test row

**Example HTML output:**

<details class="collapsible">
<summary>
<h1>H1 header</h1>
</summary>
<p>Test row</p>
</details>

**Options:**

Pass options for this plugin as the `collapsible_heading` property of the `do-markdownit` plugin options.
Set this property to `false` to disable this plugin.

- `levels` (`number[]`, optional, defaults to `[ 1, 2, 3, 4, 5, 6 ]`): List of heading tags to wrap (ex: `2`).
- `open` (`boolean`, optional, defaults to `true`): Flag indicating if the wrapped sections should be expanded by default.
- `className` (`string`, optional, defaults to `'collapsible'`): Class name to use on the collapsed section.

</details>

### callout

<details>
Expand Down Expand Up @@ -1327,6 +1361,7 @@ Variables listed here should be sorted based on the filename, and then by variab
| `$callouts-label-class` _(string)_ | `callout-label` | The class name used for labels in the `callout` plugin. | [`_callouts.scss`](./styles/_callouts.scss) |
| `$code-label-class` _(string)_ | `code-label` | The class name used for the `fence_label` plugin. | [`_code_label.scss`](./styles/_code_label.scss) |
| `$code-secondary-label-class` _(string)_ | `secondary-code-label` | The class name used for the `fence_secondary_label` plugin. | [`_code_secondary_label.scss`](./styles/_code_secondary_label.scss) |
| `$collapsible-heading-class` _(string)_ | `collapsible` | The class name used for the `collapsible_heading` plugin. | [`_collapsible.scss`](./styles/_collapsible.scss) |
| `$columns-inner-class` _(string)_ | `column` | The inner class name used for the `columns` plugin. | [`_columns.scss`](./styles/_columns.scss) |
| `$columns-outer-class` _(string)_ | `columns` | The outer class name used for the `columns` plugin. | [`_columns.scss`](./styles/_columns.scss) |
| `$hash-anchor-class` _(string)_ | `hash-anchor` | The anchor class name used for the `heading_id` plugin. | [`_heading-id.scss`](./styles/_heading_id.scss) |
Expand Down
2 changes: 1 addition & 1 deletion dev/render.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2022 DigitalOcean
Copyright 2024 DigitalOcean

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
94 changes: 93 additions & 1 deletion fixtures/full-output.html

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion index.js
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 DigitalOcean
Copyright 2024 DigitalOcean

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -29,6 +29,7 @@ const safeObject = require('./util/safe_object');
* @property {false|import('./rules/html_comment').HtmlCommentOptions} [html_comment] Disable HTML comment stripping, or set options for the feature.
* @property {false} [image_caption] Disable image captions.
* @property {false|import('./rules/table_wrapper').TableWrapperOptions} [table_wrapper] Disable table wrapper, or set options for the feature.
* @property {false|import('./modifiers/collapsible_headings').CollapsibleHeadingOptions} [collapsible_headings] Disable collapsible headings, or set options for the feature.
* @property {false|import('./rules/embeds/callout').CalloutOptions} [callout] Disable callout block syntax, or set options for the feature.
* @property {false|import('./rules/embeds/rsvp_button').RsvpButtonOptions} [rsvp_button] Disable RSVP buttons, or set options for the feature.
* @property {false|import('./rules/embeds/terminal_button').TerminalButtonOptions} [terminal_button] Disable terminal buttons, or set options for the feature.
Expand Down Expand Up @@ -92,6 +93,10 @@ module.exports = (md, options) => {
md.use(require('./rules/table_wrapper'), safeObject(optsObj.table_wrapper));
}

if (optsObj.collapsible_headings !== false) {
md.use(require('./rules/collapsible_heading'), safeObject(optsObj.collapsible_headings));
}

// Register embeds

if (optsObj.callout !== false) {
Expand Down
136 changes: 136 additions & 0 deletions rules/collapsible_heading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
Copyright 2024 DigitalOcean

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

/**
* @module rules/collapsible_heading
*/

const safeObject = require('../util/safe_object');

/**
* @typedef {Object} CollapsibleHeadingOptions
* @property {number[]} [levels=[1,2,3,4,5,6]] List of headings to transform.
* @property {boolean} [open=true] Whether to collapse the content by default.
* @property {string} [className=collapsible] Class to use for collapsible sections.
*/

/**
* Wrap specific headings in detail tag and make the content collapsible
*
* If an array of heading tags is provided, all those tags and the related content will be wrapped in a details tag, with the heading as the summary.
*
* Nesting multiple collapsible sections is supported.
*
* @example
* # H1 header
* Test row
*
* <details class="collapsible">
* <summary>
* <h1>H1 header</h1>
* </summary>
* <p>Test row</p>
* </details>
*
* @type {import('markdown-it').PluginWithOptions<CollapsibleHeadingOptions>}
*/
module.exports = (md, options) => {
// Get the correct options
const optsObj = safeObject(options);

if (!Array.isArray(optsObj.levels) || !optsObj.levels.length) {
optsObj.levels = [ 1, 2, 3, 4, 5, 6 ];
}

/**
* Rule for inserting details around headings.
*
* @type {import('markdown-it').RuleCore}
* @private
*/
const collapsibleHeading = state => {
// Track levels of collapsible headings that're open
const collapsed = [];
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
state.tokens = state.tokens.reduce((newTokens, token) => {
if (token.type === 'heading_open') {
const headingLevel = Number(token.tag.replace('h', ''));
// Close all open collapsible headings deeper than this
while (collapsed[collapsed.length - 1] >= headingLevel) {
// Close the previous detail element
const closeDetail = new state.Token('details', 'details', -1);
closeDetail.block = true;
newTokens.push(closeDetail);

// Remove the closed collapsible from the list.
collapsed.pop();
}

if (Array.isArray(optsObj.levels) && optsObj.levels.includes(headingLevel)) {
// Create the outer details element
const openDetails = new state.Token('details', 'details', 1);
openDetails.block = true;
openDetails.attrSet('class', md.utils.escapeHtml(typeof optsObj.className === 'string' ? optsObj.className : 'collapsible'));
if (optsObj.open !== false) openDetails.attrSet('open', '');
newTokens.push(openDetails);

// Create the summary element
const openSummary = new state.Token('summary', 'summary', 1);
openSummary.block = true;
newTokens.push(openSummary);

// Add the heading
newTokens.push(token);

// Track that we have an open collapsible heading
collapsed.push(headingLevel);
MSzabi marked this conversation as resolved.
Show resolved Hide resolved

return newTokens;
}
}

if (token.type === 'heading_close'
&& Array.isArray(optsObj.levels)
&& optsObj.levels.includes(Number(token.tag.replace('h', '')))
) {
// Add the heading close
newTokens.push(token);

// Close the summary element
const closeSummary = new state.Token('summary', 'summary', -1);
closeSummary.block = true;
newTokens.push(closeSummary);

return newTokens;
}

// Add the current token
newTokens.push(token);

return newTokens;
}, []);

collapsed.forEach(() => {
// Close all remaining previous detail elements
const closeDetail = new state.Token('details', 'details', -1);
closeDetail.block = true;
state.tokens.push(closeDetail);
});
};

md.core.ruler.push('collapsible_heading', collapsibleHeading);
};
139 changes: 139 additions & 0 deletions rules/collapsible_heading.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
Copyright 2024 DigitalOcean

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

const md = require('markdown-it')().use(require('./collapsible_heading'));

it('injects collapsibles by default for all headings', () => {
expect(md.render('# H1 header\nTest row\n\n## H2 header\nTest row\n\n### H3 header\nTest row\n\n#### H4 header\nTest row\n\n##### H5 header\nTest row\n\n###### H6 header\nTest row\n\n')).toBe(`<details class="collapsible" open="">
<summary>
<h1>H1 header</h1>
</summary>
<p>Test row</p>
<details class="collapsible" open="">
<summary>
<h2>H2 header</h2>
</summary>
<p>Test row</p>
<details class="collapsible" open="">
<summary>
<h3>H3 header</h3>
</summary>
<p>Test row</p>
<details class="collapsible" open="">
<summary>
<h4>H4 header</h4>
</summary>
<p>Test row</p>
<details class="collapsible" open="">
<summary>
<h5>H5 header</h5>
</summary>
<p>Test row</p>
<details class="collapsible" open="">
<summary>
<h6>H6 header</h6>
</summary>
<p>Test row</p>
</details>
</details>
</details>
</details>
</details>
</details>
`);
});

const mdAllowed = require('markdown-it')({ }).use(require('./collapsible_heading'), { levels: [ 1 ] });

it('only wraps specified headings', () => {
expect(mdAllowed.render('# H1 header\nTest row\n\n## H2 header\nTest row')).toBe(`<details class="collapsible" open="">
<summary>
<h1>H1 header</h1>
</summary>
<p>Test row</p>
<h2>H2 header</h2>
<p>Test row</p>
</details>
`);
});

const mdUsesClassName = require('markdown-it')({ }).use(require('./collapsible_heading'), { levels: [ 1 ], className: 'test' });

it('uses given classname', () => {
expect(mdUsesClassName.render('# H1 header\nTest row\n\n## H2 header\nTest row')).toBe(`<details class="test" open="">
<summary>
<h1>H1 header</h1>
</summary>
<p>Test row</p>
<h2>H2 header</h2>
<p>Test row</p>
</details>
`);
});

it('handles same level breaks correctly', () => {
expect(mdAllowed.render('# H1 header\nTest row\n\n# H1 header\nTest row')).toBe(`<details class="collapsible" open="">
<summary>
<h1>H1 header</h1>
</summary>
<p>Test row</p>
</details>
<details class="collapsible" open="">
<summary>
<h1>H1 header</h1>
</summary>
<p>Test row</p>
</details>
`);
});

const mdAllowedTwo = require('markdown-it')({ }).use(require('./collapsible_heading'), { levels: [ 2 ] });

it('handles different level breaks correctly', () => {
expect(mdAllowedTwo.render('## H2 header\nTest row\n\n# H1 header\nTest row')).toBe(`<details class="collapsible" open="">
<summary>
<h2>H2 header</h2>
</summary>
<p>Test row</p>
</details>
<h1>H1 header</h1>
<p>Test row</p>
`);
});

const mdClosed = require('markdown-it')({ }).use(require('./collapsible_heading'), { levels: [ 2 ], open: false });

it('renders the detail closed', () => {
expect(mdClosed.render('## H2 header\nTest row\n\n# H1 header\nTest row')).toBe(`<details class="collapsible">
<summary>
<h2>H2 header</h2>
</summary>
<p>Test row</p>
</details>
<h1>H1 header</h1>
<p>Test row</p>
`);
});

const mdDeactivated = require('markdown-it')({ });

it('renders the heading without wrapping', () => {
expect(mdDeactivated.render('# H1 header\nTest row')).toBe(`<h1>H1 header</h1>
<p>Test row</p>
`);
});
Loading