diff --git a/server/router/frontend/frontend.go b/server/router/frontend/frontend.go index 78c1b1c6..bfa9c7a6 100644 --- a/server/router/frontend/frontend.go +++ b/server/router/frontend/frontend.go @@ -23,7 +23,7 @@ var embeddedFiles embed.FS const ( frontendHTMLCacheControl = "no-cache, no-store, must-revalidate" frontendStaticAssetCacheControl = "public, max-age=3600" - frontendHashedAssetCacheControl = "public, max-age=3600, immutable" + frontendHashedAssetCacheControl = "public, max-age=2592000, immutable" ) type FrontendService struct { diff --git a/store/seed/sqlite/01__dump.sql b/store/seed/sqlite/01__dump.sql index 2053860b..c6855b52 100644 --- a/store/seed/sqlite/01__dump.sql +++ b/store/seed/sqlite/01__dump.sql @@ -26,7 +26,7 @@ INSERT INTO user (id,username,role,nickname,description,password_hash) VALUES(4, -- ============================================================================ -- 1. Welcome (steven, pinned) โ€” orientation + SSO call-to-action + protected teaser -INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,pinned,payload) VALUES(1,'welcome0000001',1,strftime('%s','now','-2 days'),strftime('%s','now','-2 days'),replace('# Welcome to Memos ๐Ÿ‘‹\n\nHi, I''m Steven โ€” I build Memos. You''ve found the public demo: a real, living instance where you can poke at every feature before self-hosting your own.\n\nMemos is an open-source, self-hosted home for short-form thoughts. Capture quickly, organize lightly, own everything.\n\n> Most apps treat notes like documents. Memos treats them like thoughts โ€” small, timestamped, searchable.\n\n## Make yourself at home\n\n- [ ] Scroll this Explore feed โ€” everything here was written with Memos\n- [ ] React to a memo you like (๐ŸŽ‰ works great on this one)\n- [ ] **Sign in** (top right) โ€” SSO takes ten seconds and gives you your own space\n- [ ] Write your first memo. One sentence is plenty. That''s the point.\n- [ ] Like it? Star [the repo](https://github.com/usememos/memos) โญ\n\n๐Ÿ”’ *Psst โ€” a few memos on this instance are hidden until you sign in. Members only.*\n\n## What Memos can do\n\n| Feature | Where to see it |\n|---------|-----------------|\n| **Markdown** | Everywhere โ€” tables, `code`, task lists, quotes |\n| **Math & diagrams** | KaTeX and Mermaid โ€” see my rendering test memo |\n| **Tags** | `#dev/git` โ€” nested tags grow a tree in the sidebar |\n| **Comments & reactions** | Right under this memo ๐Ÿ‘‡ |\n| **Memo references** | Alice''s weekly review links back to her week |\n| **Attachments** | Ben''s golden-hour art from the coastal trail |\n| **Locations** | Look for the ๐Ÿ“ pins |\n| **Visibility** | Public, protected, or private โ€” chosen per memo |\n\n## Take it home\n\n```bash\ndocker run -d -p 5230:5230 -v ~/.memos:/var/opt/memos neosmemo/memos:stable\n```\n\nYour data lives in one SQLite file, on your machine. #welcome #getting-started','\n',char(10)),'PUBLIC',1,'{"tags":["welcome","getting-started"],"property":{"hasLink":true,"hasCode":true,"hasTaskList":true,"hasIncompleteTasks":true}}'); +INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,pinned,payload) VALUES(1,'welcome0000001',1,strftime('%s','now','-2 days'),strftime('%s','now','-2 days'),replace('# Welcome to Memos ๐Ÿ‘‹\n\nHi, I''m Steven โ€” I build Memos. You''ve found the public demo: a real, living instance where you can poke at every feature before self-hosting your own.\n\nMemos is an open-source, self-hosted home for short-form thoughts. Capture quickly, organize lightly, own everything.\n\n> Most apps treat notes like documents. Memos treats them like thoughts โ€” small, timestamped, searchable.\n\n## Make yourself at home\n\n- [ ] Scroll this Explore feed โ€” everything here was written with Memos\n- [ ] React to a memo you like (๐ŸŽ‰ works great on this one)\n- [ ] **Sign in** (top right) โ€” SSO takes ten seconds and gives you your own space\n- [ ] Write your first memo. One sentence is plenty. That''s the point.\n- [ ] Like it? Star [the repo](https://github.com/usememos/memos) โญ\n\n๐Ÿ”’ *Psst โ€” a few memos on this instance are hidden until you sign in. Members only.*\n\n## What Memos can do\n\n| Feature | Where to see it |\n|---------|-----------------|\n| **Markdown** | Everywhere โ€” tables, `code`, task lists, quotes |\n| **Tags** | `#dev/git` โ€” nested tags grow a tree in the sidebar |\n| **Comments & reactions** | Right under this memo ๐Ÿ‘‡ |\n| **Memo references** | Alice''s weekly review links back to her week |\n| **Attachments** | Ben''s golden-hour art from the coastal trail |\n| **Locations** | Look for the ๐Ÿ“ pins |\n| **Visibility** | Public, protected, or private โ€” chosen per memo |\n\n## Take it home\n\n```bash\ndocker run -d -p 5230:5230 -v ~/.memos:/var/opt/memos neosmemo/memos:stable\n```\n\nYour data lives in one SQLite file, on your machine. #welcome #getting-started','\n',char(10)),'PUBLIC',1,'{"tags":["welcome","getting-started"],"property":{"hasLink":true,"hasCode":true,"hasTaskList":true,"hasIncompleteTasks":true}}'); -- 2. Sponsors (steven, pinned) โ€” sits below Welcome (older created_ts) INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,pinned,payload) VALUES(2,'sponsors000001',1,strftime('%s','now','-6 days'),strftime('%s','now','-6 days'),replace('Memos is free and open source, kept independent by its sponsors โ€” no ads, no telemetry, no paywalls. ๐Ÿ™ If you build with Memos, please consider supporting them in return.\n\n## โญ Sponsors\n\nCodeRabbit\n\nCut code review time & bugs in half, instantly. [coderabbit.link/usememos โ†’](https://coderabbit.link/usememos)\n\n---\n\n**SSD Nodes** โ€” Affordable VPS hosting for self-hosters. [ssdnodes.com โ†’](https://ssdnodes.com/?utm_source=memos&utm_medium=sponsor)\n\n---\n\nWant to see your company here? Reach out via [GitHub Sponsors](https://github.com/sponsors/usememos).\n\n#sponsors','\n',char(10)),'PUBLIC',1,'{"tags":["sponsors"],"property":{"hasLink":true}}'); @@ -36,7 +36,10 @@ INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,pin -- and thinning out toward -22 days so the feed reads as a living instance -- ============================================================================ --- 3. Ben: photo memo with an image attachment + location (newest in the feed) +-- 10. Steven: official Chrome extension launch (featured first in Explore) +INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,payload) VALUES(10,'webclipper0001',1,strftime('%s','now','-30 minutes'),strftime('%s','now','-30 minutes'),replace('# โœ‚๏ธ Memos Web Clipper for Chrome\n\nThe ***official*** Memos Web Clipper turns the page you''re reading into a source-linked memo in under five seconds.\n\n[Add Memos Web Clipper to Chrome โ†’](https://chromewebstore.google.com/detail/memos-web-clipper/nebaoebnljalfegiidibihhkebeiklbl)\n\n| Capture from Chrome | What lands in Memos |\n|---------------------|---------------------|\n| Current page | Title, summary, and source link |\n| Text selection | Quoted excerpt with its source |\n| Selected image | A real attachment on your instance |\n\nEdit the generated memo, choose its visibility, or customize the template and default tags before saving.\n\n### Private by design\n\nThe clipper sends captured content only to the self-hosted Memos instance you connect โ€” and only when you save. No analytics, third-party servers, or tracking. #memos/extensions','\n',char(10)),'PUBLIC','{"tags":["memos/extensions"],"property":{"hasLink":true}}'); + +-- 3. Ben: photo memo with an image attachment + location INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,payload) VALUES(3,'goldenhour0001',3,strftime('%s','now','-3 hours'),strftime('%s','now','-3 hours'),'Golden hour on the coastal trail tonight. The camera couldn''t hold the colors, so here''s my minimal-art rendition instead ๐ŸŽจ #travel/hikes','PUBLIC','{"tags":["travel/hikes"],"property":{"hasLink":false},"location":{"placeholder":"Point Reyes, California, United States","latitude":37.9954,"longitude":-123.0204}}'); -- 27. Steven: build-in-public changelog note (real v0.30 highlights) @@ -63,12 +66,8 @@ INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,pay -- 9. Zoe: recipe with a task list INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,payload) VALUES(9,'zoeramen000001',4,strftime('%s','now','-4 days'),strftime('%s','now','-4 days'),replace('## ๐Ÿœ Midnight miso ramen (15 minutes)\n\nFor nights when the book was too good to stop reading.\n\n- [x] Dashi or veg stock, 500ml\n- [x] Miso paste, 2 big spoons\n- [x] Noodles, one nest\n- [x] Soft egg โ€” 6ยฝ minutes, exactly\n- [ ] Scallions (always forget the scallions)\n\nSteep the miso, don''t boil it. That''s the whole secret. #cooking','\n',char(10)),'PUBLIC','{"tags":["cooking"],"property":{"hasLink":false,"hasTaskList":true,"hasIncompleteTasks":true}}'); --- 10. Steven: Scratchpad promo -INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,payload) VALUES(10,'scratchpad0001',1,strftime('%s','now','-8 days'),strftime('%s','now','-8 days'),replace('## ๐Ÿงฉ Try Memos Scratchpad\n\nA lightweight visual canvas for quick thoughts, links, images, files, and small cards before they become polished notes.\n\n[Open Scratchpad โ†’](https://usememos.com/scratchpad)\n\n| Need | Scratchpad helps you |\n|------|----------------------|\n| Capture fast | Double-click to add notes |\n| Arrange freely | Drag cards around |\n| Add context | Attach files, links, and images |\n| Move around | Zoom and pan without setup |\n\n### Local-first\n\nYour Scratchpad cards stay in your browser. Memos does not access, sync, or store them.','\n',char(10)),'PUBLIC','{"property":{"hasLink":true}}'); - --- 30. Steven: rendering test page โ€” the explicit feature showcase (math, mermaid, --- syntax highlighting, tables, task lists, text styles) framed as maintainer dogfooding -INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,payload) VALUES(30,'rendertest0001',1,strftime('%s','now','-10 days'),strftime('%s','now','-10 days'),replace('## ๐Ÿงช My rendering test memo #memos/dev\n\nI keep this memo around to eyeball the renderer after every release. If anything below looks broken, the next version isn''t shipping.\n\n**Bold**, *italic*, ~~strikethrough~~, `inline code`, and a [link](https://www.usememos.com/docs).\n\n> Blockquotes, naturally.\n\nInline math $e^{i\pi} + 1 = 0$ and block math:\n\n$$\n\int_{-\infty}^{\infty} e^{-x^2}\,dx = \sqrt{\pi}\n$$\n\n```mermaid\ngraph LR\n A[Capture] --> B[Tag]\n B --> C[Find it later]\n C --> A\n```\n\n```go\nfunc main() {\n fmt.Println("syntax highlighting โœ“")\n}\n```\n\n| Render | Status |\n|--------|--------|\n| Tables | โœ… |\n| Everything else | see above |\n\n- [x] KaTeX loads\n- [x] Mermaid draws\n- [ ] Find a bug before users do','\n',char(10)),'PUBLIC','{"tags":["memos/dev"],"property":{"hasLink":true,"hasCode":true,"hasTaskList":true,"hasIncompleteTasks":true}}'); +-- 30. Steven: compact Markdown rendering check framed as maintainer dogfooding +INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,payload) VALUES(30,'rendertest0001',1,strftime('%s','now','-10 days'),strftime('%s','now','-10 days'),replace('## ๐Ÿงช Markdown rendering check #memos/dev\n\nA quick smoke test I open after releases:\n\n**Bold**, *italic*, ~~strikethrough~~, `inline code`, and a [docs link](https://www.usememos.com/docs).\n\n> Simple notes should render beautifully.\n\n```go\nfmt.Println("syntax highlighting โœ“")\n```\n\n| Check | Status |\n|-------|--------|\n| Text styles | โœ… |\n| Code blocks | โœ… |\n| Tables | โœ… |\n\n- [x] Check desktop\n- [x] Check mobile\n- [ ] Ship the next release','\n',char(10)),'PUBLIC','{"tags":["memos/dev"],"property":{"hasLink":true,"hasCode":true,"hasTaskList":true,"hasIncompleteTasks":true}}'); -- 11. Zoe: movie watchlist with a table INSERT INTO memo (id,uid,creator_id,created_ts,updated_ts,content,visibility,payload) VALUES(11,'zoemovies00001',4,strftime('%s','now','-9 days'),strftime('%s','now','-9 days'),replace('## ๐ŸŽฌ Movie catch-up #movies\n\nWorking through films I''ve been meaning to watch for, uh, years.\n\n| Movie | Status | Rating |\n|-------|--------|--------|\n| The Grand Budapest Hotel | โœ… Watched | โญโญโญโญโญ |\n| Spirited Away | โœ… Watched | โญโญโญโญโญ |\n| Everything Everywhere All at Once | โœ… Watched | โญโญโญโญโญ |\n| Dune: Part Two | ๐Ÿ“… This weekend | โ€” |\n| Oppenheimer | ๐Ÿ“‹ Queued | โ€” |\n\n**Spirited Away**: cried twice, no regrets. **Everything Everywhere**: went in cold, did not expect the bagel.\n\nNext month: full Miyazaki marathon ๐ŸŽจ Taking suggestions for where to start.','\n',char(10)),'PUBLIC','{"tags":["movies"],"property":{"hasLink":false}}'); @@ -176,7 +175,7 @@ INSERT INTO reaction (id,creator_id,content_id,reaction_type) VALUES(20,1,'memos INSERT INTO reaction (id,creator_id,content_id,reaction_type) VALUES(21,4,'memos/bennighttrain1','๐Ÿ’›'); INSERT INTO reaction (id,creator_id,content_id,reaction_type) VALUES(22,3,'memos/alicegitcheat1','๐Ÿ”ฅ'); INSERT INTO reaction (id,creator_id,content_id,reaction_type) VALUES(23,4,'memos/alicegitcheat1','๐Ÿ’ก'); -INSERT INTO reaction (id,creator_id,content_id,reaction_type) VALUES(24,4,'memos/scratchpad0001','๐Ÿ’ก'); +INSERT INTO reaction (id,creator_id,content_id,reaction_type) VALUES(24,4,'memos/webclipper0001','๐Ÿ’ก'); INSERT INTO reaction (id,creator_id,content_id,reaction_type) VALUES(25,1,'memos/tagtipmemo0001','๐Ÿ‘'); INSERT INTO reaction (id,creator_id,content_id,reaction_type) VALUES(26,2,'memos/protectedintro','๐Ÿ‘€'); INSERT INTO reaction (id,creator_id,content_id,reaction_type) VALUES(27,3,'memos/protectedintro','โœ…'); diff --git a/web/src/components/MemoActionMenu/memoShareImage.ts b/web/src/components/MemoActionMenu/memoShareImage.ts index ab0516c7..6c8e4b81 100644 --- a/web/src/components/MemoActionMenu/memoShareImage.ts +++ b/web/src/components/MemoActionMenu/memoShareImage.ts @@ -3,6 +3,7 @@ import { toBlob } from "html-to-image"; const WINDOW_HORIZONTAL_MARGIN = 32; const PREVIEW_HORIZONTAL_PADDING_IN_DIALOG = 40; const PREVIEW_WIDTH_BOOST_IN_DIALOG = 48; +const PREVIEW_ASSET_TIMEOUT_MS = 5000; export const MEMO_SHARE_IMAGE_CONFIG = { dialogExtraWidth: 80, @@ -42,13 +43,26 @@ const waitForPreviewAssets = async (node: HTMLElement) => { images.map( (image) => new Promise((resolve) => { + // Share previews may sit inside a scroll container. Promote their images + // so native lazy loading cannot leave the export waiting indefinitely. + image.loading = "eager"; + if (image.complete) { resolve(); return; } - image.addEventListener("load", () => resolve(), { once: true }); - image.addEventListener("error", () => resolve(), { once: true }); + let timeoutId: number; + const finish = () => { + window.clearTimeout(timeoutId); + image.removeEventListener("load", finish); + image.removeEventListener("error", finish); + resolve(); + }; + + image.addEventListener("load", finish, { once: true }); + image.addEventListener("error", finish, { once: true }); + timeoutId = window.setTimeout(finish, PREVIEW_ASSET_TIMEOUT_MS); }), ), ); diff --git a/web/src/components/MemoCommentSection.tsx b/web/src/components/MemoCommentSection.tsx index 4a834d14..3904fbb0 100644 --- a/web/src/components/MemoCommentSection.tsx +++ b/web/src/components/MemoCommentSection.tsx @@ -1,6 +1,7 @@ import { LoaderCircleIcon, MessageCircleIcon } from "lucide-react"; -import { useState } from "react"; -import MemoEditor from "@/components/MemoEditor"; +import { type ComponentType, useCallback, useState } from "react"; +import { loadMemoEditor } from "@/components/MemoEditor/loader"; +import type { MemoEditorProps } from "@/components/MemoEditor/types"; import MemoView from "@/components/MemoView"; import { Button } from "@/components/ui/button"; import useCurrentUser from "@/hooks/useCurrentUser"; @@ -21,6 +22,8 @@ const MemoCommentSection = ({ memo, comments, parentPage, hasMoreComments, isFet const t = useTranslate(); const currentUser = useCurrentUser(); const [showEditor, setShowEditor] = useState(false); + const [isEditorLoading, setIsEditorLoading] = useState(false); + const [EditorComponent, setEditorComponent] = useState>(); const showCreateButton = currentUser && !showEditor; @@ -28,6 +31,27 @@ const MemoCommentSection = ({ memo, comments, parentPage, hasMoreComments, isFet setShowEditor(false); }; + const preloadEditor = useCallback(() => { + void loadMemoEditor().catch(() => undefined); + }, []); + + const openEditor = useCallback(async () => { + if (isEditorLoading) { + return; + } + + setIsEditorLoading(true); + try { + const { default: MemoEditor } = await loadMemoEditor(); + setEditorComponent(() => MemoEditor); + setShowEditor(true); + } catch { + // Chunk failures are handled by loadWithReload; keep the current UI mounted. + } finally { + setIsEditorLoading(false); + } + }, [isEditorLoading]); + return (

@@ -37,9 +61,19 @@ const MemoCommentSection = ({ memo, comments, parentPage, hasMoreComments, isFet {comments.length === 0 ? ( showCreateButton && (
-
) @@ -51,15 +85,23 @@ const MemoCommentSection = ({ memo, comments, parentPage, hasMoreComments, isFet ({comments.length})

{showCreateButton && ( - )} )} - {showEditor && ( + {showEditor && EditorComponent && (
- { - const { userGeneralSetting } = useAuth(); - const [copied, setCopied] = useState(false); - const codeElement = isValidElement(children) ? (children as ReactElement<{ className?: string }>) : null; const codeClassName = codeElement?.props.className || ""; const codeContent = extractCodeContent(children); @@ -34,55 +32,56 @@ export const CodeBlock = ({ children, className, node: _node, ...props }: CodeBl ); } + // Keying on the inputs remounts the block when they change, so highlight state + // can never be shown against a different code content. + return ; +}; + +interface HighlightedCodeBlockProps { + codeContent: string; + language: string; +} + +const HighlightedCodeBlock = ({ codeContent, language }: HighlightedCodeBlockProps) => { + const { userGeneralSetting } = useAuth(); + const [copied, setCopied] = useState(false); + const [highlightedCode, setHighlightedCode] = useState(); + const renderedCode = highlightedCode ?? escapeHTML(codeContent); + const theme = getThemeWithFallback(userGeneralSetting?.theme); const resolvedTheme = resolveTheme(theme); const isDarkTheme = resolvedTheme.includes("dark"); - // Dynamically load highlight.js theme based on app theme useEffect(() => { - const dynamicImportStyle = async () => { - // Remove any existing highlight.js style - const existingStyle = document.querySelector("style[data-hljs-theme]"); - if (existingStyle) { - existingStyle.remove(); - } - - try { - const cssModule = isDarkTheme - ? await import("highlight.js/styles/github-dark-dimmed.css?inline") - : await import("highlight.js/styles/github.css?inline"); - - // Create and inject the style - const style = document.createElement("style"); - style.textContent = cssModule.default; - style.setAttribute("data-hljs-theme", isDarkTheme ? "dark" : "light"); - document.head.appendChild(style); - } catch (error) { - console.warn("Failed to load highlight.js theme:", error); - } - }; - - dynamicImportStyle(); - }, [resolvedTheme, isDarkTheme]); - - // Highlight code using highlight.js - const highlightedCode = useMemo(() => { - try { - const lang = hljs.getLanguage(language); - if (lang) { - return hljs.highlight(codeContent, { - language: language, - }).value; - } - } catch { - // Skip error and use default highlighted code. + if (isPlainTextLanguage(language)) { + return; } - // Escape any HTML entities when rendering original content. - return Object.assign(document.createElement("span"), { - textContent: codeContent, - }).innerHTML; - }, [language, codeContent]); + void ensureHighlightTheme(isDarkTheme); + }, [isDarkTheme, language]); + + useEffect(() => { + if (isPlainTextLanguage(language)) { + // The escaped fallback already is the final output; skip the async round-trip. + return; + } + + let cancelled = false; + + void highlightCode(codeContent, language) + .then((value) => { + if (!cancelled) { + setHighlightedCode(value); + } + }) + .catch(() => { + // Keep the escaped plain-text fallback when a language chunk cannot load. + }); + + return () => { + cancelled = true; + }; + }, [codeContent, language]); const handleCopy = async () => { try { @@ -148,7 +147,7 @@ export const CodeBlock = ({ children, className, node: _node, ...props }: CodeBl
diff --git a/web/src/components/MemoContent/MathMarkdownRenderer.tsx b/web/src/components/MemoContent/MathMarkdownRenderer.tsx new file mode 100644 index 00000000..1afdbd23 --- /dev/null +++ b/web/src/components/MemoContent/MathMarkdownRenderer.tsx @@ -0,0 +1,14 @@ +import "katex/dist/katex.min.css"; +import rehypeKatex from "rehype-katex"; +import remarkMath from "remark-math"; +import { MemoMarkdownRendererCore, type MemoMarkdownRendererProps } from "./MemoMarkdownRenderer"; + +const MathMarkdownRenderer = (props: MemoMarkdownRendererProps) => ( + +); + +export default MathMarkdownRenderer; diff --git a/web/src/components/MemoContent/MemoMarkdownRenderer.tsx b/web/src/components/MemoContent/MemoMarkdownRenderer.tsx index 584998a4..a3e89ca6 100644 --- a/web/src/components/MemoContent/MemoMarkdownRenderer.tsx +++ b/web/src/components/MemoContent/MemoMarkdownRenderer.tsx @@ -1,14 +1,13 @@ import type { Element } from "hast"; -import "katex/dist/katex.min.css"; +import { type ComponentProps, type ReactNode, Suspense } from "react"; import type { Components } from "react-markdown"; import ReactMarkdown from "react-markdown"; -import rehypeKatex from "rehype-katex"; import rehypeRaw from "rehype-raw"; import rehypeSanitize from "rehype-sanitize"; import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; -import remarkMath from "remark-math"; import { isMentionElement, isTagElement, isTaskListItemElement } from "@/types/markdown"; +import { lazyWithReload } from "@/utils/lazy"; import { rehypeHeadingId } from "@/utils/rehype-plugins/rehype-heading-id"; import { remarkDisableSetext } from "@/utils/remark-plugins/remark-disable-setext"; import { remarkMention } from "@/utils/remark-plugins/remark-mention"; @@ -20,12 +19,13 @@ import { SANITIZE_SCHEMA } from "./constants"; import { MarkdownRenderContext, rootMarkdownRenderContext } from "./MarkdownRenderContext"; import { Mention } from "./Mention"; import { AnchorLink, Blockquote, Heading, HorizontalRule, Image, InlineCode, Link, List, ListItem, Paragraph } from "./markdown"; +import { hasMathSyntax } from "./math"; import { Table, TableBody, TableCell, TableHead, TableHeaderCell, TableRow } from "./Table"; import { Tag } from "./Tag"; import { TaskListItem } from "./TaskListItem"; import { TrustedIframe } from "./TrustedIframe"; -interface MemoMarkdownRendererProps { +export interface MemoMarkdownRendererProps { content: string; resolvedMentionUsernames: Set; /** Resource name of the memo (e.g. `memos/abc123`), used to target footnote links at the detail page. */ @@ -34,7 +34,18 @@ interface MemoMarkdownRendererProps { compact?: boolean; } -function getMentionUsername(node: Element, children?: React.ReactNode): string { +type RemarkPlugins = NonNullable["remarkPlugins"]>; +type RehypePlugins = NonNullable["rehypePlugins"]>; + +interface MemoMarkdownRendererCoreProps extends MemoMarkdownRendererProps { + /** Math plugins injected by MathMarkdownRenderer; the remark ones must run before remarkGfm. */ + mathRemarkPlugins?: RemarkPlugins; + mathRehypePlugins?: RehypePlugins; +} + +const MathMarkdownRenderer = lazyWithReload(() => import("./MathMarkdownRenderer")); + +function getMentionUsername(node: Element, children?: ReactNode): string { const dataMention = node.properties?.["data-mention"]; if (typeof dataMention === "string" && dataMention !== "") { return dataMention; @@ -53,7 +64,14 @@ function getMentionUsername(node: Element, children?: React.ReactNode): string { return ""; } -export const MemoMarkdownRenderer = ({ content, resolvedMentionUsernames, memoName, compact }: MemoMarkdownRendererProps) => { +export const MemoMarkdownRendererCore = ({ + content, + resolvedMentionUsernames, + memoName, + compact, + mathRemarkPlugins = [], + mathRehypePlugins = [], +}: MemoMarkdownRendererCoreProps) => { const markdownComponents: Components = { input: ({ node, ...inputProps }) => { if (node && isTaskListItemElement(node)) { @@ -144,7 +162,7 @@ export const MemoMarkdownRenderer = ({ content, resolvedMentionUsernames, memoNa {content} @@ -165,3 +178,15 @@ export const MemoMarkdownRenderer = ({ content, resolvedMentionUsernames, memoNa ); }; + +export const MemoMarkdownRenderer = (props: MemoMarkdownRendererProps) => { + if (!hasMathSyntax(props.content)) { + return ; + } + + return ( + }> + + + ); +}; diff --git a/web/src/components/MemoContent/highlight.ts b/web/src/components/MemoContent/highlight.ts new file mode 100644 index 00000000..af288062 --- /dev/null +++ b/web/src/components/MemoContent/highlight.ts @@ -0,0 +1,137 @@ +import type { HLJSApi, LanguageFn } from "highlight.js"; +import { escape as escapeHTML } from "lodash-es"; + +type LanguageModule = { default: LanguageFn }; +type LanguageLoader = () => Promise; + +// Keep the languages most commonly used in memos cheap. Less common languages +// fall back to the complete build, preserving existing language support without +// making every visitor download all language definitions. +const commonLanguageLoaders = { + bash: () => import("highlight.js/lib/languages/bash"), + c: () => import("highlight.js/lib/languages/c"), + cpp: () => import("highlight.js/lib/languages/cpp"), + csharp: () => import("highlight.js/lib/languages/csharp"), + css: () => import("highlight.js/lib/languages/css"), + diff: () => import("highlight.js/lib/languages/diff"), + dockerfile: () => import("highlight.js/lib/languages/dockerfile"), + go: () => import("highlight.js/lib/languages/go"), + graphql: () => import("highlight.js/lib/languages/graphql"), + java: () => import("highlight.js/lib/languages/java"), + javascript: () => import("highlight.js/lib/languages/javascript"), + json: () => import("highlight.js/lib/languages/json"), + kotlin: () => import("highlight.js/lib/languages/kotlin"), + markdown: () => import("highlight.js/lib/languages/markdown"), + php: () => import("highlight.js/lib/languages/php"), + python: () => import("highlight.js/lib/languages/python"), + ruby: () => import("highlight.js/lib/languages/ruby"), + rust: () => import("highlight.js/lib/languages/rust"), + sql: () => import("highlight.js/lib/languages/sql"), + swift: () => import("highlight.js/lib/languages/swift"), + typescript: () => import("highlight.js/lib/languages/typescript"), + xml: () => import("highlight.js/lib/languages/xml"), + yaml: () => import("highlight.js/lib/languages/yaml"), +} satisfies Record; + +type CommonLanguage = keyof typeof commonLanguageLoaders; + +const languageAliases: Record = { + cs: "csharp", + cxx: "cpp", + golang: "go", + htm: "xml", + html: "xml", + js: "javascript", + jsx: "javascript", + md: "markdown", + py: "python", + rb: "ruby", + sh: "bash", + shell: "bash", + ts: "typescript", + tsx: "typescript", + vue: "xml", + yml: "yaml", + zsh: "bash", +}; + +const plainTextLanguages = new Set(["", "plain", "plaintext", "text", "txt"]); +const registeredLanguagePromises = new Map>(); +let corePromise: Promise | undefined; +let fullBuildPromise: Promise | undefined; +let injectedThemeKey: string | undefined; + +export const isPlainTextLanguage = (language: string): boolean => plainTextLanguages.has(language.trim().toLowerCase()); + +// The hljs theme stylesheet is a document-global singleton, so it is managed here +// (keyed by theme) rather than by each rendered code block. +export const ensureHighlightTheme = async (isDarkTheme: boolean): Promise => { + const themeKey = isDarkTheme ? "dark" : "light"; + if (injectedThemeKey === themeKey) { + return; + } + injectedThemeKey = themeKey; + + try { + const cssModule = isDarkTheme + ? await import("highlight.js/styles/github-dark-dimmed.css?inline") + : await import("highlight.js/styles/github.css?inline"); + if (injectedThemeKey !== themeKey) { + return; + } + + document.querySelector("style[data-hljs-theme]")?.remove(); + const style = document.createElement("style"); + style.textContent = cssModule.default; + style.setAttribute("data-hljs-theme", themeKey); + document.head.appendChild(style); + } catch (error) { + injectedThemeKey = undefined; + console.warn("Failed to load highlight.js theme:", error); + } +}; + +const loadCore = (): Promise => { + corePromise ??= import("highlight.js/lib/core").then((module) => module.default); + return corePromise; +}; + +const loadCommonLanguage = (language: CommonLanguage): Promise => { + const existingPromise = registeredLanguagePromises.get(language); + if (existingPromise) { + return existingPromise; + } + + const languagePromise = Promise.all([loadCore(), commonLanguageLoaders[language]()]).then(([hljs, languageModule]) => { + if (!hljs.getLanguage(language)) { + hljs.registerLanguage(language, languageModule.default); + } + return hljs; + }); + registeredLanguagePromises.set(language, languagePromise); + return languagePromise; +}; + +const loadFullBuild = (): Promise => { + fullBuildPromise ??= import("highlight.js").then((module) => module.default); + return fullBuildPromise; +}; + +export const highlightCode = async (code: string, language: string): Promise => { + const normalizedLanguage = language.trim().toLowerCase(); + if (isPlainTextLanguage(normalizedLanguage)) { + return escapeHTML(code); + } + + const canonicalLanguage = + languageAliases[normalizedLanguage] ?? + (Object.hasOwn(commonLanguageLoaders, normalizedLanguage) ? (normalizedLanguage as CommonLanguage) : undefined); + + const hljs = canonicalLanguage ? await loadCommonLanguage(canonicalLanguage) : await loadFullBuild(); + const languageToHighlight = canonicalLanguage ?? normalizedLanguage; + if (!hljs.getLanguage(languageToHighlight)) { + return escapeHTML(code); + } + + return hljs.highlight(code, { language: languageToHighlight }).value; +}; diff --git a/web/src/components/MemoContent/markdown/Image.tsx b/web/src/components/MemoContent/markdown/Image.tsx index 8ae2ae27..ebcb5864 100644 --- a/web/src/components/MemoContent/markdown/Image.tsx +++ b/web/src/components/MemoContent/markdown/Image.tsx @@ -14,6 +14,8 @@ export const Image = ({ className, alt, node: _node, height, width, style, ...pr alt={alt} style={{ height: height ? `${height}px` : undefined, width: width ? `${width}px` : undefined, ...style }} {...props} + loading="lazy" + decoding="async" /> ); }; diff --git a/web/src/components/MemoContent/math.ts b/web/src/components/MemoContent/math.ts new file mode 100644 index 00000000..0ee0632e --- /dev/null +++ b/web/src/components/MemoContent/math.ts @@ -0,0 +1,11 @@ +const stripCode = (content: string): string => + content + .replace(/```[\s\S]*?```/g, "") + .replace(/~~~[\s\S]*?~~~/g, "") + .replace(/`(?:\\.|[^`\n])*`/g, ""); + +// This is only a loading heuristic; remark-math remains the source of truth for +// parsing. Any unescaped dollar outside code triggers the math chunk: a false +// positive merely loads it, whereas mirroring remark-math's grammar here risks +// false negatives that would silently render real math as raw dollars. +export const hasMathSyntax = (content: string): boolean => /(^|[^\\])\$/.test(stripCode(content)); diff --git a/web/src/components/MemoEditor/loader.ts b/web/src/components/MemoEditor/loader.ts new file mode 100644 index 00000000..e10dfb49 --- /dev/null +++ b/web/src/components/MemoEditor/loader.ts @@ -0,0 +1,15 @@ +import { loadWithReload } from "@/utils/lazy"; + +type MemoEditorModule = typeof import("."); + +let memoEditorModulePromise: Promise | undefined; + +// Share one in-flight request across edit and comment entry points. Callers +// keep their current UI mounted until this promise resolves. +export const loadMemoEditor = (): Promise => { + memoEditorModulePromise ??= loadWithReload(() => import(".")).catch((error) => { + memoEditorModulePromise = undefined; + throw error; + }); + return memoEditorModulePromise; +}; diff --git a/web/src/components/MemoMetadata/Attachment/AttachmentCard.tsx b/web/src/components/MemoMetadata/Attachment/AttachmentCard.tsx index df66880a..1ca1ff65 100644 --- a/web/src/components/MemoMetadata/Attachment/AttachmentCard.tsx +++ b/web/src/components/MemoMetadata/Attachment/AttachmentCard.tsx @@ -32,11 +32,11 @@ const AttachmentCard = ({ attachment, onClick, className }: AttachmentCardProps) } if (attachmentType === "video/*") { - return
) : isVoiceNote ? ( <> @@ -158,8 +149,7 @@ const AttachmentItemCard: FC<{