@enbox/create-dapp 0.0.2 → 0.0.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enbox/create-dapp",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "Create a minimal Enbox React application",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -40,9 +40,31 @@ accepting dependency or security fixes.
40
40
 
41
41
  `src/app.json` contains the display name used in the page, browser title, and
42
42
  wallet approval screen, plus a stable app ID. Changing the display name leaves
43
- the app ID and demo data namespace intact. `src/application.ts` defines the application manifest
44
- and wallet configuration. `src/main.tsx` mounts the SDK provider; `src/App.tsx`
45
- contains the app shell without owning authentication state.
43
+ the app ID and task-board data namespace intact.
44
+
45
+ The application follows the same feature-store structure as notesd:
46
+
47
+ ```text
48
+ src/
49
+ app/
50
+ application.ts # feature registration and wallet identity
51
+ runtime.ts # one browser-lifetime application owner
52
+ App.tsx # connection shell and feature composition
53
+ features/tasks/
54
+ protocol.ts # typed encrypted records and validation
55
+ store.ts # shared resources, commands, and domain defaults
56
+ components/ # task board and its styles
57
+ shared/components/
58
+ ProfileCard.tsx
59
+ main.tsx
60
+ sw.ts
61
+ ```
62
+
63
+ `defineApplication` derives the protocol manifest from registered stores.
64
+ `getApplication()` creates one headless runtime over a native connection.
65
+ `main.tsx` waits for worker control before passing that runtime to
66
+ `EnboxProvider application={...}`. The provider initializes the borrowed runtime;
67
+ the application owns its lifetime. Development module replacement disposes it.
46
68
 
47
69
  The profile card reads published profile information through `useProfile`.
48
70
  Names, images, settlement state, and image URL lifetimes belong to the SDK.
@@ -50,27 +72,46 @@ Missing profiles and unavailable images have local display fallbacks.
50
72
  The wallet's profile label is used when a public display name is unavailable;
51
73
  the expanded details still show which name is publicly published.
52
74
 
53
- The removable demo lives entirely in `src/demo`:
75
+ The replaceable task feature lives in `src/features/tasks`:
54
76
 
55
77
  - `protocol.ts` declares encrypted `project` and `project/task` records with
56
78
  payload validators. Tasks store a title and completion state.
57
- - `use-task-board.ts` defines `useProjects`, `useTasks`, and `useTask` with
58
- `useEnboxRecords` and `useEnboxRecord`. A child selection takes its direct
59
- parent context ID; task details also select an exact record ID.
60
- - `TaskBoard.tsx` renders the board and calls typed create, patch, and delete commands.
61
- Simple event handlers use `mutate`. Forms await `mutateAsync` and check
62
- `isCurrent()` before clearing drafts or closing details. Native observation updates the displayed data.
63
- - `demo.css` styles the demo. Shared app and profile styles live in `src/style.css`.
64
-
65
- To replace the demo, register your own typed application protocol in
66
- `application.ts` in place of `TaskBoardProtocol`. Then delete `src/demo` and remove
67
- the `TaskBoard` import and component from `App.tsx`. Enbox requires at least one
68
- application protocol, so keep your replacement registered. The profile card,
69
- connection shell, and service worker remain the base for your app.
79
+ - `store.ts` declares one shared project collection and a task collection scoped
80
+ with `tasks.within(projectContextId)`. Creation and rename defaults live here.
81
+ Native resource commands share pending/error state across consumers.
82
+ - `components/TaskBoard.tsx` resolves the feature with `useFeature(TaskBoardStore)`
83
+ and reads resources or commands with `useStore`. Task details reuse loaded list
84
+ rows and acquire a bounded single-record observation for a selection outside
85
+ the retained window. Input drafts and UI selection remain in React.
86
+ Awaited handlers check command authorization before applying their UI result.
87
+ - `components/tasks.css` styles the task feature. Shared app and profile styles
88
+ live in `src/style.css`.
89
+
90
+ Application controllers use the same store instance as React:
91
+
92
+ ```ts
93
+ const board = getApplication().store(TaskBoardStore);
94
+ const release = board.projects.retain();
95
+ try {
96
+ const state = await board.projects.ready();
97
+ // Use state.records in a controller or indexer.
98
+ } finally {
99
+ release();
100
+ }
101
+ ```
102
+
103
+ Handles belong to their authorization session. Resolve a fresh feature when
104
+ that session changes. React's `useFeature` handles that replacement automatically.
105
+
106
+ To replace the task feature, register your own store in `app/application.ts`,
107
+ delete `src/features/tasks`, and change the feature rendered by `app/App.tsx`.
108
+ Enbox requires at least one application protocol, so keep your replacement
109
+ registered. The profile card, connection shell, and service worker remain the
110
+ base for your app.
70
111
 
71
112
  The demo's default protocol URI is
72
113
  `https://example.com/<encoded app ID>/demo/v2`. Replace the URI expression in
73
- `src/demo/protocol.ts` with a stable URI
114
+ `src/features/tasks/protocol.ts` with a stable URI
74
115
  you control before publishing. This URI identifies saved records and wallet
75
116
  grants: changing it creates a different data namespace. Once deployed, keep
76
117
  that identifier fixed when changing the app's display name.
@@ -10,8 +10,8 @@
10
10
  "preview": "vite preview"
11
11
  },
12
12
  "dependencies": {
13
- "@enbox/browser": "0.3.82",
14
- "@enbox/react": "0.0.7",
13
+ "@enbox/browser": "0.3.83",
14
+ "@enbox/react": "0.0.8",
15
15
  "react": "19.3.0",
16
16
  "react-dom": "19.3.0"
17
17
  },
@@ -1,9 +1,9 @@
1
1
  import { useEnboxConnection } from '@enbox/react';
2
2
  import { useEffect } from 'react';
3
3
 
4
- import app from './app.json' with { type: 'json' };
5
- import { TaskBoard } from './demo/TaskBoard.js';
6
- import { ProfileCard } from './ProfileCard.js';
4
+ import app from '../app.json' with { type: 'json' };
5
+ import { TaskBoard } from '../features/tasks/components/TaskBoard.js';
6
+ import { ProfileCard } from '../shared/components/ProfileCard.js';
7
7
 
8
8
  export function App() {
9
9
  const connection = useEnboxConnection();
@@ -0,0 +1,7 @@
1
+ import { defineApplication } from '@enbox/browser';
2
+
3
+ import app from '../app.json' with { type: 'json' };
4
+ import { TaskBoardStore } from '../features/tasks/store.js';
5
+
6
+ export const applicationDefinition = defineApplication({ stores: { tasks: TaskBoardStore } });
7
+ export const wallet = { appName: app.name, applicationId: app.id };
@@ -0,0 +1,17 @@
1
+ import { BrowserConnectHandler, createApplication, createConnectionStore } from '@enbox/browser';
2
+
3
+ import { applicationDefinition, wallet } from './application.js';
4
+
5
+ let runtime: ReturnType<typeof createApplication> | undefined;
6
+
7
+ /** One browser-lifetime owner shared by React and application controllers. */
8
+ export function getApplication() {
9
+ return runtime ??= createApplication(applicationDefinition, {
10
+ connection: createConnectionStore({
11
+ application: applicationDefinition.manifest,
12
+ connectHandler: BrowserConnectHandler(wallet),
13
+ }),
14
+ });
15
+ }
16
+
17
+ if (import.meta.hot) import.meta.hot.dispose(() => { void runtime?.dispose(); });
@@ -0,0 +1,163 @@
1
+ import { useFeature, useStore } from '@enbox/react';
2
+ import { useState } from 'react';
3
+ import type { FormEvent } from 'react';
4
+
5
+ import { TaskBoardStore } from '../store.js';
6
+ import './tasks.css';
7
+
8
+ export function TaskBoard({ disabled = false }: { disabled?: boolean }) {
9
+ const board = useFeature(TaskBoardStore);
10
+ const projects = useStore(board.projects);
11
+ const creation = useStore(board.createProject);
12
+ const paging = useStore(board.moreProjects);
13
+ const [projectContextId, setProjectContextId] = useState<string>();
14
+ const [name, setName] = useState('');
15
+ const creating = creation.pendingCount > 0;
16
+ const prompt = projects.status === 'loading' ? 'Loading projects…'
17
+ : projects.status === 'ready' && projects.records.length === 0 ? 'Create your first project to get started.'
18
+ : 'Select a project to see its tasks.';
19
+ async function addProject(event: FormEvent) {
20
+ event.preventDefault();
21
+ try {
22
+ const record = await board.createProject.run(name);
23
+ if (board.createProject.isCurrent()) { setProjectContextId(record.contextId); setName(''); }
24
+ } catch { /* The command exposes the error below. */ }
25
+ }
26
+ return (
27
+ <section className="panel demo" aria-labelledby="demo-title">
28
+ <h2 id="demo-title">Your projects</h2>
29
+ <p>A private task board. Create a project, add tasks, and make a little progress.</p>
30
+ <form className="demo-form" onSubmit={addProject}>
31
+ <label htmlFor="project-name">Project name</label>
32
+ <input id="project-name" value={name} maxLength={60} required
33
+ disabled={disabled || creating} onChange={(event) => setName(event.target.value)} />
34
+ <button className="button button-secondary" disabled={disabled || creating || !name.trim()}>
35
+ {creating ? 'Creating…' : 'Create project'}
36
+ </button>
37
+ </form>
38
+ {creation.error && <p role="alert">Couldn’t create the project: {creation.error.message}</p>}
39
+ {projects.status === 'error' && <div role="alert">
40
+ <p>Couldn’t load projects: {projects.error.message}</p>
41
+ <button type="button" disabled={disabled} onClick={() => { void board.retryProjects.run(); }}>Try again</button>
42
+ </div>}
43
+ <div className="project-picker" role="group" aria-label="Projects">
44
+ {projects.records.map(({ record, value }) => <button type="button" className="button button-quiet" key={record.id} disabled={disabled}
45
+ aria-pressed={record.contextId === projectContextId} onClick={() => setProjectContextId(record.contextId)}>{value.name}</button>)}
46
+ </div>
47
+ {projects.hasMore && <button type="button" disabled={disabled || paging.pendingCount > 0}
48
+ onClick={() => { void board.moreProjects.run(); }}>More projects</button>}
49
+ {projectContextId !== undefined
50
+ ? <ProjectTasks key={projectContextId} within={projectContextId} disabled={disabled} />
51
+ : <p role="status">{prompt}</p>}
52
+ </section>
53
+ );
54
+ }
55
+
56
+ function ProjectTasks({ within, disabled }: { within: string; disabled: boolean }) {
57
+ const board = useFeature(TaskBoardStore);
58
+ const resource = board.tasks.within(within);
59
+ const tasks = useStore(resource);
60
+ const creation = useStore(resource.create);
61
+ const updates = useStore(resource.patch);
62
+ const paging = useStore(board.moreTasks);
63
+ const [title, setTitle] = useState('');
64
+ // Reopening the same record creates a new UI target for completion guards.
65
+ const [selection, setSelection] = useState<{ id: string }>();
66
+ const creating = creation.pendingCount > 0;
67
+ async function addTask(event: FormEvent) {
68
+ event.preventDefault();
69
+ try {
70
+ const record = await board.createTask({ within, title });
71
+ if (resource.create.isCurrent()) { setSelection({ id: record.id }); setTitle(''); }
72
+ } catch { /* The scoped create command exposes the error below. */ }
73
+ }
74
+ return <div className="project-content">
75
+ <h3>Tasks</h3>
76
+ <form className="demo-form" onSubmit={addTask}>
77
+ <label htmlFor="task-title">New task</label>
78
+ <input id="task-title" value={title} maxLength={120} required
79
+ disabled={disabled || creating} onChange={(event) => setTitle(event.target.value)} />
80
+ <button className="button button-secondary" disabled={disabled || creating || !title.trim()}>Add task</button>
81
+ </form>
82
+ {creation.error && <p role="alert">Couldn’t add the task: {creation.error.message}</p>}
83
+ {updates.error && <p role="alert">Couldn’t update the task: {updates.error.message}</p>}
84
+ {tasks.status === 'error' && <p role="alert">Couldn’t load tasks. <button type="button"
85
+ disabled={disabled} onClick={() => { void board.retryTasks.run(within); }}>Retry tasks</button></p>}
86
+ <ul className="task-list">
87
+ {tasks.records.map(({ record, value }) => <li key={record.id} data-completed={value.completed}>
88
+ <input type="checkbox" aria-label={`Complete ${value.title}`} checked={value.completed}
89
+ disabled={disabled || updates.pendingVariables.some((input) => input.id === record.id)}
90
+ onChange={(event) => { void resource.patch.run({ id: record.id, patch: { completed: event.currentTarget.checked } }); }} />
91
+ <button type="button" className="button button-quiet" aria-label={`Open task ${value.title}`}
92
+ disabled={disabled} aria-pressed={record.id === selection?.id} onClick={() => setSelection({ id: record.id })}>{value.title}</button>
93
+ </li>)}
94
+ </ul>
95
+ {tasks.hasMore && <button type="button" disabled={disabled || paging.pendingVariables.includes(within)}
96
+ onClick={() => { void board.moreTasks.run(within); }}>More tasks</button>}
97
+ {selection !== undefined
98
+ ? <TaskDetails key={selection.id} within={within} recordId={selection.id} disabled={disabled}
99
+ onClose={() => setSelection((current) => current === selection ? undefined : current)} />
100
+ : <p role="status">Select a task to see its details.</p>}
101
+ </div>;
102
+ }
103
+
104
+ function TaskDetails({ within, recordId, disabled, onClose }: {
105
+ within: string; recordId: string; disabled: boolean; onClose: () => void;
106
+ }) {
107
+ const board = useFeature(TaskBoardStore);
108
+ const resource = board.tasks.within(within);
109
+ const list = useStore(resource);
110
+ const listed = list.records.some((row) => row.record.id === recordId);
111
+ // A bounded window cannot prove an unlisted record is missing. Reuse loaded
112
+ // rows, and acquire a single-record view only while that proof is unavailable.
113
+ const needsLookup = !listed && (list.status !== 'ready' || list.hasMore);
114
+ const selection = useStore(needsLookup ? board.taskById(within, recordId) : resource);
115
+ const task = selection.records.find((row) => row.record.id === recordId);
116
+ const status = selection.status;
117
+ const updates = useStore(resource.patch);
118
+ const deletion = useStore(resource.delete);
119
+ const [draft, setDraft] = useState<string>();
120
+ const pending = updates.pendingVariables.some((input) => input.id === recordId) || deletion.pendingVariables.includes(recordId);
121
+ async function saveTitle(event: FormEvent) {
122
+ event.preventDefault();
123
+ if (draft === undefined) return;
124
+ try {
125
+ await board.renameTask({ within, id: recordId, title: draft });
126
+ if (resource.patch.isCurrent()) setDraft(undefined);
127
+ } catch { /* The scoped patch command exposes the error below. */ }
128
+ }
129
+ async function deleteTask() {
130
+ try {
131
+ await resource.delete.run(recordId);
132
+ if (resource.delete.isCurrent()) onClose();
133
+ } catch { /* The scoped delete command exposes the error below. */ }
134
+ }
135
+ const data = task?.value;
136
+ return <section className="task-details" aria-label="Task details">
137
+ <h3>Task details</h3>
138
+ {status === 'error' && <p role="alert">Couldn’t load the task. <button type="button"
139
+ disabled={disabled} onClick={() => {
140
+ if (needsLookup) void board.retryTask.run({ within, recordId });
141
+ else void board.retryTasks.run(within);
142
+ }}>Retry task</button></p>}
143
+ {data === undefined && status === 'loading' && <p role="status">Loading task…</p>}
144
+ {data === undefined && status === 'ready' && <p role="status">This task is no longer available.</p>}
145
+ {data !== undefined && <>
146
+ <p>{data.title} · {data.completed ? 'Completed' : 'To do'}</p>
147
+ {draft === undefined
148
+ ? <button type="button" className="button button-quiet" disabled={disabled || pending}
149
+ onClick={() => setDraft(data.title)}>Edit title</button>
150
+ : <form className="demo-form" onSubmit={saveTitle}>
151
+ <label htmlFor="edit-task-title">Task title</label>
152
+ <input id="edit-task-title" value={draft} maxLength={120} required disabled={disabled || pending}
153
+ onChange={(event) => setDraft(event.target.value)} />
154
+ <button className="button button-secondary" disabled={disabled || pending || !draft.trim()}>Save title</button>
155
+ <button type="button" className="button button-quiet" disabled={disabled || pending} onClick={() => setDraft(undefined)}>Cancel</button>
156
+ </form>}
157
+ <button type="button" className="button button-quiet" disabled={disabled || pending} onClick={deleteTask}>Delete task</button>
158
+ </>}
159
+ {updates.error && <p role="alert">Couldn’t update the task: {updates.error.message}</p>}
160
+ {deletion.error && <p role="alert">Couldn’t delete the task: {deletion.error.message}</p>}
161
+ <button type="button" className="button button-quiet" onClick={onClose}>Close details</button>
162
+ </section>;
163
+ }
@@ -1,6 +1,6 @@
1
- import { defineProtocol, recordCodecs } from '@enbox/react/config';
1
+ import { defineProtocol, recordCodecs } from '@enbox/browser';
2
2
 
3
- import app from '../app.json' with { type: 'json' };
3
+ import app from '../../app.json' with { type: 'json' };
4
4
 
5
5
  export type Project = { name: string };
6
6
  export type Task = { title: string; completed: boolean };
@@ -0,0 +1,31 @@
1
+ import { DateSort, defineStore } from '@enbox/browser';
2
+
3
+ import { TaskBoardProtocol } from './protocol.js';
4
+
5
+ /** Protocol resources and domain defaults are shared with every consumer. */
6
+ export const TaskBoardStore = defineStore({
7
+ protocols: { board: TaskBoardProtocol },
8
+ create({ protocols, command }) {
9
+ const projects = protocols.board.collection('project', { dateSort: DateSort.CreatedDescending });
10
+ const tasks = protocols.board.collection('project/task');
11
+ const taskById = (within: string, recordId: string) => protocols.board.collection('project/task', {
12
+ filter: { recordId }, pagination: { limit: 1 },
13
+ }).within(within);
14
+
15
+ return {
16
+ projects,
17
+ tasks,
18
+ taskById,
19
+ createProject: command((name: string) => projects.create.run({ name: name.trim() })),
20
+ createTask: ({ within, title }: { within: string; title: string }) =>
21
+ tasks.within(within).create.run({ title: title.trim(), completed: false }),
22
+ renameTask: ({ within, id, title }: { within: string; id: string; title: string }) =>
23
+ tasks.within(within).patch.run({ id, patch: { title: title.trim() } }),
24
+ moreProjects: command(() => projects.loadMore()),
25
+ moreTasks: command((within: string) => tasks.within(within).loadMore()),
26
+ retryProjects: command(() => projects.retry()),
27
+ retryTasks: command((within: string) => tasks.within(within).retry()),
28
+ retryTask: command(({ within, recordId }: { within: string; recordId: string }) => taskById(within, recordId).retry()),
29
+ };
30
+ },
31
+ });
@@ -3,15 +3,15 @@ import { EnboxProvider } from '@enbox/react';
3
3
  import { StrictMode } from 'react';
4
4
  import { createRoot } from 'react-dom/client';
5
5
 
6
- import { App } from './App.js';
7
- import { config } from './application.js';
6
+ import { App } from './app/App.js';
7
+ import { getApplication } from './app/runtime.js';
8
8
  import workerPath from './sw.ts?worker&url';
9
9
  import './style.css';
10
10
 
11
11
  void prepareBrowser(workerPath, {
12
12
  registrationOptions: { type: 'module', scope: import.meta.env.BASE_URL },
13
13
  }).then(() => {
14
- createRoot(document.getElementById('root')!).render(<StrictMode><EnboxProvider config={config}><App /></EnboxProvider></StrictMode>);
14
+ createRoot(document.getElementById('root')!).render(<StrictMode><EnboxProvider application={getApplication()}><App /></EnboxProvider></StrictMode>);
15
15
  }).catch((cause: unknown) => {
16
16
  const root = document.getElementById('root')!;
17
17
  root.textContent = cause instanceof Error ? cause.message : 'Could not open the app.';
@@ -1,10 +0,0 @@
1
- import { defineApplicationManifest } from '@enbox/react/config';
2
- import type { CreateEnboxClientOptions } from '@enbox/react/config';
3
-
4
- import app from './app.json' with { type: 'json' };
5
- import { TaskBoardProtocol } from './demo/protocol.js';
6
-
7
- export const config = {
8
- application: defineApplicationManifest({ protocols: [TaskBoardProtocol] }),
9
- wallet: { appName: app.name, applicationId: app.id },
10
- } satisfies CreateEnboxClientOptions;
@@ -1,136 +0,0 @@
1
- import { useState } from 'react';
2
- import type { FormEvent } from 'react';
3
-
4
- import { useProjects, useTask, useTasks } from './use-task-board.js';
5
- import './demo.css';
6
-
7
- export function TaskBoard({ disabled = false }: { disabled?: boolean }) {
8
- const projects = useProjects();
9
- const [projectContextId, setProjectContextId] = useState<string>();
10
- const [name, setName] = useState('');
11
- const prompt = projects.isLoading ? 'Loading projects…'
12
- : projects.isReady && projects.records.length === 0 ? 'Create your first project to get started.'
13
- : 'Select a project to see its tasks.';
14
- async function addProject(event: FormEvent) {
15
- event.preventDefault();
16
- try {
17
- const record = await projects.create.mutateAsync({ name: name.trim() });
18
- if (projects.create.isCurrent()) { setProjectContextId(record.contextId); setName(''); }
19
- } catch { /* The mutation error is rendered below. */ }
20
- }
21
- return (
22
- <section className="panel demo" aria-labelledby="demo-title">
23
- <h2 id="demo-title">Your projects</h2>
24
- <p>A private task board. Create a project, add tasks, and make a little progress.</p>
25
- <form className="demo-form" onSubmit={addProject}>
26
- <label htmlFor="project-name">Project name</label>
27
- <input id="project-name" value={name} maxLength={60} required
28
- disabled={disabled || projects.create.isPending} onChange={(event) => setName(event.target.value)} />
29
- <button className="button button-secondary" disabled={disabled || projects.create.isPending || !name.trim()}>
30
- {projects.create.isPending ? 'Creating…' : 'Create project'}
31
- </button>
32
- </form>
33
- {projects.create.error && <p role="alert">Couldn’t create the project: {projects.create.error.message}</p>}
34
- {projects.status === 'error' && <div role="alert">
35
- <p>Couldn’t load projects: {projects.error.message}</p>
36
- <button type="button" disabled={disabled} onClick={() => projects.retry()}>Try again</button>
37
- </div>}
38
- <div className="project-picker" role="group" aria-label="Projects">
39
- {projects.records.map((project) => <button type="button" className="button button-quiet" key={project.id} disabled={disabled}
40
- aria-pressed={project.contextId === projectContextId} onClick={() => setProjectContextId(project.contextId)}>{project.data.name}</button>)}
41
- </div>
42
- {projects.hasMore && <button type="button" disabled={disabled || projects.isLoadingMore}
43
- onClick={() => projects.loadMore()}>More projects</button>}
44
- {projectContextId !== undefined
45
- ? <ProjectTasks key={projectContextId} within={projectContextId} disabled={disabled} />
46
- : <p role="status">{prompt}</p>}
47
- </section>
48
- );
49
- }
50
-
51
- function ProjectTasks({ within, disabled }: { within: string; disabled: boolean }) {
52
- const tasks = useTasks(within);
53
- const [title, setTitle] = useState('');
54
- const [selectedId, setSelectedId] = useState<string>();
55
- async function addTask(event: FormEvent) {
56
- event.preventDefault();
57
- try {
58
- const record = await tasks.create.mutateAsync({ title: title.trim(), completed: false });
59
- if (tasks.create.isCurrent()) { setSelectedId(record.id); setTitle(''); }
60
- } catch { /* The mutation error is rendered below. */ }
61
- }
62
- return <div className="project-content">
63
- <h3>Tasks</h3>
64
- <form className="demo-form" onSubmit={addTask}>
65
- <label htmlFor="task-title">New task</label>
66
- <input id="task-title" value={title} maxLength={120} required
67
- disabled={disabled || tasks.create.isPending} onChange={(event) => setTitle(event.target.value)} />
68
- <button className="button button-secondary" disabled={disabled || tasks.create.isPending || !title.trim()}>Add task</button>
69
- </form>
70
- {tasks.create.error && <p role="alert">Couldn’t add the task: {tasks.create.error.message}</p>}
71
- {tasks.patch.error && <p role="alert">Couldn’t update the task: {tasks.patch.error.message}</p>}
72
- {tasks.status === 'error' && <p role="alert">Couldn’t load tasks. <button type="button"
73
- disabled={disabled} onClick={() => tasks.retry()}>Retry tasks</button></p>}
74
- <ul className="task-list">
75
- {tasks.records.map((task) => <li key={task.id} data-completed={task.data.completed}>
76
- <input type="checkbox" aria-label={`Complete ${task.data.title}`} checked={task.data.completed}
77
- disabled={disabled || tasks.patch.isPendingFor(task.id)}
78
- onChange={(event) => tasks.patch.mutate({ id: task.id, patch: { completed: event.currentTarget.checked } })} />
79
- <button type="button" className="button button-quiet" aria-label={`Open task ${task.data.title}`}
80
- disabled={disabled} aria-pressed={task.id === selectedId} onClick={() => setSelectedId(task.id)}>{task.data.title}</button>
81
- </li>)}
82
- </ul>
83
- {tasks.hasMore && <button type="button" disabled={disabled || tasks.isLoadingMore}
84
- onClick={() => tasks.loadMore()}>More tasks</button>}
85
- {selectedId !== undefined
86
- ? <TaskDetails key={selectedId} within={within} recordId={selectedId} disabled={disabled} onClose={() => setSelectedId(undefined)} />
87
- : <p role="status">Select a task to see its details.</p>}
88
- </div>;
89
- }
90
-
91
- function TaskDetails({ within, recordId, disabled, onClose }: {
92
- within: string; recordId: string; disabled: boolean; onClose: () => void;
93
- }) {
94
- const task = useTask(within, recordId);
95
- const [draft, setDraft] = useState<string>();
96
- const pending = task.patch.isPending || task.delete.isPending;
97
- async function saveTitle(event: FormEvent) {
98
- event.preventDefault();
99
- if (draft === undefined) return;
100
- try {
101
- await task.patch.mutateAsync({ title: draft.trim() });
102
- if (task.patch.isCurrent()) setDraft(undefined);
103
- } catch { /* The mutation error is rendered below. */ }
104
- }
105
- async function deleteTask() {
106
- try {
107
- await task.delete.mutateAsync();
108
- if (task.delete.isCurrent()) onClose();
109
- } catch { /* The mutation error is rendered below. */ }
110
- }
111
- const data = task.data;
112
- return <section className="task-details" aria-label="Task details">
113
- <h3>Task details</h3>
114
- {task.status === 'error' && <p role="alert">Couldn’t load the task. <button type="button"
115
- disabled={disabled} onClick={() => task.retry()}>Retry task</button></p>}
116
- {data === undefined && task.isLoading && <p role="status">Loading task…</p>}
117
- {data === undefined && task.isReady && <p role="status">This task is no longer available.</p>}
118
- {data !== undefined && <>
119
- <p>{data.title} · {data.completed ? 'Completed' : 'To do'}</p>
120
- {draft === undefined
121
- ? <button type="button" className="button button-quiet" disabled={disabled || pending}
122
- onClick={() => setDraft(data.title)}>Edit title</button>
123
- : <form className="demo-form" onSubmit={saveTitle}>
124
- <label htmlFor="edit-task-title">Task title</label>
125
- <input id="edit-task-title" value={draft} maxLength={120} required disabled={disabled || pending}
126
- onChange={(event) => setDraft(event.target.value)} />
127
- <button className="button button-secondary" disabled={disabled || pending || !draft.trim()}>Save title</button>
128
- <button type="button" className="button button-quiet" disabled={disabled || pending} onClick={() => setDraft(undefined)}>Cancel</button>
129
- </form>}
130
- <button type="button" className="button button-quiet" disabled={disabled || pending} onClick={deleteTask}>Delete task</button>
131
- </>}
132
- {task.patch.error && <p role="alert">Couldn’t update the task: {task.patch.error.message}</p>}
133
- {task.delete.error && <p role="alert">Couldn’t delete the task: {task.delete.error.message}</p>}
134
- <button type="button" className="button button-quiet" onClick={onClose}>Close details</button>
135
- </section>;
136
- }
@@ -1,16 +0,0 @@
1
- import { useEnboxRecord, useEnboxRecords } from '@enbox/react';
2
- import { DateSort } from '@enbox/react/config';
3
-
4
- import { TaskBoardProtocol } from './protocol.js';
5
-
6
- export function useProjects() {
7
- return useEnboxRecords(TaskBoardProtocol, 'project', { dateSort: DateSort.CreatedDescending });
8
- }
9
-
10
- export function useTasks(within: string) {
11
- return useEnboxRecords(TaskBoardProtocol, 'project/task', { within });
12
- }
13
-
14
- export function useTask(within: string, recordId: string) {
15
- return useEnboxRecord(TaskBoardProtocol, 'project/task', { within, recordId });
16
- }