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 5 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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1133,6 +1133,25 @@ Set this property to `false` to disable this plugin.
- `sizeUnits` (`string[]`, optional, defaults to `['', 'px', '%']`): Image size units to allow.
</details>

### collapsible_heading
<details>
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
<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.

**Options:**

Pass options for this plugin as the `collapsible_heading` property of the `do-markdownit` plugin options.
This plugin is disabled by default, pass an object to enable it.

- `levels` (`number[]`): List of heading tags to wrap (ex: `2`).
- `open` (`boolean`): 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>
MSzabi marked this conversation as resolved.
Show resolved Hide resolved

### link_attributes

<details>
Expand Down Expand Up @@ -1327,6 +1346,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/client.js
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
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
5 changes: 4 additions & 1 deletion dev/render.js
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
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 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 Expand Up @@ -33,6 +33,9 @@ const md = require('markdown-it')({
callout: {
allowedClasses: [ 'note', 'warning', 'info', 'draft' ],
},
collapsible_headings: {
levels: [],
},
});

/**
Expand Down
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 {import('./modifiers/collapsible_headings').CollapsibleHeadingOptions} [collapsible_headings] Enable transforming headings into collapsible content.
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
* @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) {
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
md.use(require('./rules/collapsible_heading'), safeObject(optsObj.collapsible_headings));
}

// Register embeds

if (optsObj.callout !== false) {
Expand Down
130 changes: 130 additions & 0 deletions rules/collapsible_heading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
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] List of headings to transform.
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
* @property {boolean} [open=true] Whether to collapse the content by default.
* @property {string} [className=collapsible] Class to use for collapsible sections.
*/

/**
* Add support for collapsing headings.
*
* When enabled this plugin wraps the specified headings and the content after in a collapsible section.
*
* @example
* # H1 header
* Test row
*
* <details class="collapsible">
* <summary>
* <h1>H1 header</h1>
* </summary>
* <p>Test row</p>
* </details>
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
*
* @type {import('markdown-it').PluginWithOptions<CollapsibleHeadingOptions>}
*/
module.exports = (md, options) => {
// Get the correct options
const optsObj = safeObject(options);

/**
* 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) openDetails.attrSet('open', '');
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
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('collapsbile_heading', collapsibleHeading);
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
};
97 changes: 97 additions & 0 deletions rules/collapsible_heading.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
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('does not inject collapsible by default', () => {
expect(md.render('# H1 header\nTest row')).toBe(`<h1>H1 header</h1>
<p>Test row</p>
`);
});
MSzabi marked this conversation as resolved.
Show resolved Hide resolved

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">
<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">
<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">
<summary>
<h1>H1 header</h1>
</summary>
<p>Test row</p>
</details>
<details class="collapsible">
<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">
<summary>
<h2>H2 header</h2>
</summary>
<p>Test row</p>
</details>
<h1>H1 header</h1>
<p>Test row</p>
`);
});

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

it('renders the detail open by default', () => {
expect(mdDefaultOpen.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>
`);
});
63 changes: 63 additions & 0 deletions styles/_collapsible.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
Copyright 2024 DigitalOcean

Licensed under the Apache License, Version 2.0 (the "License") !default;
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 "sass:math";
@import "theme";

$collapsible-heading-class: "collapsible" !default;

// Details
details.#{$collapsible-heading-class} {
border-bottom: 1px solid $gray6;
padding: 32px 0;

$size: 7;
$border: 2;

&[open] {
> summary {
&::after {
top: calc(50% - #{math.sqrt($size + $border) * 1px});
transform: translateY(-50%) rotate(225deg);
}
}
}

summary {
cursor: pointer;
list-style: none;
padding: 0 1em 0 0;
position: relative;

&::-webkit-details-marker,
&::marker {
display: none;
}

&::after {
content: "";
display: block;
position: absolute;
top: 50%;
right: 4px;
width: $size * 1px;
height: $size * 1px;
border: solid $gray4;
border-width: 0 ($border * 1px) ($border * 1px) 0;
transform: translateY(-50%) rotate(45deg);
}
}
}
Loading