docs/.vitepress/theme/components/MirrorTooltip.vue
480 lines · 12155 bytes
1<!--
2 All Rights Reserved
3
4 Copyright (c) 2025 taskylizard
5
6 All rights reserved. This code and its associated files may not be copied, modified, distributed, sublicensed, or used in any form, in whole or in part, without prior written permission from the copyright holder.
7-->
8<script setup lang="ts">
9import { computed, nextTick, ref, watch } from 'vue'
10import { resolveFaviconUrl, useFavicons } from '../composables/useFavicons'
11
12const props = withDefaults(
13 defineProps<{
14 id?: string
15 title?: string
16 src?: string
17 note?: string
18 noteType?: string
19 mirrors?: string | string[]
20 }>(),
21 {
22 id: '',
23 title: 'Mirrors',
24 src: '',
25 note: '',
26 noteType: 'warning',
27 mirrors: () => []
28 }
29)
30
31const NOTE_TYPES = ['info', 'tip', 'warning', 'danger'] as const
32
33const noteClass = computed(() =>
34 `mirror-note--${NOTE_TYPES.includes(props.noteType as typeof NOTE_TYPES[number]) ? props.noteType : 'warning'}`
35)
36
37/** Minimal `[text](url)` support for notes (in-wiki + outbound). */
38function renderNoteLinks(text: string): string {
39 const escaped = text
40 .replace(/&/g, '&')
41 .replace(/</g, '<')
42 .replace(/>/g, '>')
43 return escaped.replace(
44 /\[([^\]]+)\]\(([^)\s]+)\)/g,
45 (_m, t: string, u: string) => {
46 const safeUrl = u.replace(/"/g, '"')
47 const safeText = t.replace(/"/g, '"')
48 const attrs = /^https?:\/\//i.test(u)
49 ? ` href="${safeUrl}" target="_blank" rel="noopener noreferrer"`
50 : ` href="${safeUrl}"`
51 return `<a${attrs}>${safeText}</a>`
52 }
53 )
54}
55
56const noteHtml = computed(() => renderNoteLinks(props.note))
57
58const isOpen = ref(false)
59const buttonRef = ref<HTMLElement>()
60const panelRef = ref<HTMLElement>()
61const panelStyle = ref<Record<string, string>>({})
62
63const mirrorList = computed<string[]>(() => {
64 const raw = props.mirrors
65 const list: string[] = Array.isArray(raw)
66 ? [...raw]
67 : typeof raw === 'string' && raw.trim()
68 ? (() => {
69 try {
70 const parsed: unknown = JSON.parse(raw)
71 return Array.isArray(parsed)
72 ? parsed.filter((u): u is string => typeof u === 'string')
73 : []
74 } catch {
75 return []
76 }
77 })()
78 : []
79 const out: string[] = []
80 const seen = new Set<string>()
81 for (const u of list) {
82 const url = (u ?? '').trim()
83 if (!url || seen.has(url)) continue
84 seen.add(url)
85 out.push(url)
86 }
87 return out
88})
89
90interface UrlParts {
91 key: string
92 pre: string
93 tld: string
94 post: string
95 domain: string
96 isOnion: boolean
97}
98
99/** Split `name.tld/path` (scheme hidden) so the last domain label (`.app`, `.com`) can be bolded. */
100const MAX_URL_CHARS = 32
101const MAX_POST_CHARS = 14
102
103function splitUrl(url: string): UrlParts {
104 let pre: string
105 let tld: string
106 let post: string
107 let domain = ''
108 try {
109 const parsed = new URL(url)
110 const host = parsed.host
111 domain = host.toLowerCase()
112 const displayHost = host.replace(/^www\./i, '')
113 const dot = displayHost.lastIndexOf('.')
114 if (dot > 0) {
115 pre = displayHost.slice(0, dot)
116 tld = displayHost.slice(dot)
117 } else {
118 pre = displayHost
119 tld = ''
120 }
121 post = `${parsed.pathname === '/' ? '/' : parsed.pathname}${parsed.search}${parsed.hash}`
122 } catch {
123 pre = url.replace(/^https?:\/\//i, '')
124 tld = ''
125 post = ''
126 }
127 const isOnion = domain
128 ? domain.endsWith('.onion')
129 : /\.onion(\/|$)/i.test(url)
130
131 // Middle-truncate long URLs: the TLD/end stays visible, the middle shrinks.
132 if (pre.length + tld.length + post.length > MAX_URL_CHARS) {
133 const shownPost = post.length > MAX_POST_CHARS
134 ? post.slice(0, MAX_POST_CHARS - 1) + '…'
135 : post
136 const preBudget = Math.max(10, MAX_URL_CHARS - tld.length - shownPost.length)
137 const shownPre = pre.length > preBudget
138 ? pre.slice(0, preBudget - 1) + '…'
139 : pre
140 return { key: url, pre: shownPre, tld, post: shownPost, domain, isOnion }
141 }
142 return { key: url, pre, tld, post, domain, isOnion }
143}
144
145const rows = computed<UrlParts[]>(() => mirrorList.value.map(splitUrl))
146
147const { faviconsEnabled } = useFavicons()
148const faviconMap = ref<Record<string, string | null>>({})
149
150async function loadFavicons() {
151 if (!faviconsEnabled.value) return
152 for (const row of rows.value) {
153 if (row.isOnion || !row.domain || faviconMap.value[row.key] !== undefined) {
154 continue
155 }
156 faviconMap.value[row.key] = await resolveFaviconUrl(row.domain)
157 }
158}
159
160// Fixed-position panel teleported to <body> so table overflow clipping
161// (and tab containers) can't cut it off — same approach as icon-tip-popup.
162function positionPanel() {
163 const btn = buttonRef.value
164 const panel = panelRef.value
165 if (!btn || !panel) return
166 const rect = btn.getBoundingClientRect()
167 const pw = panel.offsetWidth
168 const ph = panel.offsetHeight
169 const margin = 8
170 let left = rect.left + rect.width / 2 - pw / 2
171 left = Math.max(margin, Math.min(left, window.innerWidth - pw - margin))
172 let top = rect.top - ph - 8
173 if (top < margin) top = rect.bottom + 8
174 if (top + ph > window.innerHeight - margin) {
175 top = Math.max(margin, window.innerHeight - ph - margin)
176 }
177 panelStyle.value = { left: `${left}px`, top: `${top}px` }
178}
179
180function onDocumentClick(e: MouseEvent) {
181 const t = e.target as Node | null
182 if (!t) return
183 if (buttonRef.value?.contains(t)) return
184 if (panelRef.value?.contains(t)) return
185 isOpen.value = false
186}
187
188function onScroll(e: Event) {
189 const t = e.target as Node | null
190 if (t && panelRef.value?.contains(t)) return
191 isOpen.value = false
192}
193
194function onKey(e: KeyboardEvent) {
195 if (e.key === 'Escape') isOpen.value = false
196}
197
198function onResize() {
199 if (isOpen.value) positionPanel()
200}
201
202watch(isOpen, (open) => {
203 if (!open) {
204 document.removeEventListener('click', onDocumentClick, true)
205 document.removeEventListener('scroll', onScroll, true)
206 window.removeEventListener('keydown', onKey)
207 window.removeEventListener('resize', onResize)
208 return
209 }
210 void nextTick(() => {
211 positionPanel()
212 void loadFavicons()
213 })
214 document.addEventListener('click', onDocumentClick, true)
215 document.addEventListener('scroll', onScroll, true)
216 window.addEventListener('keydown', onKey)
217 window.addEventListener('resize', onResize)
218})
219
220watch(faviconsEnabled, (enabled) => {
221 if (enabled && isOpen.value) void loadFavicons()
222})
223</script>
224
225<template>
226 <span ref="buttonRef" class="mirror-wrapper">
227 <button
228 type="button"
229 aria-label="Mirrors"
230 class="mirror-btn size-3 p-0 select-none font-bold cursor-pointer"
231 :aria-expanded="isOpen"
232 @click="isOpen = !isOpen"
233 >
234 <div class="i-material-symbols-directions-alt" />
235 </button>
236 </span>
237
238 <Teleport to="body">
239 <Transition name="mirror-panel">
240 <div
241 v-if="isOpen"
242 ref="panelRef"
243 class="mirror-panel"
244 :style="panelStyle"
245 role="dialog"
246 :aria-label="`Mirrors for ${title}`"
247 >
248 <div class="mirror-head">
249 <span class="mirror-head-title">{{ title }}</span>
250 <span class="mirror-head-count">{{ rows.length }}</span>
251 </div>
252 <p v-if="note" class="mirror-note" :class="noteClass" v-html="noteHtml" />
253 <div class="mirror-scroll">
254 <ul v-if="rows.length" class="mirror-list">
255 <li v-for="row in rows" :key="row.key" class="mirror-item">
256 <a
257 :href="row.key"
258 target="_blank"
259 rel="noopener noreferrer"
260 class="mirror-link"
261 :title="row.key"
262 >
263 <img
264 v-if="faviconsEnabled && !row.isOnion && faviconMap[row.key]"
265 :src="faviconMap[row.key] ?? undefined"
266 class="mirror-favicon"
267 alt=""
268 width="14"
269 height="14"
270 loading="lazy"
271 decoding="async"
272 @error="faviconMap[row.key] = null"
273 />
274 <span
275 v-else-if="row.isOnion"
276 class="i-simple-icons-torbrowser mirror-link-icon"
277 aria-hidden="true"
278 />
279 <span
280 v-else
281 class="i-lucide-globe mirror-link-icon"
282 aria-hidden="true"
283 />
284 <span class="mirror-link-text">{{ row.pre }}<strong class="mirror-tld">{{ row.tld }}</strong>{{ row.post }}</span>
285 </a>
286 </li>
287 </ul>
288 <p v-else class="mirror-empty">No mirrors listed yet.</p>
289 </div>
290 </div>
291 </Transition>
292 </Teleport>
293</template>
294
295<style scoped>
296.mirror-wrapper {
297 display: inline-flex !important;
298 vertical-align: -0.125em;
299}
300
301.mirror-btn {
302 color: var(--vp-c-brand-1);
303}
304
305.mirror-panel {
306 position: fixed;
307 z-index: 9999;
308 width: 282px;
309 max-width: calc(100vw - 24px);
310 background-color: var(--vp-c-bg-elv);
311 border: 2px solid #3d3d3d;
312 border-radius: 12px;
313 box-shadow: var(--vp-shadow-3);
314 transform-origin: top center;
315 overflow: hidden;
316}
317
318.mirror-head {
319 display: flex;
320 align-items: center;
321 gap: 8px;
322 padding: 10px 12px 6px;
323 user-select: none;
324}
325
326.mirror-head-title {
327 flex: 1;
328 min-width: 0;
329 overflow: hidden;
330 white-space: nowrap;
331 text-overflow: ellipsis;
332 font-size: 14px;
333 font-weight: 600;
334 color: var(--vp-c-text-1);
335}
336
337.mirror-head-count {
338 flex: none;
339 font-size: 11px;
340 font-weight: 600;
341 color: var(--vp-c-text-3);
342 border: 1px solid var(--vp-c-divider);
343 border-radius: 999px;
344 padding: 0 7px;
345 line-height: 18px;
346}
347
348.mirror-scroll {
349 max-height: 280px;
350 overflow-y: auto;
351 overflow-x: hidden;
352 overscroll-behavior: contain;
353 padding: 4px 8px 10px;
354}
355
356.mirror-list {
357 list-style: none;
358 padding: 0;
359 margin: 0;
360 display: flex;
361 flex-direction: column;
362 gap: 2px;
363}
364
365.mirror-item {
366 display: flex;
367 align-items: center;
368 gap: 6px;
369 border-radius: 8px;
370 padding: 2px 4px;
371 transition: background-color 0.15s;
372}
373
374.mirror-item:hover {
375 background: var(--vp-c-default-soft);
376}
377
378.mirror-link {
379 display: flex;
380 align-items: center;
381 gap: 6px;
382 flex: 1;
383 min-width: 0;
384 padding: 4px 6px;
385 font-size: 13px;
386 color: var(--vp-c-text-2);
387 text-decoration: none;
388 transition: color 0.15s;
389}
390
391.mirror-link:hover {
392 color: var(--vp-c-brand-1);
393}
394
395.mirror-link-icon {
396 flex: none;
397 font-size: 12px;
398 color: var(--vp-c-text-3);
399}
400
401.mirror-favicon {
402 flex: none;
403 width: 14px;
404 height: 14px;
405 border-radius: 3px;
406}
407
408.mirror-link-text {
409 flex: 1;
410 min-width: 0;
411 overflow: hidden;
412 white-space: nowrap;
413 text-overflow: ellipsis;
414}
415
416.mirror-tld {
417 font-weight: 700;
418 color: var(--vp-c-text-1);
419}
420
421.mirror-empty {
422 margin: 0;
423 padding: 8px 6px;
424 font-size: 13px;
425 color: var(--vp-c-text-3);
426}
427
428.mirror-note {
429 margin: 2px 8px 6px;
430 padding: 6px 8px;
431 font-size: 12px;
432 line-height: 1.5;
433 border: 1px solid;
434 border-radius: 8px;
435}
436
437.mirror-note--info {
438 color: var(--vp-custom-block-info-text);
439 background-color: var(--vp-custom-block-info-bg);
440 border-color: var(--vp-custom-block-info-border);
441}
442
443.mirror-note--tip {
444 color: var(--vp-custom-block-tip-text);
445 background-color: var(--vp-custom-block-tip-bg);
446 border-color: var(--vp-custom-block-tip-border);
447}
448
449.mirror-note--warning {
450 color: var(--vp-custom-block-warning-text);
451 background-color: var(--vp-custom-block-warning-bg);
452 border-color: var(--vp-custom-block-warning-border);
453}
454
455.mirror-note--danger {
456 color: var(--vp-custom-block-danger-text);
457 background-color: var(--vp-custom-block-danger-bg);
458 border-color: var(--vp-custom-block-danger-border);
459}
460
461.mirror-note :deep(a) {
462 color: inherit;
463 font-weight: 600;
464 text-decoration: underline dashed;
465 text-underline-offset: 3px;
466 text-decoration-thickness: 1px;
467}
468
469.mirror-panel-enter-active,
470.mirror-panel-leave-active {
471 transition: opacity 0.15s, transform 0.15s cubic-bezier(0.16, 1, 0.3, 1);
472}
473
474.mirror-panel-enter-from,
475.mirror-panel-leave-to {
476 opacity: 0;
477 transform: scale(0.95) translateY(4px);
478}
479
480</style>