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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@

`feedreader` is server-rendered HTML with vanilla JS/CSS — no framework runtime, no client hydration, no bundler payload. That keeps it genuinely tiny and fast, not just "fast for a SPA."

The home page has no render-blocking asset requests: the stylesheet and pre-paint theme bootstrap are inlined into the HTML, and the response is edge-cached per URL for five minutes. Versioned static assets are served with immutable browser caching; see [`web-static/_headers`](web-static/_headers).

Lighthouse against the production deployment (mobile, simulated throttling):

![Lighthouse report](docs/assets/lighthouse-report.png)
Expand Down Expand Up @@ -105,7 +107,7 @@ It optimizes for:
- TypeScript
- Cloudflare Workers
- Web Standard APIs
- `linkedom`
- `node-html-parser`

### Frontend

Expand Down Expand Up @@ -343,7 +345,7 @@ Presentation-layer note:
- selected density is stored in `localStorage` under `feedreader.uiDensity`
- selected theme is stored in `localStorage` under `feedreader.theme`; valid values are `system` (default), `dark`, `light`, `sepia`, `terminal`, `glacier`, and `ember`
- `system` resolves to the device's current light/dark preference and follows changes live; existing `dark`/`light` preferences keep working
- an inline pre-paint theme init script applies the stored preference before the stylesheet loads, avoiding a light/dark flash
- an inline pre-paint theme init script applies the stored preference before first paint, avoiding a light/dark flash (the script is read from `web-static/static/theme-init.js` and inlined with the stylesheet)
- article preview is off by default and stored in `localStorage` under `feedreader.articlePreviewEnabled`
- bookmark controls are off by default and stored in `localStorage` under `feedreader.bookmarksEnabled`; enabling them shows the bookmark controls and Saved filter, and disabling them hides those controls without deleting saved items
- source-specific filters render as **real icon-only buttons**
Expand Down
72 changes: 45 additions & 27 deletions core/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@
// rebinding vector; the stored-item allowlist and platform egress rules are
// the layers that bound it.

import { parseHtmlDocument } from "./sources/dom.ts";
import {
isElement,
parentElement,
parseHtmlDocument,
type HtmlDocument,
type HtmlElement,
type HtmlNode,
} from "./sources/dom.ts";

const DEFAULT_MAX_BYTES = 400_000;
const DEFAULT_TIMEOUT_MS = 10_000;
Expand Down Expand Up @@ -286,7 +293,7 @@ export function extractArticlePreview(
}

function extractBlocks(
root: Element,
root: HtmlElement,
title: string,
pageUrl: string,
): PreviewBlock[] {
Expand Down Expand Up @@ -404,7 +411,7 @@ interface InlineMarks {
}

function extractInlineSegments(
element: Element,
element: HtmlElement,
pageUrl: string,
): PreviewSegment[] {
const raw: PreviewSegment[] = [];
Expand All @@ -413,7 +420,7 @@ function extractInlineSegments(
}

function collectInlineSegments(
node: Node,
node: HtmlNode,
pageUrl: string,
marks: InlineMarks,
out: PreviewSegment[],
Expand All @@ -423,9 +430,9 @@ function collectInlineSegments(
if (text !== "") out.push({ text, ...marks });
return;
}
if (node.nodeType !== 1) return;
if (!isElement(node)) return;

const element = node as Element;
const element = node;
const tagName = element.tagName;
if (
tagName === "SCRIPT" ||
Expand Down Expand Up @@ -469,7 +476,10 @@ function collectInlineSegments(
* `normalizePreviewUrl` rejects javascript:, data:, credentials, non-standard
* ports, and private/link-local hosts, so callers never see unsafe schemes.
*/
function resolveInlineHref(raw: string | null, pageUrl: string): string {
function resolveInlineHref(
raw: string | null | undefined,
pageUrl: string,
): string {
const trimmed = (raw ?? "").trim();
if (trimmed === "") return "";
try {
Expand Down Expand Up @@ -557,7 +567,7 @@ function capSegments(
}

function extractImageBlock(
image: Element,
image: HtmlElement,
pageUrl: string,
): PreviewImageBlock | null {
const width = parseImageDimension(image.getAttribute("width"));
Expand Down Expand Up @@ -610,8 +620,8 @@ function extractImageBlock(
return block;
}

function extractTableBlock(table: Element): PreviewTableBlock | null {
if (table.parentElement?.closest("table")) return null;
function extractTableBlock(table: HtmlElement): PreviewTableBlock | null {
if (parentElement(table)?.closest("table")) return null;

const rows: string[][] = [];
let header = false;
Expand All @@ -637,7 +647,10 @@ function extractTableBlock(table: Element): PreviewTableBlock | null {
return rows.length > 0 ? { type: "table", header, rows } : null;
}

function resolveImageUrl(raw: string | null, pageUrl: string): string {
function resolveImageUrl(
raw: string | null | undefined,
pageUrl: string,
): string {
const trimmed = (raw ?? "").trim();
if (trimmed === "" || trimmed.startsWith("data:")) return "";
try {
Expand Down Expand Up @@ -698,7 +711,10 @@ function isDecorativeImageSrc(rawUrl: string): boolean {
);
}

function resolveSrcsetUrl(srcset: string | null, pageUrl: string): string {
function resolveSrcsetUrl(
srcset: string | null | undefined,
pageUrl: string,
): string {
const raw = (srcset ?? "").trim();
if (raw === "") return "";
let best = "";
Expand All @@ -717,8 +733,10 @@ function resolveSrcsetUrl(srcset: string | null, pageUrl: string): string {
return best;
}

function parseImageDimension(raw: string | null): number | undefined {
if (raw === null) return undefined;
function parseImageDimension(
raw: string | null | undefined,
): number | undefined {
if (raw === null || raw === undefined) return undefined;
const trimmed = raw.trim();
if (!/^\d+$/.test(trimmed)) return undefined;
const parsed = Number.parseInt(trimmed, 10);
Expand Down Expand Up @@ -768,7 +786,7 @@ function isHuggingFacePaperPage(pageUrl: string): boolean {
* one document. Start at the "Abstract" section so the reader view keeps the
* paper itself instead of the surrounding discussion chrome.
*/
function extractHuggingFacePaperByline(document: Document): string {
function extractHuggingFacePaperByline(document: HtmlDocument): string {
const nodes = Array.from(document.querySelectorAll(".author, h2"));
const abstractIndex = nodes.findIndex(
(element) =>
Expand All @@ -789,11 +807,11 @@ function extractHuggingFacePaperByline(document: Document): string {
}

function extractHuggingFacePaperLinks(
document: Document,
document: HtmlDocument,
pageUrl: string,
): PreviewSegment[] {
const heading = findHuggingFaceAbstractHeading(document);
const container = heading?.parentElement?.nextElementSibling;
const container = parentElement(heading)?.nextElementSibling;
const anchors = container
? Array.from(container.querySelectorAll("a[href]"))
: [];
Expand All @@ -816,7 +834,7 @@ function extractHuggingFacePaperLinks(
}

function extractHuggingFacePaperCitations(
document: Document,
document: HtmlDocument,
pageUrl: string,
): PreviewBlock[] {
const blocks: PreviewBlock[] = [];
Expand Down Expand Up @@ -853,7 +871,7 @@ function extractHuggingFacePaperCitations(
return blocks;
}

function findHuggingFaceAbstractHeading(document: Document): Element | null {
function findHuggingFaceAbstractHeading(document: HtmlDocument): HtmlElement | null {
return (
Array.from(document.querySelectorAll("h2")).find(
(element) =>
Expand All @@ -862,18 +880,18 @@ function findHuggingFaceAbstractHeading(document: Document): Element | null {
);
}

function pickHuggingFacePaperRoot(document: Document): Element | null {
function pickHuggingFacePaperRoot(document: HtmlDocument): HtmlElement | null {
const heading = findHuggingFaceAbstractHeading(document);
const parent = heading?.parentElement ?? null;
const parent = parentElement(heading);
if (!parent || parent === document.body || parent.tagName === "MAIN") {
return null;
}
return parent;
}

function pickContentRoot(document: Document): Element | null {
function pickContentRoot(document: HtmlDocument): HtmlElement | null {
const articles = Array.from(document.querySelectorAll("article"));
let bestArticle: Element | null = null;
let bestArticle: HtmlElement | null = null;
let bestArticleScore = 0;
for (const article of articles) {
const score = contentScore(article);
Expand All @@ -886,7 +904,7 @@ function pickContentRoot(document: Document): Element | null {
return bestArticle;
}

const candidates: Element[] = [...articles];
const candidates: HtmlElement[] = [...articles];
const main = document.querySelector("main, [role=main]");
if (main) candidates.push(main);
if (document.body) candidates.push(document.body);
Expand All @@ -904,7 +922,7 @@ function pickContentRoot(document: Document): Element | null {
return best;
}

function contentScore(element: Element): number {
function contentScore(element: HtmlElement): number {
let score = 0;
element.querySelectorAll("p, li, blockquote").forEach((node) => {
const length = normalizeText(node.textContent).length;
Expand All @@ -931,7 +949,7 @@ function blockTypeFor(tagName: string): PreviewTextBlockType {
}
}

function extractPublishedAt(document: Document): string | undefined {
function extractPublishedAt(document: HtmlDocument): string | undefined {
const candidates = [
metaContent(document, [
'meta[property="article:published_time"]',
Expand Down Expand Up @@ -992,7 +1010,7 @@ function isUsefulBlock(type: PreviewTextBlockType, text: string): boolean {
}
}

function metaContent(document: Document, selectors: string[]): string {
function metaContent(document: HtmlDocument, selectors: string[]): string {
for (const selector of selectors) {
const content = document.querySelector(selector)?.getAttribute("content");
const normalized = normalizeText(content);
Expand Down
14 changes: 9 additions & 5 deletions core/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ export interface PageData {
canonicalUrl: string;
socialImageUrl: string;
appVersion: string;
/** Injected by the platform layer so first paint doesn't wait on an
* external stylesheet request. Kept as parameters so core/render.ts stays
* independent of the asset pipeline. */
inlineCss: string;
themeInitScript: string;
}

export function escapeHtml(value: unknown): string {
Expand Down Expand Up @@ -187,17 +192,16 @@ export function renderIndexPage(data: PageData): string {
<meta name="apple-mobile-web-app-title" content="reader" />
<link rel="manifest" href="/site.webmanifest?v=17" />
<link rel="icon" href="/favicon.svg?v=8" sizes="any" type="image/svg+xml" />
<link rel="shortcut icon" href="/favicon.svg?v=8" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png?v=8" />
<script src="/static/theme-init.js?v=1"></script>
<link rel="stylesheet" href="/static/style.css?v=128" />
<script src="/static/app.js?v=105" defer></script>
<script>${data.themeInitScript}</script>
<style>${data.inlineCss}</style>
<script src="/static/app.js?v=106" defer></script>
</head>
<body data-app-version="${escapeHtml(data.appVersion)}">
<header class="shell page-header">
<div class="toast" data-toast role="status" aria-live="polite"></div>
<div class="header-top">
<h1 class="brand"><img class="brand-mark" src="/favicon.svg?v=7" alt="" aria-hidden="true" /><span>reader</span></h1>
<h1 class="brand"><img class="brand-mark" src="/favicon.svg?v=8" alt="" aria-hidden="true" /><span>reader</span></h1>
<div class="header-actions">
<span class="connection-indicator is-hidden" data-connection-indicator role="img" aria-label="Internet disconnected" title="Internet disconnected">
<svg class="theme-icon" viewBox="0 0 24 24" aria-hidden="true">
Expand Down
50 changes: 28 additions & 22 deletions core/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,25 +104,25 @@ export async function dashboard(
limit: number,
): Promise<SourceSnapshot[]> {
const states = await repo.listSourceStates();
const snapshots: SourceSnapshot[] = [];
for (const source of sources) {
const state = states[source.key()] ?? {
source: source.key(),
itemCount: 0,
};
const items = await repo.getCurrentItems(source.key(), limit);
snapshots.push({
source: source.key(),
label: source.label(),
homepageUrl: source.homepageUrl(),
lastAttemptAt: state.lastAttemptAt,
lastSuccessAt: state.lastSuccessAt,
lastError: state.lastError,
itemCount: state.itemCount,
items,
});
}
return snapshots;
return Promise.all(
sources.map(async (source) => {
const state = states[source.key()] ?? {
source: source.key(),
itemCount: 0,
};
const items = await repo.getCurrentItems(source.key(), limit);
return {
source: source.key(),
label: source.label(),
homepageUrl: source.homepageUrl(),
lastAttemptAt: state.lastAttemptAt,
lastSuccessAt: state.lastSuccessAt,
lastError: state.lastError,
itemCount: state.itemCount,
items,
};
}),
);
}

export async function feedItems(
Expand Down Expand Up @@ -153,8 +153,10 @@ export async function healthPayload(
sources: Source[],
repo: FeedRepository,
): Promise<Record<string, unknown>> {
const snapshots = await dashboard(sources, repo, 1);
const total = await repo.countTotalItems();
const [snapshots, total] = await Promise.all([
dashboard(sources, repo, 1),
repo.countTotalItems(),
]);
return {
status: "ok",
total_items: total,
Expand Down Expand Up @@ -194,7 +196,11 @@ export function buildCards(items: FeedItem[], offset: number): CardView[] {
});
}

export function buildErrors(snapshots: SourceSnapshot[]): ErrorView[] {
export function buildErrors(
snapshots: ReadonlyArray<
Pick<SourceSnapshot, "source" | "label" | "lastError">
>,
): ErrorView[] {
return snapshots
.filter((snapshot) => (snapshot.lastError ?? "").trim() !== "")
.map((snapshot) => ({
Expand Down
Loading
Loading