-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
341 lines (289 loc) · 9.99 KB
/
Copy pathscript.js
File metadata and controls
341 lines (289 loc) · 9.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Quest Log — gamified daily tracker
// Manually added quests live in the browser's localStorage.
// Quests added by your automations are pulled in (read-only) from Supabase each time you load the page.
const STORAGE_KEY = 'questlog_state_v1';
const RING_CIRCUMFERENCE = 327; // 2 * PI * 52
// Public read-only connection. This key can only SELECT rows — it cannot
// insert, update, or delete anything, so it's safe to expose in client-side code.
const SUPABASE_URL = 'https://heuqdyumhpjjsateitrd.supabase.co';
const SUPABASE_PUBLISHABLE_KEY = 'sb_publishable_YAtZHIQ7xedKaH2Gxq25EA_wYO6ArhF';
const supabaseClient = window.supabase
? window.supabase.createClient(SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY)
: null;
const defaultState = {
totalXp: 0,
level: 1,
currentXp: 0, // xp progress toward next level
xpToNextLevel: 100,
streak: 0,
lastActiveDate: null, // YYYY-MM-DD of the last day a quest was completed
quests: [] // { id, name, tier, xp, completed }
};
let state = loadState();
let selectedTier = { tier: 'small', xp: 5 };
// --- Live sync mode ---
// By default, this page shows a generic demo — it never touches Supabase or your
// real automated tasks. Live mode (pulling your actual daily tasks) only turns on
// for you, on your own device, and stays off for anyone else who visits this link.
const LIVE_SYNC_KEY = 'questlog_live_sync';
function isLiveSyncEnabled() {
return localStorage.getItem(LIVE_SYNC_KEY) === 'true';
}
function checkForSyncActivationLink() {
const params = new URLSearchParams(window.location.search);
if (params.get('sync') === 'on') {
localStorage.setItem(LIVE_SYNC_KEY, 'true');
// Strip the param from the URL so it isn't visible or shareable by accident
params.delete('sync');
const cleanUrl = window.location.pathname +
(params.toString() ? `?${params}` : '') + window.location.hash;
window.history.replaceState({}, '', cleanUrl);
}
}
const DEMO_QUESTS = [
{ id: 'demo-1', name: 'Morning outreach batch', tier: 'medium', xp: 15, completed: true, source: 'automation' },
{ id: 'demo-2', name: 'Post to socials', tier: 'small', xp: 5, completed: false, source: 'automation' },
{ id: 'demo-3', name: 'Deep work block', tier: 'boss', xp: 60, completed: false, source: 'manual' }
];
function seedDemoQuestsIfEmpty() {
const today = todayStr();
const hasAnyToday = state.quests.length > 0;
if (!hasAnyToday) {
state.quests = DEMO_QUESTS.map(q => ({ ...q }));
state.lastActiveDate = today;
saveState();
}
}
function loadState() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return structuredClone(defaultState);
const parsed = JSON.parse(raw);
return { ...structuredClone(defaultState), ...parsed };
} catch (e) {
console.error('Quest Log: failed to load state', e);
return structuredClone(defaultState);
}
}
function saveState() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
} catch (e) {
console.error('Quest Log: failed to save state', e);
}
}
function todayStr() {
return new Date().toISOString().slice(0, 10);
}
function daysBetween(a, b) {
const d1 = new Date(a);
const d2 = new Date(b);
return Math.round((d2 - d1) / (1000 * 60 * 60 * 24));
}
// Clear completed quests from a previous day, keep incomplete ones, adjust streak
function handleDailyRollover() {
const today = todayStr();
if (!state.lastActiveDate) {
state.lastActiveDate = today;
saveState();
return;
}
if (state.lastActiveDate === today) return; // same day, nothing to do
const gap = daysBetween(state.lastActiveDate, today);
// Streak logic: if exactly 1 day passed since last completion, streak continues.
// If more than 1 day passed with no completions, streak resets.
if (gap > 1) {
state.streak = 0;
}
// Remove completed quests, keep incomplete ones for today
state.quests = state.quests.filter(q => !q.completed);
state.lastActiveDate = today;
saveState();
}
function xpForLevel(level) {
// Each level requires a bit more XP than the last
return Math.round(100 * Math.pow(1.15, level - 1));
}
function addXp(amount) {
state.totalXp += amount;
state.currentXp += amount;
while (state.currentXp >= state.xpToNextLevel) {
state.currentXp -= state.xpToNextLevel;
state.level += 1;
state.xpToNextLevel = xpForLevel(state.level);
showToast(`Level up! You're now level ${state.level}`);
}
}
function registerCompletionForStreak() {
const today = todayStr();
const hasCompletionToday = state.quests.some(q => q.completed);
if (hasCompletionToday && state.lastStreakDate !== today) {
state.streak += 1;
state.lastStreakDate = today;
}
}
function showToast(message) {
const toast = document.getElementById('toast');
toast.textContent = message;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 2200);
}
function uid() {
return Math.random().toString(36).slice(2, 10);
}
function render() {
document.getElementById('levelNum').textContent = state.level;
document.getElementById('xpCurrent').textContent = state.currentXp;
document.getElementById('xpNeeded').textContent = state.xpToNextLevel;
document.getElementById('totalXp').textContent = state.totalXp;
document.getElementById('streakCount').textContent = state.streak;
document.getElementById('questsToday').textContent =
state.quests.filter(q => q.completed).length;
const subEl = document.querySelector('.masthead .sub');
if (subEl) {
subEl.textContent = isLiveSyncEnabled()
? 'Daily Chronicle · Live'
: 'Daily Chronicle · Demo';
}
const pct = Math.min(1, state.currentXp / state.xpToNextLevel);
const offset = RING_CIRCUMFERENCE * (1 - pct);
document.getElementById('ringFg').style.strokeDashoffset = offset;
const list = document.getElementById('questList');
const emptyState = document.getElementById('emptyState');
list.innerHTML = '';
if (state.quests.length === 0) {
emptyState.style.display = 'block';
} else {
emptyState.style.display = 'none';
state.quests
.slice()
.sort((a, b) => a.completed - b.completed)
.forEach(q => list.appendChild(renderQuestItem(q)));
}
}
function renderQuestItem(q) {
const item = document.createElement('div');
item.className = 'quest-item' + (q.completed ? ' completed' : '');
item.dataset.tier = q.tier;
const check = document.createElement('button');
check.className = 'quest-check' + (q.completed ? ' checked' : '');
check.textContent = q.completed ? '✓' : '';
check.setAttribute('aria-label', q.completed ? 'Mark incomplete' : 'Mark complete');
check.addEventListener('click', () => toggleQuest(q.id));
const name = document.createElement('span');
name.className = 'quest-name';
name.textContent = q.name;
if (q.source === 'automation') {
const tag = document.createElement('span');
tag.className = 'quest-auto-tag';
tag.textContent = 'auto';
name.appendChild(tag);
}
const xp = document.createElement('span');
xp.className = 'quest-xp';
xp.textContent = `+${q.xp}xp`;
const del = document.createElement('button');
del.className = 'quest-del';
del.textContent = '✕';
del.setAttribute('aria-label', 'Delete quest');
del.addEventListener('click', () => deleteQuest(q.id));
item.append(check, name, xp, del);
return item;
}
function toggleQuest(id) {
const q = state.quests.find(q => q.id === id);
if (!q) return;
q.completed = !q.completed;
if (q.completed) {
addXp(q.xp);
registerCompletionForStreak();
showToast(`Quest complete: +${q.xp}xp`);
} else {
// Undo XP if unchecked
state.totalXp = Math.max(0, state.totalXp - q.xp);
state.currentXp = Math.max(0, state.currentXp - q.xp);
}
saveState();
render();
}
function deleteQuest(id) {
state.quests = state.quests.filter(q => q.id !== id);
saveState();
render();
}
function addQuest() {
const input = document.getElementById('questInput');
const name = input.value.trim();
if (!name) return;
state.quests.push({
id: uid(),
name,
tier: selectedTier.tier,
xp: selectedTier.xp,
completed: false
});
input.value = '';
saveState();
render();
}
function resetAll() {
if (!confirm('This clears all quests, XP, and streak data. Continue?')) return;
state = structuredClone(defaultState);
state.lastActiveDate = todayStr();
saveState();
render();
}
// --- Event wiring ---
document.querySelectorAll('.tier-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tier-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
selectedTier = { tier: btn.dataset.tier, xp: parseInt(btn.dataset.xp, 10) };
});
});
document.getElementById('addBtn').addEventListener('click', addQuest);
document.getElementById('questInput').addEventListener('keydown', e => {
if (e.key === 'Enter') addQuest();
});
document.getElementById('resetBtn').addEventListener('click', resetAll);
// Pull in today's quests added by your automations (e.g. a Cowork or Make.com
// scenario that writes rows into the quest_log_quests table each morning).
// This only reads — nothing here can write back to Supabase.
async function fetchAutomationQuests() {
if (!supabaseClient) return;
const today = todayStr();
const { data, error } = await supabaseClient
.from('quest_log_quests')
.select('id, name, tier, xp, quest_date')
.eq('quest_date', today)
.eq('source', 'automation');
if (error) {
console.error('Quest Log: failed to fetch automation quests', error);
return;
}
data.forEach(row => {
const alreadyExists = state.quests.some(q => q.id === row.id);
if (!alreadyExists) {
state.quests.push({
id: row.id,
name: row.name,
tier: row.tier,
xp: row.xp,
completed: false,
source: 'automation'
});
}
});
saveState();
render();
}
// --- Init ---
checkForSyncActivationLink();
handleDailyRollover();
if (isLiveSyncEnabled()) {
render();
fetchAutomationQuests();
} else {
seedDemoQuestsIfEmpty();
render();
}