-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathresize-fontsize-change.hook.ts
More file actions
79 lines (69 loc) · 2.24 KB
/
resize-fontsize-change.hook.ts
File metadata and controls
79 lines (69 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { calcTextDimensions } from '@/common/utils/calc-text-dimensions';
import { useCanvasContext } from '@/core/providers';
import { useEffect, useRef } from 'react';
export interface MultipleItemsInfo {
numberOfItems: number;
horizontalSpacing: number;
}
export const useResizeOnFontSizeChange = (
id: string,
coords: { x: number; y: number },
text: string,
fontSize: number,
fontVariant: string,
multiline: boolean = false,
multipleItemsInfo?: MultipleItemsInfo // Just in case we have a list of items (horizontally), e.g horizontal menu
) => {
const previousFontSize = useRef(fontSize);
const { updateShapeSizeAndPosition, stageRef } = useCanvasContext();
const konvaLayer = stageRef.current?.getLayers()[0];
useEffect(() => {
if (previousFontSize.current !== fontSize) {
previousFontSize.current = fontSize;
const paragraphLines = _extractParagraphLines(text);
const longestLine = _findLongestString(paragraphLines);
const { width: longestLineWidth, height: longestLineHeight } =
calcTextDimensions(
multiline ? longestLine : text,
fontSize,
fontVariant,
konvaLayer
);
// We add to the longest line width the spacing between items if multiple items
const width =
longestLineWidth +
(multipleItemsInfo
? multipleItemsInfo.horizontalSpacing *
multipleItemsInfo.numberOfItems
: 0);
const height = longestLineHeight;
updateShapeSizeAndPosition(
id,
coords,
{
width: width * 1.25,
height: multiline
? _calcParagraphTotalHeight(height, 0.8, paragraphLines.length)
: height,
},
true
);
}
}, [fontSize]);
};
/* Hook Helper functions */
function _extractParagraphLines(multilineText: string) {
return multilineText.split(/\r?\n/).filter(line => line.trim() !== '');
}
function _findLongestString(stringsArray: string[]): string {
return stringsArray.reduce((longest, current) =>
current.length > longest.length ? current : longest
);
}
function _calcParagraphTotalHeight(
heightPerLine: number,
lineHeight: number = 1.3,
linesQty: number
) {
return heightPerLine * lineHeight * linesQty;
}