diff --git a/README.ja.md b/README.ja.md index 1bab6bd..a6859ae 100644 --- a/README.ja.md +++ b/README.ja.md @@ -4,9 +4,13 @@ **GitHubのリポジトリを3Dの街にして、その歴史を再生する。** -リポジトリを入れると、コードがブラウザの中で街になります。フォルダは区画、ファイルはビルで、大きいファイルほど高いビルになります。街を見て回り、ビルをクリックすると、そのファイルをGitHubで開けます。 +リポジトリを入れると、コードがブラウザの中で街になります。フォルダは区画、ファイルはビルで、何度も編集されたファイルほど高いビルに、大きいファイルほど広い敷地になります。街を見て回り、ビルをクリックすると、そのファイルをGitHubで開けます。 -![three.js の街](docs/screenshot.png) +![express の街](docs/screenshot.png) + +| vitejs/vite | 夕暮れの express | +|---|---| +| ![vite の街](docs/screenshot-vite.png) | ![夕暮れの express](docs/screenshot-dusk.png) | > 状態:v0.1。今のリポジトリの姿を街にします。コミット履歴の再生は次の版で入れます(ロードマップ参照)。 @@ -14,13 +18,23 @@ | 街 | リポジトリ | |---|---| -| 区画(一段高い台) | フォルダ。深いフォルダほど高い位置にある | +| 区画(一段高い台) | フォルダ。深いフォルダほど高い位置にあり、奥に行くほど道が細くなる | | ビル | ファイル | -| 高さ | ファイルサイズ(対数。巨大なファイル1つで他が見えなくならないように) | -| 敷地の広さ | これもファイルサイズだが、差はずっと小さい。街の印象は高さで決まる | -| 色 | ファイルの種類(JS/TS、Python、ドキュメント、設定など) | +| 高さ | そのファイルを編集したコミットの数(対数:1回で3階、10回で9階、100回で17階、1000回で25階) | +| 敷地の広さ | リポジトリ全体に対するファイルサイズの割合。既定の **Balanced** は平方根を使い、大きな画像やロックファイル数個で街の半分が空き地にならないようにする。**Exact share** はそのままの割合 | +| 建物の種類 | ファイルの種類(下の表) | +| 色 | 実際の街のような塗装。テーマの色見本から、ビルごとに壁と屋根の色を選ぶので、色分けの図ではなく本物の街っぽく見える | + +| 建物 | ファイル | +|---|---| +| ガラスのタワー | C、C++、Rust、Go、Swift、C#、Java、Kotlin、Scala | +| オフィスビル | JavaScript、TypeScript、Python、HTML/CSS、Ruby、PHP、シェル | +| 三角屋根の家 | ドキュメント:Markdown、テキスト | +| 倉庫 | データと設定:JSON、YAML、TOML、ロックファイル、SQL | +| レンガのホール | 画像、フォント、音声、動画 | +| 小屋 | その他 | -区画の配置には squarified treemap を使い、すべてのビルを1つのインスタンスメッシュで描くので、数万ファイルのリポジトリでも滑らかに動きます。 +編集回数はファイル名の変更を追いかけるので、移動したファイルも履歴を引き継ぎます。区画の配置には squarified treemap を使い、窓はシェーダーで描き(テクスチャなし)、建物の種類ごとに1つのインスタンスメッシュで描くので、数万ファイルのリポジトリでも滑らかに動きます。 ## 使い方 @@ -34,14 +48,30 @@ https://keito118.github.io/commit-city/?repo=mrdoob/three.js&theme=cyberpunk または、入力欄に `owner/repo`(GitHubのURLでも可)を入れます。URLも一緒に変わるので、見ている街をそのまま共有できます。 - ドラッグで回転、右ドラッグで移動、スクロールでズーム -- ビルをクリックすると、パスとサイズ、ファイルへのリンクが出る +- ビルをクリックすると、編集回数、サイズ、リポジトリ内の割合、最後の編集日と、ファイルへのリンクが出る - **Theme** で見た目を選べる -使えるのは公開リポジトリだけです。GitHubの認証なしAPIを使うので、1つのIPから1時間に60回までです(街1つで2回使います)。 +### 編集回数の集め方 + +GitHubのAPIでは、どのファイルが変わったかはコミットを1つずつ聞かないと分からないので、高さにはコミット1つにつき1回のリクエストがかかります。 + +| 方法 | 読む履歴 | メモ | +|---|---|---| +| トークンなし | 直近25コミット | トークンなしは1時間に60回までなので、高さは目安 | +| GitHubトークン(**GitHub token** 欄) | 直近400コミット | 自分のPrivateリポジトリも開ける。トークンはブラウザの中にだけ保存。読み取り専用の **Contents** 権限だけの fine-grained token で十分 | +| `npm run scan` | 全履歴 | 手元のクローンを読むので、APIを使わない。大きいリポジトリやPrivateリポジトリにおすすめ | + +スキャナーの使い方: + +```bash +npm run scan -- path/to/your/repo > my-repo.city.json +``` + +できたファイルを **Open snapshot** で開く(ページにドロップしてもよい)。Node.js 22.18 以上が必要です。 ## テーマ -見た目は配置とは切り離した「着せ替え」です。v0.1 には **Daylight** と **Cyberpunk** があります。テーマは [`src/themes.ts`](src/themes.ts) の1項目で、空、地面、区画の色、ファイルの種類ごとの色、ビルの光り具合を決めます。日本の町並みや西洋の旧市街も追加予定です。 +見た目は配置とは切り離した「着せ替え」です。今は **Daylight**(昼)、**Dusk**(夕暮れ)、**Cyberpunk** の3つがあります。テーマは [`src/themes.ts`](src/themes.ts) の1項目で、空、芝生、道路と歩道、建物の種類ごとの壁と屋根の色、窓の色、明かりのついた窓の割合、光の当たり方を決めます。日本の町並みや西洋の旧市街も追加予定です。 ## 手元で動かす @@ -50,6 +80,7 @@ npm install npm run dev # http://localhost:5173/?repo=vitejs/vite npm test npm run build # dist/ に静的サイトを出力 +npm run scan -- ../some-repo > some-repo.city.json ``` TypeScript、[Three.js](https://threejs.org/)、[d3-hierarchy](https://github.com/d3/d3-hierarchy)(treemap)、Vite で作っています。サーバーはなく、すべてブラウザで動きます。 diff --git a/README.md b/README.md index eabb0e6..b02745a 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,13 @@ English | [日本語](README.ja.md) **Turn any GitHub repository into a 3D city and replay its history.** -Paste a repository and its code becomes a city in your browser: folders are districts, files are buildings, and bigger files are taller. Fly around, click a building, and jump to that file on GitHub. +Paste a repository and its code becomes a city in your browser: folders are districts, files are buildings, files edited often grow into towers, and big files take up more ground. Fly around, click a building, and jump to that file on GitHub. -![three.js as a city](docs/screenshot.png) +![express as a city](docs/screenshot.png) + +| vitejs/vite | express at dusk | +|---|---| +| ![vite as a city](docs/screenshot-vite.png) | ![express at dusk](docs/screenshot-dusk.png) | > Status: v0.1. The city shows the repository as it is today. Replaying the commit history is next (see the roadmap). @@ -14,13 +18,23 @@ Paste a repository and its code becomes a city in your browser: folders are dist | In the city | In the repository | |---|---| -| District (raised plate) | Folder. Deeper folders sit higher. | +| District (raised plate) | Folder. Deeper folders sit higher; streets get narrower the deeper you go. | | Building | File | -| Height | File size (log scale, so one huge bundle doesn't hide everything else) | -| Footprint | Also file size, but much flatter, so the skyline does the talking | -| Color | Kind of file (JS/TS, Python, docs, config, ...) | +| Height | How many commits edited the file (log scale: 1 edit = 3 floors, 10 = 9, 100 = 17, 1000 = 25) | +| Ground | The file's size relative to the whole repository. **Balanced** (default) uses the square root so a few big images or lockfiles don't turn half the city into empty lots; **Exact share** is the plain ratio. | +| Kind of building | Kind of file, see below | +| Color | Real-world paint: each building picks its own wall and roof color from the theme's palette, so the city looks lived in rather than color-coded | + +| Building | Files | +|---|---| +| Glass tower | C, C++, Rust, Go, Swift, C#, Java, Kotlin, Scala | +| Office block | JavaScript, TypeScript, Python, HTML/CSS, Ruby, PHP, shell | +| House with a pitched roof | Docs: Markdown, text | +| Warehouse | Data and config: JSON, YAML, TOML, lockfiles, SQL | +| Brick hall | Images, fonts, audio, video | +| Shed | Everything else | -Districts are laid out with a squarified treemap, and all buildings are drawn as one instanced mesh, so repositories with tens of thousands of files stay smooth. +Edit counts follow renames, so a file that moved keeps its history. Districts are laid out with a squarified treemap, windows are drawn in a shader (no textures), and each kind of building is one instanced mesh, so repositories with tens of thousands of files stay smooth. ## Use it @@ -34,14 +48,30 @@ https://keito118.github.io/commit-city/?repo=mrdoob/three.js&theme=cyberpunk Or type `owner/repo` (or a GitHub URL) into the box. The URL updates as you go, so you can share the exact city you're looking at. - Drag to orbit, right-drag to pan, scroll to zoom. -- Click a building to see its path and size, with a link to the file. +- Click a building to see its edits, size, share of the repository and last edit, with a link to the file. - Pick a look from **Theme**. -Only public repositories work, through GitHub's unauthenticated API (60 requests an hour per IP; each city costs 2). +### Where the edit counts come from + +GitHub's API doesn't say which files a commit changed until you ask for that commit, so heights cost one request per commit: + +| Source | History read | Notes | +|---|---|---| +| No token | Latest 25 commits | GitHub allows 60 requests an hour without a token, so heights are only a hint | +| GitHub token (under **GitHub token**) | Latest 400 commits | Also opens your private repositories. Stored only in your browser. A fine-grained token with read-only **Contents** access is enough | +| `npm run scan` | Whole history | Reads a local clone, no API at all. Best for big or private repositories | + +To use the scanner: + +```bash +npm run scan -- path/to/your/repo > my-repo.city.json +``` + +Then click **Open snapshot** (or drop the file onto the page). Needs Node.js 22.18 or later. ## Themes -The look is a swappable skin, separate from the layout. v0.1 ships **Daylight** and **Cyberpunk**. A theme is one entry in [`src/themes.ts`](src/themes.ts): sky, ground, district colors, a color per file kind, and how much the buildings glow. Japanese streets and a European old town are planned. +The look is a swappable skin, separate from the layout. There are three for now: **Daylight**, **Dusk** and **Cyberpunk**. A theme is one entry in [`src/themes.ts`](src/themes.ts): sky, grass, roads and sidewalks, wall and roof colors for each kind of building, window colors, how many windows are lit, and lighting. Japanese streets and a European old town are planned. ## Run locally @@ -50,6 +80,7 @@ npm install npm run dev # http://localhost:5173/?repo=vitejs/vite npm test npm run build # static site in dist/ +npm run scan -- ../some-repo > some-repo.city.json ``` Built with TypeScript, [Three.js](https://threejs.org/), [d3-hierarchy](https://github.com/d3/d3-hierarchy) (treemap) and Vite. No server: everything runs in the browser. diff --git a/docs/screenshot-cyberpunk.png b/docs/screenshot-cyberpunk.png deleted file mode 100644 index 4c4ada8..0000000 Binary files a/docs/screenshot-cyberpunk.png and /dev/null differ diff --git a/docs/screenshot-dusk.png b/docs/screenshot-dusk.png new file mode 100644 index 0000000..00bab1b Binary files /dev/null and b/docs/screenshot-dusk.png differ diff --git a/docs/screenshot-vite.png b/docs/screenshot-vite.png new file mode 100644 index 0000000..f2faf42 Binary files /dev/null and b/docs/screenshot-vite.png differ diff --git a/docs/screenshot.png b/docs/screenshot.png index 39a9558..200b120 100644 Binary files a/docs/screenshot.png and b/docs/screenshot.png differ diff --git a/index.html b/index.html index 3a167bb..1ee3844 100644 --- a/index.html +++ b/index.html @@ -18,6 +18,20 @@

commit-city

+ + +
+
+ GitHub token (optional) +

Without a token, heights come from the latest 25 commits. A token reads up to 400 and opens private repositories. It is kept only in this browser.

+ +
+
Try: vite · three.js · express

diff --git a/package-lock.json b/package-lock.json index f51acaa..6456f56 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,23 +1,27 @@ { "name": "commit-city", - "version": "1.0.0", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "commit-city", - "version": "1.0.0", - "license": "ISC", + "version": "0.1.0", + "license": "MIT", "dependencies": { "d3-hierarchy": "^3.1.2", "three": "^0.186.1" }, "devDependencies": { "@types/d3-hierarchy": "^3.1.7", + "@types/node": "^26.6.5", "@types/three": "^0.186.0", "typescript": "^7.0.2", "vite": "^8.3.4", "vitest": "^5.0.5" + }, + "engines": { + "node": ">=22.18" } }, "node_modules/@dimforge/rapier3d-compat": { @@ -366,6 +370,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/node": { + "version": "26.6.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz", + "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, "node_modules/@types/stats.js": { "version": "0.17.4", "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", @@ -1368,6 +1382,13 @@ "@typescript/typescript-win32-x64": "7.0.2" } }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, "node_modules/vite": { "version": "8.3.4", "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz", diff --git a/package.json b/package.json index 429a96e..2bd996e 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,8 @@ "dev": "vite", "build": "tsc --noEmit && vite build", "preview": "vite preview", - "test": "vitest run" + "test": "vitest run", + "scan": "node scripts/scan.ts" }, "dependencies": { "d3-hierarchy": "^3.1.2", @@ -17,9 +18,13 @@ }, "devDependencies": { "@types/d3-hierarchy": "^3.1.7", + "@types/node": "^26.6.5", "@types/three": "^0.186.0", "typescript": "^7.0.2", "vite": "^8.3.4", "vitest": "^5.0.5" + }, + "engines": { + "node": ">=22.18" } } diff --git a/scripts/scan.ts b/scripts/scan.ts new file mode 100644 index 0000000..693b189 --- /dev/null +++ b/scripts/scan.ts @@ -0,0 +1,67 @@ +// Reads a local git repository and writes a commit-city snapshot (JSON) to stdout. +// +// npm run scan -- path/to/repo > my-repo.city.json +// +// Then open the city page and drop the file onto it. Works for private +// repositories too, and reads the whole history without touching the GitHub API. + +import { execFileSync } from "node:child_process"; +import { basename, resolve } from "node:path"; +import { countEdits, type ChangeStatus, type CitySnapshot, type CommitChanges } from "../src/history.ts"; + +const repoDir = resolve(process.argv[2] ?? "."); +const git = (...args: string[]) => + execFileSync("git", ["-C", repoDir, ...args], { encoding: "utf8", maxBuffer: 1 << 30 }); + +const branch = git("rev-parse", "--abbrev-ref", "HEAD").trim(); + +const sizes = new Map(); +for (const line of git("ls-tree", "-r", "-l", "-z", "HEAD").split("\0")) { + // " blob \t" + const match = line.match(/^\d+ blob \w+ +(\d+)\t(.*)$/s); + if (match) sizes.set(match[2], Number(match[1])); +} + +const commits: CommitChanges[] = []; +const log = git("log", "--no-merges", "-M", "--name-status", "-z", "--format=%x01%at", "HEAD"); +for (const chunk of log.split("\x01").slice(1)) { + const fields = chunk.split("\0"); + const time = Number(fields[0].trim()); + const changes: CommitChanges["changes"] = []; + for (let i = 1; i < fields.length; ) { + const status = fields[i].trim(); + if (!status) { + i++; + continue; + } + if (status.startsWith("R") || status.startsWith("C")) { + changes.push({ status: status[0] === "R" ? "R" : "A", from: fields[i + 1], path: fields[i + 2] }); + i += 3; + } else { + changes.push({ status: status[0] as ChangeStatus, path: fields[i + 1] }); + i += 2; + } + } + commits.push({ time, changes }); +} + +const edits = countEdits(commits, sizes.keys()); +let origin = ""; +try { + origin = git("remote", "get-url", "origin").trim(); +} catch { + // No remote: links to GitHub are simply left out. +} +const github = origin.match(/github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?$/); + +const snapshot: CitySnapshot = { + format: "commit-city/1", + repo: github?.[1], + name: github?.[1] ?? basename(repoDir), + branch, + files: [...sizes].map(([path, size]) => ({ path, size, ...edits.get(path)! })), + commitsScanned: commits.length, + partialHistory: git("rev-parse", "--is-shallow-repository").trim() === "true", +}; +process.stdout.write(JSON.stringify(snapshot)); +process.stderr.write(`${snapshot.name}: ${snapshot.files.length} files, ${commits.length} commits\n`); diff --git a/src/city.ts b/src/city.ts index fc628ef..b51983e 100644 --- a/src/city.ts +++ b/src/city.ts @@ -1,22 +1,49 @@ import * as THREE from "three"; import { OrbitControls } from "three/addons/controls/OrbitControls.js"; -import type { Building, CityLayout } from "./layout"; +import { FLOOR_HEIGHT, PLATE_HEIGHT, type Building, type CityLayout } from "./layout"; +import type { BuildingKind } from "./languages"; import type { Theme } from "./themes"; -/** Draws a CityLayout. All buildings share one InstancedMesh so big repos stay fast. */ +/** How each kind of building is shaped: its window grid and its roof. */ +interface KindStyle { + /** Window grid; null for windowless buildings. */ + windows: { spacing: number; marginU: number; bottom: number; top: number } | null; + roof: "flat" | "gable" | "flat-with-unit"; + roughness: number; + metalness: number; +} + +const STYLES: Record = { + tower: { windows: { spacing: 2.2, marginU: 0.05, bottom: 0.08, top: 0.92 }, roof: "flat-with-unit", roughness: 0.45, metalness: 0.3 }, + office: { windows: { spacing: 3.0, marginU: 0.2, bottom: 0.3, top: 0.8 }, roof: "flat-with-unit", roughness: 0.85, metalness: 0 }, + house: { windows: { spacing: 4.2, marginU: 0.3, bottom: 0.35, top: 0.75 }, roof: "gable", roughness: 0.9, metalness: 0 }, + warehouse: { windows: null, roof: "flat", roughness: 0.7, metalness: 0.15 }, + hall: { windows: { spacing: 3.6, marginU: 0.28, bottom: 0.15, top: 0.85 }, roof: "flat", roughness: 0.9, metalness: 0 }, + shed: { windows: null, roof: "flat", roughness: 0.9, metalness: 0 }, +}; + +/** Shared by every window shader, so changing the theme needs no recompiling. */ +const windowUniforms = { + cityGlass: { value: new THREE.Color() }, + cityLitA: { value: new THREE.Color() }, + cityLitB: { value: new THREE.Color() }, + cityLitShare: { value: 0 }, + cityGlow: { value: 0 }, +}; + +/** Draws a CityLayout. Each building kind is one InstancedMesh, so big repositories stay fast. */ export class CityView { private renderer: THREE.WebGLRenderer; private scene = new THREE.Scene(); private camera: THREE.PerspectiveCamera; private controls: OrbitControls; - private ambient = new THREE.HemisphereLight(0xffffff, 0x444444, 1); - private sun = new THREE.DirectionalLight(0xffffff, 1); - private ground: THREE.Mesh; + private ambient = new THREE.HemisphereLight(); + private sun = new THREE.DirectionalLight(); + private grass: THREE.Mesh; + private asphalt: THREE.Mesh; private cityGroup = new THREE.Group(); - private buildingMesh: THREE.InstancedMesh | null = null; - private districtMesh: THREE.InstancedMesh | null = null; + private pickables: THREE.InstancedMesh[] = []; private highlight: THREE.LineSegments; - private emissive = { value: 0 }; private layout: CityLayout | null = null; private theme: Theme; @@ -24,24 +51,31 @@ export class CityView { this.theme = theme; this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true }); this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); + this.renderer.shadowMap.enabled = true; + this.renderer.shadowMap.type = THREE.PCFShadowMap; + this.renderer.toneMapping = THREE.ACESFilmicToneMapping; container.appendChild(this.renderer.domElement); - this.camera = new THREE.PerspectiveCamera(45, 1, 1, 5000); - this.camera.position.set(320, 260, 320); + this.camera = new THREE.PerspectiveCamera(40, 1, 1, 20000); this.controls = new OrbitControls(this.camera, this.renderer.domElement); this.controls.enableDamping = true; - this.controls.maxPolarAngle = Math.PI * 0.48; + this.controls.maxPolarAngle = Math.PI * 0.47; - this.sun.position.set(-200, 400, 150); - this.scene.add(this.ambient, this.sun, this.cityGroup); + this.sun.castShadow = true; + this.sun.shadow.mapSize.set(4096, 4096); + this.sun.shadow.bias = -0.0004; + this.sun.shadow.normalBias = 0.4; + this.scene.add(this.ambient, this.sun, this.sun.target, this.cityGroup); - this.ground = new THREE.Mesh( - new THREE.PlaneGeometry(4000, 4000), - new THREE.MeshLambertMaterial({ color: 0xffffff }), - ); - this.ground.rotation.x = -Math.PI / 2; - this.ground.position.y = -0.05; - this.scene.add(this.ground); + this.grass = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.MeshLambertMaterial()); + this.grass.rotation.x = -Math.PI / 2; + this.grass.position.y = -0.1; + this.grass.receiveShadow = true; + this.asphalt = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.MeshStandardMaterial({ roughness: 0.95 })); + this.asphalt.rotation.x = -Math.PI / 2; + this.asphalt.position.y = -0.02; + this.asphalt.receiveShadow = true; + this.scene.add(this.grass, this.asphalt); this.highlight = new THREE.LineSegments( new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1).translate(0, 0.5, 0)), @@ -69,49 +103,35 @@ export class CityView { this.layout = layout; this.clear(); this.highlight.visible = false; + const { extent } = layout; - const box = new THREE.BoxGeometry(1, 1, 1).translate(0, 0.5, 0); - const matrix = new THREE.Matrix4(); - const color = new THREE.Color(); + this.grass.scale.set(extent * 12, extent * 12, 1); + this.asphalt.scale.set(extent + 16, extent + 16, 1); + this.fitSun(extent); - const districts = new THREE.InstancedMesh( - box, - new THREE.MeshLambertMaterial({ color: 0xffffff }), - Math.max(layout.districts.length, 1), - ); - districts.count = layout.districts.length; - layout.districts.forEach((d, i) => { - // Deeper folders sit on slightly raised plates so nesting is visible. - const plate = 0.25; - matrix.makeScale(d.width, plate, d.length).setPosition(d.x, (d.depth - 1) * plate, d.z); - districts.setMatrixAt(i, matrix); - const palette = this.theme.districts; - districts.setColorAt(i, color.set(palette[Math.min(d.depth - 1, palette.length - 1)])); - }); - - const buildings = new THREE.InstancedMesh(box, this.buildingMaterial(), Math.max(layout.buildings.length, 1)); - buildings.count = layout.buildings.length; - layout.buildings.forEach((b, i) => { - matrix.makeScale(b.width, b.height, b.depth).setPosition(b.x, this.baseOf(b), b.z); - buildings.setMatrixAt(i, matrix); - buildings.setColorAt(i, color.set(this.theme.buildings[b.language])); - }); - - this.districtMesh = districts; - this.buildingMesh = buildings; - this.cityGroup.add(districts, buildings); + this.addPlates(layout); + const byKind = new Map(); + for (const b of layout.buildings) { + const list = byKind.get(b.kind) ?? []; + list.push(b); + byKind.set(b.kind, list); + } + for (const [kind, buildings] of byKind) this.addBuildings(kind, buildings, layout.buildings); if (resetCamera) { - const tallest = layout.buildings.reduce((max, b) => Math.max(max, b.height), 0); - const r = layout.extent * 0.95; - this.camera.position.set(r, r * 0.9 + tallest * 0.5, r); + const r = extent * 1.15; + this.camera.position.set(r * 0.75, r * 0.85 + layout.tallest, r); + this.camera.far = extent * 20; + this.camera.updateProjectionMatrix(); this.controls.target.set(0, 0, 0); + this.controls.maxDistance = extent * 4; } + this.scene.fog = new THREE.Fog(this.theme.sky, extent * 1.4, extent * 5); } /** Returns the building under a screen point, or null. */ pick(clientX: number, clientY: number): Building | null { - if (!this.buildingMesh || !this.layout) return null; + if (!this.layout) return null; const rect = this.renderer.domElement.getBoundingClientRect(); const pointer = new THREE.Vector2( ((clientX - rect.left) / rect.width) * 2 - 1, @@ -119,59 +139,163 @@ export class CityView { ); const raycaster = new THREE.Raycaster(); raycaster.setFromCamera(pointer, this.camera); - const hit = raycaster.intersectObject(this.buildingMesh)[0]; - return hit?.instanceId !== undefined ? this.layout.buildings[hit.instanceId] : null; + const hit = raycaster.intersectObjects(this.pickables, false)[0]; + if (!hit || hit.instanceId === undefined) return null; + const indices = hit.object.userData.buildingIndex as number[]; + return this.layout.buildings[indices[hit.instanceId]]; } select(building: Building | null) { this.highlight.visible = building !== null; if (!building) return; this.highlight.scale.set(building.width * 1.04, building.height * 1.02, building.depth * 1.04); - this.highlight.position.set(building.x, this.baseOf(building), building.z); + this.highlight.position.set(building.x, building.base, building.z); } snapshot(): string { return this.renderer.domElement.toDataURL("image/png"); } - private baseOf(b: Building): number { - const depth = b.path.split("/").length - 1; - return depth * 0.25; + private addPlates(layout: CityLayout) { + const plates = new THREE.InstancedMesh( + new THREE.BoxGeometry(1, 1, 1).translate(0, 0.5, 0), + new THREE.MeshStandardMaterial({ roughness: 0.95 }), + Math.max(layout.districts.length, 1), + ); + plates.count = layout.districts.length; + plates.receiveShadow = true; + const matrix = new THREE.Matrix4(); + const color = new THREE.Color(); + const palette = this.theme.plates; + layout.districts.forEach((d, i) => { + matrix.makeScale(d.width, PLATE_HEIGHT, d.length).setPosition(d.x, (d.depth - 1) * PLATE_HEIGHT, d.z); + plates.setMatrixAt(i, matrix); + plates.setColorAt(i, color.set(palette[Math.min(d.depth - 1, palette.length - 1)])); + }); + this.cityGroup.add(plates); } - private buildingMaterial(): THREE.Material { - const material = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.75, metalness: 0.05 }); - // Lets night themes make buildings glow in their own color. - material.onBeforeCompile = (shader) => { - shader.uniforms.selfGlow = this.emissive; - shader.fragmentShader = shader.fragmentShader - .replace("void main() {", "uniform float selfGlow;\nvoid main() {") - .replace( - "#include ", - "#include \ntotalEmissiveRadiance += diffuseColor.rgb * selfGlow;", + private addBuildings(kind: BuildingKind, buildings: Building[], all: Building[]) { + const style = STYLES[kind]; + const colors = this.theme.kinds[kind]; + const indexOf = new Map(all.map((b, i) => [b, i])); + + // Body: a unit box standing on y = 0, with a per-instance seed for window lighting. + const bodyGeometry = new THREE.BoxGeometry(1, 1, 1).translate(0, 0.5, 0); + bodyGeometry.setAttribute( + "citySeed", + new THREE.InstancedBufferAttribute(new Float32Array(buildings.map((b) => (b.seed % 997) / 997)), 1), + ); + const body = new THREE.InstancedMesh(bodyGeometry, buildingMaterial(style), buildings.length); + body.castShadow = body.receiveShadow = true; + body.userData.buildingIndex = buildings.map((b) => indexOf.get(b)!); + + const roofGeometry = style.roof === "gable" ? gableGeometry() : new THREE.BoxGeometry(1, 1, 1).translate(0, 0.5, 0); + const roof = new THREE.InstancedMesh( + roofGeometry, + new THREE.MeshStandardMaterial({ roughness: 0.8, flatShading: style.roof === "gable" }), + buildings.length, + ); + roof.castShadow = roof.receiveShadow = true; + + const withUnit = style.roof === "flat-with-unit"; + const units = withUnit + ? new THREE.InstancedMesh( + new THREE.BoxGeometry(1, 1, 1).translate(0, 0.5, 0), + new THREE.MeshStandardMaterial({ roughness: 0.7, color: 0x8b8f93 }), + buildings.length, + ) + : null; + if (units) units.castShadow = true; + + const matrix = new THREE.Matrix4(); + const rotation = new THREE.Quaternion(); + const yAxis = new THREE.Vector3(0, 1, 0); + const color = new THREE.Color(); + buildings.forEach((b, i) => { + matrix.makeScale(b.width, b.height, b.depth).setPosition(b.x, b.base, b.z); + body.setMatrixAt(i, matrix); + // A little light/dark variation, so neighbours with the same paint still differ. + const shade = (((b.seed >>> 16) % 11) - 5) * 0.012; + body.setColorAt(i, color.set(colors.walls[b.seed % colors.walls.length]).offsetHSL(0, 0, shade)); + + const top = b.base + b.height; + if (style.roof === "gable") { + // Ridge runs along the longer side. + const alongX = b.width >= b.depth; + const span = alongX ? b.depth : b.width; + rotation.setFromAxisAngle(yAxis, alongX ? 0 : Math.PI / 2); + matrix.compose( + new THREE.Vector3(b.x, top, b.z), + rotation, + new THREE.Vector3((alongX ? b.width : b.depth) * 1.04, Math.min(span * 0.45, FLOOR_HEIGHT * 2), span * 1.08), ); - }; - return material; + } else { + matrix.makeScale(b.width * 1.02, 0.5, b.depth * 1.02).setPosition(b.x, top, b.z); + } + roof.setMatrixAt(i, matrix); + roof.setColorAt(i, color.set(colors.roofs[(b.seed >>> 8) % colors.roofs.length])); + + if (units) { + // A small machine room on the roof, offset a little so rooftops don't all look the same. + const size = Math.min(b.width, b.depth) * 0.3; + const dx = (((b.seed >>> 4) % 5) - 2) * 0.1 * b.width; + const dz = (((b.seed >>> 12) % 5) - 2) * 0.1 * b.depth; + matrix.makeScale(size, Math.min(size, FLOOR_HEIGHT * 0.8), size).setPosition(b.x + dx, top + 0.5, b.z + dz); + units.setMatrixAt(i, matrix); + } + }); + + this.cityGroup.add(body, roof); + if (units) this.cityGroup.add(units); + this.pickables.push(body); + } + + private fitSun(extent: number) { + const { elevation } = this.theme.sun; + const distance = extent * 1.5; + this.sun.position.set(-distance * 0.6, distance * Math.max(elevation, 0.15), distance * 0.45); + this.sun.target.position.set(0, 0, 0); + const cam = this.sun.shadow.camera; + const half = extent * 0.75; + cam.left = -half; + cam.right = half; + cam.top = half; + cam.bottom = -half; + cam.near = 1; + cam.far = distance * 4; + cam.updateProjectionMatrix(); } private applyTheme(theme: Theme) { this.scene.background = new THREE.Color(theme.sky); - this.scene.fog = new THREE.Fog(theme.fog, 600, 1800); - (this.ground.material as THREE.MeshLambertMaterial).color.set(theme.ground); - this.ambient.intensity = theme.ambient * 2; - this.sun.intensity = theme.sun; - this.emissive.value = theme.emissive; + if (this.scene.fog instanceof THREE.Fog) this.scene.fog.color.set(theme.sky); + (this.grass.material as THREE.MeshLambertMaterial).color.set(theme.ground); + (this.asphalt.material as THREE.MeshStandardMaterial).color.set(theme.road); + this.ambient.color.set(theme.ambient.sky); + this.ambient.groundColor.set(theme.ambient.ground); + this.ambient.intensity = theme.ambient.intensity; + this.sun.color.set(theme.sun.color); + this.sun.intensity = theme.sun.intensity; + this.sun.castShadow = theme.shadows; + this.renderer.toneMappingExposure = theme.exposure; + windowUniforms.cityGlass.value.set(theme.windows.glass); + windowUniforms.cityLitA.value.set(theme.windows.lit[0]); + windowUniforms.cityLitB.value.set(theme.windows.lit[1]); + windowUniforms.cityLitShare.value = theme.windows.litShare; + windowUniforms.cityGlow.value = theme.windows.glow; + if (this.layout) this.fitSun(this.layout.extent); } private clear() { - for (const mesh of [this.buildingMesh, this.districtMesh]) { - if (!mesh) continue; + for (const object of [...this.cityGroup.children]) { + const mesh = object as THREE.InstancedMesh; this.cityGroup.remove(mesh); mesh.geometry.dispose(); (mesh.material as THREE.Material).dispose(); mesh.dispose(); } - this.buildingMesh = this.districtMesh = null; + this.pickables = []; } private resize() { @@ -182,3 +306,112 @@ export class CityView { this.camera.updateProjectionMatrix(); } } + +/** A unit prism: base 1 x 1 on y = 0, ridge along x at y = 1. */ +function gableGeometry(): THREE.BufferGeometry { + const a = [-0.5, 0, -0.5]; + const b = [0.5, 0, -0.5]; + const c = [0.5, 0, 0.5]; + const d = [-0.5, 0, 0.5]; + const e = [-0.5, 1, 0]; + const f = [0.5, 1, 0]; + const triangles = [ + [a, f, b], [a, e, f], // slope facing -z + [d, c, f], [d, f, e], // slope facing +z + [a, d, e], // gable end at -x + [b, f, c], // gable end at +x + ]; + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(triangles.flat(2), 3)); + geometry.computeVertexNormals(); + return geometry; +} + +/** + * Walls with a window grid drawn in the shader: no textures, and the grid + * follows each building's real size so windows stay the same size everywhere. + */ +function buildingMaterial(style: KindStyle): THREE.Material { + const material = new THREE.MeshStandardMaterial({ roughness: style.roughness, metalness: style.metalness }); + const w = style.windows; + if (!w) return material; + + material.onBeforeCompile = (shader) => { + Object.assign(shader.uniforms, windowUniforms); + shader.vertexShader = shader.vertexShader + .replace( + "void main() {", + `attribute float citySeed; +varying vec3 cityLocal; +varying vec3 citySize; +varying vec3 cityNormal; +varying float citySeedV; +void main() {`, + ) + .replace( + "#include ", + `#include +cityLocal = position; +cityNormal = normal; +citySeedV = citySeed; +citySize = vec3(length(instanceMatrix[0].xyz), length(instanceMatrix[1].xyz), length(instanceMatrix[2].xyz));`, + ); + shader.fragmentShader = shader.fragmentShader + .replace( + "void main() {", + `uniform vec3 cityGlass; +uniform vec3 cityLitA; +uniform vec3 cityLitB; +uniform float cityLitShare; +uniform float cityGlow; +varying vec3 cityLocal; +varying vec3 citySize; +varying vec3 cityNormal; +varying float citySeedV; +float cityHash(vec3 p) { + p = fract(p * vec3(0.1031, 0.1030, 0.0973)); + p += dot(p, p.yxz + 33.33); + return fract((p.x + p.y) * p.z); +} +void main() { + float cityWindow = 0.0; + vec3 cityLight = vec3(0.0);`, + ) + .replace( + "#include ", + `#include +if (abs(cityNormal.y) < 0.5) { + bool sideX = abs(cityNormal.x) > 0.5; + float faceWidth = sideX ? citySize.z : citySize.x; + float u = (sideX ? cityLocal.z : cityLocal.x) + 0.5; + float columns = max(1.0, floor(faceWidth / ${w.spacing.toFixed(2)})); + float column = floor(u * columns); + float cellU = fract(u * columns); + float y = cityLocal.y * citySize.y / ${FLOOR_HEIGHT.toFixed(2)}; + float storey = floor(y); + float cellV = fract(y); + cityWindow = step(${w.marginU.toFixed(2)}, cellU) * step(cellU, ${(1 - w.marginU).toFixed(2)}) + * step(${w.bottom.toFixed(2)}, cellV) * step(cellV, ${w.top.toFixed(2)}); + float face = sideX ? sign(cityNormal.x) : 2.0 * sign(cityNormal.z); + float h = cityHash(vec3(column + face * 31.0, storey, citySeedV * 997.0)); + vec3 lit = mix(cityLitA, cityLitB, step(0.5, fract(h * 13.7))); + float isLit = step(h, cityLitShare); + diffuseColor.rgb = mix(diffuseColor.rgb, mix(cityGlass, lit * 0.6, isLit * step(0.01, cityGlow)), cityWindow); + cityLight = lit * isLit * cityWindow * cityGlow; +}`, + ) + .replace( + "#include ", + `#include +roughnessFactor = mix(roughnessFactor, 0.2, cityWindow);`, + ) + .replace( + "#include ", + `#include +totalEmissiveRadiance += cityLight;`, + ); + }; + // Same program for every material of this style, different from plain walls. + material.customProgramCacheKey = () => `city-windows-${w.spacing}-${w.marginU}-${w.bottom}-${w.top}`; + return material; +} diff --git a/src/github.ts b/src/github.ts index 6d51884..222a4db 100644 --- a/src/github.ts +++ b/src/github.ts @@ -1,18 +1,10 @@ -export interface RepoFile { - path: string; - size: number; -} - -export interface RepoSnapshot { - owner: string; - name: string; - branch: string; - files: RepoFile[]; - truncated: boolean; -} +import { countEdits, type ChangeStatus, type CitySnapshot, type CommitChanges } from "./history"; const API = "https://api.github.com"; +/** How many commits to read for edit counts. Each one costs an API request. */ +export const COMMIT_LIMIT = { withToken: 400, withoutToken: 25 }; + /** Accepts "owner/name" or a github.com URL. Returns null when it can't tell. */ export function parseRepo(input: string): { owner: string; name: string } | null { const trimmed = input.trim().replace(/\.git$/, "").replace(/\/+$/, ""); @@ -23,26 +15,93 @@ export function parseRepo(input: string): { owner: string; name: string } | null return { owner: match[1], name: match[2] }; } -async function getJson(url: string): Promise { - const res = await fetch(url, { headers: { Accept: "application/vnd.github+json" } }); - if (res.status === 404) throw new Error("Repository not found (or it is private)."); - if (res.status === 403 || res.status === 429) { - throw new Error("GitHub API rate limit reached. Try again in a while."); +const STATUS: Record = { + added: "A", + copied: "A", + modified: "M", + changed: "M", + removed: "D", + renamed: "R", +}; + +export async function fetchSnapshot( + owner: string, + name: string, + options: { token?: string; onProgress?: (text: string) => void } = {}, +): Promise { + const headers: Record = { Accept: "application/vnd.github+json" }; + if (options.token) headers.Authorization = `Bearer ${options.token}`; + + async function getJson(path: string): Promise { + const res = await fetch(`${API}${path}`, { headers }); + if (res.status === 401) throw new Error("The GitHub token was rejected."); + if (res.status === 404) throw new Error("Repository not found (private repositories need a token)."); + if (res.status === 403 || res.status === 429) { + throw new Error("GitHub API rate limit reached. Add a token, or try again later."); + } + if (!res.ok) throw new Error(`GitHub API error: ${res.status}`); + return res.json() as Promise; } - if (!res.ok) throw new Error(`GitHub API error: ${res.status}`); - return res.json() as Promise; -} -export async function fetchSnapshot(owner: string, name: string): Promise { - const repo = await getJson<{ default_branch: string }>(`${API}/repos/${owner}/${name}`); + const repoPath = `/repos/${owner}/${name}`; + const repo = await getJson<{ default_branch: string }>(repoPath); const branch = repo.default_branch; - const tree = await getJson<{ - tree: { path: string; type: string; size?: number }[]; - truncated: boolean; - }>(`${API}/repos/${owner}/${name}/git/trees/${encodeURIComponent(branch)}?recursive=1`); - - const files = tree.tree - .filter((entry) => entry.type === "blob") - .map((entry) => ({ path: entry.path, size: entry.size ?? 0 })); - return { owner, name, branch, files, truncated: tree.truncated }; + const tree = await getJson<{ tree: { path: string; type: string; size?: number }[]; truncated: boolean }>( + `${repoPath}/git/trees/${encodeURIComponent(branch)}?recursive=1`, + ); + const blobs = tree.tree.filter((entry) => entry.type === "blob"); + + // The commit list doesn't say which files changed, so each commit is fetched on its own. + const limit = options.token ? COMMIT_LIMIT.withToken : COMMIT_LIMIT.withoutToken; + const shas: string[] = []; + for (let page = 1; shas.length < limit; page++) { + const perPage = Math.min(100, limit); + const list = await getJson<{ sha: string; parents: unknown[] }[]>( + `${repoPath}/commits?sha=${encodeURIComponent(branch)}&per_page=${perPage}&page=${page}`, + ); + shas.push(...list.filter((c) => c.parents.length < 2).map((c) => c.sha)); + if (list.length < perPage) break; + } + const reachedEnd = shas.length < limit; + shas.length = Math.min(shas.length, limit); + + const commits: CommitChanges[] = new Array(shas.length); + let done = 0; + await runPool(shas, 8, async (sha, i) => { + const detail = await getJson<{ + commit: { author: { date: string } }; + files?: { filename: string; status: string; previous_filename?: string }[]; + }>(`${repoPath}/commits/${sha}`); + commits[i] = { + time: Math.floor(Date.parse(detail.commit.author.date) / 1000), + changes: (detail.files ?? []).map((f) => ({ + status: STATUS[f.status] ?? "M", + path: f.filename, + from: f.previous_filename, + })), + }; + options.onProgress?.(`Reading commits… ${++done}/${shas.length}`); + }); + + const edits = countEdits(commits, blobs.map((b) => b.path)); + return { + format: "commit-city/1", + repo: `${owner}/${name}`, + name: `${owner}/${name}`, + branch, + files: blobs.map((b) => ({ path: b.path, size: b.size ?? 0, ...edits.get(b.path)! })), + commitsScanned: commits.length, + partialHistory: !reachedEnd || tree.truncated, + }; +} + +async function runPool(items: T[], size: number, task: (item: T, index: number) => Promise) { + let next = 0; + const worker = async () => { + while (next < items.length) { + const index = next++; + await task(items[index], index); + } + }; + await Promise.all(Array.from({ length: Math.min(size, items.length) }, worker)); } diff --git a/src/history.ts b/src/history.ts new file mode 100644 index 0000000..f9be855 --- /dev/null +++ b/src/history.ts @@ -0,0 +1,66 @@ +/** A file as the city sees it: where it is, how big it is, and how often it was edited. */ +export interface RepoFile { + path: string; + size: number; + /** Number of commits that touched this file (following renames). */ + edits: number; + /** Unix seconds of the latest commit that touched it, when known. */ + lastEdited?: number; +} + +/** Everything needed to draw one city. Produced by the GitHub API loader or by `npm run scan`. */ +export interface CitySnapshot { + format: "commit-city/1"; + /** "owner/name" on GitHub, used for links. Absent for local repositories. */ + repo?: string; + name: string; + branch: string; + files: RepoFile[]; + /** How many commits the edit counts are based on. */ + commitsScanned: number; + /** True when only part of the history was read (edit counts are a lower bound). */ + partialHistory: boolean; +} + +export type ChangeStatus = "A" | "M" | "D" | "R"; + +export interface FileChange { + status: ChangeStatus; + path: string; + /** For renames: the path before the commit. */ + from?: string; +} + +export interface CommitChanges { + time: number; + changes: FileChange[]; +} + +/** + * Counts edits per current path. `commits` must be newest first, so a rename + * can send the older history of the old name to the file's current name. + */ +export function countEdits( + commits: CommitChanges[], + currentPaths: Iterable, +): Map { + const result = new Map(); + for (const path of currentPaths) result.set(path, { edits: 0, lastEdited: 0 }); + // Historical path -> path it has today. + const renamedTo = new Map(); + const resolve = (path: string) => renamedTo.get(path) ?? path; + + for (const commit of commits) { + const seen = new Set(); + for (const change of commit.changes) { + const current = resolve(change.path); + if (change.status === "R" && change.from) renamedTo.set(change.from, current); + const entry = result.get(current); + if (!entry || seen.has(current)) continue; + seen.add(current); + entry.edits += 1; + entry.lastEdited = Math.max(entry.lastEdited, commit.time); + } + } + return result; +} diff --git a/src/languages.ts b/src/languages.ts index 18c9af0..01510ea 100644 --- a/src/languages.ts +++ b/src/languages.ts @@ -30,3 +30,29 @@ export function languageOf(path: string): LanguageGroup { if (dot <= 0) return "other"; return GROUPS[base.slice(dot + 1)] ?? "other"; } + +/** The kind of building a file becomes. */ +export type BuildingKind = + | "tower" // compiled languages: glass high-rise + | "office" // scripting and web code: concrete office block + | "house" // docs: house with a pitched roof + | "warehouse" // data and config: windowless warehouse + | "hall" // media: brick hall + | "shed"; // everything else + +const KIND_BY_GROUP: Record = { + systems: "tower", + jvm: "tower", + script: "office", + python: "office", + web: "office", + shell: "office", + docs: "house", + data: "warehouse", + media: "hall", + other: "shed", +}; + +export function buildingKindOf(path: string): BuildingKind { + return KIND_BY_GROUP[languageOf(path)]; +} diff --git a/src/layout.ts b/src/layout.ts index 17095e2..0f56789 100644 --- a/src/layout.ts +++ b/src/layout.ts @@ -1,17 +1,23 @@ import { hierarchy, treemap, treemapSquarify } from "d3-hierarchy"; -import type { RepoFile } from "./github"; -import { languageOf, type LanguageGroup } from "./languages"; +import type { RepoFile } from "./history"; +import { buildingKindOf, languageOf, type BuildingKind, type LanguageGroup } from "./languages"; export interface Building { - path: string; - size: number; + file: RepoFile; language: LanguageGroup; - /** Center on the ground plane, and footprint. */ + kind: BuildingKind; + /** Share of the repository's total size, 0..1. */ + share: number; + floors: number; + /** Center on the ground plane, footprint, height, and the height of the plate it stands on. */ x: number; z: number; width: number; depth: number; height: number; + base: number; + /** Stable per-file number, used to vary colors. */ + seed: number; } export interface District { @@ -28,84 +34,119 @@ export interface CityLayout { districts: District[]; /** Side length of the square city. */ extent: number; + tallest: number; } interface Node { name: string; path: string; - size: number; + file?: RepoFile; children?: Node[]; } +/** World units per floor. */ +export const FLOOR_HEIGHT = 3.2; +/** Thickness of one district plate; nested folders stack. */ +export const PLATE_HEIGHT = 0.3; +/** Average ground per file, so building scale stays the same for small and huge repositories. */ +const GROUND_PER_FILE = 18 * 18; + /** Turns flat file paths into a folder tree. */ export function buildTree(files: RepoFile[]): Node { - const root: Node = { name: "", path: "", size: 0, children: [] }; + const root: Node = { name: "", path: "", children: [] }; + const folders = new Map([["", root]]); for (const file of files) { const parts = file.path.split("/"); let node = root; for (let i = 0; i < parts.length - 1; i++) { const path = parts.slice(0, i + 1).join("/"); - let child = node.children!.find((c) => c.children && c.name === parts[i]); + let child = folders.get(path); if (!child) { - child = { name: parts[i], path, size: 0, children: [] }; + child = { name: parts[i], path, children: [] }; node.children!.push(child); + folders.set(path, child); } node = child; } - node.children!.push({ name: parts[parts.length - 1], path: file.path, size: file.size }); + node.children!.push({ name: parts[parts.length - 1], path: file.path, file }); } return root; } -/** Building height in world units. Logarithmic, so one huge bundle doesn't dwarf the whole city. */ -export function heightFor(size: number): number { - return 1 + 8 * Math.log2(1 + size / 1000); +/** Floors grow with edits, logarithmically: 1 edit = 3 floors, 10 = 9, 100 = 17, 1000 = 25. */ +export function floorsFor(edits: number): number { + return 1 + Math.round(2.4 * Math.log2(1 + edits)); } -/** Ground area a file gets. Grows much slower than size, so the city reads by height, not by footprint. */ -export function areaFor(size: number): number { - return 20 + Math.sqrt(size); +export function seedOf(text: string): number { + let hash = 2166136261; + for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 16777619); + return hash >>> 0; } -const EXTENT = 400; +/** Street width between siblings: avenues between top-level folders, alleys deep inside. */ +function streetWidth(depth: number): number { + return depth === 0 ? 7 : depth === 1 ? 4 : 2.5; +} + +/** + * How ground follows size. "linear" is the plain share of the repository; "sqrt" + * keeps the order but tames a few huge files (images, lockfiles) that would + * otherwise turn half the city into empty lots. + */ +export type GroundScale = "linear" | "sqrt"; + +export function layoutCity(files: RepoFile[], groundScale: GroundScale = "sqrt"): CityLayout { + const total = files.reduce((sum, f) => sum + f.size, 0); + const weightOf = (size: number) => (groundScale === "sqrt" ? Math.sqrt(size) : size); + const totalWeight = files.reduce((sum, f) => sum + weightOf(f.size), 0); + // Tiny files still get a lot, so they stay visible. + const minWeight = files.length ? (totalWeight / files.length) * 0.15 || 1 : 1; + const extent = Math.max(120, Math.sqrt(files.length * GROUND_PER_FILE)); -export function layoutCity(files: RepoFile[]): CityLayout { const root = hierarchy(buildTree(files)) - .sum((d) => (d.children ? 0 : areaFor(d.size))) + .sum((d) => (d.file ? Math.max(weightOf(d.file.size), minWeight) : 0)) .sort((a, b) => (b.value ?? 0) - (a.value ?? 0)); const laidOut = treemap() .tile(treemapSquarify) - .size([EXTENT, EXTENT]) - .paddingInner(1.2) - .paddingOuter((n) => (n.depth === 0 ? 0 : 1.5)) + .size([extent, extent]) + .paddingInner((n) => streetWidth(n.depth)) + .paddingOuter((n) => (n.depth === 0 ? 0 : 1.2)) .round(false)(root); const buildings: Building[] = []; const districts: District[] = []; - const half = EXTENT / 2; + const half = extent / 2; + let tallest = 0; for (const node of laidOut.descendants()) { - const width = node.x1 - node.x0; - const length = node.y1 - node.y0; + const width = Math.max(node.x1 - node.x0, 0); + const length = Math.max(node.y1 - node.y0, 0); const x = node.x0 + width / 2 - half; const z = node.y0 + length / 2 - half; - if (node.data.children) { + const file = node.data.file; + if (!file) { if (node.depth > 0) districts.push({ path: node.data.path, depth: node.depth, x, z, width, length }); continue; } - // Leave a little gap so neighbouring buildings read as separate blocks. - const gap = Math.min(width, length) * 0.12; + const floors = floorsFor(file.edits); + const height = floors * FLOOR_HEIGHT; + tallest = Math.max(tallest, height); buildings.push({ - path: node.data.path, - size: node.data.size, - language: languageOf(node.data.path), + file, + language: languageOf(file.path), + kind: buildingKindOf(file.path), + share: total ? file.size / total : 0, + floors, x, z, - width: Math.max(width - gap, 0.05), - depth: Math.max(length - gap, 0.05), - height: heightFor(node.data.size), + width: Math.max(width, 0.4), + depth: Math.max(length, 0.4), + height, + base: (node.depth - 1) * PLATE_HEIGHT, + seed: seedOf(file.path), }); } - return { buildings, districts, extent: EXTENT }; + return { buildings, districts, extent, tallest }; } diff --git a/src/main.ts b/src/main.ts index 0fa2630..aa96b0b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,36 +1,38 @@ import { CityView } from "./city"; -import { fetchSnapshot, parseRepo } from "./github"; -import { layoutCity, type Building } from "./layout"; -import type { LanguageGroup } from "./languages"; +import { COMMIT_LIMIT, fetchSnapshot, parseRepo } from "./github"; +import type { CitySnapshot } from "./history"; +import { layoutCity, type Building, type GroundScale } from "./layout"; +import type { BuildingKind } from "./languages"; import { THEMES, themeById } from "./themes"; /** Above this many files the city gets too heavy for most laptops. */ const MAX_FILES = 40000; +const TOKEN_KEY = "commit-city:token"; -const LANGUAGE_LABELS: Record = { - script: "JS / TS", - python: "Python", - systems: "C / C++ / Rust / Go", - jvm: "Java / Kotlin", - web: "Web / Ruby / PHP", - shell: "Shell", - data: "Data / config", - docs: "Docs", - media: "Media", - other: "Other", +const KIND_LABELS: Record = { + tower: "Tower: C / C++ / Rust / Go / Java", + office: "Office: JS / TS / Python / web", + house: "House: docs", + warehouse: "Warehouse: data / config", + hall: "Hall: images / media", + shed: "Shed: other", }; const $ = (id: string) => document.getElementById(id) as T; const form = $("repo-form"); const input = $("repo-input"); +const tokenInput = $("token-input"); +const fileInput = $("file-input"); const themeSelect = $("theme-select"); +const groundSelect = $("ground-select"); const status = $("status"); const info = $("info"); const legend = $("legend"); const params = new URLSearchParams(location.search); let theme = themeById(params.get("theme")); -let current: { owner: string; name: string; branch: string } | null = null; +let groundScale: GroundScale = params.get("ground") === "linear" ? "linear" : "sqrt"; +let current: CitySnapshot | null = null; const view = new CityView($("city"), theme); @@ -42,9 +44,38 @@ themeSelect.addEventListener("change", () => { updateUrl(); }); +groundSelect.value = groundScale; +groundSelect.addEventListener("change", () => { + groundScale = groundSelect.value === "linear" ? "linear" : "sqrt"; + if (current) show(current); + updateUrl(); +}); + +tokenInput.value = readToken(); +tokenInput.addEventListener("change", () => { + try { + if (tokenInput.value.trim()) localStorage.setItem(TOKEN_KEY, tokenInput.value.trim()); + else localStorage.removeItem(TOKEN_KEY); + } catch { + // Storage blocked: the token still works for this visit. + } +}); + form.addEventListener("submit", (event) => { event.preventDefault(); - void build(input.value); + void buildFromGitHub(input.value); +}); + +fileInput.addEventListener("change", () => { + const file = fileInput.files?.[0]; + if (file) void buildFromFile(file); + fileInput.value = ""; +}); +document.addEventListener("dragover", (e) => e.preventDefault()); +document.addEventListener("drop", (e) => { + e.preventDefault(); + const file = e.dataTransfer?.files[0]; + if (file) void buildFromFile(file); }); // Treat a click as a selection only when the camera didn't move (dragging rotates the city). @@ -52,12 +83,20 @@ let downAt: { x: number; y: number } | null = null; const canvasHost = $("city"); canvasHost.addEventListener("pointerdown", (e) => (downAt = { x: e.clientX, y: e.clientY })); canvasHost.addEventListener("pointerup", (e) => { - if (!downAt || Math.hypot(e.clientX - downAt.x, e.clientY - downAt.y) > 4) return; + if (e.button !== 0 || !downAt || Math.hypot(e.clientX - downAt.x, e.clientY - downAt.y) > 4) return; const building = view.pick(e.clientX, e.clientY); view.select(building); showInfo(building); }); +function readToken(): string { + try { + return localStorage.getItem(TOKEN_KEY) ?? ""; + } catch { + return ""; + } +} + function setStatus(text: string, isError = false) { status.textContent = text; status.classList.toggle("error", isError); @@ -65,13 +104,14 @@ function setStatus(text: string, isError = false) { function updateUrl() { const next = new URLSearchParams(); - if (current) next.set("repo", `${current.owner}/${current.name}`); + if (current?.repo) next.set("repo", current.repo); if (theme.id !== THEMES[0].id) next.set("theme", theme.id); + if (groundScale !== "sqrt") next.set("ground", groundScale); const query = next.toString(); history.replaceState(null, "", query ? `?${query}` : location.pathname); } -async function build(raw: string) { +async function buildFromGitHub(raw: string) { const repo = parseRepo(raw); if (!repo) { setStatus("Enter a repository as owner/repo or a GitHub URL.", true); @@ -81,82 +121,119 @@ async function build(raw: string) { setStatus(`Fetching ${repo.owner}/${repo.name}…`); showInfo(null); try { - const snapshot = await fetchSnapshot(repo.owner, repo.name); - let files = snapshot.files; - const notes: string[] = []; - if (snapshot.truncated) notes.push("GitHub returned only part of the tree"); - if (files.length > MAX_FILES) { - files = files.slice(0, MAX_FILES); - notes.push(`showing the first ${MAX_FILES.toLocaleString()} files`); + const snapshot = await fetchSnapshot(repo.owner, repo.name, { + token: tokenInput.value.trim() || undefined, + onProgress: setStatus, + }); + show(snapshot); + } catch (error) { + setStatus(error instanceof Error ? error.message : String(error), true); + } +} + +async function buildFromFile(file: File) { + showInfo(null); + try { + const snapshot = JSON.parse(await file.text()) as CitySnapshot; + if (snapshot.format !== "commit-city/1" || !Array.isArray(snapshot.files)) { + throw new Error("That file isn't a commit-city snapshot. Make one with `npm run scan`."); } - const layout = layoutCity(files); - view.show(layout); - current = { owner: snapshot.owner, name: snapshot.name, branch: snapshot.branch }; - updateUrl(); - const folders = layout.districts.length; - setStatus( - `${snapshot.owner}/${snapshot.name}@${snapshot.branch}: ${files.length.toLocaleString()} files in ` + - `${folders.toLocaleString()} folders` + - (notes.length ? ` (${notes.join("; ")})` : "") + - ". Drag to look around, click a building.", - ); + input.value = snapshot.repo ?? ""; + show(snapshot); } catch (error) { setStatus(error instanceof Error ? error.message : String(error), true); } } +function show(snapshot: CitySnapshot) { + let files = snapshot.files; + const notes: string[] = []; + if (files.length > MAX_FILES) { + files = files.slice(0, MAX_FILES); + notes.push(`showing the first ${MAX_FILES.toLocaleString()} files`); + } + if (snapshot.partialHistory) { + notes.push( + `heights count only the latest ${snapshot.commitsScanned} commits; ` + + `add a token (up to ${COMMIT_LIMIT.withToken}) or use \`npm run scan\` for the full history`, + ); + } + const layout = layoutCity(files, groundScale); + view.show(layout); + current = snapshot; + updateUrl(); + setStatus( + `${snapshot.name}@${snapshot.branch}: ${files.length.toLocaleString()} files, ` + + `${snapshot.commitsScanned.toLocaleString()} commits` + + (notes.length ? ` (${notes.join("; ")})` : "") + + ". Drag to look around, click a building.", + ); +} + function formatBytes(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / 1024 / 1024).toFixed(1)} MB`; } +function formatShare(share: number): string { + const percent = share * 100; + return percent >= 0.1 ? `${percent.toFixed(1)}%` : "< 0.1%"; +} + function showInfo(building: Building | null) { info.hidden = building === null; if (!building || !current) return; - const url = `https://github.com/${current.owner}/${current.name}/blob/${encodeURIComponent(current.branch)}/${building.path - .split("/") - .map(encodeURIComponent) - .join("/")}`; + const { file } = building; info.replaceChildren(); const title = document.createElement("h2"); - title.textContent = building.path.split("/").pop() ?? building.path; + title.textContent = file.path.split("/").pop() ?? file.path; + const rows: [string, string][] = [ + ["Path", file.path], + ["Edits", `${file.edits.toLocaleString()} (${building.floors} floors)`], + ["Size", `${formatBytes(file.size)}, ${formatShare(building.share)} of the repo`], + ["Building", KIND_LABELS[building.kind]], + ]; + if (file.lastEdited) rows.push(["Last edit", new Date(file.lastEdited * 1000).toLocaleDateString()]); const list = document.createElement("dl"); - for (const [term, value] of [ - ["Path", building.path], - ["Size", formatBytes(building.size)], - ["Kind", LANGUAGE_LABELS[building.language]], - ]) { + for (const [term, value] of rows) { const dt = document.createElement("dt"); dt.textContent = term; const dd = document.createElement("dd"); dd.textContent = value; list.append(dt, dd); } - const link = document.createElement("a"); - link.href = url; - link.target = "_blank"; - link.rel = "noopener"; - link.textContent = "Open on GitHub"; - info.append(title, list, link); + info.append(title, list); + if (current.repo) { + const link = document.createElement("a"); + link.href = `https://github.com/${current.repo}/blob/${encodeURIComponent(current.branch)}/${file.path + .split("/") + .map(encodeURIComponent) + .join("/")}`; + link.target = "_blank"; + link.rel = "noopener"; + link.textContent = "Open on GitHub"; + info.append(link); + } } function renderLegend() { legend.replaceChildren( - ...(Object.keys(LANGUAGE_LABELS) as LanguageGroup[]).map((group) => { + ...(Object.keys(KIND_LABELS) as BuildingKind[]).map((kind) => { const item = document.createElement("span"); const swatch = document.createElement("i"); - swatch.style.background = theme.buildings[group]; - item.append(swatch, LANGUAGE_LABELS[group]); + swatch.style.background = theme.kinds[kind].walls[0]; + item.append(swatch, KIND_LABELS[kind]); return item; }), + Object.assign(document.createElement("span"), { textContent: "Height = edits · Ground = file size" }), ); } renderLegend(); const initial = params.get("repo"); if (initial) { - void build(initial); + void buildFromGitHub(initial); } else { - setStatus("Enter a public GitHub repository to build its city."); + setStatus("Enter a GitHub repository, or drop a snapshot made with `npm run scan`."); } diff --git a/src/style.css b/src/style.css index d2fbd57..1af067d 100644 --- a/src/style.css +++ b/src/style.css @@ -61,6 +61,21 @@ button[type="submit"] { background: var(--accent); border-color: var(--accent); .row select { padding: 3px 6px; margin-left: 4px; } a { color: var(--accent); } +.file-button { color: var(--accent); cursor: pointer; text-decoration: underline; } + +details { margin-top: 10px; color: var(--muted); } +details summary { cursor: pointer; } +details p { margin: 6px 0; font-size: 12px; } +#token-input { + width: 100%; + padding: 6px 8px; + border-radius: 6px; + border: 1px solid #3a404c; + background: #0d0f14; + color: inherit; + font: inherit; +} + #status { margin: 10px 0 0; color: var(--muted); min-height: 1.2em; } #status.error { color: #ff8f8f; } diff --git a/src/themes.ts b/src/themes.ts index ec9afc7..454b83b 100644 --- a/src/themes.ts +++ b/src/themes.ts @@ -1,4 +1,4 @@ -import type { LanguageGroup } from "./languages"; +import type { BuildingKind } from "./languages"; /** * A theme is the city's "skin". Layout and data never depend on it, so new @@ -8,63 +8,111 @@ export interface Theme { id: string; label: string; sky: string; - fog: string; + /** Grass around the city. */ ground: string; - /** District plates, from the outermost folder inwards. */ - districts: string[]; - buildings: Record; - /** Extra glow on buildings (0 = none). */ - emissive: number; - ambient: number; - sun: number; + /** Asphalt: the streets between districts. */ + road: string; + /** District plates (sidewalks), from the outermost folder inwards. */ + plates: string[]; + sun: { color: string; intensity: number; elevation: number }; + ambient: { sky: string; ground: string; intensity: number }; + /** Wall and roof colors per building kind. Each building picks one of each. */ + kinds: Record; + windows: { + /** Unlit glass. */ + glass: string; + /** Lit windows pick one of these two. */ + lit: [string, string]; + /** Share of windows that are lit, 0..1. */ + litShare: number; + /** How bright lit windows glow (0 = daytime, no glow). */ + glow: number; + }; + shadows: boolean; + /** Overall brightness after tone mapping. */ + exposure: number; } +/** Real-world facade and roof colors, shared by the daytime themes. */ +const CITY_COLORS: Theme["kinds"] = { + tower: { + walls: ["#5b87a8", "#4d7c8a", "#6f9fb8", "#3f6f7f", "#7a9a78", "#9a8463", "#5e6f9a", "#86a9c4"], + roofs: ["#d9dcde", "#9aa3a8", "#6f8f72", "#c9b28a", "#7c8a99"], + }, + office: { + walls: [ + "#e8d9b5", "#d98f6a", "#c9785c", "#e6c48a", "#a9c2a0", "#9fb8cc", + "#e3a99a", "#f0ece2", "#b7a6c9", "#c2b280", "#d4b8a0", "#8fb3a8", + ], + roofs: ["#e8e6e1", "#b8bcbf", "#7fa36b", "#c96f4a", "#5f8a9a", "#8a8f94", "#d8c9a8"], + }, + house: { + walls: ["#f6e7c1", "#f2c6a0", "#e8a87c", "#c9d9b0", "#bcd4e6", "#f4f1ea", "#e9c9d3", "#d9b38c"], + roofs: ["#b5523b", "#8f3e2c", "#4b6a8a", "#3f5e4a", "#6b4a3a", "#a8452f", "#c7743f"], + }, + warehouse: { + walls: ["#c9cfd2", "#9fb3bf", "#c7b98f", "#8fa6a0", "#b9a58e", "#d6d0c4", "#a7b9d1"], + roofs: ["#a6adb2", "#7b8d99", "#b5bdc1", "#8fa38a"], + }, + hall: { + walls: ["#b5603f", "#a14f38", "#c4744f", "#8f4a3a", "#c98a5a"], + roofs: ["#2f4f4f", "#5a6e6a", "#7d5a46", "#4f6d7a"], + }, + shed: { + walls: ["#d8cbb0", "#b9c4a8", "#c8b6a0", "#a8b8c8", "#d9a98a"], + roofs: ["#8a8a8a", "#6f7f6a", "#9a6a52"], + }, +}; + export const THEMES: Theme[] = [ { id: "daylight", label: "Daylight", - sky: "#cfe3f2", - fog: "#cfe3f2", - ground: "#a7b39a", - districts: ["#c9c6bd", "#bdb9ae", "#b1ada1", "#a6a295"], - buildings: { - script: "#e8c25a", - python: "#4f7fbf", - systems: "#b5654a", - jvm: "#c9874a", - web: "#d97a8c", - shell: "#6aa36f", - data: "#9aa3ad", - docs: "#f2efe6", - media: "#a58bc7", - other: "#8a8f96", - }, - emissive: 0, - ambient: 0.7, - sun: 1.6, + sky: "#bcd6ea", + ground: "#8fa577", + road: "#55585c", + plates: ["#b9b6ae", "#c4c1b9", "#cfccc4", "#d8d5ce"], + sun: { color: "#fff4e0", intensity: 2.4, elevation: 0.9 }, + ambient: { sky: "#dbe8f5", ground: "#7d7466", intensity: 1.3 }, + kinds: CITY_COLORS, + windows: { glass: "#34495c", lit: ["#ffe2a8", "#fff4d6"], litShare: 0, glow: 0 }, + shadows: true, + exposure: 1, + }, + { + id: "dusk", + label: "Dusk", + sky: "#e7a37c", + ground: "#5f6b4c", + road: "#3d3d42", + plates: ["#8d8580", "#968f89", "#a09892", "#a9a19b"], + sun: { color: "#ffb37a", intensity: 1.6, elevation: 0.25 }, + ambient: { sky: "#f0c0a8", ground: "#5a4a50", intensity: 1.4 }, + kinds: CITY_COLORS, + windows: { glass: "#3a3f4a", lit: ["#ffcf7a", "#ffe6b3"], litShare: 0.45, glow: 1.1 }, + shadows: true, + exposure: 1.15, }, { id: "cyberpunk", label: "Cyberpunk", sky: "#07040f", - fog: "#120a24", - ground: "#0b0a14", - districts: ["#1a1430", "#221a3d", "#2a204a", "#332757"], - buildings: { - script: "#ffd23f", - python: "#3fa9ff", - systems: "#ff3f6c", - jvm: "#ff8a3f", - web: "#ff3fd4", - shell: "#3fff9b", - data: "#7a7fff", - docs: "#d6f6ff", - media: "#b23fff", - other: "#5c6a80", + ground: "#0b0a12", + road: "#121019", + plates: ["#1a1626", "#201b30", "#26203a", "#2c2544"], + sun: { color: "#8a6cff", intensity: 0.9, elevation: 0.7 }, + ambient: { sky: "#5a46a0", ground: "#1a1030", intensity: 1.3 }, + kinds: { + tower: { walls: ["#2c3148", "#343a56", "#262b40"], roofs: ["#16182a"] }, + office: { walls: ["#36324a", "#2e2b40", "#3d3854"], roofs: ["#1a1824"] }, + house: { walls: ["#3a3248", "#332c40"], roofs: ["#5a1f4a", "#1f3558"] }, + warehouse: { walls: ["#2e3340", "#363c4a"], roofs: ["#1a1d26"] }, + hall: { walls: ["#46304a", "#3c2840"], roofs: ["#1c1622"] }, + shed: { walls: ["#33333f"], roofs: ["#1a1a22"] }, }, - emissive: 0.22, - ambient: 0.25, - sun: 0.6, + windows: { glass: "#0d0f18", lit: ["#ff3fd4", "#3fd4ff"], litShare: 0.55, glow: 1.6 }, + shadows: false, + exposure: 2.2, }, ]; diff --git a/tests/history.test.ts b/tests/history.test.ts new file mode 100644 index 0000000..978237c --- /dev/null +++ b/tests/history.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { countEdits } from "../src/history"; + +describe("countEdits", () => { + it("counts commits per file", () => { + const edits = countEdits( + [ + { time: 30, changes: [{ status: "M", path: "a.ts" }] }, + { time: 20, changes: [{ status: "M", path: "a.ts" }, { status: "M", path: "b.ts" }] }, + { time: 10, changes: [{ status: "A", path: "a.ts" }, { status: "A", path: "b.ts" }] }, + ], + ["a.ts", "b.ts"], + ); + expect(edits.get("a.ts")).toEqual({ edits: 3, lastEdited: 30 }); + expect(edits.get("b.ts")).toEqual({ edits: 2, lastEdited: 20 }); + }); + + it("follows renames back in time", () => { + const edits = countEdits( + [ + { time: 30, changes: [{ status: "M", path: "src/new.ts" }] }, + { time: 20, changes: [{ status: "R", from: "old.ts", path: "src/new.ts" }] }, + { time: 10, changes: [{ status: "M", path: "old.ts" }] }, + { time: 5, changes: [{ status: "A", path: "old.ts" }] }, + ], + ["src/new.ts"], + ); + expect(edits.get("src/new.ts")!.edits).toBe(4); + }); + + it("ignores files that no longer exist", () => { + const edits = countEdits([{ time: 1, changes: [{ status: "D", path: "gone.ts" }] }], ["kept.ts"]); + expect([...edits.keys()]).toEqual(["kept.ts"]); + expect(edits.get("kept.ts")!.edits).toBe(0); + }); +}); diff --git a/tests/layout.test.ts b/tests/layout.test.ts index a1e5fb8..fdba275 100644 --- a/tests/layout.test.ts +++ b/tests/layout.test.ts @@ -1,12 +1,13 @@ import { describe, expect, it } from "vitest"; -import { buildTree, heightFor, layoutCity } from "../src/layout"; -import { languageOf } from "../src/languages"; +import { buildTree, floorsFor, layoutCity, FLOOR_HEIGHT } from "../src/layout"; +import { buildingKindOf, languageOf } from "../src/languages"; +const file = (path: string, size: number, edits: number) => ({ path, size, edits }); const files = [ - { path: "README.md", size: 2000 }, - { path: "src/main.ts", size: 8000 }, - { path: "src/util/math.ts", size: 500 }, - { path: "tests/main.test.ts", size: 1200 }, + file("README.md", 2000, 40), + file("src/main.ts", 8000, 120), + file("src/util/math.ts", 500, 3), + file("tests/main.test.ts", 1200, 10), ]; describe("buildTree", () => { @@ -20,6 +21,7 @@ describe("buildTree", () => { describe("layoutCity", () => { const layout = layoutCity(files); + const byPath = (path: string) => layout.buildings.find((b) => b.file.path === path)!; it("makes one building per file and one district per folder", () => { expect(layout.buildings).toHaveLength(4); @@ -29,8 +31,8 @@ describe("layoutCity", () => { it("keeps every building inside the city", () => { const half = layout.extent / 2; for (const b of layout.buildings) { - expect(Math.abs(b.x) + b.width / 2).toBeLessThanOrEqual(half); - expect(Math.abs(b.z) + b.depth / 2).toBeLessThanOrEqual(half); + expect(Math.abs(b.x) + b.width / 2).toBeLessThanOrEqual(half + 1e-9); + expect(Math.abs(b.z) + b.depth / 2).toBeLessThanOrEqual(half + 1e-9); } }); @@ -47,11 +49,32 @@ describe("layoutCity", () => { } }); - it("makes bigger files taller", () => { - const main = layout.buildings.find((b) => b.path === "src/main.ts")!; - const math = layout.buildings.find((b) => b.path === "src/util/math.ts")!; - expect(main.height).toBeGreaterThan(math.height); - expect(heightFor(0)).toBeGreaterThan(0); + it("makes more-edited files taller", () => { + expect(byPath("src/main.ts").height).toBeGreaterThan(byPath("README.md").height); + expect(byPath("README.md").height).toBeGreaterThan(byPath("src/util/math.ts").height); + expect(byPath("src/main.ts").height).toBe(floorsFor(120) * FLOOR_HEIGHT); + }); + + it("gives bigger files more ground, in proportion to their share", () => { + const main = byPath("src/main.ts"); + const readme = byPath("README.md"); + expect(main.share).toBeCloseTo(8000 / 11700); + expect(main.width * main.depth).toBeGreaterThan(readme.width * readme.depth * 2); + }); + + it("uses the exact share of the repository with the linear ground scale", () => { + const linear = layoutCity(files, "linear"); + const area = (path: string) => { + const b = linear.buildings.find((x) => x.file.path === path)!; + return b.width * b.depth; + }; + // 8000 vs 2000 bytes: about 4x the ground (streets and padding take a little off). + expect(area("src/main.ts") / area("README.md")).toBeGreaterThan(3); + }); + + it("stands nested files on their folder's plate", () => { + expect(byPath("README.md").base).toBe(0); + expect(byPath("src/util/math.ts").base).toBeGreaterThan(byPath("src/main.ts").base); }); it("handles an empty repository", () => { @@ -59,7 +82,15 @@ describe("layoutCity", () => { }); }); -describe("languageOf", () => { +describe("floorsFor", () => { + it("grows slowly with edits", () => { + expect(floorsFor(0)).toBe(1); + expect(floorsFor(1)).toBe(3); + expect(floorsFor(1000)).toBeLessThan(30); + }); +}); + +describe("languageOf and buildingKindOf", () => { it("groups by extension", () => { expect(languageOf("src/app.tsx")).toBe("script"); expect(languageOf("pkg/main.go")).toBe("systems"); @@ -67,4 +98,13 @@ describe("languageOf", () => { expect(languageOf("Makefile")).toBe("other"); expect(languageOf(".gitignore")).toBe("other"); }); + + it("turns file kinds into building kinds", () => { + expect(buildingKindOf("src/app.ts")).toBe("office"); + expect(buildingKindOf("src/lib.rs")).toBe("tower"); + expect(buildingKindOf("README.md")).toBe("house"); + expect(buildingKindOf("package.json")).toBe("warehouse"); + expect(buildingKindOf("logo.png")).toBe("hall"); + expect(buildingKindOf("LICENSE")).toBe("shed"); + }); }); diff --git a/tsconfig.json b/tsconfig.json index 588ec41..54bf255 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,7 +8,9 @@ "noUnusedLocals": true, "noUnusedParameters": true, "skipLibCheck": true, - "types": ["vite/client"] + "allowImportingTsExtensions": true, + "noEmit": true, + "types": ["vite/client", "node"] }, - "include": ["src", "tests"] + "include": ["src", "tests", "scripts"] }