| 1 | import { createStore } from "/js/AlpineStore.js"; |
| 2 | import { store as chatsStore } from "/components/sidebar/chats/chats-store.js"; |
| 3 | import { store as sidebarStore } from "/components/sidebar/sidebar-store.js"; |
| 4 | import { store as schedulerStore } from "/components/modals/scheduler/scheduler-store.js"; |
| 5 | |
| 6 | // Tasks sidebar store: tasks list and selected task id |
| 7 | const model = { |
| 8 | tasks: [], |
| 9 | selected: "", |
| 10 | |
| 11 | init() { |
| 12 | // No-op: data is driven by poll() in index.js; this store provides a stable target |
| 13 | }, |
| 14 | |
| 15 | // Apply tasks coming from poll() and keep them sorted (newest first) |
| 16 | applyTasks(tasksList) { |
| 17 | try { |
| 18 | const tasks = Array.isArray(tasksList) ? tasksList : []; |
| 19 | const sorted = [...tasks].sort((a, b) => (b?.created_at || 0) - (a?.created_at || 0)); |
| 20 | this.tasks = sorted; |
| 21 | |
| 22 | // After updating tasks, ensure selection is still valid |
| 23 | if (this.selected && !this.contains(this.selected)) { |
| 24 | this.setSelected(""); |
| 25 | } |
| 26 | } catch (e) { |
| 27 | console.error("tasks-store.applyTasks failed", e); |
| 28 | this.tasks = []; |
| 29 | } |
| 30 | }, |
| 31 | |
| 32 | // Update selected task and persist for tab restore |
| 33 | setSelected(taskId) { |
| 34 | this.selected = taskId || ""; |
| 35 | try { localStorage.setItem("lastSelectedTask", this.selected); } catch {} |
| 36 | }, |
| 37 | |
| 38 | // Returns true if a task with the given id exists in the current list |
| 39 | contains(taskId) { |
| 40 | return Array.isArray(this.tasks) && this.tasks.some((t) => t?.id === taskId); |
| 41 | }, |
| 42 | |
| 43 | visibleTasks() { |
| 44 | return sidebarStore.sortRows("task", this.tasks); |
| 45 | }, |
| 46 | |
| 47 | // Convenience: id of the first task in the current list (or empty string) |
| 48 | firstId() { |
| 49 | return (Array.isArray(this.tasks) && this.tasks[0]?.id) || ""; |
| 50 | }, |
| 51 | |
| 52 | // Action methods for task management |
| 53 | selectTask(taskId) { |
| 54 | this.setSelected(taskId); |
| 55 | chatsStore.selectChat(taskId); |
| 56 | }, |
| 57 | |
| 58 | openDetail(taskId) { |
| 59 | // Open lightweight task detail popup directly |
| 60 | if (schedulerStore?.showTaskDetail) { |
| 61 | schedulerStore.showTaskDetail(taskId); |
| 62 | } |
| 63 | }, |
| 64 | |
| 65 | reset(taskId) { |
| 66 | chatsStore.resetChat(taskId); |
| 67 | }, |
| 68 | |
| 69 | deleteTask(taskId) { |
| 70 | if (schedulerStore?.deleteTaskFromSidebar) { |
| 71 | schedulerStore.deleteTaskFromSidebar(taskId); |
| 72 | } |
| 73 | }, |
| 74 | }; |
| 75 | |
| 76 | export const store = createStore("tasks", model); |
| 77 |