From c1d9b716a11ac5f54f226637631581666d90a8c4 Mon Sep 17 00:00:00 2001 From: Faisal Misbah Date: Thu, 5 Nov 2026 20:53:07 +0500 Subject: [PATCH 1/3] feat: private chapter highlights with notes, Markdown export, and library --- .../app/(learn)/(main)/highlights/page.tsx | 10 + .../[courseSlug]/[chapterSlug]/page.tsx | 1 + .../components/learn/chapter-highlights.tsx | 484 ++++++++++++++++++ .../components/learn/chapter-reader-shell.tsx | 10 + .../components/learn/highlights-library.tsx | 234 +++++++++ .../learn/mentee-workspace-shell.tsx | 3 +- frontend/src/server/actions/highlights.ts | 68 +++ frontend/src/shared/api/reader.ts | 11 + .../migration.sql | 38 ++ server/prisma/schema.prisma | 32 ++ server/src/controllers/chapters.ts | 41 ++ server/src/controllers/learner.ts | 5 + server/src/routes/v1/chapters.ts | 9 + server/src/routes/v1/learner.ts | 7 +- server/src/services/chapters/highlights.ts | 165 ++++++ server/src/services/chapters/reader.ts | 4 +- server/src/shared/api/reader.ts | 11 + server/src/validations/chapters.ts | 18 + 18 files changed, 1148 insertions(+), 3 deletions(-) create mode 100644 frontend/src/app/(learn)/(main)/highlights/page.tsx create mode 100644 frontend/src/components/learn/chapter-highlights.tsx create mode 100644 frontend/src/components/learn/highlights-library.tsx create mode 100644 frontend/src/server/actions/highlights.ts create mode 100644 server/prisma/migrations/20261105121548_add_chapter_highlights/migration.sql create mode 100644 server/src/services/chapters/highlights.ts diff --git a/frontend/src/app/(learn)/(main)/highlights/page.tsx b/frontend/src/app/(learn)/(main)/highlights/page.tsx new file mode 100644 index 00000000..fb32c179 --- /dev/null +++ b/frontend/src/app/(learn)/(main)/highlights/page.tsx @@ -0,0 +1,10 @@ +import { serverApiFetch } from "@/lib/api-server"; +import { HighlightsLibrary } from "@/components/learn/highlights-library"; +import type { UserHighlightView } from "@/server/actions/highlights"; + +export const dynamic = "force-dynamic"; + +export default async function HighlightsPage() { + const highlights = await serverApiFetch("/api/v1/learner/highlights").catch(() => []); + return ; +} diff --git a/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx b/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx index 47e20e20..fc96a6dc 100644 --- a/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx +++ b/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx @@ -113,6 +113,7 @@ export default async function ChapterReaderPage({ recap={content.recap} streakMilestone={content.streakMilestone} headingNotes={content.headingNotes} + highlights={content.highlights} predictGate={content.predictGate} predictRevealed={content.predictRevealed} promptCourseRating={Boolean(content.promptCourseRating)} diff --git a/frontend/src/components/learn/chapter-highlights.tsx b/frontend/src/components/learn/chapter-highlights.tsx new file mode 100644 index 00000000..4081d883 --- /dev/null +++ b/frontend/src/components/learn/chapter-highlights.tsx @@ -0,0 +1,484 @@ +"use client"; + +import { useEffect, useRef, useState, useCallback } from "react"; +import { Highlighter, Trash2, X } from "lucide-react"; +import { saveHighlight, updateHighlight, deleteHighlight } from "@/server/actions/highlights"; +import type { HighlightView, HighlightColor } from "@/server/actions/highlights"; +import { cn } from "@/lib/utils"; + +const COLOR_CLASSES: Record = { + YELLOW: "bg-yellow-200/70 dark:bg-yellow-400/30", + GREEN: "bg-green-200/70 dark:bg-green-400/30", + BLUE: "bg-blue-200/70 dark:bg-blue-400/30", + PINK: "bg-pink-200/70 dark:bg-pink-400/30", +}; + +const COLORS: HighlightColor[] = ["YELLOW", "GREEN", "BLUE", "PINK"]; + +type Highlight = HighlightView; + +function findTextRange(container: HTMLElement, quote: string, occurrence: number): Range | null { + if (!quote) return null; + const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, null); + const nodes: Text[] = []; + let n: Node | null; + while ((n = walker.nextNode())) nodes.push(n as Text); + let full = ""; + const offsets: { node: Text; start: number; end: number }[] = []; + for (const tn of nodes) { + const t = tn.nodeValue || ""; + offsets.push({ node: tn, start: full.length, end: full.length + t.length }); + full += t; + } + let idx = -1; + let searchFrom = 0; + for (let i = 0; i <= occurrence; i++) { + const found = full.indexOf(quote, searchFrom); + if (found === -1) return null; + idx = found; + searchFrom = found + 1; + } + const startOffset = idx; + const endOffset = idx + quote.length; + let startNode: Text | null = null; + let startNodeOffset = 0; + let endNode: Text | null = null; + let endNodeOffset = 0; + for (const o of offsets) { + if (!startNode && startOffset >= o.start && startOffset < o.end) { + startNode = o.node; + startNodeOffset = startOffset - o.start; + } + if (!endNode && endOffset > o.start && endOffset <= o.end) { + endNode = o.node; + endNodeOffset = endOffset - o.start; + } + } + // Fallbacks for ranges that land exactly on a node boundary. + if (!startNode && offsets.length) { + const last = offsets[offsets.length - 1]; + startNode = last.node; + startNodeOffset = last.node.nodeValue?.length || 0; + } + if (!endNode && offsets.length) { + const last = offsets[offsets.length - 1]; + endNode = last.node; + endNodeOffset = last.node.nodeValue?.length || 0; + } + if (!startNode || !endNode) return null; + const range = document.createRange(); + range.setStart(startNode, startNodeOffset); + range.setEnd(endNode, endNodeOffset); + return range; +} + +function unwrapMarks(article: HTMLElement) { + const marks = Array.from(article.querySelectorAll("mark.hl-mark")); + for (const mark of marks) { + const parent = mark.parentNode; + if (!parent) continue; + parent.replaceChild(document.createTextNode(mark.textContent || ""), mark); + } + article.normalize(); +} + +function renderHighlights(article: HTMLElement, highlights: Highlight[]) { + unwrapMarks(article); + // Build a per-character color map per text node, then rebuild each touched + // text node with runs. Walking from the article (not the range's + // common ancestor) ensures single-node ranges are handled, and overlaps are + // resolved per character (later highlight wins). + const nodeColors = new Map(); + const nodeIds = new Map(); + + const resolved: { h: Highlight; range: Range }[] = []; + for (const h of highlights) { + const range = findTextRange(article, h.quote, h.occurrence); + if (range) resolved.push({ h, range }); + } + + for (const { h, range } of resolved) { + const walker = document.createTreeWalker(article, NodeFilter.SHOW_TEXT, null); + const nodes: Text[] = []; + let n: Node | null; + while ((n = walker.nextNode())) { + if (range.intersectsNode(n)) nodes.push(n as Text); + } + for (const tn of nodes) { + if (!nodeColors.has(tn)) { + const len = tn.nodeValue?.length || 0; + nodeColors.set(tn, new Array(len).fill(null)); + nodeIds.set(tn, new Array(len).fill(null)); + } + const colors = nodeColors.get(tn)!; + const ids = nodeIds.get(tn)!; + const len = tn.nodeValue?.length || 0; + let start = 0; + let end = len; + if (tn === range.startContainer) start = range.startOffset; + if (tn === range.endContainer) end = range.endOffset; + for (let i = start; i < end && i < len; i++) { + colors[i] = h.color; + ids[i] = h.id; + } + } + } + + for (const [tn, colors] of nodeColors) { + const text = tn.nodeValue || ""; + const ids = nodeIds.get(tn)!; + const parent = tn.parentNode; + if (!parent) continue; + const frag = document.createDocumentFragment(); + let i = 0; + while (i < text.length) { + const color = colors[i]; + const id = ids[i]; + let j = i; + while (j < text.length && colors[j] === color && ids[j] === id) j++; + const chunk = text.slice(i, j); + if (color && id) { + const mark = document.createElement("mark"); + mark.className = `hl-mark ${COLOR_CLASSES[color]}`; + mark.dataset.highlightId = id; + const h = highlights.find((x) => x.id === id); + if (h?.note) mark.title = h.note; + mark.textContent = chunk; + frag.appendChild(mark); + } else { + frag.appendChild(document.createTextNode(chunk)); + } + i = j; + } + parent.replaceChild(frag, tn); + } +} + +function selectionToHighlight(article: HTMLElement, sel: Selection): { + quote: string; + prefix: string; + suffix: string; + occurrence: number; +} | null { + if (!sel.rangeCount) return null; + const range = sel.getRangeAt(0); + if (range.collapsed) return null; + if (!article.contains(range.commonAncestorContainer)) return null; + const quote = range.toString().trim(); + if (!quote || quote.length > 2000) return null; + // occurrence: count prior occurrences of quote in article text + const walker = document.createTreeWalker(article, NodeFilter.SHOW_TEXT, null); + let full = ""; + let node: Node | null; + while ((node = walker.nextNode())) full += node.nodeValue || ""; + // find occurrence index by position of range start in full text + // Re-walk to find offset of range start + const nodes: Text[] = []; + const w2 = document.createTreeWalker(article, NodeFilter.SHOW_TEXT, null); + while ((node = w2.nextNode())) nodes.push(node as Text); + let acc = 0; + let startOffset = 0; + for (const tn of nodes) { + if (tn === range.startContainer) { + startOffset = acc + range.startOffset; + break; + } + acc += tn.nodeValue?.length || 0; + } + let occurrence = 0; + let searchFrom = 0; + while (true) { + const found = full.indexOf(quote, searchFrom); + if (found === -1 || found > startOffset) break; + occurrence++; + searchFrom = found + 1; + if (found === startOffset) break; + } + occurrence = Math.max(0, occurrence - 1); + + const prefixStart = Math.max(0, startOffset - 40); + const prefix = full.slice(prefixStart, startOffset); + const suffix = full.slice(startOffset + quote.length, startOffset + quote.length + 40); + return { quote, prefix, suffix, occurrence }; +} + +export function ChapterHighlights({ + chapterId, + initialHighlights, + articleRef, +}: { + chapterId: string; + initialHighlights: Highlight[]; + articleRef: React.RefObject; +}) { + const [highlights, setHighlights] = useState(initialHighlights); + const [toolbar, setToolbar] = useState<{ x: number; y: number; selection: ReturnType } | null>(null); + const [activeId, setActiveId] = useState(null); + const [noteDraft, setNoteDraft] = useState(""); + const [panelOpen, setPanelOpen] = useState(false); + const [pending, setPending] = useState(false); + const savedSelection = useRef>(null); + + // Render marks whenever highlights change + useEffect(() => { + const article = articleRef.current; + if (!article) return; + renderHighlights(article, highlights); + }, [highlights, articleRef]); + + // Also re-render on mount (article may not be ready immediately) + useEffect(() => { + const article = articleRef.current; + if (!article) return; + const t = setTimeout(() => renderHighlights(article, highlights), 50); + return () => clearTimeout(t); + }, [articleRef]); // eslint-disable-line react-hooks/exhaustive-deps + + const handleMouseUp = useCallback(() => { + const article = articleRef.current; + if (!article) return; + const sel = window.getSelection(); + if (!sel || sel.isCollapsed) { + setToolbar(null); + return; + } + const parsed = selectionToHighlight(article, sel); + if (!parsed) { + setToolbar(null); + return; + } + savedSelection.current = parsed; + const rect = sel.getRangeAt(0).getBoundingClientRect(); + setToolbar({ x: rect.left + rect.width / 2, y: rect.top - 8, selection: parsed }); + }, [articleRef]); + + useEffect(() => { + const article = articleRef.current; + if (!article) return; + article.addEventListener("mouseup", handleMouseUp); + article.addEventListener("touchend", handleMouseUp); + return () => { + article.removeEventListener("mouseup", handleMouseUp); + article.removeEventListener("touchend", handleMouseUp); + }; + }, [articleRef, handleMouseUp]); + + // Close toolbar on outside click + useEffect(() => { + if (!toolbar) return; + const onClick = (e: MouseEvent) => { + const target = e.target as HTMLElement; + if (target.closest("[data-hl-toolbar]")) return; + setToolbar(null); + }; + document.addEventListener("mousedown", onClick); + return () => document.removeEventListener("mousedown", onClick); + }, [toolbar]); + + // Clicking a highlight opens its note editor. + useEffect(() => { + const article = articleRef.current; + if (!article) return; + const onClick = (e: MouseEvent) => { + const target = e.target as HTMLElement; + const mark = target.closest("mark.hl-mark") as HTMLElement | null; + if (!mark) return; + const id = mark.dataset.highlightId; + if (!id) return; + const h = highlights.find((x) => x.id === id); + if (h) openNote(h); + }; + article.addEventListener("click", onClick); + return () => article.removeEventListener("click", onClick); + }, [articleRef, highlights]); + + async function createHighlight(color: HighlightColor) { + const parsed = savedSelection.current || toolbar?.selection; + if (!parsed) return; + setPending(true); + const res = await saveHighlight({ + chapterId, + color, + quote: parsed.quote, + prefix: parsed.prefix, + suffix: parsed.suffix, + occurrence: parsed.occurrence, + note: null, + }); + setPending(false); + if (res.ok) { + setHighlights((prev) => [...prev, res.data]); + setToolbar(null); + window.getSelection()?.removeAllRanges(); + } + } + + function openNote(h: Highlight) { + setActiveId(h.id); + setNoteDraft(h.note ?? ""); + } + + async function saveNote() { + if (!activeId) return; + setPending(true); + const res = await updateHighlight({ highlightId: activeId, note: noteDraft }); + setPending(false); + if (res.ok) { + setHighlights((prev) => prev.map((h) => (h.id === activeId ? res.data : h))); + setActiveId(null); + } + } + + async function changeColor(h: Highlight, color: HighlightColor) { + setPending(true); + const res = await updateHighlight({ highlightId: h.id, color }); + setPending(false); + if (res.ok) setHighlights((prev) => prev.map((x) => (x.id === h.id ? res.data : x))); + } + + async function remove(h: Highlight) { + setPending(true); + const res = await deleteHighlight({ highlightId: h.id }); + setPending(false); + if (res.ok) { + setHighlights((prev) => prev.filter((x) => x.id !== h.id)); + setActiveId(null); + } + } + + const activeHighlight = highlights.find((h) => h.id === activeId) || null; + + return ( + <> + {toolbar && ( +
+ {COLORS.map((c) => ( + +
+ )} + + {activeHighlight && ( +
+
+ Highlight note + +
+