@nuasite/cms-mdx-editor 0.56.4 → 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
+ }