Skip to content

Commit

Permalink
feat(NcRichText): highlight code syntax if language provided
Browse files Browse the repository at this point in the history
Signed-off-by: Maksim Sukharev <antreesy.web@gmail.com>
  • Loading branch information
Antreesy committed Nov 20, 2024
1 parent 05e1e5d commit 8d47b86
Show file tree
Hide file tree
Showing 5 changed files with 249 additions and 4 deletions.
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const ignorePatterns = [
'hast-*',
'is-*',
'longest-streak', // ESM dependency of remark-gfm
'lowlight', // ESM dependency of rehype-highlight
'markdown-table', // ESM dependency of remark-gfm
'mdast-util-*',
'micromark',
Expand Down
34 changes: 32 additions & 2 deletions src/components/NcRichText/NcRichText.vue
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ textarea {
### Flavored Markdown

This component can support [Github Flavored Markdown](https://github.github.com/gfm/).
It adds such elements, as tables, task lists, strikethrough, and supports autolinks by default
It adds such elements, as tables, task lists, strikethrough, and supports code syntax highlighting and autolinks by default

It is also possible to make a rendered content interactive and listen for events

Expand Down Expand Up @@ -94,6 +94,17 @@ It is also possible to make a rendered content interactive and listen for events
Table header | Column A | Column B
-- | -- | --
Table row | value A | value B

---

\`\`\`js
const GenRandomId = (length) => {
\treturn Math.random()
\t\t.toString(36)
\t\t.replace(/[^a-z]+/g, '')
\t\t.slice(0, length || 5)
}
\`\`\`
`,
}
},
Expand All @@ -105,7 +116,7 @@ Table row | value A | value B
return
}
let checkBoxIndex = 0
lines = this.text.split('\n')
let lines = this.text.split('\n')
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes('[ ]') || lines[i].includes('[x]')) {
if (checkBoxIndex === index) {
Expand Down Expand Up @@ -291,6 +302,7 @@ See [NcRichContenteditable](#/Components/NcRichContenteditable) documentation fo
</docs>

<script>
import { ref } from 'vue'
import NcReferenceList from './NcReferenceList.vue'
import NcCheckboxRadioSwitch from '../NcCheckboxRadioSwitch/NcCheckboxRadioSwitch.vue'
import { getRoute, remarkAutolink } from './autolink.js'
Expand All @@ -306,6 +318,20 @@ import rehype2react from 'rehype-react'
import rehypeExternalLinks from 'rehype-external-links'
import { RouterLink } from 'vue-router'

/**
* Heavy libraries should be loaded on demand to reduce component size
*/
let rehypeHighlight
const rehypeHighlightLoaded = ref(false)
/**
* Load 'rehype-highlight' library when code block is rendered with `useExtendedMarkdown`
*/
async function importRehypeLibrary() {
const module = await import('rehype-highlight')
rehypeHighlight = module.default
rehypeHighlightLoaded.value = true
}

export default {
name: 'NcRichText',
components: {
Expand Down Expand Up @@ -447,6 +473,7 @@ export default {
},
},
})
.use((this.useExtendedMarkdown && rehypeHighlightLoaded.value) ? rehypeHighlight : undefined)
// .use(rehypeAddClasses, this.markdownCssClasses)
.use(remarkPlaceholder)
.use(rehypeExternalLinks, {
Expand All @@ -463,6 +490,9 @@ export default {

if (!tag.startsWith('#')) {
if (this.useExtendedMarkdown) {
if (tag === 'code' && !rehypeHighlightLoaded.value) {
importRehypeLibrary()
}
let nestedNode = null
if (tag === 'li' && Array.isArray(children)
&& children[0].tag === 'input'
Expand Down
171 changes: 171 additions & 0 deletions src/components/NcRichText/highlight.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

/**
* Colors and class selectors are extracted from source code of:
* - library: highlight.js (v11.10.0)
* - light theme: highlight.js/styles/github.css
* - dark theme: highlight.js/styles/github-dark.css
* and reworked to use with Nextcloud dark and light theme
*/

@mixin highlight-light-colors {
--hljs-color: var(--color-main-text, #24292e);
--hljs-background-color: var(--color-background-dark, #ffffff);
--hljs-syntax-keyword-color: #d73a49;
--hljs-syntax-entity-color: #6f42c1;
--hljs-syntax-constant-color: #005cc5;
--hljs-syntax-string-color: #032f62;
--hljs-syntax-variable-color: #e36209;
--hljs-syntax-comment-color: #6a737d;
--hljs-syntax-entity-tag-color: #22863a;
--hljs-syntax-storage-modifier-import-color: #24292e;
--hljs-syntax-markup-heading-color: #005cc5;
--hljs-syntax-markup-list-color: #735c0f;
--hljs-syntax-markup-italic-color: #24292e;
--hljs-syntax-markup-bold-color: #24292e;
--hljs-syntax-markup-inserted-color: #22863a;
--hljs-syntax-markup-inserted-background-color: #f0fff4;
--hljs-syntax-markup-deleted-color: #b31d28;
--hljs-syntax-markup-deleted-background-color: #ffeef0;
}

@mixin highlight-dark-colors {
--hljs-color: var(--color-main-text, #c9d1d9);
--hljs-background-color: var(--color-background-dark, #0d1117);
--hljs-syntax-keyword-color: #ff7b72;
--hljs-syntax-entity-color: #d2a8ff;
--hljs-syntax-constant-color: #79c0ff;
--hljs-syntax-string-color: #a5d6ff;
--hljs-syntax-variable-color: #ffa657;
--hljs-syntax-comment-color: #8b949e;
--hljs-syntax-entity-tag-color: #7ee787;
--hljs-syntax-storage-modifier-import-color: #c9d1d9;
--hljs-syntax-markup-heading-color: #1f6feb;
--hljs-syntax-markup-list-color: #f2cc60;
--hljs-syntax-markup-italic-color: #c9d1d9;
--hljs-syntax-markup-bold-color: #c9d1d9;
--hljs-syntax-markup-inserted-color: #aff5b4;
--hljs-syntax-markup-inserted-background-color: #033a16;
--hljs-syntax-markup-deleted-color: #ffdcd7;
--hljs-syntax-markup-deleted-background-color: #67060c;
}

@mixin highlight-rules {
pre:has(.hljs) {
color: var(--hljs-color);
background: var(--hljs-background-color);
}

.hljs-doctag,
.hljs-keyword,
.hljs-meta .hljs-keyword,
.hljs-template-tag,
.hljs-template-variable,
.hljs-type,
.hljs-variable.language_ {
/* prettylights-syntax-keyword */
color: var(--hljs-syntax-keyword-color);
}

.hljs-title,
.hljs-title.class_,
.hljs-title.class_.inherited__,
.hljs-title.function_ {
/* prettylights-syntax-entity */
color: var(--hljs-syntax-entity-color)
}

.hljs-attr,
.hljs-attribute,
.hljs-literal,
.hljs-meta,
.hljs-number,
.hljs-operator,
.hljs-variable,
.hljs-selector-attr,
.hljs-selector-class,
.hljs-selector-id {
/* prettylights-syntax-constant */
color: var(--hljs-syntax-constant-color);
}

.hljs-regexp,
.hljs-string,
.hljs-meta .hljs-string {
/* prettylights-syntax-string */
color: var(--hljs-syntax-string-color);
}

.hljs-built_in,
.hljs-symbol {
/* prettylights-syntax-variable */
color: var(--hljs-syntax-variable-color);
}

.hljs-comment,
.hljs-code,
.hljs-formula {
/* prettylights-syntax-comment */
color: var(--hljs-syntax-comment-color);
}

.hljs-name,
.hljs-quote,
.hljs-selector-tag,
.hljs-selector-pseudo {
/* prettylights-syntax-entity-tag */
color: var(--hljs-syntax-entity-tag-color);
}

.hljs-subst {
/* prettylights-syntax-storage-modifier-import */
color: var(--hljs-syntax-storage-modifier-import-color);
}

.hljs-section {
/* prettylights-syntax-markup-heading */
color: var(--hljs-syntax-markup-heading-color);
font-weight: bold
}

.hljs-bullet {
/* prettylights-syntax-markup-list */
color: var(--hljs-syntax-markup-list-color);
}

.hljs-emphasis {
/* prettylights-syntax-markup-italic */
color: var(--hljs-syntax-markup-italic-color);
font-style: italic
}

.hljs-strong {
/* prettylights-syntax-markup-bold */
color: var(--hljs-syntax-markup-bold-color);
font-weight: bold
}

.hljs-addition {
/* prettylights-syntax-markup-inserted */
color: var(--hljs-syntax-markup-inserted-color);
background-color: var(--hljs-syntax-markup-inserted-background-color);
}

.hljs-deletion {
/* prettylights-syntax-markup-deleted */
color: var(--hljs-syntax-markup-deleted-color);
background-color: var(--hljs-syntax-markup-deleted-background-color);
}

.hljs-char.escape_,
.hljs-link,
.hljs-params,
.hljs-property,
.hljs-punctuation,
.hljs-tag {
/* purposely ignored */
}
}
31 changes: 29 additions & 2 deletions src/components/NcRichText/richtext.scss
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**

/**
* Styles are extracted to extract scss to dist folder, too.
*/

@import './highlight.scss';

li.task-list-item > ul,
li.task-list-item > ol,
li.task-list-item > li,
Expand Down Expand Up @@ -216,3 +218,28 @@ li.task-list-item > pre {
color: var(--color-text-lighter);
}
}

/**
* Highlight code syntax in code blocks
*/
.rich-text--wrapper-markdown {
@include highlight-rules;
}

@media (prefers-color-scheme: light) {
.rich-text--wrapper-markdown {
@include highlight-light-colors;
}
[data-theme-dark] .rich-text--wrapper-markdown {
@include highlight-dark-colors;
}
}

@media (prefers-color-scheme: dark) {
.rich-text--wrapper-markdown {
@include highlight-dark-colors;
}
[data-theme-light] .rich-text--wrapper-markdown {
@include highlight-light-colors;
}
}
16 changes: 16 additions & 0 deletions tests/unit/components/NcRichText/NcRichText.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import { mount } from '@vue/test-utils'
import NcRichText from '../../../../src/components/NcRichText/NcRichText.vue'
import { nextTick } from 'vue'

describe('NcRichText', () => {
it('renders a message and responds correctly to props changes', async () => {
Expand Down Expand Up @@ -207,4 +208,19 @@ describe('NcRichText', () => {
await checkbox.vm.$emit('update:checked', true)
expect(wrapper.emitted()['interact:todo']).toBeTruthy()
})

it('properly defines syntax in code blocks and highlights it', async () => {
const wrapper = mount(NcRichText, {
propsData: {
text: '```js\nconsole.log(\'hello world\')\n```',
autolink: false,
useExtendedMarkdown: true,
},
})
expect(wrapper.text()).toEqual('console.log(\'hello world\')')
expect(wrapper.find('code').classes()).toEqual(['language-js'])
await nextTick()
await nextTick()
expect(wrapper.find('code').classes()).toEqual(['hljs', 'language-js'])
})
})

0 comments on commit 8d47b86

Please sign in to comment.