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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
|
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import {
DndContext,
PointerSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import {
SortableContext,
arrayMove,
rectSortingStrategy,
useSortable,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { SourceState } from "@/lib/types";
import { useAction } from "@/hooks/useAction";
import { spanStyle, GRID_COL_MIN, GRID_ROW_PX, GRID_GAP, MAX_ROWS } from "@/lib/layout";
import { SourceCard } from "./cards/SourceCard";
import { ThingsCard } from "./cards/ThingsCard";
export function Dashboard() {
const router = useRouter();
const [items, setItems] = useState<SourceState[]>([]);
const [loading, setLoading] = useState(true);
const [refreshingAll, setRefreshingAll] = useState(false);
const [refreshingId, setRefreshingId] = useState<string | null>(null);
const [generating, setGenerating] = useState(false);
const [editing, setEditing] = useState(false);
// Initial paint from cache, then refresh stale sources in the background.
useEffect(() => {
let alive = true;
(async () => {
const cached = await fetch("/api/sources").then((r) => r.json());
if (!alive) return;
setItems(cached.sources);
setLoading(false);
const fresh = await fetch("/api/sources?fresh=1").then((r) => r.json());
if (alive) setItems(fresh.sources);
})();
return () => {
alive = false;
};
}, []);
const refreshAll = useCallback(async () => {
setRefreshingAll(true);
try {
const fresh = await fetch("/api/sources?force=1").then((r) => r.json());
setItems(fresh.sources);
} finally {
setRefreshingAll(false);
}
}, []);
const refreshOne = useCallback(async (id: string) => {
setRefreshingId(id);
try {
const res = await fetch(`/api/sources/${id}/refresh`, { method: "POST" });
if (res.ok) {
const { source } = await res.json();
setItems((prev) => prev.map((it) => (it.source.id === id ? source : it)));
}
} finally {
setRefreshingId(null);
}
}, []);
const generatePaper = useCallback(async () => {
setGenerating(true);
try {
const res = await fetch("/api/edition", { method: "POST" });
if (res.ok) router.push("/editions");
} finally {
setGenerating(false);
}
}, [router]);
// Persist a layout patch (position / cols / rows) for one source.
const patchSource = useCallback((id: string, patch: Record<string, number>) => {
void fetch(`/api/sources/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
}, []);
// Drag-reorder: renumber enabled cards into the same set of position slots they
// already occupy, leaving disabled (hidden) sources' positions untouched.
const onDragEnd = useCallback(
(e: DragEndEvent) => {
const { active, over } = e;
if (!over || active.id === over.id) return;
setItems((prev) => {
const enabled = prev.filter((it) => it.source.enabled);
const oldIndex = enabled.findIndex((it) => it.source.id === active.id);
const newIndex = enabled.findIndex((it) => it.source.id === over.id);
if (oldIndex < 0 || newIndex < 0) return prev;
const slots = enabled.map((it) => it.source.position).sort((a, b) => a - b);
const reordered = arrayMove(enabled, oldIndex, newIndex);
const posById = new Map<string, number>();
reordered.forEach((it, i) => {
const pos = slots[i];
if (pos !== it.source.position) patchSource(it.source.id, { position: pos });
posById.set(it.source.id, pos);
});
return prev
.map((it) =>
posById.has(it.source.id)
? { ...it, source: { ...it.source, position: posById.get(it.source.id)! } }
: it,
)
.sort((a, b) => a.source.position - b.source.position);
});
},
[patchSource],
);
// Live local resize, persisted on release.
const resize = useCallback(
(id: string, cols: number, rows: number, commit: boolean) => {
setItems((prev) =>
prev.map((it) =>
it.source.id === id ? { ...it, source: { ...it.source, cols, rows } } : it,
),
);
if (commit) patchSource(id, { cols, rows });
},
[patchSource],
);
useAction(
{
id: "refresh-all",
label: "Refresh all sources",
combo: "mod+shift+r",
group: "Actions",
run: refreshAll,
},
[refreshAll],
);
useAction(
{
id: "generate-paper",
label: "Generate today's paper",
combo: "mod+shift+g",
group: "Actions",
run: generatePaper,
},
[generatePaper],
);
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
);
const enabled = items.filter((it) => it.source.enabled);
const gridStyle: React.CSSProperties = {
display: "grid",
gridTemplateColumns: `repeat(auto-fill, minmax(${GRID_COL_MIN}px, 1fr))`,
gridAutoRows: `${GRID_ROW_PX}px`,
gridAutoFlow: "dense",
gap: GRID_GAP,
};
return (
<main className="w-full px-6 py-8">
<div className="flex items-center justify-between mb-6">
<p className="text-sm" style={{ color: "var(--text-muted)" }}>
{new Date().toLocaleDateString(undefined, {
weekday: "long",
month: "long",
day: "numeric",
})}
</p>
<div className="flex gap-2">
<Btn onClick={() => setEditing((v) => !v)} primary={editing}>
{editing ? "Done" : "Edit layout"}
</Btn>
<Btn onClick={generatePaper} disabled={generating}>
{generating ? "Generating…" : "Generate paper"}
</Btn>
<Btn onClick={refreshAll} disabled={refreshingAll} primary={!editing}>
{refreshingAll ? "Refreshing…" : "Refresh all"}
</Btn>
</div>
</div>
{editing && (
<p className="text-xs mb-3" style={{ color: "var(--text-faint)" }}>
Drag cards to reorder · drag a card’s bottom-right corner to resize · click
Done when finished.
</p>
)}
{loading ? (
<p style={{ color: "var(--text-faint)" }}>Loading…</p>
) : editing ? (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
<SortableContext items={enabled.map((it) => it.source.id)} strategy={rectSortingStrategy}>
<div style={gridStyle}>
{enabled.map((it) => (
<SortableTile key={it.source.id} state={it} onResize={resize}>
<CardFor
state={it}
onRefresh={() => refreshOne(it.source.id)}
refreshing={refreshingId === it.source.id}
/>
</SortableTile>
))}
</div>
</SortableContext>
</DndContext>
) : (
<div style={gridStyle}>
{enabled.map((it) => (
<div
key={it.source.id}
style={{ ...spanStyle(it.source.cols, it.source.rows), minHeight: 0 }}
>
<CardFor
state={it}
onRefresh={() => refreshOne(it.source.id)}
refreshing={refreshingId === it.source.id}
/>
</div>
))}
</div>
)}
</main>
);
}
function CardFor({
state,
onRefresh,
refreshing,
}: {
state: SourceState;
onRefresh: () => void;
refreshing: boolean;
}) {
return state.source.kind === "todos" ? (
<ThingsCard state={state} onRefresh={onRefresh} refreshing={refreshing} />
) : (
<SourceCard state={state} onRefresh={onRefresh} refreshing={refreshing} />
);
}
// A draggable, corner-resizable grid tile (edit mode only).
function SortableTile({
state,
onResize,
children,
}: {
state: SourceState;
onResize: (id: string, cols: number, rows: number, commit: boolean) => void;
children: React.ReactNode;
}) {
const { source } = state;
const { setNodeRef, attributes, listeners, transform, transition, isDragging } = useSortable({
id: source.id,
});
const nodeRef = useRef<HTMLDivElement | null>(null);
// Corner-resize: translate pointer movement into whole grid-cell span changes.
const onResizeStart = (e: React.PointerEvent) => {
e.preventDefault();
e.stopPropagation();
const grid = nodeRef.current?.parentElement;
if (!grid) return;
const cols = getComputedStyle(grid).gridTemplateColumns.split(" ").filter(Boolean).length || 1;
const cellW = (grid.clientWidth - GRID_GAP * (cols - 1)) / cols;
const stepX = cellW + GRID_GAP;
const stepY = GRID_ROW_PX + GRID_GAP;
const startX = e.clientX;
const startY = e.clientY;
const startCols = source.cols;
const startRows = source.rows;
(e.target as Element).setPointerCapture(e.pointerId);
const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));
const move = (ev: PointerEvent) => {
const nextCols = clamp(startCols + Math.round((ev.clientX - startX) / stepX), 1, cols);
const nextRows = clamp(startRows + Math.round((ev.clientY - startY) / stepY), 1, MAX_ROWS);
onResize(source.id, nextCols, nextRows, false);
};
const up = (ev: PointerEvent) => {
const nextCols = clamp(startCols + Math.round((ev.clientX - startX) / stepX), 1, cols);
const nextRows = clamp(startRows + Math.round((ev.clientY - startY) / stepY), 1, MAX_ROWS);
onResize(source.id, nextCols, nextRows, true);
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
};
return (
<div
ref={(el) => {
setNodeRef(el);
nodeRef.current = el;
}}
style={{
...spanStyle(source.cols, source.rows),
minHeight: 0,
position: "relative",
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.4 : 1,
zIndex: isDragging ? 10 : undefined,
cursor: "grab",
outline: "2px dashed var(--border-strong)",
outlineOffset: -2,
borderRadius: 8,
}}
{...attributes}
{...listeners}
>
{/* Block inner clicks/scroll while editing; this overlay is the drag surface. */}
<div style={{ pointerEvents: "none", height: "100%" }}>{children}</div>
{/* Resize handle — bottom-right corner. */}
<div
onPointerDown={onResizeStart}
title="Drag to resize"
style={{
position: "absolute",
right: 2,
bottom: 2,
width: 16,
height: 16,
cursor: "nwse-resize",
color: "var(--text-on-accent)",
background: "var(--accent)",
borderRadius: 4,
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: 10,
lineHeight: 1,
zIndex: 5,
}}
>
⤡
</div>
</div>
);
}
function Btn({
children,
onClick,
disabled,
primary,
}: {
children: React.ReactNode;
onClick: () => void;
disabled?: boolean;
primary?: boolean;
}) {
return (
<button
onClick={onClick}
disabled={disabled}
className="px-3 py-2 text-sm font-medium"
style={{
background: primary ? "var(--accent)" : "var(--bg-elevated)",
color: primary ? "var(--text-on-accent)" : "var(--text)",
border: `1px solid ${primary ? "var(--accent)" : "var(--border-strong)"}`,
borderRadius: 6,
opacity: disabled ? 0.6 : 1,
}}
>
{children}
</button>
);
}
|