Skip to content

Commit

Permalink
Improve performance of auto-viewbox
Browse files Browse the repository at this point in the history
  • Loading branch information
LitoMore committed Sep 11, 2024
1 parent 019c0a4 commit 50422c4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
13 changes: 7 additions & 6 deletions source/icon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ export const getSimpleIcon = (slug?: string) => {
return null;
};

export const getIconSize = (path: string) => {
export const getIconSize = (path: typeof svgpath) => {
const [x0, y0, x1, y1] = svgPathBbox(path);
return { width: x1 - x0, height: y1 - y0 };
};

export const resetIconPosition = (
path: string,
pathInstance: typeof svgpath,
iconWidth: number,
iconHeight: number,
) => {
Expand All @@ -41,8 +41,8 @@ export const resetIconPosition = (
const betterViewboxWidth = Math.ceil(actualViewboxWidth);
const betterOffset = (betterViewboxWidth - actualViewboxWidth) / 2;
const pathRescale = iconWidth > iconHeight
? svgpath(path).scale(scale)
: svgpath(path);
? pathInstance.scale(scale)
: pathInstance;
const [offsetX, offsetY] = svgPathBbox(pathRescale);
const pathReset = pathRescale.translate(
-offsetX + betterOffset,
Expand All @@ -64,9 +64,10 @@ export const getIconSvg = (
let iconSvg = icon.svg;

if (viewbox === 'auto') {
const { width: iconWidth, height: iconHeight } = getIconSize(icon.path);
const pathInstance = svgpath(icon.path);
const { width: iconWidth, height: iconHeight } = getIconSize(pathInstance);
const { path, betterViewboxWidth } = resetIconPosition(
icon.path,
pathInstance,
iconWidth,
iconHeight,
);
Expand Down
6 changes: 4 additions & 2 deletions test/viewbox.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import * as si from 'npm:simple-icons';
import svgpath from 'svgpath';
import { getIconSize, resetIconPosition } from '../source/icon.ts';

const checkAutoViewboxPath = (icon: si.SimpleIcon) => {
const start = performance.now();
const pathInstance = svgpath(icon.path);
try {
const { width, height } = getIconSize(icon.path);
const { width, height } = getIconSize(pathInstance);
const { path } = resetIconPosition(
icon.path,
pathInstance,
width,
height,
);
Expand Down

0 comments on commit 50422c4

Please sign in to comment.