@surfaces-ui/components 0.0.0-stage → 0.2.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 (264) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +48 -2
  4. package/dist/appComponents.d.ts +86 -0
  5. package/dist/appComponents.js +555 -0
  6. package/dist/appComponents.js.map +1 -0
  7. package/dist/chart/BulletGraph.d.ts +44 -0
  8. package/dist/chart/BulletGraph.js +40 -0
  9. package/dist/chart/BulletGraph.js.map +1 -0
  10. package/dist/chart/Chart.d.ts +177 -0
  11. package/dist/chart/Chart.js +279 -0
  12. package/dist/chart/Chart.js.map +1 -0
  13. package/dist/chart/Sparkline.d.ts +35 -0
  14. package/dist/chart/Sparkline.js +37 -0
  15. package/dist/chart/Sparkline.js.map +1 -0
  16. package/dist/chart/advice.d.ts +28 -0
  17. package/dist/chart/advice.js +39 -0
  18. package/dist/chart/advice.js.map +1 -0
  19. package/dist/chart/option.d.ts +90 -0
  20. package/dist/chart/option.js +252 -0
  21. package/dist/chart/option.js.map +1 -0
  22. package/dist/controls/Combobox.d.ts +39 -0
  23. package/dist/controls/Combobox.js +75 -0
  24. package/dist/controls/Combobox.js.map +1 -0
  25. package/dist/controls/ConfirmDialog.d.ts +35 -0
  26. package/dist/controls/ConfirmDialog.js +84 -0
  27. package/dist/controls/ConfirmDialog.js.map +1 -0
  28. package/dist/controls/ItemControls.d.ts +115 -0
  29. package/dist/controls/ItemControls.js +109 -0
  30. package/dist/controls/ItemControls.js.map +1 -0
  31. package/dist/controls/Popover.d.ts +31 -0
  32. package/dist/controls/Popover.js +114 -0
  33. package/dist/controls/Popover.js.map +1 -0
  34. package/dist/controls/ResizeHandle.d.ts +48 -0
  35. package/dist/controls/ResizeHandle.js +91 -0
  36. package/dist/controls/ResizeHandle.js.map +1 -0
  37. package/dist/controls/SegmentedControl.d.ts +27 -0
  38. package/dist/controls/SegmentedControl.js +17 -0
  39. package/dist/controls/SegmentedControl.js.map +1 -0
  40. package/dist/controls/StatusBadge.d.ts +17 -0
  41. package/dist/controls/StatusBadge.js +10 -0
  42. package/dist/controls/StatusBadge.js.map +1 -0
  43. package/dist/controls/context.d.ts +17 -0
  44. package/dist/controls/context.js +2 -0
  45. package/dist/controls/context.js.map +1 -0
  46. package/dist/controls/placement.d.ts +43 -0
  47. package/dist/controls/placement.js +19 -0
  48. package/dist/controls/placement.js.map +1 -0
  49. package/dist/controls/resize.d.ts +23 -0
  50. package/dist/controls/resize.js +49 -0
  51. package/dist/controls/resize.js.map +1 -0
  52. package/dist/data/DataSourceProvider.d.ts +11 -0
  53. package/dist/data/DataSourceProvider.js +21 -0
  54. package/dist/data/DataSourceProvider.js.map +1 -0
  55. package/dist/data/export.d.ts +33 -0
  56. package/dist/data/export.js +77 -0
  57. package/dist/data/export.js.map +1 -0
  58. package/dist/data/format.d.ts +44 -0
  59. package/dist/data/format.js +127 -0
  60. package/dist/data/format.js.map +1 -0
  61. package/dist/data/messages.d.ts +13 -0
  62. package/dist/data/messages.js +2 -0
  63. package/dist/data/messages.js.map +1 -0
  64. package/dist/data/useRowWindow.d.ts +70 -0
  65. package/dist/data/useRowWindow.js +175 -0
  66. package/dist/data/useRowWindow.js.map +1 -0
  67. package/dist/discovery/AskData.d.ts +22 -0
  68. package/dist/discovery/AskData.js +48 -0
  69. package/dist/discovery/AskData.js.map +1 -0
  70. package/dist/discovery/ContextBuilder.d.ts +49 -0
  71. package/dist/discovery/ContextBuilder.js +167 -0
  72. package/dist/discovery/ContextBuilder.js.map +1 -0
  73. package/dist/discovery/DataSearch.d.ts +27 -0
  74. package/dist/discovery/DataSearch.js +73 -0
  75. package/dist/discovery/DataSearch.js.map +1 -0
  76. package/dist/discovery/ObjectDetail.d.ts +38 -0
  77. package/dist/discovery/ObjectDetail.js +129 -0
  78. package/dist/discovery/ObjectDetail.js.map +1 -0
  79. package/dist/discovery/RelationshipGraph.d.ts +19 -0
  80. package/dist/discovery/RelationshipGraph.js +64 -0
  81. package/dist/discovery/RelationshipGraph.js.map +1 -0
  82. package/dist/discovery/shared.d.ts +38 -0
  83. package/dist/discovery/shared.js +64 -0
  84. package/dist/discovery/shared.js.map +1 -0
  85. package/dist/editor/SqlEditor.d.ts +41 -0
  86. package/dist/editor/SqlEditor.js +181 -0
  87. package/dist/editor/SqlEditor.js.map +1 -0
  88. package/dist/explore/Explorer.d.ts +110 -0
  89. package/dist/explore/Explorer.js +471 -0
  90. package/dist/explore/Explorer.js.map +1 -0
  91. package/dist/explore/ModelLineage.d.ts +22 -0
  92. package/dist/explore/ModelLineage.js +70 -0
  93. package/dist/explore/ModelLineage.js.map +1 -0
  94. package/dist/explore/ReportBuilder.d.ts +39 -0
  95. package/dist/explore/ReportBuilder.js +98 -0
  96. package/dist/explore/ReportBuilder.js.map +1 -0
  97. package/dist/explore/SemanticModelEditor.d.ts +60 -0
  98. package/dist/explore/SemanticModelEditor.js +220 -0
  99. package/dist/explore/SemanticModelEditor.js.map +1 -0
  100. package/dist/explore/SemanticRows.d.ts +42 -0
  101. package/dist/explore/SemanticRows.js +117 -0
  102. package/dist/explore/SemanticRows.js.map +1 -0
  103. package/dist/explore/SemanticsProvider.d.ts +31 -0
  104. package/dist/explore/SemanticsProvider.js +72 -0
  105. package/dist/explore/SemanticsProvider.js.map +1 -0
  106. package/dist/explore/model.d.ts +151 -0
  107. package/dist/explore/model.js +344 -0
  108. package/dist/explore/model.js.map +1 -0
  109. package/dist/explore/report.d.ts +60 -0
  110. package/dist/explore/report.js +92 -0
  111. package/dist/explore/report.js.map +1 -0
  112. package/dist/explore/semantic-proposal.d.ts +44 -0
  113. package/dist/explore/semantic-proposal.js +67 -0
  114. package/dist/explore/semantic-proposal.js.map +1 -0
  115. package/dist/explore/semantic.d.ts +44 -0
  116. package/dist/explore/semantic.js +154 -0
  117. package/dist/explore/semantic.js.map +1 -0
  118. package/dist/files/FileBrowser.d.ts +42 -0
  119. package/dist/files/FileBrowser.js +314 -0
  120. package/dist/files/FileBrowser.js.map +1 -0
  121. package/dist/files/files.d.ts +65 -0
  122. package/dist/files/files.js +165 -0
  123. package/dist/files/files.js.map +1 -0
  124. package/dist/filter/FilterBar.d.ts +49 -0
  125. package/dist/filter/FilterBar.js +153 -0
  126. package/dist/filter/FilterBar.js.map +1 -0
  127. package/dist/filter/QueryFilters.d.ts +25 -0
  128. package/dist/filter/QueryFilters.js +58 -0
  129. package/dist/filter/QueryFilters.js.map +1 -0
  130. package/dist/form/Form.d.ts +76 -0
  131. package/dist/form/Form.js +131 -0
  132. package/dist/form/Form.js.map +1 -0
  133. package/dist/graph/NodeGraph.d.ts +30 -0
  134. package/dist/graph/NodeGraph.js +86 -0
  135. package/dist/graph/NodeGraph.js.map +1 -0
  136. package/dist/graph/model.d.ts +68 -0
  137. package/dist/graph/model.js +122 -0
  138. package/dist/graph/model.js.map +1 -0
  139. package/dist/grid/DataGrid.d.ts +98 -0
  140. package/dist/grid/DataGrid.js +399 -0
  141. package/dist/grid/DataGrid.js.map +1 -0
  142. package/dist/index.d.ts +84 -0
  143. package/dist/index.js +86 -0
  144. package/dist/index.js.map +1 -0
  145. package/dist/locale/SurfacesText.d.ts +17 -0
  146. package/dist/locale/SurfacesText.js +17 -0
  147. package/dist/locale/SurfacesText.js.map +1 -0
  148. package/dist/locale/locale.d.ts +305 -0
  149. package/dist/locale/locale.js +359 -0
  150. package/dist/locale/locale.js.map +1 -0
  151. package/dist/menu/ContextMenu.d.ts +31 -0
  152. package/dist/menu/ContextMenu.js +95 -0
  153. package/dist/menu/ContextMenu.js.map +1 -0
  154. package/dist/metric/Metric.d.ts +33 -0
  155. package/dist/metric/Metric.js +63 -0
  156. package/dist/metric/Metric.js.map +1 -0
  157. package/dist/metric/useMeasure.d.ts +23 -0
  158. package/dist/metric/useMeasure.js +43 -0
  159. package/dist/metric/useMeasure.js.map +1 -0
  160. package/dist/model/ModelDiagram.d.ts +142 -0
  161. package/dist/model/ModelDiagram.js +699 -0
  162. package/dist/model/ModelDiagram.js.map +1 -0
  163. package/dist/panzoom/usePanZoom.d.ts +117 -0
  164. package/dist/panzoom/usePanZoom.js +313 -0
  165. package/dist/panzoom/usePanZoom.js.map +1 -0
  166. package/dist/pipeline/DatasetReview.d.ts +48 -0
  167. package/dist/pipeline/DatasetReview.js +157 -0
  168. package/dist/pipeline/DatasetReview.js.map +1 -0
  169. package/dist/pipeline/IngestWizard.d.ts +51 -0
  170. package/dist/pipeline/IngestWizard.js +79 -0
  171. package/dist/pipeline/IngestWizard.js.map +1 -0
  172. package/dist/pipeline/Pipeline.d.ts +171 -0
  173. package/dist/pipeline/Pipeline.js +203 -0
  174. package/dist/pipeline/Pipeline.js.map +1 -0
  175. package/dist/pipeline/PipelineView.d.ts +63 -0
  176. package/dist/pipeline/PipelineView.js +239 -0
  177. package/dist/pipeline/PipelineView.js.map +1 -0
  178. package/dist/pivot/PivotTable.d.ts +94 -0
  179. package/dist/pivot/PivotTable.js +171 -0
  180. package/dist/pivot/PivotTable.js.map +1 -0
  181. package/dist/plan/QueryPlan.d.ts +29 -0
  182. package/dist/plan/QueryPlan.js +79 -0
  183. package/dist/plan/QueryPlan.js.map +1 -0
  184. package/dist/result/QueryResult.d.ts +51 -0
  185. package/dist/result/QueryResult.js +255 -0
  186. package/dist/result/QueryResult.js.map +1 -0
  187. package/dist/review/ActionReceipt.d.ts +52 -0
  188. package/dist/review/ActionReceipt.js +32 -0
  189. package/dist/review/ActionReceipt.js.map +1 -0
  190. package/dist/review/PiiReview.d.ts +37 -0
  191. package/dist/review/PiiReview.js +29 -0
  192. package/dist/review/PiiReview.js.map +1 -0
  193. package/dist/review/PlanReview.d.ts +42 -0
  194. package/dist/review/PlanReview.js +37 -0
  195. package/dist/review/PlanReview.js.map +1 -0
  196. package/dist/review/StepFlow.d.ts +25 -0
  197. package/dist/review/StepFlow.js +21 -0
  198. package/dist/review/StepFlow.js.map +1 -0
  199. package/dist/review/pii.d.ts +21 -0
  200. package/dist/review/pii.js +67 -0
  201. package/dist/review/pii.js.map +1 -0
  202. package/dist/rows/RowList.d.ts +41 -0
  203. package/dist/rows/RowList.js +71 -0
  204. package/dist/rows/RowList.js.map +1 -0
  205. package/dist/schema/ObjectBrowser.d.ts +78 -0
  206. package/dist/schema/ObjectBrowser.js +467 -0
  207. package/dist/schema/ObjectBrowser.js.map +1 -0
  208. package/dist/schema/ObjectInfo.d.ts +25 -0
  209. package/dist/schema/ObjectInfo.js +69 -0
  210. package/dist/schema/ObjectInfo.js.map +1 -0
  211. package/dist/schema/SchemaExplorer.d.ts +32 -0
  212. package/dist/schema/SchemaExplorer.js +175 -0
  213. package/dist/schema/SchemaExplorer.js.map +1 -0
  214. package/dist/schema/refs.d.ts +32 -0
  215. package/dist/schema/refs.js +65 -0
  216. package/dist/schema/refs.js.map +1 -0
  217. package/dist/site/Site.d.ts +191 -0
  218. package/dist/site/Site.js +138 -0
  219. package/dist/site/Site.js.map +1 -0
  220. package/dist/source/ConnectionBuilder.d.ts +54 -0
  221. package/dist/source/ConnectionBuilder.js +115 -0
  222. package/dist/source/ConnectionBuilder.js.map +1 -0
  223. package/dist/source/SourceList.d.ts +17 -0
  224. package/dist/source/SourceList.js +71 -0
  225. package/dist/source/SourceList.js.map +1 -0
  226. package/dist/styles.css +9882 -0
  227. package/dist/styles.layer.css +9886 -0
  228. package/dist/table/DataTable.d.ts +72 -0
  229. package/dist/table/DataTable.js +68 -0
  230. package/dist/table/DataTable.js.map +1 -0
  231. package/dist/table/Pagination.d.ts +20 -0
  232. package/dist/table/Pagination.js +16 -0
  233. package/dist/table/Pagination.js.map +1 -0
  234. package/dist/table/SelectionBar.d.ts +43 -0
  235. package/dist/table/SelectionBar.js +18 -0
  236. package/dist/table/SelectionBar.js.map +1 -0
  237. package/dist/text/Markdown.d.ts +71 -0
  238. package/dist/text/Markdown.js +187 -0
  239. package/dist/text/Markdown.js.map +1 -0
  240. package/dist/text/highlight.d.ts +23 -0
  241. package/dist/text/highlight.js +196 -0
  242. package/dist/text/highlight.js.map +1 -0
  243. package/dist/theme/ThemePicker.d.ts +16 -0
  244. package/dist/theme/ThemePicker.js +49 -0
  245. package/dist/theme/ThemePicker.js.map +1 -0
  246. package/dist/theme/ThemeProvider.d.ts +43 -0
  247. package/dist/theme/ThemeProvider.js +107 -0
  248. package/dist/theme/ThemeProvider.js.map +1 -0
  249. package/dist/workspace/NavBar.d.ts +23 -0
  250. package/dist/workspace/NavBar.js +171 -0
  251. package/dist/workspace/NavBar.js.map +1 -0
  252. package/dist/workspace/SideNav.d.ts +61 -0
  253. package/dist/workspace/SideNav.js +149 -0
  254. package/dist/workspace/SideNav.js.map +1 -0
  255. package/dist/workspace/Workspace.d.ts +50 -0
  256. package/dist/workspace/Workspace.js +243 -0
  257. package/dist/workspace/Workspace.js.map +1 -0
  258. package/dist/workspace/icons.d.ts +34 -0
  259. package/dist/workspace/icons.js +37 -0
  260. package/dist/workspace/icons.js.map +1 -0
  261. package/dist/workspace/layout.d.ts +74 -0
  262. package/dist/workspace/layout.js +276 -0
  263. package/dist/workspace/layout.js.map +1 -0
  264. package/package.json +85 -3
@@ -0,0 +1,69 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { TableFormat, TableKind } from "@surfaces-ui/proto";
3
+ import { useEffect, useState } from "react";
4
+ import { useDataSource } from "../data/DataSourceProvider.js";
5
+ import { messageOf } from "../data/useRowWindow.js";
6
+ import { numberFormat } from "../locale/locale.js";
7
+ const count = { format: (n) => numberFormat().format(n) };
8
+ const KIND = { [TableKind.TABLE]: "Table", [TableKind.VIEW]: "View", [TableKind.MATERIALIZED_VIEW]: "Materialised view", [TableKind.EXTERNAL]: "External table" };
9
+ function bytes(n) {
10
+ const units = ["bytes", "KB", "MB", "GB", "TB", "PB"];
11
+ let value = Number(n);
12
+ let unit = 0;
13
+ while (value >= 1024 && unit < units.length - 1) {
14
+ value /= 1024;
15
+ unit++;
16
+ }
17
+ return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`;
18
+ }
19
+ /** The name as it is written in SQL, qualified by what is known. */
20
+ export function qualifiedName(parts) {
21
+ const quote = (name) => (/^[A-Za-z_]\w*$/.test(name) ? name : `"${name.replace(/"/g, '""')}"`);
22
+ return [parts.catalog, parts.schema, parts.table, parts.column].filter((p) => Boolean(p)).map(quote).join(".");
23
+ }
24
+ /**
25
+ * What the backend knows about a database, schema or table: for a table its
26
+ * kind, format, location, size and every column with its type and keys; for
27
+ * a database or schema the tables in it. Row counts come from the catalog
28
+ * when it has them and are never worked out by scanning.
29
+ */
30
+ export function ObjectInfo(props) {
31
+ const { sourceId, catalog, schema, table, onClose } = props;
32
+ const dataSource = useDataSource(props.dataSource);
33
+ const [loaded, setLoaded] = useState();
34
+ const name = qualifiedName({ catalog, schema, table });
35
+ useEffect(() => {
36
+ let current = true;
37
+ setLoaded(undefined);
38
+ const request = table
39
+ ? dataSource.describeTable({ sourceId, ref: { catalog: catalog ?? "", schema: schema ?? "", table } }).then((r) => (r.table ? { table: r.table } : { error: "The backend returned nothing for this table." }))
40
+ : dataSource.listTables({ sourceId, catalog: catalog ?? "", schema: schema ?? "", pageSize: 50 }).then((r) => ({ tables: r.tables, more: r.nextPageToken !== "" }));
41
+ request.then((result) => current && setLoaded(result)).catch((error) => current && setLoaded({ error: messageOf(error) }));
42
+ return () => {
43
+ current = false;
44
+ };
45
+ }, [dataSource, sourceId, catalog, schema, table]);
46
+ const facts = [];
47
+ if (loaded && "table" in loaded) {
48
+ const { summary, rowCount, sizeBytes, location, properties } = loaded.table;
49
+ facts.push(["Kind", KIND[summary?.kind ?? 0] ?? "Table"]);
50
+ if (summary?.format)
51
+ facts.push(["Format", TableFormat[summary.format]?.toLowerCase() ?? ""]);
52
+ if (rowCount !== undefined)
53
+ facts.push(["Rows", count.format(rowCount)]);
54
+ if (sizeBytes !== undefined)
55
+ facts.push(["Size", bytes(sizeBytes)]);
56
+ if (location)
57
+ facts.push(["Location", location]);
58
+ facts.push(["Columns", count.format(loaded.table.columns.length)]);
59
+ for (const [key, value] of Object.entries(properties))
60
+ facts.push([key, value]);
61
+ }
62
+ return (_jsxs("section", { className: ["sf-info", props.className].filter(Boolean).join(" "), "aria-label": `Details of ${name || sourceId}`, onKeyDown: (event) => {
63
+ if (event.key === "Escape" && onClose) {
64
+ event.stopPropagation();
65
+ onClose();
66
+ }
67
+ }, children: [_jsxs("header", { className: "sf-info-head", children: [_jsxs("div", { children: [_jsx("p", { className: "sf-info-kind", children: table ? "Table" : schema ? "Schema" : catalog ? "Database" : "Source" }), _jsx("p", { className: "sf-info-name", children: name || sourceId })] }), onClose && (_jsx("button", { type: "button", className: "sf-button", onClick: onClose, autoFocus: true, children: "Close" }))] }), loaded === undefined && _jsx("p", { className: "sf-object-muted", children: "Loading\u2026" }), loaded && "error" in loaded && (_jsxs("p", { className: "sf-metric-error", role: "alert", children: ["Could not read the details: ", loaded.error] })), loaded && "table" in loaded && (_jsxs(_Fragment, { children: [loaded.table.summary?.comment && _jsx("p", { className: "sf-info-comment", children: loaded.table.summary.comment }), _jsx("dl", { className: "sf-info-facts", children: facts.map(([label, value]) => (_jsxs("div", { children: [_jsx("dt", { children: label }), _jsx("dd", { children: value })] }, label))) }), _jsx("div", { className: "sf-info-scroll", tabIndex: 0, role: "region", "aria-label": "Columns", children: _jsxs("table", { className: "sf-info-table", children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "Column" }), _jsx("th", { scope: "col", children: "Type" }), _jsx("th", { scope: "col", children: "Notes" })] }) }), _jsx("tbody", { children: loaded.table.columns.map((column) => (_jsxs("tr", { children: [_jsx("th", { scope: "row", children: column.name }), _jsx("td", { children: column.nativeType || column.arrowType }), _jsx("td", { children: [column.primaryKey && "Key", column.partitionKey && "Partition", !column.nullable && "Required", column.comment].filter(Boolean).join(" · ") })] }, column.name))) })] }) })] })), loaded && "tables" in loaded && (_jsxs(_Fragment, { children: [_jsx("p", { className: "sf-object-muted", children: loaded.tables.length === 0 ? "No tables found." : `${loaded.more ? "The first " : ""}${loaded.tables.length} ${loaded.tables.length === 1 ? "table" : "tables"}${loaded.more ? "; more exist" : ""}.` }), _jsx("div", { className: "sf-info-scroll", tabIndex: 0, role: "region", "aria-label": "Tables", children: _jsxs("table", { className: "sf-info-table", children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "Table" }), _jsx("th", { scope: "col", children: "Kind" }), _jsx("th", { scope: "col", children: "Notes" })] }) }), _jsx("tbody", { children: loaded.tables.map((summary) => (_jsxs("tr", { children: [_jsx("th", { scope: "row", children: qualifiedName({ schema: summary.ref?.schema, table: summary.ref?.table }) }), _jsx("td", { children: [KIND[summary.kind] ?? "Table", summary.format ? TableFormat[summary.format]?.toLowerCase() : ""].filter(Boolean).join(", ") }), _jsx("td", { children: summary.comment })] }, qualifiedName(summary.ref ?? {})))) })] }) })] }))] }));
68
+ }
69
+ //# sourceMappingURL=ObjectInfo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ObjectInfo.js","sourceRoot":"","sources":["../../src/schema/ObjectInfo.tsx"],"names":[],"mappings":";AACA,OAAO,EAAoB,WAAW,EAAE,SAAS,EAAqB,MAAM,oBAAoB,CAAC;AACjG,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAanD,MAAM,KAAK,GAAG,EAAE,MAAM,EAAE,CAAC,CAAkB,EAAE,EAAE,CAAC,YAAY,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;AAC3E,MAAM,IAAI,GAA2B,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAA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CAAC,OAAO,GAAM,KAHnB,aAAa,CAAC,OAAO,CAAC,GAAG,IAAI,EAAE,CAAC,CAIpC,CACN,CAAC,GACI,IACF,GACJ,IACL,CACJ,IACO,CACX,CAAC;AACJ,CAAC","sourcesContent":["import type { DataSource } from \"@surfaces-ui/data\";\nimport { type TableDetail, TableFormat, TableKind, type TableSummary } from \"@surfaces-ui/proto\";\nimport { useEffect, useState } from \"react\";\nimport { useDataSource } from \"../data/DataSourceProvider.js\";\nimport { messageOf } from \"../data/useRowWindow.js\";\nimport { numberFormat } from \"../locale/locale.js\";\n\nexport interface ObjectInfoProps {\n sourceId: string;\n /** What to describe. With `table` it is a table; without, a schema or a catalog (database). */\n catalog?: string;\n schema?: string;\n table?: string;\n onClose?(): void;\n dataSource?: DataSource;\n className?: string;\n}\n\nconst count = { format: (n: number | bigint) => numberFormat().format(n) };\nconst KIND: Record<number, string> = { [TableKind.TABLE]: \"Table\", [TableKind.VIEW]: \"View\", [TableKind.MATERIALIZED_VIEW]: \"Materialised view\", [TableKind.EXTERNAL]: \"External table\" };\n\nfunction bytes(n: bigint | number): string {\n const units = [\"bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\"];\n let value = Number(n);\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit++;\n }\n return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`;\n}\n\n/** The name as it is written in SQL, qualified by what is known. */\nexport function qualifiedName(parts: { catalog?: string; schema?: string; table?: string; column?: string }): string {\n const quote = (name: string) => (/^[A-Za-z_]\\w*$/.test(name) ? name : `\"${name.replace(/\"/g, '\"\"')}\"`);\n return [parts.catalog, parts.schema, parts.table, parts.column].filter((p): p is string => Boolean(p)).map(quote).join(\".\");\n}\n\ntype Loaded = { table: TableDetail } | { tables: TableSummary[]; more: boolean } | { error: string } | undefined;\n\n/**\n * What the backend knows about a database, schema or table: for a table its\n * kind, format, location, size and every column with its type and keys; for\n * a database or schema the tables in it. Row counts come from the catalog\n * when it has them and are never worked out by scanning.\n */\nexport function ObjectInfo(props: ObjectInfoProps) {\n const { sourceId, catalog, schema, table, onClose } = props;\n const dataSource = useDataSource(props.dataSource);\n const [loaded, setLoaded] = useState<Loaded>();\n const name = qualifiedName({ catalog, schema, table });\n\n useEffect(() => {\n let current = true;\n setLoaded(undefined);\n const request = table\n ? dataSource.describeTable({ sourceId, ref: { catalog: catalog ?? \"\", schema: schema ?? \"\", table } }).then((r): Loaded => (r.table ? { table: r.table } : { error: \"The backend returned nothing for this table.\" }))\n : dataSource.listTables({ sourceId, catalog: catalog ?? \"\", schema: schema ?? \"\", pageSize: 50 }).then((r): Loaded => ({ tables: r.tables, more: r.nextPageToken !== \"\" }));\n request.then((result) => current && setLoaded(result)).catch((error: unknown) => current && setLoaded({ error: messageOf(error) }));\n return () => {\n current = false;\n };\n }, [dataSource, sourceId, catalog, schema, table]);\n\n const facts: [string, string][] = [];\n if (loaded && \"table\" in loaded) {\n const { summary, rowCount, sizeBytes, location, properties } = loaded.table;\n facts.push([\"Kind\", KIND[summary?.kind ?? 0] ?? \"Table\"]);\n if (summary?.format) facts.push([\"Format\", TableFormat[summary.format]?.toLowerCase() ?? \"\"]);\n if (rowCount !== undefined) facts.push([\"Rows\", count.format(rowCount)]);\n if (sizeBytes !== undefined) facts.push([\"Size\", bytes(sizeBytes)]);\n if (location) facts.push([\"Location\", location]);\n facts.push([\"Columns\", count.format(loaded.table.columns.length)]);\n for (const [key, value] of Object.entries(properties)) facts.push([key, value]);\n }\n\n return (\n <section\n className={[\"sf-info\", props.className].filter(Boolean).join(\" \")}\n aria-label={`Details of ${name || sourceId}`}\n onKeyDown={(event) => {\n if (event.key === \"Escape\" && onClose) {\n event.stopPropagation();\n onClose();\n }\n }}\n >\n <header className=\"sf-info-head\">\n <div>\n <p className=\"sf-info-kind\">{table ? \"Table\" : schema ? \"Schema\" : catalog ? \"Database\" : \"Source\"}</p>\n <p className=\"sf-info-name\">{name || sourceId}</p>\n </div>\n {onClose && (\n <button type=\"button\" className=\"sf-button\" onClick={onClose} autoFocus>\n Close\n </button>\n )}\n </header>\n {loaded === undefined && <p className=\"sf-object-muted\">Loading…</p>}\n {loaded && \"error\" in loaded && (\n <p className=\"sf-metric-error\" role=\"alert\">\n Could not read the details: {loaded.error}\n </p>\n )}\n {loaded && \"table\" in loaded && (\n <>\n {loaded.table.summary?.comment && <p className=\"sf-info-comment\">{loaded.table.summary.comment}</p>}\n <dl className=\"sf-info-facts\">\n {facts.map(([label, value]) => (\n <div key={label}>\n <dt>{label}</dt>\n <dd>{value}</dd>\n </div>\n ))}\n </dl>\n <div className=\"sf-info-scroll\" tabIndex={0} role=\"region\" aria-label=\"Columns\">\n <table className=\"sf-info-table\">\n <thead>\n <tr>\n <th scope=\"col\">Column</th>\n <th scope=\"col\">Type</th>\n <th scope=\"col\">Notes</th>\n </tr>\n </thead>\n <tbody>\n {loaded.table.columns.map((column) => (\n <tr key={column.name}>\n <th scope=\"row\">{column.name}</th>\n <td>{column.nativeType || column.arrowType}</td>\n <td>{[column.primaryKey && \"Key\", column.partitionKey && \"Partition\", !column.nullable && \"Required\", column.comment].filter(Boolean).join(\" · \")}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n </>\n )}\n {loaded && \"tables\" in loaded && (\n <>\n <p className=\"sf-object-muted\">\n {loaded.tables.length === 0 ? \"No tables found.\" : `${loaded.more ? \"The first \" : \"\"}${loaded.tables.length} ${loaded.tables.length === 1 ? \"table\" : \"tables\"}${loaded.more ? \"; more exist\" : \"\"}.`}\n </p>\n <div className=\"sf-info-scroll\" tabIndex={0} role=\"region\" aria-label=\"Tables\">\n <table className=\"sf-info-table\">\n <thead>\n <tr>\n <th scope=\"col\">Table</th>\n <th scope=\"col\">Kind</th>\n <th scope=\"col\">Notes</th>\n </tr>\n </thead>\n <tbody>\n {loaded.tables.map((summary) => (\n <tr key={qualifiedName(summary.ref ?? {})}>\n <th scope=\"row\">{qualifiedName({ schema: summary.ref?.schema, table: summary.ref?.table })}</th>\n <td>{[KIND[summary.kind] ?? \"Table\", summary.format ? TableFormat[summary.format]?.toLowerCase() : \"\"].filter(Boolean).join(\", \")}</td>\n <td>{summary.comment}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n </>\n )}\n </section>\n );\n}\n"]}
@@ -0,0 +1,32 @@
1
+ import type { DataSource } from "@surfaces-ui/data";
2
+ import { type TableSummary } from "@surfaces-ui/proto";
3
+ import { type ReactNode } from "react";
4
+ /** A table or column, as handed to callbacks and placed on the clipboard when dragged. */
5
+ export interface SchemaRef {
6
+ sourceId: string;
7
+ table: string;
8
+ column?: string;
9
+ }
10
+ /** MIME type carrying a SchemaRef as JSON during drag and drop. */
11
+ export declare const SCHEMA_REF_MIME = "application/x-surfaces-ref+json";
12
+ export interface SchemaExplorerProps {
13
+ sourceId: string;
14
+ /** Called when a table or column is activated (click or Enter). */
15
+ onSelect?(ref: SchemaRef, table: TableSummary): void;
16
+ /** Called on double-click or Insert, with the name to insert into an editor. */
17
+ onInsert?(name: string, ref: SchemaRef): void;
18
+ /** Extra controls at the end of each table row, e.g. "add to context". */
19
+ renderActions?(ref: SchemaRef, table: TableSummary): ReactNode;
20
+ /** Height in px. Defaults to 420. */
21
+ height?: number;
22
+ dataSource?: DataSource;
23
+ /** Accessible name. Defaults to "Tables". */
24
+ label?: string;
25
+ className?: string;
26
+ }
27
+ /**
28
+ * A searchable tree of a source's tables and their columns. Columns load when
29
+ * a table is opened; only visible rows are in the DOM, so catalogs with
30
+ * thousands of tables stay fast. Items can be dragged into SqlEditor.
31
+ */
32
+ export declare function SchemaExplorer(props: SchemaExplorerProps): import("react").JSX.Element;
@@ -0,0 +1,175 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { TableFormat } from "@surfaces-ui/proto";
3
+ import { DENSITY_SCALE } from "@surfaces-ui/tokens";
4
+ import { useEffect, useMemo, useRef, useState } from "react";
5
+ import { useDataSource } from "../data/DataSourceProvider.js";
6
+ import { messageOf } from "../data/useRowWindow.js";
7
+ import { useOptionalTheme } from "../theme/ThemeProvider.js";
8
+ import { numberFormat } from "../locale/locale.js";
9
+ /** MIME type carrying a SchemaRef as JSON during drag and drop. */
10
+ export const SCHEMA_REF_MIME = "application/x-surfaces-ref+json";
11
+ const FORMAT_LABEL = {
12
+ [TableFormat.PARQUET]: "Parquet",
13
+ [TableFormat.CSV]: "CSV",
14
+ [TableFormat.JSON]: "JSON",
15
+ [TableFormat.ICEBERG]: "Iceberg",
16
+ [TableFormat.DELTA]: "Delta",
17
+ };
18
+ const count = { format: (n) => numberFormat({ notation: "compact", maximumFractionDigits: 1 }).format(n) };
19
+ /**
20
+ * A searchable tree of a source's tables and their columns. Columns load when
21
+ * a table is opened; only visible rows are in the DOM, so catalogs with
22
+ * thousands of tables stay fast. Items can be dragged into SqlEditor.
23
+ */
24
+ export function SchemaExplorer(props) {
25
+ const { sourceId, height = 420 } = props;
26
+ const dataSource = useDataSource(props.dataSource);
27
+ const theme = useOptionalTheme();
28
+ const rowHeight = DENSITY_SCALE[theme?.theme.density ?? "comfortable"].rowHeight - 4;
29
+ const [search, setSearch] = useState("");
30
+ const [tables, setTables] = useState([]);
31
+ const [status, setStatus] = useState({ loading: true });
32
+ const [expanded, setExpanded] = useState(new Set());
33
+ const [details, setDetails] = useState({});
34
+ const [active, setActive] = useState(0);
35
+ const [scrollTop, setScrollTop] = useState(0);
36
+ const list = useRef(null);
37
+ // Search runs on the backend so it works over catalogs too large to list.
38
+ useEffect(() => {
39
+ let current = true;
40
+ setStatus({ loading: true });
41
+ const timer = setTimeout(() => {
42
+ dataSource
43
+ .listTables({ sourceId, search: search.trim() })
44
+ .then((response) => {
45
+ if (!current)
46
+ return;
47
+ setTables(response.tables);
48
+ setStatus({ loading: false });
49
+ })
50
+ .catch((error) => current && setStatus({ loading: false, error: messageOf(error) }));
51
+ }, search ? 180 : 0);
52
+ return () => {
53
+ current = false;
54
+ clearTimeout(timer);
55
+ };
56
+ }, [dataSource, sourceId, search]);
57
+ const toggle = (name) => {
58
+ setExpanded((previous) => {
59
+ const next = new Set(previous);
60
+ if (next.has(name))
61
+ next.delete(name);
62
+ else
63
+ next.add(name);
64
+ return next;
65
+ });
66
+ if (details[name] === undefined) {
67
+ setDetails((previous) => ({ ...previous, [name]: "loading" }));
68
+ dataSource
69
+ .describeTable({ sourceId, ref: { table: name }, includeStats: true })
70
+ .then((response) => setDetails((previous) => ({ ...previous, [name]: response.table ?? { error: "No details." } })))
71
+ .catch((error) => setDetails((previous) => ({ ...previous, [name]: { error: messageOf(error) } })));
72
+ }
73
+ };
74
+ const nodes = useMemo(() => {
75
+ const out = [];
76
+ for (const table of tables) {
77
+ const name = table.ref?.table ?? "";
78
+ const open = expanded.has(name);
79
+ out.push({ kind: "table", key: `t:${name}`, table, name, expanded: open });
80
+ if (!open)
81
+ continue;
82
+ const detail = details[name];
83
+ if (detail === undefined || detail === "loading")
84
+ out.push({ kind: "note", key: `n:${name}`, text: "Loading columns…" });
85
+ else if ("error" in detail)
86
+ out.push({ kind: "note", key: `n:${name}`, text: detail.error, error: true });
87
+ else
88
+ for (const column of detail.columns)
89
+ out.push({ kind: "column", key: `c:${name}.${column.name}`, table, tableName: name, column });
90
+ }
91
+ return out;
92
+ }, [tables, expanded, details]);
93
+ const listHeight = Math.max(rowHeight, height - 44);
94
+ const first = Math.max(0, Math.floor(scrollTop / rowHeight) - 4);
95
+ const last = Math.min(nodes.length, first + Math.ceil(listHeight / rowHeight) + 8);
96
+ const refOf = (node) => node.kind === "table"
97
+ ? { sourceId, table: node.name }
98
+ : node.kind === "column"
99
+ ? { sourceId, table: node.tableName, column: node.column.name }
100
+ : undefined;
101
+ const nameOf = (ref) => ref.column ?? ref.table;
102
+ const focusRow = (index) => {
103
+ const clamped = Math.max(0, Math.min(nodes.length - 1, index));
104
+ setActive(clamped);
105
+ const element = list.current;
106
+ if (!element)
107
+ return;
108
+ if (clamped * rowHeight < element.scrollTop)
109
+ element.scrollTop = clamped * rowHeight;
110
+ else if ((clamped + 1) * rowHeight > element.scrollTop + listHeight)
111
+ element.scrollTop = (clamped + 1) * rowHeight - listHeight;
112
+ };
113
+ const onKeyDown = (event) => {
114
+ const node = nodes[active];
115
+ const handled = () => event.preventDefault();
116
+ if (event.key === "ArrowDown")
117
+ return handled(), focusRow(active + 1);
118
+ if (event.key === "ArrowUp")
119
+ return handled(), focusRow(active - 1);
120
+ if (event.key === "Home")
121
+ return handled(), focusRow(0);
122
+ if (event.key === "End")
123
+ return handled(), focusRow(nodes.length - 1);
124
+ if (!node)
125
+ return;
126
+ const ref = refOf(node);
127
+ if (event.key === "ArrowRight" && node.kind === "table" && !node.expanded)
128
+ return handled(), toggle(node.name);
129
+ if (event.key === "ArrowLeft") {
130
+ handled();
131
+ if (node.kind === "table" && node.expanded)
132
+ return toggle(node.name);
133
+ if (node.kind !== "table")
134
+ return focusRow(nodes.findIndex((n) => n.kind === "table" && n.name === (node.kind === "column" ? node.tableName : "")));
135
+ }
136
+ if (event.key === "Enter" && ref)
137
+ return handled(), props.onSelect?.(ref, node.table);
138
+ if (event.key === "Insert" && ref)
139
+ return handled(), props.onInsert?.(nameOf(ref), ref);
140
+ };
141
+ const drag = (ref) => (event) => {
142
+ event.dataTransfer.setData("text/plain", nameOf(ref));
143
+ event.dataTransfer.setData(SCHEMA_REF_MIME, JSON.stringify(ref));
144
+ event.dataTransfer.effectAllowed = "copy";
145
+ };
146
+ const rows = [];
147
+ for (let index = first; index < last; index++) {
148
+ const node = nodes[index];
149
+ const ref = refOf(node);
150
+ const common = {
151
+ id: `sf-schema-${index}`,
152
+ className: "sf-schema-row",
153
+ "data-kind": node.kind,
154
+ "data-active": index === active || undefined,
155
+ style: { top: index * rowHeight, height: rowHeight },
156
+ };
157
+ if (node.kind === "note") {
158
+ rows.push(_jsx("div", { ...common, role: "treeitem", "aria-level": 2, "aria-selected": false, "data-error": node.error || undefined, children: node.text }, node.key));
159
+ continue;
160
+ }
161
+ const detail = node.kind === "table" ? details[node.name] : undefined;
162
+ const rowCount = detail && typeof detail === "object" && "rowCount" in detail ? detail.rowCount : undefined;
163
+ rows.push(_jsx("div", { ...common, role: "treeitem", "aria-level": node.kind === "table" ? 1 : 2, "aria-expanded": node.kind === "table" ? node.expanded : undefined, "aria-selected": index === active, draggable: true, onDragStart: drag(ref), onClick: () => {
164
+ setActive(index);
165
+ if (node.kind === "table")
166
+ toggle(node.name);
167
+ props.onSelect?.(ref, node.table);
168
+ }, onDoubleClick: () => props.onInsert?.(nameOf(ref), ref), children: node.kind === "table" ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "sf-schema-caret", "aria-hidden": "true", "data-open": node.expanded || undefined, children: "\u25B8" }), _jsx("span", { className: "sf-schema-name", children: node.name }), rowCount !== undefined && _jsxs("span", { className: "sf-schema-meta", children: [count.format(Number(rowCount)), " rows"] }), FORMAT_LABEL[node.table.format] && _jsx("span", { className: "sf-schema-tag", children: FORMAT_LABEL[node.table.format] }), props.renderActions && (_jsx("span", { className: "sf-schema-actions", onClick: (e) => e.stopPropagation(), onDoubleClick: (e) => e.stopPropagation(), children: props.renderActions(ref, node.table) }))] })) : (_jsxs(_Fragment, { children: [_jsx("span", { className: "sf-schema-name", children: node.column.name }), _jsx("span", { className: "sf-schema-meta", children: node.column.nativeType.toLowerCase() })] })) }, node.key));
169
+ }
170
+ return (_jsxs("div", { className: ["sf-schema", props.className].filter(Boolean).join(" "), style: { height }, children: [_jsx("input", { className: "sf-input sf-schema-search", type: "search", placeholder: "Search tables", "aria-label": "Search tables", value: search, onChange: (event) => {
171
+ setSearch(event.target.value);
172
+ setActive(0);
173
+ } }), _jsxs("div", { ref: list, className: "sf-schema-list", role: "tree", "aria-label": props.label ?? "Tables", "aria-busy": status.loading, "aria-activedescendant": nodes.length > 0 ? `sf-schema-${active}` : undefined, tabIndex: 0, onKeyDown: onKeyDown, onScroll: (event) => setScrollTop(event.currentTarget.scrollTop), children: [_jsx("div", { style: { height: nodes.length * rowHeight, position: "relative" }, children: rows }), status.error && (_jsx("p", { className: "sf-schema-empty", role: "alert", children: status.error })), !status.loading && !status.error && tables.length === 0 && (_jsx("p", { className: "sf-schema-empty", children: search ? `No tables match “${search}”.` : "This source has no tables." }))] })] }));
174
+ }
175
+ //# sourceMappingURL=SchemaExplorer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SchemaExplorer.js","sourceRoot":"","sources":["../../src/schema/SchemaExplorer.tsx"],"names":[],"mappings":";AACA,OAAO,EAAiC,WAAW,EAAqB,MAAM,oBAAoB,CAAC;AACnG,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAsD,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACjH,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AASnD,mEAAmE;AACnE,MAAM,CAAC,MAAM,eAAe,GAAG,iCAAiC,CAAC;AAkBjE,MAAM,YAAY,GAAyC;IACzD,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,SAAS;IAChC,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE,KAAK;IACxB,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,MAAM;IAC1B,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,SAAS;IAChC,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,OAAO;CAC7B,CAAC;AAOF,MAAM,KAAK,GAAG,EAAE,MAAM,EAAE,CAAC,CAAS,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,qBAAqB,EAAE,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;A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,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;oBAC9B,SAAS,CAAC,CAAC,CAAC,CAAC;gBACf,CAAC,GACD,EACF,eACE,GAAG,EAAE,IAAI,EACT,SAAS,EAAC,gBAAgB,EAC1B,IAAI,EAAC,MAAM,gBACC,KAAK,CAAC,KAAK,IAAI,QAAQ,eACxB,MAAM,CAAC,OAAO,2BACF,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,aAAa,MAAM,EAAE,CAAC,CAAC,CAAC,SAAS,EAC3E,QAAQ,EAAE,CAAC,EACX,SAAS,EAAE,SAAS,EACpB,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,aAAa,CAAC,SAAS,CAAC,aAEhE,cAAK,KAAK,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,GAAG,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,YAAG,IAAI,GAAO,EACnF,MAAM,CAAC,KAAK,IAAI,CACf,YAAG,SAAS,EAAC,iBAAiB,EAAC,IAAI,EAAC,OAAO,YACxC,MAAM,CAAC,KAAK,GACX,CACL,EACA,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,CAC1D,YAAG,SAAS,EAAC,iBAAiB,YAAE,MAAM,CAAC,CAAC,CAAC,oBAAoB,MAAM,IAAI,CAAC,CAAC,CAAC,4BAA4B,GAAK,CAC5G,IACG,IACF,CACP,CAAC;AACJ,CAAC","sourcesContent":["import type { DataSource } from \"@surfaces-ui/data\";\nimport { type Column, type TableDetail, TableFormat, type TableSummary } from \"@surfaces-ui/proto\";\nimport { DENSITY_SCALE } from \"@surfaces-ui/tokens\";\nimport { type DragEvent, type KeyboardEvent, type ReactNode, useEffect, useMemo, useRef, useState } from \"react\";\nimport { useDataSource } from \"../data/DataSourceProvider.js\";\nimport { messageOf } from \"../data/useRowWindow.js\";\nimport { useOptionalTheme } from \"../theme/ThemeProvider.js\";\nimport { numberFormat } from \"../locale/locale.js\";\n\n/** A table or column, as handed to callbacks and placed on the clipboard when dragged. */\nexport interface SchemaRef {\n sourceId: string;\n table: string;\n column?: string;\n}\n\n/** MIME type carrying a SchemaRef as JSON during drag and drop. */\nexport const SCHEMA_REF_MIME = \"application/x-surfaces-ref+json\";\n\nexport interface SchemaExplorerProps {\n sourceId: string;\n /** Called when a table or column is activated (click or Enter). */\n onSelect?(ref: SchemaRef, table: TableSummary): void;\n /** Called on double-click or Insert, with the name to insert into an editor. */\n onInsert?(name: string, ref: SchemaRef): void;\n /** Extra controls at the end of each table row, e.g. \"add to context\". */\n renderActions?(ref: SchemaRef, table: TableSummary): ReactNode;\n /** Height in px. Defaults to 420. */\n height?: number;\n dataSource?: DataSource;\n /** Accessible name. Defaults to \"Tables\". */\n label?: string;\n className?: string;\n}\n\nconst FORMAT_LABEL: Partial<Record<TableFormat, string>> = {\n [TableFormat.PARQUET]: \"Parquet\",\n [TableFormat.CSV]: \"CSV\",\n [TableFormat.JSON]: \"JSON\",\n [TableFormat.ICEBERG]: \"Iceberg\",\n [TableFormat.DELTA]: \"Delta\",\n};\n\ntype Node =\n | { kind: \"table\"; key: string; table: TableSummary; name: string; expanded: boolean }\n | { kind: \"column\"; key: string; table: TableSummary; tableName: string; column: Column }\n | { kind: \"note\"; key: string; text: string; error?: boolean };\n\nconst count = { format: (n: number) => numberFormat({ notation: \"compact\", maximumFractionDigits: 1 }).format(n) };\n\n/**\n * A searchable tree of a source's tables and their columns. Columns load when\n * a table is opened; only visible rows are in the DOM, so catalogs with\n * thousands of tables stay fast. Items can be dragged into SqlEditor.\n */\nexport function SchemaExplorer(props: SchemaExplorerProps) {\n const { sourceId, height = 420 } = props;\n const dataSource = useDataSource(props.dataSource);\n const theme = useOptionalTheme();\n const rowHeight = DENSITY_SCALE[theme?.theme.density ?? \"comfortable\"].rowHeight - 4;\n\n const [search, setSearch] = useState(\"\");\n const [tables, setTables] = useState<TableSummary[]>([]);\n const [status, setStatus] = useState<{ loading: boolean; error?: string }>({ loading: true });\n const [expanded, setExpanded] = useState<Set<string>>(new Set());\n const [details, setDetails] = useState<Record<string, TableDetail | { error: string } | \"loading\">>({});\n const [active, setActive] = useState(0);\n const [scrollTop, setScrollTop] = useState(0);\n const list = useRef<HTMLDivElement>(null);\n\n // Search runs on the backend so it works over catalogs too large to list.\n useEffect(() => {\n let current = true;\n setStatus({ loading: true });\n const timer = setTimeout(() => {\n dataSource\n .listTables({ sourceId, search: search.trim() })\n .then((response) => {\n if (!current) return;\n setTables(response.tables);\n setStatus({ loading: false });\n })\n .catch((error: unknown) => current && setStatus({ loading: false, error: messageOf(error) }));\n }, search ? 180 : 0);\n return () => {\n current = false;\n clearTimeout(timer);\n };\n }, [dataSource, sourceId, search]);\n\n const toggle = (name: string) => {\n setExpanded((previous) => {\n const next = new Set(previous);\n if (next.has(name)) next.delete(name);\n else next.add(name);\n return next;\n });\n if (details[name] === undefined) {\n setDetails((previous) => ({ ...previous, [name]: \"loading\" }));\n dataSource\n .describeTable({ sourceId, ref: { table: name }, includeStats: true })\n .then((response) => setDetails((previous) => ({ ...previous, [name]: response.table ?? { error: \"No details.\" } })))\n .catch((error: unknown) => setDetails((previous) => ({ ...previous, [name]: { error: messageOf(error) } })));\n }\n };\n\n const nodes = useMemo<Node[]>(() => {\n const out: Node[] = [];\n for (const table of tables) {\n const name = table.ref?.table ?? \"\";\n const open = expanded.has(name);\n out.push({ kind: \"table\", key: `t:${name}`, table, name, expanded: open });\n if (!open) continue;\n const detail = details[name];\n if (detail === undefined || detail === \"loading\") out.push({ kind: \"note\", key: `n:${name}`, text: \"Loading columns…\" });\n else if (\"error\" in detail) out.push({ kind: \"note\", key: `n:${name}`, text: detail.error, error: true });\n else for (const column of detail.columns) out.push({ kind: \"column\", key: `c:${name}.${column.name}`, table, tableName: name, column });\n }\n return out;\n }, [tables, expanded, details]);\n\n const listHeight = Math.max(rowHeight, height - 44);\n const first = Math.max(0, Math.floor(scrollTop / rowHeight) - 4);\n const last = Math.min(nodes.length, first + Math.ceil(listHeight / rowHeight) + 8);\n\n const refOf = (node: Node): SchemaRef | undefined =>\n node.kind === \"table\"\n ? { sourceId, table: node.name }\n : node.kind === \"column\"\n ? { sourceId, table: node.tableName, column: node.column.name }\n : undefined;\n const nameOf = (ref: SchemaRef) => ref.column ?? ref.table;\n\n const focusRow = (index: number) => {\n const clamped = Math.max(0, Math.min(nodes.length - 1, index));\n setActive(clamped);\n const element = list.current;\n if (!element) return;\n if (clamped * rowHeight < element.scrollTop) element.scrollTop = clamped * rowHeight;\n else if ((clamped + 1) * rowHeight > element.scrollTop + listHeight) element.scrollTop = (clamped + 1) * rowHeight - listHeight;\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n const node = nodes[active];\n const handled = () => event.preventDefault();\n if (event.key === \"ArrowDown\") return handled(), focusRow(active + 1);\n if (event.key === \"ArrowUp\") return handled(), focusRow(active - 1);\n if (event.key === \"Home\") return handled(), focusRow(0);\n if (event.key === \"End\") return handled(), focusRow(nodes.length - 1);\n if (!node) return;\n const ref = refOf(node);\n if (event.key === \"ArrowRight\" && node.kind === \"table\" && !node.expanded) return handled(), toggle(node.name);\n if (event.key === \"ArrowLeft\") {\n handled();\n if (node.kind === \"table\" && node.expanded) return toggle(node.name);\n if (node.kind !== \"table\") return focusRow(nodes.findIndex((n) => n.kind === \"table\" && n.name === (node.kind === \"column\" ? node.tableName : \"\")));\n }\n if (event.key === \"Enter\" && ref) return handled(), props.onSelect?.(ref, (node as { table: TableSummary }).table);\n if (event.key === \"Insert\" && ref) return handled(), props.onInsert?.(nameOf(ref), ref);\n };\n\n const drag = (ref: SchemaRef) => (event: DragEvent) => {\n event.dataTransfer.setData(\"text/plain\", nameOf(ref));\n event.dataTransfer.setData(SCHEMA_REF_MIME, JSON.stringify(ref));\n event.dataTransfer.effectAllowed = \"copy\";\n };\n\n const rows = [];\n for (let index = first; index < last; index++) {\n const node = nodes[index]!;\n const ref = refOf(node);\n const common = {\n id: `sf-schema-${index}`,\n className: \"sf-schema-row\",\n \"data-kind\": node.kind,\n \"data-active\": index === active || undefined,\n style: { top: index * rowHeight, height: rowHeight },\n };\n if (node.kind === \"note\") {\n rows.push(\n <div key={node.key} {...common} role=\"treeitem\" aria-level={2} aria-selected={false} data-error={node.error || undefined}>\n {node.text}\n </div>,\n );\n continue;\n }\n const detail = node.kind === \"table\" ? details[node.name] : undefined;\n const rowCount = detail && typeof detail === \"object\" && \"rowCount\" in detail ? detail.rowCount : undefined;\n rows.push(\n <div\n key={node.key}\n {...common}\n role=\"treeitem\"\n aria-level={node.kind === \"table\" ? 1 : 2}\n aria-expanded={node.kind === \"table\" ? node.expanded : undefined}\n aria-selected={index === active}\n draggable\n onDragStart={drag(ref!)}\n onClick={() => {\n setActive(index);\n if (node.kind === \"table\") toggle(node.name);\n props.onSelect?.(ref!, node.table);\n }}\n onDoubleClick={() => props.onInsert?.(nameOf(ref!), ref!)}\n >\n {node.kind === \"table\" ? (\n <>\n <span className=\"sf-schema-caret\" aria-hidden=\"true\" data-open={node.expanded || undefined}>\n ▸\n </span>\n <span className=\"sf-schema-name\">{node.name}</span>\n {rowCount !== undefined && <span className=\"sf-schema-meta\">{count.format(Number(rowCount))} rows</span>}\n {FORMAT_LABEL[node.table.format] && <span className=\"sf-schema-tag\">{FORMAT_LABEL[node.table.format]}</span>}\n {props.renderActions && (\n <span className=\"sf-schema-actions\" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>\n {props.renderActions(ref!, node.table)}\n </span>\n )}\n </>\n ) : (\n <>\n <span className=\"sf-schema-name\">{node.column.name}</span>\n <span className=\"sf-schema-meta\">{node.column.nativeType.toLowerCase()}</span>\n </>\n )}\n </div>,\n );\n }\n\n return (\n <div className={[\"sf-schema\", props.className].filter(Boolean).join(\" \")} style={{ height }}>\n <input\n className=\"sf-input sf-schema-search\"\n type=\"search\"\n placeholder=\"Search tables\"\n aria-label=\"Search tables\"\n value={search}\n onChange={(event) => {\n setSearch(event.target.value);\n setActive(0);\n }}\n />\n <div\n ref={list}\n className=\"sf-schema-list\"\n role=\"tree\"\n aria-label={props.label ?? \"Tables\"}\n aria-busy={status.loading}\n aria-activedescendant={nodes.length > 0 ? `sf-schema-${active}` : undefined}\n tabIndex={0}\n onKeyDown={onKeyDown}\n onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}\n >\n <div style={{ height: nodes.length * rowHeight, position: \"relative\" }}>{rows}</div>\n {status.error && (\n <p className=\"sf-schema-empty\" role=\"alert\">\n {status.error}\n </p>\n )}\n {!status.loading && !status.error && tables.length === 0 && (\n <p className=\"sf-schema-empty\">{search ? `No tables match “${search}”.` : \"This source has no tables.\"}</p>\n )}\n </div>\n </div>\n );\n}\n"]}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A table, a column, or a file or folder, by name: what a person drags out
3
+ * of a browser and drops on a chat, a context builder or an editor. It says
4
+ * which data is meant and carries no values and no file contents.
5
+ */
6
+ export interface DataRef {
7
+ /** The source, or `local:<folder>` for a folder a person opened from their own computer. */
8
+ sourceId: string;
9
+ kind: "table" | "column" | "file";
10
+ catalog?: string;
11
+ /** The schema, or the database on an engine that has no catalog above it. */
12
+ schema?: string;
13
+ /** The table. Empty for a file. */
14
+ table: string;
15
+ column?: string;
16
+ /** A file or folder: its path in the source's storage, or within the folder a person opened (never above it). */
17
+ path?: string;
18
+ }
19
+ /** MIME type carrying a list of `DataRef`s as JSON during drag and drop. */
20
+ export declare const DATA_REFS_MIME = "application/x-surfaces-refs+json";
21
+ /** A reference's name as a person reads it: `schema.table`, or `schema.table.column`. */
22
+ export declare function dataRefLabel(ref: Pick<DataRef, "schema" | "table" | "column" | "path">): string;
23
+ /** The same thing twice is one reference. */
24
+ export declare function sameDataRef(a: DataRef, b: DataRef): boolean;
25
+ /** `more` added to `list`, leaving out what is already there. */
26
+ export declare function addDataRefs(list: DataRef[], more: DataRef[]): DataRef[];
27
+ /** Puts references on a drag: the list, the first one in the older single form, and the names as plain text for anything else. */
28
+ export declare function writeDataRefs(transfer: Pick<DataTransfer, "setData">, refs: DataRef[], text?: string): void;
29
+ /** True when a drag carries references, so a drop target can say it will take it. */
30
+ export declare function hasDataRefs(transfer: Pick<DataTransfer, "types"> | null | undefined): boolean;
31
+ /** The references a drop carries. Anything that is not a well-formed reference is left out. */
32
+ export declare function readDataRefs(transfer: Pick<DataTransfer, "getData"> | null | undefined): DataRef[];
@@ -0,0 +1,65 @@
1
+ import { SCHEMA_REF_MIME } from "./SchemaExplorer.js";
2
+ /** MIME type carrying a list of `DataRef`s as JSON during drag and drop. */
3
+ export const DATA_REFS_MIME = "application/x-surfaces-refs+json";
4
+ const isFile = (ref) => typeof ref.path === "string" && ref.path !== "";
5
+ const isRef = (value) => !!value && typeof value === "object" && typeof value.sourceId === "string" && ((typeof value.table === "string" && value.table !== "") || isFile(value));
6
+ const kindOf = (ref) => (isFile(ref) && !ref.table ? "file" : ref.column ? "column" : "table");
7
+ /** A reference's name as a person reads it: `schema.table`, or `schema.table.column`. */
8
+ export function dataRefLabel(ref) {
9
+ // A file is named by the end of its path: its folder and its own name.
10
+ if (!ref.table && ref.path)
11
+ return ref.path.replace(/\/+$/, "").split("/").slice(-2).join("/");
12
+ return [ref.schema, ref.table, ref.column].filter(Boolean).join(".");
13
+ }
14
+ /** The same thing twice is one reference. */
15
+ export function sameDataRef(a, b) {
16
+ const key = (r) => [r.sourceId, r.catalog ?? "", r.schema ?? "", r.table, r.column ?? "", r.path ?? ""].join("\u0000").toLowerCase();
17
+ return key(a) === key(b);
18
+ }
19
+ /** `more` added to `list`, leaving out what is already there. */
20
+ export function addDataRefs(list, more) {
21
+ const next = [...list];
22
+ for (const ref of more)
23
+ if (!next.some((have) => sameDataRef(have, ref)))
24
+ next.push(ref);
25
+ return next;
26
+ }
27
+ /** Puts references on a drag: the list, the first one in the older single form, and the names as plain text for anything else. */
28
+ export function writeDataRefs(transfer, refs, text) {
29
+ if (refs.length === 0)
30
+ return;
31
+ transfer.setData(DATA_REFS_MIME, JSON.stringify(refs));
32
+ // The older single form names a table, so a file has none.
33
+ const first = refs.find((ref) => ref.table);
34
+ if (first)
35
+ transfer.setData(SCHEMA_REF_MIME, JSON.stringify({ sourceId: first.sourceId, table: first.table, column: first.column }));
36
+ transfer.setData("text/plain", text ?? refs.map(dataRefLabel).join(", "));
37
+ }
38
+ /** True when a drag carries references, so a drop target can say it will take it. */
39
+ export function hasDataRefs(transfer) {
40
+ const types = Array.from(transfer?.types ?? []);
41
+ return types.includes(DATA_REFS_MIME) || types.includes(SCHEMA_REF_MIME);
42
+ }
43
+ /** The references a drop carries. Anything that is not a well-formed reference is left out. */
44
+ export function readDataRefs(transfer) {
45
+ if (!transfer)
46
+ return [];
47
+ try {
48
+ const many = JSON.parse(transfer.getData(DATA_REFS_MIME) || "null");
49
+ if (Array.isArray(many))
50
+ return many.filter(isRef).map((ref) => ({ ...ref, table: ref.table ?? "", kind: kindOf(ref) }));
51
+ }
52
+ catch {
53
+ // Not ours, or not JSON: try the single form.
54
+ }
55
+ try {
56
+ const one = JSON.parse(transfer.getData(SCHEMA_REF_MIME) || "null");
57
+ if (isRef(one))
58
+ return [{ ...one, kind: one.column ? "column" : "table" }];
59
+ }
60
+ catch {
61
+ // Nothing to read.
62
+ }
63
+ return [];
64
+ }
65
+ //# sourceMappingURL=refs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refs.js","sourceRoot":"","sources":["../../src/schema/refs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAkB,MAAM,qBAAqB,CAAC;AAqBtE,4EAA4E;AAC5E,MAAM,CAAC,MAAM,cAAc,GAAG,kCAAkC,CAAC;AAEjE,MAAM,MAAM,GAAG,CAAC,GAAY,EAAE,EAAE,CAAC,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,IAAI,KAAK,EAAE,CAAC;AACj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ACrB,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["import { SCHEMA_REF_MIME, type SchemaRef } from \"./SchemaExplorer.js\";\n\n/**\n * A table, a column, or a file or folder, by name: what a person drags out\n * of a browser and drops on a chat, a context builder or an editor. It says\n * which data is meant and carries no values and no file contents.\n */\nexport interface DataRef {\n /** The source, or `local:<folder>` for a folder a person opened from their own computer. */\n sourceId: string;\n kind: \"table\" | \"column\" | \"file\";\n catalog?: string;\n /** The schema, or the database on an engine that has no catalog above it. */\n schema?: string;\n /** The table. Empty for a file. */\n table: string;\n column?: string;\n /** A file or folder: its path in the source's storage, or within the folder a person opened (never above it). */\n path?: string;\n}\n\n/** MIME type carrying a list of `DataRef`s as JSON during drag and drop. */\nexport const DATA_REFS_MIME = \"application/x-surfaces-refs+json\";\n\nconst isFile = (ref: DataRef) => typeof ref.path === \"string\" && ref.path !== \"\";\nconst isRef = (value: unknown): value is DataRef =>\n !!value && typeof value === \"object\" && typeof (value as DataRef).sourceId === \"string\" && ((typeof (value as DataRef).table === \"string\" && (value as DataRef).table !== \"\") || isFile(value as DataRef));\nconst kindOf = (ref: DataRef): DataRef[\"kind\"] => (isFile(ref) && !ref.table ? \"file\" : ref.column ? \"column\" : \"table\");\n\n/** A reference's name as a person reads it: `schema.table`, or `schema.table.column`. */\nexport function dataRefLabel(ref: Pick<DataRef, \"schema\" | \"table\" | \"column\" | \"path\">): string {\n // A file is named by the end of its path: its folder and its own name.\n if (!ref.table && ref.path) return ref.path.replace(/\\/+$/, \"\").split(\"/\").slice(-2).join(\"/\");\n return [ref.schema, ref.table, ref.column].filter(Boolean).join(\".\");\n}\n\n/** The same thing twice is one reference. */\nexport function sameDataRef(a: DataRef, b: DataRef): boolean {\n const key = (r: DataRef) => [r.sourceId, r.catalog ?? \"\", r.schema ?? \"\", r.table, r.column ?? \"\", r.path ?? \"\"].join(\"\\u0000\").toLowerCase();\n return key(a) === key(b);\n}\n\n/** `more` added to `list`, leaving out what is already there. */\nexport function addDataRefs(list: DataRef[], more: DataRef[]): DataRef[] {\n const next = [...list];\n for (const ref of more) if (!next.some((have) => sameDataRef(have, ref))) next.push(ref);\n return next;\n}\n\n/** Puts references on a drag: the list, the first one in the older single form, and the names as plain text for anything else. */\nexport function writeDataRefs(transfer: Pick<DataTransfer, \"setData\">, refs: DataRef[], text?: string): void {\n if (refs.length === 0) return;\n transfer.setData(DATA_REFS_MIME, JSON.stringify(refs));\n // The older single form names a table, so a file has none.\n const first = refs.find((ref) => ref.table);\n if (first) transfer.setData(SCHEMA_REF_MIME, JSON.stringify({ sourceId: first.sourceId, table: first.table, column: first.column } satisfies SchemaRef));\n transfer.setData(\"text/plain\", text ?? refs.map(dataRefLabel).join(\", \"));\n}\n\n/** True when a drag carries references, so a drop target can say it will take it. */\nexport function hasDataRefs(transfer: Pick<DataTransfer, \"types\"> | null | undefined): boolean {\n const types = Array.from(transfer?.types ?? []);\n return types.includes(DATA_REFS_MIME) || types.includes(SCHEMA_REF_MIME);\n}\n\n/** The references a drop carries. Anything that is not a well-formed reference is left out. */\nexport function readDataRefs(transfer: Pick<DataTransfer, \"getData\"> | null | undefined): DataRef[] {\n if (!transfer) return [];\n try {\n const many = JSON.parse(transfer.getData(DATA_REFS_MIME) || \"null\") as unknown;\n if (Array.isArray(many)) return many.filter(isRef).map((ref) => ({ ...ref, table: ref.table ?? \"\", kind: kindOf(ref) }));\n } catch {\n // Not ours, or not JSON: try the single form.\n }\n try {\n const one = JSON.parse(transfer.getData(SCHEMA_REF_MIME) || \"null\") as unknown;\n if (isRef(one)) return [{ ...one, kind: one.column ? \"column\" : \"table\" }];\n } catch {\n // Nothing to read.\n }\n return [];\n}\n"]}