.
+ 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 {
diff --git a/core/sources/dom.ts b/core/sources/dom.ts
index b2dcde4..3d4bb28 100644
--- a/core/sources/dom.ts
+++ b/core/sources/dom.ts
@@ -26,7 +26,13 @@ export function isElement(node: HtmlNode): node is HtmlElement {
}
export function parseHtmlDocument(html: string): HtmlDocument {
- const root = parse(html, { comment: false });
+ const root = parse(html, {
+ comment: false,
+ // node-html-parser treats
as raw text by default, which leaves the
+ // nested markup inside pre.textContent. Parse its children so code
+ // text arrives clean and the language class is readable.
+ blockTextElements: { script: true, noscript: true, style: true },
+ });
return {
body: root.querySelector("body"),
querySelector: (selector) => root.querySelector(selector),
diff --git a/core/test/preview.spec.ts b/core/test/preview.spec.ts
index 658b51c..a5c6d41 100644
--- a/core/test/preview.spec.ts
+++ b/core/test/preview.spec.ts
@@ -126,6 +126,32 @@ describe("extractArticlePreview", () => {
]);
});
+ it("keeps a language hint from the page markup", () => {
+ const preview = extractArticlePreview(
+ `Worker snippets | Example
+
+ These snippets show how a Worker reads configuration and starts its local development server.
+ const edge = await env.DB.prepare("select 1").first();
+ npm run dev
+ plain text
+
+
+ `,
+ "https://example.com/snippets",
+ );
+
+ expect(preview.blocks.filter((block) => block.type === "code")).toEqual([
+ {
+ type: "code",
+ text: 'const edge = await env.DB.prepare("select 1").first();',
+ language: "ts",
+ },
+ { type: "code", text: "npm run dev", language: "bash" },
+ { type: "code", text: "plain text" },
+ { type: "code", text: "npx skills add example", language: "shell" },
+ ]);
+ });
+
it("falls back to the meta description when no readable body exists", () => {
const preview = extractArticlePreview(
`
diff --git a/core/test/previewMarkdown.spec.ts b/core/test/previewMarkdown.spec.ts
index 1161410..086586c 100644
--- a/core/test/previewMarkdown.spec.ts
+++ b/core/test/previewMarkdown.spec.ts
@@ -86,6 +86,7 @@ const cached = await cache.match(request);
expect(blocks.find((block) => block.type === "code")).toEqual({
type: "code",
text: "const cached = await cache.match(request);",
+ language: "js",
});
expect(blocks.find((block) => block.type === "image")).toEqual({
type: "image",
@@ -102,6 +103,31 @@ const cached = await cache.match(request);
});
});
+ it("keeps a simple fence language and ignores fence options", () => {
+ const markdown = `\`\`\`tsx title="app.tsx"
+const edge = ;
+\`\`\`
+
+\`\`\`js
+const demo = true;
+\`\`\`
+
+\`\`\`
+plain
+\`\`\`
+`;
+
+ const blocks = markdownToPreviewBlocks(markdown, {
+ pageUrl: "https://example.com/posts/fences",
+ });
+
+ expect(blocks).toEqual([
+ { type: "code", text: "const edge = ;", language: "tsx" },
+ { type: "code", text: "const demo = true;", language: "js" },
+ { type: "code", text: "plain" },
+ ]);
+ });
+
it("drops unsafe links and images while keeping readable text", () => {
const markdown = `This paragraph has a [dangerous link](javascript:alert(1)) and a [private link](http://127.0.0.1/admin) plus a [safe link](https://example.com/ok) for context.
@@ -195,7 +221,9 @@ const cached = await cache.match(request);
markdownToPreviewBlocks(ordinary, {
pageUrl: "https://example.com/posts/json-code",
}),
- ).toEqual([{ type: "code", text: '{"enabled":true}' }]);
+ ).toEqual([
+ { type: "code", text: '{"enabled":true}', language: "json" },
+ ]);
});
it("skips a heading that repeats the stored title", () => {
@@ -228,7 +256,7 @@ A long enough paragraph that should remain in the preview.`;
pageUrl: "https://example.com/posts/code",
}),
).toEqual([
- { type: "code", text: "# Not a heading\n**not bold**" },
+ { type: "code", text: "# Not a heading\n**not bold**", language: "md" },
]);
});
diff --git a/core/test/render.spec.ts b/core/test/render.spec.ts
index 6b3e408..33d619d 100644
--- a/core/test/render.spec.ts
+++ b/core/test/render.spec.ts
@@ -36,7 +36,7 @@ describe("renderIndexPage", () => {
expect(html).toContain(
"",
);
- expect(html).toContain('/static/app.js?v=112');
+ expect(html).toContain('/static/app.js?v=113');
expect(html).not.toContain("style.css");
expect(html).not.toContain("theme-init.js");
});
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index f2c3c7f..afee08f 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -104,6 +104,7 @@ The optional article preview is served by `GET /api/preview?url=…`.
- If the built-in extractor finds no blocks (`no_content`), truncation left no blocks (`too_large`), or the upstream is a non-HTML document (`unsupported_content_type`), `fetchArticlePreview` may call an injected fallback. Core stays platform-free: the Worker supplies a chain (`platforms/cloudflare/src/previewFallbackChain.ts`). Workers AI (`previewFallback.ts`) calls `env.AI.toMarkdown`; Browser Run (`browserPreviewFallback.ts`) calls `env.BROWSER.quickAction("markdown", …)` only for `no_content` after AI fails. Both map the converted Markdown through `core/previewMarkdown.ts`, which re-checks every link and image with `normalizePreviewUrl`, strips YAML frontmatter and trailing JSON-LD, and drops PDF filename/page-marker headings. Browser Run waits for `networkidle2` with 8-second navigation/action and 9-second outer timeouts, rejects images/media/fonts and literal private-host requests, and validates the rendered page status and `meta.finalUrl`. Blocked, timeout, rate-limited, and empty-body failures never reach the fallback. `FEEDREADER_AI_PREVIEW_FALLBACK=false` and `FEEDREADER_BROWSER_PREVIEW_FALLBACK=false` disable each adapter.
- Hugging Face paper pages are focused to ``+`` before DOM parsing, and noise removal uses one combined selector instead of one traversal per tag. This preserves title/byline/date metadata and the paper/citation blocks while cutting parse work by roughly 20% locally on the pages that have hit the Workers Free CPU limit.
- Image blocks may include a `figcaption`-derived caption and intrinsic width/height to reserve layout space. Known avatar/profile-image hosts and paths, SVG wordmarks, and common badge hosts are dropped before the image cap so author-list and README chrome doesn't displace article figures. Table blocks carry a header flag and capped rows/cells. The response also includes byline, publication date, and an estimated reading time. For Hugging Face paper URLs the extractor starts at the Abstract section, then appends the paper's resource links and citing model, dataset, space, and collection lists while excluding community comment chrome; GitHub titles drop the site prefix. The preview and card `…` dialogs expose a stored Hacker News comments URL for HN items; other sources omit it.
+- Code blocks carry an optional normalized language hint from `language-*`/`lang-*` classes or the Markdown fence info string. The parser reads `` children instead of treating the whole element as raw text, so nested `` markup and entities do not leak into block text. The client renders code blocks with a language label, a **Copy** button, and horizontal scrolling for long lines.
- The client highlights the card matching the open preview and provides previous/next navigation over the currently rendered card list, skipping duplicate or unusable cards. When the last rendered card is previewed, Next remains enabled if another page exists and appends it before advancing. On mobile the open panel pins the body scroll position (and reapplies it after rotation), the glass header/footer auto-hide on scroll down and return on scroll up, and the `theme-color` tint switches to the panel surface while the panel covers the viewport. A left-edge rightward drag follows the finger and reveals the preserved feed position underneath; releasing past a distance/velocity threshold slides the panel away and closes it, while a shorter drag springs back. Vertical edge drags remain native scrolling and the gesture is inactive while the `…` dialog is open.
- Card host rows keep the optional bookmark toggle and a more-actions dialog trigger. The dialog exposes Share, the stored Hacker News comments URL when present, and Open source; choosing an action does not open the preview.
- Successful previews are edge-cached for 30 minutes (empty results for 5 minutes) via the Cache API; cache-miss requests are limited to 20 per minute per IP. The browser-facing response is `private, no-store`, so the CDN cannot extend the client TTL.
diff --git a/web-static/service-worker.js b/web-static/service-worker.js
index 2118edd..6e3b1f0 100644
--- a/web-static/service-worker.js
+++ b/web-static/service-worker.js
@@ -1,8 +1,8 @@
-const SHELL_CACHE = "reader-shell-v146";
+const SHELL_CACHE = "reader-shell-v147";
const ITEMS_CACHE = "reader-items-v24";
const CORE_ASSETS = [
"/",
- "/static/app.js?v=112",
+ "/static/app.js?v=113",
"/static/source-icons/hackernews.svg",
"/static/source-icons/github.svg",
"/static/source-icons/huggingface.svg",
diff --git a/web-static/static/app.js b/web-static/static/app.js
index a018351..7666ce0 100644
--- a/web-static/static/app.js
+++ b/web-static/static/app.js
@@ -1307,10 +1307,10 @@
}, 2200);
};
- async function copyArticleLink(url) {
+ async function copyText(text) {
try {
if (navigator.clipboard?.writeText) {
- await navigator.clipboard.writeText(url);
+ await navigator.clipboard.writeText(text);
return true;
}
} catch {
@@ -1319,7 +1319,7 @@
let textarea = null;
try {
textarea = document.createElement("textarea");
- textarea.value = url;
+ textarea.value = text;
textarea.setAttribute("readonly", "");
textarea.style.position = "fixed";
textarea.style.opacity = "0";
@@ -1347,7 +1347,7 @@
if (error?.name === "AbortError") return;
}
}
- const copied = await copyArticleLink(target);
+ const copied = await copyText(target);
if (copied) {
showToast("Link copied");
} else {
@@ -1650,6 +1650,50 @@
if (list.childNodes.length > 0) previewContent.appendChild(list);
};
+ const renderPreviewCodeBlock = (block) => {
+ const wrapper = document.createElement("div");
+ wrapper.className = "preview-panel-code";
+
+ const header = document.createElement("div");
+ header.className = "preview-panel-code-header";
+
+ const language =
+ typeof block.language === "string" ? block.language.trim() : "";
+ if (language !== "") {
+ const label = document.createElement("span");
+ label.className = "preview-panel-code-language";
+ label.textContent = language;
+ header.appendChild(label);
+ }
+
+ const copyButton = document.createElement("button");
+ copyButton.className = "preview-panel-code-copy";
+ copyButton.type = "button";
+ copyButton.textContent = "Copy";
+ copyButton.setAttribute("aria-label", "Copy code");
+ copyButton.setAttribute("aria-live", "polite");
+ let resetTimer = 0;
+ copyButton.addEventListener("click", async () => {
+ const copied = await copyText(block.text);
+ copyButton.textContent = copied ? "Copied" : "Copy failed";
+ copyButton.classList.toggle("is-copied", copied);
+ window.clearTimeout(resetTimer);
+ resetTimer = window.setTimeout(() => {
+ copyButton.textContent = "Copy";
+ copyButton.classList.remove("is-copied");
+ }, 1600);
+ });
+ header.appendChild(copyButton);
+
+ const pre = document.createElement("pre");
+ const code = document.createElement("code");
+ code.textContent = block.text;
+ pre.appendChild(code);
+
+ wrapper.append(header, pre);
+ previewContent.appendChild(wrapper);
+ };
+
const renderPreviewBlocks = (blocks) => {
if (!previewContent) return;
previewContent.replaceChildren();
@@ -1720,14 +1764,18 @@
continue;
}
+ if (block.type === "code") {
+ if (typeof block.text !== "string" || block.text === "") continue;
+ renderPreviewCodeBlock(block);
+ continue;
+ }
+
const tagName =
block.type === "heading"
? "h3"
: block.type === "quote"
? "blockquote"
- : block.type === "code"
- ? "pre"
- : "p";
+ : "p";
const element = document.createElement(tagName);
if (Array.isArray(block.segments)) {
renderPreviewSegments(element, block.segments);
diff --git a/web-static/static/style.css b/web-static/static/style.css
index ebceb90..4c6ca15 100644
--- a/web-static/static/style.css
+++ b/web-static/static/style.css
@@ -1815,15 +1815,75 @@ body.is-dialog-open {
font-style: italic;
}
-.preview-panel-content pre {
- padding: 0.6rem 0.65rem;
+.preview-panel-code {
border: 1px solid var(--border);
border-radius: 0.55rem;
background: var(--surface-raised);
+ overflow: hidden;
+}
+
+.preview-panel-code-header {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ min-height: 1.85rem;
+ padding: 0.15rem 0.3rem 0.15rem 0.65rem;
+ border-bottom: 1px solid var(--border);
+ background: color-mix(in srgb, var(--surface-raised) 65%, var(--surface));
+}
+
+.preview-panel-code-language {
+ margin-right: auto;
+ overflow: hidden;
+ color: var(--muted);
+ font-family: var(--font-mono);
+ font-size: 0.68rem;
+ letter-spacing: 0.04em;
+ text-overflow: ellipsis;
+ text-transform: uppercase;
+ white-space: nowrap;
+}
+
+.preview-panel-code-copy {
+ flex: 0 0 auto;
+ margin-left: auto;
+ padding: 0.12rem 0.45rem;
+ border: 1px solid transparent;
+ border-radius: 0.35rem;
+ background: transparent;
+ color: var(--muted);
+ font-family: var(--font-mono);
+ font-size: 0.68rem;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ cursor: pointer;
+ transition: 140ms ease;
+}
+
+.preview-panel-code-copy:hover,
+.preview-panel-code-copy:focus-visible {
+ border-color: var(--border);
+ color: var(--text);
+}
+
+.preview-panel-code-copy:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+
+.preview-panel-code-copy.is-copied {
+ color: var(--accent);
+}
+
+.preview-panel-code pre {
+ margin: 0;
+ padding: 0.6rem 0.65rem;
+ overflow-x: auto;
+ overscroll-behavior-x: contain;
font-size: 0.78rem;
line-height: 1.45;
- white-space: pre-wrap;
- overflow-wrap: anywhere;
+ tab-size: 2;
+ white-space: pre;
}
.preview-panel-content a {