ErnSur
August 2, 2024, 2:49pm
1
I have documents with content similar to this:
Hello <note>Frank</note>. <color=red>Red Text</color>.
I would like to create a plugin that simply renders content of those custom tags with additional styling and hides tags in reading mode with live preview support.
From my research I’ve gathered that I probably need to create a Editor Extension (if I want to add a live preview support).
Do any of you kind people have any pointers or resources (i.e., existing plugins that do something similar) that I could use as a reference?
Resources:
CodeMirror official system guide will tell you the mechanism of codemirror and its extension.
Obsidian Dev Doc has an clear example of how to combine codemirror extension and obsidian plugin together.
CodeMirror official example of decoration . A replace decoration may be what you need.
I wrote an example too:
import {
Decoration, DecorationSet, EditorView, ViewPlugin,
ViewUpdate, WidgetType, MatchDecorator
} from "@codemirror/view"
import { Prec } from "@codemirror/state"
// a custom decoration of widget type
class Color extends WidgetType {
constructor(private color: string, private content: string) {
super()
}
toDOM(view: EditorView): HTMLElement {
const el = document.createElement("span");
el.innerHTML = this.content;
el.style.color = this.color
return el;
}
}
// match a text pattern to be replace to a widget
const matcher = new MatchDecorator({
regexp: /<color (.*?)>(.*?)<\/color>/g,
decoration: match => Decoration.replace({
widget: new Color(match[1], match[2])
})
})
// the extension, a ViewPlugin
export const customTag = Prec.high(ViewPlugin.fromClass(class {
dacorations: DecorationSet;
constructor(view: EditorView){
this.dacorations = matcher.createDeco(view)
}
update(update: ViewUpdate) {
const cursor = update.state.selection.main;
this.dacorations = matcher
.updateDeco(update, this.dacorations)
.update({
filter: (from, to) => (from >= cursor.to || to <= cursor.from)
})
}
}, {
decorations: v => v.dacorations
}))
Effect is like:
1 Like