Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

3.5 KB
Raw Blame
import type { StyleProp } from "./style-types";
import type { IconName } from "@reactive-resume/schema/icons";
import { commonIcons, iconFiles } from "./phosphor-icons";
import { Svg } from "./primitives";
import { flattenStyle, parseColor } from "./style";

export type { IconName };

type IconFile = keyof typeof iconFiles;

// Icon drawings (generated by `pnpm --filter @reactive-resume/tooling icons:pdf`) load as renders first ask for
// them: the ~30 most resumes draw (7 KB gzipped), then all the rest (190 KB) only when a render draws another.
const icons = new Map<string, string>();
const loaded = new Set<IconFile>();
const loading = new Map<IconFile, Promise<void>>();
const requested = new Set<IconFile>();

const loadFile = (file: IconFile) => {
	let promise = loading.get(file);
	if (!promise) {
		promise = iconFiles[file]().then(
			(module) => {
				for (const [name, markup] of Object.entries(module.default)) icons.set(name, markup);
				loaded.add(file);
			},
			(error: unknown) => {
				// A failed download may succeed next time.
				loading.delete(file);
				throw error;
			},
		);
		loading.set(file, promise);
	}
	return promise;
};

/** Loads every icon, for tests. */
export const loadAllIcons = () => Promise.all([loadFile("common"), loadFile("rest")]);

/**
 * Loads the icon files the renders since the last call asked for and didn't have. Returns whether any loaded, so
 * the caller knows to render again.
 */
export async function loadRequestedIcons(): Promise<boolean> {
	const files = [...requested];
	requested.clear();
	await Promise.all(files.map(loadFile));
	return files.length > 0;
}

type PhosphorIconProps = {
	name: IconName | string;
	size?: number | string | undefined;
	color?: string | undefined;
	opacity?: number | string | undefined;
	/** "none" hides the icon, as on react-pdf's SVG. */
	display?: "none" | "flex" | undefined;
	style?: StyleProp | undefined;
	weight?: "regular" | undefined;
};

/**
 * A regular-weight Phosphor icon, drawn as vector paths. Same props as `phosphor-icons-react-pdf`'s `Icon`; an
 * unknown name draws nothing.
 */
export function PhosphorIcon({ name, size = 16, color = "currentColor", opacity, display, style }: PhosphorIconProps) {
	if (display === "none") return null;
	const markup = icons.get(name);
	if (!markup) {
		const file = commonIcons.has(name) ? "common" : "rest";
		if (name && !loaded.has(file)) requested.add(file);
		return null;
	}
	// "currentColor" means the colour the template set on the icon's style, as in react-pdf.
	const { opacity: styleOpacity, ...flat } = flattenStyle(style);
	// Forme 0.25 lets an SVG's opacity leak into whatever it draws next, so it goes into the paint instead.
	const alpha = Number(opacity ?? styleOpacity ?? 1);
	const paint = svgPaint(
		color === "currentColor" ? (flat.color ?? "#000000") : color,
		Number.isFinite(alpha) ? alpha : 1,
	);
	return (
		<Svg
			viewBox="0 0 256 256"
			width={size}
			height={size}
			content={markup.replaceAll("<path ", `<path ${paint} `)}
			style={flat}
		/>
	);
}

/** SVG fill attributes for a CSS colour: hex, with rgba's alpha times `opacity` as `fill-opacity`. */
function svgPaint(color: string, opacity: number) {
	const { rgb, alpha: colorAlpha } = parseColor(color) ?? { rgb: [0, 0, 0], alpha: 1 };
	const hex = `#${rgb.map((channel) => Math.round(channel).toString(16).padStart(2, "0")).join("")}`;
	const alpha = Math.max(0, Math.min(1, colorAlpha * opacity));
	return alpha < 1 ? `fill="${hex}" fill-opacity="${alpha}"` : `fill="${hex}"`;
}