@nocode-factory/sanity-kit 2.0.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.
Files changed (95) hide show
  1. package/bin/ncf-kit.mjs +201 -0
  2. package/dist/index.d.ts +1643 -0
  3. package/dist/index.js +6632 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/web-server.d.ts +46 -0
  6. package/dist/web-server.js +51 -0
  7. package/dist/web-server.js.map +1 -0
  8. package/dist/web.d.ts +27 -0
  9. package/dist/web.js +117 -0
  10. package/dist/web.js.map +1 -0
  11. package/package.json +90 -0
  12. package/scripts/use-client.mjs +20 -0
  13. package/src/config/defaults.ts +74 -0
  14. package/src/config/resolve.ts +153 -0
  15. package/src/config/types.ts +290 -0
  16. package/src/config/validate.ts +193 -0
  17. package/src/context/BoardLayoutContext.tsx +24 -0
  18. package/src/context/KitContext.tsx +30 -0
  19. package/src/context/PreviewTargetContext.tsx +27 -0
  20. package/src/hooks/useAnnotations.ts +60 -0
  21. package/src/hooks/useBoardLayout.ts +398 -0
  22. package/src/hooks/useColumnOptions.ts +47 -0
  23. package/src/hooks/useDocumentColumns.ts +61 -0
  24. package/src/hooks/useHistory.ts +89 -0
  25. package/src/hooks/useInternalColumns.ts +19 -0
  26. package/src/hooks/useKitClient.ts +15 -0
  27. package/src/hooks/useOccurrences.ts +62 -0
  28. package/src/hooks/usePageContents.ts +65 -0
  29. package/src/hooks/usePages.ts +41 -0
  30. package/src/hooks/usePreviewTarget.ts +162 -0
  31. package/src/hooks/useQueryData.ts +103 -0
  32. package/src/hooks/useRegistration.ts +50 -0
  33. package/src/index.ts +280 -0
  34. package/src/lib/blocks.ts +38 -0
  35. package/src/lib/colors.ts +103 -0
  36. package/src/lib/columns.ts +137 -0
  37. package/src/lib/diff.ts +200 -0
  38. package/src/lib/elkLayout.ts +124 -0
  39. package/src/lib/graph.ts +238 -0
  40. package/src/lib/grouping.ts +116 -0
  41. package/src/lib/links.ts +70 -0
  42. package/src/lib/occurrences.ts +93 -0
  43. package/src/lib/pageThumbnail.ts +43 -0
  44. package/src/lib/pages.ts +199 -0
  45. package/src/lib/paths.ts +68 -0
  46. package/src/lib/query.ts +113 -0
  47. package/src/lib/schemaColumns.ts +162 -0
  48. package/src/lib/schemaTypes.ts +75 -0
  49. package/src/lib/sectionsMap.ts +83 -0
  50. package/src/lib/service.ts +88 -0
  51. package/src/lib/siteRoutes.ts +43 -0
  52. package/src/lib/status.ts +122 -0
  53. package/src/lib/studioLinks.ts +137 -0
  54. package/src/schema/boardLayout.ts +190 -0
  55. package/src/tools/components/BlockCard.tsx +79 -0
  56. package/src/tools/components/ComponentsTool.tsx +171 -0
  57. package/src/tools/components/map/SectionNode.tsx +109 -0
  58. package/src/tools/components/map/SectionsMap.tsx +339 -0
  59. package/src/tools/createToolComponent.tsx +67 -0
  60. package/src/tools/history/ChangeRow.tsx +87 -0
  61. package/src/tools/history/DiffPanel.tsx +227 -0
  62. package/src/tools/history/HistoryTool.tsx +230 -0
  63. package/src/tools/more/MoreTool.tsx +82 -0
  64. package/src/tools/pages/ColumnHeader.tsx +216 -0
  65. package/src/tools/pages/ColumnVisibility.tsx +173 -0
  66. package/src/tools/pages/FieldValue.tsx +327 -0
  67. package/src/tools/pages/PagesTable.tsx +394 -0
  68. package/src/tools/pages/PagesTool.tsx +333 -0
  69. package/src/tools/pages/PagesToolbar.tsx +53 -0
  70. package/src/tools/pages/PathCell.tsx +71 -0
  71. package/src/tools/pages/PreviewTarget.tsx +226 -0
  72. package/src/tools/pages/TagCell.tsx +124 -0
  73. package/src/tools/pages/ViewTabs.tsx +57 -0
  74. package/src/tools/pages/board/BoardView.tsx +661 -0
  75. package/src/tools/pages/board/PageNode.tsx +306 -0
  76. package/src/tools/pages/board/PagePanel.tsx +228 -0
  77. package/src/tools/presentation/PreviewHeader.tsx +75 -0
  78. package/src/tools/shared/AnnotationNode.tsx +126 -0
  79. package/src/ui/ActorName.tsx +20 -0
  80. package/src/ui/ConfigIssues.tsx +41 -0
  81. package/src/ui/InlineCode.tsx +22 -0
  82. package/src/ui/Popover.tsx +85 -0
  83. package/src/ui/ProjectStatusNotice.tsx +58 -0
  84. package/src/ui/QueryError.tsx +16 -0
  85. package/src/ui/QuietInput.tsx +64 -0
  86. package/src/ui/StatusBadge.tsx +11 -0
  87. package/src/ui/ToolPlaceholder.tsx +23 -0
  88. package/src/ui/formatDate.ts +14 -0
  89. package/src/ui/tokens.ts +54 -0
  90. package/src/version.ts +5 -0
  91. package/src/web/PreviewBanner.tsx +115 -0
  92. package/src/web/draftModeToggle.ts +56 -0
  93. package/src/web/environment.ts +21 -0
  94. package/src/web/index.ts +15 -0
  95. package/src/web/server.ts +11 -0
@@ -0,0 +1,333 @@
1
+ import {useCallback, useMemo, useState} from 'react'
2
+ import {Box, Card, Flex, Select, Spinner, Stack, Text} from '@sanity/ui'
3
+ import {useRouter} from 'sanity/router'
4
+ import {useKitConfig} from '../../context/KitContext'
5
+ import {useBoardLayout} from '../../context/BoardLayoutContext'
6
+ import {useInternalColumns} from '../../hooks/useInternalColumns'
7
+ import {usePages} from '../../hooks/usePages'
8
+ import {useDocumentColumns} from '../../hooks/useDocumentColumns'
9
+ import {usePreviewTarget} from '../../context/PreviewTargetContext'
10
+ import {PreviewTarget} from './PreviewTarget'
11
+ import {filterRows, sortRows, type PageRow, type SortDirection, type SortKey} from '../../lib/pages'
12
+ import {groupPageRows, type GroupBy} from '../../lib/grouping'
13
+ import {resolveColorBy, type ColorBy} from '../../lib/colors'
14
+ import * as columnOps from '../../lib/columns'
15
+ import {useColumnOptions} from '../../hooks/useColumnOptions'
16
+ import {QueryError} from '../../ui/QueryError'
17
+ import {PagesTable} from './PagesTable'
18
+ import {PagesToolbar} from './PagesToolbar'
19
+ import {FieldLabel, ViewTabs, type PagesView} from './ViewTabs'
20
+ import {ColumnVisibility, type HideableKey} from './ColumnVisibility'
21
+ import {BoardView} from './board/BoardView'
22
+
23
+ /** Au-delà, on pagine : 500 lignes d'un coup rendent le défilement poussif. */
24
+ const PAGE_SIZE = 100
25
+
26
+ export function PagesTool() {
27
+ const config = useKitConfig()
28
+ const router = useRouter()
29
+
30
+ const {byId, saveColumns, patchNode, patchField} = useBoardLayout()
31
+ const columnOptions = useColumnOptions()
32
+ const preview = usePreviewTarget()
33
+ const columns = useInternalColumns()
34
+
35
+ const [view, setView] = useState<PagesView>('list')
36
+ const [search, setSearch] = useState('')
37
+ const [groupBy, setGroupBy] = useState<GroupBy>('none')
38
+ const [rawColorBy, setColorBy] = useState<ColorBy>('tag')
39
+ // L'ordre du Studio par défaut : aucune colonne n'est marquée triée tant
40
+ // que l'éditeur n'en a pas choisi une.
41
+ const [sortKey, setSortKey] = useState<SortKey>('structure')
42
+ const [sortDirection, setSortDirection] = useState<SortDirection>('asc')
43
+ const [page, setPage] = useState(0)
44
+ const [hidden, setHidden] = useState<ReadonlySet<string>>(new Set())
45
+ // Les données du document sont masquées tant qu'on ne les demande pas : un
46
+ // tableau de pages n'est pas un export SEO.
47
+ const [shownData, setShownData] = useState<ReadonlySet<string>>(new Set())
48
+ const toggleData = useCallback((key: string) => {
49
+ setShownData((current) => {
50
+ const next = new Set(current)
51
+ if (next.has(key)) next.delete(key)
52
+ else next.add(key)
53
+ return next
54
+ })
55
+ }, [])
56
+
57
+ const documentColumns = useDocumentColumns()
58
+ const visibleDataColumns = useMemo(
59
+ () => documentColumns.filter((column) => shownData.has(column.key)),
60
+ [documentColumns, shownData],
61
+ )
62
+ const {rows, loading, error, refresh} = usePages(visibleDataColumns)
63
+
64
+ const colorBy = resolveColorBy(rawColorBy, columns)
65
+
66
+ const visible = useMemo(
67
+ () =>
68
+ sortRows(filterRows(rows, {search}), sortKey, sortDirection, {
69
+ typeOrder: config.pageTypeNames,
70
+ }),
71
+ [rows, search, sortKey, sortDirection, config.pageTypeNames],
72
+ )
73
+
74
+ // Un filtre qui réduit la liste ne doit pas laisser l'utilisateur sur une
75
+ // page vide au-delà de la fin.
76
+ const pageCount = Math.max(1, Math.ceil(visible.length / PAGE_SIZE))
77
+ const current = Math.min(page, pageCount - 1)
78
+ const slice = visible.slice(current * PAGE_SIZE, current * PAGE_SIZE + PAGE_SIZE)
79
+
80
+ const groups = useMemo(
81
+ () =>
82
+ groupPageRows(slice, groupBy, {
83
+ meta: byId,
84
+ tags: config.boardTags,
85
+ fields: columns,
86
+ }),
87
+ [slice, groupBy, byId, config.boardTags, columns],
88
+ )
89
+
90
+ /**
91
+ * Ouvrir une page mène à Presentation. Sans `previewUrl`, il n'y a rien à
92
+ * prévisualiser : on retombe sur le formulaire.
93
+ */
94
+
95
+ const openPage = useCallback(
96
+ (row: PageRow) => {
97
+ const path = preview.pathFor(row.url)
98
+ if (path) router.navigateUrl({path})
99
+ else router.navigateIntent('edit', {id: row.id, type: row.type})
100
+ },
101
+ [router, preview],
102
+ )
103
+
104
+ const onTag = useCallback(
105
+ (documentId: string, tag: string | null) => patchNode(documentId, {tag: tag ?? undefined}),
106
+ [patchNode],
107
+ )
108
+
109
+ const toggleColumn = (key: HideableKey) =>
110
+ setHidden((current) => {
111
+ const next = new Set(current)
112
+ if (next.has(key)) next.delete(key)
113
+ else next.add(key)
114
+ return next
115
+ })
116
+
117
+ const onSort = (key: SortKey) => {
118
+ if (key === sortKey) setSortDirection((d) => (d === 'asc' ? 'desc' : 'asc'))
119
+ else {
120
+ setSortKey(key)
121
+ setSortDirection('asc')
122
+ }
123
+ setPage(0)
124
+ }
125
+
126
+ if (error) return <QueryError error={error} onRetry={refresh} />
127
+
128
+ const colorOptions = [
129
+ {value: 'tag' as ColorBy, label: 'Étiquette'},
130
+ {value: 'status' as ColorBy, label: 'Statut'},
131
+ ...columns.map((field) => ({
132
+ value: `field:${field.id}` as ColorBy,
133
+ label: field.label || field.id,
134
+ })),
135
+ ]
136
+
137
+ const summary =
138
+ visible.length === rows.length
139
+ ? `${rows.length} page${rows.length > 1 ? 's' : ''}`
140
+ : `${visible.length} sur ${rows.length}`
141
+
142
+ const loadingState = (
143
+ <Flex align="center" justify="center" padding={6} gap={3}>
144
+ <Spinner muted />
145
+ <Text size={1} muted>
146
+ Chargement des pages…
147
+ </Text>
148
+ </Flex>
149
+ )
150
+
151
+ return (
152
+ <Stack gap={4}>
153
+ <Flex align="flex-end" justify="space-between" gap={4} wrap="wrap">
154
+ <ViewTabs view={view} onChange={setView} />
155
+
156
+ <Flex gap={3} align="flex-end" wrap="wrap">
157
+ <PreviewTarget
158
+ environments={preview.environments}
159
+ environmentId={preview.environmentId}
160
+ perspective={preview.perspective}
161
+ onEnvironment={preview.setEnvironment}
162
+ onPerspective={preview.setPerspective}
163
+ onCustomUrl={preview.setCustomUrl}
164
+ customUrl={preview.customUrl}
165
+ />
166
+
167
+ {view === 'list' && (
168
+ <Box style={{flex: 'none', paddingBottom: 2}}>
169
+ <ColumnVisibility
170
+ hidden={hidden}
171
+ onToggle={toggleColumn}
172
+ dataColumns={documentColumns}
173
+ shownData={shownData}
174
+ onToggleData={toggleData}
175
+ />
176
+ </Box>
177
+ )}
178
+
179
+ {view === 'list' && (
180
+ <Box style={{width: 168, flex: 'none'}}>
181
+ <FieldLabel>Grouper par</FieldLabel>
182
+ <Select
183
+ fontSize={1}
184
+ radius={2}
185
+ value={groupBy}
186
+ onChange={(event) => setGroupBy(event.currentTarget.value as GroupBy)}
187
+ >
188
+ <option value="none">Aucun</option>
189
+ <option value="tag">Étiquette</option>
190
+ <option value="status">Statut</option>
191
+ <option value="indexation">Indexation</option>
192
+ <option value="type">Type</option>
193
+ {columns.map((field) => (
194
+ <option key={field.id} value={`field:${field.id}`}>
195
+ {field.label || field.id}
196
+ </option>
197
+ ))}
198
+ </Select>
199
+ </Box>
200
+ )}
201
+
202
+ <Box style={{width: 168, flex: 'none'}}>
203
+ <FieldLabel>Colorer par</FieldLabel>
204
+ <Select
205
+ fontSize={1}
206
+ radius={2}
207
+ value={colorBy}
208
+ onChange={(event) => setColorBy(event.currentTarget.value as ColorBy)}
209
+ >
210
+ {colorOptions.map((option) => (
211
+ <option key={option.value} value={option.value}>
212
+ {option.label}
213
+ </option>
214
+ ))}
215
+ </Select>
216
+ </Box>
217
+ </Flex>
218
+ </Flex>
219
+
220
+ <PagesToolbar
221
+ search={search}
222
+ onSearch={(value) => {
223
+ setSearch(value)
224
+ setPage(0)
225
+ }}
226
+ onRefresh={refresh}
227
+ busy={loading}
228
+ summary={summary}
229
+ />
230
+
231
+ {view !== 'list' ? (
232
+ loading && rows.length === 0 ? (
233
+ loadingState
234
+ ) : (
235
+ <BoardView
236
+ rows={visible}
237
+ mode={view === 'brain' ? 'brain' : 'tree'}
238
+ colorBy={colorBy}
239
+ pathFor={preview.pathFor}
240
+ />
241
+ )
242
+ ) : (
243
+ <>
244
+ <Card radius={3} shadow={1} padding={0} style={{overflow: 'hidden'}}>
245
+ {loading && rows.length === 0 ? (
246
+ loadingState
247
+ ) : visible.length === 0 ? (
248
+ <Box padding={6}>
249
+ <Stack gap={3}>
250
+ <Text size={1} weight="medium" align="center">
251
+ {rows.length === 0 ? 'Aucune page dans ce dataset' : 'Aucun résultat'}
252
+ </Text>
253
+ <Text size={1} muted align="center">
254
+ {rows.length === 0
255
+ ? `Le kit suit les types ${config.pageTypeNames.join(', ')}.`
256
+ : 'Essaie un autre terme, ou vide la recherche.'}
257
+ </Text>
258
+ </Stack>
259
+ </Box>
260
+ ) : (
261
+ <PagesTable
262
+ groups={groups}
263
+ sortKey={sortKey}
264
+ sortDirection={sortDirection}
265
+ onSort={onSort}
266
+ columns={columns}
267
+ meta={byId}
268
+ tags={config.boardTags}
269
+ colorBy={colorBy}
270
+ fields={columns}
271
+ onField={patchField}
272
+ dataColumns={visibleDataColumns}
273
+ {...columnOptions}
274
+ onAddColumn={(label, kind) =>
275
+ saveColumns(columnOps.addColumn(columns, {label, type: kind}))
276
+ }
277
+ onRenameColumn={(id, label) =>
278
+ saveColumns(columnOps.renameColumn(columns, id, label))
279
+ }
280
+ onRemoveColumn={(id) => saveColumns(columnOps.removeColumn(columns, id))}
281
+ onMoveColumn={(id, delta) => saveColumns(columnOps.moveColumn(columns, id, delta))}
282
+ onOpen={openPage}
283
+ hidden={hidden}
284
+ onTag={onTag}
285
+ />
286
+ )}
287
+ </Card>
288
+
289
+ <Flex align="center" justify="space-between" gap={3}>
290
+ <Text size={1} muted>
291
+ {summary}
292
+ {pageCount > 1 ? ` · page ${current + 1} / ${pageCount}` : ''}
293
+ </Text>
294
+
295
+ {pageCount > 1 && (
296
+ <Flex gap={2}>
297
+ <PageStep label="Précédent" disabled={current === 0} onClick={() => setPage(current - 1)} />
298
+ <PageStep
299
+ label="Suivant"
300
+ disabled={current >= pageCount - 1}
301
+ onClick={() => setPage(current + 1)}
302
+ />
303
+ </Flex>
304
+ )}
305
+ </Flex>
306
+ </>
307
+ )}
308
+ </Stack>
309
+ )
310
+ }
311
+
312
+ function PageStep(props: {label: string; disabled: boolean; onClick: () => void}) {
313
+ return (
314
+ <button
315
+ type="button"
316
+ disabled={props.disabled}
317
+ onClick={props.onClick}
318
+ style={{
319
+ font: 'inherit',
320
+ fontSize: 13,
321
+ padding: '4px 10px',
322
+ borderRadius: 3,
323
+ border: '1px solid var(--card-border-color, rgba(127,127,127,0.25))',
324
+ background: 'transparent',
325
+ color: 'var(--card-fg-color)',
326
+ opacity: props.disabled ? 0.4 : 1,
327
+ cursor: props.disabled ? 'default' : 'pointer',
328
+ }}
329
+ >
330
+ {props.label}
331
+ </button>
332
+ )
333
+ }
@@ -0,0 +1,53 @@
1
+ import {Box, Button, Flex, TextInput} from '@sanity/ui'
2
+ import {SearchIcon} from '@sanity/icons/Search'
3
+ import {SyncIcon} from '@sanity/icons/Sync'
4
+
5
+ export interface PagesToolbarProps {
6
+ search: string
7
+ onSearch: (value: string) => void
8
+ onRefresh: () => void
9
+ busy: boolean
10
+ /** Résumé à droite : nombre de pages, de liens… */
11
+ summary: string
12
+ }
13
+
14
+ /**
15
+ * Recherche et rafraîchissement, rien de plus.
16
+ *
17
+ * Les filtres par type, statut et langue ont été retirés : le regroupement
18
+ * rend les mêmes distinctions visibles sans rien masquer, et deux mécanismes
19
+ * concurrents pour trancher le même ensemble coûtaient plus qu'ils
20
+ * n'apportaient.
21
+ */
22
+ export function PagesToolbar(props: PagesToolbarProps) {
23
+ return (
24
+ <Flex gap={2} align="center">
25
+ <Box flex={1} style={{minWidth: 200}}>
26
+ <TextInput
27
+ value={props.search}
28
+ onChange={(event) => props.onSearch(event.currentTarget.value)}
29
+ placeholder="Rechercher un titre ou un chemin"
30
+ icon={SearchIcon}
31
+ clearButton={props.search.length > 0}
32
+ onClear={() => props.onSearch('')}
33
+ fontSize={1}
34
+ radius={2}
35
+ />
36
+ </Box>
37
+
38
+ <Box style={{flex: 'none'}}>
39
+ <Button
40
+ icon={SyncIcon}
41
+ mode="bleed"
42
+ tone="default"
43
+ fontSize={1}
44
+ padding={2}
45
+ title="Rafraîchir"
46
+ aria-label="Rafraîchir"
47
+ onClick={props.onRefresh}
48
+ disabled={props.busy}
49
+ />
50
+ </Box>
51
+ </Flex>
52
+ )
53
+ }
@@ -0,0 +1,71 @@
1
+ import {Flex, Text} from '@sanity/ui'
2
+ import {MONO} from '../../ui/tokens'
3
+
4
+ /**
5
+ * Chemin d'une page.
6
+ *
7
+ * C'est l'identifiant que les éditeurs reconnaissent, pas le titre : il est
8
+ * donc rendu en chasse fixe, à pleine opacité, avec le dernier segment mis en
9
+ * avant. Le préfixe reste visible pour situer la page dans le site, mais ne
10
+ * concurrence plus le segment qui la distingue.
11
+ */
12
+ export function PathCell(props: {
13
+ path: string | null
14
+ locale: string | null
15
+ showLocale: boolean
16
+ /** URL publique : le chemin devient alors un lien vers le site. */
17
+ url: string | null
18
+ }) {
19
+ const {path, locale, showLocale, url} = props
20
+
21
+ if (!path) {
22
+ return (
23
+ <Text size={1} muted>
24
+ —
25
+ </Text>
26
+ )
27
+ }
28
+
29
+ const segments = path.split('/').filter(Boolean)
30
+ const last = segments.length > 0 ? segments[segments.length - 1] : null
31
+ const prefix = last ? path.slice(0, path.length - (last as string).length) : path
32
+
33
+ const label = (
34
+ <Text size={1} textOverflow="ellipsis" style={MONO}>
35
+ <span style={{opacity: 0.55}}>{prefix}</span>
36
+ {last && <span style={{fontWeight: 500}}>{last}</span>}
37
+ </Text>
38
+ )
39
+
40
+ return (
41
+ <Flex align="center" gap={2} style={{minWidth: 0}}>
42
+ {/* Le chemin mène au site en ligne ; le titre, lui, mène à
43
+ Presentation. Deux destinations attendues, deux cibles distinctes. */}
44
+ {url ? (
45
+ <a
46
+ href={url}
47
+ target="_blank"
48
+ rel="noreferrer"
49
+ title={`Ouvrir ${url}`}
50
+ style={{color: 'inherit', textDecoration: 'none', minWidth: 0, display: 'block'}}
51
+ onMouseEnter={(event) => {
52
+ event.currentTarget.style.textDecoration = 'underline'
53
+ event.currentTarget.style.textUnderlineOffset = '3px'
54
+ }}
55
+ onMouseLeave={(event) => {
56
+ event.currentTarget.style.textDecoration = 'none'
57
+ }}
58
+ >
59
+ {label}
60
+ </a>
61
+ ) : (
62
+ label
63
+ )}
64
+ {showLocale && locale && (
65
+ <Text size={0} muted style={{flex: 'none', textTransform: 'uppercase', letterSpacing: '0.04em'}}>
66
+ {locale}
67
+ </Text>
68
+ )}
69
+ </Flex>
70
+ )
71
+ }
@@ -0,0 +1,226 @@
1
+ import {useState} from 'react'
2
+ import {Box, Button, Flex, Stack, Text} from '@sanity/ui'
3
+ import {CheckmarkIcon} from '@sanity/icons/Checkmark'
4
+ import {CloseIcon} from '@sanity/icons/Close'
5
+ import {EarthGlobeIcon} from '@sanity/icons/EarthGlobe'
6
+ import {InlinePopover} from '../../ui/Popover'
7
+ import {FieldLabel} from './ViewTabs'
8
+ import {BORDER} from '../../ui/tokens'
9
+ import {
10
+ CUSTOM_ENVIRONMENT_ID,
11
+ PERSPECTIVES,
12
+ type PreviewPerspective,
13
+ } from '../../lib/studioLinks'
14
+ import type {NcfEnvironment} from '../../config/types'
15
+
16
+ export interface PreviewTargetProps {
17
+ environments: readonly NcfEnvironment[]
18
+ environmentId: string | null
19
+ perspective: PreviewPerspective
20
+ onEnvironment: (id: string) => void
21
+ onPerspective: (perspective: PreviewPerspective) => void
22
+ /** Rend `false` si l'adresse n'est pas exploitable. */
23
+ onCustomUrl: (url: string) => boolean
24
+ customUrl: string | null
25
+ }
26
+
27
+ /**
28
+ * Ce que l'aperçu doit montrer : quelle version du site, et quel état du
29
+ * contenu.
30
+ *
31
+ * Deux axes indépendants, et c'est le point. L'environnement porte le code,
32
+ * la perspective porte les données : regarder le contenu de production dans
33
+ * le front d'une branche de recette est justement ce qu'on veut pouvoir
34
+ * faire.
35
+ *
36
+ * Le sélecteur d'environnement n'apparaît que s'il y a un choix à faire : un
37
+ * menu à une entrée occupe la place sans rien offrir.
38
+ */
39
+ export function PreviewTarget(props: PreviewTargetProps) {
40
+ const {environments, environmentId, perspective, onEnvironment, onPerspective} = props
41
+ const {onCustomUrl, customUrl} = props
42
+ const current = environments.find((environment) => environment.id === environmentId)
43
+
44
+ return (
45
+ <Box style={{flex: 'none'}}>
46
+ <FieldLabel>Aperçu</FieldLabel>
47
+ <Flex gap={1} align="center">
48
+ {PERSPECTIVES.map((option) => {
49
+ const active = option.id === perspective
50
+ return (
51
+ <Button
52
+ key={option.id}
53
+ mode={active ? 'default' : 'bleed'}
54
+ tone={active ? 'primary' : 'default'}
55
+ fontSize={1}
56
+ padding={2}
57
+ text={option.label}
58
+ title={option.hint}
59
+ aria-pressed={active}
60
+ onClick={() => onPerspective(option.id)}
61
+ />
62
+ )
63
+ })}
64
+
65
+ <InlinePopover
66
+ width={252}
67
+ trigger={({toggle}) => (
68
+ <Button
69
+ mode="bleed"
70
+ fontSize={1}
71
+ padding={2}
72
+ icon={EarthGlobeIcon}
73
+ text={current?.label ?? 'Environnement'}
74
+ title="Version du site chargée dans l'aperçu"
75
+ onClick={toggle}
76
+ />
77
+ )}
78
+ >
79
+ {({close}) => (
80
+ <Stack gap={1}>
81
+ <Box paddingX={2} paddingTop={2} paddingBottom={1}>
82
+ <Text size={0} muted>
83
+ Version du site. Les données ne changent pas.
84
+ </Text>
85
+ </Box>
86
+
87
+ {environments.map((environment) => (
88
+ <EnvironmentRow
89
+ key={environment.id}
90
+ environment={environment}
91
+ selected={environment.id === environmentId}
92
+ onSelect={() => {
93
+ onEnvironment(environment.id)
94
+ close()
95
+ }}
96
+ onForget={
97
+ environment.id === CUSTOM_ENVIRONMENT_ID ? () => onCustomUrl('') : undefined
98
+ }
99
+ />
100
+ ))}
101
+
102
+ <CustomUrlField
103
+ current={customUrl}
104
+ onSubmit={(url) => {
105
+ const accepted = onCustomUrl(url)
106
+ if (accepted) close()
107
+ return accepted
108
+ }}
109
+ />
110
+ </Stack>
111
+ )}
112
+ </InlinePopover>
113
+ </Flex>
114
+ </Box>
115
+ )
116
+ }
117
+
118
+ function EnvironmentRow(props: {
119
+ environment: NcfEnvironment
120
+ selected: boolean
121
+ onSelect: () => void
122
+ onForget?: () => void
123
+ }) {
124
+ return (
125
+ <Flex
126
+ align="center"
127
+ gap={2}
128
+ padding={2}
129
+ style={{cursor: 'pointer', borderRadius: 3}}
130
+ onMouseEnter={(event) => {
131
+ event.currentTarget.style.background =
132
+ 'var(--card-muted-bg-color, rgba(127,127,127,0.12))'
133
+ }}
134
+ onMouseLeave={(event) => {
135
+ event.currentTarget.style.background = 'transparent'
136
+ }}
137
+ >
138
+ <Box style={{width: 14, flex: 'none'}} onClick={props.onSelect}>
139
+ {props.selected && <CheckmarkIcon style={{fontSize: 14, opacity: 0.7}} />}
140
+ </Box>
141
+ <Stack gap={1} flex={1} style={{minWidth: 0}} onClick={props.onSelect}>
142
+ <Text size={1} textOverflow="ellipsis">
143
+ {props.environment.label}
144
+ </Text>
145
+ {/* L'hôte lève l'ambiguïté entre deux branches au nom voisin. */}
146
+ <Text size={0} muted textOverflow="ellipsis">
147
+ {hostOf(props.environment.url)}
148
+ </Text>
149
+ </Stack>
150
+ {/* Seule l'adresse collée s'oublie : les environnements déclarés
151
+ viennent de la configuration, pas d'ici. */}
152
+ {props.onForget && (
153
+ <Button
154
+ mode="bleed"
155
+ padding={1}
156
+ fontSize={0}
157
+ icon={CloseIcon}
158
+ title="Oublier cette adresse"
159
+ aria-label="Oublier cette adresse"
160
+ onClick={props.onForget}
161
+ />
162
+ )}
163
+ </Flex>
164
+ )
165
+ }
166
+
167
+ /**
168
+ * Adresse quelconque, collée à la volée.
169
+ *
170
+ * Toute adresse qui n'est pas la production en est une autre version : une
171
+ * préversion par branche, parfois par commit. Les déclarer d'avance serait
172
+ * vain, on colle celle qu'on a sous les yeux.
173
+ */
174
+ function CustomUrlField(props: {current: string | null; onSubmit: (url: string) => boolean}) {
175
+ const [value, setValue] = useState('')
176
+ const [rejected, setRejected] = useState(false)
177
+
178
+ const submit = () => {
179
+ if (!value.trim()) return
180
+ setRejected(!props.onSubmit(value))
181
+ }
182
+
183
+ return (
184
+ <Box paddingX={1} paddingBottom={1} paddingTop={2} style={{borderTop: `1px solid ${BORDER}`}}>
185
+ <Stack gap={2}>
186
+ <input
187
+ type="text"
188
+ value={value}
189
+ placeholder={props.current ? 'Autre adresse…' : 'Coller une URL de préversion…'}
190
+ onChange={(event) => {
191
+ setValue(event.currentTarget.value)
192
+ setRejected(false)
193
+ }}
194
+ onKeyDown={(event) => {
195
+ if (event.key === 'Enter') submit()
196
+ }}
197
+ onBlur={submit}
198
+ style={{
199
+ width: '100%',
200
+ font: 'inherit',
201
+ fontSize: 12,
202
+ padding: '6px',
203
+ borderRadius: 3,
204
+ border: `1px solid ${rejected ? 'var(--card-badge-critical-dot-color, #e03131)' : BORDER}`,
205
+ background: 'var(--card-bg-color)',
206
+ color: 'var(--card-fg-color)',
207
+ outline: 'none',
208
+ }}
209
+ />
210
+ {rejected && (
211
+ <Text size={0} style={{color: 'var(--card-badge-critical-dot-color, #e03131)'}}>
212
+ Adresse inexploitable.
213
+ </Text>
214
+ )}
215
+ </Stack>
216
+ </Box>
217
+ )
218
+ }
219
+
220
+ const hostOf = (url: string): string => {
221
+ try {
222
+ return new URL(url).host
223
+ } catch {
224
+ return url
225
+ }
226
+ }