-
Notifications
You must be signed in to change notification settings - Fork 9
/
slider.ts
81 lines (64 loc) · 2.48 KB
/
slider.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { Frame, getFrameChecked } from '../core/frame';
import { Color, Rect, Vector2 } from '../core/types';
import { InputControl } from '../core/input';
import { getDefaultStyleSelectorState } from '../core/utils';
/**
* @category Items
*/
export function slider(value: number, min: number, max: number, w: number, text: string | null = null): number {
const frame = getFrameChecked();
const input = frame.getInput();
const layout = frame.getLayout();
const painter = frame.getPainter();
const style = Frame.getStyle();
const h = style.item.height;
frame.beginItem(w, h);
const selector = frame.buildStyleSelector('slider', getDefaultStyleSelectorState(frame));
const sliderStyle = style.slider;
const font = style.getPropertyAs<number>(selector, 'font-family');
const scale = style.getPropertyAs<number>(selector, 'font-size');
const sliderText = text ?? value.toFixed(2);
const tw = painter.getTextWidth(sliderText, font, scale);
const sw = tw !== 0 ? w - tw - style.slider.padding : w;
const frameScale = Frame.getScale();
const inputValue =
!frame.isItemDisabled() &&
frame.isAreaHovered(
new Rect(
new Vector2(
layout.getItemRect().position.x - (sliderStyle.thumbSize.x * frameScale) / 2,
layout.getItemRect().position.y
),
new Vector2((sw + sliderStyle.thumbSize.x) * frameScale, h * frameScale)
)
) &&
(input.isControlDown(InputControl.MouseLeftButton) || input.isControlPressed(InputControl.MouseLeftButton))
? Math.min(
max,
Math.max(
min,
min +
((input.getMousePosition().x - layout.getItemRect().position.x) / (sw * frameScale)) *
(max - min)
)
)
: value;
const sh = (h - sliderStyle.height) / 2;
painter.setColor(style.getPropertyAs<Color>(selector, 'background-color'));
painter.move(0, sh);
painter.drawRect(sw, sliderStyle.height);
if (tw !== 0) {
const tho = sw + style.slider.padding;
const tvo = -sh + (h - GetRenderedCharacterHeight(scale, font)) / 2 + style.item.textOffset;
painter.move(tho, tvo);
painter.setColor(style.getPropertyAs<Color>(selector, 'color'));
painter.drawText(sliderText, font, scale);
painter.move(-tho, -tvo);
}
const sx = (sw * (inputValue - min)) / (max - min);
painter.move(sx - sliderStyle.thumbSize.x / 2, (sliderStyle.height - sliderStyle.thumbSize.y) / 2);
painter.setColor(style.getPropertyAs<Color>(selector, 'accent-color'));
painter.drawRect(sliderStyle.thumbSize.x, sliderStyle.thumbSize.y);
frame.endItem();
return inputValue;
}