perf: use svg sprite for icons (#16135)

Co-authored-by: zomars <[email protected]>
This commit is contained in:
Nafees Nazikandzomars authored and GitHub committed 2024-08-08 15:12:08 -07:00
1 parent 3e28160fa7
commit da5df7164a
30 files changed
+1511 -1698

No files matched your search

+1
View File
@@ -0,0 +1 @@
/svg-icons/
@@ -1,8 +1,8 @@
import type { Column } from "@tanstack/react-table";
import type { LucideIcon } from "lucide-react";
import { classNames } from "@calcom/lib";
import type { IconName } from "../..";
import { Icon } from "../..";
import { Badge } from "../badge";
import { Button } from "../button";
@@ -23,7 +23,7 @@ interface DataTableFilter<TData, TValue> {
options: {
label: string;
value: string;
icon?: LucideIcon;
icon?: IconName;
}[];
}
export function DataTableFilter<TData, TValue>({ column, title, options }: DataTableFilter<TData, TValue>) {
@@ -85,7 +85,7 @@ export function DataTableFilter<TData, TValue>({ column, title, options }: DataT
)}>
<Icon name="check" className={classNames("h-4 w-4")} />
</div>
{option.icon && <option.icon className="text-muted mr-2 h-4 w-4" />}
{option.icon && <Icon name={option.icon} className="text-muted mr-2 h-4 w-4" />}
<span>{option.label}</span>
{facets?.get(option.value) && (
<span className="ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs">
@@ -1,7 +1,6 @@
"use client";
import type { Table } from "@tanstack/react-table";
import type { LucideIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { useDebounce } from "@calcom/lib/hooks/useDebounce";
@@ -9,6 +8,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "../button";
import { Input } from "../form";
import type { IconName } from "../icon/icon-names";
import { DataTableFilter } from "./DataTableFilter";
export type FilterableItems = {
@@ -17,7 +17,7 @@ export type FilterableItems = {
options: {
label: string;
value: string;
icon?: LucideIcon;
icon?: IconName;
}[];
}[];
+15 -18
View File
@@ -1,23 +1,20 @@
// find all lucide icons at https://lucide.dev/
// github https://github.com/lucide-icons/lucide
import type { LucideProps } from "lucide-react";
import dynamic from "next/dynamic";
import { memo } from "react";
import { type SVGProps } from "react";
import type { IconName } from "./dynamicIconImports";
import type { IconName } from "./icon-names";
interface IconProps extends Omit<LucideProps, "ref"> {
function Icon({
name,
size,
...props
}: SVGProps<SVGSVGElement> & {
name: IconName;
size?: number | string;
}) {
return (
<svg height={size} width={size} {...props} aria-hidden>
<use href={`/icons/sprite.svg#${name}`} />
</svg>
);
}
const IconLazy = dynamic(
// Fast refresh doesn't play nice with dynamic imports
// This prevent slowdowns in development mode
process.env.NODE_ENV === "production" ? () => import("./IconProd") : () => import("./IconDev")
);
const Icon = memo((props: IconProps) => <IconLazy {...props} />);
Icon.displayName = "Icon";
export { IconName };
export default Icon;
-22
View File
@@ -1,22 +0,0 @@
// find all lucide icons at https://lucide.dev/
// github https://github.com/lucide-icons/lucide
import type { LucideProps } from "lucide-react";
import { icons } from "lucide-react";
import type { IconName } from "./dynamicIconImports";
interface IconProps extends Omit<LucideProps, "ref"> {
name: IconName;
}
const clearAndUpper = (text: string) => text.replace(/-/, "").toUpperCase();
const toPascalCase = (text: string) => text.replace(/(^\w|-\w)/g, clearAndUpper);
const IconDev = ({ name, ...props }: IconProps) => {
const CamelCaseName = toPascalCase(name);
const LucideIcon = icons[CamelCaseName as keyof typeof icons];
if (!LucideIcon) return null;
return <LucideIcon {...props} />;
};
export default IconDev;
-30
View File
@@ -1,30 +0,0 @@
"use client";
// find all lucide icons at https://lucide.dev/
// github https://github.com/lucide-icons/lucide
import type { LucideProps } from "lucide-react";
import { memo } from "react";
import { dynamicIconImports } from "./dynamicIconImports";
export type IconName = keyof typeof dynamicIconImports;
interface IconProps extends Omit<LucideProps, "ref"> {
name: IconName;
}
const fallback = <div className="bg-emphasis h-4 w-4 animate-pulse rounded-lg" />;
const LazyIcon = memo(({ name, ...props }: IconProps) => {
const LucideIcon = dynamicIconImports[name];
// This should never happen, but just in case
if (!LucideIcon) return fallback;
// @ts-expect-error - LucideIcon is a lazy loaded component
return <LucideIcon {...props} />;
});
LazyIcon.displayName = "LazyIcon";
export default LazyIcon;
+5
View File
@@ -0,0 +1,5 @@
# Icons
This directory contains SVG icons that are used by the app.
Everything in this directory is generated by `yarn run build:icons`.
File diff suppressed because it is too large. Load diff
+139
View File
@@ -0,0 +1,139 @@
// icon name from lucide-react
// this list is extracted based on what icons are currently used
export const lucideIconList = new Set([
"activity",
"arrow-down",
"arrow-left",
"arrow-right",
"arrow-up-right",
"arrow-up",
"asterisk",
"at-sign",
"atom",
"badge-check",
"ban",
"bell",
"bold",
"book-open-check",
"book-open",
"book-user",
"building",
"calendar-check-2",
"calendar-heart",
"calendar-search",
"calendar-x-2",
"calendar",
"chart-bar",
"chart-line",
"check-check",
"check",
"chevron-down",
"chevron-left",
"chevron-right",
"chevron-up",
"chevrons-left",
"chevrons-right",
"circle-alert",
"circle-arrow-up",
"circle-check-big",
"circle-check",
"circle-help",
"circle-x",
"circle",
"clipboard-check",
"clipboard",
"clipboard",
"clock",
"code",
"columns-3",
"command",
"contact",
"copy",
"corner-down-left",
"corner-down-right",
"credit-card",
"dot",
"download",
"ellipsis-vertical",
"ellipsis",
"external-link",
"eye-off",
"eye",
"file-down",
"file-text",
"file",
"filter",
"fingerprint",
"flag",
"folder",
"git-merge",
"github",
"globe",
"grid-3x3",
"handshake",
"info",
"italic",
"key",
"layers",
"layout-dashboard",
"link-2",
"link",
"loader",
"lock-open",
"lock",
"log-out",
"mail-open",
"mail",
"map-pin",
"map",
"menu",
"message-circle",
"messages-square",
"moon",
"paintbrush",
"paperclip",
"pencil",
"pencil",
"phone-call",
"phone",
"plus",
"refresh-ccw",
"refresh-cw",
"repeat",
"rocket",
"rotate-ccw",
"rotate-cw",
"search",
"send",
"settings",
"share-2",
"shield-check",
"shield",
"shuffle",
"sliders-vertical",
"smartphone",
"sparkles",
"square-check",
"star",
"sun",
"sunrise",
"sunset",
"terminal",
"terminal",
"trash-2",
"trash",
"trash",
"trello",
"triangle-alert",
"upload",
"user-check",
"user-plus",
"user-x",
"user",
"users",
"venetian-mask",
"video",
"webhook",
"x",
"zap",
]);
+134
View File
@@ -0,0 +1,134 @@
// This file is generated by yarn run build:icons
export type IconName =
| "activity"
| "arrow-down"
| "arrow-left"
| "arrow-right"
| "arrow-up-right"
| "arrow-up"
| "asterisk"
| "at-sign"
| "atom"
| "badge-check"
| "ban"
| "bell"
| "bold"
| "book-open-check"
| "book-open"
| "book-user"
| "building"
| "calendar-check-2"
| "calendar-heart"
| "calendar-search"
| "calendar-x-2"
| "calendar"
| "chart-bar"
| "chart-line"
| "check-check"
| "check"
| "chevron-down"
| "chevron-left"
| "chevron-right"
| "chevron-up"
| "chevrons-left"
| "chevrons-right"
| "circle-alert"
| "circle-arrow-up"
| "circle-check-big"
| "circle-check"
| "circle-help"
| "circle-x"
| "circle"
| "clipboard-check"
| "clipboard"
| "clock"
| "code"
| "columns-3"
| "command"
| "contact"
| "copy"
| "corner-down-left"
| "corner-down-right"
| "credit-card"
| "dot"
| "download"
| "ellipsis-vertical"
| "ellipsis"
| "external-link"
| "eye-off"
| "eye"
| "file-down"
| "file-text"
| "file"
| "filter"
| "fingerprint"
| "flag"
| "folder"
| "git-merge"
| "github"
| "globe"
| "grid-3x3"
| "handshake"
| "info"
| "italic"
| "key"
| "layers"
| "layout-dashboard"
| "link-2"
| "link"
| "loader"
| "lock-open"
| "lock"
| "log-out"
| "mail-open"
| "mail"
| "map-pin"
| "map"
| "menu"
| "message-circle"
| "messages-square"
| "moon"
| "paintbrush"
| "paperclip"
| "pencil"
| "phone-call"
| "phone"
| "plus"
| "refresh-ccw"
| "refresh-cw"
| "repeat"
| "rocket"
| "rotate-ccw"
| "rotate-cw"
| "search"
| "send"
| "settings"
| "share-2"
| "shield-check"
| "shield"
| "shuffle"
| "sliders-vertical"
| "smartphone"
| "sparkles"
| "square-check"
| "star"
| "sun"
| "sunrise"
| "sunset"
| "terminal"
| "trash-2"
| "trash"
| "trello"
| "triangle-alert"
| "upload"
| "user-check"
| "user-plus"
| "user-x"
| "user"
| "users"
| "venetian-mask"
| "video"
| "webhook"
| "x"
| "zap";
@@ -1,5 +1,4 @@
import classNames from "classnames";
import type { LucideProps } from "lucide-react";
import type { ReactNode } from "react";
import { TOP_BANNER_HEIGHT } from "@calcom/lib/constants";
@@ -21,8 +20,7 @@ const variantClassName = {
const defaultIconProps = {
className: "text-emphasis h-4 w-4 stroke-[2.5px]",
"aria-hidden": "true",
} as LucideProps;
};
export function TopBanner(props: TopBannerProps) {
const { icon, variant = "default", text, actions } = props;
+1 -1
View File
@@ -199,4 +199,4 @@ export type { OrgBannerProps } from "./components/organization-banner";
export { StorybookTrpcProvider } from "./components/mocks/trpc";
export { default as Icon } from "./components/icon/Icon";
export type { IconName } from "./components/icon/dynamicIconImports";
export type { IconName } from "./components/icon/icon-names";
+7 -3
View File
@@ -20,7 +20,8 @@
"type-check": "tsc --pretty --noEmit",
"type-check:ci": "tsc-absolute --pretty --noEmit",
"lint:fix": "eslint . --fix",
"lint:report": "eslint . --format json --output-file ../../lint-results/ui.json"
"lint:report": "eslint . --format json --output-file ../../lint-results/ui.json",
"build:icons": "node ./scripts/build-icons.mjs"
},
"dependencies": {
"@calcom/lib": "*",
@@ -41,13 +42,11 @@
"cmk": "^0.1.1",
"date-fns": "^3.6.0",
"downshift": "^6.1.9",
"lucide-react": "^0.364.0",
"next": "^13.5.4",
"next-seo": "^6.0.0",
"react": "^18.2.0",
"react-colorful": "^5.6.0",
"react-day-picker": "^8.10.1",
"react-feather": "^2.0.10",
"react-hook-form": "^7.43.3",
"react-select": "^5.7.0",
"react-virtual": "^2.10.4"
@@ -57,6 +56,11 @@
"@calcom/tsconfig": "*",
"@types/react": "18.0.26",
"@types/react-dom": "^18.0.9",
"execa": "^9.3.0",
"fast-glob": "^3.3.2",
"fs-extra": "^11.2.0",
"lucide-static": "^0.424.0",
"node-html-parser": "^6.1.13",
"typescript": "^4.9.4"
}
}
+126
View File
@@ -0,0 +1,126 @@
// this script is based on https://github.com/epicweb-dev/epic-stack/blob/main/other/build-icons.ts
//
import { $ } from "execa";
import glob from "fast-glob";
import fsExtra from "fs-extra";
import { parse } from "node-html-parser";
import * as path from "node:path";
import { copyIcons, removeTempDir } from "./generate-icons.mjs";
const cwd = process.cwd();
const inputDir = path.join(cwd, "svg-icons");
const inputDirRelative = path.relative(cwd, inputDir);
const typesDir = path.join(cwd, "components", "icon");
const outputDir = path.join(cwd, "../../", "apps", "web", "public", "icons");
const shouldVerboseLog = process.argv.includes("--log=verbose");
const logVerbose = shouldVerboseLog ? console.log : () => {};
async function generateIconFiles() {
const files = glob
.sync("**/*.svg", {
cwd: inputDir,
})
.sort((a, b) => a.localeCompare(b));
await fsExtra.ensureDir(outputDir);
const spriteFilepath = path.join(outputDir, "sprite.svg");
const typeOutputFilepath = path.join(typesDir, "icon-names.ts");
const currentSprite = await fsExtra.readFile(spriteFilepath, "utf8").catch(() => "");
const currentTypes = await fsExtra.readFile(typeOutputFilepath, "utf8").catch(() => "");
const iconNames = files.map((file) => iconName(file));
const spriteUpToDate = iconNames.every((name) => currentSprite.includes(`id=${name}`));
const typesUpToDate = iconNames.every((name) => currentTypes.includes(`"${name}"`));
if (spriteUpToDate && typesUpToDate) {
logVerbose(`Icons are up to date`);
return;
}
logVerbose(`Generating sprite for ${inputDirRelative}`);
const spriteChanged = await generateSvgSprite({
files,
inputDir,
outputPath: spriteFilepath,
});
for (const file of files) {
logVerbose("✅", file);
}
logVerbose(`Saved to ${path.relative(cwd, spriteFilepath)}`);
const stringifiedIconNames = iconNames.map((name) => JSON.stringify(name));
const typeOutputContent = `// This file is generated by yarn run build:icons
export type IconName =
\t| ${stringifiedIconNames.join("\n\t| ")};
`;
const typesChanged = await writeIfChanged(typeOutputFilepath, typeOutputContent);
logVerbose(`Manifest saved to ${path.relative(cwd, typeOutputFilepath)}`);
if (spriteChanged || typesChanged) {
console.log(`Generated ${files.length} icons`);
}
}
function iconName(file) {
return file.replace(/\.svg$/, "");
}
/**
* Creates a single SVG file that contains all the icons
*/
async function generateSvgSprite({ files, inputDir, outputPath }) {
// Each SVG becomes a symbol and we wrap them all in a single SVG
const symbols = await Promise.all(
files.map(async (file) => {
const input = await fsExtra.readFile(path.join(inputDir, file), "utf8");
const root = parse(input);
const svg = root.querySelector("svg");
if (!svg) throw new Error("No SVG element found");
svg.tagName = "symbol";
svg.setAttribute("id", iconName(file));
svg.removeAttribute("xmlns");
svg.removeAttribute("xmlns:xlink");
svg.removeAttribute("version");
svg.removeAttribute("width");
svg.removeAttribute("height");
return svg.toString().trim();
})
);
const output = [
`<?xml version="1.0" encoding="UTF-8"?>`,
`<!-- This file is generated by npm run build:icons -->`,
`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0" height="0">`,
`<defs>`, // for semantics: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs
...symbols,
`</defs>`,
`</svg>`,
"", // trailing newline
].join("\n");
return writeIfChanged(outputPath, output);
}
async function writeIfChanged(filepath, newContent) {
const currentContent = await fsExtra.readFile(filepath, "utf8").catch(() => "");
if (currentContent === newContent) return false;
await fsExtra.writeFile(filepath, newContent, "utf8");
await $`prettier --write ${filepath} --ignore-unknown`;
return true;
}
await copyIcons();
await generateIconFiles();
await removeTempDir();
+34
View File
@@ -0,0 +1,34 @@
import glob from "fast-glob";
import fs from "fs-extra";
import path from "node:path";
import { lucideIconList } from "../components/icon/icon-list.mjs";
const cwd = process.cwd();
const inputDir = path.join(cwd, "../../", "node_modules", "lucide-static", "icons");
const tempDir = path.join(cwd, "svg-icons");
export async function copyIcons() {
fs.ensureDirSync(tempDir);
const svgIcons = glob.sync("**/*.svg", {
cwd: inputDir,
});
for (const icon of svgIcons) {
if (lucideIconList.has(icon.replace(".svg", ""))) {
const destinationFile = path.join(tempDir, icon);
const file = path.join(inputDir, icon);
try {
fs.copyFileSync(file, destinationFile);
console.log(`Copied icon: ${icon}`);
} catch (err) {
console.error(`Error copying file: ${icon}`, err);
}
}
}
}
export const removeTempDir = async () => {
await fs.remove(tempDir);
};