diff --git a/build/lib/generateContent.ts b/build/lib/generateContent.ts index 12c35ee5..cb0bb6b8 100644 --- a/build/lib/generateContent.ts +++ b/build/lib/generateContent.ts @@ -1,7 +1,8 @@ import fs from "node:fs/promises"; import { packageDirectory } from "package-directory"; import path from "node:path"; -import { frameworkVersions } from "../../frameworks.ts"; +import { frameworkVersions, isUpgradePair, orderPair } from "../../frameworks.ts"; +import { diffUpgrade, type SourceFile, type UpgradeDiff } from "./upgradeDiff.ts"; import playgroundUrlByFramework from "./playgroundUrlByFramework.ts"; import prettier from "prettier"; import { mustUseAngularHighlighter } from "./angularHighlighter.ts"; @@ -68,12 +69,16 @@ async function shouldRegenerateFiles( const treeDtsFilePath = path.join(generatedContentDirPath, "tree.d.ts"); const frameworkIndexPath = path.join(frameworkDirPath, "index.js"); const frameworkIndexDtsPath = path.join(frameworkDirPath, "index.d.ts"); + const upgradeDiffsPath = path.join(generatedContentDirPath, "upgradeDiffs.js"); + const upgradeDiffsDtsPath = path.join(generatedContentDirPath, "upgradeDiffs.d.ts"); const generatedFilesExist = await Promise.all([ pathExists(treeFilePath), pathExists(treeDtsFilePath), pathExists(frameworkIndexPath), pathExists(frameworkIndexDtsPath), + pathExists(upgradeDiffsPath), + pathExists(upgradeDiffsDtsPath), ]); // If any generated file is missing, regenerate @@ -81,9 +86,15 @@ async function shouldRegenerateFiles( return true; } - // Get the modification time of the content directory - const contentStats = await fs.stat(contentPath); - const contentModTime = contentStats.mtime; + // Newest of the inputs: the content directory, and the sources that decide + // the upgrade pairs and their diffs. + const rootDir = path.dirname(contentPath); + const inputStats = await Promise.all( + [contentPath, "frameworks.ts", "build/lib/upgradeDiff.ts", "build/lib/generateContent.ts"].map( + (input) => fs.stat(path.resolve(rootDir, input)), + ), + ); + const contentModTime = new Date(Math.max(...inputStats.map((stats) => stats.mtimeMs))); // Check if any generated file is older than the content directory const generatedFilePaths = [ @@ -91,6 +102,8 @@ async function shouldRegenerateFiles( treeDtsFilePath, frameworkIndexPath, frameworkIndexDtsPath, + upgradeDiffsPath, + upgradeDiffsDtsPath, ]; for (const filePath of generatedFilePaths) { @@ -139,6 +152,8 @@ export default async function generateContent(options: { noCache?: boolean } = { }; const byFrameworkId: Record = {}; + // Source of each example's code files, kept for the upgrade diffs. + const sourcesByFrameworkId: Record> = {}; for (const sectionDirName of sectionDirNames) { const sectionTitle = dirNameToTitle(sectionDirName); @@ -237,6 +252,10 @@ export default async function generateContent(options: { noCache?: boolean } = { frameworkSnippet.playgroundURL = playgroundURL; } + (sourcesByFrameworkId[frameworkId] ??= {})[snippetId] = frameworkSnippet.files.map( + (file) => ({ fileName: file.fileName, content: file.content ?? "" }), + ); + // Remove content key, not used anymore frameworkSnippet.files = frameworkSnippet.files.map((file) => ({ fileName: file.fileName, @@ -324,6 +343,31 @@ export default async function generateContent(options: { noCache?: boolean } = { `, ); + await writeJsFile( + path.join(generatedContentDirPath, "upgradeDiffs.js"), + ` + ${commentDisclaimer} + export default ${JSON.stringify(buildUpgradeDiffs(sourcesByFrameworkId), null, 2)}; + `, + ); + + await writeDtsFile( + path.join(generatedContentDirPath, "upgradeDiffs.d.ts"), + ` + ${commentDisclaimer} + export interface UpgradeDiff { + changed: boolean; + /** 1-based line numbers, keyed by file name. */ + removedLines: Record; + addedLines: Record; + } + + /** Keyed by canonical slug ("solid1-vs-solid2"), then by snippet id. */ + declare const upgradeDiffs: Record>; + export default upgradeDiffs; + `, + ); + await writeDtsFile( frameworkIndexDtsPath, ` @@ -337,6 +381,30 @@ export default async function generateContent(options: { noCache?: boolean } = { ); } +/** + * For each upgrade pair (2 versions of one framework, older first) and each + * example both versions have, which lines changed. + */ +function buildUpgradeDiffs( + sourcesByFrameworkId: Record>, +): Record> { + const result: Record> = {}; + const ids = frameworkVersions.map(({ id }) => id); + for (const [i, idA] of ids.entries()) { + for (const idB of ids.slice(i + 1)) { + if (!isUpgradePair(idA, idB)) continue; + const [older, newer] = orderPair(idA, idB); + const diffs: Record = {}; + for (const [snippetId, oldFiles] of Object.entries(sourcesByFrameworkId[older] ?? {})) { + const newFiles = sourcesByFrameworkId[newer]?.[snippetId]; + if (newFiles) diffs[snippetId] = diffUpgrade(oldFiles, newFiles); + } + result[`${older}-vs-${newer}`] = diffs; + } + } + return result; +} + function dirNameToTitle(dirName: string): string { return capitalize(dirName.split("-").splice(1).join(" ")); } diff --git a/build/lib/upgradeDiff.test.ts b/build/lib/upgradeDiff.test.ts new file mode 100644 index 00000000..c1dc78af --- /dev/null +++ b/build/lib/upgradeDiff.test.ts @@ -0,0 +1,79 @@ +import { describe, it, expect } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import { diffUpgrade, type SourceFile } from "./upgradeDiff"; + +function read(dir: string): SourceFile[] { + const full = path.join("content", dir); + return fs + .readdirSync(full) + .sort() + .map((fileName) => ({ fileName, content: fs.readFileSync(path.join(full, fileName), "utf8") })); +} + +describe("diffUpgrade", () => { + it("marks the lines Solid 2 changes in update-state", () => { + const diff = diffUpgrade( + read("1-reactivity/2-update-state/solid1"), + read("1-reactivity/2-update-state/solid2"), + ); + expect(diff.changed).toBe(true); + // Solid 1 line 5: `setName("Jane");` in the component body. + expect(diff.removedLines["Name.jsx"]).toEqual([1, 5]); + // Solid 2: the import with onSettled, then the onSettled block. + expect(diff.addedLines["Name.jsx"]).toEqual([1, 6, 7, 8]); + }); + + it("reports an identical example as unchanged", () => { + const diff = diffUpgrade( + read("1-reactivity/1-declare-state/solid1"), + read("1-reactivity/1-declare-state/solid2"), + ); + expect(diff).toEqual({ changed: false, removedLines: {}, addedLines: {} }); + }); + + it("diffs Ember's .hbs + .js pair against the matching .gjs", () => { + const oldFiles = [ + { fileName: "name.hbs", content: "

{{this.name}}

\n" }, + { fileName: "name.js", content: "export default class Name {}\n" }, + ]; + const newFiles = [ + { + fileName: "name.gjs", + content: "export default class Name {}\n\n", + }, + ]; + const diff = diffUpgrade(oldFiles, newFiles); + expect(diff.removedLines).toEqual({ "name.hbs": [1] }); + expect(diff.addedLines).toEqual({ "name.gjs": [2] }); + }); + + it("marks a file only one version has as fully removed or added", () => { + const diff = diffUpgrade( + [ + { fileName: "app.module.ts", content: "a\nb\n" }, + { fileName: "app.ts", content: "x\n" }, + ], + [{ fileName: "app.ts", content: "x\n" }], + ); + expect(diff.changed).toBe(true); + expect(diff.removedLines).toEqual({ "app.module.ts": [1, 2] }); + expect(diff.addedLines).toEqual({}); + }); + + it("counts a blank-line-only change as changed, without tinting it", () => { + const diff = diffUpgrade( + [{ fileName: "a.js", content: "x\ny\n" }], + [{ fileName: "a.js", content: "x\n\ny\n" }], + ); + expect(diff).toEqual({ changed: true, removedLines: {}, addedLines: {} }); + }); + + it("pairs base names whatever their case", () => { + const diff = diffUpgrade( + [{ fileName: "app.js", content: "same\n" }], + [{ fileName: "App.gjs", content: "same\n" }], + ); + expect(diff).toEqual({ changed: true, removedLines: {}, addedLines: {} }); + }); +}); diff --git a/build/lib/upgradeDiff.ts b/build/lib/upgradeDiff.ts new file mode 100644 index 00000000..16584b4e --- /dev/null +++ b/build/lib/upgradeDiff.ts @@ -0,0 +1,124 @@ +/** + * Line diff between 2 versions of one example, for upgrade pages (e.g. Solid 1 + * to Solid 2). Files pair by exact name, then by base name, so Ember's + * `name.hbs` + `name.js` pair with `name.gjs`. A file left without a pair is + * fully removed or fully added. + */ + +export interface SourceFile { + fileName: string; + content: string; +} + +/** 1-based line numbers, keyed by file name. */ +export type LinesByFile = Record; + +export interface UpgradeDiff { + changed: boolean; + removedLines: LinesByFile; + addedLines: LinesByFile; +} + +interface Line { + fileName: string; + lineNumber: number; + text: string; +} + +function toLines(files: SourceFile[]): Line[] { + return files.flatMap((file) => + file.content + .replace(/\n+$/, "") + .split("\n") + .map((text, i) => ({ fileName: file.fileName, lineNumber: i + 1, text: text.trimEnd() })), + ); +} + +/** Indexes of the lines of `a` and `b` that are not in their longest common subsequence. */ +function diffLines(a: string[], b: string[]): { removed: number[]; added: number[] } { + const lcs: number[][] = Array.from({ length: a.length + 1 }, () => Array(b.length + 1).fill(0)); + for (let i = a.length - 1; i >= 0; i--) { + for (let j = b.length - 1; j >= 0; j--) { + lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); + } + } + const removed: number[] = []; + const added: number[] = []; + let i = 0; + let j = 0; + while (i < a.length && j < b.length) { + if (a[i] === b[j]) { + i++; + j++; + } else if (lcs[i + 1][j] >= lcs[i][j + 1]) { + removed.push(i++); + } else { + added.push(j++); + } + } + while (i < a.length) removed.push(i++); + while (j < b.length) added.push(j++); + return { removed, added }; +} + +// Case-insensitive, so Ember's `app.hbs` + `app.js` pair with `App.gjs`. +const baseName = (fileName: string) => fileName.replace(/\.[^.]+$/, "").toLowerCase(); + +/** Groups of old and new files that diff against each other, in input order. */ +function pairFiles(oldFiles: SourceFile[], newFiles: SourceFile[]): [SourceFile[], SourceFile[]][] { + const groups: [SourceFile[], SourceFile[]][] = []; + const oldLeft = [...oldFiles]; + const newLeft = [...newFiles]; + + for (const file of [...oldLeft]) { + const match = newLeft.find((n) => n.fileName === file.fileName); + if (match) { + groups.push([[file], [match]]); + oldLeft.splice(oldLeft.indexOf(file), 1); + newLeft.splice(newLeft.indexOf(match), 1); + } + } + + for (const name of new Set(oldLeft.map((f) => baseName(f.fileName)))) { + const olds = oldLeft.filter((f) => baseName(f.fileName) === name); + const news = newLeft.filter((f) => baseName(f.fileName) === name); + if (news.length === 0) continue; + groups.push([olds, news]); + for (const f of olds) oldLeft.splice(oldLeft.indexOf(f), 1); + for (const f of news) newLeft.splice(newLeft.indexOf(f), 1); + } + + for (const file of oldLeft) groups.push([[file], []]); + for (const file of newLeft) groups.push([[], [file]]); + return groups; +} + +function push(target: LinesByFile, line: Line): void { + (target[line.fileName] ??= []).push(line.lineNumber); +} + +export function diffUpgrade(oldFiles: SourceFile[], newFiles: SourceFile[]): UpgradeDiff { + const removedLines: LinesByFile = {}; + const addedLines: LinesByFile = {}; + + for (const [olds, news] of pairFiles(oldFiles, newFiles)) { + const oldLines = toLines(olds); + const newLines = toLines(news); + const { removed, added } = diffLines( + oldLines.map((l) => l.text), + newLines.map((l) => l.text), + ); + // A blank line carries no change worth a tint. + for (const i of removed) if (oldLines[i].text.trim()) push(removedLines, oldLines[i]); + for (const j of added) if (newLines[j].text.trim()) push(addedLines, newLines[j]); + } + + // "Unchanged" means byte for byte: the page then shows the code once. + const changed = + oldFiles.length !== newFiles.length || + oldFiles.some( + (file) => newFiles.find((n) => n.fileName === file.fileName)?.content !== file.content, + ); + + return { changed, removedLines, addedLines }; +} diff --git a/build/redirects.test.ts b/build/redirects.test.ts index 59b4db4b..83291d8d 100644 --- a/build/redirects.test.ts +++ b/build/redirects.test.ts @@ -16,9 +16,17 @@ describe("buildRedirectLines", () => { // The exact URLs Google Search Console reported as 404 (Introuvable). it.each([ ["/compare/react-vs-svelte5", "/compare/svelte5-vs-react/"], // inverse, no slash - ["/compare/svelte4-vs-svelte5", "/compare/svelte5-vs-svelte4/"], // inverse, no slash - ["/compare/aurelia1-vs-aurelia2", "/compare/aurelia2-vs-aurelia1/"], // inverse, no slash - ["/compare/emberOctane-vs-emberPolaris", "/compare/emberPolaris-vs-emberOctane/"], // inverse, no slash + // Upgrade pairs read old to new; their former newer-first pages 301. + ["/compare/svelte5-vs-svelte4/", "/compare/svelte4-vs-svelte5/"], + ["/compare/vue3-vs-vue2/", "/compare/vue2-vs-vue3/"], + [ + "/compare/angularRenaissance-vs-angularClassic/", + "/compare/angularClassic-vs-angularRenaissance/", + ], + ["/compare/emberPolaris-vs-emberOctane", "/compare/emberOctane-vs-emberPolaris/"], + ["/compare/solid2-vs-solid1/", "/compare/solid1-vs-solid2/"], + ["/compare/aurelia2-vs-aurelia1", "/compare/aurelia1-vs-aurelia2/"], + ["/compare/svelte-vs-svelte4/", "/compare/svelte4-vs-svelte5/"], // family alias ["/compare/react-vs-vue", "/compare/react-vs-vue3/"], // family alias, no slash ["/compare/angular-vs-solid", "/compare/angularRenaissance-vs-solid2/"], // family alias, no slash ["/compare/angularRenaissance-vs-solid/", "/compare/angularRenaissance-vs-solid2/"], // old Solid canonical page diff --git a/build/redirects.ts b/build/redirects.ts index ee7364c2..22bb1fa0 100644 --- a/build/redirects.ts +++ b/build/redirects.ts @@ -1,10 +1,12 @@ -import { frameworkVersions, frameworks } from "../frameworks.ts"; +import { frameworks } from "../frameworks.ts"; +import { canonicalPairs } from "../src/lib/comparisonPairs.ts"; /** * Every non-canonical URL form that should 301 to a canonical comparison page. * - * The canonical page for a pair is `/compare/{a}-vs-{b}/`, where `a` precedes - * `b` in `frameworkVersions` order and both are concrete version ids. Google has + * The canonical page for a pair is `/compare/{a}-vs-{b}/`, in `orderPair` + * order (older release first for 2 versions of one framework, else + * `frameworkVersions` order), with concrete version ids. Google has * historically indexed URLs that no longer match that exact shape: * - inverse order (`b-vs-a`), * - family-name aliases (`svelte`→`svelte5`, `vue`→`vue3`, `angular`→ @@ -19,8 +21,6 @@ import { frameworkVersions, frameworks } from "../frameworks.ts"; * The bare (no-slash) canonical form is left to Cloudflare's own 308 handling. */ export function buildRedirectLines(): string[] { - const versions = frameworkVersions.map((f) => f.id); - // A version id plus any family whose latest stable release is that version, // e.g. svelte5 → ["svelte5", "svelte"]; react → ["react"] (family id === version id). const aliasesFor = (versionId: string): string[] => { @@ -34,22 +34,18 @@ export function buildRedirectLines(): string[] { const lines: string[] = []; const seenSources = new Set(); - for (let i = 0; i < versions.length; i++) { - for (let j = i + 1; j < versions.length; j++) { - const a = versions[i]; - const b = versions[j]; - const canonicalSlug = `${a}-vs-${b}`; - const canonicalPath = `/compare/${canonicalSlug}/`; + for (const [a, b] of canonicalPairs()) { + const canonicalSlug = `${a}-vs-${b}`; + const canonicalPath = `/compare/${canonicalSlug}/`; - for (const x of aliasesFor(a)) { - for (const y of aliasesFor(b)) { - for (const slug of [`${x}-vs-${y}`, `${y}-vs-${x}`]) { - if (slug === canonicalSlug) continue; // never shadow the real page - for (const source of [`/compare/${slug}/`, `/compare/${slug}`]) { - if (seenSources.has(source)) continue; - seenSources.add(source); - lines.push(`${source} ${canonicalPath} 301`); - } + for (const x of aliasesFor(a)) { + for (const y of aliasesFor(b)) { + for (const slug of [`${x}-vs-${y}`, `${y}-vs-${x}`]) { + if (slug === canonicalSlug) continue; // never shadow the real page + for (const source of [`/compare/${slug}/`, `/compare/${slug}`]) { + if (seenSources.has(source)) continue; + seenSources.add(source); + lines.push(`${source} ${canonicalPath} 301`); } } } diff --git a/docs/superpowers/specs/2026-11-18-version-upgrade-pages-design.md b/docs/superpowers/specs/2026-11-18-version-upgrade-pages-design.md new file mode 100644 index 00000000..a6fbc9bc --- /dev/null +++ b/docs/superpowers/specs/2026-11-18-version-upgrade-pages-design.md @@ -0,0 +1,112 @@ +# Version upgrade pages: read as before and after + +## Problem + +Six comparison pages put 2 versions of the same framework side by side. Today +they read like any other comparison: the newer version comes first (left), the +title is "Solid 2 vs Solid 1", and nothing says which examples changed. A +reader who upgrades wants the old code on the left, the new code on the right, +and the changes made visible. + +| Pair | Canonical URL today | Examples | Identical in both | +| ----------------------------- | ------------------------------------------------ | -------- | ----------------- | +| Svelte 4 → Svelte 5 | `/compare/svelte5-vs-svelte4/` | 22 | 3 | +| Vue 2 → Vue 3 | `/compare/vue3-vs-vue2/` | 22 | 1 | +| Angular → Angular Renaissance | `/compare/angularRenaissance-vs-angularClassic/` | 22 | 0 | +| Ember Octane → Ember Polaris | `/compare/emberPolaris-vs-emberOctane/` | 21 | 0 | +| Solid 1 → Solid 2 | `/compare/solid2-vs-solid1/` | 22 | 14 | +| Aurelia 1 → Aurelia 2 | `/compare/aurelia2-vs-aurelia1/` | 20 | 0 | + +"Identical" counts examples whose files are byte for byte the same. + +## Design + +An _upgrade pair_ is 2 versions of the same family (`frameworks` in +`frameworks.ts`). The page of an upgrade pair changes in 5 ways. Every other +comparison page stays as it is. + +1. **Old on the left, new on the right.** The canonical URL of an upgrade + pair becomes `/compare/-vs-/`, older by `releaseDate` + (`/compare/solid1-vs-solid2/`). The current URLs 301 to the new ones, and + their OG images keep rendering (same mechanism as the retired `solid` id). + The column order, the framework bar and the OG image follow the same order. +2. **Upgrade framing.** The title becomes "Solid 1 to Solid 2", the H1 + "Upgrade from Solid 1 to Solid 2". The intro says how many examples change + ("8 of 22 examples change") and links the official migration guide, from a + new optional `migrationGuideURL` on the newer version. The meta description + follows, and so does the JSON-LD headline (`src/lib/seo.ts`). The count only + covers examples that exist in both versions; an example missing on one side + keeps today's "Missing snippet" cell and gets no label. +3. **Changed or unchanged, per example.** Each example shows a "Changed" or + "Unchanged" label next to its title. An unchanged example shows its code + once, full width, with "Same code in Solid 1 and Solid 2", instead of 2 + identical columns. Its header keeps both version labels, each with its own + playground link (the runtimes differ) and edit link. The reserved height of + off-screen examples (`snippetIntrinsicHeight`) counts 1 cell for a collapsed + example. The side menu marks unchanged examples in a dimmer color. +4. **Line changes.** In a changed example, removed lines get a red tint in the + left column and added lines a green tint in the right column, from a line + diff of the 2 versions. Files pair by exact name first, then by base name, + so Ember's `name.hbs` + `name.js` pair with `name.gjs` (the old files are + joined in `filesSorter` order before the diff). A file left without a pair + is fully removed or fully added (Angular's `app.module.ts`, Vue's + `useFetchUsers.js`). `CodeEditor.svelte` gets the line numbers as an + optional prop, so the shared Shiki HTML stays untouched and no tint appears + elsewhere. Colors meet WCAG AA contrast on the code background. No + animation, no hover effect. +5. **Footer.** The "Comparing Legacy version & Current Version" group lists + all 6 upgrade pairs in old-to-new order, Ember included (Polaris is the + current stable, so the "Upcoming" group goes away). + +The home page comparison (`/?f=…`) keeps the order the reader chose and gets +none of this. On an upgrade page, labels, collapse and tints apply only while +the selection is exactly the pair in old-to-new order; if the reader adds or +swaps a framework in the bar, the page shows the plain comparison, and the +route title stays. + +## Out of scope + +- Rewriting examples or writing migration prose per example. +- Diff inside a line (word level). +- Pairs of different families. + +## Global Constraints + +- The diff and the labels come from the build (`generateContent`), never from + the client, so prerendered HTML already carries them. The content cache + regenerates when the diff module is missing or `frameworks.ts` changes. +- The footer stays below the first screen at 390x844 and 1440x900. +- Every old URL keeps answering: a 301 for pages, a 200 for OG images. + +## Tasks + +### Task 1: Upgrade pair order and URLs + +- Files: `frameworks.ts`, `src/lib/frameworkUrl.ts`, `src/lib/comparisonPairs.ts`, + `build/redirects.ts`, OG route, their tests. +- Before the change, snapshot the list of every `/compare/*` page and + `/og/*.png` the current build emits; the test checks each one still answers. +- Produces: `isUpgradePair(a, b)` and the old-to-new canonical order; 301s and + OG images for the previous URLs. +- Proves: each of the 6 previous URLs 301s to the old-to-new page; no canonical + page redirects to itself; previous OG URLs answer 200. + +### Task 2: Build-time diff of upgrade pairs + +- Files: `build/lib/generateContent.ts`, `build/generateContentVitePlugin.ts` + (cache inputs), a new generated module, its test. +- Produces: for each upgrade pair and example, `changed` and the removed and + added line numbers per file. +- Proves: Solid 1 to Solid 2 reports 8 changed of 22; `update-state` marks the + `setName` and `onSettled` lines; an Ember `.hbs` + `.js` pair diffs against + its `.gjs`; Angular `app.module.ts` comes out fully removed. + +### Task 3: Upgrade page layout + +- Files: `src/routes/compare/[comparison]/+page.*`, `Comparison.svelte`, + `CodeEditor.svelte`, the menu component, `src/lib/footerNavigation.ts`, + `src/lib/seo.ts`. +- Consumes: Task 1 order, Task 2 diff, `migrationGuideURL`. +- Proves: captures at 390x844 and 1440x900 of a changed and an unchanged + example on the Solid, Svelte and Ember pages, read back; footer position + measured; after a swap in the framework bar, no label or tint remains. diff --git a/frameworks.ts b/frameworks.ts index 73ba84f2..ea842c7f 100644 --- a/frameworks.ts +++ b/frameworks.ts @@ -15,6 +15,8 @@ function sortAllFilenames(files: File[], filenamesSorted: string[]): File[] { */ export interface FrameworkVersion { id: string; + /** Id of the `Framework` family this version belongs to, e.g. "solid". */ + family: string; title: string; img: string; playgroundURL: string; @@ -23,6 +25,8 @@ export interface FrameworkVersion { repositoryLink: string; mainPackageName: string; releaseDate: string; + /** Official guide to upgrade from the previous version of the same framework. */ + migrationGuideURL?: string; } /** @@ -40,6 +44,7 @@ export interface Framework { export const frameworkVersions: FrameworkVersion[] = [ { id: "svelte5", + family: "svelte", title: "Svelte 5", img: "framework/svelte.svg", playgroundURL: "https://svelte.dev/playground", @@ -50,9 +55,11 @@ export const frameworkVersions: FrameworkVersion[] = [ repositoryLink: "https://github.com/sveltejs/svelte", mainPackageName: "svelte", releaseDate: "2024-10-01", + migrationGuideURL: "https://svelte.dev/docs/svelte/v5-migration-guide", }, { id: "react", + family: "react", title: "React", img: "framework/react.svg", playgroundURL: "https://codesandbox.io/s/mystifying-goldberg-6wx04b", @@ -66,6 +73,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "vue3", + family: "vue", title: "Vue 3", img: "framework/vue.svg", playgroundURL: "https://play.vuejs.org/", @@ -76,9 +84,11 @@ export const frameworkVersions: FrameworkVersion[] = [ repositoryLink: "https://github.com/vuejs/core", mainPackageName: "vue", releaseDate: "2020-09-18", + migrationGuideURL: "https://v3-migration.vuejs.org/", }, { id: "angularRenaissance", + family: "angular", title: "Angular Renaissance", img: "framework/angular-renaissance.svg", playgroundURL: "https://codesandbox.io/s/angular", @@ -97,6 +107,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "angularClassic", + family: "angular", title: "Angular", img: "framework/angular.svg", playgroundURL: "https://codesandbox.io/s/angular", @@ -115,6 +126,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "lit", + family: "lit", title: "Lit", img: "framework/lit.svg", playgroundURL: "https://lit.dev/playground", @@ -128,6 +140,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "emberPolaris", + family: "ember", title: "Ember Polaris", img: "framework/ember.svg", playgroundURL: "http://new.emberjs.com", @@ -141,6 +154,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "emberOctane", + family: "ember", title: "Ember Octane", img: "framework/ember.svg", playgroundURL: "https://ember-twiddle.com", @@ -154,6 +168,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "solid2", + family: "solid", title: "Solid 2", img: "framework/solid.svg", playgroundURL: "https://playground.solidjs.com/", @@ -164,9 +179,11 @@ export const frameworkVersions: FrameworkVersion[] = [ repositoryLink: "https://github.com/solidjs/solid", mainPackageName: "solid-js", releaseDate: "2026-11-16", + migrationGuideURL: "https://docs.solidjs.com/migration/from-solid-1", }, { id: "solid1", + family: "solid", title: "Solid 1", img: "framework/solid.svg", playgroundURL: "https://playground.solidjs.com/", @@ -180,6 +197,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "svelte4", + family: "svelte", title: "Svelte 4", img: "framework/svelte.svg", playgroundURL: "https://svelte.dev/repl", @@ -193,6 +211,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "vue2", + family: "vue", title: "Vue 2", img: "framework/vue.svg", playgroundURL: "", @@ -206,6 +225,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "alpine", + family: "alpine", title: "Alpine", img: "framework/alpine.svg", playgroundURL: "https://codesandbox.io/s/7br3q8", @@ -219,6 +239,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "mithril", + family: "mithril", title: "Mithril", img: "framework/mithril.svg", playgroundURL: "https://codesandbox.io/s/q99qzov66", @@ -232,6 +253,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "aurelia2", + family: "aurelia", title: "Aurelia 2", img: "framework/aurelia.svg", playgroundURL: "https://stackblitz.com/edit/au2-conventions?file=src%2Fmy-app.html", @@ -242,9 +264,11 @@ export const frameworkVersions: FrameworkVersion[] = [ repositoryLink: "https://github.com/aurelia/aurelia", mainPackageName: "aurelia", releaseDate: "2021-01-19", + migrationGuideURL: "https://docs.aurelia.io/migrating-to-aurelia-2/migrating-to-aurelia-2", }, { id: "qwik", + family: "qwik", title: "Qwik", img: "framework/qwik.svg", playgroundURL: "https://qwik.builder.io/playground", @@ -258,6 +282,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "marko", + family: "marko", title: "Marko", img: "framework/marko.svg", playgroundURL: "https://markojs.com/playground/", @@ -271,6 +296,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "aurelia1", + family: "aurelia", title: "Aurelia 1", img: "framework/aurelia.svg", playgroundURL: "https://codesandbox.io/s/ppmy26opw7", @@ -284,6 +310,7 @@ export const frameworkVersions: FrameworkVersion[] = [ }, { id: "ripple", + family: "ripple", title: "Ripple", img: "framework/ripple.svg", playgroundURL: "https://www.ripple-ts.com/playground", @@ -297,13 +324,6 @@ export const frameworkVersions: FrameworkVersion[] = [ }, ]; -/** - * Version ids that were renamed, mapped to the version their old URLs now - * show. `solid` was Solid 1 until Solid 2 shipped; the `solid` family id now - * resolves to Solid 2. - */ -export const retiredVersionIds: Record = { solid: "solid2" }; - export const frameworks: Framework[] = [ { id: "svelte", name: "Svelte", latestStable: "svelte5" }, { id: "react", name: "React", latestStable: "react" }, @@ -325,7 +345,8 @@ export const frameworks: Framework[] = [ * of silently resolving to the wrong version: * - version ids are unique, * - framework (family) ids are unique, - * - each family's `latestStable` references an existing version. + * - each family's `latestStable` references an existing version, + * - each version names an existing family. */ function assertValidFrameworksConfig(versions: FrameworkVersion[], families: Framework[]): void { const errors: string[] = []; @@ -340,13 +361,19 @@ function assertValidFrameworksConfig(versions: FrameworkVersion[], families: Fra for (const family of families) { if (familyIds.has(family.id)) errors.push(`duplicate framework id "${family.id}"`); familyIds.add(family.id); - if (!versionIds.has(family.latestStable)) { + if (versions.find((v) => v.id === family.latestStable)?.family !== family.id) { errors.push( - `framework "${family.id}".latestStable points to unknown version "${family.latestStable}"`, + `framework "${family.id}".latestStable points to "${family.latestStable}", not one of its versions`, ); } } + for (const version of versions) { + if (!familyIds.has(version.family)) { + errors.push(`version "${version.id}".family points to unknown framework "${version.family}"`); + } + } + if (errors.length > 0) { throw new Error(`Invalid frameworks configuration:\n - ${errors.join("\n - ")}`); } @@ -376,6 +403,29 @@ export function matchFrameworkId(id: string): FrameworkVersion | undefined { /** * Get the latest stable version of a framework family, e.g. "svelte" -> Svelte 5. */ +/** + * Two versions of the same framework, e.g. Solid 1 and Solid 2. Their page + * reads as an upgrade: older release on the left. + */ +export function isUpgradePair(idA: string, idB: string): boolean { + const a = frameworkVersions.find((v) => v.id === idA); + const b = frameworkVersions.find((v) => v.id === idB); + return !!a && !!b && a.id !== b.id && a.family === b.family; +} + +/** + * The order a pair is shown in: an upgrade pair goes from the older release to + * the newer one; any other pair follows `frameworkVersions`. + */ +export function orderPair(idA: string, idB: string): [string, string] { + if (isUpgradePair(idA, idB)) { + const releaseDate = (id: string) => frameworkVersions.find((v) => v.id === id)!.releaseDate; + return releaseDate(idA) <= releaseDate(idB) ? [idA, idB] : [idB, idA]; + } + const index = (id: string) => frameworkVersions.findIndex((v) => v.id === id); + return index(idA) <= index(idB) ? [idA, idB] : [idB, idA]; +} + export function getLatestStableVersion(frameworkId: string): FrameworkVersion | undefined { const family = frameworks.find((f) => f.id === frameworkId); if (!family) return undefined; diff --git a/src/lib/comparisonPairs.test.ts b/src/lib/comparisonPairs.test.ts index 5dd7ce7b..08055a5b 100644 --- a/src/lib/comparisonPairs.test.ts +++ b/src/lib/comparisonPairs.test.ts @@ -8,9 +8,13 @@ describe("canonicalPairs", () => { const n = frameworkVersions.length; expect(pairs.length).toBe((n * (n - 1)) / 2); }); - it("orders each pair by framework array position (canonical)", () => { - const index = new Map(frameworkVersions.map((f, i) => [f.id, i])); - for (const [a, b] of pairs) expect(index.get(a)!).toBeLessThan(index.get(b)!); + it("orders a pair of 2 frameworks by array position, an upgrade pair by release", () => { + const byId = new Map(frameworkVersions.map((f, i) => [f.id, { ...f, index: i }])); + for (const [a, b] of pairs) { + const [fa, fb] = [byId.get(a)!, byId.get(b)!]; + if (fa.family === fb.family) expect(fa.releaseDate < fb.releaseDate).toBe(true); + else expect(fa.index).toBeLessThan(fb.index); + } }); it("has no duplicates", () => { const keys = new Set(pairs.map(([a, b]) => `${a}|${b}`)); @@ -18,11 +22,34 @@ describe("canonicalPairs", () => { }); }); +describe("upgrade pairs", () => { + it("put the older release first", () => { + const pairs = canonicalPairs().map(([a, b]) => `${a}-vs-${b}`); + for (const slug of [ + "svelte4-vs-svelte5", + "vue2-vs-vue3", + "angularClassic-vs-angularRenaissance", + "emberOctane-vs-emberPolaris", + "solid1-vs-solid2", + "aurelia1-vs-aurelia2", + ]) { + expect(pairs).toContain(slug); + } + }); +}); + describe("retiredComparisonSlugs", () => { + const slugs = retiredComparisonSlugs(); it("keeps the slugs published while Solid 1 was `solid`", () => { - const slugs = retiredComparisonSlugs(); expect(slugs).toContain("react-vs-solid"); - expect(slugs).toContain("angularRenaissance-vs-solid"); - expect(slugs.every((slug) => slug.split("-vs-").includes("solid"))).toBe(true); + expect(slugs).toContain("solid-vs-solid1"); + }); + it("keeps the newer-first slugs of upgrade pairs", () => { + expect(slugs).toContain("svelte5-vs-svelte4"); + expect(slugs).toContain("solid2-vs-solid1"); + }); + it("never lists a canonical slug", () => { + const canonical = new Set(canonicalPairs().map(([a, b]) => `${a}-vs-${b}`)); + expect(slugs.filter((slug) => canonical.has(slug))).toEqual([]); }); }); diff --git a/src/lib/comparisonPairs.ts b/src/lib/comparisonPairs.ts index 65fd015b..6b4f5932 100644 --- a/src/lib/comparisonPairs.ts +++ b/src/lib/comparisonPairs.ts @@ -1,28 +1,24 @@ -import { frameworkVersions, retiredVersionIds } from "#frameworks"; +import { frameworkVersions, orderPair } from "#frameworks"; +import { legacyOgSlugs } from "./legacyOgSlugs.ts"; export function canonicalPairs(): [string, string][] { const ids = frameworkVersions.map((f) => f.id); const pairs: [string, string][] = []; for (let i = 0; i < ids.length; i++) { for (let j = i + 1; j < ids.length; j++) { - pairs.push([ids[i], ids[j]]); + pairs.push(orderPair(ids[i], ids[j])); } } return pairs; } /** - * Comparison slugs published under a version id that was later renamed, e.g. - * `react-vs-solid` before Solid 1 became `solid1`. Shared links still point at - * their images, so the OG route keeps rendering them. + * OG image slugs that were published once and are no longer canonical: the + * former `solid` id (Solid 1 before Solid 2) and the newer-first order of + * upgrade pairs. Shared links still point at these images, so the OG route + * keeps rendering them. */ export function retiredComparisonSlugs(): string[] { - const slugs: string[] = []; - for (const [a, b] of canonicalPairs()) { - for (const [retiredId, currentId] of Object.entries(retiredVersionIds)) { - if (a === currentId) slugs.push(`${retiredId}-vs-${b}`); - if (b === currentId) slugs.push(`${a}-vs-${retiredId}`); - } - } - return slugs; + const canonical = new Set(canonicalPairs().map(([a, b]) => `${a}-vs-${b}`)); + return legacyOgSlugs.filter((slug) => !canonical.has(slug)); } diff --git a/src/lib/components/Aside.svelte b/src/lib/components/Aside.svelte index ef2f0225..51ae1f96 100644 --- a/src/lib/components/Aside.svelte +++ b/src/lib/components/Aside.svelte @@ -3,6 +3,13 @@ import { onMount } from "svelte"; import throttle from "just-throttle"; + interface Props { + /** Upgrade pages: examples whose code is the same in both versions. */ + unchangedSnippetIds?: string[]; + } + + const { unchangedSnippetIds = [] }: Props = $props(); + let largestVisibleSnippetId: string = $state(""); function getLargestElement(elements: NodeListOf): Element | null { @@ -113,7 +120,9 @@ "inline-block w-full py-1.5 px-4 text-white font-medium hover:bg-gray-800 rounded hover:opacity-100 transition-opacity text-left", snippetPathId === largestVisibleSnippetId ? "bg-gray-800 opacity-70" - : "opacity-50", + : unchangedSnippetIds.includes(snippet.snippetId) + ? "opacity-30" + : "opacity-50", ]} onclick={() => scrollToElement(snippetPathId)} > diff --git a/src/lib/components/CodeEditor.svelte b/src/lib/components/CodeEditor.svelte index 66642d5c..e51acd2e 100644 --- a/src/lib/components/CodeEditor.svelte +++ b/src/lib/components/CodeEditor.svelte @@ -1,5 +1,6 @@
-