forked from microsoft/pxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.ts
More file actions
363 lines (306 loc) · 10.3 KB
/
core.ts
File metadata and controls
363 lines (306 loc) · 10.3 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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/// <reference path="../../built/pxtlib.d.ts" />
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as data from "./data";
import * as sui from "./sui";
import * as coretsx from "./coretsx";
import Cloud = pxt.Cloud;
import Util = pxt.Util;
export type Component<S, T> = data.Component<S, T>;
///////////////////////////////////////////////////////////
//////////// Loading spinner /////////////
///////////////////////////////////////////////////////////
let dimmerInitialized = false;
let loadingDimmer: coretsx.LoadingDimmer;
let loadingQueue: string[] = [];
let loadingQueueMsg: pxt.Map<string> = {};
export function isLoading() {
return loadingDimmer && loadingDimmer.isVisible();
}
export function hideLoading(id: string) {
pxt.debug("hideloading: " + id);
if (loadingQueueMsg[id] != undefined) {
// loading exists, remove from queue
const index = loadingQueue.indexOf(id);
if (index > -1) loadingQueue.splice(index, 1);
delete loadingQueueMsg[id];
} else {
pxt.debug("Loading not in queue, disregard: " + id);
}
if (loadingQueue.length > 0) {
// Show the next loading message
displayNextLoading();
} else {
// Hide loading
if (dimmerInitialized && loadingDimmer) {
loadingDimmer.hide();
}
}
}
export function killLoadingQueue() {
// Use this with care, only when you want to kill the loading queue
// and force close them all
loadingQueue = [];
loadingQueueMsg = {};
// Hide loading
if (dimmerInitialized && loadingDimmer) {
loadingDimmer.hide();
}
}
export function showLoading(id: string, msg: string) {
pxt.debug("showloading: " + id);
if (loadingQueueMsg[id]) return; // already loading?
initializeDimmer();
loadingDimmer.show(lf("Please wait"));
loadingQueue.push(id);
loadingQueueMsg[id] = msg;
displayNextLoading();
}
function displayNextLoading() {
if (!loadingQueue.length) return;
const id = loadingQueue[loadingQueue.length - 1]; // get last item
const msg = loadingQueueMsg[id];
loadingDimmer.show(msg);
}
function initializeDimmer() {
if (dimmerInitialized) return;
const wrapper = document.getElementById('content').appendChild(document.createElement('div'));
loadingDimmer = ReactDOM.render(React.createElement(coretsx.LoadingDimmer, {}), wrapper);
dimmerInitialized = true;
}
let asyncLoadingTimeout: pxt.Map<number> = {};
export function showLoadingAsync(id: string, msg: string, operation: Promise<any>, delay: number = 700) {
clearTimeout(asyncLoadingTimeout[id]);
asyncLoadingTimeout[id] = setTimeout(function () {
showLoading(id, msg);
}, delay);
return operation.finally(() => {
cancelAsyncLoading(id);
});
}
export function cancelAsyncLoading(id: string) {
clearTimeout(asyncLoadingTimeout[id]);
hideLoading(id);
}
///////////////////////////////////////////////////////////
//////////// Notification msg /////////////
///////////////////////////////////////////////////////////
function showNotificationMsg(kind: string, msg: string) {
coretsx.pushNotificationMessage({ kind: kind, text: msg, hc: highContrast });
}
export function errorNotification(msg: string) {
pxt.tickEvent("notification.error", { message: msg })
debugger // trigger a breakpoint when a debugger is connected, like in U.oops()
showNotificationMsg("err", msg)
}
export function warningNotification(msg: string) {
pxt.log("warning: " + msg)
showNotificationMsg("warn", msg)
}
export function infoNotification(msg: string) {
pxt.debug(msg)
showNotificationMsg("info", msg)
}
///////////////////////////////////////////////////////////
//////////// Dialogs (confirm, prompt) /////////////
///////////////////////////////////////////////////////////
export interface ConfirmOptions extends DialogOptions {
agreeLbl?: string;
agreeIcon?: string;
agreeClass?: string;
hideAgree?: boolean;
deleteLbl?: string;
}
export interface PromptOptions extends ConfirmOptions {
initialValue?: string;
placeholder?: string;
onInputChanged?: (newValue?: string) => void;
}
export interface DialogOptions {
type?: string;
hideCancel?: boolean;
disagreeLbl?: string;
disagreeClass?: string;
disagreeIcon?: string;
logos?: string[];
className?: string;
header: string;
body?: string;
jsx?: JSX.Element;
htmlBody?: string;
copyable?: string;
size?: string; // defaults to "small"
onLoaded?: (_: HTMLElement) => void;
buttons?: sui.ModalButton[];
timeout?: number;
modalContext?: string;
hasCloseIcon?: boolean;
}
export function dialogAsync(options: DialogOptions): Promise<void> {
if (!options.type) options.type = 'dialog';
if (!options.hideCancel) {
if (!options.buttons) options.buttons = [];
options.buttons.push({
label: options.disagreeLbl || lf("Cancel"),
className: (options.disagreeClass || "cancel"),
icon: options.disagreeIcon || "cancel"
})
}
return coretsx.renderConfirmDialogAsync(options as PromptOptions);
}
export function hideDialog() {
coretsx.hideDialog();
}
export function confirmAsync(options: ConfirmOptions): Promise<number> {
options.type = 'confirm';
if (!options.buttons) options.buttons = []
let result = 0
if (!options.hideAgree) {
options.buttons.push({
label: options.agreeLbl || lf("Go ahead!"),
className: options.agreeClass,
icon: options.agreeIcon || "checkmark",
approveButton: true,
onclick: () => {
result = 1;
}
})
}
if (options.deleteLbl) {
options.buttons.push({
label: options.deleteLbl,
className: "delete red",
icon: "trash",
onclick: () => {
result = 2
}
})
}
return dialogAsync(options)
.then(() => result)
}
export function confirmDelete(what: string, cb: () => Promise<void>, multiDelete?: boolean) {
confirmAsync({
header: multiDelete ?
lf("Would you like to delete {0} projects?", what) :
lf("Would you like to delete '{0}'?", what),
body: lf("It will be deleted for good. No undo."),
agreeLbl: lf("Delete"),
agreeClass: "red",
agreeIcon: "trash",
}).then(res => {
if (res) {
cb().done()
}
}).done()
}
export function promptAsync(options: PromptOptions): Promise<string> {
options.type = 'prompt';
if (!options.buttons) options.buttons = []
let result = options.initialValue || "";
let cancelled: boolean = false;
options.onInputChanged = (v: string) => { result = v };
if (!options.hideAgree) {
options.buttons.push({
label: options.agreeLbl || lf("Go ahead!"),
className: options.agreeClass,
icon: options.agreeIcon || "checkmark",
approveButton: true
})
}
if (!options.hideCancel) {
// Replace the default cancel button with our own
options.buttons.push({
label: options.disagreeLbl || lf("Cancel"),
className: (options.disagreeClass || "cancel"),
icon: options.disagreeIcon || "cancel",
onclick: () => {
cancelled = true;
}
});
options.hideCancel = true;
}
return dialogAsync(options)
.then(() => cancelled ? null : result);
}
///////////////////////////////////////////////////////////
//////////// Accessibility /////////////
///////////////////////////////////////////////////////////
export let highContrast: boolean;
export const TAB_KEY = 9;
export const ESC_KEY = 27;
export const ENTER_KEY = 13;
export const SPACE_KEY = 32;
export function setHighContrast(on: boolean) {
highContrast = on;
}
export function resetFocus() {
let content = document.getElementById('content');
content.tabIndex = 0;
content.focus();
content.blur();
content.tabIndex = -1;
}
export function keyCodeFromEvent(e: any) {
return (typeof e.which == "number") ? e.which : e.keyCode;
}
///////////////////////////////////////////////////////////
//////////// Helper functions /////////////
///////////////////////////////////////////////////////////
export function navigateInWindow(url: string) {
window.location.href = url;
}
export function findChild(c: React.Component<any, any>, selector: string): Element[] {
let self = ReactDOM.findDOMNode(c);
if (!selector) return [self]
return pxt.Util.toArray(self.querySelectorAll(selector));
}
export function parseQueryString(qs: string) {
let r: pxt.Map<string> = {}
qs.replace(/\+/g, " ").replace(/([^#?&=]+)=([^#?&=]*)/g, (f: string, k: string, v: string) => {
r[decodeURIComponent(k)] = decodeURIComponent(v)
return ""
})
return r
}
export function stringifyQueryString(url: string, qs: any) {
for (let k of Object.keys(qs)) {
if (url.indexOf("?") >= 0) {
url += "&"
} else {
url += "?"
}
url += encodeURIComponent(k) + "=" + encodeURIComponent(qs[k])
}
return url
}
export function handleNetworkError(e: any, ignoredCodes?: number[]) {
let statusCode = parseInt(e.statusCode);
if (e.isOffline || statusCode === 0) {
warningNotification(lf("Network request failed; you appear to be offline"));
} else if (!isNaN(statusCode) && statusCode !== 200) {
if (ignoredCodes && ignoredCodes.indexOf(statusCode) !== -1) {
return e;
}
warningNotification(lf("Network request failed"));
}
throw e;
}
///////////////////////////////////////////////////////////
//////////// Javascript console /////////////
///////////////////////////////////////////////////////////
export function apiAsync(path: string, data?: any) {
return (data ?
Cloud.privatePostAsync(path, data) :
Cloud.privateGetAsync(path))
.then(resp => {
console.log("*")
console.log("*******", path, "--->")
console.log("*")
console.log(resp)
console.log("*")
return resp
}, err => {
console.log(err.message)
})
}