diff --git a/SMTplugins/Calendar/calendarWidget.py b/SMTplugins/Calendar/calendarWidget.py index 2744cf6..4a7d8bd 100644 --- a/SMTplugins/Calendar/calendarWidget.py +++ b/SMTplugins/Calendar/calendarWidget.py @@ -3,16 +3,28 @@ # Falls back to a static calendar view if no credentials are provided from widget import Widget -from datetime import datetime, date +from datetime import datetime, date, timedelta import calendar import json +import os +import time class calendarWidget(Widget): def __init__(self): self._preferences = self.widgetDefaultPreferences - self._events = {} # date_str -> list of event names + self.file = "calendar_events.json" + if os.path.exists(self.file): + with open(self.file, "r") as f: + self._events = json.load(f) + else: + self._events = {} + + self.current_date = date.today() + self.state_file = "calendar_state.json" + + # -------- METADATA -------- @property def widgetName(self): return "Calendar Widget" @@ -23,17 +35,16 @@ def widgetID(self): @property def widgetHTML(self): - """Returns the HTML template name; Flask renders it via Jinja.""" return "calendar_widget.html" + # -------- MAIN DATA -------- @property def widgetData(self): - """Returns current calendar data as a JSON-serialisable dict.""" today = date.today() - year = today.year - month = today.month + year = self.current_date.year + month = self.current_date.month - cal = calendar.Calendar(firstweekday=6) # week starts Sunday + cal = calendar.Calendar(firstweekday=6) weeks = cal.monthdatescalendar(year, month) weeks_data = [] @@ -50,19 +61,17 @@ def widgetData(self): weeks_data.append(days) return { - "month_name": today.strftime("%B"), + "month_name": self.current_date.strftime("%B"), "year": year, "weeks": weeks_data, "day_headers": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] } + # -------- PREFERENCES -------- @property def widgetPreferences(self): - return self._preferences - - @widgetPreferences.setter - def widgetPreferences(self, value): - self._preferences = value + return {} + @property def widgetDefaultPreferences(self): @@ -77,16 +86,28 @@ def updateTimer(self): # Refresh every 10 minutes return 600_000 + # -------- SAVE HELPERS -------- + def _save_state(self): + with open(self.state_file, "w") as f: + json.dump({ + "current_date": self.current_date.isoformat() + }, f) + + def _save_events(self): + with open(self.events_file, "w") as f: + json.dump(self._events, f) + + # -------- OPTIONAL DEFAULT DATA -------- def update(self): """Called by the widget subsystem on a timer. Fetches events if enabled.""" if self._preferences.get("use_google_cal"): self._fetch_google_events() else: - # Placeholder: inject a couple of demo events so the UI isn't empty - today = date.today().isoformat() - self._events = { - today: ["Class 4PM – LC 22", "Gym 5PM"] - } + # Only add demo data if nothing exists yet + if not self._events: + today = date.today().isoformat() + self._events[today] = ["Class 4PM – LC 22", "Gym 5PM"] + print(f"Calendar Widget updated – {date.today().strftime('%B %Y')}") def _fetch_google_events(self): @@ -105,19 +126,56 @@ def _fetch_google_events(self): print(f"[calendarWidget] Google Calendar fetch failed: {e}") def handle_event(self, event, args): - """ - Supported events: - - "prev_month" : (future) navigate to previous month - - "next_month" : (future) navigate to next month - - "add_event" : args = {"date": "YYYY-MM-DD", "title": "..."} - """ + + # -------- ADD TASK -------- if event == "add_event": date_str = args.get("date") title = args.get("title", "Event") + if date_str: if date_str not in self._events: self._events[date_str] = [] - self._events[date_str].append(title) - print(f"[calendarWidget] Added event '{title}' on {date_str}") + + self._events[date_str].append({ + "id": int(time.time()*1000), + "title": title + }) + + self._save_events() + + # -------- NEXT MONTH -------- + elif event == "next_month": + print("NEXT MONTH TRIGGERED") + + if self.current_date.month == 12: + self.current_date = self.current_date.replace( + year=self.current_date.year + 1, + month=1 + ) + else: + self.current_date = self.current_date.replace( + month=self.current_date.month + 1 + ) + + self._save_state() + print("NEW MONTH:", self.current_date) + + # -------- PREVIOUS MONTH -------- + elif event == "prev_month": + print("PREV MONTH TRIGGERED") + + if self.current_date.month == 1: + self.current_date = self.current_date.replace( + year=self.current_date.year - 1, + month=12 + ) + else: + self.current_date = self.current_date.replace( + month=self.current_date.month - 1 + ) + + self._save_state() + print("NEW MONTH:", self.current_date) + else: print(f"[calendarWidget] Unhandled event: {event} args={args}") \ No newline at end of file diff --git a/SMTplugins/Calendar/calendar_plugin.py b/SMTplugins/Calendar/calendar_plugin.py index 1bf0d23..72e3322 100644 --- a/SMTplugins/Calendar/calendar_plugin.py +++ b/SMTplugins/Calendar/calendar_plugin.py @@ -10,6 +10,7 @@ @calendar_bp.route("/widget/calendar") def calendar_view(): + print("RENDERING MONTH:", _widget.current_date) # debug return render_template("calendar_widget.html", data=_widget.widgetData) @calendar_bp.route("/api/calendar/data") diff --git a/SMTplugins/Calendar/credentials.json b/SMTplugins/Calendar/credentials.json new file mode 100644 index 0000000..d877c52 --- /dev/null +++ b/SMTplugins/Calendar/credentials.json @@ -0,0 +1 @@ +{"installed":{"client_id":"772172144197-ldo19j0f7s5m7s55jd6ndkadoj4c4ehd.apps.googleusercontent.com","project_id":"smt-tasks","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost"]}} \ No newline at end of file diff --git a/SMTplugins/Calendar/token_cal.json b/SMTplugins/Calendar/token_cal.json new file mode 100644 index 0000000..acb34eb --- /dev/null +++ b/SMTplugins/Calendar/token_cal.json @@ -0,0 +1 @@ +{"token": "ya29.a0AQvPyINm3-Umt-poLbkfSpf3sLXjFOYawOQnHssKmcD6iWd6qI8Vxog2HqhWPjDc4-Gwib_qHJB0JgbnWlVCZeoMCrkxipNogHWpkAVsD4rjQxllKDdjlO7lcHQiFEODBc05EtXZHSdpdkqp3ah9cWzQeOHi2QksUPudqv8QNapkJpvElGqKDljOyvnuJMENZ8bTXnEaCgYKAaMSARQSFQHGX2Mi1bah18Yfs0QmPf9s0gUP6A0206", "refresh_token": "1//05NlvPY06LAVrCgYIARAAGAUSNwF-L9IrBh5LQKCmxDpM-lbVWh3B_Grots1N2s4FdVmAsdTZQ3AeBEwIUmtCI3uZRvfDXKTb4V4", "token_uri": "https://oauth2.googleapis.com/token", "client_id": "772172144197-ldo19j0f7s5m7s55jd6ndkadoj4c4ehd.apps.googleusercontent.com", "client_secret": "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", "scopes": ["https://www.googleapis.com/auth/calendar.readonly"], "universe_domain": "googleapis.com", "account": "", "expiry": "2026-04-30T16:24:43Z"} \ No newline at end of file diff --git a/calendar_events.json b/calendar_events.json new file mode 100644 index 0000000..c5877dd --- /dev/null +++ b/calendar_events.json @@ -0,0 +1 @@ +{"2026-05-24": [{"id": "8ifd00fvn8hqjf73o7o24he5os", "title": "Photography Session (Easha Mashud)", "google_event": true}]} \ No newline at end of file diff --git a/calendar_state.json b/calendar_state.json new file mode 100644 index 0000000..4d666ef --- /dev/null +++ b/calendar_state.json @@ -0,0 +1 @@ +{"current_date": "2026-04-30"} \ No newline at end of file diff --git a/flaskServer.py b/flaskServer.py index 77d379e..a27a1a0 100644 --- a/flaskServer.py +++ b/flaskServer.py @@ -29,7 +29,7 @@ #allows for easier starting of flask from start file def run_flask(): - app.run(debug=True, port=5000, use_reloader=False) + app.run(debug=True, port=8000, use_reloader=False) diff --git a/layout_client.json b/layout_client.json index 6411891..9bc30f2 100644 --- a/layout_client.json +++ b/layout_client.json @@ -33,10 +33,10 @@ "col": 3 }, { - "id": "bj-container", - "name": "Blackjack", - "class": "blackjack-widget", - "css_name": "blackjack_widget.css", + "id": "calendar", + "name": "Calendar", + "class": "calendar-widget", + "css_name": "calendar_widget.css", "row": 2, "col": 2 }, diff --git a/static/js/plugins/calendar_script.js b/static/js/plugins/calendar_script.js index 60e78db..7e4c849 100644 --- a/static/js/plugins/calendar_script.js +++ b/static/js/plugins/calendar_script.js @@ -1,15 +1,216 @@ +/** + * PREREQUISITES FOR THIS FILE: + * 1. An HTML container with id="calendar". + * 2. An API endpoint at /widget/calendar that returns HTML. + * 3. An API endpoint at /api/calendar/event that handles POST requests. + * 4. A global window.calendarEvents array (usually provided by the server-side HTML). + */ + +let selectedDate = null; +let calendarInitialized = false; + +/** + * Attaches event listeners to the calendar container. + * Uses delegation so we don't have to re-bind listeners to every single day. + */ +function attachCalendarListeners() { + const container = document.getElementById("calendar"); + if (!container) return; + + calendarInitialized = true; + + container.addEventListener("click", (e) => { + const day = e.target.closest(".cal-day"); + if (!day) return; + + selectedDate = day.dataset.date; + + // UI Elements + const eventsContainer = document.getElementById("selectedEventsContainer"); + const title = document.getElementById("eventsTitle"); + const taskSection = document.getElementById("taskSection"); + const label = document.getElementById("selectedDateLabel"); + + if (eventsContainer && title && window.calendarEvents) { + let events = []; + + // Find events for the clicked date from the global data store + window.calendarEvents.forEach(week => { + week.forEach(dayData => { + if (dayData.date_str === selectedDate) { + events = dayData.events; + } + }); + }); + + title.innerText = new Date(selectedDate).toDateString(); + eventsContainer.innerHTML = ""; + + if (events.length > 0) { + events.forEach(e => { + const div = document.createElement("div"); + div.className = "cal-event-item"; + div.style.display = "flex"; + div.style.marginBottom = "5px"; + div.innerHTML = ` + ${e.title || e} +
+
+ + +
+ `; + eventsContainer.appendChild(div); + }); + } else { + eventsContainer.innerHTML = `
No tasks
`; + } + } + + // Visual Highlight: Clear others, highlight selected + document.querySelectorAll(".cal-day").forEach(d => d.style.outline = "none"); + day.style.outline = "2px solid #c084fc"; + + // Toggle task input visibility + if (taskSection) taskSection.style.display = "block"; + if (label) { + label.innerText = "Editing tasks for: " + new Date(selectedDate).toDateString(); + } + + console.log("Selected date:", selectedDate); + }); +} + +/** + * Sends a new task to the server and refreshes the UI. + */ +function addTask() { + const input = document.getElementById("taskInput"); + const task = input.value; + + if (!selectedDate || !task) { + alert("Select a date and enter a task"); + return; + } + + fetch("/api/calendar/event", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + event: "add_event", + args: { date: selectedDate, title: task } + }) + }) + .then(() => { + input.value = ""; + updateCalendar().then(() => { + setTimeout(() => { + const selected = document.querySelector(`.cal-day[data-date="${selectedDate}"]`); + if (selected) { + selected.click(); + setTimeout(() => selected.click(), 50); + } + }, 50); + }); + }); +} + +function deleteTask(id, date) { + fetch("/api/calendar/event", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + event: "delete_event", + args: { id, date } + }) + }).then(() => { + updateCalendar().then(() => { + setTimeout(() => { + const day = document.querySelector(`[data-date="${date}"]`); + if (day) day.click(); + }, 50); + }); + }); +} + +function editTask(id, date, oldTitle) { + const newTitle = prompt("Edit task:", oldTitle); + if (!newTitle) return; + + fetch("/api/calendar/event", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + event: "edit_event", + args: { id, date, title: newTitle } + }) + }).then(() => { + updateCalendar().then(() => { + setTimeout(() => { + const day = document.querySelector(`[data-date="${date}"]`); + if (day) day.click(); + }, 50); + }); + }); +} + + +function changeMonth(direction) { + fetch("/api/calendar/event", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + event: direction === "next" ? "next_month" : "prev_month" + }) + }) + .then(res => res.json()) + .then(() => updateCalendar()) + .catch(err => console.error("ERROR:", err)); +} + +window.changeMonth = changeMonth; + export async function updateCalendar() { try { const response = await fetch('/widget/calendar'); const html = await response.text(); const container = document.getElementById('calendar'); - if (container) container.innerHTML = html; - } catch (error) { - console.error('Calendar update failed:', error); - } + + if (container) { + container.innerHTML = html; + + // Execute the script embedded in the fetched HTML to update window.calendarEvents + const scriptTag = container.querySelector("script"); + if (scriptTag) { + eval(scriptTag.innerText); + } + + attachCalendarListeners(); + } + // Default back to "Today" after background updates + setTimeout(() => { + const today = document.querySelector(".cal-day.today"); + if (today) today.click(); + }, 50); + + } catch (error) { + console.error('Calendar update failed:', error); + } } -// Update every 60 seconds + +// Initialize on Load +updateCalendar().then(() => { + setTimeout(() => { + const today = document.querySelector(".cal-day.today"); + if (today) today.click(); + }, 50); +}); + +// Background Sync setInterval(updateCalendar, 60000); -// Run once immediately -updateCalendar(); \ No newline at end of file + +// make button work globally +window.addTask = addTask; +window.deleteTask = deleteTask; +window.editTask = editTask; \ No newline at end of file diff --git a/static/js/plugins/date_script.js b/static/js/plugins/date_script.js index 22f256f..fb7117e 100644 --- a/static/js/plugins/date_script.js +++ b/static/js/plugins/date_script.js @@ -10,6 +10,9 @@ async function updateDate() { await fetch('/api/date'); const d = new Date(); + + const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; + const dayName = days[new Date().getDay()]; const month = d.toLocaleString('en-US', { month: 'long' }); const day = d.getDate(); @@ -17,6 +20,7 @@ async function updateDate() { widget.innerHTML = `
+
${dayName}
${month}
${day}
${year}
diff --git a/static/widgetCSS/calendar_widget.css b/static/widgetCSS/calendar_widget.css index 10a0ef0..bf80d41 100644 --- a/static/widgetCSS/calendar_widget.css +++ b/static/widgetCSS/calendar_widget.css @@ -131,4 +131,107 @@ font-size: 0.65rem; color: rgba(255, 255, 255, 0.3); font-style: italic; +} + +.task-section { + margin-top: 12px; + display: none; + padding-top: 10px; + border-top: 1px solid rgba(255,255,255,0.08); +} + +.task-label { + font-size: 0.7rem; + color: #c084fc; + margin-bottom: 6px; + letter-spacing: 0.04em; +} + +.task-input-row { + display: flex; + gap: 6px; +} + +/* INPUT */ +.task-input-row input { + flex: 1; + padding: 6px 8px; + border-radius: 6px; + border: 1px solid rgba(255,255,255,0.1); + background: #1a1a24; + color: #e8e6f0; + font-size: 0.7rem; + outline: none; + transition: 0.2s; +} + +.task-input-row input::placeholder { + color: #5a5870; +} + +.task-input-row input:focus { + border-color: #7c6af7; + box-shadow: 0 0 6px rgba(124,106,247,0.4); +} + +/* BUTTON */ +.task-input-row button { + padding: 6px 12px; + border-radius: 6px; + border: none; + background: linear-gradient(135deg, #7c6af7, #c084fc); + color: white; + font-size: 0.7rem; + cursor: pointer; + transition: 0.2s; +} + +.task-input-row button:hover { + transform: translateY(-1px); + box-shadow: 0 4px 10px rgba(124,106,247,0.4); +} + +.task-input-row button:active { + transform: scale(0.96); +} + +.cal-event-item { + display: flex; + align-items: center; + justify-content: space-between; +} + +.cal-event-item button { + background: none; + border: none; + color: #c084fc; + cursor: pointer; + font-size: 0.8rem; +} + +.cal-event-item button:hover { + color: white; +} + +.cal-header { + display: flex; + justify-content: space-between; + align-items: center; +} + +.cal-nav-btn { + background: transparent; + border: none; + color: #c084fc; /* purple */ + font-size: 1.2rem; + cursor: pointer; + padding: 6px 10px; + border-radius: 6px; + transition: all 0.2s ease; +} + +.cal-nav-btn:hover { + background: rgba(192, 132, 252, 0.15); + color: white; + transform: scale(1.2); } \ No newline at end of file diff --git a/static/widgetCSS/date_widget.css b/static/widgetCSS/date_widget.css index 31f66dd..9fdeb50 100644 --- a/static/widgetCSS/date_widget.css +++ b/static/widgetCSS/date_widget.css @@ -20,6 +20,7 @@ .date-month, .date-day, +.date-name, .date-year { /*font-size: 40px; /* SAME SIZE for all */ font-weight: bold; diff --git a/templates/calendar_widget.html b/templates/calendar_widget.html index 978a441..7baf5d7 100644 --- a/templates/calendar_widget.html +++ b/templates/calendar_widget.html @@ -187,10 +187,21 @@
- {{ data.month_name }} + + + + + +
+ {{ data.month_name }}
{{ data.year }}
+ + + +
+
{% for header in data.day_headers %} @@ -203,38 +214,40 @@
{{ day.day }} - {% if day.events %} -
+ {% if day.is_today and day.events %} +
{% endif %}
{% endfor %} {% endfor %}
- -
-
Today
- {% set today_events = [] %} - {% for week in data.weeks %} - {% for day in week %} - {% if day.is_today and day.events %} - {% for e in day.events %} - {% set _ = today_events.append(e) %} - {% endfor %} - {% endif %} - {% endfor %} - {% endfor %} + +
+
Select a day
- {% if today_events %} - {% for event in today_events %} -
- {{ event }} -
- {% endfor %} - {% else %} -
No events today
- {% endif %} +
+
Click a date to see tasks
+
+
+ + + +
+ +
+ +
-
\ No newline at end of file + +
+ + + +
+