133 lines
2.6 KiB
Markdown
133 lines
2.6 KiB
Markdown
```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(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/&/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')
|
|
|
|
``` |
JavaScript
98.9%
CSS
1.1%