This repository has been archived by the owner on Sep 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stores.js
100 lines (90 loc) · 2.95 KB
/
stores.js
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
95
96
97
98
99
100
import { derived, writable } from 'svelte/store';
import isEqual from 'lodash/isEqual';
import cloneDeep from 'lodash/cloneDeep';
import debounce from 'lodash/debounce';
import httpReq from '@datawrapper/shared/httpReq';
export const chart = new writable({});
export const data = new writable('');
export const hasUnsavedChanges = new writable(false);
export const unsavedChanges = {};
export function initChartStore(rawChart) {
chart.set(rawChart);
let prevState;
const allowedChartKeys = new Set([
'title',
'theme',
'type',
'metadata',
'language',
'external_data',
'last_edit_step'
]);
const patchChartSoon = debounce(async function (id) {
const savedKeys = Object.keys(unsavedChanges);
if (savedKeys.length) {
const payload = {};
savedKeys.forEach(k => {
payload[k] = unsavedChanges[k];
delete unsavedChanges[k];
});
const res = await httpReq.patch(`/v3/charts/${id}`, {
payload
});
if (!Object.keys(unsavedChanges).length) {
hasUnsavedChanges.set(false);
}
}
}, 1000);
chart.subscribe(value => {
if (!prevState && value.id) {
// initial set
prevState = cloneDeep(value);
} else if (prevState && !isEqual(prevState, value)) {
const payload = {};
let newUnsaved = false;
Object.keys(value).forEach(key => {
if (!isEqual(value[key], prevState[key])) {
if (allowedChartKeys.has(key)) {
newUnsaved = true;
unsavedChanges[key] = cloneDeep(value[key]);
} else {
// restore prev value
value[key] = prevState[key];
}
}
});
prevState = cloneDeep(value);
if (newUnsaved) {
hasUnsavedChanges.set(true);
patchChartSoon(value.id);
}
}
});
}
export function initDataStore(chartId, rawData) {
let prevState;
let unsavedState;
data.set(rawData);
const storeDataSoon = debounce(async function () {
const res = await httpReq.put(`/v3/charts/${chartId}/data`, {
body: unsavedState,
headers: {
// @todo: handle json data as well
'Content-Type': 'text/csv'
}
});
if (!Object.keys(unsavedChanges).length) {
hasUnsavedChanges.set(false);
}
}, 1000);
data.subscribe(value => {
if (!prevState && value !== undefined) {
// initial set
prevState = cloneDeep(value);
} else if (prevState && !isEqual(prevState, value)) {
unsavedState = value;
hasUnsavedChanges.set(true);
storeDataSoon();
}
});
}