ui-optago 1.2.2 → 1.2.4

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 (6) hide show
  1. package/README.md +197 -178
  2. package/index.html +1799 -1474
  3. package/llms.txt +18 -7
  4. package/package.json +1 -1
  5. package/ui-optago.css +2453 -2295
  6. package/ui-optago.js +897 -805
package/ui-optago.js CHANGED
@@ -1,805 +1,897 @@
1
- /* ============================================================================
2
- UI ÓPTAGO: Design System v1.2.2 (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.2';
55
- OptagoUI.version = VERSION;
56
-
57
- console.log(
58
- '%c Óptago UI %c v' + VERSION + ' ',
59
- 'background:#0a0a0a;color:#C0FF6B;font-weight:700;padding:3px 8px;border-radius:4px 0 0 4px;font-family:"JetBrains Mono",monospace;font-size:12px;',
60
- 'background:#C0FF6B;color:#0a0a0a;font-weight:700;padding:3px 8px;border-radius:0 4px 4px 0;font-family:"JetBrains Mono",monospace;font-size:12px;'
61
- );
62
-
63
- /* --------------------------------------------------------------------------
64
- 1. TEMA: aplicado imediatamente (antes do primeiro paint)
65
- -------------------------------------------------------------------------- */
66
- var THEME_KEY = 'op-theme';
67
-
68
- // document.currentScript só é confiável em scripts síncronos (sem defer/
69
- // async), que é exatamente como esta lib precisa ser carregada mesmo.
70
- var THEME_DOMAIN = (function () {
71
- var s = document.currentScript;
72
- return (s && s.getAttribute('data-op-theme-domain')) || null;
73
- })();
74
-
75
- function readCookie(name) {
76
- var m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
77
- return m ? decodeURIComponent(m[1]) : null;
78
- }
79
-
80
- function writeCookie(name, value) {
81
- var attrs = 'path=/; max-age=31536000; SameSite=Lax; domain=' + THEME_DOMAIN;
82
- if (window.location.protocol === 'https:') attrs += '; Secure';
83
- document.cookie = name + '=' + encodeURIComponent(value) + '; ' + attrs;
84
- }
85
-
86
- function currentTheme() {
87
- var saved = (THEME_DOMAIN && readCookie(THEME_KEY)) || localStorage.getItem(THEME_KEY);
88
- if (saved === 'light' || saved === 'dark') return saved;
89
- return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
90
- }
91
-
92
- OptagoUI.setTheme = function (theme) {
93
- document.documentElement.classList.toggle('light', theme === 'light');
94
- localStorage.setItem(THEME_KEY, theme);
95
- if (THEME_DOMAIN) writeCookie(THEME_KEY, theme);
96
- document.querySelectorAll('[data-op-theme-toggle]').forEach(function (btn) {
97
- var moon = btn.querySelector('.op-icon-moon');
98
- var sun = btn.querySelector('.op-icon-sun');
99
- if (moon) moon.style.display = theme === 'dark' ? 'none' : '';
100
- if (sun) sun.style.display = theme === 'dark' ? '' : 'none';
101
- });
102
- };
103
-
104
- OptagoUI.toggleTheme = function () {
105
- OptagoUI.setTheme(document.documentElement.classList.contains('light') ? 'dark' : 'light');
106
- };
107
-
108
- // Aplica já, sem esperar o DOM (evita FOUC)
109
- document.documentElement.classList.toggle('light', currentTheme() === 'light');
110
-
111
- // Suprime a transição de width/transform da sidebar só no carregamento
112
- // inicial da página (evita ver ela "animando" pra fechada/aberta ao
113
- // recarregar, já que o JS só consegue aplicar is-collapsed depois que o
114
- // <aside class="op-sidebar"> existir no DOM - até lá a sidebar já pintou
115
- // uma vez no estado padrão do CSS, e a troca de classe reativaria a
116
- // transição normalmente usada pro toggle manual). Removida em init(),
117
- // depois que o estado inicial (colapsada ou não) já foi aplicado.
118
- document.documentElement.classList.add('op-preload');
119
-
120
- /* --------------------------------------------------------------------------
121
- 2. INJEÇÃO DE DEPENDÊNCIAS (Google Fonts + Phosphor Icons)
122
- -------------------------------------------------------------------------- */
123
- function ensureAssets() {
124
- if (!document.getElementById('op-fonts')) {
125
- var pre1 = document.createElement('link');
126
- pre1.rel = 'preconnect'; pre1.href = 'https://fonts.googleapis.com';
127
- var pre2 = document.createElement('link');
128
- pre2.rel = 'preconnect'; pre2.href = 'https://fonts.gstatic.com'; pre2.crossOrigin = '';
129
- var fonts = document.createElement('link');
130
- fonts.id = 'op-fonts';
131
- fonts.rel = 'stylesheet';
132
- 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';
133
- document.head.append(pre1, pre2, fonts);
134
- }
135
- if (!document.getElementById('op-icons') && !window.PhosphorIcons) {
136
- var icons = document.createElement('script');
137
- icons.id = 'op-icons';
138
- icons.src = 'https://unpkg.com/@phosphor-icons/web';
139
- document.head.appendChild(icons);
140
- }
141
- }
142
- ensureAssets();
143
-
144
- /* --------------------------------------------------------------------------
145
- 3. SIDEBAR (colapsar no desktop / drawer no mobile)
146
- -------------------------------------------------------------------------- */
147
- var SIDEBAR_KEY = 'op-sidebar-collapsed';
148
-
149
- function getSidebar() { return document.querySelector('.op-sidebar'); }
150
- function getOverlay() {
151
- var ov = document.querySelector('.op-overlay');
152
- if (!ov) {
153
- ov = document.createElement('div');
154
- ov.className = 'op-overlay';
155
- ov.addEventListener('click', OptagoUI.closeSidebarMobile);
156
- document.body.appendChild(ov);
157
- }
158
- return ov;
159
- }
160
-
161
- OptagoUI.toggleSidebar = function () {
162
- var sb = getSidebar();
163
- if (!sb) return;
164
- if (window.innerWidth < 1024) { OptagoUI.toggleSidebarMobile(); return; }
165
- sb.classList.toggle('is-collapsed');
166
- localStorage.setItem(SIDEBAR_KEY, sb.classList.contains('is-collapsed') ? '1' : '0');
167
- };
168
-
169
- OptagoUI.toggleSidebarMobile = function () {
170
- var sb = getSidebar();
171
- if (!sb) return;
172
- var open = sb.classList.toggle('is-open');
173
- getOverlay().classList.toggle('is-open', open);
174
- };
175
-
176
- OptagoUI.closeSidebarMobile = function () {
177
- var sb = getSidebar();
178
- if (sb) sb.classList.remove('is-open');
179
- var ov = document.querySelector('.op-overlay');
180
- if (ov) ov.classList.remove('is-open');
181
- };
182
-
183
- /* --------------------------------------------------------------------------
184
- 4. TOASTS: OptagoUI.toast('Mensagem', 'success'|'error'|'warning'|'info')
185
- -------------------------------------------------------------------------- */
186
- var TOAST_ICONS = {
187
- success: 'ph-check-circle',
188
- error: 'ph-x-circle',
189
- danger: 'ph-x-circle',
190
- warning: 'ph-warning',
191
- info: 'ph-info'
192
- };
193
-
194
- OptagoUI.toast = function (message, type, duration) {
195
- type = type || 'info';
196
- if (type === 'error') type = 'danger';
197
- duration = duration || 4000;
198
-
199
- var container = document.querySelector('.op-toast-container');
200
- if (!container) {
201
- container = document.createElement('div');
202
- container.className = 'op-toast-container';
203
- document.body.appendChild(container);
204
- }
205
-
206
- var toast = document.createElement('div');
207
- toast.className = 'op-toast op-toast-' + type;
208
- toast.setAttribute('role', 'status');
209
- toast.innerHTML =
210
- '<div class="op-toast-icon"><i class="ph ' + (TOAST_ICONS[type] || TOAST_ICONS.info) + '"></i></div>' +
211
- '<span></span>' +
212
- '<button class="op-toast-close" aria-label="Fechar"><i class="ph ph-x"></i></button>' +
213
- '<div class="op-toast-progress"><div class="op-toast-progress-bar"></div></div>';
214
- toast.querySelector('span').textContent = message;
215
- container.appendChild(toast);
216
-
217
- var bar = toast.querySelector('.op-toast-progress-bar');
218
- var removed = false;
219
- var timer = null;
220
- var remaining = duration;
221
- var startedAt = 0;
222
-
223
- var dismiss = function () {
224
- if (removed) return;
225
- removed = true;
226
- toast.classList.remove('is-visible');
227
- setTimeout(function () { toast.remove(); }, 320);
228
- };
229
-
230
- // Anima a barra de largura atual até 0 ao longo de `ms`; usar
231
- // transition (não @keyframes) permite congelar no valor exato em pause().
232
- var run = function (ms) {
233
- startedAt = Date.now();
234
- timer = setTimeout(dismiss, ms);
235
- requestAnimationFrame(function () {
236
- bar.style.transitionDuration = ms + 'ms';
237
- bar.style.width = '0%';
238
- });
239
- };
240
-
241
- var pause = function () {
242
- if (removed || !timer) return;
243
- clearTimeout(timer);
244
- timer = null;
245
- remaining -= Date.now() - startedAt;
246
- // Congela a barra no ponto exato em px (transition-duration 0 = sem salto).
247
- bar.style.width = getComputedStyle(bar).width;
248
- bar.style.transitionDuration = '0ms';
249
- };
250
-
251
- var resume = function () {
252
- if (removed || timer || remaining <= 0) return;
253
- run(remaining);
254
- };
255
-
256
- toast.addEventListener('mouseenter', pause);
257
- toast.addEventListener('mouseleave', resume);
258
- toast.addEventListener('focusin', pause);
259
- toast.addEventListener('focusout', resume);
260
- toast.querySelector('.op-toast-close').addEventListener('click', dismiss);
261
-
262
- requestAnimationFrame(function () {
263
- requestAnimationFrame(function () { toast.classList.add('is-visible'); });
264
- });
265
-
266
- run(duration);
267
-
268
- return toast;
269
- };
270
-
271
- /* --------------------------------------------------------------------------
272
- 5. MODAIS
273
- -------------------------------------------------------------------------- */
274
- OptagoUI.openModal = function (selector) {
275
- var modal = typeof selector === 'string' ? document.querySelector(selector) : selector;
276
- if (!modal) return;
277
- modal.classList.remove('is-closing');
278
- modal.classList.add('is-open');
279
- };
280
-
281
- OptagoUI.closeModal = function (selector) {
282
- var modal = typeof selector === 'string' ? document.querySelector(selector) : selector;
283
- if (!modal || !modal.classList.contains('is-open')) return;
284
- modal.classList.add('is-closing');
285
- setTimeout(function () {
286
- modal.classList.remove('is-open', 'is-closing');
287
- }, 200);
288
- };
289
-
290
- /* --------------------------------------------------------------------------
291
- 5b. TABULATOR: tabela avançada com tema Óptago
292
- Uso: OptagoUI.tabulator('#minhaTabela', { data: [...], columns: [...] })
293
- Carrega a biblioteca (CDN) sob demanda; o CSS base do Tabulator é
294
- inserido ANTES do ui-optago.css para que o tema personalizado
295
- (.op-tabulator) vença na cascata.
296
- -------------------------------------------------------------------------- */
297
- var TABULATOR_JS = 'https://unpkg.com/tabulator-tables@6.3/dist/js/tabulator.min.js';
298
- var TABULATOR_CSS = 'https://unpkg.com/tabulator-tables@6.3/dist/css/tabulator.min.css';
299
-
300
- OptagoUI.tabulator = function (selector, options) {
301
- return new Promise(function (resolve, reject) {
302
- function build() {
303
- var el = typeof selector === 'string' ? document.querySelector(selector) : selector;
304
- if (!el) { reject(new Error('Tabulator: elemento não encontrado: ' + selector)); return; }
305
- el.classList.add('op-tabulator');
306
- resolve(new window.Tabulator(el, options || {}));
307
- }
308
-
309
- if (window.Tabulator) { build(); return; }
310
-
311
- if (!document.getElementById('op-tabulator-css')) {
312
- var css = document.createElement('link');
313
- css.id = 'op-tabulator-css';
314
- css.rel = 'stylesheet';
315
- css.href = TABULATOR_CSS;
316
- var own = document.querySelector('link[href*="ui-optago.css"]');
317
- if (own && own.parentNode) {
318
- own.parentNode.insertBefore(css, own);
319
- } else {
320
- document.head.prepend(css);
321
- }
322
- }
323
-
324
- var script = document.getElementById('op-tabulator-js');
325
- if (!script) {
326
- script = document.createElement('script');
327
- script.id = 'op-tabulator-js';
328
- script.src = TABULATOR_JS;
329
- document.head.appendChild(script);
330
- }
331
- script.addEventListener('load', build);
332
- script.addEventListener('error', function () {
333
- reject(new Error('Tabulator: falha ao carregar a biblioteca via CDN.'));
334
- });
335
- });
336
- };
337
-
338
- /* --------------------------------------------------------------------------
339
- 5c. TELA DE CARREGAMENTO: overlay em tela cheia
340
- Uso: OptagoUI.showLoading('Salvando...') ... OptagoUI.hideLoading()
341
- ou data-op-loading-form no <form> para acionar sozinho no submit.
342
- -------------------------------------------------------------------------- */
343
- var LOADING_ID = 'opLoadingOverlay';
344
-
345
- function getLoadingOverlay() {
346
- var ov = document.getElementById(LOADING_ID);
347
- if (!ov) {
348
- ov = document.createElement('div');
349
- ov.id = LOADING_ID;
350
- ov.className = 'op-loading-overlay';
351
- ov.setAttribute('role', 'alert');
352
- ov.setAttribute('aria-live', 'assertive');
353
- ov.innerHTML =
354
- '<span class="op-spinner"></span>' +
355
- '<span class="op-loading-message"></span>';
356
- document.body.appendChild(ov);
357
- }
358
- return ov;
359
- }
360
-
361
- OptagoUI.showLoading = function (message) {
362
- var ov = getLoadingOverlay();
363
- ov.querySelector('.op-loading-message').textContent = message || 'Carregando...';
364
- ov.classList.add('is-open');
365
- requestAnimationFrame(function () {
366
- requestAnimationFrame(function () { ov.classList.add('is-visible'); });
367
- });
368
- };
369
-
370
- OptagoUI.hideLoading = function () {
371
- var ov = document.getElementById(LOADING_ID);
372
- if (!ov) return;
373
- ov.classList.remove('is-visible');
374
- setTimeout(function () { ov.classList.remove('is-open'); }, 250);
375
- };
376
-
377
- // Ao voltar pelo botão "Voltar" do navegador, a página pode ser restaurada
378
- // do bfcache exatamente como estava ao sair (overlay de carregamento ainda
379
- // visível, já que o clique/submit anterior nunca chegou a escondê-lo).
380
- // pageshow com event.persisted=true é o sinal de que veio do bfcache.
381
- window.addEventListener('pageshow', function (e) {
382
- if (e.persisted) OptagoUI.hideLoading();
383
- });
384
-
385
- /* --------------------------------------------------------------------------
386
- 6. HELPERS DO SHOWCASE: copiar HTML / ver código
387
- -------------------------------------------------------------------------- */
388
- function dedentHTML(el) {
389
- var html = el.innerHTML.replace(/^\n+|\s+$/g, '');
390
- var lines = html.split('\n');
391
- var indent = Infinity;
392
- lines.forEach(function (line) {
393
- if (!line.trim()) return;
394
- var m = line.match(/^\s*/);
395
- indent = Math.min(indent, m[0].length);
396
- });
397
- if (!isFinite(indent)) indent = 0;
398
- return lines.map(function (line) { return line.slice(indent); }).join('\n');
399
- }
400
-
401
- OptagoUI.copyHTML = function (targetSelector, feedbackBtn) {
402
- var target = document.querySelector(targetSelector);
403
- if (!target) return;
404
- var html = dedentHTML(target);
405
-
406
- var done = function () {
407
- if (feedbackBtn) {
408
- var original = feedbackBtn.innerHTML;
409
- feedbackBtn.innerHTML = '<i class="ph ph-check"></i> Copiado!';
410
- setTimeout(function () { feedbackBtn.innerHTML = original; }, 2000);
411
- }
412
- };
413
-
414
- if (navigator.clipboard && navigator.clipboard.writeText) {
415
- navigator.clipboard.writeText(html).then(done);
416
- } else {
417
- var ta = document.createElement('textarea');
418
- ta.value = html;
419
- ta.style.position = 'fixed';
420
- ta.style.left = '-9999px';
421
- document.body.appendChild(ta);
422
- ta.select();
423
- document.execCommand('copy');
424
- ta.remove();
425
- done();
426
- }
427
- };
428
-
429
- OptagoUI.toggleCode = function (targetSelector, btn) {
430
- var target = document.querySelector(targetSelector);
431
- if (!target) return;
432
- var demo = btn.closest('.op-demo') || target.parentElement;
433
- var pre = demo.querySelector('.op-demo-code');
434
- if (!pre) {
435
- pre = document.createElement('pre');
436
- pre.className = 'op-demo-code';
437
- demo.appendChild(pre);
438
- }
439
- if (!pre.dataset.filled) {
440
- pre.textContent = dedentHTML(target);
441
- pre.dataset.filled = '1';
442
- }
443
- pre.classList.toggle('is-visible');
444
- };
445
-
446
- /* --------------------------------------------------------------------------
447
- 7. BINDING GLOBAL via data-attributes (event delegation)
448
- -------------------------------------------------------------------------- */
449
-
450
- /**
451
- * Garante que o .op-menu de um dropdown recém-aberto não vaze pra fora da
452
- * tela nem pela esquerda nem pela direita (perto de qualquer borda do
453
- * viewport, não só a direita como .op-menu-end resolve manualmente). Só
454
- * ajusta a variável CSS --op-menu-shift (soma ao transform de abertura em
455
- * vez de substituí-lo) - nunca escreve `transform` direto no elemento,
456
- * senão atropelaria a animação de abrir/fechar já feita em CSS.
457
- */
458
- function posicionarMenu(dd) {
459
- var menu = dd.querySelector('.op-menu');
460
- if (!menu) return;
461
-
462
- menu.style.removeProperty('--op-menu-shift');
463
-
464
- // offsetLeft/offsetWidth são medidas de LAYOUT puras, nunca afetadas
465
- // por transform - ao contrário de menu.getBoundingClientRect(), que
466
- // reflete o transform da animação de abrir/fechar (scale/translateY/
467
- // translateX) em tempo real. Numa 2ª+ abertura, uma transição CSS ainda
468
- // ativa tem prioridade de cascata sobre QUALQUER valor (mesmo inline),
469
- // então nem forçar transform:none temporariamente adianta: o
470
- // getBoundingClientRect() continuava capturando o --op-menu-shift
471
- // residual da abertura anterior, cortando o menu. Medindo via
472
- // offsetLeft/offsetWidth (relativos ao .op-dropdown, que não anima)
473
- // a conta fica sempre exata, em qualquer abertura, sem precisar tocar
474
- // em transition nem em transform e sem atrapalhar a animação de
475
- // entrada.
476
- var ddRect = dd.getBoundingClientRect();
477
- var left = ddRect.left + menu.offsetLeft;
478
- var right = left + menu.offsetWidth;
479
-
480
- var margem = 12;
481
- var vazaDireita = right - (window.innerWidth - margem);
482
- var vazaEsquerda = margem - left;
483
-
484
- if (vazaDireita > 0) {
485
- menu.style.setProperty('--op-menu-shift', (-vazaDireita) + 'px');
486
- } else if (vazaEsquerda > 0) {
487
- menu.style.setProperty('--op-menu-shift', vazaEsquerda + 'px');
488
- }
489
- }
490
-
491
- document.addEventListener('click', function (e) {
492
- var t;
493
-
494
- // Tema
495
- if (e.target.closest('[data-op-theme-toggle]')) { OptagoUI.toggleTheme(); return; }
496
-
497
- // Sidebar
498
- if (e.target.closest('[data-op-sidebar-toggle]')) { OptagoUI.toggleSidebar(); return; }
499
- if (e.target.closest('[data-op-sidebar-mobile]')) { OptagoUI.toggleSidebarMobile(); return; }
500
-
501
- // Fecha drawer mobile ao clicar em link da sidebar
502
- if (e.target.closest('.op-sidebar .op-nav-item') && window.innerWidth < 1024) {
503
- OptagoUI.closeSidebarMobile();
504
- }
505
-
506
- // Modal
507
- t = e.target.closest('[data-op-modal-open]');
508
- if (t) { OptagoUI.openModal(t.getAttribute('data-op-modal-open')); return; }
509
- if (e.target.closest('[data-op-modal-close]')) {
510
- OptagoUI.closeModal(e.target.closest('.op-modal'));
511
- return;
512
- }
513
- if (e.target.classList && e.target.classList.contains('op-modal')) {
514
- OptagoUI.closeModal(e.target); // clique no backdrop
515
- return;
516
- }
517
-
518
- // Tabs
519
- t = e.target.closest('[data-op-tab]');
520
- if (t) {
521
- var name = t.getAttribute('data-op-tab');
522
- var group = t.closest('[data-op-tab-group]');
523
- var scope = group ? '[data-op-tab-group="' + group.getAttribute('data-op-tab-group') + '"]' : '';
524
- document.querySelectorAll(scope + ' [data-op-tab]').forEach(function (tab) {
525
- tab.classList.toggle('is-active', tab === t);
526
- });
527
- document.querySelectorAll(scope + ' [data-op-tab-panel]').forEach(function (panel) {
528
- panel.classList.toggle('is-active', panel.getAttribute('data-op-tab-panel') === name);
529
- });
530
- return;
531
- }
532
-
533
- // Dropdown
534
- t = e.target.closest('[data-op-dropdown-toggle]');
535
- if (t) {
536
- var dd = t.closest('.op-dropdown');
537
- var wasOpen = dd.classList.contains('is-open');
538
- document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
539
- if (!wasOpen) {
540
- dd.classList.add('is-open');
541
- posicionarMenu(dd);
542
- }
543
- return;
544
- }
545
- // Fecha dropdowns em clique fora
546
- if (!e.target.closest('.op-dropdown')) {
547
- document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
548
- }
549
-
550
- // Alert dismiss
551
- t = e.target.closest('[data-op-dismiss]');
552
- if (t) {
553
- var box = t.closest('.op-alert') || t.parentElement;
554
- box.style.transition = 'opacity .25s, transform .25s';
555
- box.style.opacity = '0';
556
- box.style.transform = 'translateX(8px)';
557
- setTimeout(function () { box.remove(); }, 250);
558
- return;
559
- }
560
-
561
- // Copiar HTML
562
- t = e.target.closest('[data-op-copy]');
563
- if (t) { OptagoUI.copyHTML(t.getAttribute('data-op-copy'), t); return; }
564
-
565
- // Ver código
566
- t = e.target.closest('[data-op-code]');
567
- if (t) { OptagoUI.toggleCode(t.getAttribute('data-op-code'), t); return; }
568
-
569
- // Mostrar/ocultar senha: [data-op-reveal] envolvendo o input,
570
- // com um <button data-op-reveal-toggle> dentro.
571
- t = e.target.closest('[data-op-reveal-toggle]');
572
- if (t) {
573
- var wrap = t.closest('[data-op-reveal]');
574
- var input = wrap ? wrap.querySelector('input') : null;
575
- if (input) {
576
- var show = input.type === 'password';
577
- input.type = show ? 'text' : 'password';
578
- var icon = t.querySelector('i');
579
- if (icon) icon.className = show ? 'ph ph-eye-slash' : 'ph ph-eye';
580
- t.setAttribute('aria-label', show ? 'Ocultar senha' : 'Mostrar senha');
581
- }
582
- return;
583
- }
584
-
585
- // Combobox: clique numa opção seleciona; clique fora fecha.
586
- t = e.target.closest('[data-op-combobox-option]');
587
- if (t && !t.hasAttribute('hidden')) { selectComboboxOption(t); return; }
588
- if (!e.target.closest('[data-op-combobox]')) {
589
- document.querySelectorAll('.op-combobox.is-open').forEach(closeCombobox);
590
- }
591
- });
592
-
593
- /* --------------------------------------------------------------------------
594
- 7b. COMBOBOX: input com filtro de opções (autocomplete)
595
- -------------------------------------------------------------------------- */
596
- function comboboxOptions(box) {
597
- var menu = box.querySelector('[data-op-combobox-menu]');
598
- return menu ? Array.prototype.slice.call(menu.querySelectorAll('[data-op-combobox-option]')) : [];
599
- }
600
-
601
- function visibleComboboxOptions(box) {
602
- return comboboxOptions(box).filter(function (o) { return !o.hasAttribute('hidden'); });
603
- }
604
-
605
- function openCombobox(box) {
606
- box.classList.add('is-open');
607
- }
608
-
609
- function closeCombobox(box) {
610
- box.classList.remove('is-open');
611
- comboboxOptions(box).forEach(function (o) { o.classList.remove('is-active'); });
612
- }
613
-
614
- function selectComboboxOption(option) {
615
- var box = option.closest('[data-op-combobox]');
616
- var input = box.querySelector('[data-op-combobox-input]');
617
- comboboxOptions(box).forEach(function (o) { o.classList.remove('is-selected'); });
618
- option.classList.add('is-selected');
619
- if (input) {
620
- input.value = option.textContent.trim();
621
- box.dataset.value = option.getAttribute('data-value') || '';
622
- input.dispatchEvent(new Event('change', { bubbles: true }));
623
- }
624
- closeCombobox(box);
625
- }
626
-
627
- function filterCombobox(box) {
628
- var input = box.querySelector('[data-op-combobox-input]');
629
- var empty = box.querySelector('.op-combobox-empty');
630
- var query = (input.value || '').trim().toLowerCase();
631
- var anyVisible = false;
632
- comboboxOptions(box).forEach(function (o) {
633
- var match = o.textContent.toLowerCase().indexOf(query) !== -1;
634
- o.toggleAttribute('hidden', !match);
635
- o.classList.remove('is-active');
636
- if (match) anyVisible = true;
637
- });
638
- if (empty) empty.hidden = anyVisible;
639
- }
640
-
641
- document.addEventListener('input', function (e) {
642
- var input = e.target.closest('[data-op-combobox-input]');
643
- if (!input) return;
644
- var box = input.closest('[data-op-combobox]');
645
- filterCombobox(box);
646
- openCombobox(box);
647
- });
648
-
649
- document.addEventListener('focusin', function (e) {
650
- var input = e.target.closest('[data-op-combobox-input]');
651
- if (!input) return;
652
- openCombobox(input.closest('[data-op-combobox]'));
653
- });
654
-
655
- // Tooltip da sidebar colapsada: o overflow-y da nav cortaria um tooltip
656
- // com position:absolute, então ele usa position:fixed e o top/right é
657
- // calculado aqui a cada hover.
658
- document.addEventListener('mouseover', function (e) {
659
- var item = e.target.closest('.op-sidebar.is-collapsed .op-nav-item');
660
- if (!item) return;
661
- var tip = item.querySelector('.op-nav-tooltip');
662
- if (!tip) return;
663
- var r = item.getBoundingClientRect();
664
- tip.style.top = (r.top + r.height / 2) + 'px';
665
- tip.style.right = (window.innerWidth - r.left + 14) + 'px';
666
- tip.style.left = 'auto';
667
- });
668
-
669
- // Tooltip genérico (data-op-tip, inclusive em cima de badge): o balão é
670
- // centralizado no gatilho por padrão (::after com left:50%+translate), o
671
- // que vaza da tela quando o gatilho está perto da borda esquerda ou
672
- // direita do viewport. Como ::after não é um nó real do DOM, não dá pra
673
- // medir o balão em si com getBoundingClientRect() - a correção usa a
674
- // largura MÁXIMA possível dele (220px, mesmo teto do CSS) como estimativa
675
- // segura a partir da posição do próprio gatilho (esse sim mensurável),
676
- // aplicando uma classe que alinha o balão pela ponta em vez do centro.
677
- // A setinha (::before) não muda de classe, continua centralizada no
678
- // gatilho e sempre aponta certo pra ele.
679
- document.addEventListener('mouseover', function (e) {
680
- var el = e.target.closest('[data-op-tip]');
681
- if (!el) return;
682
-
683
- el.classList.remove('op-tip-align-start', 'op-tip-align-end');
684
-
685
- var rect = el.getBoundingClientRect();
686
- var centro = rect.left + rect.width / 2;
687
- var meiaLargura = 110; // metade do max-width de 220px do balão (ver CSS)
688
- var margem = 8;
689
-
690
- if (centro - meiaLargura < margem) {
691
- el.classList.add('op-tip-align-start');
692
- } else if (centro + meiaLargura > window.innerWidth - margem) {
693
- el.classList.add('op-tip-align-end');
694
- }
695
- });
696
-
697
- // Formulário com data-op-loading-form: mostra a tela de carregamento
698
- // sozinho ao submeter (mensagem em data-op-loading-message, se houver).
699
- document.addEventListener('submit', function (e) {
700
- var form = e.target.closest('[data-op-loading-form]');
701
- if (!form) return;
702
- OptagoUI.showLoading(form.getAttribute('data-op-loading-message'));
703
- });
704
-
705
- // ESC fecha modais, dropdowns e comboboxes
706
- document.addEventListener('keydown', function (e) {
707
- if (e.key === 'Escape') {
708
- document.querySelectorAll('.op-modal.is-open').forEach(function (m) { OptagoUI.closeModal(m); });
709
- document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
710
- document.querySelectorAll('.op-combobox.is-open').forEach(closeCombobox);
711
- OptagoUI.closeSidebarMobile();
712
- return;
713
- }
714
-
715
- // Navegação por teclado dentro de um combobox aberto
716
- var comboInput = e.target.closest('[data-op-combobox-input]');
717
- if (!comboInput) return;
718
- var box = comboInput.closest('[data-op-combobox]');
719
- if (!box.classList.contains('is-open')) return;
720
-
721
- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
722
- e.preventDefault();
723
- var opts = visibleComboboxOptions(box);
724
- if (!opts.length) return;
725
- var current = opts.findIndex(function (o) { return o.classList.contains('is-active'); });
726
- var next = e.key === 'ArrowDown' ? current + 1 : current - 1;
727
- if (next < 0) next = opts.length - 1;
728
- if (next >= opts.length) next = 0;
729
- opts.forEach(function (o) { o.classList.remove('is-active'); });
730
- opts[next].classList.add('is-active');
731
- opts[next].scrollIntoView({ block: 'nearest' });
732
- } else if (e.key === 'Enter') {
733
- var active = visibleComboboxOptions(box).filter(function (o) { return o.classList.contains('is-active'); })[0];
734
- if (active) { e.preventDefault(); selectComboboxOption(active); }
735
- }
736
- });
737
-
738
- /* --------------------------------------------------------------------------
739
- 8. INICIALIZAÇÃO no DOM pronto
740
- -------------------------------------------------------------------------- */
741
- function init() {
742
- // Versão exibida no badge do header e no rodapé
743
- document.querySelectorAll('[data-op-version]').forEach(function (el) {
744
- el.textContent = 'v' + VERSION;
745
- });
746
-
747
- // Toasts vindos do servidor (flash messages), sem precisar de <script>
748
- // inline: importante para funcionar com Content-Security-Policy estrito.
749
- // Uso: <div hidden data-op-toast='[{"type":"success","message":"Oi!"}]'></div>
750
- document.querySelectorAll('[data-op-toast]').forEach(function (el) {
751
- try {
752
- var items = JSON.parse(el.getAttribute('data-op-toast'));
753
- (Array.isArray(items) ? items : [items]).forEach(function (t) {
754
- OptagoUI.toast(t.message, t.type, t.duration);
755
- });
756
- } catch (e) { /* atributo malformado: ignora silenciosamente */ }
757
- });
758
-
759
- // Sidebar (desktop): fechada por padrão, mas respeita a escolha do
760
- // usuário salva no localStorage assim que ele abrir/fechar uma vez.
761
- var sb = getSidebar();
762
- if (sb && window.innerWidth >= 1024 && localStorage.getItem(SIDEBAR_KEY) !== '0') {
763
- sb.classList.add('is-collapsed');
764
- }
765
-
766
- // Só agora, com o estado inicial da sidebar já decidido, reabilita a
767
- // transição (ver comentário em cima de "op-preload", perto do topo do
768
- // arquivo). offsetHeight força o navegador a aplicar/pintar o estado
769
- // atual ANTES de tirar o "transition:none" - sem isso o toggle inicial
770
- // e a reabilitação da transição poderiam cair no mesmo frame e a
771
- // animação apareceria de qualquer jeito.
772
- if (sb) { void sb.offsetHeight; }
773
- document.documentElement.classList.remove('op-preload');
774
-
775
- // Ajusta ícones do botão de tema
776
- OptagoUI.setTheme(document.documentElement.classList.contains('light') ? 'light' : 'dark');
777
-
778
- // Scrollspy simples: marca .op-nav-item ativo conforme a seção visível
779
- var main = document.querySelector('.op-main');
780
- var links = Array.prototype.slice.call(document.querySelectorAll('.op-sidebar .op-nav-item[href^="#"]'));
781
- if (main && links.length) {
782
- var sections = links
783
- .map(function (l) { return document.querySelector(l.getAttribute('href')); })
784
- .filter(Boolean);
785
- var onScroll = function () {
786
- var top = main.scrollTop + 120;
787
- var active = sections[0];
788
- sections.forEach(function (s) { if (s.offsetTop <= top) active = s; });
789
- links.forEach(function (l) {
790
- l.classList.toggle('is-active', active && l.getAttribute('href') === '#' + active.id);
791
- });
792
- };
793
- main.addEventListener('scroll', onScroll, { passive: true });
794
- onScroll();
795
- }
796
- }
797
-
798
- if (document.readyState === 'loading') {
799
- document.addEventListener('DOMContentLoaded', init);
800
- } else {
801
- init();
802
- }
803
-
804
- window.OptagoUI = OptagoUI;
805
- })();
1
+ /* ============================================================================
2
+ UI ÓPTAGO: Design System v1.2.4 (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.4';
55
+ OptagoUI.version = VERSION;
56
+
57
+ console.log(
58
+ '%c Óptago UI %c v' + VERSION + ' ',
59
+ 'background:#0a0a0a;color:#C0FF6B;font-weight:700;padding:3px 8px;border-radius:4px 0 0 4px;font-family:"JetBrains Mono",monospace;font-size:12px;',
60
+ 'background:#C0FF6B;color:#0a0a0a;font-weight:700;padding:3px 8px;border-radius:0 4px 4px 0;font-family:"JetBrains Mono",monospace;font-size:12px;'
61
+ );
62
+
63
+ /* --------------------------------------------------------------------------
64
+ 1. TEMA: aplicado imediatamente (antes do primeiro paint)
65
+ -------------------------------------------------------------------------- */
66
+ var THEME_KEY = 'op-theme';
67
+
68
+ // document.currentScript só é confiável em scripts síncronos (sem defer/
69
+ // async), que é exatamente como esta lib precisa ser carregada mesmo.
70
+ var THEME_DOMAIN = (function () {
71
+ var s = document.currentScript;
72
+ return (s && s.getAttribute('data-op-theme-domain')) || null;
73
+ })();
74
+
75
+ function readCookie(name) {
76
+ var m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
77
+ return m ? decodeURIComponent(m[1]) : null;
78
+ }
79
+
80
+ function writeCookie(name, value) {
81
+ var attrs = 'path=/; max-age=31536000; SameSite=Lax; domain=' + THEME_DOMAIN;
82
+ if (window.location.protocol === 'https:') attrs += '; Secure';
83
+ document.cookie = name + '=' + encodeURIComponent(value) + '; ' + attrs;
84
+ }
85
+
86
+ function currentTheme() {
87
+ var saved = (THEME_DOMAIN && readCookie(THEME_KEY)) || localStorage.getItem(THEME_KEY);
88
+ if (saved === 'light' || saved === 'dark') return saved;
89
+ return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
90
+ }
91
+
92
+ OptagoUI.setTheme = function (theme) {
93
+ document.documentElement.classList.toggle('light', theme === 'light');
94
+ localStorage.setItem(THEME_KEY, theme);
95
+ if (THEME_DOMAIN) writeCookie(THEME_KEY, theme);
96
+ document.querySelectorAll('[data-op-theme-toggle]').forEach(function (btn) {
97
+ var moon = btn.querySelector('.op-icon-moon');
98
+ var sun = btn.querySelector('.op-icon-sun');
99
+ if (moon) moon.style.display = theme === 'dark' ? 'none' : '';
100
+ if (sun) sun.style.display = theme === 'dark' ? '' : 'none';
101
+ });
102
+ };
103
+
104
+ OptagoUI.toggleTheme = function () {
105
+ OptagoUI.setTheme(document.documentElement.classList.contains('light') ? 'dark' : 'light');
106
+ };
107
+
108
+ // Sobrescreve tokens (--op-*) em runtime, ex.: OptagoUI.customize({ accent: '#FF6B00' })
109
+ // ou OptagoUI.customize({ '--op-radius': '4px' }) com o nome completo da variável.
110
+ // Útil pra marca por sistema/tenant sem precisar de um <style> próprio.
111
+ OptagoUI.customize = function (tokens) {
112
+ var root = document.documentElement.style;
113
+ Object.keys(tokens || {}).forEach(function (name) {
114
+ var prop = name.indexOf('--') === 0 ? name : '--op-' + name;
115
+ root.setProperty(prop, tokens[name]);
116
+ });
117
+ };
118
+
119
+ // Aplica já, sem esperar o DOM (evita FOUC)
120
+ document.documentElement.classList.toggle('light', currentTheme() === 'light');
121
+
122
+ // Suprime a transição de width/transform da sidebar só no carregamento
123
+ // inicial da página (evita ver ela "animando" pra fechada/aberta ao
124
+ // recarregar, já que o JS só consegue aplicar is-collapsed depois que o
125
+ // <aside class="op-sidebar"> existir no DOM - até lá a sidebar já pintou
126
+ // uma vez no estado padrão do CSS, e a troca de classe reativaria a
127
+ // transição normalmente usada pro toggle manual). Removida em init(),
128
+ // depois que o estado inicial (colapsada ou não) já foi aplicado.
129
+ document.documentElement.classList.add('op-preload');
130
+
131
+ /* --------------------------------------------------------------------------
132
+ 2. INJEÇÃO DE DEPENDÊNCIAS (Google Fonts + Phosphor Icons)
133
+ -------------------------------------------------------------------------- */
134
+ function ensureAssets() {
135
+ if (!document.getElementById('op-fonts')) {
136
+ var pre1 = document.createElement('link');
137
+ pre1.rel = 'preconnect'; pre1.href = 'https://fonts.googleapis.com';
138
+ var pre2 = document.createElement('link');
139
+ pre2.rel = 'preconnect'; pre2.href = 'https://fonts.gstatic.com'; pre2.crossOrigin = '';
140
+ var fonts = document.createElement('link');
141
+ fonts.id = 'op-fonts';
142
+ fonts.rel = 'stylesheet';
143
+ 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';
144
+ document.head.append(pre1, pre2, fonts);
145
+ }
146
+ if (!document.getElementById('op-icons') && !window.PhosphorIcons) {
147
+ var icons = document.createElement('script');
148
+ icons.id = 'op-icons';
149
+ icons.src = 'https://unpkg.com/@phosphor-icons/web';
150
+ document.head.appendChild(icons);
151
+ }
152
+ }
153
+ ensureAssets();
154
+
155
+ /* --------------------------------------------------------------------------
156
+ 3. SIDEBAR (colapsar no desktop / drawer no mobile)
157
+ -------------------------------------------------------------------------- */
158
+ var SIDEBAR_KEY = 'op-sidebar-collapsed';
159
+
160
+ function getSidebar() { return document.querySelector('.op-sidebar'); }
161
+ function getOverlay() {
162
+ var ov = document.querySelector('.op-overlay');
163
+ if (!ov) {
164
+ ov = document.createElement('div');
165
+ ov.className = 'op-overlay';
166
+ ov.addEventListener('click', OptagoUI.closeSidebarMobile);
167
+ document.body.appendChild(ov);
168
+ }
169
+ return ov;
170
+ }
171
+
172
+ OptagoUI.toggleSidebar = function () {
173
+ var sb = getSidebar();
174
+ if (!sb) return;
175
+ if (window.innerWidth < 1024) { OptagoUI.toggleSidebarMobile(); return; }
176
+ sb.classList.toggle('is-collapsed');
177
+ localStorage.setItem(SIDEBAR_KEY, sb.classList.contains('is-collapsed') ? '1' : '0');
178
+ };
179
+
180
+ OptagoUI.toggleSidebarMobile = function () {
181
+ var sb = getSidebar();
182
+ if (!sb) return;
183
+ var open = sb.classList.toggle('is-open');
184
+ getOverlay().classList.toggle('is-open', open);
185
+ };
186
+
187
+ OptagoUI.closeSidebarMobile = function () {
188
+ var sb = getSidebar();
189
+ if (sb) sb.classList.remove('is-open');
190
+ var ov = document.querySelector('.op-overlay');
191
+ if (ov) ov.classList.remove('is-open');
192
+ };
193
+
194
+ /* --------------------------------------------------------------------------
195
+ 4. TOASTS: OptagoUI.toast('Mensagem', 'success'|'error'|'warning'|'info')
196
+ -------------------------------------------------------------------------- */
197
+ var TOAST_ICONS = {
198
+ success: 'ph-check-circle',
199
+ error: 'ph-x-circle',
200
+ danger: 'ph-x-circle',
201
+ warning: 'ph-warning',
202
+ info: 'ph-info'
203
+ };
204
+
205
+ OptagoUI.toast = function (message, type, duration) {
206
+ type = type || 'info';
207
+ if (type === 'error') type = 'danger';
208
+ duration = duration || 4000;
209
+
210
+ var container = document.querySelector('.op-toast-container');
211
+ if (!container) {
212
+ container = document.createElement('div');
213
+ container.className = 'op-toast-container';
214
+ document.body.appendChild(container);
215
+ }
216
+
217
+ var toast = document.createElement('div');
218
+ toast.className = 'op-toast op-toast-' + type;
219
+ toast.setAttribute('role', 'status');
220
+ toast.innerHTML =
221
+ '<div class="op-toast-icon"><i class="ph ' + (TOAST_ICONS[type] || TOAST_ICONS.info) + '"></i></div>' +
222
+ '<span></span>' +
223
+ '<button class="op-toast-close" aria-label="Fechar"><i class="ph ph-x"></i></button>' +
224
+ '<div class="op-toast-progress"><div class="op-toast-progress-bar"></div></div>';
225
+ toast.querySelector('span').textContent = message;
226
+ container.appendChild(toast);
227
+
228
+ var bar = toast.querySelector('.op-toast-progress-bar');
229
+ var removed = false;
230
+ var timer = null;
231
+ var remaining = duration;
232
+ var startedAt = 0;
233
+
234
+ var dismiss = function () {
235
+ if (removed) return;
236
+ removed = true;
237
+ toast.classList.remove('is-visible');
238
+ setTimeout(function () { toast.remove(); }, 320);
239
+ };
240
+
241
+ // Anima a barra de largura atual até 0 ao longo de `ms`; usar
242
+ // transition (não @keyframes) permite congelar no valor exato em pause().
243
+ var run = function (ms) {
244
+ startedAt = Date.now();
245
+ timer = setTimeout(dismiss, ms);
246
+ requestAnimationFrame(function () {
247
+ bar.style.transitionDuration = ms + 'ms';
248
+ bar.style.width = '0%';
249
+ });
250
+ };
251
+
252
+ var pause = function () {
253
+ if (removed || !timer) return;
254
+ clearTimeout(timer);
255
+ timer = null;
256
+ remaining -= Date.now() - startedAt;
257
+ // Congela a barra no ponto exato em px (transition-duration 0 = sem salto).
258
+ bar.style.width = getComputedStyle(bar).width;
259
+ bar.style.transitionDuration = '0ms';
260
+ };
261
+
262
+ var resume = function () {
263
+ if (removed || timer || remaining <= 0) return;
264
+ run(remaining);
265
+ };
266
+
267
+ toast.addEventListener('mouseenter', pause);
268
+ toast.addEventListener('mouseleave', resume);
269
+ toast.addEventListener('focusin', pause);
270
+ toast.addEventListener('focusout', resume);
271
+ toast.querySelector('.op-toast-close').addEventListener('click', dismiss);
272
+
273
+ requestAnimationFrame(function () {
274
+ requestAnimationFrame(function () { toast.classList.add('is-visible'); });
275
+ });
276
+
277
+ run(duration);
278
+
279
+ return toast;
280
+ };
281
+
282
+ /* --------------------------------------------------------------------------
283
+ 5. MODAIS
284
+ -------------------------------------------------------------------------- */
285
+ OptagoUI.openModal = function (selector) {
286
+ var modal = typeof selector === 'string' ? document.querySelector(selector) : selector;
287
+ if (!modal) return;
288
+ modal.classList.remove('is-closing');
289
+ modal.classList.add('is-open');
290
+ };
291
+
292
+ OptagoUI.closeModal = function (selector) {
293
+ var modal = typeof selector === 'string' ? document.querySelector(selector) : selector;
294
+ if (!modal || !modal.classList.contains('is-open')) return;
295
+ modal.classList.add('is-closing');
296
+ setTimeout(function () {
297
+ modal.classList.remove('is-open', 'is-closing');
298
+ }, 200);
299
+ };
300
+
301
+ /* --------------------------------------------------------------------------
302
+ 5b. TABULATOR: tabela avançada com tema Óptago
303
+ Uso: OptagoUI.tabulator('#minhaTabela', { data: [...], columns: [...] })
304
+ Carrega a biblioteca (CDN) sob demanda; o CSS base do Tabulator é
305
+ inserido ANTES do ui-optago.css para que o tema personalizado
306
+ (.op-tabulator) vença na cascata.
307
+ -------------------------------------------------------------------------- */
308
+ var TABULATOR_JS = 'https://unpkg.com/tabulator-tables@6.3/dist/js/tabulator.min.js';
309
+ var TABULATOR_CSS = 'https://unpkg.com/tabulator-tables@6.3/dist/css/tabulator.min.css';
310
+
311
+ OptagoUI.tabulator = function (selector, options) {
312
+ return new Promise(function (resolve, reject) {
313
+ function build() {
314
+ var el = typeof selector === 'string' ? document.querySelector(selector) : selector;
315
+ if (!el) { reject(new Error('Tabulator: elemento não encontrado: ' + selector)); return; }
316
+ el.classList.add('op-tabulator');
317
+ resolve(new window.Tabulator(el, options || {}));
318
+ }
319
+
320
+ if (window.Tabulator) { build(); return; }
321
+
322
+ if (!document.getElementById('op-tabulator-css')) {
323
+ var css = document.createElement('link');
324
+ css.id = 'op-tabulator-css';
325
+ css.rel = 'stylesheet';
326
+ css.href = TABULATOR_CSS;
327
+ var own = document.querySelector('link[href*="ui-optago.css"]');
328
+ if (own && own.parentNode) {
329
+ own.parentNode.insertBefore(css, own);
330
+ } else {
331
+ document.head.prepend(css);
332
+ }
333
+ }
334
+
335
+ var script = document.getElementById('op-tabulator-js');
336
+ if (!script) {
337
+ script = document.createElement('script');
338
+ script.id = 'op-tabulator-js';
339
+ script.src = TABULATOR_JS;
340
+ document.head.appendChild(script);
341
+ }
342
+ script.addEventListener('load', build);
343
+ script.addEventListener('error', function () {
344
+ reject(new Error('Tabulator: falha ao carregar a biblioteca via CDN.'));
345
+ });
346
+ });
347
+ };
348
+
349
+ /* --------------------------------------------------------------------------
350
+ 5c. TOUR GUIADO (driver.js)
351
+ Carrega a biblioteca do CDN sob demanda e aplica o tema Óptago.
352
+ Uso: OptagoUI.tour(steps, options?) → Promise<instância driver>
353
+
354
+ Cada step: { element: '#seletor', popover: { title: 'Título', description: 'Texto' } }
355
+ O step sem `element` vira um modal genérico centralizado.
356
+ -------------------------------------------------------------------------- */
357
+ var DRIVER_CSS = 'https://cdn.jsdelivr.net/npm/driver.js/dist/driver.css';
358
+ var DRIVER_ESM = 'https://esm.run/driver.js';
359
+
360
+ OptagoUI.tour = function (steps, options) {
361
+ if (!document.getElementById('op-driver-css')) {
362
+ var css = document.createElement('link');
363
+ css.id = 'op-driver-css';
364
+ css.rel = 'stylesheet';
365
+ css.href = DRIVER_CSS;
366
+ // Inserido ANTES do ui-optago.css para que nosso CSS venha depois na
367
+ // cascata e vença os estilos base do driver.js com a mesma especificidade.
368
+ var ownCss = document.querySelector('link[href*="ui-optago.css"]');
369
+ if (ownCss && ownCss.parentNode) {
370
+ ownCss.parentNode.insertBefore(css, ownCss);
371
+ } else {
372
+ document.head.prepend(css);
373
+ }
374
+ }
375
+
376
+ return import(DRIVER_ESM).then(function (mod) {
377
+ var driverFn = mod.driver || mod.default;
378
+ var isLight = document.documentElement.classList.contains('light');
379
+ var defaults = {
380
+ animate: true,
381
+ smoothScroll: true,
382
+ showProgress: true,
383
+ progressText: '{{current}} de {{total}}',
384
+ nextBtnText: 'Próximo →',
385
+ prevBtnText: '← Anterior',
386
+ doneBtnText: 'Concluir',
387
+ popoverClass: 'op-tour-popover',
388
+ overlayColor: isLight ? '#0F172A' : '#000000',
389
+ overlayOpacity: isLight ? 0.5 : 0.75
390
+ };
391
+ var merged = {};
392
+ Object.keys(defaults).forEach(function (k) { merged[k] = defaults[k]; });
393
+ Object.keys(options || {}).forEach(function (k) { merged[k] = options[k]; });
394
+ merged.steps = steps;
395
+
396
+ // O conteúdo rola dentro de um container (.op-main, com scroll suave),
397
+ // não na janela. O driver.js mede o elemento ANTES desse scroll
398
+ // terminar e só reposiciona o recorte do backdrop em scroll/resize da
399
+ // janela, então o recorte ficava num lugar e o elemento em outro: ele
400
+ // parecia destacado (outline) mas continuava coberto pelo backdrop.
401
+ // Aqui o recorte é recalculado a cada scroll (captura = pega o de
402
+ // qualquer container) e a cada resize, até o tour acabar.
403
+ var d;
404
+ var agendado = false;
405
+ function reajustar() {
406
+ if (agendado) return;
407
+ agendado = true;
408
+ requestAnimationFrame(function () {
409
+ agendado = false;
410
+ try { d.refresh(); } catch (e) { /* tour já encerrado */ }
411
+ });
412
+ }
413
+ document.addEventListener('scroll', reajustar, true);
414
+ window.addEventListener('resize', reajustar);
415
+ var aoDestruir = merged.onDestroyed;
416
+ merged.onDestroyed = function () {
417
+ document.removeEventListener('scroll', reajustar, true);
418
+ window.removeEventListener('resize', reajustar);
419
+ if (typeof aoDestruir === 'function') return aoDestruir.apply(this, arguments);
420
+ };
421
+
422
+ d = driverFn(merged);
423
+ d.drive();
424
+ return d;
425
+ }).catch(function (err) {
426
+ throw new Error('driver.js: falha ao carregar via CDN. ' + (err && err.message || ''));
427
+ });
428
+ };
429
+
430
+ /* --------------------------------------------------------------------------
431
+ 5d. TELA DE CARREGAMENTO: overlay em tela cheia
432
+ Uso: OptagoUI.showLoading('Salvando...') ... OptagoUI.hideLoading()
433
+ ou data-op-loading-form no <form> para acionar sozinho no submit.
434
+ -------------------------------------------------------------------------- */
435
+ var LOADING_ID = 'opLoadingOverlay';
436
+
437
+ function getLoadingOverlay() {
438
+ var ov = document.getElementById(LOADING_ID);
439
+ if (!ov) {
440
+ ov = document.createElement('div');
441
+ ov.id = LOADING_ID;
442
+ ov.className = 'op-loading-overlay';
443
+ ov.setAttribute('role', 'alert');
444
+ ov.setAttribute('aria-live', 'assertive');
445
+ ov.innerHTML =
446
+ '<span class="op-spinner"></span>' +
447
+ '<span class="op-loading-message"></span>';
448
+ document.body.appendChild(ov);
449
+ }
450
+ return ov;
451
+ }
452
+
453
+ OptagoUI.showLoading = function (message) {
454
+ var ov = getLoadingOverlay();
455
+ ov.querySelector('.op-loading-message').textContent = message || 'Carregando...';
456
+ ov.classList.add('is-open');
457
+ requestAnimationFrame(function () {
458
+ requestAnimationFrame(function () { ov.classList.add('is-visible'); });
459
+ });
460
+ };
461
+
462
+ OptagoUI.hideLoading = function () {
463
+ var ov = document.getElementById(LOADING_ID);
464
+ if (!ov) return;
465
+ ov.classList.remove('is-visible');
466
+ setTimeout(function () { ov.classList.remove('is-open'); }, 250);
467
+ };
468
+
469
+ // Ao voltar pelo botão "Voltar" do navegador, a página pode ser restaurada
470
+ // do bfcache exatamente como estava ao sair (overlay de carregamento ainda
471
+ // visível, já que o clique/submit anterior nunca chegou a escondê-lo).
472
+ // pageshow com event.persisted=true é o sinal de que veio do bfcache.
473
+ window.addEventListener('pageshow', function (e) {
474
+ if (e.persisted) OptagoUI.hideLoading();
475
+ });
476
+
477
+ /* --------------------------------------------------------------------------
478
+ 6. HELPERS DO SHOWCASE: copiar HTML / ver código
479
+ -------------------------------------------------------------------------- */
480
+ function dedentHTML(el) {
481
+ var html = el.innerHTML.replace(/^\n+|\s+$/g, '');
482
+ var lines = html.split('\n');
483
+ var indent = Infinity;
484
+ lines.forEach(function (line) {
485
+ if (!line.trim()) return;
486
+ var m = line.match(/^\s*/);
487
+ indent = Math.min(indent, m[0].length);
488
+ });
489
+ if (!isFinite(indent)) indent = 0;
490
+ return lines.map(function (line) { return line.slice(indent); }).join('\n');
491
+ }
492
+
493
+ OptagoUI.copyHTML = function (targetSelector, feedbackBtn) {
494
+ var target = document.querySelector(targetSelector);
495
+ if (!target) return;
496
+ var html = dedentHTML(target);
497
+
498
+ var done = function () {
499
+ if (feedbackBtn) {
500
+ var original = feedbackBtn.innerHTML;
501
+ feedbackBtn.innerHTML = '<i class="ph ph-check"></i> Copiado!';
502
+ setTimeout(function () { feedbackBtn.innerHTML = original; }, 2000);
503
+ }
504
+ };
505
+
506
+ if (navigator.clipboard && navigator.clipboard.writeText) {
507
+ navigator.clipboard.writeText(html).then(done);
508
+ } else {
509
+ var ta = document.createElement('textarea');
510
+ ta.value = html;
511
+ ta.style.position = 'fixed';
512
+ ta.style.left = '-9999px';
513
+ document.body.appendChild(ta);
514
+ ta.select();
515
+ document.execCommand('copy');
516
+ ta.remove();
517
+ done();
518
+ }
519
+ };
520
+
521
+ OptagoUI.toggleCode = function (targetSelector, btn) {
522
+ var target = document.querySelector(targetSelector);
523
+ if (!target) return;
524
+ var demo = btn.closest('.op-demo') || target.parentElement;
525
+ var pre = demo.querySelector('.op-demo-code');
526
+ if (!pre) {
527
+ pre = document.createElement('pre');
528
+ pre.className = 'op-demo-code';
529
+ demo.appendChild(pre);
530
+ }
531
+ if (!pre.dataset.filled) {
532
+ pre.textContent = dedentHTML(target);
533
+ pre.dataset.filled = '1';
534
+ }
535
+ pre.classList.toggle('is-visible');
536
+ };
537
+
538
+ /* --------------------------------------------------------------------------
539
+ 7. BINDING GLOBAL via data-attributes (event delegation)
540
+ -------------------------------------------------------------------------- */
541
+
542
+ /**
543
+ * Garante que o .op-menu de um dropdown recém-aberto não vaze pra fora da
544
+ * tela nem pela esquerda nem pela direita (perto de qualquer borda do
545
+ * viewport, não só a direita como .op-menu-end resolve manualmente). Só
546
+ * ajusta a variável CSS --op-menu-shift (soma ao transform de abertura em
547
+ * vez de substituí-lo) - nunca escreve `transform` direto no elemento,
548
+ * senão atropelaria a animação de abrir/fechar já feita em CSS.
549
+ */
550
+ function posicionarMenu(dd) {
551
+ var menu = dd.querySelector('.op-menu');
552
+ if (!menu) return;
553
+
554
+ menu.style.removeProperty('--op-menu-shift');
555
+
556
+ // offsetLeft/offsetWidth são medidas de LAYOUT puras, nunca afetadas
557
+ // por transform - ao contrário de menu.getBoundingClientRect(), que
558
+ // reflete o transform da animação de abrir/fechar (scale/translateY/
559
+ // translateX) em tempo real. Numa 2ª+ abertura, uma transição CSS ainda
560
+ // ativa tem prioridade de cascata sobre QUALQUER valor (mesmo inline),
561
+ // então nem forçar transform:none temporariamente adianta: o
562
+ // getBoundingClientRect() continuava capturando o --op-menu-shift
563
+ // residual da abertura anterior, cortando o menu. Medindo via
564
+ // offsetLeft/offsetWidth (relativos ao .op-dropdown, que não anima)
565
+ // a conta fica sempre exata, em qualquer abertura, sem precisar tocar
566
+ // em transition nem em transform e sem atrapalhar a animação de
567
+ // entrada.
568
+ var ddRect = dd.getBoundingClientRect();
569
+ var left = ddRect.left + menu.offsetLeft;
570
+ var right = left + menu.offsetWidth;
571
+
572
+ var margem = 12;
573
+ var vazaDireita = right - (window.innerWidth - margem);
574
+ var vazaEsquerda = margem - left;
575
+
576
+ if (vazaDireita > 0) {
577
+ menu.style.setProperty('--op-menu-shift', (-vazaDireita) + 'px');
578
+ } else if (vazaEsquerda > 0) {
579
+ menu.style.setProperty('--op-menu-shift', vazaEsquerda + 'px');
580
+ }
581
+ }
582
+
583
+ document.addEventListener('click', function (e) {
584
+ var t;
585
+
586
+ // Tema
587
+ if (e.target.closest('[data-op-theme-toggle]')) { OptagoUI.toggleTheme(); return; }
588
+
589
+ // Sidebar
590
+ if (e.target.closest('[data-op-sidebar-toggle]')) { OptagoUI.toggleSidebar(); return; }
591
+ if (e.target.closest('[data-op-sidebar-mobile]')) { OptagoUI.toggleSidebarMobile(); return; }
592
+
593
+ // Fecha drawer mobile ao clicar em link da sidebar
594
+ if (e.target.closest('.op-sidebar .op-nav-item') && window.innerWidth < 1024) {
595
+ OptagoUI.closeSidebarMobile();
596
+ }
597
+
598
+ // Modal
599
+ t = e.target.closest('[data-op-modal-open]');
600
+ if (t) { OptagoUI.openModal(t.getAttribute('data-op-modal-open')); return; }
601
+ if (e.target.closest('[data-op-modal-close]')) {
602
+ OptagoUI.closeModal(e.target.closest('.op-modal'));
603
+ return;
604
+ }
605
+ if (e.target.classList && e.target.classList.contains('op-modal')) {
606
+ OptagoUI.closeModal(e.target); // clique no backdrop
607
+ return;
608
+ }
609
+
610
+ // Tabs
611
+ t = e.target.closest('[data-op-tab]');
612
+ if (t) {
613
+ var name = t.getAttribute('data-op-tab');
614
+ var group = t.closest('[data-op-tab-group]');
615
+ var scope = group ? '[data-op-tab-group="' + group.getAttribute('data-op-tab-group') + '"]' : '';
616
+ document.querySelectorAll(scope + ' [data-op-tab]').forEach(function (tab) {
617
+ tab.classList.toggle('is-active', tab === t);
618
+ });
619
+ document.querySelectorAll(scope + ' [data-op-tab-panel]').forEach(function (panel) {
620
+ panel.classList.toggle('is-active', panel.getAttribute('data-op-tab-panel') === name);
621
+ });
622
+ return;
623
+ }
624
+
625
+ // Dropdown
626
+ t = e.target.closest('[data-op-dropdown-toggle]');
627
+ if (t) {
628
+ var dd = t.closest('.op-dropdown');
629
+ var wasOpen = dd.classList.contains('is-open');
630
+ document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
631
+ if (!wasOpen) {
632
+ dd.classList.add('is-open');
633
+ posicionarMenu(dd);
634
+ }
635
+ return;
636
+ }
637
+ // Fecha dropdowns em clique fora
638
+ if (!e.target.closest('.op-dropdown')) {
639
+ document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
640
+ }
641
+
642
+ // Alert dismiss
643
+ t = e.target.closest('[data-op-dismiss]');
644
+ if (t) {
645
+ var box = t.closest('.op-alert') || t.parentElement;
646
+ box.style.transition = 'opacity .25s, transform .25s';
647
+ box.style.opacity = '0';
648
+ box.style.transform = 'translateX(8px)';
649
+ setTimeout(function () { box.remove(); }, 250);
650
+ return;
651
+ }
652
+
653
+ // Copiar HTML
654
+ t = e.target.closest('[data-op-copy]');
655
+ if (t) { OptagoUI.copyHTML(t.getAttribute('data-op-copy'), t); return; }
656
+
657
+ // Ver código
658
+ t = e.target.closest('[data-op-code]');
659
+ if (t) { OptagoUI.toggleCode(t.getAttribute('data-op-code'), t); return; }
660
+
661
+ // Mostrar/ocultar senha: [data-op-reveal] envolvendo o input,
662
+ // com um <button data-op-reveal-toggle> dentro.
663
+ t = e.target.closest('[data-op-reveal-toggle]');
664
+ if (t) {
665
+ var wrap = t.closest('[data-op-reveal]');
666
+ var input = wrap ? wrap.querySelector('input') : null;
667
+ if (input) {
668
+ var show = input.type === 'password';
669
+ input.type = show ? 'text' : 'password';
670
+ var icon = t.querySelector('i');
671
+ if (icon) icon.className = show ? 'ph ph-eye-slash' : 'ph ph-eye';
672
+ t.setAttribute('aria-label', show ? 'Ocultar senha' : 'Mostrar senha');
673
+ }
674
+ return;
675
+ }
676
+
677
+ // Combobox: clique numa opção seleciona; clique fora fecha.
678
+ t = e.target.closest('[data-op-combobox-option]');
679
+ if (t && !t.hasAttribute('hidden')) { selectComboboxOption(t); return; }
680
+ if (!e.target.closest('[data-op-combobox]')) {
681
+ document.querySelectorAll('.op-combobox.is-open').forEach(closeCombobox);
682
+ }
683
+ });
684
+
685
+ /* --------------------------------------------------------------------------
686
+ 7b. COMBOBOX: input com filtro de opções (autocomplete)
687
+ -------------------------------------------------------------------------- */
688
+ function comboboxOptions(box) {
689
+ var menu = box.querySelector('[data-op-combobox-menu]');
690
+ return menu ? Array.prototype.slice.call(menu.querySelectorAll('[data-op-combobox-option]')) : [];
691
+ }
692
+
693
+ function visibleComboboxOptions(box) {
694
+ return comboboxOptions(box).filter(function (o) { return !o.hasAttribute('hidden'); });
695
+ }
696
+
697
+ function openCombobox(box) {
698
+ box.classList.add('is-open');
699
+ }
700
+
701
+ function closeCombobox(box) {
702
+ box.classList.remove('is-open');
703
+ comboboxOptions(box).forEach(function (o) { o.classList.remove('is-active'); });
704
+ }
705
+
706
+ function selectComboboxOption(option) {
707
+ var box = option.closest('[data-op-combobox]');
708
+ var input = box.querySelector('[data-op-combobox-input]');
709
+ comboboxOptions(box).forEach(function (o) { o.classList.remove('is-selected'); });
710
+ option.classList.add('is-selected');
711
+ if (input) {
712
+ input.value = option.textContent.trim();
713
+ box.dataset.value = option.getAttribute('data-value') || '';
714
+ input.dispatchEvent(new Event('change', { bubbles: true }));
715
+ }
716
+ closeCombobox(box);
717
+ }
718
+
719
+ function filterCombobox(box) {
720
+ var input = box.querySelector('[data-op-combobox-input]');
721
+ var empty = box.querySelector('.op-combobox-empty');
722
+ var query = (input.value || '').trim().toLowerCase();
723
+ var anyVisible = false;
724
+ comboboxOptions(box).forEach(function (o) {
725
+ var match = o.textContent.toLowerCase().indexOf(query) !== -1;
726
+ o.toggleAttribute('hidden', !match);
727
+ o.classList.remove('is-active');
728
+ if (match) anyVisible = true;
729
+ });
730
+ if (empty) empty.hidden = anyVisible;
731
+ }
732
+
733
+ document.addEventListener('input', function (e) {
734
+ var input = e.target.closest('[data-op-combobox-input]');
735
+ if (!input) return;
736
+ var box = input.closest('[data-op-combobox]');
737
+ filterCombobox(box);
738
+ openCombobox(box);
739
+ });
740
+
741
+ document.addEventListener('focusin', function (e) {
742
+ var input = e.target.closest('[data-op-combobox-input]');
743
+ if (!input) return;
744
+ openCombobox(input.closest('[data-op-combobox]'));
745
+ });
746
+
747
+ // Tooltip da sidebar colapsada: o overflow-y da nav cortaria um tooltip
748
+ // com position:absolute, então ele usa position:fixed e o top/right é
749
+ // calculado aqui a cada hover.
750
+ document.addEventListener('mouseover', function (e) {
751
+ var item = e.target.closest('.op-sidebar.is-collapsed .op-nav-item');
752
+ if (!item) return;
753
+ var tip = item.querySelector('.op-nav-tooltip');
754
+ if (!tip) return;
755
+ var r = item.getBoundingClientRect();
756
+ tip.style.top = (r.top + r.height / 2) + 'px';
757
+ tip.style.right = (window.innerWidth - r.left + 14) + 'px';
758
+ tip.style.left = 'auto';
759
+ });
760
+
761
+ // Tooltip genérico (data-op-tip, inclusive em cima de badge): o balão é
762
+ // centralizado no gatilho por padrão (::after com left:50%+translate), o
763
+ // que vaza da tela quando o gatilho está perto da borda esquerda ou
764
+ // direita do viewport. Como ::after não é um nó real do DOM, não dá pra
765
+ // medir o balão em si com getBoundingClientRect() - a correção usa a
766
+ // largura MÁXIMA possível dele (220px, mesmo teto do CSS) como estimativa
767
+ // segura a partir da posição do próprio gatilho (esse sim mensurável),
768
+ // aplicando uma classe que alinha o balão pela ponta em vez do centro.
769
+ // A setinha (::before) não muda de classe, continua centralizada no
770
+ // gatilho e sempre aponta certo pra ele.
771
+ document.addEventListener('mouseover', function (e) {
772
+ var el = e.target.closest('[data-op-tip]');
773
+ if (!el) return;
774
+
775
+ el.classList.remove('op-tip-align-start', 'op-tip-align-end');
776
+
777
+ var rect = el.getBoundingClientRect();
778
+ var centro = rect.left + rect.width / 2;
779
+ var meiaLargura = 110; // metade do max-width de 220px do balão (ver CSS)
780
+ var margem = 8;
781
+
782
+ if (centro - meiaLargura < margem) {
783
+ el.classList.add('op-tip-align-start');
784
+ } else if (centro + meiaLargura > window.innerWidth - margem) {
785
+ el.classList.add('op-tip-align-end');
786
+ }
787
+ });
788
+
789
+ // Formulário com data-op-loading-form: mostra a tela de carregamento
790
+ // sozinho ao submeter (mensagem em data-op-loading-message, se houver).
791
+ document.addEventListener('submit', function (e) {
792
+ var form = e.target.closest('[data-op-loading-form]');
793
+ if (!form) return;
794
+ OptagoUI.showLoading(form.getAttribute('data-op-loading-message'));
795
+ });
796
+
797
+ // ESC fecha modais, dropdowns e comboboxes
798
+ document.addEventListener('keydown', function (e) {
799
+ if (e.key === 'Escape') {
800
+ document.querySelectorAll('.op-modal.is-open').forEach(function (m) { OptagoUI.closeModal(m); });
801
+ document.querySelectorAll('.op-dropdown.is-open').forEach(function (d) { d.classList.remove('is-open'); });
802
+ document.querySelectorAll('.op-combobox.is-open').forEach(closeCombobox);
803
+ OptagoUI.closeSidebarMobile();
804
+ return;
805
+ }
806
+
807
+ // Navegação por teclado dentro de um combobox aberto
808
+ var comboInput = e.target.closest('[data-op-combobox-input]');
809
+ if (!comboInput) return;
810
+ var box = comboInput.closest('[data-op-combobox]');
811
+ if (!box.classList.contains('is-open')) return;
812
+
813
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
814
+ e.preventDefault();
815
+ var opts = visibleComboboxOptions(box);
816
+ if (!opts.length) return;
817
+ var current = opts.findIndex(function (o) { return o.classList.contains('is-active'); });
818
+ var next = e.key === 'ArrowDown' ? current + 1 : current - 1;
819
+ if (next < 0) next = opts.length - 1;
820
+ if (next >= opts.length) next = 0;
821
+ opts.forEach(function (o) { o.classList.remove('is-active'); });
822
+ opts[next].classList.add('is-active');
823
+ opts[next].scrollIntoView({ block: 'nearest' });
824
+ } else if (e.key === 'Enter') {
825
+ var active = visibleComboboxOptions(box).filter(function (o) { return o.classList.contains('is-active'); })[0];
826
+ if (active) { e.preventDefault(); selectComboboxOption(active); }
827
+ }
828
+ });
829
+
830
+ /* --------------------------------------------------------------------------
831
+ 8. INICIALIZAÇÃO no DOM pronto
832
+ -------------------------------------------------------------------------- */
833
+ function init() {
834
+ // Versão exibida no badge do header e no rodapé
835
+ document.querySelectorAll('[data-op-version]').forEach(function (el) {
836
+ el.textContent = 'v' + VERSION;
837
+ });
838
+
839
+ // Toasts vindos do servidor (flash messages), sem precisar de <script>
840
+ // inline: importante para funcionar com Content-Security-Policy estrito.
841
+ // Uso: <div hidden data-op-toast='[{"type":"success","message":"Oi!"}]'></div>
842
+ document.querySelectorAll('[data-op-toast]').forEach(function (el) {
843
+ try {
844
+ var items = JSON.parse(el.getAttribute('data-op-toast'));
845
+ (Array.isArray(items) ? items : [items]).forEach(function (t) {
846
+ OptagoUI.toast(t.message, t.type, t.duration);
847
+ });
848
+ } catch (e) { /* atributo malformado: ignora silenciosamente */ }
849
+ });
850
+
851
+ // Sidebar (desktop): fechada por padrão, mas respeita a escolha do
852
+ // usuário salva no localStorage assim que ele abrir/fechar uma vez.
853
+ var sb = getSidebar();
854
+ if (sb && window.innerWidth >= 1024 && localStorage.getItem(SIDEBAR_KEY) !== '0') {
855
+ sb.classList.add('is-collapsed');
856
+ }
857
+
858
+ // Só agora, com o estado inicial da sidebar já decidido, reabilita a
859
+ // transição (ver comentário em cima de "op-preload", perto do topo do
860
+ // arquivo). offsetHeight força o navegador a aplicar/pintar o estado
861
+ // atual ANTES de tirar o "transition:none" - sem isso o toggle inicial
862
+ // e a reabilitação da transição poderiam cair no mesmo frame e a
863
+ // animação apareceria de qualquer jeito.
864
+ if (sb) { void sb.offsetHeight; }
865
+ document.documentElement.classList.remove('op-preload');
866
+
867
+ // Ajusta ícones do botão de tema
868
+ OptagoUI.setTheme(document.documentElement.classList.contains('light') ? 'light' : 'dark');
869
+
870
+ // Scrollspy simples: marca .op-nav-item ativo conforme a seção visível
871
+ var main = document.querySelector('.op-main');
872
+ var links = Array.prototype.slice.call(document.querySelectorAll('.op-sidebar .op-nav-item[href^="#"]'));
873
+ if (main && links.length) {
874
+ var sections = links
875
+ .map(function (l) { return document.querySelector(l.getAttribute('href')); })
876
+ .filter(Boolean);
877
+ var onScroll = function () {
878
+ var top = main.scrollTop + 120;
879
+ var active = sections[0];
880
+ sections.forEach(function (s) { if (s.offsetTop <= top) active = s; });
881
+ links.forEach(function (l) {
882
+ l.classList.toggle('is-active', active && l.getAttribute('href') === '#' + active.id);
883
+ });
884
+ };
885
+ main.addEventListener('scroll', onScroll, { passive: true });
886
+ onScroll();
887
+ }
888
+ }
889
+
890
+ if (document.readyState === 'loading') {
891
+ document.addEventListener('DOMContentLoaded', init);
892
+ } else {
893
+ init();
894
+ }
895
+
896
+ window.OptagoUI = OptagoUI;
897
+ })();