-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathshow.tsx
More file actions
365 lines (332 loc) · 13.7 KB
/
show.tsx
File metadata and controls
365 lines (332 loc) · 13.7 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// import { rawConnect } from "@fireproof/cloud";
import React, { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Link, useParams } from "react-router-dom";
import { useFireproof } from "use-fireproof";
import { TableRow, DynamicTable } from "../../components/DynamicTable.jsx";
import { headersForDocs } from "../../components/dynamicTableHelpers.js";
import { SYNC_DB_NAME, truncateDbName } from "../../helpers.js";
export function DatabasesShow() {
const { name } = useParams();
if (!name) {
throw new Error("Name is required");
}
return <TableView key={name} name={name} />;
}
function TableView({ name }: { name: string }) {
const { useLiveQuery, database } = useFireproof(name);
const [showConnectionInfo, setShowConnectionInfo] = useState(false);
const [copySuccess, setCopySuccess] = useState(false);
const [showActions, setShowActions] = useState(false);
const [showQuickstart, setShowQuickstart] = useState(false);
const [activeTab, setActiveTab] = useState<"react" | "vanilla">("react");
const connectionInfoRef = useRef<HTMLDivElement>(null);
const actionsRef = useRef<HTMLDivElement>(null);
const [connectionInfoPosition, setConnectionInfoPosition] = useState({
top: 0,
left: 0,
});
const { useLiveQuery: usePetnameLiveQuery } = useFireproof(SYNC_DB_NAME);
const myPetnames = usePetnameLiveQuery<{
localName: string;
endpoint: string;
remoteName: string;
}>("sanitizedRemoteName", {
key: name,
});
console.log(myPetnames);
const petName = myPetnames.docs[0]?.localName || "";
let connection, remoteName;
if (myPetnames.docs.length > 0) {
// const endpoint = myPetnames.docs[0].endpoint;
remoteName = myPetnames.docs[0].remoteName;
// if (endpoint) {
// connection = rawConnect(database as any, remoteName, endpoint);
// }
}
const allDocs = useLiveQuery("_id");
const docs = allDocs.docs.filter((doc) => doc);
const headers = headersForDocs(docs);
async function handleDeleteDatabase() {
if (window.confirm(`Are you sure you want to delete the database "${name}"?`)) {
const DBDeleteRequest = window.indexedDB.deleteDatabase(`fp.${name}`);
DBDeleteRequest.onerror = () => {
console.error("Error deleting database.");
};
DBDeleteRequest.onsuccess = (event) => {
console.log("Database deleted successfully");
console.log(event);
};
window.location.href = "/";
}
}
async function deleteDocument(docId: string) {
if (window.confirm(`Are you sure you want to delete this document?`)) {
await database.del(docId);
}
}
const currentHost = window.location.origin;
const currentEndpoint = myPetnames.docs[0]?.endpoint || "";
const currentLocalName = myPetnames.docs[0]?.localName || "";
const currentRemoteName = myPetnames.docs[0]?.remoteName || "";
const connectionUrl = `${currentHost}/fp/databases/connect?endpoint=${encodeURIComponent(
currentEndpoint,
)}&localName=${encodeURIComponent(currentLocalName)}&remoteName=${encodeURIComponent(currentRemoteName)}`;
function copyToClipboard(e: React.MouseEvent) {
e.stopPropagation(); // Prevent event from bubbling up
navigator.clipboard.writeText(connectionUrl).then(
() => {
setCopySuccess(true);
setTimeout(() => setCopySuccess(false), 2000);
},
(err) => console.error("Could not copy text: ", err),
);
}
function handleConnectionInfoClick() {
if (connectionInfoRef.current) {
const rect = connectionInfoRef.current.getBoundingClientRect();
setConnectionInfoPosition({
top: rect.bottom + window.scrollY + 2,
left: rect.right + window.scrollX - 256, // 256px is width of the popup
});
}
setShowConnectionInfo(!showConnectionInfo);
}
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
// Don't close if clicking inside the popup
const popupElement = document.getElementById("connection-info-popup");
if (popupElement?.contains(event.target as Node)) {
return;
}
if (connectionInfoRef.current && !connectionInfoRef.current.contains(event.target as Node)) {
setShowConnectionInfo(false);
}
if (actionsRef.current && !actionsRef.current.contains(event.target as Node)) {
setShowActions(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
return (
<div className="p-6 bg-[--muted]">
{connection && (
<div className="mb-4 bg-[--background] border border-[--border] rounded-md p-4">
<div className="flex items-center cursor-pointer" onClick={() => setShowQuickstart(!showQuickstart)}>
<h3 className="font-bold text-sm flex-grow">Quickstart</h3>
<svg
xmlns="http://www.w3.org/2000/svg"
className={`h-4 w-4 transform transition-transform ${showQuickstart ? "rotate-180" : ""}`}
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg>
</div>
{showQuickstart && (
<div className="mt-4">
<div className="flex border-b border-[--border] mb-4">
<button
className={`px-4 py-2 text-sm font-medium ${
activeTab === "react" ? "border-b-2 border-[--accent] text-[--accent]" : "text-[--muted-foreground]"
}`}
onClick={() => setActiveTab("react")}
>
React
</button>
<button
className={`px-4 py-2 text-sm font-medium ${
activeTab === "vanilla" ? "border-b-2 border-[--accent] text-[--accent]" : "text-[--muted-foreground]"
}`}
onClick={() => setActiveTab("vanilla")}
>
Vanilla JS
</button>
</div>
{activeTab === "react" && (
<pre className="bg-[--muted] p-2 rounded text-xs overflow-x-auto">
{`
import { useFireproof } from "@fireproof/core-react";
import { connect } from "@fireproof/cloud";
export default function App() {
const { database, useLiveQuery, useDocument } = useFireproof("my_db");
connect(database, '${remoteName}');
const { docs } = useLiveQuery("_id");
const [newDoc, setNewDoc, saveNewDoc] = useDocument({ input: "" });
const handleSubmit = async (e) => {
e.preventDefault();
if (newDoc.input) {
await saveNewDoc();
setNewDoc(); // Reset for new entry
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
value={newDoc.input}
onChange={(e) => setNewDoc({ input: e.target.value })}
/>
<button>Add</button>
</form>
<ul>
{docs.map((doc) => (
<li key={doc._id}>{JSON.stringify(doc)}</li>
))}
</ul>
</div>
);
}`}
</pre>
)}
{activeTab === "vanilla" && <pre className="bg-[--muted] p-2 rounded text-xs overflow-x-auto">{``}</pre>}
</div>
)}
</div>
)}
<div className="@container flex justify-between items-start mb-4 gap-4">
<nav className="text-base max-[500px]:text-sm text-[--muted-foreground] flex-grow flex items-center flex-wrap">
<Link to={`/fp/databases/${name}`} className="font-medium text-[--foreground] hover:underline truncate max-w-[150px]">
{truncateDbName(name, 12)}
</Link>
{petName && (
<>
<span className="mx-1">></span>
<span className="truncate max-w-[80px]">{petName}</span>
</>
)}
<span className="mx-1">></span>
<span className="truncate">All Documents ({docs.length})</span>
</nav>
<div className="flex gap-2 items-center max-[500px]:self-auto">
{connection && (
<div className="relative" ref={connectionInfoRef}>
<div
onClick={handleConnectionInfoClick}
className="cursor-pointer inline-flex items-center justify-center rounded bg-[--background] px-3 py-2 text-sm font-medium text-[--foreground] transition-colors hover:bg-[--background]/80 border border-[--border] whitespace-nowrap"
>
<span className="w-2 h-2 bg-green-500 rounded-full mr-2"></span>
Connected
</div>
{showConnectionInfo &&
createPortal(
<div
id="connection-info-popup"
className="fixed bg-[--background] border border-[--border] rounded-md shadow-lg z-[9999] w-64"
style={{
top: connectionInfoPosition.top + "px",
left: connectionInfoPosition.left + "px",
}}
>
<div className="p-4">
<h3 className="font-bold mb-2">Share Database:</h3>
<button
onClick={copyToClipboard}
className="w-full p-2 bg-[--accent] text-accent-foreground rounded hover:bg-[--accent]/80 transition-colors"
>
{copySuccess ? "Copied!" : "Copy Share Link"}
</button>
</div>
</div>,
document.body,
)}
</div>
)}
{/* Mobile Actions Dropdown */}
<div className="relative block @[575px]:hidden" ref={actionsRef}>
<button
onClick={() => setShowActions(!showActions)}
className="inline-flex items-center justify-center rounded bg-[--accent] px-3 py-2 text-sm font-medium text-accent-foreground transition-colors hover:bg-[--accent]/80 whitespace-nowrap"
>
Actions
<svg
xmlns="http://www.w3.org/2000/svg"
className={`h-4 w-4 ml-2 transform transition-transform ${showActions ? "rotate-180" : ""}`}
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg>
</button>
{showActions && (
<div className="absolute right-0 mt-2 w-48 bg-[--background] rounded-md shadow-lg z-10 border border-[--border]">
<Link
to={`/fp/databases/${name}/docs/new`}
className="block px-4 py-2 text-sm text-[--foreground] hover:bg-[--muted] hover:text-[--foreground] whitespace-nowrap"
>
New Document
</Link>
<button
onClick={handleDeleteDatabase}
className="w-full text-left px-4 py-2 text-sm text-[--destructive] hover:bg-[--destructive] hover:text-destructive-foreground whitespace-nowrap"
>
Delete Database
</button>
</div>
)}
</div>
{/* Desktop Actions */}
<div className="hidden @[575px]:flex gap-2">
<Link
to={`/fp/databases/${name}/docs/new`}
className="inline-flex items-center justify-center rounded bg-[--accent] px-3 py-2 text-sm font-medium text-accent-foreground transition-colors hover:bg-[--accent]/80 whitespace-nowrap"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M10 5a1 1 0 011 1v3h3a1 1 0 110 2h-3v3a1 1 0 11-2 0v-3H6a1 1 0 110-2h3V6a1 1 0 011-1z"
clipRule="evenodd"
/>
</svg>
New Document
</Link>
<button
onClick={handleDeleteDatabase}
className="inline-flex items-center justify-center rounded bg-[--destructive] px-3 py-2 text-sm text-destructive-foreground transition-colors hover:bg-[--destructive]/80 whitespace-nowrap"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z"
clipRule="evenodd"
/>
</svg>
Delete Database
</button>
</div>
</div>
</div>
<div>
{docs.length === 0 ? (
<div className="mt-4 text-center text-[--muted-foreground]">
No documents found.{" "}
<Link to={`/fp/databases/${name}/docs/new`} className="font-semibold text-[--accent] hover:underline">
Create a new document
</Link>{" "}
to get started.
</div>
) : (
<DynamicTable
headers={headers}
th="key"
link={["_id"]}
rows={docs as TableRow[]}
dbName={name}
onDelete={deleteDocument}
/>
)}
</div>
</div>
);
}