Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ node_modules/
.dev.vars
.envrc
*.log
.playwright-mcp/
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
32 changes: 31 additions & 1 deletion core/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 <div class="highlight-source-*">.
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;
Expand Down
20 changes: 17 additions & 3 deletions core/previewMarkdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import {
isDecorativePreviewImageSrc,
normalizeCodeLanguage,
normalizePreviewUrl,
type PreviewBlock,
type PreviewSegment,
Expand Down Expand Up @@ -58,6 +59,7 @@ interface InlineMarks {

interface FenceStart {
marker: string;
language?: string;
}

interface StandaloneImage {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion core/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ export function renderIndexPage(data: PageData): string {
<link rel="apple-touch-icon" href="/apple-touch-icon.png?v=8" />
<script>${data.themeInitScript}</script>
<style>${data.inlineCss}</style>
<script src="/static/app.js?v=112" defer></script>
<script src="/static/app.js?v=113" defer></script>
</head>
<body data-app-version="${escapeHtml(data.appVersion)}">
<div class="boot-veil" data-boot-veil aria-hidden="true">
Expand Down
8 changes: 7 additions & 1 deletion core/sources/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <pre> as raw text by default, which leaves the
// nested <code> 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),
Expand Down
26 changes: 26 additions & 0 deletions core/test/preview.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,32 @@ describe("extractArticlePreview", () => {
]);
});

it("keeps a language hint from the page markup", () => {
const preview = extractArticlePreview(
`<html><head><title>Worker snippets | Example</title></head><body>
<main><article>
<p>These snippets show how a Worker reads configuration and starts its local development server.</p>
<pre><code class="language-ts">const edge = await env.DB.prepare("select 1").first();</code></pre>
<pre class="lang-bash"><code>npm run dev</code></pre>
<pre><code class="highlight">plain text</code></pre>
<div class="highlight highlight-source-shell"><pre class="notranslate">npx skills add example</pre></div>
</article></main>
</body></html>`,
"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(
`<html><head>
Expand Down
32 changes: 30 additions & 2 deletions core/test/previewMarkdown.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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 = <main />;
\`\`\`

\`\`\`js
const demo = true;
\`\`\`

\`\`\`
plain
\`\`\`
`;

const blocks = markdownToPreviewBlocks(markdown, {
pageUrl: "https://example.com/posts/fences",
});

expect(blocks).toEqual([
{ type: "code", text: "const edge = <main />;", 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.

Expand Down Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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" },
]);
});

Expand Down
2 changes: 1 addition & 1 deletion core/test/render.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ describe("renderIndexPage", () => {
expect(html).toContain(
"<script>document.documentElement.dataset.theme='dark';</script>",
);
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");
});
Expand Down
1 change: 1 addition & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<head>`+`<main>` 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 `<pre>` children instead of treating the whole element as raw text, so nested `<code>` 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.
Expand Down
4 changes: 2 additions & 2 deletions web-static/service-worker.js
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
62 changes: 55 additions & 7 deletions web-static/static/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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";
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Expand Down
Loading