@openpeepshq/react 0.8.0 → 0.8.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.
@@ -3,6 +3,10 @@ import type { MediaAttachmentData } from '@openpeepshq/common';
3
3
  export interface ComposeAttachmentsProps {
4
4
  attachments: MediaAttachmentData[];
5
5
  onChange: (attachments: MediaAttachmentData[]) => void;
6
+ /** Image picker may select several files at once (resource galleries). */
7
+ multipleImages?: boolean;
8
+ /** Audio picker may select several files at once (default: yes). */
9
+ multipleAudio?: boolean;
6
10
  }
7
11
  export interface ComposeAttachmentsApi {
8
12
  openImagePicker: () => void;
@@ -22,5 +26,5 @@ export interface ComposeAttachmentsApi {
22
26
  * attachments are reported back via `onChange`. Exposes the toolbar pickers and
23
27
  * preview grid separately so callers can lay them out independently.
24
28
  */
25
- export declare function useComposeAttachments({ attachments, onChange, }: ComposeAttachmentsProps): ComposeAttachmentsApi;
29
+ export declare function useComposeAttachments({ attachments, onChange, multipleImages, multipleAudio, }: ComposeAttachmentsProps): ComposeAttachmentsApi;
26
30
  export declare function ComposeAttachments(props: ComposeAttachmentsProps): import("react/jsx-runtime").JSX.Element;
@@ -33,7 +33,7 @@ const readyItem = (attachment) => ({
33
33
  * attachments are reported back via `onChange`. Exposes the toolbar pickers and
34
34
  * preview grid separately so callers can lay them out independently.
35
35
  */
36
- export function useComposeAttachments({ attachments, onChange, }) {
36
+ export function useComposeAttachments({ attachments, onChange, multipleImages = false, multipleAudio = true, }) {
37
37
  const imageInputRef = useRef(null);
38
38
  const audioInputRef = useRef(null);
39
39
  const documentInputRef = useRef(null);
@@ -79,6 +79,20 @@ export function useComposeAttachments({ attachments, onChange, }) {
79
79
  }
80
80
  enqueueFile(processed);
81
81
  };
82
+ // A single pick keeps the crop/alt-text flow; a bulk pick is enqueued
83
+ // directly, since per-file cropping isn't practical for a gallery batch.
84
+ const handleImageFilesSelected = async (files) => {
85
+ const first = files[0];
86
+ if (!first)
87
+ return;
88
+ if (files.length === 1) {
89
+ await handleImageSelected(first);
90
+ return;
91
+ }
92
+ for (const file of files) {
93
+ enqueueFile(await convertToWebpIfHeic(file));
94
+ }
95
+ };
82
96
  const onUploaded = (key, attachment) => setItems((prev) => prev.map((i) => {
83
97
  if (i.key !== key)
84
98
  return i;
@@ -111,12 +125,12 @@ export function useComposeAttachments({ attachments, onChange, }) {
111
125
  const pending = items.some((i) => (i.file && !i.attachment && !i.failed) ||
112
126
  i.attachment?.status === 'processing');
113
127
  const previews = items.length > 0 ? (_jsx("div", { className: "grid grid-cols-2 gap-2", children: items.map((item) => (_jsx(AttachmentCard, { item: item, onUploaded: onUploaded, onProcessed: onProcessed, onFailed: onFailed, onRemove: onRemove, onUpdate: onUpdate }, item.key))) })) : null;
114
- const inputs = (_jsxs(_Fragment, { children: [_jsx("input", { ref: imageInputRef, type: "file", accept: "image/*,video/*,.mkv", className: "hidden", onChange: (e) => {
115
- const file = e.target.files?.[0];
116
- if (file)
117
- void handleImageSelected(file);
128
+ const inputs = (_jsxs(_Fragment, { children: [_jsx("input", { ref: imageInputRef, type: "file", accept: "image/*,video/*,.mkv", multiple: multipleImages, className: "hidden", onChange: (e) => {
129
+ const files = e.target.files;
130
+ if (files?.length)
131
+ void handleImageFilesSelected(Array.from(files));
118
132
  e.target.value = '';
119
- } }), _jsx("input", { ref: audioInputRef, type: "file", accept: "audio/*,.mp3,.wav,.ogg,.m4a,.aac,.flac,.opus,.weba", multiple: true, className: "hidden", onChange: (e) => {
133
+ } }), _jsx("input", { ref: audioInputRef, type: "file", accept: "audio/*,.mp3,.wav,.ogg,.m4a,.aac,.flac,.opus,.weba", multiple: multipleAudio, className: "hidden", onChange: (e) => {
120
134
  const files = e.target.files;
121
135
  if (files) {
122
136
  Array.from(files).forEach((file) => enqueueFile(file));
@@ -0,0 +1,131 @@
1
+ /** @vitest-environment jsdom */
2
+ import { act, createElement } from 'react';
3
+ import { createRoot } from 'react-dom/client';
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
+ import { useComposeAttachments } from './ComposeAttachments.js';
6
+ const { useMediaUpload } = vi.hoisted(() => ({
7
+ useMediaUpload: vi.fn(),
8
+ }));
9
+ vi.mock('../../../contexts/openpeeps', () => ({
10
+ useOpenpeeps: () => ({
11
+ openpeepsApi: {
12
+ useMediaUpload,
13
+ useMediaProgress: () => undefined,
14
+ },
15
+ }),
16
+ }));
17
+ vi.mock('../../../i18n', () => ({
18
+ useT: () => (key, opts) => opts?.defaultValue ?? key,
19
+ }));
20
+ // The crop modal is exercised through its presence, not its internals.
21
+ vi.mock('../../form/ImageEditModal', () => ({
22
+ ImageEditModal: ({ open }) => open ? createElement('div', { 'data-testid': 'crop-modal' }) : null,
23
+ }));
24
+ vi.mock('./DescriptionEditModal', () => ({
25
+ DescriptionEditModal: () => null,
26
+ }));
27
+ const uploadMock = vi.fn();
28
+ let urlCounter = 0;
29
+ const imageFile = (name) => new File([new Uint8Array(16)], name, { type: 'image/png' });
30
+ const Harness = ({ multipleImages, multipleAudio, onChange, }) => {
31
+ const api = useComposeAttachments({
32
+ attachments: [],
33
+ onChange,
34
+ multipleImages,
35
+ multipleAudio,
36
+ });
37
+ return createElement('div', null, api.previews, api.inputs);
38
+ };
39
+ const pickFiles = (container, files) => act(async () => {
40
+ const input = container.querySelector('input[accept^="image"]');
41
+ if (!(input instanceof HTMLInputElement)) {
42
+ throw new Error('image input not found');
43
+ }
44
+ Object.defineProperty(input, 'files', { value: files, configurable: true });
45
+ input.dispatchEvent(new Event('change', { bubbles: true }));
46
+ await new Promise((resolve) => setTimeout(resolve, 0));
47
+ });
48
+ describe('useComposeAttachments pickers', () => {
49
+ let container;
50
+ let root;
51
+ const render = (props) => {
52
+ const onChange = vi.fn();
53
+ const r = createRoot(container);
54
+ root = r;
55
+ act(() => {
56
+ r.render(createElement(Harness, { ...props, onChange }));
57
+ });
58
+ return { onChange };
59
+ };
60
+ const inputs = () => ({
61
+ image: container.querySelector('input[accept^="image"]'),
62
+ audio: container.querySelector('input[accept^="audio"]'),
63
+ });
64
+ beforeEach(() => {
65
+ useMediaUpload.mockReset();
66
+ useMediaUpload.mockReturnValue({
67
+ state: { uploading: false, uploadPercent: 0 },
68
+ upload: uploadMock,
69
+ abort: vi.fn(),
70
+ });
71
+ uploadMock.mockReset();
72
+ uploadMock.mockImplementation(async ({ description }) => {
73
+ urlCounter += 1;
74
+ return {
75
+ id: `attachment-${urlCounter}`,
76
+ type: 'image',
77
+ url: `https://cdn.example.com/images/${urlCounter}.webp`,
78
+ previewUrl: null,
79
+ textUrl: null,
80
+ filename: description ?? 'image',
81
+ meta: { usage: 'post-image', mimetype: 'image/webp', size: 16 },
82
+ status: 'ready',
83
+ };
84
+ });
85
+ urlCounter = 0;
86
+ container = document.createElement('div');
87
+ document.body.appendChild(container);
88
+ vi.stubGlobal('URL', class extends URL {
89
+ static createObjectURL() {
90
+ urlCounter += 1;
91
+ return `blob:mock-${urlCounter}`;
92
+ }
93
+ static revokeObjectURL() { }
94
+ });
95
+ });
96
+ afterEach(() => {
97
+ act(() => {
98
+ root?.unmount();
99
+ });
100
+ container.remove();
101
+ vi.unstubAllGlobals();
102
+ });
103
+ it('marks the image input multiple only when requested', () => {
104
+ render({ multipleImages: true, multipleAudio: false });
105
+ const { image, audio } = inputs();
106
+ expect(image.multiple).toBe(true);
107
+ expect(audio.multiple).toBe(false);
108
+ });
109
+ it('enqueues each file of a bulk pick without the crop modal', async () => {
110
+ const { onChange } = render({ multipleImages: true, multipleAudio: false });
111
+ await pickFiles(container, [imageFile('one.png'), imageFile('two.png')]);
112
+ expect(uploadMock).toHaveBeenCalledTimes(2);
113
+ const ready = onChange.mock.calls.at(-1)?.[0] ?? [];
114
+ expect(ready).toHaveLength(2);
115
+ const urls = ready.map((attachment) => attachment.url);
116
+ expect(new Set(urls).size).toBe(2);
117
+ expect(container.querySelector('[data-testid="crop-modal"]')).toBeNull();
118
+ });
119
+ it('keeps the crop modal for a single image pick', async () => {
120
+ render({ multipleImages: true, multipleAudio: false });
121
+ await pickFiles(container, [imageFile('one.png')]);
122
+ expect(container.querySelector('[data-testid="crop-modal"]')).not.toBeNull();
123
+ expect(uploadMock).not.toHaveBeenCalled();
124
+ });
125
+ it('stays single-file by default for post composers', () => {
126
+ render({});
127
+ const { image, audio } = inputs();
128
+ expect(image.multiple).toBe(false);
129
+ expect(audio.multiple).toBe(true);
130
+ });
131
+ });
@@ -21,6 +21,9 @@ export const ResourceForm = ({ postData, onChange, isEdit = false, groupOnly = f
21
21
  const attachments = useComposeAttachments({
22
22
  attachments: resource.attachments ?? [],
23
23
  onChange: (next) => patchResource({ attachments: next }),
24
+ // Only galleries take more than one file; other kinds pick one at a time.
25
+ multipleImages: resource.resourceKind === 'gallery',
26
+ multipleAudio: false,
24
27
  });
25
28
  const patchResource = (patch) => {
26
29
  onChange({
@@ -2,13 +2,13 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
2
2
  import { useMemo, useState } from 'react';
3
3
  import { BookmarkCheck, BookmarkPlus, Link as LinkIcon, ImageOff, } from 'lucide-react';
4
4
  import { attachmentMediaKind, formatSize, groupName, normalizeResourceTags, } from '@openpeepshq/common/lib';
5
- import { useHrefOf } from '../../contexts/router/index.js';
5
+ import { useHrefOf, useNavigate } from '../../contexts/router/index.js';
6
6
  import { useT } from '../../i18n/index.js';
7
+ import { useStaticRender } from '../markdown/staticRender.js';
7
8
  import { useOpenpeeps } from '../../contexts/openpeeps/index.js';
8
9
  import { useCurrentProfile } from '../layout/IdentityContext.js';
9
10
  import { VideoPlayOverlay } from '../post/VideoPlayOverlay.js';
10
11
  import { TruncatedMarkdown } from '../post/TruncatedMarkdown.js';
11
- import { useNavigate } from '../../contexts/router/index.js';
12
12
  const visualAttachments = (attachments) => attachments.filter((att) => attachmentMediaKind(att) !== 'audio');
13
13
  const previewSrc = (att) => att.previewUrl ?? att.url;
14
14
  /** Thumbnail size shared between list and card previews. */
@@ -28,6 +28,64 @@ const primaryActionLabel = (kind, t) => {
28
28
  return null;
29
29
  }
30
30
  };
31
+ /**
32
+ * Bookmark toggle. Lives in its own component so ResourceCard itself stays
33
+ * free of app providers (OpenpeepsProvider, IdentityContext, RouterProvider)
34
+ * and can render in provider-less static contexts such as notification emails.
35
+ */
36
+ const ResourceSaveButton = ({ postId, className, }) => {
37
+ const t = useT();
38
+ const { openpeepsApi } = useOpenpeeps();
39
+ const me = useCurrentProfile();
40
+ const bookmarkedIdsQuery = openpeepsApi.useCurrentProfileBookmarkedIds();
41
+ const bookmarkPost = openpeepsApi.bookmarkPostAction({ id: postId });
42
+ const unbookmarkPost = openpeepsApi.unbookmarkPostAction({ id: postId });
43
+ const isBookmarked = bookmarkedIdsQuery.data?.includes(postId) ?? false;
44
+ const toggleBookmark = () => {
45
+ if (!me)
46
+ return;
47
+ if (isBookmarked) {
48
+ unbookmarkPost(undefined);
49
+ }
50
+ else {
51
+ bookmarkPost(undefined);
52
+ }
53
+ };
54
+ return (_jsx("button", { type: "button", onClick: (e) => {
55
+ e.preventDefault();
56
+ e.stopPropagation();
57
+ toggleBookmark();
58
+ }, disabled: !me, className: className, title: isBookmarked
59
+ ? t('resources.actions.saved', { defaultValue: 'Saved' })
60
+ : t('resources.actions.save', { defaultValue: 'Save' }), children: isBookmarked ? (_jsx(BookmarkCheck, { className: "text-primary size-4" })) : (_jsx(BookmarkPlus, { className: "size-4" })) }));
61
+ };
62
+ /**
63
+ * Clickable hashtag chip. Child component like ResourceSaveButton so the
64
+ * router hook stays out of ResourceCard's static (email) render path.
65
+ */
66
+ const ResourceTagChip = ({ value }) => {
67
+ const navigate = useNavigate();
68
+ return (_jsxs("button", { type: "button", className: "bg-muted text-muted-foreground hover:text-foreground rounded-full px-2 py-0.5 text-xs", onClick: (e) => {
69
+ e.preventDefault();
70
+ e.stopPropagation();
71
+ navigate({ type: 'tags', hashtag: value });
72
+ }, children: ["#", value] }));
73
+ };
74
+ /** Clickable group label. Child component so the router hook stays out of the static render path. */
75
+ const ResourceGroupLabel = ({ group }) => {
76
+ const t = useT();
77
+ const hrefOf = useHrefOf();
78
+ const groupLabel = groupName(group);
79
+ return (_jsx("a", { href: hrefOf({ type: 'group', handle: group.handle }), onClick: (e) => {
80
+ e.stopPropagation();
81
+ }, className: "text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs", title: t('resources.group.inGroup', {
82
+ defaultValue: 'in {{groupName}}',
83
+ groupName: groupLabel,
84
+ }), children: _jsx("span", { className: "bg-muted rounded-full px-2 py-0.5 text-xs", children: t('resources.group.inGroup', {
85
+ defaultValue: 'in {{groupName}}',
86
+ groupName: groupLabel,
87
+ }) }) }));
88
+ };
31
89
  const MediaPreview = ({ src, alt, className, isVideo, isLast, extra, }) => {
32
90
  const [errored, setErrored] = useState(false);
33
91
  if (!src) {
@@ -40,25 +98,24 @@ const MediaPreview = ({ src, alt, className, isVideo, isLast, extra, }) => {
40
98
  };
41
99
  export const ResourceCard = ({ post, layout = 'card', preview, showDescription = true, inGroup = false, }) => {
42
100
  const t = useT();
43
- const navigate = useNavigate();
44
- const hrefOf = useHrefOf();
45
- const { openpeepsApi } = useOpenpeeps();
46
- const me = useCurrentProfile();
47
- if (post.data?.type !== 'resource')
48
- return null;
49
- const resource = post.data;
50
- const attachments = resource.attachments ?? [];
101
+ const { enabled: staticRender } = useStaticRender();
102
+ const resource = post.data?.type === 'resource' ? post.data : undefined;
103
+ const attachments = resource?.attachments ?? [];
51
104
  const visuals = visualAttachments(attachments);
52
- const tags = normalizeResourceTags(resource.tags);
53
- const isGallery = resource.resourceKind === 'gallery' && visuals.length > 1;
105
+ const tags = normalizeResourceTags(resource?.tags);
106
+ const isGallery = resource?.resourceKind === 'gallery' && visuals.length > 1;
54
107
  const tiles = isGallery ? visuals.slice(0, 4) : visuals.slice(0, 1);
55
108
  const extra = isGallery ? Math.max(0, visuals.length - 4) : 0;
56
- const actionLabel = primaryActionLabel(resource.resourceKind, t);
109
+ const actionLabel = resource
110
+ ? primaryActionLabel(resource.resourceKind, t)
111
+ : null;
57
112
  const thumbnail = visuals[0];
58
113
  const thumbSrc = thumbnail ? previewSrc(thumbnail) : null;
59
114
  const group = post.group;
60
115
  const groupLabel = group ? groupName(group) : null;
61
116
  const metaText = useMemo(() => {
117
+ if (!resource)
118
+ return null;
62
119
  if (resource.resourceKind === 'gallery' && visuals.length > 1) {
63
120
  return t('resources.meta.imagesCount', {
64
121
  defaultValue: '{{count}} images',
@@ -72,44 +129,24 @@ export const ResourceCard = ({ post, layout = 'card', preview, showDescription =
72
129
  if (size)
73
130
  return formatSize(size);
74
131
  return null;
75
- }, [resource.resourceKind, visuals, attachments, t]);
76
- const bookmarkedIdsQuery = openpeepsApi.useCurrentProfileBookmarkedIds();
77
- const isBookmarked = bookmarkedIdsQuery.data?.includes(post.id) ?? false;
78
- const bookmarkPost = openpeepsApi.bookmarkPostAction({ id: post.id });
79
- const unbookmarkPost = openpeepsApi.unbookmarkPostAction({ id: post.id });
80
- const toggleBookmark = () => {
81
- if (!me)
82
- return;
83
- if (isBookmarked) {
84
- unbookmarkPost(undefined);
85
- }
86
- else {
87
- bookmarkPost(undefined);
88
- }
89
- };
132
+ }, [resource, visuals, attachments, t]);
133
+ if (!resource)
134
+ return null;
90
135
  const downloadUrl = resource.resourceKind === 'file'
91
136
  ? attachments.find((att) => attachmentMediaKind(att) === 'file')?.url
92
137
  : null;
93
- const renderBookmarkButton = (className) => (_jsx("button", { type: "button", onClick: (e) => {
94
- e.preventDefault();
95
- e.stopPropagation();
96
- toggleBookmark();
97
- }, disabled: !me, className: className, title: isBookmarked
98
- ? t('resources.actions.saved', { defaultValue: 'Saved' })
99
- : t('resources.actions.save', { defaultValue: 'Save' }), children: isBookmarked ? (_jsx(BookmarkCheck, { className: "text-primary size-4" })) : (_jsx(BookmarkPlus, { className: "size-4" })) }));
138
+ const renderSaveButton = (className) => staticRender ? null : (_jsx(ResourceSaveButton, { postId: post.id, className: className }));
100
139
  const renderGroupLabel = () => {
101
140
  if (!group || !groupLabel || inGroup)
102
141
  return null;
103
- const groupHref = hrefOf({ type: 'group', handle: group.handle });
104
- return (_jsx("a", { href: groupHref, onClick: (e) => {
105
- e.stopPropagation();
106
- }, className: "text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs", title: t('resources.group.inGroup', {
107
- defaultValue: 'in {{groupName}}',
108
- groupName: groupLabel,
109
- }), children: _jsx("span", { className: "bg-muted rounded-full px-2 py-0.5 text-xs", children: t('resources.group.inGroup', {
110
- defaultValue: 'in {{groupName}}',
111
- groupName: groupLabel,
112
- }) }) }));
142
+ const label = t('resources.group.inGroup', {
143
+ defaultValue: 'in {{groupName}}',
144
+ groupName: groupLabel,
145
+ });
146
+ if (staticRender) {
147
+ return (_jsx("span", { className: "text-muted-foreground inline-flex items-center gap-1 text-xs", children: _jsx("span", { className: "bg-muted rounded-full px-2 py-0.5 text-xs", children: label }) }));
148
+ }
149
+ return _jsx(ResourceGroupLabel, { group: group });
113
150
  };
114
151
  const renderThumbnail = () => {
115
152
  if (thumbSrc) {
@@ -123,8 +160,8 @@ export const ResourceCard = ({ post, layout = 'card', preview, showDescription =
123
160
  return null;
124
161
  };
125
162
  if (layout === 'list') {
126
- return (_jsxs("div", { className: "flex w-full min-w-0 items-center gap-3 px-4 py-3", children: [renderThumbnail(), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("h3", { className: "text-lg font-semibold", children: resource.title }), resource.categoryPath?.length ? (_jsx("p", { className: "text-muted-foreground text-xs", children: resource.categoryPath.join(' / ') })) : null, renderGroupLabel(), showDescription ? (_jsx(TruncatedMarkdown, { source: resource.content ?? '', maxBlocks: 2, maxChars: 240, maxLines: 2, className: "text-sm text-muted-foreground" })) : null, metaText ? (_jsx("p", { className: "text-muted-foreground text-xs", children: metaText })) : null] }), _jsxs("div", { className: "flex items-center gap-2", children: [resource.resourceKind === 'link' &&
127
- resource.url ? null : actionLabel ? (resource.resourceKind === 'file' && downloadUrl ? (_jsx("a", { href: downloadUrl, download: true, onClick: (e) => e.stopPropagation(), className: "text-primary text-xs font-medium", children: actionLabel })) : (_jsx("span", { className: "text-muted-foreground text-xs", children: actionLabel }))) : null, renderBookmarkButton('text-muted-foreground hover:text-foreground disabled:opacity-50')] })] }));
163
+ return (_jsxs("div", { className: "flex w-full min-w-0 items-center gap-3 px-4 py-3", children: [renderThumbnail(), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("h3", { className: "text-lg font-semibold", children: resource.title }), resource.categoryPath?.length ? (_jsx("p", { className: "text-muted-foreground text-xs", children: resource.categoryPath.join(' / ') })) : null, renderGroupLabel(), showDescription ? (_jsx(TruncatedMarkdown, { source: resource.content ?? '', maxBlocks: 2, maxChars: 240, maxLines: 2, interactive: !staticRender, className: "text-sm text-muted-foreground" })) : null, metaText ? (_jsx("p", { className: "text-muted-foreground text-xs", children: metaText })) : null] }), _jsxs("div", { className: "flex items-center gap-2", children: [resource.resourceKind === 'link' &&
164
+ resource.url ? null : actionLabel ? (resource.resourceKind === 'file' && downloadUrl ? (_jsx("a", { href: downloadUrl, download: true, onClick: (e) => e.stopPropagation(), className: "text-primary text-xs font-medium", children: actionLabel })) : (_jsx("span", { className: "text-muted-foreground text-xs", children: actionLabel }))) : null, renderSaveButton('text-muted-foreground hover:text-foreground disabled:opacity-50')] })] }));
128
165
  }
129
166
  return (_jsxs("div", { className: "flex w-full min-w-0 flex-col gap-2", children: [_jsxs("div", { className: "relative", children: [preview ? (preview) : tiles.length ? (_jsx("div", { className: `overflow-hidden rounded-md ${tiles.length > 1
130
167
  ? 'grid h-48 grid-cols-2 grid-rows-2 gap-1'
@@ -135,11 +172,7 @@ export const ResourceCard = ({ post, layout = 'card', preview, showDescription =
135
172
  return (_jsx("div", { className: "bg-surface relative h-full w-full overflow-hidden", children: _jsx(MediaPreview, { src: src, alt: att.description ?? resource.title, className: tiles.length > 1
136
173
  ? 'h-full w-full object-cover'
137
174
  : CARD_IMG_CLASS, isVideo: kind === 'video', isLast: last, extra: extra }) }, `${att.url ?? index}-${index}`));
138
- }) })) : resource.resourceKind === 'link' && resource.url ? (_jsx("div", { className: "bg-muted flex h-48 w-full items-center justify-center rounded-md", children: _jsx(LinkIcon, { className: "text-muted-foreground/50 size-8" }) })) : null, renderBookmarkButton('bg-background text-muted-foreground hover:text-foreground absolute right-2 top-2 rounded-full p-1 opacity-70 hover:opacity-100 disabled:opacity-50')] }), _jsx("h3", { className: "text-lg font-semibold", children: resource.title }), resource.categoryPath?.length ? (_jsx("p", { className: "text-muted-foreground text-xs", children: resource.categoryPath.join(' / ') })) : null, renderGroupLabel(), showDescription ? (_jsx(TruncatedMarkdown, { source: resource.content ?? '', maxBlocks: 2, maxChars: 240, maxLines: 2, className: "text-sm text-muted-foreground" })) : null, metaText ? (_jsx("p", { className: "text-muted-foreground text-xs", children: metaText })) : null, tags.length ? (_jsx("div", { className: "flex flex-wrap gap-1", children: tags.map((value) => (_jsxs("button", { type: "button", className: "bg-muted text-muted-foreground hover:text-foreground rounded-full px-2 py-0.5 text-xs", onClick: (e) => {
139
- e.preventDefault();
140
- e.stopPropagation();
141
- navigate({ type: 'tags', hashtag: value });
142
- }, children: ["#", value] }, value))) })) : null, _jsx("p", { className: "text-muted-foreground text-xs uppercase", children: t(`resources.kinds.${resource.resourceKind}`, {
175
+ }) })) : resource.resourceKind === 'link' && resource.url ? (_jsx("div", { className: "bg-muted flex h-48 w-full items-center justify-center rounded-md", children: _jsx(LinkIcon, { className: "text-muted-foreground/50 size-8" }) })) : null, renderSaveButton('bg-background text-muted-foreground hover:text-foreground absolute right-2 top-2 rounded-full p-1 opacity-70 hover:opacity-100 disabled:opacity-50')] }), _jsx("h3", { className: "text-lg font-semibold", children: resource.title }), resource.categoryPath?.length ? (_jsx("p", { className: "text-muted-foreground text-xs", children: resource.categoryPath.join(' / ') })) : null, renderGroupLabel(), showDescription ? (_jsx(TruncatedMarkdown, { source: resource.content ?? '', maxBlocks: 2, maxChars: 240, maxLines: 2, interactive: !staticRender, className: "text-sm text-muted-foreground" })) : null, metaText ? (_jsx("p", { className: "text-muted-foreground text-xs", children: metaText })) : null, tags.length ? (_jsx("div", { className: "flex flex-wrap gap-1", children: tags.map((value) => staticRender ? (_jsxs("span", { className: "bg-muted text-muted-foreground rounded-full px-2 py-0.5 text-xs", children: ["#", value] }, value)) : (_jsx(ResourceTagChip, { value: value }, value))) })) : null, _jsx("p", { className: "text-muted-foreground text-xs uppercase", children: t(`resources.kinds.${resource.resourceKind}`, {
143
176
  defaultValue: resource.resourceKind,
144
177
  }) })] }));
145
178
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/react",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -10,6 +10,10 @@ import { isBlobUrl, revokeBlobUrl } from '../attachmentPreview';
10
10
  export interface ComposeAttachmentsProps {
11
11
  attachments: MediaAttachmentData[];
12
12
  onChange: (attachments: MediaAttachmentData[]) => void;
13
+ /** Image picker may select several files at once (resource galleries). */
14
+ multipleImages?: boolean;
15
+ /** Audio picker may select several files at once (default: yes). */
16
+ multipleAudio?: boolean;
13
17
  }
14
18
 
15
19
  const AUDIO_NAME = /\.(mp3|wav|ogg|oga|m4a|aac|flac|opus|weba)$/i;
@@ -59,6 +63,8 @@ export interface ComposeAttachmentsApi {
59
63
  export function useComposeAttachments({
60
64
  attachments,
61
65
  onChange,
66
+ multipleImages = false,
67
+ multipleAudio = true,
62
68
  }: ComposeAttachmentsProps): ComposeAttachmentsApi {
63
69
  const imageInputRef = useRef<HTMLInputElement>(null);
64
70
  const audioInputRef = useRef<HTMLInputElement>(null);
@@ -130,6 +136,20 @@ export function useComposeAttachments({
130
136
  enqueueFile(processed);
131
137
  };
132
138
 
139
+ // A single pick keeps the crop/alt-text flow; a bulk pick is enqueued
140
+ // directly, since per-file cropping isn't practical for a gallery batch.
141
+ const handleImageFilesSelected = async (files: File[]) => {
142
+ const first = files[0];
143
+ if (!first) return;
144
+ if (files.length === 1) {
145
+ await handleImageSelected(first);
146
+ return;
147
+ }
148
+ for (const file of files) {
149
+ enqueueFile(await convertToWebpIfHeic(file));
150
+ }
151
+ };
152
+
133
153
  const onUploaded = (key: string, attachment: MediaAttachment) =>
134
154
  setItems((prev) =>
135
155
  prev.map((i) => {
@@ -204,10 +224,11 @@ export function useComposeAttachments({
204
224
  ref={imageInputRef}
205
225
  type="file"
206
226
  accept="image/*,video/*,.mkv"
227
+ multiple={multipleImages}
207
228
  className="hidden"
208
229
  onChange={(e) => {
209
- const file = e.target.files?.[0];
210
- if (file) void handleImageSelected(file);
230
+ const files = e.target.files;
231
+ if (files?.length) void handleImageFilesSelected(Array.from(files));
211
232
  e.target.value = '';
212
233
  }}
213
234
  />
@@ -215,7 +236,7 @@ export function useComposeAttachments({
215
236
  ref={audioInputRef}
216
237
  type="file"
217
238
  accept="audio/*,.mp3,.wav,.ogg,.m4a,.aac,.flac,.opus,.weba"
218
- multiple
239
+ multiple={multipleAudio}
219
240
  className="hidden"
220
241
  onChange={(e) => {
221
242
  const files = e.target.files;
@@ -48,6 +48,9 @@ export const ResourceForm = ({
48
48
  const attachments = useComposeAttachments({
49
49
  attachments: resource.attachments ?? [],
50
50
  onChange: (next) => patchResource({ attachments: next }),
51
+ // Only galleries take more than one file; other kinds pick one at a time.
52
+ multipleImages: resource.resourceKind === 'gallery',
53
+ multipleAudio: false,
51
54
  });
52
55
 
53
56
  const patchResource = (patch: Partial<ResourcePost>) => {
@@ -7,6 +7,7 @@ import {
7
7
  ImageOff,
8
8
  } from 'lucide-react';
9
9
  import type {
10
+ GroupWithMeta,
10
11
  MediaAttachmentData,
11
12
  PublicPost,
12
13
  ResourceKind,
@@ -17,13 +18,13 @@ import {
17
18
  groupName,
18
19
  normalizeResourceTags,
19
20
  } from '@openpeepshq/common/lib';
20
- import { useHrefOf } from '../../contexts/router';
21
+ import { useHrefOf, useNavigate } from '../../contexts/router';
21
22
  import { useT } from '../../i18n';
23
+ import { useStaticRender } from '../markdown/staticRender';
22
24
  import { useOpenpeeps } from '../../contexts/openpeeps';
23
25
  import { useCurrentProfile } from '../layout/IdentityContext';
24
26
  import { VideoPlayOverlay } from '../post/VideoPlayOverlay';
25
27
  import { TruncatedMarkdown } from '../post/TruncatedMarkdown';
26
- import { useNavigate } from '../../contexts/router';
27
28
 
28
29
  export interface ResourceCardProps {
29
30
  post: PublicPost;
@@ -59,6 +60,108 @@ const primaryActionLabel = (kind: ResourceKind, t: ReturnType<typeof useT>) => {
59
60
  }
60
61
  };
61
62
 
63
+ /**
64
+ * Bookmark toggle. Lives in its own component so ResourceCard itself stays
65
+ * free of app providers (OpenpeepsProvider, IdentityContext, RouterProvider)
66
+ * and can render in provider-less static contexts such as notification emails.
67
+ */
68
+ const ResourceSaveButton = ({
69
+ postId,
70
+ className,
71
+ }: {
72
+ postId: string;
73
+ className: string;
74
+ }) => {
75
+ const t = useT();
76
+ const { openpeepsApi } = useOpenpeeps();
77
+ const me = useCurrentProfile();
78
+ const bookmarkedIdsQuery = openpeepsApi.useCurrentProfileBookmarkedIds();
79
+ const bookmarkPost = openpeepsApi.bookmarkPostAction({ id: postId });
80
+ const unbookmarkPost = openpeepsApi.unbookmarkPostAction({ id: postId });
81
+ const isBookmarked = bookmarkedIdsQuery.data?.includes(postId) ?? false;
82
+
83
+ const toggleBookmark = () => {
84
+ if (!me) return;
85
+ if (isBookmarked) {
86
+ unbookmarkPost(undefined);
87
+ } else {
88
+ bookmarkPost(undefined);
89
+ }
90
+ };
91
+
92
+ return (
93
+ <button
94
+ type="button"
95
+ onClick={(e) => {
96
+ e.preventDefault();
97
+ e.stopPropagation();
98
+ toggleBookmark();
99
+ }}
100
+ disabled={!me}
101
+ className={className}
102
+ title={
103
+ isBookmarked
104
+ ? t('resources.actions.saved', { defaultValue: 'Saved' })
105
+ : t('resources.actions.save', { defaultValue: 'Save' })
106
+ }
107
+ >
108
+ {isBookmarked ? (
109
+ <BookmarkCheck className="text-primary size-4" />
110
+ ) : (
111
+ <BookmarkPlus className="size-4" />
112
+ )}
113
+ </button>
114
+ );
115
+ };
116
+
117
+ /**
118
+ * Clickable hashtag chip. Child component like ResourceSaveButton so the
119
+ * router hook stays out of ResourceCard's static (email) render path.
120
+ */
121
+ const ResourceTagChip = ({ value }: { value: string }) => {
122
+ const navigate = useNavigate();
123
+ return (
124
+ <button
125
+ type="button"
126
+ className="bg-muted text-muted-foreground hover:text-foreground rounded-full px-2 py-0.5 text-xs"
127
+ onClick={(e) => {
128
+ e.preventDefault();
129
+ e.stopPropagation();
130
+ navigate({ type: 'tags', hashtag: value });
131
+ }}
132
+ >
133
+ #{value}
134
+ </button>
135
+ );
136
+ };
137
+
138
+ /** Clickable group label. Child component so the router hook stays out of the static render path. */
139
+ const ResourceGroupLabel = ({ group }: { group: GroupWithMeta }) => {
140
+ const t = useT();
141
+ const hrefOf = useHrefOf();
142
+ const groupLabel = groupName(group);
143
+ return (
144
+ <a
145
+ href={hrefOf({ type: 'group', handle: group.handle })}
146
+ onClick={(e) => {
147
+ e.stopPropagation();
148
+ }}
149
+ className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs"
150
+ title={t('resources.group.inGroup', {
151
+ defaultValue: 'in {{groupName}}',
152
+ groupName: groupLabel,
153
+ })}
154
+ >
155
+ <span className="bg-muted rounded-full px-2 py-0.5 text-xs">
156
+ {t('resources.group.inGroup', {
157
+ defaultValue: 'in {{groupName}}',
158
+ groupName: groupLabel,
159
+ })}
160
+ </span>
161
+ </a>
162
+ );
163
+ };
164
+
62
165
  const MediaPreview = ({
63
166
  src,
64
167
  alt,
@@ -118,19 +221,17 @@ export const ResourceCard = ({
118
221
  inGroup = false,
119
222
  }: ResourceCardProps) => {
120
223
  const t = useT();
121
- const navigate = useNavigate();
122
- const hrefOf = useHrefOf();
123
- const { openpeepsApi } = useOpenpeeps();
124
- const me = useCurrentProfile();
125
- if (post.data?.type !== 'resource') return null;
126
- const resource = post.data;
127
- const attachments = resource.attachments ?? [];
224
+ const { enabled: staticRender } = useStaticRender();
225
+ const resource = post.data?.type === 'resource' ? post.data : undefined;
226
+ const attachments = resource?.attachments ?? [];
128
227
  const visuals = visualAttachments(attachments);
129
- const tags = normalizeResourceTags(resource.tags);
130
- const isGallery = resource.resourceKind === 'gallery' && visuals.length > 1;
228
+ const tags = normalizeResourceTags(resource?.tags);
229
+ const isGallery = resource?.resourceKind === 'gallery' && visuals.length > 1;
131
230
  const tiles = isGallery ? visuals.slice(0, 4) : visuals.slice(0, 1);
132
231
  const extra = isGallery ? Math.max(0, visuals.length - 4) : 0;
133
- const actionLabel = primaryActionLabel(resource.resourceKind, t);
232
+ const actionLabel = resource
233
+ ? primaryActionLabel(resource.resourceKind, t)
234
+ : null;
134
235
  const thumbnail = visuals[0];
135
236
  const thumbSrc = thumbnail ? previewSrc(thumbnail) : null;
136
237
 
@@ -138,6 +239,7 @@ export const ResourceCard = ({
138
239
  const groupLabel = group ? groupName(group) : null;
139
240
 
140
241
  const metaText = useMemo(() => {
242
+ if (!resource) return null;
141
243
  if (resource.resourceKind === 'gallery' && visuals.length > 1) {
142
244
  return t('resources.meta.imagesCount', {
143
245
  defaultValue: '{{count}} images',
@@ -153,74 +255,36 @@ export const ResourceCard = ({
153
255
  const size = fileAtt?.meta?.size;
154
256
  if (size) return formatSize(size);
155
257
  return null;
156
- }, [resource.resourceKind, visuals, attachments, t]);
157
-
158
- const bookmarkedIdsQuery = openpeepsApi.useCurrentProfileBookmarkedIds();
159
- const isBookmarked = bookmarkedIdsQuery.data?.includes(post.id) ?? false;
160
- const bookmarkPost = openpeepsApi.bookmarkPostAction({ id: post.id });
161
- const unbookmarkPost = openpeepsApi.unbookmarkPostAction({ id: post.id });
258
+ }, [resource, visuals, attachments, t]);
162
259
 
163
- const toggleBookmark = () => {
164
- if (!me) return;
165
- if (isBookmarked) {
166
- unbookmarkPost(undefined);
167
- } else {
168
- bookmarkPost(undefined);
169
- }
170
- };
260
+ if (!resource) return null;
171
261
 
172
262
  const downloadUrl =
173
263
  resource.resourceKind === 'file'
174
264
  ? attachments.find((att) => attachmentMediaKind(att) === 'file')?.url
175
265
  : null;
176
266
 
177
- const renderBookmarkButton = (className: string) => (
178
- <button
179
- type="button"
180
- onClick={(e) => {
181
- e.preventDefault();
182
- e.stopPropagation();
183
- toggleBookmark();
184
- }}
185
- disabled={!me}
186
- className={className}
187
- title={
188
- isBookmarked
189
- ? t('resources.actions.saved', { defaultValue: 'Saved' })
190
- : t('resources.actions.save', { defaultValue: 'Save' })
191
- }
192
- >
193
- {isBookmarked ? (
194
- <BookmarkCheck className="text-primary size-4" />
195
- ) : (
196
- <BookmarkPlus className="size-4" />
197
- )}
198
- </button>
199
- );
267
+ const renderSaveButton = (className: string) =>
268
+ staticRender ? null : (
269
+ <ResourceSaveButton postId={post.id} className={className} />
270
+ );
200
271
 
201
272
  const renderGroupLabel = () => {
202
273
  if (!group || !groupLabel || inGroup) return null;
203
- const groupHref = hrefOf({ type: 'group', handle: group.handle });
204
- return (
205
- <a
206
- href={groupHref}
207
- onClick={(e) => {
208
- e.stopPropagation();
209
- }}
210
- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs"
211
- title={t('resources.group.inGroup', {
212
- defaultValue: 'in {{groupName}}',
213
- groupName: groupLabel,
214
- })}
215
- >
216
- <span className="bg-muted rounded-full px-2 py-0.5 text-xs">
217
- {t('resources.group.inGroup', {
218
- defaultValue: 'in {{groupName}}',
219
- groupName: groupLabel,
220
- })}
274
+ const label = t('resources.group.inGroup', {
275
+ defaultValue: 'in {{groupName}}',
276
+ groupName: groupLabel,
277
+ });
278
+ if (staticRender) {
279
+ return (
280
+ <span className="text-muted-foreground inline-flex items-center gap-1 text-xs">
281
+ <span className="bg-muted rounded-full px-2 py-0.5 text-xs">
282
+ {label}
283
+ </span>
221
284
  </span>
222
- </a>
223
- );
285
+ );
286
+ }
287
+ return <ResourceGroupLabel group={group} />;
224
288
  };
225
289
 
226
290
  const renderThumbnail = () => {
@@ -264,6 +328,7 @@ export const ResourceCard = ({
264
328
  maxBlocks={2}
265
329
  maxChars={240}
266
330
  maxLines={2}
331
+ interactive={!staticRender}
267
332
  className="text-sm text-muted-foreground"
268
333
  />
269
334
  ) : null}
@@ -289,7 +354,7 @@ export const ResourceCard = ({
289
354
  </span>
290
355
  )
291
356
  ) : null}
292
- {renderBookmarkButton(
357
+ {renderSaveButton(
293
358
  'text-muted-foreground hover:text-foreground disabled:opacity-50',
294
359
  )}
295
360
  </div>
@@ -340,7 +405,7 @@ export const ResourceCard = ({
340
405
  <LinkIcon className="text-muted-foreground/50 size-8" />
341
406
  </div>
342
407
  ) : null}
343
- {renderBookmarkButton(
408
+ {renderSaveButton(
344
409
  'bg-background text-muted-foreground hover:text-foreground absolute right-2 top-2 rounded-full p-1 opacity-70 hover:opacity-100 disabled:opacity-50',
345
410
  )}
346
411
  </div>
@@ -358,6 +423,7 @@ export const ResourceCard = ({
358
423
  maxBlocks={2}
359
424
  maxChars={240}
360
425
  maxLines={2}
426
+ interactive={!staticRender}
361
427
  className="text-sm text-muted-foreground"
362
428
  />
363
429
  ) : null}
@@ -366,20 +432,18 @@ export const ResourceCard = ({
366
432
  ) : null}
367
433
  {tags.length ? (
368
434
  <div className="flex flex-wrap gap-1">
369
- {tags.map((value) => (
370
- <button
371
- key={value}
372
- type="button"
373
- className="bg-muted text-muted-foreground hover:text-foreground rounded-full px-2 py-0.5 text-xs"
374
- onClick={(e) => {
375
- e.preventDefault();
376
- e.stopPropagation();
377
- navigate({ type: 'tags', hashtag: value });
378
- }}
379
- >
380
- #{value}
381
- </button>
382
- ))}
435
+ {tags.map((value) =>
436
+ staticRender ? (
437
+ <span
438
+ key={value}
439
+ className="bg-muted text-muted-foreground rounded-full px-2 py-0.5 text-xs"
440
+ >
441
+ #{value}
442
+ </span>
443
+ ) : (
444
+ <ResourceTagChip key={value} value={value} />
445
+ ),
446
+ )}
383
447
  </div>
384
448
  ) : null}
385
449
  <p className="text-muted-foreground text-xs uppercase">