forked from owid/owid-grapher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChartEditor.ts
296 lines (250 loc) · 8.21 KB
/
ChartEditor.ts
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/* ChartEditor.ts
* ================
*
* Mobx store that represents the current editor state and governs non-UI-related operations.
*
*/
import { Grapher } from "@ourworldindata/grapher"
import {
type DetailDictionary,
type RawPageview,
Topic,
PostReference,
ChartRedirect,
DimensionProperty,
Json,
} from "@ourworldindata/utils"
import { computed, observable, runInAction, when } from "mobx"
import { BAKED_GRAPHER_URL } from "../settings/clientSettings.js"
import { Admin } from "./Admin.js"
import { EditorFeatures } from "./EditorFeatures.js"
type EditorTab = string
interface Variable {
id: number
name: string
}
export interface Dataset {
id: number
name: string
namespace: string
version: string | undefined
variables: Variable[]
isPrivate: boolean
nonRedistributable: boolean
}
export interface Log {
userId: number
userName: string
config: Json
createdAt: string
}
export interface References {
postsWordpress: PostReference[]
postsGdocs: PostReference[]
explorers: string[]
}
export const getFullReferencesCount = (references: References): number => {
return (
references.postsWordpress.length +
references.postsGdocs.length +
references.explorers.length
)
}
export interface Namespace {
name: string
description?: string
isArchived: boolean
}
// This contains the dataset/variable metadata for the entire database
// Used for variable selector interface
export interface NamespaceData {
datasets: Dataset[]
}
export class EditorDatabase {
@observable.ref namespaces: Namespace[]
@observable.ref variableUsageCounts: Map<number, number> = new Map()
@observable dataByNamespace: Map<string, NamespaceData> = new Map()
constructor(json: any) {
this.namespaces = json.namespaces
}
}
export type FieldWithDetailReferences =
| "subtitle"
| "note"
| "axisLabelX"
| "axisLabelY"
export type DetailReferences = Record<FieldWithDetailReferences, string[]>
export interface DimensionErrorMessage {
displayName?: string
}
export interface ChartEditorManager {
admin: Admin
grapher: Grapher
database: EditorDatabase
logs: Log[]
references: References | undefined
redirects: ChartRedirect[]
pageviews?: RawPageview
allTopics: Topic[]
details: DetailDictionary
invalidDetailReferences: DetailReferences
errorMessages: Partial<Record<FieldWithDetailReferences, string>>
errorMessagesForDimensions: Record<
DimensionProperty,
DimensionErrorMessage[]
>
}
interface VariableIdUsageRecord {
variableId: number
usageCount: number
}
export class ChartEditor {
manager: ChartEditorManager
// Whether the current chart state is saved or not
@observable.ref currentRequest: Promise<any> | undefined
@observable.ref tab: EditorTab = "basic"
@observable.ref errorMessage?: { title: string; content: string }
@observable.ref previewMode: "mobile" | "desktop"
@observable.ref showStaticPreview = false
@observable.ref savedGrapherJson: string = ""
// This gets set when we save a new chart for the first time
// so the page knows to update the url
@observable.ref newChartId?: number
constructor(props: { manager: ChartEditorManager }) {
this.manager = props.manager
this.previewMode =
localStorage.getItem("editorPreviewMode") === "mobile"
? "mobile"
: "desktop"
when(
() => this.grapher.isReady,
() => (this.savedGrapherJson = JSON.stringify(this.grapher.object))
)
}
@computed get isModified(): boolean {
return JSON.stringify(this.grapher.object) !== this.savedGrapherJson
}
@computed get grapher() {
return this.manager.grapher
}
@computed get database() {
return this.manager.database
}
@computed get logs() {
return this.manager.logs
}
@computed get references() {
return this.manager.references
}
@computed get redirects() {
return this.manager.redirects
}
@computed get pageviews() {
return this.manager.pageviews
}
@computed get allTopics() {
return this.manager.allTopics
}
@computed get details() {
return this.manager.details
}
@computed get availableTabs(): EditorTab[] {
const tabs: EditorTab[] = ["basic", "data", "text", "customize"]
if (this.grapher.hasMapTab) tabs.push("map")
if (this.grapher.isScatter) tabs.push("scatter")
if (this.grapher.isMarimekko) tabs.push("marimekko")
tabs.push("revisions")
tabs.push("refs")
tabs.push("export")
return tabs
}
@computed get isNewGrapher() {
return this.grapher.id === undefined
}
@computed get features() {
return new EditorFeatures(this)
}
async loadVariableUsageCounts(): Promise<void> {
const data = (await this.manager.admin.getJSON(
`/api/variables.usages.json`
)) as VariableIdUsageRecord[]
const finalData = new Map(
data.map(({ variableId, usageCount }: VariableIdUsageRecord) => [
variableId,
+usageCount,
])
)
runInAction(() => (this.database.variableUsageCounts = finalData))
}
async saveGrapher({
onError,
}: { onError?: () => void } = {}): Promise<void> {
const { grapher, isNewGrapher } = this
const currentGrapherObject = this.grapher.object
// Chart title and slug may be autocalculated from data, in which case they won't be in props
// But the server will need to know what we calculated in order to do its job
if (!currentGrapherObject.title)
currentGrapherObject.title = grapher.displayTitle
if (!currentGrapherObject.slug)
currentGrapherObject.slug = grapher.displaySlug
const targetUrl = isNewGrapher
? "/api/charts"
: `/api/charts/${grapher.id}`
const json = await this.manager.admin.requestJSON(
targetUrl,
currentGrapherObject,
isNewGrapher ? "POST" : "PUT"
)
if (json.success) {
if (isNewGrapher) {
this.newChartId = json.chartId
this.grapher.id = json.chartId
this.savedGrapherJson = JSON.stringify(this.grapher.object)
} else {
runInAction(() => {
grapher.version += 1
this.logs.unshift(json.newLog)
this.savedGrapherJson = JSON.stringify(currentGrapherObject)
})
}
} else onError?.()
}
async saveAsNewGrapher(): Promise<void> {
const currentGrapherObject = this.grapher.object
const chartJson = { ...currentGrapherObject }
delete chartJson.id
delete chartJson.isPublished
// Need to open intermediary tab before AJAX to avoid popup blockers
const w = window.open("/", "_blank") as Window
const json = await this.manager.admin.requestJSON(
"/api/charts",
chartJson,
"POST"
)
if (json.success)
w.location.assign(
this.manager.admin.url(`charts/${json.chartId}/edit`)
)
}
publishGrapher(): void {
const url = `${BAKED_GRAPHER_URL}/${this.grapher.displaySlug}`
if (window.confirm(`Publish chart at ${url}?`)) {
this.grapher.isPublished = true
void this.saveGrapher({
onError: () => (this.grapher.isPublished = undefined),
})
}
}
unpublishGrapher(): void {
const message =
this.references && getFullReferencesCount(this.references) > 0
? "WARNING: This chart might be referenced from public posts, please double check before unpublishing. Try to remove the chart anyway?"
: "Are you sure you want to unpublish this chart?"
if (window.confirm(message)) {
this.grapher.isPublished = undefined
void this.saveGrapher({
onError: () => (this.grapher.isPublished = true),
})
}
}
}