Skip to content
Prev Previous commit
Next Next commit
feat(markown): parse link to snippets
  • Loading branch information
antonreshetov committed Aug 13, 2022
commit 678d2716afd9ece6a70a26b2c894a17bfc230146
28 changes: 20 additions & 8 deletions src/renderer/components/markdown/TheMarkdown.vue
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ import { computed, onBeforeUnmount, onMounted, ref, watch, nextTick } from 'vue'
import { ipc, store } from '@/electron'
import { marked } from 'marked'
import mermaid from 'mermaid'
import { useHljsTheme } from '@/composable'
import { useHljsTheme, goToSnippet } from '@/composable'
import { useCodemirror } from '@/composable/codemirror'

import { nanoid } from 'nanoid'

const isDev = import.meta.env.DEV
Expand Down Expand Up @@ -75,7 +74,12 @@ const init = () => {
}
},
link (href: string, title: string, text: string) {
return `<a href="${href}" class="external">${text}</a>`
if (/^masscode:\/\/snippets/.test(href)) {
const id = href.split('/').pop()
return `<a href="${href}" class="snippet-link" data-snippet-id="${id}">${text}</a>`
} else {
return `<a href="${href}" class="external">${text}</a>`
}
}
}

Expand Down Expand Up @@ -181,9 +185,11 @@ const render = () => {
'type',
'checked',
'disabled',
'id'
'id',
'data-*'
]
}
},
allowedSchemes: ['http', 'https', 'masscode']
})

const re = /src="\.\//g
Expand All @@ -196,12 +202,18 @@ const render = () => {
renderedHtml.value = html
}

const openExternal = (e: Event) => {
const onLink = async (e: Event) => {
const el = e.target as HTMLAnchorElement
e.preventDefault()

if (el.classList.contains('external')) {
ipc.invoke('main:open-url', el.href)
}

if (el.classList.contains('snippet-link')) {
const { snippetId } = el.dataset
if (snippetId) goToSnippet(snippetId)
}
}

const height = computed(() => {
Expand Down Expand Up @@ -257,11 +269,11 @@ watch(
init()

onMounted(() => {
document.addEventListener('click', openExternal)
document.addEventListener('click', onLink)
})

onBeforeUnmount(() => {
document.removeEventListener('click', openExternal)
document.removeEventListener('click', onLink)
})

window.addEventListener('resize', () => {
Expand Down