"use client";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, memo } from "react";
import { createPortal } from "react-dom";
// Loaded dynamically inside the component to prevent render-blocking
import type { Entity } from "@/uhm/api/entities";
import type { Wiki } from "@/uhm/api/wikis";
type TocItem = {
id: string;
level: number;
text: string;
};
type Props = {
entity: Entity | null;
wiki: Wiki | null;
isLoading: boolean;
error?: string | null;
onClose: () => void;
onWikiLinkRequest: (request: { slug: string; rect: DOMRect }) => void;
onWikiLinkEntitySelectionRequest?: (request: { slug: string; rect: DOMRect }) => void;
sidebarWidth?: number;
onSidebarWidthChange?: (width: number) => void;
maxDragWidth?: number;
compactHeader?: boolean;
sidebarHeight?: number;
onSidebarHeightChange?: (height: number) => void;
};
function escapeHtml(input: string): string {
return input
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("\"", """)
.replaceAll("'", "'");
}
function normalizeWikiContentToHtml(raw: string | null | undefined): string {
let value = String(raw || "").trim();
if (!value.length) return "";
// Replace non-breaking spaces to allow text wrap
value = value.replaceAll(" ", " ").replaceAll("\u00a0", " ");
if (value[0] === "<") return value;
return `
${escapeHtml(value).replace(/\n/g, "
")}
`;
}
function slugifyHeading(raw: string): string {
const input = String(raw || "").trim();
if (!input.length) return "";
return input
.toLowerCase()
.replace(/đ/g, "d")
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "")
.slice(0, 80);
}
function isExternalHref(href: string): boolean {
const h = href.trim().toLowerCase();
return (
h.startsWith("http://") ||
h.startsWith("https://") ||
h.startsWith("mailto:") ||
h.startsWith("tel:") ||
h.startsWith("sms:")
);
}
function extractWikiSlugFromHref(href: string): string {
const raw = String(href || "").trim();
if (!raw.length || raw === "__missing__") return "";
if (raw.startsWith("#wiki:")) return raw.slice("#wiki:".length).trim();
if (raw.startsWith("#")) return "";
const isAbsoluteUrl = /^[a-z][a-z\d+.-]*:/i.test(raw);
const baseOrigin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
if (isAbsoluteUrl) {
try {
const url = new URL(raw, baseOrigin);
if (typeof window !== "undefined" && url.origin !== window.location.origin) return "";
const path = url.pathname.replace(/\/+$/, "");
if (!path.startsWith("/wiki/")) return "";
return decodeWikiSlug(path.slice("/wiki/".length));
} catch {
return "";
}
}
const match = raw.match(/^([^?#]+)([?#].*)?$/);
let slug = String(match?.[1] || "").replace(/^\/+/, "").replace(/\/+$/, "").trim();
if (slug.startsWith("wiki/")) {
slug = slug.slice("wiki/".length).trim();
}
return decodeWikiSlug(slug);
}
function decodeWikiSlug(slug: string): string {
try {
return decodeURIComponent(slug).trim();
} catch {
return slug.trim();
}
}
function prepareWikiHtml(inputHtml: string): { html: string; toc: TocItem[] } {
const parser = new DOMParser();
const doc = parser.parseFromString(inputHtml, "text/html");
for (const el of Array.from(doc.querySelectorAll("script"))) el.remove();
for (const a of Array.from(doc.querySelectorAll("a[href]"))) {
const href = String(a.getAttribute("href") || "").trim();
if (!href.length) continue;
if (href === "__missing__") continue;
const slugPart = extractWikiSlugFromHref(href);
if (slugPart.length) {
a.setAttribute("href", `#wiki:${slugPart}`);
a.setAttribute("data-wiki-slug", slugPart);
a.setAttribute("target", "_self");
continue;
}
if (isExternalHref(href)) {
a.setAttribute("target", "_blank");
a.setAttribute("rel", "noopener noreferrer");
}
}
const toc: TocItem[] = [];
const seen = new Map();
const headings = Array.from(doc.body.querySelectorAll("h1,h2,h3,h4,h5,h6"));
for (const h of headings) {
const text = String(h.textContent || "").trim();
if (!text.length) continue;
const level = Number(String(h.tagName || "").replace(/^H/i, "")) || 1;
const existingId = String(h.getAttribute("id") || "").trim();
if (existingId) {
toc.push({ id: existingId, level, text });
continue;
}
const base = slugifyHeading(text) || "heading";
const nextCount = (seen.get(base) || 0) + 1;
seen.set(base, nextCount);
const id = nextCount === 1 ? base : `${base}-${nextCount}`;
h.setAttribute("id", id);
toc.push({ id, level, text });
}
return { html: doc.body.innerHTML, toc };
}
function PublicWikiSidebar({
entity,
wiki,
isLoading,
error,
onClose,
onWikiLinkRequest,
onWikiLinkEntitySelectionRequest,
sidebarWidth,
onSidebarWidthChange,
maxDragWidth,
compactHeader = false,
sidebarHeight,
onSidebarHeightChange,
}: Props) {
const contentRootRef = useRef(null);
const tocContainerRef = useRef(null);
const [wikiLinkMenu, setWikiLinkMenu] = useState<{
slug: string;
rect: DOMRect;
top: number;
left: number;
} | null>(null);
useEffect(() => {
import("react-quill-new/dist/quill.snow.css");
}, []);
const [localWidth, setLocalWidth] = useState(() => {
if (typeof window !== "undefined") {
const saved = localStorage.getItem("public-wiki-sidebar-width");
if (saved) {
const parsed = parseInt(saved, 10);
if (!isNaN(parsed) && parsed >= 320 && parsed <= 800) {
return parsed;
}
}
}
return 420;
});
const width = sidebarWidth ?? localWidth;
const setWidth = onSidebarWidthChange ?? setLocalWidth;
const maxDragWidthLimit = maxDragWidth ?? 800;
const handlePointerDown = (event: React.PointerEvent) => {
event.preventDefault();
const startX = event.clientX;
const startWidth = width;
// Tạo đường ghost ảo chỉ vị trí kéo thay vì kích hoạt re-render liên tục
const ghost = document.createElement("div");
ghost.style.position = "fixed";
ghost.style.top = "0";
ghost.style.bottom = "0";
ghost.style.width = "4px";
ghost.style.backgroundColor = "#38bdf8";
ghost.style.boxShadow = "0 0 12px rgba(56, 189, 248, 0.8)";
ghost.style.zIndex = "99999";
ghost.style.cursor = "col-resize";
ghost.style.pointerEvents = "none";
ghost.style.left = `${startX}px`;
document.body.appendChild(ghost);
const onMove = (e: PointerEvent) => {
ghost.style.left = `${e.clientX}px`;
};
const onUp = (e: PointerEvent) => {
window.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerup", onUp);
if (ghost.parentNode) {
ghost.parentNode.removeChild(ghost);
}
const deltaX = e.clientX - startX;
const nextWidth = Math.max(320, Math.min(maxDragWidthLimit, startWidth - deltaX));
setWidth(nextWidth);
if (typeof window !== "undefined") {
localStorage.setItem("public-wiki-sidebar-width", String(nextWidth));
}
};
window.addEventListener("pointermove", onMove);
window.addEventListener("pointerup", onUp);
};
const [activeHeadingId, setActiveHeadingId] = useState(null);
const processedWiki = useMemo(() => {
if (!wiki) return { html: "", toc: [] as TocItem[] };
const html = normalizeWikiContentToHtml(wiki.content ?? "");
try {
return prepareWikiHtml(html);
} catch (err) {
console.error("Failed to process sidebar wiki HTML", err);
return { html, toc: [] as TocItem[] };
}
}, [wiki]);
const renderHtml = processedWiki.html;
const toc = processedWiki.toc;
const effectiveActiveHeadingId = toc.some((item) => item.id === activeHeadingId)
? activeHeadingId
: (toc[0]?.id ?? null);
useLayoutEffect(() => {
const firstHeadingId = toc[0]?.id ?? null;
setActiveHeadingId(firstHeadingId);
const scrollContainer = contentRootRef.current?.parentElement;
scrollContainer?.scrollTo({ top: 0, behavior: "auto" });
tocContainerRef.current?.scrollTo({ left: 0, behavior: "auto" });
}, [wiki?.id, wiki?.slug, renderHtml, toc]);
useEffect(() => {
if (!toc.length) return;
const root = contentRootRef.current;
if (!root) return;
const headings = toc
.map((item) => root.querySelector(`#${CSS.escape(item.id)}`))
.filter((item): item is HTMLElement => Boolean(item));
if (!headings.length) return;
const scrollContainer = root.parentElement;
const updateActiveHeading = () => {
const containerRect = scrollContainer?.getBoundingClientRect();
const topBoundary = (containerRect?.top ?? 0) + (containerRect?.height ?? window.innerHeight) * 0.18;
const bottomBoundary = (containerRect?.top ?? 0) + (containerRect?.height ?? window.innerHeight) * 0.82;
const visibleHeadings = headings
.map((heading) => ({ heading, rect: heading.getBoundingClientRect() }))
.filter(({ rect }) => rect.bottom >= topBoundary && rect.top <= bottomBoundary)
.sort((a, b) => {
const aDistance = Math.abs(a.rect.top - topBoundary);
const bDistance = Math.abs(b.rect.top - topBoundary);
return aDistance - bDistance;
});
const nextHeading = visibleHeadings[0]?.heading || headings[0];
if (nextHeading?.id) setActiveHeadingId(nextHeading.id);
};
const observer = new IntersectionObserver(
updateActiveHeading,
{ root: scrollContainer || null, rootMargin: "-18% 0px -70% 0px", threshold: [0, 1] }
);
for (const heading of headings) observer.observe(heading);
scrollContainer?.addEventListener("scroll", updateActiveHeading, { passive: true });
return () => {
observer.disconnect();
scrollContainer?.removeEventListener("scroll", updateActiveHeading);
};
}, [toc]);
useEffect(() => {
const container = tocContainerRef.current;
if (!container) return;
const handleWheel = (e: WheelEvent) => {
if (e.deltaY !== 0) {
e.preventDefault();
container.scrollLeft += e.deltaY;
}
};
container.addEventListener("wheel", handleWheel, { passive: false });
return () => {
container.removeEventListener("wheel", handleWheel);
};
}, [toc]);
useEffect(() => {
const root = contentRootRef.current;
if (!root) return;
const handleClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const link = target?.closest?.("a[data-wiki-slug]") as HTMLAnchorElement | null;
const fallbackLink = target?.closest?.("a[href]") as HTMLAnchorElement | null;
const sourceLink = link || fallbackLink;
if (!sourceLink) return;
const slug = String(
sourceLink.getAttribute("data-wiki-slug") ||
extractWikiSlugFromHref(sourceLink.getAttribute("href") || "")
).trim();
if (!slug.length) return;
event.preventDefault();
onWikiLinkRequest({ slug, rect: sourceLink.getBoundingClientRect() });
};
root.addEventListener("click", handleClick);
return () => root.removeEventListener("click", handleClick);
}, [onWikiLinkRequest, renderHtml]);
useEffect(() => {
const root = contentRootRef.current;
if (!root) return;
const handleContextMenu = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const link = target?.closest?.("a[data-wiki-slug]") as HTMLAnchorElement | null;
const fallbackLink = target?.closest?.("a[href]") as HTMLAnchorElement | null;
const sourceLink = link || fallbackLink;
if (!sourceLink) return;
const slug = String(
sourceLink.getAttribute("data-wiki-slug") ||
extractWikiSlugFromHref(sourceLink.getAttribute("href") || "")
).trim();
if (!slug.length) return;
event.preventDefault();
setWikiLinkMenu({
slug,
rect: sourceLink.getBoundingClientRect(),
...computeContextMenuPosition(event.clientX, event.clientY, 220, 88),
});
};
root.addEventListener("contextmenu", handleContextMenu, true);
return () => root.removeEventListener("contextmenu", handleContextMenu, true);
}, [renderHtml]);
useEffect(() => {
if (!wikiLinkMenu) return;
const handlePointerDown = (event: PointerEvent) => {
const target = event.target as HTMLElement | null;
if (target?.closest?.("[data-wiki-link-context-menu='true']")) return;
setWikiLinkMenu(null);
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") setWikiLinkMenu(null);
};
const closeMenu = () => setWikiLinkMenu(null);
window.addEventListener("pointerdown", handlePointerDown);
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("resize", closeMenu);
window.addEventListener("scroll", closeMenu, true);
return () => {
window.removeEventListener("pointerdown", handlePointerDown);
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("resize", closeMenu);
window.removeEventListener("scroll", closeMenu, true);
};
}, [wikiLinkMenu]);
const handleOpenStandaloneWiki = (slug: string) => {
if (typeof window === "undefined") return;
const url = `/wiki/${encodeURIComponent(slug)}`;
const nextWindow = window.open(url, "_blank", "noopener,noreferrer");
if (nextWindow) nextWindow.opener = null;
};
const isExpanded = useMemo(() => {
if (typeof window === "undefined") return false;
const fullHeight = Math.round(window.innerHeight * 0.70);
return (sidebarHeight || 400) >= fullHeight;
}, [sidebarHeight]);
const handleHeightToggle = () => {
if (typeof window === "undefined") return;
const halfHeight = Math.round(window.innerHeight * 0.45);
const fullHeight = Math.round(window.innerHeight * 0.85);
const currentHeight = sidebarHeight || 400;
const nextHeight = Math.abs(currentHeight - halfHeight) < Math.abs(currentHeight - fullHeight)
? fullHeight
: halfHeight;
if (onSidebarHeightChange) {
onSidebarHeightChange(nextHeight);
}
};
const [isMobileOrTablet, setIsMobileOrTablet] = useState(false);
useEffect(() => {
const checkDevice = () => setIsMobileOrTablet(window.innerWidth < 1024);
checkDevice();
window.addEventListener("resize", checkDevice);
return () => window.removeEventListener("resize", checkDevice);
}, []);
return (
{/* Grab Handle for bottom sheet on mobile */}
{isMobileOrTablet ? (
) : null}
{/* Drag Handle on the left edge */}
{/* Visual drag line overlay */}
{compactHeader ? null : (
Wiki
)}
{wiki?.title?.trim() || entity?.name?.trim() || "Wiki"}
{toc.length ? (
{toc.slice(0, 8).map((item) => {
const isActive = effectiveActiveHeadingId === item.id;
return (
{
e.preventDefault();
setActiveHeadingId(item.id);
const root = contentRootRef.current;
if (root) {
const targetElement = root.querySelector(`#${CSS.escape(item.id)}`) as HTMLElement | null;
const scrollContainer = root.parentElement;
if (targetElement && scrollContainer) {
const containerTop = scrollContainer.getBoundingClientRect().top;
const targetTop = targetElement.getBoundingClientRect().top;
const scrollOffset = targetTop - containerTop + scrollContainer.scrollTop;
scrollContainer.scrollTo({
top: scrollOffset - 12,
behavior: "smooth"
});
}
}
}}
style={{
flexShrink: 0,
borderRadius: 9999,
padding: "4px 10px",
fontSize: 11,
fontWeight: 650,
textDecoration: "none",
transition: "all 0.2s",
background: isActive
? "rgba(56, 189, 248, 0.15)"
: "rgba(30, 41, 59, 0.4)",
color: isActive ? "#38bdf8" : "#94a3b8",
border: isActive
? "1px solid rgba(56, 189, 248, 0.3)"
: "1px solid rgba(148, 163, 184, 0.1)",
}}
className={isActive ? "" : "hover:bg-slate-700/40 hover:text-slate-200"}
>
{item.text}
);
})}
) : null}
{isLoading && !wiki ? (
) : error ? (
{error}
) : wiki ? (
) : (
Entity này chưa có wiki liên kết.
)}
{wikiLinkMenu && typeof document !== "undefined"
? createPortal(
,
document.body
)
: null}
);
}
const wikiLinkMenuButtonStyle = {
display: "block",
width: "100%",
border: 0,
borderRadius: 7,
background: "transparent",
padding: "9px 10px",
color: "inherit",
cursor: "pointer",
fontSize: 13,
fontWeight: 700,
lineHeight: "18px",
textAlign: "left" as const,
};
function computeContextMenuPosition(clientX: number, clientY: number, width: number, height: number) {
const margin = 8;
const viewportWidth = typeof window !== "undefined" ? window.innerWidth : 1440;
const viewportHeight = typeof window !== "undefined" ? window.innerHeight : 900;
return {
left: Math.max(margin, Math.min(clientX, viewportWidth - width - margin)),
top: Math.max(margin, Math.min(clientY, viewportHeight - height - margin)),
};
}
export default memo(PublicWikiSidebar);