@asteby/metacore-runtime-react 23.3.0 → 23.5.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.
@@ -62,6 +62,7 @@ import {
62
62
  useIsDarkTheme,
63
63
  type DisplayOption,
64
64
  } from '../display-value'
65
+ import { MediaValue, RichText } from '../rich-url'
65
66
  import { generateBadgeStyles } from '@asteby/metacore-ui/lib'
66
67
  import { CollectionCell, type ItemField } from '../collection-cell'
67
68
  import type { ActionFieldDef, RelationMeta } from '../types'
@@ -1120,18 +1121,20 @@ export function ViewValue({
1120
1121
  // carrying `cellStyle:'url'` (e.g. `github_url`) renders as a clickable
1121
1122
  // external link, opening in a new tab, truncated.
1122
1123
  if ((renderAs === 'url' || renderAs === 'link') && value) {
1123
- const urlStr = String(value)
1124
- const href = /^https?:\/\//i.test(urlStr) ? urlStr : `https://${urlStr}`
1124
+ // Shared media renderer (same as the table cell): an image URL shows a
1125
+ // larger inline thumbnail, a file a chip, else a compact link chip with
1126
+ // a smart label — never the raw 120-char URL.
1125
1127
  return (
1126
- <a
1127
- href={href}
1128
- target="_blank"
1129
- rel="noopener noreferrer"
1130
- className="inline-flex items-center gap-1.5 text-sm font-medium text-primary hover:underline"
1131
- >
1132
- <ExternalLink className="h-3.5 w-3.5 shrink-0" />
1133
- <span className="truncate max-w-[360px]">{urlStr}</span>
1134
- </a>
1128
+ <div className="py-1">
1129
+ <MediaValue
1130
+ url={String(value)}
1131
+ getImageUrl={getImageUrl}
1132
+ label={field.styleConfig?.label as string | undefined}
1133
+ icon={field.styleConfig?.icon as string | undefined}
1134
+ thumbHeight={200}
1135
+ maxLabelWidth={360}
1136
+ />
1137
+ </div>
1135
1138
  )
1136
1139
  }
1137
1140
 
@@ -1240,16 +1243,32 @@ export function ViewValue({
1240
1243
  }
1241
1244
 
1242
1245
  const display = formatDisplayValue(value, field)
1246
+ // Free text may embed URLs (a github body, notes, a long-text field). Turn
1247
+ // them into rich chips / inline thumbnails with the shared linkifier instead
1248
+ // of showing raw URLs — the rest of the text is preserved verbatim.
1249
+ const hasUrl = display !== '—' && /(https?:\/\/|www\.)\S/i.test(display)
1243
1250
 
1244
- if (field.type === 'textarea') {
1251
+ if (field.type === 'textarea' || renderAs === 'textarea' || renderAs === 'long-text') {
1245
1252
  return (
1246
- <p className="text-sm whitespace-pre-wrap rounded-md bg-muted/40 p-3 min-h-[60px]">
1247
- {display}
1253
+ <p className="text-sm whitespace-pre-wrap rounded-md bg-muted/40 p-3 min-h-[60px] [&_img]:my-1">
1254
+ {hasUrl ? (
1255
+ <RichText text={display} getImageUrl={getImageUrl} imageHeight={200} />
1256
+ ) : (
1257
+ display
1258
+ )}
1248
1259
  </p>
1249
1260
  )
1250
1261
  }
1251
1262
 
1252
- return <p className="text-sm py-1">{display}</p>
1263
+ return (
1264
+ <p className="text-sm py-1">
1265
+ {hasUrl ? (
1266
+ <RichText text={display} getImageUrl={getImageUrl} imageHeight={160} />
1267
+ ) : (
1268
+ display
1269
+ )}
1270
+ </p>
1271
+ )
1253
1272
  }
1254
1273
 
1255
1274
  // IconNameViewValue — read view for a column whose value is a lucide icon name
@@ -48,6 +48,7 @@ import {
48
48
  statusColorFor,
49
49
  useIsDarkTheme,
50
50
  } from './display-value'
51
+ import { MediaValue } from './rich-url'
51
52
  import { OptionsContext } from './options-context'
52
53
  import { DynamicIcon, isLucideIconName } from './dynamic-icon'
53
54
  import { CollectionCell } from './collection-cell'
@@ -843,33 +844,24 @@ export function makeDefaultGetDynamicColumns(
843
844
  : value
844
845
  if (!rawUrl) return <EmptyCell />
845
846
  const urlStr = String(rawUrl)
846
- const href = /^https?:\/\//i.test(urlStr) ? urlStr : `https://${urlStr}`
847
- let label: string
848
- if (labelField) {
849
- label = String(getNestedValue(row.original, labelField) ?? href)
850
- } else {
851
- try {
852
- label = new URL(href).hostname
853
- } catch {
854
- label = urlStr
855
- }
856
- }
857
- const isExternal = !/^https?:\/\/(localhost|127\.)/i.test(href)
858
- const newTab =
859
- styleCfg(col, 'new_tab', 'newTab') === true || isExternal
860
- const iconName = styleCfg(col, 'icon') || 'ExternalLink'
847
+ // Explicit label from a `label_field` wins; otherwise
848
+ // the shared primitive derives a smart label (hostname
849
+ // / file name). Images render as a small (~h-8) inline
850
+ // thumbnail, files as a chip, else a link chip. Same
851
+ // renderer as the detail dialog.
852
+ const label = labelField
853
+ ? String(getNestedValue(row.original, labelField) ?? '')
854
+ : undefined
855
+ const iconName = styleCfg(col, 'icon')
861
856
  return (
862
- <a
863
- href={href}
864
- {...(newTab
865
- ? { target: '_blank', rel: 'noopener noreferrer' }
866
- : {})}
867
- className="inline-flex items-center gap-1.5 text-sm font-medium text-primary hover:underline"
868
- onClick={(e) => e.stopPropagation()}
869
- >
870
- <DynamicIcon name={iconName} className="h-3.5 w-3.5 shrink-0" />
871
- <span className="truncate max-w-[260px]">{label}</span>
872
- </a>
857
+ <MediaValue
858
+ url={urlStr}
859
+ getImageUrl={getImageUrl}
860
+ label={label || undefined}
861
+ icon={iconName || undefined}
862
+ thumbHeight={32}
863
+ maxLabelWidth={260}
864
+ />
873
865
  )
874
866
  }
875
867
 
@@ -238,6 +238,28 @@ export function applyLaneTotalsOnMove<T extends { total: number | null }>(
238
238
  return next
239
239
  }
240
240
 
241
+ /**
242
+ * Formats a lane header's count badge. Three cases:
243
+ * - A lane filter/search is active → `shown/loaded` (the client-side narrowed
244
+ * count over what this lane has loaded).
245
+ * - Otherwise, when the stage's server total is known → `shown` alone once
246
+ * everything is loaded (`shown >= total`), else `shown/total` (partial).
247
+ * - Total still unknown → just `shown`.
248
+ * Pure — exported for unit tests.
249
+ */
250
+ export function formatLaneCount(
251
+ shown: number,
252
+ loaded: number,
253
+ serverTotal: number | null,
254
+ laneActive: boolean,
255
+ ): string {
256
+ if (laneActive) return `${shown}/${loaded}`
257
+ if (serverTotal != null) {
258
+ return shown >= serverTotal ? String(serverTotal) : `${shown}/${serverTotal}`
259
+ }
260
+ return String(shown)
261
+ }
262
+
241
263
  /**
242
264
  * Picks the columns shown on a card: a `title` column (first searchable column,
243
265
  * else first text-ish column) and up to `maxFields` secondary columns. Excludes
@@ -450,6 +472,11 @@ export function DynamicKanban({
450
472
  // Active drag card id (for the DragOverlay + drop-zone highlighting).
451
473
  const [activeId, setActiveId] = useState<string | null>(null)
452
474
 
475
+ // Monotonic token for the current board load. Bumped on every fetchData so a
476
+ // slow eager-totals response from a superseded filter set can't inject stale
477
+ // stage totals into the fresh board.
478
+ const fetchGenRef = useRef(0)
479
+
453
480
  const sensors = useSensors(
454
481
  useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
455
482
  )
@@ -507,6 +534,7 @@ export function DynamicKanban({
507
534
  // change (fetchData's identity changes with filterParams).
508
535
  const fetchData = useCallback(async () => {
509
536
  if (!metadata) return
537
+ const gen = ++fetchGenRef.current
510
538
  setLoadingData(true)
511
539
  try {
512
540
  const res = (await api.get(endpoint || `/data/${model}`, {
@@ -519,6 +547,49 @@ export function DynamicKanban({
519
547
  setLoadingData(false)
520
548
  }
521
549
  setLanePagination({})
550
+ // Eager per-lane totals: so every lane header shows the REAL stage count
551
+ // on first render (not just what the global page happened to load), fire
552
+ // one lightweight `per_page=1` request per declared stage — in parallel,
553
+ // scoped by the SAME active filters/search (`f_<group_by>=<stage>` on top
554
+ // of filterParams). We read only `meta.total`; the row itself is ignored
555
+ // (the lane loads its real cards via loadMoreLane on scroll). The
556
+ // "unassigned" lane can't be stage-scoped, so it keeps its loaded count.
557
+ const gb = metadata.group_by
558
+ const declaredStages = deriveStages(metadata)
559
+ if (gb && declaredStages.length > 0) {
560
+ void Promise.all(
561
+ declaredStages.map(async (stage) => {
562
+ try {
563
+ const r = (await api.get(endpoint || `/data/${model}`, {
564
+ params: {
565
+ ...filterParams,
566
+ page: 1,
567
+ per_page: 1,
568
+ [`f_${gb}`]: stage.key,
569
+ },
570
+ })) as { data: ApiResponse<any[]> & { meta?: any } }
571
+ const total = r.data.meta?.total ?? r.data.meta?.count ?? null
572
+ if (total == null || gen !== fetchGenRef.current) return
573
+ setLanePagination((p) => {
574
+ const existing = p[stage.key]
575
+ // A real page fetch already learned this lane's total.
576
+ if (existing?.total != null) return p
577
+ return {
578
+ ...p,
579
+ [stage.key]: {
580
+ nextPage: existing?.nextPage ?? 1,
581
+ total,
582
+ loading: existing?.loading ?? false,
583
+ done: existing?.done ?? total === 0,
584
+ },
585
+ }
586
+ })
587
+ } catch (err) {
588
+ // A failed total just leaves the header on the loaded count.
589
+ }
590
+ }),
591
+ )
592
+ }
522
593
  }, [api, endpoint, model, metadata, pageSize, filterParams])
523
594
 
524
595
  // Load the next page for ONE lane/stage and append it (deduped by id) into
@@ -1257,11 +1328,7 @@ function KanbanLane({
1257
1328
  {t(stage.label, { defaultValue: stage.label })}
1258
1329
  </Badge>
1259
1330
  <span className="text-xs font-medium tabular-nums text-muted-foreground">
1260
- {laneActive
1261
- ? `${count}/${totalCount}`
1262
- : serverTotal != null
1263
- ? `${count}/${serverTotal}`
1264
- : count}
1331
+ {formatLaneCount(count, totalCount, serverTotal, laneActive)}
1265
1332
  </span>
1266
1333
  </div>
1267
1334
  {/* Lane actions — always visible in muted (a hidden hover-reveal
package/src/index.ts CHANGED
@@ -129,6 +129,23 @@ export {
129
129
  type DynamicColumnsHelpers,
130
130
  } from './dynamic-columns'
131
131
  export { humanizeToken } from './dynamic-columns-helpers'
132
+ export {
133
+ UrlChip,
134
+ FileChip,
135
+ ImageThumbnail,
136
+ MediaValue,
137
+ RichText,
138
+ linkifyText,
139
+ classifyUrl,
140
+ isImageUrl,
141
+ isFileUrl,
142
+ ensureHref,
143
+ smartUrlLabel,
144
+ fileNameFromUrl,
145
+ splitTrailingPunct,
146
+ type UrlKind,
147
+ type LinkifyOptions,
148
+ } from './rich-url'
132
149
  export {
133
150
  CollectionCell,
134
151
  formatScalar,
@@ -0,0 +1,359 @@
1
+ /**
2
+ * Rich URL & media rendering primitives.
3
+ *
4
+ * A URL is never shown raw. Depending on what it points at we render:
5
+ * - an IMAGE (jpg/png/gif/webp/… or a `link.asteby.com/storage/media/` path)
6
+ * → an inline clickable THUMBNAIL that opens the full image in a new tab,
7
+ * - a FILE (pdf/zip/docx/…) → a chip with a file icon and the file name,
8
+ * - anything else → a compact link CHIP: an external-link glyph plus a short
9
+ * smart label (hostname, e.g. "github.com", or the last path segment for a
10
+ * file-like URL), with the full URL in a native tooltip.
11
+ *
12
+ * These live here (not inline in the table/dialog) so the dynamic TABLE cell
13
+ * (`dynamic-columns.tsx`) and the read-only DETAIL DIALOG (`dynamic-record.tsx`)
14
+ * share the EXACT same rendering. Ecosystem rule: shared primitives, zero copy.
15
+ *
16
+ * No external requests are made to render a link (no favicon service — CSP /
17
+ * privacy): the icon is a local lucide glyph.
18
+ */
19
+ import React from 'react'
20
+ import { cn } from '@asteby/metacore-ui/lib'
21
+ import { DynamicIcon } from './dynamic-icon'
22
+
23
+ /** Image file extensions we render as an inline thumbnail. */
24
+ const IMAGE_EXT_RE = /\.(jpe?g|png|gif|webp|avif|svg|bmp|ico)(?:[?#].*)?$/i
25
+
26
+ /**
27
+ * Storage paths that serve images without a file extension (the link.asteby.com
28
+ * media CDN hands back opaque ids). Treated as images so uploaded photos still
29
+ * thumbnail.
30
+ */
31
+ const MEDIA_PATH_RE = /\/storage\/media\//i
32
+
33
+ /** Non-image file extensions we render as a download-ish file chip. */
34
+ const FILE_EXT_RE =
35
+ /\.(pdf|zip|rar|7z|tar|t?gz|docx?|xlsx?|pptx?|csv|txt|json|xml|md|rtf|odt|mp4|mov|avi|mkv|webm|mp3|wav|ogg|flac|apk|dmg|exe|pkg)(?:[?#].*)?$/i
36
+
37
+ export type UrlKind = 'image' | 'file' | 'link'
38
+
39
+ /** `true` when the string looks like an image URL/path. */
40
+ export function isImageUrl(url: string): boolean {
41
+ return IMAGE_EXT_RE.test(url) || MEDIA_PATH_RE.test(url)
42
+ }
43
+
44
+ /** `true` when the string looks like a non-image downloadable file. */
45
+ export function isFileUrl(url: string): boolean {
46
+ return FILE_EXT_RE.test(url)
47
+ }
48
+
49
+ /** Classify a URL so the right primitive (thumbnail / file chip / link) renders. */
50
+ export function classifyUrl(url: string): UrlKind {
51
+ if (isImageUrl(url)) return 'image'
52
+ if (isFileUrl(url)) return 'file'
53
+ return 'link'
54
+ }
55
+
56
+ /** Ensure a URL is absolute so `<a href>` and `new URL()` behave. */
57
+ export function ensureHref(url: string): string {
58
+ return /^(https?:)?\/\//i.test(url) || /^(mailto|tel):/i.test(url)
59
+ ? url
60
+ : `https://${url}`
61
+ }
62
+
63
+ /**
64
+ * A short, human label for a URL. For a file-like URL (last segment carries an
65
+ * extension) the file name wins ("report.pdf"); otherwise the bare hostname
66
+ * ("github.com"), so a 120-char issue URL never shows raw. Falls back to the
67
+ * input when it can't be parsed.
68
+ */
69
+ export function smartUrlLabel(url: string): string {
70
+ try {
71
+ const u = new URL(ensureHref(url))
72
+ const segs = u.pathname.split('/').filter(Boolean)
73
+ const last = segs[segs.length - 1]
74
+ if (last && /\.[a-z0-9]{1,8}$/i.test(last)) {
75
+ return decodeURIComponent(last)
76
+ }
77
+ return u.hostname.replace(/^www\./i, '')
78
+ } catch {
79
+ return url
80
+ }
81
+ }
82
+
83
+ /** Last path segment (decoded) — the file name for a file/image URL. */
84
+ export function fileNameFromUrl(url: string): string {
85
+ try {
86
+ const u = new URL(ensureHref(url))
87
+ const segs = u.pathname.split('/').filter(Boolean)
88
+ return decodeURIComponent(segs[segs.length - 1] || u.hostname)
89
+ } catch {
90
+ return url.split(/[?#]/)[0].split('/').pop() || url
91
+ }
92
+ }
93
+
94
+ /** Stops row-click / dialog-close when a link inside them is clicked. */
95
+ function stop(e: React.MouseEvent) {
96
+ e.stopPropagation()
97
+ }
98
+
99
+ /**
100
+ * Compact link chip: external-link glyph + smart label, full URL in the
101
+ * tooltip, opens in a new tab. The canonical render for a plain (non-media)
102
+ * URL, matching the table's `url`/`link` cell.
103
+ */
104
+ export const UrlChip: React.FC<{
105
+ url: string
106
+ label?: string
107
+ icon?: string
108
+ /** Smaller label cap for a table/kanban cell. */
109
+ maxLabelWidth?: number
110
+ className?: string
111
+ }> = ({ url, label, icon, maxLabelWidth = 260, className }) => {
112
+ const href = ensureHref(url)
113
+ const text = label || smartUrlLabel(url)
114
+ return (
115
+ <a
116
+ href={href}
117
+ target="_blank"
118
+ rel="noopener noreferrer"
119
+ title={url}
120
+ onClick={stop}
121
+ className={cn(
122
+ 'inline-flex max-w-full items-center gap-1.5 align-middle text-sm font-medium text-primary hover:underline',
123
+ className
124
+ )}
125
+ >
126
+ <DynamicIcon name={icon || 'ExternalLink'} className="h-3.5 w-3.5 shrink-0" />
127
+ <span className="truncate" style={{ maxWidth: maxLabelWidth }}>
128
+ {text}
129
+ </span>
130
+ </a>
131
+ )
132
+ }
133
+
134
+ /**
135
+ * Chip for a downloadable non-image file: file-text glyph + the file name,
136
+ * opens the file in a new tab.
137
+ */
138
+ export const FileChip: React.FC<{
139
+ url: string
140
+ maxLabelWidth?: number
141
+ className?: string
142
+ }> = ({ url, maxLabelWidth = 240, className }) => {
143
+ const href = ensureHref(url)
144
+ return (
145
+ <a
146
+ href={href}
147
+ target="_blank"
148
+ rel="noopener noreferrer"
149
+ title={url}
150
+ onClick={stop}
151
+ className={cn(
152
+ 'inline-flex max-w-full items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1 align-middle text-sm font-medium text-foreground hover:bg-muted',
153
+ className
154
+ )}
155
+ >
156
+ <DynamicIcon name="FileText" className="h-3.5 w-3.5 shrink-0 opacity-70" />
157
+ <span className="truncate" style={{ maxWidth: maxLabelWidth }}>
158
+ {fileNameFromUrl(url)}
159
+ </span>
160
+ </a>
161
+ )
162
+ }
163
+
164
+ /**
165
+ * Inline image thumbnail — rounded, bordered, `object-cover` — that opens the
166
+ * full image in a new tab. On load error it degrades to a normal link chip so a
167
+ * dead image URL is still reachable (and never a broken-image icon). `maxHeight`
168
+ * keeps a cell thumbnail small (~h-8) while the dialog shows a larger preview.
169
+ */
170
+ export const ImageThumbnail: React.FC<{
171
+ url: string
172
+ getImageUrl?: (path: string) => string
173
+ /** Max rendered height in px. */
174
+ maxHeight?: number
175
+ className?: string
176
+ }> = ({ url, getImageUrl, maxHeight = 160, className }) => {
177
+ const [failed, setFailed] = React.useState(false)
178
+ const href = ensureHref(url)
179
+ // Absolute URLs are used verbatim; only relative storage paths go through
180
+ // the host's image resolver (which prefixes the media base).
181
+ const src =
182
+ /^(https?:)?\/\//i.test(url) ? url : getImageUrl ? getImageUrl(url) : url
183
+ if (failed) return <UrlChip url={url} icon="Image" />
184
+ return (
185
+ <a
186
+ href={href}
187
+ target="_blank"
188
+ rel="noopener noreferrer"
189
+ title={url}
190
+ onClick={stop}
191
+ className="inline-block max-w-full align-middle"
192
+ >
193
+ <img
194
+ src={src}
195
+ alt={smartUrlLabel(url)}
196
+ onError={() => setFailed(true)}
197
+ style={{ maxHeight }}
198
+ className={cn(
199
+ 'max-w-full rounded-md border object-cover',
200
+ className
201
+ )}
202
+ />
203
+ </a>
204
+ )
205
+ }
206
+
207
+ /**
208
+ * One URL value → the right primitive (thumbnail / file chip / link chip).
209
+ * Single entry point used by both the table cell and the detail dialog so a URL
210
+ * renders identically everywhere.
211
+ */
212
+ export const MediaValue: React.FC<{
213
+ url: string
214
+ getImageUrl?: (path: string) => string
215
+ /** Explicit label for the link chip (from a `label_field`). */
216
+ label?: string
217
+ /** Explicit icon for the link chip. */
218
+ icon?: string
219
+ /** Thumbnail max height (small in a cell, larger in the dialog). */
220
+ thumbHeight?: number
221
+ /** Link/file label truncation cap. */
222
+ maxLabelWidth?: number
223
+ className?: string
224
+ }> = ({ url, getImageUrl, label, icon, thumbHeight, maxLabelWidth, className }) => {
225
+ switch (classifyUrl(url)) {
226
+ case 'image':
227
+ return (
228
+ <ImageThumbnail
229
+ url={url}
230
+ getImageUrl={getImageUrl}
231
+ maxHeight={thumbHeight}
232
+ className={className}
233
+ />
234
+ )
235
+ case 'file':
236
+ return <FileChip url={url} maxLabelWidth={maxLabelWidth} className={className} />
237
+ default:
238
+ return (
239
+ <UrlChip
240
+ url={url}
241
+ label={label}
242
+ icon={icon}
243
+ maxLabelWidth={maxLabelWidth}
244
+ className={className}
245
+ />
246
+ )
247
+ }
248
+ }
249
+
250
+ // URL / markdown-link matcher used to linkify free text. Captures either a
251
+ // markdown `[label](url)` or a bare http(s)/www URL. `[^\s<]+` is greedy on
252
+ // purpose — trailing punctuation is trimmed afterwards by `splitTrailingPunct`.
253
+ const LINK_IN_TEXT_RE =
254
+ /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s<]+|www\.[^\s<]+)/gi
255
+
256
+ /**
257
+ * Peel trailing punctuation a URL shouldn't swallow (sentence period, closing
258
+ * bracket, quote). A closing paren is kept only when the URL itself opened one
259
+ * (Wikipedia-style `(…)` paths), so `(see https://x.com/a)` links `https://x.com/a`
260
+ * but `https://en.wikipedia.org/wiki/Foo_(bar)` keeps its paren.
261
+ */
262
+ export function splitTrailingPunct(match: string): [string, string] {
263
+ const m = match.match(/[).,;:!?\]}'"»›]+$/)
264
+ if (!m) return [match, '']
265
+ let trail = m[0]
266
+ let core = match.slice(0, match.length - trail.length)
267
+ if (trail.startsWith(')')) {
268
+ const opens = (core.match(/\(/g) || []).length
269
+ const closes = (core.match(/\)/g) || []).length
270
+ if (opens > closes) {
271
+ core += ')'
272
+ trail = trail.slice(1)
273
+ }
274
+ }
275
+ return [core, trail]
276
+ }
277
+
278
+ export interface LinkifyOptions {
279
+ getImageUrl?: (path: string) => string
280
+ /** Max height for an inline image found in the text. */
281
+ imageHeight?: number
282
+ }
283
+
284
+ /**
285
+ * Turn free text into React nodes, replacing every URL (bare or markdown
286
+ * `[label](url)`) with the matching rich primitive: an inline thumbnail for an
287
+ * image URL, a file chip for a file, otherwise a link chip. Plain text between
288
+ * matches is preserved verbatim (caller keeps `whitespace-pre-wrap`).
289
+ */
290
+ export function linkifyText(
291
+ text: string,
292
+ opts: LinkifyOptions = {}
293
+ ): React.ReactNode[] {
294
+ if (!text) return []
295
+ const nodes: React.ReactNode[] = []
296
+ const re = new RegExp(LINK_IN_TEXT_RE.source, 'gi')
297
+ let lastIndex = 0
298
+ let key = 0
299
+ let m: RegExpExecArray | null
300
+ while ((m = re.exec(text)) !== null) {
301
+ const [full, mdLabel, mdUrl, bareUrl] = m
302
+ const start = m.index
303
+ if (start > lastIndex) nodes.push(text.slice(lastIndex, start))
304
+
305
+ if (mdUrl) {
306
+ // Markdown link: honor the author's label, keep media inline.
307
+ const kind = classifyUrl(mdUrl)
308
+ if (kind === 'image') {
309
+ nodes.push(
310
+ <ImageThumbnail
311
+ key={key}
312
+ url={mdUrl}
313
+ getImageUrl={opts.getImageUrl}
314
+ maxHeight={opts.imageHeight ?? 200}
315
+ />
316
+ )
317
+ } else if (kind === 'file') {
318
+ nodes.push(<FileChip key={key} url={mdUrl} />)
319
+ } else {
320
+ nodes.push(<UrlChip key={key} url={mdUrl} label={mdLabel} />)
321
+ }
322
+ lastIndex = start + full.length
323
+ } else {
324
+ const [core, trail] = splitTrailingPunct(bareUrl)
325
+ const kind = classifyUrl(core)
326
+ if (kind === 'image') {
327
+ nodes.push(
328
+ <ImageThumbnail
329
+ key={key}
330
+ url={core}
331
+ getImageUrl={opts.getImageUrl}
332
+ maxHeight={opts.imageHeight ?? 200}
333
+ />
334
+ )
335
+ } else if (kind === 'file') {
336
+ nodes.push(<FileChip key={key} url={core} />)
337
+ } else {
338
+ nodes.push(<UrlChip key={key} url={core} />)
339
+ }
340
+ if (trail) nodes.push(trail)
341
+ lastIndex = start + bareUrl.length
342
+ }
343
+ key++
344
+ }
345
+ if (lastIndex < text.length) nodes.push(text.slice(lastIndex))
346
+ return nodes
347
+ }
348
+
349
+ /**
350
+ * Linkified free text. Renders the raw string with every URL turned into a rich
351
+ * chip/thumbnail — the read view for a long-text / textarea / body field.
352
+ */
353
+ export const RichText: React.FC<{
354
+ text: string
355
+ getImageUrl?: (path: string) => string
356
+ imageHeight?: number
357
+ }> = ({ text, getImageUrl, imageHeight }) => (
358
+ <>{linkifyText(text, { getImageUrl, imageHeight })}</>
359
+ )