@notis_ai/cli 0.2.25 → 0.2.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +186 -5
- package/config/notis_app_design_rules.json +36 -14
- package/config/portal-route-roots.json +1 -0
- package/dist/agent-hooks/notis-agent-hook.mjs +2784 -541
- package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
- package/dist/base-skills/notis-cli/references/intelligence.md +1 -1
- package/dist/base-skills/notis-query/.notis-base-skill.json +1 -1
- package/dist/base-skills/notis-query/SKILL.md +0 -1
- package/dist/base-skills/notis-query/references/documents.md +7 -0
- package/dist/base-skills/notis-query/references/query.md +1 -0
- package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
- package/dist/base-skills/notis-spaces/SKILL.md +96 -24
- package/dist/base-skills/notis-spaces/references/architecture.md +4 -3
- package/dist/base-skills/notis-spaces/references/design.md +37 -18
- package/dist/base-skills/notis-spaces/references/reading.md +8 -1
- package/dist/base-skills/notis-spaces/references/reports.md +6 -6
- package/dist/base-skills/notis-spaces/references/sdk.md +71 -7
- package/dist/base-skills/notis-spaces/references/store.md +22 -13
- package/dist/base-skills/notis-spaces/references/views.md +99 -6
- package/dist/sdk/package.json +3 -0
- package/dist/sdk/src/cloudComputerWords.ts +53 -0
- package/dist/sdk/src/components/Audience.tsx +76 -0
- package/dist/sdk/src/components/DocumentPage.tsx +15 -4
- package/dist/sdk/src/components/MarkdownEditor.tsx +44 -14
- package/dist/sdk/src/components/MultiSelectActionBar.tsx +16 -5
- package/dist/sdk/src/components/Skeleton.tsx +162 -6
- package/dist/sdk/src/hooks/useAction.ts +12 -2
- package/dist/sdk/src/hooks/useAgentQueue.ts +125 -0
- package/dist/sdk/src/hooks/useCloudComputerJob.ts +142 -0
- package/dist/sdk/src/hooks/useCloudComputerService.ts +388 -0
- package/dist/sdk/src/hooks/useCloudComputerShell.ts +95 -7
- package/dist/sdk/src/hooks/useCollectionInteractions.ts +40 -2
- package/dist/sdk/src/hooks/useItemThread.ts +58 -0
- package/dist/sdk/src/hooks/useMarqueeSelection.ts +6 -1
- package/dist/sdk/src/hooks/useNativeDocuments.ts +61 -8
- package/dist/sdk/src/hooks/useNotisNavigation.ts +31 -8
- package/dist/sdk/src/hooks/useQuery.ts +67 -10
- package/dist/sdk/src/hooks/useViewParams.ts +47 -11
- package/dist/sdk/src/index.ts +31 -4
- package/dist/sdk/src/interactions.ts +2 -0
- package/dist/sdk/src/nativeData.ts +2 -0
- package/dist/sdk/src/optimisticRows.ts +329 -0
- package/dist/sdk/src/perf.ts +188 -0
- package/dist/sdk/src/provider.tsx +2 -1
- package/dist/sdk/src/queryCache.ts +366 -17
- package/dist/sdk/src/runtime.ts +55 -4
- package/dist/sdk/src/skeleton.ts +103 -0
- package/dist/sdk/src/space.ts +662 -28
- package/dist/sdk/src/spacePublicUI.ts +36 -0
- package/dist/sdk/src/ui/engine/step.ts +54 -0
- package/dist/sdk/src/ui/icons.tsx +3 -1
- package/dist/sdk/src/words/shell.ts +1 -0
- package/dist/skill-sync/index.js +7 -2
- package/dist/skill-sync-worker.mjs +40 -26
- package/dist/space-harness/host.js +272 -105
- package/dist/space-sdk/dist/chunk-BWHAORT4.js +5 -0
- package/dist/space-sdk/dist/index.js +9 -4
- package/dist/space-sdk/dist/ui.js +12 -12
- package/dist/space-sdk/package.json +3 -0
- package/dist/space-sdk/src/cloudComputerWords.d.ts +34 -0
- package/dist/space-sdk/src/components/Audience.d.ts +46 -0
- package/dist/space-sdk/src/components/DocumentPage.d.ts +3 -1
- package/dist/space-sdk/src/components/MarkdownEditor.d.ts +21 -0
- package/dist/space-sdk/src/components/MultiSelectActionBar.d.ts +5 -1
- package/dist/space-sdk/src/components/Skeleton.d.ts +7 -2
- package/dist/space-sdk/src/hooks/useAction.d.ts +8 -1
- package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +61 -0
- package/dist/space-sdk/src/hooks/useCloudComputerJob.d.ts +35 -0
- package/dist/space-sdk/src/hooks/useCloudComputerService.d.ts +75 -0
- package/dist/space-sdk/src/hooks/useCloudComputerShell.d.ts +36 -3
- package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +6 -0
- package/dist/space-sdk/src/hooks/useItemThread.d.ts +32 -0
- package/dist/space-sdk/src/hooks/useMarqueeSelection.d.ts +2 -1
- package/dist/space-sdk/src/hooks/useNativeDocumentBody.d.ts +1 -0
- package/dist/space-sdk/src/hooks/useNativeDocuments.d.ts +20 -5
- package/dist/space-sdk/src/hooks/useNotisNavigation.d.ts +11 -2
- package/dist/space-sdk/src/hooks/useQuery.d.ts +24 -2
- package/dist/space-sdk/src/hooks/useViewParams.d.ts +2 -0
- package/dist/space-sdk/src/index.d.ts +24 -4
- package/dist/space-sdk/src/nativeData.d.ts +6 -0
- package/dist/space-sdk/src/queryCache.d.ts +97 -2
- package/dist/space-sdk/src/runtime.d.ts +53 -4
- package/dist/space-sdk/src/skeleton.d.ts +42 -0
- package/dist/space-sdk/src/space.ts +662 -28
- package/dist/space-sdk/src/tailwind-candidates.d.ts +754 -5
- package/dist/space-sdk/src/ui/cloud/CloudComputerFrame.d.ts +29 -0
- package/dist/space-sdk/src/ui/cloud/CloudComputerWaking.d.ts +20 -0
- package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +15 -2
- package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +50 -0
- package/dist/space-sdk/src/ui/comments/commentFiles.d.ts +64 -0
- package/dist/space-sdk/src/ui/comments/commentModel.d.ts +49 -1
- package/dist/space-sdk/src/ui/comments/commentWords.d.ts +26 -0
- package/dist/space-sdk/src/ui/comments/index.d.ts +4 -0
- package/dist/space-sdk/src/ui/comments/passageModel.d.ts +82 -0
- package/dist/space-sdk/src/ui/comments/useComments.d.ts +34 -4
- package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +67 -0
- package/dist/space-sdk/src/ui/engine/index.d.ts +2 -2
- package/dist/space-sdk/src/ui/engine/step.d.ts +9 -0
- package/dist/space-sdk/src/ui/fields/fields.d.ts +2 -1
- package/dist/space-sdk/src/ui/index.d.ts +4 -0
- package/dist/space-sdk/src/ui/layout/Panels.d.ts +9 -2
- package/dist/space-sdk/src/ui/layout/SidePane.d.ts +42 -0
- package/dist/space-sdk/src/ui/layout/index.d.ts +2 -1
- package/dist/space-sdk/src/ui/layout/panelMath.d.ts +11 -2
- package/dist/space-sdk/src/ui/list/ListReader.d.ts +38 -7
- package/dist/space-sdk/src/ui/list/Row.d.ts +4 -0
- package/dist/space-sdk/src/ui/list/SelectionBar.d.ts +9 -4
- package/dist/space-sdk/src/ui/list/useListKeys.d.ts +4 -0
- package/dist/space-sdk/src/words/shell.ts +1 -0
- package/dist/view-renderer/dist/host.js +355 -188
- package/dist/view-renderer/dist/theme.css +1 -1
- package/dist/view-renderer/src/host.tsx +4 -1
- package/dist/view-renderer/src/index.js +3 -0
- package/dist/view-renderer/src/pool.js +8 -4
- package/dist/view-renderer/src/renderer.js +92 -23
- package/dist/view-renderer/src/skeleton.js +450 -0
- package/package.json +4 -4
- package/skills/notis-cli/AGENT_INSTRUCTIONS.md +8 -4
- package/skills/notis-onboarding/BRIEF.md +15 -9
- package/skills/notis-spaces/cli.md +43 -4
- package/src/command-specs/auth.js +5 -3
- package/src/command-specs/cc.js +410 -0
- package/src/command-specs/computer.js +320 -0
- package/src/command-specs/diagnostics.js +2 -13
- package/src/command-specs/documents.js +22 -4
- package/src/command-specs/index.js +7 -0
- package/src/command-specs/onboarding.js +127 -7
- package/src/command-specs/skills.js +2 -2
- package/src/command-specs/spaces.js +162 -30
- package/src/command-specs/tools.js +26 -8
- package/src/command-specs/views.js +4 -1
- package/src/runtime/agent-setup.js +20 -2
- package/src/runtime/app-boundary-validator.js +2 -1
- package/src/runtime/app-platform.js +13 -0
- package/src/runtime/auth-recovery.js +5 -0
- package/src/runtime/channel.js +16 -2
- package/src/runtime/cloud-transfer.js +587 -0
- package/src/runtime/computer-ssh.js +127 -0
- package/src/runtime/oauth.js +50 -4
- package/src/runtime/skill-sync/index.ts +20 -1
- package/src/runtime/skill-sync/local-scanner.ts +1 -0
- package/src/runtime/skill-sync/types.ts +2 -0
- package/src/runtime/space-audience.js +94 -0
- package/src/runtime/space-collection-scaffold.js +2 -1
- package/src/runtime/space-fixture-broker.js +2 -1
- package/src/runtime/space-lock.js +1 -4
- package/src/runtime/space-platform.js +18 -2
- package/src/runtime/space-source.js +105 -7
- package/src/runtime/space-test-server.js +13 -2
- package/src/runtime/space-verification.js +99 -6
- package/src/runtime/space-view-manifest.js +22 -4
- package/src/runtime/sync-skills.js +24 -20
- package/src/runtime/transport.js +19 -0
- package/src/runtime/view-render.js +2 -2
- package/template/.harness/index.html.tmpl +1 -1
- package/dist/skill-sync/index.js.map +0 -7
- package/dist/space-sdk/dist/chunk-SVZATGZB.js +0 -5
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
4
|
+
import { useNotisRuntime } from '../provider';
|
|
5
|
+
import { CLOUD_COMPUTER_WORDS } from '../cloudComputerWords';
|
|
6
|
+
import { fillWords, pick, type Locale } from '../words';
|
|
7
|
+
import type { SpaceCloudComputerFrameCode, SpaceCloudComputerLeaseResult, SpaceCloudComputerMediaLink } from '../space';
|
|
8
|
+
|
|
9
|
+
export type CloudComputerServiceStatus = 'unavailable' | 'idle' | 'starting' | 'ready' | 'failed';
|
|
10
|
+
|
|
11
|
+
export interface UseCloudComputerServiceOptions {
|
|
12
|
+
/**
|
|
13
|
+
* How long a start may take before the hook says it failed, in seconds (default 90). While the machine says the
|
|
14
|
+
* service process runs and is getting ready (`launching`), the wait starts over on each answer.
|
|
15
|
+
*/
|
|
16
|
+
waitSeconds?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface UseCloudComputerServiceResult {
|
|
20
|
+
/** The declared service id, or null. */
|
|
21
|
+
id: string | null;
|
|
22
|
+
/**
|
|
23
|
+
* `unavailable`: this host offers no services (Sites, links, verification harnesses, older hosts) or the Space does
|
|
24
|
+
* not declare this one. `idle`: not asked yet. `starting`, `ready`, or `failed` (see `error`).
|
|
25
|
+
*/
|
|
26
|
+
status: CloudComputerServiceStatus;
|
|
27
|
+
/** The last lease answer. */
|
|
28
|
+
lease: SpaceCloudComputerLeaseResult | null;
|
|
29
|
+
/**
|
|
30
|
+
* True while `starting` because the machine runs but is still restoring its files after a pause (it can take
|
|
31
|
+
* minutes); `CloudComputerWaking` says so instead of the usual start words.
|
|
32
|
+
*/
|
|
33
|
+
restoring: boolean;
|
|
34
|
+
/** What went wrong while `failed`: the server's message when it gave one. */
|
|
35
|
+
error: Error | null;
|
|
36
|
+
/** The service address for `path` (`/` by default), or null until the gate serves it. */
|
|
37
|
+
url(path?: string): string | null;
|
|
38
|
+
/** `fetch` on the service with its pass. Throws while there is no gate yet. */
|
|
39
|
+
fetch(path: string, init?: RequestInit): Promise<Response>;
|
|
40
|
+
/**
|
|
41
|
+
* A link a media element (video, audio, img) can open without a header, seeking included: one file for ten minutes.
|
|
42
|
+
* Null until the service is ready and the link is issued; the hook asks for it on first use, re-renders when it
|
|
43
|
+
* arrives and swaps in a fresh link two minutes before the old one ends (keep the play position when `src` changes).
|
|
44
|
+
*/
|
|
45
|
+
mediaUrl(path: string): string | null;
|
|
46
|
+
/** The same links on demand, up to 50 paths at once. Throws while the service is not ready or the host predates them. */
|
|
47
|
+
media(paths: string[]): Promise<SpaceCloudComputerMediaLink[]>;
|
|
48
|
+
/**
|
|
49
|
+
* A one-time code for a frame of the service (see `CloudComputerFrame`), landing on `path`. A root path (`/`) serves
|
|
50
|
+
* the service from the gate root, so an app built for its own origin runs unchanged.
|
|
51
|
+
*/
|
|
52
|
+
frameCode(path?: string): Promise<SpaceCloudComputerFrameCode>;
|
|
53
|
+
/** Ask again at once and restart the bounded wait. */
|
|
54
|
+
retry(): void;
|
|
55
|
+
/**
|
|
56
|
+
* True while `failed` because the viewer has not allowed this Space's current code on their Cloud Computer yet:
|
|
57
|
+
* offer `allow()` instead of Try again (`CloudComputerWaking` does).
|
|
58
|
+
*/
|
|
59
|
+
approvalRequired: boolean;
|
|
60
|
+
/** Open the host's approval prompt; once the viewer allows it, the service starts at once. */
|
|
61
|
+
allow(): Promise<void>;
|
|
62
|
+
/** The cloud computer's price while it runs, when known. */
|
|
63
|
+
price: SpaceCloudComputerLeaseResult['price'] | null;
|
|
64
|
+
/** The bounded wait in seconds. */
|
|
65
|
+
waitSeconds: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A media link is renewed this long before it ends. */
|
|
69
|
+
const MEDIA_RENEW_MS = 120_000;
|
|
70
|
+
|
|
71
|
+
/** A visible view renews its lease this often; the server holds a lease for 120 s. */
|
|
72
|
+
export const SERVICE_PULSE_MS = 30_000;
|
|
73
|
+
const DEFAULT_WAIT_SECONDS = 90;
|
|
74
|
+
/** While pulsing a ready service, this many failed pulses in a row turn it failed (one lost pulse is not an outage). */
|
|
75
|
+
const READY_PULSE_FAILURES = 3;
|
|
76
|
+
|
|
77
|
+
function documentVisible(): boolean {
|
|
78
|
+
return typeof document === 'undefined' || document.visibilityState !== 'hidden';
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function newHolder(): string {
|
|
82
|
+
const random = globalThis.crypto?.randomUUID?.();
|
|
83
|
+
if (random) return random;
|
|
84
|
+
return `holder-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function clampRetrySeconds(value: number | null | undefined): number {
|
|
88
|
+
const seconds = typeof value === 'number' && Number.isFinite(value) ? value : 2;
|
|
89
|
+
return Math.min(10, Math.max(1, seconds));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A service the Space declares in `cloudComputer.services`, kept running on the signed-in viewer's own cloud computer
|
|
94
|
+
* while this page is on screen.
|
|
95
|
+
*
|
|
96
|
+
* ```tsx
|
|
97
|
+
* const preview = useCloudComputerService('preview');
|
|
98
|
+
* if (preview.status !== 'ready') return <CloudComputerWaking service={preview}>{null}</CloudComputerWaking>;
|
|
99
|
+
* const answer = await preview.fetch('/api/items');
|
|
100
|
+
* ```
|
|
101
|
+
*
|
|
102
|
+
* While the page is visible it renews the service's lease at once and every 30 s, which starts the service when needed;
|
|
103
|
+
* hidden or unmounted, it stops and tells the host once, so the cloud computer stops about two minutes later. A start
|
|
104
|
+
* that takes longer than `waitSeconds` without the machine saying the service is launching turns `failed`; `retry()` asks again. Hosts without services answer
|
|
105
|
+
* `unavailable` and never ask anything.
|
|
106
|
+
*/
|
|
107
|
+
export function useCloudComputerService(id: string | null | undefined, options: UseCloudComputerServiceOptions = {}): UseCloudComputerServiceResult {
|
|
108
|
+
const runtime = useNotisRuntime();
|
|
109
|
+
const transport = runtime?.spaceCloudComputer;
|
|
110
|
+
const space = runtime?.space;
|
|
111
|
+
const locale: Locale = runtime?.context?.locale === 'fr' ? 'fr' : 'en';
|
|
112
|
+
const waitSeconds = Math.max(1, options.waitSeconds ?? DEFAULT_WAIT_SECONDS);
|
|
113
|
+
const serviceId = id || null;
|
|
114
|
+
const declared = Boolean(serviceId && space?.cloudComputer === 'shell' && Array.isArray(space.cloudComputerServices)
|
|
115
|
+
&& space.cloudComputerServices.includes(serviceId));
|
|
116
|
+
const lease = transport?.lease;
|
|
117
|
+
const offered = Boolean(declared && lease && transport);
|
|
118
|
+
|
|
119
|
+
const [holder] = useState(newHolder);
|
|
120
|
+
const [state, setState] = useState<{ status: CloudComputerServiceStatus; lease: SpaceCloudComputerLeaseResult | null; error: Error | null }>(
|
|
121
|
+
{ status: 'idle', lease: null, error: null });
|
|
122
|
+
const [attempt, setAttempt] = useState(0);
|
|
123
|
+
const latest = useRef({ locale, waitSeconds });
|
|
124
|
+
latest.current = { locale, waitSeconds };
|
|
125
|
+
|
|
126
|
+
useEffect(() => {
|
|
127
|
+
if (!offered || !serviceId || !transport?.lease) return undefined;
|
|
128
|
+
const call = (visible: boolean) => transport.lease!({ service: serviceId, visible, holder });
|
|
129
|
+
let alive = true;
|
|
130
|
+
let epoch = 0;
|
|
131
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
132
|
+
let deadline: ReturnType<typeof setTimeout> | null = null;
|
|
133
|
+
let inFlight = false;
|
|
134
|
+
let holding = false;
|
|
135
|
+
let failures = 0;
|
|
136
|
+
let status: CloudComputerServiceStatus = 'idle';
|
|
137
|
+
let waitStarted: number | null = null;
|
|
138
|
+
let restoring = false;
|
|
139
|
+
|
|
140
|
+
const set = (next: { status: CloudComputerServiceStatus; lease?: SpaceCloudComputerLeaseResult | null; error?: Error | null }) => {
|
|
141
|
+
status = next.status;
|
|
142
|
+
if (!alive) return;
|
|
143
|
+
setState((current) => ({ status: next.status, lease: next.lease === undefined ? current.lease : next.lease,
|
|
144
|
+
error: next.error === undefined ? (next.status === 'failed' ? current.error : null) : next.error }));
|
|
145
|
+
};
|
|
146
|
+
const clearTimers = () => {
|
|
147
|
+
if (timer) clearTimeout(timer);
|
|
148
|
+
if (deadline) clearTimeout(deadline);
|
|
149
|
+
timer = null; deadline = null;
|
|
150
|
+
};
|
|
151
|
+
const release = () => {
|
|
152
|
+
if (!holding) return;
|
|
153
|
+
holding = false;
|
|
154
|
+
// Best effort: the lease ends at its own expiry anyway.
|
|
155
|
+
void call(false).catch(() => undefined);
|
|
156
|
+
};
|
|
157
|
+
const fail = (error: Error, answer?: SpaceCloudComputerLeaseResult | null) => {
|
|
158
|
+
epoch += 1;
|
|
159
|
+
inFlight = false;
|
|
160
|
+
clearTimers();
|
|
161
|
+
waitStarted = null;
|
|
162
|
+
set({ status: 'failed', error, ...(answer !== undefined ? { lease: answer } : {}) });
|
|
163
|
+
release();
|
|
164
|
+
};
|
|
165
|
+
const armDeadline = () => {
|
|
166
|
+
if (deadline || waitStarted === null) return;
|
|
167
|
+
const left = waitStarted + latest.current.waitSeconds * 1000 - Date.now();
|
|
168
|
+
const timeOut = () => {
|
|
169
|
+
deadline = null;
|
|
170
|
+
// A pulse still in flight is the server waking the machine (it can take over a minute): its answer decides,
|
|
171
|
+
// and the wait runs out then unless the service is launching.
|
|
172
|
+
if (inFlight) return;
|
|
173
|
+
fail(new Error(pick(restoring ? CLOUD_COMPUTER_WORDS.restoringTimedOut
|
|
174
|
+
: fillWords(CLOUD_COMPUTER_WORDS.timedOut, { seconds: latest.current.waitSeconds }), latest.current.locale)));
|
|
175
|
+
};
|
|
176
|
+
if (left <= 0) { timeOut(); return; }
|
|
177
|
+
deadline = setTimeout(timeOut, left);
|
|
178
|
+
};
|
|
179
|
+
const schedule = (ms: number) => {
|
|
180
|
+
if (timer) clearTimeout(timer);
|
|
181
|
+
timer = setTimeout(() => { timer = null; void pulse(); }, ms);
|
|
182
|
+
};
|
|
183
|
+
const pulse = async () => {
|
|
184
|
+
if (!alive || inFlight || status === 'failed' || !documentVisible()) return;
|
|
185
|
+
const mine = epoch;
|
|
186
|
+
inFlight = true;
|
|
187
|
+
holding = true;
|
|
188
|
+
if (status === 'idle') {
|
|
189
|
+
waitStarted ??= Date.now();
|
|
190
|
+
set({ status: 'starting' });
|
|
191
|
+
armDeadline();
|
|
192
|
+
}
|
|
193
|
+
let answer: SpaceCloudComputerLeaseResult;
|
|
194
|
+
try {
|
|
195
|
+
answer = await call(true);
|
|
196
|
+
} catch (reason) {
|
|
197
|
+
if (mine === epoch) inFlight = false;
|
|
198
|
+
if (!alive || mine !== epoch) return;
|
|
199
|
+
failures += 1;
|
|
200
|
+
// A ready service survives a lost pulse or two: its lease outlives them.
|
|
201
|
+
if (status === 'ready' && failures < READY_PULSE_FAILURES) { schedule(SERVICE_PULSE_MS); return; }
|
|
202
|
+
fail(reason instanceof Error ? reason : new Error(pick(CLOUD_COMPUTER_WORDS.noAnswer, latest.current.locale)));
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (mine === epoch) inFlight = false;
|
|
206
|
+
if (!alive || mine !== epoch) return;
|
|
207
|
+
failures = 0;
|
|
208
|
+
if (answer?.status === 'ready') {
|
|
209
|
+
waitStarted = null;
|
|
210
|
+
if (deadline) { clearTimeout(deadline); deadline = null; }
|
|
211
|
+
set({ status: 'ready', lease: answer, error: null });
|
|
212
|
+
schedule(SERVICE_PULSE_MS);
|
|
213
|
+
} else if (answer?.status === 'failed') {
|
|
214
|
+
fail(new Error(answer.message || pick(CLOUD_COMPUTER_WORDS.failedGeneric, latest.current.locale)), answer);
|
|
215
|
+
} else if (answer?.status === 'starting') {
|
|
216
|
+
restoring = answer.reason === 'restoring';
|
|
217
|
+
if (answer.reason === 'launching') {
|
|
218
|
+
// The service runs on the machine and is getting ready: each such answer starts the wait over, so only a
|
|
219
|
+
// machine that stops answering (or the machine's own bound) ends it.
|
|
220
|
+
waitStarted = Date.now();
|
|
221
|
+
if (deadline) { clearTimeout(deadline); deadline = null; }
|
|
222
|
+
}
|
|
223
|
+
waitStarted ??= Date.now();
|
|
224
|
+
set({ status: 'starting', lease: answer });
|
|
225
|
+
armDeadline();
|
|
226
|
+
if (status === 'starting') schedule(clampRetrySeconds(answer.retry_after_seconds) * 1000);
|
|
227
|
+
} else {
|
|
228
|
+
// `released` (another tab let it go): ask again on the next pulse.
|
|
229
|
+
set({ status: 'idle', lease: answer ?? null });
|
|
230
|
+
schedule(SERVICE_PULSE_MS);
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
const onVisibility = () => {
|
|
234
|
+
if (!alive) return;
|
|
235
|
+
if (documentVisible()) {
|
|
236
|
+
if (status === 'failed') return;
|
|
237
|
+
// A start resumes with a fresh wait: the time hidden does not count.
|
|
238
|
+
if (status === 'starting') waitStarted = Date.now();
|
|
239
|
+
armDeadline();
|
|
240
|
+
void pulse();
|
|
241
|
+
} else {
|
|
242
|
+
epoch += 1;
|
|
243
|
+
inFlight = false;
|
|
244
|
+
clearTimers();
|
|
245
|
+
release();
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
set({ status: 'idle', error: null });
|
|
250
|
+
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisibility);
|
|
251
|
+
if (documentVisible()) void pulse();
|
|
252
|
+
return () => {
|
|
253
|
+
alive = false;
|
|
254
|
+
epoch += 1;
|
|
255
|
+
clearTimers();
|
|
256
|
+
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisibility);
|
|
257
|
+
release();
|
|
258
|
+
};
|
|
259
|
+
}, [offered, serviceId, transport, holder, attempt]);
|
|
260
|
+
|
|
261
|
+
const retry = useCallback(() => {
|
|
262
|
+
setState({ status: 'idle', lease: null, error: null });
|
|
263
|
+
setAttempt((value) => value + 1);
|
|
264
|
+
}, []);
|
|
265
|
+
|
|
266
|
+
// A refused start may only need the viewer's approval: read it once per failure, never before a start.
|
|
267
|
+
const [approvalRequired, setApprovalRequired] = useState(false);
|
|
268
|
+
useEffect(() => {
|
|
269
|
+
if (!offered || state.status !== 'failed' || !transport) { setApprovalRequired(false); return undefined; }
|
|
270
|
+
let live = true;
|
|
271
|
+
transport.status().then((status) => { if (live) setApprovalRequired(status?.approved === false); },
|
|
272
|
+
() => { if (live) setApprovalRequired(false); });
|
|
273
|
+
return () => { live = false; };
|
|
274
|
+
}, [offered, state.status, state.error, transport]);
|
|
275
|
+
const allow = useCallback(async () => {
|
|
276
|
+
if (!transport) return;
|
|
277
|
+
const next = await transport.requestApproval();
|
|
278
|
+
if (next?.approved !== true) return;
|
|
279
|
+
setApprovalRequired(false);
|
|
280
|
+
retry();
|
|
281
|
+
}, [transport, retry]);
|
|
282
|
+
|
|
283
|
+
const currentLease = offered ? state.lease : null;
|
|
284
|
+
const gate = currentLease?.gate_url ? currentLease.gate_url.replace(/\/+$/, '') : null;
|
|
285
|
+
const pass = currentLease?.pass ?? null;
|
|
286
|
+
const spaceId = space?.id ?? '';
|
|
287
|
+
const url = useCallback((path = '/') => {
|
|
288
|
+
if (!gate || !serviceId) return null;
|
|
289
|
+
const rest = path.startsWith('/') ? path : `/${path}`;
|
|
290
|
+
return `${gate}/s/${encodeURIComponent(spaceId)}/${encodeURIComponent(serviceId)}${rest}`;
|
|
291
|
+
}, [gate, serviceId, spaceId]);
|
|
292
|
+
const serviceFetch = useCallback(async (path: string, init: RequestInit = {}) => {
|
|
293
|
+
const address = url(path);
|
|
294
|
+
if (!address || !pass) throw new Error(pick(CLOUD_COMPUTER_WORDS.noGate, latest.current.locale));
|
|
295
|
+
const headers = new Headers(init.headers);
|
|
296
|
+
headers.set('Authorization', `Bearer ${pass}`);
|
|
297
|
+
return globalThis.fetch(address, { ...init, headers });
|
|
298
|
+
}, [url, pass]);
|
|
299
|
+
const access = transport?.access;
|
|
300
|
+
const ready = offered && state.status === 'ready' && Boolean(gate);
|
|
301
|
+
const accessible = ready && Boolean(access) && Boolean(serviceId);
|
|
302
|
+
const media = useCallback(async (paths: string[]): Promise<SpaceCloudComputerMediaLink[]> => {
|
|
303
|
+
if (!accessible || !access || !serviceId) throw new Error(pick(CLOUD_COMPUTER_WORDS.noGate, latest.current.locale));
|
|
304
|
+
if (!paths.length) return [];
|
|
305
|
+
const answer = await access({ service: serviceId, media: paths });
|
|
306
|
+
return answer.media ?? [];
|
|
307
|
+
}, [accessible, access, serviceId]);
|
|
308
|
+
const frameCode = useCallback(async (path?: string): Promise<SpaceCloudComputerFrameCode> => {
|
|
309
|
+
if (!accessible || !access || !serviceId) throw new Error(pick(CLOUD_COMPUTER_WORDS.noGate, latest.current.locale));
|
|
310
|
+
const answer = await access({ service: serviceId, frame: true, ...(path ? { path } : {}) });
|
|
311
|
+
if (!answer.frame) throw new Error(pick(CLOUD_COMPUTER_WORDS.noGate, latest.current.locale));
|
|
312
|
+
return answer.frame;
|
|
313
|
+
}, [accessible, access, serviceId]);
|
|
314
|
+
|
|
315
|
+
// Media links: issued per file on first use, batched, renewed before they end. A new gate starts a new cache.
|
|
316
|
+
const [links, setLinks] = useState<{ gate: string | null; byPath: Record<string, SpaceCloudComputerMediaLink> }>(
|
|
317
|
+
{ gate: null, byPath: {} });
|
|
318
|
+
const wanted = useRef<{ gate: string | null; paths: Set<string>; inFlight: Set<string>; failedAt: Map<string, number> }>(
|
|
319
|
+
{ gate: null, paths: new Set(), inFlight: new Set(), failedAt: new Map() });
|
|
320
|
+
if (wanted.current.gate !== gate) wanted.current = { gate, paths: new Set(), inFlight: new Set(), failedAt: new Map() };
|
|
321
|
+
const mediaRef = useRef(media);
|
|
322
|
+
mediaRef.current = media;
|
|
323
|
+
const flushScheduled = useRef(false);
|
|
324
|
+
const flushMedia = useCallback(() => {
|
|
325
|
+
if (flushScheduled.current) return;
|
|
326
|
+
flushScheduled.current = true;
|
|
327
|
+
void Promise.resolve().then(async () => {
|
|
328
|
+
flushScheduled.current = false;
|
|
329
|
+
const batch = wanted.current;
|
|
330
|
+
const paths = [...batch.paths].filter((path) => !batch.inFlight.has(path)).slice(0, 50);
|
|
331
|
+
if (!paths.length) return;
|
|
332
|
+
for (const path of paths) { batch.paths.delete(path); batch.inFlight.add(path); }
|
|
333
|
+
try {
|
|
334
|
+
const issued = await mediaRef.current(paths);
|
|
335
|
+
if (wanted.current !== batch) return;
|
|
336
|
+
setLinks((current) => {
|
|
337
|
+
const byPath = current.gate === batch.gate ? { ...current.byPath } : {};
|
|
338
|
+
for (const link of issued) byPath[link.path] = link;
|
|
339
|
+
return { gate: batch.gate, byPath };
|
|
340
|
+
});
|
|
341
|
+
} catch {
|
|
342
|
+
// Asked again on a later render, not in a loop.
|
|
343
|
+
for (const path of paths) batch.failedAt.set(path, Date.now());
|
|
344
|
+
} finally {
|
|
345
|
+
for (const path of paths) batch.inFlight.delete(path);
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
}, []);
|
|
349
|
+
const known = links.gate === gate ? links.byPath : {};
|
|
350
|
+
const mediaUrl = useCallback((path: string): string | null => {
|
|
351
|
+
if (!accessible || typeof path !== 'string' || !path.startsWith('/')) return null;
|
|
352
|
+
const link = known[path];
|
|
353
|
+
const ends = link ? Date.parse(link.expires_at) : 0;
|
|
354
|
+
const now = Date.now();
|
|
355
|
+
const batch = wanted.current;
|
|
356
|
+
const failed = batch.failedAt.get(path);
|
|
357
|
+
const renew = !link || !Number.isFinite(ends) || ends - now <= MEDIA_RENEW_MS;
|
|
358
|
+
if (renew && !batch.inFlight.has(path) && !(failed && now - failed < 5_000)) {
|
|
359
|
+
batch.paths.add(path);
|
|
360
|
+
flushMedia();
|
|
361
|
+
}
|
|
362
|
+
return link && ends > now ? link.url : null;
|
|
363
|
+
}, [accessible, known, flushMedia]);
|
|
364
|
+
// Re-render shortly before a link ends, so the view asks for its renewal while it still plays.
|
|
365
|
+
const nextRenewal = useMemo(() => {
|
|
366
|
+
const ends = Object.values(known).map((link) => Date.parse(link.expires_at)).filter(Number.isFinite);
|
|
367
|
+
return ends.length ? Math.min(...ends) - MEDIA_RENEW_MS : null;
|
|
368
|
+
}, [known]);
|
|
369
|
+
const [, setRenewTick] = useState(0);
|
|
370
|
+
useEffect(() => {
|
|
371
|
+
if (nextRenewal === null) return undefined;
|
|
372
|
+
const timer = setTimeout(() => setRenewTick((value) => value + 1), Math.max(1_000, nextRenewal - Date.now()));
|
|
373
|
+
return () => clearTimeout(timer);
|
|
374
|
+
}, [nextRenewal]);
|
|
375
|
+
|
|
376
|
+
return useMemo(() => ({
|
|
377
|
+
id: serviceId,
|
|
378
|
+
status: offered ? state.status : 'unavailable',
|
|
379
|
+
lease: currentLease,
|
|
380
|
+
restoring: offered && state.status === 'starting' && currentLease?.status === 'starting' && currentLease.reason === 'restoring',
|
|
381
|
+
error: offered && state.status === 'failed' ? state.error : null,
|
|
382
|
+
url, fetch: serviceFetch, mediaUrl, media, frameCode, retry,
|
|
383
|
+
approvalRequired: offered && state.status === 'failed' && approvalRequired, allow,
|
|
384
|
+
price: currentLease?.price ?? null,
|
|
385
|
+
waitSeconds,
|
|
386
|
+
}), [serviceId, offered, state, currentLease, url, serviceFetch, mediaUrl, media, frameCode, retry, approvalRequired, allow,
|
|
387
|
+
waitSeconds]);
|
|
388
|
+
}
|
|
@@ -4,6 +4,13 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
|
|
4
4
|
import { useNotisRuntime } from '../provider';
|
|
5
5
|
import { invalidateCloudComputerFacts } from './useCloudComputer';
|
|
6
6
|
import type {
|
|
7
|
+
SpaceCloudComputerFileUpload,
|
|
8
|
+
SpaceCloudComputerFileUploadResult,
|
|
9
|
+
SpaceCloudComputerImportInput,
|
|
10
|
+
SpaceCloudComputerImportResult,
|
|
11
|
+
SpaceCloudComputerUploadProgress,
|
|
12
|
+
SpaceCloudComputerJobLogs,
|
|
13
|
+
SpaceCloudComputerJobStatus,
|
|
7
14
|
SpaceCloudComputerLevel,
|
|
8
15
|
SpaceCloudComputerRunResult,
|
|
9
16
|
SpaceCloudComputerStatus,
|
|
@@ -28,8 +35,25 @@ export interface UseCloudComputerShellResult {
|
|
|
28
35
|
* Pass the same `requestId` when the page retries this run itself: a run is never repeated for one key.
|
|
29
36
|
*/
|
|
30
37
|
run(command: string, options?: RunOptions): Promise<SpaceCloudComputerRunResult>;
|
|
31
|
-
/**
|
|
38
|
+
/** A background job started with `run(command, { detach: true })`: its state and exit code. */
|
|
39
|
+
jobStatus(jobId: string): Promise<SpaceCloudComputerJobStatus>;
|
|
40
|
+
/** Up to `maxBytes` (default 65536, at most 200000) of the job's output from byte `offset` (default 0). */
|
|
41
|
+
jobLogs(jobId: string, options?: { offset?: number; maxBytes?: number }): Promise<SpaceCloudComputerJobLogs>;
|
|
42
|
+
/** Stop a background job; answers its state once stopped. */
|
|
43
|
+
cancelJob(jobId: string): Promise<SpaceCloudComputerJobStatus>;
|
|
44
|
+
/**
|
|
45
|
+
* Write one file straight to the cloud computer; it never travels by URL or chat. With `{ path, content }`: text
|
|
46
|
+
* or base64, at most 1 MiB, at a machine path. With `{ file, dest: { space: 'files/clip.mp4' } }`: a `File` or
|
|
47
|
+
* `Blob` of any size into the Space folder; above 1 MiB its parts go from the browser to the machine directly,
|
|
48
|
+
* `uploadProgress` follows it, and the machine checks its sha256 before it replaces the file.
|
|
49
|
+
*/
|
|
32
50
|
upload(file: SpaceCloudComputerUploadInput): Promise<SpaceCloudComputerUploadResult>;
|
|
51
|
+
upload(file: SpaceCloudComputerFileUpload): Promise<SpaceCloudComputerFileUploadResult>;
|
|
52
|
+
/** The `{ file }` upload in progress (the latest one when several run), else null. */
|
|
53
|
+
uploadProgress: SpaceCloudComputerUploadProgress | null;
|
|
54
|
+
/** Have the cloud computer download a public URL itself into the Space folder; a rerun resumes a cut download. */
|
|
55
|
+
importUrl(url: string, dest: { space: string }, options?: { sha256?: string; overwrite?: boolean; requestId?: string }):
|
|
56
|
+
Promise<SpaceCloudComputerImportResult>;
|
|
33
57
|
/**
|
|
34
58
|
* Ask the host to show its approval prompt, for either declared level. Only the person's click in
|
|
35
59
|
* that prompt approves; once allowed, every `useCloudComputer()` reads the facts again.
|
|
@@ -38,12 +62,30 @@ export interface UseCloudComputerShellResult {
|
|
|
38
62
|
refresh(): Promise<void>;
|
|
39
63
|
}
|
|
40
64
|
|
|
41
|
-
|
|
65
|
+
/**
|
|
66
|
+
* `cwd`: a machine path, or `{ space: 'rel' }` inside the Space folder (`{ space: '' }` is its root); without it a run
|
|
67
|
+
* starts in /vercel/sandbox. `detach`: start a background job and answer at once with `job_id` (follow it with
|
|
68
|
+
* `useCloudComputerJob`); `timeoutMs` then bounds the job, up to 6 hours.
|
|
69
|
+
*/
|
|
70
|
+
type RunOptions = { cwd?: string | { space: string }; detach?: boolean; timeoutMs?: number; maxOutputLength?: number; requestId?: string };
|
|
42
71
|
|
|
43
72
|
const unavailable = async (): Promise<never> => {
|
|
44
|
-
throw new Error('The
|
|
73
|
+
throw new Error('The Cloud Computer is not available in this Space.');
|
|
45
74
|
};
|
|
46
75
|
|
|
76
|
+
const INLINE_FILE_BYTES = 1024 * 1024;
|
|
77
|
+
|
|
78
|
+
function isFileUpload(input: SpaceCloudComputerUploadInput | SpaceCloudComputerFileUpload): input is SpaceCloudComputerFileUpload {
|
|
79
|
+
return Boolean(input) && typeof input === 'object' && 'file' in input;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function base64Of(file: Blob): Promise<string> {
|
|
83
|
+
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
84
|
+
let text = '';
|
|
85
|
+
for (let at = 0; at < bytes.length; at += 0x8000) text += String.fromCharCode(...bytes.subarray(at, at + 0x8000));
|
|
86
|
+
return btoa(text);
|
|
87
|
+
}
|
|
88
|
+
|
|
47
89
|
/**
|
|
48
90
|
* The viewer's approval and, for `cloudComputer: 'shell'`, commands and file writes on the signed-in
|
|
49
91
|
* viewer's own cloud computer, from a Space page.
|
|
@@ -66,6 +108,7 @@ export function useCloudComputerShell(): UseCloudComputerShellResult {
|
|
|
66
108
|
const available = level === 'shell';
|
|
67
109
|
const [status, setStatus] = useState<SpaceCloudComputerStatus | null>(null);
|
|
68
110
|
const [loading, setLoading] = useState(Boolean(level));
|
|
111
|
+
const [uploadProgress, setUploadProgress] = useState<SpaceCloudComputerUploadProgress | null>(null);
|
|
69
112
|
const mounted = useRef(true);
|
|
70
113
|
useEffect(() => () => { mounted.current = false; }, []);
|
|
71
114
|
|
|
@@ -89,15 +132,60 @@ export function useCloudComputerShell(): UseCloudComputerShellResult {
|
|
|
89
132
|
|
|
90
133
|
const run = useCallback(async (command: string, options: RunOptions = {}) => {
|
|
91
134
|
if (!available || !transport) return unavailable();
|
|
92
|
-
return transport.run({ command, ...(options.cwd ? { cwd: options.cwd } : {}),
|
|
135
|
+
return transport.run({ command, ...(options.cwd !== undefined && options.cwd !== '' ? { cwd: options.cwd } : {}),
|
|
136
|
+
...(options.detach ? { detach: true } : {}),
|
|
93
137
|
...(options.timeoutMs ? { timeout_ms: options.timeoutMs } : {}),
|
|
94
138
|
...(options.maxOutputLength ? { max_output_length: options.maxOutputLength } : {}),
|
|
95
139
|
...(options.requestId ? { request_id: options.requestId } : {}) });
|
|
96
140
|
}, [available, transport]);
|
|
97
141
|
|
|
98
|
-
const
|
|
142
|
+
const jobStatus = useCallback(async (jobId: string) => {
|
|
143
|
+
if (!available || !transport?.job) return unavailable();
|
|
144
|
+
return transport.job('job.status', { job_id: jobId });
|
|
145
|
+
}, [available, transport]);
|
|
146
|
+
const jobLogs = useCallback(async (jobId: string, options: { offset?: number; maxBytes?: number } = {}) => {
|
|
147
|
+
if (!available || !transport?.job) return unavailable();
|
|
148
|
+
return transport.job('job.logs', { job_id: jobId, ...(options.offset ? { offset: options.offset } : {}),
|
|
149
|
+
...(options.maxBytes ? { max_bytes: options.maxBytes } : {}) });
|
|
150
|
+
}, [available, transport]);
|
|
151
|
+
const cancelJob = useCallback(async (jobId: string) => {
|
|
152
|
+
if (!available || !transport?.job) return unavailable();
|
|
153
|
+
return transport.job('job.cancel', { job_id: jobId });
|
|
154
|
+
}, [available, transport]);
|
|
155
|
+
|
|
156
|
+
const upload = useCallback(async (input: SpaceCloudComputerUploadInput | SpaceCloudComputerFileUpload) => {
|
|
99
157
|
if (!available || !transport) return unavailable();
|
|
100
|
-
return transport.upload(
|
|
158
|
+
if (!isFileUpload(input)) return transport.upload(input);
|
|
159
|
+
if (!(input.file instanceof Blob) || typeof input.dest?.space !== 'string') {
|
|
160
|
+
throw new Error("Pass { file: File | Blob, dest: { space: 'files/name' } }.");
|
|
161
|
+
}
|
|
162
|
+
const onProgress = (progress: SpaceCloudComputerUploadProgress) => {
|
|
163
|
+
if (mounted.current) setUploadProgress(progress.phase === 'done' ? null : progress);
|
|
164
|
+
input.onProgress?.(progress);
|
|
165
|
+
};
|
|
166
|
+
try {
|
|
167
|
+
if (transport.sendFile) return await transport.sendFile({ ...input, onProgress });
|
|
168
|
+
// An older host: a small file still goes inline into the Space folder.
|
|
169
|
+
if (input.file.size > INLINE_FILE_BYTES || !transport.folder) {
|
|
170
|
+
throw new Error('This host sends files of at most 1 MiB. Update Notis to send bigger ones.');
|
|
171
|
+
}
|
|
172
|
+
const folder = await transport.folder();
|
|
173
|
+
const path = `${folder.path}/${input.dest.space}`;
|
|
174
|
+
const written = await transport.upload({ path, content: await base64Of(input.file), content_encoding: 'base64' });
|
|
175
|
+
if (written.status && written.status !== 'success') throw new Error(written.message || 'The file could not be written.');
|
|
176
|
+
return { status: 'success' as const, path: written.path || path, size: written.size ?? input.file.size, sha256: '' };
|
|
177
|
+
} finally {
|
|
178
|
+
if (mounted.current) setUploadProgress(current => (current?.path === input.dest.space ? null : current));
|
|
179
|
+
}
|
|
180
|
+
}, [available, transport]) as UseCloudComputerShellResult['upload'];
|
|
181
|
+
|
|
182
|
+
const importUrl = useCallback(async (url: string, dest: { space: string },
|
|
183
|
+
options: { sha256?: string; overwrite?: boolean; requestId?: string } = {}) => {
|
|
184
|
+
if (!available || !transport?.importUrl) return unavailable();
|
|
185
|
+
const input: SpaceCloudComputerImportInput = { url, dest, ...(options.sha256 ? { sha256: options.sha256 } : {}),
|
|
186
|
+
...(options.overwrite !== undefined ? { overwrite: options.overwrite } : {}),
|
|
187
|
+
...(options.requestId ? { request_id: options.requestId } : {}) };
|
|
188
|
+
return transport.importUrl(input);
|
|
101
189
|
}, [available, transport]);
|
|
102
190
|
|
|
103
191
|
const requestApproval = useCallback(async () => {
|
|
@@ -110,5 +198,5 @@ export function useCloudComputerShell(): UseCloudComputerShellResult {
|
|
|
110
198
|
}, [level, runtime, transport]);
|
|
111
199
|
|
|
112
200
|
return { level, available, status, approved: status?.approved === true, loading: Boolean(level) && loading,
|
|
113
|
-
run, upload, requestApproval, refresh };
|
|
201
|
+
run, jobStatus, jobLogs, cancelJob, upload, uploadProgress, importUrl, requestApproval, refresh };
|
|
114
202
|
}
|
|
@@ -26,6 +26,7 @@ import {
|
|
|
26
26
|
|
|
27
27
|
import type { MultiSelectActionBarProps } from '../components/MultiSelectActionBar';
|
|
28
28
|
import { isInteractionElementVisible } from '../interactions/visibility';
|
|
29
|
+
import { travelBetween, type TravelDirection } from '../ui/engine/step';
|
|
29
30
|
import { useLongPressSelection } from './useLongPressSelection';
|
|
30
31
|
import { useMarqueeSelection, type SelectionMarqueeRect } from './useMarqueeSelection';
|
|
31
32
|
|
|
@@ -117,6 +118,11 @@ export interface CollectionInteractionController<T> {
|
|
|
117
118
|
lastClickedId: string | null;
|
|
118
119
|
dragRect: SelectionMarqueeRect | null;
|
|
119
120
|
actions: ResolvedCollectionAction[];
|
|
121
|
+
/**
|
|
122
|
+
* The way the active item last moved (J/K, the arrows, a click further up or down); 'next' until it moves. A page
|
|
123
|
+
* that removes the active item continues this way (iOS Photos), else the other way at the edge.
|
|
124
|
+
*/
|
|
125
|
+
travelDirection: () => TravelDirection;
|
|
120
126
|
getActionBarProps: () => Pick<MultiSelectActionBarProps, 'selectedCount' | 'actions' | 'collectionOwnerId' | 'isAvailable' | 'shortcutsEnabled' | 'onClearSelection'>;
|
|
121
127
|
|
|
122
128
|
isSelected: (id: string) => boolean;
|
|
@@ -237,6 +243,7 @@ export function useCollectionInteractions<T>(
|
|
|
237
243
|
const selectedIdsRef = useRef(selectedIds);
|
|
238
244
|
const activeIdRef = useRef(activeId);
|
|
239
245
|
const anchorIdRef = useRef(anchorId);
|
|
246
|
+
const travelRef = useRef<TravelDirection>('next');
|
|
240
247
|
// Keep manually selected rows outside the current keyboard range on reversal.
|
|
241
248
|
const keyboardRangeBaseRef = useRef<Set<string> | null>(null);
|
|
242
249
|
const onSelectionChangeRef = useRef(onSelectionChange);
|
|
@@ -278,6 +285,13 @@ export function useCollectionInteractions<T>(
|
|
|
278
285
|
);
|
|
279
286
|
const selectableIdsRef = useRef(selectableIds);
|
|
280
287
|
selectableIdsRef.current = selectableIds;
|
|
288
|
+
// The list as it was when it last held the active item: J/K from an item that left the list go on from its place.
|
|
289
|
+
const activePlaceRef = useRef<{ id: string; ids: string[] } | null>(null);
|
|
290
|
+
const droppedActiveIdRef = useRef<string | null>(null);
|
|
291
|
+
const lastPlace = activePlaceRef.current;
|
|
292
|
+
if (activeId && (lastPlace?.id !== activeId || lastPlace.ids !== selectableIds) && selectableIds.includes(activeId)) {
|
|
293
|
+
activePlaceRef.current = { id: activeId, ids: selectableIds };
|
|
294
|
+
}
|
|
281
295
|
|
|
282
296
|
const getItemsForIds = useCallback((ids: ReadonlySet<string>) => {
|
|
283
297
|
return itemsRef.current.filter((item) => ids.has(getIdRef.current(item)));
|
|
@@ -307,6 +321,9 @@ export function useCollectionInteractions<T>(
|
|
|
307
321
|
const setActive = useCallback((id: string | null, reason: CollectionInteractionReason = 'activate') => {
|
|
308
322
|
const next = id && selectableIdsRef.current.includes(id) ? id : null;
|
|
309
323
|
if (activeIdRef.current === next) return;
|
|
324
|
+
// A click or focus further up or down sets the way; keys set it themselves (moveActive), a wrap included.
|
|
325
|
+
const travel = reason === 'items-changed' ? null : travelBetween(selectableIdsRef.current, activeIdRef.current, next);
|
|
326
|
+
if (travel) travelRef.current = travel;
|
|
310
327
|
activeIdRef.current = next;
|
|
311
328
|
if (controlledActiveId === undefined) setUncontrolledActiveId(next);
|
|
312
329
|
onActiveIdChangeRef.current?.(next, reason);
|
|
@@ -411,7 +428,17 @@ export function useCollectionInteractions<T>(
|
|
|
411
428
|
}
|
|
412
429
|
const pruned = new Set(Array.from(selectedIdsRef.current).filter((id) => allowed.has(id)));
|
|
413
430
|
if (!setsEqual(pruned, selectedIdsRef.current)) commitSelection(pruned, 'items-changed');
|
|
414
|
-
|
|
431
|
+
const active = activeIdRef.current;
|
|
432
|
+
if (active && !allowed.has(active)) {
|
|
433
|
+
// Dropped once: a controller that keeps the item active (still open beside the list) is not told again on
|
|
434
|
+
// every list change, which would set its state on each render.
|
|
435
|
+
if (droppedActiveIdRef.current !== active) {
|
|
436
|
+
droppedActiveIdRef.current = active;
|
|
437
|
+
setActive(null, 'items-changed');
|
|
438
|
+
}
|
|
439
|
+
} else {
|
|
440
|
+
droppedActiveIdRef.current = null;
|
|
441
|
+
}
|
|
415
442
|
if (anchorIdRef.current && !allowed.has(anchorIdRef.current)) {
|
|
416
443
|
setAnchor(null, 'items-changed');
|
|
417
444
|
}
|
|
@@ -448,6 +475,7 @@ export function useCollectionInteractions<T>(
|
|
|
448
475
|
const ids = selectableIdsRef.current;
|
|
449
476
|
if (ids.length === 0) return;
|
|
450
477
|
const current = activeIdRef.current;
|
|
478
|
+
const forward = direction === 'next' || direction === 'down' || direction === 'right';
|
|
451
479
|
// Range gestures follow the displayed order, independent of asymmetric grid geometry.
|
|
452
480
|
let next = extend ? null : resolveNextIdRef.current?.({
|
|
453
481
|
direction,
|
|
@@ -455,9 +483,16 @@ export function useCollectionInteractions<T>(
|
|
|
455
483
|
items: itemsRef.current,
|
|
456
484
|
orderedIds: ids,
|
|
457
485
|
}) ?? null;
|
|
486
|
+
const place = activePlaceRef.current;
|
|
487
|
+
if (!next && current && place?.id === current && !ids.includes(current)) {
|
|
488
|
+
// The active item left the list (it is still open beside it): the nearest item still listed that way.
|
|
489
|
+
const present = new Set(ids);
|
|
490
|
+
const at = place.ids.indexOf(current);
|
|
491
|
+
const way = forward ? place.ids.slice(at + 1) : place.ids.slice(0, at).reverse();
|
|
492
|
+
next = way.find((id) => present.has(id)) ?? null;
|
|
493
|
+
}
|
|
458
494
|
if (!next) {
|
|
459
495
|
const currentIndex = current ? ids.indexOf(current) : -1;
|
|
460
|
-
const forward = direction === 'next' || direction === 'down' || direction === 'right';
|
|
461
496
|
const nextIndex = currentIndex === -1
|
|
462
497
|
? forward ? 0 : ids.length - 1
|
|
463
498
|
: Math.min(ids.length - 1, Math.max(0, currentIndex + (forward ? 1 : -1)));
|
|
@@ -478,6 +513,7 @@ export function useCollectionInteractions<T>(
|
|
|
478
513
|
setAnchor(next, 'navigate');
|
|
479
514
|
}
|
|
480
515
|
setActive(next, extend ? 'range' : 'navigate');
|
|
516
|
+
travelRef.current = forward ? 'next' : 'previous';
|
|
481
517
|
const nextId = next;
|
|
482
518
|
requestAnimationFrame(() => focusItem(nextId));
|
|
483
519
|
}, [focusItem, replaceRange, setActive, setAnchor]);
|
|
@@ -649,6 +685,7 @@ export function useCollectionInteractions<T>(
|
|
|
649
685
|
}), [enabled, onCheckboxClick]);
|
|
650
686
|
|
|
651
687
|
const getSelectedItems = useCallback(() => getItemsForIds(selectedIdsRef.current), [getItemsForIds]);
|
|
688
|
+
const travelDirection = useCallback(() => travelRef.current, []);
|
|
652
689
|
const isSelected = useCallback((id: string) => selectedIds.has(id), [selectedIds]);
|
|
653
690
|
|
|
654
691
|
const actionContext = useMemo<CollectionActionContext<T>>(() => ({
|
|
@@ -716,6 +753,7 @@ export function useCollectionInteractions<T>(
|
|
|
716
753
|
lastClickedId: anchorId,
|
|
717
754
|
dragRect,
|
|
718
755
|
actions: resolvedActions,
|
|
756
|
+
travelDirection,
|
|
719
757
|
getActionBarProps,
|
|
720
758
|
isSelected,
|
|
721
759
|
getSelectedItems,
|