@openpeepshq/react 0.6.0 → 0.6.1

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.
Files changed (93) hide show
  1. package/dist/components/index.d.ts +1 -0
  2. package/dist/components/index.js +1 -0
  3. package/dist/components/post/CompactReplyParent.js +8 -0
  4. package/dist/components/post/FeedPostContent.js +3 -0
  5. package/dist/components/post/NewResourceButton.d.ts +8 -0
  6. package/dist/components/post/NewResourceButton.js +36 -0
  7. package/dist/components/post/PostDetail.js +3 -0
  8. package/dist/components/post/index.d.ts +5 -0
  9. package/dist/components/post/index.js +3 -0
  10. package/dist/components/post/pieces/PostMenu.js +4 -0
  11. package/dist/components/post/post-form/PostTypeSwitcher.js +12 -2
  12. package/dist/components/post/post-form/ResourceForm.d.ts +7 -0
  13. package/dist/components/post/post-form/ResourceForm.js +68 -0
  14. package/dist/components/post/types/resource/FullResource.d.ts +5 -0
  15. package/dist/components/post/types/resource/FullResource.js +99 -0
  16. package/dist/components/resources/CategoryPathPicker.d.ts +7 -0
  17. package/dist/components/resources/CategoryPathPicker.js +26 -0
  18. package/dist/components/resources/ResourceCard.d.ts +8 -0
  19. package/dist/components/resources/ResourceCard.js +121 -0
  20. package/dist/components/resources/ResourceLibrary.d.ts +4 -0
  21. package/dist/components/resources/ResourceLibrary.js +106 -0
  22. package/dist/components/resources/index.d.ts +6 -0
  23. package/dist/components/resources/index.js +3 -0
  24. package/dist/contexts/openpeeps/hooks/admin.d.ts +1064 -38
  25. package/dist/contexts/openpeeps/hooks/jams.d.ts +1064 -38
  26. package/dist/contexts/openpeeps/hooks/posts.d.ts +4508 -39936
  27. package/dist/hooks/events/useEventComposer.d.ts +1184 -44
  28. package/dist/hooks/events/useEventsCalendar.d.ts +2113 -61
  29. package/dist/hooks/index.d.ts +2 -0
  30. package/dist/hooks/index.js +2 -0
  31. package/dist/hooks/jams/useCreateNewJamForm.d.ts +39 -1
  32. package/dist/hooks/jams/useJamDetails.d.ts +1064 -38
  33. package/dist/hooks/jams/useJamRoom.d.ts +2113 -61
  34. package/dist/hooks/posts/useArticleComposer.d.ts +1184 -44
  35. package/dist/hooks/posts/useFeedPostPresentation.d.ts +2113 -61
  36. package/dist/hooks/posts/usePostDetailTitle.d.ts +1064 -38
  37. package/dist/hooks/posts/useResourceComposer.d.ts +12019 -0
  38. package/dist/hooks/posts/useResourceComposer.js +139 -0
  39. package/dist/hooks/resources/useResourceLibrary.d.ts +21880 -0
  40. package/dist/hooks/resources/useResourceLibrary.js +130 -0
  41. package/dist/hooks/settings/useNotificationPreferences.d.ts +1 -1
  42. package/dist/navigation/menuItems.js +5 -0
  43. package/dist/navigation/targets.d.ts +4 -0
  44. package/dist/pages/admin/analytics/Content.js +2 -1
  45. package/dist/pages/admin/analytics/Overview.js +15 -3
  46. package/dist/pages/groups/Show.js +7 -3
  47. package/dist/pages/index.d.ts +3 -0
  48. package/dist/pages/index.js +3 -0
  49. package/dist/pages/resources/Edit.d.ts +1 -0
  50. package/dist/pages/resources/Edit.js +26 -0
  51. package/dist/pages/resources/Index.d.ts +1 -0
  52. package/dist/pages/resources/Index.js +29 -0
  53. package/dist/pages/resources/New.d.ts +1 -0
  54. package/dist/pages/resources/New.js +15 -0
  55. package/dist/react-native.d.ts +1 -1
  56. package/dist/react-native.js +1 -1
  57. package/dist/stores/index.d.ts +1 -1
  58. package/dist/stores/index.js +1 -1
  59. package/dist/stores/newPosts.d.ts +79 -2
  60. package/dist/stores/newPosts.js +26 -2
  61. package/dist/stores/types.d.ts +2 -0
  62. package/package.json +6 -6
  63. package/src/components/index.ts +1 -0
  64. package/src/components/post/CompactReplyParent.tsx +8 -0
  65. package/src/components/post/FeedPostContent.tsx +3 -0
  66. package/src/components/post/NewResourceButton.tsx +75 -0
  67. package/src/components/post/PostDetail.tsx +3 -0
  68. package/src/components/post/index.ts +5 -0
  69. package/src/components/post/pieces/PostMenu.tsx +4 -0
  70. package/src/components/post/post-form/PostTypeSwitcher.tsx +19 -1
  71. package/src/components/post/post-form/ResourceForm.tsx +237 -0
  72. package/src/components/post/types/resource/FullResource.tsx +173 -0
  73. package/src/components/resources/CategoryPathPicker.tsx +95 -0
  74. package/src/components/resources/ResourceCard.tsx +335 -0
  75. package/src/components/resources/ResourceLibrary.tsx +374 -0
  76. package/src/components/resources/index.ts +6 -0
  77. package/src/contexts/openpeeps/hooks/posts.ts +11 -2
  78. package/src/hooks/index.ts +2 -0
  79. package/src/hooks/posts/useResourceComposer.ts +165 -0
  80. package/src/hooks/resources/useResourceLibrary.ts +156 -0
  81. package/src/navigation/menuItems.ts +6 -0
  82. package/src/navigation/targets.ts +1 -0
  83. package/src/pages/admin/analytics/Content.tsx +2 -1
  84. package/src/pages/admin/analytics/Overview.tsx +15 -3
  85. package/src/pages/groups/Show.tsx +30 -1
  86. package/src/pages/index.ts +3 -0
  87. package/src/pages/resources/Edit.tsx +73 -0
  88. package/src/pages/resources/Index.tsx +45 -0
  89. package/src/pages/resources/New.tsx +53 -0
  90. package/src/react-native.ts +1 -0
  91. package/src/stores/index.ts +1 -0
  92. package/src/stores/newPosts.ts +33 -2
  93. package/src/stores/types.ts +2 -0
@@ -0,0 +1,374 @@
1
+ import {
2
+ LayoutList,
3
+ LayoutGrid,
4
+ BookmarkIcon,
5
+ ChevronDown,
6
+ ChevronRight,
7
+ } from 'lucide-react';
8
+ import type { ResourceKind } from '@openpeepshq/common/types';
9
+ import { RESOURCE_KINDS } from '@openpeepshq/common/lib';
10
+ import { Button, Input, LoadingSpinner } from '@openpeepshq/react-ui';
11
+ import { useMemo, useState } from 'react';
12
+ import { useT } from '../../i18n';
13
+ import { useHrefOf } from '../../contexts/router';
14
+ import { useResourceLibrary } from '../../hooks';
15
+ import { ResourceCard } from './ResourceCard';
16
+ import type { CategoryNode } from '@openpeepshq/common/lib';
17
+
18
+ export interface ResourceLibraryProps {
19
+ groupId?: string;
20
+ }
21
+
22
+ const COLLECTION_LIMIT = 5;
23
+
24
+ const Tree = ({
25
+ nodes,
26
+ selected,
27
+ onSelect,
28
+ counts,
29
+ expanded,
30
+ onToggle,
31
+ }: {
32
+ nodes: CategoryNode[];
33
+ selected: string[];
34
+ onSelect: (path: string[]) => void;
35
+ counts: Map<string, number>;
36
+ expanded: Set<string>;
37
+ onToggle: (nodeKey: string) => void;
38
+ }) => (
39
+ <ul className="space-y-1">
40
+ {nodes.map((node) => {
41
+ const nodeKey = node.path.join('/');
42
+ const nodeCount = counts.get(nodeKey) ?? 0;
43
+ const isExpanded = expanded.has(nodeKey);
44
+ const isSelected = selected.join('/') === nodeKey;
45
+ const hasChildren = node.children.length > 0;
46
+ return (
47
+ <li key={nodeKey}>
48
+ <div className="flex items-center gap-1">
49
+ <button
50
+ type="button"
51
+ className={`text-muted-foreground hover:text-foreground ${
52
+ hasChildren ? '' : 'invisible'
53
+ }`}
54
+ onClick={hasChildren ? () => onToggle(nodeKey) : undefined}
55
+ >
56
+ <ChevronRight
57
+ className={`size-3 transition-transform ${
58
+ isExpanded ? 'rotate-90' : ''
59
+ }`}
60
+ />
61
+ </button>
62
+ <button
63
+ type="button"
64
+ className={`text-sm ${
65
+ isSelected
66
+ ? 'font-semibold'
67
+ : 'text-muted-foreground hover:text-foreground'
68
+ }`}
69
+ onClick={() => onSelect(node.path)}
70
+ >
71
+ {node.name}
72
+ {nodeCount > 0 ? (
73
+ <span className="text-xs opacity-60">({nodeCount})</span>
74
+ ) : null}
75
+ </button>
76
+ </div>
77
+ {hasChildren && isExpanded ? (
78
+ <div className="ml-4">
79
+ <Tree
80
+ nodes={node.children}
81
+ selected={selected}
82
+ onSelect={onSelect}
83
+ counts={counts}
84
+ expanded={expanded}
85
+ onToggle={onToggle}
86
+ />
87
+ </div>
88
+ ) : null}
89
+ </li>
90
+ );
91
+ })}
92
+ </ul>
93
+ );
94
+
95
+ export const ResourceLibrary = ({ groupId }: ResourceLibraryProps) => {
96
+ const t = useT();
97
+ const hrefOf = useHrefOf();
98
+ const library = useResourceLibrary(groupId);
99
+ const [expanded, setExpanded] = useState<Set<string>>(new Set());
100
+
101
+ const toggleNode = (nodeKey: string) => {
102
+ setExpanded((prev) => {
103
+ const next = new Set(prev);
104
+ if (next.has(nodeKey)) next.delete(nodeKey);
105
+ else next.add(nodeKey);
106
+ return next;
107
+ });
108
+ };
109
+
110
+ const collectionCounts = useMemo(() => {
111
+ const counts = new Map<string, number>();
112
+ let rootCount = 0;
113
+ for (const post of library.posts) {
114
+ if (post.data?.type !== 'resource') continue;
115
+ const path = post.data.categoryPath;
116
+ if (!path?.length) continue;
117
+ rootCount++;
118
+ for (let i = 1; i <= path.length; i++) {
119
+ const key = path.slice(0, i).join('/');
120
+ counts.set(key, (counts.get(key) ?? 0) + 1);
121
+ }
122
+ }
123
+ counts.set('', rootCount);
124
+ return counts;
125
+ }, [library.posts]);
126
+
127
+ const treeNodes = useMemo(() => {
128
+ if (library.tree.length === 0) return [];
129
+ return [
130
+ {
131
+ name: t('resources.library.allFolders', {
132
+ defaultValue: 'All folders',
133
+ }),
134
+ path: [] as string[],
135
+ children: library.tree,
136
+ },
137
+ ];
138
+ }, [library.tree, t]);
139
+
140
+ const sortedTags = useMemo(
141
+ () =>
142
+ library.tags
143
+ .filter((entry) => library.selectedTags.includes(entry.name))
144
+ .concat(
145
+ library.tags.filter(
146
+ (entry) => !library.selectedTags.includes(entry.name),
147
+ ),
148
+ ),
149
+ [library.tags, library.selectedTags],
150
+ );
151
+
152
+ const visibleTags = library.tagsOpen
153
+ ? sortedTags
154
+ : sortedTags.slice(0, COLLECTION_LIMIT);
155
+ const hasMoreTags = sortedTags.length > COLLECTION_LIMIT;
156
+
157
+ return (
158
+ <div>
159
+ <div className="flex flex-col gap-3 p-4">
160
+ {/* Search + view toggle */}
161
+ <div className="flex flex-wrap items-center gap-2">
162
+ <Input
163
+ className="flex-1"
164
+ value={library.search}
165
+ onChange={(event) => library.setSearch(event.target.value)}
166
+ placeholder={t('resources.library.search', {
167
+ defaultValue: 'Search resources',
168
+ })}
169
+ data-testid="resources-search"
170
+ />
171
+ <div className="ml-auto flex gap-1">
172
+ <Button
173
+ compact
174
+ size="sm"
175
+ variant={library.view === 'list' ? 'default' : 'outline'}
176
+ action={() => library.setView('list')}
177
+ data-testid="resources-view-list"
178
+ title={t('resources.library.viewList', {
179
+ defaultValue: 'List view',
180
+ })}
181
+ >
182
+ <LayoutList className="size-4" />
183
+ </Button>
184
+ <Button
185
+ compact
186
+ size="sm"
187
+ variant={library.view === 'cards' ? 'default' : 'outline'}
188
+ action={() => library.setView('cards')}
189
+ data-testid="resources-view-cards"
190
+ title={t('resources.library.viewCards', {
191
+ defaultValue: 'Cards view',
192
+ })}
193
+ >
194
+ <LayoutGrid className="size-4" />
195
+ </Button>
196
+ <Button
197
+ compact
198
+ size="sm"
199
+ variant={library.saved ? 'default' : 'outline'}
200
+ action={() => library.setSaved(!library.saved)}
201
+ data-testid="resources-saved"
202
+ title={t('resources.library.saved', { defaultValue: 'Saved' })}
203
+ >
204
+ <BookmarkIcon className="size-4" />
205
+ {t('resources.library.saved', { defaultValue: 'Saved' })}
206
+ </Button>
207
+ </div>
208
+ </div>
209
+
210
+ {/* Type filters (format-level) */}
211
+ <div className="flex flex-wrap gap-2">
212
+ <Button
213
+ compact
214
+ variant={library.kind === 'all' ? 'default' : 'outline'}
215
+ action={() => library.setKind('all')}
216
+ >
217
+ {t('resources.library.allKinds', { defaultValue: 'All' })}
218
+ </Button>
219
+ {RESOURCE_KINDS.map((kind) => (
220
+ <Button
221
+ key={kind}
222
+ compact
223
+ variant={library.kind === kind ? 'default' : 'outline'}
224
+ action={() => library.setKind(kind as ResourceKind)}
225
+ >
226
+ {t(`resources.kinds.${kind}`, { defaultValue: kind })}
227
+ </Button>
228
+ ))}
229
+ </div>
230
+
231
+ {/* Breadcrumb + tree */}
232
+ <div>
233
+ <div className="flex items-center gap-2 text-sm">
234
+ <button
235
+ type="button"
236
+ className="text-muted-foreground hover:text-foreground"
237
+ onClick={() => library.setPathPrefix([])}
238
+ >
239
+ All
240
+ </button>
241
+ {library.pathPrefix.length > 0 ? (
242
+ <>
243
+ <span className="text-muted-foreground">/</span>
244
+ <span className="text-muted-foreground">
245
+ {library.pathPrefix.join(' / ')}
246
+ </span>
247
+ </>
248
+ ) : null}
249
+ <button
250
+ type="button"
251
+ className="text-muted-foreground hover:text-foreground ml-auto"
252
+ onClick={() => library.setHierarchy(!library.hierarchy)}
253
+ >
254
+ {library.hierarchy ? (
255
+ <ChevronDown className="size-4" />
256
+ ) : (
257
+ <ChevronRight className="size-4" />
258
+ )}
259
+ </button>
260
+ </div>
261
+ {library.hierarchy ? (
262
+ <div className="border-border mt-2 rounded-md border p-3">
263
+ {treeNodes.length ? (
264
+ <Tree
265
+ nodes={treeNodes}
266
+ selected={library.pathPrefix}
267
+ onSelect={library.setPathPrefix}
268
+ counts={collectionCounts}
269
+ expanded={expanded}
270
+ onToggle={toggleNode}
271
+ />
272
+ ) : null}
273
+ </div>
274
+ ) : null}
275
+ </div>
276
+
277
+ {/* Tags (collapsible secondary discovery) */}
278
+ {library.tags.length ? (
279
+ <div className="flex flex-col gap-1">
280
+ <div className="flex flex-wrap gap-1">
281
+ {visibleTags.map((entry) => {
282
+ const isSelected = library.selectedTags.includes(entry.name);
283
+ return (
284
+ <button
285
+ key={entry.name}
286
+ type="button"
287
+ className={`rounded-full px-2 py-0.5 text-xs ${
288
+ isSelected
289
+ ? 'bg-primary text-primary-foreground'
290
+ : 'bg-muted text-muted-foreground'
291
+ }`}
292
+ onClick={() => library.toggleTag(entry.name)}
293
+ >
294
+ #{entry.name} {entry.count}
295
+ </button>
296
+ );
297
+ })}
298
+ </div>
299
+ {hasMoreTags ? (
300
+ <button
301
+ type="button"
302
+ className="bg-muted text-muted-foreground rounded-full px-2 py-0.5 text-xs"
303
+ onClick={() => library.setTagsOpen(!library.tagsOpen)}
304
+ >
305
+ {library.tagsOpen
306
+ ? t('resources.library.hideTags', {
307
+ defaultValue: 'Hide',
308
+ })
309
+ : t('resources.library.showHiddenTags', {
310
+ defaultValue: '+ {{count}}',
311
+ count: sortedTags.length - COLLECTION_LIMIT,
312
+ })}
313
+ </button>
314
+ ) : null}
315
+ </div>
316
+ ) : null}
317
+
318
+ {/* Resource count */}
319
+ {library.posts.length > 0 ? (
320
+ <p className="text-muted-foreground text-xs">
321
+ {t('resources.library.resourceCount', {
322
+ defaultValue: 'Showing {{count}} resources',
323
+ count: library.posts.length,
324
+ })}
325
+ </p>
326
+ ) : null}
327
+ </div>
328
+
329
+ {library.query.isLoading ? (
330
+ <div className="flex h-32 items-center justify-center">
331
+ <LoadingSpinner />
332
+ </div>
333
+ ) : library.posts.length === 0 ? (
334
+ <p className="text-muted-foreground p-8 text-center text-sm">
335
+ {library.activeFilterCount > 0
336
+ ? t('resources.library.noResults', {
337
+ defaultValue: 'No resources match your current filters.',
338
+ })
339
+ : library.pathPrefix.length
340
+ ? t('resources.library.emptyCollection', {
341
+ defaultValue: 'This collection has no resources yet.',
342
+ })
343
+ : t('resources.library.empty', {
344
+ defaultValue: 'No resources yet.',
345
+ })}
346
+ </p>
347
+ ) : library.view === 'list' ? (
348
+ <div className="divide-border flex flex-col divide-y">
349
+ {library.posts.map((post) => (
350
+ <a
351
+ key={post.id}
352
+ href={hrefOf({ type: 'post', id: post.id })}
353
+ className="block"
354
+ >
355
+ <ResourceCard post={post} layout="list" />
356
+ </a>
357
+ ))}
358
+ </div>
359
+ ) : (
360
+ <div className="grid grid-cols-1 gap-4 p-4 sm:grid-cols-2 lg:grid-cols-3">
361
+ {library.posts.map((post) => (
362
+ <a
363
+ key={post.id}
364
+ href={hrefOf({ type: 'post', id: post.id })}
365
+ className="block"
366
+ >
367
+ <ResourceCard post={post} layout="card" />
368
+ </a>
369
+ ))}
370
+ </div>
371
+ )}
372
+ </div>
373
+ );
374
+ };
@@ -0,0 +1,6 @@
1
+ export { ResourceLibrary } from './ResourceLibrary';
2
+ export type { ResourceLibraryProps } from './ResourceLibrary';
3
+ export { ResourceCard } from './ResourceCard';
4
+ export type { ResourceCardProps } from './ResourceCard';
5
+ export { CategoryPathPicker } from './CategoryPathPicker';
6
+ export type { CategoryPathPickerProps } from './CategoryPathPicker';
@@ -88,7 +88,14 @@ type EventFeeds = ReturnType<typeof eventFeeds>;
88
88
  */
89
89
  const DEFAULT_FEED_LIMIT = 15;
90
90
 
91
- const jamFeeds = (client: OpenpeepsClient) => ({
91
+ const jamFeeds = (
92
+ client: OpenpeepsClient,
93
+ ): {
94
+ useUpcomingJamsFeed: (pageSize?: number) => EventFeedHook;
95
+ usePastJamsFeed: (pageSize?: number) => EventFeedHook;
96
+ useMyUpcomingJamsFeed: (pageSize?: number) => EventFeedHook;
97
+ useMyPastJamsFeed: (pageSize?: number) => EventFeedHook;
98
+ } => ({
92
99
  useUpcomingJamsFeed: (pageSize: number | undefined = DEFAULT_FEED_LIMIT) =>
93
100
  infiniteOffsetQueryApiHook(client.posts.feeds.jams.upcoming, { pageSize }),
94
101
  usePastJamsFeed: (pageSize: number | undefined = DEFAULT_FEED_LIMIT) =>
@@ -235,7 +242,9 @@ const postMutators = (client: OpenpeepsClient) => ({
235
242
  ['profiles', 'current', 'bookmarkedIds'],
236
243
  ]),
237
244
  markPostsSeenAction: payloadPostsReadMutation(client.posts.seen),
238
- markGroupPostsSeenAction: noPayloadPostsReadMutation(client.posts.seenByGroup),
245
+ markGroupPostsSeenAction: noPayloadPostsReadMutation(
246
+ client.posts.seenByGroup,
247
+ ),
239
248
  repostPostAction: noPayloadMutation(client.posts.repost, [['posts']]),
240
249
  voteOnPostAction: payloadMutation(client.posts.vote, [['posts']]),
241
250
  rsvpToEventAction: payloadMutation(client.posts.rsvp, [['posts'], ['rsvp']]),
@@ -80,6 +80,8 @@ export { useNewGroup } from './groups/useNewGroup';
80
80
  export { useGroupTemplateSelection } from './groups/useGroupTemplateSelection';
81
81
  export type { UseGroupTemplateSelectionArgs } from './groups/useGroupTemplateSelection';
82
82
  export { useNewArticle, useEditArticle } from './posts/useArticleComposer';
83
+ export { useNewResource, useEditResource } from './posts/useResourceComposer';
84
+ export { useResourceLibrary } from './resources/useResourceLibrary';
83
85
  export {
84
86
  useEventsCalendar,
85
87
  eventName as calendarEventName,
@@ -0,0 +1,165 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import type {
3
+ PostCreationData,
4
+ PostDataUnion,
5
+ ResourcePost,
6
+ } from '@openpeepshq/common/types';
7
+ import {
8
+ normalizeResourceTags,
9
+ resourceHasRequiredMedia,
10
+ } from '@openpeepshq/common/lib';
11
+ import { useOpenpeeps } from '../../contexts/openpeeps';
12
+ import { useNavigate } from '../../contexts/router';
13
+ import { useT } from '../../i18n/context';
14
+ import { useServerInfo } from '../../components/server-data';
15
+ import { defaultNewResource, getNewPostStores } from '../../stores';
16
+
17
+ const asResource = (data: PostDataUnion): ResourcePost | null =>
18
+ data.type === 'resource' ? data : null;
19
+
20
+ const preparedResource = (resource: ResourcePost): ResourcePost => ({
21
+ ...resource,
22
+ title: resource.title.trim(),
23
+ tags: normalizeResourceTags(resource.tags),
24
+ categoryPath: (resource.categoryPath ?? [])
25
+ .map((segment) => segment.trim())
26
+ .filter(Boolean),
27
+ url: resource.url?.trim() || undefined,
28
+ });
29
+
30
+ export const useNewResource = () => {
31
+ const t = useT();
32
+ const navigate = useNavigate();
33
+ const serverInfo = useServerInfo();
34
+ const { openpeepsApi } = useOpenpeeps();
35
+ const createPost = openpeepsApi.createPostAction();
36
+ const stores = getNewPostStores();
37
+
38
+ const [postData, setPostDataState] = useState<PostCreationData>(() => {
39
+ const stored = stores.resource;
40
+ if (stored.type === 'resource' && stored.data.type === 'resource') {
41
+ return stored;
42
+ }
43
+ return defaultNewResource(serverInfo.publicContent);
44
+ });
45
+ const [submitting, setSubmitting] = useState(false);
46
+ const [error, setError] = useState<string | null>(null);
47
+
48
+ const resource = asResource(postData.data);
49
+ const canSubmit =
50
+ !!resource?.title.trim() &&
51
+ !!resource &&
52
+ resourceHasRequiredMedia(resource) &&
53
+ !(postData.visibility === 'direct' && !postData.audience?.length);
54
+
55
+ const setPostData = (data: PostCreationData) => {
56
+ setPostDataState(data);
57
+ stores.resource = data;
58
+ };
59
+
60
+ const submit = useCallback(async () => {
61
+ setError(null);
62
+ if (!resource?.title.trim()) {
63
+ setError(
64
+ t('resources.validation.titleRequired', {
65
+ defaultValue: 'Title is required',
66
+ }),
67
+ );
68
+ return;
69
+ }
70
+ if (!resourceHasRequiredMedia(resource)) {
71
+ setError(
72
+ t('resources.validation.mediaRequired', {
73
+ defaultValue: 'Add the media or link this resource needs',
74
+ }),
75
+ );
76
+ return;
77
+ }
78
+ if (postData.visibility === 'direct' && !postData.audience?.length) {
79
+ setError(
80
+ t('resources.validation.directAudience', {
81
+ defaultValue: 'Choose at least one recipient for a direct resource.',
82
+ }),
83
+ );
84
+ return;
85
+ }
86
+ setSubmitting(true);
87
+ try {
88
+ const created = await createPost({
89
+ ...postData,
90
+ type: 'resource',
91
+ data: preparedResource(resource),
92
+ });
93
+ stores.resetNewResourceState();
94
+ navigate({ type: 'post', id: created.id });
95
+ } catch (err) {
96
+ setError((err as Error).message);
97
+ } finally {
98
+ setSubmitting(false);
99
+ }
100
+ }, [createPost, navigate, postData, resource, stores, t]);
101
+
102
+ return {
103
+ postData,
104
+ setPostData,
105
+ canSubmit,
106
+ submitting,
107
+ error,
108
+ clearError: () => setError(null),
109
+ submit,
110
+ };
111
+ };
112
+
113
+ export const useEditResource = (resourceId: string) => {
114
+ const navigate = useNavigate();
115
+ const { openpeepsApi } = useOpenpeeps();
116
+ const postQuery = openpeepsApi.usePost(resourceId);
117
+ const updatePost = openpeepsApi.updatePostAction({ id: resourceId });
118
+
119
+ const [postData, setPostData] = useState<PostCreationData | null>(null);
120
+ const [submitting, setSubmitting] = useState(false);
121
+ const [error, setError] = useState<string | null>(null);
122
+
123
+ useEffect(() => {
124
+ if (postQuery.data && postQuery.data.type === 'resource') {
125
+ setPostData({
126
+ visibility: postQuery.data.visibility,
127
+ type: 'resource',
128
+ groupId: postQuery.data.groupId ?? undefined,
129
+ audience: postQuery.data.audience ?? undefined,
130
+ data: postQuery.data.data as PostDataUnion & { type: 'resource' },
131
+ });
132
+ }
133
+ }, [postQuery.data]);
134
+
135
+ const resourceTitle = asResource(
136
+ postQuery.data?.data as PostDataUnion,
137
+ )?.title;
138
+
139
+ const submit = useCallback(async () => {
140
+ if (!postData) return;
141
+ const resource = asResource(postData.data);
142
+ if (!resource) return;
143
+ setError(null);
144
+ setSubmitting(true);
145
+ try {
146
+ await updatePost(preparedResource(resource));
147
+ navigate({ type: 'post', id: resourceId });
148
+ } catch (err) {
149
+ setError((err as Error).message);
150
+ } finally {
151
+ setSubmitting(false);
152
+ }
153
+ }, [navigate, postData, resourceId, updatePost]);
154
+
155
+ return {
156
+ postQuery,
157
+ postData,
158
+ setPostData,
159
+ resourceTitle,
160
+ submitting,
161
+ error,
162
+ clearError: () => setError(null),
163
+ submit,
164
+ };
165
+ };