代码块, 代码高亮,markdown解析器大重构

master
yutent 2023-04-24 17:34:01 +08:00
parent 856d23c8e5
commit 93afc6adbf
6 changed files with 256 additions and 53 deletions

View File

@ -8,23 +8,23 @@ const DOCTYPE_EXP = /<\!DOCTYPE html>/
const TAG_START_EXP = /<([\w\-]+)([\w\W]*?)>/g const TAG_START_EXP = /<([\w\-]+)([\w\W]*?)>/g
const TAG_END_EXP = /<\/([\w\-]+)>/g const TAG_END_EXP = /<\/([\w\-]+)>/g
const TAG_ATTR_EXP = const TAG_ATTR_EXP =
/[@a-zA-Z\-.]+=(["'])[^"]+\1|[@a-zA-Z\-.]+=[a-zA-Z0-9]+|[@a-zA-Z\-.]+/g /[@a-zA-Z\-.:#]+=(["'])[^"]+\1|[@a-zA-Z\-.:#]+=[a-zA-Z0-9]+|[@a-zA-Z\-.:#]+=\$\{.+\}|[@a-zA-Z\-.]+/g
const TAG_CM_EXP = /<!--([\w\W]*?)-->/g const TAG_CM_EXP = /<!--([\w\W]*?)-->/g
const SCRIPT_TAG = /(<script[^>]*?>)([\w\W]*?)(<\/script>)/g const SCRIPT_TAG = /(<script[^>]*?>)([\w\W]*?)(<\/script>)/g
const IMPORT_1 = /import (['"])([^'"]*?)\1/g const IMPORT_1 = /import (['"])([^'"]*?)\1/g
const IMPORT_2 = /import ([\w\W]*?) from (['"])([^'"]*?)\2/g const IMPORT_2 = /import ([\w\W]*?) from (['"])([^'"]*?)\2/g
const IMPORT_3 = /import\((['"])([^'"]*?)\1\)/g const IMPORT_3 = /import\((['"])([^'"]*?)\1\)/g
const KEYWOWRD1 = const KEYWOWRD1 =
/\b(var|const|let|function|for|switch|with|if|else|export|import|assert|as|from|async|await|break|continue|return|class|try|catch|throw|new|while|this|super|default|case|debugger|delete|do|goto|in|static|get|set|public|private|protected|package|typeof|void)\b/g /\b(var|const|let|function|for|switch|with|if|else|export|import|assert|as|from|async|await|break|continue|return|class|extends|try|catch|throw|new|while|this|super|default|case|debugger|delete|do|goto|in|static|get|set|public|private|protected|package|typeof|void)\b/g
const KEYWOWRD2 = /\s(=|-|\+|\/|\*|<|>|%)\s/g const KEYWOWRD2 = /\s(=|-|\+|\/|\*|<|>|%)\s/g
const KEYWOWRD3 = const KEYWOWRD3 =
/(\+\=|-=|\/=|\*=|--|\+\+|===|==|=>|\.\.\.|\.|\?\.|\?\?|&&|\|\|)/g /(\+\=|-=|\/=|\*=|--|\+\+|===|==|=>|\.\.\.|\.|\?\.|\?\?|&&|\|\|)/g
const BUILDIN1 = /\b(null|undefined|true|false|NaN|Infinity)\b/g const BUILDIN1 = /\b(null|undefined|true|false|NaN|Infinity)\b/g
const BUILDIN2 = const BUILDIN2 =
/\b(Object|String|Array|Boolean|Number|Function|class|Promise|Map|Set|WeakMap|WeakSet|URL)\b/g /\b(Object|String|Array|Boolean|Number|Function|Promise|Map|Set|WeakMap|WeakSet|URL)\b/g
const STR = /(['"`])(.*?)(?<!\\)\1/g const STR = /(['"`])(.*?)(?<!\\)\1/g
const NUM = /\b(\d+)\b/g const NUM = /\b(\d+)\b/g
const FN = /([\.\s])([a-zA-Z$_#][\da-zA-Z_]*)\s?(\(.*?\)?)/g const FN = /([\.\s])((?!if|for)[a-zA-Z$_#][\da-zA-Z_]*)\s?(\(.*?\)?)/g
const CM1 = /(?=\s)?([ ]*\/\/.*)|(^\/\/.*)/g const CM1 = /(?=\s)?([ ]*\/\/.*)|(^\/\/.*)/g
const CM2 = /\/\*([\w\W]*?)\*\//g const CM2 = /\/\*([\w\W]*?)\*\//g
const EXP = /([=\(][ ]*)\/(.+?)\/([gmi]*)/g const EXP = /([=\(][ ]*)\/(.+?)\/([gmi]*)/g
@ -65,11 +65,11 @@ function parseJs(code) {
}` }`
}) })
.replace(FN, '$1[fn]$2[/fn]$3') .replace(FN, '$1[fn]$2[/fn]$3')
.replace(KEYWOWRD1, '[key]<em>$1</em>[/key]') .replace(KEYWOWRD1, '[key]$1[/key]')
.replace(KEYWOWRD2, ' [key]$1[/key] ') .replace(KEYWOWRD2, ' [key]$1[/key] ')
.replace(KEYWOWRD3, '[key]$1[/key]') .replace(KEYWOWRD3, '[key]$1[/key]')
.replace(BUILDIN1, '[num]<em>$1</em>[/num]') .replace(BUILDIN1, '[buildin]$1[/buildin]')
.replace(BUILDIN2, '[type]<strong><em>$1</em></strong>[/type]') .replace(BUILDIN2, '[type]$1[/type]')
.replace(NUM, '[num]$1[/num]') .replace(NUM, '[num]$1[/num]')
.replace(STR, (m, pun, str) => { .replace(STR, (m, pun, str) => {
if (str.startsWith('[link]') && str.endsWith('[/link]')) { if (str.startsWith('[link]') && str.endsWith('[/link]')) {
@ -112,16 +112,18 @@ function parseJs(code) {
function rebuild(code) { function rebuild(code) {
// console.log(code) // console.log(code)
return code return code
.replace(/\[(\/?)tag\]/g, (m, s) => (s ? '</i>' : '<i class="r">')) .replace(/\[(\/?)tag\]/g, (m, s) => (s ? '</c>' : '<c class="t-tag">'))
.replace(/\[(\/?)attr\]/g, (m, s) => (s ? '</i>' : '<i class="b">')) .replace(/\[(\/?)attr\]/g, (m, s) => (s ? '</c>' : '<c class="t-attr">'))
.replace(/\[(\/?)str\]/g, (m, s) => (s ? '</i>' : '<i class="g">')) .replace(/\[(\/?)str\]/g, (m, s) => (s ? '</c>' : '<c class="t-str">'))
.replace(/\[(\/?)key\]/g, (m, s) => (s ? '</i>' : '<i class="r">')) .replace(/\[(\/?)key\]/g, (m, s) => (s ? '</c>' : '<c class="t-keyword">'))
.replace(/\[(\/?)str\]/g, (m, s) => (s ? '</i>' : '<i class="g">')) .replace(/\[(\/?)num\]/g, (m, s) => (s ? '</c>' : '<c class="t-num">'))
.replace(/\[(\/?)num\]/g, (m, s) => (s ? '</i>' : '<i class="pp">')) .replace(/\[(\/?)fn\]/g, (m, s) => (s ? '</c>' : '<c class="t-fn">'))
.replace(/\[(\/?)fn\]/g, (m, s) => (s ? '</i>' : '<i class="b">')) .replace(/\[(\/?)cm\]/g, (m, s) => (s ? '</c>' : '<c class="t-comment">'))
.replace(/\[(\/?)cm\]/g, (m, s) => (s ? '</i>' : '<i class="gr">')) .replace(/\[(\/?)buildin\]/g, (m, s) =>
.replace(/\[(\/?)type\]/g, (m, s) => (s ? '</i>' : '<i class="o">')) s ? '</c>' : '<c class="t-buildin">'
.replace(/\[(\/?)link\]/g, (m, s) => (s ? '</i>' : '<i class="link">')) )
.replace(/\[(\/?)type\]/g, (m, s) => (s ? '</c>' : '<c class="t-type">'))
.replace(/\[(\/?)link\]/g, (m, s) => (s ? '</c>' : '<c class="t-link">'))
} }
export function colorMd(code) { export function colorMd(code) {
@ -169,6 +171,10 @@ export function colorHtml(code) {
t = t.split('=') t = t.split('=')
let a = t.shift() let a = t.shift()
let b = t.join('=').replace(/(\n+)/g, '[/str]\n[str]') let b = t.join('=').replace(/(\n+)/g, '[/str]\n[str]')
if (b.startsWith('${') && b.endsWith('}')) {
return `[attr]${a}[/attr]=${b}`
}
return `[attr]${a}[/attr]=[str]${b}[/str]` return `[attr]${a}[/attr]=[str]${b}[/str]`
} else { } else {
return `[attr]${t}[/attr]` return `[attr]${t}[/attr]`
@ -185,22 +191,66 @@ export function colorHtml(code) {
return rebuild(code) return rebuild(code)
} }
// css 不走rebuild, 因为css有 [xxx] 这种选择器语法
export function colorCss(code) { export function colorCss(code) {
code = code code = code
.replace(STR, '<cc class="t-str">$1$2$1</cc>')
.replace(/(\$[a-zA-Z\d_]+)/g, '<c class="t-var">$1</c>')
.replace(/(\-\-[a-z\d]+\-[a-z\d]+)/g, '<c class="t-const">$1</c>')
.replace( .replace(
/:(hover|after|active|last\-child|first\-child)/g, /:(hover|after|active|last\-child|first\-child|nth\-child)/g,
'<i class="o">:$1</i>' '<c class="t-buildin">:$1</c>'
) )
.replace(/([\.#])([\w\-]+)/g, '<i class="gr">$1</i><i class="o">$2</i>')
.replace( .replace(
/([a-zA-Z\-]+):\s?([^;\n]+);?/g, /(?=\s)?([ ][\.#])([\w\-]+)/g,
'<b class="gr">$1: </b><i class="b">$2</i><i class="gr">;</i>' '<c class="t-comment">$1</c><c class="t-buildin">$2</c>'
) )
.replace(/([,\{\}])/g, '<i class="gr">$1</i>') .replace(/([a-zA-Z\-]+):(\s?[^\n]+)/g, (m, k, v) => {
.replace(/&/g, '<i class="r">&</i>') if (v.trim() !== '(' && !v.endsWith('</cc>;')) {
v = v.replace(
/([^,;]*)([,;]?$)/,
'<c class="t-num">$1</c><c class="t-comment">$2</c>'
)
}
return `<c class="t-comment"><b>${k}</b>:</c>${v}`
})
.replace(/([,\{\}])/g, '<c class="t-comment">$1</c>')
.replace(/\b(in|from|to|throught)\b/g, '<c class="t-keyword">$1</c>')
.replace(/(&|@use|@each|@for)/g, '<c class="t-keyword">$1</c>')
.replace(/<cc class="t-str">(.*?)<\/cc>/g, (m, str) => {
str = str.replace(/<\/?\w+[^>]*?>/g, '')
return `<c class="t-str">${str}</c>`
})
return code return code
} }
export function colorJs(code) { export function colorJs(code) {
return rebuild(parseJs(code)) let cache = {}
let num = 160 // to hex is a0
let restore = str => {
for (let k in cache) {
if (str.includes(k)) {
str = str.replace(k, cache[k])
delete cache[k]
}
}
return str
}
// 匹配单行的
code = code.replace(/html`(.*)`/g, (m, v) => {
let _key = '' + (num++).toString(16)
cache[_key] = `html\`${colorHtml(v)}\``
return _key
})
// 匹配多行的
code = code.replace(/html`([\w\W]*?)`/g, (m, v) => {
let _key = '' + (num++).toString(16)
cache[_key] = restore(`html\`${colorHtml(v)}\``)
return _key
})
return restore(rebuild(parseJs(code)))
} }

View File

@ -104,7 +104,7 @@ class Code extends Component {
cursor: text; cursor: text;
counter-reset: code; counter-reset: code;
code { > code {
display: block; display: block;
position: relative; position: relative;
min-height: 20px; min-height: 20px;
@ -125,33 +125,42 @@ class Code extends Component {
counter-increment: code; counter-increment: code;
} }
i { .t-tag,
font-style: normal; .t-keyword,
} .t-const {
.r {
color: var(--color-red-2); color: var(--color-red-2);
} }
.b { .t-attr,
.t-fn,
.t-var {
color: var(--color-blue-2); color: var(--color-blue-2);
} }
.g { .t-str {
color: var(--color-green-2); color: var(--color-green-2);
} }
.gr { .t-comment {
color: var(--color-grey-2); color: var(--color-grey-2);
} }
.o {
.t-type {
font-weight: bold;
color: var(--color-orange-1); color: var(--color-orange-1);
} }
.pp { .t-num,
.t-buildin {
color: #a46ad3; color: #a46ad3;
} }
.link { .t-link {
font-style: italic;
text-decoration: underline; text-decoration: underline;
color: var(--color-grey-2); color: var(--color-grey-2);
} }
.t-buildin,
.t-keyword,
.t-type,
.t-link,
.t-comment {
font-style: italic;
}
} }
} }
` `

View File

@ -205,8 +205,8 @@ class Tool {
var qlink var qlink
if (isCodeBlock) { if (isCodeBlock) {
it = it it = it
.replace(/<(\/?)([a-z][a-z\d\-]*?)([^>]*?)>/g, '&lt;$1$2$3&gt;')
.replace('\\`\\`\\`', '```') .replace('\\`\\`\\`', '```')
.replace(/<(\/?)xmp>/g, '&lt;$1xmp&gt;') // 转义这个特殊标签
} else { } else {
if (Helper.isTable(tmp) && !isTable) { if (Helper.isTable(tmp) && !isTable) {
var thead = tmp.split('|') var thead = tmp.split('|')
@ -261,6 +261,7 @@ class Tool {
list.push(tmp) list.push(tmp)
} }
} }
return new this(list, links) return new this(list, links)
} }
@ -595,5 +596,5 @@ class Tool {
} }
export default function (str) { export default function (str) {
return Tool.init(str).parse() return Tool.init(str).parse() //.replace(/\\</g, '<').replace(/\\>/g, '>')
} }

View File

@ -193,6 +193,7 @@ class Markd extends Component {
` `
render() { render() {
// console.log(md2html(this.code))
return html`<div class="container">${raw(md2html(this.code))}</div>` return html`<div class="container">${raw(md2html(this.code))}</div>`
} }
} }

View File

@ -277,7 +277,7 @@ class Lang extends Component {
cursor: text; cursor: text;
counter-reset: code; counter-reset: code;
code { > code {
display: block; display: block;
position: relative; position: relative;
min-height: 20px; min-height: 20px;
@ -298,33 +298,42 @@ class Lang extends Component {
counter-increment: code; counter-increment: code;
} }
i { .t-tag,
font-style: normal; .t-keyword,
} .t-const {
.r {
color: var(--color-red-2); color: var(--color-red-2);
} }
.b { .t-attr,
.t-fn,
.t-var {
color: var(--color-blue-2); color: var(--color-blue-2);
} }
.g { .t-str {
color: var(--color-green-2); color: var(--color-green-2);
} }
.gr { .t-comment {
color: var(--color-grey-2); color: var(--color-grey-2);
} }
.o {
.t-type {
font-weight: bold;
color: var(--color-orange-1); color: var(--color-orange-1);
} }
.pp { .t-num,
.t-buildin {
color: #a46ad3; color: #a46ad3;
} }
.link { .t-link {
font-style: italic;
text-decoration: underline; text-decoration: underline;
color: var(--color-grey-2); color: var(--color-grey-2);
} }
.t-buildin,
.t-keyword,
.t-type,
.t-link,
.t-comment {
font-style: italic;
}
} }
} }
` `

133
test.md Normal file
View File

@ -0,0 +1,133 @@
```html
<div class="code-box">
<header class="title">
<section><i></i><i></i><i></i></section>
<section>${this.lang}</section>
<wc-icon
title="复制"
class="act"
name="doc"
@click=${this.copyCode}
></wc-icon>
</header>
<div class="code-block">
${this.#code.map(s => html`<code>${raw(s)}</code>`)}
</div>
</div>
```
```js
import { html, raw, css, Component, nextTick } from '@bd/core'
import { colorHtml, colorJs, colorCss, colorMd } from './colorful.js'
import '../icon/index.js'
import '../layer/index.js'
function trim(str) {
return str
.trim()
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&')
}
class Code extends Component {
static props = {
code: {
type: String,
default: '',
attribute: false,
observer(v) {
this.setCode(v.trim())
}
},
lang: ''
}
#code = []
setCode(txt, a) {
let lang = this.lang
switch (lang) {
case 'js':
case 'javascript':
case 'ts':
case 'typescript':
txt = colorJs(txt)
break
case 'html':
txt = colorHtml(txt)
break
case 'css':
case 'scss':
case 'less':
txt = colorCss(txt)
break
case 'md':
case 'markdown':
txt = colorMd(txt)
break
}
this.#code = txt.split('\n')
}
copyCode() {
navigator.clipboard.writeText(this.code)
layer.toast('复制到粘贴板成功', 'success')
}
mounted() {
var txt = this.innerHTML || this.textContent
txt = txt.trim().replace(/^[\r\n]|\s{2,}$/g, '')
if (txt.startsWith('<xmp>') && txt.endsWith('</xmp>')) {
txt = txt.slice(5, -6).trim()
} else if (this.firstElementChild?.tagName === 'TEXTAREA') {
txt = this.firstElementChild.value.trim()
} else if (txt.startsWith('<pre>') && txt.endsWith('</pre>')) {
txt = trim(txt.slice(5, -6))
} else {
txt = trim(txt)
}
this.textContent = ''
if (txt) {
nextTick(_ => {
this.code = txt
})
}
}
render() {
let foo = html`<section>${this.#code.map(s => html`<a>${s}</a>`)}</section>`
return html`
<div class="code-box">
<header class="title">
<section><i></i><i></i><i></i></section>
<section>${this.lang}</section>
<wc-icon
title="复制"
class="act"
name="doc"
@click=${this.copyCode}
></wc-icon>
</header>
<div class="code-block">
${this.#code.map(s => html`<code>${raw(s)}</code>`)}
</div>
</div>
`
}
}
Code.reg('code')
```