Code syntax highlight Web Component
npm i code-syntax
|
pnpm add code-syntax
|
yarn add code-syntax
|
web
view source
import 'code-syntax/themes/default.css'
import 'plenty-themes/cobalt2.css'
import 'plenty-themes/laser.css'
import { CodeSyntaxElement, languages } from 'code-syntax'
customElements.define('code-syntax', CodeSyntaxElement)
languages.js = import('code-syntax/languages/js')
document.body.innerHTML = `
<code-syntax id="demo" language="js" theme="laser">class Vector {
x: number
y: number
constructor(x: number, y: number) {
this.x = x
this.y = y
}
add(v: Vector): Vector {
return new Vector(this.x + v.x, this.y + v.y)
}
}
</code-syntax>
`
CodeSyntaxElement
constructor
()
new CodeSyntaxElement
() code
HTMLElement
codeHTML
= String
string
codeRawText
string
highlight
s
string
(s) =>
language
= String
string
onTextContent
textContent
string
(textContent) =>
syntax
theme
= String
string
PatchOptions
theme
string
getLanguage
(el)
el
Element
getLanguage(el) =>
SyntaxDefinition
RegExpMap
Record<string, RegExpMapped>
RegExpMapped
RegExp & {
keys
Set<string>
map
SyntaxOrImport
SyntaxDefinition | Promise<{
default
languages
= {}
Record<string, SyntaxOrImport>
compile
(def, keys) – Compiles a syntax definition.
const r = await compile({
foo: /[a-z]/,
bar: /[0-9]/,
})
def
– The syntax definition to compile. Can be a promise returned by import()
.
keys
= ...
Set<string>
compile(def, keys) =>
patchElements
(elements, Partial<PatchOptions>)
elements
Element []
patchElements(elements, Partial<PatchOptions>) =>
patchPreCodeElements
(opts)
opts
Partial<PatchOptions>
patchPreCodeElements(opts) =>
syntax
(regexp, s) – Syntax highlights a string as html with the given syntax.
const regexp = await compile({
foo: /[a-z]+/,
bar: [
/[0-9]+/,
{
bar: /[0-5]+/,
},
],
})
const html = syntax(regexp, 'hello 123 789 world')
regexp
– The syntax definition returned by compile()
RegExp | RegExpMapped
s
– The string to highlight.
string
syntax(regexp, s) =>
All contributions are welcome!