From 9413207aaa2382c705bf27fe525ae5994c42e633 Mon Sep 17 00:00:00 2001 From: jie <2413704818@qq.com> Date: Mon, 19 Oct 2026 23:17:19 +0800 Subject: [PATCH] feat:Add local bookmarks and passage notes --- docusaurus.config.js | 8 + src/components/bookmarks/ArticleNotes.tsx | 109 ++++ src/components/bookmarks/BookmarkButton.tsx | 75 +++ src/components/bookmarks/BookmarkList.tsx | 249 +++++++++ src/components/bookmarks/BookmarkSystem.tsx | 16 + src/components/bookmarks/BookmarksNavLink.tsx | 48 ++ src/components/bookmarks/NoteCapture.tsx | 150 ++++++ src/components/bookmarks/bookmarks.module.css | 475 ++++++++++++++++++ src/css/custom.css | 21 + src/features/bookmarks/docContext.ts | 68 +++ src/features/bookmarks/noteDom.ts | 110 ++++ src/features/bookmarks/noteText.ts | 69 +++ src/features/bookmarks/readingKeys.ts | 73 +++ src/features/bookmarks/restore.ts | 86 ++++ src/features/bookmarks/strings.ts | 141 ++++++ src/features/bookmarks/types.ts | 60 +++ src/features/bookmarks/useBookmarks.ts | 169 +++++++ src/features/bookmarks/useNotes.ts | 164 ++++++ src/pages/bookmarks.module.css | 36 ++ src/pages/bookmarks.tsx | 39 ++ src/theme-modules.d.ts | 12 + src/theme/DocItem/Layout/index.tsx | 60 +++ src/theme/DocItem/Layout/styles.module.css | 12 + src/theme/DocItem/TOC/Desktop/index.tsx | 27 + src/theme/NavbarItem/ComponentTypes.tsx | 14 + src/theme/Root/index.tsx | 2 + 26 files changed, 2293 insertions(+) create mode 100644 src/components/bookmarks/ArticleNotes.tsx create mode 100644 src/components/bookmarks/BookmarkButton.tsx create mode 100644 src/components/bookmarks/BookmarkList.tsx create mode 100644 src/components/bookmarks/BookmarkSystem.tsx create mode 100644 src/components/bookmarks/BookmarksNavLink.tsx create mode 100644 src/components/bookmarks/NoteCapture.tsx create mode 100644 src/components/bookmarks/bookmarks.module.css create mode 100644 src/features/bookmarks/docContext.ts create mode 100644 src/features/bookmarks/noteDom.ts create mode 100644 src/features/bookmarks/noteText.ts create mode 100644 src/features/bookmarks/readingKeys.ts create mode 100644 src/features/bookmarks/restore.ts create mode 100644 src/features/bookmarks/strings.ts create mode 100644 src/features/bookmarks/types.ts create mode 100644 src/features/bookmarks/useBookmarks.ts create mode 100644 src/features/bookmarks/useNotes.ts create mode 100644 src/pages/bookmarks.module.css create mode 100644 src/pages/bookmarks.tsx create mode 100644 src/theme/DocItem/Layout/index.tsx create mode 100644 src/theme/DocItem/Layout/styles.module.css create mode 100644 src/theme/DocItem/TOC/Desktop/index.tsx create mode 100644 src/theme/NavbarItem/ComponentTypes.tsx diff --git a/docusaurus.config.js b/docusaurus.config.js index 831a3ef..0e36619 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -94,6 +94,14 @@ module.exports = { label: '文档', position: 'left', }, + { + type: 'custom-bookmark', + position: 'right', + }, + { + type: 'custom-bookmarks-link', + position: 'right', + }, { type: 'localeDropdown', position: 'right', diff --git a/src/components/bookmarks/ArticleNotes.tsx b/src/components/bookmarks/ArticleNotes.tsx new file mode 100644 index 0000000..ffb4f21 --- /dev/null +++ b/src/components/bookmarks/ArticleNotes.tsx @@ -0,0 +1,109 @@ +import React from 'react'; +import Link from '@docusaurus/Link'; +import {useLocation} from '@docusaurus/router'; +import {bookmarksHref, getDocRoot, isDocPath, isEnglishPath, scrollToPercent} from '@site/src/features/bookmarks/docContext'; +import {flashRange, leadOf, locateLead} from '@site/src/features/bookmarks/noteDom'; +import {pathnameToKey} from '@site/src/features/bookmarks/readingKeys'; +import {useBookmarkStrings} from '@site/src/features/bookmarks/strings'; +import {useNotesForPath, removeNote} from '@site/src/features/bookmarks/useNotes'; +import type {Note} from '@site/src/features/bookmarks/types'; +import styles from './bookmarks.module.css'; + +/** + * "Notes on this page" panel, rendered under the desktop right-hand TOC. + * + * Empty state explains how to capture a note; the heading's "All ↗" link goes + * to the global bookmarks page. Clicking a note locates the quoted passage in + * the article and flashes it, falling back to the stored scroll percentage. + */ + +function shortTime(ts: number, english: boolean): string { + if (!ts) return ''; + const d = new Date(ts); + const now = new Date(); + const pad = (n: number) => String(n).padStart(2, '0'); + if (d.toDateString() === now.toDateString()) { + return `${pad(d.getHours())}:${pad(d.getMinutes())}`; + } + if (d.getFullYear() === now.getFullYear()) { + return english + ? d.toLocaleDateString('en-US', {month: 'short', day: 'numeric'}) + : `${d.getMonth() + 1}月${d.getDate()}日`; + } + return `${String(d.getFullYear()).slice(2)}-${d.getMonth() + 1}-${d.getDate()}`; +} + +export default function ArticleNotes(): React.JSX.Element | null { + const {pathname} = useLocation(); + const t = useBookmarkStrings(); + const notes = useNotesForPath(pathname); + const key = pathnameToKey(pathname); + const english = isEnglishPath(pathname); + + if (!isDocPath(pathname)) return null; + + const visible = notes.filter((n) => n.path === key); + + const jump = (note: Note) => { + const root = getDocRoot(); + if (root) { + const range = locateLead(root, leadOf(note.quote)); + if (range && flashRange(range)) return; + } + scrollToPercent(note.scrollPercent); + }; + + const onRemove = (note: Note) => { + removeNote(note.id); + }; + + return ( +
+
+ + {t.notesTitle} + + {visible.length > 0 ? {visible.length} : null} + + {t.notesAll} + +
+ + {visible.length === 0 ? ( +
+

{t.notesEmptyTitle}

+

{t.notesEmptyHint}

+
+ ) : ( + + )} +
+ ); +} diff --git a/src/components/bookmarks/BookmarkButton.tsx b/src/components/bookmarks/BookmarkButton.tsx new file mode 100644 index 0000000..ce320d6 --- /dev/null +++ b/src/components/bookmarks/BookmarkButton.tsx @@ -0,0 +1,75 @@ +import React from 'react'; +import {useLocation} from '@docusaurus/router'; +import { + currentScrollPercent, + getDocTitle, + isDocPath, +} from '@site/src/features/bookmarks/docContext'; +import {useBookmarkStrings} from '@site/src/features/bookmarks/strings'; +import {useBookmarkState} from '@site/src/features/bookmarks/useBookmarks'; +import styles from './bookmarks.module.css'; + +/** + * Navbar bookmark toggle, registered as the custom NavbarItem type + * `custom-bookmark`. On desktop it is a compact pill in the navbar; in the + * mobile menu Docusaurus expects the item to render its own `
  • ` wrapper. + */ +type NavItemProps = { + mobile?: boolean; + onClick?: () => void; +}; + +export default function BookmarkButton({mobile = false, onClick}: NavItemProps): React.JSX.Element | null { + const {pathname} = useLocation(); + const t = useBookmarkStrings(); + const {bookmark, toggle} = useBookmarkState(pathname); + + if (!isDocPath(pathname)) return null; + + const active = bookmark !== null; + const title = active + ? t.bookmarkAddedTitle(Math.round(bookmark.scrollPercent)) + : t.bookmarkAddTitle; + + const onToggle = () => { + toggle(getDocTitle(), currentScrollPercent()); + onClick?.(); + }; + + const content = ( + <> + + {active ? t.bookmarkAdded : t.bookmarkAdd} + + ); + + if (mobile) { + return ( +
  • + +
  • + ); + } + + return ( + + ); +} diff --git a/src/components/bookmarks/BookmarkList.tsx b/src/components/bookmarks/BookmarkList.tsx new file mode 100644 index 0000000..49b15ce --- /dev/null +++ b/src/components/bookmarks/BookmarkList.tsx @@ -0,0 +1,249 @@ +import React, {useEffect, useMemo, useRef, useState} from 'react'; +import Link from '@docusaurus/Link'; +import {leadOf} from '@site/src/features/bookmarks/noteDom'; +import {markRestore} from '@site/src/features/bookmarks/readingKeys'; +import {useBookmarkStrings} from '@site/src/features/bookmarks/strings'; +import type {Bookmark, Note} from '@site/src/features/bookmarks/types'; +import { + BOOKMARKS_EVENT, + exportBookmarks, + importBookmarks, + loadBookmarks, + removeBookmark, +} from '@site/src/features/bookmarks/useBookmarks'; +import {NOTES_EVENT, loadNotes, removeNote} from '@site/src/features/bookmarks/useNotes'; +import styles from './bookmarks.module.css'; + +/** + * Bookmarks page body: articles with a star and/or notes, grouped by article. + * Group headers resume reading at the stored percentage; note rows jump to the + * exact passage (text fingerprint with percentage fallback). + * + * The shelf only lives in this browser, so JSON export/import is the way to + * move it to another device. + */ + +interface Group { + path: string; + title: string; + bookmark: Bookmark | null; + notes: Note[]; + sortAt: number; +} + +function formatTime(ts: number): string { + if (!ts) return ''; + const d = new Date(ts); + const pad = (n: number) => String(n).padStart(2, '0'); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; +} + +export default function BookmarkList(): React.JSX.Element { + const t = useBookmarkStrings(); + const [bookmarks, setBookmarks] = useState([]); + const [notes, setNotes] = useState([]); + const [message, setMessage] = useState(''); + const fileInput = useRef(null); + const messageTimer = useRef | null>(null); + + const sync = () => { + setBookmarks(loadBookmarks()); + setNotes(loadNotes()); + }; + + useEffect(() => { + sync(); + const onStorage = () => sync(); + window.addEventListener(BOOKMARKS_EVENT, onStorage); + window.addEventListener(NOTES_EVENT, onStorage); + window.addEventListener('storage', onStorage); + return () => { + window.removeEventListener(BOOKMARKS_EVENT, onStorage); + window.removeEventListener(NOTES_EVENT, onStorage); + window.removeEventListener('storage', onStorage); + if (messageTimer.current) clearTimeout(messageTimer.current); + }; + }, []); + + /** One group per article that has a bookmark, a note, or both. */ + const groups = useMemo(() => { + const byPath = new Map(); + for (const bookmark of bookmarks) { + byPath.set(bookmark.path, { + path: bookmark.path, + title: bookmark.title, + bookmark, + notes: [], + sortAt: bookmark.updatedAt, + }); + } + for (const note of notes) { + const group = byPath.get(note.path) ?? { + path: note.path, + title: note.title || note.path, + bookmark: null, + notes: [], + sortAt: 0, + }; + group.notes.push(note); + if (note.createdAt > group.sortAt) group.sortAt = note.createdAt; + if (!group.bookmark) group.title = note.title || group.title; + byPath.set(note.path, group); + } + // Babel's Docusaurus preset compiles `[...map.values()]` loosely to + // `[].concat(iterator)`, so use Array.from for iterables. + return Array.from(byPath.values()).sort((a, b) => b.sortAt - a.sortAt); + }, [bookmarks, notes]); + + const flash = (text: string) => { + setMessage(text); + if (messageTimer.current) clearTimeout(messageTimer.current); + messageTimer.current = setTimeout(() => setMessage(''), 8000); + }; + + const onJumpGroup = (group: Group) => { + if (group.bookmark) markRestore(group.path, group.bookmark.scrollPercent); + }; + + const onJumpNote = (note: Note) => { + markRestore(note.path, note.scrollPercent, leadOf(note.quote)); + }; + + const onRemoveBookmark = (group: Group) => { + if (!group.bookmark) return; + removeBookmark(group.path); + sync(); + flash(t.unstarDone(group.title)); + }; + + const onRemoveNote = (note: Note) => { + removeNote(note.id); + sync(); + }; + + const exportBackup = () => { + try { + const blob = new Blob([exportBookmarks()], {type: 'application/json'}); + const url = URL.createObjectURL(blob); + const anchor = document.createElement('a'); + anchor.href = url; + anchor.download = `bookmarks-backup-${new Date().toISOString().slice(0, 10)}.json`; + anchor.click(); + URL.revokeObjectURL(url); + flash(t.exportStarted); + } catch { + flash(t.exportFailed); + } + }; + + const onImportFile = async (event: React.ChangeEvent) => { + const input = event.target; + const file = input.files?.[0]; + input.value = ''; + if (!file) return; + try { + const result = importBookmarks(await file.text()); + if (!result) { + flash(t.importFailedFormat); + return; + } + sync(); + flash(t.importDone(result.bookmarks, result.notes)); + } catch { + flash(t.importFailedRead); + } + }; + + return ( +
    + {groups.length === 0 ? ( +

    {t.pageEmpty}

    + ) : ( +
      + {groups.map((group) => ( +
    • +
      + onJumpGroup(group)}> + + {group.title} + {group.bookmark && formatTime(group.bookmark.updatedAt) ? ( + + {t.readAt(formatTime(group.bookmark.updatedAt))} + + ) : null} + + {group.bookmark ? ( + + ) : null} +
      + + {group.notes.length > 0 ? ( +
        + {group.notes.map((note) => ( +
      • + onJumpNote(note)}> + 「{note.quote.length > 90 ? `${note.quote.slice(0, 90)}…` : note.quote}」 + + +
      • + ))} +
      + ) : null} +
    • + ))} +
    + )} + +
    + + {t.backupHint(bookmarks.length, notes.length)} + + + + + + + {message ? ( + + {message} + + ) : null} +
    +
    + ); +} diff --git a/src/components/bookmarks/BookmarkSystem.tsx b/src/components/bookmarks/BookmarkSystem.tsx new file mode 100644 index 0000000..2166c63 --- /dev/null +++ b/src/components/bookmarks/BookmarkSystem.tsx @@ -0,0 +1,16 @@ +import React from 'react'; +import {useBookmarkAutoTrack, useBookmarkRestore} from '@site/src/features/bookmarks/restore'; +import NoteCapture from './NoteCapture'; + +/** + * App-level bookmark behaviour, mounted once by the Root wrapper: + * - restores the position / passage after a bookmarks-page jump; + * - silently tracks progress for already-bookmarked articles; + * - hosts the floating note-capture button. + */ +export default function BookmarkSystem(): React.JSX.Element { + useBookmarkRestore(); + useBookmarkAutoTrack(); + + return ; +} diff --git a/src/components/bookmarks/BookmarksNavLink.tsx b/src/components/bookmarks/BookmarksNavLink.tsx new file mode 100644 index 0000000..aba5809 --- /dev/null +++ b/src/components/bookmarks/BookmarksNavLink.tsx @@ -0,0 +1,48 @@ +import React from 'react'; +import Link from '@docusaurus/Link'; +import {useLocation} from '@docusaurus/router'; +import {bookmarksHref} from '@site/src/features/bookmarks/docContext'; +import {useBookmarkStrings} from '@site/src/features/bookmarks/strings'; + +/** + * Locale-aware navbar link to the bookmarks page, registered as the custom + * NavbarItem type `custom-bookmarks-link`. Renders a mobile-menu `
  • ` when + * Docusaurus asks for the mobile variant. + */ +type NavItemProps = { + mobile?: boolean; + onClick?: () => void; +}; + +export default function BookmarksNavLink({ + mobile = false, + onClick, +}: NavItemProps): React.JSX.Element { + const {pathname} = useLocation(); + const t = useBookmarkStrings(); + const href = bookmarksHref(pathname); + const active = pathname === href; + + if (mobile) { + return ( +
  • + + {t.navBookmarks} + +
  • + ); + } + + return ( + + {t.navBookmarks} + + ); +} diff --git a/src/components/bookmarks/NoteCapture.tsx b/src/components/bookmarks/NoteCapture.tsx new file mode 100644 index 0000000..6369ff6 --- /dev/null +++ b/src/components/bookmarks/NoteCapture.tsx @@ -0,0 +1,150 @@ +import React, {useEffect, useRef, useState} from 'react'; +import {useLocation} from '@docusaurus/router'; +import {getDocRoot, getDocTitle, isDocPath} from '@site/src/features/bookmarks/docContext'; +import {useBookmarkStrings} from '@site/src/features/bookmarks/strings'; +import {captureNoteFromSelection} from '@site/src/features/bookmarks/useNotes'; +import styles from './bookmarks.module.css'; + +/** + * Floating "Save as note" button above a text selection in a doc article. + * + * `selectionchange` drives visibility; scrolling hides it because the cached + * rect goes stale. The button prevents mousedown so the selection survives the + * click (otherwise the selection is cleared before capture). + */ + +type Popup = { + x: number; + y: number; + kind: 'ready' | 'saved' | 'rejected'; +}; + +export default function NoteCapture(): React.JSX.Element | null { + const {pathname} = useLocation(); + const t = useBookmarkStrings(); + const [popup, setPopup] = useState(null); + const popupRef = useRef(null); + const timerRef = useRef | null>(null); + const isDoc = isDocPath(pathname); + + const update = (next: Popup | null) => { + popupRef.current = next; + setPopup(next); + }; + + const reset = () => { + if (timerRef.current) clearTimeout(timerRef.current); + timerRef.current = null; + update(null); + }; + + // Route changes always dismiss a stale popup. + useEffect(() => { + reset(); + return () => { + if (timerRef.current) clearTimeout(timerRef.current); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [pathname]); + + useEffect(() => { + if (!isDoc) return; + + const onSelectionChange = () => { + const current = popupRef.current; + if (current && current.kind !== 'ready') return; // keep the result state visible + + const sel = window.getSelection(); + if (!sel || sel.isCollapsed || sel.rangeCount === 0) { + update(null); + return; + } + const root = getDocRoot(); + if (!root) { + update(null); + return; + } + const range = sel.getRangeAt(0); + const container = range.commonAncestorContainer; + const el = + container.nodeType === Node.TEXT_NODE + ? container.parentElement + : (container as Element); + if (!el || !root.contains(el)) { + update(null); + return; + } + if (sel.toString().replace(/\s+/g, ' ').trim().length < 4) { + update(null); + return; + } + const rect = range.getBoundingClientRect(); + if (!rect || (rect.width === 0 && rect.height === 0)) { + update(null); + return; + } + update({ + x: rect.left + rect.width / 2, + y: Math.max(rect.top, 44), + kind: 'ready', + }); + }; + + const hide = () => { + const current = popupRef.current; + if (!current || current.kind === 'ready') update(null); + }; + + document.addEventListener('selectionchange', onSelectionChange); + window.addEventListener('scroll', hide, {passive: true}); + window.addEventListener('resize', hide); + return () => { + document.removeEventListener('selectionchange', onSelectionChange); + window.removeEventListener('scroll', hide); + window.removeEventListener('resize', hide); + }; + }, [isDoc]); + + if (!isDoc || !popup) return null; + + const onSave = (event: React.MouseEvent) => { + event.preventDefault(); + const note = captureNoteFromSelection(getDocTitle()); + update({ + ...popup, + kind: note ? 'saved' : 'rejected', + }); + if (note) { + // Drop the browser selection so the highlight does not linger. + window.getSelection()?.removeAllRanges(); + } + if (timerRef.current) clearTimeout(timerRef.current); + timerRef.current = setTimeout(() => update(null), 900); + }; + + return ( +
    event.preventDefault()}> + {popup.kind === 'ready' ? ( + + ) : ( + + {popup.kind === 'saved' ? t.captureSaved : t.captureRejected} + + )} +
    + ); +} diff --git a/src/components/bookmarks/bookmarks.module.css b/src/components/bookmarks/bookmarks.module.css new file mode 100644 index 0000000..825cf67 --- /dev/null +++ b/src/components/bookmarks/bookmarks.module.css @@ -0,0 +1,475 @@ +/* Local bookmarks / notes UI. XRobot Style tokens only (no VitePress vars). */ + +/* ── Right-hand "notes on this page" panel ─────────────────────────────── */ + +.notes { + margin-top: var(--space-6); + padding-top: var(--space-3); + border-top: var(--stroke) solid var(--line); +} + +.notesHeading { + display: flex; + align-items: center; + gap: 6px; + margin: 0 0 10px; + font-size: var(--type-label-size); + font-weight: 700; + letter-spacing: 0.02em; + color: var(--ink-muted); +} + +.notesTitle { + display: inline-flex; + align-items: center; + gap: 5px; +} + +.notesCount { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 16px; + height: 16px; + padding: 0 5px; + border: var(--stroke) solid var(--line-strong); + background: var(--paper-sunken); + color: var(--ink); + font-size: 11px; + font-weight: 700; + border-radius: 0; +} + +.notesAll { + margin-left: auto; + color: var(--ink-muted); + font-size: 11.5px; + font-weight: 500; + text-decoration: none; +} + +.notesAll:hover { + color: var(--ink); + text-decoration: underline; + text-underline-offset: 3px; +} + +/* empty-state guidance */ +.notesHint { + border: 1px dashed var(--line-strong); + background: var(--paper-sunken); + padding: 10px 12px; +} + +.notesHintTitle { + margin: 0; + color: var(--ink); + font-size: 12px; + font-weight: 700; + line-height: 1.8; +} + +.notesHintBody { + margin: 2px 0 0; + color: var(--ink-muted); + font-size: 12px; + line-height: 1.8; + white-space: pre-line; +} + +/* note rows */ +.notesList { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 2px; +} + +.notesItem { + display: flex; + align-items: stretch; + transition: background-color var(--duration-fast); +} + +.notesItem:hover { + background: var(--paper-sunken); +} + +.notesMain { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 2px; + border: none; + border-left: var(--stroke-strong) solid var(--ink); + background: none; + padding: 6px 4px 6px 9px; + text-align: left; + color: inherit; + cursor: pointer; +} + +.notesQuote { + color: var(--ink-muted); + font-size: 12.5px; + line-height: 1.7; + overflow-wrap: anywhere; + transition: color var(--duration-fast); +} + +.notesMain:hover .notesQuote { + color: var(--ink); +} + +.notesTime { + color: var(--ink-muted); + font-size: 11px; + line-height: 1; + opacity: 0.8; +} + +.notesRemove { + flex-shrink: 0; + border: none; + background: none; + padding: 0 5px; + color: var(--ink-muted); + font-size: 14px; + cursor: pointer; + opacity: 0; + transition: opacity var(--duration-fast), color var(--duration-fast); +} + +.notesItem:hover .notesRemove, +.notesRemove:focus-visible { + opacity: 1; +} + +.notesRemove:hover { + color: var(--fail); +} + +/* ── Floating "save as note" button ────────────────────────────────────── */ + +.capture { + position: fixed; + z-index: 1000; + transform: translate(-50%, calc(-100% - 10px)); + pointer-events: auto; + filter: drop-shadow(0 4px 14px rgba(0, 0, 0, 0.18)); +} + +.captureBtn { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 6px 14px; + border: var(--stroke) solid var(--ink); + border-radius: 0; + background: var(--paper-raised); + color: var(--ink); + font-family: var(--font-sans); + font-size: 13px; + font-weight: 700; + line-height: 1.4; + cursor: pointer; + user-select: none; + transition: background-color var(--duration-fast), color var(--duration-fast); +} + +.captureBtn:hover { + background: var(--ink); + color: var(--on-ink); +} + +.captureDone { + display: inline-flex; + padding: 6px 14px; + border: var(--stroke) solid var(--line-strong); + background: var(--paper-raised); + color: var(--ink-muted); + font-size: 13px; + white-space: nowrap; + user-select: none; +} + +.captureRejected { + color: var(--fail); + border-color: var(--fail); +} + +/* ── Navbar toggle ─────────────────────────────────────────────────────── */ + +.navToggle { + display: inline-flex; + align-items: center; + gap: 4px; + margin: 0 8px; + padding: 0 10px; + height: 28px; + border: var(--stroke) solid var(--line); + border-radius: 0; + background: var(--paper-sunken); + color: var(--ink-muted); + font-family: var(--font-sans); + font-size: 12px; + font-weight: 700; + line-height: 1; + cursor: pointer; + transition: color var(--duration-base), border-color var(--duration-base), + background-color var(--duration-base); +} + +.navToggle:hover { + color: var(--ink); + border-color: var(--ink); +} + +.navToggleActive { + color: var(--ink); + border-color: var(--ink); + background: var(--paper-raised); +} + +.navMark { + font-size: 13px; + line-height: 1; +} + +@media (max-width: 996px) { + .navToggle { + margin: 8px 0; + } +} + +/* Custom navbar item rendered inside the mobile menu
      . */ +.mobileNavToggle { + width: 100%; + border: none; + background: none; + color: inherit; + font-family: var(--font-sans); + font-size: inherit; + text-align: left; + cursor: pointer; +} + +.mobileNavToggleActive { + color: var(--ink); + font-weight: 700; +} + +/* ── Bookmarks page list ───────────────────────────────────────────────── */ + +.list { + max-width: 860px; +} + +.empty { + border: 1px dashed var(--line-strong); + background: var(--paper-sunken); + padding: 18px 20px; + color: var(--ink-muted); + line-height: 1.9; +} + +.groups { + list-style: none; + padding: 0; + margin: 0 0 var(--space-6); + display: flex; + flex-direction: column; + gap: var(--space-4); +} + +.group { + border: var(--stroke) solid var(--line); + background: var(--paper-raised); + overflow: hidden; +} + +.groupHead { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding-left: 4px; +} + +.groupTitle { + flex: 1; + min-width: 0; + display: inline-flex; + align-items: baseline; + gap: 8px; + padding: 10px 12px; + color: var(--ink); + text-decoration: none; +} + +.groupStar { + color: var(--ink); + font-size: 14px; +} + +.groupName { + font-weight: 700; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.groupTitle:hover .groupName { + text-decoration: underline; + text-underline-offset: 3px; +} + +.groupTime { + flex-shrink: 0; + color: var(--ink-muted); + font-size: 12px; + font-weight: 400; +} + +.unstar { + flex-shrink: 0; + margin-right: 10px; + border: none; + background: none; + padding: 4px 6px; + color: var(--ink-muted); + font-size: 12px; + cursor: pointer; +} + +.unstar:hover { + color: var(--fail); + background: var(--paper-sunken); +} + +.bmNotes { + list-style: none; + margin: 0; + padding: 6px 12px 10px 30px; + display: flex; + flex-direction: column; + gap: 6px; + border-top: 1px dashed var(--line); +} + +.bmNote { + display: flex; + align-items: flex-start; + gap: 4px; +} + +.bmNoteQuote { + flex: 1; + min-width: 0; + display: block; + padding: 2px 8px; + border-left: 3px solid var(--ink); + color: var(--ink-muted); + font-size: 13.5px; + line-height: 1.8; + text-decoration: none; + transition: color var(--duration-fast), border-left-color var(--duration-fast); +} + +.bmNoteQuote:hover { + color: var(--ink); + border-left-color: var(--line-strong); +} + +.bmNoteRemove { + flex-shrink: 0; + border: none; + background: none; + color: var(--ink-muted); + font-size: 16px; + line-height: 1.8; + cursor: pointer; + padding: 0 4px; +} + +.bmNoteRemove:hover { + color: var(--fail); +} + +/* ── export / import ───────────────────────────────────────────────────── */ + +.backup { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 16px; + border-top: var(--stroke) solid var(--line); + padding-top: 14px; +} + +.backupHint { + color: var(--ink-muted); + font-size: 13px; +} + +.backupActions { + display: inline-flex; + gap: 14px; +} + +.textLink { + border: none; + background: none; + padding: 0; + color: var(--ink); + font-family: var(--font-sans); + font-size: 13.5px; + font-weight: 600; + cursor: pointer; + text-decoration: underline; + text-decoration-thickness: var(--stroke); + text-underline-offset: 3px; +} + +.textLink:hover { + text-decoration-thickness: var(--stroke-strong); +} + +.fileInput { + display: none; +} + +.backupNote { + flex-basis: 100%; + color: var(--ink-muted); + font-size: 13px; +} + +@media print { + .capture { + display: none; + } + + .notes, + .backup { + display: none; + } +} + +@media (max-width: 600px) { + .notesHeading { + flex-wrap: wrap; + } + + .groupHead { + align-items: flex-start; + } + + .groupTitle { + flex-wrap: wrap; + } +} diff --git a/src/css/custom.css b/src/css/custom.css index 228528b..31104bf 100644 --- a/src/css/custom.css +++ b/src/css/custom.css @@ -294,3 +294,24 @@ body { .token.function { color: var(--ink); } + +/* ---- Local notes / bookmarks ------------------------------------------- */ + +/* Desktop TOC column, replacing the stock sticky TOC so the notes panel can + * live in the same scroll container below the outline. */ +.xr-doc-toc { + max-height: calc(100vh - (var(--ifm-navbar-height) + 2rem)); + overflow-y: auto; + position: sticky; + top: calc(var(--ifm-navbar-height) + 1rem); +} + +/* Flash used after jumping to a note (CSS Custom Highlight API). */ +::highlight(note-flash) { + background-color: rgba(161, 32, 111, 0.2); + background-color: color-mix(in srgb, var(--ch2) 22%, transparent); + text-decoration: underline; + text-decoration-color: var(--ch2); + text-decoration-thickness: var(--stroke-strong); + text-underline-offset: 3px; +} diff --git a/src/features/bookmarks/docContext.ts b/src/features/bookmarks/docContext.ts new file mode 100644 index 0000000..236bf67 --- /dev/null +++ b/src/features/bookmarks/docContext.ts @@ -0,0 +1,68 @@ +/** + * Small DOM helpers shared by the bookmark button, note capture and restore + * pipeline. Everything here is browser-only and guarded for SSR. + */ + +export const DOC_ROOT_SELECTOR = '.theme-doc-markdown'; + +/** Docs live at `/docs/...` (zh) and `/en/docs/...` (localised). */ +export function isDocPath(pathname: string): boolean { + return /^\/(?:[a-z]{2}(?:-[A-Za-z]{2})?\/)?docs(?:\/|$)/.test(pathname); +} + +/** `/en/docs/a` is on the English locale; `/docs/a` is the default one. */ +export function isEnglishPath(pathname: string): boolean { + return pathname === '/en' || pathname.startsWith('/en/'); +} + +/** Locale-aware bookmarks page href. */ +export function bookmarksHref(pathname: string): string { + return isEnglishPath(pathname) ? '/en/bookmarks' : '/bookmarks'; +} + +/** The article body of the current doc page, or null outside a doc. */ +export function getDocRoot(): Element | null { + if (typeof document === 'undefined') return null; + return ( + document.querySelector(DOC_ROOT_SELECTOR) ?? + document.querySelector('article .markdown') ?? + null + ); +} + +/** + * Article title for storage. Prefer the rendered `

      ` so front-matter titles + * without a Markdown heading (Docusaurus synthesises one) work too; fall back + * to the document title with the site suffix removed. + */ +export function getDocTitle(): string { + if (typeof document === 'undefined') return ''; + const heading = getDocRoot()?.querySelector('h1') ?? document.querySelector('article h1'); + const text = heading?.textContent?.trim(); + if (text) return text; + return document.title.split(/[||]/)[0].trim(); +} + +/** Current scroll position as a 0-100 percentage. */ +export function currentScrollPercent(): number { + if (typeof document === 'undefined') return 0; + const el = document.documentElement; + const max = el.scrollHeight - el.clientHeight; + return max > 0 ? Math.min(100, Math.max(0, Math.round((el.scrollTop / max) * 100))) : 0; +} + +/** + * Scroll to a percentage, re-applying three times. Images, Mermaid diagrams + * and lazily rendered content keep growing after the first paint, so a single + * attempt lands in the wrong place. + */ +export function scrollToPercent(percent: number): void { + const attempt = () => { + const el = document.documentElement; + const max = el.scrollHeight - el.clientHeight; + if (max > 0) el.scrollTop = (max * Math.min(100, Math.max(0, percent))) / 100; + }; + requestAnimationFrame(attempt); + setTimeout(attempt, 300); + setTimeout(attempt, 1200); +} diff --git a/src/features/bookmarks/noteDom.ts b/src/features/bookmarks/noteDom.ts new file mode 100644 index 0000000..2915ef8 --- /dev/null +++ b/src/features/bookmarks/noteDom.ts @@ -0,0 +1,110 @@ +import {appendNodeText, findLeadIndex, normalizeQuote, type CharSite} from './noteText'; +import {getDocRoot} from './docContext'; + +/** + * DOM locating and highlighting for notes (no storage dependency). + * + * The first 40 normalised characters of the quote act as a fingerprint. After + * navigation we rebuild a normalised-text ↔ text-node-offset map for the + * article body, `indexOf` the fingerprint, turn the hit into a Range, scroll it + * into view and flash it with the CSS Custom Highlight API (graceful fallback: + * scroll only). + */ + +/** Fingerprint length: long enough to be unique, short enough to survive edits. */ +const LEAD_LEN = 40; +const FLASH_MS = 2600; +const HIGHLIGHT_NAME = 'note-flash'; + +export function leadOf(quote: string): string { + return normalizeQuote(quote).slice(0, LEAD_LEN); +} + +interface TextIndex { + big: string; + map: CharSite[]; +} + +function buildIndex(root: Element): TextIndex { + const big: string[] = []; + const map: CharSite[] = []; + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode(node) { + const parent = (node as Text).parentElement; + if (!parent) return NodeFilter.FILTER_REJECT; + // Skip UI chrome Docusaurus puts inside the prose: heading hash links, + // copy buttons, hidden helper text. They are never part of a selection. + if (parent.closest('button, .hash-link, script, style, [aria-hidden="true"]')) { + return NodeFilter.FILTER_REJECT; + } + return NodeFilter.FILTER_ACCEPT; + }, + }); + let prev = ''; + while (walker.nextNode()) { + const node = walker.currentNode as Text; + prev = appendNodeText(node.data, prev, big, map, node); + } + return {big: big.join(''), map}; +} + +/** Locate `leadText` inside `root`; the returned Range spans the fingerprint. */ +export function locateLead(root: Element, leadText: string): Range | null { + if (!leadText || typeof document === 'undefined' || !document.createRange) return null; + const {big, map} = buildIndex(root); + const idx = findLeadIndex(big, leadText); + if (idx < 0) return null; + const end = Math.min(idx + leadText.length - 1, map.length - 1); + const start = map[idx]; + const stop = map[end]; + if (!start || !stop) return null; + const range = document.createRange(); + range.setStart(start.node, start.offset); + range.setEnd(stop.node, stop.offset + 1); + return range; +} + +let flashTimer: ReturnType | null = null; + +/** Scroll a Range into the middle of the viewport and flash it. */ +export function flashRange(range: Range): boolean { + const anchor = + range.startContainer.nodeType === Node.TEXT_NODE + ? range.startContainer.parentElement + : (range.startContainer as Element); + if (!anchor) return false; + + // Three attempts race Docusaurus' own route scroll reset and async media. + const scroll = () => anchor.scrollIntoView({block: 'center'}); + try { + scroll(); + setTimeout(scroll, 300); + setTimeout(scroll, 1200); + } catch { + return false; + } + + type HighlightCtor = new (range: Range) => unknown; + const css = (globalThis as {CSS?: {highlights?: Map}}).CSS; + const HighlightCtor = (globalThis as {Highlight?: HighlightCtor}).Highlight; + if (css?.highlights && HighlightCtor) { + try { + css.highlights.set(HIGHLIGHT_NAME, new HighlightCtor(range)); + if (flashTimer) clearTimeout(flashTimer); + flashTimer = setTimeout(() => css.highlights?.delete(HIGHLIGHT_NAME), FLASH_MS); + } catch { + // Highlighting is progressive enhancement; locating still succeeded. + } + } + return true; +} + +/** Restore a note: locate fingerprint + scroll + flash. False = use percent fallback. */ +export function restoreByLeadText(quote: string): boolean { + if (typeof document === 'undefined') return false; + const root = getDocRoot(); + if (!root) return false; + const range = locateLead(root, leadOf(quote)); + if (!range) return false; + return flashRange(range); +} diff --git a/src/features/bookmarks/noteText.ts b/src/features/bookmarks/noteText.ts new file mode 100644 index 0000000..e528054 --- /dev/null +++ b/src/features/bookmarks/noteText.ts @@ -0,0 +1,69 @@ +/** + * Text normalisation and index mapping for note anchors (pure logic). + * + * A selection's text is what the reader sees, but the DOM splits it across + * inline elements (`code`, `strong`, `a`) and whitespace from the Markdown + * source. To turn "first 40 chars of the quote" back into a DOM Range after a + * navigation, we build a per-character map from a normalised string to the + * original text-node offsets. + * + * Normalisation rules (must be identical on capture and lookup): + * - runs of whitespace collapse to one space, including at text-node edges; + * - zero-width characters (Docusaurus heading hash links inject them) are + * dropped so they cannot break a fingerprint. + */ + +export interface CharSite { + node: Text; + /** Index of this normalised character inside `node.data`. */ + offset: number; +} + +const ZERO_WIDTH = /[\u200B-\u200D\uFEFF]/; + +/** Fold one text node into `big` / `map`; `prevChar` handles cross-node whitespace. */ +export function appendNodeText( + data: string, + prevChar: string, + big: string[], + map: CharSite[], + node: Text, +): string { + let prev = prevChar; + for (let i = 0; i < data.length; i++) { + const ch = data[i]; + if (ZERO_WIDTH.test(ch)) continue; + if (/\s/.test(ch)) { + if (prev === ' ') continue; + big.push(' '); + map.push({node, offset: i}); + prev = ' '; + } else { + big.push(ch); + map.push({node, offset: i}); + prev = ch; + } + } + return prev; +} + +/** Normalise selection / quote text with the same rules as `appendNodeText`. */ +export function normalizeQuote(text: string): string { + return text.replace(/[\u200B-\u200D\uFEFF]/g, '').replace(/\s+/g, ' ').trim(); +} + +/** + * Find `leadText` in `big`. The exact match wins; for robust matching against + * small punctuation differences (list markers, spacing before punctuation), + * fall back to searching the tail after skipping two leading characters. + */ +export function findLeadIndex(big: string, leadText: string): number { + const idx = big.indexOf(leadText); + if (idx >= 0) return idx; + if (leadText.length > 8) { + const tail = leadText.slice(2); + const t = big.indexOf(tail); + if (t >= 0) return t - 2 >= 0 ? t - 2 : t; + } + return -1; +} diff --git a/src/features/bookmarks/readingKeys.ts b/src/features/bookmarks/readingKeys.ts new file mode 100644 index 0000000..d97c7d1 --- /dev/null +++ b/src/features/bookmarks/readingKeys.ts @@ -0,0 +1,73 @@ +import type {RestoreMark} from './types'; + +/** + * Path helpers shared by bookmarks and notes. + * + * A stored key is always a clean, leading-slash path without query, hash, + * `.html` suffix or trailing slash. Docusaurus runs with `trailingSlash: false` + * and `baseUrl: '/'`, so `location.pathname` already matches that shape; the + * normalisation still protects against hand-edited URLs and old backups. + */ + +export function stripHtmlExt(path: string): string { + return path.endsWith('.html') ? path.slice(0, -5) : path; +} + +/** Normalise any article path into the canonical localStorage key. */ +export function normalizePath(path: string): string { + let p = stripHtmlExt(path.split('#')[0].split('?')[0]); + if (!p) return '/'; + if (!p.startsWith('/')) p = `/${p}`; + if (p.length > 1 && p.endsWith('/')) p = p.slice(0, -1); + return p; +} + +/** `location.pathname` → storage key (see `normalizePath`). */ +export function pathnameToKey(pathname: string): string { + return normalizePath(pathname); +} + +// ── one-shot restore mark ────────────────────────────────────────────────── +// The bookmarks page writes it right before navigating; the target doc page +// consumes it once. sessionStorage keeps it scoped to this tab. + +const RESTORE_KEY = 'bookmarks:restore'; +/** Marks older than this are leftovers from an abandoned navigation. */ +const RESTORE_TTL_MS = 60 * 60 * 1000; + +export function markRestore(path: string, scrollPercent: number, noteLead?: string): void { + if (typeof sessionStorage === 'undefined') return; + try { + sessionStorage.setItem( + RESTORE_KEY, + JSON.stringify({ + path: normalizePath(path), + scrollPercent, + noteLead, + ts: Date.now(), + } satisfies RestoreMark), + ); + } catch { + // Private mode / quota: restoring is a bonus, navigation still works. + } +} + +/** Consume the mark if it targets `path` and is still fresh; otherwise drop it. */ +export function takeRestoreMark(path: string): RestoreMark | null { + if (typeof sessionStorage === 'undefined') return null; + let mark: RestoreMark | null = null; + try { + mark = JSON.parse(sessionStorage.getItem(RESTORE_KEY) ?? 'null') as RestoreMark | null; + sessionStorage.removeItem(RESTORE_KEY); + } catch { + try { + sessionStorage.removeItem(RESTORE_KEY); + } catch { + // Both reads and writes failed; nothing else to do. + } + return null; + } + if (!mark || normalizePath(mark.path) !== normalizePath(path)) return null; + if (typeof mark.ts !== 'number' || Date.now() - mark.ts > RESTORE_TTL_MS) return null; + return {...mark, path: normalizePath(mark.path)}; +} diff --git a/src/features/bookmarks/restore.ts b/src/features/bookmarks/restore.ts new file mode 100644 index 0000000..54ad515 --- /dev/null +++ b/src/features/bookmarks/restore.ts @@ -0,0 +1,86 @@ +import {useEffect} from 'react'; +import {useLocation} from '@docusaurus/router'; +import {currentScrollPercent} from './docContext'; +import {restoreByLeadText} from './noteDom'; +import {getBookmark, saveBookmark} from './useBookmarks'; +import {pathnameToKey, takeRestoreMark} from './readingKeys'; + +/** + * Restore the position recorded by a bookmarks-page click. + * + * A note jump carries a text fingerprint: locate and flash it (this is the + * precise path). A plain bookmark carries only a percentage, re-applied three + * times because Docusaurus' own route reset and async media fight the first + * attempt. If a note fingerprint no longer matches, the percentage is the + * fallback, exactly like the Tutorial code. + */ +export function useBookmarkRestore(): void { + const {pathname} = useLocation(); + + useEffect(() => { + const key = pathnameToKey(pathname); + const mark = takeRestoreMark(key); + if (!mark) return; + + let cancelled = false; + let noteDone = false; + + const attempt = () => { + if (cancelled || noteDone) return; + if (mark.noteLead && restoreByLeadText(mark.noteLead)) { + noteDone = true; + return; + } + const el = document.documentElement; + const max = el.scrollHeight - el.clientHeight; + if (max > 0) el.scrollTop = (max * Math.min(100, Math.max(0, mark.scrollPercent))) / 100; + }; + + const raf = requestAnimationFrame(attempt); + const timers = [setTimeout(attempt, 350), setTimeout(attempt, 1200)]; + return () => { + cancelled = true; + cancelAnimationFrame(raf); + timers.forEach(clearTimeout); + }; + }, [pathname]); +} + +/** + * Keep a bookmarked article's stored position up to date. Only articles that + * are already bookmarked are tracked, so merely reading leaves no trace. + */ +export function useBookmarkAutoTrack(): void { + const {pathname} = useLocation(); + + useEffect(() => { + const key = pathnameToKey(pathname); + let percent = currentScrollPercent(); + let disposed = false; + + const onScroll = () => { + if (disposed) return; + if (pathnameToKey(window.location.pathname) !== key) return; + percent = currentScrollPercent(); + }; + + const snapshot = () => { + // A jump to the top right before leaving must not overwrite useful progress. + if (percent <= 0) return; + const prev = getBookmark(key); + if (!prev) return; + saveBookmark({path: key, title: prev.title, scrollPercent: percent}); + }; + + window.addEventListener('scroll', onScroll, {passive: true}); + window.addEventListener('pagehide', snapshot); + onScroll(); + + return () => { + window.removeEventListener('scroll', onScroll); + window.removeEventListener('pagehide', snapshot); + snapshot(); + disposed = true; + }; + }, [pathname]); +} diff --git a/src/features/bookmarks/strings.ts b/src/features/bookmarks/strings.ts new file mode 100644 index 0000000..3abaaa8 --- /dev/null +++ b/src/features/bookmarks/strings.ts @@ -0,0 +1,141 @@ +import {useLocation} from '@docusaurus/router'; +import {isEnglishPath} from './docContext'; + +/** + * UI copy for the bookmark/note feature. The site has a Chinese default locale + * and an English one under `/en`; route-based selection keeps every component + * (including the navbar items) consistent without extra i18n wiring. + */ + +export interface BookmarkStrings { + navBookmarks: string; + notesTitle: string; + notesAll: string; + notesAllTitle: string; + notesEmptyTitle: string; + notesEmptyHint: string; + noteJumpTitle: string; + noteRemove: string; + + captureButton: string; + captureTitle: string; + captureSaved: string; + captureRejected: string; + + bookmarkAdd: string; + bookmarkAdded: string; + bookmarkAddTitle: string; + bookmarkAddedTitle: (percent: number) => string; + + pageTitle: string; + pageDescription: string; + pageIntro: string; + pageEmpty: string; + unstar: string; + unstarAria: (title: string) => string; + unstarTitle: string; + unstarDone: (title: string) => string; + readAt: (time: string) => string; + backupHint: (bookmarks: number, notes: number) => string; + exportBackup: string; + importBackup: string; + exportStarted: string; + exportFailed: string; + importFailedFormat: string; + importFailedRead: string; + importDone: (bookmarks: number, notes: number) => string; +} + +const zh: BookmarkStrings = { + navBookmarks: '书签', + notesTitle: '本页便签', + notesAll: '全部 ↗', + notesAllTitle: '去书签页看全部收藏与便签', + notesEmptyTitle: '本页还没有便签', + notesEmptyHint: + '划选正文里的一段文字,点弹出的\n「✎ 存为便签」,回头在这里一键跳回原处。', + noteJumpTitle: '点击定位到原文原处', + noteRemove: '删除这条便签', + + captureButton: '✎ 存为便签', + captureTitle: '把选中的文字存成便签,回头从书签页点它跳回原处', + captureSaved: '✓ 已存,书签页见', + captureRejected: '这段存不进(太短啦)', + + bookmarkAdd: '收藏', + bookmarkAdded: '已收藏', + bookmarkAddTitle: '收藏本页当前位置,回头从导航「书签」进来续读', + bookmarkAddedTitle: (percent) => `已收藏在 ${percent}%(点此取消,想换位置就删了重收)`, + + pageTitle: '书签', + pageDescription: '收藏的文章与摘录的便签都在这里——续读、跳回原文原处、导出导入备份', + pageIntro: '收藏的文章与摘录的便签都在这里。', + pageEmpty: + '还没有书签,也没有便签。读文章时点导航栏的「☆ 收藏」收下整篇;在正文里划选一段文字,点弹出的「✎ 存为便签」,回头从这里点它就能跳回原处。换设备前导出一份备份。', + unstar: '取消收藏', + unstarAria: (title) => `取消收藏「${title}」`, + unstarTitle: '取消收藏(这篇的便签会保留)', + unstarDone: (title) => `已取消「${title}」的收藏。`, + readAt: (time) => `读到 ${time}`, + backupHint: (bookmarks, notes) => + `书签与便签(${bookmarks} + ${notes})只存在当前浏览器,换设备或清缓存会丢,走之前导出一份,到了新地方再导入接上。`, + exportBackup: '导出备份 ↓', + importBackup: '导入备份 ↑', + exportStarted: '备份文件已开始下载,收好它;到新设备回到这里导入就能接上。', + exportFailed: '导出失败:当前浏览器不允许下载文件。QAQ', + importFailedFormat: '导入失败:这不是书签备份文件。', + importFailedRead: '导入失败:文件读不出来。', + importDone: (bookmarks, notes) => + `已导入:合并 ${bookmarks} 条书签、${notes} 条便签(同一条两边都动过时,保留更新时间晚的一方)。`, +}; + +const en: BookmarkStrings = { + navBookmarks: 'Bookmarks', + notesTitle: 'Notes on this page', + notesAll: 'All ↗', + notesAllTitle: 'Open Bookmarks to see all saved articles and notes', + notesEmptyTitle: 'No notes on this page yet', + notesEmptyHint: + 'Select a passage in the article, choose “✎ Save as note”, then jump back to it here.', + noteJumpTitle: 'Jump back to the original passage', + noteRemove: 'Delete this note', + + captureButton: '✎ Save as note', + captureTitle: + 'Save the selected text as a note; open it from Bookmarks to jump back to the spot', + captureSaved: '✓ Saved — see Bookmarks', + captureRejected: 'Too short to save', + + bookmarkAdd: 'Bookmark', + bookmarkAdded: 'Bookmarked', + bookmarkAddTitle: 'Bookmark this position; resume from Bookmarks later', + bookmarkAddedTitle: (percent) => + `Bookmarked at ${percent}% (click to remove; re-add to change position)`, + + pageTitle: 'Bookmarks', + pageDescription: + 'Your saved articles and highlighted notes live here — resume reading, jump back to the exact passage, export/import a backup', + pageIntro: 'Your saved articles and highlighted notes live here.', + pageEmpty: + 'No bookmarks or notes yet. While reading, click “☆ Bookmark” in the navbar to save the whole article, or select a passage and choose “✎ Save as note”; open it here later to jump back. Export a backup before switching devices.', + unstar: 'Remove', + unstarAria: (title) => `Remove bookmark “${title}”`, + unstarTitle: 'Remove bookmark (its notes are kept)', + unstarDone: (title) => `Removed “${title}” from bookmarks.`, + readAt: (time) => `read at ${time}`, + backupHint: (bookmarks, notes) => + `${bookmarks} bookmark(s) and ${notes} note(s) live only in this browser. Export a backup before switching devices or clearing site data, then import it on the new one.`, + exportBackup: 'Export backup ↓', + importBackup: 'Import backup ↑', + exportStarted: 'The backup download has started. Keep it safe and import it on the new device.', + exportFailed: 'Export failed: this browser does not allow downloads. QAQ', + importFailedFormat: 'Import failed: this is not a bookmark backup file.', + importFailedRead: 'Import failed: the file could not be read.', + importDone: (bookmarks, notes) => + `Imported: merged ${bookmarks} bookmark(s) and ${notes} note(s) (when both sides changed an item, the newer update wins).`, +}; + +export function useBookmarkStrings(): BookmarkStrings { + const {pathname} = useLocation(); + return isEnglishPath(pathname) ? en : zh; +} diff --git a/src/features/bookmarks/types.ts b/src/features/bookmarks/types.ts new file mode 100644 index 0000000..700ac25 --- /dev/null +++ b/src/features/bookmarks/types.ts @@ -0,0 +1,60 @@ +/** + * Shared data shapes for the local bookmark / note feature. + * + * Everything lives in localStorage, keyed by the clean article path, so the + * shapes are intentionally small and versioned by the storage key names. + */ + +/** A passage-level note captured from a text selection. */ +export interface Note { + /** Unique id: path + creation time + random suffix; used as React key and for deletion. */ + id: string; + /** Clean article path, e.g. `/docs/intro` or `/en/docs/intro`. */ + path: string; + /** Article title at capture time. */ + title: string; + /** Quoted source text (whitespace-normalised, truncated to 240 chars). */ + quote: string; + /** Scroll percentage at capture time: fallback when text matching fails. */ + scrollPercent: number; + createdAt: number; + updatedAt: number; +} + +/** An article-level bookmark (one star per article). */ +export interface Bookmark { + /** Clean article path, e.g. `/docs/intro`. */ + path: string; + /** Article title at bookmark time. */ + title: string; + /** Last read scroll percentage 0-100; auto-tracked while bookmarked. */ + scrollPercent: number; + createdAt: number; + updatedAt: number; +} + +/** Backup file written by the export button; v2 carries notes as well. */ +export interface BookmarksBackup { + app: 'site-bookmarks'; + version: 1 | 2; + exportedAt: string; + bookmarks: Bookmark[]; + notes?: Note[]; +} + +export interface ImportResult { + /** Number of bookmarks merged into this browser. */ + bookmarks: number; + /** Number of notes merged into this browser (0 for a v1 backup). */ + notes: number; +} + +/** One-shot restore instruction written by the bookmarks page before navigation. */ +export interface RestoreMark { + path: string; + scrollPercent: number; + /** Note lead fingerprint (first 40 chars); absent for bookmark jumps. */ + noteLead?: string; + /** Epoch ms, used to discard stale marks. */ + ts?: number; +} diff --git a/src/features/bookmarks/useBookmarks.ts b/src/features/bookmarks/useBookmarks.ts new file mode 100644 index 0000000..f58900c --- /dev/null +++ b/src/features/bookmarks/useBookmarks.ts @@ -0,0 +1,169 @@ +import {useCallback, useEffect, useState} from 'react'; +import {normalizePath, pathnameToKey} from './readingKeys'; +import {importNotes, loadNotes} from './useNotes'; +import type {Bookmark, BookmarksBackup, ImportResult} from './types'; + +/** + * "Bookmarks" localStorage store: one star per article, remembering the read + * position. No account and no cloud — export/import JSON is the only way to + * move a shelf between browsers. + */ + +const BOOKMARKS_KEY = 'bookmarks:v1'; +export const BOOKMARKS_EVENT = 'bookmarks:change'; + +function readStore(): Record { + if (typeof localStorage === 'undefined') return {}; + try { + const parsed = JSON.parse(localStorage.getItem(BOOKMARKS_KEY) ?? '{}'); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { + return {}; + } +} + +function writeStore(value: Record): boolean { + if (typeof localStorage === 'undefined') return false; + try { + localStorage.setItem(BOOKMARKS_KEY, JSON.stringify(value)); + window.dispatchEvent(new Event(BOOKMARKS_EVENT)); + return true; + } catch { + // Private mode / quota: bookmarks are optional, reading is not. + return false; + } +} + +function coerceBookmark(raw: unknown): Bookmark | null { + if (!raw || typeof raw !== 'object') return null; + const b = raw as Partial; + if (typeof b.path !== 'string' || !b.path || typeof b.title !== 'string') return null; + const percent = typeof b.scrollPercent === 'number' ? b.scrollPercent : 0; + return { + path: normalizePath(b.path), + title: b.title, + scrollPercent: Math.min(100, Math.max(0, percent)), + createdAt: typeof b.createdAt === 'number' ? b.createdAt : 0, + updatedAt: typeof b.updatedAt === 'number' ? b.updatedAt : 0, + }; +} + +/** All bookmarks, most recently read first. */ +export function loadBookmarks(): Bookmark[] { + return Object.values(readStore()) + .map(coerceBookmark) + .filter((b): b is Bookmark => b !== null) + .sort((a, b) => b.updatedAt - a.updatedAt); +} + +export function getBookmark(path: string): Bookmark | null { + return coerceBookmark(readStore()[normalizePath(path)]); +} + +/** Bookmark an article; an existing entry keeps its `createdAt`. */ +export function saveBookmark(input: { + path: string; + title: string; + scrollPercent: number; +}): Bookmark | null { + if (!input.path) return null; + const store = readStore(); + const key = normalizePath(input.path); + const prev = coerceBookmark(store[key]); + const now = Date.now(); + const next: Bookmark = { + path: key, + title: input.title, + scrollPercent: Math.min(100, Math.max(0, input.scrollPercent)), + createdAt: prev?.createdAt ?? now, + updatedAt: now, + }; + store[key] = next; + writeStore(store); + return next; +} + +export function removeBookmark(path: string): void { + const store = readStore(); + delete store[normalizePath(path)]; + writeStore(store); +} + +// ── backup ───────────────────────────────────────────────────────────────── + +/** Backup v2 carries notes; import remains compatible with v1 files. */ +export function exportBookmarks(): string { + const backup: BookmarksBackup = { + app: 'site-bookmarks', + version: 2, + exportedAt: new Date().toISOString(), + bookmarks: loadBookmarks(), + notes: loadNotes(), + }; + return JSON.stringify(backup); +} + +/** Merge a backup: bookmark path + newer `updatedAt` wins; notes merge by id. */ +export function importBookmarks(raw: string): ImportResult | null { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return null; + } + const data = parsed && typeof parsed === 'object' ? (parsed as Partial) : null; + if (!data || data.app !== 'site-bookmarks' || !Array.isArray(data.bookmarks)) return null; + + const store = readStore(); + let bookmarkCount = 0; + for (const rawBookmark of data.bookmarks) { + const incoming = coerceBookmark(rawBookmark); + if (!incoming) continue; + const local = coerceBookmark(store[incoming.path]); + if (!local || incoming.updatedAt >= local.updatedAt) { + store[incoming.path] = incoming; + bookmarkCount++; + } + } + writeStore(store); + const noteCount = importNotes(data.notes); + return {bookmarks: bookmarkCount, notes: noteCount}; +} + +// ── React binding ────────────────────────────────────────────────────────── + +/** Current article's bookmark plus a toggle action. */ +export function useBookmarkState(pathname: string): { + bookmark: Bookmark | null; + toggle: (title: string, scrollPercent: number) => void; +} { + const key = pathnameToKey(pathname); + const [bookmark, setBookmark] = useState(null); + + const sync = useCallback(() => setBookmark(getBookmark(key)), [key]); + + useEffect(() => { + sync(); + const onStorage = () => sync(); + window.addEventListener(BOOKMARKS_EVENT, onStorage); + window.addEventListener('storage', onStorage); + return () => { + window.removeEventListener(BOOKMARKS_EVENT, onStorage); + window.removeEventListener('storage', onStorage); + }; + }, [sync]); + + const toggle = useCallback( + (title: string, scrollPercent: number) => { + const existing = getBookmark(key); + if (existing) removeBookmark(key); + else saveBookmark({path: key, title, scrollPercent}); + setBookmark(getBookmark(key)); + }, + [key], + ); + + // During a route transition the effect has not synced yet; never expose the + // previous article's bookmark as if it belonged to the new one. + return {bookmark: bookmark?.path === key ? bookmark : null, toggle}; +} diff --git a/src/features/bookmarks/useNotes.ts b/src/features/bookmarks/useNotes.ts new file mode 100644 index 0000000..9716050 --- /dev/null +++ b/src/features/bookmarks/useNotes.ts @@ -0,0 +1,164 @@ +import {useCallback, useEffect, useState} from 'react'; +import {currentScrollPercent, getDocRoot} from './docContext';import {normalizePath, pathnameToKey} from './readingKeys'; +import {normalizeQuote} from './noteText'; +import type {Note} from './types'; + +/** + * "Notes" localStorage store: a passage selected in an article is saved with a + * text fingerprint and the scroll percentage at capture time. Notes are + * browser-local; they travel between devices only through the bookmark backup + * file (version 2). + */ + +const NOTES_KEY = 'notes:v1'; +export const NOTES_EVENT = 'notes:change'; + +/** Stored quote length limit. */ +const QUOTE_MAX = 240; + +function readStore(): Record { + if (typeof localStorage === 'undefined') return {}; + try { + const parsed = JSON.parse(localStorage.getItem(NOTES_KEY) ?? '{}'); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { + return {}; + } +} + +function writeStore(value: Record): boolean { + if (typeof localStorage === 'undefined') return false; + try { + localStorage.setItem(NOTES_KEY, JSON.stringify(value)); + window.dispatchEvent(new Event(NOTES_EVENT)); + return true; + } catch { + // Private mode / quota: never block reading because a note cannot be saved. + return false; + } +} + +function coerceNote(raw: unknown): Note | null { + if (!raw || typeof raw !== 'object') return null; + const n = raw as Partial; + if (typeof n.id !== 'string' || !n.id || typeof n.path !== 'string' || !n.path) return null; + if (typeof n.quote !== 'string' || !n.quote) return null; + return { + id: n.id, + path: normalizePath(n.path), + title: typeof n.title === 'string' ? n.title : '', + quote: n.quote, + scrollPercent: + typeof n.scrollPercent === 'number' + ? Math.min(100, Math.max(0, n.scrollPercent)) + : 0, + createdAt: typeof n.createdAt === 'number' ? n.createdAt : 0, + updatedAt: typeof n.updatedAt === 'number' ? n.updatedAt : 0, + }; +} + +/** All notes, newest first. */ +export function loadNotes(): Note[] { + return Object.values(readStore()) + .map(coerceNote) + .filter((n): n is Note => n !== null) + .sort((a, b) => b.createdAt - a.createdAt); +} + +export function removeNote(id: string): void { + const store = readStore(); + delete store[id]; + writeStore(store); +} + +// ── capture: selection → Note ────────────────────────────────────────────── + +/** Whether the selection is inside the article body (code blocks and tables included). */ +function selectionInDoc(sel: Selection): boolean { + if (sel.rangeCount === 0) return false; + const root = getDocRoot(); + if (!root) return false; + const container = sel.getRangeAt(0).commonAncestorContainer; + const el = + container.nodeType === Node.TEXT_NODE + ? container.parentElement + : (container as Element); + return !!el && root.contains(el); +} + +/** + * Capture the current selection as a note. + * Returns null when the selection is empty, outside the article, or too short. + */ +export function captureNoteFromSelection(title: string): Note | null { + if (typeof window === 'undefined') return null; + const sel = window.getSelection(); + if (!sel || sel.isCollapsed || !selectionInDoc(sel)) return null; + + const quote = normalizeQuote(sel.toString()).slice(0, QUOTE_MAX); + if (quote.length < 4) return null; + + const path = pathnameToKey(location.pathname); + const now = Date.now(); + const note: Note = { + id: `${path}#${now}${Math.random().toString(36).slice(2, 6)}`, + path, + title, + quote, + scrollPercent: currentScrollPercent(), + createdAt: now, + updatedAt: now, + }; + const store = readStore(); + store[note.id] = note; + writeStore(store); + return note; +} + +// ── backup segment ───────────────────────────────────────────────────────── + +/** Merge a `notes` array from a backup; same id → newer `updatedAt` wins. */ +export function importNotes(rawNotes: unknown[] | undefined): number { + if (!Array.isArray(rawNotes)) return 0; + const store = readStore(); + let count = 0; + for (const raw of rawNotes) { + const incoming = coerceNote(raw); + if (!incoming) continue; + const local = coerceNote(store[incoming.id]); + if (!local || incoming.updatedAt >= local.updatedAt) { + store[incoming.id] = incoming; + count++; + } + } + writeStore(store); + return count; +} + +// ── React binding ────────────────────────────────────────────────────────── + +/** + * Notes for the current article, refreshed on every save/delete and on + * cross-tab storage updates. `pathname` is the dependency that changes when + * Docusaurus navigates between docs. + */ +export function useNotesForPath(pathname: string): Note[] { + const [notes, setNotes] = useState([]); + const sync = useCallback(() => { + const key = pathnameToKey(pathname); + setNotes(loadNotes().filter((n) => n.path === key)); + }, [pathname]); + + useEffect(() => { + sync(); + const onStorage = () => sync(); + window.addEventListener(NOTES_EVENT, onStorage); + window.addEventListener('storage', onStorage); + return () => { + window.removeEventListener(NOTES_EVENT, onStorage); + window.removeEventListener('storage', onStorage); + }; + }, [sync]); + + return notes; +} diff --git a/src/pages/bookmarks.module.css b/src/pages/bookmarks.module.css new file mode 100644 index 0000000..27e5f89 --- /dev/null +++ b/src/pages/bookmarks.module.css @@ -0,0 +1,36 @@ +/* Bookmarks page (/bookmarks). XRobot Style tokens only. */ + +.page { + background: var(--paper); + color: var(--ink); +} + +.inner { + max-width: var(--measure-page); + margin: 0 auto; + padding: var(--space-12) var(--space-8) var(--space-16); +} + +.header { + max-width: var(--measure-prose); + margin-bottom: var(--space-8); +} + +.title { + margin: var(--space-2) 0 var(--space-3); + font-size: var(--type-display-size); + line-height: var(--type-display-line); + font-weight: 700; + color: var(--ink); +} + +.lead { + margin: 0; + color: var(--ink-muted); +} + +@media (max-width: 600px) { + .inner { + padding: var(--space-8) var(--space-4) var(--space-12); + } +} diff --git a/src/pages/bookmarks.tsx b/src/pages/bookmarks.tsx new file mode 100644 index 0000000..54ea030 --- /dev/null +++ b/src/pages/bookmarks.tsx @@ -0,0 +1,39 @@ +import React from 'react'; +import Layout from '@theme/Layout'; +import {useLocation} from '@docusaurus/router'; +import BookmarkList from '@site/src/components/bookmarks/BookmarkList'; +import {PathLabel} from '@site/src/components/xr'; +import {isEnglishPath} from '@site/src/features/bookmarks/docContext'; +import {useBookmarkStrings} from '@site/src/features/bookmarks/strings'; +import styles from './bookmarks.module.css'; + +/** `@theme/Layout` is typed as a bare component alias; mirror the props we use. */ +const PageLayout = Layout as unknown as React.ComponentType<{ + title?: string; + description?: string; + children: React.ReactNode; +}>; + +/** + * `/bookmarks` (and `/en/bookmarks`): the local shelf of bookmarked articles + * and captured notes. Everything is client-side localStorage. + */ +export default function BookmarksPage(): React.JSX.Element { + const {pathname} = useLocation(); + const t = useBookmarkStrings(); + + return ( + +
      +
      +
      + +

      {t.pageTitle}

      +

      {t.pageIntro}

      +
      + +
      +
      +
      + ); +} diff --git a/src/theme-modules.d.ts b/src/theme-modules.d.ts index c35f919..068d582 100644 --- a/src/theme-modules.d.ts +++ b/src/theme-modules.d.ts @@ -10,6 +10,18 @@ declare module '@theme/*'; declare module '@theme-original/*'; +declare module '@docusaurus/plugin-content-docs/client' { + export function useDoc(): { + toc: Array<{id: string; value: string; level: number; children?: unknown[]}>; + frontMatter: { + toc_min_heading_level?: number; + toc_max_heading_level?: number; + [key: string]: unknown; + }; + metadata: {title: string; [key: string]: unknown}; + }; +} + declare module '@docusaurus/Translate' { import type React from 'react'; export function translate( diff --git a/src/theme/DocItem/Layout/index.tsx b/src/theme/DocItem/Layout/index.tsx new file mode 100644 index 0000000..4895a38 --- /dev/null +++ b/src/theme/DocItem/Layout/index.tsx @@ -0,0 +1,60 @@ +import React, {type ReactNode} from 'react'; +import clsx from 'clsx'; +import {useWindowSize} from '@docusaurus/theme-common'; +import {useDoc} from '@docusaurus/plugin-content-docs/client'; +import DocItemPaginator from '@theme/DocItem/Paginator'; +import DocVersionBanner from '@theme/DocVersionBanner'; +import DocVersionBadge from '@theme/DocVersionBadge'; +import DocItemFooter from '@theme/DocItem/Footer'; +import DocItemTOCMobile from '@theme/DocItem/TOC/Mobile'; +import DocItemTOCDesktop from '@theme/DocItem/TOC/Desktop'; +import DocItemContent from '@theme/DocItem/Content'; +import DocBreadcrumbs from '@theme/DocBreadcrumbs'; +import ContentVisibility from '@theme/ContentVisibility'; +import styles from './styles.module.css'; + +/** + * Stock `DocItem/Layout`, adapted for the local notes panel. + * + * Docusaurus only renders the right-hand column when `toc.length > 0`. Short + * articles without any `##` heading would then lose the "notes on this page" + * panel entirely, so the desktop column is kept whenever the TOC is not + * explicitly hidden; `DocItem/TOC/Desktop` renders the notes panel and simply + * omits an empty outline. + */ +function useDocTOC() { + const {frontMatter, toc} = useDoc(); + const windowSize = useWindowSize(); + const hidden = frontMatter.hide_table_of_contents; + const hasHeadings = !hidden && toc.length > 0; + const mobile = hasHeadings ? : undefined; + const desktop = + !hidden && (windowSize === 'desktop' || windowSize === 'ssr') ? ( + + ) : undefined; + return {hidden, mobile, desktop}; +} + +export default function DocItemLayout({children}: {children: ReactNode}): ReactNode { + const docTOC = useDocTOC(); + const {metadata} = useDoc(); + return ( +
      +
      + + +
      +
      + + + {docTOC.mobile} + {children} + +
      + +
      +
      + {docTOC.desktop &&
      {docTOC.desktop}
      } +
      + ); +} diff --git a/src/theme/DocItem/Layout/styles.module.css b/src/theme/DocItem/Layout/styles.module.css new file mode 100644 index 0000000..c5d3067 --- /dev/null +++ b/src/theme/DocItem/Layout/styles.module.css @@ -0,0 +1,12 @@ +/* Copied from @docusaurus/theme-classic DocItem/Layout (3.9.2). */ + +.docItemContainer header + *, +.docItemContainer article > *:first-child { + margin-top: 0; +} + +@media (min-width: 997px) { + .docItemCol { + max-width: 75% !important; + } +} diff --git a/src/theme/DocItem/TOC/Desktop/index.tsx b/src/theme/DocItem/TOC/Desktop/index.tsx new file mode 100644 index 0000000..4f56c5a --- /dev/null +++ b/src/theme/DocItem/TOC/Desktop/index.tsx @@ -0,0 +1,27 @@ +import React from 'react'; +import {useDoc} from '@docusaurus/plugin-content-docs/client'; +import TOCItems from '@theme/TOCItems'; +import ArticleNotes from '@site/src/components/bookmarks/ArticleNotes'; + +/** + * Desktop right-hand TOC, with the current article's notes appended inside the + * same sticky column (we replace the stock `DocItem/TOC/Desktop` component). + */ +export default function DocItemTOCDesktop(): React.JSX.Element { + const {toc, frontMatter} = useDoc(); + + return ( +
      + {toc.length > 0 ? ( + + ) : null} + +
      + ); +} diff --git a/src/theme/NavbarItem/ComponentTypes.tsx b/src/theme/NavbarItem/ComponentTypes.tsx new file mode 100644 index 0000000..09f9cc7 --- /dev/null +++ b/src/theme/NavbarItem/ComponentTypes.tsx @@ -0,0 +1,14 @@ +import ComponentTypes from '@theme-original/NavbarItem/ComponentTypes'; +import BookmarkButton from '@site/src/components/bookmarks/BookmarkButton'; +import BookmarksNavLink from '@site/src/components/bookmarks/BookmarksNavLink'; + +/** + * Custom navbar item types used by docusaurus.config.js: + * type: 'custom-bookmark' → article star toggle + * type: 'custom-bookmarks-link' → locale-aware link to /bookmarks + */ +export default { + ...ComponentTypes, + 'custom-bookmark': BookmarkButton, + 'custom-bookmarks-link': BookmarksNavLink, +}; diff --git a/src/theme/Root/index.tsx b/src/theme/Root/index.tsx index defd25c..696107b 100644 --- a/src/theme/Root/index.tsx +++ b/src/theme/Root/index.tsx @@ -1,6 +1,7 @@ import React, {type ReactNode} from 'react'; import OriginalRoot from '@theme-original/Root'; import ReadingProgress from '@site/src/components/reading/ReadingProgress'; +import BookmarkSystem from '@site/src/components/bookmarks/BookmarkSystem'; /** * App-level wrapper (wrapped `@theme/Root`, which Docusaurus core provides as @@ -15,6 +16,7 @@ export default function Root({children}: {children: ReactNode}): ReactNode { {children} + ); }