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

Export highlightCode #352

Merged
merged 1 commit into from
Apr 8, 2019
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
41 changes: 39 additions & 2 deletions addon/utils/compile-markdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,43 @@ hljs.registerLanguage('sh', shell);
hljs.registerLanguage('typescript', typescript);
hljs.registerLanguage('ts', typescript);

function highlightCode(code, lang) {
/**
This function is used when `compileMarkdown` encounters code blocks while
rendering Markdown source.

You can use this function on its own if you have code snippets you want
to highlight at run-time, for example snippets that change based on some
user interaction.

```js
import Component from '@ember/component';
import dedent from 'dedent';
import { highlightCode } from 'ember-cli-addon-docs/utils/compile-markdown';

export default Component.extend({
snippet: dedent`
let { foo } = bar;
`,

highlightedSnippet: computed(function() {
return highlightCode(this.snippet, 'js');
})
});
```

```hbs
<div class='docs-bg-code-base text-grey overflow-x-scroll'>
<div class="p-4 w-full">
<pre>{{{highlightedSnippet}}}</pre>
</div>
</div>
```

@function highlightCode
@param {string} snippet Snippet of code
@param {string} lang Language to use for syntax highlighting
*/
export function highlightCode(code, lang) {
return hljs.getLanguage(lang) ? hljs.highlight(lang, code).value : code
}

Expand All @@ -54,7 +90,8 @@ function highlightCode(code, lang) {
});
```

@function
@function compileMarkdown
@export default
@param {string} source Markdown string representing the source content
@param {object} options? Options. Pass `targetHandlebars: true` if turning MD into HBS
*/
Expand Down
11 changes: 11 additions & 0 deletions tests/unit/utils/highlight-code-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { highlightCode } from 'ember-cli-addon-docs/utils/compile-markdown';
import { module, test } from 'qunit';

module('Unit | Utility | highlight-code', function(hooks) {

// Replace this with your real tests.
test('it works', function(assert) {
let result = highlightCode(`let foo = 'bar';`, 'js');
assert.equal(result, `<span class="hljs-keyword">let</span> foo = <span class="hljs-string">'bar'</span>;`);
});
});