185 lines
7.5 KiB
TypeScript
185 lines
7.5 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect, useRef, useCallback, type ReactNode } from "react";
|
|
import { createShortLink } from "@/lib/share";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Kautilya Icon
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export function KautilyaIcon({ className }: { className?: string }) {
|
|
return (
|
|
<svg
|
|
xmlns="http://www.w3.org/2000/svg"
|
|
viewBox="0 0 512 512"
|
|
fill="currentColor"
|
|
className={className}
|
|
>
|
|
<path d="M205.867,364.795c-5.754,0.608-15.501,1.389-27.658,1.389c-31.076,0-77.727-5.134-112.693-31.359 C34.93,350.329,10.713,375.897,0,388.396c15.983,18.648,62.023,66.389,114.434,66.388c52.577,0,98.505-47.727,114.441-66.377 C223.894,382.593,215.985,373.945,205.867,364.795z" />
|
|
<path d="M446.245,334.708c-34.981,26.324-81.723,31.476-112.845,31.476c-11.916,0-21.519-0.75-27.316-1.353 c-10.091,9.129-17.982,17.757-22.959,23.564c15.982,18.648,62.018,66.389,114.43,66.388 c52.578,0.001,98.508-47.726,114.445-66.375C501.269,375.884,476.952,350.206,446.245,334.708z" />
|
|
<path d="M198.416,340.733c0.055-0.718,0.109-1.48,0.164-2.27c-27.465-32.128-55.905-77.85-55.905-129.438 c0-4.031,0.189-8.023,0.523-11.979C105.908,176.27,56.889,177.339,36.586,178.9c-1.886,24.489-3.088,90.803,33.973,127.861 C107.615,343.819,173.925,342.617,198.416,340.733z" />
|
|
<path d="M313.088,339.308c0.034,0.48,0.068,0.974,0.102,1.426c24.474,1.885,90.793,3.092,127.855-33.972 c37.179-37.176,35.908-103.403,33.99-127.859c-20.149-1.554-68.666-2.629-105.873,17.723c0.357,4.093,0.556,8.224,0.556,12.398 C369.718,261.067,340.775,307.139,313.088,339.308z" />
|
|
<path d="M256.194,57.217c-22.488,18.886-88.917,80.701-88.917,151.809c0,71.11,66.429,132.927,88.917,151.811 c22.479-18.876,88.922-80.696,88.922-151.811C345.116,137.918,278.683,76.101,256.194,57.217z" />
|
|
</svg>
|
|
);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Types
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export type Position = { x: number; y: number };
|
|
|
|
export type ToolbarAction = {
|
|
key: string;
|
|
label: string;
|
|
icon: ReactNode;
|
|
onClick: () => void;
|
|
className?: string;
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Hook: useMediaQuery
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export function useMediaQuery(query: string): boolean {
|
|
const [matches, setMatches] = useState(() => {
|
|
if (typeof window === "undefined") return false;
|
|
return window.matchMedia(query).matches;
|
|
});
|
|
|
|
useEffect(() => {
|
|
const mq = window.matchMedia(query);
|
|
const handler = (e: MediaQueryListEvent) => setMatches(e.matches);
|
|
mq.addEventListener("change", handler);
|
|
return () => mq.removeEventListener("change", handler);
|
|
}, [query]);
|
|
|
|
return matches;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Hook: copy to clipboard with success feedback
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Match a URL inside the copy payload that carries a `?hl=` highlight
|
|
// fragment. Used by useCopyFeedback to transparently swap such URLs for the
|
|
// short `/share/<code>` form before writing to the clipboard. The native
|
|
// ⌘C / Ctrl+C path goes through a different (synchronous) handler in
|
|
// text-selection-toolbar.tsx and is intentionally not affected.
|
|
//
|
|
// The regex stops at whitespace or trailing punctuation that wouldn't appear
|
|
// in a real URL (`>`, `]`, etc.), so it works against multi-line copy
|
|
// payloads like the source-attribution block produced by formatCopyText().
|
|
const HL_URL_RE = /https?:\/\/[^\s<>"'`)\]]+\?hl=[^\s<>"'`)\]]+/g;
|
|
|
|
async function shortenHighlightUrlsIn(text: string): Promise<string> {
|
|
// Cheap pre-check — most text passed to copy() has no `?hl=` URL.
|
|
if (!text.includes("?hl=")) return text;
|
|
|
|
const matches = Array.from(text.matchAll(HL_URL_RE));
|
|
if (matches.length === 0) return text;
|
|
|
|
let result = text;
|
|
for (const m of matches) {
|
|
const longUrl = m[0];
|
|
try {
|
|
const u = new URL(longUrl);
|
|
const relativePath = u.pathname + u.search + u.hash;
|
|
const code = await createShortLink(relativePath);
|
|
if (!code) continue; // BFF failed — leave the long URL alone.
|
|
const shortUrl = new URL(`/share/${code}`, u.origin).toString();
|
|
result = result.replace(longUrl, shortUrl);
|
|
} catch {
|
|
// Malformed URL or unexpected error — fall through with the original.
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export function useCopyFeedback() {
|
|
const [copied, setCopied] = useState(false);
|
|
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
|
|
const copy = useCallback(async (text: string) => {
|
|
let success = false;
|
|
|
|
// Why we don't just `await shortenHighlightUrlsIn(text)` first: the URL
|
|
// shortening is a network round-trip, and awaiting it consumes the
|
|
// transient user activation that navigator.clipboard needs. The write
|
|
// would then silently fail on the *first* click and only succeed on the
|
|
// second (when the short link is cached and the shorten resolves
|
|
// synchronously). Instead we hand the clipboard a *Promise* of the text
|
|
// via ClipboardItem — the browser keeps the gesture alive while the
|
|
// async work finishes, so a single click copies the shortened URL.
|
|
if (typeof ClipboardItem !== "undefined" && navigator.clipboard?.write) {
|
|
try {
|
|
const item = new ClipboardItem({
|
|
"text/plain": shortenHighlightUrlsIn(text).then(
|
|
(s) => new Blob([s], { type: "text/plain" }),
|
|
),
|
|
});
|
|
await navigator.clipboard.write([item]);
|
|
success = true;
|
|
} catch {
|
|
// ClipboardItem-with-promise unsupported or rejected — fall through.
|
|
}
|
|
}
|
|
|
|
if (!success) {
|
|
// Legacy path: now that ClipboardItem failed, await the text and try
|
|
// the synchronous fallbacks. (May still need a second click on very old
|
|
// browsers, but those lack ClipboardItem entirely.)
|
|
const finalText = await shortenHighlightUrlsIn(text);
|
|
try {
|
|
await navigator.clipboard.writeText(finalText);
|
|
success = true;
|
|
} catch {
|
|
// Fallback for older browsers without the async clipboard API.
|
|
const ta = document.createElement("textarea");
|
|
ta.value = finalText;
|
|
ta.style.position = "fixed";
|
|
ta.style.top = "0";
|
|
ta.style.left = "0";
|
|
ta.style.opacity = "0";
|
|
document.body.appendChild(ta);
|
|
ta.focus();
|
|
ta.select();
|
|
try {
|
|
document.execCommand("copy");
|
|
success = true;
|
|
} catch {
|
|
// silent fail
|
|
}
|
|
document.body.removeChild(ta);
|
|
}
|
|
}
|
|
|
|
if (success) {
|
|
setCopied(true);
|
|
if (timerRef.current) clearTimeout(timerRef.current);
|
|
timerRef.current = setTimeout(() => setCopied(false), 1500);
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (timerRef.current) clearTimeout(timerRef.current);
|
|
};
|
|
}, []);
|
|
|
|
return { copied, copy };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Pseudo collection data (placeholder for future backend)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export const PSEUDO_COLLECTIONS = [
|
|
{ id: "favorites", name: "Favorites", count: 12 },
|
|
{ id: "study-notes", name: "Study Notes", count: 8 },
|
|
{ id: "share-worthy", name: "Share Worthy", count: 23 },
|
|
{ id: "memorize", name: "To Memorize", count: 5 },
|
|
{ id: "daily-reading", name: "Daily Reading", count: 17 },
|
|
];
|