@datagouv/components-next 1.0.2-dev.18 → 1.0.2-dev.180

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 (151) hide show
  1. package/README.md +7 -6
  2. package/assets/main.css +4 -0
  3. package/dist/{Control-DuZJdKV_.js → Control-B9WQxlpJ.js} +1 -1
  4. package/dist/{Datafair.client-Ds3VQrRi.js → Datafair.client-CaxMyNif.js} +9 -9
  5. package/dist/{Event--kp8kMdJ.js → Event-iXDrp-fy.js} +31 -31
  6. package/dist/{Image-34hvypZI.js → Image-mNMBOofs.js} +9 -9
  7. package/dist/ImagePreview.client-CPmCyisP.js +36 -0
  8. package/dist/JsonPreview.client-CKOU-LBs.js +40 -0
  9. package/dist/{Map-BjUnLyj8.js → Map-BfqKMw0S.js} +1739 -1599
  10. package/dist/{MapContainer.client-B2BijMx5.js → MapContainer.client-IGYJWP5m.js} +41 -42
  11. package/dist/{OSM-s40W6sQ2.js → OSM-CcrUhItr.js} +15 -23
  12. package/dist/{PdfPreview.client-DJBMzrlC.js → PdfPreview.client-csUebU3A.js} +835 -856
  13. package/dist/Pmtiles.client-CLq7UHBg.js +26333 -0
  14. package/dist/PreviewWrapper.vue_vue_type_script_setup_true_lang-DeoHZXW1.js +60 -0
  15. package/dist/{ScaleLine-KW-nXqp3.js → ScaleLine-VGQ7nkMS.js} +2 -2
  16. package/dist/{Tile-DbNFNPfU.js → Tile-CSpn0Ca8.js} +160 -163
  17. package/dist/{TileImage-BsXBxMtq.js → TileImage-CpbaEFwd.js} +143 -131
  18. package/dist/{View-BR92hTWP.js → View-BYBpt-AU.js} +483 -422
  19. package/dist/XmlPreview.client-C1toAbQ0.js +34 -0
  20. package/dist/{common-PJfpC179.js → common-BoeTUnDZ.js} +52 -52
  21. package/dist/components-next.css +1 -52
  22. package/dist/components-next.js +193 -149
  23. package/dist/components.css +2 -2
  24. package/dist/{index-BFQX7Ccz.js → index-CaUlhl3k.js} +21842 -15810
  25. package/dist/{leaflet-src-7m1mB8LI.js → leaflet-src-ByYGrf8H.js} +185 -187
  26. package/dist/{main-vqhkVhVS.js → main-DD4ieUAo.js} +41500 -73223
  27. package/dist/{proj-DsetBcW7.js → proj-DxGbobp7.js} +662 -626
  28. package/dist/{text-clamp.esm-B5kW_XMt.js → text-clamp.esm-DVseBqZZ.js} +4 -4
  29. package/dist/{tilecoord-Db24Px13.js → tilecoord-DvX7WWiA.js} +273 -264
  30. package/dist/{vue3-json-viewer-BXwup7nO.js → vue3-json-viewer-CJLQFzXZ.js} +10 -16
  31. package/dist/{vue3-xml-viewer.common-BcNJo35o.js → vue3-xml-viewer.common-B1KPK4L4.js} +16 -16
  32. package/package.json +47 -38
  33. package/src/chart.ts +5 -0
  34. package/src/components/ActivityList/ActivityList.vue +3 -2
  35. package/src/components/AppLink.vue +3 -0
  36. package/src/components/BannerAction.vue +6 -2
  37. package/src/components/Chart/ChartViewer.vue +320 -0
  38. package/src/components/Chart/ChartViewerWrapper.vue +182 -0
  39. package/src/components/CopyButton.vue +6 -2
  40. package/src/components/DataserviceCard.vue +9 -0
  41. package/src/components/DataserviceQuality.vue +82 -0
  42. package/src/components/DataserviceQualityInline.vue +31 -0
  43. package/src/components/DataserviceQualityTooltipContent.vue +79 -0
  44. package/src/components/DatasetCard.vue +9 -4
  45. package/src/components/DatasetQuality.vue +11 -11
  46. package/src/components/DatasetQualityInline.vue +2 -2
  47. package/src/components/DatasetQualityTooltipContent.vue +1 -1
  48. package/src/components/Form/Listbox.vue +101 -0
  49. package/src/components/Form/SchemaSelect.vue +2 -0
  50. package/src/components/InfiniteLoader.vue +53 -0
  51. package/src/components/ObjectCardHeader.vue +11 -4
  52. package/src/components/OpenApiViewer/ContentTypeSelect.vue +48 -0
  53. package/src/components/OpenApiViewer/EndpointRequest.vue +164 -0
  54. package/src/components/OpenApiViewer/EndpointResponses.vue +149 -0
  55. package/src/components/OpenApiViewer/OpenApiViewer.vue +308 -0
  56. package/src/components/OpenApiViewer/SchemaPanel.vue +53 -0
  57. package/src/components/OpenApiViewer/SchemaTree.vue +77 -0
  58. package/src/components/OpenApiViewer/openapi.ts +150 -0
  59. package/src/components/OrganizationNameWithCertificate.vue +3 -2
  60. package/src/components/Pagination.vue +8 -5
  61. package/src/components/RadioInput.vue +7 -2
  62. package/src/components/ResourceAccordion/DataStructure.vue +11 -33
  63. package/src/components/ResourceAccordion/Datafair.client.vue +1 -1
  64. package/src/components/ResourceAccordion/Downloads.vue +160 -0
  65. package/src/components/ResourceAccordion/ImagePreview.client.vue +48 -0
  66. package/src/components/ResourceAccordion/JsonPreview.client.vue +23 -104
  67. package/src/components/ResourceAccordion/MapContainer.client.vue +2 -11
  68. package/src/components/ResourceAccordion/Metadata.vue +1 -2
  69. package/src/components/ResourceAccordion/PdfPreview.client.vue +58 -97
  70. package/src/components/ResourceAccordion/PdfSkeleton.vue +44 -0
  71. package/src/components/ResourceAccordion/Pmtiles.client.vue +28 -13
  72. package/src/components/ResourceAccordion/Preview.vue +11 -11
  73. package/src/components/ResourceAccordion/PreviewWrapper.vue +89 -0
  74. package/src/components/ResourceAccordion/ResourceAccordion.vue +23 -114
  75. package/src/components/ResourceAccordion/XmlPreview.client.vue +16 -98
  76. package/src/components/ResourceExplorer/ResourceExplorer.vue +102 -210
  77. package/src/components/ResourceExplorer/ResourceExplorerHeader.vue +74 -0
  78. package/src/components/ResourceExplorer/ResourceExplorerSidebar.vue +103 -71
  79. package/src/components/ResourceExplorer/ResourceExplorerViewer.vue +143 -291
  80. package/src/components/ResourceExplorer/ResourceMainAction.vue +240 -0
  81. package/src/components/ResourceExplorer/ResourceSelector.vue +51 -0
  82. package/src/components/ResourceExplorer/ResourceViewerHeader.vue +115 -0
  83. package/src/components/ResourceExplorer/ResourceViewerSkeleton.vue +94 -0
  84. package/src/components/ResourceListItem.vue +154 -0
  85. package/src/components/ReuseCard.vue +14 -6
  86. package/src/components/ReuseDetails.vue +2 -2
  87. package/src/components/ReuseHorizontalCard.vue +2 -2
  88. package/src/components/SchemaCard.vue +10 -1
  89. package/src/components/Search/Filter/AccessTypeFilter.vue +2 -2
  90. package/src/components/Search/GlobalSearch.vue +219 -117
  91. package/src/components/Search/SearchInput.vue +5 -4
  92. package/src/components/TabularExplorer/TabularActiveFilters.vue +79 -0
  93. package/src/components/TabularExplorer/TabularCell.vue +50 -0
  94. package/src/components/TabularExplorer/TabularCellPopover.vue +170 -0
  95. package/src/components/TabularExplorer/TabularColumnsMenu.vue +112 -0
  96. package/src/components/TabularExplorer/TabularExplorer.vue +299 -0
  97. package/src/components/TabularExplorer/TabularFilterContent.vue +362 -0
  98. package/src/components/TabularExplorer/TabularFilterPopover.vue +106 -0
  99. package/src/components/TabularExplorer/TabularMobileFilterButton.vue +21 -0
  100. package/src/components/TabularExplorer/TabularMobileFilters.vue +150 -0
  101. package/src/components/TabularExplorer/TabularRowsInfo.vue +31 -0
  102. package/src/components/TabularExplorer/TabularSkeleton.vue +92 -0
  103. package/src/components/TabularExplorer/TabularTable.vue +481 -0
  104. package/src/components/TabularExplorer/TabularToolbar.vue +25 -0
  105. package/src/components/TabularExplorer/types.ts +81 -0
  106. package/src/components/TabularExplorer/useColumnMetadata.ts +98 -0
  107. package/src/components/TabularExplorer/useTabularContext.ts +82 -0
  108. package/src/composables/useActiveDescendant.ts +5 -0
  109. package/src/composables/useDatasetResources.ts +164 -0
  110. package/src/composables/useHasTabularData.ts +15 -1
  111. package/src/composables/useMetrics.ts +1 -1
  112. package/src/composables/useResizable.ts +46 -0
  113. package/src/composables/useResourceCapabilities.ts +47 -21
  114. package/src/composables/useSearchFilter.ts +120 -0
  115. package/src/composables/useStableQueryParams.ts +38 -6
  116. package/src/composables/useTabularProfile.ts +70 -0
  117. package/src/config.ts +21 -3
  118. package/src/functions/activities.ts +3 -3
  119. package/src/functions/api.ts +20 -42
  120. package/src/functions/api.types.ts +1 -0
  121. package/src/functions/charts.ts +99 -0
  122. package/src/functions/datasets.ts +0 -17
  123. package/src/functions/dates.ts +3 -2
  124. package/src/functions/metrics.ts +6 -4
  125. package/src/functions/resources.ts +136 -1
  126. package/src/functions/schemas.ts +27 -0
  127. package/src/functions/tabular.ts +214 -0
  128. package/src/functions/tabularApi.ts +96 -11
  129. package/src/main.ts +117 -14
  130. package/src/types/dataservices.ts +17 -0
  131. package/src/types/organizations.ts +10 -0
  132. package/src/types/pages.ts +0 -5
  133. package/src/types/posts.ts +2 -2
  134. package/src/types/reports.ts +5 -1
  135. package/src/types/resources.ts +0 -1
  136. package/src/types/reuses.ts +12 -1
  137. package/src/types/search.ts +63 -1
  138. package/src/types/site.ts +5 -3
  139. package/src/types/ui.ts +2 -0
  140. package/src/types/users.ts +2 -1
  141. package/src/types/visualizations.ts +93 -0
  142. package/assets/swagger-themes/newspaper.css +0 -1670
  143. package/dist/JsonPreview.client-CYxmz0yV.js +0 -72
  144. package/dist/Pmtiles.client-C_hvRDuy.js +0 -25185
  145. package/dist/Swagger.client-B4y0hXME.js +0 -4
  146. package/dist/XmlPreview.client-LETEfNBH.js +0 -64
  147. package/src/components/ResourceAccordion/Swagger.client.vue +0 -48
  148. package/src/functions/pagination.ts +0 -9
  149. /package/src/components/{DatasetQualityItem.vue → QualityItem.vue} +0 -0
  150. /package/src/components/{DatasetQualityItemWarning.vue → QualityItemWarning.vue} +0 -0
  151. /package/src/components/{DatasetQualityScore.vue → QualityScore.vue} +0 -0
@@ -0,0 +1,82 @@
1
+ import type { Component, ComputedRef, InjectionKey, Ref } from 'vue'
2
+ import { inject, provide } from 'vue'
3
+ import type {
4
+ ColumnFilters,
5
+ ColumnType,
6
+ SortConfig,
7
+ TabularColumnProfile,
8
+ TabularDataResponse,
9
+ TabularRow,
10
+ } from './types'
11
+
12
+ export type ActiveFilter = {
13
+ column: string
14
+ label: string
15
+ }
16
+
17
+ export type ColumnDisplay = {
18
+ icon: Component
19
+ label: string
20
+ }
21
+
22
+ // Data + cross-cutting state shared by the tabular explorer's parts (toolbar, header
23
+ // filters, table). Provided by <TabularExplorer>, injected by children so they can be
24
+ // arranged freely without prop-drilling.
25
+ //
26
+ // NOT here — kept local to whoever renders it, because nothing else needs it:
27
+ // - column widths / resize, cell popover, mobile row expansion → TabularTable
28
+ // - mobile filter sheet's expanded column → TabularMobileFilters
29
+ export type TabularContext = {
30
+ // Data & pagination (the parent owns the fetch, children just render it)
31
+ tableData: Ref<TabularDataResponse | null>
32
+ totalLines: ComputedRef<number>
33
+ allRows: Ref<TabularRow[]>
34
+ hasMore: Ref<boolean>
35
+ loadNextPage: () => Promise<void>
36
+ // A sort / filter / search change is refetching while the previous rows are
37
+ // still on screen.
38
+ isRefreshing: ComputedRef<boolean>
39
+
40
+ // Sort & filters
41
+ sort: Ref<SortConfig | null>
42
+ filters: Ref<Record<string, ColumnFilters>>
43
+ activeFilters: ComputedRef<ActiveFilter[]>
44
+ removeFilter: (column: string) => void
45
+ clearAllFilters: () => void
46
+ hasFilterForColumn: (col: string) => boolean
47
+
48
+ // Columns visibility
49
+ allColumns: ComputedRef<string[]>
50
+ visibleColumns: Ref<Set<string>>
51
+ displayedColumns: ComputedRef<string[]>
52
+ hiddenCount: ComputedRef<number>
53
+ toggleColumn: (col: string) => void
54
+ showAllColumns: () => void
55
+ hideAllColumns: () => void
56
+ selectOnlyColumn: (col: string) => void
57
+
58
+ // Mobile filter sheet open/close (button lives in the toolbar, sheet elsewhere)
59
+ mobileFilterOpen: Ref<boolean>
60
+
61
+ // Column metadata helpers (pure derivations of the profile)
62
+ columnTypesMap: ComputedRef<Record<string, ColumnType>>
63
+ getColumnType: (col: string) => ColumnType
64
+ getColumnProfile: (col: string) => TabularColumnProfile | null
65
+ getColumnDisplay: (col: string) => ColumnDisplay
66
+ getNullPercent: (col: string) => string
67
+ getBooleanCounts: (col: string) => { trueCount: number, falseCount: number }
68
+ }
69
+
70
+ const TABULAR_CONTEXT_KEY: InjectionKey<TabularContext> = Symbol('tabular-context')
71
+
72
+ export function provideTabularContext(context: TabularContext) {
73
+ provide(TABULAR_CONTEXT_KEY, context)
74
+ }
75
+
76
+ export function useTabularContext(): TabularContext {
77
+ const context = inject(TABULAR_CONTEXT_KEY)
78
+ if (!context) {
79
+ throw new Error('useTabularContext() must be used inside a <TabularExplorer>')
80
+ }
81
+ return context
82
+ }
@@ -60,23 +60,28 @@ export function useActiveDescendant<T extends Option>(options: MaybeRefOrGetter<
60
60
 
61
61
  function handleKeyPressForActiveDescendant(key: KeyboardEvent, alreadyMovedDown = false) {
62
62
  switch (key.key as CommonKeyboardKeys) {
63
+ // An arrow that moves the active option must not also scroll the page behind it
63
64
  case 'ArrowDown':
64
65
  if (direction === 'vertical' && !alreadyMovedDown && !key.altKey) {
66
+ key.preventDefault()
65
67
  activateNextOption()
66
68
  }
67
69
  break
68
70
  case 'ArrowUp':
69
71
  if (direction === 'vertical') {
72
+ key.preventDefault()
70
73
  activatePreviousOption()
71
74
  }
72
75
  break
73
76
  case 'ArrowLeft':
74
77
  if (direction === 'horizontal') {
78
+ key.preventDefault()
75
79
  activatePreviousOption()
76
80
  }
77
81
  break
78
82
  case 'ArrowRight':
79
83
  if (direction === 'horizontal' && !alreadyMovedDown && !key.altKey) {
84
+ key.preventDefault()
80
85
  activateNextOption()
81
86
  }
82
87
  break
@@ -0,0 +1,164 @@
1
+ import { computed, ref, toValue, watch, type MaybeRefOrGetter, type Ref } from 'vue'
2
+ import { useRouteQuery } from '@vueuse/router'
3
+ import { useComponentsConfig } from '../config'
4
+ import { useDebouncedRef } from './useDebouncedRef'
5
+ import { useFetch } from '../functions/api'
6
+ import { RESOURCE_EXPLORER_PAGE_SIZE, RESOURCE_TYPE } from '../functions/resources'
7
+ import type { PaginatedArray } from '../types/api'
8
+ import type { DatasetV2 } from '../types/datasets'
9
+ import type { Resource, ResourceGroup, ResourceType } from '../types/resources'
10
+
11
+ // Fetches a dataset's resources grouped by type (paginated per type, searchable)
12
+ // and derives the currently selected resource from the `resource_id` query param.
13
+ // Shared by the dataset page and the explore page so the left navigation behaves
14
+ // identically in both.
15
+ export async function useDatasetResources(datasetGetter: MaybeRefOrGetter<DatasetV2>) {
16
+ const config = useComponentsConfig()
17
+
18
+ const search = ref('')
19
+ const { debounced: searchDebounced, flush } = useDebouncedRef(search, config.searchDebounce ?? 300)
20
+
21
+ const datasetId = computed(() => toValue(datasetGetter).id)
22
+ const url = computed(() => `/api/2/datasets/${datasetId.value}/resources/`)
23
+
24
+ const makeParams = (type: ResourceType) => computed(() => ({
25
+ type,
26
+ page_size: RESOURCE_EXPLORER_PAGE_SIZE,
27
+ q: searchDebounced.value || undefined,
28
+ }))
29
+
30
+ // Evaluated once at setup (before any search) — never changes afterwards
31
+ const hasAnyResources = computed(() => toValue(datasetGetter).resources.total > 0)
32
+
33
+ const extraResourcesByType: Ref<Resource[]>[] = RESOURCE_TYPE.map(() => ref<Resource[]>([]))
34
+ const pageByType: Ref<number>[] = RESOURCE_TYPE.map(() => ref(1))
35
+
36
+ watch(searchDebounced, () => {
37
+ for (let i = 0; i < RESOURCE_TYPE.length; i++) {
38
+ extraResourcesByType[i]!.value = []
39
+ pageByType[i]!.value = 1
40
+ }
41
+ })
42
+
43
+ // Separate useFetch for loadMore, initialized with immediate: false so it doesn't
44
+ // fetch until execute() is called from the event handler.
45
+ const loadMoreType = ref<ResourceType>('main')
46
+ const loadMorePage = ref(1)
47
+ const loadMoreParams = computed(() => ({
48
+ type: loadMoreType.value,
49
+ page_size: RESOURCE_EXPLORER_PAGE_SIZE,
50
+ page: loadMorePage.value,
51
+ q: searchDebounced.value || undefined,
52
+ }))
53
+
54
+ const resourceIdQuery = useRouteQuery<string | undefined>('resource_id')
55
+ const initialResourceId = resourceIdQuery.value
56
+
57
+ // Vue rule: composables must be called synchronously, before any `await` — `inject()`
58
+ // needs the active component instance, which a plain .ts composable loses after its
59
+ // first await (documented in useTabularProfile.ts). The package's `useFetch` calls
60
+ // `useComponentsConfig()` (an inject) on every call, so we kick off every request
61
+ // up-front, then await them together. This is also the idiomatic Nuxt parallel-fetch.
62
+ const typeFetches = RESOURCE_TYPE.map(type =>
63
+ useFetch<PaginatedArray<Resource>>(url, {
64
+ params: makeParams(type),
65
+ // Only main is server-rendered; the rest hydrate client-side to keep SSR light.
66
+ server: type === 'main',
67
+ }),
68
+ )
69
+ const loadMoreFetch = useFetch<PaginatedArray<Resource>>(url, { params: loadMoreParams, immediate: false, watch: false })
70
+ // The resource pointed at by `resource_id` (SSR / deep link) may live beyond the first
71
+ // page of its type group, so it wouldn't be in flatResources — fetch it directly.
72
+ const fetchedResourceFetch = initialResourceId
73
+ ? useFetch<Resource>(`/api/1/datasets/${datasetId.value}/resources/${initialResourceId}/`)
74
+ : null
75
+
76
+ const typeResults = await Promise.all(typeFetches)
77
+ const { data: loadMoreData, execute: executeLoadMore } = await loadMoreFetch
78
+ const fetchedResource = fetchedResourceFetch ? (await fetchedResourceFetch).data : ref<Resource | null>(null)
79
+
80
+ const rawDataByType = typeResults.map(result => result.data)
81
+
82
+ // Which type group is currently loading its next page. A single loadMoreFetch is
83
+ // shared across types, so we track the type here to show the spinner on the right
84
+ // group's "Charger plus…" button.
85
+ const loadingType = ref<ResourceType | null>(null)
86
+
87
+ const loadMore = async (type: ResourceType) => {
88
+ const index = RESOURCE_TYPE.indexOf(type)
89
+ if (index === -1) return
90
+ const pageRef = pageByType[index]!
91
+ const extraRef = extraResourcesByType[index]!
92
+ pageRef.value++
93
+
94
+ loadMoreType.value = type
95
+ loadMorePage.value = pageRef.value
96
+ loadingType.value = type
97
+ try {
98
+ await executeLoadMore()
99
+
100
+ if (loadMoreData.value) {
101
+ extraRef.value = [...extraRef.value, ...loadMoreData.value.data]
102
+ }
103
+ }
104
+ finally {
105
+ loadingType.value = null
106
+ }
107
+ }
108
+
109
+ const groups = computed<ResourceGroup[]>(() => {
110
+ return RESOURCE_TYPE
111
+ .map((type, index) => {
112
+ const rawData = rawDataByType[index]!
113
+ const extraData = extraResourcesByType[index]!
114
+ return {
115
+ type: type as ResourceType,
116
+ total: rawData.value?.total ?? 0,
117
+ items: [...(rawData.value?.data ?? []), ...extraData.value],
118
+ }
119
+ })
120
+ .filter(group => group.items.length > 0)
121
+ })
122
+
123
+ const flatResources = computed(() => groups.value.flatMap(g => g.items))
124
+
125
+ // The URL is the single source of truth for the selection: no ref to keep in
126
+ // sync, navigation is done with plain links that change `resource_id`.
127
+ let lastShown: Resource | null = null
128
+ const remember = (resource: Resource | null) => {
129
+ if (resource) lastShown = resource
130
+ return resource
131
+ }
132
+
133
+ const selectedResource = computed<Resource | null>(() => {
134
+ const wantedId = resourceIdQuery.value
135
+ const fromList = flatResources.value.find(r => r.id === wantedId)
136
+ if (fromList) return remember(fromList)
137
+ // `fetchedResource` answers for `initialResourceId` only: it holds that one
138
+ // resource, so using it for any other id would show something the URL doesn't
139
+ // point at.
140
+ if (wantedId && wantedId === initialResourceId) return remember(fetchedResource.value)
141
+ // A search that matches nothing narrows the navigation, it doesn't unload the
142
+ // viewer — keep showing what we had, which is the dataset's first resource when
143
+ // nothing has been clicked yet.
144
+ return remember(flatResources.value[0] ?? null) ?? lastShown
145
+ })
146
+
147
+ function updateSearch(newSearch: string) {
148
+ search.value = newSearch
149
+ // Only a reset skips the debounce: typing must stay debounced, since each
150
+ // change fires one request per resource type.
151
+ if (!newSearch) flush()
152
+ }
153
+
154
+ return {
155
+ groups,
156
+ flatResources,
157
+ hasAnyResources,
158
+ selectedResource,
159
+ loadMore,
160
+ loadingType,
161
+ search,
162
+ updateSearch,
163
+ }
164
+ }
@@ -1,14 +1,28 @@
1
1
  import { useComponentsConfig } from '../config'
2
+ import { hasTabularParsingError } from '../functions/resources'
2
3
  import type { Resource } from '../types/resources'
3
4
 
5
+ /**
6
+ * Composable to determine if a resource has tabular data.
7
+ * This is used to show the "Données" tab for tabular files AND the "Structure des données" tab (for tabular data structure).
8
+ *
9
+ * @returns A function to check if a resource has tabular data.
10
+ */
4
11
  export const useHasTabularData = () => {
5
12
  const config = useComponentsConfig()
6
13
 
7
14
  return (resource: Resource) => {
15
+ // Reject resources whose source URL last check failed (>= 400):
16
+ // the tabular-api purges its parquet when the source dies, but
17
+ // `parsing_table` may still be set — leading to a 404 on fetch.
18
+ const checkStatus = resource.extras['check:status']
19
+ const sourceUnreachable = typeof checkStatus === 'number' && checkStatus >= 400
20
+
8
21
  return (
9
22
  config.tabularApiUrl
10
23
  && resource.extras['analysis:parsing:parsing_table']
11
- && !resource.extras['analysis:parsing:error']
24
+ && !hasTabularParsingError(resource)
25
+ && !sourceUnreachable
12
26
  && (config.tabularAllowRemote || resource.filetype === 'file')
13
27
  )
14
28
  }
@@ -13,6 +13,6 @@ export function useMetrics() {
13
13
  getDatasetMetrics: (datasetId: string) => getDatasetMetrics(datasetId, config.metricsApiUrl!),
14
14
  getDataserviceMetrics: (dataserviceId: string) => getDataserviceMetrics(dataserviceId, config.metricsApiUrl!),
15
15
  getReuseMetrics: (reuseId: string) => getReuseMetrics(reuseId, config.metricsApiUrl!),
16
- createDatasetsForOrganizationMetricsUrl: (organizationId: string) => createDatasetsForOrganizationMetricsUrl(organizationId, config.metricsApiUrl!, config.apiBase),
16
+ createDatasetsForOrganizationMetricsUrl: (organizationId: string) => createDatasetsForOrganizationMetricsUrl(organizationId, config.metricsApiUrl!, config.apiBase, config.$fetch),
17
17
  }
18
18
  }
@@ -0,0 +1,46 @@
1
+ import { ref } from 'vue'
2
+ import { useEventListener } from '@vueuse/core'
3
+
4
+ type UseResizableOptions = {
5
+ initialWidth: number
6
+ minWidth: number
7
+ maxWidth: number
8
+ }
9
+
10
+ // Drag-to-resize a horizontal panel. Returns the reactive width, a `resizing`
11
+ // flag (to disable width transitions while dragging) and a `startResize` handler
12
+ // to bind on a drag handle's `mousedown`. Encapsulates the drag math, clamping and
13
+ // the temporary body cursor / text-selection lock. VueUse has no ready-made panel
14
+ // resize (useResizeObserver only observes size), so we build it on `useEventListener`
15
+ // which handles listener cleanup and SSR for us.
16
+ export function useResizable({ initialWidth, minWidth, maxWidth }: UseResizableOptions) {
17
+ const width = ref(initialWidth)
18
+ const resizing = ref(false)
19
+ let startX = 0
20
+ let startWidth = 0
21
+
22
+ const clamp = (value: number) => Math.min(maxWidth, Math.max(minWidth, Math.round(value)))
23
+
24
+ function startResize(event: MouseEvent) {
25
+ event.preventDefault()
26
+ startX = event.clientX
27
+ startWidth = width.value
28
+ resizing.value = true
29
+ document.body.style.userSelect = 'none'
30
+ document.body.style.cursor = 'col-resize'
31
+ }
32
+
33
+ useEventListener('mousemove', (event: MouseEvent) => {
34
+ if (!resizing.value) return
35
+ width.value = clamp(startWidth + event.clientX - startX)
36
+ })
37
+
38
+ useEventListener('mouseup', () => {
39
+ if (!resizing.value) return
40
+ resizing.value = false
41
+ document.body.style.userSelect = ''
42
+ document.body.style.cursor = ''
43
+ })
44
+
45
+ return { width, resizing, startResize }
46
+ }
@@ -1,16 +1,21 @@
1
- import { computed, toValue, type MaybeRefOrGetter } from 'vue'
1
+ import { computed, type MaybeRefOrGetter, toValue } from 'vue'
2
2
  import { useComponentsConfig } from '../config'
3
- import { useTranslation } from './useTranslation'
4
- import { useHasTabularData } from './useHasTabularData'
5
- import { detectOgcService } from '../functions/resources'
6
3
  import { isOrganizationCertified } from '../functions/organizations'
7
- import type { Resource, WfsMetadata } from '../types/resources'
8
- import type { Dataset, DatasetV2 } from '../types/datasets'
9
4
  import { getWfsExportFormats } from '../functions/resourceCapabilities'
5
+ import { detectOgcService, getParsingErrorMessage, getParsingErrorStep, isImagePreviewFormat } from '../functions/resources'
6
+ import type { Dataset, DatasetV2 } from '../types/datasets'
7
+ import type { Resource, WfsMetadata } from '../types/resources'
8
+ import { useHasTabularData } from './useHasTabularData'
9
+ import { useTranslation } from './useTranslation'
10
10
 
11
11
  const GENERATED_FORMATS = ['parquet', 'pmtiles', 'geojson']
12
12
  const URL_FORMATS = ['url', 'doi', 'www:link', 'www:link-1.0-http--link', 'www:link-1.0-http--partners', 'www:link-1.0-http--related', 'www:link-1.0-http--samples']
13
13
 
14
+ // Which preview the data tab shows. Single source of truth: the viewer renders it and
15
+ // the skeleton picks the matching placeholder shape, so each holding its own copy of
16
+ // this precedence would let the two drift apart.
17
+ export type PreviewKind = 'json' | 'pdf' | 'xml' | 'image' | 'datafair' | 'openapi' | 'tabular' | 'unavailable'
18
+
14
19
  export function useResourceCapabilities(
15
20
  resource: MaybeRefOrGetter<Resource>,
16
21
  dataset: MaybeRefOrGetter<Dataset | DatasetV2>,
@@ -19,11 +24,6 @@ export function useResourceCapabilities(
19
24
  const { t } = useTranslation()
20
25
  const checkTabularData = useHasTabularData()
21
26
 
22
- const hasPreview = computed(() => {
23
- const format = toValue(resource).format?.toLowerCase()
24
- return format === 'json' || format === 'pdf' || format === 'xml'
25
- })
26
-
27
27
  const hasTabularData = computed(() => {
28
28
  const r = toValue(resource)
29
29
  return checkTabularData(r)
@@ -49,6 +49,11 @@ export function useResourceCapabilities(
49
49
  const ogcService = computed(() => detectOgcService(toValue(resource)))
50
50
  const ogcWms = computed(() => ogcService.value === 'wms')
51
51
 
52
+ // The map is built from a pmtiles export; when that export fails we still want
53
+ // to show the Carte tab, but with the reason it could not be generated.
54
+ const hasPmtilesError = computed(() => getParsingErrorStep(toValue(resource)) === 'pmtiles_export')
55
+ const pmtilesError = computed(() => hasPmtilesError.value ? getParsingErrorMessage(toValue(resource)) : null)
56
+
52
57
  const generatedFormats = computed(() => {
53
58
  const r = toValue(resource)
54
59
  const formats = GENERATED_FORMATS
@@ -81,43 +86,64 @@ export function useResourceCapabilities(
81
86
 
82
87
  const isResourceUrl = computed(() => URL_FORMATS.includes(toValue(resource).format))
83
88
 
89
+ // A dedicated preview always wins over the interactive table: a PDF that also
90
+ // carries a parsing table is a PDF first.
91
+ const previewKind = computed<PreviewKind>(() => {
92
+ const format = toValue(resource).format?.toLowerCase()
93
+ if (format === 'json') return 'json'
94
+ if (format === 'pdf') return 'pdf'
95
+ if (format === 'xml') return 'xml'
96
+ if (isImagePreviewFormat(format)) return 'image'
97
+ if (hasDatafairPreview.value) return 'datafair'
98
+ if (hasOpenAPIPreview.value) return 'openapi'
99
+ if (hasTabularData.value) return 'tabular'
100
+ return 'unavailable'
101
+ })
102
+
84
103
  const tabsOptions = computed(() => {
85
104
  const r = toValue(resource)
86
105
  const options = []
87
106
 
88
- if (hasTabularData.value) {
89
- options.push({ key: 'data', label: t('Données') })
107
+ const dataTab = { key: 'data', label: hasTabularData.value ? t('Données') : t('Aperçu') }
108
+ const mapTab = { key: 'map', label: t('Carte') }
109
+ const hasMap = hasPmtiles.value || ogcWms.value
110
+
111
+ // The map is the most visual preview: when it is available, show it first.
112
+ // When its generation failed, keep the data preview first and surface the
113
+ // Carte tab (with its error) right after.
114
+ if (hasMap) {
115
+ options.push(mapTab, dataTab)
116
+ }
117
+ else if (hasPmtilesError.value) {
118
+ options.push(dataTab, mapTab)
90
119
  }
91
120
  else {
92
- options.push({ key: 'data', label: t('Aperçu') })
121
+ options.push(dataTab)
93
122
  }
94
123
 
95
124
  if (hasTabularData.value) {
96
125
  options.push({ key: 'data-structure', label: t('Structure des données') })
97
126
  }
98
127
 
99
- if (hasPmtiles.value || ogcWms.value) {
100
- options.push({ key: 'map', label: t('Carte') })
101
- }
102
-
103
128
  if (r.description) {
104
129
  options.push({ key: 'description', label: t('Description') })
105
130
  }
106
131
 
107
132
  options.push({ key: 'metadata', label: t('Métadonnées') })
108
- options.push({ key: 'downloads', label: t('Téléchargements') })
109
133
 
110
134
  if (hasTabularData.value) {
111
- options.push({ key: 'swagger', label: t('Swagger') })
135
+ options.push({ key: 'api', label: t('API') })
112
136
  }
113
137
 
114
138
  return options
115
139
  })
116
140
 
117
141
  return {
118
- hasPreview,
142
+ previewKind,
119
143
  hasTabularData,
120
144
  hasPmtiles,
145
+ hasPmtilesError,
146
+ pmtilesError,
121
147
  hasDatafairPreview,
122
148
  hasOpenAPIPreview,
123
149
  ogcService,
@@ -0,0 +1,120 @@
1
+ import { type InjectionKey, type Ref, inject, onMounted, onScopeDispose } from 'vue'
2
+ import { useRoute, useRouter } from 'vue-router'
3
+ import { useRouteQuery } from '@vueuse/router'
4
+ import type { SearchTypeConfig } from '../types/search'
5
+
6
+ export function configKey(c: SearchTypeConfig): string {
7
+ return c.key ?? c.class
8
+ }
9
+
10
+ export interface CustomFilterEntry {
11
+ apiParam: string
12
+ ref: Ref<string | undefined>
13
+ defaultValue: string | undefined
14
+ typeKeys?: string[] // undefined = applies to all types
15
+ }
16
+
17
+ export interface SearchFilterContext {
18
+ register(urlParam: string, entry: CustomFilterEntry): void
19
+ unregister(urlParam: string): void
20
+ }
21
+
22
+ export function isCustomFilterActive(entry: CustomFilterEntry): boolean {
23
+ const v = entry.ref.value
24
+ return v !== undefined && v !== null && v !== '' && v !== entry.defaultValue
25
+ }
26
+
27
+ export function forEachActiveCustomFilter(
28
+ registry: Map<string, CustomFilterEntry>,
29
+ apply: (apiParam: string, value: string) => void,
30
+ typeKey?: string,
31
+ ): void {
32
+ for (const entry of registry.values()) {
33
+ if (!isCustomFilterActive(entry)) continue
34
+ if (typeKey && entry.typeKeys && !entry.typeKeys.includes(typeKey)) continue
35
+ apply(entry.apiParam, String(entry.ref.value))
36
+ }
37
+ }
38
+
39
+ export const searchFilterContextKey: InjectionKey<SearchFilterContext>
40
+ = Symbol('SearchFilterContext')
41
+
42
+ export interface UseSearchFilterOptions {
43
+ /** The API parameter name to map this filter to. Defaults to the urlParam. */
44
+ apiParam?: string
45
+ /** Default value when not present in URL. Defaults to undefined. */
46
+ defaultValue?: string
47
+ /** One or more type config keys this filter applies to. Undefined means all types. */
48
+ typeKeys?: string | string[]
49
+ }
50
+
51
+ /**
52
+ * Registers a custom filter with the parent GlobalSearch component.
53
+ *
54
+ * Must be called inside a component rendered within GlobalSearch's
55
+ * `#custom-filters-top` or `#custom-filters-bottom` slot.
56
+ *
57
+ * @param urlParam - The URL query parameter name (e.g. 'theme' → `?theme=value`)
58
+ * @param options - Optional: `apiParam` to map to a different API param (e.g. 'tag'), `defaultValue`
59
+ * @returns A reactive ref bound to the URL parameter, suitable for v-model
60
+ *
61
+ * @example
62
+ * ```vue
63
+ * <script setup>
64
+ * import { useSearchFilter } from '@datagouv/components-next'
65
+ * // URL: ?theme=environment → API: ?tag=environment
66
+ * const value = useSearchFilter('theme', { apiParam: 'tag' })
67
+ * </script>
68
+ * ```
69
+ */
70
+ export function useSearchFilter(
71
+ urlParam: string,
72
+ options: UseSearchFilterOptions = {},
73
+ ): Ref<string | undefined> {
74
+ const context = inject(searchFilterContextKey)
75
+ if (!context) {
76
+ throw new Error(
77
+ `useSearchFilter("${urlParam}") must be used inside a <GlobalSearch> component.`,
78
+ )
79
+ }
80
+
81
+ const { apiParam = urlParam, defaultValue = undefined, typeKeys } = options
82
+ const normalizedTypeKeys = typeKeys
83
+ ? (Array.isArray(typeKeys) ? typeKeys : [typeKeys])
84
+ : undefined
85
+
86
+ const route = useRoute()
87
+ const router = useRouter()
88
+ const value = useRouteQuery<string | undefined>(urlParam, defaultValue)
89
+
90
+ // Register in onMounted to avoid SSR/hydration mismatch: the registry must be
91
+ // empty during SSR so server and client produce the same initial HTML.
92
+ onMounted(() => {
93
+ context.register(urlParam, { apiParam, ref: value, defaultValue, typeKeys: normalizedTypeKeys })
94
+ })
95
+
96
+ onScopeDispose(() => {
97
+ // Type-scoped filters (typeKeys set) are cleared by GlobalSearch's
98
+ // watch(currentType) instead, so their URL update batches with the other
99
+ // type-change resets via useRouteQuery rather than racing them with the
100
+ // separate router.replace below. Here we only clear filters that apply to
101
+ // all types: their unmount is a consumer signal unrelated to a type switch,
102
+ // which GlobalSearch has no way to detect.
103
+ //
104
+ // We cannot use `value.value = defaultValue` here because VueUse's
105
+ // useRouteQuery registers its own tryOnScopeDispose cleanup that zeroes
106
+ // the internal `query` variable to undefined (FIFO order, it runs first).
107
+ // The setter then sees `query === v` and early-returns without ever
108
+ // calling router.replace(). Instead we read the live route.query directly
109
+ // (which is router state, not affected by that cleanup) and push the update.
110
+ if (normalizedTypeKeys === undefined && route.query[urlParam] !== undefined) {
111
+ const { [urlParam]: _removed, ...restQuery } = route.query
112
+ router.replace({
113
+ query: defaultValue === undefined ? restQuery : { ...restQuery, [urlParam]: String(defaultValue) },
114
+ })
115
+ }
116
+ context.unregister(urlParam)
117
+ })
118
+
119
+ return value
120
+ }