Create LinkThumnailDecoPlugin

This commit is contained in:
kim365my 2024-02-18 03:22:28 +09:00
parent e60294b950
commit 26a0b09c73
8 changed files with 2713 additions and 136 deletions

View File

@ -15,7 +15,7 @@ const context = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ["main.ts"],
entryPoints: ["./src/main.ts"],
bundle: true,
external: [
"obsidian",

134
main.ts
View File

@ -1,134 +0,0 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
// Remember to rename these classes and interfaces!
interface MyPluginSettings {
mySetting: string;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
mySetting: 'default'
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
async onload() {
await this.loadSettings();
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => {
// Called when the user clicks the icon.
new Notice('This is a notice!');
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText('Status Bar Text');
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'open-sample-modal-simple',
name: 'Open sample modal (simple)',
callback: () => {
new SampleModal(this.app).open();
}
});
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'sample-editor-command',
name: 'Sample editor command',
editorCallback: (editor: Editor, view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class SampleModal extends Modal {
constructor(app: App) {
super(app);
}
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Setting #1')
.setDesc('It\'s a secret')
.addText(text => text
.setPlaceholder('Enter your secret')
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => {
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
}
}

2326
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -19,6 +19,11 @@
"esbuild": "0.17.3",
"obsidian": "latest",
"tslib": "2.4.0",
"typescript": "4.7.4"
"typescript": "4.7.4",
"compare-versions": "^4.1.3",
"@codemirror/search": "6.0.0",
"@codemirror/view": "6.0.0",
"@codemirror/commands": "6.0.0",
"@codemirror/language": "https://github.com/lishid/cm-language"
}
}

219
src/EnbedDecoratiion.ts Normal file
View File

@ -0,0 +1,219 @@
import {debounce, editorLivePreviewField, requestUrl} from "obsidian";
import {EditorView, Decoration, DecorationSet, ViewUpdate, ViewPlugin, WidgetType} from "@codemirror/view";
import {StateField, StateEffect, StateEffectType} from "@codemirror/state";
import {Range} from "@codemirror/rangeset";
import {syntaxTree, tokenClassNodeProp} from "@codemirror/language";
import MyPlugin from "./main";
//based on: https://gist.github.com/nothingislost/faa89aa723254883d37f45fd16162337
interface TokenSpec {
from: number;
to: number;
value: string;
}
const statefulDecorations = defineStatefulDecoration();
class StatefulDecorationSet {
editor: EditorView;
decoCache: { [cls: string]: Decoration } = Object.create(null);
plugin: MyPlugin;
constructor(editor: EditorView, plugin: MyPlugin) {
this.editor = editor;
this.plugin = plugin;
}
async computeAsyncDecorations(tokens: TokenSpec[]): Promise<DecorationSet | null> {
const isSourceMode = !this.editor.state.field(editorLivePreviewField);
if (isSourceMode) {
return Decoration.none;
} else {
const decorations: Range<Decoration>[] = [];
for (const token of tokens) {
let deco = this.decoCache[token.value];
if (!deco) {
const div = createDiv();
// 클래스 추가
div.addClass("cm-embed-block");
div.addClass("cm-embed-link");
// 넣을 EL 받아오기
const params = await linkThumbnailWidgetParams(token.value);
if (params != null) {
div.innerHTML = params;
} else {
return Decoration.none;
}
deco = this.decoCache[token.value] = Decoration.replace({widget: new EmojiWidget(div), block: true});
}
decorations.push(deco.range(token.from, token.to));
}
return Decoration.set(decorations, true);
}
}
debouncedUpdate = debounce(this.updateAsyncDecorations, 100, true);
async updateAsyncDecorations(tokens: TokenSpec[]): Promise<void> {
const decorations = await this.computeAsyncDecorations(tokens);
// if our compute function returned nothing and the state field still has decorations, clear them out
if (decorations || this.editor.state.field(statefulDecorations.field).size) {
this.editor.dispatch({effects: statefulDecorations.update.of(decorations || Decoration.none)});
}
}
}
function buildViewPlugin(plugin: MyPlugin) {
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[] = [];
try {
const tree = syntaxTree(view.state);
tree.iterate({
enter: ({node, from, to}) => {
const tokenProps = node.type.prop<string>(tokenClassNodeProp);
if (tokenProps && node.name === "url") {
const value = view.state.doc.sliceString(from, to);
if (value) {
targetElements.push({from: from, to: to, value: value});
}
}
},
});
} catch (error) {
console.error("Custom CM6 view plugin failure", error);
throw error;
}
this.decoManager.debouncedUpdate(targetElements);
}
}
);
}
export function asyncDecoBuilderExt(plugin: MyPlugin) {
return [statefulDecorations.field, buildViewPlugin(plugin)];
}
////////////////
// 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};
}
class EmojiWidget extends WidgetType {
private readonly source: HTMLDivElement;
constructor(source: HTMLDivElement) {
super();
this.source = source;
}
eq(other: EmojiWidget) {
return other == this;
}
toDOM() {
return this.source;
}
ignoreEvent(): boolean {
return false;
}
}
export async function linkThumbnailWidgetParams(url: string) {
try {
// url 정규식
const urlRegex = new RegExp("^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/)?[a-z0-9]+([\\-.]{1}[a-z0-9]+)*\\.[a-z]{2,5}(:[0-9]{1,5})?(\\/.*)?$");
const urlT = urlRegex.exec(url);
if (urlT?.length != 0 && urlT != null) {
const domainUrl = url.replace(urlT[4], "");
const response = await requestUrl(url);
const responseDomain = await requestUrl(domainUrl);
if (response.status === 200) {
const htmlString = response.text;
const parser = new DOMParser();
const document = parser.parseFromString(htmlString, 'text/html');
const htmlDomainString = responseDomain.text;
const domainDocument = parser.parseFromString(htmlDomainString, 'text/html');
const ogTitle = document.querySelector("meta[property='og:title']")?.getAttribute("content") || document.querySelector("title")?.textContent || domainDocument.querySelector("meta[property='og:title']")?.getAttribute("content") || domainDocument.querySelector("title")?.textContent || "";
const ogDescription = document.querySelector("meta[property='og:description']")?.getAttribute("content") || domainDocument.querySelector("meta[property='og:description']")?.getAttribute("content") || "";
const ogImage = document.querySelector("meta[property='og:image']")?.getAttribute("content") || domainDocument.querySelector("meta[property='og:image']")?.getAttribute("content") || "";
const ogImageAlt = document.querySelector("meta[property='og:image:alt']")?.getAttribute("content") || domainDocument.querySelector("meta[property='og:image']")?.getAttribute("content") || "";
const ogUrl = document.querySelector("meta[property='og:url']")?.getAttribute("content") || domainUrl;
let result = "";
if (ogImage === "") {
result = `
<a href="${url}">
<div class="openGraphPreview">
<div class="se-oglink-info-container">
<strong class="se-oglink-info">${ogTitle}</strong>
<description class="se-oglink-summary">${ogDescription}</description>
<p class="se-oglink-url"> ${ogUrl}</p>
</div>
</div>
</a>
`
} else {
result = `
<a href="${url}">
<div class="openGraphPreview">
<div class="se-oglink-thumbnail">
<img src="${ogImage}" alt="${ogImageAlt}" class="se-oglink-thumbnail-resource"></img>
</div>
<div class="se-oglink-info-container">
<strong class="se-oglink-info">${ogTitle}</strong>
<description class="se-oglink-summary">${ogDescription}</description>
<p class="se-oglink-url"> ${ogUrl}</p>
</div>
</div>
</a>
`
}
return result;
}
}
return null
} catch (error) {
// console.error(error);
return null;
}
}

35
src/PostProcessor.ts Normal file
View File

@ -0,0 +1,35 @@
import { MarkdownPostProcessorContext } from "obsidian";
import MyPlugin from "./main";
import { linkThumbnailWidgetParams } from "./EnbedDecoratiion";
export class PostProcessor {
plugin: MyPlugin;
constructor(plugin: MyPlugin) {
this.plugin = plugin;
}
processor = async (
element: HTMLElement,
context: MarkdownPostProcessorContext
) => {
// 링크 변환
const linkEls = element.findAll("a.external-link");
for (const linkEl of linkEls) {
// dataview 클래스를 가진 부모 요소를 확인합니다.
if (linkEl.closest(".dataview") !== null) {
continue;
}
const url = linkEl.innerHTML;
const params = await linkThumbnailWidgetParams(url);
if (params != null) {
linkEl.innerHTML = params;
}
}
};
isDisabled = (el: Element) => {
return false;
};
}

38
src/main.ts Normal file
View File

@ -0,0 +1,38 @@
import { Plugin } from 'obsidian';
import { asyncDecoBuilderExt } from './EnbedDecoratiion';
import { PostProcessor } from './PostProcessor';
export default class MyPlugin extends Plugin {
/**
* @returns true if Live Preview is supported
*/
isUsingLivePreviewEnabledEditor(): boolean {
//@ts-ignore
return !this.app.vault.getConfig('legacyEditor');
}
async onload() {
// In LivePre view Mode
if (this.isUsingLivePreviewEnabledEditor()) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Prec = require("@codemirror/state").Prec;
this.registerEditorExtension(Prec.lowest(asyncDecoBuilderExt(this)));
}
// In Reading Mode
const postProcessor = new PostProcessor(this);
this.registerMarkdownPostProcessor(postProcessor.processor);
// updateOptions
this.registerEvent(this.app.workspace.on('css-change', () => {
this.app.workspace.updateOptions();
}));
this.app.workspace.updateOptions();
}
async onunload() {
console.log("disabling plugin: link");
}
}

View File

@ -6,3 +6,91 @@ available in the app when your plugin is enabled.
If your plugin does not need CSS, delete this file.
*/
a:has(.openGraphPreview) {
text-decoration: none;
background-image: none;
}
a:has(.openGraphPreview):hover {
text-decoration: none;
}
.openGraphPreview {
height: 100%;
display: flex;
flex-direction: column;
gap: 8px;
border: var(--cards-border-width) solid var(--background-modifier-border);
background: none;
color: var(--text-normal);
text-decoration: none;
background: none;
}
.openGraphPreview:hover {
text-decoration: none;
color: var(--text-normal);
}
.openGraphPreview .se-oglink-thumbnail {
flex-shrink: 0;
width: 100%;
height: initial;
overflow: hidden;
}
.openGraphPreview .se-oglink-thumbnail-resource {
height: 100%;
object-fit: cover !important;
border-radius: 0 !important;
}
.openGraphPreview .se-oglink-info-container {
display: flex;
flex-direction: column;
justify-content: center;
gap: 8px;
overflow: auto;
padding: var(--size-4-4) var(--size-4-2);
}
.openGraphPreview .se-oglink-info {
display: block;
text-decoration: none;
color: var(--text-normal);
}
.openGraphPreview .se-oglink-summary {
font-size: 0.8rem;
overflow: hidden;
-webkit-line-clamp: 2;
display: box;
display: -webkit-box;
-webkit-box-orient: vertical;
text-overflow: ellipsis;
white-space: normal;
text-decoration: none;
color: var(--text-normal);
}
.openGraphPreview .se-oglink-url {
font-size: 0.8rem;
margin-block: 0 !important;
color: var(--link-color);
text-decoration: none;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.table-cards table .openGraphPreview,
.cards table .openGraphPreview {
flex-direction: column;
border: none;
}
.table-cards table .openGraphPreview .se-oglink-thumbnail,
.cards table .openGraphPreview .se-oglink-thumbnail {
width: 100%;
}
@media (min-width: 500px) {
.openGraphPreview {
flex-direction: row;
}
.openGraphPreview .se-oglink-thumbnail {
width: 150px;
}
}