@openpeepshq/react 0.8.0 → 0.8.2

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.
@@ -2,13 +2,14 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
2
2
  import { Link } from 'react-router-dom';
3
3
  import { ChevronRight } from 'lucide-react';
4
4
  import { useT } from '../../i18n/index.js';
5
+ import { Markdown } from '../../lib/Markdown.js';
5
6
  /**
6
7
  * Row in a settings / configuration menu: title, description and a chevron.
7
8
  * Shared by the admin configuration screens and the user settings index.
8
9
  */
9
10
  export function ConfigMenuButton({ translationPrefix, action, onPress, testId, titleFallback, descriptionFallback, }) {
10
11
  const t = useT();
11
- const content = (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsx("div", { className: "font-medium", children: t(`${translationPrefix}.title`, titleFallback ? { defaultValue: titleFallback } : {}) }), _jsx("div", { className: "text-muted-foreground text-xs", children: t(`${translationPrefix}.description`, descriptionFallback ? { defaultValue: descriptionFallback } : {}) })] }), _jsx("span", { "aria-hidden": "true", children: _jsx(ChevronRight, { className: "h-4 w-4" }) })] }));
12
+ const content = (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsx("div", { className: "font-medium", children: t(`${translationPrefix}.title`, titleFallback ? { defaultValue: titleFallback } : {}) }), _jsx("div", { className: "text-muted-foreground text-xs", children: _jsx(Markdown, { inline: true, source: t(`${translationPrefix}.description`, descriptionFallback ? { defaultValue: descriptionFallback } : {}) }) })] }), _jsx("span", { "aria-hidden": "true", children: _jsx(ChevronRight, { className: "h-4 w-4" }) })] }));
12
13
  if (onPress) {
13
14
  return (_jsx("button", { "data-testid": testId, onClick: onPress, className: "hover:bg-surface flex w-full items-center justify-between px-4 py-3 text-start", children: content }));
14
15
  }
@@ -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({
@@ -1,15 +1,17 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { useMemo, useState } from 'react';
3
- import { BookmarkCheck, BookmarkPlus, Link as LinkIcon, ImageOff, } from 'lucide-react';
3
+ import { AudioLines, 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
- const visualAttachments = (attachments) => attachments.filter((att) => attachmentMediaKind(att) !== 'audio');
12
+ // Audio attachments render their generated waveform preview like any other
13
+ // visual; without one they fall back to the kind placeholder below.
14
+ const visualAttachments = (attachments) => attachments.filter((att) => attachmentMediaKind(att) !== 'audio' || !!att.previewUrl);
13
15
  const previewSrc = (att) => att.previewUrl ?? att.url;
14
16
  /** Thumbnail size shared between list and card previews. */
15
17
  const THUMB_CLASS = 'h-12 w-12 object-cover';
@@ -28,6 +30,64 @@ const primaryActionLabel = (kind, t) => {
28
30
  return null;
29
31
  }
30
32
  };
33
+ /**
34
+ * Bookmark toggle. Lives in its own component so ResourceCard itself stays
35
+ * free of app providers (OpenpeepsProvider, IdentityContext, RouterProvider)
36
+ * and can render in provider-less static contexts such as notification emails.
37
+ */
38
+ const ResourceSaveButton = ({ postId, className, }) => {
39
+ const t = useT();
40
+ const { openpeepsApi } = useOpenpeeps();
41
+ const me = useCurrentProfile();
42
+ const bookmarkedIdsQuery = openpeepsApi.useCurrentProfileBookmarkedIds();
43
+ const bookmarkPost = openpeepsApi.bookmarkPostAction({ id: postId });
44
+ const unbookmarkPost = openpeepsApi.unbookmarkPostAction({ id: postId });
45
+ const isBookmarked = bookmarkedIdsQuery.data?.includes(postId) ?? false;
46
+ const toggleBookmark = () => {
47
+ if (!me)
48
+ return;
49
+ if (isBookmarked) {
50
+ unbookmarkPost(undefined);
51
+ }
52
+ else {
53
+ bookmarkPost(undefined);
54
+ }
55
+ };
56
+ return (_jsx("button", { type: "button", onClick: (e) => {
57
+ e.preventDefault();
58
+ e.stopPropagation();
59
+ toggleBookmark();
60
+ }, disabled: !me, className: className, title: isBookmarked
61
+ ? t('resources.actions.saved', { defaultValue: 'Saved' })
62
+ : t('resources.actions.save', { defaultValue: 'Save' }), children: isBookmarked ? (_jsx(BookmarkCheck, { className: "text-primary size-4" })) : (_jsx(BookmarkPlus, { className: "size-4" })) }));
63
+ };
64
+ /**
65
+ * Clickable hashtag chip. Child component like ResourceSaveButton so the
66
+ * router hook stays out of ResourceCard's static (email) render path.
67
+ */
68
+ const ResourceTagChip = ({ value }) => {
69
+ const navigate = useNavigate();
70
+ 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) => {
71
+ e.preventDefault();
72
+ e.stopPropagation();
73
+ navigate({ type: 'tags', hashtag: value });
74
+ }, children: ["#", value] }));
75
+ };
76
+ /** Clickable group label. Child component so the router hook stays out of the static render path. */
77
+ const ResourceGroupLabel = ({ group }) => {
78
+ const t = useT();
79
+ const hrefOf = useHrefOf();
80
+ const groupLabel = groupName(group);
81
+ return (_jsx("a", { href: hrefOf({ type: 'group', handle: group.handle }), onClick: (e) => {
82
+ e.stopPropagation();
83
+ }, className: "text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs", title: t('resources.group.inGroup', {
84
+ defaultValue: 'in {{groupName}}',
85
+ groupName: groupLabel,
86
+ }), children: _jsx("span", { className: "bg-muted rounded-full px-2 py-0.5 text-xs", children: t('resources.group.inGroup', {
87
+ defaultValue: 'in {{groupName}}',
88
+ groupName: groupLabel,
89
+ }) }) }));
90
+ };
31
91
  const MediaPreview = ({ src, alt, className, isVideo, isLast, extra, }) => {
32
92
  const [errored, setErrored] = useState(false);
33
93
  if (!src) {
@@ -40,25 +100,24 @@ const MediaPreview = ({ src, alt, className, isVideo, isLast, extra, }) => {
40
100
  };
41
101
  export const ResourceCard = ({ post, layout = 'card', preview, showDescription = true, inGroup = false, }) => {
42
102
  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 ?? [];
103
+ const { enabled: staticRender } = useStaticRender();
104
+ const resource = post.data?.type === 'resource' ? post.data : undefined;
105
+ const attachments = resource?.attachments ?? [];
51
106
  const visuals = visualAttachments(attachments);
52
- const tags = normalizeResourceTags(resource.tags);
53
- const isGallery = resource.resourceKind === 'gallery' && visuals.length > 1;
107
+ const tags = normalizeResourceTags(resource?.tags);
108
+ const isGallery = resource?.resourceKind === 'gallery' && visuals.length > 1;
54
109
  const tiles = isGallery ? visuals.slice(0, 4) : visuals.slice(0, 1);
55
110
  const extra = isGallery ? Math.max(0, visuals.length - 4) : 0;
56
- const actionLabel = primaryActionLabel(resource.resourceKind, t);
111
+ const actionLabel = resource
112
+ ? primaryActionLabel(resource.resourceKind, t)
113
+ : null;
57
114
  const thumbnail = visuals[0];
58
115
  const thumbSrc = thumbnail ? previewSrc(thumbnail) : null;
59
116
  const group = post.group;
60
117
  const groupLabel = group ? groupName(group) : null;
61
118
  const metaText = useMemo(() => {
119
+ if (!resource)
120
+ return null;
62
121
  if (resource.resourceKind === 'gallery' && visuals.length > 1) {
63
122
  return t('resources.meta.imagesCount', {
64
123
  defaultValue: '{{count}} images',
@@ -72,44 +131,24 @@ export const ResourceCard = ({ post, layout = 'card', preview, showDescription =
72
131
  if (size)
73
132
  return formatSize(size);
74
133
  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
- };
134
+ }, [resource, visuals, attachments, t]);
135
+ if (!resource)
136
+ return null;
90
137
  const downloadUrl = resource.resourceKind === 'file'
91
138
  ? attachments.find((att) => attachmentMediaKind(att) === 'file')?.url
92
139
  : 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" })) }));
140
+ const renderSaveButton = (className) => staticRender ? null : (_jsx(ResourceSaveButton, { postId: post.id, className: className }));
100
141
  const renderGroupLabel = () => {
101
142
  if (!group || !groupLabel || inGroup)
102
143
  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
- }) }) }));
144
+ const label = t('resources.group.inGroup', {
145
+ defaultValue: 'in {{groupName}}',
146
+ groupName: groupLabel,
147
+ });
148
+ if (staticRender) {
149
+ 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 }) }));
150
+ }
151
+ return _jsx(ResourceGroupLabel, { group: group });
113
152
  };
114
153
  const renderThumbnail = () => {
115
154
  if (thumbSrc) {
@@ -117,14 +156,17 @@ export const ResourceCard = ({ post, layout = 'card', preview, showDescription =
117
156
  e.target.style.display = 'none';
118
157
  } }));
119
158
  }
159
+ if (resource.resourceKind === 'audio') {
160
+ return (_jsx("div", { className: "bg-muted flex h-12 w-12 items-center justify-center rounded-md", children: _jsx(AudioLines, { className: "text-muted-foreground size-5" }) }));
161
+ }
120
162
  if (resource.resourceKind === 'link' && resource.url) {
121
163
  return (_jsx("div", { className: "bg-muted flex h-12 w-12 items-center justify-center rounded-md", children: _jsx(LinkIcon, { className: "text-muted-foreground size-5" }) }));
122
164
  }
123
165
  return null;
124
166
  };
125
167
  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')] })] }));
168
+ 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' &&
169
+ 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
170
  }
129
171
  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
172
  ? 'grid h-48 grid-cols-2 grid-rows-2 gap-1'
@@ -135,11 +177,7 @@ export const ResourceCard = ({ post, layout = 'card', preview, showDescription =
135
177
  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
178
  ? 'h-full w-full object-cover'
137
179
  : 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}`, {
180
+ }) })) : resource.resourceKind === 'audio' ? (_jsx("div", { className: "bg-muted flex h-48 w-full items-center justify-center rounded-md", children: _jsx(AudioLines, { className: "text-muted-foreground/50 size-8" }) })) : 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
181
  defaultValue: resource.resourceKind,
144
182
  }) })] }));
145
183
  };
@@ -148,5 +148,6 @@ export declare const useNewGroup: () => {
148
148
  error: string | null;
149
149
  clearError: () => void;
150
150
  fieldErrors: GroupFormFieldErrors;
151
+ canCreate: boolean;
151
152
  submit: () => Promise<void>;
152
153
  };
@@ -1,9 +1,10 @@
1
1
  import { useState } from 'react';
2
2
  import { HANDLE_RESERVED_MESSAGE, isForbiddenHandle, } from '@openpeepshq/common/types';
3
- import { applySimpleGroupTemplate, defaultSimpleGroupTemplate, } from '@openpeepshq/common/lib';
3
+ import { applySimpleGroupTemplate, canCreateGroup, defaultSimpleGroupTemplate, } from '@openpeepshq/common/lib';
4
4
  import { useOpenpeeps } from '../../contexts/openpeeps/index.js';
5
5
  import { useNavigate } from '../../contexts/router/index.js';
6
6
  import { useT } from '../../i18n/context.js';
7
+ import { useCurrentProfile } from '../../components/layout/IdentityContext.js';
7
8
  import { useServerInfo } from '../../components/server-data/context.js';
8
9
  import { apiErrorMessage } from '../../lib/apiErrorMessage.js';
9
10
  import { duplicateHandleMessage, groupFormFieldErrors, hasGroupFormFieldErrors, isDuplicateHandleError, } from '../../lib/groupFormErrors.js';
@@ -16,6 +17,8 @@ const handleFromDisplayName = (displayName) => displayName
16
17
  export const useNewGroup = () => {
17
18
  const t = useT();
18
19
  const navigate = useNavigate();
20
+ const profile = useCurrentProfile();
21
+ const canCreate = !!profile && canCreateGroup(profile.roles);
19
22
  const { openpeepsApi } = useOpenpeeps();
20
23
  const createGroup = openpeepsApi.createGroupAction();
21
24
  const serverInfo = useServerInfo();
@@ -33,6 +36,8 @@ export const useNewGroup = () => {
33
36
  const [error, setError] = useState(null);
34
37
  const [fieldErrors, setFieldErrors] = useState({});
35
38
  const submit = async () => {
39
+ if (!canCreate)
40
+ return;
36
41
  setError(null);
37
42
  const nextFieldErrors = groupFormFieldErrors(groupData, t, {
38
43
  additionalForbiddenHandles,
@@ -90,6 +95,7 @@ export const useNewGroup = () => {
90
95
  error,
91
96
  clearError: () => setError(null),
92
97
  fieldErrors,
98
+ canCreate,
93
99
  submit,
94
100
  };
95
101
  };
@@ -1,6 +1,12 @@
1
1
  export interface MarkdownProps {
2
2
  source: string;
3
3
  className?: string;
4
+ /**
5
+ * Render as inline markdown (no block `<p>` wrapper) via `marked.parseInline`.
6
+ * Use for short help text inside tight layouts (e.g. config card rows) where
7
+ * block margins would disrupt alignment.
8
+ */
9
+ inline?: boolean;
4
10
  }
5
11
  /**
6
12
  * Inline Markdown renderer. Uses `marked` synchronously to render trusted
@@ -11,4 +17,4 @@ export interface MarkdownProps {
11
17
  * Svelte app behaves. If you ever feed untrusted markdown through here,
12
18
  * sanitize first.
13
19
  */
14
- export declare function Markdown({ source, className }: MarkdownProps): import("react/jsx-runtime").JSX.Element;
20
+ export declare function Markdown({ source, className, inline }: MarkdownProps): import("react/jsx-runtime").JSX.Element;
@@ -10,7 +10,9 @@ import { marked } from 'marked';
10
10
  * Svelte app behaves. If you ever feed untrusted markdown through here,
11
11
  * sanitize first.
12
12
  */
13
- export function Markdown({ source, className }) {
14
- const html = useMemo(() => marked.parse(source ?? '', { async: false }), [source]);
13
+ export function Markdown({ source, className, inline }) {
14
+ const html = useMemo(() => inline
15
+ ? marked.parseInline(source ?? '', { async: false })
16
+ : marked.parse(source ?? '', { async: false }), [source, inline]);
15
17
  return (_jsx("div", { className: className ?? 'prose prose-sm dark:prose-invert max-w-none', dangerouslySetInnerHTML: { __html: html } }));
16
18
  }
@@ -2,13 +2,15 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useMemo, useState } from 'react';
3
3
  import { useNavigate } from 'react-router-dom';
4
4
  import { Users } from 'lucide-react';
5
- import { groupName } from '@openpeepshq/common/lib';
6
- import { useT, useOpenpeeps, useSetPageHeader } from '../../index.js';
5
+ import { canCreateGroup, groupName } from '@openpeepshq/common/lib';
6
+ import { useT, useOpenpeeps, useSetPageHeader, useCurrentProfile, } from '../../index.js';
7
7
  import { Button, Dialog, DialogActions, DialogContent, DialogHeader, DialogTitle, Input, } from '@openpeepshq/react-ui';
8
8
  import { AdminGroupCard } from './components/AdminGroupCard.js';
9
9
  export function AdminGroups() {
10
10
  const t = useT();
11
11
  const navigate = useNavigate();
12
+ const profile = useCurrentProfile();
13
+ const canCreate = !!profile && canCreateGroup(profile.roles);
12
14
  const { openpeepsApi } = useOpenpeeps();
13
15
  const groupsQuery = openpeepsApi.admin.useAllGroupsList();
14
16
  const [search, setSearch] = useState('');
@@ -16,7 +18,7 @@ export function AdminGroups() {
16
18
  const createLabel = t('groups.create.title', {
17
19
  defaultValue: 'Create Group',
18
20
  });
19
- const headerActions = useMemo(() => (_jsx(Button, { title: createLabel, variant: "default", action: () => navigate('/groups/new'), children: createLabel })), [createLabel, navigate]);
21
+ const headerActions = useMemo(() => canCreate ? (_jsx(Button, { title: createLabel, variant: "default", action: () => navigate('/groups/new'), children: createLabel })) : undefined, [canCreate, createLabel, navigate]);
20
22
  useSetPageHeader(t('admin.groups.title', { defaultValue: 'Groups' }), headerActions);
21
23
  const groups = groupsQuery.data ?? [];
22
24
  const filtered = search
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useMemo, useState } from 'react';
3
3
  import { Plus, Users } from 'lucide-react';
4
- import { checkRoleCapabilities } from '@openpeepshq/common';
4
+ import { canCreateGroup } from '@openpeepshq/common';
5
5
  import { matchesQuery } from '@openpeepshq/common/lib';
6
6
  import { useT, useOpenpeeps, useSetPageHeader, useSetPlusButtonActions, } from '../../index.js';
7
7
  import { GroupCard, useCurrentProfile } from '../../components/index.js';
@@ -20,14 +20,14 @@ export function GroupsIndex() {
20
20
  const tabGroups = useMemo(() => tab === 'mine'
21
21
  ? groups.filter((group) => myGroupIds.has(group.id))
22
22
  : groups, [groups, myGroupIds, tab]);
23
- const plusButton = useMemo(() => checkRoleCapabilities(currentProfile?.roles ?? [], ['core-groups-create'])
24
- .success
23
+ const canCreate = canCreateGroup(currentProfile?.roles ?? []);
24
+ const plusButton = useMemo(() => canCreate
25
25
  ? {
26
26
  title: t('groups.new', { defaultValue: 'New Group' }),
27
27
  icon: Plus,
28
28
  action: '/groups/new',
29
29
  }
30
- : undefined, [currentProfile?.roles, t]);
30
+ : undefined, [canCreate, t]);
31
31
  useSetPlusButtonActions(plusButton);
32
32
  useSetPageHeader(t('navigation.groups', { defaultValue: 'Groups' }));
33
33
  const filtered = useMemo(() => tabGroups.filter((g) => !search || matchesQuery(g, search)), [tabGroups, search]);
@@ -1 +1 @@
1
- export declare function NewGroup(): import("react/jsx-runtime").JSX.Element;
1
+ export declare function NewGroup(): import("react/jsx-runtime").JSX.Element | null;
@@ -1,4 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Navigate } from 'react-router-dom';
2
3
  import { useT, useSetPageHeader } from '../../index.js';
3
4
  import { GroupForm, ProfilesInput, useCurrentProfile } from '../../components/index.js';
4
5
  import { useNewGroup } from '../../hooks/index.js';
@@ -6,8 +7,13 @@ import { Button, Label, Toast } from '@openpeepshq/react-ui';
6
7
  export function NewGroup() {
7
8
  const t = useT();
8
9
  const me = useCurrentProfile();
9
- const { groupData, setGroupData, members, setMembers, submitting, error, clearError, fieldErrors, submit, } = useNewGroup();
10
- useSetPageHeader(t('groups.new.title', { defaultValue: 'Create group' }), undefined, 'groups-create-page-title');
10
+ const { groupData, setGroupData, members, setMembers, submitting, error, clearError, fieldErrors, canCreate, submit, } = useNewGroup();
11
+ useSetPageHeader(canCreate
12
+ ? t('groups.new.title', { defaultValue: 'Create group' })
13
+ : undefined, undefined, canCreate ? 'groups-create-page-title' : undefined);
14
+ if (!canCreate) {
15
+ return me ? _jsx(Navigate, { to: "/groups", replace: true }) : null;
16
+ }
11
17
  return (_jsxs("div", { className: "space-y-4 p-4 pb-12", children: [_jsx(GroupForm, { groupData: groupData, fieldErrors: fieldErrors, onChange: setGroupData }), _jsxs("div", { className: "space-y-2 px-1", children: [_jsx(Label, { htmlFor: "group-members", children: t('groups.form.members', { defaultValue: 'Members' }) }), _jsx(ProfilesInput, { value: members, onChange: setMembers, banlist: me ? [me] : [], placeholder: t('groups.form.membersPlaceholder', {
12
18
  defaultValue: 'Add members to this group',
13
19
  }) })] }), error && (_jsx(Toast, { variant: "error", testId: "groups-duplicate-handle-error", onDismiss: clearError, children: error })), _jsx(Button, { title: "Create group", variant: "default", action: submit, disabled: submitting, "data-testid": "groups-create-submit", children: submitting
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/react",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -52,8 +52,8 @@
52
52
  "simple-icons": "^16.31.0",
53
53
  "uuidv7": "^1.0.2",
54
54
  "@openpeepshq/client": "^0.2.1",
55
- "@openpeepshq/common": "^0.4.0",
56
55
  "@openpeepshq/greenscreen": "^0.2.1",
56
+ "@openpeepshq/common": "^0.4.0",
57
57
  "@openpeepshq/react-ui": "^0.4.1"
58
58
  },
59
59
  "peerDependencies": {