Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Link preview in live mode #7

Merged
merged 4 commits into from
Nov 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
"author": "",
"license": "MIT",
"devDependencies": {
"@codemirror/language": "^6.8.0",
"@codemirror/state": "^6.2.1",
"@codemirror/view": "^6.16.0",
"@types/node": "^16.11.6",
"@typescript-eslint/eslint-plugin": "5.29.0",
"@typescript-eslint/parser": "5.29.0",
Expand Down
46 changes: 41 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

114 changes: 65 additions & 49 deletions src/LinkPreview.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,78 @@
import { MarkdownPostProcessorContext, requestUrl } from "obsidian";
import { requestUrl } from "obsidian";

Check failure on line 1 in src/LinkPreview.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

Expression expected.
import tippy from "tippy.js";

export default function linkPreview(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
const targetLinks = Array.from(element.getElementsByTagName("a")).filter(
(link) =>
link.classList.contains("external-link") &&
link.href !== link.innerHTML &&
link.href.startsWith("https://www.bible.com/bible")
);

for (const link of targetLinks) {
processLink(link);
}
}
type cacheType = { [key: string]: any };

export default class LinkPreviewManager {
static cache: cacheType = {};

static async processLink(link: HTMLAnchorElement) {
if (!this.cache[link.href]) {
const res = await requestUrl(link.href);
let text = await res.text;

const match = text.match(
/<script\s*id="__NEXT_DATA__"\s*type="application\/json"\s*>.+?(?=<\/script>\s*<\/body>\s*<\/html>)/
);
if (match) {
const json_text = match[0].replace(
/<script\s*id="__NEXT_DATA__"\s*type="application\/json"\s*>/,
""
);

async function processLink(link: HTMLAnchorElement) {
const res = await requestUrl(link.href);
let text = await res.text;

const match = text.match(
/<script\s*id="__NEXT_DATA__"\s*type="application\/json"\s*>.+?(?=<\/script>\s*<\/body>\s*<\/html>)/
);
if (match) {
const json_text = match[0].replace(
/<script\s*id="__NEXT_DATA__"\s*type="application\/json"\s*>/,
""
);
const data = JSON.parse(json_text);

if (data.props.pageProps.type !== "verse") {
const popup = document.createElement("div");
popup.addClass("preview-youversion");

popup
.createSpan({ cls: "error-youversion" })
.setText("Verse preview is unavailable for this type of link.");

tippy(link, { content: popup, allowHTML: true });
return;
try {
const data = JSON.parse(json_text);

if (data.props.pageProps.type !== "verse") {
throw;
}

const info =
data.props.pageProps.referenceTitle.title +
" " +
data.props.pageProps.version.local_abbreviation;
const verses = data.props.pageProps.verses
.map((ele: any) => ele.content)
.join(" ");
this.cache[link.href] = { info, verses };
} catch {
this.cache[link.href] = { err: true };
}
} else {
this.cache[link.href] = { err: true };
}
}

const info =
data.props.pageProps.referenceTitle.title +
" " +
data.props.pageProps.version.local_abbreviation;
const verses = data.props.pageProps.verses
.map((ele: any) => ele.content)
.join(" ");
if (this.cache[link.href].err) {

const popup = document.createElement("div");
popup.addClass("preview-youversion");

popup
.createSpan({ cls: "error-youversion" })
.setText("Verse preview is unavailable for this link.");

tippy(link, { content: popup, allowHTML: true });
return;
}
const popup = document.createElement("div");
popup.addClass("preview-youversion");

popup.createSpan({ cls: "content-youversion" }).setText(verses);
popup.createSpan({ cls: "info-youversion" }).setText(info);
popup
.createSpan({ cls: "content-youversion" })
.setText(this.cache[link.href]?.verses);
popup
.createSpan({ cls: "info-youversion" })
.setText(this.cache[link.href].info);

tippy(link, { content: popup, allowHTML: true });
}

static clearCache(notClear: Array<string>) {
let dict: cacheType = {};
notClear.forEach((ele) => {
dict[ele] = this.cache[ele];
});
this.cache = dict;
}
}
93 changes: 93 additions & 0 deletions src/LinkPreviewEditor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { syntaxTree } from "@codemirror/language";
import { RangeSetBuilder } from "@codemirror/state";
import {
Decoration,
DecorationSet,
EditorView,
PluginSpec,
PluginValue,
ViewPlugin,
ViewUpdate,
WidgetType,
} from "@codemirror/view";
import LinkPreviewManager from "./LinkPreview";

class LinkPreviewView implements PluginValue {
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): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
let last_f: number = 0;
let last_t: number = 0;
let content: string = "";
let urls: Array<string> = [];

for (let { from, to } of view.visibleRanges) {
syntaxTree(view.state).iterate({
from,
to,
enter(node) {
if (node.type.name.startsWith("link")) {
const slice = view.state.sliceDoc(node.from, node.to);
last_f = node.from;
last_t = node.to;
content = slice;
}
if (node.type.name.startsWith("string_url")) {
const slice = view.state.sliceDoc(node.from, node.to);
if (slice.startsWith("https://www.bible.com/bible")) {
urls.push(slice);
builder.add(
last_f,
last_t,
Decoration.replace({
widget: new LinkTooltip(content, slice),
})
);
}
}
},
mode: 2,
});
}
LinkPreviewManager.clearCache(urls);
return builder.finish();
}
}

const pluginSpec: PluginSpec<LinkPreviewView> = {
decorations: (value: LinkPreviewView) => value.decorations,
};

export const linkPreviewPlugin = ViewPlugin.fromClass(
LinkPreviewView,
pluginSpec
);

class LinkTooltip extends WidgetType {
constructor(private text: string, private url: string) {
super();
}

toDOM(view: EditorView): HTMLElement {
const el = document.createElement("a");
el.href = this.url;
el.innerHTML = this.text;

LinkPreviewManager.processLink(el);

return el;
}
}
21 changes: 21 additions & 0 deletions src/LinkPreviewReader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { MarkdownPostProcessorContext } from "obsidian";
import tippy from "tippy.js";
import LinkPreviewManager from "./LinkPreview";
import { link } from "fs";

export default function linkPreview(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
const targetLinks = Array.from(element.getElementsByTagName("a")).filter(
(link) =>
link.classList.contains("external-link") &&
link.href !== link.innerHTML &&
link.href.startsWith("https://www.bible.com/bible")
);

for (const link of targetLinks) {
LinkPreviewManager.processLink(link);
}
LinkPreviewManager.clearCache(targetLinks.map((ele) => ele.href));
}
26 changes: 26 additions & 0 deletions src/SettingTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,31 @@ export default class SettingTab extends PluginSettingTab {
new Notice("Bible version settings updated");
});
});

new Setting(containerEl)
.setName("Link Preview in read view")
.setDesc(
"Enable or disable verse preview shown when hovered over link in read view. DISCLAIMER: Will take effect after restart."
)
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.linkPreviewRead);
toggle.onChange(async (value) => {
this.plugin.settings.linkPreviewRead = value;
await this.plugin.saveSettings();
});
});

new Setting(containerEl)
.setName("Link Preview in edit view (experimental)")
.setDesc(
"Enable or disable verse preview shown when hovered over link in edit view. DISCLAIMER: Will take effect after restart."
)
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.linkPreviewLive);
toggle.onChange(async (value) => {
this.plugin.settings.linkPreviewLive = value;
await this.plugin.saveSettings();
});
});
}
}
4 changes: 4 additions & 0 deletions src/SettingsData.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
export interface ObsidianYouversionLinkerSettings {
bibleLanguage: string;
bibleVersion: string;
linkPreviewRead: boolean;
linkPreviewLive: boolean;
}

export const DEFAULT_SETTINGS: ObsidianYouversionLinkerSettings = {
bibleLanguage: "eng",
bibleVersion: "1",
linkPreviewRead: true,
linkPreviewLive: true,
};
Loading
Loading