@codemirror/view#ViewPlugin TypeScript Examples
The following examples show how to use
@codemirror/view#ViewPlugin.
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: index.ts From codemirror-languageserver with BSD 3-Clause "New" or "Revised" License | 5 votes |
export function languageServerWithTransport(options: LanguageServerOptions) {
let plugin: LanguageServerPlugin | null = null;
return [
client.of(options.client || new LanguageServerClient({...options, autoClose: true})),
documentUri.of(options.documentUri),
languageId.of(options.languageId),
ViewPlugin.define((view) => (plugin = new LanguageServerPlugin(view))),
hoverTooltip(
(view, pos) =>
plugin?.requestHoverTooltip(
view,
offsetToPos(view.state.doc, pos)
) ?? null
),
autocompletion({
override: [
async (context) => {
if (plugin == null) return null;
const { state, pos, explicit } = context;
const line = state.doc.lineAt(pos);
let trigKind: CompletionTriggerKind =
CompletionTriggerKind.Invoked;
let trigChar: string | undefined;
if (
!explicit &&
plugin.client.capabilities?.completionProvider?.triggerCharacters?.includes(
line.text[pos - line.from - 1]
)
) {
trigKind = CompletionTriggerKind.TriggerCharacter;
trigChar = line.text[pos - line.from - 1];
}
if (
trigKind === CompletionTriggerKind.Invoked &&
!context.matchBefore(/\w+$/)
) {
return null;
}
return await plugin.requestCompletion(
context,
offsetToPos(state.doc, pos),
{
triggerKind: trigKind,
triggerCharacter: trigChar,
}
);
},
],
}),
baseTheme,
];
}
Example #2
Source File: EmbedDecoration.ts From obsidian-plantuml with MIT License | 5 votes |
function buildViewPlugin(plugin: PlantumlPlugin) {
return ViewPlugin.fromClass(
class {
decoManager: StatefulDecorationSet;
constructor(view: EditorView) {
this.decoManager = new StatefulDecorationSet(view, plugin);
this.buildAsyncDecorations(view);
}
update(update: ViewUpdate) {
if (update.docChanged || update.viewportChanged) {
this.buildAsyncDecorations(update.view);
}
}
buildAsyncDecorations(view: EditorView) {
const targetElements: TokenSpec[] = [];
for (const {from, to} of view.visibleRanges) {
const tree = syntaxTree(view.state);
tree.iterate({
from,
to,
enter: (type, from, to) => {
const tokenProps = type.prop(tokenClassNodeProp);
if (tokenProps) {
const props = new Set(tokenProps.split(" "));
const isEmbed = props.has("formatting-embed");
if (isEmbed) {
const content = view.state.doc.sliceString(from);
const index = content.indexOf("]]");
const filename = content.slice(3, index).split("|")[0];
if (filename.endsWith(".puml") || filename.endsWith(".pu")) {
targetElements.push({from: from, to: index, value: filename});
}
}
}
},
});
}
this.decoManager.debouncedUpdate(targetElements);
}
}
);
}
Example #3
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 #4
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
})