-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
56 lines (49 loc) · 1.25 KB
/
index.ts
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
export const fit = (
node: HTMLElement,
{ min_size = 10, max_size = 100 } = { min_size: 10, max_size: 100 }
): { destroy: () => void } => {
const on_resize = (): void => {
if (node.parentElement) {
resize_text(node, node.parentElement, min_size, max_size)
}
}
on_resize()
// const resize_observer = new ResizeObserver(on_resize)
// resize_observer.observe(node?.parentElement as HTMLElement)
// return {
// destroy(): void {
// resize_observer.disconnect()
// },
// }
}
function is_overflow({
clientWidth,
clientHeight,
scrollWidth,
scrollHeight,
}: HTMLElement): boolean {
return scrollWidth > clientWidth || scrollHeight > clientHeight
}
function resize_text(
element: HTMLElement,
parent: HTMLElement,
min_size: number,
max_size: number
): void {
let i: number = min_size
let overflow: boolean = false
let size: number = min_size
element.style.fontSize = `${size}px`
while (!overflow && i < max_size) {
overflow = is_overflow(parent)
if (!overflow) {
// If not overflowing, increase the font size
element.style.fontSize = `${i}px`
i += 2
}
}
size = i - 2
// console.log('overflow', i, size, element)
element.style.fontSize = `${size}px`
}
export const parent_style = `display: inline-block; width: 100%; height: 100%;`