@muxima-ui/core 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,755 @@
1
+ import * as i0 from '@angular/core';
2
+ import { model, input, booleanAttribute, output, viewChild, signal, computed, effect, untracked, ViewEncapsulation, ChangeDetectionStrategy, Component, inject, ElementRef } from '@angular/core';
3
+ import { mxUniqueId, MxFormField, MX_FORM_FIELD_CONTROL } from '@muxima-ui/core/form-field';
4
+ import { CdkOverlayOrigin, CdkConnectedOverlay } from '@angular/cdk/overlay';
5
+ import { NgControl, Validators } from '@angular/forms';
6
+
7
+ const clamp = (n, min = 0, max = 1) => Math.min(Math.max(n, min), max);
8
+ /**
9
+ * Lê uma cor escrita: "#1f6f78", "1f6f78", "#1f6", "#1f6f7880" ou "rgb(31, 111, 120)" / "rgba(...)".
10
+ * Devolve o hex normalizado ("#1F6F78" ou "#1F6F7880" com opacidade) ou null.
11
+ */
12
+ function mxParseColor(text) {
13
+ const t = text.trim();
14
+ const rgb = t.match(/^rgba?\(\s*(\d{1,3})\s*[,\s]\s*(\d{1,3})\s*[,\s]\s*(\d{1,3})\s*(?:[,/]\s*([\d.]+%?)\s*)?\)$/i);
15
+ if (rgb) {
16
+ const [r, g, b] = [rgb[1], rgb[2], rgb[3]].map(Number);
17
+ if ([r, g, b].some((n) => n > 255))
18
+ return null;
19
+ let a = 1;
20
+ if (rgb[4])
21
+ a = rgb[4].endsWith('%') ? Number(rgb[4].slice(0, -1)) / 100 : Number(rgb[4]);
22
+ return rgbaToHex(r, g, b, clamp(a));
23
+ }
24
+ let h = t.replace(/^#/, '');
25
+ if (!/^([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(h))
26
+ return null;
27
+ if (h.length <= 4)
28
+ h = [...h].map((c) => c + c).join('');
29
+ h = h.toUpperCase();
30
+ if (h.length === 8 && h.endsWith('FF'))
31
+ h = h.slice(0, 6);
32
+ return '#' + h;
33
+ }
34
+ function rgbaToHex(r, g, b, a = 1) {
35
+ const x = (n) => Math.round(n).toString(16).padStart(2, '0').toUpperCase();
36
+ return `#${x(r)}${x(g)}${x(b)}${a < 1 ? x(a * 255) : ''}`;
37
+ }
38
+ function mxHexToRgba(hex) {
39
+ const h = (mxParseColor(hex) ?? '#000000').slice(1);
40
+ return {
41
+ r: parseInt(h.slice(0, 2), 16),
42
+ g: parseInt(h.slice(2, 4), 16),
43
+ b: parseInt(h.slice(4, 6), 16),
44
+ a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
45
+ };
46
+ }
47
+ function mxHexToHsva(hex) {
48
+ const { r, g, b, a } = mxHexToRgba(hex);
49
+ const [rr, gg, bb] = [r / 255, g / 255, b / 255];
50
+ const max = Math.max(rr, gg, bb);
51
+ const min = Math.min(rr, gg, bb);
52
+ const d = max - min;
53
+ let h = 0;
54
+ if (d) {
55
+ if (max === rr)
56
+ h = ((gg - bb) / d) % 6;
57
+ else if (max === gg)
58
+ h = (bb - rr) / d + 2;
59
+ else
60
+ h = (rr - gg) / d + 4;
61
+ h *= 60;
62
+ if (h < 0)
63
+ h += 360;
64
+ }
65
+ return { h, s: max ? d / max : 0, v: max, a };
66
+ }
67
+ function mxHsvaToHex({ h, s, v, a }) {
68
+ const f = (n) => {
69
+ const k = (n + h / 60) % 6;
70
+ return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
71
+ };
72
+ return rgbaToHex(f(5) * 255, f(3) * 255, f(1) * 255, a);
73
+ }
74
+ /** Contraste WCAG entre duas cores (1 a 21). */
75
+ function mxContrast(a, b) {
76
+ const lum = (hex) => {
77
+ const { r, g, b: bb } = mxHexToRgba(hex);
78
+ const c = [r, g, bb].map((x) => {
79
+ const s = x / 255;
80
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
81
+ });
82
+ return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
83
+ };
84
+ const [l1, l2] = [lum(a), lum(b)].sort((x, y) => y - x);
85
+ return (l1 + 0.05) / (l2 + 0.05);
86
+ }
87
+ const HUES = [
88
+ [15, 'vermelho'],
89
+ [40, 'laranja'],
90
+ [65, 'amarelo'],
91
+ [80, 'verde-lima'],
92
+ [160, 'verde'],
93
+ [195, 'azul-petróleo'],
94
+ [250, 'azul'],
95
+ [285, 'roxo'],
96
+ [330, 'magenta'],
97
+ [360, 'vermelho'],
98
+ ];
99
+ /** Nome aproximado da cor em português, para o leitor de ecrã: "azul escuro", "cinzento claro". */
100
+ function mxColorName(hex) {
101
+ const { h, s, v } = mxHexToHsva(hex);
102
+ if (v < 0.12)
103
+ return 'preto';
104
+ if (s < 0.12)
105
+ return v > 0.92
106
+ ? 'branco'
107
+ : v > 0.6
108
+ ? 'cinzento claro'
109
+ : v > 0.3
110
+ ? 'cinzento'
111
+ : 'cinzento escuro';
112
+ let name = HUES.find(([max]) => h < max)[1];
113
+ if (name === 'laranja' && v < 0.6)
114
+ name = 'castanho';
115
+ // luminosidade HSL: escuro abaixo de 38%, claro acima de 70%
116
+ const l = v * (1 - s / 2);
117
+ const tone = l < 0.38 ? ' escuro' : l > 0.7 ? ' claro' : '';
118
+ return name + tone;
119
+ }
120
+
121
+ /**
122
+ * Editor de cor: área de saturação e brilho, matiz, opacidade opcional, campo hex,
123
+ * amostras e conta-gotas (quando o navegador o tem). O valor é um hex ("#1F6F78",
124
+ * ou "#1F6F7880" com opacidade).
125
+ *
126
+ * ```html
127
+ * <mx-color-panel [(value)]="cor" [swatches]="marca" />
128
+ * ```
129
+ *
130
+ * Teclado na área: ← → mudam a saturação, ↑ ↓ o brilho (Shift para passos de 10).
131
+ * A matiz e a opacidade são input range nativos.
132
+ */
133
+ class MxColorPanel {
134
+ value = model('#1F6F78', ...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
135
+ /** Mostra o controlo de opacidade e devolve hex de 8 dígitos quando < 100%. */
136
+ alpha = input(false, { ...(ngDevMode ? { debugName: "alpha" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
137
+ swatches = input([], ...(ngDevMode ? [{ debugName: "swatches" }] : /* istanbul ignore next */ []));
138
+ showInput = input(true, { ...(ngDevMode ? { debugName: "showInput" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
139
+ /** Só as amostras: uma paleta fechada, sem área nem matiz. */
140
+ swatchesOnly = input(false, { ...(ngDevMode ? { debugName: "swatchesOnly" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
141
+ disabled = input(false, { ...(ngDevMode ? { debugName: "disabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
142
+ areaLabel = input('Saturação e brilho', ...(ngDevMode ? [{ debugName: "areaLabel" }] : /* istanbul ignore next */ []));
143
+ hueLabel = input('Matiz', ...(ngDevMode ? [{ debugName: "hueLabel" }] : /* istanbul ignore next */ []));
144
+ alphaLabel = input('Opacidade', ...(ngDevMode ? [{ debugName: "alphaLabel" }] : /* istanbul ignore next */ []));
145
+ swatchesLabel = input('Cores sugeridas', ...(ngDevMode ? [{ debugName: "swatchesLabel" }] : /* istanbul ignore next */ []));
146
+ /** Emite ao largar o rato, escolher amostra ou terminar de escrever (para guardar). */
147
+ committed = output();
148
+ area = viewChild.required('area');
149
+ inputId = mxUniqueId('mx-color-hex');
150
+ eyeDropper = typeof window !== 'undefined' && 'EyeDropper' in window;
151
+ /** HSVA interno: guarda a matiz quando a cor é cinzenta (o hex não a tem). */
152
+ hsva = signal(mxHexToHsva('#1F6F78'), ...(ngDevMode ? [{ debugName: "hsva" }] : /* istanbul ignore next */ []));
153
+ hex = computed(() => mxHsvaToHex(this.hsva()), ...(ngDevMode ? [{ debugName: "hex" }] : /* istanbul ignore next */ []));
154
+ opaque = computed(() => mxHsvaToHex({ ...this.hsva(), a: 1 }), ...(ngDevMode ? [{ debugName: "opaque" }] : /* istanbul ignore next */ []));
155
+ draft = signal(null, ...(ngDevMode ? [{ debugName: "draft" }] : /* istanbul ignore next */ []));
156
+ draftInvalid = computed(() => !!this.draft() && !mxParseColor(this.draft()), ...(ngDevMode ? [{ debugName: "draftInvalid" }] : /* istanbul ignore next */ []));
157
+ hueName = computed(() => mxColorName(mxHsvaToHex({ h: this.hsva().h, s: 1, v: 1, a: 1 })), ...(ngDevMode ? [{ debugName: "hueName" }] : /* istanbul ignore next */ []));
158
+ areaText = computed(() => {
159
+ const c = this.hsva();
160
+ return `Saturação ${this.pct(c.s)}%, brilho ${this.pct(c.v)}%, ${mxColorName(this.hex())}`;
161
+ }, ...(ngDevMode ? [{ debugName: "areaText" }] : /* istanbul ignore next */ []));
162
+ swatchList = computed(() => this.swatches().map((s) => {
163
+ const color = mxParseColor(typeof s === 'string' ? s : s.color) ?? '#000000';
164
+ const label = typeof s === 'string' ? `${mxColorName(color)}, ${color}` : `${s.label}, ${color}`;
165
+ return { color, label };
166
+ }), ...(ngDevMode ? [{ debugName: "swatchList" }] : /* istanbul ignore next */ []));
167
+ constructor() {
168
+ // valor de fora -> HSVA (sem perder a matiz quando é a mesma cor)
169
+ effect(() => {
170
+ const v = mxParseColor(this.value() ?? '');
171
+ if (!v)
172
+ return;
173
+ if (untracked(() => this.hex()) === v)
174
+ return;
175
+ const next = mxHexToHsva(v);
176
+ const prev = untracked(() => this.hsva());
177
+ this.hsva.set(next.s === 0 || next.v === 0 ? { ...next, h: prev.h } : next);
178
+ });
179
+ }
180
+ round(n) {
181
+ return Math.round(n);
182
+ }
183
+ pct(n) {
184
+ return Math.round(n * 100);
185
+ }
186
+ update(next, commit = false) {
187
+ this.hsva.update((c) => ({ ...c, ...next }));
188
+ const hex = this.alpha() ? this.hex() : mxHsvaToHex({ ...this.hsva(), a: 1 });
189
+ this.value.set(hex);
190
+ if (commit)
191
+ this.committed.emit(hex);
192
+ }
193
+ setHex(hex) {
194
+ const v = mxParseColor(hex);
195
+ if (!v)
196
+ return;
197
+ const next = mxHexToHsva(v);
198
+ this.hsva.set(next.s === 0 || next.v === 0 ? { ...next, h: this.hsva().h } : next);
199
+ this.value.set(this.alpha() ? v : mxHsvaToHex({ ...this.hsva(), a: 1 }));
200
+ this.committed.emit(this.value());
201
+ }
202
+ setHue(e) {
203
+ this.update({ h: Number(e.target.value) });
204
+ }
205
+ setAlpha(e) {
206
+ this.update({ a: Number(e.target.value) / 100 });
207
+ }
208
+ onHexInput(e) {
209
+ const text = e.target.value;
210
+ this.draft.set(text);
211
+ const v = mxParseColor(text);
212
+ if (v)
213
+ this.setHex(v);
214
+ }
215
+ onAreaKey(e) {
216
+ if (this.disabled())
217
+ return;
218
+ const step = e.shiftKey ? 0.1 : 0.01;
219
+ const c = this.hsva();
220
+ const moves = {
221
+ ArrowRight: { s: Math.min(1, c.s + step) },
222
+ ArrowLeft: { s: Math.max(0, c.s - step) },
223
+ ArrowUp: { v: Math.min(1, c.v + step) },
224
+ ArrowDown: { v: Math.max(0, c.v - step) },
225
+ PageUp: { v: Math.min(1, c.v + 0.1) },
226
+ PageDown: { v: Math.max(0, c.v - 0.1) },
227
+ Home: { s: 0 },
228
+ End: { s: 1 },
229
+ };
230
+ const m = moves[e.key];
231
+ if (m) {
232
+ e.preventDefault();
233
+ this.update(m, true);
234
+ }
235
+ }
236
+ onAreaDown(e) {
237
+ if (this.disabled() || e.button !== 0)
238
+ return;
239
+ e.preventDefault();
240
+ const el = this.area().nativeElement;
241
+ el.querySelector('.mx-color-area-thumb')?.focus();
242
+ const rect = el.getBoundingClientRect();
243
+ const move = (ev) => this.update({
244
+ s: Math.min(Math.max((ev.clientX - rect.left) / rect.width, 0), 1),
245
+ v: 1 - Math.min(Math.max((ev.clientY - rect.top) / rect.height, 0), 1),
246
+ });
247
+ move(e);
248
+ const up = () => {
249
+ window.removeEventListener('pointermove', move);
250
+ window.removeEventListener('pointerup', up);
251
+ this.committed.emit(this.value());
252
+ };
253
+ window.addEventListener('pointermove', move);
254
+ window.addEventListener('pointerup', up);
255
+ }
256
+ async pickFromScreen() {
257
+ try {
258
+ const Ctor = window.EyeDropper;
259
+ const r = await new Ctor().open();
260
+ this.setHex(r.sRGBHex);
261
+ }
262
+ catch {
263
+ // a pessoa cancelou
264
+ }
265
+ }
266
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: MxColorPanel, deps: [], target: i0.ɵɵFactoryTarget.Component });
267
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.25", type: MxColorPanel, isStandalone: true, selector: "mx-color-panel", inputs: { value: { classPropertyName: "value", publicName: "value", isSignal: true, isRequired: false, transformFunction: null }, alpha: { classPropertyName: "alpha", publicName: "alpha", isSignal: true, isRequired: false, transformFunction: null }, swatches: { classPropertyName: "swatches", publicName: "swatches", isSignal: true, isRequired: false, transformFunction: null }, showInput: { classPropertyName: "showInput", publicName: "showInput", isSignal: true, isRequired: false, transformFunction: null }, swatchesOnly: { classPropertyName: "swatchesOnly", publicName: "swatchesOnly", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, areaLabel: { classPropertyName: "areaLabel", publicName: "areaLabel", isSignal: true, isRequired: false, transformFunction: null }, hueLabel: { classPropertyName: "hueLabel", publicName: "hueLabel", isSignal: true, isRequired: false, transformFunction: null }, alphaLabel: { classPropertyName: "alphaLabel", publicName: "alphaLabel", isSignal: true, isRequired: false, transformFunction: null }, swatchesLabel: { classPropertyName: "swatchesLabel", publicName: "swatchesLabel", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { value: "valueChange", committed: "committed" }, host: { properties: { "attr.data-disabled": "disabled() ? \"\" : null", "attr.data-swatches-only": "swatchesOnly() ? \"\" : null", "style.--mx-color-hue": "hsva().h", "style.--mx-color-current": "hex()", "style.--mx-color-opaque": "opaque()" }, classAttribute: "mx-color-panel" }, viewQueries: [{ propertyName: "area", first: true, predicate: ["area"], descendants: true, isSignal: true }], exportAs: ["mxColorPanel"], ngImport: i0, template: `
268
+ @if (!swatchesOnly()) {
269
+ <div class="mx-color-area" #area (pointerdown)="onAreaDown($event)">
270
+ <div
271
+ class="mx-color-area-thumb"
272
+ role="slider"
273
+ [attr.tabindex]="disabled() ? -1 : 0"
274
+ [attr.aria-label]="areaLabel()"
275
+ aria-valuemin="0"
276
+ aria-valuemax="100"
277
+ [attr.aria-valuenow]="pct(hsva().s)"
278
+ [attr.aria-valuetext]="areaText()"
279
+ [attr.aria-disabled]="disabled() ? 'true' : null"
280
+ [style.left.%]="hsva().s * 100"
281
+ [style.top.%]="(1 - hsva().v) * 100"
282
+ (keydown)="onAreaKey($event)"
283
+ ></div>
284
+ </div>
285
+
286
+ <div class="mx-color-sliders">
287
+ <div class="mx-color-preview" aria-hidden="true"><span></span></div>
288
+ <div class="mx-color-ranges">
289
+ <input
290
+ type="range"
291
+ class="mx-color-range mx-color-hue"
292
+ min="0"
293
+ max="359"
294
+ [value]="round(hsva().h)"
295
+ [disabled]="disabled()"
296
+ [attr.aria-label]="hueLabel()"
297
+ [attr.aria-valuetext]="round(hsva().h) + ' graus, ' + hueName()"
298
+ (input)="setHue($event)"
299
+ />
300
+ @if (alpha()) {
301
+ <input
302
+ type="range"
303
+ class="mx-color-range mx-color-alpha"
304
+ min="0"
305
+ max="100"
306
+ [value]="pct(hsva().a)"
307
+ [disabled]="disabled()"
308
+ [attr.aria-label]="alphaLabel()"
309
+ [attr.aria-valuetext]="pct(hsva().a) + '%'"
310
+ (input)="setAlpha($event)"
311
+ />
312
+ }
313
+ </div>
314
+ @if (eyeDropper) {
315
+ <button
316
+ type="button"
317
+ class="mx-color-tool"
318
+ [disabled]="disabled()"
319
+ aria-label="Escolher uma cor do ecrã"
320
+ (click)="pickFromScreen()"
321
+ >
322
+ <svg viewBox="0 0 16 16" fill="none" aria-hidden="true">
323
+ <path
324
+ d="M10.5 2.5l3 3-1.5 1.5-.8-.8-5.7 5.7H3.5v-2l5.7-5.7-.8-.8z"
325
+ stroke="currentColor"
326
+ stroke-width="1.3"
327
+ stroke-linejoin="round"
328
+ />
329
+ </svg>
330
+ </button>
331
+ }
332
+ </div>
333
+ }
334
+
335
+ @if (showInput() && !swatchesOnly()) {
336
+ <div class="mx-color-input-row">
337
+ <label class="mx-color-input-label" [for]="inputId">Hex</label>
338
+ <input
339
+ class="mx-input mx-color-hex"
340
+ data-size="sm"
341
+ [id]="inputId"
342
+ spellcheck="false"
343
+ autocomplete="off"
344
+ [disabled]="disabled()"
345
+ [value]="draft() ?? hex()"
346
+ [attr.aria-invalid]="draftInvalid() ? 'true' : null"
347
+ (input)="onHexInput($event)"
348
+ (blur)="draft.set(null)"
349
+ />
350
+ </div>
351
+ }
352
+
353
+ @if (swatchList().length) {
354
+ <div class="mx-color-swatches" role="group" [attr.aria-label]="swatchesLabel()">
355
+ @for (s of swatchList(); track s.color) {
356
+ <button
357
+ type="button"
358
+ class="mx-color-swatch"
359
+ [style.--mx-swatch]="s.color"
360
+ [attr.aria-label]="s.label"
361
+ [attr.aria-pressed]="s.color === hex()"
362
+ [disabled]="disabled()"
363
+ (click)="setHex(s.color)"
364
+ ></button>
365
+ }
366
+ </div>
367
+ }
368
+ `, isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
369
+ }
370
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: MxColorPanel, decorators: [{
371
+ type: Component,
372
+ args: [{
373
+ selector: 'mx-color-panel',
374
+ exportAs: 'mxColorPanel',
375
+ changeDetection: ChangeDetectionStrategy.OnPush,
376
+ encapsulation: ViewEncapsulation.None,
377
+ host: {
378
+ class: 'mx-color-panel',
379
+ '[attr.data-disabled]': 'disabled() ? "" : null',
380
+ '[attr.data-swatches-only]': 'swatchesOnly() ? "" : null',
381
+ '[style.--mx-color-hue]': 'hsva().h',
382
+ '[style.--mx-color-current]': 'hex()',
383
+ '[style.--mx-color-opaque]': 'opaque()',
384
+ },
385
+ template: `
386
+ @if (!swatchesOnly()) {
387
+ <div class="mx-color-area" #area (pointerdown)="onAreaDown($event)">
388
+ <div
389
+ class="mx-color-area-thumb"
390
+ role="slider"
391
+ [attr.tabindex]="disabled() ? -1 : 0"
392
+ [attr.aria-label]="areaLabel()"
393
+ aria-valuemin="0"
394
+ aria-valuemax="100"
395
+ [attr.aria-valuenow]="pct(hsva().s)"
396
+ [attr.aria-valuetext]="areaText()"
397
+ [attr.aria-disabled]="disabled() ? 'true' : null"
398
+ [style.left.%]="hsva().s * 100"
399
+ [style.top.%]="(1 - hsva().v) * 100"
400
+ (keydown)="onAreaKey($event)"
401
+ ></div>
402
+ </div>
403
+
404
+ <div class="mx-color-sliders">
405
+ <div class="mx-color-preview" aria-hidden="true"><span></span></div>
406
+ <div class="mx-color-ranges">
407
+ <input
408
+ type="range"
409
+ class="mx-color-range mx-color-hue"
410
+ min="0"
411
+ max="359"
412
+ [value]="round(hsva().h)"
413
+ [disabled]="disabled()"
414
+ [attr.aria-label]="hueLabel()"
415
+ [attr.aria-valuetext]="round(hsva().h) + ' graus, ' + hueName()"
416
+ (input)="setHue($event)"
417
+ />
418
+ @if (alpha()) {
419
+ <input
420
+ type="range"
421
+ class="mx-color-range mx-color-alpha"
422
+ min="0"
423
+ max="100"
424
+ [value]="pct(hsva().a)"
425
+ [disabled]="disabled()"
426
+ [attr.aria-label]="alphaLabel()"
427
+ [attr.aria-valuetext]="pct(hsva().a) + '%'"
428
+ (input)="setAlpha($event)"
429
+ />
430
+ }
431
+ </div>
432
+ @if (eyeDropper) {
433
+ <button
434
+ type="button"
435
+ class="mx-color-tool"
436
+ [disabled]="disabled()"
437
+ aria-label="Escolher uma cor do ecrã"
438
+ (click)="pickFromScreen()"
439
+ >
440
+ <svg viewBox="0 0 16 16" fill="none" aria-hidden="true">
441
+ <path
442
+ d="M10.5 2.5l3 3-1.5 1.5-.8-.8-5.7 5.7H3.5v-2l5.7-5.7-.8-.8z"
443
+ stroke="currentColor"
444
+ stroke-width="1.3"
445
+ stroke-linejoin="round"
446
+ />
447
+ </svg>
448
+ </button>
449
+ }
450
+ </div>
451
+ }
452
+
453
+ @if (showInput() && !swatchesOnly()) {
454
+ <div class="mx-color-input-row">
455
+ <label class="mx-color-input-label" [for]="inputId">Hex</label>
456
+ <input
457
+ class="mx-input mx-color-hex"
458
+ data-size="sm"
459
+ [id]="inputId"
460
+ spellcheck="false"
461
+ autocomplete="off"
462
+ [disabled]="disabled()"
463
+ [value]="draft() ?? hex()"
464
+ [attr.aria-invalid]="draftInvalid() ? 'true' : null"
465
+ (input)="onHexInput($event)"
466
+ (blur)="draft.set(null)"
467
+ />
468
+ </div>
469
+ }
470
+
471
+ @if (swatchList().length) {
472
+ <div class="mx-color-swatches" role="group" [attr.aria-label]="swatchesLabel()">
473
+ @for (s of swatchList(); track s.color) {
474
+ <button
475
+ type="button"
476
+ class="mx-color-swatch"
477
+ [style.--mx-swatch]="s.color"
478
+ [attr.aria-label]="s.label"
479
+ [attr.aria-pressed]="s.color === hex()"
480
+ [disabled]="disabled()"
481
+ (click)="setHex(s.color)"
482
+ ></button>
483
+ }
484
+ </div>
485
+ }
486
+ `,
487
+ }]
488
+ }], ctorParameters: () => [], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "value", required: false }] }, { type: i0.Output, args: ["valueChange"] }], alpha: [{ type: i0.Input, args: [{ isSignal: true, alias: "alpha", required: false }] }], swatches: [{ type: i0.Input, args: [{ isSignal: true, alias: "swatches", required: false }] }], showInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "showInput", required: false }] }], swatchesOnly: [{ type: i0.Input, args: [{ isSignal: true, alias: "swatchesOnly", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], areaLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "areaLabel", required: false }] }], hueLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "hueLabel", required: false }] }], alphaLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "alphaLabel", required: false }] }], swatchesLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "swatchesLabel", required: false }] }], committed: [{ type: i0.Output, args: ["committed"] }], area: [{ type: i0.ViewChild, args: ['area', { isSignal: true }] }] } });
489
+
490
+ const POSITIONS = [
491
+ { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', offsetY: 4 },
492
+ { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', offsetY: -4 },
493
+ ];
494
+ /**
495
+ * Campo de cor: escreve-se o hex (ou rgb()) ou escolhe-se no painel que abre no botão
496
+ * da amostra. Funciona com ngModel e Reactive Forms; o valor é um hex ou null.
497
+ *
498
+ * ```html
499
+ * <mx-form-field>
500
+ * <label mxLabel>Cor da marca</label>
501
+ * <mx-color-picker formControlName="cor" [swatches]="sugestoes" />
502
+ * </mx-form-field>
503
+ * ```
504
+ */
505
+ class MxColorPicker {
506
+ value = model(null, ...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
507
+ alpha = input(false, { ...(ngDevMode ? { debugName: "alpha" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
508
+ swatches = input([], ...(ngDevMode ? [{ debugName: "swatches" }] : /* istanbul ignore next */ []));
509
+ placeholder = input('#RRGGBB', ...(ngDevMode ? [{ debugName: "placeholder" }] : /* istanbul ignore next */ []));
510
+ dialogLabel = input('Escolher cor', ...(ngDevMode ? [{ debugName: "dialogLabel" }] : /* istanbul ignore next */ []));
511
+ disabled = input(false, { ...(ngDevMode ? { debugName: "disabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
512
+ required = input(false, { ...(ngDevMode ? { debugName: "required" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
513
+ invalid = input(false, { ...(ngDevMode ? { debugName: "invalid" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
514
+ size = input('md', ...(ngDevMode ? [{ debugName: "size" }] : /* istanbul ignore next */ []));
515
+ id = input(undefined, ...(ngDevMode ? [{ debugName: "id" }] : /* istanbul ignore next */ []));
516
+ ariaLabel = input(undefined, { ...(ngDevMode ? { debugName: "ariaLabel" } : /* istanbul ignore next */ {}), alias: 'aria-label' });
517
+ field = inject(MxFormField, { optional: true });
518
+ ngControl = inject(NgControl, { self: true, optional: true });
519
+ host = inject(ElementRef).nativeElement;
520
+ toggleButton = viewChild.required('toggleButton');
521
+ panel = viewChild('panel', ...(ngDevMode ? [{ debugName: "panel" }] : /* istanbul ignore next */ []));
522
+ positions = POSITIONS;
523
+ generatedId = mxUniqueId('mx-color');
524
+ controlId = computed(() => this.id() ?? this.generatedId, ...(ngDevMode ? [{ debugName: "controlId" }] : /* istanbul ignore next */ []));
525
+ isOpen = signal(false, ...(ngDevMode ? [{ debugName: "isOpen" }] : /* istanbul ignore next */ []));
526
+ draft = signal(null, ...(ngDevMode ? [{ debugName: "draft" }] : /* istanbul ignore next */ []));
527
+ formDisabled = signal(false, ...(ngDevMode ? [{ debugName: "formDisabled" }] : /* istanbul ignore next */ []));
528
+ isDisabled = computed(() => this.disabled() || this.formDisabled(), ...(ngDevMode ? [{ debugName: "isDisabled" }] : /* istanbul ignore next */ []));
529
+ badFormat = computed(() => !!this.draft() && !mxParseColor(this.draft()), ...(ngDevMode ? [{ debugName: "badFormat" }] : /* istanbul ignore next */ []));
530
+ toggleLabel = computed(() => {
531
+ const v = this.value();
532
+ return v ? `Mudar cor, ${mxColorName(v)}, ${v}` : 'Escolher cor';
533
+ }, ...(ngDevMode ? [{ debugName: "toggleLabel" }] : /* istanbul ignore next */ []));
534
+ onChange = () => { };
535
+ onTouched = () => { };
536
+ constructor() {
537
+ if (this.ngControl)
538
+ this.ngControl.valueAccessor = this;
539
+ }
540
+ open() {
541
+ if (!this.isDisabled())
542
+ this.isOpen.set(true);
543
+ }
544
+ toggle() {
545
+ if (this.isOpen())
546
+ this.close();
547
+ else
548
+ this.open();
549
+ }
550
+ close(restoreFocus = true) {
551
+ if (!this.isOpen())
552
+ return;
553
+ this.isOpen.set(false);
554
+ if (restoreFocus)
555
+ this.toggleButton().nativeElement.focus();
556
+ }
557
+ onAttach() {
558
+ queueMicrotask(() => this.panel()?.nativeElement.querySelector('.mx-color-area-thumb')?.focus());
559
+ }
560
+ onOverlayKey(e) {
561
+ if (e.key === 'Escape') {
562
+ e.preventDefault();
563
+ this.close();
564
+ }
565
+ }
566
+ onOutside(e) {
567
+ if (!this.host.contains(e.target))
568
+ this.close(false);
569
+ }
570
+ setValue(v) {
571
+ this.draft.set(null);
572
+ if (v === this.value())
573
+ return;
574
+ this.value.set(v);
575
+ this.onChange(v);
576
+ }
577
+ onInput(e) {
578
+ const text = e.target.value;
579
+ const v = mxParseColor(text);
580
+ this.draft.set(text && !v ? text : null);
581
+ if (v || !text)
582
+ this.setValue(v);
583
+ if (v)
584
+ this.draft.set(text);
585
+ }
586
+ onBlur() {
587
+ if (!this.badFormat())
588
+ this.draft.set(null);
589
+ this.onTouched();
590
+ }
591
+ // ---- MxFormFieldControl ----
592
+ errorState() {
593
+ if (this.invalid() || this.badFormat())
594
+ return true;
595
+ const c = this.ngControl;
596
+ return !!c && !!c.invalid && !!(c.touched || c.dirty);
597
+ }
598
+ isRequired() {
599
+ return this.required() || !!this.ngControl?.control?.hasValidator?.(Validators.required);
600
+ }
601
+ // ---- ControlValueAccessor ----
602
+ writeValue(value) {
603
+ this.value.set(value ? mxParseColor(value) : null);
604
+ this.draft.set(null);
605
+ }
606
+ registerOnChange(fn) {
607
+ this.onChange = fn;
608
+ }
609
+ registerOnTouched(fn) {
610
+ this.onTouched = fn;
611
+ }
612
+ setDisabledState(isDisabled) {
613
+ this.formDisabled.set(isDisabled);
614
+ }
615
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: MxColorPicker, deps: [], target: i0.ɵɵFactoryTarget.Component });
616
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.2.0", version: "21.2.25", type: MxColorPicker, isStandalone: true, selector: "mx-color-picker", inputs: { value: { classPropertyName: "value", publicName: "value", isSignal: true, isRequired: false, transformFunction: null }, alpha: { classPropertyName: "alpha", publicName: "alpha", isSignal: true, isRequired: false, transformFunction: null }, swatches: { classPropertyName: "swatches", publicName: "swatches", isSignal: true, isRequired: false, transformFunction: null }, placeholder: { classPropertyName: "placeholder", publicName: "placeholder", isSignal: true, isRequired: false, transformFunction: null }, dialogLabel: { classPropertyName: "dialogLabel", publicName: "dialogLabel", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, required: { classPropertyName: "required", publicName: "required", isSignal: true, isRequired: false, transformFunction: null }, invalid: { classPropertyName: "invalid", publicName: "invalid", isSignal: true, isRequired: false, transformFunction: null }, size: { classPropertyName: "size", publicName: "size", isSignal: true, isRequired: false, transformFunction: null }, id: { classPropertyName: "id", publicName: "id", isSignal: true, isRequired: false, transformFunction: null }, ariaLabel: { classPropertyName: "ariaLabel", publicName: "aria-label", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { value: "valueChange" }, host: { properties: { "attr.aria-label": "null" }, classAttribute: "mx-color-picker" }, providers: [{ provide: MX_FORM_FIELD_CONTROL, useExisting: MxColorPicker }], viewQueries: [{ propertyName: "toggleButton", first: true, predicate: ["toggleButton"], descendants: true, isSignal: true }, { propertyName: "panel", first: true, predicate: ["panel"], descendants: true, isSignal: true }], exportAs: ["mxColorPicker"], ngImport: i0, template: `
617
+ <div class="mx-color-picker-field" cdkOverlayOrigin #origin="cdkOverlayOrigin">
618
+ <button
619
+ #toggleButton
620
+ type="button"
621
+ class="mx-color-picker-toggle"
622
+ aria-haspopup="dialog"
623
+ [style.--mx-swatch]="value() ?? 'transparent'"
624
+ [attr.data-empty]="value() ? null : ''"
625
+ [attr.aria-expanded]="isOpen()"
626
+ [attr.aria-label]="toggleLabel()"
627
+ [disabled]="isDisabled()"
628
+ (click)="toggle()"
629
+ ></button>
630
+ <input
631
+ class="mx-input mx-color-picker-input"
632
+ spellcheck="false"
633
+ autocomplete="off"
634
+ [id]="controlId()"
635
+ [placeholder]="placeholder()"
636
+ [value]="draft() ?? value() ?? ''"
637
+ [disabled]="isDisabled()"
638
+ [attr.data-size]="size() === 'md' ? null : size()"
639
+ [attr.aria-invalid]="errorState() ? 'true' : null"
640
+ [attr.aria-required]="isRequired() ? 'true' : null"
641
+ [attr.aria-describedby]="field?.describedBy() ?? null"
642
+ [attr.aria-label]="ariaLabel() ?? null"
643
+ (input)="onInput($event)"
644
+ (blur)="onBlur()"
645
+ (keydown.alt.arrowdown)="$event.preventDefault(); open()"
646
+ />
647
+ </div>
648
+
649
+ <ng-template
650
+ cdkConnectedOverlay
651
+ [cdkConnectedOverlayOrigin]="origin"
652
+ [cdkConnectedOverlayOpen]="isOpen()"
653
+ [cdkConnectedOverlayPositions]="positions"
654
+ (overlayOutsideClick)="onOutside($event)"
655
+ (overlayKeydown)="onOverlayKey($event)"
656
+ (attach)="onAttach()"
657
+ (detach)="close(false)"
658
+ >
659
+ <div
660
+ class="mx-color-picker-panel"
661
+ role="dialog"
662
+ aria-modal="false"
663
+ [attr.aria-label]="dialogLabel()"
664
+ #panel
665
+ >
666
+ <mx-color-panel
667
+ [value]="value() ?? '#1F6F78'"
668
+ (valueChange)="setValue($event)"
669
+ [alpha]="alpha()"
670
+ [swatches]="swatches()"
671
+ [showInput]="false"
672
+ />
673
+ </div>
674
+ </ng-template>
675
+ `, isInline: true, dependencies: [{ kind: "directive", type: CdkOverlayOrigin, selector: "[cdk-overlay-origin], [overlay-origin], [cdkOverlayOrigin]", exportAs: ["cdkOverlayOrigin"] }, { kind: "directive", type: CdkConnectedOverlay, selector: "[cdk-connected-overlay], [connected-overlay], [cdkConnectedOverlay]", inputs: ["cdkConnectedOverlayOrigin", "cdkConnectedOverlayPositions", "cdkConnectedOverlayPositionStrategy", "cdkConnectedOverlayOffsetX", "cdkConnectedOverlayOffsetY", "cdkConnectedOverlayWidth", "cdkConnectedOverlayHeight", "cdkConnectedOverlayMinWidth", "cdkConnectedOverlayMinHeight", "cdkConnectedOverlayBackdropClass", "cdkConnectedOverlayPanelClass", "cdkConnectedOverlayViewportMargin", "cdkConnectedOverlayScrollStrategy", "cdkConnectedOverlayOpen", "cdkConnectedOverlayDisableClose", "cdkConnectedOverlayTransformOriginOn", "cdkConnectedOverlayHasBackdrop", "cdkConnectedOverlayLockPosition", "cdkConnectedOverlayFlexibleDimensions", "cdkConnectedOverlayGrowAfterOpen", "cdkConnectedOverlayPush", "cdkConnectedOverlayDisposeOnNavigation", "cdkConnectedOverlayUsePopover", "cdkConnectedOverlayMatchWidth", "cdkConnectedOverlay"], outputs: ["backdropClick", "positionChange", "attach", "detach", "overlayKeydown", "overlayOutsideClick"], exportAs: ["cdkConnectedOverlay"] }, { kind: "component", type: MxColorPanel, selector: "mx-color-panel", inputs: ["value", "alpha", "swatches", "showInput", "swatchesOnly", "disabled", "areaLabel", "hueLabel", "alphaLabel", "swatchesLabel"], outputs: ["valueChange", "committed"], exportAs: ["mxColorPanel"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
676
+ }
677
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: MxColorPicker, decorators: [{
678
+ type: Component,
679
+ args: [{
680
+ selector: 'mx-color-picker',
681
+ exportAs: 'mxColorPicker',
682
+ imports: [CdkOverlayOrigin, CdkConnectedOverlay, MxColorPanel],
683
+ providers: [{ provide: MX_FORM_FIELD_CONTROL, useExisting: MxColorPicker }],
684
+ changeDetection: ChangeDetectionStrategy.OnPush,
685
+ encapsulation: ViewEncapsulation.None,
686
+ host: { class: 'mx-color-picker', '[attr.aria-label]': 'null' },
687
+ template: `
688
+ <div class="mx-color-picker-field" cdkOverlayOrigin #origin="cdkOverlayOrigin">
689
+ <button
690
+ #toggleButton
691
+ type="button"
692
+ class="mx-color-picker-toggle"
693
+ aria-haspopup="dialog"
694
+ [style.--mx-swatch]="value() ?? 'transparent'"
695
+ [attr.data-empty]="value() ? null : ''"
696
+ [attr.aria-expanded]="isOpen()"
697
+ [attr.aria-label]="toggleLabel()"
698
+ [disabled]="isDisabled()"
699
+ (click)="toggle()"
700
+ ></button>
701
+ <input
702
+ class="mx-input mx-color-picker-input"
703
+ spellcheck="false"
704
+ autocomplete="off"
705
+ [id]="controlId()"
706
+ [placeholder]="placeholder()"
707
+ [value]="draft() ?? value() ?? ''"
708
+ [disabled]="isDisabled()"
709
+ [attr.data-size]="size() === 'md' ? null : size()"
710
+ [attr.aria-invalid]="errorState() ? 'true' : null"
711
+ [attr.aria-required]="isRequired() ? 'true' : null"
712
+ [attr.aria-describedby]="field?.describedBy() ?? null"
713
+ [attr.aria-label]="ariaLabel() ?? null"
714
+ (input)="onInput($event)"
715
+ (blur)="onBlur()"
716
+ (keydown.alt.arrowdown)="$event.preventDefault(); open()"
717
+ />
718
+ </div>
719
+
720
+ <ng-template
721
+ cdkConnectedOverlay
722
+ [cdkConnectedOverlayOrigin]="origin"
723
+ [cdkConnectedOverlayOpen]="isOpen()"
724
+ [cdkConnectedOverlayPositions]="positions"
725
+ (overlayOutsideClick)="onOutside($event)"
726
+ (overlayKeydown)="onOverlayKey($event)"
727
+ (attach)="onAttach()"
728
+ (detach)="close(false)"
729
+ >
730
+ <div
731
+ class="mx-color-picker-panel"
732
+ role="dialog"
733
+ aria-modal="false"
734
+ [attr.aria-label]="dialogLabel()"
735
+ #panel
736
+ >
737
+ <mx-color-panel
738
+ [value]="value() ?? '#1F6F78'"
739
+ (valueChange)="setValue($event)"
740
+ [alpha]="alpha()"
741
+ [swatches]="swatches()"
742
+ [showInput]="false"
743
+ />
744
+ </div>
745
+ </ng-template>
746
+ `,
747
+ }]
748
+ }], ctorParameters: () => [], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "value", required: false }] }, { type: i0.Output, args: ["valueChange"] }], alpha: [{ type: i0.Input, args: [{ isSignal: true, alias: "alpha", required: false }] }], swatches: [{ type: i0.Input, args: [{ isSignal: true, alias: "swatches", required: false }] }], placeholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "placeholder", required: false }] }], dialogLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "dialogLabel", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], required: [{ type: i0.Input, args: [{ isSignal: true, alias: "required", required: false }] }], invalid: [{ type: i0.Input, args: [{ isSignal: true, alias: "invalid", required: false }] }], size: [{ type: i0.Input, args: [{ isSignal: true, alias: "size", required: false }] }], id: [{ type: i0.Input, args: [{ isSignal: true, alias: "id", required: false }] }], ariaLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "aria-label", required: false }] }], toggleButton: [{ type: i0.ViewChild, args: ['toggleButton', { isSignal: true }] }], panel: [{ type: i0.ViewChild, args: ['panel', { isSignal: true }] }] } });
749
+
750
+ /**
751
+ * Generated bundle index. Do not edit.
752
+ */
753
+
754
+ export { MxColorPanel, MxColorPicker, mxColorName, mxContrast, mxHexToHsva, mxHexToRgba, mxHsvaToHex, mxParseColor };
755
+ //# sourceMappingURL=muxima-ui-core-color-picker.mjs.map