feat: support sending and preview links
This commit is contained in:
@@ -0,0 +1,104 @@
|
|||||||
|
import { Copy, ExternalLink, Globe } from "lucide-react";
|
||||||
|
import type { LinkMetadata } from "@/lib/link-metadata";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface LinkPreviewCardProps {
|
||||||
|
metadata: LinkMetadata;
|
||||||
|
compact?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LinkPreviewCard({ metadata, compact }: LinkPreviewCardProps) {
|
||||||
|
const handleOpen = (e: React.MouseEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
window.electronLink.openExternal(metadata.url);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCopy = (e: React.MouseEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
navigator.clipboard.writeText(metadata.url);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="max-w-sm overflow-hidden rounded-2xl bg-white/10 backdrop-blur-md"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{metadata.image && (
|
||||||
|
<img
|
||||||
|
src={metadata.image}
|
||||||
|
alt=""
|
||||||
|
className="h-32 w-full object-cover"
|
||||||
|
onError={(e) => {
|
||||||
|
(e.target as HTMLImageElement).style.display = "none";
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<div className="flex flex-col gap-1 p-3">
|
||||||
|
<div className="flex items-center gap-1.5 text-xs text-white/50">
|
||||||
|
{metadata.favicon ? (
|
||||||
|
<img
|
||||||
|
src={metadata.favicon}
|
||||||
|
alt=""
|
||||||
|
className="size-4 rounded-sm"
|
||||||
|
onError={(e) => {
|
||||||
|
(e.target as HTMLImageElement).replaceWith(
|
||||||
|
document.createElement("span"),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Globe className="size-4" />
|
||||||
|
)}
|
||||||
|
<span className="truncate">{metadata.domain}</span>
|
||||||
|
</div>
|
||||||
|
{metadata.title && (
|
||||||
|
<p className="truncate text-sm font-semibold leading-snug text-white">
|
||||||
|
{metadata.title}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{metadata.description && (
|
||||||
|
<p className="line-clamp-2 text-xs leading-relaxed text-white/70">
|
||||||
|
{metadata.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{!compact && (
|
||||||
|
<div className="mt-1.5 flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="xs"
|
||||||
|
className="text-white/70 hover:bg-white/10 hover:text-white"
|
||||||
|
onClick={handleOpen}
|
||||||
|
>
|
||||||
|
<ExternalLink data-icon="inline-start" />
|
||||||
|
Open
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="xs"
|
||||||
|
className="text-white/70 hover:bg-white/10 hover:text-white"
|
||||||
|
onClick={handleCopy}
|
||||||
|
>
|
||||||
|
<Copy data-icon="inline-start" />
|
||||||
|
Copy
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LinkPreviewCardSkeleton() {
|
||||||
|
return (
|
||||||
|
<div className="max-w-sm overflow-hidden rounded-2xl bg-white/10 backdrop-blur-md">
|
||||||
|
<Skeleton className="h-32 w-full rounded-none bg-white/5" />
|
||||||
|
<div className="flex flex-col gap-2 p-3">
|
||||||
|
<Skeleton className="h-3 w-24 bg-white/10" />
|
||||||
|
<Skeleton className="h-4 w-48 bg-white/10" />
|
||||||
|
<Skeleton className="h-3 w-full bg-white/10" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Vendored
+16
-6
@@ -1,7 +1,17 @@
|
|||||||
interface Window {
|
import type { LinkMetadata } from './lib/link-metadata';
|
||||||
electronWindow: {
|
|
||||||
minimize: () => void;
|
declare global {
|
||||||
maximize: () => void;
|
interface Window {
|
||||||
close: () => void;
|
electronWindow: {
|
||||||
};
|
minimize: () => void;
|
||||||
|
maximize: () => void;
|
||||||
|
close: () => void;
|
||||||
|
};
|
||||||
|
electronLink: {
|
||||||
|
fetchMetadata: (url: string) => Promise<LinkMetadata | null>;
|
||||||
|
openExternal: (url: string) => Promise<void>;
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export {};
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import { useEffect, useRef, useCallback } from "react";
|
import { useEffect, useRef, useCallback, useState } from "react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { useFirstLinkMetadata } from "@/hooks/use-link-metadata";
|
||||||
|
import {
|
||||||
|
LinkPreviewCard,
|
||||||
|
LinkPreviewCardSkeleton,
|
||||||
|
} from "@/components/link-preview-card";
|
||||||
|
|
||||||
interface TextComposeStepProps {
|
interface TextComposeStepProps {
|
||||||
textContent: string;
|
textContent: string;
|
||||||
@@ -8,11 +13,12 @@ interface TextComposeStepProps {
|
|||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getTextStyle(length: number) {
|
const IMMERSIVE_CHAR_LIMIT = 120;
|
||||||
if (length < 50) return { size: "text-5xl", weight: "font-semibold" };
|
|
||||||
if (length < 150) return { size: "text-3xl", weight: "font-semibold" };
|
function getImmersiveTextStyle(length: number) {
|
||||||
if (length < 300) return { size: "text-2xl", weight: "font-normal" };
|
if (length < 30) return { size: "text-5xl", weight: "font-semibold" };
|
||||||
return { size: "text-lg", weight: "font-normal" };
|
if (length < 70) return { size: "text-3xl", weight: "font-semibold" };
|
||||||
|
return { size: "text-2xl", weight: "font-normal" };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TextComposeStep({
|
export function TextComposeStep({
|
||||||
@@ -23,6 +29,14 @@ export function TextComposeStep({
|
|||||||
}: TextComposeStepProps) {
|
}: TextComposeStepProps) {
|
||||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
// Debounce URL detection to avoid fetching on every keystroke
|
||||||
|
const [debouncedText, setDebouncedText] = useState(textContent);
|
||||||
|
useEffect(() => {
|
||||||
|
const t = setTimeout(() => setDebouncedText(textContent), 500);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [textContent]);
|
||||||
|
const { data: metadata, isLoading, url: firstUrl } = useFirstLinkMetadata(debouncedText);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
textareaRef.current?.focus();
|
textareaRef.current?.focus();
|
||||||
}, []);
|
}, []);
|
||||||
@@ -40,37 +54,79 @@ export function TextComposeStep({
|
|||||||
[onCancel, onAdvance, textContent],
|
[onCancel, onAdvance, textContent],
|
||||||
);
|
);
|
||||||
|
|
||||||
const style = getTextStyle(textContent.length);
|
const immersive = textContent.length < IMMERSIVE_CHAR_LIMIT;
|
||||||
|
const showPreview = firstUrl && (isLoading || metadata);
|
||||||
|
|
||||||
|
const linkPreview = (
|
||||||
|
<>
|
||||||
|
{firstUrl && isLoading && <LinkPreviewCardSkeleton />}
|
||||||
|
{firstUrl && metadata && <LinkPreviewCard metadata={metadata} compact />}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
const keyboardHints = (
|
||||||
|
<div className="absolute bottom-8 flex items-center gap-4 text-sm text-white/50">
|
||||||
|
<span>
|
||||||
|
<kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
|
||||||
|
Esc
|
||||||
|
</kbd>{" "}
|
||||||
|
cancel
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
<kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
|
||||||
|
⌘+Enter
|
||||||
|
</kbd>{" "}
|
||||||
|
next
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (immersive) {
|
||||||
|
const style = getImmersiveTextStyle(textContent.length);
|
||||||
|
return (
|
||||||
|
<div className="absolute inset-0 z-50 flex items-center justify-center bg-black/90">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex w-full items-center justify-center gap-6 px-6",
|
||||||
|
showPreview ? "flex-row" : "flex-col",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<textarea
|
||||||
|
ref={textareaRef}
|
||||||
|
value={textContent}
|
||||||
|
onChange={(e) => onTextChange(e.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
placeholder="Type a message..."
|
||||||
|
className={cn(
|
||||||
|
"flex-1 resize-none border-none bg-transparent p-8 text-white placeholder-white/40 outline-none",
|
||||||
|
showPreview ? "text-left" : "text-center",
|
||||||
|
style.size,
|
||||||
|
style.weight,
|
||||||
|
)}
|
||||||
|
rows={4}
|
||||||
|
/>
|
||||||
|
{showPreview && <div className="shrink-0">{linkPreview}</div>}
|
||||||
|
</div>
|
||||||
|
{keyboardHints}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="absolute inset-0 z-50 flex items-center justify-center bg-black/90">
|
<div className="absolute inset-0 z-50 flex items-center justify-center bg-black/90">
|
||||||
<textarea
|
<div className="flex max-h-[calc(100%-6rem)] max-w-md flex-col gap-4 overflow-y-auto rounded-2xl bg-white/10 p-5 backdrop-blur-md">
|
||||||
ref={textareaRef}
|
<textarea
|
||||||
value={textContent}
|
ref={textareaRef}
|
||||||
onChange={(e) => onTextChange(e.target.value)}
|
value={textContent}
|
||||||
onKeyDown={handleKeyDown}
|
onChange={(e) => onTextChange(e.target.value)}
|
||||||
placeholder="Type a message..."
|
onKeyDown={handleKeyDown}
|
||||||
className={cn(
|
placeholder="Type a message..."
|
||||||
"w-full max-w-2xl resize-none border-none bg-transparent p-8 text-center text-white placeholder-white/40 outline-none",
|
className="w-full resize-none border-none bg-transparent text-base leading-relaxed text-white placeholder-white/40 outline-none"
|
||||||
style.size,
|
rows={6}
|
||||||
style.weight,
|
/>
|
||||||
)}
|
{showPreview && linkPreview}
|
||||||
rows={4}
|
|
||||||
/>
|
|
||||||
<div className="absolute bottom-8 flex items-center gap-4 text-sm text-white/50">
|
|
||||||
<span>
|
|
||||||
<kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
|
|
||||||
Esc
|
|
||||||
</kbd>{" "}
|
|
||||||
cancel
|
|
||||||
</span>
|
|
||||||
<span>
|
|
||||||
<kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
|
|
||||||
⌘+Enter
|
|
||||||
</kbd>{" "}
|
|
||||||
next
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
{keyboardHints}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import type { Particle } from "@/api/types";
|
import type { Particle } from "@/api/types";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { useFirstLinkMetadata } from "@/hooks/use-link-metadata";
|
||||||
|
import {
|
||||||
|
LinkPreviewCard,
|
||||||
|
LinkPreviewCardSkeleton,
|
||||||
|
} from "@/components/link-preview-card";
|
||||||
|
|
||||||
type TextParticle = Extract<Particle, { type: "text" }>;
|
type TextParticle = Extract<Particle, { type: "text" }>;
|
||||||
|
|
||||||
@@ -11,22 +16,27 @@ interface TextParticleViewProps {
|
|||||||
onProgress?: (ratio: number) => void;
|
onProgress?: (ratio: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const WORDS_PER_MINUTE = 200;
|
// Characters per minute (~1000 cpm ≈ 200 wpm at ~5 chars/word)
|
||||||
|
const CHARS_PER_MINUTE = 1000;
|
||||||
const MIN_DURATION_S = 3;
|
const MIN_DURATION_S = 3;
|
||||||
const MAX_DURATION_S = 15;
|
const MAX_DURATION_S = 15;
|
||||||
const TICK_MS = 100;
|
const TICK_MS = 100;
|
||||||
|
const LINK_EXTRA_DURATION_S = 3;
|
||||||
|
|
||||||
function computeReadDuration(text: string): number {
|
// Below this threshold: immersive centered display
|
||||||
const wordCount = text.trim().split(/\s+/).length;
|
// Above: contained left-aligned card
|
||||||
const seconds = (wordCount / WORDS_PER_MINUTE) * 60;
|
const IMMERSIVE_CHAR_LIMIT = 120;
|
||||||
|
|
||||||
|
function computeReadDuration(text: string, hasLink: boolean): number {
|
||||||
|
const base = (text.length / CHARS_PER_MINUTE) * 60;
|
||||||
|
const seconds = hasLink ? base + LINK_EXTRA_DURATION_S : base;
|
||||||
return Math.min(Math.max(seconds, MIN_DURATION_S), MAX_DURATION_S);
|
return Math.min(Math.max(seconds, MIN_DURATION_S), MAX_DURATION_S);
|
||||||
}
|
}
|
||||||
|
|
||||||
function getTextStyle(length: number) {
|
function getImmersiveTextStyle(length: number) {
|
||||||
if (length < 50) return { size: "text-5xl", weight: "font-semibold" };
|
if (length < 30) return { size: "text-5xl", weight: "font-semibold" };
|
||||||
if (length < 150) return { size: "text-3xl", weight: "font-semibold" };
|
if (length < 70) return { size: "text-3xl", weight: "font-semibold" };
|
||||||
if (length < 300) return { size: "text-2xl", weight: "font-normal" };
|
return { size: "text-2xl", weight: "font-normal" };
|
||||||
return { size: "text-lg", weight: "font-normal" };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TextParticleView({
|
export function TextParticleView({
|
||||||
@@ -35,8 +45,11 @@ export function TextParticleView({
|
|||||||
onEnded,
|
onEnded,
|
||||||
onProgress,
|
onProgress,
|
||||||
}: TextParticleViewProps) {
|
}: TextParticleViewProps) {
|
||||||
const style = getTextStyle(particle.properties.content.length);
|
const content = particle.properties.content;
|
||||||
const durationS = computeReadDuration(particle.properties.content);
|
const { data: metadata, isLoading, url: firstUrl } = useFirstLinkMetadata(content);
|
||||||
|
const hasLink = !!firstUrl;
|
||||||
|
const immersive = content.length < IMMERSIVE_CHAR_LIMIT;
|
||||||
|
const durationS = computeReadDuration(content, hasLink);
|
||||||
const elapsedRef = useRef(0);
|
const elapsedRef = useRef(0);
|
||||||
|
|
||||||
// Reset elapsed when particle changes
|
// Reset elapsed when particle changes
|
||||||
@@ -61,17 +74,51 @@ export function TextParticleView({
|
|||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, [paused, durationS, onEnded, onProgress, particle.id]);
|
}, [paused, durationS, onEnded, onProgress, particle.id]);
|
||||||
|
|
||||||
|
const linkPreview = (
|
||||||
|
<>
|
||||||
|
{isLoading && <LinkPreviewCardSkeleton />}
|
||||||
|
{metadata && <LinkPreviewCard metadata={metadata} />}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Content is just a bare URL with no surrounding text
|
||||||
|
const linkOnly = hasLink && content.trim() === firstUrl;
|
||||||
|
|
||||||
|
if (linkOnly) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-full w-full items-center justify-center bg-gradient-to-b from-black/40 via-black/20 to-black/40 p-8">
|
||||||
|
{linkPreview}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (immersive && !hasLink) {
|
||||||
|
const style = getImmersiveTextStyle(content.length);
|
||||||
|
return (
|
||||||
|
<div className="flex h-full w-full flex-col items-center justify-center bg-gradient-to-b from-black/40 via-black/20 to-black/40 p-8">
|
||||||
|
<p
|
||||||
|
className={cn(
|
||||||
|
"max-w-2xl break-words text-center leading-relaxed text-white",
|
||||||
|
style.size,
|
||||||
|
style.weight,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-full w-full items-center justify-center bg-gradient-to-b from-black/40 via-black/20 to-black/40 p-8">
|
<div className="flex h-full w-full items-center justify-center bg-gradient-to-b from-black/40 via-black/20 to-black/40 p-8">
|
||||||
<p
|
<div className="flex max-h-full w-full max-w-3xl items-center gap-6 px-2">
|
||||||
className={cn(
|
<div className="flex-1 overflow-y-auto rounded-2xl bg-white/10 p-5 backdrop-blur-md">
|
||||||
"max-w-2xl text-center leading-relaxed text-white",
|
<p className="break-words text-base leading-relaxed text-white">
|
||||||
style.size,
|
{content}
|
||||||
style.weight,
|
</p>
|
||||||
)}
|
</div>
|
||||||
>
|
{hasLink && <div className="shrink-0">{linkPreview}</div>}
|
||||||
{particle.properties.content}
|
</div>
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { extractUrls, type LinkMetadata } from "@/lib/link-metadata";
|
||||||
|
|
||||||
|
export function useLinkMetadata(url: string | null) {
|
||||||
|
return useQuery<LinkMetadata | null>({
|
||||||
|
queryKey: ["link-metadata", url],
|
||||||
|
queryFn: () => window.electronLink.fetchMetadata(url!),
|
||||||
|
enabled: !!url,
|
||||||
|
staleTime: Infinity,
|
||||||
|
gcTime: 30 * 60 * 1000,
|
||||||
|
retry: 1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useFirstLinkMetadata(text: string) {
|
||||||
|
const urls = extractUrls(text);
|
||||||
|
const firstUrl = urls[0] ?? null;
|
||||||
|
return { ...useLinkMetadata(firstUrl), url: firstUrl };
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
export interface LinkMetadata {
|
||||||
|
url: string;
|
||||||
|
title: string | null;
|
||||||
|
description: string | null;
|
||||||
|
image: string | null;
|
||||||
|
favicon: string | null;
|
||||||
|
domain: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const URL_REGEX = /https?:\/\/[^\s<>"')\]]+/g;
|
||||||
|
|
||||||
|
export function extractUrls(text: string): string[] {
|
||||||
|
return Array.from(text.matchAll(URL_REGEX), (m) => m[0]);
|
||||||
|
}
|
||||||
+117
-1
@@ -1,8 +1,10 @@
|
|||||||
import { app, BrowserWindow, ipcMain, session } from 'electron';
|
import { app, BrowserWindow, ipcMain, session, shell } from 'electron';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import started from 'electron-squirrel-startup';
|
import started from 'electron-squirrel-startup';
|
||||||
import { updateElectronApp, UpdateSourceType } from 'update-electron-app';
|
import { updateElectronApp, UpdateSourceType } from 'update-electron-app';
|
||||||
|
|
||||||
|
import type { LinkMetadata } from './lib/link-metadata';
|
||||||
|
|
||||||
updateElectronApp({
|
updateElectronApp({
|
||||||
updateSource: {
|
updateSource: {
|
||||||
type: UpdateSourceType.StaticStorage,
|
type: UpdateSourceType.StaticStorage,
|
||||||
@@ -59,6 +61,120 @@ ipcMain.on('window:close', (event) => {
|
|||||||
BrowserWindow.fromWebContents(event.sender)?.close();
|
BrowserWindow.fromWebContents(event.sender)?.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- Link metadata ---
|
||||||
|
|
||||||
|
const metadataCache = new Map<string, LinkMetadata>();
|
||||||
|
|
||||||
|
function getMetaContent(html: string, property: string): string | null {
|
||||||
|
// Match both property="..." and name="..." attributes
|
||||||
|
const regex = new RegExp(
|
||||||
|
`<meta[^>]*(?:property|name)=["']${property}["'][^>]*content=["']([^"']*)["']|<meta[^>]*content=["']([^"']*)["'][^>]*(?:property|name)=["']${property}["']`,
|
||||||
|
'i',
|
||||||
|
);
|
||||||
|
const match = html.match(regex);
|
||||||
|
return match?.[1] ?? match?.[2] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTitle(html: string): string | null {
|
||||||
|
const match = html.match(/<title[^>]*>([^<]*)<\/title>/i);
|
||||||
|
return match?.[1]?.trim() ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getFavicon(html: string, baseUrl: string): string | null {
|
||||||
|
const match = html.match(/<link[^>]*rel=["'](?:shortcut )?icon["'][^>]*href=["']([^"']*)["']/i)
|
||||||
|
?? html.match(/<link[^>]*href=["']([^"']*)["'][^>]*rel=["'](?:shortcut )?icon["']/i);
|
||||||
|
if (!match?.[1]) {
|
||||||
|
// Fall back to /favicon.ico
|
||||||
|
try {
|
||||||
|
const url = new URL(baseUrl);
|
||||||
|
return `${url.protocol}//${url.host}/favicon.ico`;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return new URL(match[1], baseUrl).href;
|
||||||
|
} catch {
|
||||||
|
return match[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveUrl(src: string | null, baseUrl: string): string | null {
|
||||||
|
if (!src) return null;
|
||||||
|
try {
|
||||||
|
return new URL(src, baseUrl).href;
|
||||||
|
} catch {
|
||||||
|
return src;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchLinkMetadata(url: string): Promise<LinkMetadata | null> {
|
||||||
|
const cached = metadataCache.get(url);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), 5000);
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
signal: controller.signal,
|
||||||
|
headers: {
|
||||||
|
'User-Agent': 'Mozilla/5.0 (compatible; llink/1.0)',
|
||||||
|
'Accept': 'text/html',
|
||||||
|
},
|
||||||
|
redirect: 'follow',
|
||||||
|
});
|
||||||
|
clearTimeout(timeout);
|
||||||
|
|
||||||
|
if (!response.ok) return null;
|
||||||
|
|
||||||
|
// Only read the first ~50KB to get <head> content
|
||||||
|
const reader = response.body?.getReader();
|
||||||
|
if (!reader) return null;
|
||||||
|
|
||||||
|
let html = '';
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
while (html.length < 50_000) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
html += decoder.decode(value, { stream: true });
|
||||||
|
}
|
||||||
|
reader.cancel();
|
||||||
|
|
||||||
|
const domain = new URL(url).hostname.replace(/^www\./, '');
|
||||||
|
const metadata: LinkMetadata = {
|
||||||
|
url,
|
||||||
|
title: getMetaContent(html, 'og:title') ?? getTitle(html),
|
||||||
|
description: getMetaContent(html, 'og:description') ?? getMetaContent(html, 'description'),
|
||||||
|
image: resolveUrl(getMetaContent(html, 'og:image'), url),
|
||||||
|
favicon: getFavicon(html, url),
|
||||||
|
domain,
|
||||||
|
};
|
||||||
|
|
||||||
|
metadataCache.set(url, metadata);
|
||||||
|
return metadata;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ipcMain.handle('link:fetch-metadata', async (_event, url: string) => {
|
||||||
|
if (typeof url !== 'string') return null;
|
||||||
|
try {
|
||||||
|
new URL(url);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return fetchLinkMetadata(url);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('link:open-external', async (_event, url: string) => {
|
||||||
|
if (typeof url !== 'string') return;
|
||||||
|
// Only allow http(s) URLs for security
|
||||||
|
if (!url.startsWith('http://') && !url.startsWith('https://')) return;
|
||||||
|
await shell.openExternal(url);
|
||||||
|
});
|
||||||
|
|
||||||
// This method will be called when Electron has finished
|
// This method will be called when Electron has finished
|
||||||
// initialization and is ready to create browser windows.
|
// initialization and is ready to create browser windows.
|
||||||
// Some APIs can only be used after this event occurs.
|
// Some APIs can only be used after this event occurs.
|
||||||
|
|||||||
@@ -7,3 +7,8 @@ contextBridge.exposeInMainWorld('electronWindow', {
|
|||||||
maximize: () => ipcRenderer.send('window:maximize'),
|
maximize: () => ipcRenderer.send('window:maximize'),
|
||||||
close: () => ipcRenderer.send('window:close'),
|
close: () => ipcRenderer.send('window:close'),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
contextBridge.exposeInMainWorld('electronLink', {
|
||||||
|
fetchMetadata: (url: string) => ipcRenderer.invoke('link:fetch-metadata', url),
|
||||||
|
openExternal: (url: string) => ipcRenderer.invoke('link:open-external', url),
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user