From 4915d193d93ac2457c004d7f3f546f425a0c8cd2 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 07:37:07 +0700 Subject: [PATCH 1/7] feat(qr): draw a QR code in the repo, checked by an independent decoder --- .../js/components/download/action-pair.tsx | 100 ------ .../js/components/download/ios-panel.tsx | 37 --- .../js/components/download/linux-install.tsx | 226 ------------- .../js/components/download/linux-panel.tsx | 36 --- .../js/components/download/mac-panel.tsx | 115 ------- .../js/components/download/panel-facts.tsx | 29 -- .../components/download/platform-switch.tsx | 87 ----- resources/js/lib/qr.ts | 299 ++++++++++++++++++ tests/js/qr.test.ts | 212 +++++++++++++ 9 files changed, 511 insertions(+), 630 deletions(-) delete mode 100644 resources/js/components/download/action-pair.tsx delete mode 100644 resources/js/components/download/ios-panel.tsx delete mode 100644 resources/js/components/download/linux-install.tsx delete mode 100644 resources/js/components/download/linux-panel.tsx delete mode 100644 resources/js/components/download/mac-panel.tsx delete mode 100644 resources/js/components/download/panel-facts.tsx delete mode 100644 resources/js/components/download/platform-switch.tsx create mode 100644 resources/js/lib/qr.ts create mode 100644 tests/js/qr.test.ts diff --git a/resources/js/components/download/action-pair.tsx b/resources/js/components/download/action-pair.tsx deleted file mode 100644 index 34f4b43c..00000000 --- a/resources/js/components/download/action-pair.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import type { ReactNode } from 'react'; -import AppStoreBadge from '@/components/download/app-store-badge'; -import { buttonClasses } from '@/components/ui/button'; -import CellGrid from '@/components/ui/cell-grid'; -import { AppleGlyph } from '@/components/ui/glyph'; -import LocaleLink from '@/components/ui/locale-link'; -import { useI18n } from '@/i18n'; -import { trackDownload } from '@/lib/analytics'; -import { cn } from '@/lib/utils'; - -interface ActionPairProps { - /** The `download_click` location of both actions. */ - location: string; - /** The Mac action's availability line: its requirement, the architectures. */ - macCaption: ReactNode; - /** Under the Mac caption: the hero's "Other ways to install" link. */ - macExtra?: ReactNode; - /** The App Store listing and its availability line, or null where the iPhone and iPad app does not apply. */ - ios: { url: string; caption: ReactNode } | null; - // The way to /download#linux and its availability line, where the Linux app applies. - linux?: { caption: ReactNode } | null; - /** - * Each action in a cell of the page grid, side by side from 640px - * (design-system §4.7). Only in a wide section, where the cells can reach - * the rails. - */ - cells?: boolean; - className?: string; -} - -/** - * The two ways to get TablePro, each with its availability line under it - * (design-system §5.1 `DownloadBand`, §5.3.18 `PlatformActions`). Every - * download band on the site is this one row: the hero and the homepage's - * closing section, the feature and database pages. Three hand-built copies - * had drifted apart in button size, glyph and caption spacing. - * - * "Download for Mac" is the large primary button with the Apple glyph and - * goes to /download, which offers the DMG; it never starts a download. - * The App Store badge (40px, Apple's minimum) sits centred in a 48px row, the - * button's height, so the two captions start on one line. Side by side from - * 640px, stacked below, each caption under its own action. - * - * The badge is Apple's artwork in the page's language, and its accessible name - * is that artwork's visible text (see app-store-badge.tsx). - * - * The markup is Mac first on every device. On an iPhone or iPad the badge is - * drawn first (positioning §3.2), from the `ios` class the root template sets - * before first paint, so nothing moves after the page is shown. - */ -export default function ActionPair({ location, macCaption, macExtra, ios, linux = null, cells = false, className }: ActionPairProps) { - const { m } = useI18n(); - - const mac = ( -
- trackDownload(location, 'mac')} className={buttonClasses('primary', 'lg')}> - - {m.download.macCta} - -

{macCaption}

- {macExtra} -
- ); - - const iosAction = ios !== null && ( -
-
- -
-

{ios.caption}

-
- ); - - const linuxAction = linux !== null && ( -
- trackDownload(location, 'linux')} className={buttonClasses('secondary', 'lg')}> - {m.download.linuxCta} - -

{linux.caption}

-
- ); - - if (cells) { - return ( - - {mac} - {linuxAction} - {iosAction} - - ); - } - - return ( -
- {mac} - {linuxAction} - {iosAction} -
- ); -} diff --git a/resources/js/components/download/ios-panel.tsx b/resources/js/components/download/ios-panel.tsx deleted file mode 100644 index 579d29e0..00000000 --- a/resources/js/components/download/ios-panel.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import LocaleLink from '@/components/ui/locale-link'; -import { textLinkClasses } from '@/components/ui/text-link'; -import { useI18n } from '@/i18n'; -import { joinList, keepTogether } from '@/i18n/format'; -import AppStoreBadge from './app-store-badge'; -import { requirementLine } from './format'; -import PanelFacts from './panel-facts'; -import type { DownloadContent, IosProp } from './types'; - -interface IosPanelProps { - content: DownloadContent; - ios: IosProp; -} - -// The App Store URL has no country segment, so Apple sends each reader to their own storefront. -export default function IosPanel({ content, ios }: IosPanelProps) { - const { m, fmt } = useI18n(); - const version = - ios.version !== null - ? ios.publishedAtFormatted !== null - ? fmt(m.download.release.dated, { version: ios.version, date: keepTogether(ios.publishedAtFormatted) }) - : fmt(m.download.release.undated, { version: ios.version }) - : null; - - return ( - } - lines={[[version, ios.free && !ios.inAppPurchases && m.platforms.free], [requirementLine(ios.requirements, m.platforms)]]} - updates={m.download.panel.updates.ios} - > - - {fmt(content.ios.link, { devices: joinList(ios.deviceNames, m.common.shortList) })} - - - - ); -} diff --git a/resources/js/components/download/linux-install.tsx b/resources/js/components/download/linux-install.tsx deleted file mode 100644 index c7825234..00000000 --- a/resources/js/components/download/linux-install.tsx +++ /dev/null @@ -1,226 +0,0 @@ -import { useEffect, useState, type ReactNode } from 'react'; -import { InlineCode } from '@/components/ui/code'; -import DataTable, { TABLE_CELL, TABLE_HEAD_CELL, TABLE_ROW, TABLE_ROW_HEADER } from '@/components/ui/data-table'; -import Disclosure from '@/components/ui/disclosure'; -import SegmentedControl from '@/components/ui/segmented-control'; -import TextLink, { textLinkClasses } from '@/components/ui/text-link'; -import { Trans, useI18n } from '@/i18n'; -import { joinList } from '@/i18n/format'; -import { trackDownload } from '@/lib/analytics'; -import CommandBlock from './command-block'; -import { megabytes } from './format'; -import { methodLabel } from './linux-text'; -import { CENTRED_DISCLOSURE } from './panel-facts'; -import type { LinuxFile, LinuxMethod, LinuxMethodKind, LinuxProp } from './types'; - -type Tab = LinuxMethodKind | 'files'; - -const LINUX_TAB_STORAGE_KEY = 'tablepro:linux-install'; - -function storedTab(tabs: Tab[]): Tab | null { - try { - const value = window.localStorage.getItem(LINUX_TAB_STORAGE_KEY); - - return tabs.find((tab) => tab === value) ?? null; - } catch { - return null; - } -} - -function storeTab(tab: Tab): void { - try { - window.localStorage.setItem(LINUX_TAB_STORAGE_KEY, tab); - } catch { - // Storage can be off or full; the choice then lasts for this page only. - } -} - -// The server renders the first method; the reader's last choice replaces it after mount. Every panel is in the -// markup, the unchosen ones hidden, so each command is in the page whichever tab shows. -export default function LinuxInstall({ linux }: { linux: LinuxProp }) { - const { m, fmt } = useI18n(); - const strings = m.download.linux; - const tabs: Tab[] = [...linux.methods.map((method) => method.kind), ...(linux.packages.length > 0 ? (['files'] as const) : [])]; - const [tab, setTab] = useState(tabs[0] ?? 'files'); - - useEffect(() => { - const stored = storedTab(tabs); - - if (stored !== null) { - setTab(stored); - } - }, []); - - const label = (each: Tab): string => (each === 'files' ? strings.files : methodLabel(each, linux, strings)); - - return ( -
- - legend={strings.methods} - name="linux-install" - className="flex justify-center max-sm:[&_label]:px-2.5" - value={tab} - options={tabs.map((each) => ({ value: each, label: label(each) }))} - onChange={(next) => { - setTab(next); - storeTab(next); - }} - /> - -
- {linux.methods.map((method) => ( - - ))} - {tabs.includes('files') && ( - - )} -
-
- ); -} - -function MethodPanel({ method, linux, title }: { method: LinuxMethod; linux: LinuxProp; title: string }) { - const { m, fmt } = useI18n(); - const strings = m.download.linux; - const architectures = joinList(linux.architectures, m.download.orList); - const distribution = linux.distributions.find((each) => each.via === method.kind && each.name !== null); - const requirement = - distribution !== undefined && distribution.name !== null - ? fmt(strings.requirement, { name: distribution.name, versions: joinList(distribution.versions, m.download.orList), architectures }) - : fmt(strings.flatpakRequirement, { architectures, version: linux.desktop?.version ?? '' }); - - return ( -
- trackDownload(`download-page-${method.kind}`, 'linux')} - /> -

{requirement}

- {method.update !== null && ( -

- {text} }} /> -

- )} -
- ); -} - -function FilesPanel({ linux }: { linux: LinuxProp }) { - const { m, fmt } = useI18n(); - const strings = m.download.linux; - const { release, checksums } = linux; - const example = linux.packages.flatMap((row) => Object.values(row.files)).find((file): file is LinuxFile => file !== null); - - const file = (each: LinuxFile | null): ReactNode => { - if (each === null) { - return ( - - ); - } - - const architecture = each.name.slice(each.name.lastIndexOf('-') + 1, each.name.lastIndexOf('.')); - - return ( - - trackDownload('download-page-files', 'linux')} - className={textLinkClasses('inline', 'justify-self-start font-mono text-[0.8125rem] whitespace-nowrap')} - > - {architecture} - - {each.bytes !== null && {fmt(m.download.file.size, { size: megabytes(each.bytes, m.download.file.number) })}} - - ); - }; - - return ( -
-
- - - - - {strings.table.package} - - {linux.architectures.map((architecture) => ( - - {architecture} - - ))} - - - - {linux.packages.map((row) => ( - - - {row.distribution !== null && row.series !== null ? `${row.distribution} ${row.series}` : strings.table.bundle} - .{row.format} - - {linux.architectures.map((architecture) => ( - - {file(row.files[architecture] ?? null)} - - ))} - - ))} - - -
- - {checksums !== null && ( -

- - checksums.url !== null ? ( - - {text} - - ) : ( - {text} - ), - }} - /> -

- )} - - {release !== null && ( -

- - {fmt(strings.release, { version: release.version })} - -

- )} - - {linux.verify !== null && example !== undefined && checksums !== null && ( - -

{fmt(strings.verify.body, { file: checksums.name })}

- - -
- )} -
- ); -} diff --git a/resources/js/components/download/linux-panel.tsx b/resources/js/components/download/linux-panel.tsx deleted file mode 100644 index 424c93d9..00000000 --- a/resources/js/components/download/linux-panel.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import TextLink from '@/components/ui/text-link'; -import { Trans, useI18n } from '@/i18n'; -import { keepTogether } from '@/i18n/format'; -import LinuxInstall from './linux-install'; -import type { LinuxProp } from './types'; - -interface LinuxPanelProps { - linux: LinuxProp; - issues: string | null; -} - -// Installing takes a choice of method, so the panel leads with the methods instead of one file. -export default function LinuxPanel({ linux, issues }: LinuxPanelProps) { - const { m, fmt } = useI18n(); - const { release } = linux; - const version = - release !== null - ? release.publishedOn !== null - ? fmt(m.download.release.dated, { version: release.version, date: keepTogether(release.publishedOn) }) - : fmt(m.download.release.undated, { version: release.version }) - : null; - - return ( -
-
- {version !== null &&

{version}

} - {linux.channel === 'beta' && ( -

- (issues !== null ? {text} : text) }} /> -

- )} -
- -
- ); -} diff --git a/resources/js/components/download/mac-panel.tsx b/resources/js/components/download/mac-panel.tsx deleted file mode 100644 index eceb69e4..00000000 --- a/resources/js/components/download/mac-panel.tsx +++ /dev/null @@ -1,115 +0,0 @@ -import { useState } from 'react'; -import { Download } from 'lucide-react'; -import Button from '@/components/ui/button'; -import Callout from '@/components/ui/callout'; -import { CodeBlock, InlineCode } from '@/components/ui/code'; -import Disclosure from '@/components/ui/disclosure'; -import { textLinkClasses } from '@/components/ui/text-link'; -import { Trans, useI18n } from '@/i18n'; -import { keepTogether } from '@/i18n/format'; -import { trackDownload } from '@/lib/analytics'; -import { architecturesText } from '@/lib/data/platforms'; -import { megabytes, requirementLine } from './format'; -import PanelFacts, { CENTRED_DISCLOSURE } from './panel-facts'; -import type { DownloadContent, MacProp, ReleaseProp } from './types'; - -const UI_TAGS = { ui: (text: string) => {text} }; - -interface MacPanelProps { - content: DownloadContent; - release: ReleaseProp; - mac: MacProp; -} - -// The DMG link is in the server render with its real URL, and nothing claims a download started: the install hint -// appears only after the reader clicked, and offers the same file again in case nothing arrived. -export default function MacPanel({ content, release, mac }: MacPanelProps) { - const { m, fmt } = useI18n(); - const [clicked, setClicked] = useState(false); - - const available = release.source !== 'unavailable'; - const { asset } = release; - const version = - available && release.version !== null - ? release.publishedAtFormatted !== null - ? fmt(m.download.release.dated, { version: release.version, date: keepTogether(release.publishedAtFormatted) }) - : fmt(m.download.release.undated, { version: release.version }) - : null; - - return ( -
- - - {(mac.homebrewCommand !== null || asset.sha256 !== null) && ( -
- {mac.homebrewCommand !== null && ( -
-

{content.mac.homebrew.title}

- - {mac.homebrewTrails && ( -

- -

- )} -
- )} - - {asset.name !== null && asset.sha256 !== null && ( - -

{content.mac.signing}

-

- {text} }} /> -

-

- {asset.name} - {asset.sha256} -

-
- )} -
- )} -
- ); -} diff --git a/resources/js/components/download/panel-facts.tsx b/resources/js/components/download/panel-facts.tsx deleted file mode 100644 index 9b0f7a31..00000000 --- a/resources/js/components/download/panel-facts.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import type { ReactNode } from 'react'; -import DotList from '@/components/ui/dot-list'; - -// A disclosure under the centred facts: its summary centred, what it opens left-aligned at full width. -export const CENTRED_DISCLOSURE = 'text-center [&>div]:pl-0 [&>div]:text-left'; - -interface PanelFactsProps { - action: ReactNode; - // Each line is one DotList: version and size, then requirement and architecture. - lines: ReactNode[][]; - updates: string; - children?: ReactNode; -} - -// The centred top of a platform panel: the one action, its facts in two short lines, and how it updates. -export default function PanelFacts({ action, lines, updates, children }: PanelFactsProps) { - return ( -
- {action} -
- {lines.map((items, index) => ( - - ))} -
-

{updates}

- {children} -
- ); -} diff --git a/resources/js/components/download/platform-switch.tsx b/resources/js/components/download/platform-switch.tsx deleted file mode 100644 index f55a9113..00000000 --- a/resources/js/components/download/platform-switch.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; -import SegmentedControl from '@/components/ui/segmented-control'; -import { classifyDevice } from '@/lib/device'; -import { cn } from '@/lib/utils'; -import type { PlatformKey } from './types'; - -export interface PlatformTab { - key: PlatformKey; - // The accessible heading of the panel, and the segment's text. - name: string; - label: ReactNode; - icon: ReactNode; - panel: ReactNode; -} - -interface PlatformSwitchProps { - legend: string; - tabs: PlatformTab[]; -} - -function fromHash(keys: PlatformKey[]): PlatformKey | null { - return keys.find((key) => window.location.hash === `#${key}`) ?? null; -} - -// One panel at a time. The server renders the first platform; before paint, a root `ios` or `linux` class from the head -// script shows that platform instead (app.css), and the layout effect then takes over without a visible swap. A link to -// `#mac`, `#ios` or `#linux` opens that panel, and a choice is kept in the URL so a reload or a shared link keeps it. -// The browser scrolls to a linked panel after the layout effect, so a panel's scroll margin clears the switch above it -// and both land the switch under the header. -export default function PlatformSwitch({ legend, tabs }: PlatformSwitchProps) { - const root = useRef(null); - const keys = tabs.map((tab) => tab.key); - const [chosen, setChosen] = useState(null); - - useLayoutEffect(() => { - const linked = fromHash(keys); - const device = classifyDevice(navigator.userAgent, navigator.maxTouchPoints ?? 0); - - setChosen(linked ?? keys.find((key) => key === device) ?? keys[0]); - - if (linked !== null) { - root.current?.scrollIntoView({ block: 'start' }); - } - }, []); - - useEffect(() => { - const follow = (): void => { - const linked = fromHash(keys); - - if (linked !== null) { - setChosen(linked); - root.current?.scrollIntoView({ block: 'start' }); - } - }; - - window.addEventListener('hashchange', follow); - - return () => window.removeEventListener('hashchange', follow); - }, []); - - const shown = chosen ?? keys[0]; - - return ( -
- - legend={legend} - name="platform" - size="lg" - value={shown} - options={tabs.map((tab) => ({ value: tab.key, label: tab.label, icon: tab.icon }))} - onChange={(next) => { - setChosen(next); - window.history.replaceState(window.history.state, '', `#${next}`); - }} - /> - - {tabs.map((tab) => ( -
-

- {tab.name} -

- {tab.panel} -
- ))} -
- ); -} diff --git a/resources/js/lib/qr.ts b/resources/js/lib/qr.ts new file mode 100644 index 00000000..c7b919c6 --- /dev/null +++ b/resources/js/lib/qr.ts @@ -0,0 +1,299 @@ +// A QR code in byte mode at error correction level M, versions 1 to 6 (up to 106 bytes): enough for a store link, drawn +// on the server with no third-party host. Pure, with no imports, so `node --test` loads it (tests/js/qr.test.ts). + +// Per version: error correction codewords per block, blocks, data codewords per block. Level M has equal blocks up to 6. +const LEVEL_M: ReadonlyArray = [ + [10, 1, 16], + [16, 1, 28], + [26, 1, 44], + [18, 2, 32], + [24, 2, 43], + [16, 4, 27], +]; + +const ALIGNMENT: ReadonlyArray = [[], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34]]; + +const EXP = new Uint8Array(512); +const LOG = new Uint8Array(256); + +for (let i = 0, x = 1; i < 255; i++) { + EXP[i] = x; + LOG[x] = i; + x <<= 1; + + if (x & 0x100) { + x ^= 0x11d; + } +} + +for (let i = 255; i < 512; i++) { + EXP[i] = EXP[i - 255]; +} + +function multiply(a: number, b: number): number { + return a === 0 || b === 0 ? 0 : EXP[LOG[a] + LOG[b]]; +} + +function errorCorrection(data: number[], degree: number): number[] { + let generator = [1]; + + for (let i = 0; i < degree; i++) { + const next = new Array(generator.length + 1).fill(0); + + generator.forEach((coefficient, j) => { + next[j] ^= coefficient; + next[j + 1] ^= multiply(coefficient, EXP[i]); + }); + generator = next; + } + + const remainder = new Array(degree).fill(0); + + for (const byte of data) { + const factor = byte ^ (remainder.shift() ?? 0); + remainder.push(0); + + for (let j = 0; j < degree; j++) { + remainder[j] ^= multiply(generator[j + 1], factor); + } + } + + return remainder; +} + +function codewords(text: string): { version: number; words: number[] } { + const bytes = [...new TextEncoder().encode(text)]; + const index = LEVEL_M.findIndex(([, blocks, data]) => blocks * data * 8 >= 12 + bytes.length * 8); + + if (index === -1) { + throw new RangeError(`A QR code here holds at most 106 bytes; got ${bytes.length}.`); + } + + const [degree, blocks, perBlock] = LEVEL_M[index]; + const capacity = blocks * perBlock * 8; + const bits: number[] = []; + const push = (value: number, length: number): void => { + for (let i = length - 1; i >= 0; i--) { + bits.push((value >>> i) & 1); + } + }; + + push(0b0100, 4); + push(bytes.length, 8); + bytes.forEach((byte) => push(byte, 8)); + push(0, Math.min(4, capacity - bits.length)); + push(0, (8 - (bits.length % 8)) % 8); + + const data: number[] = []; + + for (let i = 0; i < bits.length; i += 8) { + data.push(bits.slice(i, i + 8).reduce((byte, bit) => (byte << 1) | bit, 0)); + } + + for (let pad = 0xec; data.length < blocks * perBlock; pad ^= 0xec ^ 0x11) { + data.push(pad); + } + + const split = Array.from({ length: blocks }, (_, block) => data.slice(block * perBlock, (block + 1) * perBlock)); + const corrections = split.map((block) => errorCorrection(block, degree)); + const words: number[] = []; + + for (let i = 0; i < perBlock; i++) { + split.forEach((block) => words.push(block[i])); + } + + for (let i = 0; i < degree; i++) { + corrections.forEach((block) => words.push(block[i])); + } + + return { version: index + 1, words }; +} + +const MASKS: ReadonlyArray<(x: number, y: number) => boolean> = [ + (x, y) => (x + y) % 2 === 0, + (_, y) => y % 2 === 0, + (x) => x % 3 === 0, + (x, y) => (x + y) % 3 === 0, + (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0, + (x, y) => ((x * y) % 2) + ((x * y) % 3) === 0, + (x, y) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0, + (x, y) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0, +]; + +function penalty(modules: boolean[][]): number { + const size = modules.length; + let score = 0; + let dark = 0; + + for (const lines of [modules, modules.map((_, x) => modules.map((row) => row[x]))]) { + for (const line of lines) { + let run = 1; + + for (let i = 1; i <= size; i++) { + if (i < size && line[i] === line[i - 1]) { + run++; + continue; + } + + score += run >= 5 ? run - 2 : 0; + run = 1; + } + + const text = line.map((module) => (module ? '1' : '0')).join(''); + + for (const pattern of ['10111010000', '00001011101']) { + for (let at = text.indexOf(pattern); at !== -1; at = text.indexOf(pattern, at + 1)) { + score += 40; + } + } + } + } + + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + dark += modules[y][x] ? 1 : 0; + + if (x < size - 1 && y < size - 1) { + const color = modules[y][x]; + + score += color === modules[y][x + 1] && color === modules[y + 1][x] && color === modules[y + 1][x + 1] ? 3 : 0; + } + } + } + + return score + Math.floor(Math.abs((dark * 100) / (size * size) - 50) / 5) * 10; +} + +// The two cells of format bit i, the least significant first: beside the top-left finder, then split between the +// other two. +function formatCells(size: number): Array<[[number, number], [number, number]]> { + return Array.from({ length: 15 }, (_, i): [[number, number], [number, number]] => [ + i <= 5 ? [8, i] : i === 6 ? [8, 7] : i === 7 ? [8, 8] : i === 8 ? [7, 8] : [14 - i, 8], + i < 8 ? [size - 1 - i, 8] : [8, size - 15 + i], + ]); +} + +// Level M's two format bits are 00, so the mask number is the whole five-bit value. +function formatBits(mask: number): number { + let remainder = mask; + + for (let i = 0; i < 10; i++) { + remainder = (remainder << 1) ^ ((remainder >>> 9) * 0x537); + } + + return ((mask << 10) | remainder) ^ 0x5412; +} + +// Rows of modules, true for dark, without the quiet zone. +export function qrMatrix(text: string): boolean[][] { + const { version, words } = codewords(text); + const size = 17 + version * 4; + const modules = Array.from({ length: size }, () => new Array(size).fill(false)); + const reserved = Array.from({ length: size }, () => new Array(size).fill(false)); + const set = (x: number, y: number, dark: boolean): void => { + modules[y][x] = dark; + reserved[y][x] = true; + }; + + for (let i = 0; i < size; i++) { + set(6, i, i % 2 === 0); + set(i, 6, i % 2 === 0); + } + + for (const [cx, cy] of [ + [3, 3], + [size - 4, 3], + [3, size - 4], + ]) { + for (let dy = -4; dy <= 4; dy++) { + for (let dx = -4; dx <= 4; dx++) { + const x = cx + dx; + const y = cy + dy; + const distance = Math.max(Math.abs(dx), Math.abs(dy)); + + if (x >= 0 && x < size && y >= 0 && y < size) { + set(x, y, distance !== 2 && distance !== 4); + } + } + } + } + + const centres = ALIGNMENT[version - 1]; + const last = centres.length - 1; + + centres.forEach((cy, row) => + centres.forEach((cx, column) => { + if ((row === 0 && (column === 0 || column === last)) || (row === last && column === 0)) { + return; + } + + for (let dy = -2; dy <= 2; dy++) { + for (let dx = -2; dx <= 2; dx++) { + set(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1); + } + } + }), + ); + + const cells = formatCells(size); + + cells.flat().forEach(([x, y]) => set(x, y, false)); + set(8, size - 8, true); + + let bit = 0; + + for (let right = size - 1; right >= 1; right -= 2) { + if (right === 6) { + right = 5; + } + + for (let vertical = 0; vertical < size; vertical++) { + for (let j = 0; j < 2; j++) { + const x = right - j; + const y = ((right + 1) & 2) === 0 ? size - 1 - vertical : vertical; + + if (!reserved[y][x] && bit < words.length * 8) { + modules[y][x] = ((words[bit >>> 3] >>> (7 - (bit & 7))) & 1) === 1; + bit++; + } + } + } + } + + const masked = MASKS.map((mask, number) => { + const grid = modules.map((row, y) => row.map((dark, x) => (reserved[y][x] ? dark : dark !== mask(x, y)))); + const bits = formatBits(number); + + cells.forEach((pair, i) => pair.forEach(([x, y]) => (grid[y][x] = ((bits >>> i) & 1) === 1))); + + return grid; + }); + const scores = masked.map(penalty); + + return masked[scores.indexOf(Math.min(...scores))]; +} + +// One SVG path of the dark modules, a run of them per subpath, offset by the quiet zone. +export function qrPath(matrix: boolean[][], margin: number): string { + const parts: string[] = []; + + matrix.forEach((row, y) => { + for (let x = 0; x < row.length; x++) { + if (!row[x]) { + continue; + } + + const start = x; + + while (x + 1 < row.length && row[x + 1]) { + x++; + } + + const run = x - start + 1; + + parts.push(`M${start + margin} ${y + margin}h${run}v1h-${run}z`); + } + }); + + return parts.join(''); +} diff --git a/tests/js/qr.test.ts b/tests/js/qr.test.ts new file mode 100644 index 00000000..4d834fad --- /dev/null +++ b/tests/js/qr.test.ts @@ -0,0 +1,212 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import platforms from '../../resources/data/platforms.json' with { type: 'json' }; +import { qrMatrix, qrPath } from '../../resources/js/lib/qr.ts'; + +// A reader written from the QR specification, not from the encoder: it finds the format, removes the mask, reads the +// codewords in placement order, checks every block's Reed-Solomon syndromes and parses the byte segment. + +const LEVEL_M_BLOCKS: Record = { + 1: { ec: 10, blocks: 1, data: 16 }, + 2: { ec: 16, blocks: 1, data: 28 }, + 3: { ec: 26, blocks: 1, data: 44 }, + 4: { ec: 18, blocks: 2, data: 32 }, + 5: { ec: 24, blocks: 2, data: 43 }, + 6: { ec: 16, blocks: 4, data: 27 }, +}; + +const ALIGNMENT_CENTRES: Record = { 1: [], 2: [6, 18], 3: [6, 22], 4: [6, 26], 5: [6, 30], 6: [6, 34] }; + +function gf(): { exp: number[]; log: number[] } { + const exp: number[] = []; + const log: number[] = []; + + for (let i = 0, value = 1; i < 255; i++) { + exp[i] = value; + log[value] = i; + value = value & 0x80 ? ((value << 1) ^ 0x11d) & 0xff : value << 1; + } + + return { exp, log }; +} + +function syndromesAreZero(block: number[], ec: number): boolean { + const { exp, log } = gf(); + const times = (a: number, b: number): number => (a === 0 || b === 0 ? 0 : exp[(log[a] + log[b]) % 255]); + + for (let i = 0; i < ec; i++) { + let sum = 0; + + for (const word of block) { + sum = times(sum, exp[i]) ^ word; + } + + if (sum !== 0) { + return false; + } + } + + return true; +} + +function functionModules(size: number, version: number): boolean[][] { + const taken = Array.from({ length: size }, () => new Array(size).fill(false)); + const square = (left: number, top: number, side: number): void => { + for (let y = top; y < top + side; y++) { + for (let x = left; x < left + side; x++) { + taken[y][x] = true; + } + } + }; + + // Each finder with its separator. + square(0, 0, 8); + square(size - 8, 0, 8); + square(0, size - 8, 8); + + for (const cy of ALIGNMENT_CENTRES[version]) { + for (const cx of ALIGNMENT_CENTRES[version]) { + if (!taken[cy][cx]) { + square(cx - 2, cy - 2, 5); + } + } + } + + for (let i = 0; i < size; i++) { + taken[6][i] = true; + taken[i][6] = true; + } + + // The format areas, and the dark module above the bottom-left one. + for (let i = 0; i < 9; i++) { + taken[8][i] = true; + taken[i][8] = true; + } + + for (let i = 0; i < 8; i++) { + taken[8][size - 1 - i] = true; + taken[size - 1 - i][8] = true; + } + + return taken; +} + +function decode(matrix: boolean[][]): string { + const size = matrix.length; + const version = (size - 17) / 4; + const layout = LEVEL_M_BLOCKS[version]; + + assert.ok(layout !== undefined, `a ${size}-module code is not a level M version 1 to 6`); + + // Format bits 14 down to 9 run along row 8 left to right, then 8 to 0 up column 8, skipping the timing row. + const order: Array<[number, number]> = [ + [0, 8], + [1, 8], + [2, 8], + [3, 8], + [4, 8], + [5, 8], + [7, 8], + [8, 8], + [8, 7], + [8, 5], + [8, 4], + [8, 3], + [8, 2], + [8, 1], + [8, 0], + ]; + const read = order.reduce((bits, [x, y]) => (bits << 1) | (matrix[y][x] ? 1 : 0), 0); + // The specification's table of level M format strings, masks 0 to 7, after the 101010000010010 XOR. + const mask = [0b101010000010010, 0b101000100100101, 0b101111001111100, 0b101101101001011, 0b100010111111001, 0b100000011001110, 0b100111110010111, 0b100101010100000].indexOf(read); + + assert.ok(mask !== -1, 'the format bits name level M and a mask'); + + const flip: Record boolean> = { + 0: (i, j) => (i + j) % 2 === 0, + 1: (i) => i % 2 === 0, + 2: (_, j) => j % 3 === 0, + 3: (i, j) => (i + j) % 3 === 0, + 4: (i, j) => (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0, + 5: (i, j) => ((i * j) % 2) + ((i * j) % 3) === 0, + 6: (i, j) => (((i * j) % 2) + ((i * j) % 3)) % 2 === 0, + 7: (i, j) => (((i * j) % 3) + ((i + j) % 2)) % 2 === 0, + }; + const taken = functionModules(size, version); + const bits: number[] = []; + let upward = true; + + for (let column = size - 1; column > 0; column -= 2) { + if (column === 6) { + column--; + } + + for (let step = 0; step < size; step++) { + const row = upward ? size - 1 - step : step; + + for (const x of [column, column - 1]) { + if (!taken[row][x]) { + bits.push(matrix[row][x] !== flip[mask](row, x) ? 1 : 0); + } + } + } + + upward = !upward; + } + + const total = layout.blocks * (layout.data + layout.ec); + const words = Array.from({ length: total }, (_, i) => bits.slice(i * 8, i * 8 + 8).reduce((byte, bit) => (byte << 1) | bit, 0)); + const blocks = Array.from({ length: layout.blocks }, () => [] as number[]); + + words.forEach((word, i) => { + const block = i < layout.blocks * layout.data ? i % layout.blocks : (i - layout.blocks * layout.data) % layout.blocks; + blocks[block].push(word); + }); + + blocks.forEach((block, i) => assert.ok(syndromesAreZero(block, layout.ec), `block ${i} has no Reed-Solomon errors`)); + + const data = blocks.flatMap((block) => block.slice(0, layout.data)); + const stream = data.flatMap((word) => Array.from({ length: 8 }, (_, i) => (word >>> (7 - i)) & 1)); + const take = (count: number): number => stream.splice(0, count).reduce((value, bit) => (value << 1) | bit, 0); + + assert.equal(take(4), 0b0100, 'one byte-mode segment'); + + const length = take(8); + + return new TextDecoder().decode(Uint8Array.from({ length }, () => take(8))); +} + +function fromPath(path: string, margin: number): boolean[][] { + const runs = [...path.matchAll(/M(\d+) (\d+)h(\d+)v1h-\3z/g)].map((match) => match.slice(1).map(Number)); + const size = Math.max(...runs.map(([x, , run]) => x + run)) - margin; + const matrix = Array.from({ length: size }, () => new Array(size).fill(false)); + + assert.equal(runs.map((match) => `M${match[0]} ${match[1]}h${match[2]}v1h-${match[2]}z`).join(''), path, 'the path is only module runs'); + + for (const [x, y, run] of runs) { + for (let i = 0; i < run; i++) { + matrix[y - margin][x - margin + i] = true; + } + } + + return matrix; +} + +const appStoreUrl = platforms.platforms.find((platform) => platform.id === 'ios')?.destinations?.find((destination) => destination.kind === 'app-store')?.url; + +test('the App Store QR code on /download encodes the App Store URL from platforms.json', () => { + assert.ok(typeof appStoreUrl === 'string' && appStoreUrl.startsWith('https://apps.apple.com/')); + + const matrix = fromPath(qrPath(qrMatrix(appStoreUrl), 4), 4); + + assert.equal(decode(matrix), appStoreUrl); +}); + +test('a QR code round-trips text of every version it supports', () => { + for (const text of ['A', 'https://tablepro.app', 'x'.repeat(40), 'é'.repeat(30), 'y'.repeat(84), 'z'.repeat(106)]) { + assert.equal(decode(qrMatrix(text)), text); + } + + assert.throws(() => qrMatrix('x'.repeat(107)), RangeError); +}); From 42939cee4977aa60d35fdecdd6614bc926c4890f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 07:37:08 +0700 Subject: [PATCH 2/7] fix(features): let a band's text column shrink, so a wide code block cannot widen the page --- resources/js/components/features/feature-band.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/js/components/features/feature-band.tsx b/resources/js/components/features/feature-band.tsx index d3458ee0..57409709 100644 --- a/resources/js/components/features/feature-band.tsx +++ b/resources/js/components/features/feature-band.tsx @@ -40,7 +40,7 @@ export function BandFrame({ id, also, title, marker, asset, assetClassName, besi {marker} -
{children}
+
{children}
{beside !== undefined &&
{beside}
} {after !== undefined &&
{after}
} From 42067b7a0b2b3a56b04a9ff60ba1c066a173bd3b Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 07:37:08 +0700 Subject: [PATCH 3/7] feat(device): mark a machine TablePro has no app for with other-device before first paint --- resources/js/lib/device.ts | 2 +- resources/views/app.blade.php | 15 ++++++++++----- tests/js/device.test.ts | 11 +++++------ 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/resources/js/lib/device.ts b/resources/js/lib/device.ts index 0bfbafd7..48a305df 100644 --- a/resources/js/lib/device.ts +++ b/resources/js/lib/device.ts @@ -1,5 +1,5 @@ // What the download page may infer about the reader's device (architecture §1.13). It never acts on it: every download -// is a server-rendered link and nothing starts on its own. The result only decides which card is marked and leads. +// is a server-rendered link and nothing starts on its own. The result only decides which action leads. // Pure, with no imports, so `node --test` loads it directly (tests/js/device.test.ts). export type DeviceKind = 'mac' | 'ios' | 'linux' | 'other'; diff --git a/resources/views/app.blade.php b/resources/views/app.blade.php index fe3eccbc..352bdf32 100644 --- a/resources/views/app.blade.php +++ b/resources/views/app.blade.php @@ -33,17 +33,22 @@ {{-- Theme before anything paints: the system's unless the reader chose otherwise. --}} @include('partials.head-theme') - {{-- An iPhone or iPad, or a Linux desktop, by `classifyDevice` in - resources/js/lib/device.ts (tests/js/device.test.ts runs this against - it), before first paint: the App Store badge leads on iOS, the download - page opens on the reader's platform, and nothing swaps under a finger. --}} + {{-- The reader's machine by `classifyDevice` in resources/js/lib/device.ts + (tests/js/device.test.ts runs this against it), before first paint: + `ios`, `linux`, `other-device` for one TablePro has no app for, and no + class on a Mac. The App Store badge leads on iOS, the download page + shows that machine's action, and nothing swaps under a finger. --}} diff --git a/tests/js/device.test.ts b/tests/js/device.test.ts index 52343df3..b7aa1f11 100644 --- a/tests/js/device.test.ts +++ b/tests/js/device.test.ts @@ -57,8 +57,8 @@ test('the App Store card leads only on an iPhone or iPad', () => { assert.equal(appStoreFirst('linux'), false); }); -// The head script cannot import this module, so it repeats the rule. -test('the head script marks exactly the devices classifyDevice calls ios or linux', () => { +// The head script cannot import this module, so it repeats the rule: one class per machine but a Mac. +test('the head script marks each device as classifyDevice names it, and a Mac with nothing', () => { const blade = readFileSync(new URL('../../resources/views/app.blade.php', import.meta.url), 'utf8'); const start = blade.indexOf('var ua = navigator.userAgent;'); const end = blade.indexOf('})();', start); @@ -67,16 +67,15 @@ test('the head script marks exactly the devices classifyDevice calls ios or linu assert.ok(start < blade.indexOf("document.documentElement.classList.remove('has-banner')"), 'the device is known before the banner rule reads it'); const run = new Function('navigator', 'document', blade.slice(start, end)); + const classes = { mac: [], ios: ['ios'], linux: ['linux'], other: ['other-device'] }; - for (const [name, userAgent] of Object.entries(UA)) { + for (const [name, userAgent] of Object.entries({ ...UA, unknown: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' })) { for (const maxTouchPoints of [0, 1, 5]) { const added: string[] = []; run({ userAgent, maxTouchPoints }, { documentElement: { classList: { add: (cls: string) => added.push(cls) } } }); - const kind = classifyDevice(userAgent, maxTouchPoints); - - assert.deepEqual(added, kind === 'ios' || kind === 'linux' ? [kind] : [], `${name}, ${maxTouchPoints} touch points`); + assert.deepEqual(added, classes[classifyDevice(userAgent, maxTouchPoints)], `${name}, ${maxTouchPoints} touch points`); } } }); From 21addd8137ec32b52762c95f1be7bd9b4a532e27 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 8 Nov 2026 07:37:13 +0700 Subject: [PATCH 4/7] feat(download): rebuild /download as the reader's release and action, then a band per platform --- app/Http/Controllers/DownloadController.php | 78 ++-- resources/css/app.css | 48 +-- resources/data/content/en/download.json | 42 ++- .../js/components/download/command-block.tsx | 17 +- .../js/components/download/download-hero.tsx | 168 +++++++++ resources/js/components/download/format.ts | 19 +- .../js/components/download/linux-text.ts | 9 +- .../js/components/download/mac-download.tsx | 77 ++++ resources/js/components/download/qr-code.tsx | 21 ++ resources/js/components/download/types.ts | 35 +- .../js/components/features/feature-hero.tsx | 2 +- resources/js/components/ui/code.tsx | 6 +- resources/js/components/ui/copy-button.tsx | 2 +- resources/js/pages/Download.tsx | 272 ++++++++------ tests/Feature/Data/PlatformsDataTest.php | 6 +- tests/Feature/Pages/DownloadTest.php | 339 +++++++++++------- tests/Feature/Pages/FaqTest.php | 15 +- tests/js/download-linux.test.ts | 10 +- 18 files changed, 765 insertions(+), 401 deletions(-) create mode 100644 resources/js/components/download/download-hero.tsx create mode 100644 resources/js/components/download/mac-download.tsx create mode 100644 resources/js/components/download/qr-code.tsx diff --git a/app/Http/Controllers/DownloadController.php b/app/Http/Controllers/DownloadController.php index f08e589a..839270b3 100644 --- a/app/Http/Controllers/DownloadController.php +++ b/app/Http/Controllers/DownloadController.php @@ -10,7 +10,6 @@ use App\Support\Content\ContentRepository; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\File; use Inertia\Inertia; use Inertia\Response; @@ -18,8 +17,7 @@ // once platforms.json says it is released, the same way an unreleased iPhone app sends null. class DownloadController extends Controller { - // Which install method a package format belongs to, so a file row can name its distribution. - private const PACKAGE_METHOD = ['deb' => 'ppa', 'rpm' => 'copr', 'flatpak' => 'flatpak']; + private const LINUX_METHODS = ['ppa', 'copr', 'flatpak']; public function __invoke( ContentRepository $content, @@ -30,19 +28,17 @@ public function __invoke( ): Response { $locale = App::getLocale(); $release = $releases->latest(); - $floor = $platforms->macFloorVersion(); - $linux = $platforms->isReleased('linux') ? $this->linux($platforms, $linuxReleases->latest(), $locale) : null; return Inertia::render('Download', [ 'content' => $content->page('download', $locale), - 'release' => $release->toProps($locale), + 'release' => [...$release->toProps($locale), 'shortVersion' => $this->shortVersion($release->version)], 'mac' => [ ...($platforms->summary('mac') ?? ['deviceNames' => [], 'requirements' => null]), + 'universal' => ($platforms->find('mac')['universalBinary'] ?? false) === true, 'homebrewCommand' => $this->string($platforms->destination('mac', 'homebrew')['command'] ?? null), - 'homebrewTrails' => $floor !== null && $release->version !== null && version_compare($floor, $release->version, '<'), ], 'ios' => $this->ios($platforms, $facts, $locale), - 'linux' => $linux, + 'linux' => $platforms->isReleased('linux') ? $this->linux($platforms, $linuxReleases->latest(), $locale) : null, 'unreleased' => $platforms->unreleased(), 'links' => $this->links($facts), 'featuredEngines' => $facts->featuredEngineNames(), @@ -50,7 +46,7 @@ public function __invoke( } /** - * @return array{deviceNames: list, requirements: array{systems: list, minVersion: string, displayVersion: string, releaseName: string|null}, appStoreUrl: string|null, free: bool, inAppPurchases: bool, version: string|null, publishedAtFormatted: string|null}|null + * @return array{deviceNames: list, requirements: array{systems: list, minVersion: string, displayVersion: string, releaseName: string|null}, appStoreUrl: string|null, free: bool, inAppPurchases: bool, version: string|null, shortVersion: string|null, publishedAtFormatted: string|null}|null */ private function ios(PlatformCatalog $platforms, SiteFacts $facts, string $locale): ?array { @@ -63,77 +59,45 @@ private function ios(PlatformCatalog $platforms, SiteFacts $facts, string $local $platform = $platforms->find('ios') ?? []; $price = is_array($platform['price'] ?? null) ? $platform['price'] : []; $release = is_array($platform['release'] ?? null) ? $platform['release'] : []; + $version = $this->string($release['version'] ?? null); return [ ...$summary, 'appStoreUrl' => $this->url($platforms->destination('ios', 'app-store')['url'] ?? null) ?? $facts->links()['appStore'], 'free' => is_numeric($price['amount'] ?? null) && (float) $price['amount'] === 0.0, 'inAppPurchases' => ($price['inAppPurchases'] ?? false) === true, - 'version' => $this->string($release['version'] ?? null), + 'version' => $version, + 'shortVersion' => $this->shortVersion($version), 'publishedAtFormatted' => $this->date($release['publishedAt'] ?? null, $locale), ]; } /** - * @return array{deviceNames: list, channel: string, distributions: list, via: string}>, desktop: array{name: string, version: string}|null, architectures: list, methods: list, update: string|null}>, packages: list}>, checksums: array{name: string, url: string|null}|null, verify: string|null, release: array{version: string, publishedOn: string|null, releaseUrl: string, releasesUrl: string}|null} + * @return array{deviceNames: list, channel: string, distributions: list, via: string}>, architectures: list, methods: list}>, release: array{version: string, shortVersion: string, publishedOn: string|null, releaseUrl: string, releasesUrl: string}|null} */ private function linux(PlatformCatalog $platforms, ?LinuxRelease $release, string $locale): array { $platform = $platforms->find('linux') ?? []; $summary = $platforms->linuxSummary() ?? ['deviceNames' => [], 'channel' => $platforms->linuxChannel(), 'distributions' => []]; - $packages = $platforms->linuxPackages(); - $architectures = $this->strings($platform['architectures'] ?? []); - $desktop = $platform['desktop'] ?? null; - $distributions = $summary['distributions']; - $methods = []; foreach (is_array($platform['destinations'] ?? null) ? $platform['destinations'] : [] as $destination) { $commands = $this->strings(is_array($destination) ? ($destination['commands'] ?? []) : []); - if ($commands !== [] && in_array($destination['kind'] ?? null, self::PACKAGE_METHOD, true)) { - $methods[] = ['kind' => $destination['kind'], 'commands' => $commands, 'update' => $this->string($destination['update'] ?? null)]; - } - } - - $byName = []; - - foreach ($release?->assets ?? [] as $asset) { - $byName[$asset['name']] = ['name' => $asset['name'], 'url' => $asset['url'], 'bytes' => $asset['bytes']]; - } - - $rows = []; - - foreach ($release !== null ? ($packages['assets'] ?? []) : [] as $asset) { - $via = self::PACKAGE_METHOD[$asset['format']] ?? null; - $named = collect($distributions)->first(fn(array $distribution): bool => $distribution['via'] === $via && $distribution['name'] !== null); - - foreach ($asset['series'] === [] ? [null] : $asset['series'] as $series) { - $files = []; - - foreach ($architectures as $architecture) { - $name = strtr($asset['template'], ['{version}' => $release->version, '{series}' => (string) $series, '{arch}' => $asset['arch'][$architecture] ?? $architecture]); - $files[$architecture] = $byName[$name] ?? null; - } - - if (array_filter($files) !== []) { - $rows[] = ['format' => $asset['format'], 'series' => $series, 'distribution' => $named['name'] ?? null, 'files' => $files]; - } + if ($commands !== [] && in_array($destination['kind'] ?? null, self::LINUX_METHODS, true)) { + $methods[] = ['kind' => $destination['kind'], 'commands' => $commands]; } } return [ 'deviceNames' => $summary['deviceNames'], 'channel' => $summary['channel'], - 'distributions' => $distributions, - 'desktop' => is_array($desktop) && is_string($desktop['name'] ?? null) && is_string($desktop['version'] ?? null) ? ['name' => $desktop['name'], 'version' => $desktop['version']] : null, - 'architectures' => $architectures, + 'distributions' => $summary['distributions'], + 'architectures' => $this->strings($platform['architectures'] ?? []), 'methods' => $methods, - 'packages' => $rows, - 'checksums' => $packages !== null && is_string($packages['checksums'] ?? null) ? ['name' => $packages['checksums'], 'url' => $release?->checksumsUrl] : null, - 'verify' => $this->string($packages['verify'] ?? null), 'release' => $release === null ? null : [ 'version' => $release->version, + 'shortVersion' => $this->shortVersion($release->version) ?? $release->version, 'publishedOn' => $this->date($release->publishedAt, $locale), 'releaseUrl' => $release->releaseUrl, 'releasesUrl' => $release->releasesUrl, @@ -142,21 +106,29 @@ private function linux(PlatformCatalog $platforms, ?LinuxRelease $release, strin } /** - * @return array{docs: string|null, changelog: string|null, source: string|null, license: string|null, issues: string|null} + * @return array{changelog: string|null, source: string|null, license: string|null} */ private function links(SiteFacts $facts): array { $links = $facts->links(); return [ - 'docs' => $links['docs'], 'changelog' => $links['changelog'] ?? ($links['docs'] !== null ? rtrim($links['docs'], '/') . '/changelog' : null), 'source' => $links['github'] ?? 'https://github.com/' . config('services.github.repo'), 'license' => $links['license'], - 'issues' => $links['issues'], ]; } + // The page's H1 names a release by major and minor, as Zed does: 0.85.0 is "0.85", 0.1.0-beta.3 is "0.1". + private function shortVersion(?string $version): ?string + { + if ($version === null || preg_match('/^(\d+)\.(\d+)/', $version, $parts) !== 1) { + return $version; + } + + return "{$parts[1]}.{$parts[2]}"; + } + private function date(mixed $date, string $locale): ?string { if (! is_string($date) || preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) { diff --git a/resources/css/app.css b/resources/css/app.css index 3f2851ac..4393609c 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -458,34 +458,42 @@ html.campaign-live .campaign-band { } /* - * The download page's platform before React has chosen it (PlatformSwitch): the head script's `ios` or `linux` class - * shows that panel and marks its segment, so an iPhone or a Linux desktop never sees the Mac panel first. Panels hide - * with the `hidden` class, not the attribute, which preflight hides with `!important`. + * /download's variants for the reader's machine (components/download/download-hero.tsx), chosen before first paint by + * the head script's class in app.blade.php. With no class the machine is a Mac, as the server rendered it. */ -:is(html.ios [data-platform-switch]:has(> [data-panel='ios']), html.linux [data-platform-switch]:has(> [data-panel='linux'])):not([data-ready]) { - & > [data-panel] { - display: none; +html:not(.ios, .linux, .other-device) [data-device]:not([data-device~='mac']), +html.ios [data-device]:not([data-device~='ios']), +html.linux [data-device]:not([data-device~='linux']), +html.other-device [data-device]:not([data-device~='other']) { + display: none; +} + +/* The DMG action giving way to the install steps after a click. */ +@media (prefers-reduced-motion: no-preference) { + .download-started { + animation: download-started 240ms var(--ease-panel) both; } +} - & > fieldset [data-segment] { - border-color: transparent; - background-color: transparent; - box-shadow: none; - color: var(--muted-foreground); +@keyframes download-started { + from { + opacity: 0; + transform: translateY(4px); } } -/* The same specificity as the rule above, so these win by coming after it. */ -html.ios [data-platform-switch]:has(> [data-panel='ios']):not([data-ready]) > [data-panel='ios'], -html.linux [data-platform-switch]:has(> [data-panel='linux']):not([data-ready]) > [data-panel='linux'] { - display: block; +/* A copy button's check mark arriving. */ +@media (prefers-reduced-motion: no-preference) { + .copy-confirm { + animation: copy-confirm var(--dur-state) var(--ease-feedback) both; + } } -html.ios [data-platform-switch]:has(> [data-panel='ios']):not([data-ready]) > fieldset [data-segment='ios'], -html.linux [data-platform-switch]:has(> [data-panel='linux']):not([data-ready]) > fieldset [data-segment='linux'] { - border-color: var(--rule); - background-color: var(--segment-selected); - color: var(--foreground); +@keyframes copy-confirm { + from { + opacity: 0; + transform: scale(0.6); + } } /* A row of the plan table under the pointer, on whichever ground the table sits. */ diff --git a/resources/data/content/en/download.json b/resources/data/content/en/download.json index e28d434c..337fa5d2 100644 --- a/resources/data/content/en/download.json +++ b/resources/data/content/en/download.json @@ -10,24 +10,44 @@ "header": { "title": "Download TablePro" }, + "hero": { + "title": "TablePro {version}", + "released": "Released {date}.", + "universal": "Universal app. Requires {requirement}.", + "requires": "Requires {requirement}.", + "linux": "Runs on {distributions}.", + "free": "Free. Requires {requirement}.", + "other": "TablePro runs on {platforms}." + }, + "started": { + "title": "Your download has started.", + "retry": "If it didn’t, download again.", + "steps": [ + "Open {file}.", + "Drag TablePro to Applications.", + "Open TablePro." + ] + }, "mac": { - "homebrew": { - "title": "Homebrew", - "trails": "Homebrew’s copy is updated separately and can trail a new release. If it installs an older version, choose TablePro > Check for Updates… to get the current one." - }, - "signing": "TablePro is signed with a Developer ID and notarized by Apple, so you don’t need to change any security setting to open it.", - "source": "Build from source (AGPLv3)" + "text": "Requires {requirement}, on {architectures}. TablePro updates itself.", + "homebrew": "Homebrew" + }, + "linux": { + "distribution": "{name} {versions}", + "flatpak": "Other distributions, with Flatpak", + "architectures": "Builds for {architectures}. Your package manager picks the right one and keeps it up to date.", + "packages": "Packages on GitHub" }, "ios": { "link": "TablePro for {devices}" }, "otherPlatforms": { - "body": "TablePro is not available for {platforms}, and there is no release date.", - "faq": "Platform questions in the FAQ" + "body": "{platform} is coming later." }, - "olderVersions": { - "title": "Older versions", - "releases": "All releases on GitHub", + "more": { + "title": "Releases and source", + "releases": "Older versions on GitHub", + "source": "Build from source (AGPLv3)", "changelog": "Changelog" } } diff --git a/resources/js/components/download/command-block.tsx b/resources/js/components/download/command-block.tsx index 7f9fdbdb..48b6ee71 100644 --- a/resources/js/components/download/command-block.tsx +++ b/resources/js/components/download/command-block.tsx @@ -2,6 +2,8 @@ import { Fragment } from 'react'; import { CodeBlock } from '@/components/ui/code'; import { useI18n } from '@/i18n'; +const WHOLE_TOKEN = 32; + interface CommandBlockProps { // One command per line, exactly as copied: no prompt. lines: string[]; @@ -11,14 +13,14 @@ interface CommandBlockProps { className?: string; } -// One copy button takes every line. A line wraps only at a space (a browser would also break after a hyphen, so every -// token is kept whole), its continuation indented so it never reads as the next command; a token wider than the block -// (a URL) scrolls inside it. +// One copy button takes every line. A line wraps at a space, its continuation indented so it never reads as the next +// command. Tokens are kept whole, since a browser would break one after a hyphen; a long one (a URL) may also break +// after a slash, so it wraps on a phone instead of scrolling. export default function CommandBlock({ lines, title, label, onCopied, className }: CommandBlockProps) { const { m } = useI18n(); return ( - +
                 
                     {lines.map((line, index) => (
@@ -26,7 +28,12 @@ export default function CommandBlock({ lines, title, label, onCopied, className
                             {line.split(' ').map((token, position) => (
                                 
                                     {position > 0 && ' '}
-                                    {token}
+                                    {(token.length > WHOLE_TOKEN ? token.split(/(?<=\/)(?!\/)/) : [token]).map((part, at) => (
+                                        
+                                            {at > 0 && }
+                                            {part}
+                                        
+                                    ))}
                                 
                             ))}
                         
diff --git a/resources/js/components/download/download-hero.tsx b/resources/js/components/download/download-hero.tsx
new file mode 100644
index 00000000..5f23195f
--- /dev/null
+++ b/resources/js/components/download/download-hero.tsx
@@ -0,0 +1,168 @@
+import { Fragment, type ReactNode } from 'react';
+import { ArrowDown } from 'lucide-react';
+import FeatureHero from '@/components/features/feature-hero';
+import Badge from '@/components/ui/badge';
+import { buttonClasses } from '@/components/ui/button';
+import TextLink from '@/components/ui/text-link';
+import { useI18n } from '@/i18n';
+import { joinList, keepTogether } from '@/i18n/format';
+import { trackDownload } from '@/lib/analytics';
+import AppStoreBadge from './app-store-badge';
+import { requirementLine } from './format';
+import { distributionsText } from './linux-text';
+import MacDownload from './mac-download';
+import type { DeviceKey, DownloadContent, IosProp, LinuxProp, MacProp, ReleaseProp } from './types';
+
+interface DownloadHeroProps {
+    content: DownloadContent;
+    release: ReleaseProp;
+    mac: MacProp;
+    linux: LinuxProp | null;
+    ios: IosProp | null;
+}
+
+interface Variant {
+    devices: DeviceKey[];
+    node: ReactNode;
+}
+
+// Each variant names the machines it is for, and app.css shows the reader's before first paint. The space between them
+// keeps the H1's words apart where no CSS applies.
+function Variants({ variants, as: Tag = 'span' }: { variants: Variant[]; as?: 'span' | 'div' }) {
+    return variants.map((variant, index) => (
+        
+            {index > 0 && ' '}
+            {variant.node}
+        
+    ));
+}
+
+export function IosAction({ content, ios, store, location }: { content: DownloadContent; ios: IosProp; store: string; location: string }) {
+    const { m, fmt } = useI18n();
+    const requirement = requirementLine(ios.requirements, m.platforms);
+
+    return (
+        
+ +

{fmt(ios.free && !ios.inAppPurchases ? content.hero.free : content.hero.requires, { requirement })}

+
+ ); +} + +// The release and the one action for the reader's machine: the DMG on a Mac, the Linux commands on Linux, the App Store +// on an iPhone or iPad. Any other machine gets the Mac's release and a sentence naming where TablePro runs, never a +// guessed download. The server renders every variant with the Mac's showing, and the head script's class picks before +// first paint, so nothing moves. +export default function DownloadHero({ content, release, mac, linux, ios }: DownloadHeroProps) { + const { m, fmt } = useI18n(); + const store = ios !== null ? ios.appStoreUrl : null; + const noApp: DeviceKey[] = ['other', ...(linux === null ? (['linux'] as const) : []), ...(store === null ? (['ios'] as const) : [])]; + + const title = (version: string | null): string => (version !== null ? fmt(content.hero.title, { version }) : content.header.title); + const released = (date: string | null, notes: string | null): ReactNode => ( + <> + {date !== null && fmt(content.hero.released, { date: keepTogether(date) })} + {date !== null && notes !== null && ' '} + {notes !== null && ( + + {m.download.release.notes} + + )} + + ); + + const live = release.source !== 'unavailable'; + const releases: { devices: DeviceKey[]; title: ReactNode; lead: ReactNode }[] = [ + { + devices: ['mac', ...noApp], + title: title(live ? release.shortVersion : null), + lead: live ? released(release.publishedAtFormatted, release.releaseUrl) : null, + }, + ]; + + if (linux !== null) { + releases.push({ + devices: ['linux'], + title: ( + <> + {title(linux.release?.shortVersion ?? null)} + {linux.channel === 'beta' && linux.release !== null && ( + <> + {' '} + + {m.download.panel.beta} + + + )} + + ), + lead: linux.release !== null ? released(linux.release.publishedOn, linux.release.releaseUrl) : null, + }); + } + + if (ios !== null && store !== null) { + releases.push({ devices: ['ios'], title: title(ios.shortVersion), lead: released(ios.publishedAtFormatted, null) }); + } + + const names = [...mac.deviceNames, ...(linux?.deviceNames ?? []), ...(ios?.deviceNames ?? [])]; + const actions: Variant[] = [ + { + devices: ['mac'], + node: ( + + ), + }, + ]; + + if (linux !== null) { + actions.push({ + devices: ['linux'], + node: ( +
+ trackDownload('download-page', 'linux')} className={buttonClasses('primary', 'lg')}> + +

{fmt(content.hero.linux, { distributions: distributionsText(linux, m.download) })}

+
+ ), + }); + } + + if (ios !== null && store !== null) { + actions.push({ devices: ['ios'], node: }); + } + + actions.push({ + devices: noApp, + node:

{fmt(content.hero.other, { platforms: joinList(names, m.common.list) })}

, + }); + + return ( + + } + title={ ({ devices: each.devices, node: each.title }))} />} + lead={ ({ devices: each.devices, node: each.lead }))} />} + actions={} + /> + ); +} diff --git a/resources/js/components/download/format.ts b/resources/js/components/download/format.ts index 1744ace5..fcee7d37 100644 --- a/resources/js/components/download/format.ts +++ b/resources/js/components/download/format.ts @@ -1,16 +1,8 @@ import { interpolate } from '@/i18n/core'; -import { formatNumber, type NumberStyle } from '@/i18n/format'; import type { PlatformStrings } from '@/lib/data/platforms'; import type { Requirements } from './types'; -/** - * A platform's requirement from the server's `platforms.json` props, through - * the `platforms` catalog's templates: "macOS 13 Ventura or later", "iOS and - * iPadOS 18 trở lên". The same rule as `requirementText()` in - * lib/data/platforms.ts, which takes a whole platform from the bundled file; - * the download page reads its facts from the server instead, so the page and - * its tests see the same `platforms.json`. - */ +// "macOS 13 Ventura or later" from the server's platforms.json props, so the page and its tests read the same file. export function requirementLine(requirements: Requirements, strings: Pick): string { const { systems, displayVersion, releaseName } = requirements; const template = releaseName === null ? strings.requirement.unnamed : strings.requirement.named; @@ -21,12 +13,3 @@ export function requirementLine(requirements: Requirements, strings: Pick each.via === kind && each.name !== null); - - return distribution !== undefined ? distributionFloor(distribution, strings) : strings.flatpak; -} - // "Ubuntu 26.04+, Fedora 44+ or any distribution via Flatpak", in data order. export function distributionsText(linux: Pick, strings: Messages['download']): string { return joinList( diff --git a/resources/js/components/download/mac-download.tsx b/resources/js/components/download/mac-download.tsx new file mode 100644 index 00000000..2e4078eb --- /dev/null +++ b/resources/js/components/download/mac-download.tsx @@ -0,0 +1,77 @@ +import { useEffect, useRef, useState, type ReactNode } from 'react'; +import { Download } from 'lucide-react'; +import Button from '@/components/ui/button'; +import { textLinkClasses } from '@/components/ui/text-link'; +import { Trans, useI18n } from '@/i18n'; +import { trackDownload } from '@/lib/analytics'; +import type { DownloadContent, ReleaseProp } from './types'; + +interface MacDownloadProps { + content: DownloadContent; + release: ReleaseProp; + variant: 'primary' | 'secondary'; + location: string; + caption?: ReactNode; +} + +// The DMG link is in the server render with its real URL and nothing starts on its own. Once the reader clicked, the +// action makes way for the three install steps and the same file again; with no release data the link opens GitHub, so +// nothing claims a download started. +export default function MacDownload({ content, release, variant, location, caption }: MacDownloadProps) { + const { m, fmt } = useI18n(); + const [started, setStarted] = useState(false); + const status = useRef(null); + const { asset } = release; + const file = release.source !== 'unavailable' ? asset.name : null; + + useEffect(() => { + if (started) { + status.current?.focus(); + } + }, [started]); + + if (started && file !== null) { + return ( +
+

+ {content.started.title}{' '} + ( + trackDownload('download-retry', 'mac')} className={textLinkClasses('inline')}> + {text} + + ), + }} + /> +

+
    + {content.started.steps.map((step) => ( +
  1. + {fmt(step, { file })} +
  2. + ))} +
+
+ ); + } + + return ( +
+ + {caption !== undefined &&

{caption}

} +
+ ); +} diff --git a/resources/js/components/download/qr-code.tsx b/resources/js/components/download/qr-code.tsx new file mode 100644 index 00000000..8a508602 --- /dev/null +++ b/resources/js/components/download/qr-code.tsx @@ -0,0 +1,21 @@ +import { useMemo } from 'react'; +import { qrMatrix, qrPath } from '@/lib/qr'; +import { cn } from '@/lib/utils'; + +const QUIET_ZONE = 4; + +// Black on white in both themes: a phone camera reads dark modules on a light ground, and the quiet zone is part of it. +export default function QrCode({ value, className }: { value: string; className?: string }) { + const { path, size } = useMemo(() => { + const matrix = qrMatrix(value); + + return { path: qrPath(matrix, QUIET_ZONE), size: matrix.length + QUIET_ZONE * 2 }; + }, [value]); + + return ( + + ); +} diff --git a/resources/js/components/download/types.ts b/resources/js/components/download/types.ts index 41a04389..68cf783a 100644 --- a/resources/js/components/download/types.ts +++ b/resources/js/components/download/types.ts @@ -10,13 +10,14 @@ export interface ReleaseAsset { name: string | null; // GitHub's latest-release page when no release source answered. url: string; - // The Sparkle appcast has no sizes or digests, only the GitHub API does. bytes: number | null; sha256: string | null; } export interface ReleaseProp { version: string | null; + // "0.85" for 0.85.0, the H1's version. + shortVersion: string | null; publishedAt: string | null; // Formatted in PHP, so SSR and the browser agree. publishedAtFormatted: string | null; @@ -29,9 +30,9 @@ export interface ReleaseProp { export interface MacProp { deviceNames: string[]; requirements: Requirements | null; + // One DMG for Apple silicon and Intel. + universal: boolean; homebrewCommand: string | null; - // The Homebrew cask still serves an older version than this release. - homebrewTrails: boolean; } export interface IosProp { @@ -41,6 +42,7 @@ export interface IosProp { free: boolean; inAppPurchases: boolean; version: string | null; + shortVersion: string | null; publishedAtFormatted: string | null; } @@ -56,49 +58,28 @@ export interface LinuxDistributionProp { export interface LinuxMethod { kind: LinuxMethodKind; commands: string[]; - update: string | null; -} - -export interface LinuxFile { - name: string; - url: string; - bytes: number | null; -} - -export interface LinuxPackageRow { - format: 'deb' | 'rpm' | 'flatpak'; - series: string | null; - distribution: string | null; - // Keyed by the architecture as platforms.json names it; null where the release has no such file. - files: Record; } export interface LinuxProp { deviceNames: string[]; channel: 'beta' | 'stable'; distributions: LinuxDistributionProp[]; - desktop: { name: string; version: string } | null; architectures: string[]; methods: LinuxMethod[]; - packages: LinuxPackageRow[]; - checksums: { name: string; url: string | null } | null; - // `{file}` stands for the downloaded file. - verify: string | null; - release: { version: string; publishedOn: string | null; releaseUrl: string; releasesUrl: string } | null; + release: { version: string; shortVersion: string; publishedOn: string | null; releaseUrl: string; releasesUrl: string } | null; } // What a page outside /download says about Linux: `PlatformCatalog::linuxSummary`, null until Linux is released. export type LinuxSummary = Pick; export interface LinksProp { - docs: string | null; changelog: string | null; source: string | null; license: string | null; - issues: string | null; } -export type PlatformKey = 'mac' | 'linux' | 'ios'; +// What the head script in app.blade.php calls the reader's machine; a Mac carries no class. +export type DeviceKey = 'mac' | 'linux' | 'ios' | 'other'; export interface DownloadPageProps { content: DownloadContent; diff --git a/resources/js/components/features/feature-hero.tsx b/resources/js/components/features/feature-hero.tsx index 763127af..8034b581 100644 --- a/resources/js/components/features/feature-hero.tsx +++ b/resources/js/components/features/feature-hero.tsx @@ -10,7 +10,7 @@ import { cn } from '@/lib/utils'; import { docsHref } from './model'; interface FeatureHeroProps { - title: string; + title: ReactNode; lead: ReactNode; // A docs.tablepro.app path; the hub links the docs home. docs?: string; diff --git a/resources/js/components/ui/code.tsx b/resources/js/components/ui/code.tsx index 56ec9421..aca30a5a 100644 --- a/resources/js/components/ui/code.tsx +++ b/resources/js/components/ui/code.tsx @@ -29,6 +29,8 @@ interface CodeBlockProps { command?: boolean; // Without them there is no copy button. copyLabels?: CopyButtonLabels; + // `md` writes "Copy" and "Copied" beside the icon. + copySize?: 'sm' | 'md'; // What to copy when `code` is not given. copyValue?: string; onCopied?: () => void; @@ -37,9 +39,9 @@ interface CodeBlockProps { } // A line wider than the column scrolls inside the block, from the keyboard too, instead of widening the page. -export function CodeBlock({ label, title, code, command = false, copyLabels, copyValue, onCopied, className, children }: CodeBlockProps) { +export function CodeBlock({ label, title, code, command = false, copyLabels, copySize, copyValue, onCopied, className, children }: CodeBlockProps) { const value = code ?? copyValue; - const copy = copyLabels && value !== undefined ? : null; + const copy = copyLabels && value !== undefined ? : null; return (
diff --git a/resources/js/components/ui/copy-button.tsx b/resources/js/components/ui/copy-button.tsx index 897ea6a5..c941a705 100644 --- a/resources/js/components/ui/copy-button.tsx +++ b/resources/js/components/ui/copy-button.tsx @@ -75,7 +75,7 @@ export default function CopyButton({ value, label, size = 'sm', labels = ENGLISH )} > {copied ? ( -