support custom dynamic highlight color

This commit is contained in:
Felix Roos 2022-04-29 21:27:12 +02:00
parent 9e46b3cd00
commit 4fcec82917

View File

@ -6,12 +6,7 @@ import { javascript } from '@codemirror/lang-javascript';
// import { materialPalenight } from 'codemirror6-themes'; // import { materialPalenight } from 'codemirror6-themes';
import { materialPalenight } from './themes/material-palenight'; import { materialPalenight } from './themes/material-palenight';
const highlightMark = Decoration.mark({ class: 'cm-highlight' });
export const setHighlights = StateEffect.define(); export const setHighlights = StateEffect.define();
const highlightTheme = EditorView.baseTheme({
'.cm-highlight': { outline: '1px solid #FFCA28' },
// '.cm-highlight': { background: '#FFCA28' },
});
const highlightField = StateField.define({ const highlightField = StateField.define({
create() { create() {
return Decoration.none; return Decoration.none;
@ -22,16 +17,19 @@ const highlightField = StateField.define({
if (e.is(setHighlights)) { if (e.is(setHighlights)) {
highlights = Decoration.set( highlights = Decoration.set(
e.value e.value
.flatMap((event) => event.context.locations || []) .flatMap((hap) =>
.map(({ start, end }) => { (hap.context.locations || []).map(({ start, end }) => {
let from = tr.newDoc.line(start.line).from + start.column; const color = hap.context.color || '#FFCA28';
let to = tr.newDoc.line(end.line).from + end.column; let from = tr.newDoc.line(start.line).from + start.column;
const l = tr.newDoc.length; let to = tr.newDoc.line(end.line).from + end.column;
if (from > l || to > l) { const l = tr.newDoc.length;
return; if (from > l || to > l) {
} return; // dont mark outside of range, as it will throw an error
return highlightMark.range(from, to); }
}) const mark = Decoration.mark({ attributes: { style: `outline: 1px solid ${color}` } });
return mark.range(from, to);
}),
)
.filter(Boolean), .filter(Boolean),
true, true,
); );
@ -62,7 +60,6 @@ export default function CodeMirror({ value, onChange, onViewChanged, onCursor, o
javascript(), javascript(),
materialPalenight, materialPalenight,
highlightField, highlightField,
highlightTheme,
// theme, language, ... // theme, language, ...
]} ]}
/> />