@surfaces-ui/components 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +51 -2
- package/dist/appComponents.d.ts +86 -0
- package/dist/appComponents.js +555 -0
- package/dist/appComponents.js.map +1 -0
- package/dist/chart/BulletGraph.d.ts +44 -0
- package/dist/chart/BulletGraph.js +41 -0
- package/dist/chart/BulletGraph.js.map +1 -0
- package/dist/chart/Chart.d.ts +178 -0
- package/dist/chart/Chart.js +285 -0
- package/dist/chart/Chart.js.map +1 -0
- package/dist/chart/Sparkline.d.ts +35 -0
- package/dist/chart/Sparkline.js +38 -0
- package/dist/chart/Sparkline.js.map +1 -0
- package/dist/chart/advice.d.ts +32 -0
- package/dist/chart/advice.js +48 -0
- package/dist/chart/advice.js.map +1 -0
- package/dist/chart/option.d.ts +90 -0
- package/dist/chart/option.js +252 -0
- package/dist/chart/option.js.map +1 -0
- package/dist/chart/wheel.d.ts +12 -0
- package/dist/chart/wheel.js +21 -0
- package/dist/chart/wheel.js.map +1 -0
- package/dist/controls/Combobox.d.ts +39 -0
- package/dist/controls/Combobox.js +75 -0
- package/dist/controls/Combobox.js.map +1 -0
- package/dist/controls/ConfirmDialog.d.ts +35 -0
- package/dist/controls/ConfirmDialog.js +84 -0
- package/dist/controls/ConfirmDialog.js.map +1 -0
- package/dist/controls/ItemControls.d.ts +115 -0
- package/dist/controls/ItemControls.js +109 -0
- package/dist/controls/ItemControls.js.map +1 -0
- package/dist/controls/Popover.d.ts +31 -0
- package/dist/controls/Popover.js +114 -0
- package/dist/controls/Popover.js.map +1 -0
- package/dist/controls/ResizeHandle.d.ts +48 -0
- package/dist/controls/ResizeHandle.js +91 -0
- package/dist/controls/ResizeHandle.js.map +1 -0
- package/dist/controls/SegmentedControl.d.ts +27 -0
- package/dist/controls/SegmentedControl.js +17 -0
- package/dist/controls/SegmentedControl.js.map +1 -0
- package/dist/controls/StatusBadge.d.ts +17 -0
- package/dist/controls/StatusBadge.js +10 -0
- package/dist/controls/StatusBadge.js.map +1 -0
- package/dist/controls/context.d.ts +17 -0
- package/dist/controls/context.js +2 -0
- package/dist/controls/context.js.map +1 -0
- package/dist/controls/placement.d.ts +43 -0
- package/dist/controls/placement.js +19 -0
- package/dist/controls/placement.js.map +1 -0
- package/dist/controls/resize.d.ts +23 -0
- package/dist/controls/resize.js +49 -0
- package/dist/controls/resize.js.map +1 -0
- package/dist/data/DataNotes.d.ts +13 -0
- package/dist/data/DataNotes.js +18 -0
- package/dist/data/DataNotes.js.map +1 -0
- package/dist/data/DataSourceProvider.d.ts +11 -0
- package/dist/data/DataSourceProvider.js +21 -0
- package/dist/data/DataSourceProvider.js.map +1 -0
- package/dist/data/export.d.ts +33 -0
- package/dist/data/export.js +77 -0
- package/dist/data/export.js.map +1 -0
- package/dist/data/format.d.ts +44 -0
- package/dist/data/format.js +127 -0
- package/dist/data/format.js.map +1 -0
- package/dist/data/messages.d.ts +13 -0
- package/dist/data/messages.js +2 -0
- package/dist/data/messages.js.map +1 -0
- package/dist/data/useRowWindow.d.ts +70 -0
- package/dist/data/useRowWindow.js +175 -0
- package/dist/data/useRowWindow.js.map +1 -0
- package/dist/discovery/AskData.d.ts +22 -0
- package/dist/discovery/AskData.js +49 -0
- package/dist/discovery/AskData.js.map +1 -0
- package/dist/discovery/ContextBuilder.d.ts +49 -0
- package/dist/discovery/ContextBuilder.js +167 -0
- package/dist/discovery/ContextBuilder.js.map +1 -0
- package/dist/discovery/DataSearch.d.ts +27 -0
- package/dist/discovery/DataSearch.js +73 -0
- package/dist/discovery/DataSearch.js.map +1 -0
- package/dist/discovery/ObjectDetail.d.ts +38 -0
- package/dist/discovery/ObjectDetail.js +129 -0
- package/dist/discovery/ObjectDetail.js.map +1 -0
- package/dist/discovery/RelationshipGraph.d.ts +19 -0
- package/dist/discovery/RelationshipGraph.js +64 -0
- package/dist/discovery/RelationshipGraph.js.map +1 -0
- package/dist/discovery/shared.d.ts +38 -0
- package/dist/discovery/shared.js +64 -0
- package/dist/discovery/shared.js.map +1 -0
- package/dist/editor/SqlEditor.d.ts +41 -0
- package/dist/editor/SqlEditor.js +181 -0
- package/dist/editor/SqlEditor.js.map +1 -0
- package/dist/explore/Explorer.d.ts +110 -0
- package/dist/explore/Explorer.js +471 -0
- package/dist/explore/Explorer.js.map +1 -0
- package/dist/explore/ModelLineage.d.ts +22 -0
- package/dist/explore/ModelLineage.js +70 -0
- package/dist/explore/ModelLineage.js.map +1 -0
- package/dist/explore/ReportBuilder.d.ts +39 -0
- package/dist/explore/ReportBuilder.js +98 -0
- package/dist/explore/ReportBuilder.js.map +1 -0
- package/dist/explore/SemanticModelEditor.d.ts +60 -0
- package/dist/explore/SemanticModelEditor.js +220 -0
- package/dist/explore/SemanticModelEditor.js.map +1 -0
- package/dist/explore/SemanticRows.d.ts +42 -0
- package/dist/explore/SemanticRows.js +121 -0
- package/dist/explore/SemanticRows.js.map +1 -0
- package/dist/explore/SemanticsProvider.d.ts +31 -0
- package/dist/explore/SemanticsProvider.js +72 -0
- package/dist/explore/SemanticsProvider.js.map +1 -0
- package/dist/explore/model.d.ts +151 -0
- package/dist/explore/model.js +344 -0
- package/dist/explore/model.js.map +1 -0
- package/dist/explore/report.d.ts +60 -0
- package/dist/explore/report.js +92 -0
- package/dist/explore/report.js.map +1 -0
- package/dist/explore/semantic-proposal.d.ts +44 -0
- package/dist/explore/semantic-proposal.js +67 -0
- package/dist/explore/semantic-proposal.js.map +1 -0
- package/dist/explore/semantic.d.ts +44 -0
- package/dist/explore/semantic.js +154 -0
- package/dist/explore/semantic.js.map +1 -0
- package/dist/files/FileBrowser.d.ts +42 -0
- package/dist/files/FileBrowser.js +314 -0
- package/dist/files/FileBrowser.js.map +1 -0
- package/dist/files/files.d.ts +65 -0
- package/dist/files/files.js +165 -0
- package/dist/files/files.js.map +1 -0
- package/dist/filter/FilterBar.d.ts +49 -0
- package/dist/filter/FilterBar.js +153 -0
- package/dist/filter/FilterBar.js.map +1 -0
- package/dist/filter/QueryFilters.d.ts +25 -0
- package/dist/filter/QueryFilters.js +58 -0
- package/dist/filter/QueryFilters.js.map +1 -0
- package/dist/form/Form.d.ts +76 -0
- package/dist/form/Form.js +131 -0
- package/dist/form/Form.js.map +1 -0
- package/dist/graph/NodeGraph.d.ts +30 -0
- package/dist/graph/NodeGraph.js +89 -0
- package/dist/graph/NodeGraph.js.map +1 -0
- package/dist/graph/model.d.ts +68 -0
- package/dist/graph/model.js +122 -0
- package/dist/graph/model.js.map +1 -0
- package/dist/grid/DataGrid.d.ts +98 -0
- package/dist/grid/DataGrid.js +400 -0
- package/dist/grid/DataGrid.js.map +1 -0
- package/dist/index.d.ts +85 -0
- package/dist/index.js +87 -0
- package/dist/index.js.map +1 -0
- package/dist/locale/SurfacesText.d.ts +17 -0
- package/dist/locale/SurfacesText.js +17 -0
- package/dist/locale/SurfacesText.js.map +1 -0
- package/dist/locale/locale.d.ts +305 -0
- package/dist/locale/locale.js +359 -0
- package/dist/locale/locale.js.map +1 -0
- package/dist/menu/ContextMenu.d.ts +31 -0
- package/dist/menu/ContextMenu.js +95 -0
- package/dist/menu/ContextMenu.js.map +1 -0
- package/dist/metric/Metric.d.ts +33 -0
- package/dist/metric/Metric.js +64 -0
- package/dist/metric/Metric.js.map +1 -0
- package/dist/metric/useMeasure.d.ts +25 -0
- package/dist/metric/useMeasure.js +44 -0
- package/dist/metric/useMeasure.js.map +1 -0
- package/dist/model/ModelDiagram.d.ts +142 -0
- package/dist/model/ModelDiagram.js +700 -0
- package/dist/model/ModelDiagram.js.map +1 -0
- package/dist/panzoom/usePanZoom.d.ts +117 -0
- package/dist/panzoom/usePanZoom.js +313 -0
- package/dist/panzoom/usePanZoom.js.map +1 -0
- package/dist/pipeline/DatasetReview.d.ts +48 -0
- package/dist/pipeline/DatasetReview.js +157 -0
- package/dist/pipeline/DatasetReview.js.map +1 -0
- package/dist/pipeline/IngestWizard.d.ts +51 -0
- package/dist/pipeline/IngestWizard.js +79 -0
- package/dist/pipeline/IngestWizard.js.map +1 -0
- package/dist/pipeline/Pipeline.d.ts +171 -0
- package/dist/pipeline/Pipeline.js +203 -0
- package/dist/pipeline/Pipeline.js.map +1 -0
- package/dist/pipeline/PipelineView.d.ts +63 -0
- package/dist/pipeline/PipelineView.js +239 -0
- package/dist/pipeline/PipelineView.js.map +1 -0
- package/dist/pivot/PivotTable.d.ts +94 -0
- package/dist/pivot/PivotTable.js +176 -0
- package/dist/pivot/PivotTable.js.map +1 -0
- package/dist/plan/QueryPlan.d.ts +29 -0
- package/dist/plan/QueryPlan.js +79 -0
- package/dist/plan/QueryPlan.js.map +1 -0
- package/dist/result/QueryResult.d.ts +51 -0
- package/dist/result/QueryResult.js +256 -0
- package/dist/result/QueryResult.js.map +1 -0
- package/dist/review/ActionReceipt.d.ts +52 -0
- package/dist/review/ActionReceipt.js +32 -0
- package/dist/review/ActionReceipt.js.map +1 -0
- package/dist/review/PiiReview.d.ts +37 -0
- package/dist/review/PiiReview.js +29 -0
- package/dist/review/PiiReview.js.map +1 -0
- package/dist/review/PlanReview.d.ts +42 -0
- package/dist/review/PlanReview.js +37 -0
- package/dist/review/PlanReview.js.map +1 -0
- package/dist/review/StepFlow.d.ts +25 -0
- package/dist/review/StepFlow.js +21 -0
- package/dist/review/StepFlow.js.map +1 -0
- package/dist/review/pii.d.ts +21 -0
- package/dist/review/pii.js +67 -0
- package/dist/review/pii.js.map +1 -0
- package/dist/rows/RowList.d.ts +41 -0
- package/dist/rows/RowList.js +72 -0
- package/dist/rows/RowList.js.map +1 -0
- package/dist/schema/ObjectBrowser.d.ts +78 -0
- package/dist/schema/ObjectBrowser.js +467 -0
- package/dist/schema/ObjectBrowser.js.map +1 -0
- package/dist/schema/ObjectInfo.d.ts +25 -0
- package/dist/schema/ObjectInfo.js +69 -0
- package/dist/schema/ObjectInfo.js.map +1 -0
- package/dist/schema/SchemaExplorer.d.ts +32 -0
- package/dist/schema/SchemaExplorer.js +175 -0
- package/dist/schema/SchemaExplorer.js.map +1 -0
- package/dist/schema/refs.d.ts +32 -0
- package/dist/schema/refs.js +65 -0
- package/dist/schema/refs.js.map +1 -0
- package/dist/site/Site.d.ts +191 -0
- package/dist/site/Site.js +138 -0
- package/dist/site/Site.js.map +1 -0
- package/dist/source/ConnectionBuilder.d.ts +54 -0
- package/dist/source/ConnectionBuilder.js +115 -0
- package/dist/source/ConnectionBuilder.js.map +1 -0
- package/dist/source/SourceList.d.ts +17 -0
- package/dist/source/SourceList.js +71 -0
- package/dist/source/SourceList.js.map +1 -0
- package/dist/styles.css +9930 -0
- package/dist/styles.layer.css +9934 -0
- package/dist/table/DataTable.d.ts +72 -0
- package/dist/table/DataTable.js +68 -0
- package/dist/table/DataTable.js.map +1 -0
- package/dist/table/Pagination.d.ts +20 -0
- package/dist/table/Pagination.js +16 -0
- package/dist/table/Pagination.js.map +1 -0
- package/dist/table/SelectionBar.d.ts +43 -0
- package/dist/table/SelectionBar.js +18 -0
- package/dist/table/SelectionBar.js.map +1 -0
- package/dist/text/Markdown.d.ts +71 -0
- package/dist/text/Markdown.js +187 -0
- package/dist/text/Markdown.js.map +1 -0
- package/dist/text/highlight.d.ts +23 -0
- package/dist/text/highlight.js +196 -0
- package/dist/text/highlight.js.map +1 -0
- package/dist/theme/ThemePicker.d.ts +16 -0
- package/dist/theme/ThemePicker.js +50 -0
- package/dist/theme/ThemePicker.js.map +1 -0
- package/dist/theme/ThemeProvider.d.ts +52 -0
- package/dist/theme/ThemeProvider.js +111 -0
- package/dist/theme/ThemeProvider.js.map +1 -0
- package/dist/workspace/NavBar.d.ts +23 -0
- package/dist/workspace/NavBar.js +171 -0
- package/dist/workspace/NavBar.js.map +1 -0
- package/dist/workspace/SideNav.d.ts +61 -0
- package/dist/workspace/SideNav.js +149 -0
- package/dist/workspace/SideNav.js.map +1 -0
- package/dist/workspace/Workspace.d.ts +53 -0
- package/dist/workspace/Workspace.js +243 -0
- package/dist/workspace/Workspace.js.map +1 -0
- package/dist/workspace/icons.d.ts +34 -0
- package/dist/workspace/icons.js +37 -0
- package/dist/workspace/icons.js.map +1 -0
- package/dist/workspace/layout.d.ts +74 -0
- package/dist/workspace/layout.js +276 -0
- package/dist/workspace/layout.js.map +1 -0
- package/package.json +85 -3
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { create } from "@bufbuild/protobuf";
|
|
3
|
+
import { checkSubmission, fieldAsked, fieldCondition } from "@surfaces-ui/data";
|
|
4
|
+
import { FieldType, FormDefinitionSchema } from "@surfaces-ui/proto";
|
|
5
|
+
import { createContext, useContext, useId, useRef, useState } from "react";
|
|
6
|
+
import { label as text } from "../locale/locale.js";
|
|
7
|
+
const FormsContext = createContext(undefined);
|
|
8
|
+
/** Supplies where forms send their submissions. Without it a form only reports what was entered. */
|
|
9
|
+
export function FormsProvider({ forms, children }) {
|
|
10
|
+
return _jsx(FormsContext.Provider, { value: forms, children: children });
|
|
11
|
+
}
|
|
12
|
+
export function useOptionalForms(override) {
|
|
13
|
+
const context = useContext(FormsContext);
|
|
14
|
+
return override ?? context;
|
|
15
|
+
}
|
|
16
|
+
const KIND_TYPE = {
|
|
17
|
+
text: FieldType.TEXT,
|
|
18
|
+
longtext: FieldType.TEXT,
|
|
19
|
+
number: FieldType.NUMBER,
|
|
20
|
+
integer: FieldType.INTEGER,
|
|
21
|
+
boolean: FieldType.BOOLEAN,
|
|
22
|
+
date: FieldType.DATE,
|
|
23
|
+
datetime: FieldType.DATETIME,
|
|
24
|
+
choice: FieldType.CHOICE,
|
|
25
|
+
};
|
|
26
|
+
/** The fields as the backend's form definition, so the browser checks exactly what the server will. */
|
|
27
|
+
export function formDefinition(formId, fields) {
|
|
28
|
+
return create(FormDefinitionSchema, {
|
|
29
|
+
id: formId,
|
|
30
|
+
fields: fields.map((f) => ({ name: f.name, label: f.label, type: KIND_TYPE[f.type], required: f.required ?? false, options: f.options ?? [], min: f.min, max: f.max, maxLength: f.maxLength, pattern: f.pattern ?? "", help: f.help ?? "", visibleWhen: fieldCondition(f.visibleWhen) })),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/** One labelled input of the right kind, with its help and its error tied to it for assistive technology. */
|
|
34
|
+
export function FieldInput({ field, value, onChange, error, disabled }) {
|
|
35
|
+
const id = useId();
|
|
36
|
+
const describedBy = [field.help ? `${id}-help` : "", error ? `${id}-error` : ""].filter(Boolean).join(" ") || undefined;
|
|
37
|
+
const common = { id, name: field.name, disabled, "aria-invalid": error ? true : undefined, "aria-describedby": describedBy, required: field.required };
|
|
38
|
+
const str = value == null ? "" : String(value);
|
|
39
|
+
let input;
|
|
40
|
+
switch (field.type) {
|
|
41
|
+
case "longtext":
|
|
42
|
+
input = _jsx("textarea", { ...common, className: "sf-input sf-form-textarea", value: str, maxLength: field.maxLength, placeholder: field.placeholder, onChange: (e) => onChange(e.target.value) });
|
|
43
|
+
break;
|
|
44
|
+
case "number":
|
|
45
|
+
case "integer":
|
|
46
|
+
input = (_jsx("input", { ...common, className: "sf-input", type: "number", inputMode: field.type === "integer" ? "numeric" : "decimal", value: str, min: field.min, max: field.max, step: field.step ?? (field.type === "integer" ? 1 : "any"), placeholder: field.placeholder, onChange: (e) => onChange(e.target.value === "" ? "" : Number(e.target.value)) }));
|
|
47
|
+
break;
|
|
48
|
+
case "boolean":
|
|
49
|
+
return (_jsxs("div", { className: "sf-form-field sf-form-check", children: [_jsx("input", { ...common, required: undefined, type: "checkbox", checked: value === true, onChange: (e) => onChange(e.target.checked) }), _jsx("label", { htmlFor: id, children: field.label }), field.help && _jsx("p", { id: `${id}-help`, className: "sf-form-help", children: field.help }), error && _jsx("p", { id: `${id}-error`, className: "sf-form-error", role: "alert", children: error })] }));
|
|
50
|
+
case "date":
|
|
51
|
+
input = _jsx("input", { ...common, className: "sf-input", type: "date", value: str, onChange: (e) => onChange(e.target.value) });
|
|
52
|
+
break;
|
|
53
|
+
case "datetime":
|
|
54
|
+
input = _jsx("input", { ...common, className: "sf-input", type: "datetime-local", value: str.replace(/Z$/, "").slice(0, 16), onChange: (e) => onChange(e.target.value ? new Date(e.target.value).toISOString() : "") });
|
|
55
|
+
break;
|
|
56
|
+
case "choice":
|
|
57
|
+
input =
|
|
58
|
+
(field.options?.length ?? 0) <= 4 ? (_jsx("div", { role: "radiogroup", "aria-labelledby": `${id}-label`, "aria-describedby": describedBy, className: "sf-form-choices", children: (field.options ?? []).map((option) => (_jsxs("label", { className: "sf-form-choice", children: [_jsx("input", { type: "radio", name: `${id}-${field.name}`, value: option, checked: str === option, disabled: disabled, onChange: () => onChange(option) }), option] }, option))) })) : (_jsxs("select", { ...common, className: "sf-input", value: str, onChange: (e) => onChange(e.target.value), children: [_jsx("option", { value: "", children: text("form.choose") }), (field.options ?? []).map((option) => (_jsx("option", { value: option, children: option }, option)))] }));
|
|
59
|
+
break;
|
|
60
|
+
default:
|
|
61
|
+
input = _jsx("input", { ...common, className: "sf-input", type: "text", value: str, maxLength: field.maxLength, placeholder: field.placeholder, onChange: (e) => onChange(e.target.value) });
|
|
62
|
+
}
|
|
63
|
+
return (_jsxs("div", { className: "sf-form-field", children: [_jsxs("label", { id: `${id}-label`, htmlFor: field.type === "choice" && (field.options?.length ?? 0) <= 4 ? undefined : id, className: "sf-form-label", children: [field.label, field.required && _jsxs("span", { className: "sf-form-required", children: [" ", text("form.required")] })] }), input, field.help && (_jsx("p", { id: `${id}-help`, className: "sf-form-help", children: field.help })), error && (_jsx("p", { id: `${id}-error`, className: "sf-form-error", role: "alert", children: error }))] }));
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* A form that checks what a person entered against its fields and submits
|
|
67
|
+
* it. The same rules run again in the backend, which decides where the
|
|
68
|
+
* values are stored; this component never names a table or writes SQL.
|
|
69
|
+
* Errors are shown beside each field and announced; nothing is sent while
|
|
70
|
+
* any field is wrong.
|
|
71
|
+
*/
|
|
72
|
+
export function Form(props) {
|
|
73
|
+
const { formId, fields, title, description, submitLabel = text("form.submit"), onSubmit, children } = props;
|
|
74
|
+
const forms = useOptionalForms(props.forms);
|
|
75
|
+
const [own, setOwn] = useState({});
|
|
76
|
+
const values = props.values ?? own;
|
|
77
|
+
const [errors, setErrors] = useState({});
|
|
78
|
+
const [status, setStatus] = useState({ kind: "idle" });
|
|
79
|
+
const key = useRef(0);
|
|
80
|
+
const headingId = useId();
|
|
81
|
+
const setValues = (next) => {
|
|
82
|
+
if (props.values === undefined)
|
|
83
|
+
setOwn(next);
|
|
84
|
+
props.onValuesChange?.(next);
|
|
85
|
+
};
|
|
86
|
+
const change = (name, value) => {
|
|
87
|
+
setValues({ ...values, [name]: value });
|
|
88
|
+
if (errors[name])
|
|
89
|
+
setErrors(({ [name]: _gone, ...rest }) => rest);
|
|
90
|
+
};
|
|
91
|
+
const definition = formDefinition(formId, fields);
|
|
92
|
+
// Fields that wait on another are drawn only while it holds what they wait for.
|
|
93
|
+
const asked = fields.filter((_, index) => fieldAsked(definition, definition.fields[index], values));
|
|
94
|
+
const submit = async (event) => {
|
|
95
|
+
event.preventDefault();
|
|
96
|
+
if (status.kind === "sending")
|
|
97
|
+
return;
|
|
98
|
+
const checked = checkSubmission(definition, values);
|
|
99
|
+
if (checked.errors.length > 0) {
|
|
100
|
+
setErrors(Object.fromEntries(checked.errors.map((e) => [e.field, e.message])));
|
|
101
|
+
setStatus({ kind: "rejected", text: checked.errors.length === 1 ? text("form.needsAttentionOne") : text("form.needsAttention", { count: checked.errors.length }) });
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
setErrors({});
|
|
105
|
+
if (!forms) {
|
|
106
|
+
onSubmit?.({ values: checked.values });
|
|
107
|
+
setStatus({ kind: "saved", text: text("form.sent") });
|
|
108
|
+
if (props.resetOnSubmit !== false)
|
|
109
|
+
setValues({});
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
setStatus({ kind: "sending" });
|
|
113
|
+
try {
|
|
114
|
+
const response = await forms.submit({ formId, values: checked.values, idempotencyKey: `${formId}-${Date.now()}-${key.current++}` });
|
|
115
|
+
if (!response.submission) {
|
|
116
|
+
setErrors(Object.fromEntries(response.fieldErrors.map((e) => [e.field, e.message])));
|
|
117
|
+
setStatus({ kind: "rejected", text: response.message || text("form.notSaved") });
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
setStatus({ kind: "saved", text: response.message || text("form.saved") });
|
|
121
|
+
onSubmit?.({ submissionId: response.submission.id, values: (response.submission.values ?? checked.values) });
|
|
122
|
+
if (props.resetOnSubmit !== false)
|
|
123
|
+
setValues({});
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
setStatus({ kind: "rejected", text: text("form.couldNotSend", { error: error instanceof Error ? error.message : String(error) }) });
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
return (_jsxs("form", { className: ["sf-form", props.className].filter(Boolean).join(" "), onSubmit: submit, noValidate: true, "aria-labelledby": title ? headingId : undefined, children: [title && (_jsx("p", { id: headingId, className: "sf-form-title", children: title })), description && _jsx("p", { className: "sf-form-help", children: description }), children ?? asked.map((field) => _jsx(FieldInput, { field: field, value: values[field.name], error: errors[field.name], disabled: status.kind === "sending", onChange: (v) => change(field.name, v) }, field.name)), children && Object.keys(errors).length > 0 && (_jsx("ul", { className: "sf-form-error", role: "alert", children: Object.entries(errors).map(([name, message]) => (_jsxs("li", { children: [fields.find((f) => f.name === name)?.label ?? name, ": ", message] }, name))) })), _jsxs("div", { className: "sf-form-actions", children: [_jsx("button", { type: "submit", className: "sf-button", "data-variant": "primary", disabled: status.kind === "sending", "aria-busy": status.kind === "sending" || undefined, children: status.kind === "sending" ? text("form.sending") : submitLabel }), _jsx("p", { className: status.kind === "rejected" ? "sf-form-error" : "sf-form-status", role: "status", "aria-live": "polite", children: status.kind === "saved" || status.kind === "rejected" ? status.text : "" })] }), _jsx("p", { className: "sf-form-help", children: forms ? text("form.connected") : text("form.notConnected") })] }));
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AC,EAAE,KAAK,IAAI,IAAI,QAAI,OAAO,KADvD,IAAI,CAER,CACN,CAAC,GACC,CACN,EACD,eAAK,SAAS,EAAC,iBAAiB,aAC9B,iBAAQ,IAAI,EAAC,QAAQ,EAAC,SAAS,EAAC,WAAW,kBAAc,SAAS,EAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,KAAK,SAAS,eAAa,MAAM,CAAC,IAAI,KAAK,SAAS,IAAI,SAAS,YACtJ,MAAM,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,WAAW,GACxD,EACT,YAAG,SAAS,EAAE,MAAM,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,gBAAgB,EAAE,IAAI,EAAC,QAAQ,eAAW,QAAQ,YAC5G,MAAM,CAAC,IAAI,KAAK,OAAO,IAAI,MAAM,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GACvE,IACA,EACN,YAAG,SAAS,EAAC,cAAc,YAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAK,IACvF,CACR,CAAC;AACJ,CAAC","sourcesContent":["import { create, type JsonObject, type JsonValue } from \"@bufbuild/protobuf\";\nimport { type FieldConditionSpec, type Forms, checkSubmission, fieldAsked, fieldCondition } from \"@surfaces-ui/data\";\nimport { FieldType, FormDefinitionSchema } from \"@surfaces-ui/proto\";\nimport { type FormEvent, type ReactNode, createContext, useContext, useId, useRef, useState } from \"react\";\nimport { label as text } from \"../locale/locale.js\";\n\nconst FormsContext = createContext<Forms | undefined>(undefined);\n\n/** Supplies where forms send their submissions. Without it a form only reports what was entered. */\nexport function FormsProvider({ forms, children }: { forms: Forms; children: ReactNode }) {\n return <FormsContext.Provider value={forms}>{children}</FormsContext.Provider>;\n}\n\nexport function useOptionalForms(override?: Forms): Forms | undefined {\n const context = useContext(FormsContext);\n return override ?? context;\n}\n\nexport type FormFieldKind = \"text\" | \"longtext\" | \"number\" | \"integer\" | \"boolean\" | \"date\" | \"datetime\" | \"choice\";\n\n/** One field of a form: what it holds and the rules it must meet. The same rules are checked again by the backend. */\nexport interface FormFieldSpec {\n /** The key the value is sent and stored under. */\n name: string;\n label: string;\n type: FormFieldKind;\n required?: boolean;\n /** For \"choice\". */\n options?: string[];\n min?: number;\n max?: number;\n step?: number;\n maxLength?: number;\n /** A regular expression the whole text must match. */\n pattern?: string;\n /** A sentence under the field, outside the label. */\n help?: string;\n placeholder?: string;\n /** Asked for only while another field of the form holds this: `{ field: \"kind\", equals: \"Table\" }`. Not drawn, not required and sent as null otherwise. */\n visibleWhen?: FieldConditionSpec;\n}\n\nconst KIND_TYPE: Record<FormFieldKind, FieldType> = {\n text: FieldType.TEXT,\n longtext: FieldType.TEXT,\n number: FieldType.NUMBER,\n integer: FieldType.INTEGER,\n boolean: FieldType.BOOLEAN,\n date: FieldType.DATE,\n datetime: FieldType.DATETIME,\n choice: FieldType.CHOICE,\n};\n\n/** The fields as the backend's form definition, so the browser checks exactly what the server will. */\nexport function formDefinition(formId: string, fields: FormFieldSpec[]) {\n return create(FormDefinitionSchema, {\n id: formId,\n fields: fields.map((f) => ({ name: f.name, label: f.label, type: KIND_TYPE[f.type], required: f.required ?? false, options: f.options ?? [], min: f.min, max: f.max, maxLength: f.maxLength, pattern: f.pattern ?? \"\", help: f.help ?? \"\", visibleWhen: fieldCondition(f.visibleWhen) })),\n });\n}\n\nexport interface FieldInputProps {\n field: FormFieldSpec;\n value: unknown;\n onChange(value: JsonValue): void;\n error?: string;\n disabled?: boolean;\n}\n\n/** One labelled input of the right kind, with its help and its error tied to it for assistive technology. */\nexport function FieldInput({ field, value, onChange, error, disabled }: FieldInputProps) {\n const id = useId();\n const describedBy = [field.help ? `${id}-help` : \"\", error ? `${id}-error` : \"\"].filter(Boolean).join(\" \") || undefined;\n const common = { id, name: field.name, disabled, \"aria-invalid\": error ? true : undefined, \"aria-describedby\": describedBy, required: field.required };\n const str = value == null ? \"\" : String(value);\n let input: ReactNode;\n switch (field.type) {\n case \"longtext\":\n input = <textarea {...common} className=\"sf-input sf-form-textarea\" value={str} maxLength={field.maxLength} placeholder={field.placeholder} onChange={(e) => onChange(e.target.value)} />;\n break;\n case \"number\":\n case \"integer\":\n input = (\n <input\n {...common}\n className=\"sf-input\"\n type=\"number\"\n inputMode={field.type === \"integer\" ? \"numeric\" : \"decimal\"}\n value={str}\n min={field.min}\n max={field.max}\n step={field.step ?? (field.type === \"integer\" ? 1 : \"any\")}\n placeholder={field.placeholder}\n onChange={(e) => onChange(e.target.value === \"\" ? \"\" : Number(e.target.value))}\n />\n );\n break;\n case \"boolean\":\n return (\n <div className=\"sf-form-field sf-form-check\">\n <input {...common} required={undefined} type=\"checkbox\" checked={value === true} onChange={(e) => onChange(e.target.checked)} />\n <label htmlFor={id}>{field.label}</label>\n {field.help && <p id={`${id}-help`} className=\"sf-form-help\">{field.help}</p>}\n {error && <p id={`${id}-error`} className=\"sf-form-error\" role=\"alert\">{error}</p>}\n </div>\n );\n case \"date\":\n input = <input {...common} className=\"sf-input\" type=\"date\" value={str} onChange={(e) => onChange(e.target.value)} />;\n break;\n case \"datetime\":\n input = <input {...common} className=\"sf-input\" type=\"datetime-local\" value={str.replace(/Z$/, \"\").slice(0, 16)} onChange={(e) => onChange(e.target.value ? new Date(e.target.value).toISOString() : \"\")} />;\n break;\n case \"choice\":\n input =\n (field.options?.length ?? 0) <= 4 ? (\n <div role=\"radiogroup\" aria-labelledby={`${id}-label`} aria-describedby={describedBy} className=\"sf-form-choices\">\n {(field.options ?? []).map((option) => (\n <label key={option} className=\"sf-form-choice\">\n <input type=\"radio\" name={`${id}-${field.name}`} value={option} checked={str === option} disabled={disabled} onChange={() => onChange(option)} />\n {option}\n </label>\n ))}\n </div>\n ) : (\n <select {...common} className=\"sf-input\" value={str} onChange={(e) => onChange(e.target.value)}>\n <option value=\"\">{text(\"form.choose\")}</option>\n {(field.options ?? []).map((option) => (\n <option key={option} value={option}>\n {option}\n </option>\n ))}\n </select>\n );\n break;\n default:\n input = <input {...common} className=\"sf-input\" type=\"text\" value={str} maxLength={field.maxLength} placeholder={field.placeholder} onChange={(e) => onChange(e.target.value)} />;\n }\n return (\n <div className=\"sf-form-field\">\n <label id={`${id}-label`} htmlFor={field.type === \"choice\" && (field.options?.length ?? 0) <= 4 ? undefined : id} className=\"sf-form-label\">\n {field.label}\n {field.required && <span className=\"sf-form-required\"> {text(\"form.required\")}</span>}\n </label>\n {input}\n {field.help && (\n <p id={`${id}-help`} className=\"sf-form-help\">\n {field.help}\n </p>\n )}\n {error && (\n <p id={`${id}-error`} className=\"sf-form-error\" role=\"alert\">\n {error}\n </p>\n )}\n </div>\n );\n}\n\nexport interface FormResult {\n /** Stored by the backend, with its id. */\n submissionId?: string;\n /** What was sent, after checking: numbers as numbers, times in UTC. */\n values: JsonObject;\n}\n\nexport interface FormProps {\n /** The form as the backend knows it. With a `Forms` backend, submissions go there under this id. */\n formId: string;\n fields: FormFieldSpec[];\n title?: string;\n description?: string;\n submitLabel?: string;\n /** The values; leave out to let the form keep its own. */\n values?: JsonObject;\n onValuesChange?(values: JsonObject): void;\n /** Called after the values pass every check (and, with a backend, after it stored them). */\n onSubmit?(result: FormResult): void;\n /** Where to send submissions. Defaults to `FormsProvider`; without either, the form only calls `onSubmit`. */\n forms?: Forms;\n /** Lay the fields out yourself; the form still checks and submits them. */\n children?: ReactNode;\n /** Clear the form after a successful submission. Default true. */\n resetOnSubmit?: boolean;\n className?: string;\n}\n\ntype Status = { kind: \"idle\" } | { kind: \"sending\" } | { kind: \"saved\"; text: string } | { kind: \"rejected\"; text: string };\n\n/**\n * A form that checks what a person entered against its fields and submits\n * it. The same rules run again in the backend, which decides where the\n * values are stored; this component never names a table or writes SQL.\n * Errors are shown beside each field and announced; nothing is sent while\n * any field is wrong.\n */\nexport function Form(props: FormProps) {\n const { formId, fields, title, description, submitLabel = text(\"form.submit\"), onSubmit, children } = props;\n const forms = useOptionalForms(props.forms);\n const [own, setOwn] = useState<JsonObject>({});\n const values = props.values ?? own;\n const [errors, setErrors] = useState<Record<string, string>>({});\n const [status, setStatus] = useState<Status>({ kind: \"idle\" });\n const key = useRef(0);\n const headingId = useId();\n\n const setValues = (next: JsonObject) => {\n if (props.values === undefined) setOwn(next);\n props.onValuesChange?.(next);\n };\n const change = (name: string, value: JsonValue) => {\n setValues({ ...values, [name]: value });\n if (errors[name]) setErrors(({ [name]: _gone, ...rest }) => rest);\n };\n\n const definition = formDefinition(formId, fields);\n // Fields that wait on another are drawn only while it holds what they wait for.\n const asked = fields.filter((_, index) => fieldAsked(definition, definition.fields[index]!, values));\n\n const submit = async (event: FormEvent) => {\n event.preventDefault();\n if (status.kind === \"sending\") return;\n const checked = checkSubmission(definition, values);\n if (checked.errors.length > 0) {\n setErrors(Object.fromEntries(checked.errors.map((e) => [e.field, e.message])));\n setStatus({ kind: \"rejected\", text: checked.errors.length === 1 ? text(\"form.needsAttentionOne\") : text(\"form.needsAttention\", { count: checked.errors.length }) });\n return;\n }\n setErrors({});\n if (!forms) {\n onSubmit?.({ values: checked.values });\n setStatus({ kind: \"saved\", text: text(\"form.sent\") });\n if (props.resetOnSubmit !== false) setValues({});\n return;\n }\n setStatus({ kind: \"sending\" });\n try {\n const response = await forms.submit({ formId, values: checked.values, idempotencyKey: `${formId}-${Date.now()}-${key.current++}` });\n if (!response.submission) {\n setErrors(Object.fromEntries(response.fieldErrors.map((e) => [e.field, e.message])));\n setStatus({ kind: \"rejected\", text: response.message || text(\"form.notSaved\") });\n return;\n }\n setStatus({ kind: \"saved\", text: response.message || text(\"form.saved\") });\n onSubmit?.({ submissionId: response.submission.id, values: (response.submission.values ?? checked.values) as JsonObject });\n if (props.resetOnSubmit !== false) setValues({});\n } catch (error) {\n setStatus({ kind: \"rejected\", text: text(\"form.couldNotSend\", { error: error instanceof Error ? error.message : String(error) }) });\n }\n };\n\n return (\n <form className={[\"sf-form\", props.className].filter(Boolean).join(\" \")} onSubmit={submit} noValidate aria-labelledby={title ? headingId : undefined}>\n {title && (\n <p id={headingId} className=\"sf-form-title\">\n {title}\n </p>\n )}\n {description && <p className=\"sf-form-help\">{description}</p>}\n {children ?? asked.map((field) => <FieldInput key={field.name} field={field} value={values[field.name]} error={errors[field.name]} disabled={status.kind === \"sending\"} onChange={(v) => change(field.name, v)} />)}\n {children && Object.keys(errors).length > 0 && (\n <ul className=\"sf-form-error\" role=\"alert\">\n {Object.entries(errors).map(([name, message]) => (\n <li key={name}>\n {fields.find((f) => f.name === name)?.label ?? name}: {message}\n </li>\n ))}\n </ul>\n )}\n <div className=\"sf-form-actions\">\n <button type=\"submit\" className=\"sf-button\" data-variant=\"primary\" disabled={status.kind === \"sending\"} aria-busy={status.kind === \"sending\" || undefined}>\n {status.kind === \"sending\" ? text(\"form.sending\") : submitLabel}\n </button>\n <p className={status.kind === \"rejected\" ? \"sf-form-error\" : \"sf-form-status\"} role=\"status\" aria-live=\"polite\">\n {status.kind === \"saved\" || status.kind === \"rejected\" ? status.text : \"\"}\n </p>\n </div>\n <p className=\"sf-form-help\">{forms ? text(\"form.connected\") : text(\"form.notConnected\")}</p>\n </form>\n );\n}\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ContextNote } from "../controls/context.js";
|
|
2
|
+
import { type GraphLink, type GraphNode } from "./model.js";
|
|
3
|
+
export interface NodeGraphProps {
|
|
4
|
+
/** What the graph shows, for assistive technology: "Terms and how they are linked". */
|
|
5
|
+
label: string;
|
|
6
|
+
nodes: GraphNode[];
|
|
7
|
+
links: GraphLink[];
|
|
8
|
+
/** The node that is open. */
|
|
9
|
+
selected?: string;
|
|
10
|
+
onSelect?(id: string): void;
|
|
11
|
+
/** The order groups take colours and appear in the legend. */
|
|
12
|
+
groups?: readonly string[];
|
|
13
|
+
/** What a level means in words, for the list: `{ full: "Certified", half: "Partly certified", outline: "Not certified" }`. */
|
|
14
|
+
levels?: Partial<Record<NonNullable<GraphNode["level"]>, string>>;
|
|
15
|
+
/** What the nodes are called: "term" gives "7 terms". Default "node". */
|
|
16
|
+
noun?: string;
|
|
17
|
+
height?: number;
|
|
18
|
+
/** The most nodes drawn at once; past it the graph shows what is around the selected node. */
|
|
19
|
+
limit?: number;
|
|
20
|
+
/** Told what a person does here, as context for an agent. */
|
|
21
|
+
onContext?(note: ContextNote): void;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Things and the links between them, drawn as a graph and listed beside it. The list does everything the canvas
|
|
25
|
+
* does (find a node, open it, walk to a neighbour), so the graph is never the only way in. The layout settles and
|
|
26
|
+
* stops; under reduced motion it is placed without moving. When the nodes change, those already drawn keep their
|
|
27
|
+
* places and the new ones grow in, so a graph can be watched as it fills. A large graph shows what is around one node and says
|
|
28
|
+
* how many it left out.
|
|
29
|
+
*/
|
|
30
|
+
export declare function NodeGraph({ label, nodes, links, selected, onSelect, groups, levels, noun, height, limit, onContext }: NodeGraphProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { defaultTheme, echartsTheme } from "@surfaces-ui/tokens";
|
|
3
|
+
import { GraphChart } from "echarts/charts";
|
|
4
|
+
import { AriaComponent, LegendComponent, TooltipComponent } from "echarts/components";
|
|
5
|
+
import * as echarts from "echarts/core";
|
|
6
|
+
import { CanvasRenderer } from "echarts/renderers";
|
|
7
|
+
import { useEffect, useId, useMemo, useRef } from "react";
|
|
8
|
+
import { useOptionalTheme } from "../theme/ThemeProvider.js";
|
|
9
|
+
import { GRAPH_NODE_LIMIT, buildGraphOption, graphGroups, graphNeighbours, graphWindow, linkCounts } from "./model.js";
|
|
10
|
+
import { wheelScrollsThePage } from "../chart/wheel.js";
|
|
11
|
+
echarts.use([GraphChart, TooltipComponent, LegendComponent, AriaComponent, CanvasRenderer]);
|
|
12
|
+
const LEVEL_SYMBOL = { full: "●", half: "◐", outline: "○" };
|
|
13
|
+
/**
|
|
14
|
+
* Things and the links between them, drawn as a graph and listed beside it. The list does everything the canvas
|
|
15
|
+
* does (find a node, open it, walk to a neighbour), so the graph is never the only way in. The layout settles and
|
|
16
|
+
* stops; under reduced motion it is placed without moving. When the nodes change, those already drawn keep their
|
|
17
|
+
* places and the new ones grow in, so a graph can be watched as it fills. A large graph shows what is around one node and says
|
|
18
|
+
* how many it left out.
|
|
19
|
+
*/
|
|
20
|
+
export function NodeGraph({ label, nodes, links, selected, onSelect, groups, levels, noun = "node", height = 420, limit = GRAPH_NODE_LIMIT, onContext }) {
|
|
21
|
+
const theme = useOptionalTheme();
|
|
22
|
+
const themeDocument = theme?.theme ?? defaultTheme;
|
|
23
|
+
const mode = theme?.resolvedMode ?? "light";
|
|
24
|
+
const shown = useMemo(() => graphWindow(nodes, links, selected, limit), [nodes, links, selected, limit]);
|
|
25
|
+
const counts = useMemo(() => linkCounts(shown.links), [shown]);
|
|
26
|
+
const legend = useMemo(() => graphGroups(shown.nodes, groups), [shown, groups]);
|
|
27
|
+
const chartTheme = useMemo(() => echartsTheme(themeDocument, mode), [themeDocument, mode]);
|
|
28
|
+
const colors = useMemo(() => chartTheme.color ?? [], [chartTheme]);
|
|
29
|
+
const text = useMemo(() => {
|
|
30
|
+
const color = chartTheme.textStyle?.color;
|
|
31
|
+
const muted = chartTheme.legend?.textStyle?.color;
|
|
32
|
+
const fontFamily = chartTheme.textStyle?.fontFamily;
|
|
33
|
+
return { ...(color ? { color } : {}), ...(muted ? { muted } : {}), ...(fontFamily ? { fontFamily } : {}) };
|
|
34
|
+
}, [chartTheme]);
|
|
35
|
+
const canvas = useRef(null);
|
|
36
|
+
const chart = useRef(undefined);
|
|
37
|
+
const noteId = useId();
|
|
38
|
+
const pick = useRef(() => { });
|
|
39
|
+
pick.current = (id) => {
|
|
40
|
+
const node = shown.nodes.find((n) => n.id === id);
|
|
41
|
+
onSelect?.(id);
|
|
42
|
+
onContext?.({ kind: "node.opened", summary: `Opened ${node?.label ?? id} on the graph.`, subject: { node: id } });
|
|
43
|
+
};
|
|
44
|
+
useEffect(() => {
|
|
45
|
+
const element = canvas.current;
|
|
46
|
+
if (!element)
|
|
47
|
+
return;
|
|
48
|
+
let made;
|
|
49
|
+
try {
|
|
50
|
+
made = echarts.init(element, echartsTheme(themeDocument, mode));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// No canvas here (a test, a very old browser): the list beside it still works.
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
chart.current = made;
|
|
57
|
+
made.on("click", (event) => {
|
|
58
|
+
const id = event.data?.id;
|
|
59
|
+
if (event.dataType === "node" && id)
|
|
60
|
+
pick.current(id);
|
|
61
|
+
});
|
|
62
|
+
const observer = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(() => made.resize());
|
|
63
|
+
observer?.observe(element);
|
|
64
|
+
const unwheel = wheelScrollsThePage(element);
|
|
65
|
+
return () => {
|
|
66
|
+
unwheel();
|
|
67
|
+
observer?.disconnect();
|
|
68
|
+
made.dispose();
|
|
69
|
+
chart.current = undefined;
|
|
70
|
+
};
|
|
71
|
+
}, [themeDocument, mode]);
|
|
72
|
+
useEffect(() => {
|
|
73
|
+
const still = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
74
|
+
try {
|
|
75
|
+
// Merged into the graph that is there, so a node that was drawn keeps its place and a new one grows in beside it.
|
|
76
|
+
chart.current?.setOption(buildGraphOption({ nodes: shown.nodes, links: shown.links, ...(selected ? { selected } : {}), ...(groups ? { groups } : {}), colors, text, animate: !still }), { replaceMerge: ["legend", "series"] });
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
// Where a canvas cannot be drawn on, the list beside it is the graph.
|
|
80
|
+
}
|
|
81
|
+
}, [shown, selected, groups, colors, text]);
|
|
82
|
+
const current = shown.nodes.find((n) => n.id === selected);
|
|
83
|
+
const around = current ? graphNeighbours(current.id, shown.links) : [];
|
|
84
|
+
const nameOf = (id) => shown.nodes.find((n) => n.id === id)?.label ?? id;
|
|
85
|
+
const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
86
|
+
const tooMany = legend.length > colors.length && colors.length > 0;
|
|
87
|
+
return (_jsx("section", { className: "sf-nodegraph", "aria-label": label, children: _jsxs("div", { className: "sf-nodegraph-frame", children: [_jsx("div", { ref: canvas, className: "sf-nodegraph-canvas", style: { height }, role: "img", "aria-label": `${label}: ${plural(shown.nodes.length, noun)} and ${plural(shown.links.length, "link")}, drawn as a graph.`, "aria-describedby": noteId }), _jsxs("div", { className: "sf-nodegraph-side", style: { maxHeight: height }, children: [_jsxs("p", { id: noteId, className: "sf-nodegraph-note", role: "status", children: [plural(shown.nodes.length, noun), ", ", plural(shown.links.length, "link"), ", also listed here.", shown.hidden > 0 ? ` ${shown.hidden} more are not drawn: open one to see what is around it.` : "", tooMany ? ` There are more groups than colours, so the last ${legend.length - colors.length + 1} share one.` : ""] }), current && (_jsxs("div", { className: "sf-nodegraph-current", children: [_jsxs("p", { children: [_jsx("strong", { children: current.label }), around.length === 0 ? " has no links." : " is linked to:"] }), around.length > 0 && (_jsx("ul", { children: around.map((other, index) => (_jsxs("li", { children: [_jsx("button", { type: "button", className: "sf-button", onClick: () => pick.current(other.id), children: nameOf(other.id) }), other.label && _jsx("span", { className: "sf-nodegraph-kind", children: other.label })] }, `${other.id}:${index}`))) }))] })), _jsx("ul", { className: "sf-nodegraph-list", children: shown.nodes.map((node) => (_jsx("li", { children: _jsxs("button", { type: "button", className: "sf-nodegraph-row", "aria-current": node.id === selected ? "true" : undefined, onClick: () => pick.current(node.id), children: [_jsx("span", { className: "sf-nodegraph-name", children: node.label }), node.level && (_jsxs("span", { className: "sf-nodegraph-level", children: [_jsx("span", { "aria-hidden": "true", children: LEVEL_SYMBOL[node.level] }), " ", levels?.[node.level] ?? ""] })), _jsx("span", { className: "sf-nodegraph-kind", children: [node.group, plural(counts.get(node.id) ?? 0, "link")].filter(Boolean).join(", ") })] }) }, node.id))) })] })] }) }));
|
|
88
|
+
}
|
|
89
|
+
//# sourceMappingURL=NodeGraph.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NodeGraph.js","sourceRoot":"","sources":["../../src/graph/NodeGraph.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtF,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAE1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAkC,gBAAgB,EAAE,WAAW,EAAE,eAAe,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACvJ,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,OAAO,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,gBAAgB,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC,CAAC;AAuB5F,MAAM,YAAY,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAW,CAAC;AAErE;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,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C","sourcesContent":["import { defaultTheme, echartsTheme } from \"@surfaces-ui/tokens\";\nimport { GraphChart } from \"echarts/charts\";\nimport { AriaComponent, LegendComponent, TooltipComponent } from \"echarts/components\";\nimport * as echarts from \"echarts/core\";\nimport { CanvasRenderer } from \"echarts/renderers\";\nimport { useEffect, useId, useMemo, useRef } from \"react\";\nimport type { ContextNote } from \"../controls/context.js\";\nimport { useOptionalTheme } from \"../theme/ThemeProvider.js\";\nimport { GRAPH_NODE_LIMIT, type GraphLink, type GraphNode, buildGraphOption, graphGroups, graphNeighbours, graphWindow, linkCounts } from \"./model.js\";\nimport { wheelScrollsThePage } from \"../chart/wheel.js\";\n\necharts.use([GraphChart, TooltipComponent, LegendComponent, AriaComponent, CanvasRenderer]);\n\nexport interface NodeGraphProps {\n /** What the graph shows, for assistive technology: \"Terms and how they are linked\". */\n label: string;\n nodes: GraphNode[];\n links: GraphLink[];\n /** The node that is open. */\n selected?: string;\n onSelect?(id: string): void;\n /** The order groups take colours and appear in the legend. */\n groups?: readonly string[];\n /** What a level means in words, for the list: `{ full: \"Certified\", half: \"Partly certified\", outline: \"Not certified\" }`. */\n levels?: Partial<Record<NonNullable<GraphNode[\"level\"]>, string>>;\n /** What the nodes are called: \"term\" gives \"7 terms\". Default \"node\". */\n noun?: string;\n height?: number;\n /** The most nodes drawn at once; past it the graph shows what is around the selected node. */\n limit?: number;\n /** Told what a person does here, as context for an agent. */\n onContext?(note: ContextNote): void;\n}\n\nconst LEVEL_SYMBOL = { full: \"●\", half: \"◐\", outline: \"○\" } as const;\n\n/**\n * Things and the links between them, drawn as a graph and listed beside it. The list does everything the canvas\n * does (find a node, open it, walk to a neighbour), so the graph is never the only way in. The layout settles and\n * stops; under reduced motion it is placed without moving. When the nodes change, those already drawn keep their\n * places and the new ones grow in, so a graph can be watched as it fills. A large graph shows what is around one node and says\n * how many it left out.\n */\nexport function NodeGraph({ label, nodes, links, selected, onSelect, groups, levels, noun = \"node\", height = 420, limit = GRAPH_NODE_LIMIT, onContext }: NodeGraphProps) {\n const theme = useOptionalTheme();\n const themeDocument = theme?.theme ?? defaultTheme;\n const mode = theme?.resolvedMode ?? \"light\";\n const shown = useMemo(() => graphWindow(nodes, links, selected, limit), [nodes, links, selected, limit]);\n const counts = useMemo(() => linkCounts(shown.links), [shown]);\n const legend = useMemo(() => graphGroups(shown.nodes, groups), [shown, groups]);\n const chartTheme = useMemo(() => echartsTheme(themeDocument, mode) as { color?: string[]; textStyle?: { color?: string; fontFamily?: string }; legend?: { textStyle?: { color?: string } } }, [themeDocument, mode]);\n const colors = useMemo(() => chartTheme.color ?? [], [chartTheme]);\n const text = useMemo(() => {\n const color = chartTheme.textStyle?.color;\n const muted = chartTheme.legend?.textStyle?.color;\n const fontFamily = chartTheme.textStyle?.fontFamily;\n return { ...(color ? { color } : {}), ...(muted ? { muted } : {}), ...(fontFamily ? { fontFamily } : {}) };\n }, [chartTheme]);\n const canvas = useRef<HTMLDivElement>(null);\n const chart = useRef<echarts.ECharts | undefined>(undefined);\n const noteId = useId();\n const pick = useRef<(id: string) => void>(() => {});\n pick.current = (id) => {\n const node = shown.nodes.find((n) => n.id === id);\n onSelect?.(id);\n onContext?.({ kind: \"node.opened\", summary: `Opened ${node?.label ?? id} on the graph.`, subject: { node: id } });\n };\n\n useEffect(() => {\n const element = canvas.current;\n if (!element) return;\n let made: echarts.ECharts;\n try {\n made = echarts.init(element, echartsTheme(themeDocument, mode));\n } catch {\n // No canvas here (a test, a very old browser): the list beside it still works.\n return;\n }\n chart.current = made;\n made.on(\"click\", (event) => {\n const id = (event.data as { id?: string } | undefined)?.id;\n if (event.dataType === \"node\" && id) pick.current(id);\n });\n const observer = typeof ResizeObserver === \"undefined\" ? undefined : new ResizeObserver(() => made.resize());\n observer?.observe(element);\n const unwheel = wheelScrollsThePage(element);\n return () => {\n unwheel();\n observer?.disconnect();\n made.dispose();\n chart.current = undefined;\n };\n }, [themeDocument, mode]);\n\n useEffect(() => {\n const still = typeof matchMedia === \"function\" && matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n try {\n // Merged into the graph that is there, so a node that was drawn keeps its place and a new one grows in beside it.\n chart.current?.setOption(buildGraphOption({ nodes: shown.nodes, links: shown.links, ...(selected ? { selected } : {}), ...(groups ? { groups } : {}), colors, text, animate: !still }), { replaceMerge: [\"legend\", \"series\"] });\n } catch {\n // Where a canvas cannot be drawn on, the list beside it is the graph.\n }\n }, [shown, selected, groups, colors, text]);\n\n const current = shown.nodes.find((n) => n.id === selected);\n const around = current ? graphNeighbours(current.id, shown.links) : [];\n const nameOf = (id: string) => shown.nodes.find((n) => n.id === id)?.label ?? id;\n const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n const tooMany = legend.length > colors.length && colors.length > 0;\n\n return (\n <section className=\"sf-nodegraph\" aria-label={label}>\n <div className=\"sf-nodegraph-frame\">\n <div ref={canvas} className=\"sf-nodegraph-canvas\" style={{ height }} role=\"img\" aria-label={`${label}: ${plural(shown.nodes.length, noun)} and ${plural(shown.links.length, \"link\")}, drawn as a graph.`} aria-describedby={noteId} />\n <div className=\"sf-nodegraph-side\" style={{ maxHeight: height }}>\n <p id={noteId} className=\"sf-nodegraph-note\" role=\"status\">\n {plural(shown.nodes.length, noun)}, {plural(shown.links.length, \"link\")}, also listed here.\n {shown.hidden > 0 ? ` ${shown.hidden} more are not drawn: open one to see what is around it.` : \"\"}\n {tooMany ? ` There are more groups than colours, so the last ${legend.length - colors.length + 1} share one.` : \"\"}\n </p>\n {current && (\n <div className=\"sf-nodegraph-current\">\n <p>\n <strong>{current.label}</strong>\n {around.length === 0 ? \" has no links.\" : \" is linked to:\"}\n </p>\n {around.length > 0 && (\n <ul>\n {around.map((other, index) => (\n <li key={`${other.id}:${index}`}>\n <button type=\"button\" className=\"sf-button\" onClick={() => pick.current(other.id)}>\n {nameOf(other.id)}\n </button>\n {other.label && <span className=\"sf-nodegraph-kind\">{other.label}</span>}\n </li>\n ))}\n </ul>\n )}\n </div>\n )}\n <ul className=\"sf-nodegraph-list\">\n {shown.nodes.map((node) => (\n <li key={node.id}>\n <button type=\"button\" className=\"sf-nodegraph-row\" aria-current={node.id === selected ? \"true\" : undefined} onClick={() => pick.current(node.id)}>\n <span className=\"sf-nodegraph-name\">{node.label}</span>\n {node.level && (\n <span className=\"sf-nodegraph-level\">\n <span aria-hidden=\"true\">{LEVEL_SYMBOL[node.level]}</span> {levels?.[node.level] ?? \"\"}\n </span>\n )}\n <span className=\"sf-nodegraph-kind\">\n {[node.group, plural(counts.get(node.id) ?? 0, \"link\")].filter(Boolean).join(\", \")}\n </span>\n </button>\n </li>\n ))}\n </ul>\n </div>\n </div>\n </section>\n );\n}\n"]}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** One thing on a graph. */
|
|
2
|
+
export interface GraphNode {
|
|
3
|
+
id: string;
|
|
4
|
+
label: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
/** What kind of thing it is. Each group takes a series colour, in the order of `groups`, and is named in the legend. */
|
|
7
|
+
group?: string;
|
|
8
|
+
/**
|
|
9
|
+
* How far along it is, shown by how full the node is drawn in its group's colour: `full`, `half` or `outline`.
|
|
10
|
+
* For a level (certified, partly, not), where a different hue would say "a different thing".
|
|
11
|
+
*/
|
|
12
|
+
level?: "full" | "half" | "outline";
|
|
13
|
+
/** It has just arrived: drawn lit until the caller stops saying so. For a graph that grows while a person watches. */
|
|
14
|
+
fresh?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/** A link between two nodes. Direction is not drawn. */
|
|
17
|
+
export interface GraphLink {
|
|
18
|
+
source: string;
|
|
19
|
+
target: string;
|
|
20
|
+
/** What the link is, in words. */
|
|
21
|
+
label?: string;
|
|
22
|
+
/** It has just arrived: drawn brighter until the caller stops saying so. */
|
|
23
|
+
fresh?: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** The most nodes drawn at once. Past it a person sees what is around one node, never everything at once. */
|
|
26
|
+
export declare const GRAPH_NODE_LIMIT = 300;
|
|
27
|
+
/** How many links each node has, by id. */
|
|
28
|
+
export declare function linkCounts(links: GraphLink[]): Map<string, number>;
|
|
29
|
+
/** The other end of every link a node has, with what the link is. */
|
|
30
|
+
export declare function graphNeighbours(id: string, links: GraphLink[]): {
|
|
31
|
+
id: string;
|
|
32
|
+
label: string;
|
|
33
|
+
}[];
|
|
34
|
+
/**
|
|
35
|
+
* What to draw: everything when it fits; otherwise the selected node (or the most linked one) with what is within
|
|
36
|
+
* two links of it, up to the limit. `hidden` is how many nodes were left out, so the screen can say so.
|
|
37
|
+
*/
|
|
38
|
+
export declare function graphWindow(nodes: GraphNode[], links: GraphLink[], selected: string | undefined, limit?: number): {
|
|
39
|
+
nodes: GraphNode[];
|
|
40
|
+
links: GraphLink[];
|
|
41
|
+
hidden: number;
|
|
42
|
+
};
|
|
43
|
+
/** The groups to name in the legend: those given, in order, then any a node has that were not given. */
|
|
44
|
+
export declare function graphGroups(nodes: GraphNode[], groups?: readonly string[]): string[];
|
|
45
|
+
export interface GraphOptionInput {
|
|
46
|
+
nodes: GraphNode[];
|
|
47
|
+
links: GraphLink[];
|
|
48
|
+
selected?: string;
|
|
49
|
+
/** Legend order. */
|
|
50
|
+
groups?: readonly string[];
|
|
51
|
+
/** The theme's series colours. A group past the last colour shares it, and the graph says so. */
|
|
52
|
+
colors: readonly string[];
|
|
53
|
+
/** False under reduced motion: the layout is placed, not animated. */
|
|
54
|
+
animate: boolean;
|
|
55
|
+
/** The theme's text: its colour, a quieter one for links, and the font. Without it the chart's own are used. */
|
|
56
|
+
text?: {
|
|
57
|
+
color?: string;
|
|
58
|
+
muted?: string;
|
|
59
|
+
fontFamily?: string;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** The one series' id. With it, new data is merged into the graph that is there, so nodes keep their places. */
|
|
63
|
+
export declare const GRAPH_SERIES_ID = "graph";
|
|
64
|
+
/**
|
|
65
|
+
* The ECharts option for a node-link graph. Plain data, so it is tested without a canvas. A node's size follows
|
|
66
|
+
* how many links it has; its colour is its group's; its fill is its level.
|
|
67
|
+
*/
|
|
68
|
+
export declare function buildGraphOption(input: GraphOptionInput): Record<string, unknown>;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/** The most nodes drawn at once. Past it a person sees what is around one node, never everything at once. */
|
|
2
|
+
export const GRAPH_NODE_LIMIT = 300;
|
|
3
|
+
/** How many links each node has, by id. */
|
|
4
|
+
export function linkCounts(links) {
|
|
5
|
+
const counts = new Map();
|
|
6
|
+
for (const link of links) {
|
|
7
|
+
counts.set(link.source, (counts.get(link.source) ?? 0) + 1);
|
|
8
|
+
if (link.target !== link.source)
|
|
9
|
+
counts.set(link.target, (counts.get(link.target) ?? 0) + 1);
|
|
10
|
+
}
|
|
11
|
+
return counts;
|
|
12
|
+
}
|
|
13
|
+
/** The other end of every link a node has, with what the link is. */
|
|
14
|
+
export function graphNeighbours(id, links) {
|
|
15
|
+
return links.flatMap((link) => (link.source === id ? [{ id: link.target, label: link.label ?? "" }] : link.target === id ? [{ id: link.source, label: link.label ?? "" }] : []));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* What to draw: everything when it fits; otherwise the selected node (or the most linked one) with what is within
|
|
19
|
+
* two links of it, up to the limit. `hidden` is how many nodes were left out, so the screen can say so.
|
|
20
|
+
*/
|
|
21
|
+
export function graphWindow(nodes, links, selected, limit = GRAPH_NODE_LIMIT) {
|
|
22
|
+
const known = new Set(nodes.map((n) => n.id));
|
|
23
|
+
const real = links.filter((l) => known.has(l.source) && known.has(l.target));
|
|
24
|
+
if (nodes.length <= limit)
|
|
25
|
+
return { nodes, links: real, hidden: 0 };
|
|
26
|
+
const counts = linkCounts(real);
|
|
27
|
+
const start = selected && known.has(selected) ? selected : [...nodes].sort((a, b) => (counts.get(b.id) ?? 0) - (counts.get(a.id) ?? 0))[0]?.id;
|
|
28
|
+
const keep = new Set(start ? [start] : []);
|
|
29
|
+
for (let hop = 0; hop < 2 && keep.size < limit; hop++) {
|
|
30
|
+
for (const id of [...keep])
|
|
31
|
+
for (const next of graphNeighbours(id, real))
|
|
32
|
+
if (keep.size < limit)
|
|
33
|
+
keep.add(next.id);
|
|
34
|
+
}
|
|
35
|
+
const shown = nodes.filter((n) => keep.has(n.id));
|
|
36
|
+
return { nodes: shown, links: real.filter((l) => keep.has(l.source) && keep.has(l.target)), hidden: nodes.length - shown.length };
|
|
37
|
+
}
|
|
38
|
+
/** The groups to name in the legend: those given, in order, then any a node has that were not given. */
|
|
39
|
+
export function graphGroups(nodes, groups = []) {
|
|
40
|
+
const used = new Set(nodes.map((n) => n.group ?? ""));
|
|
41
|
+
return [...groups.filter((g) => used.has(g)), ...[...used].filter((g) => g !== "" && !groups.includes(g))];
|
|
42
|
+
}
|
|
43
|
+
/** The one series' id. With it, new data is merged into the graph that is there, so nodes keep their places. */
|
|
44
|
+
export const GRAPH_SERIES_ID = "graph";
|
|
45
|
+
/**
|
|
46
|
+
* The ECharts option for a node-link graph. Plain data, so it is tested without a canvas. A node's size follows
|
|
47
|
+
* how many links it has; its colour is its group's; its fill is its level.
|
|
48
|
+
*/
|
|
49
|
+
export function buildGraphOption(input) {
|
|
50
|
+
const { nodes, links, selected, colors, animate, text } = input;
|
|
51
|
+
const groups = graphGroups(nodes, input.groups);
|
|
52
|
+
const counts = linkCounts(links);
|
|
53
|
+
const most = Math.max(1, ...nodes.map((n) => counts.get(n.id) ?? 0));
|
|
54
|
+
const colorOf = (group) => colors[Math.min(Math.max(0, groups.indexOf(group ?? "")), Math.max(0, colors.length - 1))] ?? colors[0];
|
|
55
|
+
const fill = (node) => {
|
|
56
|
+
const color = colorOf(node.group);
|
|
57
|
+
if (node.level === "half")
|
|
58
|
+
return { color, opacity: 0.5 };
|
|
59
|
+
if (node.level === "outline")
|
|
60
|
+
return { color: "rgba(0, 0, 0, 0)", borderColor: color, borderWidth: 2 };
|
|
61
|
+
return { color };
|
|
62
|
+
};
|
|
63
|
+
// Names are plain text in the theme's colour and font: no outline around the letters, which smears on a dark ground.
|
|
64
|
+
const words = { ...(text?.color ? { color: text.color } : {}), ...(text?.fontFamily ? { fontFamily: text.fontFamily } : {}), fontSize: 12, textBorderWidth: 0, textBorderColor: "transparent", textShadowBlur: 0 };
|
|
65
|
+
return {
|
|
66
|
+
aria: { enabled: true },
|
|
67
|
+
animation: animate,
|
|
68
|
+
// A node that arrives grows into place and what was there eases aside, rather than everything jumping.
|
|
69
|
+
animationDuration: 700,
|
|
70
|
+
animationEasing: "backOut",
|
|
71
|
+
animationDurationUpdate: 600,
|
|
72
|
+
animationEasingUpdate: "cubicOut",
|
|
73
|
+
tooltip: {
|
|
74
|
+
trigger: "item",
|
|
75
|
+
formatter: (item) => item.dataType === "edge" ? (item.data.label ?? "") : `${item.data.name ?? ""}${item.data.description ? `: ${item.data.description}` : ""}`,
|
|
76
|
+
},
|
|
77
|
+
...(groups.length > 1 ? { legend: [{ data: groups, bottom: 4, icon: "circle", itemWidth: 10, itemHeight: 10, itemGap: 16 }] } : {}),
|
|
78
|
+
series: [
|
|
79
|
+
{
|
|
80
|
+
id: GRAPH_SERIES_ID,
|
|
81
|
+
type: "graph",
|
|
82
|
+
layout: "force",
|
|
83
|
+
roam: true,
|
|
84
|
+
draggable: true,
|
|
85
|
+
// Room is kept for the legend, so no node sits under it.
|
|
86
|
+
top: 24,
|
|
87
|
+
bottom: groups.length > 1 ? 56 : 24,
|
|
88
|
+
// A layout that settles and then stops, never a simulation that keeps moving.
|
|
89
|
+
force: { repulsion: 420, edgeLength: [80, 150], gravity: 0.1, friction: 0.5, layoutAnimation: animate },
|
|
90
|
+
label: { show: nodes.length <= 80, position: "right", distance: 8, ...words },
|
|
91
|
+
// Where names would sit on top of each other, the later one is left to the list and the tooltip.
|
|
92
|
+
labelLayout: { hideOverlap: true },
|
|
93
|
+
lineStyle: { ...(text?.muted ? { color: text.muted } : {}), width: 1.25, opacity: 0.55, curveness: 0.12 },
|
|
94
|
+
edgeLabel: { ...words, ...(text?.muted ? { color: text.muted } : {}), fontSize: 11 },
|
|
95
|
+
emphasis: { focus: "adjacency", scale: 1.15, label: { show: true, fontWeight: "bold" }, lineStyle: { width: 2.5, opacity: 1 } },
|
|
96
|
+
blur: { itemStyle: { opacity: 0.25 }, lineStyle: { opacity: 0.12 }, label: { opacity: 0.35 } },
|
|
97
|
+
categories: groups.map((name) => ({ name, itemStyle: { color: colorOf(name) } })),
|
|
98
|
+
data: nodes.map((node) => {
|
|
99
|
+
const size = 14 + Math.round((22 * (counts.get(node.id) ?? 0)) / most);
|
|
100
|
+
const chosen = node.id === selected;
|
|
101
|
+
return {
|
|
102
|
+
id: node.id,
|
|
103
|
+
name: node.label,
|
|
104
|
+
...(node.description ? { description: node.description } : {}),
|
|
105
|
+
...(groups.length > 0 && node.group !== undefined ? { category: groups.indexOf(node.group) } : {}),
|
|
106
|
+
symbolSize: (chosen ? size + 6 : size) + (node.fresh ? 4 : 0),
|
|
107
|
+
itemStyle: { ...fill(node), ...(chosen ? { borderColor: colorOf(node.group), borderWidth: 4 } : {}), ...(node.fresh ? { shadowBlur: 28, shadowColor: colorOf(node.group) } : {}) },
|
|
108
|
+
// A node drawn at half strength keeps its name at full strength: the fill says the level, the text must stay readable.
|
|
109
|
+
...(chosen || node.level === "half" ? { label: { ...(node.level === "half" ? { opacity: 1 } : {}), ...(chosen ? { show: true, fontWeight: "bold" } : {}) } } : {}),
|
|
110
|
+
};
|
|
111
|
+
}),
|
|
112
|
+
links: links.map((link) => ({
|
|
113
|
+
source: link.source,
|
|
114
|
+
target: link.target,
|
|
115
|
+
...(link.label ? { label: link.label } : {}),
|
|
116
|
+
...(link.fresh ? { lineStyle: { width: 2.5, opacity: 1, ...(colors[0] ? { color: colors[0], shadowBlur: 12, shadowColor: colors[0] } : {}) } } : {}),
|
|
117
|
+
})),
|
|
118
|
+
},
|
|
119
|
+
],
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
//# sourceMappingURL=model.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.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C,CAAC,EAAE,CAAC;oBAC5C,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBACrJ,CAAC,CAAC;aACJ;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["/** One thing on a graph. */\nexport interface GraphNode {\n id: string;\n label: string;\n description?: string;\n /** What kind of thing it is. Each group takes a series colour, in the order of `groups`, and is named in the legend. */\n group?: string;\n /**\n * How far along it is, shown by how full the node is drawn in its group's colour: `full`, `half` or `outline`.\n * For a level (certified, partly, not), where a different hue would say \"a different thing\".\n */\n level?: \"full\" | \"half\" | \"outline\";\n /** It has just arrived: drawn lit until the caller stops saying so. For a graph that grows while a person watches. */\n fresh?: boolean;\n}\n\n/** A link between two nodes. Direction is not drawn. */\nexport interface GraphLink {\n source: string;\n target: string;\n /** What the link is, in words. */\n label?: string;\n /** It has just arrived: drawn brighter until the caller stops saying so. */\n fresh?: boolean;\n}\n\n/** The most nodes drawn at once. Past it a person sees what is around one node, never everything at once. */\nexport const GRAPH_NODE_LIMIT = 300;\n\n/** How many links each node has, by id. */\nexport function linkCounts(links: GraphLink[]): Map<string, number> {\n const counts = new Map<string, number>();\n for (const link of links) {\n counts.set(link.source, (counts.get(link.source) ?? 0) + 1);\n if (link.target !== link.source) counts.set(link.target, (counts.get(link.target) ?? 0) + 1);\n }\n return counts;\n}\n\n/** The other end of every link a node has, with what the link is. */\nexport function graphNeighbours(id: string, links: GraphLink[]): { id: string; label: string }[] {\n return links.flatMap((link) => (link.source === id ? [{ id: link.target, label: link.label ?? \"\" }] : link.target === id ? [{ id: link.source, label: link.label ?? \"\" }] : []));\n}\n\n/**\n * What to draw: everything when it fits; otherwise the selected node (or the most linked one) with what is within\n * two links of it, up to the limit. `hidden` is how many nodes were left out, so the screen can say so.\n */\nexport function graphWindow(nodes: GraphNode[], links: GraphLink[], selected: string | undefined, limit = GRAPH_NODE_LIMIT): { nodes: GraphNode[]; links: GraphLink[]; hidden: number } {\n const known = new Set(nodes.map((n) => n.id));\n const real = links.filter((l) => known.has(l.source) && known.has(l.target));\n if (nodes.length <= limit) return { nodes, links: real, hidden: 0 };\n const counts = linkCounts(real);\n const start = selected && known.has(selected) ? selected : [...nodes].sort((a, b) => (counts.get(b.id) ?? 0) - (counts.get(a.id) ?? 0))[0]?.id;\n const keep = new Set<string>(start ? [start] : []);\n for (let hop = 0; hop < 2 && keep.size < limit; hop++) {\n for (const id of [...keep]) for (const next of graphNeighbours(id, real)) if (keep.size < limit) keep.add(next.id);\n }\n const shown = nodes.filter((n) => keep.has(n.id));\n return { nodes: shown, links: real.filter((l) => keep.has(l.source) && keep.has(l.target)), hidden: nodes.length - shown.length };\n}\n\n/** The groups to name in the legend: those given, in order, then any a node has that were not given. */\nexport function graphGroups(nodes: GraphNode[], groups: readonly string[] = []): string[] {\n const used = new Set(nodes.map((n) => n.group ?? \"\"));\n return [...groups.filter((g) => used.has(g)), ...[...used].filter((g) => g !== \"\" && !groups.includes(g))];\n}\n\nexport interface GraphOptionInput {\n nodes: GraphNode[];\n links: GraphLink[];\n selected?: string;\n /** Legend order. */\n groups?: readonly string[];\n /** The theme's series colours. A group past the last colour shares it, and the graph says so. */\n colors: readonly string[];\n /** False under reduced motion: the layout is placed, not animated. */\n animate: boolean;\n /** The theme's text: its colour, a quieter one for links, and the font. Without it the chart's own are used. */\n text?: { color?: string; muted?: string; fontFamily?: string };\n}\n\n/** The one series' id. With it, new data is merged into the graph that is there, so nodes keep their places. */\nexport const GRAPH_SERIES_ID = \"graph\";\n\n/**\n * The ECharts option for a node-link graph. Plain data, so it is tested without a canvas. A node's size follows\n * how many links it has; its colour is its group's; its fill is its level.\n */\nexport function buildGraphOption(input: GraphOptionInput): Record<string, unknown> {\n const { nodes, links, selected, colors, animate, text } = input;\n const groups = graphGroups(nodes, input.groups);\n const counts = linkCounts(links);\n const most = Math.max(1, ...nodes.map((n) => counts.get(n.id) ?? 0));\n const colorOf = (group: string | undefined) => colors[Math.min(Math.max(0, groups.indexOf(group ?? \"\")), Math.max(0, colors.length - 1))] ?? colors[0];\n const fill = (node: GraphNode): Record<string, unknown> => {\n const color = colorOf(node.group);\n if (node.level === \"half\") return { color, opacity: 0.5 };\n if (node.level === \"outline\") return { color: \"rgba(0, 0, 0, 0)\", borderColor: color, borderWidth: 2 };\n return { color };\n };\n // Names are plain text in the theme's colour and font: no outline around the letters, which smears on a dark ground.\n const words = { ...(text?.color ? { color: text.color } : {}), ...(text?.fontFamily ? { fontFamily: text.fontFamily } : {}), fontSize: 12, textBorderWidth: 0, textBorderColor: \"transparent\", textShadowBlur: 0 };\n return {\n aria: { enabled: true },\n animation: animate,\n // A node that arrives grows into place and what was there eases aside, rather than everything jumping.\n animationDuration: 700,\n animationEasing: \"backOut\",\n animationDurationUpdate: 600,\n animationEasingUpdate: \"cubicOut\",\n tooltip: {\n trigger: \"item\",\n formatter: (item: { dataType?: string; data: { name?: string; description?: string; label?: string } }) =>\n item.dataType === \"edge\" ? (item.data.label ?? \"\") : `${item.data.name ?? \"\"}${item.data.description ? `: ${item.data.description}` : \"\"}`,\n },\n ...(groups.length > 1 ? { legend: [{ data: groups, bottom: 4, icon: \"circle\", itemWidth: 10, itemHeight: 10, itemGap: 16 }] } : {}),\n series: [\n {\n id: GRAPH_SERIES_ID,\n type: \"graph\",\n layout: \"force\",\n roam: true,\n draggable: true,\n // Room is kept for the legend, so no node sits under it.\n top: 24,\n bottom: groups.length > 1 ? 56 : 24,\n // A layout that settles and then stops, never a simulation that keeps moving.\n force: { repulsion: 420, edgeLength: [80, 150], gravity: 0.1, friction: 0.5, layoutAnimation: animate },\n label: { show: nodes.length <= 80, position: \"right\", distance: 8, ...words },\n // Where names would sit on top of each other, the later one is left to the list and the tooltip.\n labelLayout: { hideOverlap: true },\n lineStyle: { ...(text?.muted ? { color: text.muted } : {}), width: 1.25, opacity: 0.55, curveness: 0.12 },\n edgeLabel: { ...words, ...(text?.muted ? { color: text.muted } : {}), fontSize: 11 },\n emphasis: { focus: \"adjacency\", scale: 1.15, label: { show: true, fontWeight: \"bold\" }, lineStyle: { width: 2.5, opacity: 1 } },\n blur: { itemStyle: { opacity: 0.25 }, lineStyle: { opacity: 0.12 }, label: { opacity: 0.35 } },\n categories: groups.map((name) => ({ name, itemStyle: { color: colorOf(name) } })),\n data: nodes.map((node) => {\n const size = 14 + Math.round((22 * (counts.get(node.id) ?? 0)) / most);\n const chosen = node.id === selected;\n return {\n id: node.id,\n name: node.label,\n ...(node.description ? { description: node.description } : {}),\n ...(groups.length > 0 && node.group !== undefined ? { category: groups.indexOf(node.group) } : {}),\n symbolSize: (chosen ? size + 6 : size) + (node.fresh ? 4 : 0),\n itemStyle: { ...fill(node), ...(chosen ? { borderColor: colorOf(node.group), borderWidth: 4 } : {}), ...(node.fresh ? { shadowBlur: 28, shadowColor: colorOf(node.group) } : {}) },\n // A node drawn at half strength keeps its name at full strength: the fill says the level, the text must stay readable.\n ...(chosen || node.level === \"half\" ? { label: { ...(node.level === \"half\" ? { opacity: 1 } : {}), ...(chosen ? { show: true, fontWeight: \"bold\" } : {}) } } : {}),\n };\n }),\n links: links.map((link) => ({\n source: link.source,\n target: link.target,\n ...(link.label ? { label: link.label } : {}),\n ...(link.fresh ? { lineStyle: { width: 2.5, opacity: 1, ...(colors[0] ? { color: colors[0], shadowBlur: 12, shadowColor: colors[0] } : {}) } } : {}),\n })),\n },\n ],\n };\n}\n"]}
|