This repository has been archived by the owner on Oct 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
TextEditor.tsx
342 lines (296 loc) · 10.2 KB
/
TextEditor.tsx
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
* Copyright (C) 2017-2019 HERE Europe B.V.
* Licensed under Apache 2.0, see full license in LICENSE
* SPDX-License-Identifier: Apache-2.0
*/
import { Theme } from "@here/harp-datasource-protocol";
import { LoggerManager } from "@here/harp-utils";
import * as React from "react";
import { Side, WindowCommands } from "../types";
import PopupsContainer from "./components-smart/PopupsContainer";
import MapHighlighter from "./map-handler/MapHighliter";
import settings from "./Settings";
export const logger = LoggerManager.instance.create("TextEditor");
/**
* This class controls the monaco editor and communicate thru messages with the Theme editor.
*/
class TextEditor {
readonly elemEditor = document.createElement("div");
private m_frameURL: string;
/**
* Contains the child window when [[Side.DeTouch]] is selected
*/
private m_editorWindow: Window | null = null;
/**
* Contains the child page when [[Side.DeTouch]] is not selected
*/
private m_editorIframe: null | HTMLIFrameElement = null;
/**
* The source code of current editable theme.
*/
private m_value = "";
/**
* Last parsed source code of the theme. If equals [[null]] then the source code probably
* invalid [[JSON]].
*/
private m_parsedTheme: Theme | null = null;
/**
* handles commands of the child text editor
*/
private onMessage: (data: MessageEvent) => void;
constructor() {
const pagePath = window.location.pathname.toLocaleLowerCase().replace("/index.html", "");
this.m_frameURL = `${window.location.origin}/${pagePath}/textEditor.html`;
this.elemEditor.id = "editor-container";
this.onMessage = (data: MessageEvent) => {
if (!data.isTrusted || data.origin !== window.location.origin) {
return;
}
const msg: WindowCommands = data.data;
switch (msg.command) {
case "Init":
this.sendMsg({
command: "InitData",
value: this.m_value,
column: settings.get("textEditor:column"),
line: settings.get("textEditor:line"),
notificationsVisible: settings.get("notificationsVisible"),
notificationsSize: settings.get("notificationsSize")
});
break;
case "HighlightFeature":
MapHighlighter.highlight(msg.condition);
break;
case "UpdateSourceValue":
this.updateSource(msg.value);
settings.set("textEditor:sourceCode", this.m_value);
settings.set("textEditor:column", msg.column);
settings.set("textEditor:line", msg.line);
break;
case "UpdateCursorPosition":
settings.set("textEditor:column", msg.column);
settings.set("textEditor:line", msg.line);
break;
case "UpdateNotificationsCount":
settings.setStoreData("notificationsState", {
count: msg.count,
severity: msg.severity
});
break;
case "UpdateNotificationsSize":
settings.set("notificationsSize", msg.UpdateNotificationsSize);
break;
default:
logger.warn(`unhandled command: ${msg.command}`);
}
};
}
async init() {
this.createIframe();
this.updateSource(settings.get("textEditor:sourceCode"));
window.addEventListener("message", this.onMessage);
window.addEventListener("beforeunload", () => {
if (this.m_editorWindow !== null) {
this.m_editorWindow.close();
}
});
settings.on("setting:notificationsVisible", notificationsVisible => {
this.sendMsg({
command: "ToggleNotifications",
notificationsVisible,
notificationsSize: settings.get("notificationsSize")
});
});
}
/**
* Ensures that the text editor in the child iframe.
*/
createIframe() {
if (this.m_editorWindow !== null) {
this.m_editorWindow.close();
this.m_editorWindow = null;
}
if (this.m_editorIframe !== null) {
return;
}
this.m_editorIframe = document.createElement("iframe");
this.m_editorIframe.className = "editor";
this.m_editorIframe.src = this.m_frameURL;
this.elemEditor.appendChild(this.m_editorIframe);
return this.m_editorIframe;
}
/**
* Ensures that the text editor in the floating window.
*/
createWindow() {
if (this.m_editorWindow !== null) {
return;
}
if (this.m_editorIframe !== null) {
this.elemEditor.removeChild(this.m_editorIframe);
this.m_editorIframe = null;
}
this.m_editorWindow = window.open(
this.m_frameURL,
"Text editor",
"width=600,height=400,toolbar=0,status=0"
);
this.m_editorWindow!.addEventListener("message", this.onMessage);
this.m_editorWindow!.onbeforeunload = () => {
settings.emit("editor:setSide", Side.Left);
};
}
/**
* Theme source code getter.
*/
getValue() {
return this.m_value;
}
undo() {
return this.sendMsg({ command: "undo" });
}
redo() {
return this.sendMsg({ command: "redo" });
}
/**
* Sets the source code, updates the available styles, and sets the proper style.
*/
setValue(str: string) {
this.sendMsg({ command: "SetSourceValue", value: str });
this.updateSource(str);
}
/**
* Send [[WindowCommands]] to the child text editor.
*/
sendMsg(msg: WindowCommands) {
if (this.m_editorWindow !== null) {
this.m_editorWindow.postMessage(msg, this.m_frameURL);
} else if (this.m_editorIframe !== null && this.m_editorIframe.contentWindow !== null) {
this.m_editorIframe.contentWindow.postMessage(msg, this.m_frameURL);
}
}
/**
* Generates a file and open a file save dialogue.
*/
download() {
saveData(this.getValue(), "theme.json");
}
/**
* Opens a file and sets it as the source code of the theme.
*/
openFile() {
openFile()
.then(value => {
this.setValue(value);
})
.catch(() => {
const popup = {
name: "ERROR",
options: {},
component: <p>Can't open file.</p>
};
PopupsContainer.addPopup(popup);
});
}
/**
* Send a [[Format]] command to the child text editor.
*/
formatFile() {
this.sendMsg({ command: "Format" });
}
/**
* Send a [[ShowCommands]] command to the child text editor.
*/
showCommands() {
this.sendMsg({ command: "ShowCommands" });
}
getParsedTheme() {
return this.m_parsedTheme;
}
setCursor(line: number, column: number) {
this.sendMsg({
command: "SetCursor",
column,
line
});
}
/**
* Updates the available styles list, and sets the proper style.
*/
private updateSource(source: string) {
this.m_value = source;
this.m_parsedTheme = null;
let styles: string[] = [];
try {
this.m_parsedTheme = JSON.parse(source) as Theme;
} catch (error) {
settings.setStoreData("styles", styles);
settings.setStoreData("parsedTheme", this.m_parsedTheme);
return;
}
if (this.m_parsedTheme.styles !== undefined) {
const values = Object.values(this.m_parsedTheme.styles);
if (values.length > 0 && values.every(value => Array.isArray(value))) {
styles = Object.keys(this.m_parsedTheme.styles);
}
}
const currentStyle = settings.get("editorCurrentStyle");
settings.setStoreData("styles", styles);
settings.setStoreData("parsedTheme", this.m_parsedTheme);
if (styles.length === 0) {
settings.set("editorCurrentStyle", null);
} else if (currentStyle === null || !styles.includes(currentStyle)) {
settings.set("editorCurrentStyle", styles[0]);
}
}
}
const saveData = (() => {
const link = document.createElement("a");
document.body.appendChild(link);
link.style.display = "none";
return (data: string, fileName: string) => {
const blob = new Blob([data], { type: "octet/stream" });
const url = window.URL.createObjectURL(blob);
link.href = url;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(url);
};
})();
async function openFile(): Promise<string> {
const fileBrowser = document.createElement("input");
document.body.appendChild(fileBrowser);
fileBrowser.style.display = "none";
fileBrowser.type = "file";
fileBrowser.click();
function removeObj() {
document.body.removeChild(fileBrowser);
}
return new Promise((resolve, reject) => {
fileBrowser.addEventListener(
"change",
event => {
if (!event || !event.target) {
return reject("");
}
const { files } = event.target as HTMLInputElement;
if (!files || !files[0]) {
return reject("");
}
const reader = new FileReader();
reader.onload = () => {
resolve((reader.result || "").toString());
};
reader.onerror = () => {
reject("");
};
reader.readAsText(files[0]);
},
false
);
}).then(str => {
removeObj();
return str as string;
});
}
export default new TextEditor();