Skip to content

Allow custom attributes to be applied to pre and code tags #48

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

Merged
merged 4 commits into from
May 23, 2021
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules/
_site/
package-lock.json
yarn.lock
1 change: 1 addition & 0 deletions demo/eleventy-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const syntaxHighlight = require("../.eleventy.js");
module.exports = function(eleventyConfig) {
eleventyConfig.addPlugin(syntaxHighlight, {
// alwaysWrapLineHighlights: true
preAttributes: { tabindex: 0 }
});

eleventyConfig.setTemplateFormats("njk,liquid,md,css");
Expand Down
6 changes: 6 additions & 0 deletions demo/test-markdown.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ let multilineString = `
this is the middle line
this is the last line
`;
```

## Scrollbar

```js
import { aReallyLongFunctionNameThatCouldBeLongerButThisShouldBeLongEnoughByNowHopefully as anEvenLongerFunctionNameWithMoreCharactersThanCouldBeImaginedByAnyOnePersonInThisEntireWorldOfPeopleThatOneMightKnowAtLeastThatIsWhatIsTheorizedByThisLongName } from 'wow-this-is-so-long-you-might-need-a-scrollbar-to-see-it.long-ol-file-extension-that-should-not-be-this-long-on-a-real-site-but-this-is-to-demonstrate-the-accessibility-of-tabindex-and-scrollbars.js';
```

</body>
Expand Down
8 changes: 6 additions & 2 deletions src/HighlightPairedShortcode.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
const Prism = require("prismjs");
const PrismLoader = require("./PrismLoader");
const HighlightLinesGroup = require("./HighlightLinesGroup");
const getAttributes = require("./getAttributes");

module.exports = function (content, language, highlightNumbers, options = {}) {
const preAttributes = getAttributes(options.preAttributes)
const codeAttributes = getAttributes(options.codeAttributes)

module.exports = function(content, language, highlightNumbers, options = {}) {
// default to on
if(options.trim === undefined || options.trim === true) {
content = content.trim();
Expand All @@ -25,5 +29,5 @@ module.exports = function(content, language, highlightNumbers, options = {}) {
return line;
});

return `<pre class="language-${language}"><code class="language-${language}">` + lines.join(options.lineSeparator || "<br>") + "</code></pre>";
return `<pre class="language-${language}"${preAttributes}><code class="language-${language}"${codeAttributes}>` + lines.join(options.lineSeparator || "<br>") + "</code></pre>";
};
42 changes: 42 additions & 0 deletions src/getAttributes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
function attributeEntryToString([key, value]) {
if (typeof value !== "string" && typeof value !== "number")
throw new Error(
`Attribute "${key}" must have a value of type string or number not "${typeof value}".`
);

return `${key}="${value}"`;
}

/**
* ## Usage
* The function `getAttributes` is used to convert an object, `attributes`, with HTML attributes as keys and the values as the corresponding HTML attribute's values.
* If the `attributes` parameter is a string, it will be returned. If it is falsey, an empty string will be returned.
*
* ```js
getAttributes('tabindex="0" data-language="HTML"')
// => ' tabindex="0" data-language="HTML"'

getAttributes({
tabindex: 0,
'data-language': 'JavaScript',
'data-otherStuff': 'value'
}) // => ' tabindex="0" data-language="JavaScript" data-otherStuff="value"'
```
*
* @param {string | {[s: string]: string | number}} attributes A string containing HTML attributes or an object with key-value pairs that represent attributes.
* @returns {string} A string containing the above HTML attributes preceded by a single space.
*/
function getAttributes(attributes) {
if (!attributes) {
return "";
} else if (typeof attributes === "string") {
return ` ${attributes}`;
} else if (typeof attributes === "object") {
const formattedAttributes = Object.entries(attributes).map(
attributeEntryToString
);
return ` ${formattedAttributes.join(" ")}`;
}
}

module.exports = getAttributes;
8 changes: 6 additions & 2 deletions src/markdownSyntaxHighlightOptions.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
const Prism = require("prismjs");
const PrismLoader = require("./PrismLoader");
const HighlightLinesGroup = require("./HighlightLinesGroup");
const getAttributes = require("./getAttributes");

module.exports = function (options = {}) {
const preAttributes = getAttributes(options.preAttributes)
const codeAttributes = getAttributes(options.codeAttributes)

module.exports = function(options = {}) {
return function(str, language) {
if(!language) {
// empty string means defer to the upstream escaping code built into markdown lib.
Expand Down Expand Up @@ -33,6 +37,6 @@ module.exports = function(options = {}) {
return line;
});

return `<pre class="language-${language}"><code class="language-${language}">${lines.join(options.lineSeparator || "<br>")}</code></pre>`;
return `<pre class="language-${language}"${preAttributes}><code class="language-${language}"${codeAttributes}>${lines.join(options.lineSeparator || "<br>")}</code></pre>`;
};
};
4 changes: 2 additions & 2 deletions test/CharacterWrapTest.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions test/HighlightPairedShortcodeTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ test("Base", async t => {
alert();`, "js", "", { alwaysWrapLineHighlights: true }), `<pre class="language-js"><code class="language-js"><span class="highlight-line"><span class="token function">alert</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span><br><span class="highlight-line"><span class="token function">alert</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span></code></pre>`);
});

test("Base with custom attributes", async t => {
t.is(await HighlightPairedShortcode(`alert();
alert();`, "js", "", { alwaysWrapLineHighlights: true, preAttributes: { tabindex: 0, 'data-testid': 'code' } }), `<pre class="language-js" tabindex="0" data-testid="code"><code class="language-js"><span class="highlight-line"><span class="token function">alert</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span><br><span class="highlight-line"><span class="token function">alert</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span></code></pre>`);
});

test("Base change the line separator", async t => {
t.is(await HighlightPairedShortcode(`alert();
alert();`, "js", "", {
Expand Down