fix text align

This commit is contained in:
Hamid
2026-05-17 01:26:34 -07:00
parent 5bbd677f41
commit 642155661c
2 changed files with 83 additions and 30 deletions
+66 -1
View File
@@ -144,7 +144,7 @@ export const getEffectiveTextWidth = (
return Math.max(1, base + SINGLE_LINE_WIDTH_SLACK_PX);
};
/** Scaled width for viewer text (wrapped / multi-line layout only). */
/** Scaled width for viewer text boxes (includes slack to avoid tighter CSS wrapping than Konva). */
export const getScaledTextWidth = (
width: number | undefined,
scale: number,
@@ -152,3 +152,68 @@ export const getScaledTextWidth = (
if (!width) return undefined;
return Math.ceil(width * scale) + Math.ceil(SINGLE_LINE_WIDTH_SLACK_PX * scale);
};
export type TextAlignValue = "left" | "center" | "right";
export type ViewerTextLayout = {
leftPx: number;
widthPx: number | undefined;
textAlign: TextAlignValue;
transform: string | undefined;
transformOrigin: "top right";
};
/**
* Viewer HTML layout matching Konva TextShape: (x, y) is the top-right anchor of the text box.
* Text alignment is applied inside a fixed-width box that extends left from the anchor.
*/
export function getViewerTextLayout(args: {
x: number;
width?: number;
text?: string;
textAlign?: TextAlignValue;
rotation?: number;
scale: number;
measureOpts: TextMeasureOptions;
wrapped: boolean;
}): ViewerTextLayout {
const {
x,
width: storedWidth,
text,
textAlign = "right",
rotation = 0,
scale,
measureOpts,
wrapped,
} = args;
const layoutWidth = getEffectiveTextWidth(
storedWidth,
text,
measureOpts,
!wrapped,
);
const widthPx = getScaledTextWidth(layoutWidth, scale);
const slackPx =
widthPx !== undefined ? Math.ceil(SINGLE_LINE_WIDTH_SLACK_PX * scale) : 0;
const rightPx = x * scale;
const boxWidthUnscaled = layoutWidth ?? storedWidth ?? 0;
let leftPx: number;
if (widthPx !== undefined && boxWidthUnscaled > 0) {
leftPx = Math.round(rightPx - boxWidthUnscaled * scale) - slackPx;
} else {
leftPx = Math.round(rightPx);
}
const rotationTransform = rotation ? `rotate(${rotation}deg)` : undefined;
return {
leftPx,
widthPx,
textAlign,
transform: rotationTransform,
transformOrigin: "top right",
};
}