Skip to content

Commit 714c153

Browse files
authored
Export highlightCode (ember-learn#352)
1 parent a64bfca commit 714c153

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

addon/utils/compile-markdown.js

+39-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,43 @@ hljs.registerLanguage('sh', shell);
2727
hljs.registerLanguage('typescript', typescript);
2828
hljs.registerLanguage('ts', typescript);
2929

30-
function highlightCode(code, lang) {
30+
/**
31+
This function is used when `compileMarkdown` encounters code blocks while
32+
rendering Markdown source.
33+
34+
You can use this function on its own if you have code snippets you want
35+
to highlight at run-time, for example snippets that change based on some
36+
user interaction.
37+
38+
```js
39+
import Component from '@ember/component';
40+
import dedent from 'dedent';
41+
import { highlightCode } from 'ember-cli-addon-docs/utils/compile-markdown';
42+
43+
export default Component.extend({
44+
snippet: dedent`
45+
let { foo } = bar;
46+
`,
47+
48+
highlightedSnippet: computed(function() {
49+
return highlightCode(this.snippet, 'js');
50+
})
51+
});
52+
```
53+
54+
```hbs
55+
<div class='docs-bg-code-base text-grey overflow-x-scroll'>
56+
<div class="p-4 w-full">
57+
<pre>{{{highlightedSnippet}}}</pre>
58+
</div>
59+
</div>
60+
```
61+
62+
@function highlightCode
63+
@param {string} snippet Snippet of code
64+
@param {string} lang Language to use for syntax highlighting
65+
*/
66+
export function highlightCode(code, lang) {
3167
return hljs.getLanguage(lang) ? hljs.highlight(lang, code).value : code
3268
}
3369

@@ -54,7 +90,8 @@ function highlightCode(code, lang) {
5490
});
5591
```
5692
57-
@function
93+
@function compileMarkdown
94+
@export default
5895
@param {string} source Markdown string representing the source content
5996
@param {object} options? Options. Pass `targetHandlebars: true` if turning MD into HBS
6097
*/
+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { highlightCode } from 'ember-cli-addon-docs/utils/compile-markdown';
2+
import { module, test } from 'qunit';
3+
4+
module('Unit | Utility | highlight-code', function(hooks) {
5+
6+
// Replace this with your real tests.
7+
test('it works', function(assert) {
8+
let result = highlightCode(`let foo = 'bar';`, 'js');
9+
assert.equal(result, `<span class="hljs-keyword">let</span> foo = <span class="hljs-string">'bar'</span>;`);
10+
});
11+
});

0 commit comments

Comments
 (0)