-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathviz.js
More file actions
94 lines (85 loc) · 2.48 KB
/
viz.js
File metadata and controls
94 lines (85 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { createStateField } from 'd3-rosetta';
import { setupSVG } from './setupSVG.js';
import { renderLoadingState } from './renderLoadingState.js';
import { asyncRequest } from './asyncRequest.js';
import { loadAndParseData } from './loadAndParseData.js';
import { scatterPlot } from './scatterPlot.js';
import { measureDimensions } from './measureDimensions.js';
import { json } from 'd3';
export const viz = (container, state, setState) => {
const stateField = createStateField(state, setState);
const [dataRequest, setDataRequest] =
stateField('dataRequest');
const [config, setConfig] = stateField('config');
// Set up postMessage event listener if not already set
if (!state.eventListenerAttached) {
window.addEventListener('message', (event) => {
if (event.data && typeof event.data === 'object') {
setState((state) => ({
...state,
config: {
...state.config,
...event.data,
},
}));
}
});
setState((prevState) => ({
...prevState,
eventListenerAttached: true,
}));
}
// Load config first if not already loaded
if (!config) {
json('config.json')
.then((loadedConfig) => {
setConfig(loadedConfig);
})
.catch((error) => {
console.error('Failed to load config:', error);
});
return;
}
// After config is loaded, load the data
if (!dataRequest) {
return asyncRequest(setDataRequest, () =>
loadAndParseData(config.dataUrl),
);
}
const { data, error } = dataRequest;
const dimensions = measureDimensions(container);
const svg = setupSVG(container, dimensions);
renderLoadingState(svg, {
shouldShow: !data,
text: error
? `Error: ${error.message}`
: config.loadingMessage,
x: dimensions.width / 2,
y: dimensions.height / 2,
fontSize: config.loadingFontSize,
fontFamily: config.loadingFontFamily,
});
if (data) {
// Safely transform config properties to accessor functions
const configWithAccessors = {
...config,
xValue: config.xValue
? (d) => d[config.xValue]
: () => 0,
yValue: config.yValue
? (d) => d[config.yValue]
: () => 0,
sizeValue: config.sizeValue
? (d) => d[config.sizeValue]
: null,
pointRadiusValue: config.pointRadiusValue
? (d) => d[config.pointRadiusValue]
: null,
};
scatterPlot(svg, {
...configWithAccessors,
data,
dimensions,
});
}
};