-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathlink_embed.ts
More file actions
193 lines (162 loc) · 7.04 KB
/
link_embed.ts
File metadata and controls
193 lines (162 loc) · 7.04 KB
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
import "../widgets/type_widgets/text/LinkEmbed.css";
import type { LinkEmbedMetadata } from "@triliumnext/commons";
import server from "./server.js";
/** Paste mode chosen by user from the floating popup. */
export type LinkPasteMode = "mention" | "url" | "embed";
const metadataCache = new Map<string, LinkEmbedMetadata>();
const pendingRequests = new Map<string, Promise<LinkEmbedMetadata>>();
const YOUTUBE_REGEX = /(?:youtube\.com\/watch\?.*v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/;
export function extractYouTubeVideoId(url: string): string | null {
const match = url.match(YOUTUBE_REGEX);
return match ? match[1] : null;
}
export function detectEmbedType(url: string): "youtube" | "opengraph" {
return extractYouTubeVideoId(url) ? "youtube" : "opengraph";
}
export function safeHostname(url: string): string {
try {
return new URL(url).hostname;
} catch {
return url;
}
}
export async function fetchMetadata(url: string): Promise<LinkEmbedMetadata> {
const cached = metadataCache.get(url);
if (cached) return cached;
const pending = pendingRequests.get(url);
if (pending) return pending;
const request = server.get<LinkEmbedMetadata>(`link-embed/metadata?url=${encodeURIComponent(url)}`)
.then((metadata) => {
metadataCache.set(url, metadata);
pendingRequests.delete(url);
return metadata;
})
.catch(() => {
pendingRequests.delete(url);
const fallback: LinkEmbedMetadata = {
url,
title: safeHostname(url),
embedType: detectEmbedType(url)
};
metadataCache.set(url, fallback);
return fallback;
});
pendingRequests.set(url, request);
return request;
}
// ---------------------------------------------------------------------------
// Loading spinner (shared by all renderers)
// ---------------------------------------------------------------------------
function createLoadingEl(): JQuery<HTMLElement> {
return $('<div class="link-embed-loader">').append(
$('<div class="link-embed-loader-dot">'),
$('<div class="link-embed-loader-dot">'),
$('<div class="link-embed-loader-dot">')
);
}
// ---------------------------------------------------------------------------
// Mention renderer (inline: favicon + title)
// ---------------------------------------------------------------------------
export async function renderMention(url: string, $container: JQuery<HTMLElement>) {
$container.empty().append(createLoadingEl());
const metadata = await fetchMetadata(url);
const $link = $('<a class="link-embed-mention">')
.attr("href", metadata.url)
.attr("target", "_blank")
.attr("rel", "noopener noreferrer");
const faviconSrc = metadata.favicon
|| `https://www.google.com/s2/favicons?domain=${encodeURIComponent(safeHostname(url))}&sz=32`;
$link.append(
$('<img class="link-embed-mention-favicon">')
.attr("src", faviconSrc)
.attr("width", "16")
.attr("height", "16")
.on("error", function () { $(this).replaceWith($('<span class="link-embed-mention-dot">')); })
);
const displayTitle = metadata.embedType === "youtube" && metadata.siteName
? `${metadata.siteName} - ${metadata.title || "Video"}`
: metadata.title || safeHostname(url);
$link.append($('<span class="link-embed-mention-title">').text(displayTitle));
$container.empty().append($link);
}
// ---------------------------------------------------------------------------
// Embed renderer (YouTube = iframe, otherwise = card)
// ---------------------------------------------------------------------------
export async function renderEmbed(url: string, embedType: string, $container: JQuery<HTMLElement>) {
const videoId = extractYouTubeVideoId(url);
if (videoId) {
const origin = window.location.origin;
$container.empty().append(
$('<div class="link-embed-video">').append(
$('<iframe>')
.attr("src", `https://www.youtube-nocookie.com/embed/${videoId}?origin=${encodeURIComponent(origin)}&rel=0`)
.attr("frameborder", "0")
.attr("allowfullscreen", "true")
.attr("allow", "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share")
.attr("referrerpolicy", "strict-origin-when-cross-origin")
.attr("loading", "lazy")
)
);
return;
}
// Non-YouTube: card preview
$container.empty().append(createLoadingEl());
const metadata = await fetchMetadata(url);
renderCard(metadata, $container);
}
// ---------------------------------------------------------------------------
// Card renderer (Notion-style: image left, content right)
// ---------------------------------------------------------------------------
function renderCard(metadata: LinkEmbedMetadata, $container: JQuery<HTMLElement>) {
const $card = $('<a class="link-embed-card">')
.attr("href", metadata.url)
.attr("target", "_blank")
.attr("rel", "noopener noreferrer");
if (metadata.image) {
const $imgWrap = $('<div class="link-embed-card-image-wrapper">');
$imgWrap.append(
$('<img class="link-embed-card-image">')
.attr("src", metadata.image)
.attr("alt", "")
.attr("loading", "lazy")
.on("error", function () {
$imgWrap.empty().append($('<div class="link-embed-card-image-placeholder">').html("🔗"));
})
);
$card.append($imgWrap);
} else {
$card.append(
$('<div class="link-embed-card-image-wrapper">').append(
$('<div class="link-embed-card-image-placeholder">').html(
metadata.embedType === "youtube" ? "▶" : "🔗"
)
)
);
}
const $content = $('<div class="link-embed-card-content">');
if (metadata.title) $content.append($('<div class="link-embed-card-title">').text(metadata.title));
if (metadata.description) $content.append($('<div class="link-embed-card-description">').text(metadata.description));
$content.append($('<div class="link-embed-card-url">').text(metadata.siteName || safeHostname(metadata.url)));
$card.append($content);
$container.empty().append($card);
}
/**
* Renders the appropriate preview based on embedType.
* Used by ReadOnlyText and share renderer for persisted elements.
*/
export async function renderPreview(url: string, embedType: string, $container: JQuery<HTMLElement>) {
if (embedType === "mention") {
await renderMention(url, $container);
} else {
await renderEmbed(url, embedType, $container);
}
}
export default {
fetchMetadata,
renderPreview,
renderMention,
renderEmbed,
detectEmbedType,
extractYouTubeVideoId,
safeHostname
};