diff --git a/README.md b/README.md index 1b89e1f..a5c8f7f 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@ A small online tool for checking the minified gzip/brotli size of npm packages. -I used [monaco-editor](https://github.com/microsoft/monaco-editor) for the code-editor, [esbuild](https://github.com/evanw/esbuild) and [rollup](https://github.com/rollup/rollup) as bundler and treeshaker respectively, [pako](https://github.com/nodeca/pako) as a js port of the zlib and gzip libraries, [pretty-bytes](https://github.com/sindresorhus/pretty-bytes) to convert the gzip size to human readable values, and [countapi-js](https://github.com/mlomb/countapi-js) to keep track of the number of page visits, in a private and secure way. - -This project was greatly influenced by the [hardfist/neo-tools](https://github.com/hardfist/neo-tools) and [mizchi/uniroll](https://github.com/mizchi/uniroll) projects. +I used [monaco-editor](https://github.com/microsoft/monaco-editor) for the code-editor, [esbuild](https://github.com/evanw/esbuild) as bundler and treeshaker respectively, [denoflate](https://github.com/hazae41/denoflate) as a wasm port of gzip, [deno\_brotli](https://github.com/denosaurs/deno_brotli) as a wasm port of brotli, [deno\_lz4](https://github.com/denosaurs/deno_lz4) as a wasm port of lz4, [bytes](https://github.com/visionmedia/bytes.js) to convert the compressed size to human readable values, [esbuild-visualizer](https://github.com/btd/esbuild-visualizer) to visualize and analyze your esbuild bundle to see which modules are taking up space, [umami](https://github.com/mikecao/umami) for private, publicly available analytics and general usage stats all without cookies, and [countapi-js](https://github.com/mlomb/countapi-js) to keep track of the number of page visits, in a private and secure way. + +This project was greatly influenced by [@hardfists](https://github.com/hardfist) [neo-tools](https://github.com/hardfist/neo-tools) and [@mizchi's](https://github.com/mizchi) [uniroll](https://github.com/mizchi/uniroll) projects. **bundlejs** is a quick and easy way to bundle your projects, minify and see it's gzip size. It's an online tool similar to [bundlephobia](https://bundlephobia.com), but **bundle** does all the bundling locally on you browser and can treeshake and bundle multiple packages (both commonjs and esm) together, all without having to install any npm packages and with typescript support. diff --git a/gulpfile.js b/gulpfile.js index b80dc61..89a743a 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -236,7 +236,78 @@ task("js", async () => { }), gulpif( - (file) => /\.js$/.test(file.path), + (file) => /\.(js|css)$/.test(file.path), + size({ + gzip: true, + showFiles: true, + showTotal: false, + }) + ), + ], + dest: jsFolder, // Output + } + ); +}); + +// JS Analyzer Tasks +task("js-analyzer", async () => { + const [ + { default: gulpEsBuild, createGulpEsbuild }, + { default: size }, + { default: gulpif }, + + { SASS }, + ] = await Promise.all([ + import("gulp-esbuild"), + import("gulp-size"), + import("gulp-if"), + + import("./plugins/sass.js"), + ]); + + const TEMPLATE = ["sunburst", "treemap", "network"]; + + const esbuild = + mode == "watch" + ? createGulpEsbuild({ incremental: true }) + : gulpEsBuild; + + return stream( + [ + `${tsFolder}/plugins/analyzer/src/{${TEMPLATE.toString()}}/index.tsx`, + `!${tsFolder}/**/*.d.ts` + ], + { + pipes: [ + // Bundle Modules + esbuild({ + target: ["es2019"], + platform: "browser", + treeShaking: true, + + assetNames: "[dir]", + entryNames: "[dir].min", + + jsxFragment: "Fragment", + jsxFactory: "h", + + bundle: true, + minify: true, + color: true, + format: "esm", + sourcemap: true, + splitting: true, + + loader: { + ".ttf": "file", + ".wasm": "file", + }, + + plugins: [SASS()], + }), + + gulpif( + (file) => /\.(js|css)$/.test(file.path), size({ gzip: true, showFiles: true, @@ -457,9 +528,9 @@ task("watch", async () => { ); watch( - [`${tsFolder}/**/*.{tsx,ts,js}`, `!${tsFolder}/**/*.d.ts`], + [`${tsFolder}/**/*.{tsx,ts,js,jsx}`, `!${tsFolder}/**/*.d.ts`], { delay: 850 }, - series("js", /* "preload-chunks", */ "service-worker", "reload") + series(parallel("js", "js-analyzer"), /* "preload-chunks", */ "service-worker", "reload") ); watch( @@ -473,7 +544,7 @@ task( "build", series( "clean", - parallel("html", "css", "assets", "js"), + parallel("html", "css", "assets", "js", "js-analyzer"), /* "preload-chunks", */ parallelFn("minify-css", "service-worker", "sitemap") ) @@ -482,7 +553,7 @@ task( "default", series( "clean", - parallel("html", "css", "assets", "js"), + parallel("html", "css", "assets", "js", "js-analyzer"), /* "preload-chunks", */ "service-worker", "watch" diff --git a/package.json b/package.json index 0c69405..8f414aa 100644 --- a/package.json +++ b/package.json @@ -62,15 +62,23 @@ "@okikio/native": "^3.0.1", "@okikio/sharedworker": "^1.0.4", "@typescript/ata": "^0.9.3", + "bytes": "^3.1.2", "countapi-js": "^1.0.2", + "d3-array": "^3.1.6", + "d3-color": "^3.1.0", + "d3-hierarchy": "^3.1.2", + "d3-scale": "^4.0.2", + "d3-shape": "^3.1.0", "esbuild-wasm": "0.14.37", "monaco-editor": "^0.33.0", + "nanoid": "^3.3.4", "parse-package-name": "^1.0.0", - "pretty-bytes": "^6.0.0", + "preact": "^10.7.2", "resolve.exports": "^1.1.0", "solid-js": "^1.3.17", "typescript": "^4.6.4", "web-animations-js": "^2.3.2", + "webcola": "^3.4.0", "workbox-window": "^6.5.3" }, "devDependencies": { @@ -79,6 +87,12 @@ "@csstools/postcss-sass": "^5.0.1", "@semantic-release/changelog": "^6.0.1", "@semantic-release/git": "^10.0.1", + "@types/bytes": "^3.1.1", + "@types/d3-array": "^3.0.2", + "@types/d3-color": "^3.0.2", + "@types/d3-hierarchy": "^3.0.2", + "@types/d3-scale": "^4.0.2", + "@types/d3-shape": "^3.0.2", "@types/node": "^17.0.31", "autoprefixer": "^10.4.7", "browser-sync": "^2.27.9", diff --git a/plugins/sass.js b/plugins/sass.js new file mode 100644 index 0000000..06d438f --- /dev/null +++ b/plugins/sass.js @@ -0,0 +1,19 @@ +import sass from "sass"; + +export const SASS = () => { + /** + * @type {import('esbuild').Plugin} + */ + return { + name: "sass", + setup(build) { + build.onLoad({ filter: /\.scss$/ }, async (args) => { + const result = await sass.compileAsync(args.path, { style: "compressed" }); + return { + contents: result.css.toString("utf-8"), + loader: "css", + }; + }); + }, + }; +}; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9c08e4b..bd7f660 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -12,12 +12,24 @@ specifiers: '@okikio/sharedworker': ^1.0.4 '@semantic-release/changelog': ^6.0.1 '@semantic-release/git': ^10.0.1 + '@types/bytes': ^3.1.1 + '@types/d3-array': ^3.0.2 + '@types/d3-color': ^3.0.2 + '@types/d3-hierarchy': ^3.0.2 + '@types/d3-scale': ^4.0.2 + '@types/d3-shape': ^3.0.2 '@types/node': ^17.0.31 '@typescript/ata': ^0.9.3 autoprefixer: ^10.4.7 browser-sync: ^2.27.9 + bytes: ^3.1.2 commitizen: ^4.2.4 countapi-js: ^1.0.2 + d3-array: ^3.1.6 + d3-color: ^3.1.0 + d3-hierarchy: ^3.1.2 + d3-scale: ^4.0.2 + d3-shape: ^3.1.0 del: ^6.0.0 esbuild: 0.14.37 esbuild-plugin-solid: ^0.4.2 @@ -36,13 +48,14 @@ specifiers: husky: ^7.0.4 jstransformer-markdown-it: ^2.1.0 monaco-editor: ^0.33.0 + nanoid: ^3.3.4 parse-package-name: ^1.0.0 postcss: ^8.4.13 postcss-csso: ^6.0.0 postcss-scss: ^4.0.4 posthtml-parser: ^0.11.0 posthtml-render: ^3.0.0 - pretty-bytes: ^6.0.0 + preact: ^10.7.2 rehype: ^12.0.1 rehype-autolink-headings: ^6.1.1 rehype-external-links: ^1.0.1 @@ -59,6 +72,7 @@ specifiers: typescript: ^4.6.4 typescript-json-schema: ^0.53.0 web-animations-js: ^2.3.2 + webcola: ^3.4.0 workbox-build: ^6.5.3 workbox-window: ^6.5.3 @@ -70,15 +84,23 @@ dependencies: '@okikio/native': 3.0.1 '@okikio/sharedworker': 1.0.4 '@typescript/ata': 0.9.3_typescript@4.6.4 + bytes: 3.1.2 countapi-js: 1.0.2 + d3-array: 3.1.6 + d3-color: 3.1.0 + d3-hierarchy: 3.1.2 + d3-scale: 4.0.2 + d3-shape: 3.1.0 esbuild-wasm: 0.14.37 monaco-editor: 0.33.0 + nanoid: 3.3.4 parse-package-name: 1.0.0 - pretty-bytes: 6.0.0 + preact: 10.7.2 resolve.exports: 1.1.0 solid-js: 1.3.17 typescript: 4.6.4 web-animations-js: 2.3.2 + webcola: 3.4.0 workbox-window: 6.5.3 devDependencies: @@ -87,6 +109,12 @@ devDependencies: '@csstools/postcss-sass': 5.0.1_postcss@8.4.13 '@semantic-release/changelog': 6.0.1_semantic-release@19.0.2 '@semantic-release/git': 10.0.1_semantic-release@19.0.2 + '@types/bytes': 3.1.1 + '@types/d3-array': 3.0.2 + '@types/d3-color': 3.0.2 + '@types/d3-hierarchy': 3.0.2 + '@types/d3-scale': 4.0.2 + '@types/d3-shape': 3.0.2 '@types/node': 17.0.31 autoprefixer: 10.4.7_postcss@8.4.13 browser-sync: 2.27.9 @@ -1952,6 +1980,10 @@ packages: resolution: {integrity: sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA==} dev: true + /@types/bytes/3.1.1: + resolution: {integrity: sha512-lOGyCnw+2JVPKU3wIV0srU0NyALwTBJlVSx5DfMQOFuuohA8y9S8orImpuIQikZ0uIQ8gehrRjxgQC1rLRi11w==} + dev: true + /@types/component-emitter/1.2.11: resolution: {integrity: sha512-SRXjM+tfsSlA9VuG8hGO2nft2p8zjXCK1VcC6N4NXbBbYbSia9kzCChYQajIjzIqOOOuh5Ock6MmV2oux4jDZQ==} dev: true @@ -1964,6 +1996,38 @@ packages: resolution: {integrity: sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==} dev: true + /@types/d3-array/3.0.2: + resolution: {integrity: sha512-5mjGjz6XOXKOCdTajXTZ/pMsg236RdiwKPrRPWAEf/2S/+PzwY+LLYShUpeysWaMvsdS7LArh6GdUefoxpchsQ==} + dev: true + + /@types/d3-color/3.0.2: + resolution: {integrity: sha512-WVx6zBiz4sWlboCy7TCgjeyHpNjMsoF36yaagny1uXfbadc9f+5BeBf7U+lRmQqY3EHbGQpP8UdW8AC+cywSwQ==} + dev: true + + /@types/d3-hierarchy/3.0.2: + resolution: {integrity: sha512-+krnrWOZ+aQB6v+E+jEkmkAx9HvsNAD+1LCD0vlBY3t+HwjKnsBFbpVLx6WWzDzCIuiTWdAxXMEnGnVXpB09qQ==} + dev: true + + /@types/d3-path/3.0.0: + resolution: {integrity: sha512-0g/A+mZXgFkQxN3HniRDbXMN79K3CdTpLsevj+PXiTcb2hVyvkZUBg37StmgCQkaD84cUJ4uaDAWq7UJOQy2Tg==} + dev: true + + /@types/d3-scale/4.0.2: + resolution: {integrity: sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==} + dependencies: + '@types/d3-time': 3.0.0 + dev: true + + /@types/d3-shape/3.0.2: + resolution: {integrity: sha512-5+ButCmIfNX8id5seZ7jKj3igdcxx+S9IDBiT35fQGTLZUfkFgTv+oBH34xgeoWDKpWcMITSzBILWQtBoN5Piw==} + dependencies: + '@types/d3-path': 3.0.0 + dev: true + + /@types/d3-time/3.0.0: + resolution: {integrity: sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==} + dev: true + /@types/estree/0.0.39: resolution: {integrity: sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==} dev: true @@ -2209,8 +2273,6 @@ packages: dependencies: micromatch: 3.1.10 normalize-path: 2.1.1 - transitivePeerDependencies: - - supports-color dev: true /anymatch/3.1.2: @@ -2614,8 +2676,6 @@ packages: snapdragon-node: 2.1.1 split-string: 3.1.0 to-regex: 3.0.2 - transitivePeerDependencies: - - supports-color dev: true /braces/3.0.2: @@ -2736,7 +2796,6 @@ packages: /bytes/3.1.2: resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} engines: {node: '>= 0.8'} - dev: true /cache-base/1.0.1: resolution: {integrity: sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==} @@ -2878,8 +2937,6 @@ packages: upath: 1.2.0 optionalDependencies: fsevents: 1.2.13 - transitivePeerDependencies: - - supports-color dev: true /chokidar/3.5.3: @@ -3103,8 +3160,6 @@ packages: finalhandler: 1.1.0 parseurl: 1.3.3 utils-merge: 1.0.1 - transitivePeerDependencies: - - supports-color dev: true /constantinople/4.0.1: @@ -3453,6 +3508,101 @@ packages: type: 1.2.0 dev: true + /d3-array/3.1.6: + resolution: {integrity: sha512-DCbBBNuKOeiR9h04ySRBMW52TFVc91O9wJziuyXw6Ztmy8D3oZbmCkOO3UHKC7ceNJsN2Mavo9+vwV8EAEUXzA==} + engines: {node: '>=12'} + dependencies: + internmap: 2.0.3 + dev: false + + /d3-color/3.1.0: + resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==} + engines: {node: '>=12'} + dev: false + + /d3-dispatch/1.0.6: + resolution: {integrity: sha512-fVjoElzjhCEy+Hbn8KygnmMS7Or0a9sI2UzGwoB7cCtvI1XpVN9GpoYlnb3xt2YV66oXYb1fLJ8GMvP4hdU1RA==} + dev: false + + /d3-drag/1.2.5: + resolution: {integrity: sha512-rD1ohlkKQwMZYkQlYVCrSFxsWPzI97+W+PaEIBNTMxRuxz9RF0Hi5nJWHGVJ3Om9d2fRTe1yOBINJyy/ahV95w==} + dependencies: + d3-dispatch: 1.0.6 + d3-selection: 1.4.2 + dev: false + + /d3-format/3.1.0: + resolution: {integrity: sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==} + engines: {node: '>=12'} + dev: false + + /d3-hierarchy/3.1.2: + resolution: {integrity: sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==} + engines: {node: '>=12'} + dev: false + + /d3-interpolate/3.0.1: + resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==} + engines: {node: '>=12'} + dependencies: + d3-color: 3.1.0 + dev: false + + /d3-path/1.0.9: + resolution: {integrity: sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==} + dev: false + + /d3-path/3.0.1: + resolution: {integrity: sha512-gq6gZom9AFZby0YLduxT1qmrp4xpBA1YZr19OI717WIdKE2OM5ETq5qrHLb301IgxhLwcuxvGZVLeeWc/k1I6w==} + engines: {node: '>=12'} + dev: false + + /d3-scale/4.0.2: + resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==} + engines: {node: '>=12'} + dependencies: + d3-array: 3.1.6 + d3-format: 3.1.0 + d3-interpolate: 3.0.1 + d3-time: 3.0.0 + d3-time-format: 4.1.0 + dev: false + + /d3-selection/1.4.2: + resolution: {integrity: sha512-SJ0BqYihzOjDnnlfyeHT0e30k0K1+5sR3d5fNueCNeuhZTnGw4M4o8mqJchSwgKMXCNFo+e2VTChiSJ0vYtXkg==} + dev: false + + /d3-shape/1.3.7: + resolution: {integrity: sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==} + dependencies: + d3-path: 1.0.9 + dev: false + + /d3-shape/3.1.0: + resolution: {integrity: sha512-tGDh1Muf8kWjEDT/LswZJ8WF85yDZLvVJpYU9Nq+8+yW1Z5enxrmXOhTArlkaElU+CTn0OTVNli+/i+HP45QEQ==} + engines: {node: '>=12'} + dependencies: + d3-path: 3.0.1 + dev: false + + /d3-time-format/4.1.0: + resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==} + engines: {node: '>=12'} + dependencies: + d3-time: 3.0.0 + dev: false + + /d3-time/3.0.0: + resolution: {integrity: sha512-zmV3lRnlaLI08y9IMRXSDshQb5Nj77smnfpnd2LrBa/2K281Jijactokeak14QacHs/kKq0AQ121nidNYlarbQ==} + engines: {node: '>=12'} + dependencies: + d3-array: 3.1.6 + dev: false + + /d3-timer/1.0.10: + resolution: {integrity: sha512-B1JDm0XDaQC+uvo4DT79H0XmBskgS3l6Ve+1SBCfxgmtIb1AVrPIoqd+nPSv+loMX8szQ0sVUhGngL7D5QPiXw==} + dev: false + /dargs/7.0.0: resolution: {integrity: sha512-2iy1EkLdlBzQGvbweYRFxmFath8+K7+AKB0TlhHWkNuH+TmovaMH/Wp7V7R4u7f4SnX3OgLsU9t1NI9ioDnUpg==} engines: {node: '>=8'} @@ -3464,11 +3614,6 @@ packages: /debug/2.6.9: resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true dependencies: ms: 2.0.0 dev: true @@ -4457,8 +4602,6 @@ packages: regex-not: 1.0.2 snapdragon: 0.8.2 to-regex: 3.0.2 - transitivePeerDependencies: - - supports-color dev: true /expand-tilde/2.0.2: @@ -4521,8 +4664,6 @@ packages: regex-not: 1.0.2 snapdragon: 0.8.2 to-regex: 3.0.2 - transitivePeerDependencies: - - supports-color dev: true /fancy-log/1.3.3: @@ -4624,8 +4765,6 @@ packages: parseurl: 1.3.3 statuses: 1.3.1 unpipe: 1.0.0 - transitivePeerDependencies: - - supports-color dev: true /find-node-modules/2.1.3: @@ -4692,8 +4831,6 @@ packages: is-glob: 3.1.0 micromatch: 3.1.10 resolve-dir: 1.0.1 - transitivePeerDependencies: - - supports-color dev: true /findup-sync/3.0.0: @@ -4704,8 +4841,6 @@ packages: is-glob: 4.0.3 micromatch: 3.1.10 resolve-dir: 1.0.1 - transitivePeerDependencies: - - supports-color dev: true /findup-sync/4.0.0: @@ -5047,8 +5182,6 @@ packages: just-debounce: 1.1.0 normalize-path: 3.0.0 object.defaults: 1.1.0 - transitivePeerDependencies: - - supports-color dev: true /glob/7.1.4: @@ -5159,8 +5292,6 @@ packages: semver-greatest-satisfied-range: 1.1.0 v8flags: 3.2.0 yargs: 7.1.2 - transitivePeerDependencies: - - supports-color dev: true /gulp-esbuild/0.10.3: @@ -5281,8 +5412,6 @@ packages: gulp-cli: 2.3.0 undertaker: 1.3.0 vinyl-fs: 3.0.3 - transitivePeerDependencies: - - supports-color dev: true /gulplog/1.0.0: @@ -5683,6 +5812,11 @@ packages: side-channel: 1.0.4 dev: true + /internmap/2.0.3: + resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} + engines: {node: '>=12'} + dev: false + /interpret/1.4.0: resolution: {integrity: sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==} engines: {node: '>= 0.10'} @@ -6297,8 +6431,6 @@ packages: object.map: 1.0.1 rechoir: 0.6.2 resolve: 1.22.0 - transitivePeerDependencies: - - supports-color dev: true /lilconfig/2.0.5: @@ -6527,8 +6659,6 @@ packages: micromatch: 3.1.10 resolve: 1.22.0 stack-trace: 0.0.10 - transitivePeerDependencies: - - supports-color dev: true /mdn-data/2.0.23: @@ -6586,8 +6716,6 @@ packages: regex-not: 1.0.2 snapdragon: 0.8.2 to-regex: 3.0.2 - transitivePeerDependencies: - - supports-color dev: true /micromatch/4.0.5: @@ -6725,7 +6853,6 @@ packages: resolution: {integrity: sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true - dev: true /nanomatch/1.2.13: resolution: {integrity: sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==} @@ -6742,8 +6869,6 @@ packages: regex-not: 1.0.2 snapdragon: 0.8.2 to-regex: 3.0.2 - transitivePeerDependencies: - - supports-color dev: true /negotiator/0.6.3: @@ -7505,16 +7630,15 @@ packages: posthtml-render: 1.4.0 dev: true + /preact/10.7.2: + resolution: {integrity: sha512-GLjn0I3r6ka+NvxJUppsVFqb4V0qDTEHT/QxHlidPuClGaxF/4AI2Qti4a0cv3XMh5n1+D3hLScW10LRIm5msQ==} + dev: false + /pretty-bytes/5.6.0: resolution: {integrity: sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg==} engines: {node: '>=6'} dev: true - /pretty-bytes/6.0.0: - resolution: {integrity: sha512-6UqkYefdogmzqAZWzJ7laYeJnaXDy2/J+ZqiiMtS7t7OfpXWTlaeGMwX8U6EFvPV/YWWEKRkS8hKS4k60WHTOg==} - engines: {node: ^14.13.1 || >=16.0.0} - dev: false - /pretty-hrtime/1.0.3: resolution: {integrity: sha1-t+PqQkNaTJsnWdmeDyAesZWALuE=} engines: {node: '>= 0.8'} @@ -7781,8 +7905,6 @@ packages: graceful-fs: 4.2.10 micromatch: 3.1.10 readable-stream: 2.3.7 - transitivePeerDependencies: - - supports-color dev: true /readdirp/3.6.0: @@ -8082,8 +8204,6 @@ packages: dependencies: debug: 2.6.9 minimatch: 3.1.2 - transitivePeerDependencies: - - supports-color dev: true /restore-cursor/2.0.0: @@ -8295,8 +8415,6 @@ packages: on-finished: 2.3.0 range-parser: 1.2.1 statuses: 1.4.0 - transitivePeerDependencies: - - supports-color dev: true /serialize-javascript/4.0.0: @@ -8316,8 +8434,6 @@ packages: http-errors: 1.6.3 mime-types: 2.1.35 parseurl: 1.3.3 - transitivePeerDependencies: - - supports-color dev: true /serve-static/1.13.2: @@ -8328,8 +8444,6 @@ packages: escape-html: 1.0.3 parseurl: 1.3.3 send: 0.16.2 - transitivePeerDependencies: - - supports-color dev: true /server-destroy/1.0.1: @@ -8424,8 +8538,6 @@ packages: source-map: 0.5.7 source-map-resolve: 0.5.3 use: 3.1.1 - transitivePeerDependencies: - - supports-color dev: true /socket.io-adapter/2.4.0: @@ -9575,6 +9687,15 @@ packages: resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==} dev: true + /webcola/3.4.0: + resolution: {integrity: sha512-4BiLXjXw3SJHo3Xd+rF+7fyClT6n7I+AR6TkBqyQ4kTsePSAMDLRCXY1f3B/kXJeP9tYn4G1TblxTO+jAt0gaw==} + dependencies: + d3-dispatch: 1.0.6 + d3-drag: 1.2.5 + d3-shape: 1.3.7 + d3-timer: 1.0.10 + dev: false + /webidl-conversions/3.0.1: resolution: {integrity: sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=} diff --git a/src/css/app.scss b/src/css/app.scss index 57b0971..9fbb568 100644 --- a/src/css/app.scss +++ b/src/css/app.scss @@ -592,4 +592,11 @@ details.accordian { .giscus-frame { color-scheme: none; +} + +#analyzer { + color-scheme: none; + @apply w-full rounded-lg; + resize: vertical; + min-height: theme("spacing.2"); } \ No newline at end of file diff --git a/src/pug/about.pug b/src/pug/about.pug index 63bd274..3c10eef 100644 --- a/src/pug/about.pug +++ b/src/pug/about.pug @@ -33,8 +33,10 @@ block content | as a wasm port of brotli, a(href="https://github.com/denosaurs/deno_lz4" target="_blank" rel="noopener") deno_lz4 | as a wasm port of lz4, - a(href="https://github.com/sindresorhus/pretty-bytes" target="_blank" rel="noopener") pretty-bytes + a(href="https://github.com/visionmedia/bytes.js" target="_blank" rel="noopener") bytes | to convert the compressed size to human readable values, + a(href="https://github.com/btd/esbuild-visualizer" target="_blank" rel="noopener") esbuild-visualizer + | to visualize and analyze your esbuild bundle to see which modules are taking up space, a(href="https://github.com/mikecao/umami" target="_blank" rel="noopener") umami | for private, publicly available analytics and general usage stats all without cookies, and a(href="https://github.com/mlomb/countapi-js" target="_blank" rel="noopener") countapi-js diff --git a/src/pug/index.pug b/src/pug/index.pug index 22de7c8..8c33009 100644 --- a/src/pug/index.pug +++ b/src/pug/index.pug @@ -127,7 +127,26 @@ block content .info-pane(class="!pt-0") +code-info("sm:hidden") - br + br + + details#analysis.accordian(class="bg-white border border-gray-300 dark:bg-elevated dark:border-gray-700").rounded-md + summary + p.px-4.py-2.cursor-pointer.select-none Analysis + div.content.pl-4.pr-2.py-4 + p + :markdown-it(linkify langPrefix='language-') + Enable the `analysis` config to view the size of output files with interactive zoomable charts. + ```ts + { + "analysis": "treemap" | "network" | "sunburst" | true | false, + "esbuild": { ... } + } + ``` + br + iframe#analyzer(src="about:blank" allowtransparency="true") + .drag-section.vertical#handle-3 + .drag-handle + br mixin divider diff --git a/src/ts/configs/bundle-options.ts b/src/ts/configs/bundle-options.ts index 5107f62..04da460 100644 --- a/src/ts/configs/bundle-options.ts +++ b/src/ts/configs/bundle-options.ts @@ -1,5 +1,7 @@ import type { BuildOptions } from "esbuild-wasm"; +import type { TemplateType } from "../plugins/analyzer/types/template-types"; + import { deepAssign } from "../util/deep-equal"; import { DEFAULT_CDN_HOST } from "../util/util-cdn"; @@ -51,11 +53,18 @@ export type BundleConfigOptions = { * ``` */ compression?: CompressionOptions | CompressionType + + /** + * Generates interactive zoomable charts displaing the size of output files. + * It's a great way to determine what causes the bundle size to be so large. + */ + analysis?: TemplateType | boolean }; export const EasyDefaultConfig: BundleConfigOptions = { "cdn": DEFAULT_CDN_HOST, "compression": "gzip", + "analysis": false, "esbuild": { "target": ["esnext"], "format": "esm", diff --git a/src/ts/index.ts b/src/ts/index.ts index b85ac9d..981f91d 100644 --- a/src/ts/index.ts +++ b/src/ts/index.ts @@ -232,6 +232,13 @@ export const build = async (app: App) => { { title: `Bundle size is ${initialSize} -> ${size}` } ]); fileSizeEl.forEach(el => (el.textContent = `` + size)); + }, + iframe(details) { + let { content: newHTML } = details; + let iframe = document.querySelector("#analyzer") as HTMLIFrameElement; + iframe.contentWindow.document.open(); + iframe.contentWindow.document.write(newHTML); + iframe.contentWindow.document.close(); } }); @@ -425,51 +432,6 @@ export const build = async (app: App) => { loadingContainerEl = null; FadeLoadingScreen = null; - // const TypeAquisition = setupTypeAcquisition({ - // projectName: "My ATA Project", - // typescript: ts, - // logger: console, - // async fetcher(input, init) { - // return await getRequest(input, false, init); - // }, - // delegate: { - // started: () => { - // console.log("Types Aquisition Start") - // }, - // receivedFile: (code: string, path: string) => { - // // Add code to your runtime at the path... - // languages.typescript.typescriptDefaults.addExtraLib(code, "file://" + path); - - // const uri = Uri.file(path); - // if (Editor.getModel(uri) === null) { - // Editor.createModel(code, "typescript", uri); - // } - // }, - // progress: (downloaded: number, total: number) => { - // console.log(`Got ${downloaded} out of ${total}`) - // }, - // finished: vfs => { - // console.log("Types Aquisition Done"); - // }, - // }, - // }); - - // const getTypescriptTypes = async (model: typeof inputModel) => { - // try { - // const worker = await languages.typescript.getTypeScriptWorker(); - // await worker(model.uri); - - // // @ts-ignore - // TypeAquisition(model.getValue()); - // } catch (e) { - // console.warn(e); - // } - // }; - - // setTimeout(() => { - // getTypescriptTypes(inputModel); - // }, 1000); - // Update the URL share query everytime user makes a change editor.onDidChangeModelContent( debounce((e) => { @@ -707,13 +669,12 @@ export const InitialRender = (shareURL: URL) => { }, 50)).observe(parentEl); })(); - // Drag handle - Resizable Full height - (() => { + let dragHandleY = (target = ".flex-wrapper", section = ".drag-section#handle-2", handle = ".drag-handle") => { // Based on the tutorial at https://htmldom.dev/create-resizable-split-views/ // Honestly, I am surprised that native dragging doesn't work for this use case - const dragSection = document.querySelector(".drag-section#handle-2") as HTMLElement; - const dragHandle = dragSection.querySelector(".drag-handle") as HTMLElement; - const targetEl = document.querySelector(".flex-wrapper") as HTMLElement; + const dragSection = document.querySelector(section) as HTMLElement; + const dragHandle = dragSection.querySelector(handle) as HTMLElement; + const targetEl = document.querySelector(target) as HTMLElement; // The current position of mouse let y = 0; @@ -755,7 +716,13 @@ export const InitialRender = (shareURL: URL) => { }; dragHandle.addEventListener('pointerdown', pointerDown); - })(); + }; + + // Drag handle - Resizable Full height + dragHandleY(); + + // Drag handle - (Analyzer iframe) Resizable Full height + dragHandleY("#analyzer", ".drag-section#handle-3"); // Console solidjs component (async () => { diff --git a/src/ts/plugins/analyzer/index.ts b/src/ts/plugins/analyzer/index.ts new file mode 100644 index 0000000..90b5803 --- /dev/null +++ b/src/ts/plugins/analyzer/index.ts @@ -0,0 +1,17 @@ +// Based off of https://github.com/btd/esbuild-visualizer +import type { TemplateType } from "./types/template-types"; +import type { Metadata } from "./types/metafile"; +import { visualizer } from "./plugin/index"; + +export const analyze = async (metadata: Metadata, template: TemplateType = "treemap", logger = console.log) => { + try { + return await visualizer(metadata, { + title: "Bundle Analysis", + template, + }); + } catch (err) { + let { stack } = (err as Error); + logger([`[Analyzer] ${err}`, stack], "warn"); + console.warn(err, stack); + } +}; diff --git a/src/ts/plugins/analyzer/plugin/build-stats.ts b/src/ts/plugins/analyzer/plugin/build-stats.ts new file mode 100644 index 0000000..da19a92 --- /dev/null +++ b/src/ts/plugins/analyzer/plugin/build-stats.ts @@ -0,0 +1,58 @@ +/// +import type { VisualizerData } from "../types/types"; +import type { TemplateType } from "../types/template-types"; + +// import { getRequest } from "../../../util/cache"; + +const htmlEscape = (str: string) => + str.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">"); + +interface BuildHtmlOptions { + title: string; + data: VisualizerData; + template: TemplateType; +} + +export async function buildHtml({ title, data, template }: BuildHtmlOptions): Promise { + // const [script, style]: Response[] = await Promise.all([ + // getRequest(`/js/${template}.min.js`), + // getRequest(`/js/${template}.min.css`) + // ]); + + return ` + + + + + + + ${htmlEscape(title)} + + + + +
+ + + + + `; +} diff --git a/src/ts/plugins/analyzer/plugin/data.ts b/src/ts/plugins/analyzer/plugin/data.ts new file mode 100644 index 0000000..3f50d19 --- /dev/null +++ b/src/ts/plugins/analyzer/plugin/data.ts @@ -0,0 +1,150 @@ +import type { GetModuleInfo } from "../types/rollup"; +import type { ModuleLink, ModuleRenderInfo, ModuleTree, ModuleTreeLeaf } from "../types/types"; + +import { isModuleTree } from "../utils/is-module-tree"; +import { ModuleMapper } from "./module-mapper"; + +interface MappedNode { + uid: string; +} + +const addToPath = (moduleId: string, tree: ModuleTree, modulePath: string[], node: MappedNode): void => { + if (modulePath.length === 0) { + throw new Error(`Error adding node to path ${moduleId}`); + } + + const [head, ...rest] = modulePath; + + if (rest.length === 0) { + tree.children.push({ ...node, name: head }); + return; + } else { + let newTree = tree.children.find((folder): folder is ModuleTree => folder.name === head && isModuleTree(folder)); + + if (!newTree) { + newTree = { name: head, children: [] }; + tree.children.push(newTree); + } + addToPath(moduleId, newTree, rest, node); + return; + } +}; + +// TODO try to make it without recursion, but still typesafe +const mergeSingleChildTrees = (tree: ModuleTree): ModuleTree | ModuleTreeLeaf => { + if (tree.children.length === 1) { + const child = tree.children[0]; + const name = `${tree.name}/${child.name}`; + if (isModuleTree(child)) { + tree.name = name; + tree.children = child.children; + return mergeSingleChildTrees(tree); + } else { + return { + name, + uid: child.uid, + }; + } + } else { + tree.children = tree.children.map((node) => { + if (isModuleTree(node)) { + return mergeSingleChildTrees(node); + } else { + return node; + } + }); + return tree; + } +}; + +export const buildTree = (bundleId: string, modules: Array, mapper: ModuleMapper): ModuleTree => { + const tree: ModuleTree = { + name: bundleId, + children: [], + }; + + for (const { id, renderedLength, gzipLength, brotliLength } of modules) { + const bundleModuleUid = mapper.setValue(bundleId, id, { + renderedLength, + gzipLength, + brotliLength, + }); + + const trimmedModuleId = mapper.trimProjectRootId(id); + + const pathParts = trimmedModuleId.split(/\\|\//).filter((p) => p !== ""); + addToPath(trimmedModuleId, tree, pathParts, { uid: bundleModuleUid }); + } + + tree.children = tree.children.map((node) => { + if (isModuleTree(node)) { + return mergeSingleChildTrees(node); + } else { + return node; + } + }); + + return tree; +}; + +export const mergeTrees = (trees: Array): ModuleTree => { + const newTree = { + name: "root", + children: trees, + isRoot: true, + }; + + return newTree; +}; + +export const addLinks = ( + bundleId: string, + startModuleId: string, + getModuleInfo: GetModuleInfo, + links: ModuleLink[], + mapper: ModuleMapper +): void => { + const processedNodes: Record = {}; + + const moduleIds = [startModuleId]; + + while (moduleIds.length > 0) { + const moduleId = moduleIds.shift() as string; + + if (processedNodes[moduleId]) { + continue; + } else { + processedNodes[moduleId] = true; + } + + const moduleInfo = getModuleInfo(moduleId); + + if (!mapper.hasValue(bundleId, moduleId)) { + mapper.setValue(bundleId, moduleId, { renderedLength: 0 }); + } + + if (!moduleInfo) { + return; + } + + if (moduleInfo.isEntry) { + mapper.appendValue(bundleId, moduleId, { isEntry: true }); + } + if (moduleInfo.isExternal) { + mapper.appendValue(bundleId, moduleId, { isExternal: true }); + } + + const moduleUid = mapper.getModuleUid(moduleId); + + for (const importedId of moduleInfo.importedIds) { + const importedUid = mapper.getModuleUid(importedId); + links.push({ source: moduleUid, target: importedUid }); + moduleIds.push(importedId); + } + for (const importedId of moduleInfo.dynamicallyImportedIds) { + const importedUid = mapper.getModuleUid(importedId); + links.push({ source: moduleUid, target: importedUid, dynamic: true }); + moduleIds.push(importedId); + } + } +}; diff --git a/src/ts/plugins/analyzer/plugin/index.ts b/src/ts/plugins/analyzer/plugin/index.ts new file mode 100644 index 0000000..86a3302 --- /dev/null +++ b/src/ts/plugins/analyzer/plugin/index.ts @@ -0,0 +1,85 @@ +import type { TemplateType } from "../types/template-types"; +import type { ModuleLink, ModuleRenderInfo, ModuleTree, ModuleTreeLeaf, VisualizerData } from "../types/types"; +import type { Metadata, MetadataOutput } from "../types/metafile"; +import type { ModuleInfo } from "../types/rollup"; + +import { ModuleMapper } from "./module-mapper"; +import { addLinks, buildTree, mergeTrees } from "./data"; +import { buildHtml } from "./build-stats"; + +export interface PluginVisualizerOptions { + title?: string; + template?: TemplateType; +} + +export const visualizer = async (metadata: Metadata, opts: PluginVisualizerOptions = {}): Promise => { + const title = opts.title ?? "Esbuild Visualizer"; + + const template = opts.template ?? "treemap"; + const projectRoot = ""; + + const renderedModuleToInfo = (id: string, mod: { bytesInOutput: number }): ModuleRenderInfo => { + const result = { + id, + renderedLength: mod.bytesInOutput, + }; + return result; + }; + + const roots: Array = []; + const mapper = new ModuleMapper(projectRoot); + const links: ModuleLink[] = []; + + // collect trees + for (const [bundleId, bundle] of Object.entries(metadata.outputs)) { + const modules = Object.entries(bundle.inputs).map(([id, mod]) => renderedModuleToInfo(id, mod)); + + const tree = buildTree(bundleId, modules, mapper); + + roots.push(tree); + } + + const getModuleInfo = (bundle: MetadataOutput) => (moduleId: string): ModuleInfo => { + const input = metadata.inputs?.[moduleId]; + + const imports = input?.imports.map((i) => i.path); + + return { + renderedLength: bundle.inputs?.[moduleId]?.bytesInOutput ?? 0, + importedIds: imports ?? [], + dynamicallyImportedIds: [], + isEntry: bundle.entryPoint === moduleId, + isExternal: false, + }; + }; + + for (const [bundleId, bundle] of Object.entries(metadata.outputs)) { + if (bundle.entryPoint == null) continue; + + addLinks(bundleId, bundle.entryPoint, getModuleInfo(bundle), links, mapper); + } + + const tree = mergeTrees(roots); + + const data: VisualizerData = { + version: 2.0, + tree, + nodes: mapper.getNodes(), + nodeParts: mapper.getNodeParts(), + links, + env: {}, + options: { + gzip: false, + brotli: false, + sourcemap: false, + }, + }; + + const fileContent: string = await buildHtml({ + title, + data, + template, + }); + + return fileContent; +}; diff --git a/src/ts/plugins/analyzer/plugin/module-mapper.ts b/src/ts/plugins/analyzer/plugin/module-mapper.ts new file mode 100644 index 0000000..a19518b --- /dev/null +++ b/src/ts/plugins/analyzer/plugin/module-mapper.ts @@ -0,0 +1,84 @@ +import { customAlphabet } from "nanoid/non-secure"; +import type { ModuleRenderInfo, ModuleUID } from "../types/types"; + +const nanoid = customAlphabet("1234567890abcdef", 4); + +const UNIQUE_PREFIX = nanoid(); +let COUNTER = 0; + +const uniqueId = (): ModuleUID => `${UNIQUE_PREFIX}-${COUNTER++}`; + +type ModuleIdStorage = { + bundles: Record; + uid: ModuleUID; +}; + +export class ModuleMapper { + private nodes: Record = {}; + private nodeIds: Record = {}; + + constructor(private projectRoot: string | RegExp) {} + + trimProjectRootId(moduleId: string): string { + return moduleId.replace(this.projectRoot, ""); + } + + getModuleUid(moduleId: string): ModuleUID { + if (!(moduleId in this.nodeIds)) { + this.nodeIds[moduleId] = { bundles: {}, uid: uniqueId() }; + } + + return this.nodeIds[moduleId].uid; + } + + getBundleModuleUid(bundleId: string, moduleId: string): ModuleUID { + if (!(moduleId in this.nodeIds)) { + this.nodeIds[moduleId] = { bundles: {}, uid: uniqueId() }; + } + if (!(bundleId in this.nodeIds[moduleId].bundles)) { + this.nodeIds[moduleId].bundles[bundleId] = uniqueId(); + } + + return this.nodeIds[moduleId].bundles[bundleId]; + } + + setValue(bundleId: string, moduleId: string, value: Omit): ModuleUID { + const uid = this.getBundleModuleUid(bundleId, moduleId); + if (uid in this.nodes) { + throw new Error( + `Override module: bundle id ${bundleId}, module id ${moduleId}, value ${JSON.stringify( + value + )}, existing value: ${JSON.stringify(this.nodes[uid])}` + ); + } + const id = this.trimProjectRootId(moduleId); + this.nodes[uid] = { ...value, id }; + return uid; + } + + appendValue(bundleId: string, moduleId: string, value: Partial>): ModuleUID { + const uid = this.getBundleModuleUid(bundleId, moduleId); + if (!(uid in this.nodes)) { + throw new Error(`Missing module: bundle id ${bundleId}, module id ${moduleId}, value ${JSON.stringify(value)}`); + } + const id = this.trimProjectRootId(moduleId); + this.nodes[uid] = { ...this.nodes[uid], ...value, id }; + return uid; + } + + hasValue(bundleId: string, moduleId: string): boolean { + return !!this.nodeIds?.[moduleId]?.bundles?.[bundleId]; + } + + getNodes(): ModuleMapper["nodes"] { + return this.nodes; + } + + getNodeParts(): Record> { + const nodeParts: Record> = {}; + for (const nodeId of Object.values(this.nodeIds)) { + nodeParts[nodeId.uid] = nodeId.bundles; + } + return nodeParts; + } +} diff --git a/src/ts/plugins/analyzer/src/color.ts b/src/ts/plugins/analyzer/src/color.ts new file mode 100644 index 0000000..132e27f --- /dev/null +++ b/src/ts/plugins/analyzer/src/color.ts @@ -0,0 +1,22 @@ +import type { ModuleTree, ModuleTreeLeaf } from "../types/types"; +import { HierarchyRectangularNode } from "d3-hierarchy"; + +export type CssColor = string; + +export const COLOR_DEFAULT_FILE: CssColor = "#db7100"; +export const COLOR_DEFAULT_OWN_SOURCE: CssColor = "#487ea4"; +export const COLOR_DEFAULT_VENDOR_SOURCE: CssColor = "#599e59"; + +export const COLOR_BASE: CssColor = "#cecece"; + +const colorDefault = (node: HierarchyRectangularNode): CssColor => { + if (node.children && node.children.length) { + const parents = node.ancestors(); + const hasNodeModules = parents.some(({ data: { name } }) => name === "node_modules"); + return hasNodeModules ? COLOR_DEFAULT_VENDOR_SOURCE : COLOR_DEFAULT_OWN_SOURCE; + } else { + return COLOR_DEFAULT_FILE; + } +}; + +export default colorDefault; diff --git a/src/ts/plugins/analyzer/src/network/chart.tsx b/src/ts/plugins/analyzer/src/network/chart.tsx new file mode 100644 index 0000000..8148683 --- /dev/null +++ b/src/ts/plugins/analyzer/src/network/chart.tsx @@ -0,0 +1,46 @@ +import { h, Fragment, FunctionalComponent } from "preact"; +import { useState, useEffect } from "preact/hooks"; +import webcola from "webcola"; + +import type { SizeKey } from "../../types/types"; +import { Tooltip } from "./tooltip"; +import { Network } from "./network"; +import { NetworkLink, NetworkNode } from "./index"; + +export interface ChartProps { + sizeProperty: SizeKey; + links: NetworkLink[]; + nodes: NetworkNode[]; + groups: Record; +} + +export const Chart: FunctionalComponent = ({ sizeProperty, links, nodes, groups }) => { + const [showTooltip, setShowTooltip] = useState(false); + const [tooltipNode, setTooltipNode] = useState(undefined); + + useEffect(() => { + const handleMouseOut = () => { + setShowTooltip(false); + }; + + document.addEventListener("mouseover", handleMouseOut); + return () => { + document.removeEventListener("mouseover", handleMouseOut); + }; + }, []); + + return ( + <> + { + setTooltipNode(node); + setShowTooltip(true); + }} + /> + + + ); +}; diff --git a/src/ts/plugins/analyzer/src/network/color.ts b/src/ts/plugins/analyzer/src/network/color.ts new file mode 100644 index 0000000..fd320de --- /dev/null +++ b/src/ts/plugins/analyzer/src/network/color.ts @@ -0,0 +1,5 @@ +import { COLOR_DEFAULT_OWN_SOURCE, COLOR_DEFAULT_VENDOR_SOURCE, COLOR_BASE, CssColor } from "../color"; +import { NODE_MODULES } from "./util"; + +export const getModuleColor = ({ renderedLength, id }: { renderedLength: number; id: string }): CssColor => + renderedLength === 0 ? COLOR_BASE : NODE_MODULES.test(id) ? COLOR_DEFAULT_VENDOR_SOURCE : COLOR_DEFAULT_OWN_SOURCE; diff --git a/src/ts/plugins/analyzer/src/network/index.tsx b/src/ts/plugins/analyzer/src/network/index.tsx new file mode 100644 index 0000000..1eaef98 --- /dev/null +++ b/src/ts/plugins/analyzer/src/network/index.tsx @@ -0,0 +1,94 @@ +import type { ModuleRenderInfo, ModuleRenderSizes, ModuleUID, SizeKey, VisualizerData } from "../../types/types"; + +import { h, createContext, render } from "preact"; +import webcola from "webcola"; + +import { Main } from "./main"; + +import { getAvailableSizeOptions } from "../sizes"; +import { CssColor } from "../color"; + +import "../style/style-treemap.scss"; + +export type NetworkNode = NodeInfo & { color: CssColor; radius: number } & webcola.Node; +export type NetworkLink = webcola.Link; + +export interface StaticData { + data: VisualizerData; + availableSizeProperties: SizeKey[]; + width: number; + height: number; +} + +export type NodeInfo = { bundles: Record; uid: ModuleUID } & ModuleRenderInfo; +export type ModuleNodeInfo = Map; + +export interface ChartData { + importedCache: ModuleNodeInfo; + importedByCache: ModuleNodeInfo; + nodes: Record; +} + +export type Context = StaticData & ChartData; + +export const StaticContext = createContext(({} as unknown) as Context); + +const createNodeInfo = (data: VisualizerData, availableSizeProperties: SizeKey[], uid: ModuleUID): NodeInfo => { + const parts = data.nodeParts[uid]; + const entries: [string, ModuleRenderInfo][] = Object.entries(parts).map(([bundleId, partUid]) => [ + bundleId, + data.nodes[partUid], + ]); + const sizes = (Object.fromEntries(availableSizeProperties.map((key) => [key, 0])) as unknown) as ModuleRenderSizes; + + for (const [, renderInfo] of entries) { + for (const sizeKey of availableSizeProperties) { + sizes[sizeKey] += renderInfo[sizeKey] ?? 0; + } + } + const bundles = Object.fromEntries(entries); + return { uid, bundles, ...sizes, id: entries[0][1].id }; +}; + +const drawChart = (parentNode: Element, data: VisualizerData, width: number, height: number): void => { + const availableSizeProperties = getAvailableSizeOptions(data.options); + + const importedByCache = new Map(); + const importedCache = new Map(); + + const nodes: Record = {}; + for (const uid of Object.keys(data.nodeParts)) { + nodes[uid] = createNodeInfo(data, availableSizeProperties, uid); + } + + for (const { source, target } of data.links) { + if (!importedByCache.has(target)) { + importedByCache.set(target, []); + } + if (!importedCache.has(source)) { + importedCache.set(source, []); + } + + importedByCache.get(target)?.push(nodes[source]); + importedCache.get(source)?.push(nodes[target]); + } + + render( + +
+ , + parentNode + ); +}; + +export default drawChart; diff --git a/src/ts/plugins/analyzer/src/network/main.tsx b/src/ts/plugins/analyzer/src/network/main.tsx new file mode 100644 index 0000000..db91f0f --- /dev/null +++ b/src/ts/plugins/analyzer/src/network/main.tsx @@ -0,0 +1,149 @@ +import { h, Fragment, FunctionalComponent } from "preact"; +import { useContext, useMemo, useState } from "preact/hooks"; +import { scaleSqrt } from "d3-scale"; +import { max } from "d3-array"; +import webcola from "webcola"; + +import type { ModuleRenderInfo, ModuleUID, SizeKey } from "../../types/types"; + +import { SideBar } from "../sidebar"; +import { Chart } from "./chart"; +import { NODE_MODULES } from "./util"; + +import { NetworkLink, NetworkNode, StaticContext } from "./index"; +import { getModuleColor } from "./color"; +import { useFilter } from "../use-filter"; + +export type LinkInfo = ModuleRenderInfo & { uid: ModuleUID }; +export type ModuleLinkInfo = Map; + +export const Main: FunctionalComponent = () => { + const { availableSizeProperties, nodes, data, width, height } = useContext(StaticContext); + + const [sizeProperty, setSizeProperty] = useState(availableSizeProperties[0]); + + const { getModuleFilterMultiplier, setExcludeFilter, setIncludeFilter } = useFilter(); + + const sizeScale = useMemo(() => { + const maxLines = max(Object.values(nodes), (d) => d[sizeProperty]) as number; + const size = scaleSqrt().domain([1, maxLines]).range([5, 30]); + return size; + }, [nodes, sizeProperty]); + + const processedNodes = Object.values(nodes) + .map((node) => { + const radius = sizeScale(node[sizeProperty] as number) + 1; + return { + ...node, + width: radius * 2, + height: radius * 2, + radius, + color: getModuleColor(node), + }; + }) + .filter((networkNode) => getModuleFilterMultiplier(networkNode) === 1) as Array; + + const groups: Record = {}; + for (const node of processedNodes) { + const match = NODE_MODULES.exec(node.id); + if (match) { + const [, nodeModuleName] = match; + groups[nodeModuleName] = groups[nodeModuleName] ?? { leaves: [], padding: 1 }; + groups[nodeModuleName].leaves?.push(node); + } + } + + const nodesCache = new Map(processedNodes.map((d) => [d.uid, d])); + + // webcola has weird types, layour require array of links to Node references, but Nodes are computed from later + const links: NetworkLink[] = data.links + .map(({ source, target }) => { + return { + source: nodesCache.get(source) as NetworkNode, + target: nodesCache.get(target) as NetworkNode, + value: 1, + }; + }) + .filter(({ source, target }) => { + return source && target; + }); + + const cola = webcola.adaptor({}).size([width, height]); + + const paddingX = 20; + const paddingY = 20; + + const pageBounds = { + x: paddingX, + y: paddingY, + width: width - paddingX, + height: height - paddingY, + }; + + const realGraphNodes = processedNodes.slice(0); + const topLeft = { x: pageBounds.x, y: pageBounds.y, fixed: 1 }; + const tlIndex = (processedNodes as webcola.InputNode[]).push(topLeft) - 1; + const bottomRight = { + x: pageBounds.x + pageBounds.width, + y: pageBounds.y + pageBounds.height, + fixed: 1, + }; + const brIndex = (processedNodes as webcola.InputNode[]).push(bottomRight) - 1; + const constraints = []; + for (let i = 0; i < realGraphNodes.length; i++) { + const node = realGraphNodes[i]; + constraints.push({ + axis: "x", + type: "separation", + left: tlIndex, + right: i, + gap: node.radius, + }); + constraints.push({ + axis: "y", + type: "separation", + left: tlIndex, + right: i, + gap: node.radius, + }); + constraints.push({ + axis: "x", + type: "separation", + left: i, + right: brIndex, + gap: node.radius, + }); + constraints.push({ + axis: "y", + type: "separation", + left: i, + right: brIndex, + gap: node.radius, + }); + } + + cola + .nodes(processedNodes) + .links(links) + //.groups(Object.values(groups)) + .groupCompactness(1e-3) + .constraints(constraints) + .jaccardLinkLengths(50, 0.7) + .avoidOverlaps(true) + .handleDisconnected(false) + .start(30, 30, 30, 30, false, true) + .stop(); + + return ( + <> + + + + ); +}; diff --git a/src/ts/plugins/analyzer/src/network/network.tsx b/src/ts/plugins/analyzer/src/network/network.tsx new file mode 100644 index 0000000..554e02f --- /dev/null +++ b/src/ts/plugins/analyzer/src/network/network.tsx @@ -0,0 +1,72 @@ +import { h, FunctionalComponent } from "preact"; +import { useContext } from "preact/hooks"; +import webcola from "webcola"; +import { NetworkLink, NetworkNode, StaticContext } from "./index"; +import { COLOR_BASE } from "../color"; + +export interface NetworkProps { + onNodeHover: (event: NetworkNode) => void; + nodes: NetworkNode[]; + links: NetworkLink[]; + + groups: Record; +} + +export const Network: FunctionalComponent = ({ links, nodes, groups, onNodeHover }) => { + const { width, height } = useContext(StaticContext); + return ( + + + {Object.entries(groups).map(([name, group]) => { + const bounds = group.bounds; + return ( + + ); + })} + + + {links.map((link) => { + return ( + + ); + })} + + + {nodes.map((node) => { + return ( + { + evt.stopPropagation(); + onNodeHover(node); + }} + /> + ); + })} + + + ); +}; diff --git a/src/ts/plugins/analyzer/src/network/tooltip.tsx b/src/ts/plugins/analyzer/src/network/tooltip.tsx new file mode 100644 index 0000000..bba03bf --- /dev/null +++ b/src/ts/plugins/analyzer/src/network/tooltip.tsx @@ -0,0 +1,100 @@ +import type { SizeKey } from "../../types/types"; + +import { h, Fragment, FunctionalComponent } from "preact"; +import { useContext, useEffect, useMemo, useRef, useState, type MutableRef } from "preact/hooks"; +import { format as formatBytes } from "bytes"; +import { StaticContext, NetworkNode } from "./index"; +import { LABELS } from "../sizes"; + +export interface TooltipProps { + node?: NetworkNode; + sizeProperty: SizeKey; + visible: boolean; +} + +const Tooltip_marginX = 10; +const Tooltip_marginY = 30; + +export const Tooltip: FunctionalComponent = ({ node, visible, sizeProperty }) => { + const { availableSizeProperties, importedByCache } = useContext(StaticContext); + + const ref = useRef() as MutableRef; + const [style, setStyle] = useState({}); + const content = useMemo(() => { + if (!node) return null; + + return ( + <> +
{node.id}
+ {availableSizeProperties.map((sizeProp) => { + if (sizeProp === sizeProperty) { + return ( +
+ + {LABELS[sizeProp]}: {formatBytes(node[sizeProp] ?? 0)} + +
+ ); + } else { + return ( +
+ {LABELS[sizeProp]}: {formatBytes(node[sizeProp] ?? 0)} +
+ ); + } + })} + {node.uid && importedByCache.has(node.uid) && ( +
+
+ Imported By: +
+ {[...new Set(importedByCache.get(node.uid)?.map(({ id }) => id))].map((id) => ( +
{id}
+ ))} +
+ )} + + ); + }, [availableSizeProperties, importedByCache, node, sizeProperty]); + + const updatePosition = (mouseCoords: { x: number; y: number }) => { + const pos = { + left: mouseCoords.x + Tooltip_marginX, + top: mouseCoords.y + Tooltip_marginY, + }; + + const boundingRect = ref.current.getBoundingClientRect(); + + if (pos.left + boundingRect.width > window.innerWidth) { + // Shifting horizontally + pos.left = window.innerWidth - boundingRect.width; + } + + if (pos.top + boundingRect.height > window.innerHeight) { + // Flipping vertically + pos.top = mouseCoords.y - Tooltip_marginY - boundingRect.height; + } + + setStyle(pos); + }; + + useEffect(() => { + const handleMouseMove = (event: MouseEvent) => { + updatePosition({ + x: event.pageX, + y: event.pageY, + }); + }; + + document.addEventListener("mousemove", handleMouseMove, true); + return () => { + document.removeEventListener("mousemove", handleMouseMove, true); + }; + }, []); + + return ( +
+ {content} +
+ ); +}; diff --git a/src/ts/plugins/analyzer/src/network/util.ts b/src/ts/plugins/analyzer/src/network/util.ts new file mode 100644 index 0000000..712df58 --- /dev/null +++ b/src/ts/plugins/analyzer/src/network/util.ts @@ -0,0 +1 @@ +export const NODE_MODULES = /.*(?:\/|\\\\)?node_modules(?:\/|\\\\)([^/\\]+)(?:\/|\\\\).+/; diff --git a/src/ts/plugins/analyzer/src/sidebar.tsx b/src/ts/plugins/analyzer/src/sidebar.tsx new file mode 100644 index 0000000..ee4a99a --- /dev/null +++ b/src/ts/plugins/analyzer/src/sidebar.tsx @@ -0,0 +1,74 @@ +import type { SizeKey } from "../types/types"; + +import { h, FunctionalComponent, JSX } from "preact"; +import { useState } from "preact/hooks"; +import { LABELS } from "./sizes"; + +export interface SideBarProps { + availableSizeProperties: SizeKey[]; + sizeProperty: SizeKey; + setSizeProperty: (key: SizeKey) => void; + onExcludeChange: (value: string) => void; + onIncludeChange: (value: string) => void; +} + +export const SideBar: FunctionalComponent = ({ + availableSizeProperties, + sizeProperty, + setSizeProperty, + onExcludeChange, + onIncludeChange, +}) => { + const [includeValue, setIncludeValue] = useState(""); + const [excludeValue, setExcludeValue] = useState(""); + + const handleSizePropertyChange = (sizeProp: SizeKey) => () => { + if (sizeProp !== sizeProperty) { + setSizeProperty(sizeProp); + } + }; + + const handleIncludeChange = (event: JSX.TargetedEvent) => { + const value = event.currentTarget.value; + setIncludeValue(value); + onIncludeChange(value); + }; + + const handleExcludeChange = (event: JSX.TargetedEvent) => { + const value = event.currentTarget.value; + setExcludeValue(value); + onExcludeChange(value); + }; + + return ( + + ); +}; diff --git a/src/ts/plugins/analyzer/src/sizes.ts b/src/ts/plugins/analyzer/src/sizes.ts new file mode 100644 index 0000000..9c005f5 --- /dev/null +++ b/src/ts/plugins/analyzer/src/sizes.ts @@ -0,0 +1,19 @@ +import type { SizeKey, VisualizerData } from "../types/types"; + +export const LABELS: Record = { + renderedLength: "Rendered", + gzipLength: "Gzip", + brotliLength: "Brotli", +}; + +export const getAvailableSizeOptions = (options: VisualizerData["options"]): SizeKey[] => { + const availableSizeProperties: SizeKey[] = ["renderedLength"]; + if (options.gzip) { + availableSizeProperties.push("gzipLength"); + } + if (options.brotli) { + availableSizeProperties.push("brotliLength"); + } + + return availableSizeProperties; +}; diff --git a/src/ts/plugins/analyzer/src/style/_base.scss b/src/ts/plugins/analyzer/src/style/_base.scss new file mode 100644 index 0000000..24c909c --- /dev/null +++ b/src/ts/plugins/analyzer/src/style/_base.scss @@ -0,0 +1,145 @@ +:root { + --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, + "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", + "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; + --background-color: #f7eedf; + --text-color: #333; +} + +@media (prefers-color-scheme: dark) { + :root { + --background-color: #2b2d42; + --text-color: #edf2f4; + } +} + +html { + box-sizing: border-box; +} + +*, +*:before, +*:after { + box-sizing: inherit; +} + +html { + background-color: var(--background-color); + color: var(--text-color); + font-family: var(--font-family); +} + +body { + padding: 0; + margin: 0; +} + +html, +body { + height: 100%; + width: 100%; + overflow: hidden; +} + +body { + display: flex; + flex-direction: column; +} + +svg { + vertical-align: middle; + width: 100%; + height: 100%; + max-height: 100vh; +} + +main { + flex-grow: 1; + height: 100vh; + padding: 20px; +} + +.tooltip { + position: absolute; + z-index: 1070; + + border: 2px solid; + border-radius: 5px; + + padding: 5px; + + white-space: nowrap; + + font-size: 0.875rem; + + background-color: var(--background-color); + color: var(--text-color); +} + +.tooltip-hidden { + visibility: hidden; + opacity: 0; +} + +.sidebar { + position: fixed; + top: 0; + left: 0; + right: 0; + display: flex; + flex-direction: row; + font-size: 0.7rem; + align-items: center; + margin: 0 50px; + height: 20px; +} + +.size-selectors { + display: flex; + flex-direction: row; + align-items: center; +} + +.size-selector { + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; + margin-right: 1rem; + + input { + margin: 0 0.3rem 0 0; + } +} + +.filters { + flex: 1; + display: flex; + flex-direction: row; + align-items: center; +} + +.module-filters { + display: flex; +} + +.module-filter { + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; + + flex: 1; + + input { + flex: 1; + height: 1rem; + padding: 0.01rem; + font-size: 0.7rem; + margin-left: 0.3rem; + } + + & + & { + margin-left: 0.5rem; + } +} diff --git a/src/ts/plugins/analyzer/src/style/style-network.scss b/src/ts/plugins/analyzer/src/style/style-network.scss new file mode 100644 index 0000000..079e71b --- /dev/null +++ b/src/ts/plugins/analyzer/src/style/style-network.scss @@ -0,0 +1 @@ +@import "./base"; diff --git a/src/ts/plugins/analyzer/src/style/style-sunburst.scss b/src/ts/plugins/analyzer/src/style/style-sunburst.scss new file mode 100644 index 0000000..c5e51fb --- /dev/null +++ b/src/ts/plugins/analyzer/src/style/style-sunburst.scss @@ -0,0 +1,36 @@ +@import "./base"; + +.details { + position: absolute; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + + top: calc(50% - 85px); + left: calc(50% - 85px); + + width: 170px; + height: 170px; + + font-size: 14px; + text-align: center; + color: var(--font-color); + z-index: 100; + overflow: hidden; + text-overflow: ellipsis; +} + +.details-size { + font-size: 0.8em; +} + +.details-name { + font-weight: bold; +} + +.details-percentage { + margin: 0.4em 0em; + font-size: 2.4em; + line-height: 1em; +} diff --git a/src/ts/plugins/analyzer/src/style/style-treemap.scss b/src/ts/plugins/analyzer/src/style/style-treemap.scss new file mode 100644 index 0000000..079e71b --- /dev/null +++ b/src/ts/plugins/analyzer/src/style/style-treemap.scss @@ -0,0 +1 @@ +@import "./base"; diff --git a/src/ts/plugins/analyzer/src/sunburst/chart.tsx b/src/ts/plugins/analyzer/src/sunburst/chart.tsx new file mode 100644 index 0000000..374444f --- /dev/null +++ b/src/ts/plugins/analyzer/src/sunburst/chart.tsx @@ -0,0 +1,57 @@ +import type { ModuleTree, ModuleTreeLeaf, SizeKey } from "../../types/types"; + +import { h, Fragment, FunctionalComponent } from "preact"; +import { useState, useEffect, useMemo } from "preact/hooks"; + +import { HierarchyRectangularNode } from "d3-hierarchy"; +import { Tooltip } from "./tooltip"; +import { SunBurst } from "./sunburst"; + +export interface ChartProps { + root: HierarchyRectangularNode; + sizeProperty: SizeKey; + selectedNode: HierarchyRectangularNode | undefined; + setSelectedNode: (node: HierarchyRectangularNode | undefined) => void; +} + +type NodeSelectHandler = (node: HierarchyRectangularNode) => boolean; + +export const Chart: FunctionalComponent = ({ root, sizeProperty, selectedNode, setSelectedNode }) => { + const [tooltipNode, setTooltipNode] = useState(root); + + const isNodeHighlighted = useMemo(() => { + const highlightedNodes = new Set(tooltipNode === root ? root.descendants() : tooltipNode.ancestors()); + return (node: HierarchyRectangularNode): boolean => { + return highlightedNodes.has(node); + }; + }, [root, tooltipNode]); + + useEffect(() => { + const handleMouseOut = () => { + setTooltipNode(root); + }; + + handleMouseOut(); + document.addEventListener("mouseover", handleMouseOut); + return () => { + document.removeEventListener("mouseover", handleMouseOut); + }; + }, [root]); + + return ( + <> + { + setTooltipNode(node); + }} + isNodeHighlighted={isNodeHighlighted} + selectedNode={selectedNode} + onNodeClick={(node) => { + setSelectedNode(selectedNode === node ? undefined : node); + }} + /> + + + ); +}; diff --git a/src/ts/plugins/analyzer/src/sunburst/index.tsx b/src/ts/plugins/analyzer/src/sunburst/index.tsx new file mode 100644 index 0000000..aa5bb94 --- /dev/null +++ b/src/ts/plugins/analyzer/src/sunburst/index.tsx @@ -0,0 +1,120 @@ +import type { + ModuleRenderSizes, + ModuleTree, + ModuleTreeLeaf, + SizeKey, + VisualizerData, +} from "../../types/types"; + +import { h, createContext, render } from "preact"; +import { hierarchy, HierarchyNode, HierarchyRectangularNode, partition, PartitionLayout } from "d3-hierarchy"; +import { Arc, arc as d3arc } from "d3-shape"; +import { scaleLinear, scaleSqrt } from "d3-scale"; + +import { isModuleTree } from "../../utils/is-module-tree"; + +import { Main } from "./main"; + +import { getAvailableSizeOptions } from "../sizes"; +import { generateUniqueId, Id } from "../uid"; + +import "../style/style-sunburst.scss"; + +export interface StaticData { + data: VisualizerData; + availableSizeProperties: SizeKey[]; + width: number; + height: number; +} + +export interface ModuleIds { + nodeUid: Id; +} + +export interface ChartData { + layout: PartitionLayout; + rawHierarchy: HierarchyNode; + getModuleSize: (node: ModuleTree | ModuleTreeLeaf, sizeKey: SizeKey) => number; + getModuleIds: (node: ModuleTree | ModuleTreeLeaf) => ModuleIds; + size: number; + radius: number; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + arc: Arc>; +} + +export type Context = StaticData & ChartData; + +export const StaticContext = createContext(({} as unknown) as Context); + +const drawChart = (parentNode: Element, data: VisualizerData, width: number, height: number): void => { + const availableSizeProperties = getAvailableSizeOptions(data.options); + + const layout = partition(); + + const rawHierarchy = hierarchy(data.tree); + + const nodeSizesCache = new Map(); + + const nodeIdsCache = new Map(); + + const getModuleSize = (node: ModuleTree | ModuleTreeLeaf, sizeKey: SizeKey) => + nodeSizesCache.get(node)?.[sizeKey] ?? 0; + + rawHierarchy.eachAfter((node) => { + const nodeData = node.data; + + nodeIdsCache.set(nodeData, { + nodeUid: generateUniqueId("node"), + }); + + const sizes: ModuleRenderSizes = { renderedLength: 0 }; + if (isModuleTree(nodeData)) { + for (const sizeKey of availableSizeProperties) { + sizes[sizeKey] = nodeData.children.reduce((acc, child) => getModuleSize(child, sizeKey) + acc, 0); + } + } else { + for (const sizeKey of availableSizeProperties) { + sizes[sizeKey] = data.nodes[nodeData.uid][sizeKey] ?? 0; + } + } + nodeSizesCache.set(nodeData, sizes); + }); + + const getModuleIds = (node: ModuleTree | ModuleTreeLeaf) => nodeIdsCache.get(node) as ModuleIds; + + const size = Math.min(width, height); + const radius = size / 2; + + const x = scaleLinear().range([0, 2 * Math.PI]); + const y = scaleSqrt().range([0, radius]); + + const arc = d3arc>() + .startAngle((d) => Math.max(0, Math.min(2 * Math.PI, x(d.x0)))) + .endAngle((d) => Math.max(0, Math.min(2 * Math.PI, x(d.x1)))) + .innerRadius((d) => y(d.y0)) + .outerRadius((d) => y(d.y1)); + + render( + +
+ , + parentNode + ); +}; + +export default drawChart; diff --git a/src/ts/plugins/analyzer/src/sunburst/main.tsx b/src/ts/plugins/analyzer/src/sunburst/main.tsx new file mode 100644 index 0000000..3fbe2c6 --- /dev/null +++ b/src/ts/plugins/analyzer/src/sunburst/main.tsx @@ -0,0 +1,77 @@ +import type { ModuleRenderInfo, ModuleTree, ModuleTreeLeaf, ModuleUID, SizeKey } from "../../types/types"; + +import { h, Fragment, FunctionalComponent } from "preact"; +import { useContext, useMemo, useState } from "preact/hooks"; +import { HierarchyRectangularNode } from "d3-hierarchy"; + +import { SideBar } from "../sidebar"; +import { useFilter } from "../use-filter"; +import { Chart } from "./chart"; + +import { StaticContext } from "./index"; +import { isModuleTree } from "../../utils/is-module-tree"; + +export type LinkInfo = ModuleRenderInfo & { uid: ModuleUID }; +export type ModuleLinkInfo = Map; + +export const Main: FunctionalComponent = () => { + const { availableSizeProperties, rawHierarchy, getModuleSize, layout, data } = useContext(StaticContext); + + const [sizeProperty, setSizeProperty] = useState(availableSizeProperties[0]); + + const [selectedNode, setSelectedNode] = useState | undefined>( + undefined + ); + + const { getModuleFilterMultiplier, setExcludeFilter, setIncludeFilter } = useFilter(); + + const getNodeSizeMultiplier = useMemo(() => { + if (selectedNode === undefined) { + return (): number => 1; + } else if (isModuleTree(selectedNode.data)) { + const descendants = new Set(selectedNode.descendants().map((d) => d.data)); + return (node: ModuleTree | ModuleTreeLeaf): number => { + if (descendants.has(node)) { + return 3; + } + return 1; + }; + } else { + return (node: ModuleTree | ModuleTreeLeaf): number => { + if (node === selectedNode.data) { + return 3; + } + return 1; + }; + } + }, [selectedNode]); + + // root here always be the same as rawHierarchy even after layouting + const root = useMemo(() => { + const rootWithSizesAndSorted = rawHierarchy + .sum((node) => { + if (isModuleTree(node)) return 0; + const ownSize = getModuleSize(node, sizeProperty); + const zoomMultiplier = getNodeSizeMultiplier(node); + const filterMultiplier = getModuleFilterMultiplier(data.nodes[node.uid]); + + return ownSize * zoomMultiplier * filterMultiplier; + }) + .sort((a, b) => getModuleSize(a.data, sizeProperty) - getModuleSize(b.data, sizeProperty)); + + return layout(rootWithSizesAndSorted); + }, [data.nodes, getModuleFilterMultiplier, getModuleSize, getNodeSizeMultiplier, layout, rawHierarchy, sizeProperty]); + + return ( + <> + + + + ); +}; diff --git a/src/ts/plugins/analyzer/src/sunburst/node.tsx b/src/ts/plugins/analyzer/src/sunburst/node.tsx new file mode 100644 index 0000000..87e055a --- /dev/null +++ b/src/ts/plugins/analyzer/src/sunburst/node.tsx @@ -0,0 +1,37 @@ +import type { ModuleTree, ModuleTreeLeaf } from "../../types/types"; + +import { h, FunctionalComponent } from "preact"; +import { HierarchyRectangularNode } from "d3-hierarchy"; +import color from "../color"; + +type NodeEventHandler = (event: HierarchyRectangularNode) => void; + +export interface NodeProps { + node: HierarchyRectangularNode; + onMouseOver: NodeEventHandler; + path: string; + highlighted: boolean; + selected: boolean; + onClick: NodeEventHandler; +} + +export const Node: FunctionalComponent = ({ node, onMouseOver, onClick, path, highlighted, selected }) => { + return ( + { + evt.stopPropagation(); + onMouseOver(node); + }} + onClick={(evt: MouseEvent) => { + evt.stopPropagation(); + onClick(node); + }} + opacity={highlighted ? 1 : 0.3} + stroke-width={selected ? 3 : undefined} + /> + ); +}; diff --git a/src/ts/plugins/analyzer/src/sunburst/sunburst.tsx b/src/ts/plugins/analyzer/src/sunburst/sunburst.tsx new file mode 100644 index 0000000..6092bb5 --- /dev/null +++ b/src/ts/plugins/analyzer/src/sunburst/sunburst.tsx @@ -0,0 +1,46 @@ +import type { ModuleTree, ModuleTreeLeaf } from "../../types/types"; + +import { h, FunctionalComponent } from "preact"; +import { HierarchyRectangularNode } from "d3-hierarchy"; +import { useContext } from "preact/hooks"; +import { StaticContext } from "./index"; + +import { Node } from "./node"; + +export interface SunBurstProps { + root: HierarchyRectangularNode; + onNodeHover: (event: HierarchyRectangularNode) => void; + isNodeHighlighted: (node: HierarchyRectangularNode) => boolean; + selectedNode: HierarchyRectangularNode | undefined; + onNodeClick: (node: HierarchyRectangularNode) => void; +} + +export const SunBurst: FunctionalComponent = ({ + root, + onNodeHover, + isNodeHighlighted, + selectedNode, + onNodeClick, +}) => { + const { getModuleIds, size, arc, radius } = useContext(StaticContext); + + return ( + + + {root.descendants().map((node) => { + return ( + + ); + })} + + + ); +}; diff --git a/src/ts/plugins/analyzer/src/sunburst/tooltip.tsx b/src/ts/plugins/analyzer/src/sunburst/tooltip.tsx new file mode 100644 index 0000000..4eb88d7 --- /dev/null +++ b/src/ts/plugins/analyzer/src/sunburst/tooltip.tsx @@ -0,0 +1,57 @@ +import type { ModuleTree, ModuleTreeLeaf, SizeKey } from "../../types/types"; + +import { h, Fragment, FunctionalComponent } from "preact"; +import { useContext, useMemo } from "preact/hooks"; + +import { format as formatBytes } from "bytes"; + +import { HierarchyRectangularNode } from "d3-hierarchy"; + +import { LABELS } from "../sizes"; +import { StaticContext } from "./index"; + +export interface TooltipProps { + node: HierarchyRectangularNode; + root: HierarchyRectangularNode; + sizeProperty: SizeKey; +} + +export const Tooltip: FunctionalComponent = ({ node, root, sizeProperty }) => { + const { availableSizeProperties, getModuleSize } = useContext(StaticContext); + + const content = useMemo(() => { + if (!node) return null; + + const mainSize = getModuleSize(node.data, sizeProperty); + + const percentageNum = (100 * mainSize) / getModuleSize(root.data, sizeProperty); + const percentage = percentageNum.toFixed(2); + const percentageString = percentage + "%"; + + return ( + <> +
{node.data.name}
+
{percentageString}
+ {availableSizeProperties.map((sizeProp) => { + if (sizeProp === sizeProperty) { + return ( +
+ + {LABELS[sizeProp]}: {formatBytes(getModuleSize(node.data, sizeProp))} + +
+ ); + } else { + return ( +
+ {LABELS[sizeProp]}: {formatBytes(getModuleSize(node.data, sizeProp))} +
+ ); + } + })} + + ); + }, [availableSizeProperties, getModuleSize, node, root.data, sizeProperty]); + + return
{content}
; +}; diff --git a/src/ts/plugins/analyzer/src/treemap/chart.tsx b/src/ts/plugins/analyzer/src/treemap/chart.tsx new file mode 100644 index 0000000..0d33b7b --- /dev/null +++ b/src/ts/plugins/analyzer/src/treemap/chart.tsx @@ -0,0 +1,51 @@ +import type { ModuleTree, ModuleTreeLeaf, SizeKey } from "../../types/types"; + +import { h, Fragment, FunctionalComponent } from "preact"; +import { useState, useEffect } from "preact/hooks"; +import { HierarchyRectangularNode } from "d3-hierarchy"; + +import { TreeMap } from "./treemap"; +import { Tooltip } from "./tooltip"; + +export interface ChartProps { + root: HierarchyRectangularNode; + sizeProperty: SizeKey; + selectedNode: HierarchyRectangularNode | undefined; + setSelectedNode: (node: HierarchyRectangularNode | undefined) => void; +} + +export const Chart: FunctionalComponent = ({ root, sizeProperty, selectedNode, setSelectedNode }) => { + const [showTooltip, setShowTooltip] = useState(false); + const [tooltipNode, setTooltipNode] = useState | undefined>( + undefined + ); + + useEffect(() => { + const handleMouseOut = () => { + setShowTooltip(false); + }; + + document.addEventListener("mouseover", handleMouseOut); + return () => { + document.removeEventListener("mouseover", handleMouseOut); + }; + }, []); + + return ( + <> + { + setTooltipNode(node); + setShowTooltip(true); + }} + selectedNode={selectedNode} + onNodeClick={(node) => { + setSelectedNode(selectedNode === node ? undefined : node); + }} + sizeProperty={sizeProperty} + /> + + + ); +}; diff --git a/src/ts/plugins/analyzer/src/treemap/color.ts b/src/ts/plugins/analyzer/src/treemap/color.ts new file mode 100644 index 0000000..63f55f8 --- /dev/null +++ b/src/ts/plugins/analyzer/src/treemap/color.ts @@ -0,0 +1,80 @@ +import type { ModuleTree, ModuleTreeLeaf } from "../../types/types"; + +import { scaleSequential, scaleLinear } from "d3-scale"; +import { hsl, RGBColor } from "d3-color"; + +import { COLOR_BASE, CssColor } from "../color"; +import { HierarchyNode } from "d3-hierarchy"; + +// https://www.w3.org/TR/WCAG20/#relativeluminancedef +const rc = 0.2126; +const gc = 0.7152; +const bc = 0.0722; +// low-gamma adjust coefficient +const lowc = 1 / 12.92; + +function adjustGamma(p: number) { + return Math.pow((p + 0.055) / 1.055, 2.4); +} + +function relativeLuminance(o: RGBColor) { + const rsrgb = o.r / 255; + const gsrgb = o.g / 255; + const bsrgb = o.b / 255; + + const r = rsrgb <= 0.03928 ? rsrgb * lowc : adjustGamma(rsrgb); + const g = gsrgb <= 0.03928 ? gsrgb * lowc : adjustGamma(gsrgb); + const b = bsrgb <= 0.03928 ? bsrgb * lowc : adjustGamma(bsrgb); + + return r * rc + g * gc + b * bc; +} + +export interface NodeColor { + backgroundColor: CssColor; + fontColor: CssColor; +} + +export type NodeColorGetter = (node: HierarchyNode) => NodeColor; + +const createRainbowColor = (root: HierarchyNode): NodeColorGetter => { + const colorParentMap = new Map, CssColor>(); + colorParentMap.set(root, COLOR_BASE); + + if (root.children != null) { + const colorScale = scaleSequential([0, root.children.length - 1], (n) => hsl(360 * n, 0.6, 0.85)); + root.children.forEach((c, id) => { + colorParentMap.set(c, colorScale(id).toString()); + }); + } + + const colorMap = new Map, NodeColor>(); + + const lightScale = scaleLinear().domain([0, root.height]).range([0.9, 0.3]); + + const getBackgroundColor = (node: HierarchyNode) => { + const parents = node.ancestors(); + const colorStr = + parents.length === 1 ? colorParentMap.get(parents[0]) : colorParentMap.get(parents[parents.length - 2]); + + const hslColor = hsl(colorStr as string); + hslColor.l = lightScale(node.depth); + + return hslColor; + }; + + return (node: HierarchyNode): NodeColor => { + if (!colorMap.has(node)) { + const backgroundColor = getBackgroundColor(node); + const l = relativeLuminance(backgroundColor.rgb()); + const fontColor = l > 0.179 ? "#000" : "#fff"; + colorMap.set(node, { + backgroundColor: backgroundColor.toString(), + fontColor, + }); + } + + return colorMap.get(node) as NodeColor; + }; +}; + +export default createRainbowColor; diff --git a/src/ts/plugins/analyzer/src/treemap/index.tsx b/src/ts/plugins/analyzer/src/treemap/index.tsx new file mode 100644 index 0000000..6ef13d5 --- /dev/null +++ b/src/ts/plugins/analyzer/src/treemap/index.tsx @@ -0,0 +1,133 @@ +import type { + ModuleRenderInfo, + ModuleRenderSizes, + ModuleTree, + ModuleTreeLeaf, + ModuleUID, + SizeKey, + VisualizerData, +} from "../../types/types"; + +import { h, createContext, render } from "preact"; +import { hierarchy, HierarchyNode, treemap, TreemapLayout, treemapResquarify } from "d3-hierarchy"; + +import { Main } from "./main"; + +import { generateUniqueId, Id } from "../uid"; +import { getAvailableSizeOptions } from "../sizes"; +import createRainbowColor, { NodeColorGetter } from "./color"; + +import "../style/style-treemap.scss"; +import { isModuleTree } from "../../utils/is-module-tree"; + +export interface StaticData { + data: VisualizerData; + availableSizeProperties: SizeKey[]; + width: number; + height: number; +} + +export interface ModuleIds { + nodeUid: Id; + clipUid: Id; +} + +export type LinkInfo = ModuleRenderInfo & { uid: ModuleUID }; +export type ModuleLinkInfo = Map; +export interface ChartData { + layout: TreemapLayout; + rawHierarchy: HierarchyNode; + getModuleSize: (node: ModuleTree | ModuleTreeLeaf, sizeKey: SizeKey) => number; + getModuleIds: (node: ModuleTree | ModuleTreeLeaf) => ModuleIds; + getModuleColor: NodeColorGetter; + importedCache: ModuleLinkInfo; + importedByCache: ModuleLinkInfo; +} + +export type Context = StaticData & ChartData; + +export const StaticContext = createContext(({} as unknown) as Context); + +const drawChart = (parentNode: Element, data: VisualizerData, width: number, height: number): void => { + const availableSizeProperties = getAvailableSizeOptions(data.options); + + const layout = treemap() + .size([width, height]) + .paddingOuter(5) + .paddingTop(20) + .paddingInner(5) + .round(true) + .tile(treemapResquarify); + + const rawHierarchy = hierarchy(data.tree); + + const nodeSizesCache = new Map(); + + const nodeIdsCache = new Map(); + + const getModuleSize = (node: ModuleTree | ModuleTreeLeaf, sizeKey: SizeKey) => + nodeSizesCache.get(node)?.[sizeKey] ?? 0; + + rawHierarchy.eachAfter((node) => { + const nodeData = node.data; + + nodeIdsCache.set(nodeData, { + nodeUid: generateUniqueId("node"), + clipUid: generateUniqueId("clip"), + }); + + const sizes: ModuleRenderSizes = { renderedLength: 0 }; + if (isModuleTree(nodeData)) { + for (const sizeKey of availableSizeProperties) { + sizes[sizeKey] = nodeData.children.reduce((acc, child) => getModuleSize(child, sizeKey) + acc, 0); + } + } else { + for (const sizeKey of availableSizeProperties) { + sizes[sizeKey] = data.nodes[nodeData.uid][sizeKey] ?? 0; + } + } + nodeSizesCache.set(nodeData, sizes); + }); + + const getModuleIds = (node: ModuleTree | ModuleTreeLeaf) => nodeIdsCache.get(node) as ModuleIds; + + const getModuleColor = createRainbowColor(rawHierarchy); + + const importedByCache = new Map(); + const importedCache = new Map(); + + for (const { source, target } of data.links) { + if (!importedByCache.has(target)) { + importedByCache.set(target, []); + } + if (!importedCache.has(source)) { + importedCache.set(source, []); + } + + importedByCache.get(target)?.push({ uid: source, ...data.nodes[source] }); + importedCache.get(source)?.push({ uid: target, ...data.nodes[target] }); + } + + render( + +
+ , + parentNode + ); +}; + +export default drawChart; diff --git a/src/ts/plugins/analyzer/src/treemap/main.tsx b/src/ts/plugins/analyzer/src/treemap/main.tsx new file mode 100644 index 0000000..280ec5c --- /dev/null +++ b/src/ts/plugins/analyzer/src/treemap/main.tsx @@ -0,0 +1,77 @@ +import type { ModuleTree, ModuleTreeLeaf, SizeKey } from "../../types/types"; + +import { h, Fragment, FunctionalComponent } from "preact"; +import { useContext, useMemo, useState } from "preact/hooks"; +import { HierarchyRectangularNode } from "d3-hierarchy"; + +import { SideBar } from "../sidebar"; +import { Chart } from "./chart"; + +import { StaticContext } from "./index"; +import { useFilter } from "../use-filter"; +import { isModuleTree } from "../../utils/is-module-tree"; + +export const Main: FunctionalComponent = () => { + const { availableSizeProperties, rawHierarchy, getModuleSize, layout, data } = useContext(StaticContext); + + const [sizeProperty, setSizeProperty] = useState(availableSizeProperties[0]); + + const [selectedNode, setSelectedNode] = useState | undefined>( + undefined + ); + + const { getModuleFilterMultiplier, setExcludeFilter, setIncludeFilter } = useFilter(); + + const getNodeSizeMultiplier = useMemo(() => { + const rootSize = getModuleSize(rawHierarchy.data, sizeProperty); + const selectedSize = selectedNode ? getModuleSize(selectedNode.data, sizeProperty) : 1; + const multiplier = rootSize * 0.2 > selectedSize ? (rootSize * 0.2) / selectedSize : 3; + if (selectedNode === undefined) { + return (): number => 1; + } else if (isModuleTree(selectedNode.data)) { + const leaves = new Set(selectedNode.leaves().map((d) => d.data)); + return (node: ModuleTree | ModuleTreeLeaf): number => { + if (leaves.has(node)) { + return multiplier; + } + return 1; + }; + } else { + return (node: ModuleTree | ModuleTreeLeaf): number => { + if (node === selectedNode.data) { + return multiplier; + } + return 1; + }; + } + }, [getModuleSize, rawHierarchy.data, selectedNode, sizeProperty]); + + // root here always be the same as rawHierarchy even after layouting + const root = useMemo(() => { + const rootWithSizesAndSorted = rawHierarchy + .sum((node) => { + if (isModuleTree(node)) return 0; + const ownSize = getModuleSize(node, sizeProperty); + const zoomMultiplier = getNodeSizeMultiplier(node); + const filterMultiplier = getModuleFilterMultiplier(data.nodes[node.uid]); + + return ownSize * zoomMultiplier * filterMultiplier; + }) + .sort((a, b) => getModuleSize(a.data, sizeProperty) - getModuleSize(b.data, sizeProperty)); + + return layout(rootWithSizesAndSorted); + }, [data.nodes, getModuleFilterMultiplier, getModuleSize, getNodeSizeMultiplier, layout, rawHierarchy, sizeProperty]); + + return ( + <> + + + + ); +}; diff --git a/src/ts/plugins/analyzer/src/treemap/node.tsx b/src/ts/plugins/analyzer/src/treemap/node.tsx new file mode 100644 index 0000000..c24b177 --- /dev/null +++ b/src/ts/plugins/analyzer/src/treemap/node.tsx @@ -0,0 +1,88 @@ +import type { ModuleTree, ModuleTreeLeaf, SizeKey } from "../../types/types"; + +import { h, FunctionalComponent } from "preact"; +import { useContext } from "preact/hooks"; +import { format as formatBytes } from "bytes"; +import { HierarchyRectangularNode } from "d3-hierarchy"; +import { StaticContext } from "./index"; + +type NodeEventHandler = (event: HierarchyRectangularNode) => void; + +export interface NodeProps { + node: HierarchyRectangularNode; + onMouseOver: NodeEventHandler; + selected: boolean; + onClick: NodeEventHandler; + sizeProperty: SizeKey; +} + +interface tspanProps { + x?: number | string; + y?: number | string; + dx?: number; + dy?: number; +} + +export const Node: FunctionalComponent = ({ node, onMouseOver, onClick, selected, sizeProperty }) => { + const { getModuleColor, getModuleIds, getModuleSize } = useContext(StaticContext); + const { backgroundColor, fontColor } = getModuleColor(node); + const { clipUid, nodeUid } = getModuleIds(node.data); + const { x0, x1, y1, y0, data, children = null } = node; + + const tspan1Props: tspanProps = {}; + const tspan2Props: tspanProps = {}; + if (children != null) { + tspan1Props.dx = 3; + tspan2Props.dx = 3; + tspan1Props.y = 13; + tspan2Props.y = 13; + } else { + tspan1Props.x = 3; + tspan2Props.x = 3; + tspan1Props.y = "1.1em"; + tspan2Props.y = "2.3em"; + } + + const handleClickSelection = (event: MouseEvent) => { + if (window.getSelection()?.toString() !== "") { + event.stopPropagation(); + } + }; + + return ( + { + event.stopPropagation(); + onClick(node); + }} + onMouseOver={(evt: MouseEvent) => { + evt.stopPropagation(); + onMouseOver(node); + }} + > + + + + + + + {data.name} + + + {formatBytes(getModuleSize(data, sizeProperty))} + + + + ); +}; diff --git a/src/ts/plugins/analyzer/src/treemap/tooltip.tsx b/src/ts/plugins/analyzer/src/treemap/tooltip.tsx new file mode 100644 index 0000000..1d11ecc --- /dev/null +++ b/src/ts/plugins/analyzer/src/treemap/tooltip.tsx @@ -0,0 +1,120 @@ +import type { ModuleTree, ModuleTreeLeaf, SizeKey } from "../../types/types"; + +import { h, Fragment, FunctionalComponent } from "preact"; +import { useState, useRef, useEffect, useMemo, useContext, type MutableRef } from "preact/hooks"; + +import { format as formatBytes } from "bytes"; + +import { LABELS } from "../sizes"; +import { HierarchyRectangularNode } from "d3-hierarchy"; +import { StaticContext } from "."; +import { isModuleTree } from "../../utils/is-module-tree"; + +export interface TooltipProps { + node?: HierarchyRectangularNode; + root: HierarchyRectangularNode; + sizeProperty: SizeKey; + visible: boolean; +} + +const Tooltip_marginX = 10; +const Tooltip_marginY = 30; + +export const Tooltip: FunctionalComponent = ({ node, visible, root, sizeProperty }) => { + const { availableSizeProperties, getModuleSize, importedByCache } = useContext(StaticContext); + + const ref = useRef() as MutableRef; + const [style, setStyle] = useState({}); + const content = useMemo(() => { + if (!node) return null; + + const mainSize = getModuleSize(node.data, sizeProperty); + + const percentageNum = (100 * mainSize) / getModuleSize(root.data, sizeProperty); + const percentage = percentageNum.toFixed(2); + const percentageString = percentage + "%"; + + const path = node + .ancestors() + .reverse() + .map((d) => d.data.name) + .join("/"); + + return ( + <> +
{path}
+ {availableSizeProperties.map((sizeProp) => { + if (sizeProp === sizeProperty) { + return ( +
+ + {LABELS[sizeProp]}: {formatBytes(mainSize)} + {" "} + ({percentageString}) +
+ ); + } else { + return ( +
+ {LABELS[sizeProp]}: {formatBytes(getModuleSize(node.data, sizeProp))} +
+ ); + } + })} + {!isModuleTree(node.data) && importedByCache.has(node.data.uid) && ( +
+
+ Imported By: +
+ {[...new Set(importedByCache.get(node.data.uid)?.map(({ id }) => id))].map((id) => ( +
{id}
+ ))} +
+ )} + + ); + }, [availableSizeProperties, getModuleSize, importedByCache, node, root.data, sizeProperty]); + + const updatePosition = (mouseCoords: { x: number; y: number }) => { + const pos = { + left: mouseCoords.x + Tooltip_marginX, + top: mouseCoords.y + Tooltip_marginY, + }; + + const boundingRect = ref.current.getBoundingClientRect(); + + if (pos.left + boundingRect.width > window.innerWidth) { + // Shifting horizontally + pos.left = window.innerWidth - boundingRect.width; + } + + if (pos.top + boundingRect.height > window.innerHeight) { + // Flipping vertically + pos.top = mouseCoords.y - Tooltip_marginY - boundingRect.height; + } + + setStyle(pos); + }; + + useEffect(() => { + const handleMouseMove = (event: MouseEvent) => { + updatePosition({ + x: event.pageX, + y: event.pageY, + }); + }; + + document.addEventListener("mousemove", handleMouseMove, true); + return () => { + document.removeEventListener("mousemove", handleMouseMove, true); + }; + }, []); + + return ( +
+ {content} +
+ ); +}; + +export default Tooltip; diff --git a/src/ts/plugins/analyzer/src/treemap/treemap.tsx b/src/ts/plugins/analyzer/src/treemap/treemap.tsx new file mode 100644 index 0000000..2d69e77 --- /dev/null +++ b/src/ts/plugins/analyzer/src/treemap/treemap.tsx @@ -0,0 +1,61 @@ +import type { ModuleTree, ModuleTreeLeaf, SizeKey } from "../../types/types"; + +import { h, FunctionalComponent } from "preact"; +import { useContext, useMemo } from "preact/hooks"; +import { group } from "d3-array"; +import { HierarchyNode, HierarchyRectangularNode } from "d3-hierarchy"; + +import { Node } from "./node"; +import { StaticContext } from "./index"; + +export interface TreeMapProps { + root: HierarchyRectangularNode; + onNodeHover: (event: HierarchyRectangularNode) => void; + selectedNode: HierarchyRectangularNode | undefined; + onNodeClick: (node: HierarchyRectangularNode) => void; + sizeProperty: SizeKey; +} + +export const TreeMap: FunctionalComponent = ({ + root, + onNodeHover, + selectedNode, + onNodeClick, + sizeProperty, +}) => { + const { width, height, getModuleIds } = useContext(StaticContext); + + // this will make groups by height + const nestedData = useMemo(() => { + const nestedDataMap = group(root.descendants(), (d: HierarchyNode) => d.height); + const nestedData = Array.from(nestedDataMap, ([key, values]) => ({ + key, + values, + })); + nestedData.sort((a, b) => b.key - a.key); + return nestedData; + }, [root]); + + return ( + + {nestedData.map(({ key, values }) => { + return ( + + {values.map((node) => { + return ( + + ); + })} + + ); + })} + + ); +}; diff --git a/src/ts/plugins/analyzer/src/uid.ts b/src/ts/plugins/analyzer/src/uid.ts new file mode 100644 index 0000000..36f1e34 --- /dev/null +++ b/src/ts/plugins/analyzer/src/uid.ts @@ -0,0 +1,31 @@ +let count = 0; + +export class Id { + private _id: string; + private _href: string; + + constructor(id: string) { + this._id = id; + const url = new URL(window.location.href); + url.hash = id; + this._href = url.toString(); + } + + get id(): Id["_id"] { + return this._id; + } + + get href(): Id["_href"] { + return this._href; + } + + toString(): string { + return `url(${this.href})`; + } +} + +export function generateUniqueId(name: string): Id { + count += 1; + const id = ["O", name, count].filter(Boolean).join("-"); + return new Id(id); +} diff --git a/src/ts/plugins/analyzer/src/use-filter.ts b/src/ts/plugins/analyzer/src/use-filter.ts new file mode 100644 index 0000000..cfb6b96 --- /dev/null +++ b/src/ts/plugins/analyzer/src/use-filter.ts @@ -0,0 +1,76 @@ +import type { ModuleRenderInfo } from "../types/types"; +import { useState, useMemo } from "preact/hooks"; + +export type FilterSetter = (value: string) => void; + +const throttleFilter = (callback: FilterSetter, limit: number): typeof callback => { + let waiting = false; + return (val: string): void => { + if (!waiting) { + callback(val); + waiting = true; + setTimeout(() => { + waiting = false; + }, limit); + } + }; +}; + +export type UseFilter = { + includeFilter: string; + excludeFilter: string; + setIncludeFilter: FilterSetter; + setExcludeFilter: FilterSetter; + getModuleFilterMultiplier: (data: ModuleRenderInfo) => number; +}; + +export const useFilter = (): UseFilter => { + const [includeFilter, setIncludeFilter] = useState(""); + const [excludeFilter, setExcludeFilter] = useState(""); + + const setIncludeFilterTrottled = useMemo(() => throttleFilter(setIncludeFilter, 200), []); + const setExcludeFilterTrottled = useMemo(() => throttleFilter(setExcludeFilter, 200), []); + + const isModuleIncluded = useMemo(() => { + if (includeFilter === "") { + return () => true; + } + try { + const re = new RegExp(includeFilter); + return ({ id }: ModuleRenderInfo) => re.test(id); + } catch (err) { + return () => false; + } + }, [includeFilter]); + + const isModuleExcluded = useMemo(() => { + if (excludeFilter === "") { + return () => false; + } + try { + const re = new RegExp(excludeFilter); + return ({ id }: ModuleRenderInfo) => re.test(id); + } catch (err) { + return () => false; + } + }, [excludeFilter]); + + const isDefaultInclude = includeFilter === ""; + + const getModuleFilterMultiplier = useMemo(() => { + return (data: ModuleRenderInfo) => { + if (isDefaultInclude) { + return isModuleExcluded(data) ? 0 : 1; + } + return isModuleExcluded(data) && !isModuleIncluded(data) ? 0 : 1; + }; + }, [isDefaultInclude, isModuleExcluded, isModuleIncluded]); + + return { + getModuleFilterMultiplier, + includeFilter, + excludeFilter, + setExcludeFilter: setExcludeFilterTrottled, + setIncludeFilter: setIncludeFilterTrottled, + }; +}; diff --git a/src/ts/plugins/analyzer/types/metafile.d.ts b/src/ts/plugins/analyzer/types/metafile.d.ts new file mode 100644 index 0000000..83020e8 --- /dev/null +++ b/src/ts/plugins/analyzer/types/metafile.d.ts @@ -0,0 +1,29 @@ +export interface MetadataOutput { + bytes: number; + inputs: { + [path: string]: { + bytesInOutput: number; + }; + }; + imports: { + path: string; + kind: string; + }[]; + exports: string[]; + entryPoint?: string; +} + +export interface Metadata { + inputs: { + [path: string]: { + bytes: number; + imports: { + path: string; + kind: string; + }[]; + }; + }; + outputs: { + [path: string]: MetadataOutput; + }; +} diff --git a/src/ts/plugins/analyzer/types/rollup.d.ts b/src/ts/plugins/analyzer/types/rollup.d.ts new file mode 100644 index 0000000..3eea68e --- /dev/null +++ b/src/ts/plugins/analyzer/types/rollup.d.ts @@ -0,0 +1,9 @@ +export type ModuleInfo = { + renderedLength: number; + isEntry: boolean; + isExternal: boolean; + importedIds: string[]; + dynamicallyImportedIds: string[]; +}; + +export type GetModuleInfo = (moduleId: string) => ModuleInfo | null; diff --git a/src/ts/plugins/analyzer/types/template-types.ts b/src/ts/plugins/analyzer/types/template-types.ts new file mode 100644 index 0000000..e9c5d51 --- /dev/null +++ b/src/ts/plugins/analyzer/types/template-types.ts @@ -0,0 +1,5 @@ +export type TemplateType = "sunburst" | "treemap" | "network"; + +export const templates: ReadonlyArray = ["sunburst", "treemap", "network"]; + +export default templates; diff --git a/src/ts/plugins/analyzer/types/types.d.ts b/src/ts/plugins/analyzer/types/types.d.ts new file mode 100644 index 0000000..c85e6d2 --- /dev/null +++ b/src/ts/plugins/analyzer/types/types.d.ts @@ -0,0 +1,47 @@ +export type SizeKey = "renderedLength" | "gzipLength" | "brotliLength"; + +export interface ModuleTreeLeaf { + uid: string; + name: string; +} + +export interface ModuleTree { + name: string; + children: Array; +} + +export type ModuleUID = string; + +export type ModuleRenderInfo = { + id: string; + isEntry?: boolean; + isExternal?: boolean; +} & ModuleRenderSizes; + +export interface ModuleRenderSizes { + renderedLength: number; + gzipLength?: number; + brotliLength?: number; +} + +export interface ModuleLink { + source: ModuleUID; + target: ModuleUID; + dynamic?: boolean; +} + +export interface VisualizerData { + version: number; + tree: ModuleTree; + nodes: Record; + nodeParts: Record>; + links: ModuleLink[]; + env: { + [key: string]: unknown; + }; + options: { + gzip: boolean; + brotli: boolean; + sourcemap: boolean; + }; +} diff --git a/src/ts/plugins/analyzer/utils/is-module-tree.ts b/src/ts/plugins/analyzer/utils/is-module-tree.ts new file mode 100644 index 0000000..91bab33 --- /dev/null +++ b/src/ts/plugins/analyzer/utils/is-module-tree.ts @@ -0,0 +1,3 @@ +import type { ModuleTree, ModuleTreeLeaf } from "../types/types"; + +export const isModuleTree = (mod: ModuleTree | ModuleTreeLeaf): mod is ModuleTree => "children" in mod; \ No newline at end of file diff --git a/src/ts/workers/empty.ts b/src/ts/workers/empty.ts index a2a8f33..4ac3bcb 100644 --- a/src/ts/workers/empty.ts +++ b/src/ts/workers/empty.ts @@ -1,2 +1,49 @@ /// -export {}; \ No newline at end of file +export {}; + + + +// const TypeAquisition = setupTypeAcquisition({ +// projectName: "My ATA Project", +// typescript: ts, +// logger: console, +// async fetcher(input, init) { +// return await getRequest(input, false, init); +// }, +// delegate: { +// started: () => { +// console.log("Types Aquisition Start") +// }, +// receivedFile: (code: string, path: string) => { +// // Add code to your runtime at the path... +// languages.typescript.typescriptDefaults.addExtraLib(code, "file://" + path); + +// const uri = Uri.file(path); +// if (Editor.getModel(uri) === null) { +// Editor.createModel(code, "typescript", uri); +// } +// }, +// progress: (downloaded: number, total: number) => { +// console.log(`Got ${downloaded} out of ${total}`) +// }, +// finished: vfs => { +// console.log("Types Aquisition Done"); +// }, +// }, +// }); + +// const getTypescriptTypes = async (model: typeof inputModel) => { +// try { +// const worker = await languages.typescript.getTypeScriptWorker(); +// await worker(model.uri); + +// // @ts-ignore +// TypeAquisition(model.getValue()); +// } catch (e) { +// console.warn(e); +// } +// }; + +// setTimeout(() => { +// getTypescriptTypes(inputModel); +// }, 1000); diff --git a/src/ts/workers/esbuild.ts b/src/ts/workers/esbuild.ts index c030912..94e7d55 100644 --- a/src/ts/workers/esbuild.ts +++ b/src/ts/workers/esbuild.ts @@ -3,7 +3,7 @@ import { FileSystem } from "../util/filesystem"; import { initialize, build, formatMessages } from "esbuild-wasm"; import { EventEmitter } from "@okikio/emitter"; -import prettyBytes from "pretty-bytes"; +import bytes from "bytes"; import { gzip, getWASM } from "../deno/denoflate/mod"; import { compress } from "../deno/brotli/mod"; @@ -24,6 +24,7 @@ import type { BuildResult, OutputFile, BuildIncremental, PartialMessage } from " import { ALIAS } from "../plugins/alias"; import { getCDNUrl } from "../util/util-cdn"; +import { analyze } from "../plugins/analyzer"; export let _initialized = false; export const initEvent = new EventEmitter(); @@ -160,7 +161,8 @@ export const start = async (port: MessagePort) => { }, ...esbuildOpts, - + + metafile: true, write: false, loader: { '.png': 'file', @@ -220,7 +222,16 @@ export const start = async (port: MessagePort) => { return contents; }); - console.log(Array.from(FileSystem.keys())) + try { + if (config?.analysis) { + postMessage({ + event: "iframe", + details: { + content: await analyze(result?.metafile, config?.analysis == true ? "treemap" : config?.analysis, logger) + } + }); + } + } catch (e) {} // Print warning if (result?.warnings.length > 0) { @@ -245,10 +256,10 @@ export const start = async (port: MessagePort) => { (typeof compression == "string" ? { type: compression } : (compression ?? {})) as CompressionOptions; // @ts-ignore - let totalByteLength = prettyBytes( + let totalByteLength = bytes( content.reduce((acc, { byteLength }) => acc + byteLength, 0) ); - let totalCompressedSize = prettyBytes( + let totalCompressedSize = bytes( (await Promise.all( content.map((code: Uint8Array) => { switch (type) {