agentgui 1.0.821 → 1.0.822

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ ## 2026-04-11
2
+ - refactor: split conversations.js (742L→116L) into conv-sidebar-actions.js (prototype extension: drag/drop, bulk actions, folder browser), conv-list-renderer.js (loadConversations, render, vnode), conv-sidebar-clone.js (clone UI, delete-all); all ≤200 lines
3
+ - refactor: split websocket-manager.js (643L) into ws-core.js (class constructor, connect, onOpen, onMessage, reconnect), websocket-manager.js (sendMessage, subscriptions, state); ws-latency/connection/heartbeat empty stubs deleted
4
+ - refactor: split event-filter.js into event-filter.js + event-filter-config.js (window export/CSV/Markdown helpers)
5
+ - refactor: split agent-auth.js into agent-auth.js + agent-auth-oauth.js (IIFE, OAuth modal flows)
6
+ - refactor: fix index.html script load order — ws-core.js before websocket-manager.js; remove empty stub script tags (ws-connection, ws-latency, ws-heartbeat)
7
+
1
8
  ## 2026-04-11
2
9
  - refactor: split jsonl-watcher.js parse/event logic into jsonl-parser.js; watcher retains file watching/polling only
3
10
  - refactor: split tool-version.js into tool-version-check.js (sync) and tool-version-fetch.js (async/network)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentgui",
3
- "version": "1.0.821",
3
+ "version": "1.0.822",
4
4
  "description": "Multi-agent ACP client with real-time communication",
5
5
  "type": "module",
6
6
  "main": "electron/main.js",
package/static/index.html CHANGED
@@ -294,7 +294,10 @@
294
294
  <script defer src="/gm/js/terminal-machine.js"></script>
295
295
  <script defer src="/gm/js/conversations.js"></script>
296
296
  <script defer src="/gm/js/conv-sidebar-actions.js"></script>
297
+ <script defer src="/gm/js/conv-list-renderer.js"></script>
298
+ <script defer src="/gm/js/conv-sidebar-clone.js"></script>
297
299
  <script defer src="/gm/lib/msgpackr.min.js"></script>
300
+ <script defer src="/gm/js/ws-core.js"></script>
298
301
  <script defer src="/gm/js/websocket-manager.js"></script>
299
302
  <script defer src="/gm/js/ws-client.js"></script>
300
303
  <script defer src="/gm/js/syntax-highlighter.js"></script>
@@ -0,0 +1,197 @@
1
+ Object.assign(ConversationManager.prototype, {
2
+ async loadConversations() {
3
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'LOAD_START' });
4
+ try {
5
+ const base = window.__BASE_URL || '/gm';
6
+ const res = await fetch(base + '/api/conversations');
7
+ if (!res.ok) throw new Error('HTTP ' + res.status);
8
+ const data = await res.json();
9
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'LOAD_DONE', conversations: data.conversations || [] });
10
+ const cliStreaming = window.agentGuiClient?.state?.streamingConversations;
11
+ for (const conv of this.conversations) {
12
+ const streaming = conv.isStreaming === 1 || conv.isStreaming === true || (cliStreaming ? cliStreaming.has(conv.id) : false);
13
+ window.convListMachineAPI?.send({ type: streaming ? 'SET_STREAMING' : 'CLEAR_STREAMING', id: conv.id });
14
+ }
15
+ this.render();
16
+ } catch (err) {
17
+ console.error('Failed to load conversations:', err);
18
+ window.convListMachineAPI?.send({ type: 'LOAD_ERROR' });
19
+ if (this.conversations.length === 0) this.showEmpty('Failed to load conversations');
20
+ }
21
+ },
22
+
23
+ _convVnode(conv) {
24
+ const h = window.webjsx?.createElement;
25
+ if (!h) return null;
26
+ const isActive = conv.id === this.activeId;
27
+ const isStreaming = this.streamingConversations.has(conv.id);
28
+ const title = conv.title || `Conversation ${conv.id.slice(0, 8)}`;
29
+ const timestamp = conv.created_at ? new Date(conv.created_at).toLocaleDateString() : 'Unknown';
30
+ const agent = this.getAgentDisplayName(conv.agentId || conv.agentType);
31
+ const modelLabel = this.formatModelLabel(conv.model);
32
+ const wd = conv.workingDirectory ? pathBasename(conv.workingDirectory) : '';
33
+ const metaParts = [agent + modelLabel, timestamp];
34
+ if (wd) metaParts.push(wd);
35
+ const badge = isStreaming ? h('span', { class: 'conversation-streaming-badge', title: 'Streaming in progress' }, h('span', { class: 'streaming-dot' })) : null;
36
+ const dragAttrs = conv.pinned ? { draggable: 'true', 'data-drag-conv': conv.id } : {};
37
+ return h('li', { class: 'conversation-item' + (isActive ? ' active' : '') + (conv.pinned ? ' pinned' : ''), 'data-conv-id': conv.id, ...dragAttrs },
38
+ h('div', { class: 'conversation-item-content' },
39
+ h('div', { class: 'conversation-item-title' }, ...(badge ? [badge, title] : [title])),
40
+ h('div', { class: 'conversation-item-meta' }, metaParts.join(' • '))
41
+ ),
42
+ h('input', { type: 'checkbox', class: 'conversation-item-checkbox', 'data-bulk-check': conv.id, title: 'Select for bulk action', onclick: 'event.stopPropagation()' }),
43
+ h('button', { class: 'conversation-item-export', title: 'Export as markdown', 'data-export-conv': conv.id },
44
+ h('svg', { width: '14', height: '14', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2' },
45
+ h('path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }),
46
+ h('polyline', { points: '7 10 12 15 17 10' }),
47
+ h('line', { x1: '12', y1: '15', x2: '12', y2: '3' }))),
48
+ h('button', { class: 'conversation-item-archive', title: 'Archive conversation', 'data-archive-conv': conv.id },
49
+ h('svg', { width: '14', height: '14', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2' },
50
+ h('path', { d: 'M21 8v13H3V8' }), h('path', { d: 'M1 3h22v5H1z' }), h('path', { d: 'M10 12h4' }))),
51
+ h('button', { class: 'conversation-item-delete', title: 'Delete conversation', 'data-delete-conv': conv.id },
52
+ h('svg', { width: '14', height: '14', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2' },
53
+ h('polyline', { points: '3 6 5 6 21 6' }),
54
+ h('path', { d: 'M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2' })))
55
+ );
56
+ },
57
+
58
+ render() {
59
+ if (!this.listEl) return;
60
+ if (this.conversations.length === 0) { this.showEmpty(); return; }
61
+ this.emptyEl.style.display = 'none';
62
+ const sorted = [...this.conversations].sort((a, b) => new Date(b.createdAt || 0) - new Date(a.createdAt || 0));
63
+ if (window.webjsx?.applyDiff) {
64
+ window.webjsx.applyDiff(this.listEl, sorted.map(conv => this._convVnode(conv)).filter(Boolean));
65
+ } else {
66
+ this._renderFallback(sorted);
67
+ }
68
+ },
69
+
70
+ _renderFallback(sorted) {
71
+ const existingMap = {};
72
+ for (const child of Array.from(this.listEl.children)) {
73
+ if (child.dataset.convId) existingMap[child.dataset.convId] = child;
74
+ }
75
+ const frag = document.createDocumentFragment();
76
+ for (const conv of sorted) {
77
+ const el = existingMap[conv.id] || document.createElement('li');
78
+ el.className = 'conversation-item' + (conv.id === this.activeId ? ' active' : '');
79
+ el.dataset.convId = conv.id;
80
+ delete existingMap[conv.id];
81
+ frag.appendChild(el);
82
+ }
83
+ for (const orphan of Object.values(existingMap)) orphan.remove();
84
+ this.listEl.appendChild(frag);
85
+ },
86
+
87
+ async confirmDelete(convId, title) {
88
+ const confirmed = await window.UIDialog.confirm(`Delete conversation "${title || 'Untitled'}"?\n\nThis will also delete any associated Claude Code session data. This action cannot be undone.`, 'Delete Conversation');
89
+ if (!confirmed) return;
90
+ try {
91
+ await window.wsClient.rpc('conv.del', { id: convId });
92
+ this.deleteConversation(convId);
93
+ } catch (err) {
94
+ window.UIDialog.alert('Failed to delete conversation: ' + (err.message || 'Unknown error'), 'Error');
95
+ }
96
+ },
97
+
98
+ select(convId) {
99
+ const result = window.ConversationState?.selectConversation(convId, 'user_click', 1) || { success: false };
100
+ if (!result.success && result.reason !== 'already_selected') { console.error('[ConvMgr] activeId mutation rejected:', result.reason); return; }
101
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'SELECT', id: convId });
102
+ document.querySelectorAll('.conversation-item').forEach(item => item.classList.remove('active'));
103
+ const active = document.querySelector(`[data-conv-id="${convId}"]`);
104
+ if (active) active.classList.add('active');
105
+ window.dispatchEvent(new CustomEvent('conversation-selected', { detail: { conversationId: convId } }));
106
+ },
107
+
108
+ createNew() {
109
+ window.dispatchEvent(new CustomEvent('preparing-new-conversation'));
110
+ window.dispatchEvent(new CustomEvent('create-new-conversation'));
111
+ },
112
+
113
+ showEmpty(message = 'No conversations yet') {
114
+ if (!this.listEl) return;
115
+ this.listEl.innerHTML = '';
116
+ this.emptyEl.textContent = message;
117
+ this.emptyEl.style.display = 'block';
118
+ },
119
+
120
+ addConversation(conv) {
121
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'ADD', conversation: conv });
122
+ this.render();
123
+ },
124
+
125
+ updateConversation(convId, updates) {
126
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'UPDATE', conversation: Object.assign({ id: convId }, updates) });
127
+ this.render();
128
+ },
129
+
130
+ deleteConversation(convId) {
131
+ const wasActive = this.activeId === convId;
132
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'DELETE', id: convId });
133
+ if (wasActive) { window.ConversationState?.deleteConversation(convId, 1); window.dispatchEvent(new CustomEvent('conversation-deselected')); }
134
+ this.render();
135
+ },
136
+
137
+ getSelectedIds() {
138
+ return [...this.listEl.querySelectorAll('.conversation-item-checkbox:checked')].map(cb => cb.dataset.bulkCheck);
139
+ },
140
+
141
+ async bulkArchive() {
142
+ const ids = this.getSelectedIds();
143
+ if (ids.length === 0) return;
144
+ if (!await window.UIDialog?.confirm(`Archive ${ids.length} conversation(s)?`, 'Bulk Archive')) return;
145
+ const base = window.__BASE_URL || '';
146
+ for (const id of ids) {
147
+ try { await fetch(`${base}/api/conversations/${id}/archive`, { method: 'POST' }); } catch (_) {}
148
+ this.deleteConversation(id);
149
+ }
150
+ },
151
+
152
+ async bulkDelete() {
153
+ const ids = this.getSelectedIds();
154
+ if (ids.length === 0) return;
155
+ if (!await window.UIDialog?.confirm(`Permanently delete ${ids.length} conversation(s)?`, 'Bulk Delete')) return;
156
+ for (const id of ids) this.confirmDelete(id, '');
157
+ },
158
+
159
+ async exportConversation(convId) {
160
+ try {
161
+ const result = await window.wsClient.rpc('conv.export', { id: convId, format: 'markdown' });
162
+ const blob = new Blob([result.markdown], { type: 'text/markdown' });
163
+ const url = URL.createObjectURL(blob);
164
+ const a = document.createElement('a');
165
+ a.href = url; a.download = (result.title || 'conversation').replace(/[^a-zA-Z0-9_-]/g, '_') + '.md';
166
+ a.click(); URL.revokeObjectURL(url);
167
+ } catch (e) { console.error('[export] Failed:', e.message); }
168
+ },
169
+
170
+ async archiveConversation(convId) {
171
+ try {
172
+ const resp = await fetch(`${window.__BASE_URL || ''}/api/conversations/${convId}/archive`, { method: 'POST' });
173
+ if (!resp.ok) return;
174
+ this.deleteConversation(convId);
175
+ } catch (e) { console.error('[archive] Failed:', e.message); }
176
+ },
177
+
178
+ setupWebSocketListener() {
179
+ window.addEventListener('ws-message', (event) => {
180
+ const msg = event.detail;
181
+ if (msg.type === 'conversation_created') { this.addConversation(msg.conversation); }
182
+ else if (msg.type === 'conversation_updated') { this.updateConversation(msg.conversation.id, msg.conversation); }
183
+ else if (msg.type === 'conversation_deleted') { this.deleteConversation(msg.conversationId); }
184
+ else if (msg.type === 'all_conversations_deleted') {
185
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'CLEAR_ALL' });
186
+ window.ConversationState?.clear('all_deleted');
187
+ this.showEmpty('No conversations yet');
188
+ } else if (msg.type === 'streaming_start' && msg.conversationId) {
189
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'SET_STREAMING', id: msg.conversationId });
190
+ this.render();
191
+ } else if ((msg.type === 'streaming_complete' || msg.type === 'streaming_error') && msg.conversationId) {
192
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'CLEAR_STREAMING', id: msg.conversationId });
193
+ this.render();
194
+ }
195
+ });
196
+ }
197
+ });
@@ -0,0 +1,91 @@
1
+ Object.assign(ConversationManager.prototype, {
2
+ setupDeleteAllButton() {
3
+ this.deleteAllBtn = document.getElementById('deleteAllConversationsBtn');
4
+ if (!this.deleteAllBtn) return;
5
+ this.deleteAllBtn.addEventListener('click', () => this.confirmDeleteAll());
6
+ },
7
+
8
+ async confirmDeleteAll() {
9
+ if (this.conversations.length === 0) { window.UIDialog.alert('No conversations to delete', 'Information'); return; }
10
+ const confirmed = await window.UIDialog.confirm(`Delete all ${this.conversations.length} conversation(s) and associated Claude Code artifacts?\n\nThis action cannot be undone.`, 'Delete All Conversations');
11
+ if (!confirmed) return;
12
+ try {
13
+ this.deleteAllBtn.disabled = true;
14
+ await window.wsClient.rpc('conv.del.all', {});
15
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'CLEAR_ALL' });
16
+ window.ConversationState?.clear('delete_all');
17
+ window.dispatchEvent(new CustomEvent('conversation-deselected'));
18
+ this.render();
19
+ } catch (err) {
20
+ console.error('[ConversationManager] Delete all error:', err);
21
+ window.UIDialog.alert('Failed to delete all conversations: ' + (err.message || 'Unknown error'), 'Error');
22
+ } finally { this.deleteAllBtn.disabled = false; }
23
+ },
24
+
25
+ setupCloneUI() {
26
+ this.cloneBtn = document.getElementById('cloneRepoBtn');
27
+ this.cloneBar = document.getElementById('cloneInputBar');
28
+ this.cloneInput = document.getElementById('cloneRepoInput');
29
+ this.cloneGoBtn = document.getElementById('cloneGoBtn');
30
+ this.cloneCancelBtn = document.getElementById('cloneCancelBtn');
31
+ if (!this.cloneBtn || !this.cloneBar) return;
32
+ this.cloneBtn.addEventListener('click', () => this.toggleCloneBar());
33
+ this.cloneCancelBtn?.addEventListener('click', () => this.hideCloneBar());
34
+ this.cloneGoBtn?.addEventListener('click', () => this.performClone());
35
+ this.cloneInput?.addEventListener('keydown', (e) => { if (e.key === 'Enter') this.performClone(); if (e.key === 'Escape') this.hideCloneBar(); });
36
+ },
37
+
38
+ toggleCloneBar() {
39
+ if (!this.cloneBar) return;
40
+ if (this.cloneBar.style.display !== 'none') { this.hideCloneBar(); return; }
41
+ this.cloneBar.style.display = 'flex';
42
+ this.cloneInput.value = '';
43
+ this.cloneInput.focus();
44
+ this.removeCloneStatus();
45
+ },
46
+
47
+ hideCloneBar() {
48
+ if (this.cloneBar) this.cloneBar.style.display = 'none';
49
+ this.removeCloneStatus();
50
+ },
51
+
52
+ removeCloneStatus() {
53
+ const existing = this.sidebarEl?.querySelector('.clone-status');
54
+ if (existing) existing.remove();
55
+ },
56
+
57
+ showCloneStatus(message, type) {
58
+ this.removeCloneStatus();
59
+ const statusEl = document.createElement('div');
60
+ statusEl.className = `clone-status ${type}`;
61
+ statusEl.textContent = message;
62
+ if (this.cloneBar && this.cloneBar.parentNode) this.cloneBar.parentNode.insertBefore(statusEl, this.cloneBar.nextSibling);
63
+ if (type === 'clone-success' || type === 'clone-error') setTimeout(() => statusEl.remove(), 5000);
64
+ },
65
+
66
+ async performClone() {
67
+ const repo = (this.cloneInput?.value || '').trim();
68
+ if (!repo) return;
69
+ if (!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo)) { this.showCloneStatus('Invalid format. Use org/repo', 'clone-error'); return; }
70
+ this.cloneGoBtn.disabled = true;
71
+ this.cloneInput.disabled = true;
72
+ this.showCloneStatus(`Cloning ${repo}...`, 'cloning');
73
+ try {
74
+ const data = await window.wsClient.rpc('clone', { repo });
75
+ this.showCloneStatus(`Cloned ${data.name}`, 'clone-success');
76
+ this.hideCloneBar();
77
+ window.dispatchEvent(new CustomEvent('create-new-conversation', { detail: { workingDirectory: data.path, title: data.name } }));
78
+ } catch (err) {
79
+ this.showCloneStatus(err.message || 'Clone failed', 'clone-error');
80
+ } finally {
81
+ if (this.cloneGoBtn) this.cloneGoBtn.disabled = false;
82
+ if (this.cloneInput) this.cloneInput.disabled = false;
83
+ }
84
+ }
85
+ });
86
+
87
+ if (document.readyState === 'loading') {
88
+ document.addEventListener('DOMContentLoaded', () => { window.conversationManager = new ConversationManager(); });
89
+ } else {
90
+ window.conversationManager = new ConversationManager();
91
+ }
@@ -113,3 +113,4 @@ class ConversationManager {
113
113
  return window._escHtml(text);
114
114
  }
115
115
  }
116
+
@@ -1,187 +1,88 @@
1
-
2
- class UIComponents {
3
- static createModal(config = {}) {
4
- const {
5
- title = 'Dialog',
6
- content = '',
7
- buttons = [],
8
- onClose = null,
9
- size = 'medium'
10
- } = config;
11
-
12
- const modal = document.createElement('div');
13
- modal.className = 'modal-overlay';
14
- modal.dataset.modal = 'true';
15
-
16
- const sizeClasses = {
17
- 'small': 'max-w-sm',
18
- 'medium': 'max-w-md',
19
- 'large': 'max-w-2xl'
20
- };
21
-
22
- modal.innerHTML = `
23
- <div class="modal-content card ${sizeClasses[size] || sizeClasses['medium']}">
24
- <div class="card-header flex justify-between items-center">
25
- <h2 class="text-xl font-bold">${UIComponents.escapeHtml(title)}</h2>
26
- <button class="btn btn-ghost btn-sm modal-close">&times;</button>
27
- </div>
28
- <div class="card-body modal-body">
29
- ${typeof content === 'string' ? UIComponents.escapeHtml(content) : ''}
30
- </div>
31
- <div class="card-footer flex gap-2 justify-end">
32
- ${buttons.map(btn => `
33
- <button class="btn btn-${btn.variant || 'secondary'}" data-action="${btn.action || 'close'}">
34
- ${UIComponents.escapeHtml(btn.label)}
35
- </button>
36
- `).join('')}
37
- </div>
38
- </div>
39
- `;
40
-
41
- const closeBtn = modal.querySelector('.modal-close');
42
- closeBtn.addEventListener('click', () => {
43
- modal.remove();
44
- if (onClose) onClose();
45
- });
46
-
47
- modal.querySelectorAll('[data-action]').forEach(btn => {
48
- btn.addEventListener('click', (e) => {
49
- const action = e.target.dataset.action;
50
- if (action === 'close') {
51
- modal.remove();
52
- if (onClose) onClose();
53
- }
54
- });
55
- });
56
-
57
- modal.addEventListener('click', (e) => {
58
- if (e.target === modal) {
59
- modal.remove();
60
- if (onClose) onClose();
61
- }
62
- });
63
-
64
- return modal;
65
- }
66
-
67
- static createTabs(config = {}) {
68
- const {
69
- tabs = [],
70
- activeTab = 0,
71
- onChange = null
72
- } = config;
73
-
74
- const container = document.createElement('div');
75
- container.className = 'tabs';
76
-
77
- const tabButtons = document.createElement('div');
78
- tabButtons.className = 'tab-buttons flex border-b';
79
-
80
- tabs.forEach((tab, index) => {
81
- const btn = document.createElement('button');
82
- btn.className = `tab tab-underline tab-button ${index === activeTab ? 'tab-active' : ''}`;
83
- btn.textContent = tab.label;
84
- btn.dataset.tabIndex = index;
85
-
86
- btn.addEventListener('click', () => {
87
- tabButtons.querySelectorAll('.tab-button').forEach((b, i) => {
88
- if (i === index) {
89
- b.classList.add('tab-active');
90
- } else {
91
- b.classList.remove('tab-active');
92
- }
93
- });
94
-
95
- tabContent.querySelectorAll('.tab-pane').forEach((pane, i) => {
96
- pane.style.display = i === index ? 'block' : 'none';
97
- });
98
-
99
- if (onChange) onChange(index);
100
- });
101
-
102
- tabButtons.appendChild(btn);
103
- });
104
-
105
- container.appendChild(tabButtons);
106
-
107
- const tabContent = document.createElement('div');
108
- tabContent.className = 'tab-content mt-4';
109
-
110
- tabs.forEach((tab, index) => {
111
- const pane = document.createElement('div');
112
- pane.className = 'tab-pane';
113
- pane.style.display = index === activeTab ? 'block' : 'none';
114
- pane.innerHTML = typeof tab.content === 'string' ? tab.content : '';
115
- tabContent.appendChild(pane);
116
- });
117
-
118
- container.appendChild(tabContent);
119
- return container;
120
- }
121
-
122
- static createAlert(config = {}) {
123
- const {
124
- message = '',
125
- type = 'info',
126
- duration = 5000,
127
- dismissible = true
128
- } = config;
129
-
130
- const alert = document.createElement('div');
131
- const typeClasses = {
132
- 'info': 'alert-info',
133
- 'success': 'alert-success',
134
- 'warning': 'alert-warning',
135
- 'error': 'alert-error'
136
- };
137
-
138
- alert.className = `alert ${typeClasses[type] || typeClasses['info']}`;
139
- alert.innerHTML = `
140
- <div class="flex justify-between items-center">
141
- <span>${UIComponents.escapeHtml(message)}</span>
142
- ${dismissible ? '<button class="text-current hover:opacity-75">&times;</button>' : ''}
143
- </div>
144
- `;
145
-
146
- if (dismissible) {
147
- const closeBtn = alert.querySelector('button');
148
- closeBtn.addEventListener('click', () => alert.remove());
149
- }
150
-
151
- if (duration > 0) {
152
- setTimeout(() => alert.remove(), duration);
153
- }
154
-
155
- return alert;
156
- }
157
-
158
- static createSpinner(config = {}) {
159
- const {
160
- size = 'medium',
161
- text = 'Loading...'
162
- } = config;
163
-
164
- const sizeClasses = {
165
- 'small': 'spinner-xs',
166
- 'medium': 'spinner-sm',
167
- 'large': 'spinner-md'
168
- };
169
-
170
- const container = document.createElement('div');
171
- container.className = 'flex items-center gap-3 justify-center p-4';
172
- container.innerHTML = `
173
- <div class="spinner-simple spinner-primary ${sizeClasses[size] || sizeClasses['medium']}"></div>
174
- <span class="text-base-content">${UIComponents.escapeHtml(text)}</span>
175
- `;
176
- return container;
177
- }
178
-
179
- static escapeHtml(text) {
180
- return window._escHtml(text);
181
- }
182
-
183
- }
184
-
185
- if (typeof module !== 'undefined' && module.exports) {
186
- module.exports = UIComponents;
187
- }
1
+ class UIComponents {
2
+ static createModal(config = {}) {
3
+ const { title = 'Dialog', content = '', buttons = [], onClose = null, size = 'medium' } = config;
4
+ const modal = document.createElement('div');
5
+ modal.className = 'modal-overlay';
6
+ modal.dataset.modal = 'true';
7
+ const sizeClasses = { 'small': 'max-w-sm', 'medium': 'max-w-md', 'large': 'max-w-2xl' };
8
+ modal.innerHTML = `<div class="modal-content card ${sizeClasses[size] || sizeClasses['medium']}"><div class="card-header flex justify-between items-center"><h2 class="text-xl font-bold">${UIComponents.escapeHtml(title)}</h2><button class="btn btn-ghost btn-sm modal-close">&times;</button></div><div class="card-body modal-body">${typeof content === 'string' ? UIComponents.escapeHtml(content) : ''}</div><div class="card-footer flex gap-2 justify-end">${buttons.map(btn => `<button class="btn btn-${btn.variant || 'secondary'}" data-action="${btn.action || 'close'}">${UIComponents.escapeHtml(btn.label)}</button>`).join('')}</div></div>`;
9
+ const closeBtn = modal.querySelector('.modal-close');
10
+ closeBtn.addEventListener('click', () => { modal.remove(); if (onClose) onClose(); });
11
+ modal.querySelectorAll('[data-action]').forEach(btn => {
12
+ btn.addEventListener('click', (e) => { const action = e.target.dataset.action; if (action === 'close') { modal.remove(); if (onClose) onClose(); } });
13
+ });
14
+ modal.addEventListener('click', (e) => { if (e.target === modal) { modal.remove(); if (onClose) onClose(); } });
15
+ return modal;
16
+ }
17
+
18
+ static createTabs(config = {}) {
19
+ const { tabs = [], activeTab = 0, onChange = null } = config;
20
+ const container = document.createElement('div');
21
+ container.className = 'tabs';
22
+ const tabButtons = document.createElement('div');
23
+ tabButtons.className = 'tab-buttons flex border-b';
24
+ const tabContent = document.createElement('div');
25
+ tabContent.className = 'tab-content mt-4';
26
+ tabs.forEach((tab, index) => {
27
+ const btn = document.createElement('button');
28
+ btn.className = `tab tab-underline tab-button ${index === activeTab ? 'tab-active' : ''}`;
29
+ btn.textContent = tab.label;
30
+ btn.dataset.tabIndex = index;
31
+ btn.addEventListener('click', () => {
32
+ tabButtons.querySelectorAll('.tab-button').forEach((b, i) => b.classList.toggle('tab-active', i === index));
33
+ tabContent.querySelectorAll('.tab-pane').forEach((pane, i) => { pane.style.display = i === index ? 'block' : 'none'; });
34
+ if (onChange) onChange(index);
35
+ });
36
+ tabButtons.appendChild(btn);
37
+ const pane = document.createElement('div');
38
+ pane.className = 'tab-pane';
39
+ pane.style.display = index === activeTab ? 'block' : 'none';
40
+ pane.innerHTML = typeof tab.content === 'string' ? tab.content : '';
41
+ tabContent.appendChild(pane);
42
+ });
43
+ container.appendChild(tabButtons);
44
+ container.appendChild(tabContent);
45
+ return container;
46
+ }
47
+
48
+ static createAlert(config = {}) {
49
+ const { message = '', type = 'info', duration = 5000, dismissible = true } = config;
50
+ const alert = document.createElement('div');
51
+ const typeClasses = { 'info': 'alert-info', 'success': 'alert-success', 'warning': 'alert-warning', 'error': 'alert-error' };
52
+ alert.className = `alert ${typeClasses[type] || typeClasses['info']}`;
53
+ alert.innerHTML = `<div class="flex justify-between items-center"><span>${UIComponents.escapeHtml(message)}</span>${dismissible ? '<button class="text-current hover:opacity-75">&times;</button>' : ''}</div>`;
54
+ if (dismissible) alert.querySelector('button').addEventListener('click', () => alert.remove());
55
+ if (duration > 0) setTimeout(() => alert.remove(), duration);
56
+ return alert;
57
+ }
58
+
59
+ static createSpinner(config = {}) {
60
+ const { size = 'medium', text = 'Loading...' } = config;
61
+ const sizeClasses = { 'small': 'spinner-xs', 'medium': 'spinner-sm', 'large': 'spinner-md' };
62
+ const container = document.createElement('div');
63
+ container.className = 'flex items-center gap-3 justify-center p-4';
64
+ container.innerHTML = `<div class="spinner-simple spinner-primary ${sizeClasses[size] || sizeClasses['medium']}"></div><span class="text-base-content">${UIComponents.escapeHtml(text)}</span>`;
65
+ return container;
66
+ }
67
+
68
+ static createProgressBar(config = {}) {
69
+ const { percentage = 0, label = '', showLabel = true } = config;
70
+ const container = document.createElement('div');
71
+ container.className = 'progress-container';
72
+ let html = '';
73
+ if (label && showLabel) html += `<div class="flex justify-between mb-2 text-sm"><span>${UIComponents.escapeHtml(label)}</span><span>${Math.round(percentage)}%</span></div>`;
74
+ html += `<progress class="progress progress-primary progress-xs w-full" value="${Math.min(100, Math.max(0, percentage))}" max="100"></progress>`;
75
+ container.innerHTML = html;
76
+ return container;
77
+ }
78
+
79
+ static createCollapsible(config = {}) {
80
+ const { title = 'Details', content = '', isOpen = false } = config;
81
+ const container = document.createElement('div');
82
+ container.className = 'collapsible';
83
+ container.innerHTML = `<details ${isOpen ? 'open' : ''}><summary class="cursor-pointer font-semibold hover:bg-base-200 px-2 py-1 rounded transition-colors">${UIComponents.escapeHtml(title)}</summary><div class="content mt-2 ml-4">${typeof content === 'string' ? content : ''}</div></details>`;
84
+ return container;
85
+ }
86
+ }
87
+
88
+ if (typeof module !== 'undefined' && module.exports) module.exports = UIComponents;