ui-optago 1.2.0 → 1.2.1

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.
Files changed (5) hide show
  1. package/README.md +178 -178
  2. package/index.html +1474 -1414
  3. package/package.json +30 -30
  4. package/ui-optago.css +99 -18
  5. package/ui-optago.js +786 -708
package/ui-optago.js CHANGED
@@ -1,708 +1,786 @@
1
- /* ============================================================================
2
- UI ÓPTAGO: Design System v1.2.0 (JavaScript)
3
- Sem dependências de build. Carregue no <head> SEM defer para evitar
4
- flash de tema errado (FOUC):
5
-
6
- <link rel="stylesheet" href="ui-optago.css">
7
- <script src="ui-optago.js"></script>
8
-
9
- O script injeta automaticamente as fontes (Google Fonts) e os ícones
10
- Phosphor, aplica o tema salvo e liga todos os comportamentos via
11
- atributos data-op-*:
12
-
13
- data-op-theme-toggle → alterna tema claro/escuro
14
- data-op-sidebar-toggle → colapsa/expande a sidebar (desktop)
15
- data-op-sidebar-mobile → abre/fecha a sidebar (mobile drawer)
16
- data-op-modal-open="#id" → abre o modal
17
- data-op-modal-close → fecha o modal (dentro dele)
18
- data-op-tab="nome" → botão de aba (com data-op-tab-group no pai)
19
- data-op-tab-panel="nome" → painel correspondente
20
- data-op-dropdown-toggle → abre/fecha o .op-dropdown pai
21
- data-op-dismiss → remove o elemento pai .op-alert
22
- data-op-copy="#seletor" → copia o HTML do elemento alvo
23
- data-op-code="#seletor" → mostra/esconde o código-fonte do alvo
24
- data-op-loading-form → no <form>: mostra a tela de carregamento
25
- sozinho ao submeter (mensagem opcional em
26
- data-op-loading-message="Enviando...")
27
- data-op-reveal / data-op-reveal-toggle → mostrar/ocultar senha (envolva o
28
- input com data-op-reveal e ponha o botão
29
- com data-op-reveal-toggle dentro)
30
- data-op-toast='[{"type":"success","message":"Oi"}]' → dispara toasts a
31
- partir de flash messages do servidor,
32
- sem precisar de <script> inline (CSP-safe)
33
-
34
- Tema compartilhado entre subdomínios: adicione data-op-theme-domain no
35
- próprio <script src="ui-optago.js"> pra o tema virar cookie em vez de só
36
- localStorage, e todo app sob esse domínio (ex.: app1.seusite.com,
37
- app2.seusite.com) passa a enxergar a mesma escolha de tema:
38
-
39
- <script src="ui-optago.js" data-op-theme-domain=".seusite.com"></script>
40
-
41
- Sem esse atributo, o tema continua só em localStorage (por app, como antes).
42
-
43
- API global: OptagoUI.toast(msg, tipo, ms) · OptagoUI.openModal(sel)
44
- OptagoUI.closeModal(sel) · OptagoUI.setTheme('dark'|'light')
45
- OptagoUI.showLoading(msg) · OptagoUI.hideLoading()
46
- ============================================================================ */
47
- (function () {
48
- 'use strict';
49
-
50
- var OptagoUI = {};
51
-
52
- // Fonte única da versão exibida no badge do header e no rodapé
53
- // (elementos com o atributo data-op-version). Atualize só aqui.
54
- var VERSION = '1.2.0';
55
- OptagoUI.version = VERSION;
56
-
57
- /* --------------------------------------------------------------------------
58
- 1. TEMA: aplicado imediatamente (antes do primeiro paint)
59
- -------------------------------------------------------------------------- */
60
- var THEME_KEY = 'op-theme';
61
-
62
- // document.currentScript só é confiável em scripts síncronos (sem defer/
63
- // async), que é exatamente como esta lib precisa ser carregada mesmo.
64
- var THEME_DOMAIN = (function () {
65
- var s = document.currentScript;
66
- return (s && s.getAttribute('data-op-theme-domain')) || null;
67
- })();
68
-
69
- function readCookie(name) {
70
- var m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
71
- return m ? decodeURIComponent(m[1]) : null;
72
- }
73
-
74
- function writeCookie(name, value) {
75
- var attrs = 'path=/; max-age=31536000; SameSite=Lax; domain=' + THEME_DOMAIN;
76
- if (window.location.protocol === 'https:') attrs += '; Secure';
77
- document.cookie = name + '=' + encodeURIComponent(value) + '; ' + attrs;
78
- }
79
-
80
- function currentTheme() {
81
- var saved = (THEME_DOMAIN && readCookie(THEME_KEY)) || localStorage.getItem(THEME_KEY);
82
- if (saved === 'light' || saved === 'dark') return saved;
83
- return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
84
- }
85
-
86
- OptagoUI.setTheme = function (theme) {
87
- document.documentElement.classList.toggle('light', theme === 'light');
88
- localStorage.setItem(THEME_KEY, theme);
89
- if (THEME_DOMAIN) writeCookie(THEME_KEY, theme);
90
- document.querySelectorAll('[data-op-theme-toggle]').forEach(function (btn) {
91
- var moon = btn.querySelector('.op-icon-moon');
92
- var sun = btn.querySelector('.op-icon-sun');
93
- if (moon) moon.style.display = theme === 'dark' ? 'none' : '';
94
- if (sun) sun.style.display = theme === 'dark' ? '' : 'none';
95
- });
96
- };
97
-
98
- OptagoUI.toggleTheme = function () {
99
- OptagoUI.setTheme(document.documentElement.classList.contains('light') ? 'dark' : 'light');
100
- };
101
-
102
- // Aplica já, sem esperar o DOM (evita FOUC)
103
- document.documentElement.classList.toggle('light', currentTheme() === 'light');
104
-
105
- /* --------------------------------------------------------------------------
106
- 2. INJEÇÃO DE DEPENDÊNCIAS (Google Fonts + Phosphor Icons)
107
- -------------------------------------------------------------------------- */
108
- function ensureAssets() {
109
- if (!document.getElementById('op-fonts')) {
110
- var pre1 = document.createElement('link');
111
- pre1.rel = 'preconnect'; pre1.href = 'https://fonts.googleapis.com';
112
- var pre2 = document.createElement('link');
113
- pre2.rel = 'preconnect'; pre2.href = 'https://fonts.gstatic.com'; pre2.crossOrigin = '';
114
- var fonts = document.createElement('link');
115
- fonts.id = 'op-fonts';
116
- fonts.rel = 'stylesheet';
117
- fonts.href = 'https://fonts.googleapis.com/css2?family=Chakra+Petch:wght@500;600;700&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap';
118
- document.head.append(pre1, pre2, fonts);
119
- }
120
- if (!document.getElementById('op-icons') && !window.PhosphorIcons) {
121
- var icons = document.createElement('script');
122
- icons.id = 'op-icons';
123
- icons.src = 'https://unpkg.com/@phosphor-icons/web';
124
- document.head.appendChild(icons);
125
- }
126
- }
127
- ensureAssets();
128
-
129
- /* --------------------------------------------------------------------------
130
- 3. SIDEBAR (colapsar no desktop / drawer no mobile)
131
- -------------------------------------------------------------------------- */
132
- var SIDEBAR_KEY = 'op-sidebar-collapsed';
133
-
134
- function getSidebar() { return document.querySelector('.op-sidebar'); }
135
- function getOverlay() {
136
- var ov = document.querySelector('.op-overlay');
137
- if (!ov) {
138
- ov = document.createElement('div');
139
- ov.className = 'op-overlay';
140
- ov.addEventListener('click', OptagoUI.closeSidebarMobile);
141
- document.body.appendChild(ov);
142
- }
143
- return ov;
144
- }
145
-
146
- OptagoUI.toggleSidebar = function () {
147
- var sb = getSidebar();
148
- if (!sb) return;
149
- if (window.innerWidth < 1024) { OptagoUI.toggleSidebarMobile(); return; }
150
- sb.classList.toggle('is-collapsed');
151
- localStorage.setItem(SIDEBAR_KEY, sb.classList.contains('is-collapsed') ? '1' : '0');
152
- };
153
-
154
- OptagoUI.toggleSidebarMobile = function () {
155
- var sb = getSidebar();
156
- if (!sb) return;
157
- var open = sb.classList.toggle('is-open');
158
- getOverlay().classList.toggle('is-open', open);
159
- };
160
-
161
- OptagoUI.closeSidebarMobile = function () {
162
- var sb = getSidebar();
163
- if (sb) sb.classList.remove('is-open');
164
- var ov = document.querySelector('.op-overlay');
165
- if (ov) ov.classList.remove('is-open');
166
- };
167
-
168
- /* --------------------------------------------------------------------------
169
- 4. TOASTS: OptagoUI.toast('Mensagem', 'success'|'error'|'warning'|'info')
170
- -------------------------------------------------------------------------- */
171
- var TOAST_ICONS = {
172
- success: 'ph-check-circle',
173
- error: 'ph-x-circle',
174
- danger: 'ph-x-circle',
175
- warning: 'ph-warning',
176
- info: 'ph-info'
177
- };
178
-
179
- OptagoUI.toast = function (message, type, duration) {
180
- type = type || 'info';
181
- if (type === 'error') type = 'danger';
182
- duration = duration || 4000;
183
-
184
- var container = document.querySelector('.op-toast-container');
185
- if (!container) {
186
- container = document.createElement('div');
187
- container.className = 'op-toast-container';
188
- document.body.appendChild(container);
189
- }
190
-
191
- var toast = document.createElement('div');
192
- toast.className = 'op-toast op-toast-' + type;
193
- toast.setAttribute('role', 'status');
194
- toast.innerHTML =
195
- '<div class="op-toast-icon"><i class="ph ' + (TOAST_ICONS[type] || TOAST_ICONS.info) + '"></i></div>' +
196
- '<span></span>' +
197
- '<button class="op-toast-close" aria-label="Fechar"><i class="ph ph-x"></i></button>' +
198
- '<div class="op-toast-progress"><div class="op-toast-progress-bar"></div></div>';
199
- toast.querySelector('span').textContent = message;
200
- container.appendChild(toast);
201
-
202
- var bar = toast.querySelector('.op-toast-progress-bar');
203
- var removed = false;
204
- var timer = null;
205
- var remaining = duration;
206
- var startedAt = 0;
207
-
208
- var dismiss = function () {
209
- if (removed) return;
210
- removed = true;
211
- toast.classList.remove('is-visible');
212
- setTimeout(function () { toast.remove(); }, 320);
213
- };
214
-
215
- // Anima a barra de largura atual até 0 ao longo de `ms`; usar
216
- // transition (não @keyframes) permite congelar no valor exato em pause().
217
- var run = function (ms) {
218
- startedAt = Date.now();
219
- timer = setTimeout(dismiss, ms);
220
- requestAnimationFrame(function () {
221
- bar.style.transitionDuration = ms + 'ms';
222
- bar.style.width = '0%';
223
- });
224
- };
225
-
226
- var pause = function () {
227
- if (removed || !timer) return;
228
- clearTimeout(timer);
229
- timer = null;
230
- remaining -= Date.now() - startedAt;
231
- // Congela a barra no ponto exato em px (transition-duration 0 = sem salto).
232
- bar.style.width = getComputedStyle(bar).width;
233
- bar.style.transitionDuration = '0ms';
234
- };
235
-
236
- var resume = function () {
237
- if (removed || timer || remaining <= 0) return;
238
- run(remaining);
239
- };
240
-
241
- toast.addEventListener('mouseenter', pause);
242
- toast.addEventListener('mouseleave', resume);
243
- toast.addEventListener('focusin', pause);
244
- toast.addEventListener('focusout', resume);
245
- toast.querySelector('.op-toast-close').addEventListener('click', dismiss);
246
-
247
- requestAnimationFrame(function () {
248
- requestAnimationFrame(function () { toast.classList.add('is-visible'); });
249
- });
250
-
251
- run(duration);
252
-
253
- return toast;
254
- };
255
-
256
- /* --------------------------------------------------------------------------
257
- 5. MODAIS
258
- -------------------------------------------------------------------------- */
259
- OptagoUI.openModal = function (selector) {
260
- var modal = typeof selector === 'string' ? document.querySelector(selector) : selector;
261
- if (!modal) return;
262
- modal.classList.remove('is-closing');
263
- modal.classList.add('is-open');
264
- };
265
-
266
- OptagoUI.closeModal = function (selector) {
267
- var modal = typeof selector === 'string' ? document.querySelector(selector) : selector;
268
- if (!modal || !modal.classList.contains('is-open')) return;
269
- modal.classList.add('is-closing');
270
- setTimeout(function () {
271
- modal.classList.remove('is-open', 'is-closing');
272
- }, 200);
273
- };
274
-
275
- /* --------------------------------------------------------------------------
276
- 5b. TABULATOR: tabela avançada com tema Óptago
277
- Uso: OptagoUI.tabulator('#minhaTabela', { data: [...], columns: [...] })
278
- Carrega a biblioteca (CDN) sob demanda; o CSS base do Tabulator é
279
- inserido ANTES do ui-optago.css para que o tema personalizado
280
- (.op-tabulator) vença na cascata.
281
- -------------------------------------------------------------------------- */
282
- var TABULATOR_JS = 'https://unpkg.com/tabulator-tables@6.3/dist/js/tabulator.min.js';
283
- var TABULATOR_CSS = 'https://unpkg.com/tabulator-tables@6.3/dist/css/tabulator.min.css';
284
-
285
- OptagoUI.tabulator = function (selector, options) {
286
- return new Promise(function (resolve, reject) {
287
- function build() {
288
- var el = typeof selector === 'string' ? document.querySelector(selector) : selector;
289
- if (!el) { reject(new Error('Tabulator: elemento não encontrado: ' + selector)); return; }
290
- el.classList.add('op-tabulator');
291
- resolve(new window.Tabulator(el, options || {}));
292
- }
293
-
294
- if (window.Tabulator) { build(); return; }
295
-
296
- if (!document.getElementById('op-tabulator-css')) {
297
- var css = document.createElement('link');
298
- css.id = 'op-tabulator-css';
299
- css.rel = 'stylesheet';
300
- css.href = TABULATOR_CSS;
301
- var own = document.querySelector('link[href*="ui-optago.css"]');
302
- if (own && own.parentNode) {
303
- own.parentNode.insertBefore(css, own);
304
- } else {
305
- document.head.prepend(css);
306
- }
307
- }
308
-
309
- var script = document.getElementById('op-tabulator-js');
310
- if (!script) {
311
- script = document.createElement('script');
312
- script.id = 'op-tabulator-js';
313
- script.src = TABULATOR_JS;
314
- document.head.appendChild(script);
315
- }
316
- script.addEventListener('load', build);
317
- script.addEventListener('error', function () {
318
- reject(new Error('Tabulator: falha ao carregar a biblioteca via CDN.'));
319
- });
320
- });
321
- };
322
-
323
- /* --------------------------------------------------------------------------
324
- 5c. TELA DE CARREGAMENTO: overlay em tela cheia
325
- Uso: OptagoUI.showLoading('Salvando...') ... OptagoUI.hideLoading()
326
- ou data-op-loading-form no <form> para acionar sozinho no submit.
327
- -------------------------------------------------------------------------- */
328
- var LOADING_ID = 'opLoadingOverlay';
329
-
330
- function getLoadingOverlay() {
331
- var ov = document.getElementById(LOADING_ID);
332
- if (!ov) {
333
- ov = document.createElement('div');
334
- ov.id = LOADING_ID;
335
- ov.className = 'op-loading-overlay';
336
- ov.setAttribute('role', 'alert');
337
- ov.setAttribute('aria-live', 'assertive');
338
- ov.innerHTML =
339
- '<span class="op-spinner"></span>' +
340
- '<span class="op-loading-message"></span>';
341
- document.body.appendChild(ov);
342
- }
343
- return ov;
344
- }
345
-
346
- OptagoUI.showLoading = function (message) {
347
- var ov = getLoadingOverlay();
348
- ov.querySelector('.op-loading-message').textContent = message || 'Carregando...';
349
- ov.classList.add('is-open');
350
- requestAnimationFrame(function () {
351
- requestAnimationFrame(function () { ov.classList.add('is-visible'); });
352
- });
353
- };
354
-
355
- OptagoUI.hideLoading = function () {
356
- var ov = document.getElementById(LOADING_ID);
357
- if (!ov) return;
358
- ov.classList.remove('is-visible');
359
- setTimeout(function () { ov.classList.remove('is-open'); }, 250);
360
- };
361
-
362
- // Ao voltar pelo botão "Voltar" do navegador, a página pode ser restaurada
363
- // do bfcache exatamente como estava ao sair (overlay de carregamento ainda
364
- // visível, já que o clique/submit anterior nunca chegou a escondê-lo).
365
- // pageshow com event.persisted=true é o sinal de que veio do bfcache.
366
- window.addEventListener('pageshow', function (e) {
367
- if (e.persisted) OptagoUI.hideLoading();
368
- });
369
-
370
- /* --------------------------------------------------------------------------
371
- 6. HELPERS DO SHOWCASE: copiar HTML / ver código
372
- -------------------------------------------------------------------------- */
373
- function dedentHTML(el) {
374
- var html = el.innerHTML.replace(/^\n+|\s+$/g, '');
375
- var lines = html.split('\n');
376
- var indent = Infinity;
377
- lines.forEach(function (line) {
378
- if (!line.trim()) return;
379
- var m = line.match(/^\s*/);
380
- indent = Math.min(indent, m[0].length);
381
- });
382
- if (!isFinite(indent)) indent = 0;
383
- return lines.map(function (line) { return line.slice(indent); }).join('\n');
384
- }
385
-
386
- OptagoUI.copyHTML = function (targetSelector, feedbackBtn) {
387
- var target = document.querySelector(targetSelector);
388
- if (!target) return;
389
- var html = dedentHTML(target);
390
-
391
- var done = function () {
392
- if (feedbackBtn) {
393
- var original = feedbackBtn.innerHTML;
394
- feedbackBtn.innerHTML = '<i class="ph ph-check"></i> Copiado!';
395
- setTimeout(function () { feedbackBtn.innerHTML = original; }, 2000);
396
- }
397
- };
398
-
399
- if (navigator.clipboard && navigator.clipboard.writeText) {
400
- navigator.clipboard.writeText(html).then(done);
401
- } else {
402
- var ta = document.createElement('textarea');
403
- ta.value = html;
404
- ta.style.position = 'fixed';
405
- ta.style.left = '-9999px';
406
- document.body.appendChild(ta);
407
- ta.select();
408
- document.execCommand('copy');
409
- ta.remove();
410
- done();
411
- }
412
- };
413
-
414
- OptagoUI.toggleCode = function (targetSelector, btn) {
415
- var target = document.querySelector(targetSelector);
416
- if (!target) return;
417
- var demo = btn.closest('.op-demo') || target.parentElement;
418
- var pre = demo.querySelector('.op-demo-code');
419
- if (!pre) {
420
- pre = document.createElement('pre');
421
- pre.className = 'op-demo-code';
422
- demo.appendChild(pre);
423
- }
424
- if (!pre.dataset.filled) {
425
- pre.textContent = dedentHTML(target);
426
- pre.dataset.filled = '1';
427
- }
428
- pre.classList.toggle('is-visible');
429
- };
430
-
431
- /* --------------------------------------------------------------------------
432
- 7. BINDING GLOBAL via data-attributes (event delegation)
433
- -------------------------------------------------------------------------- */
434
- document.addEventListener('click', function (e) {
435
- var t;
436
-
437
- // Tema
438
- if (e.target.closest('[data-op-theme-toggle]')) { OptagoUI.toggleTheme(); return; }
439
-
440
- // Sidebar
441
- if (e.target.closest('[data-op-sidebar-toggle]')) { OptagoUI.toggleSidebar(); return; }
442
- if (e.target.closest('[data-op-sidebar-mobile]')) { OptagoUI.toggleSidebarMobile(); return; }
443
-
444
- // Fecha drawer mobile ao clicar em link da sidebar
445
- if (e.target.closest('.op-sidebar .op-nav-item') && window.innerWidth < 1024) {
446
- OptagoUI.closeSidebarMobile();
447
- }
448
-
449
- // Modal
450
- t = e.target.closest('[data-op-modal-open]');
451
- if (t) { OptagoUI.openModal(t.getAttribute('data-op-modal-open')); return; }
452
- if (e.target.closest('[data-op-modal-close]')) {
453
- OptagoUI.closeModal(e.target.closest('.op-modal'));
454
- return;
455
- }
456
- if (e.target.classList && e.target.classList.contains('op-modal')) {
457
- OptagoUI.closeModal(e.target); // clique no backdrop
458
- return;
459
- }
460
-
461
- // Tabs
462
- t = e.target.closest('[data-op-tab]');
463
- if (t) {
464
- var name = t.getAttribute('data-op-tab');
465
- var group = t.closest('[data-op-tab-group]');
466
- var scope = group ? '[data-op-tab-group="' + group.getAttribute('data-op-tab-group') + '"]' : '';
467
- document.querySelectorAll(scope + ' [data-op-tab]').forEach(function (tab) {
468
- tab.classList.toggle('is-active', tab === t);
469
- });
470
- document.querySelectorAll(scope + ' [data-op-tab-panel]').forEach(function (panel) {
471
- panel.classList.toggle('is-active', panel.getAttribute('data-op-tab-panel') === name);
472
- });
473
- return;
474
- }
475
-
476
- // Dropdown
477
- t = e.target.closest('[data-op-dropdown-toggle]');
478
- if (t) {
479
- var dd = t.closest('.op-dropdown');
480
- var wasOpen = dd.classList.contains('is-open');
481
- document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
482
- if (!wasOpen) dd.classList.add('is-open');
483
- return;
484
- }
485
- // Fecha dropdowns em clique fora
486
- if (!e.target.closest('.op-dropdown')) {
487
- document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
488
- }
489
-
490
- // Alert dismiss
491
- t = e.target.closest('[data-op-dismiss]');
492
- if (t) {
493
- var box = t.closest('.op-alert') || t.parentElement;
494
- box.style.transition = 'opacity .25s, transform .25s';
495
- box.style.opacity = '0';
496
- box.style.transform = 'translateX(8px)';
497
- setTimeout(function () { box.remove(); }, 250);
498
- return;
499
- }
500
-
501
- // Copiar HTML
502
- t = e.target.closest('[data-op-copy]');
503
- if (t) { OptagoUI.copyHTML(t.getAttribute('data-op-copy'), t); return; }
504
-
505
- // Ver código
506
- t = e.target.closest('[data-op-code]');
507
- if (t) { OptagoUI.toggleCode(t.getAttribute('data-op-code'), t); return; }
508
-
509
- // Mostrar/ocultar senha: [data-op-reveal] envolvendo o input,
510
- // com um <button data-op-reveal-toggle> dentro.
511
- t = e.target.closest('[data-op-reveal-toggle]');
512
- if (t) {
513
- var wrap = t.closest('[data-op-reveal]');
514
- var input = wrap ? wrap.querySelector('input') : null;
515
- if (input) {
516
- var show = input.type === 'password';
517
- input.type = show ? 'text' : 'password';
518
- var icon = t.querySelector('i');
519
- if (icon) icon.className = show ? 'ph ph-eye-slash' : 'ph ph-eye';
520
- t.setAttribute('aria-label', show ? 'Ocultar senha' : 'Mostrar senha');
521
- }
522
- return;
523
- }
524
-
525
- // Combobox: clique numa opção seleciona; clique fora fecha.
526
- t = e.target.closest('[data-op-combobox-option]');
527
- if (t && !t.hasAttribute('hidden')) { selectComboboxOption(t); return; }
528
- if (!e.target.closest('[data-op-combobox]')) {
529
- document.querySelectorAll('.op-combobox.is-open').forEach(closeCombobox);
530
- }
531
- });
532
-
533
- /* --------------------------------------------------------------------------
534
- 7b. COMBOBOX: input com filtro de opções (autocomplete)
535
- -------------------------------------------------------------------------- */
536
- function comboboxOptions(box) {
537
- var menu = box.querySelector('[data-op-combobox-menu]');
538
- return menu ? Array.prototype.slice.call(menu.querySelectorAll('[data-op-combobox-option]')) : [];
539
- }
540
-
541
- function visibleComboboxOptions(box) {
542
- return comboboxOptions(box).filter(function (o) { return !o.hasAttribute('hidden'); });
543
- }
544
-
545
- function openCombobox(box) {
546
- box.classList.add('is-open');
547
- }
548
-
549
- function closeCombobox(box) {
550
- box.classList.remove('is-open');
551
- comboboxOptions(box).forEach(function (o) { o.classList.remove('is-active'); });
552
- }
553
-
554
- function selectComboboxOption(option) {
555
- var box = option.closest('[data-op-combobox]');
556
- var input = box.querySelector('[data-op-combobox-input]');
557
- comboboxOptions(box).forEach(function (o) { o.classList.remove('is-selected'); });
558
- option.classList.add('is-selected');
559
- if (input) {
560
- input.value = option.textContent.trim();
561
- box.dataset.value = option.getAttribute('data-value') || '';
562
- input.dispatchEvent(new Event('change', { bubbles: true }));
563
- }
564
- closeCombobox(box);
565
- }
566
-
567
- function filterCombobox(box) {
568
- var input = box.querySelector('[data-op-combobox-input]');
569
- var empty = box.querySelector('.op-combobox-empty');
570
- var query = (input.value || '').trim().toLowerCase();
571
- var anyVisible = false;
572
- comboboxOptions(box).forEach(function (o) {
573
- var match = o.textContent.toLowerCase().indexOf(query) !== -1;
574
- o.toggleAttribute('hidden', !match);
575
- o.classList.remove('is-active');
576
- if (match) anyVisible = true;
577
- });
578
- if (empty) empty.hidden = anyVisible;
579
- }
580
-
581
- document.addEventListener('input', function (e) {
582
- var input = e.target.closest('[data-op-combobox-input]');
583
- if (!input) return;
584
- var box = input.closest('[data-op-combobox]');
585
- filterCombobox(box);
586
- openCombobox(box);
587
- });
588
-
589
- document.addEventListener('focusin', function (e) {
590
- var input = e.target.closest('[data-op-combobox-input]');
591
- if (!input) return;
592
- openCombobox(input.closest('[data-op-combobox]'));
593
- });
594
-
595
- // Tooltip da sidebar colapsada: o overflow-y da nav cortaria um tooltip
596
- // com position:absolute, então ele usa position:fixed e o top/right é
597
- // calculado aqui a cada hover.
598
- document.addEventListener('mouseover', function (e) {
599
- var item = e.target.closest('.op-sidebar.is-collapsed .op-nav-item');
600
- if (!item) return;
601
- var tip = item.querySelector('.op-nav-tooltip');
602
- if (!tip) return;
603
- var r = item.getBoundingClientRect();
604
- tip.style.top = (r.top + r.height / 2) + 'px';
605
- tip.style.right = (window.innerWidth - r.left + 14) + 'px';
606
- tip.style.left = 'auto';
607
- });
608
-
609
- // Formulário com data-op-loading-form: mostra a tela de carregamento
610
- // sozinho ao submeter (mensagem em data-op-loading-message, se houver).
611
- document.addEventListener('submit', function (e) {
612
- var form = e.target.closest('[data-op-loading-form]');
613
- if (!form) return;
614
- OptagoUI.showLoading(form.getAttribute('data-op-loading-message'));
615
- });
616
-
617
- // ESC fecha modais, dropdowns e comboboxes
618
- document.addEventListener('keydown', function (e) {
619
- if (e.key === 'Escape') {
620
- document.querySelectorAll('.op-modal.is-open').forEach(function (m) { OptagoUI.closeModal(m); });
621
- document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
622
- document.querySelectorAll('.op-combobox.is-open').forEach(closeCombobox);
623
- OptagoUI.closeSidebarMobile();
624
- return;
625
- }
626
-
627
- // Navegação por teclado dentro de um combobox aberto
628
- var comboInput = e.target.closest('[data-op-combobox-input]');
629
- if (!comboInput) return;
630
- var box = comboInput.closest('[data-op-combobox]');
631
- if (!box.classList.contains('is-open')) return;
632
-
633
- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
634
- e.preventDefault();
635
- var opts = visibleComboboxOptions(box);
636
- if (!opts.length) return;
637
- var current = opts.findIndex(function (o) { return o.classList.contains('is-active'); });
638
- var next = e.key === 'ArrowDown' ? current + 1 : current - 1;
639
- if (next < 0) next = opts.length - 1;
640
- if (next >= opts.length) next = 0;
641
- opts.forEach(function (o) { o.classList.remove('is-active'); });
642
- opts[next].classList.add('is-active');
643
- opts[next].scrollIntoView({ block: 'nearest' });
644
- } else if (e.key === 'Enter') {
645
- var active = visibleComboboxOptions(box).filter(function (o) { return o.classList.contains('is-active'); })[0];
646
- if (active) { e.preventDefault(); selectComboboxOption(active); }
647
- }
648
- });
649
-
650
- /* --------------------------------------------------------------------------
651
- 8. INICIALIZAÇÃO no DOM pronto
652
- -------------------------------------------------------------------------- */
653
- function init() {
654
- // Versão exibida no badge do header e no rodapé
655
- document.querySelectorAll('[data-op-version]').forEach(function (el) {
656
- el.textContent = 'v' + VERSION;
657
- });
658
-
659
- // Toasts vindos do servidor (flash messages), sem precisar de <script>
660
- // inline: importante para funcionar com Content-Security-Policy estrito.
661
- // Uso: <div hidden data-op-toast='[{"type":"success","message":"Oi!"}]'></div>
662
- document.querySelectorAll('[data-op-toast]').forEach(function (el) {
663
- try {
664
- var items = JSON.parse(el.getAttribute('data-op-toast'));
665
- (Array.isArray(items) ? items : [items]).forEach(function (t) {
666
- OptagoUI.toast(t.message, t.type, t.duration);
667
- });
668
- } catch (e) { /* atributo malformado: ignora silenciosamente */ }
669
- });
670
-
671
- // Sidebar (desktop): fechada por padrão, mas respeita a escolha do
672
- // usuário salva no localStorage assim que ele abrir/fechar uma vez.
673
- var sb = getSidebar();
674
- if (sb && window.innerWidth >= 1024 && localStorage.getItem(SIDEBAR_KEY) !== '0') {
675
- sb.classList.add('is-collapsed');
676
- }
677
-
678
- // Ajusta ícones do botão de tema
679
- OptagoUI.setTheme(document.documentElement.classList.contains('light') ? 'light' : 'dark');
680
-
681
- // Scrollspy simples: marca .op-nav-item ativo conforme a seção visível
682
- var main = document.querySelector('.op-main');
683
- var links = Array.prototype.slice.call(document.querySelectorAll('.op-sidebar .op-nav-item[href^="#"]'));
684
- if (main && links.length) {
685
- var sections = links
686
- .map(function (l) { return document.querySelector(l.getAttribute('href')); })
687
- .filter(Boolean);
688
- var onScroll = function () {
689
- var top = main.scrollTop + 120;
690
- var active = sections[0];
691
- sections.forEach(function (s) { if (s.offsetTop <= top) active = s; });
692
- links.forEach(function (l) {
693
- l.classList.toggle('is-active', active && l.getAttribute('href') === '#' + active.id);
694
- });
695
- };
696
- main.addEventListener('scroll', onScroll, { passive: true });
697
- onScroll();
698
- }
699
- }
700
-
701
- if (document.readyState === 'loading') {
702
- document.addEventListener('DOMContentLoaded', init);
703
- } else {
704
- init();
705
- }
706
-
707
- window.OptagoUI = OptagoUI;
708
- })();
1
+ /* ============================================================================
2
+ UI ÓPTAGO: Design System v1.2.1 (JavaScript)
3
+ Sem dependências de build. Carregue no <head> SEM defer para evitar
4
+ flash de tema errado (FOUC):
5
+
6
+ <link rel="stylesheet" href="ui-optago.css">
7
+ <script src="ui-optago.js"></script>
8
+
9
+ O script injeta automaticamente as fontes (Google Fonts) e os ícones
10
+ Phosphor, aplica o tema salvo e liga todos os comportamentos via
11
+ atributos data-op-*:
12
+
13
+ data-op-theme-toggle → alterna tema claro/escuro
14
+ data-op-sidebar-toggle → colapsa/expande a sidebar (desktop)
15
+ data-op-sidebar-mobile → abre/fecha a sidebar (mobile drawer)
16
+ data-op-modal-open="#id" → abre o modal
17
+ data-op-modal-close → fecha o modal (dentro dele)
18
+ data-op-tab="nome" → botão de aba (com data-op-tab-group no pai)
19
+ data-op-tab-panel="nome" → painel correspondente
20
+ data-op-dropdown-toggle → abre/fecha o .op-dropdown pai
21
+ data-op-dismiss → remove o elemento pai .op-alert
22
+ data-op-copy="#seletor" → copia o HTML do elemento alvo
23
+ data-op-code="#seletor" → mostra/esconde o código-fonte do alvo
24
+ data-op-loading-form → no <form>: mostra a tela de carregamento
25
+ sozinho ao submeter (mensagem opcional em
26
+ data-op-loading-message="Enviando...")
27
+ data-op-reveal / data-op-reveal-toggle → mostrar/ocultar senha (envolva o
28
+ input com data-op-reveal e ponha o botão
29
+ com data-op-reveal-toggle dentro)
30
+ data-op-toast='[{"type":"success","message":"Oi"}]' → dispara toasts a
31
+ partir de flash messages do servidor,
32
+ sem precisar de <script> inline (CSP-safe)
33
+
34
+ Tema compartilhado entre subdomínios: adicione data-op-theme-domain no
35
+ próprio <script src="ui-optago.js"> pra o tema virar cookie em vez de só
36
+ localStorage, e todo app sob esse domínio (ex.: app1.seusite.com,
37
+ app2.seusite.com) passa a enxergar a mesma escolha de tema:
38
+
39
+ <script src="ui-optago.js" data-op-theme-domain=".seusite.com"></script>
40
+
41
+ Sem esse atributo, o tema continua só em localStorage (por app, como antes).
42
+
43
+ API global: OptagoUI.toast(msg, tipo, ms) · OptagoUI.openModal(sel)
44
+ OptagoUI.closeModal(sel) · OptagoUI.setTheme('dark'|'light')
45
+ OptagoUI.showLoading(msg) · OptagoUI.hideLoading()
46
+ ============================================================================ */
47
+ (function () {
48
+ 'use strict';
49
+
50
+ var OptagoUI = {};
51
+
52
+ // Fonte única da versão exibida no badge do header e no rodapé
53
+ // (elementos com o atributo data-op-version). Atualize só aqui.
54
+ var VERSION = '1.2.1';
55
+ OptagoUI.version = VERSION;
56
+
57
+ /* --------------------------------------------------------------------------
58
+ 1. TEMA: aplicado imediatamente (antes do primeiro paint)
59
+ -------------------------------------------------------------------------- */
60
+ var THEME_KEY = 'op-theme';
61
+
62
+ // document.currentScript só é confiável em scripts síncronos (sem defer/
63
+ // async), que é exatamente como esta lib precisa ser carregada mesmo.
64
+ var THEME_DOMAIN = (function () {
65
+ var s = document.currentScript;
66
+ return (s && s.getAttribute('data-op-theme-domain')) || null;
67
+ })();
68
+
69
+ function readCookie(name) {
70
+ var m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
71
+ return m ? decodeURIComponent(m[1]) : null;
72
+ }
73
+
74
+ function writeCookie(name, value) {
75
+ var attrs = 'path=/; max-age=31536000; SameSite=Lax; domain=' + THEME_DOMAIN;
76
+ if (window.location.protocol === 'https:') attrs += '; Secure';
77
+ document.cookie = name + '=' + encodeURIComponent(value) + '; ' + attrs;
78
+ }
79
+
80
+ function currentTheme() {
81
+ var saved = (THEME_DOMAIN && readCookie(THEME_KEY)) || localStorage.getItem(THEME_KEY);
82
+ if (saved === 'light' || saved === 'dark') return saved;
83
+ return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
84
+ }
85
+
86
+ OptagoUI.setTheme = function (theme) {
87
+ document.documentElement.classList.toggle('light', theme === 'light');
88
+ localStorage.setItem(THEME_KEY, theme);
89
+ if (THEME_DOMAIN) writeCookie(THEME_KEY, theme);
90
+ document.querySelectorAll('[data-op-theme-toggle]').forEach(function (btn) {
91
+ var moon = btn.querySelector('.op-icon-moon');
92
+ var sun = btn.querySelector('.op-icon-sun');
93
+ if (moon) moon.style.display = theme === 'dark' ? 'none' : '';
94
+ if (sun) sun.style.display = theme === 'dark' ? '' : 'none';
95
+ });
96
+ };
97
+
98
+ OptagoUI.toggleTheme = function () {
99
+ OptagoUI.setTheme(document.documentElement.classList.contains('light') ? 'dark' : 'light');
100
+ };
101
+
102
+ // Aplica já, sem esperar o DOM (evita FOUC)
103
+ document.documentElement.classList.toggle('light', currentTheme() === 'light');
104
+
105
+ // Suprime a transição de width/transform da sidebar só no carregamento
106
+ // inicial da página (evita ver ela "animando" pra fechada/aberta ao
107
+ // recarregar, já que o JS só consegue aplicar is-collapsed depois que o
108
+ // <aside class="op-sidebar"> existir no DOM - até lá a sidebar já pintou
109
+ // uma vez no estado padrão do CSS, e a troca de classe reativaria a
110
+ // transição normalmente usada pro toggle manual). Removida em init(),
111
+ // depois que o estado inicial (colapsada ou não) já foi aplicado.
112
+ document.documentElement.classList.add('op-preload');
113
+
114
+ /* --------------------------------------------------------------------------
115
+ 2. INJEÇÃO DE DEPENDÊNCIAS (Google Fonts + Phosphor Icons)
116
+ -------------------------------------------------------------------------- */
117
+ function ensureAssets() {
118
+ if (!document.getElementById('op-fonts')) {
119
+ var pre1 = document.createElement('link');
120
+ pre1.rel = 'preconnect'; pre1.href = 'https://fonts.googleapis.com';
121
+ var pre2 = document.createElement('link');
122
+ pre2.rel = 'preconnect'; pre2.href = 'https://fonts.gstatic.com'; pre2.crossOrigin = '';
123
+ var fonts = document.createElement('link');
124
+ fonts.id = 'op-fonts';
125
+ fonts.rel = 'stylesheet';
126
+ fonts.href = 'https://fonts.googleapis.com/css2?family=Chakra+Petch:wght@500;600;700&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap';
127
+ document.head.append(pre1, pre2, fonts);
128
+ }
129
+ if (!document.getElementById('op-icons') && !window.PhosphorIcons) {
130
+ var icons = document.createElement('script');
131
+ icons.id = 'op-icons';
132
+ icons.src = 'https://unpkg.com/@phosphor-icons/web';
133
+ document.head.appendChild(icons);
134
+ }
135
+ }
136
+ ensureAssets();
137
+
138
+ /* --------------------------------------------------------------------------
139
+ 3. SIDEBAR (colapsar no desktop / drawer no mobile)
140
+ -------------------------------------------------------------------------- */
141
+ var SIDEBAR_KEY = 'op-sidebar-collapsed';
142
+
143
+ function getSidebar() { return document.querySelector('.op-sidebar'); }
144
+ function getOverlay() {
145
+ var ov = document.querySelector('.op-overlay');
146
+ if (!ov) {
147
+ ov = document.createElement('div');
148
+ ov.className = 'op-overlay';
149
+ ov.addEventListener('click', OptagoUI.closeSidebarMobile);
150
+ document.body.appendChild(ov);
151
+ }
152
+ return ov;
153
+ }
154
+
155
+ OptagoUI.toggleSidebar = function () {
156
+ var sb = getSidebar();
157
+ if (!sb) return;
158
+ if (window.innerWidth < 1024) { OptagoUI.toggleSidebarMobile(); return; }
159
+ sb.classList.toggle('is-collapsed');
160
+ localStorage.setItem(SIDEBAR_KEY, sb.classList.contains('is-collapsed') ? '1' : '0');
161
+ };
162
+
163
+ OptagoUI.toggleSidebarMobile = function () {
164
+ var sb = getSidebar();
165
+ if (!sb) return;
166
+ var open = sb.classList.toggle('is-open');
167
+ getOverlay().classList.toggle('is-open', open);
168
+ };
169
+
170
+ OptagoUI.closeSidebarMobile = function () {
171
+ var sb = getSidebar();
172
+ if (sb) sb.classList.remove('is-open');
173
+ var ov = document.querySelector('.op-overlay');
174
+ if (ov) ov.classList.remove('is-open');
175
+ };
176
+
177
+ /* --------------------------------------------------------------------------
178
+ 4. TOASTS: OptagoUI.toast('Mensagem', 'success'|'error'|'warning'|'info')
179
+ -------------------------------------------------------------------------- */
180
+ var TOAST_ICONS = {
181
+ success: 'ph-check-circle',
182
+ error: 'ph-x-circle',
183
+ danger: 'ph-x-circle',
184
+ warning: 'ph-warning',
185
+ info: 'ph-info'
186
+ };
187
+
188
+ OptagoUI.toast = function (message, type, duration) {
189
+ type = type || 'info';
190
+ if (type === 'error') type = 'danger';
191
+ duration = duration || 4000;
192
+
193
+ var container = document.querySelector('.op-toast-container');
194
+ if (!container) {
195
+ container = document.createElement('div');
196
+ container.className = 'op-toast-container';
197
+ document.body.appendChild(container);
198
+ }
199
+
200
+ var toast = document.createElement('div');
201
+ toast.className = 'op-toast op-toast-' + type;
202
+ toast.setAttribute('role', 'status');
203
+ toast.innerHTML =
204
+ '<div class="op-toast-icon"><i class="ph ' + (TOAST_ICONS[type] || TOAST_ICONS.info) + '"></i></div>' +
205
+ '<span></span>' +
206
+ '<button class="op-toast-close" aria-label="Fechar"><i class="ph ph-x"></i></button>' +
207
+ '<div class="op-toast-progress"><div class="op-toast-progress-bar"></div></div>';
208
+ toast.querySelector('span').textContent = message;
209
+ container.appendChild(toast);
210
+
211
+ var bar = toast.querySelector('.op-toast-progress-bar');
212
+ var removed = false;
213
+ var timer = null;
214
+ var remaining = duration;
215
+ var startedAt = 0;
216
+
217
+ var dismiss = function () {
218
+ if (removed) return;
219
+ removed = true;
220
+ toast.classList.remove('is-visible');
221
+ setTimeout(function () { toast.remove(); }, 320);
222
+ };
223
+
224
+ // Anima a barra de largura atual até 0 ao longo de `ms`; usar
225
+ // transition (não @keyframes) permite congelar no valor exato em pause().
226
+ var run = function (ms) {
227
+ startedAt = Date.now();
228
+ timer = setTimeout(dismiss, ms);
229
+ requestAnimationFrame(function () {
230
+ bar.style.transitionDuration = ms + 'ms';
231
+ bar.style.width = '0%';
232
+ });
233
+ };
234
+
235
+ var pause = function () {
236
+ if (removed || !timer) return;
237
+ clearTimeout(timer);
238
+ timer = null;
239
+ remaining -= Date.now() - startedAt;
240
+ // Congela a barra no ponto exato em px (transition-duration 0 = sem salto).
241
+ bar.style.width = getComputedStyle(bar).width;
242
+ bar.style.transitionDuration = '0ms';
243
+ };
244
+
245
+ var resume = function () {
246
+ if (removed || timer || remaining <= 0) return;
247
+ run(remaining);
248
+ };
249
+
250
+ toast.addEventListener('mouseenter', pause);
251
+ toast.addEventListener('mouseleave', resume);
252
+ toast.addEventListener('focusin', pause);
253
+ toast.addEventListener('focusout', resume);
254
+ toast.querySelector('.op-toast-close').addEventListener('click', dismiss);
255
+
256
+ requestAnimationFrame(function () {
257
+ requestAnimationFrame(function () { toast.classList.add('is-visible'); });
258
+ });
259
+
260
+ run(duration);
261
+
262
+ return toast;
263
+ };
264
+
265
+ /* --------------------------------------------------------------------------
266
+ 5. MODAIS
267
+ -------------------------------------------------------------------------- */
268
+ OptagoUI.openModal = function (selector) {
269
+ var modal = typeof selector === 'string' ? document.querySelector(selector) : selector;
270
+ if (!modal) return;
271
+ modal.classList.remove('is-closing');
272
+ modal.classList.add('is-open');
273
+ };
274
+
275
+ OptagoUI.closeModal = function (selector) {
276
+ var modal = typeof selector === 'string' ? document.querySelector(selector) : selector;
277
+ if (!modal || !modal.classList.contains('is-open')) return;
278
+ modal.classList.add('is-closing');
279
+ setTimeout(function () {
280
+ modal.classList.remove('is-open', 'is-closing');
281
+ }, 200);
282
+ };
283
+
284
+ /* --------------------------------------------------------------------------
285
+ 5b. TABULATOR: tabela avançada com tema Óptago
286
+ Uso: OptagoUI.tabulator('#minhaTabela', { data: [...], columns: [...] })
287
+ Carrega a biblioteca (CDN) sob demanda; o CSS base do Tabulator é
288
+ inserido ANTES do ui-optago.css para que o tema personalizado
289
+ (.op-tabulator) vença na cascata.
290
+ -------------------------------------------------------------------------- */
291
+ var TABULATOR_JS = 'https://unpkg.com/tabulator-tables@6.3/dist/js/tabulator.min.js';
292
+ var TABULATOR_CSS = 'https://unpkg.com/tabulator-tables@6.3/dist/css/tabulator.min.css';
293
+
294
+ OptagoUI.tabulator = function (selector, options) {
295
+ return new Promise(function (resolve, reject) {
296
+ function build() {
297
+ var el = typeof selector === 'string' ? document.querySelector(selector) : selector;
298
+ if (!el) { reject(new Error('Tabulator: elemento não encontrado: ' + selector)); return; }
299
+ el.classList.add('op-tabulator');
300
+ resolve(new window.Tabulator(el, options || {}));
301
+ }
302
+
303
+ if (window.Tabulator) { build(); return; }
304
+
305
+ if (!document.getElementById('op-tabulator-css')) {
306
+ var css = document.createElement('link');
307
+ css.id = 'op-tabulator-css';
308
+ css.rel = 'stylesheet';
309
+ css.href = TABULATOR_CSS;
310
+ var own = document.querySelector('link[href*="ui-optago.css"]');
311
+ if (own && own.parentNode) {
312
+ own.parentNode.insertBefore(css, own);
313
+ } else {
314
+ document.head.prepend(css);
315
+ }
316
+ }
317
+
318
+ var script = document.getElementById('op-tabulator-js');
319
+ if (!script) {
320
+ script = document.createElement('script');
321
+ script.id = 'op-tabulator-js';
322
+ script.src = TABULATOR_JS;
323
+ document.head.appendChild(script);
324
+ }
325
+ script.addEventListener('load', build);
326
+ script.addEventListener('error', function () {
327
+ reject(new Error('Tabulator: falha ao carregar a biblioteca via CDN.'));
328
+ });
329
+ });
330
+ };
331
+
332
+ /* --------------------------------------------------------------------------
333
+ 5c. TELA DE CARREGAMENTO: overlay em tela cheia
334
+ Uso: OptagoUI.showLoading('Salvando...') ... OptagoUI.hideLoading()
335
+ ou data-op-loading-form no <form> para acionar sozinho no submit.
336
+ -------------------------------------------------------------------------- */
337
+ var LOADING_ID = 'opLoadingOverlay';
338
+
339
+ function getLoadingOverlay() {
340
+ var ov = document.getElementById(LOADING_ID);
341
+ if (!ov) {
342
+ ov = document.createElement('div');
343
+ ov.id = LOADING_ID;
344
+ ov.className = 'op-loading-overlay';
345
+ ov.setAttribute('role', 'alert');
346
+ ov.setAttribute('aria-live', 'assertive');
347
+ ov.innerHTML =
348
+ '<span class="op-spinner"></span>' +
349
+ '<span class="op-loading-message"></span>';
350
+ document.body.appendChild(ov);
351
+ }
352
+ return ov;
353
+ }
354
+
355
+ OptagoUI.showLoading = function (message) {
356
+ var ov = getLoadingOverlay();
357
+ ov.querySelector('.op-loading-message').textContent = message || 'Carregando...';
358
+ ov.classList.add('is-open');
359
+ requestAnimationFrame(function () {
360
+ requestAnimationFrame(function () { ov.classList.add('is-visible'); });
361
+ });
362
+ };
363
+
364
+ OptagoUI.hideLoading = function () {
365
+ var ov = document.getElementById(LOADING_ID);
366
+ if (!ov) return;
367
+ ov.classList.remove('is-visible');
368
+ setTimeout(function () { ov.classList.remove('is-open'); }, 250);
369
+ };
370
+
371
+ // Ao voltar pelo botão "Voltar" do navegador, a página pode ser restaurada
372
+ // do bfcache exatamente como estava ao sair (overlay de carregamento ainda
373
+ // visível, já que o clique/submit anterior nunca chegou a escondê-lo).
374
+ // pageshow com event.persisted=true é o sinal de que veio do bfcache.
375
+ window.addEventListener('pageshow', function (e) {
376
+ if (e.persisted) OptagoUI.hideLoading();
377
+ });
378
+
379
+ /* --------------------------------------------------------------------------
380
+ 6. HELPERS DO SHOWCASE: copiar HTML / ver código
381
+ -------------------------------------------------------------------------- */
382
+ function dedentHTML(el) {
383
+ var html = el.innerHTML.replace(/^\n+|\s+$/g, '');
384
+ var lines = html.split('\n');
385
+ var indent = Infinity;
386
+ lines.forEach(function (line) {
387
+ if (!line.trim()) return;
388
+ var m = line.match(/^\s*/);
389
+ indent = Math.min(indent, m[0].length);
390
+ });
391
+ if (!isFinite(indent)) indent = 0;
392
+ return lines.map(function (line) { return line.slice(indent); }).join('\n');
393
+ }
394
+
395
+ OptagoUI.copyHTML = function (targetSelector, feedbackBtn) {
396
+ var target = document.querySelector(targetSelector);
397
+ if (!target) return;
398
+ var html = dedentHTML(target);
399
+
400
+ var done = function () {
401
+ if (feedbackBtn) {
402
+ var original = feedbackBtn.innerHTML;
403
+ feedbackBtn.innerHTML = '<i class="ph ph-check"></i> Copiado!';
404
+ setTimeout(function () { feedbackBtn.innerHTML = original; }, 2000);
405
+ }
406
+ };
407
+
408
+ if (navigator.clipboard && navigator.clipboard.writeText) {
409
+ navigator.clipboard.writeText(html).then(done);
410
+ } else {
411
+ var ta = document.createElement('textarea');
412
+ ta.value = html;
413
+ ta.style.position = 'fixed';
414
+ ta.style.left = '-9999px';
415
+ document.body.appendChild(ta);
416
+ ta.select();
417
+ document.execCommand('copy');
418
+ ta.remove();
419
+ done();
420
+ }
421
+ };
422
+
423
+ OptagoUI.toggleCode = function (targetSelector, btn) {
424
+ var target = document.querySelector(targetSelector);
425
+ if (!target) return;
426
+ var demo = btn.closest('.op-demo') || target.parentElement;
427
+ var pre = demo.querySelector('.op-demo-code');
428
+ if (!pre) {
429
+ pre = document.createElement('pre');
430
+ pre.className = 'op-demo-code';
431
+ demo.appendChild(pre);
432
+ }
433
+ if (!pre.dataset.filled) {
434
+ pre.textContent = dedentHTML(target);
435
+ pre.dataset.filled = '1';
436
+ }
437
+ pre.classList.toggle('is-visible');
438
+ };
439
+
440
+ /* --------------------------------------------------------------------------
441
+ 7. BINDING GLOBAL via data-attributes (event delegation)
442
+ -------------------------------------------------------------------------- */
443
+
444
+ /**
445
+ * Garante que o .op-menu de um dropdown recém-aberto não vaze pra fora da
446
+ * tela nem pela esquerda nem pela direita (perto de qualquer borda do
447
+ * viewport, não só a direita como .op-menu-end resolve manualmente). Só
448
+ * ajusta a variável CSS --op-menu-shift (soma ao transform de abertura em
449
+ * vez de substituí-lo) - nunca escreve `transform` direto no elemento,
450
+ * senão atropelaria a animação de abrir/fechar já feita em CSS.
451
+ */
452
+ function posicionarMenu(dd) {
453
+ var menu = dd.querySelector('.op-menu');
454
+ if (!menu) return;
455
+
456
+ menu.style.removeProperty('--op-menu-shift');
457
+ var rect = menu.getBoundingClientRect();
458
+ // margem folgada (não só 8px) porque a medição acontece durante a
459
+ // transição de abertura (scale(.98) -> scale(1)) - o retângulo final
460
+ // real pode ficar uns px maior que o medido aqui.
461
+ var margem = 12;
462
+ var vazaDireita = rect.right - (window.innerWidth - margem);
463
+ var vazaEsquerda = margem - rect.left;
464
+
465
+ if (vazaDireita > 0) {
466
+ menu.style.setProperty('--op-menu-shift', (-vazaDireita) + 'px');
467
+ } else if (vazaEsquerda > 0) {
468
+ menu.style.setProperty('--op-menu-shift', vazaEsquerda + 'px');
469
+ }
470
+ }
471
+
472
+ document.addEventListener('click', function (e) {
473
+ var t;
474
+
475
+ // Tema
476
+ if (e.target.closest('[data-op-theme-toggle]')) { OptagoUI.toggleTheme(); return; }
477
+
478
+ // Sidebar
479
+ if (e.target.closest('[data-op-sidebar-toggle]')) { OptagoUI.toggleSidebar(); return; }
480
+ if (e.target.closest('[data-op-sidebar-mobile]')) { OptagoUI.toggleSidebarMobile(); return; }
481
+
482
+ // Fecha drawer mobile ao clicar em link da sidebar
483
+ if (e.target.closest('.op-sidebar .op-nav-item') && window.innerWidth < 1024) {
484
+ OptagoUI.closeSidebarMobile();
485
+ }
486
+
487
+ // Modal
488
+ t = e.target.closest('[data-op-modal-open]');
489
+ if (t) { OptagoUI.openModal(t.getAttribute('data-op-modal-open')); return; }
490
+ if (e.target.closest('[data-op-modal-close]')) {
491
+ OptagoUI.closeModal(e.target.closest('.op-modal'));
492
+ return;
493
+ }
494
+ if (e.target.classList && e.target.classList.contains('op-modal')) {
495
+ OptagoUI.closeModal(e.target); // clique no backdrop
496
+ return;
497
+ }
498
+
499
+ // Tabs
500
+ t = e.target.closest('[data-op-tab]');
501
+ if (t) {
502
+ var name = t.getAttribute('data-op-tab');
503
+ var group = t.closest('[data-op-tab-group]');
504
+ var scope = group ? '[data-op-tab-group="' + group.getAttribute('data-op-tab-group') + '"]' : '';
505
+ document.querySelectorAll(scope + ' [data-op-tab]').forEach(function (tab) {
506
+ tab.classList.toggle('is-active', tab === t);
507
+ });
508
+ document.querySelectorAll(scope + ' [data-op-tab-panel]').forEach(function (panel) {
509
+ panel.classList.toggle('is-active', panel.getAttribute('data-op-tab-panel') === name);
510
+ });
511
+ return;
512
+ }
513
+
514
+ // Dropdown
515
+ t = e.target.closest('[data-op-dropdown-toggle]');
516
+ if (t) {
517
+ var dd = t.closest('.op-dropdown');
518
+ var wasOpen = dd.classList.contains('is-open');
519
+ document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
520
+ if (!wasOpen) {
521
+ dd.classList.add('is-open');
522
+ posicionarMenu(dd);
523
+ }
524
+ return;
525
+ }
526
+ // Fecha dropdowns em clique fora
527
+ if (!e.target.closest('.op-dropdown')) {
528
+ document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
529
+ }
530
+
531
+ // Alert dismiss
532
+ t = e.target.closest('[data-op-dismiss]');
533
+ if (t) {
534
+ var box = t.closest('.op-alert') || t.parentElement;
535
+ box.style.transition = 'opacity .25s, transform .25s';
536
+ box.style.opacity = '0';
537
+ box.style.transform = 'translateX(8px)';
538
+ setTimeout(function () { box.remove(); }, 250);
539
+ return;
540
+ }
541
+
542
+ // Copiar HTML
543
+ t = e.target.closest('[data-op-copy]');
544
+ if (t) { OptagoUI.copyHTML(t.getAttribute('data-op-copy'), t); return; }
545
+
546
+ // Ver código
547
+ t = e.target.closest('[data-op-code]');
548
+ if (t) { OptagoUI.toggleCode(t.getAttribute('data-op-code'), t); return; }
549
+
550
+ // Mostrar/ocultar senha: [data-op-reveal] envolvendo o input,
551
+ // com um <button data-op-reveal-toggle> dentro.
552
+ t = e.target.closest('[data-op-reveal-toggle]');
553
+ if (t) {
554
+ var wrap = t.closest('[data-op-reveal]');
555
+ var input = wrap ? wrap.querySelector('input') : null;
556
+ if (input) {
557
+ var show = input.type === 'password';
558
+ input.type = show ? 'text' : 'password';
559
+ var icon = t.querySelector('i');
560
+ if (icon) icon.className = show ? 'ph ph-eye-slash' : 'ph ph-eye';
561
+ t.setAttribute('aria-label', show ? 'Ocultar senha' : 'Mostrar senha');
562
+ }
563
+ return;
564
+ }
565
+
566
+ // Combobox: clique numa opção seleciona; clique fora fecha.
567
+ t = e.target.closest('[data-op-combobox-option]');
568
+ if (t && !t.hasAttribute('hidden')) { selectComboboxOption(t); return; }
569
+ if (!e.target.closest('[data-op-combobox]')) {
570
+ document.querySelectorAll('.op-combobox.is-open').forEach(closeCombobox);
571
+ }
572
+ });
573
+
574
+ /* --------------------------------------------------------------------------
575
+ 7b. COMBOBOX: input com filtro de opções (autocomplete)
576
+ -------------------------------------------------------------------------- */
577
+ function comboboxOptions(box) {
578
+ var menu = box.querySelector('[data-op-combobox-menu]');
579
+ return menu ? Array.prototype.slice.call(menu.querySelectorAll('[data-op-combobox-option]')) : [];
580
+ }
581
+
582
+ function visibleComboboxOptions(box) {
583
+ return comboboxOptions(box).filter(function (o) { return !o.hasAttribute('hidden'); });
584
+ }
585
+
586
+ function openCombobox(box) {
587
+ box.classList.add('is-open');
588
+ }
589
+
590
+ function closeCombobox(box) {
591
+ box.classList.remove('is-open');
592
+ comboboxOptions(box).forEach(function (o) { o.classList.remove('is-active'); });
593
+ }
594
+
595
+ function selectComboboxOption(option) {
596
+ var box = option.closest('[data-op-combobox]');
597
+ var input = box.querySelector('[data-op-combobox-input]');
598
+ comboboxOptions(box).forEach(function (o) { o.classList.remove('is-selected'); });
599
+ option.classList.add('is-selected');
600
+ if (input) {
601
+ input.value = option.textContent.trim();
602
+ box.dataset.value = option.getAttribute('data-value') || '';
603
+ input.dispatchEvent(new Event('change', { bubbles: true }));
604
+ }
605
+ closeCombobox(box);
606
+ }
607
+
608
+ function filterCombobox(box) {
609
+ var input = box.querySelector('[data-op-combobox-input]');
610
+ var empty = box.querySelector('.op-combobox-empty');
611
+ var query = (input.value || '').trim().toLowerCase();
612
+ var anyVisible = false;
613
+ comboboxOptions(box).forEach(function (o) {
614
+ var match = o.textContent.toLowerCase().indexOf(query) !== -1;
615
+ o.toggleAttribute('hidden', !match);
616
+ o.classList.remove('is-active');
617
+ if (match) anyVisible = true;
618
+ });
619
+ if (empty) empty.hidden = anyVisible;
620
+ }
621
+
622
+ document.addEventListener('input', function (e) {
623
+ var input = e.target.closest('[data-op-combobox-input]');
624
+ if (!input) return;
625
+ var box = input.closest('[data-op-combobox]');
626
+ filterCombobox(box);
627
+ openCombobox(box);
628
+ });
629
+
630
+ document.addEventListener('focusin', function (e) {
631
+ var input = e.target.closest('[data-op-combobox-input]');
632
+ if (!input) return;
633
+ openCombobox(input.closest('[data-op-combobox]'));
634
+ });
635
+
636
+ // Tooltip da sidebar colapsada: o overflow-y da nav cortaria um tooltip
637
+ // com position:absolute, então ele usa position:fixed e o top/right é
638
+ // calculado aqui a cada hover.
639
+ document.addEventListener('mouseover', function (e) {
640
+ var item = e.target.closest('.op-sidebar.is-collapsed .op-nav-item');
641
+ if (!item) return;
642
+ var tip = item.querySelector('.op-nav-tooltip');
643
+ if (!tip) return;
644
+ var r = item.getBoundingClientRect();
645
+ tip.style.top = (r.top + r.height / 2) + 'px';
646
+ tip.style.right = (window.innerWidth - r.left + 14) + 'px';
647
+ tip.style.left = 'auto';
648
+ });
649
+
650
+ // Tooltip genérico (data-op-tip, inclusive em cima de badge): o balão é
651
+ // centralizado no gatilho por padrão (::after com left:50%+translate), o
652
+ // que vaza da tela quando o gatilho está perto da borda esquerda ou
653
+ // direita do viewport. Como ::after não é um nó real do DOM, não dá pra
654
+ // medir o balão em si com getBoundingClientRect() - a correção usa a
655
+ // largura MÁXIMA possível dele (220px, mesmo teto do CSS) como estimativa
656
+ // segura a partir da posição do próprio gatilho (esse sim mensurável),
657
+ // aplicando uma classe que alinha o balão pela ponta em vez do centro.
658
+ // A setinha (::before) não muda de classe, continua centralizada no
659
+ // gatilho e sempre aponta certo pra ele.
660
+ document.addEventListener('mouseover', function (e) {
661
+ var el = e.target.closest('[data-op-tip]');
662
+ if (!el) return;
663
+
664
+ el.classList.remove('op-tip-align-start', 'op-tip-align-end');
665
+
666
+ var rect = el.getBoundingClientRect();
667
+ var centro = rect.left + rect.width / 2;
668
+ var meiaLargura = 110; // metade do max-width de 220px do balão (ver CSS)
669
+ var margem = 8;
670
+
671
+ if (centro - meiaLargura < margem) {
672
+ el.classList.add('op-tip-align-start');
673
+ } else if (centro + meiaLargura > window.innerWidth - margem) {
674
+ el.classList.add('op-tip-align-end');
675
+ }
676
+ });
677
+
678
+ // Formulário com data-op-loading-form: mostra a tela de carregamento
679
+ // sozinho ao submeter (mensagem em data-op-loading-message, se houver).
680
+ document.addEventListener('submit', function (e) {
681
+ var form = e.target.closest('[data-op-loading-form]');
682
+ if (!form) return;
683
+ OptagoUI.showLoading(form.getAttribute('data-op-loading-message'));
684
+ });
685
+
686
+ // ESC fecha modais, dropdowns e comboboxes
687
+ document.addEventListener('keydown', function (e) {
688
+ if (e.key === 'Escape') {
689
+ document.querySelectorAll('.op-modal.is-open').forEach(function (m) { OptagoUI.closeModal(m); });
690
+ document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
691
+ document.querySelectorAll('.op-combobox.is-open').forEach(closeCombobox);
692
+ OptagoUI.closeSidebarMobile();
693
+ return;
694
+ }
695
+
696
+ // Navegação por teclado dentro de um combobox aberto
697
+ var comboInput = e.target.closest('[data-op-combobox-input]');
698
+ if (!comboInput) return;
699
+ var box = comboInput.closest('[data-op-combobox]');
700
+ if (!box.classList.contains('is-open')) return;
701
+
702
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
703
+ e.preventDefault();
704
+ var opts = visibleComboboxOptions(box);
705
+ if (!opts.length) return;
706
+ var current = opts.findIndex(function (o) { return o.classList.contains('is-active'); });
707
+ var next = e.key === 'ArrowDown' ? current + 1 : current - 1;
708
+ if (next < 0) next = opts.length - 1;
709
+ if (next >= opts.length) next = 0;
710
+ opts.forEach(function (o) { o.classList.remove('is-active'); });
711
+ opts[next].classList.add('is-active');
712
+ opts[next].scrollIntoView({ block: 'nearest' });
713
+ } else if (e.key === 'Enter') {
714
+ var active = visibleComboboxOptions(box).filter(function (o) { return o.classList.contains('is-active'); })[0];
715
+ if (active) { e.preventDefault(); selectComboboxOption(active); }
716
+ }
717
+ });
718
+
719
+ /* --------------------------------------------------------------------------
720
+ 8. INICIALIZAÇÃO no DOM pronto
721
+ -------------------------------------------------------------------------- */
722
+ function init() {
723
+ // Versão exibida no badge do header e no rodapé
724
+ document.querySelectorAll('[data-op-version]').forEach(function (el) {
725
+ el.textContent = 'v' + VERSION;
726
+ });
727
+
728
+ // Toasts vindos do servidor (flash messages), sem precisar de <script>
729
+ // inline: importante para funcionar com Content-Security-Policy estrito.
730
+ // Uso: <div hidden data-op-toast='[{"type":"success","message":"Oi!"}]'></div>
731
+ document.querySelectorAll('[data-op-toast]').forEach(function (el) {
732
+ try {
733
+ var items = JSON.parse(el.getAttribute('data-op-toast'));
734
+ (Array.isArray(items) ? items : [items]).forEach(function (t) {
735
+ OptagoUI.toast(t.message, t.type, t.duration);
736
+ });
737
+ } catch (e) { /* atributo malformado: ignora silenciosamente */ }
738
+ });
739
+
740
+ // Sidebar (desktop): fechada por padrão, mas respeita a escolha do
741
+ // usuário salva no localStorage assim que ele abrir/fechar uma vez.
742
+ var sb = getSidebar();
743
+ if (sb && window.innerWidth >= 1024 && localStorage.getItem(SIDEBAR_KEY) !== '0') {
744
+ sb.classList.add('is-collapsed');
745
+ }
746
+
747
+ // Só agora, com o estado inicial da sidebar já decidido, reabilita a
748
+ // transição (ver comentário em cima de "op-preload", perto do topo do
749
+ // arquivo). offsetHeight força o navegador a aplicar/pintar o estado
750
+ // atual ANTES de tirar o "transition:none" - sem isso o toggle inicial
751
+ // e a reabilitação da transição poderiam cair no mesmo frame e a
752
+ // animação apareceria de qualquer jeito.
753
+ if (sb) { void sb.offsetHeight; }
754
+ document.documentElement.classList.remove('op-preload');
755
+
756
+ // Ajusta ícones do botão de tema
757
+ OptagoUI.setTheme(document.documentElement.classList.contains('light') ? 'light' : 'dark');
758
+
759
+ // Scrollspy simples: marca .op-nav-item ativo conforme a seção visível
760
+ var main = document.querySelector('.op-main');
761
+ var links = Array.prototype.slice.call(document.querySelectorAll('.op-sidebar .op-nav-item[href^="#"]'));
762
+ if (main && links.length) {
763
+ var sections = links
764
+ .map(function (l) { return document.querySelector(l.getAttribute('href')); })
765
+ .filter(Boolean);
766
+ var onScroll = function () {
767
+ var top = main.scrollTop + 120;
768
+ var active = sections[0];
769
+ sections.forEach(function (s) { if (s.offsetTop <= top) active = s; });
770
+ links.forEach(function (l) {
771
+ l.classList.toggle('is-active', active && l.getAttribute('href') === '#' + active.id);
772
+ });
773
+ };
774
+ main.addEventListener('scroll', onScroll, { passive: true });
775
+ onScroll();
776
+ }
777
+ }
778
+
779
+ if (document.readyState === 'loading') {
780
+ document.addEventListener('DOMContentLoaded', init);
781
+ } else {
782
+ init();
783
+ }
784
+
785
+ window.OptagoUI = OptagoUI;
786
+ })();