diff --git a/client/src/components/Widgets/ExplosionEvents.jsx b/client/src/components/Widgets/ExplosionEvents.jsx index ddd8044..8aad3b7 100644 --- a/client/src/components/Widgets/ExplosionEvents.jsx +++ b/client/src/components/Widgets/ExplosionEvents.jsx @@ -4,7 +4,7 @@ import { useColorMode } from "@/components/ui/color-mode.jsx"; import Plot from 'react-plotly.js'; import VdapApi from '../../hooks/useVdapApi.js'; // Adjust path as needed -export default function ExplosionEvents({ settings }) { +export default function ExplosionEvents({ settings, widgetID }) { // Plotly expects 'linear' for normal axes const plotYAxisType = settings?.yAxisScale === 'log' ? 'log' : 'linear'; diff --git a/client/src/components/Widgets/IvansAlerts.jsx b/client/src/components/Widgets/IvansAlerts.jsx index f9d35ef..345da11 100644 --- a/client/src/components/Widgets/IvansAlerts.jsx +++ b/client/src/components/Widgets/IvansAlerts.jsx @@ -1,164 +1,354 @@ import VdapApi from '../../hooks/useVdapApi.js'; -import {Flex, Spinner, Text, Button, Dialog, Box} from "@chakra-ui/react"; -import * as url from "node:url"; // Adjust path as needed -import { useState } from 'react'; +import {Button, Dialog, Flex, Grid, GridItem, Spinner, Text} from "@chakra-ui/react"; +import {useEffect, useMemo, useState} from 'react'; +import {useDashboardStore} from "@/store/useDashboardStore.jsx"; -export default function IvansAlerts() { - console.log("IvansAlerts"); - const [isSummaryOpen, setIsSummaryOpen] = useState(false); - const [isFileOpen, setIsFileOpen] = useState(false); +export default function IvansAlerts({ settings, widgetID }) { + console.log("IvansAlerts"); + const [activeSummaryItem, setActiveSummaryItem] = useState(false); + const [activeFileItem, setActiveFileItem] = useState(false); + const [activeImageItem, setActiveImageItem] = useState(false); + const widgets = useDashboardStore(state => state.widgets); + console.log("widgets: ", widgets); + const updateSettings = useDashboardStore(state => state.updateWidgetSettings); + const isCopy = settings?.copyToClipboard === true; // acts as a failsafe if no default setting is set + const sorts = settings?.activeSorts; - function SummaryDialog({ open, onOpenChange, item }) { + // build url once on mount + const seven_day_url = useMemo(() => { + const base_url = '/api/v2/comm_coor_ivans' + let today = new Date(); + let sevenDaysAgo = new Date(today); + sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7); + + sevenDaysAgo = sevenDaysAgo.toLocaleDateString('en-CA'); + today = today.toLocaleDateString('en-CA'); + + return base_url + '?start_date=' + sevenDaysAgo + '&end_date=' + today; + }, []); + + // VdapApi hook only calls api if the url changes + const {data: apiD, isLoading, error} = VdapApi(seven_day_url); + + const apiData = [ + { + id: 277, + volcano_number: 268010, + report_num: "2026-01", + report_date: "2026-05-08T22:05:44Z", + preparer: "hwright", + reviewer: "dramsey", + send_time: "2026-05-08T22:05:52Z", + volcano_name: "Dukono", + summary: "At 07:41 local time on 8 May 2026, an explosion of persistently active Dukono volcano occurred, producing an ash plume that rose over 15 km (52,000 feet) above sea level and ejecting ballistic blocks of lava beyond the crater rim. The eruption killed three tourists who were hiking within the official exclusion zone; other hikers were rescued and returned to safety.", + files: [ + { + name: "277-268010-Dukono-2026-01.pdf", + url: "https://vdap.org/ivans/sitrep/277-268010-Dukono-2026-01.pdf", + type: "pdf" + } + ] + }, + { + id: 279, + volcano_number: 250030, + report_num: "2026-01", + report_date: "2026-05-15T05:11:53Z", + preparer: "charpel", + reviewer: "jlwnstrn", + send_time: "2026-05-15T05:12:01Z", + volcano_name: "Central Bismarck Sea", + summary: "A M5.4 earthquake occurred on 14 May 2026 at 17:13 (UTC) during the ongoing eruption of the submarine Central Bismarck Sea volcano that began 8 May 2026. The volcano's current activity does not threaten any populated areas, but today’s earthquake indicates that eruptive activity will continue or increase.", + files: [ + { + name: "279-250030-Central Bismarck Sea-2026-01.pdf", + url: "https://vdap.org/ivans/sitrep/279-250030-Central Bismarck Sea-2026-01.pdf", + type: "pdf" + } + ] + }, + { + id: 275, + volcano_number: 273030, + report_num: "2026-02", + report_date: "2026-05-03T05:28:12Z", + preparer: "dramsey", + reviewer: "hwright", + send_time: "2026-05-03T05:28:20Z", + volcano_name: "Mayon", + summary: "At around 5:30 PM local time on May 2, 2026, a pyroclastic flow (cloud of searing ash and rock particles) from erupting Mayon Volcano traveled around 4 km (~2.5 miles) down the southwestern slope of the volcano and produced an ash plume that drifted to the west-southwest. At least 52 villages in various towns in Albay province were heavily affected by thick ash fall, reducing visibility to near zero and making travel extremely difficult. There were no reports of casualties and the volcano alert level remained at Level 3 (on a 0-5 level scale).", + files: [ + { + name: "275-273030-Mayon-2026-02.pdf", + url: "https://vdap.org/ivans/sitrep/275-273030-Mayon-2026-02.pdf", + type: "pdf" + }, + { + name: "275-273030-Mayon-2026-02.pdf", + url: "https://vdap.org/ivans/sitrep/275-273030-Mayon-2026-02.pdf", + type: "pdf" + } + ] + } + ]; + + const data = useMemo(() => { + if (apiData.length === 0) return []; + let sorted = []; + + if (sorts?.volcanoSort && sorts?.timeSort === "asc") { + sorted = [...apiData].sort(ascTimeVolcanoSort); + } else if (sorts?.volcanoSort && sorts?.timeSort === "desc") { + sorted = [...apiData].sort(descTimeVolcanoSort); + } else if (sorts?.timeSort === "asc") { + sorted = [...apiData].sort(ascTimeSort); + } else { + sorted = [...apiData].sort(descTimeSort); + } + + console.log("sorted data: ", sorted); + return sorted; + }, [apiData, sorts]); + + useEffect(() => { + if(isCopy) { + navigator.clipboard.writeText(data) + .then(() => { + alert('Copied to clipboard!'); + }) + .catch((err => { + console.error('Failed to copy: ', err); + })); + updateSettings(widgetID, {copyToClipboard: false}); + } + }, [isCopy]); + + if (isLoading) return ( + + + + ); + + if (error) return ( + + {error} + + ); + + if (data.length === 0) return ( + + No flight level data available this week. + + ); + + return ( + + {/**/} + {/* Volcano*/} + {/* Report Number*/} + {/* Report Send Time*/} + {/* Preparer*/} + {/* Summary*/} + {/* Attachments*/} + {/**/} + {data.map((item, index) => { + const context_string = item.volcano_name + ' β€’ ' + item.send_time; return ( - - - - - - Summary - - - - {item.summary} - - - - - - - - - - ) - } - - function FileDialog({ open, onOpenChange, item, context }) { - return ( - - - - - - - - {item.name ? item.name : 'PDF Attachment'} - {context} - - - {item.type} - - - - - - - - - Your browser cannot display this PDF directly. - - Download PDF - - - - - - - - - - - - - - ) - } - - const get_7_day_range_url = () => { - const base_url = '/api/v2/comm_coor_ivans' - let today = new Date(); - let sevenDaysAgo = new Date(today); - sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7); - - sevenDaysAgo = sevenDaysAgo.toLocaleDateString('en-CA'); - today = today.toLocaleDateString('en-CA'); - - const url_with_dates = base_url + '?start_date=' + sevenDaysAgo + '&end_date=' + today; - return url_with_dates; - } - - const seven_day_url = get_7_day_range_url(); - - const {data: apiData, isLoading, error} = VdapApi(seven_day_url); - - if (isLoading) return ( - - - - ); - - if (error) return ( - - {error} - - ); - - if (apiData.length === 0) return ( - - No flight level data available. - - ); - - return ( - - - Volcano - Report Number - Report Send Time - Preparer - Summary - Attachments - - {apiData.map((item, index) => { - const context_str = item.volcano_name + " " + "β€’" + " " + item.send_time; - - return ( - - {item.volcano_name} - {item.report_num} - {item.send_time} - {item.preparer} - - setIsSummaryOpen(e.open)} - item={item} - /> - {item.files.map((item, index) => { - const $file_name = item.name; - const $url = item.url; - const $type = item.type; - - if ($type === "pdf") return ( - <> - - setIsFileOpen(e.open)} - item={item} - context={context_str} - /> - - ) - })} - + + {item.volcano_name} + {item.report_num} + {item.send_time} + {item.preparer} + + <> + + setActiveSummaryItem(null)} + item={activeSummaryItem} + context={context_string} + /> + + + + + {item.files.length === 0 ? ( + No Attachments + ):( + item.files.map((file, index) => { + if (file.type === "pdf") return ( +
+ + setActiveFileItem(null)} + item={activeFileItem} + context={context_string} + /> +
) - })} - + else if (file.type === "image") return ( +
+ + setActiveImageItem(null)} + item={activeImageItem} + context={context_string} + /> +
+ ) + else if (file.type === "download") return ( + + ) + }) + )} +
+
+
+ ) + })} +
+ ); +} + +function SummaryDialog({ open, onOpenChange, item }) { + return ( + + + + + + + + + {item?.volcano_name} + Preparer: {item?.preparer} + + {item?.send_time} + + + + + + {item?.summary} + + + + + + + + + + ) +} + +function FileDialog({ open, onOpenChange, item, context }) { + return ( + + + + + + + + {item?.name ? item?.name : 'PDF Attachment'} + {context} + + {(item?.type || '').toUpperCase()} -
- ); + + + + + + + Your browser cannot display this PDF directly. + + Download PDF + + + + + + + + + + + + + + ) +} + +function ImageDialog({ open, onOpenChange, item, context }) { + return ( + + + + + + {item?.name} + {context} + + + + {item?.name} + + + + + + + + + + ) +} + +const downloadReport = ( url, name ) => { + const link = document.createElement('a'); + link.href = url; + link.download = name; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); +} + +function ascTimeVolcanoSort(a, b) { + if (a.volcano_name < b.volcano_name) return -1 + else if (a.volcano_name > b.volcano_name) return 1 + else return ascTimeSort(a, b); +} + +function descTimeVolcanoSort(a, b) { + if (a.volcano_name < b.volcano_name) return -1 + else if (a.volcano_name > b.volcano_name) return 1 + else return descTimeSort(a, b); +} + +function ascTimeSort(a, b) { + const aTime = new Date(a.send_time); + const bTime = new Date(b.send_time); + + if (aTime > bTime) return 1; + if (aTime < bTime) return -1; + return 0; +} + +function descTimeSort(a, b) { + const aTime = new Date(a.send_time); + const bTime = new Date(b.send_time); + + if (aTime > bTime) return -1; + if (aTime < bTime) return 1; + return 0; } \ No newline at end of file diff --git a/client/src/components/Widgets/IvansAlerts.stories.jsx b/client/src/components/Widgets/IvansAlerts.stories.jsx index f528b51..a79dfcd 100644 --- a/client/src/components/Widgets/IvansAlerts.stories.jsx +++ b/client/src/components/Widgets/IvansAlerts.stories.jsx @@ -67,6 +67,11 @@ const mockData = [ volcano_name: "Mayon", summary: "At around 5:30 PM local time on May 2, 2026, a pyroclastic flow (cloud of searing ash and rock particles) from erupting Mayon Volcano traveled around 4 km (~2.5 miles) down the southwestern slope of the volcano and produced an ash plume that drifted to the west-southwest. At least 52 villages in various towns in Albay province were heavily affected by thick ash fall, reducing visibility to near zero and making travel extremely difficult. There were no reports of casualties and the volcano alert level remained at Level 3 (on a 0-5 level scale).", files: [ + { + name: "275-273030-Mayon-2026-02.pdf", + url: "https://vdap.org/ivans/sitrep/275-273030-Mayon-2026-02.pdf", + type: "pdf" + }, { name: "275-273030-Mayon-2026-02.pdf", url: "https://vdap.org/ivans/sitrep/275-273030-Mayon-2026-02.pdf", diff --git a/client/src/components/Widgets/VaaActivity7Day.jsx b/client/src/components/Widgets/VaaActivity7Day.jsx index 85d35c1..a6bb48c 100644 --- a/client/src/components/Widgets/VaaActivity7Day.jsx +++ b/client/src/components/Widgets/VaaActivity7Day.jsx @@ -3,7 +3,7 @@ import { Box, Flex, Spinner, Text } from '@chakra-ui/react'; import Plot from 'react-plotly.js'; import VdapApi from '../../hooks/useVdapApi.js'; // Adjust path as needed -export default function VaaActivity7Day({ settings }) { +export default function VaaActivity7Day({ settings, widgetID }) { console.log("3. Chart received settings:", settings); // Plotly expects 'linear' for normal axes const plotYAxisType = settings?.yAxisScale === 'symlog' ? 'symlog' : 'linear'; diff --git a/client/src/components/Widgets/settings/IvansAlertsSettings.jsx b/client/src/components/Widgets/settings/IvansAlertsSettings.jsx new file mode 100644 index 0000000..59a8d6e --- /dev/null +++ b/client/src/components/Widgets/settings/IvansAlertsSettings.jsx @@ -0,0 +1,46 @@ +import {Button, Flex, Switch, Text} from "@chakra-ui/react"; +import {useDashboardStore} from "../../../store/useDashboardStore.jsx"; + +export default function IvansAlertsSettings({ widgetId, currentSettings }) { + const updateSettings = useDashboardStore(state => state.updateWidgetSettings); + + const handleCopyToClipboard = () => { + updateSettings(widgetId, {copyToClipboard: true}); + } + const handleVolcanoSort = (details) => { + const isSort = currentSettings?.activeSorts?.volcanoSort === true; + updateSettings(widgetId, { activeSorts: { ...currentSettings?.activeSorts, volcanoSort: !isSort }}); + } + const handleTimeSort = (details) => { + const sort = currentSettings?.activeSorts?.timeSort === "desc" ? "asc" : "desc"; + updateSettings(widgetId, { activeSorts: { ...currentSettings?.activeSorts, timeSort: sort }}); + } + + return ( + + + + + + + + Sort Oldest to Newest + + + + + + + Sort by Volcano + + + ) +} \ No newline at end of file diff --git a/client/src/constants/widgetRegistry.jsx b/client/src/constants/widgetRegistry.jsx index 77cb4ea..7eb9bd4 100644 --- a/client/src/constants/widgetRegistry.jsx +++ b/client/src/constants/widgetRegistry.jsx @@ -41,10 +41,17 @@ export const WIDGET_REGISTRY = { name: "IVANS", category: "Communications", description: "Feed of recent IVANS reports and reviewer statuses.", - component: lazy(() => import('../components/widgets/IvansAlerts.jsx')), + component: lazy(() => import('../components/Widgets/IvansAlerts.jsx')), + settingsComponent: lazy(() => import('../components/Widgets/settings/IvansAlertsSettings.jsx')), + defaultSettings: { + copyToClipboard: false, + activeSorts: { + timeSort: "desc", + volcanoSort: false + } + }, allowedSizes: { - small: { w: 3, h: 12 }, - medium: { w: 6, h: 24 } + small: { w: 6, h: 9 } } }, @@ -89,8 +96,7 @@ export const WIDGET_REGISTRY = { "llm_al_changes_quad_plot": { name: "Alert Level Changes Quad Plot", category: "Computer Science", - description: "Percentage of True-Positive, True-Negative, False-Positive, and False-Negative changes in all " + - "alert levels.", + description: "Percentage of TP, TN, FP, and FN changes in viable alert levels.", component: lazy(() => import('../components/Widgets/LlmAlChangesQuadPlot.jsx')), allowedSizes: { small: { w: 3, h: 12 } diff --git a/client/src/pages/home/tabs/MyDashboard.jsx b/client/src/pages/home/tabs/MyDashboard.jsx index 05f2c24..86452a7 100644 --- a/client/src/pages/home/tabs/MyDashboard.jsx +++ b/client/src/pages/home/tabs/MyDashboard.jsx @@ -1,209 +1,210 @@ -import { Box, Text, Flex, IconButton, Spinner, Popover } from "@chakra-ui/react"; -import { X, MoreVertical } from "lucide-react"; -import { Responsive, WidthProvider } from "react-grid-layout"; -import { useDashboardStore } from "@/store/useDashboardStore.jsx"; -import { Suspense, useEffect, useRef } from 'react'; -import { useColorModeValue } from "@/components/ui/color-mode"; +import {Box, Text, Flex, IconButton, Spinner, Popover} from "@chakra-ui/react"; +import {X, MoreVertical} from "lucide-react"; +import {Responsive, WidthProvider} from "react-grid-layout"; +import {useDashboardStore} from "@/store/useDashboardStore.jsx"; +import {Suspense, useEffect, useRef} from 'react'; +import {useColorModeValue} from "@/components/ui/color-mode"; // 1. Import database messenger import useAuthStore from "@/store/authStore"; // 2. Import registry -import { WIDGET_REGISTRY } from '@/constants/widgetRegistry.jsx'; +import {WIDGET_REGISTRY} from '@/constants/widgetRegistry.jsx'; // React-Grid-Layout requires this wrapper to automatically calculate screen width const ResponsiveGridLayout = WidthProvider(Responsive); export default function MyDashboard() { - // πŸŒ— Let's adjust for our light and dark mode - const frameBg = useColorModeValue("gray.100", "gray.800"); - const titleColor = useColorModeValue("gray.800", "gray.100"); - const iconColor = useColorModeValue("gray.600", "gray.400"); - const iconHoverBg = useColorModeValue("gray.100", "gray.700"); + // πŸŒ— Let's adjust for our light and dark mode + const frameBg = useColorModeValue("gray.100", "gray.800"); + const titleColor = useColorModeValue("gray.800", "gray.100"); + const iconColor = useColorModeValue("gray.600", "gray.400"); + const iconHoverBg = useColorModeValue("gray.100", "gray.700"); - // ☁️ Database Connection - const { user } = useAuthStore(); + // ☁️ Database Connection + const {user} = useAuthStore(); - // ☁️ Local UI Connections - const widgets = useDashboardStore(state => state.widgets); - const isEditing = useDashboardStore(state => state.isEditing); - const updateLayoutPositions = useDashboardStore(state => state.updateLayoutPositions); - const removeWidget = useDashboardStore(state => state.removeWidget); - const setWidgets = useDashboardStore(state => state.setWidgets); // The injection action + // ☁️ Local UI Connections + const widgets = useDashboardStore(state => state.widgets); + const isEditing = useDashboardStore(state => state.isEditing); + const updateLayoutPositions = useDashboardStore(state => state.updateLayoutPositions); + const removeWidget = useDashboardStore(state => state.removeWidget); + const setWidgets = useDashboardStore(state => state.setWidgets); // The injection action - // πŸ”’ Safety lock to prevent infinite re-renders - const hasHydrated = useRef(false); + // πŸ”’ Safety lock to prevent infinite re-renders + const hasHydrated = useRef(false); - // ========================================== - // INITIAL LOAD: Grab data from Django - // ========================================== - useEffect(() => { - if (user?.preferences?.dashboard_layout && !hasHydrated.current) { - const savedLayout = user.preferences.dashboard_layout; + // ========================================== + // INITIAL LOAD: Grab data from Django + // ========================================== + useEffect(() => { + if (user?.preferences?.dashboard_layout && !hasHydrated.current) { + const savedLayout = user.preferences.dashboard_layout; - // Safety check: Only inject if it's actually an array of widgets. - // (Prevents a crash if MariaDB returns a default empty object {}) - if (Array.isArray(savedLayout)) { - setWidgets(savedLayout); - } + // Safety check: Only inject if it's actually an array of widgets. + // (Prevents a crash if MariaDB returns a default empty object {}) + if (Array.isArray(savedLayout)) { + setWidgets(savedLayout); + } - hasHydrated.current = true; - } - }, [user, setWidgets]); + hasHydrated.current = true; + } + }, [user, setWidgets]); - // πŸ› οΈ Format the data for RGL - const rglLayout = widgets.map(w => ({ - i: w.id, - x: w.x, - y: w.y, - w: w.w, - h: w.h, - isResizable: false // 🚫 The magic lock! No resizing allowed globally. - })); + // πŸ› οΈ Format the data for RGL + const rglLayout = widgets.map(w => ({ + i: w.id, + x: w.x, + y: w.y, + w: w.w, + h: w.h, + isResizable: false // 🚫 The magic lock! No resizing allowed globally. + })); - // 3. THE COMPONENT MAPPER - const renderWidget = (widget) => { - const registryEntry = WIDGET_REGISTRY[widget.type]; + // 3. THE COMPONENT MAPPER + const renderWidget = (widget) => { + const registryEntry = WIDGET_REGISTRY[widget.type]; - if (registryEntry && registryEntry.component) { - const Component = registryEntry.component; + if (registryEntry && registryEntry.component) { + const Component = registryEntry.component; - // 1. Check if this widget type has a settings component registered - const SettingsUI = registryEntry.settingsComponent; + // 1. Check if this widget type has a settings component registered + const SettingsUI = registryEntry.settingsComponent; - return ( - // The "Frame" that holds both the Title and the Chart - + return ( + // The "Frame" that holds both the Title and the Chart + - {/* THE TITLE BAR */} - - - {registryEntry.name} - + {/* THE TITLE BAR */} + + + {registryEntry.name} + - {/* THE SETTINGS ELLIPSIS */} - {SettingsUI ? ( - - - - - - + {/* THE SETTINGS ELLIPSIS */} + {SettingsUI ? ( + + + + + + - {/* NEW: The Positioner lifts the content out of the Flexbox flow */} - - - }> - - - - - - ) : ( - - )} - - - {/* THE CHART CANVAS */} - - {/* Pass the settings object into the actual chart component */} - - - - - ); - } - - // Fallback if someone asks for a widget that doesn't exist - return ( - - Error - Widget '{widget.type}' not found. - - ); - }; - - return ( - - updateLayoutPositions(newLayout)} // Fires when user drops a widget - compactType="vertical" // Auto-packs widgets to the top - > - {/* 3. 🎨 Paint the Widgets */} - {widgets.map(widget => ( - - {/* 4. THE DELETE BUTTON */} - {isEditing && ( - removeWidget(widget.id)} - onMouseDown={(e) => e.stopPropagation()} // 🚫 Stops RGL from grabbing the widget - onTouchStart={(e) => e.stopPropagation()} // 🚫 Same protection for mobile touches - > - - - )} - - {/* 4. SUSPENSE BOUNDARY wrapping the render function */} - - - - }> - {renderWidget(widget)} - - - - ))} - - - {/* Empty State Helper */} - {widgets.length === 0 && ( - - Your dashboard is empty. Click Settings to add widgets. - + {/* NEW: The Positioner lifts the content out of the Flexbox flow */} + + + }> + + + + + + ) : ( + )} - + + + {/* THE CHART CANVAS */} + + {/* Pass the settings object into the actual chart component */} + {/* Pass widget ID to allow updating settings in widget component rather than just in settings component */} + + + + + ); + } + + // Fallback if someone asks for a widget that doesn't exist + return ( + + Error + Widget '{widget.type}' not found. + ); + }; + + return ( + + updateLayoutPositions(newLayout)} // Fires when user drops a widget + compactType="vertical" // Auto-packs widgets to the top + > + {/* 3. 🎨 Paint the Widgets */} + {widgets.map(widget => ( + + {/* 4. THE DELETE BUTTON */} + {isEditing && ( + removeWidget(widget.id)} + onMouseDown={(e) => e.stopPropagation()} // 🚫 Stops RGL from grabbing the widget + onTouchStart={(e) => e.stopPropagation()} // 🚫 Same protection for mobile touches + > + + + )} + + {/* 4. SUSPENSE BOUNDARY wrapping the render function */} + + + + }> + {renderWidget(widget)} + + + + ))} + + + {/* Empty State Helper */} + {widgets.length === 0 && ( + + Your dashboard is empty. Click Settings to add widgets. + + )} + + ); } \ No newline at end of file diff --git a/client/src/store/useDashboardStore.jsx b/client/src/store/useDashboardStore.jsx index 43803cb..af51da3 100644 --- a/client/src/store/useDashboardStore.jsx +++ b/client/src/store/useDashboardStore.jsx @@ -1,109 +1,110 @@ -import { create } from 'zustand'; -import { v4 as uuid } from 'uuid'; -import { WIDGET_REGISTRY } from '../constants/widgetRegistry.jsx'; +import {create} from 'zustand'; +import {v4 as uuid} from 'uuid'; +import {WIDGET_REGISTRY} from '../constants/widgetRegistry.jsx'; // 1. Import your database messenger import useAuthStore from './authStore'; export const useDashboardStore = create((set, get) => ({ - // ========================================== - // 1. STATE (The Data) - // ========================================== + // ========================================== + // 1. STATE (The Data) + // ========================================== + isEditing: false, + widgets: [], // The master array of what is currently on the screen + backupWidgets: [], // Holds the layout snapshot for the "Cancel" button + + // ========================================== + // 2. ACTIONS (The Logic) + // ========================================== + + enterEditMode: () => set({ + isEditing: true, + backupWidgets: get().widgets // πŸ“Έ Take a snapshot of current positions + }), + + cancelEdit: () => set({ isEditing: false, - widgets: [], // The master array of what is currently on the screen - backupWidgets: [], // Holds the layout snapshot for the "Cancel" button + widgets: get().backupWidgets // βͺ Restore snapshot, instantly undoing any drags + }), - // ========================================== - // 2. ACTIONS (The Logic) - // ========================================== + saveEdit: async () => { + // 1. Grab the exact current state of the grid + const currentLayout = get().widgets; - enterEditMode: () => set({ - isEditing: true, - backupWidgets: get().widgets // πŸ“Έ Take a snapshot of current positions - }), + // 2. Lock the UI immediately so the user feels zero lag + set({isEditing: false, backupWidgets: []}); - cancelEdit: () => set({ - isEditing: false, - widgets: get().backupWidgets // βͺ Restore snapshot, instantly undoing any drags - }), + // 3. Reach outside this store and trigger the Django API call! + try { + await useAuthStore.getState().saveDashboardLayout(currentLayout); + } catch (error) { + console.error("Failed to sync layout to MariaDB:", error); + // If the database save fails, you could technically revert the UI here if needed + } + }, - saveEdit: async () => { - // 1. Grab the exact current state of the grid - const currentLayout = get().widgets; + updateWidgetSettings: (id, newSettings) => set((state) => { + // console.log("2. Zustand updating widget:", id, "with:", newSettings); + return { + widgets: state.widgets.map(widget => + widget.id === id + ? {...widget, settings: {...widget.settings, ...newSettings}} + : widget + ) + }; + }), - // 2. Lock the UI immediately so the user feels zero lag - set({ isEditing: false, backupWidgets: [] }); + addWidget: (widgetId, sizeKey) => { + const registryEntry = WIDGET_REGISTRY[widgetId]; - // 3. Reach outside this store and trigger the Django API call! - try { - await useAuthStore.getState().saveDashboardLayout(currentLayout); - } catch (error) { - console.error("Failed to sync layout to MariaDB:", error); - // If the database save fails, you could technically revert the UI here if needed - } - }, + if (!registryEntry || !registryEntry.allowedSizes[sizeKey]) { + console.error(`Invalid widget ID or Size: ${widgetId} - ${sizeKey}`); + return; + } - updateWidgetSettings: (id, newSettings) => set((state) => { - console.log("2. Zustand updating widget:", id, "with:", newSettings); - return { - widgets: state.widgets.map(widget => - widget.id === id - ? { ...widget, settings: { ...widget.settings, ...newSettings } } - : widget - ) - }; - }), + const dimensions = registryEntry.allowedSizes[sizeKey]; + const widgets = get().widgets; - addWidget: (widgetId, sizeKey) => { - const registryEntry = WIDGET_REGISTRY[widgetId]; + let startX = 0; + let startY = Infinity; - if (!registryEntry || !registryEntry.allowedSizes[sizeKey]) { - console.error(`Invalid widget ID or Size: ${widgetId} - ${sizeKey}`); - return; - } + if (widgets.length > 0) { + const bottomRowY = Math.max(...widgets.map(w => w.y)); + const bottomRowWidgets = widgets.filter(w => w.y === bottomRowY); + const rightmostEdge = Math.max(...bottomRowWidgets.map(w => w.x + w.w)); - const dimensions = registryEntry.allowedSizes[sizeKey]; - const widgets = get().widgets; + if (rightmostEdge + dimensions.w <= 12) { + startX = rightmostEdge; // ...tuck it right next to the last widget! + startY = bottomRowY; // ...and keep it on the same row. + } + } + const newWidget = { + id: uuid(), + type: widgetId, + size: sizeKey, + settings: registryEntry.defaultSettings, + x: startX, + y: startY, + w: dimensions.w, + h: dimensions.h + }; + console.log("newWidget: ", newWidget); + set((state) => ({widgets: [...state.widgets, newWidget]})); + }, - let startX = 0; - let startY = Infinity; + removeWidget: (id) => set((state) => ({ + widgets: state.widgets.filter(w => w.id !== id) + })), - if (widgets.length > 0) { - const bottomRowY = Math.max(...widgets.map(w => w.y)); - const bottomRowWidgets = widgets.filter(w => w.y === bottomRowY); - const rightmostEdge = Math.max(...bottomRowWidgets.map(w => w.x + w.w)); + updateLayoutPositions: (rglLayout) => { + set((state) => ({ + widgets: state.widgets.map(widget => { + const gridItem = rglLayout.find(l => l.i === widget.id); + return gridItem ? {...widget, x: gridItem.x, y: gridItem.y} : widget; + }) + })); + }, - if (rightmostEdge + dimensions.w <= 12) { - startX = rightmostEdge; // ...tuck it right next to the last widget! - startY = bottomRowY; // ...and keep it on the same row. - } - } - const newWidget = { - id: uuid(), - type: widgetId, - size: sizeKey, - x: startX, - y: startY, - w: dimensions.w, - h: dimensions.h - }; - - set((state) => ({ widgets: [...state.widgets, newWidget] })); - }, - - removeWidget: (id) => set((state) => ({ - widgets: state.widgets.filter(w => w.id !== id) - })), - - updateLayoutPositions: (rglLayout) => { - set((state) => ({ - widgets: state.widgets.map(widget => { - const gridItem = rglLayout.find(l => l.i === widget.id); - return gridItem ? { ...widget, x: gridItem.x, y: gridItem.y } : widget; - }) - })); - }, - - // NEW: Action to hydrate the store on initial page load - setWidgets: (savedWidgets) => set({ widgets: savedWidgets || [] }) + // NEW: Action to hydrate the store on initial page load + setWidgets: (savedWidgets) => set({widgets: savedWidgets || []}) })); \ No newline at end of file