From 555b4e8f37bbccbac79617476f217c70851cde4d Mon Sep 17 00:00:00 2001 From: Phat Pham Date: Sun, 22 Nov 2026 23:17:47 +0700 Subject: [PATCH 1/2] feat(preview): improve reader code block rendering - Parse
 children so nested  markup and entities no longer leak
  into extracted code text.
- Keep language hints from language-*/lang-* classes, GitHub highlight-source
  wrappers, and Markdown fence info strings.
- Render code blocks with a language label, copy button, and horizontal
  scrolling for long lines.

Co-Authored-By: Claude Code 
---
 README.md                         |  3 +-
 core/preview.ts                   | 32 ++++++++++++++-
 core/previewMarkdown.ts           | 20 +++++++--
 core/render.ts                    |  2 +-
 core/sources/dom.ts               |  8 +++-
 core/test/preview.spec.ts         | 26 ++++++++++++
 core/test/previewMarkdown.spec.ts | 32 ++++++++++++++-
 core/test/render.spec.ts          |  2 +-
 docs/ARCHITECTURE.md              |  1 +
 web-static/service-worker.js      |  4 +-
 web-static/static/app.js          | 62 ++++++++++++++++++++++++----
 web-static/static/style.css       | 68 +++++++++++++++++++++++++++++--
 12 files changed, 237 insertions(+), 23 deletions(-)

diff --git a/README.md b/README.md
index 44074d8..c13c484 100644
--- a/README.md
+++ b/README.md
@@ -79,7 +79,7 @@ npx lighthouse https://reader.boringcode.dev --view
 - **Scheduled refresh** every 1 hour on wall-clock boundaries
 - **Manual refresh** from the header re-fetches the current feed view from backend stored items only; it does **not** re-fetch upstream sources
 - **Persisted visited-link dimming** for feed card titles across reload/reopen using local storage
-- **Optional article preview** (off by default, toggled in Reader settings) that opens a reader view beside the feed on wide screens or full-screen on phones, with inline links/emphasis, image captions, tables, publication date/reading time, a Workers AI Markdown fallback for PDFs, Office documents, and HTML pages with no readable blocks, a Browser Run fallback for JavaScript-rendered pages, source-specific Hacker News comments, and an **Open source** button
+- **Optional article preview** (off by default, toggled in Reader settings) that opens a reader view beside the feed on wide screens or full-screen on phones, with inline links/emphasis, image captions, tables, code blocks with language labels and one-tap copy, publication date/reading time, a Workers AI Markdown fallback for PDFs, Office documents, and HTML pages with no readable blocks, a Browser Run fallback for JavaScript-rendered pages, source-specific Hacker News comments, and an **Open source** button
 - **Saved articles** with an optional per-card bookmark toggle, a `Saved` filter, and a preview-panel toggle; bookmark controls are disabled by default and can be enabled in Reader settings, with saved items stored locally under `feedreader.bookmarks`
 - **PWA-ready assets and offline caching** including manifest, service worker, touch icons, cached shell assets, cached `/api/items` responses for previously visited views, a standalone launch veil, and skeleton loading states
 - **Reconnect list refresh** re-fetches the current view from backend stored items only; it does **not** refresh upstream sources
@@ -383,6 +383,7 @@ Presentation-layer note:
 - `Cmd`/`Ctrl`/`Shift`-clicking a title still opens the article in a new tab
 - the panel shows the extracted title, byline, publication date/reading time, rich text with validated inline links/emphasis/inline code, image blocks with captions and intrinsic dimensions, and semantic tables; images load directly from the source with lazy loading and no referrer; `Open source` opens the original page
 - consecutive list items render as one list and prose uses the full preview width; figures are capped in height so a single image cannot dominate the panel
+- code blocks keep the page's language hint (for example `ts` or `bash`) in a small header with a **Copy** button, and long lines scroll horizontally instead of wrapping
 - previews are source-aware: GitHub README previews drop the `GitHub - ` title prefix and decorative SVG/badge images, while Hugging Face paper previews render the abstract, authors, arXiv/PDF/project/GitHub links, and citing model, dataset, space, and collection lists instead of community comment chrome
 - Hacker News items also show a **Comments** action inside the preview and card `…` dialogs; other sources omit it
 - each card’s `…` dialog includes an **Open source** action that opens the article directly without opening the preview
diff --git a/core/preview.ts b/core/preview.ts
index 1f19314..6e9a2ae 100644
--- a/core/preview.ts
+++ b/core/preview.ts
@@ -76,6 +76,8 @@ export interface PreviewRichTextBlock {
 export interface PreviewCodeBlock {
   type: "code";
   text: string;
+  /** Language hint from the page, already normalized for display. */
+  language?: string;
 }
 
 export interface PreviewImageBlock {
@@ -504,7 +506,12 @@ function extractBlocks(
       const text = normalizeCodeText(element.textContent);
       if (text === "") continue;
       const capped = text.slice(0, MAX_BLOCK_CHARS);
-      blocks.push({ type: "code", text: capped });
+      const language = codeLanguageFor(element);
+      blocks.push({
+        type: "code",
+        text: capped,
+        ...(language === undefined ? {} : { language }),
+      });
       totalChars += capped.length;
       if (totalChars >= MAX_TOTAL_CHARS) break;
       continue;
@@ -1233,6 +1240,29 @@ function normalizeCodeText(value: string | null | undefined): string {
     .trim();
 }
 
+/** Keep only simple tokens that are safe to show as a language label. */
+export function normalizeCodeLanguage(
+  value: string | null | undefined,
+): string | undefined {
+  const token = (value ?? "").trim().toLowerCase().replace(/^\./, "");
+  return /^[a-z0-9+#._-]{1,20}$/.test(token) ? token : undefined;
+}
+
+function codeLanguageFor(pre: HtmlElement): string | undefined {
+  const code = pre.querySelector("code");
+  for (const element of [code, pre, parentElement(pre)]) {
+    const className = element?.getAttribute("class") ?? "";
+    const languageMatch = /(?:^|\s)(?:language|lang)-([^\s]+)/i.exec(className);
+    const language = normalizeCodeLanguage(languageMatch?.[1]);
+    if (language !== undefined) return language;
+    // GitHub wraps README fences in 
. + const highlightMatch = /(?:^|\s)highlight-source-([^\s]+)/i.exec(className); + const highlighted = normalizeCodeLanguage(highlightMatch?.[1]); + if (highlighted !== undefined) return highlighted; + } + return undefined; +} + function cleanByline(value: string): string | undefined { const trimmed = value.trim().slice(0, 120); if (trimmed === "" || /^https?:\/\//i.test(trimmed)) return undefined; diff --git a/core/previewMarkdown.ts b/core/previewMarkdown.ts index eadd943..dac2a12 100644 --- a/core/previewMarkdown.ts +++ b/core/previewMarkdown.ts @@ -5,6 +5,7 @@ import { isDecorativePreviewImageSrc, + normalizeCodeLanguage, normalizePreviewUrl, type PreviewBlock, type PreviewSegment, @@ -58,6 +59,7 @@ interface InlineMarks { interface FenceStart { marker: string; + language?: string; } interface StandaloneImage { @@ -146,7 +148,11 @@ export function markdownToPreviewBlocks( index = code.nextIndex; const text = code.text.slice(0, MAX_BLOCK_CHARS); if (text !== "" && blocks.length < MAX_BLOCKS) { - blocks.push({ type: "code", text }); + blocks.push({ + type: "code", + text, + ...(fence.language === undefined ? {} : { language: fence.language }), + }); totalChars += text.length; } continue; @@ -259,8 +265,16 @@ function readCodeFence( } function parseFenceStart(line: string): FenceStart | null { - const match = /^ {0,3}(`{3,}|~{3,})/.exec(line); - return match ? { marker: match[1]! } : null; + const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line); + if (!match) return null; + const info = (match[2] ?? "") + .trim() + .split(/\s+/)[0] + ?.replace(/^language-/, ""); + const language = normalizeCodeLanguage(info); + return language === undefined + ? { marker: match[1]! } + : { marker: match[1]!, language }; } function isFenceClose(line: string, marker: string): boolean { diff --git a/core/render.ts b/core/render.ts index 297646f..9ff48b8 100644 --- a/core/render.ts +++ b/core/render.ts @@ -195,7 +195,7 @@ export function renderIndexPage(data: PageData): string { - +