refactor(editor): add a lookup map for freedraw StrokeWidthKey

This commit is contained in:
dwelle
2026-06-24 09:18:44 +02:00
parent cd514d72d6
commit 80e83374d4
2 changed files with 22 additions and 19 deletions
+20
View File
@@ -435,6 +435,26 @@ export const FREEDRAW_STROKE_WIDTH: Readonly<
extraBold: 4, // legacy (may be used again in the future)
};
const STROKE_WIDTH_TO_KEY = {
generic: Object.fromEntries(
Object.entries(STROKE_WIDTH).map(([key, value]) => [value, key]),
) as Record<ExcalidrawElement["strokeWidth"], StrokeWidthKey | undefined>,
freedraw: Object.fromEntries(
Object.entries(FREEDRAW_STROKE_WIDTH).map(([key, value]) => [value, key]),
) as Record<ExcalidrawElement["strokeWidth"], StrokeWidthKey | undefined>,
};
export const getStrokeWidthKeyForElement = (
element: Pick<ExcalidrawElement, "type" | "strokeWidth">,
): StrokeWidthKey | null => {
const strokeWidthToKey =
element.type === "freedraw"
? STROKE_WIDTH_TO_KEY.freedraw
: STROKE_WIDTH_TO_KEY.generic;
return strokeWidthToKey[element.strokeWidth] ?? null;
};
export const getStrokeWidthByKey = (
elementType: ExcalidrawElement["type"],
strokeWidthKey: StrokeWidthKey,
@@ -12,7 +12,6 @@ import {
DEFAULT_FONT_SIZE,
FONT_FAMILY,
ROUNDNESS,
STROKE_WIDTH_KEYS,
VERTICAL_ALIGN,
KEYS,
randomInteger,
@@ -25,6 +24,7 @@ import {
invariant,
FONT_SIZES,
type StrokeWidthKey,
getStrokeWidthKeyForElement,
} from "@excalidraw/common";
import { canBecomePolygon, getNonDeletedElements } from "@excalidraw/element";
@@ -554,23 +554,6 @@ export const actionChangeFillStyle = register<ExcalidrawElement["fillStyle"]>({
},
});
const getStrokeWidthKeyForElement = (
element: ExcalidrawElement,
): StrokeWidthKey | null => {
return (
STROKE_WIDTH_KEYS.find(
(key) => getStrokeWidthByKey(element.type, key) === element.strokeWidth,
) ?? null
);
};
const getStrokeWidthForElement = (
element: ExcalidrawElement,
strokeWidthKey: StrokeWidthKey,
): ExcalidrawElement["strokeWidth"] => {
return getStrokeWidthByKey(element.type, strokeWidthKey);
};
export const actionChangeStrokeWidth = register<StrokeWidthKey>({
name: "changeStrokeWidth",
label: "labels.strokeWidth",
@@ -581,7 +564,7 @@ export const actionChangeStrokeWidth = register<StrokeWidthKey>({
return {
elements: changeProperty(elements, appState, (el) =>
newElementWith(el, {
strokeWidth: getStrokeWidthForElement(el, value),
strokeWidth: getStrokeWidthByKey(el.type, value),
}),
),
appState: { ...appState, currentItemStrokeWidthKey: value },