trackops 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ui/js/theme.js ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * theme.js — Gestor de tema claro / oscuro
3
+ * Persiste en localStorage. Si no hay preferencia guardada, usa tema claro.
4
+ */
5
+
6
+ const STORAGE_KEY = 'trackops-theme';
7
+ const THEMES = { dark: 'dark', light: 'light' };
8
+
9
+ /** Inicializa el tema aplicando el guardado o el preferido por el sistema */
10
+ export function init() {
11
+ const saved = localStorage.getItem(STORAGE_KEY);
12
+ apply(saved || THEMES.light, false);
13
+ }
14
+
15
+ /** Aplica un tema
16
+ * @param {'dark'|'light'} theme
17
+ * @param {boolean} [save=true] - persistir en localStorage
18
+ */
19
+ export function apply(theme, save = true) {
20
+ const root = document.documentElement;
21
+
22
+ if (theme === THEMES.light) {
23
+ root.setAttribute('data-theme', 'light');
24
+ } else {
25
+ root.removeAttribute('data-theme');
26
+ }
27
+
28
+ if (save) {
29
+ localStorage.setItem(STORAGE_KEY, theme);
30
+ }
31
+
32
+ // Actualizar icono del botón del topbar
33
+ _updateButton(theme);
34
+ }
35
+
36
+ /** Alterna entre claro y oscuro */
37
+ export function toggle() {
38
+ const current = document.documentElement.getAttribute('data-theme') === 'light'
39
+ ? THEMES.light
40
+ : THEMES.dark;
41
+ apply(current === THEMES.light ? THEMES.dark : THEMES.light);
42
+ }
43
+
44
+ /** Obtiene el tema activo */
45
+ export function current() {
46
+ return document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
47
+ }
48
+
49
+ /** Renderiza el botón toggle para el topbar */
50
+ export function renderButton() {
51
+ const isDark = current() === 'dark';
52
+ return `
53
+ <button
54
+ class="btn btn-ghost btn-sm btn-icon theme-toggle"
55
+ id="theme-toggle-btn"
56
+ type="button"
57
+ aria-label="${isDark ? 'Cambiar a tema claro' : 'Cambiar a tema oscuro'}"
58
+ title="${isDark ? 'Tema claro' : 'Tema oscuro'}"
59
+ >
60
+ ${isDark ? _iconSun() : _iconMoon()}
61
+ </button>
62
+ `;
63
+ }
64
+
65
+ /** Vincula el botón toggle (llamar tras renderizar el topbar) */
66
+ export function bindButton() {
67
+ const btn = document.getElementById('theme-toggle-btn');
68
+ btn?.addEventListener('click', toggle);
69
+ }
70
+
71
+ // ─────────────────────────────── PRIVADO ────────────────────────────────────
72
+
73
+ function _updateButton(theme) {
74
+ const btn = document.getElementById('theme-toggle-btn');
75
+ if (!btn) return;
76
+ const isDark = theme === 'dark';
77
+ btn.setAttribute('aria-label', isDark ? 'Cambiar a tema claro' : 'Cambiar a tema oscuro');
78
+ btn.setAttribute('title', isDark ? 'Tema claro' : 'Tema oscuro');
79
+ btn.innerHTML = isDark ? _iconSun() : _iconMoon();
80
+ }
81
+
82
+ function _iconSun() {
83
+ return `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
84
+ <circle cx="12" cy="12" r="5"/>
85
+ <line x1="12" y1="1" x2="12" y2="3"/>
86
+ <line x1="12" y1="21" x2="12" y2="23"/>
87
+ <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
88
+ <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
89
+ <line x1="1" y1="12" x2="3" y2="12"/>
90
+ <line x1="21" y1="12" x2="23" y2="12"/>
91
+ <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
92
+ <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
93
+ </svg>`;
94
+ }
95
+
96
+ function _iconMoon() {
97
+ return `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
98
+ <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
99
+ </svg>`;
100
+ }
@@ -0,0 +1,248 @@
1
+ /**
2
+ * time-tracker.js — Cronómetro de tiempo por tarea
3
+ * Integración con la API de time tracking del backend.
4
+ */
5
+
6
+ import * as state from './state.js';
7
+ import * as api from './api.js';
8
+ import { formatDuration } from './utils.js';
9
+ import { flash } from './views/flash.js';
10
+
11
+ let _interval = null;
12
+ let _startMs = null;
13
+
14
+ // ─────────────────────────────── PÚBLICO ────────────────────────────────────
15
+
16
+ /**
17
+ * Inicia el timer para una tarea
18
+ * @param {string} taskId
19
+ * @param {string} taskTitle
20
+ */
21
+ export async function start(taskId, taskTitle) {
22
+ // Si hay uno en curso, detenerlo primero
23
+ if (state.get('activeEntry')) {
24
+ await stop();
25
+ }
26
+
27
+ try {
28
+ const result = await api.startTimeEntry(taskId, taskTitle);
29
+ const entry = {
30
+ id: result.entry?.id || `local-${Date.now()}`,
31
+ taskId,
32
+ taskTitle,
33
+ startedAt: result.entry?.startedAt || new Date().toISOString(),
34
+ };
35
+ state.update('activeEntry', entry);
36
+ _startMs = Date.now() - (result.entry?.elapsedMs || 0);
37
+ _startInterval();
38
+ _updateTopbarTimer();
39
+ flash(`Timer iniciado: ${taskTitle}`, 'success');
40
+ } catch (err) {
41
+ // Fallback local si el backend no tiene el endpoint todavía
42
+ const entry = {
43
+ id: `local-${Date.now()}`,
44
+ taskId,
45
+ taskTitle,
46
+ startedAt: new Date().toISOString(),
47
+ };
48
+ state.update('activeEntry', entry);
49
+ _startMs = Date.now();
50
+ _startInterval();
51
+ _updateTopbarTimer();
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Pausa el timer (detiene el interval pero conserva el entry)
57
+ */
58
+ export function pause() {
59
+ _stopInterval();
60
+ _updateTopbarTimer();
61
+ }
62
+
63
+ /**
64
+ * Reanuda el timer
65
+ */
66
+ export function resume() {
67
+ if (!state.get('activeEntry')) return;
68
+ _startInterval();
69
+ _updateTopbarTimer();
70
+ }
71
+
72
+ /**
73
+ * Detiene el timer y persiste en el backend
74
+ */
75
+ export async function stop() {
76
+ const entry = state.get('activeEntry');
77
+ if (!entry) return;
78
+
79
+ _stopInterval();
80
+ const elapsed = _startMs ? Date.now() - _startMs : 0;
81
+
82
+ try {
83
+ const result = await api.stopTimeEntry(entry.id);
84
+ const timeEntries = state.get('timeEntries');
85
+ timeEntries.unshift({
86
+ ...entry,
87
+ stoppedAt: new Date().toISOString(),
88
+ durationMs: result.entry?.durationMs || elapsed,
89
+ });
90
+ state.update('timeEntries', timeEntries.slice(0, 50)); // Máximo 50 entries
91
+ } catch {
92
+ // Guardar localmente si el backend no está disponible
93
+ const timeEntries = state.get('timeEntries');
94
+ timeEntries.unshift({
95
+ ...entry,
96
+ stoppedAt: new Date().toISOString(),
97
+ durationMs: elapsed,
98
+ });
99
+ state.update('timeEntries', timeEntries.slice(0, 50));
100
+ }
101
+
102
+ state.update('activeEntry', null);
103
+ _startMs = null;
104
+ _updateTopbarTimer();
105
+ }
106
+
107
+ /**
108
+ * Obtiene el tiempo transcurrido actual en ms
109
+ */
110
+ export function getElapsed() {
111
+ if (!state.get('activeEntry') || !_startMs) return 0;
112
+ return Date.now() - _startMs;
113
+ }
114
+
115
+ /**
116
+ * Obtiene el total de tiempo registrado para una tarea (en ms)
117
+ * @param {string} taskId
118
+ */
119
+ export function getTotalForTask(taskId) {
120
+ return state.get('timeEntries')
121
+ .filter(e => e.taskId === taskId)
122
+ .reduce((acc, e) => acc + (e.durationMs || 0), 0);
123
+ }
124
+
125
+ /**
126
+ * Carga los time entries del backend
127
+ */
128
+ export async function loadEntries() {
129
+ try {
130
+ const result = await api.getTimeEntries();
131
+ state.update('timeEntries', result.entries || []);
132
+ } catch {
133
+ // Si el endpoint no existe aún, usar array vacío
134
+ state.update('timeEntries', []);
135
+ }
136
+ }
137
+
138
+ // ─────────────────────────────── PRIVADO ────────────────────────────────────
139
+
140
+ function _startInterval() {
141
+ _stopInterval();
142
+ _interval = setInterval(() => {
143
+ _updateTimerDisplays();
144
+ }, 1000);
145
+ }
146
+
147
+ function _stopInterval() {
148
+ if (_interval) {
149
+ clearInterval(_interval);
150
+ _interval = null;
151
+ }
152
+ state.update('timerInterval', null);
153
+ }
154
+
155
+ function _updateTimerDisplays() {
156
+ const elapsed = getElapsed();
157
+ const formatted = formatDuration(elapsed);
158
+
159
+ // Topbar timer
160
+ const topbarDisplay = document.getElementById('topbar-timer-display');
161
+ if (topbarDisplay) topbarDisplay.textContent = formatted;
162
+
163
+ // Widget grande (si está visible en Overview)
164
+ const bigDisplay = document.querySelector('.timer-display');
165
+ if (bigDisplay) bigDisplay.textContent = formatted;
166
+ }
167
+
168
+ function _updateTopbarTimer() {
169
+ const entry = state.get('activeEntry');
170
+ const topbarTimer = document.getElementById('topbar-timer');
171
+ if (!topbarTimer) return;
172
+
173
+ if (entry) {
174
+ topbarTimer.classList.add('is-running');
175
+ const dot = topbarTimer.querySelector('.topbar-timer-dot');
176
+ const display = document.getElementById('topbar-timer-display');
177
+ if (display) display.textContent = formatDuration(getElapsed());
178
+ } else {
179
+ topbarTimer.classList.remove('is-running');
180
+ const display = document.getElementById('topbar-timer-display');
181
+ if (display) display.textContent = '00:00:00';
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Renderiza el widget grande del timer (para overview.js)
187
+ * @param {string|null} taskId - tarea preseleccionada
188
+ * @returns {string} HTML
189
+ */
190
+ export function renderWidget(taskId = null) {
191
+ const entry = state.get('activeEntry');
192
+ const isRunning = !!entry && (!taskId || entry.taskId === taskId);
193
+ const elapsed = isRunning ? getElapsed() : 0;
194
+ const totalMs = taskId ? getTotalForTask(taskId) : 0;
195
+
196
+ const taskTitle = entry?.taskTitle || 'Sin tarea seleccionada';
197
+
198
+ return `
199
+ <div class="time-tracker-card" id="time-tracker-widget">
200
+ <div class="section-header" style="margin-bottom:var(--space-2)">
201
+ <div class="section-header-left">
202
+ <p class="eyebrow">Time Tracker</p>
203
+ </div>
204
+ </div>
205
+
206
+ <p class="timer-task-name" id="timer-task-name">${isRunning ? taskTitle : (taskId ? 'Clic en Iniciar para comenzar' : 'Selecciona una tarea en el board')}</p>
207
+
208
+ <div class="timer-display ${isRunning ? 'is-running' : ''}" id="timer-display">
209
+ ${formatDuration(elapsed)}
210
+ </div>
211
+
212
+ <div class="timer-controls">
213
+ ${isRunning ? `
214
+ <button class="timer-btn timer-btn-stop" id="timer-stop" type="button" aria-label="Detener timer" title="Detener">
215
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
216
+ </button>
217
+ <button class="timer-btn timer-btn-pause timer-btn-play" id="timer-pause" type="button" aria-label="Pausar timer" title="Pausar">
218
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
219
+ </button>
220
+ ` : `
221
+ <button class="timer-btn timer-btn-play" id="timer-play" type="button" aria-label="Iniciar timer" title="Iniciar" ${!taskId ? 'disabled' : ''}>
222
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>
223
+ </button>
224
+ `}
225
+ </div>
226
+
227
+ ${totalMs > 0 ? `<p class="timer-total">Total registrado: <strong>${formatDuration(totalMs)}</strong></p>` : ''}
228
+ </div>
229
+ `;
230
+ }
231
+
232
+ /**
233
+ * Vincula los eventos del widget del timer al DOM
234
+ * @param {string|null} taskId
235
+ * @param {string|null} taskTitle
236
+ */
237
+ export function bindWidget(taskId, taskTitle) {
238
+ const playBtn = document.getElementById('timer-play');
239
+ const pauseBtn = document.getElementById('timer-pause');
240
+ const stopBtn = document.getElementById('timer-stop');
241
+
242
+ playBtn?.addEventListener('click', () => start(taskId, taskTitle));
243
+ pauseBtn?.addEventListener('click', () => {
244
+ if (_interval) pause();
245
+ else resume();
246
+ });
247
+ stopBtn?.addEventListener('click', stop);
248
+ }
package/ui/js/utils.js ADDED
@@ -0,0 +1,172 @@
1
+ /**
2
+ * utils.js — Funciones de utilidad globales
3
+ */
4
+
5
+ /**
6
+ * Escapa caracteres HTML para prevenir XSS
7
+ * @param {*} value
8
+ * @returns {string}
9
+ */
10
+ export function esc(value) {
11
+ return String(value ?? '')
12
+ .replace(/&/g, '&amp;')
13
+ .replace(/</g, '&lt;')
14
+ .replace(/>/g, '&gt;')
15
+ .replace(/"/g, '&quot;')
16
+ .replace(/'/g, '&#39;');
17
+ }
18
+
19
+ /**
20
+ * Formatea una fecha ISO a formato legible según locale
21
+ * @param {string} value - ISO date string
22
+ * @param {'date'|'datetime'|'time'} style
23
+ * @returns {string}
24
+ */
25
+ export function formatDate(value, style = 'datetime') {
26
+ if (!value) return '—';
27
+ try {
28
+ const date = new Date(value);
29
+ if (isNaN(date.getTime())) return value;
30
+ if (style === 'date') {
31
+ return new Intl.DateTimeFormat('es-ES', { dateStyle: 'medium' }).format(date);
32
+ }
33
+ if (style === 'time') {
34
+ return new Intl.DateTimeFormat('es-ES', { timeStyle: 'short' }).format(date);
35
+ }
36
+ return new Intl.DateTimeFormat('es-ES', { dateStyle: 'medium', timeStyle: 'short' }).format(date);
37
+ } catch {
38
+ return value;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Formatea duración en ms a HH:MM:SS
44
+ * @param {number} ms - milisegundos
45
+ * @returns {string}
46
+ */
47
+ export function formatDuration(ms) {
48
+ if (!ms || ms < 0) return '00:00:00';
49
+ const totalSeconds = Math.floor(ms / 1000);
50
+ const hours = Math.floor(totalSeconds / 3600);
51
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
52
+ const seconds = totalSeconds % 60;
53
+ return [hours, minutes, seconds]
54
+ .map(n => String(n).padStart(2, '0'))
55
+ .join(':');
56
+ }
57
+
58
+ /**
59
+ * Formatea duración en ms a string legible (ej: "2h 15m")
60
+ * @param {number} ms
61
+ * @returns {string}
62
+ */
63
+ export function formatDurationShort(ms) {
64
+ if (!ms || ms < 0) return '0m';
65
+ const totalMinutes = Math.floor(ms / 60000);
66
+ const hours = Math.floor(totalMinutes / 60);
67
+ const minutes = totalMinutes % 60;
68
+ if (hours === 0) return `${minutes}m`;
69
+ if (minutes === 0) return `${hours}h`;
70
+ return `${hours}h ${minutes}m`;
71
+ }
72
+
73
+ /**
74
+ * Debounce: retrasa la ejecución de una función hasta que deja de llamarse
75
+ * @param {Function} fn
76
+ * @param {number} wait - ms
77
+ * @returns {Function}
78
+ */
79
+ export function debounce(fn, wait = 250) {
80
+ let timer;
81
+ return (...args) => {
82
+ clearTimeout(timer);
83
+ timer = setTimeout(() => fn(...args), wait);
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Genera array de los últimos N días (YYYY-MM-DD)
89
+ * @param {number} count
90
+ * @returns {string[]}
91
+ */
92
+ export function lastDays(count = 10) {
93
+ return Array.from({ length: count }, (_, i) => {
94
+ const d = new Date();
95
+ d.setDate(d.getDate() - (count - i - 1));
96
+ return d.toISOString().slice(0, 10);
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Divide un string multilínea o separado por comas en array de strings
102
+ * @param {string} value
103
+ * @returns {string[]}
104
+ */
105
+ export function splitLines(value) {
106
+ return String(value || '')
107
+ .split(/\r?\n|,/)
108
+ .map(s => s.trim())
109
+ .filter(Boolean);
110
+ }
111
+
112
+ /**
113
+ * Slugifica un string (minúsculas, sin acentos, sin caracteres especiales)
114
+ * @param {string} value
115
+ * @returns {string}
116
+ */
117
+ export function slugify(value) {
118
+ return String(value || '')
119
+ .normalize('NFD')
120
+ .replace(/[\u0300-\u036f]/g, '')
121
+ .toLowerCase()
122
+ .replace(/[^a-z0-9]+/g, '-')
123
+ .replace(/^-+|-+$/g, '')
124
+ .slice(0, 48);
125
+ }
126
+
127
+ /**
128
+ * Extrae el historial de todas las tareas ordenado desc por fecha
129
+ * @param {Array} tasks
130
+ * @returns {Array}
131
+ */
132
+ export function extractHistory(tasks) {
133
+ return (tasks || [])
134
+ .flatMap(t => (t.history || []).map(e => ({ ...e, taskId: t.id, taskTitle: t.title })))
135
+ .sort((a, b) => (a.at < b.at ? 1 : -1));
136
+ }
137
+
138
+ /**
139
+ * Genera un número de color consistente desde un string
140
+ * @param {string} str
141
+ * @returns {string} hsl color
142
+ */
143
+ export function stringToColor(str) {
144
+ let hash = 0;
145
+ for (const ch of (str || '')) {
146
+ hash = ch.charCodeAt(0) + ((hash << 5) - hash);
147
+ }
148
+ const hue = ((hash % 360) + 360) % 360;
149
+ return `hsl(${hue}, 60%, 65%)`;
150
+ }
151
+
152
+ /**
153
+ * Clamp: limita valor entre min y max
154
+ */
155
+ export function clamp(value, min, max) {
156
+ return Math.min(Math.max(value, min), max);
157
+ }
158
+
159
+ /**
160
+ * Crea un elemento <div> con clases opcionales e innerHTML
161
+ * (helper para generación de DOM sin frameworks)
162
+ * @param {string} tag
163
+ * @param {string} [className]
164
+ * @param {string} [innerHTML]
165
+ * @returns {HTMLElement}
166
+ */
167
+ export function el(tag = 'div', className = '', innerHTML = '') {
168
+ const element = document.createElement(tag);
169
+ if (className) element.className = className;
170
+ if (innerHTML) element.innerHTML = innerHTML;
171
+ return element;
172
+ }