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 4 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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1133,6 +1133,24 @@ 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` (`string[]`): List of heading tags to wrap (ex: `"h2"`).
- `open` (`boolean`): Flag indicating if the wrapped sections should be expanded by default.

</details>

### link_attributes

<details>
Expand Down
1 change: 1 addition & 0 deletions 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
Expand Up @@ -38,6 +38,7 @@ document.addEventListener('DOMContentLoaded', event => {
textbox.style.height = `${textbox.scrollHeight}px`;

// Render the Markdown to HTML
console.log(render(textbox.value));
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
output.innerHTML = render(textbox.value);

// Ensure scripts are loaded
Expand Down
3 changes: 3 additions & 0 deletions 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
Expand Up @@ -33,6 +33,9 @@ const md = require('markdown-it')({
callout: {
allowedClasses: [ 'note', 'warning', 'info', 'draft' ],
},
collapsible_headings: {
levels: [],
},
});

/**
Expand Down
5 changes: 5 additions & 0 deletions index.js
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ const safeObject = require('./util/safe_object');
* @property {false|import('./modifiers/image_settings').ImageSettingsOptions} [image_settings] Disable image settings syntax, or set options for the feature.
* @property {false|import('./modifiers/prismjs').PrismJsOptions} [prismjs] Disable Prism highlighting, or set options for the feature.
* @property {import('./modifiers/link_attributes').LinkAttributesOptions} [link_attributes] Enable custom link attributes by setting 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 {import('./rules/limit_tokens').LimitTokensOptions} [limit_tokens] Enable token filtering by setting options for the feature.
*/

Expand Down Expand Up @@ -166,6 +167,10 @@ module.exports = (md, options) => {
md.use(require('./rules/embeds/compare'), safeObject(optsObj.compare));
}

if (optsObj.collapsible_headings) {
md.use(require('./rules/collapsible_heading'), safeObject(optsObj.collapsible_headings));
}
MSzabi marked this conversation as resolved.
Show resolved Hide resolved

// Register modifiers

if (optsObj.underline !== false) {
Expand Down
118 changes: 118 additions & 0 deletions rules/collapsible_heading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
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 modifiers/link_attributes
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
*/

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

/**
* @typedef {Object} CollapsibleHeadingOptions
* @property {string[]} [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.
*/

/**
* Add support for mentioning users, using an `@` symbol. Wraps the mention in a link to the user.
*
* By default, any characters that are not a space or newline after an `@` symbol will be treated as a mention.
*
* @example
* Hello @test
*
* <p>Hello <a href="/users/test">@test</a></p>
*
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 => {
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 hanging collapsible sections.
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
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(token.tag)) {
// Create the outer details element
const openDetails = new state.Token('details', 'details', 1);
openDetails.block = true;
openDetails.attrSet('class', 'collapsible');
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
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);

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(token.tag)) {
// 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
};
83 changes: 83 additions & 0 deletions rules/collapsible_heading.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
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: [ 'h1' ] });

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>
`);
});

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: [ 'h2' ] });

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: [ 'h2' ], 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>
`);
});
61 changes: 61 additions & 0 deletions styles/_collapsible.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
Copyright 2022 DigitalOcean
MSzabi marked this conversation as resolved.
Show resolved Hide resolved

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";

// Details
details.collapsible {
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
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);
}
}
}
4 changes: 2 additions & 2 deletions styles/_details.scss
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ limitations under the License.
@import "theme";

// Details
details {
details:not(.collapsible) {
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
background: $gray10;
border-radius: 16px;
padding: 1em;
Expand All @@ -28,7 +28,7 @@ details {
$border: 2;

&[open] {
summary {
> summary {
border-bottom: 1px solid $gray8;
padding: 0 1em 1em 0;
margin: 0 0 1em;
Expand Down
1 change: 1 addition & 0 deletions styles/index.scss
MSzabi marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,4 @@ limitations under the License.
@import "code_secondary_label";
@import "table_wrapper";
@import "compare";
@import "collapsible";