@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.
- package/dist/types/format-toolbar.d.ts +11 -2
- package/dist/types/format-toolbar.d.ts.map +1 -1
- package/dist/types/image-popover.d.ts +7 -1
- package/dist/types/image-popover.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/media-annotation-editor.d.ts +20 -0
- package/dist/types/media-annotation-editor.d.ts.map +1 -0
- package/dist/types/media-library.d.ts.map +1 -1
- package/dist/types/media-source.d.ts +15 -1
- package/dist/types/media-source.d.ts.map +1 -1
- package/dist/types/milkdown-utils.d.ts +17 -0
- package/dist/types/milkdown-utils.d.ts.map +1 -1
- package/dist/types/slot-editor.d.ts +6 -2
- package/dist/types/slot-editor.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/src/format-toolbar.tsx +95 -9
- package/src/image-popover.tsx +32 -6
- package/src/index.ts +1 -1
- package/src/mdx-block-card.tsx +1 -1
- package/src/media-annotation-editor.tsx +105 -0
- package/src/media-library.tsx +146 -56
- package/src/media-source.ts +12 -2
- package/src/milkdown-utils.ts +48 -1
- package/src/slot-editor.tsx +13 -2
package/src/media-library.tsx
CHANGED
|
@@ -6,21 +6,27 @@
|
|
|
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.
|
|
10
|
-
*
|
|
11
|
-
*
|
|
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
|
-
* rest is pulled in by an explicit "Load more".
|
|
15
|
-
*
|
|
16
|
-
*
|
|
16
|
+
* rest is pulled in by an explicit "Load more".
|
|
17
|
+
*
|
|
18
|
+
* The type tabs are a server filter (`?type=`), so switching one starts a fresh
|
|
19
|
+
* listing rather than narrowing the loaded pages — its first page is already the
|
|
20
|
+
* answer. Search is not, and an endpoint that does not know `?type=` says so by
|
|
21
|
+
* omitting `appliedType`; either case falls back to filtering here, which means
|
|
22
|
+
* draining the remaining pages first so a match on page 3 is not reported missing.
|
|
23
|
+
* See `Listing` and the drain effect for how that stays bounded and cancellable.
|
|
17
24
|
*/
|
|
18
|
-
import type
|
|
25
|
+
import { filterMediaItems, type MediaFolderItem, type MediaItem, type MediaListResult, type MediaTypeFilter } from '@nuasite/cms-types'
|
|
19
26
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
27
|
+
import { MediaAnnotationEditor } from './media-annotation-editor'
|
|
20
28
|
import { isMediaUnavailableError, type MediaContext, type MediaSource } from './media-source'
|
|
21
29
|
|
|
22
|
-
const VECTOR_TYPES = new Set(['image/svg+xml', 'image/x-icon'])
|
|
23
|
-
|
|
24
30
|
/**
|
|
25
31
|
* Items per listing request. Above the server's default of 50 so most folders are
|
|
26
32
|
* one page, low enough that the first paint does not fetch hundreds of thumbnails.
|
|
@@ -50,6 +56,12 @@ const MAX_PAGES = 200
|
|
|
50
56
|
*/
|
|
51
57
|
interface Listing {
|
|
52
58
|
folder: string
|
|
59
|
+
/**
|
|
60
|
+
* The tab this listing was requested under. It travels with the listing because the server may
|
|
61
|
+
* have filtered by it, which makes the pages — and their cursors — specific to it: switching
|
|
62
|
+
* tabs starts a new listing rather than re-filtering the loaded one.
|
|
63
|
+
*/
|
|
64
|
+
type: MediaTypeFilter
|
|
53
65
|
/** Cursor for the next page; `undefined` once the listing is exhausted. */
|
|
54
66
|
cursor: string | undefined
|
|
55
67
|
/** Cursors already followed — one coming back means the server is not advancing. */
|
|
@@ -61,8 +73,8 @@ interface Listing {
|
|
|
61
73
|
failed: boolean
|
|
62
74
|
}
|
|
63
75
|
|
|
64
|
-
function createListing(folder: string): Listing {
|
|
65
|
-
return { folder, cursor: undefined, seen: new Set(), pages: 0, busy: false, failed: false }
|
|
76
|
+
function createListing(folder: string, type: MediaTypeFilter): Listing {
|
|
77
|
+
return { folder, type, cursor: undefined, seen: new Set(), pages: 0, busy: false, failed: false }
|
|
66
78
|
}
|
|
67
79
|
|
|
68
80
|
/**
|
|
@@ -103,14 +115,6 @@ const TYPE_FILTERS: Array<{ value: MediaTypeFilter; label: string }> = [
|
|
|
103
115
|
{ value: 'document', label: 'Documents' },
|
|
104
116
|
]
|
|
105
117
|
|
|
106
|
-
function matchesTypeFilter(contentType: string, filter: MediaTypeFilter): boolean {
|
|
107
|
-
if (filter === 'all') return true
|
|
108
|
-
if (filter === 'photo') return contentType.startsWith('image/') && !VECTOR_TYPES.has(contentType)
|
|
109
|
-
if (filter === 'graphic') return VECTOR_TYPES.has(contentType)
|
|
110
|
-
if (filter === 'document') return contentType === 'application/pdf'
|
|
111
|
-
return true
|
|
112
|
-
}
|
|
113
|
-
|
|
114
118
|
export interface MediaLibraryProps {
|
|
115
119
|
media: MediaSource
|
|
116
120
|
context?: MediaContext
|
|
@@ -190,8 +194,10 @@ const grid: React.CSSProperties = {
|
|
|
190
194
|
padding: 16,
|
|
191
195
|
overflowY: 'auto',
|
|
192
196
|
}
|
|
197
|
+
const tileCell: React.CSSProperties = { position: 'relative' }
|
|
193
198
|
const tile: React.CSSProperties = {
|
|
194
199
|
position: 'relative',
|
|
200
|
+
width: '100%',
|
|
195
201
|
aspectRatio: '1 / 1',
|
|
196
202
|
border: '1px solid #e4e4e7',
|
|
197
203
|
borderRadius: 8,
|
|
@@ -205,6 +211,19 @@ const tile: React.CSSProperties = {
|
|
|
205
211
|
justifyContent: 'center',
|
|
206
212
|
gap: 6,
|
|
207
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
|
+
}
|
|
208
227
|
const emptyPanel: React.CSSProperties = { padding: 32, textAlign: 'center', color: '#a1a1aa' }
|
|
209
228
|
const pagerBar: React.CSSProperties = {
|
|
210
229
|
display: 'flex',
|
|
@@ -242,13 +261,30 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
|
|
|
242
261
|
/** A follow-up page — the grid stays on screen underneath. */
|
|
243
262
|
const [loadingMore, setLoadingMore] = useState(false)
|
|
244
263
|
const [hasMore, setHasMore] = useState(false)
|
|
264
|
+
/** The server said it applied the tab (`appliedType`), so these pages need no filtering here. */
|
|
265
|
+
const [serverFiltered, setServerFiltered] = useState(false)
|
|
266
|
+
/**
|
|
267
|
+
* The last page was server filtered yet came back short of what was asked for. A server bounds
|
|
268
|
+
* the work one filtered page may do, so a sparse tab can end a page early (even empty) with
|
|
269
|
+
* more still to come; the gallery keeps pulling rather than show a short page as the answer.
|
|
270
|
+
*/
|
|
271
|
+
const [shortPage, setShortPage] = useState(false)
|
|
272
|
+
/**
|
|
273
|
+
* How many pages have landed, ever. The drain effect's trigger: it has to re-run once per page,
|
|
274
|
+
* and neither `items` nor the loading flags can carry that. A page whose items are the same
|
|
275
|
+
* array React already holds re-renders nothing (`Object.is` bails the update out), and a flag
|
|
276
|
+
* can flip back before React re-renders at all. A number that only ever goes up cannot do
|
|
277
|
+
* either — including across the reset a folder or tab switch performs.
|
|
278
|
+
*/
|
|
279
|
+
const [pagesLanded, setPagesLanded] = useState(0)
|
|
245
280
|
const [unavailable, setUnavailable] = useState(false)
|
|
246
281
|
const [uploading, setUploading] = useState(false)
|
|
247
282
|
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
|
248
283
|
const [showNewFolder, setShowNewFolder] = useState(false)
|
|
249
284
|
const [newFolderName, setNewFolderName] = useState('')
|
|
285
|
+
const [annotating, setAnnotating] = useState<MediaItem | null>(null)
|
|
250
286
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
|
251
|
-
const listingRef = useRef<Listing>(createListing(''))
|
|
287
|
+
const listingRef = useRef<Listing>(createListing('', 'all'))
|
|
252
288
|
const mountedRef = useRef(true)
|
|
253
289
|
|
|
254
290
|
useEffect(() => {
|
|
@@ -273,9 +309,17 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
|
|
|
273
309
|
else setLoadingMore(true)
|
|
274
310
|
setErrorMsg(null)
|
|
275
311
|
try {
|
|
276
|
-
const result = await media.listMedia({
|
|
312
|
+
const result = await media.listMedia({
|
|
313
|
+
folder: listing.folder || undefined,
|
|
314
|
+
limit: pageSize,
|
|
315
|
+
cursor: listing.cursor,
|
|
316
|
+
type: listing.type,
|
|
317
|
+
})
|
|
277
318
|
if (!mountedRef.current || listingRef.current !== listing) return
|
|
278
319
|
listing.pages += 1
|
|
320
|
+
setPagesLanded(landed => landed + 1)
|
|
321
|
+
setServerFiltered(result.appliedType === listing.type)
|
|
322
|
+
setShortPage(result.appliedType === listing.type && result.items.length < pageSize)
|
|
279
323
|
setFolders(prev => mergeFolders(prev, result.folders))
|
|
280
324
|
setItems(prev => (first ? result.items : [...prev, ...result.items]))
|
|
281
325
|
const next = advance(result, listing)
|
|
@@ -301,33 +345,43 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
|
|
|
301
345
|
}
|
|
302
346
|
}, [media])
|
|
303
347
|
|
|
304
|
-
// A folder switch starts a brand-new listing; the old one is abandoned mid-flight.
|
|
348
|
+
// A folder or tab switch starts a brand-new listing; the old one is abandoned mid-flight. The
|
|
349
|
+
// tab is part of the request, so its pages and cursors belong to it and cannot be reused.
|
|
305
350
|
useEffect(() => {
|
|
306
|
-
const listing = createListing(currentFolder)
|
|
351
|
+
const listing = createListing(currentFolder, typeFilter)
|
|
307
352
|
listingRef.current = listing
|
|
308
353
|
setItems([])
|
|
309
354
|
setFolders([])
|
|
310
355
|
setHasMore(false)
|
|
356
|
+
setServerFiltered(false)
|
|
357
|
+
setShortPage(false)
|
|
311
358
|
void loadPage(listing)
|
|
312
|
-
}, [currentFolder, loadPage])
|
|
359
|
+
}, [currentFolder, typeFilter, loadPage])
|
|
313
360
|
|
|
314
361
|
const query = searchQuery.trim().toLowerCase()
|
|
315
362
|
const filterActive = query !== '' || typeFilter !== 'all'
|
|
363
|
+
/** What the loaded pages still have to be narrowed by here, on top of whatever the server did. */
|
|
364
|
+
const clientFilter = query !== '' || (typeFilter !== 'all' && !serverFiltered)
|
|
316
365
|
|
|
317
366
|
/**
|
|
318
|
-
*
|
|
319
|
-
*
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
*
|
|
323
|
-
*
|
|
367
|
+
* A filter this side of the wire only sees what is loaded, so on a paged listing it would
|
|
368
|
+
* report "no matches" for a file sitting on page 3. Drain the remaining pages while one is
|
|
369
|
+
* on — one page per landed page (see `pagesLanded`), so the drain is interruptible by a folder
|
|
370
|
+
* switch, stops on error and never runs unbounded.
|
|
371
|
+
*
|
|
372
|
+
* A tab the server filtered needs none of this: a full page is already the answer, and the
|
|
373
|
+
* pager pulls the rest the ordinary way. Only a search, or a tab against an endpoint that does
|
|
374
|
+
* not know `?type=`, still drains. A server-filtered page that came back short with more to
|
|
375
|
+
* come (see `shortPage`) is topped up the same way, one ordinary page at a time, until a full
|
|
376
|
+
* one lands or the listing ends; `MAX_PAGES` bounds it like any other listing.
|
|
324
377
|
*/
|
|
378
|
+
const drain = filterActive && clientFilter
|
|
325
379
|
useEffect(() => {
|
|
326
|
-
if (!
|
|
380
|
+
if (!drain && !shortPage) return
|
|
327
381
|
const listing = listingRef.current
|
|
328
382
|
if (listing.busy || listing.failed || listing.cursor === undefined) return
|
|
329
|
-
void loadPage(listing, DRAIN_PAGE_SIZE)
|
|
330
|
-
}, [
|
|
383
|
+
void loadPage(listing, drain ? DRAIN_PAGE_SIZE : PAGE_SIZE)
|
|
384
|
+
}, [drain, shortPage, pagesLanded, loadPage])
|
|
331
385
|
|
|
332
386
|
const navigateToFolder = (folder: string) => {
|
|
333
387
|
setSearchQuery('')
|
|
@@ -351,6 +405,7 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
|
|
|
351
405
|
url: result.url,
|
|
352
406
|
filename: result.filename ?? file.name,
|
|
353
407
|
annotation: result.annotation,
|
|
408
|
+
annotationEditable: result.annotationEditable,
|
|
354
409
|
contentType: file.type || 'application/octet-stream',
|
|
355
410
|
folder: currentFolder || undefined,
|
|
356
411
|
}
|
|
@@ -388,8 +443,17 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
|
|
|
388
443
|
setShowNewFolder(false)
|
|
389
444
|
}
|
|
390
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
|
+
|
|
453
|
+
// Applied even when the server already did: it is the same shared predicate, so it is a no-op
|
|
454
|
+
// on a filtered page, and depending on `serverFiltered` here would only add a way to be wrong.
|
|
391
455
|
const filteredItems = useMemo(() => {
|
|
392
|
-
const byType =
|
|
456
|
+
const byType = filterMediaItems(items, typeFilter)
|
|
393
457
|
return query === '' ? byType : byType.filter(i => i.filename.toLowerCase().includes(query))
|
|
394
458
|
}, [items, typeFilter, query])
|
|
395
459
|
|
|
@@ -506,7 +570,16 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
|
|
|
506
570
|
{errorMsg ? <div style={{ fontSize: 12, color: '#dc2626' }}>{errorMsg}</div> : null}
|
|
507
571
|
</div>
|
|
508
572
|
|
|
509
|
-
{
|
|
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
|
|
510
583
|
? <div style={emptyPanel}>Loading…</div>
|
|
511
584
|
: visibleFolders.length === 0 && filteredItems.length === 0
|
|
512
585
|
? (
|
|
@@ -514,6 +587,8 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
|
|
|
514
587
|
<div style={emptyPanel}>
|
|
515
588
|
{loadingMore
|
|
516
589
|
? (filterActive ? 'Searching…' : 'Loading…')
|
|
590
|
+
: filterActive && hasMore
|
|
591
|
+
? 'No matches loaded yet.'
|
|
517
592
|
: filterActive
|
|
518
593
|
? 'No matching files.'
|
|
519
594
|
: 'No files yet. Upload one to get started.'}
|
|
@@ -537,36 +612,51 @@ export function MediaLibrary({ media, context, field, accept = 'image/*,applicat
|
|
|
537
612
|
</button>
|
|
538
613
|
))}
|
|
539
614
|
{filteredItems.map(item => (
|
|
540
|
-
<
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
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/')
|
|
549
638
|
? (
|
|
550
|
-
<
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
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>
|
|
557
648
|
)
|
|
558
|
-
:
|
|
559
|
-
|
|
560
|
-
</button>
|
|
649
|
+
: null}
|
|
650
|
+
</div>
|
|
561
651
|
))}
|
|
562
652
|
</div>
|
|
563
653
|
)}
|
|
564
654
|
|
|
565
|
-
{!loading && hasMore
|
|
655
|
+
{!loading && !annotating && hasMore
|
|
566
656
|
? (
|
|
567
657
|
<div style={pagerBar}>
|
|
568
658
|
{loadingMore
|
|
569
|
-
? <span>{
|
|
659
|
+
? <span>{drain ? `Searching the whole folder… ${items.length} files scanned` : filterActive ? 'Searching…' : 'Loading…'}</span>
|
|
570
660
|
: (
|
|
571
661
|
<button type="button" style={btn} onClick={() => void loadPage(listingRef.current)}>
|
|
572
662
|
Load more
|
package/src/media-source.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* sidecar with a folder-less adapter) still satisfies it; the gallery hides the
|
|
9
9
|
* "new folder" affordance when it is absent.
|
|
10
10
|
*/
|
|
11
|
-
import type { MediaListResult, MediaUploadResult } from '@nuasite/cms-types'
|
|
11
|
+
import type { MediaListResult, MediaTypeFilter, MediaUploadResult } from '@nuasite/cms-types'
|
|
12
12
|
|
|
13
13
|
/** Where an upload is filed — mirrors the SDK's `MediaContext`. */
|
|
14
14
|
export interface MediaUploadContext {
|
|
@@ -20,9 +20,19 @@ export interface MediaUploadContext {
|
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
export interface MediaSource {
|
|
23
|
-
|
|
23
|
+
/**
|
|
24
|
+
* `type` asks the source to filter the page. A source that does not is free to ignore it — the
|
|
25
|
+
* gallery reads `MediaListResult.appliedType` to find out, and filters what it loaded when the
|
|
26
|
+
* answer came back unfiltered.
|
|
27
|
+
*/
|
|
28
|
+
listMedia(options?: { folder?: string; cursor?: string; limit?: number; type?: MediaTypeFilter }): Promise<MediaListResult>
|
|
24
29
|
uploadMedia(file: File, context?: MediaUploadContext): Promise<MediaUploadResult>
|
|
25
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 }>
|
|
26
36
|
/**
|
|
27
37
|
* Loadable URL for a repository file at its runtime path (`/uploads/hero.webp`). Optional: a
|
|
28
38
|
* host serving the project from the editor's own origin does not need one — see
|
package/src/milkdown-utils.ts
CHANGED
|
@@ -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
|
/**
|
package/src/slot-editor.tsx
CHANGED
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
*
|
|
8
8
|
* Emits `onChange` on blur (not per keystroke) so typing never triggers a node-view
|
|
9
9
|
* re-render that would clobber the focused editor.
|
|
10
|
+
*
|
|
11
|
+
* `media` serves an image already in the slot (its preview, "Replace image"); the toolbar
|
|
12
|
+
* still offers no image insertion here.
|
|
10
13
|
*/
|
|
11
14
|
import { defaultValueCtx, Editor, rootCtx } from '@milkdown/core'
|
|
12
15
|
import { listener, listenerCtx } from '@milkdown/plugin-listener'
|
|
@@ -15,11 +18,19 @@ import { gfm } from '@milkdown/preset-gfm'
|
|
|
15
18
|
import { replaceAll } from '@milkdown/utils'
|
|
16
19
|
import { useEffect, useRef, useState } from 'react'
|
|
17
20
|
import { FormatToolbar } from './format-toolbar'
|
|
21
|
+
import type { MediaContext, MediaSource } from './media-source'
|
|
18
22
|
|
|
19
23
|
const wrapper: React.CSSProperties = { border: '1px solid #e4e4e7', borderRadius: 6, background: '#fff' }
|
|
20
24
|
const host: React.CSSProperties = { padding: '6px 10px', minHeight: 60, fontSize: 13, lineHeight: 1.5, outline: 'none' }
|
|
21
25
|
|
|
22
|
-
export
|
|
26
|
+
export interface SlotEditorProps {
|
|
27
|
+
value: string
|
|
28
|
+
onChange: (markdown: string) => void
|
|
29
|
+
media?: MediaSource
|
|
30
|
+
mediaContext?: MediaContext
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function SlotEditor({ value, onChange, media, mediaContext }: SlotEditorProps) {
|
|
23
34
|
const hostRef = useRef<HTMLDivElement>(null)
|
|
24
35
|
const editorRef = useRef<Editor | null>(null)
|
|
25
36
|
const [editor, setEditor] = useState<Editor | null>(null)
|
|
@@ -75,7 +86,7 @@ export function SlotEditor({ value, onChange }: { value: string; onChange: (mark
|
|
|
75
86
|
|
|
76
87
|
return (
|
|
77
88
|
<div style={wrapper}>
|
|
78
|
-
<FormatToolbar editor={editor} />
|
|
89
|
+
<FormatToolbar editor={editor} media={media} mediaContext={mediaContext} field="children" allowImageInsert={false} />
|
|
79
90
|
<div
|
|
80
91
|
ref={hostRef}
|
|
81
92
|
style={host}
|