Skip to content
76 changes: 72 additions & 4 deletions build/lib/generateContent.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -68,29 +69,41 @@ 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
if (!generatedFilesExist.every(Boolean)) {
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 = [
treeFilePath,
treeDtsFilePath,
frameworkIndexPath,
frameworkIndexDtsPath,
upgradeDiffsPath,
upgradeDiffsDtsPath,
];

for (const filePath of generatedFilePaths) {
Expand Down Expand Up @@ -139,6 +152,8 @@ export default async function generateContent(options: { noCache?: boolean } = {
};

const byFrameworkId: Record<string, FrameworkSnippet[]> = {};
// Source of each example's code files, kept for the upgrade diffs.
const sourcesByFrameworkId: Record<string, Record<string, SourceFile[]>> = {};

for (const sectionDirName of sectionDirNames) {
const sectionTitle = dirNameToTitle(sectionDirName);
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, number[]>;
addedLines: Record<string, number[]>;
}

/** Keyed by canonical slug ("solid1-vs-solid2"), then by snippet id. */
declare const upgradeDiffs: Record<string, Record<string, UpgradeDiff>>;
export default upgradeDiffs;
`,
);

await writeDtsFile(
frameworkIndexDtsPath,
`
Expand All @@ -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<string, Record<string, SourceFile[]>>,
): Record<string, Record<string, UpgradeDiff>> {
const result: Record<string, Record<string, UpgradeDiff>> = {};
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<string, UpgradeDiff> = {};
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(" "));
}
Expand Down
79 changes: 79 additions & 0 deletions build/lib/upgradeDiff.test.ts
Original file line number Diff line number Diff line change
@@ -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: "<h1>{{this.name}}</h1>\n" },
{ fileName: "name.js", content: "export default class Name {}\n" },
];
const newFiles = [
{
fileName: "name.gjs",
content: "export default class Name {}\n<template><h1>x</h1></template>\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: {} });
});
});
124 changes: 124 additions & 0 deletions build/lib/upgradeDiff.ts
Original file line number Diff line number Diff line change
@@ -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<string, number[]>;

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 };
}
14 changes: 11 additions & 3 deletions build/redirects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading