-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathhome-page.tsx
More file actions
636 lines (589 loc) · 19 KB
/
Copy pathhome-page.tsx
File metadata and controls
636 lines (589 loc) · 19 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/* Copyright 2026 Marimo. All rights reserved. */
import { useAtom, useSetAtom } from "jotai";
import {
BookTextIcon,
ChevronDownIcon,
ChevronRightIcon,
ChevronsDownUpIcon,
ClockIcon,
ExternalLinkIcon,
PlayCircleIcon,
PowerOffIcon,
RefreshCcwIcon,
SearchIcon,
} from "lucide-react";
import type React from "react";
import { Suspense, use, useEffect, useMemo, useRef, useState } from "react";
import {
type NodeApi,
type NodeRendererProps,
Tree,
type TreeApi,
} from "react-arborist";
import { useLocale } from "react-aria";
import useEvent from "react-use-event-hook";
import { MarkdownIcon } from "@/components/editor/cell/code/icons";
import {
FILE_ICON as FILE_TYPE_ICONS,
type FileIconType as FileType,
guessFileIconType as guessFileType,
} from "@/components/editor/file-tree/file-icons";
import { FileNameInput } from "@/components/editor/file-tree/file-name-input";
import {
DeleteMenuItem,
DuplicateMenuItem,
FileActionsDropdown,
RenameMenuItem,
useFileOperations,
useNotebookFileActions,
} from "@/components/editor/file-tree/file-operations";
import { useImperativeModal } from "@/components/modal/ImperativeModal";
import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { Label } from "@/components/ui/label";
import { Tooltip } from "@/components/ui/tooltip";
import { toast } from "@/components/ui/use-toast";
import { getSessionId, isSessionId } from "@/core/kernel/session";
import { useRequestClient } from "@/core/network/requests";
import type { FileInfo, MarimoFile } from "@/core/network/types";
import { combineAsyncData, useAsyncData } from "@/hooks/useAsyncData";
import { useInterval } from "@/hooks/useInterval";
import { Banner } from "@/plugins/impl/common/error-banner";
import { assertExists } from "@/utils/assertExists";
import { cn } from "@/utils/cn";
import { timeAgo } from "@/utils/dates";
import { prettyError } from "@/utils/errors";
import { Maps } from "@/utils/maps";
import { Paths } from "@/utils/paths";
import { asURL } from "@/utils/url";
import { newNotebookURL } from "@/utils/urls";
import { ConfigButton } from "../app-config/app-config-button";
import { ErrorBoundary } from "../editor/boundary/ErrorBoundary";
import { ShutdownButton } from "../editor/controls/shutdown-button";
import {
Header,
OpenTutorialDropDown,
ResourceLinks,
} from "../home/components";
import {
expandedFoldersAtom,
includeMarkdownAtom,
RunningNotebooksContext,
WorkspaceContext,
} from "../home/state";
import { Spinner } from "../icons/spinner";
import { Input } from "../ui/input";
function tabTarget(path: string) {
// Consistent tab target so we open in the same tab when clicking on the same notebook
return `${getSessionId()}-${encodeURIComponent(path)}`;
}
const HomePage: React.FC = () => {
const [nonce, setNonce] = useState(0);
const { getRecentFiles, getRunningNotebooks } = useRequestClient();
const recentsResponse = useAsyncData(() => getRecentFiles(), []);
useInterval(
() => {
setNonce((nonce) => nonce + 1);
},
// Refresh every 10 seconds, or when the document becomes visible
{ delayMs: 10_000, whenVisible: true },
);
const runningResponse = useAsyncData(async () => {
const response = await getRunningNotebooks();
return Maps.keyBy(response.files, (file) => file.path);
}, [nonce]);
const response = combineAsyncData(recentsResponse, runningResponse);
if (response.error) {
throw response.error;
}
const data = response.data;
if (!data) {
return <Spinner centered={true} size="xlarge" />;
}
const [recents, running] = data;
return (
<Suspense>
<RunningNotebooksContext
value={{
runningNotebooks: running,
setRunningNotebooks: runningResponse.setData,
}}
>
<div className="absolute top-3 right-5 flex gap-3 z-50">
<OpenTutorialDropDown />
<ConfigButton showAppConfig={false} />
<ShutdownButton
description={`This will shutdown the notebook server and terminate all running notebooks (${running.size}). You'll lose all data that's in memory.`}
/>
</div>
<div className="flex flex-col gap-6 max-w-6xl container pt-5 pb-20 z-10">
<img src="logo.png" alt="marimo logo" className="w-48 mb-2" />
<CreateNewNotebook />
<ResourceLinks />
<NotebookList
header={<Header Icon={PlayCircleIcon}>Running notebooks</Header>}
files={[...running.values()]}
/>
<NotebookList
header={<Header Icon={ClockIcon}>Recent notebooks</Header>}
files={recents.files}
/>
<ErrorBoundary>
<WorkspaceNotebooks onRefreshRecents={recentsResponse.refetch} />
</ErrorBoundary>
</div>
</RunningNotebooksContext>
</Suspense>
);
};
const WorkspaceNotebooks: React.FC<{ onRefreshRecents: () => void }> = ({
onRefreshRecents,
}) => {
const { getWorkspaceFiles } = useRequestClient();
const [includeMarkdown, setIncludeMarkdown] = useAtom(includeMarkdownAtom);
const [searchText, setSearchText] = useState("");
const {
isPending,
data: workspace,
error,
isFetching,
refetch,
} = useAsyncData(
() => getWorkspaceFiles({ includeMarkdown }),
[includeMarkdown],
);
// Fire-and-forget refresh of both the workspace tree and the "Recent
// notebooks" list — file mutations on the workspace tree can affect both,
// so we invalidate them together rather than having two refresh triggers.
const refreshWorkspace = useEvent(() => {
refetch();
onRefreshRecents();
});
const workspaceContextValue = useMemo(
() => ({ root: workspace?.root ?? "", refreshWorkspace }),
[workspace?.root, refreshWorkspace],
);
if (isPending) {
return <Spinner centered={true} size="xlarge" className="mt-6" />;
}
if (error) {
return (
<Banner kind="danger" className="rounded p-4">
{prettyError(error)}
</Banner>
);
}
return (
<WorkspaceContext value={workspaceContextValue}>
<div className="flex flex-col gap-2">
{workspace.hasMore && (
<Banner kind="warn" className="rounded p-4">
Showing first {workspace.fileCount} files. Your workspace has more
files.
</Banner>
)}
<Header
Icon={BookTextIcon}
control={
<div className="flex items-center gap-2">
<Input
id="search"
value={searchText}
icon={<SearchIcon size={13} />}
onChange={(e) => setSearchText(e.target.value)}
placeholder="Search"
className="mb-0 border-border"
/>
<CollapseAllButton />
<Checkbox
data-testid="include-markdown-checkbox"
id="include-markdown"
checked={includeMarkdown}
onCheckedChange={(checked) =>
setIncludeMarkdown(Boolean(checked))
}
/>
<Label htmlFor="include-markdown">Include markdown</Label>
</div>
}
>
Workspace
<Button
variant="text"
size="icon"
className="w-4 h-4 ml-1 p-0 opacity-70 hover:opacity-100"
onClick={() => refetch()}
aria-label="Refresh workspace"
>
<RefreshCcwIcon className="w-4 h-4" />
</Button>
{isFetching && <Spinner size="small" />}
</Header>
<div className="flex flex-col divide-y divide-(--slate-3) border rounded overflow-hidden max-h-192 overflow-y-auto shadow-sm bg-background">
<NotebookFileTree searchText={searchText} files={workspace.files} />
</div>
</div>
</WorkspaceContext>
);
};
const CollapseAllButton: React.FC = () => {
const setOpenState = useSetAtom(expandedFoldersAtom);
return (
<Button
variant="text"
size="sm"
className="h-fit hidden sm:flex"
onClick={() => {
setOpenState({});
}}
>
<ChevronsDownUpIcon className="w-4 h-4 mr-1" />
Collapse all
</Button>
);
};
const NotebookFileTree: React.FC<{
files: FileInfo[];
searchText?: string;
}> = ({ files, searchText }) => {
const [openState, setOpenState] = useAtom(expandedFoldersAtom);
const openStateIsEmpty = Object.keys(openState).length === 0;
const ref = useRef<TreeApi<FileInfo>>(undefined);
const { root, refreshWorkspace } = use(WorkspaceContext);
const { renameFile } = useFileOperations({ root });
useEffect(() => {
// If empty, collapse all
if (openStateIsEmpty) {
ref.current?.closeAll();
}
}, [openStateIsEmpty]);
const handleRename = useEvent(async (id: string, name: string) => {
const node = ref.current?.get(id);
if (!node) {
toast({
title: "Failed",
description: `Node with id ${id} not found in the tree`,
});
return;
}
const result = await renameFile(node.data, name);
if (result) {
refreshWorkspace();
}
});
if (files.length === 0) {
return (
<div className="flex flex-col px-5 py-10 items-center justify-center">
<p className="text-center text-muted-foreground">
No files in this workspace
</p>
</div>
);
}
return (
<Tree<FileInfo>
ref={ref}
width="100%"
height={500}
searchTerm={searchText}
className="h-full"
idAccessor={(data) => data.path}
data={files}
openByDefault={false}
initialOpenState={openState}
onToggle={async (id) => {
const prevOpen = openState[id] ?? false;
setOpenState({ ...openState, [id]: !prevOpen });
}}
onRename={async ({ id, name }) => {
await handleRename(id, name);
}}
padding={5}
rowHeight={35}
indent={15}
overscanCount={1000}
// Hide the drop cursor
renderCursor={() => null}
// Disable interactions
disableDrop={true}
disableDrag={true}
disableMultiSelection={true}
>
{Node}
</Tree>
);
};
const Node = ({ node, style }: NodeRendererProps<FileInfo>) => {
const fileType: FileType = node.data.isDirectory
? "directory"
: guessFileType(node.data.name);
const Icon = FILE_TYPE_ICONS[fileType];
const iconEl = <Icon className="w-5 h-5 shrink-0" strokeWidth={1.5} />;
const { root } = use(WorkspaceContext);
const { runningNotebooks } = use(RunningNotebooksContext);
const renderItem = () => {
const itemClassName =
"flex items-center pl-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l flex-1 overflow-hidden h-full pr-3 gap-2";
// Inline rename input; react-arborist flips `node.isEditing` when
// `node.edit()` is called from the FileActions menu.
if (node.isEditing) {
return (
<div className={itemClassName}>
{iconEl}
<FileNameInput node={node} />
</div>
);
}
if (node.data.isDirectory) {
return (
<span className={itemClassName}>
{iconEl}
{node.data.name}
</span>
);
}
const relativePath =
node.data.path.startsWith(root) && Paths.isAbsolute(node.data.path)
? Paths.rest(node.data.path, root)
: node.data.path;
const isMarkdown =
relativePath.endsWith(".md") || relativePath.endsWith(".qmd");
const isRunning = runningNotebooks.has(relativePath);
return (
<a
className={itemClassName}
href={asURL(`?file=${encodeURIComponent(relativePath)}`).toString()}
target={tabTarget(relativePath)}
>
{iconEl}
<span className="flex-1 overflow-hidden text-ellipsis">
{node.data.name}
{isMarkdown && <MarkdownIcon className="ml-2 inline opacity-80" />}
</span>
<FileActions node={node} isRunning={isRunning} />
{/*
Trailing action slots. Using a fixed-width row here (rather than
conditionally rendered inline elements) keeps every row's right
edge aligned even though any individual slot may be empty.
*/}
<div className="w-8 h-8 flex items-center justify-center shrink-0">
<SessionShutdownButton filePath={relativePath} />
</div>
<ExternalLinkIcon
size={20}
className="group-hover:opacity-100 opacity-0 text-primary shrink-0"
/>
</a>
);
};
return (
<div
style={style}
className={cn(
"flex items-center cursor-pointer ml-1 text-muted-foreground whitespace-nowrap group h-full",
)}
onClick={(evt) => {
evt.stopPropagation();
if (node.data.isDirectory) {
node.toggle();
}
}}
>
<FolderArrow node={node} />
{renderItem()}
</div>
);
};
const FileActions = ({
node,
isRunning,
}: {
node: NodeApi<FileInfo>;
isRunning: boolean;
}) => {
const { root, refreshWorkspace } = use(WorkspaceContext);
const { handleRename, handleDuplicate, handleDelete } =
useNotebookFileActions({ node, root, onAfterChange: refreshWorkspace });
const lockedReason = isRunning
? "Stop the notebook's kernel before renaming or deleting."
: undefined;
return (
<FileActionsDropdown
testId="workspace-more-button"
buttonClassName="w-8 h-8 p-0 shrink-0"
contentClassName="print:hidden w-fit min-w-[140px]"
preventDefaultOnTrigger={true}
>
<RenameMenuItem
onSelect={handleRename}
disabled={isRunning}
title={lockedReason}
/>
<DuplicateMenuItem onSelect={handleDuplicate} />
<DropdownMenuSeparator />
<DeleteMenuItem
onSelect={handleDelete}
disabled={isRunning}
title={lockedReason}
/>
</FileActionsDropdown>
);
};
const FolderArrow = ({ node }: { node: NodeApi<FileInfo> }) => {
if (!node.data.isDirectory) {
return <span className="w-5 h-5 shrink-0" />;
}
return node.isOpen ? (
<ChevronDownIcon className="w-5 h-5 shrink-0" />
) : (
<ChevronRightIcon className="w-5 h-5 shrink-0" />
);
};
const NotebookList: React.FC<{
header: React.ReactNode;
files: MarimoFile[];
}> = ({ header, files }) => {
if (files.length === 0) {
return null;
}
return (
<div className="flex flex-col gap-2">
{header}
<div className="flex flex-col divide-y divide-(--slate-3) border rounded overflow-hidden max-h-192 overflow-y-auto shadow-sm bg-background">
{files.map((file) => {
return <MarimoFileComponent key={file.path} file={file} />;
})}
</div>
</div>
);
};
const MarimoFileComponent = ({ file }: { file: MarimoFile }) => {
const { locale } = useLocale();
// If path is a sessionId, then it has not been saved yet
// We want to keep the sessionId in this case
const isNewNotebook = isSessionId(file.path);
const href = isNewNotebook
? asURL(
`?file=${encodeURIComponent(file.initializationId ?? file.path)}&session_id=${file.path}`,
)
: asURL(`?file=${encodeURIComponent(file.path)}`);
const isMarkdown = file.path.endsWith(".md");
return (
<a
className="py-1.5 px-4 hover:bg-(--blue-2) hover:text-primary transition-all duration-300 cursor-pointer group relative flex gap-4 items-center"
key={file.path}
href={href.toString()}
target={tabTarget(file.initializationId || file.path)}
>
<div className="flex flex-col justify-between flex-1">
<span className="flex items-center gap-2">
{file.name}
{isMarkdown && (
<span className="opacity-80">
<MarkdownIcon />
</span>
)}
</span>
<p
title={file.path}
className="text-sm text-muted-foreground overflow-hidden whitespace-nowrap text-ellipsis"
>
{file.path}
</p>
</div>
<div className="flex flex-col gap-1 items-end">
<div className="flex gap-3 items-center">
<div>
<SessionShutdownButton filePath={file.path} />
</div>
<ExternalLinkIcon
size={20}
className="group-hover:opacity-100 opacity-0 transition-all duration-300 text-primary"
/>
</div>
{!!file.lastModified && (
<div className="text-xs text-muted-foreground opacity-80">
{timeAgo(file.lastModified * 1000, locale)}
</div>
)}
</div>
</a>
);
};
const SessionShutdownButton: React.FC<{ filePath: string }> = ({
filePath,
}) => {
const { openConfirm, closeModal } = useImperativeModal();
const { shutdownSession } = useRequestClient();
const { runningNotebooks, setRunningNotebooks } = use(
RunningNotebooksContext,
);
if (!runningNotebooks.has(filePath)) {
return null;
}
return (
<Tooltip content="Shutdown">
<Button
size={"icon"}
variant="outline"
className="opacity-80 hover:opacity-100 hover:bg-accent text-destructive border-destructive hover:border-destructive hover:text-destructive bg-background hover:bg-(--red-1)"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
openConfirm({
title: "Shutdown",
description:
"This will terminate the Python kernel. You'll lose all data that's in memory.",
variant: "destructive",
confirmAction: (
<AlertDialogDestructiveAction
onClick={() => {
const ids = runningNotebooks.get(filePath);
assertExists(ids?.sessionId);
shutdownSession({
sessionId: ids.sessionId,
}).then((response) => {
setRunningNotebooks(
Maps.keyBy(response.files, (file) => file.path),
);
});
closeModal();
toast({
description: "Notebook has been shutdown.",
});
}}
aria-label="Confirm Shutdown"
>
Shutdown
</AlertDialogDestructiveAction>
),
});
}}
>
<PowerOffIcon size={14} />
</Button>
</Tooltip>
);
};
const CreateNewNotebook: React.FC = () => {
const url = newNotebookURL();
return (
<a
className="relative rounded-lg p-6 group
text-primary hover:bg-(--blue-2) shadow-md-solid shadow-accent border bg-(--blue-1)
transition-all duration-300 cursor-pointer
"
href={url}
target="_blank"
rel="noreferrer"
>
<h2 className="text-lg font-semibold">Create a new notebook</h2>
<div className="group-hover:opacity-100 opacity-0 absolute right-5 top-0 bottom-0 rounded-lg flex items-center justify-center transition-all duration-300">
<ExternalLinkIcon size={24} />
</div>
</a>
);
};
export default HomePage;