```html
${this.lang}
${this.#code.map(s => html`${raw(s)}`)}
``` ```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('') && txt.endsWith('')) { txt = txt.slice(5, -6).trim() } else if (this.firstElementChild?.tagName === 'TEXTAREA') { txt = this.firstElementChild.value.trim() } else if (txt.startsWith('
') && txt.endsWith('
')) { txt = trim(txt.slice(5, -6)) } else { txt = trim(txt) } this.textContent = '' if (txt) { nextTick(_ => { this.code = txt }) } } render() { let foo = html`
${this.#code.map(s => html`${s}`)}
` return html`
${this.lang}
${this.#code.map(s => html`${raw(s)}`)}
` } } Code.reg('code') ```