@codemirror/view#EditorView TypeScript Examples
The following examples show how to use
@codemirror/view#EditorView.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PumlView.ts From obsidian-plantuml with MIT License | 7 votes |
extensions: Extension[] = [
highlightActiveLine(),
highlightActiveLineGutter(),
highlightSelectionMatches(),
drawSelection(),
keymap.of([...defaultKeymap, indentWithTab]),
history(),
search(),
EditorView.updateListener.of(v => {
if(v.docChanged) {
this.requestSave();
this.renderPreview();
}
})
]
Example #2
Source File: code.tsx From nota with MIT License | 6 votes |
theme = EditorView.theme({
".cm-scroller": {
fontFamily: "Inconsolata, monospace",
},
".cm-gutters": {
background: "none",
border: "none",
},
".cm-lineNumbers .cm-gutterElement": {
fontSize: "10px",
paddingTop: "3px",
paddingRight: "7px",
minWidth: "10px",
},
".cm-highlight": {
padding: "0 2px",
margin: "-1px -2px",
borderRadius: "2px",
},
})
Example #3
Source File: CodeMirrorWrapper.tsx From console with GNU Affero General Public License v3.0 | 6 votes |
darkTheme = EditorView.theme(
{
"&": {
backgroundColor: "#282a36",
color: "#ffb86c",
},
".cm-gutter.cm-foldGutter": {
borderRight: "1px solid #eaeaea",
},
".cm-gutterElement": {
fontSize: "13px",
},
".cm-line": {
fontSize: "13px",
"& .ͼd, & .ͼc": {
color: "#8e6cef",
},
},
"& .ͼb": {
color: "#2781B0",
},
".cm-activeLine": {
backgroundColor: "#44475a",
},
".cm-matchingBracket": {
backgroundColor: "#842de5",
color: "#ff79c6",
},
".cm-selectionLayer .cm-selectionBackground": {
backgroundColor: "green",
},
},
{
dark: true,
}
)
Example #4
Source File: CMTheme.tsx From fe-v5 with Apache License 2.0 | 6 votes |
darkTheme = EditorView.theme(
{
'.cm-content': {
caretColor: '#fff',
},
'.cm-tooltip.cm-completionInfo': {
backgroundColor: '#333338',
},
'.cm-tooltip > .cm-completionInfo.cm-completionInfo-right': {
'&:before': {
borderRightColor: '#333338',
},
},
'.cm-tooltip > .cm-completionInfo.cm-completionInfo-left': {
'&:before': {
borderLeftColor: '#333338',
},
},
'.cm-line': {
'&::selection': {
backgroundColor: '#767676',
},
'& > span::selection': {
backgroundColor: '#767676',
},
},
},
{ dark: true },
)
Example #5
Source File: EmbedDecoration.ts From obsidian-plantuml with MIT License | 6 votes |
////////////////
// Utility Code
////////////////
// Generic helper for creating pairs of editor state fields and
// effects to model imperatively updated decorations.
// source: https://github.com/ChromeDevTools/devtools-frontend/blob/8f098d33cda3dd94b53e9506cd3883d0dccc339e/front_end/panels/sources/DebuggerPlugin.ts#L1722
function defineStatefulDecoration(): {
update: StateEffectType<DecorationSet>;
field: StateField<DecorationSet>;
} {
const update = StateEffect.define<DecorationSet>();
const field = StateField.define<DecorationSet>({
create(): DecorationSet {
return Decoration.none;
},
update(deco, tr): DecorationSet {
return tr.effects.reduce((deco, effect) => (effect.is(update) ? effect.value : deco), deco.map(tr.changes));
},
provide: field => EditorView.decorations.from(field),
});
return {update, field};
}
Example #6
Source File: CMTheme.tsx From fe-v5 with Apache License 2.0 | 6 votes |
darkTheme = EditorView.theme(
{
'.cm-content': {
caretColor: '#fff',
},
'.cm-tooltip.cm-completionInfo': {
backgroundColor: '#333338',
},
'.cm-tooltip > .cm-completionInfo.cm-completionInfo-right': {
'&:before': {
borderRightColor: '#333338',
},
},
'.cm-tooltip > .cm-completionInfo.cm-completionInfo-left': {
'&:before': {
borderLeftColor: '#333338',
},
},
'.cm-line': {
'&::selection': {
backgroundColor: '#767676',
},
'& > span::selection': {
backgroundColor: '#767676',
},
},
},
{ dark: true },
)
Example #7
Source File: code.tsx From nota with MIT License | 6 votes |
highlightField = StateField.define<DecorationSet>({
create() {
return Decoration.none;
},
update(highlights, tr) {
highlights = highlights.map(tr.changes);
for (let e of tr.effects) {
if (e.is(addHighlight)) {
let { to, from, color } = e.value;
let mark = Decoration.mark({
class: `cm-highlight bgcolor-${color}`,
});
highlights = highlights.update({
add: [mark.range(from, to)],
});
} else if (e.is(clearHighlights)) {
return highlights.update({ filter: _ => false });
}
}
return highlights;
},
provide: f => EditorView.decorations.from(f),
})
Example #8
Source File: PumlView.ts From obsidian-plantuml with MIT License | 6 votes |
constructor(leaf: WorkspaceLeaf, plugin: PlantumlPlugin) {
super(leaf);
this.plugin = plugin;
this.debounced = debounce(this.plugin.getProcessor().png, this.plugin.settings.debounce * 1000, true);
this.sourceEl = this.contentEl.createDiv({cls: 'plantuml-source-view', attr: {'style': 'display: block'}});
this.previewEl = this.contentEl.createDiv({cls: 'plantuml-preview-view', attr: {'style': 'display: none'}});
const vault = (this.app.vault as any);
if (vault.getConfig("showLineNumber")) {
this.extensions.push(lineNumbers());
}
if(vault.getConfig("lineWrap")) {
this.extensions.push(EditorView.lineWrapping);
}
this.editor = new EditorView({
state: EditorState.create({
extensions: this.extensions,
doc: this.data,
}),
parent: this.sourceEl,
dispatch: syncDispatch(views.length),
});
this.dispatchId = views.push(this.editor) - 1;
}
Example #9
Source File: highlight.ts From starboard-notebook with Mozilla Public License 2.0 | 6 votes |
function highlight(markdownIt: MarkdownIt, opts: any, text: string, lang: string) {
const cmHighlight = import(
/* webpackChunkName: "codemirrorHighlight", webpackPrefetch: true */ "../editor/codemirror/highlight"
);
// An empty line is inserted without this at the end in codemirror, not sure why.
if (text.endsWith("\n")) {
text = text.substring(0, text.length - 1);
}
const uid = generateUniqueId(12);
cmHighlight
.then((cm) => {
return cm.createCodeMirrorCodeHighlight(text, { language: lang });
})
.then((ev: EditorView) => {
const placeholderEl = document.getElementById(uid);
if (placeholderEl) {
placeholderEl.id = "";
placeholderEl.innerText = "";
placeholderEl.appendChild(ev.contentDOM);
}
});
// Placeholder while we load codemirror asynchrionously.
const placeholder = `<pre><code id="${uid}">${text}</code></pre>`;
return placeholder;
}
Example #10
Source File: highlight.ts From starboard-notebook with Mozilla Public License 2.0 | 6 votes |
// Async in preparation of highlighters that are loaded dynamically
export async function createCodeMirrorCodeHighlight(
content: string,
opts: {
language?: string;
}
) {
const languageExtension = getCodemirrorLanguageExtension(opts.language);
const editorView = new EditorView({
state: EditorState.create({
doc: content,
extensions: [...commonExtensions, ...(languageExtension ? [languageExtension] : [])],
}),
});
return editorView;
}
Example #11
Source File: editor.tsx From nota with MIT License | 6 votes |
theme = EditorView.theme({
"&": {
height: "100%",
textAlign: "left",
},
"&.cm-editor.cm-focused": {
outline: "0",
},
".cm-scroller": {
fontFamily: "Inconsolata, monospace",
lineHeight: "1.3",
},
".cm-gutters": {
background: "none",
border: "none",
},
".cm-highlight": {
padding: "0 2px",
margin: "-1px -2px",
borderRadius: "2px",
},
})
Example #12
Source File: index.ts From codemirror-languageserver with BSD 3-Clause "New" or "Revised" License | 6 votes |
baseTheme = EditorView.baseTheme({
'.cm-tooltip.documentation': {
display: 'block',
marginLeft: '0',
padding: '3px 6px 3px 8px',
borderLeft: '5px solid #999',
whiteSpace: 'pre',
},
'.cm-tooltip.lint': {
whiteSpace: 'pre',
},
})
Example #13
Source File: index.ts From codemirror-languageserver with BSD 3-Clause "New" or "Revised" License | 6 votes |
constructor(private view: EditorView) {
this.client = this.view.state.facet(client);
this.documentUri = this.view.state.facet(documentUri);
this.languageId = this.view.state.facet(languageId);
this.documentVersion = 0;
this.changesTimeout = 0;
this.client.attachPlugin(this);
this.initialize({
documentText: this.view.state.doc.toString(),
});
}
Example #14
Source File: editor.tsx From nota with MIT License | 6 votes |
Editor: React.FC<EditorProps> = ({ embedded }) => {
let ref = useRef<HTMLDivElement>(null);
let state = useContext(StateContext)!;
useEffect(() => {
let visualExts = [
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
EditorView.lineWrapping,
theme,
];
let editingExts = [keymap.of([...keyBindings, indentWithTab])];
let customExts = [
EditorView.updateListener.of(
action(update => {
if (update.docChanged) {
state.contents = update.state.doc.toJSON().join("\n");
}
})
),
];
let _editor = new EditorView({
state: EditorState.create({
doc: state.contents,
extensions: [notaLang, visualExts, editingExts, customExts, basicSetup],
}),
parent: ref.current!,
});
}, []);
return <div className={classNames("nota-editor", { embedded })} ref={ref} />;
}
Example #15
Source File: code.tsx From nota with MIT License | 5 votes |
linecolToPos = (editor: EditorView, { line, col }: Linecol): number => {
let lineObj = editor.state.doc.line(line);
return lineObj.from + col;
}
Example #16
Source File: code.tsx From nota with MIT License | 5 votes |
posToLinecol = (editor: EditorView, pos: number): Linecol => {
let lineObj = editor.state.doc.lineAt(pos);
return {
line: lineObj.number,
col: pos - lineObj.from,
};
}
Example #17
Source File: livePreview.ts From obsidian_supercharged_links with MIT License | 5 votes |
export function buildCMViewPlugin(app: App, _settings: SuperchargedLinksSettings)
{
// Implements the live preview supercharging
// Code structure based on https://github.com/nothingislost/obsidian-cm6-attributes/blob/743d71b0aa616407149a0b6ea5ffea28e2154158/src/main.ts
// Code help credits to @NothingIsLost! They have been a great help getting this to work properly.
class HeaderWidget extends WidgetType {
attributes: Record<string, string>
after: boolean
constructor(attributes: Record<string, string>, after: boolean) {
super();
this.attributes = attributes
this.after = after
}
toDOM() {
let headerEl = document.createElement("span");
headerEl.setAttrs(this.attributes);
if (this.after) {
headerEl.addClass('data-link-icon-after');
}
else {
headerEl.addClass('data-link-icon')
}
// create a naive bread crumb
return headerEl;
}
ignoreEvent() {
return true;
}
}
const settings = _settings;
const viewPlugin = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = this.buildDecorations(view);
}
update(update: ViewUpdate) {
if (update.docChanged || update.viewportChanged) {
this.decorations = this.buildDecorations(update.view);
}
}
destroy() {
}
buildDecorations(view: EditorView) {
let builder = new RangeSetBuilder<Decoration>();
if (!settings.enableEditor) {
return builder.finish();
}
const mdView = view.state.field(editorViewField) as MarkdownView;
let lastAttributes = {};
let iconDecoAfter: Decoration = null;
let iconDecoAfterWhere: number = null;
let mdAliasFrom: number = null;
let mdAliasTo: number = null;
for (let {from, to} of view.visibleRanges) {
syntaxTree(view.state).iterate({
from,
to,
enter: (type, from, to) => {
const tokenProps = type.prop(tokenClassNodeProp);
if (tokenProps) {
const props = new Set(tokenProps.split(" "));
const isLink = props.has("hmd-internal-link");
const isAlias = props.has("link-alias");
const isPipe = props.has("link-alias-pipe");
// The 'alias' of the md link
const isMDLink = props.has('link');
// The 'internal link' of the md link
const isMDUrl = props.has('url');
const isMDFormatting = props.has('formatting-link');
if (isMDLink && !isMDFormatting) {
// Link: The 'alias'
// URL: The internal link
mdAliasFrom = from;
mdAliasTo = to;
}
if (!isPipe && !isAlias) {
if (iconDecoAfter) {
builder.add(iconDecoAfterWhere, iconDecoAfterWhere, iconDecoAfter);
iconDecoAfter = null;
iconDecoAfterWhere = null;
}
}
if (isLink && !isAlias && !isPipe || isMDUrl) {
let linkText = view.state.doc.sliceString(from, to);
linkText = linkText.split("#")[0];
let file = app.metadataCache.getFirstLinkpathDest(linkText, mdView.file.basename);
if (isMDUrl && !file) {
try {
file = app.vault.getAbstractFileByPath(decodeURIComponent(linkText)) as TFile;
}
catch(e) {}
}
if (file) {
let _attributes = fetchTargetAttributesSync(app, settings, file, true);
let attributes: Record<string, string> = {};
for (let key in _attributes) {
attributes["data-link-" + key] = _attributes[key];
}
let deco = Decoration.mark({
attributes,
class: "data-link-text"
});
let iconDecoBefore = Decoration.widget({
widget: new HeaderWidget(attributes, false),
});
iconDecoAfter = Decoration.widget({
widget: new HeaderWidget(attributes, true),
});
if (isMDUrl) {
// Apply retroactively to the alias found before
let deco = Decoration.mark({
attributes: attributes,
class: "data-link-text"
});
builder.add(mdAliasFrom, mdAliasFrom, iconDecoBefore);
builder.add(mdAliasFrom, mdAliasTo, deco);
if (iconDecoAfter) {
builder.add(mdAliasTo, mdAliasTo, iconDecoAfter);
iconDecoAfter = null;
iconDecoAfterWhere = null;
mdAliasFrom = null;
mdAliasTo = null;
}
}
else {
builder.add(from, from, iconDecoBefore);
}
builder.add(from, to, deco);
lastAttributes = attributes;
iconDecoAfterWhere = to;
}
} else if (isLink && isAlias) {
let deco = Decoration.mark({
attributes: lastAttributes,
class: "data-link-text"
});
builder.add(from, to, deco);
if (iconDecoAfter) {
builder.add(to, to, iconDecoAfter);
iconDecoAfter = null;
iconDecoAfterWhere = null;
}
}
}
}
})
}
return builder.finish();
}
},
{
decorations: v => v.decorations
}
);
return viewPlugin;
}
Example #18
Source File: code.tsx From nota with MIT License | 5 votes |
Listing: React.FC<ListingProps> = props => {
let ctx = usePlugin(ListingPlugin);
let ref = useRef(null);
useEffect(() => {
let language = props.language || ctx.language;
let code = joinRecursive(props.children as any);
let parseResult = null;
if (props.delimiters) {
parseResult = parseWithDelimiters(code, props.delimiters.delimiters);
if (parseResult.error) {
throw parseResult.error;
} else {
code = parseResult.outputCode!;
}
}
let editor = new EditorView({
state: EditorState.create({
doc: code,
extensions: [
lineNumbers(),
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
theme,
EditorView.editable.of(props.editable || false),
props.wrap || ctx.wrap ? EditorView.lineWrapping : [],
highlightField,
]
.concat(language ? [language] : [])
.concat(props.extensions || []),
}),
parent: ref.current!,
});
if (props.onLoad) {
props.onLoad(editor);
}
if (props.delimiters) {
props.delimiters.onParse(parseResult!.ranges!);
}
}, []);
return <div className="listing" ref={ref} />;
}
Example #19
Source File: index.ts From obsidian-banners with MIT License | 5 votes |
getViewPlugin = (plugin: BannersPlugin) => ViewPlugin.fromClass(class BannerPV implements PluginValue {
decor: DecorationSet;
constructor(view: EditorView) {
this.decor = this.decorate(view.state);
}
update(_update: ViewUpdate) {
const { docChanged, view, state, startState } = _update;
if (docChanged || state.facet(bannerDecorFacet) !== startState.facet(bannerDecorFacet) || state.facet(iconDecorFacet) !== startState.facet(iconDecorFacet)) {
this.decor = this.decorate(view.state);
}
}
decorate(state: EditorState): DecorationSet {
// If there's no YAML, stop here
const cursor = syntaxTree(state).cursor();
cursor.firstChild();
if (cursor.name !== YAML_SEPARATOR_TOKEN) { return Decoration.none }
// Get all frontmatter fields to later process
const frontmatter: {[key: string]: string} = {};
let key;
while (cursor.nextSibling() && cursor.name !== YAML_SEPARATOR_TOKEN) {
const { from, to, name } = cursor;
if (name === YAML_DEF_NAME_TOKEN) {
key = state.sliceDoc(from, to);
} else if (YAML_DEF_VAL_TOKENS.includes(name) && !frontmatter[key]) {
const isStr = name === YAML_DEF_STR_TOKEN;
const val = state.sliceDoc(from + (isStr ? 1 : 0), to - (isStr ? 1 : 0));
frontmatter[key] = val;
}
};
const bannerData = plugin.metaManager.getBannerData(frontmatter);
const { src, icon } = bannerData;
const { contentEl, file } = state.field(editorViewField);
const widgets: Decoration[] = [];
// Add banner widgets if applicable
if (src) {
const settingsFacet = state.facet(bannerDecorFacet);
widgets.push(
Decoration.widget({ widget: new BannerWidget(plugin, bannerData, file.path, contentEl, settingsFacet) }),
Decoration.widget({ widget: new SpacerWidget() }),
Decoration.line({ class: 'has-banner' })
);
}
// Add icon widget if applicable
if (icon) {
const settingsFacet = state.facet(iconDecorFacet);
widgets.push(
Decoration.widget({ widget: new IconWidget(plugin, icon, file, settingsFacet) }),
Decoration.line({ class: "has-banner-icon", attributes: { "data-icon-v": settingsFacet.iconVerticalAlignment }})
);
}
return Decoration.set(widgets.map(w => w.range(0)), true);
}
}, {
decorations: v => v.decor
})
Example #20
Source File: index.tsx From fe-v5 with Apache License 2.0 | 5 votes |
export default function PromqlEditor(props: Props) {
const { onChange, value, className, style = {}, editable = true, xCluster } = props;
const [view, setView] = useState<EditorView>();
const containerRef = useRef<HTMLDivElement>(null);
const url = '/api/n9e/prometheus';
function myHTTPClient(resource: string, options = {}): Promise<Response> {
return fetch(resource, {
method: 'Get',
headers: new Headers({
'X-Cluster': xCluster,
Authorization: `Bearer ${localStorage.getItem('access_token') || ''}`,
}),
...options,
});
}
const promQL = new PromQLExtension().setComplete({
remote: { fetchFn: myHTTPClient, url },
// remote: { url: 'http://10.86.76.13:8090' },
});
useEffect(() => {
const v = new EditorView({
state: EditorState.create({
doc: value,
extensions: [
baseTheme,
basicSetup,
promQL.asExtension(),
EditorView.updateListener.of((update: ViewUpdate): void => {
onChange?.(update.state.doc.toString());
}),
EditorView.editable.of(editable),
],
}),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
// tslint:disable-next-line:no-non-null-assertion
parent: containerRef.current!,
});
setView(v);
}, []);
return <div ref={containerRef} className={className} style={Object.assign({ fontSize: 12 }, style)}></div>;
}
Example #21
Source File: CMTheme.tsx From fe-v5 with Apache License 2.0 | 5 votes |
lightTheme = EditorView.theme(
{
'.cm-tooltip': {
backgroundColor: '#f8f8f8',
borderColor: 'rgba(52, 79, 113, 0.2)',
},
'.cm-tooltip.cm-tooltip-autocomplete': {
'& li:hover': {
backgroundColor: '#ddd',
},
'& > ul > li[aria-selected]': {
backgroundColor: '#d6ebff',
color: 'unset',
},
},
'.cm-tooltip.cm-completionInfo': {
backgroundColor: '#d6ebff',
},
'.cm-tooltip > .cm-completionInfo.cm-completionInfo-right': {
'&:before': {
borderRightColor: '#d6ebff',
},
},
'.cm-tooltip > .cm-completionInfo.cm-completionInfo-left': {
'&:before': {
borderLeftColor: '#d6ebff',
},
},
'.cm-line': {
'&::selection': {
backgroundColor: '#add6ff',
},
'& > span::selection': {
backgroundColor: '#add6ff',
},
},
},
{ dark: false },
)
Example #22
Source File: CMTheme.tsx From fe-v5 with Apache License 2.0 | 5 votes |
lightTheme = EditorView.theme(
{
'.cm-tooltip': {
backgroundColor: '#f8f8f8',
borderColor: 'rgba(52, 79, 113, 0.2)',
},
'.cm-tooltip.cm-tooltip-autocomplete': {
'& li:hover': {
backgroundColor: '#ddd',
},
'& > ul > li[aria-selected]': {
backgroundColor: '#d6ebff',
color: 'unset',
},
},
'.cm-tooltip.cm-completionInfo': {
backgroundColor: '#d6ebff',
},
'.cm-tooltip > .cm-completionInfo.cm-completionInfo-right': {
'&:before': {
borderRightColor: '#d6ebff',
},
},
'.cm-tooltip > .cm-completionInfo.cm-completionInfo-left': {
'&:before': {
borderLeftColor: '#d6ebff',
},
},
'.cm-line': {
'&::selection': {
backgroundColor: '#add6ff',
},
'& > span::selection': {
backgroundColor: '#add6ff',
},
},
},
{ dark: false },
)
Example #23
Source File: CodeMirrorWrapper.tsx From console with GNU Affero General Public License v3.0 | 5 votes |
lightTheme = EditorView.theme(
{
"&": {
backgroundColor: "#FBFAFA",
},
".cm-content": {
caretColor: "#05122B",
},
"&.cm-focused .cm-cursor": {
borderLeftColor: "#05122B",
},
".cm-gutters": {
backgroundColor: "#FBFAFA",
color: "#000000",
border: "none",
},
".cm-gutter.cm-foldGutter": {
borderRight: "1px solid #eaeaea",
},
".cm-gutterElement": {
fontSize: "13px",
},
".cm-line": {
fontSize: "13px",
color: "#2781B0",
"& .ͼc": {
color: "#C83B51",
},
},
"& .ͼb": {
color: "#2781B0",
},
".cm-activeLine": {
backgroundColor: "#dde1f1",
},
".cm-matchingBracket": {
backgroundColor: "#05122B",
color: "#ffffff",
},
".cm-selectionMatch": {
backgroundColor: "#ebe7f1",
},
".cm-selectionLayer": {
fontWeight: 500,
},
" .cm-selectionBackground": {
backgroundColor: "#a180c7",
color: "#ffffff",
},
},
{
dark: false,
}
)
Example #24
Source File: index.ts From codemirror-languageserver with BSD 3-Clause "New" or "Revised" License | 5 votes |
async requestHoverTooltip(
view: EditorView,
{ line, character }: { line: number; character: number }
): Promise<Tooltip | null> {
if (!this.client.ready || !this.client.capabilities!.hoverProvider) return null;
this.sendChange({ documentText: view.state.doc.toString() });
const result = await this.client.textDocumentHover({
textDocument: { uri: this.documentUri },
position: { line, character },
});
if (!result) return null;
const { contents, range } = result;
let pos = posToOffset(view.state.doc, { line, character })!;
let end: number;
if (range) {
pos = posToOffset(view.state.doc, range.start)!;
end = posToOffset(view.state.doc, range.end);
}
if (pos === null) return null;
const dom = document.createElement('div');
dom.classList.add('documentation');
dom.textContent = formatContents(contents);
return { pos, end, create: (view) => ({ dom }), above: true };
}
Example #25
Source File: Editor.tsx From react-jupyter-notebook with MIT License | 5 votes |
function Editor(props: EditorPropsType) {
const {
editable=true,
onChange=(value) => console.log(value),
} = props;
const [state, setState] = useState<{[key:string]: any}>({});
const extensions = [
javascript(),
lineNumbers(),
// onChange listener
EditorView.updateListener.of((viewUpdate: ViewUpdate) => {
if (viewUpdate.docChanged && typeof onChange === 'function') {
const doc = viewUpdate.state.doc;
const value = doc.toString();
onChange(value);
}
}),
// Jupyter theme
EditorView.theme(
{
'&.cm-editor': {
border: "1px solid rgb(224, 224, 224)",
backgroundColor: "rgb(245, 245, 245)",
},
'&.cm-editor.cm-focused': {
outline: "1px solid #1976d2",
},
'.cm-gutters': {
minWidth: "37px",
display: "initial",
backgroundColor: "rgb(238, 238, 238)"
}
},
{dark: false},
),
// Editable
EditorView.editable.of(editable),
];
const codeMirrorRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (codeMirrorRef.current && !state.view) {
const view = new EditorView({
state: EditorState.create({
extensions: extensions,
doc: "TEST",
}),
parent: codeMirrorRef.current,
})
setState((state) => ({...state, view}))
}
}, [codeMirrorRef.current])
return (
<div ref={codeMirrorRef}/>
)
}
Example #26
Source File: highlight.ts From starboard-notebook with Mozilla Public License 2.0 | 5 votes |
commonExtensions = [highlightSpecialChars(), starboardHighlighter, EditorView.editable.of(false)]
Example #27
Source File: PumlView.ts From obsidian-plantuml with MIT License | 5 votes |
editor: EditorView;
Example #28
Source File: PumlView.ts From obsidian-plantuml with MIT License | 5 votes |
views: EditorView[] = []
Example #29
Source File: EmbedDecoration.ts From obsidian-plantuml with MIT License | 5 votes |
constructor(editor: EditorView, plugin: PlantumlPlugin) {
this.editor = editor;
this.plugin = plugin;
}