-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhex-input.gts
More file actions
91 lines (81 loc) · 2.32 KB
/
hex-input.gts
File metadata and controls
91 lines (81 loc) · 2.32 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
80
81
82
83
84
85
86
87
88
89
90
91
import { hash } from '@ember/helper';
import { on } from '@ember/modifier';
import { action, set, setProperties } from '@ember/object';
import Component from '@glimmer/component';
import OneWayInputMask from 'ember-inputmask/components/one-way-input-mask';
import { TinyColor } from '@ctrl/tinycolor';
import type {
SelectedColorModel,
SelectedColorPOJO,
} from '../components/rgb-input.gts';
import { rgbaToHex } from '../data-models/color.ts';
interface HexInputSignature {
Element: HTMLInputElement;
Args: {
selectedColor: SelectedColorModel | SelectedColorPOJO;
update: (value: string | number) => void;
updateColor: () => void;
value?: string;
};
}
export default class HexInputComponent extends Component<HexInputSignature> {
<template>
<OneWayInputMask
...attributes
@options={{hash
isComplete=this.isComplete
regex=this.hexRegex
showMaskOnFocus=false
showMaskOnHover=false
onincomplete=this.onIncomplete
oncomplete=this.onComplete
}}
@mask="\#*{6,8}"
@update={{@update}}
@value={{@value}}
{{on "keypress" this.enterPress}}
/>
</template>
hexRegex = /^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6})$/;
@action
enterPress(event: KeyboardEvent): void {
if (event.keyCode === 13) {
(<HTMLInputElement>event.target).blur();
}
}
@action
isComplete(buffer: Array<string>, opts: { regex?: string }): boolean {
return new RegExp(opts.regex as string).test(buffer.join(''));
}
/**
* Executes whenever the hex value matches the regex. We can use this to change the color values only when valid.
* @param {Event} event The event when the hex matches the regex and is valid
*/
@action
onComplete(event: InputEvent): void {
const tinyColor = new TinyColor((<HTMLInputElement>event.target).value);
const { r, g, b, a } = tinyColor.toRgb();
const hex = rgbaToHex(r, g, b, a);
const alpha = parseFloat(a.toFixed(2));
setProperties(this.args.selectedColor, {
_hex: hex,
_r: r,
_g: g,
_b: b,
_a: alpha,
hex,
r,
g,
b,
a: alpha,
});
this.args.updateColor();
}
/**
* Resets the hex value if you navigate away
*/
@action
onIncomplete(): void {
set(this.args.selectedColor, '_hex', this.args.selectedColor?.hex);
}
}