Skip to content

Commit

Permalink
feat(icon-in-editor): support source mode
Browse files Browse the repository at this point in the history
  • Loading branch information
aidenlx committed Mar 4, 2022
1 parent 797e76f commit b3bfdd8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
20 changes: 14 additions & 6 deletions src/icon-in-editor/deco.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { EditorView } from "@codemirror/view";
import { Decoration, WidgetType } from "@codemirror/view";
import type { NodeType } from "@lezer/common";
import cls from "classnames";
import { editorLivePreviewField } from "obsidian";

import {
getGlobalRegexp,
Expand Down Expand Up @@ -102,12 +103,19 @@ const icons = (view: EditorView, plugin: IconSC) => {
if (prevTo !== to) getShortcodeRange(prevTo, from);
}
return Decoration.set(
ranges.map(([code, from, to]) =>
Decoration.replace({
widget: new IconWidget(code, plugin),
side: 1,
}).range(from, to),
),
ranges.map(([code, from, to]) => {
if (view.state.field(editorLivePreviewField)) {
return Decoration.replace({
widget: new IconWidget(code, plugin),
side: 1,
}).range(from, to);
} else {
return Decoration.widget({
widget: new IconWidget(code, plugin),
side: 1,
}).range(to);
}
}),
);
};

Expand Down
14 changes: 11 additions & 3 deletions src/icon-in-editor/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { EditorView } from "@codemirror/view";
import { DecorationSet, ViewPlugin, ViewUpdate } from "@codemirror/view";
import { editorLivePreviewField } from "obsidian";
import { ViewPlugin, EditorView, Decoration } from "@codemirror/view";
import type { DecorationSet, ViewUpdate } from "@codemirror/view";

import type IconSC from "../isc-main";
import icons from "./deco";
Expand All @@ -16,8 +17,15 @@ const buildIconPlugin = (plugin: IconSC) =>
}

update(update: ViewUpdate) {
if (update.docChanged || update.viewportChanged)
const prevMode = update.startState.field(editorLivePreviewField),
currMode = update.state.field(editorLivePreviewField);
if (
update.docChanged ||
update.viewportChanged ||
prevMode !== currMode
) {
this.decorations = icons(update.view, this.plugin);
}
}
},
{
Expand Down

0 comments on commit b3bfdd8

Please sign in to comment.