chore: add custom variable

This commit is contained in:
Joel 2025-09-04 18:41:48 +08:00
parent b1e123c3aa
commit 783b78cc0a
2 changed files with 40 additions and 36 deletions

View File

@ -41,7 +41,6 @@ const FormContentPreview: FC<Props> = ({
<div className='max-h-[calc(100vh-167px)] overflow-y-auto px-4'>
<Markdown
content={content}
customDisallowedElements={['variable']}
rehypePlugins={[rehypeVariable]}
customComponents={{
variable: ({ node, ...props }: any) => (

View File

@ -1,45 +1,50 @@
import React from 'react'
const regex = /\{\{#(.+?)#\}\}/g
export function rehypeVariable() {
return (tree: any) => {
const iterate = (node: any) => {
console.log(node.type)
const iterate = (node: any, index: number, parent: any) => {
const value = node.value
if(node.type === 'text')
console.log(value)
if(node.type === 'text' && regex.test(value)) {
let m: RegExpExecArray | null
let last = 0
const parts: any[] = []
regex.lastIndex = 0
while ((m = regex.exec(value))) {
if (m.index > last)
parts.push({ type: 'text', value: value.slice(last, m.index) })
parts.push({
type: 'element',
tagName: 'variable', // variable is also be cleared
properties: { path: m[0].trim() },
})
last = m.index + m[0].length
}
if (parts.length) {
if (last < value.length)
parts.push({ type: 'text', value: value.slice(last) })
parent.children.splice(index, 1, ...parts)
}
}
if (node.children) {
node.children.forEach((item: any, i: number) => {
iterate(item, i, node)
})
}
}
tree.children.forEach(iterate)
// visit(tree, 'text', (node: any, index: number, parent: any) => {
// if (!parent || parent.type !== 'element') return
// const tag = parent.tagName
// if (tag === 'code' || tag === 'pre') return
// const value: string = node.value
// const regex = /\{\{#\$(.+?)#\}\}/g
// let m: RegExpExecArray | null
// let last = 0
// const parts: any[] = []
// while ((m = regex.exec(value))) {
// if (m.index > last)
// parts.push({ type: 'text', value: value.slice(last, m.index) })
// parts.push({
// type: 'element',
// tagName: 'variable',
// properties: { path: m[1].trim() },
// children: [],
// })
// last = m.index + m[0].length
// }
// if (!parts.length) return
// if (last < value.length)
// parts.push({ type: 'text', value: value.slice(last) })
// parent.children.splice(index, 1, ...parts)
// })
tree.children.forEach((item: any, i: number) => {
iterate(item, i, tree)
}, tree)
}
}
export const Variable: React.FC<{ path: string }> = ({ path }) => {
return <span style={{ color: 'red', fontWeight: 700 }}>{path}</span>
return <span style={{ color: 'blue', fontWeight: 700 }}>{path.replaceAll('.', '/')}</span>
}