forked from 0x7b1/logseq-plugin-automatic-url-title
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
228 lines (198 loc) · 6.68 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import '@logseq/libs';
const DEFAULT_REGEX = {
wrappedInCommand:
/(\{\{(video)\s*(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})\s*\}\})/gi,
htmlTitleTag: /<title(\s[^>]+)*>([^<]*)<\/title>/,
line: /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi,
imageExtension: /\.(gif|jpe?g|tiff?|png|webp|bmp|tga|psd|ai)$/i,
};
const FORMAT_SETTINGS = {
markdown: {
formatBeginning: '](',
applyFormat: (title, url) => `[${title}](${url})`,
},
org: {
formatBeginning: '][',
applyFormat: (title, url) => `[[${url}][${title}]]`,
},
};
function decodeHTML(input) {
if (!input) {
return '';
}
const doc = new DOMParser().parseFromString(input, 'text/html');
return doc.documentElement.textContent;
}
async function getTitle(url) {
try {
const response = await fetch(url);
const responseText = await response.text();
const matches = responseText.match(DEFAULT_REGEX.htmlTitleTag);
if (matches !== null && matches.length > 1 && matches[2] !== null) {
return decodeHTML(matches[2].trim());
}
} catch (e) {
console.error(e);
}
return '';
}
async function convertUrlToMarkdownLink(
url,
text,
urlStartIndex,
offset,
applyFormat
) {
const title = await getTitle(url);
if (title === '') {
return { text, offset };
}
const startSection = text.slice(0, urlStartIndex);
const wrappedUrl = applyFormat(title, url);
const endSection = text.slice(urlStartIndex + url.length);
return {
text: `${startSection}${wrappedUrl}${endSection}`,
offset: urlStartIndex + url.length,
};
}
function isImage(url) {
const imageRegex = new RegExp(DEFAULT_REGEX.imageExtension);
return imageRegex.test(url);
}
function isAlreadyFormatted(text, url, urlIndex, formatBeginning) {
return text.slice(urlIndex - 2, urlIndex) === formatBeginning;
}
function isWrappedInCommand(text, url) {
const wrappedLinks = text.match(DEFAULT_REGEX.wrappedInCommand);
if (!wrappedLinks) {
return false;
}
return wrappedLinks.some((command) => command.includes(url));
}
async function getFormatSettings() {
const { preferredFormat } = await logseq.App.getUserConfigs();
if (!preferredFormat) {
return null;
}
return FORMAT_SETTINGS[preferredFormat];
}
async function parseBlockForLink(uuid: string) {
if (!uuid) {
return;
}
const rawBlock = await logseq.Editor.getBlock(uuid);
if (!rawBlock) {
return;
}
let text = rawBlock.content;
const urls = text.match(DEFAULT_REGEX.line);
if (!urls) {
return;
}
const formatSettings = await getFormatSettings();
if (!formatSettings) {
return;
}
let offset = 0;
for (const url of urls) {
const urlIndex = text.indexOf(url, offset);
if (
isAlreadyFormatted(
text,
url,
urlIndex,
formatSettings.formatBeginning
) ||
isImage(url) ||
isWrappedInCommand(text, url)
) {
continue;
}
const updatedTitle = await convertUrlToMarkdownLink(
url,
text,
urlIndex,
offset,
formatSettings.applyFormat
);
text = updatedTitle.text;
offset = updatedTitle.offset;
}
await logseq.Editor.updateBlock(uuid, text);
}
const main = async () => {
logseq.provideStyle(`
.external-link {
padding: 2px 4px;
border-radius: 3px;
border: 0;
text-decoration: underline;
text-decoration-style: dashed;
text-decoration-thickness: 1px;
text-underline-offset: 2px;
}
.external-link-img {
display: var(--favicons, inline-block);
width: 16px;
height: 16px;
margin: -3px 7px 0 0;
}`);
const doc = parent.document;
const appContainer = doc.getElementById('app-container')!;
// External links favicons
const setFavicon = (extLinkEl: HTMLAnchorElement) => {
const oldFav = extLinkEl.querySelector('.external-link-img');
if (oldFav) {
oldFav.remove();
}
const { hostname } = new URL(extLinkEl.href);
const faviconValue = `https://www.google.com/s2/favicons?domain=${hostname}&sz=32`;
const fav = doc.createElement('img');
fav.src = faviconValue;
fav.width = 16;
fav.height = 16;
fav.classList.add('external-link-img');
extLinkEl.insertAdjacentElement('afterbegin', fav);
};
const extLinksObserverConfig = { childList: true, subtree: true };
const extLinksObserver = new MutationObserver(async (mutationsList) => {
for (const element of mutationsList) {
const addedNode = element.addedNodes[0] as Element;
if (addedNode?.childNodes.length) {
if (addedNode.querySelector('.external-link')) {
const blockId = addedNode
.querySelectorAll('.block-content')[0]
.getAttribute('blockid');
if (blockId) {
await parseBlockForLink(blockId);
setTimeout(() => {
addedNode
.querySelectorAll('.external-link')
.forEach((extLink) => {
const extLinkElement =
extLink as HTMLAnchorElement;
setFavicon(extLinkElement);
});
}, 250);
}
}
}
}
});
setTimeout(() => {
doc
.querySelectorAll('.external-link')
?.forEach((extLink) => setFavicon(extLink as HTMLAnchorElement));
extLinksObserver.observe(appContainer, extLinksObserverConfig);
}, 500);
logseq.Editor.registerBlockContextMenuItem(
'Format url titles',
async ({ uuid }) => {
await parseBlockForLink(uuid);
const extLinkList: NodeListOf<HTMLAnchorElement> =
doc.querySelectorAll('.external-link');
extLinkList.forEach((extLink) => setFavicon(extLink));
}
);
};
logseq.ready(main).catch(console.error);