@nuasite/cms-mdx-editor 0.57.0 → 0.58.0

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,8 +2,12 @@
2
2
  * Rich-text toolbar shared by the body editor and the nested slot editor. Reflects
3
3
  * and toggles inline/block formatting on the bound Milkdown editor; optionally
4
4
  * surfaces an image button (opens the media library) and an "insert component"
5
- * button (body editor only). The nested slot editor passes neither, matching the
5
+ * button (body editor only). The nested slot editor offers neither, matching the
6
6
  * original mini-editor's formatting-only toolbar.
7
+ *
8
+ * "Edit image" appears in both whenever an image is selected: alt text and caption
9
+ * of an image already in the text, plus "Replace image" when a media source is
10
+ * given. Without one, the alt and caption are still editable.
7
11
  */
8
12
  import { type Editor, editorViewCtx } from '@milkdown/core'
9
13
  import {
@@ -23,8 +27,18 @@ import { useEffect, useState } from 'react'
23
27
  import { ImagePopover } from './image-popover'
24
28
  import { LinkPopover } from './link-popover'
25
29
  import { MediaLibrary } from './media-library'
30
+ import { mediaPreviewSrc } from './media-preview'
26
31
  import type { MediaContext, MediaSource } from './media-source'
27
- import { type ActiveFormats, defaultActiveFormats, isInListType, removeLinkMark, setupFormatTracking, toggleHeading } from './milkdown-utils'
32
+ import {
33
+ type ActiveFormats,
34
+ defaultActiveFormats,
35
+ isInListType,
36
+ removeLinkMark,
37
+ type SelectedImage,
38
+ setupFormatTracking,
39
+ toggleHeading,
40
+ updateImage,
41
+ } from './milkdown-utils'
28
42
  import { setListStyleCommand } from './styled-list-plugin'
29
43
  import { insertYoutubeCommand } from './youtube-plugin'
30
44
  import { YoutubePopover } from './youtube-popover'
@@ -85,9 +99,20 @@ export interface FormatToolbarProps {
85
99
  mediaContext?: MediaContext
86
100
  /** Upload field the image is filed under (e.g. 'body'). */
87
101
  field?: string
102
+ /**
103
+ * Offer "Insert image" when `media` is given. The slot editor turns it off: it passes `media`
104
+ * only so an existing image can be previewed and replaced. Defaults to `true`.
105
+ */
106
+ allowImageInsert?: boolean
88
107
  onInsertComponent?: () => void
89
108
  }
90
109
 
110
+ /** An existing image being edited, and the file it will point at once saved. */
111
+ interface ImageEdit {
112
+ image: SelectedImage
113
+ src: string
114
+ }
115
+
91
116
  // The toolbar root is the header of the body editor's flex column (`mdx-body-editor`):
92
117
  // it must keep its height while the prose pane below it scrolls, otherwise the flex
93
118
  // line would squash the bar (the pane has `flex-basis: 0`, so it absorbs no shrink).
@@ -155,12 +180,14 @@ function Btn({ active, title, onClick, style, children }: {
155
180
  )
156
181
  }
157
182
 
158
- export function FormatToolbar({ editor, listStyles, media, mediaContext, field, onInsertComponent }: FormatToolbarProps) {
183
+ export function FormatToolbar({ editor, listStyles, media, mediaContext, field, allowImageInsert = true, onInsertComponent }: FormatToolbarProps) {
159
184
  const formats = useFormatTracking(editor)
160
185
  const [linkOpen, setLinkOpen] = useState(false)
161
- const [mediaOpen, setMediaOpen] = useState(false)
186
+ /** What a pick in the media library does: insert a new image, or replace the one being edited. */
187
+ const [mediaPurpose, setMediaPurpose] = useState<'insert' | 'replace' | null>(null)
162
188
  const [youtubeOpen, setYoutubeOpen] = useState(false)
163
189
  const [pendingImage, setPendingImage] = useState<{ url: string; alt: string } | null>(null)
190
+ const [imageEdit, setImageEdit] = useState<ImageEdit | null>(null)
164
191
  const disabled = editor === null
165
192
  const hasListStyles = (listStyles?.length ?? 0) > 0
166
193
  const inList = formats.bulletList || formats.orderedList
@@ -174,6 +201,31 @@ export function FormatToolbar({ editor, listStyles, media, mediaContext, field,
174
201
  editor.action(callCommand(formats.link ? updateLinkCommand.key : toggleLinkCommand.key, { href: url }))
175
202
  }
176
203
 
204
+ // Moving the selection off the image (or onto another one) abandons the edit, so what was typed
205
+ // can never land on an image other than the one it was opened for.
206
+ const selectedImage = formats.image
207
+ const editedImage = imageEdit?.image ?? null
208
+ useEffect(() => {
209
+ if (editedImage === null) return
210
+ if (selectedImage === null || selectedImage.pos !== editedImage.pos || selectedImage.src !== editedImage.src) setImageEdit(null)
211
+ }, [editedImage, selectedImage])
212
+
213
+ // Focus goes back to the editor either way: the slot editor reports its content on blur, and
214
+ // the popover's input took the focus away before the image changed.
215
+ const saveImage = (alt: string, caption: string) => {
216
+ const edit = imageEdit
217
+ setImageEdit(null)
218
+ if (!editor || !edit) return
219
+ const view = editor.ctx.get(editorViewCtx)
220
+ updateImage(view, edit.image, { src: edit.src, alt, title: caption })
221
+ view.focus()
222
+ }
223
+
224
+ const cancelImageEdit = () => {
225
+ setImageEdit(null)
226
+ editor?.ctx.get(editorViewCtx).focus()
227
+ }
228
+
177
229
  const removeLink = () => {
178
230
  setLinkOpen(false)
179
231
  if (!editor) return
@@ -236,7 +288,18 @@ export function FormatToolbar({ editor, listStyles, media, mediaContext, field,
236
288
  <Btn active={youtubeOpen} title="Insert YouTube" onClick={() => !disabled && setYoutubeOpen(v => !v)}>YouTube</Btn>
237
289
  <span style={sep} />
238
290
  <Btn active={formats.link || linkOpen} title="Link" onClick={() => !disabled && setLinkOpen(v => !v)}>🔗 Link</Btn>
239
- {media ? <Btn title="Insert image" onClick={() => !disabled && setMediaOpen(true)}>🖼 Image</Btn> : null}
291
+ {media && allowImageInsert ? <Btn title="Insert image" onClick={() => !disabled && setMediaPurpose('insert')}>🖼 Image</Btn> : null}
292
+ {selectedImage
293
+ ? (
294
+ <Btn
295
+ active={imageEdit !== null}
296
+ title="Edit the alt text, caption or file of the selected image"
297
+ onClick={() => setImageEdit({ image: selectedImage, src: selectedImage.src })}
298
+ >
299
+ Edit image
300
+ </Btn>
301
+ )
302
+ : null}
240
303
  {onInsertComponent
241
304
  ? (
242
305
  <>
@@ -277,11 +340,31 @@ export function FormatToolbar({ editor, listStyles, media, mediaContext, field,
277
340
  )
278
341
  : null}
279
342
 
343
+ {imageEdit
344
+ ? (
345
+ <div style={{ padding: '0 6px' }}>
346
+ <ImagePopover
347
+ key={imageEdit.image.pos}
348
+ mode="edit"
349
+ initialAlt={imageEdit.image.alt}
350
+ initialCaption={imageEdit.image.title}
351
+ previewSrc={mediaPreviewSrc(media, imageEdit.src, mediaContext)}
352
+ onReplace={media ? () => setMediaPurpose('replace') : undefined}
353
+ onApply={saveImage}
354
+ onClose={cancelImageEdit}
355
+ />
356
+ </div>
357
+ )
358
+ : null}
359
+
280
360
  {pendingImage
281
361
  ? (
282
362
  <div style={{ padding: '0 6px' }}>
283
363
  <ImagePopover
364
+ mode="insert"
284
365
  initialAlt={pendingImage.alt}
366
+ initialCaption=""
367
+ previewSrc={mediaPreviewSrc(media, pendingImage.url, mediaContext)}
285
368
  onApply={(alt, caption) => {
286
369
  const { url } = pendingImage
287
370
  setPendingImage(null)
@@ -293,7 +376,7 @@ export function FormatToolbar({ editor, listStyles, media, mediaContext, field,
293
376
  )
294
377
  : null}
295
378
 
296
- {mediaOpen && media
379
+ {mediaPurpose && media
297
380
  ? (
298
381
  <MediaLibrary
299
382
  media={media}
@@ -301,10 +384,13 @@ export function FormatToolbar({ editor, listStyles, media, mediaContext, field,
301
384
  field={field}
302
385
  accept="image/*"
303
386
  onSelect={(url, alt) => {
304
- setMediaOpen(false)
305
- if (editor) setPendingImage({ url, alt: alt ?? '' })
387
+ setMediaPurpose(null)
388
+ // A replacement keeps the alt and caption already in the popover: they describe this
389
+ // usage, and the author swapping the file has usually not changed what it shows.
390
+ if (mediaPurpose === 'replace') setImageEdit(edit => (edit ? { ...edit, src: url } : edit))
391
+ else if (editor) setPendingImage({ url, alt: alt ?? '' })
306
392
  }}
307
- onClose={() => setMediaOpen(false)}
393
+ onClose={() => setMediaPurpose(null)}
308
394
  />
309
395
  )
310
396
  : null}
@@ -1,23 +1,45 @@
1
1
  /**
2
- * Inline popover shown after an image is picked from the media library: confirm the
3
- * alt text (prefilled from the library) and optionally add a caption/source. Apply
4
- * inserts the image; Cancel aborts insertion entirely. Mirrors the LinkPopover style.
2
+ * Inline popover for an image's alt text and caption, next to a preview of the image they describe.
3
+ * The caption is the image's `title`.
4
+ *
5
+ * - `insert` — shown after an image is picked from the media library: confirm the alt text
6
+ * (prefilled from the library) and optionally add a caption/source. Apply inserts the image;
7
+ * Cancel aborts insertion entirely.
8
+ * - `edit` — shown for an image already in the text: change its alt text and caption, and swap the
9
+ * file itself when the host offers `onReplace`. What is typed survives a swap.
10
+ *
11
+ * Mirrors the LinkPopover style.
5
12
  */
6
13
  import { useState } from 'react'
7
14
  import { popoverBtn, popoverInput, popoverWrap } from './link-popover'
8
15
 
9
16
  export interface ImagePopoverProps {
17
+ mode: 'insert' | 'edit'
10
18
  initialAlt: string
19
+ initialCaption: string
20
+ /** Loadable URL of the image (see `mediaPreviewSrc`); `''` when nothing can load it. */
21
+ previewSrc: string
22
+ /** Pick another file for this image. Only in `edit` mode; absent → no media source to pick from. */
23
+ onReplace?: () => void
11
24
  onApply: (alt: string, caption: string) => void
12
25
  onClose: () => void
13
26
  }
14
27
 
15
28
  const wrap: React.CSSProperties = { ...popoverWrap, flexWrap: 'wrap' }
16
29
  const label: React.CSSProperties = { fontSize: 11, color: '#71717a', whiteSpace: 'nowrap' }
30
+ const preview: React.CSSProperties = {
31
+ width: 48,
32
+ height: 48,
33
+ objectFit: 'contain',
34
+ border: '1px solid #e4e4e7',
35
+ borderRadius: 4,
36
+ background: '#fafafa',
37
+ flexShrink: 0,
38
+ }
17
39
 
18
- export function ImagePopover({ initialAlt, onApply, onClose }: ImagePopoverProps) {
40
+ export function ImagePopover({ mode, initialAlt, initialCaption, previewSrc, onReplace, onApply, onClose }: ImagePopoverProps) {
19
41
  const [alt, setAlt] = useState(initialAlt)
20
- const [caption, setCaption] = useState('')
42
+ const [caption, setCaption] = useState(initialCaption)
21
43
 
22
44
  const apply = () => onApply(alt.trim(), caption.trim())
23
45
 
@@ -31,6 +53,10 @@ export function ImagePopover({ initialAlt, onApply, onClose }: ImagePopoverProps
31
53
 
32
54
  return (
33
55
  <div style={wrap} data-mdx-action="image" onMouseDown={e => e.stopPropagation()}>
56
+ {previewSrc !== '' ? <img src={previewSrc} alt="" style={preview} data-mdx-image-preview="" /> : null}
57
+ {onReplace
58
+ ? <button type="button" style={popoverBtn} onMouseDown={e => e.preventDefault()} onClick={onReplace}>Replace image</button>
59
+ : null}
34
60
  <span style={label}>Alt</span>
35
61
  <input
36
62
  style={popoverInput}
@@ -54,7 +80,7 @@ export function ImagePopover({ initialAlt, onApply, onClose }: ImagePopoverProps
54
80
  onMouseDown={e => e.preventDefault()}
55
81
  onClick={apply}
56
82
  >
57
- Insert
83
+ {mode === 'insert' ? 'Insert' : 'Save'}
58
84
  </button>
59
85
  <button type="button" style={popoverBtn} onMouseDown={e => e.preventDefault()} onClick={onClose}>Cancel</button>
60
86
  </div>
package/src/index.ts CHANGED
@@ -24,4 +24,4 @@ export { type InsertMdxComponentPayload, MDX_EXPR_PREFIX } from './mdx-plugin'
24
24
  export { MediaLibrary, type MediaLibraryProps } from './media-library'
25
25
  export { mediaPreviewSrc } from './media-preview'
26
26
  export { isMediaUnavailableError, type MediaContext, type MediaSource, type MediaUploadContext } from './media-source'
27
- export { SlotEditor } from './slot-editor'
27
+ export { SlotEditor, type SlotEditorProps } from './slot-editor'
@@ -215,7 +215,7 @@ export function MdxBlockCard({
215
215
  <div data-mdx-action="children">
216
216
  <div style={rowLabel}>Content</div>
217
217
  {onSlotContentChange
218
- ? <SlotEditor value={slotContent} onChange={onSlotContentChange} />
218
+ ? <SlotEditor value={slotContent} onChange={onSlotContentChange} media={media} mediaContext={mediaContext} />
219
219
  : <div style={{ ...roInput, whiteSpace: 'pre-wrap', minHeight: 40 }}>{slotContent}</div>}
220
220
  </div>
221
221
  )
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The media library's "default alt text" panel for one item. It takes the grid's place inside the
3
+ * modal, so the preview and filename leave no doubt which file the text belongs to, and nothing on
4
+ * screen can insert the image by accident.
5
+ *
6
+ * The saved text only prefills the alt of later insertions; content that already uses the item
7
+ * keeps its own alt.
8
+ */
9
+ import type { MediaItem } from '@nuasite/cms-types'
10
+ import { useState } from 'react'
11
+
12
+ export interface MediaAnnotationEditorProps {
13
+ item: MediaItem
14
+ save: (annotation: string) => Promise<{ success: boolean; error?: string }>
15
+ onSaved: (annotation: string) => void
16
+ onCancel: () => void
17
+ }
18
+
19
+ const panel: React.CSSProperties = { display: 'flex', gap: 16, padding: 16, overflowY: 'auto' }
20
+ const preview: React.CSSProperties = {
21
+ width: 220,
22
+ height: 220,
23
+ flexShrink: 0,
24
+ objectFit: 'contain',
25
+ border: '1px solid #e4e4e7',
26
+ borderRadius: 8,
27
+ background: '#fafafa',
28
+ }
29
+ const fields: React.CSSProperties = { display: 'flex', flexDirection: 'column', gap: 8, flex: 1, minWidth: 0 }
30
+ const input: React.CSSProperties = {
31
+ border: '1px solid #d4d4d8',
32
+ borderRadius: 6,
33
+ padding: '6px 10px',
34
+ font: 'inherit',
35
+ outline: 'none',
36
+ }
37
+ const btn: React.CSSProperties = {
38
+ border: '1px solid #d4d4d8',
39
+ background: '#fff',
40
+ borderRadius: 6,
41
+ padding: '6px 12px',
42
+ font: 'inherit',
43
+ cursor: 'pointer',
44
+ color: '#3f3f46',
45
+ }
46
+ const primaryBtn: React.CSSProperties = { ...btn, background: '#2563eb', border: '1px solid #2563eb', color: '#fff' }
47
+
48
+ export function MediaAnnotationEditor({ item, save, onSaved, onCancel }: MediaAnnotationEditorProps) {
49
+ const [annotation, setAnnotation] = useState(item.annotation ?? '')
50
+ const [saving, setSaving] = useState(false)
51
+ const [errorMsg, setErrorMsg] = useState<string | null>(null)
52
+
53
+ const submit = async () => {
54
+ if (saving) return
55
+ const value = annotation.trim()
56
+ setSaving(true)
57
+ setErrorMsg(null)
58
+ try {
59
+ const result = await save(value)
60
+ if (result.success) {
61
+ onSaved(value)
62
+ return
63
+ }
64
+ setErrorMsg(result.error ?? 'Failed to save the alt text')
65
+ } catch (err: unknown) {
66
+ setErrorMsg(err instanceof Error ? err.message : 'Failed to save the alt text')
67
+ }
68
+ setSaving(false)
69
+ }
70
+
71
+ return (
72
+ <div style={panel} data-cms-media-annotation={item.id}>
73
+ <img src={item.thumbnailUrl ?? item.url} alt="" style={preview} />
74
+ <div style={fields}>
75
+ <strong style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={item.filename}>{item.filename}</strong>
76
+ <label style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12, color: '#52525b' }}>
77
+ Default alt text
78
+ <input
79
+ style={input}
80
+ autoFocus
81
+ placeholder="Describe the image for screen readers"
82
+ value={annotation}
83
+ disabled={saving}
84
+ onChange={e => setAnnotation(e.currentTarget.value)}
85
+ onKeyDown={e => {
86
+ if (e.key === 'Enter') {
87
+ e.preventDefault()
88
+ void submit()
89
+ }
90
+ if (e.key === 'Escape') onCancel()
91
+ }}
92
+ />
93
+ </label>
94
+ <div style={{ fontSize: 12, color: '#71717a' }}>
95
+ Prefilled as the alt text when this image is inserted. Images already in the content keep their own.
96
+ </div>
97
+ {errorMsg ? <div style={{ fontSize: 12, color: '#dc2626' }}>{errorMsg}</div> : null}
98
+ <div style={{ display: 'flex', gap: 8 }}>
99
+ <button type="button" style={primaryBtn} disabled={saving} onClick={() => void submit()}>{saving ? 'Saving…' : 'Save'}</button>
100
+ <button type="button" style={btn} disabled={saving} onClick={onCancel}>Cancel</button>
101
+ </div>
102
+ </div>
103
+ </div>
104
+ )
105
+ }
@@ -6,9 +6,11 @@
6
6
  * inline styles so it renders in any host.
7
7
  *
8
8
  * Opened from the body/slot toolbar (insert an image into prose) and from `image`
9
- * props in the block card. Degrades gracefully when the sidecar has no media
10
- * adapter (`501`): the gallery shows an "unavailable" hint and the manual-URL path
11
- * stays usable upstream.
9
+ * props in the block card. An item whose source stores annotations gets a separate
10
+ * "Alt" action for its default alt text (`MediaAnnotationEditor`), apart from the
11
+ * tile itself, so editing it never inserts the image. Degrades gracefully when the
12
+ * sidecar has no media adapter (`501`): the gallery shows an "unavailable" hint and
13
+ * the manual-URL path stays usable upstream.
12
14
  *
13
15
  * The listing is paged: each folder is read one `PAGE_SIZE` page at a time and the
14
16
  * rest is pulled in by an explicit "Load more".
@@ -22,6 +24,7 @@
22
24
  */
23
25
  import { filterMediaItems, type MediaFolderItem, type MediaItem, type MediaListResult, type MediaTypeFilter } from '@nuasite/cms-types'
24
26
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
27
+ import { MediaAnnotationEditor } from './media-annotation-editor'
25
28
  import { isMediaUnavailableError, type MediaContext, type MediaSource } from './media-source'
26
29
 
27
30
  /**
@@ -191,8 +194,10 @@ const grid: React.CSSProperties = {
191
194
  padding: 16,
192
195
  overflowY: 'auto',
193
196
  }
197
+ const tileCell: React.CSSProperties = { position: 'relative' }
194
198
  const tile: React.CSSProperties = {
195
199
  position: 'relative',
200
+ width: '100%',
196
201
  aspectRatio: '1 / 1',
197
202
  border: '1px solid #e4e4e7',
198
203
  borderRadius: 8,
@@ -206,6 +211,19 @@ const tile: React.CSSProperties = {
206
211
  justifyContent: 'center',
207
212
  gap: 6,
208
213
  }
214
+ const altAction: React.CSSProperties = {
215
+ position: 'absolute',
216
+ top: 6,
217
+ right: 6,
218
+ border: '1px solid #d4d4d8',
219
+ background: 'rgba(255,255,255,0.92)',
220
+ borderRadius: 4,
221
+ padding: '1px 6px',
222
+ font: 'inherit',
223
+ fontSize: 11,
224
+ color: '#3f3f46',
225
+ cursor: 'pointer',
226
+ }
209
227
  const emptyPanel: React.CSSProperties = { padding: 32, textAlign: 'center', color: '#a1a1aa' }
210
228
  const pagerBar: React.CSSProperties = {
211
229
  display: 'flex',
@@ -264,6 +282,7 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
264
282
  const [errorMsg, setErrorMsg] = useState<string | null>(null)
265
283
  const [showNewFolder, setShowNewFolder] = useState(false)
266
284
  const [newFolderName, setNewFolderName] = useState('')
285
+ const [annotating, setAnnotating] = useState<MediaItem | null>(null)
267
286
  const fileInputRef = useRef<HTMLInputElement>(null)
268
287
  const listingRef = useRef<Listing>(createListing('', 'all'))
269
288
  const mountedRef = useRef(true)
@@ -386,6 +405,7 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
386
405
  url: result.url,
387
406
  filename: result.filename ?? file.name,
388
407
  annotation: result.annotation,
408
+ annotationEditable: result.annotationEditable,
389
409
  contentType: file.type || 'application/octet-stream',
390
410
  folder: currentFolder || undefined,
391
411
  }
@@ -423,6 +443,13 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
423
443
  setShowNewFolder(false)
424
444
  }
425
445
 
446
+ const updateAnnotation = media.updateMediaAnnotation?.bind(media)
447
+
448
+ const annotationSaved = (id: string, annotation: string) => {
449
+ setItems(prev => prev.map(item => (item.id === id ? { ...item, annotation } : item)))
450
+ setAnnotating(null)
451
+ }
452
+
426
453
  // Applied even when the server already did: it is the same shared predicate, so it is a no-op
427
454
  // on a filtered page, and depending on `serverFiltered` here would only add a way to be wrong.
428
455
  const filteredItems = useMemo(() => {
@@ -543,7 +570,16 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
543
570
  {errorMsg ? <div style={{ fontSize: 12, color: '#dc2626' }}>{errorMsg}</div> : null}
544
571
  </div>
545
572
 
546
- {loading
573
+ {annotating && updateAnnotation
574
+ ? (
575
+ <MediaAnnotationEditor
576
+ item={annotating}
577
+ save={annotation => updateAnnotation(annotating.id, annotation)}
578
+ onSaved={annotation => annotationSaved(annotating.id, annotation)}
579
+ onCancel={() => setAnnotating(null)}
580
+ />
581
+ )
582
+ : loading
547
583
  ? <div style={emptyPanel}>Loading…</div>
548
584
  : visibleFolders.length === 0 && filteredItems.length === 0
549
585
  ? (
@@ -576,32 +612,47 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
576
612
  </button>
577
613
  ))}
578
614
  {filteredItems.map(item => (
579
- <button
580
- key={item.id}
581
- type="button"
582
- style={tile}
583
- title={item.filename}
584
- data-cms-media-item={item.id}
585
- onClick={() => onSelect(item.url, item.annotation || item.filename || 'Image')}
586
- >
587
- {item.contentType.startsWith('image/')
615
+ <div key={item.id} style={tileCell}>
616
+ <button
617
+ type="button"
618
+ style={tile}
619
+ title={item.filename}
620
+ data-cms-media-item={item.id}
621
+ // `??`, not `||`: an annotation of '' is a deliberately empty alt.
622
+ onClick={() => onSelect(item.url, item.annotation ?? (item.filename || 'Image'))}
623
+ >
624
+ {item.contentType.startsWith('image/')
625
+ ? (
626
+ <img
627
+ src={item.thumbnailUrl ?? item.url}
628
+ alt={item.annotation || item.filename}
629
+ // `contain`, not `cover`: this grid exists to tell one asset from another, and a
630
+ // square crop of a wide photo throws away the part that identifies it.
631
+ style={{ width: '100%', height: '100%', objectFit: 'contain' }}
632
+ />
633
+ )
634
+ : <span style={{ fontSize: 30 }}>{item.contentType === 'application/pdf' ? '📄' : '📎'}</span>}
635
+ <span style={tileCaption}>{item.filename}</span>
636
+ </button>
637
+ {item.annotationEditable && updateAnnotation && item.contentType.startsWith('image/')
588
638
  ? (
589
- <img
590
- src={item.thumbnailUrl ?? item.url}
591
- alt={item.annotation || item.filename}
592
- // `contain`, not `cover`: this grid exists to tell one asset from another, and a
593
- // square crop of a wide photo throws away the part that identifies it.
594
- style={{ width: '100%', height: '100%', objectFit: 'contain' }}
595
- />
639
+ <button
640
+ type="button"
641
+ style={altAction}
642
+ title="Edit the default alt text"
643
+ data-cms-media-alt={item.id}
644
+ onClick={() => setAnnotating(item)}
645
+ >
646
+ Alt
647
+ </button>
596
648
  )
597
- : <span style={{ fontSize: 30 }}>{item.contentType === 'application/pdf' ? '📄' : '📎'}</span>}
598
- <span style={tileCaption}>{item.filename}</span>
599
- </button>
649
+ : null}
650
+ </div>
600
651
  ))}
601
652
  </div>
602
653
  )}
603
654
 
604
- {!loading && hasMore
655
+ {!loading && !annotating && hasMore
605
656
  ? (
606
657
  <div style={pagerBar}>
607
658
  {loadingMore
@@ -28,6 +28,11 @@ export interface MediaSource {
28
28
  listMedia(options?: { folder?: string; cursor?: string; limit?: number; type?: MediaTypeFilter }): Promise<MediaListResult>
29
29
  uploadMedia(file: File, context?: MediaUploadContext): Promise<MediaUploadResult>
30
30
  createFolder?(folder: string): Promise<{ success: boolean; error?: string }>
31
+ /**
32
+ * Replace an item's default alt text. Optional like `createFolder`; the gallery offers the
33
+ * edit only when this exists *and* the item says `annotationEditable`.
34
+ */
35
+ updateMediaAnnotation?(id: string, annotation: string): Promise<{ success: boolean; error?: string }>
31
36
  /**
32
37
  * Loadable URL for a repository file at its runtime path (`/uploads/hero.webp`). Optional: a
33
38
  * host serving the project from the editor's own origin does not need one — see
@@ -7,6 +7,16 @@
7
7
  import { type Editor, editorViewCtx } from '@milkdown/core'
8
8
  import type { EditorView } from '@milkdown/prose/view'
9
9
 
10
+ /** The image node the selection covers exactly — a click on an inline image selects the node itself. */
11
+ export interface SelectedImage {
12
+ pos: number
13
+ src: string
14
+ alt: string
15
+ title: string
16
+ }
17
+
18
+ export type ImageAttrs = Omit<SelectedImage, 'pos'>
19
+
10
20
  export interface ActiveFormats {
11
21
  bold: boolean
12
22
  italic: boolean
@@ -18,6 +28,7 @@ export interface ActiveFormats {
18
28
  listStyle: string | null
19
29
  blockquote: boolean
20
30
  heading: number | null
31
+ image: SelectedImage | null
21
32
  }
22
33
 
23
34
  export const defaultActiveFormats: ActiveFormats = {
@@ -31,6 +42,7 @@ export const defaultActiveFormats: ActiveFormats = {
31
42
  listStyle: null,
32
43
  blockquote: false,
33
44
  heading: null,
45
+ image: null,
34
46
  }
35
47
 
36
48
  /** Detect active inline/block formats at the current selection. */
@@ -90,7 +102,41 @@ export function getActiveFormats(view: EditorView): ActiveFormats {
90
102
  heading = typeof level === 'number' ? level : null
91
103
  }
92
104
 
93
- return { bold, italic, strikethrough, link, linkHref, bulletList, orderedList, listStyle, blockquote, heading }
105
+ return { bold, italic, strikethrough, link, linkHref, bulletList, orderedList, listStyle, blockquote, heading, image: getSelectedImage(view) }
106
+ }
107
+
108
+ function getSelectedImage(view: EditorView): SelectedImage | null {
109
+ const { doc, selection } = view.state
110
+ const node = doc.nodeAt(selection.from)
111
+ if (node === null || node.type.name !== 'image' || selection.to - selection.from !== node.nodeSize) return null
112
+ return { pos: selection.from, src: stringAttr(node.attrs.src), alt: stringAttr(node.attrs.alt), title: stringAttr(node.attrs.title) }
113
+ }
114
+
115
+ function stringAttr(value: unknown): string {
116
+ return typeof value === 'string' ? value : ''
117
+ }
118
+
119
+ /**
120
+ * Rewrite the attributes of the image at `image.pos`, leaving everything around it as it is.
121
+ * Does nothing when that position no longer holds the same image — the document changed while the
122
+ * image was being edited, and writing to whatever sits there now would hit the wrong one.
123
+ *
124
+ * Attribute steps rather than a node replacement, so the node selection survives the edit.
125
+ */
126
+ export function updateImage(view: EditorView, image: SelectedImage, attrs: ImageAttrs): boolean {
127
+ const node = view.state.doc.nodeAt(image.pos)
128
+ if (node === null || node.type.name !== 'image' || stringAttr(node.attrs.src) !== image.src) return false
129
+ const tr = view.state.tr
130
+ .setNodeAttribute(image.pos, 'src', attrs.src)
131
+ .setNodeAttribute(image.pos, 'alt', attrs.alt)
132
+ .setNodeAttribute(image.pos, 'title', attrs.title)
133
+ view.dispatch(tr)
134
+ return true
135
+ }
136
+
137
+ function imagesEqual(a: SelectedImage | null, b: SelectedImage | null): boolean {
138
+ if (a === null || b === null) return a === b
139
+ return a.pos === b.pos && a.src === b.src && a.alt === b.alt && a.title === b.title
94
140
  }
95
141
 
96
142
  /** Whether the current selection is inside a list of the given node-type name. */
@@ -152,6 +198,7 @@ function formatsEqual(a: ActiveFormats, b: ActiveFormats): boolean {
152
198
  && a.listStyle === b.listStyle
153
199
  && a.blockquote === b.blockquote
154
200
  && a.heading === b.heading
201
+ && imagesEqual(a.image, b.image)
155
202
  }
156
203
 
157
204
  /**