-
Notifications
You must be signed in to change notification settings - Fork 56
/
index.js
463 lines (428 loc) · 13.2 KB
/
index.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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/* eslint no-underscore-dangle:0 */
import appLocaleFn from './locale/app-locale';
import appThemeFn from './app-theme';
import deviceTypeFn from './device-type';
import bootNebulaApp from './components/NebulaApp';
import AppSelectionsPortal from './components/selections/AppSelections';
import ListBoxPortal from './components/listbox/ListBoxInline';
import create from './object/create-session-object';
import get from './object/get-object';
import flagsFn from './flags/flags';
import { create as typesFn } from './sn/types';
/**
* @interface Context
* @property {boolean=} disableCellPadding
* @property {boolean=} keyboardNavigation
* @property {object=} constraints
* @property {boolean=} constraints.active
* @property {boolean=} constraints.passive
* @property {boolean=} constraints.select
*/
const DEFAULT_CONTEXT = /** @lends Context */ {
/** @type {string=} */
theme: 'light',
/** @type {string=} */
language: 'en-US',
/** @type {string=} */
deviceType: 'auto',
constraints: {},
keyboardNavigation: false,
disableCellPadding: false,
};
/**
* @interface SnapshotConfiguration
* @private
*/
const DEFAULT_SNAPSHOT_CONFIG = /** @lends SnapshotConfiguration */ {
/**
* @param {string} id
* @returns {Promise<SnapshotLayout>}
*/
get: async (id) => {
const res = await fetch(`/njs/snapshot/${id}`);
if (!res.ok) {
throw new Error(res.statusText);
}
return res.json();
},
capture(payload) {
return fetch(`/njs/capture`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
}).then((res) => res.json());
},
};
/**
* @interface Configuration
*/
const DEFAULT_CONFIG = /** @lends Configuration */ {
/**
* @type {Context=}
*/
context: DEFAULT_CONTEXT,
load: () => undefined,
/**
* @type {(TypeInfo[])=}
*/
types: [],
/**
* @type {(ThemeInfo[])=}
*/
themes: [],
/** @type {object=} */
anything: {},
/**
* @type {SnapshotConfiguration=}
* @private
*/
snapshot: DEFAULT_SNAPSHOT_CONFIG,
};
/**
* @interface Galaxy
*/
const mergeObj = (o1 = {}, o2 = {}) => ({
...o1,
...o2,
});
const mergeArray = (a1 = [], a2 = []) =>
// Simple merge and deduplication
[...a1, ...a2].filter((v, i, a) => a.indexOf(v) === i);
const mergeConfigs = (base, c) => ({
context: mergeObj(base.context, c.context),
load: c.load || base.load,
snapshot: {
...(c.snapshot || base.snapshot),
},
types: mergeArray(base.types, c.types),
themes: mergeArray(base.themes, c.themes),
flags: mergeObj(base.flags, c.flags),
anything: mergeObj(base.anything, c.anything),
});
function nuked(configuration = {}) {
const locale = appLocaleFn(configuration.context.language);
/**
* Initiates a new `Embed` instance using the specified enigma `app`.
* @entry
* @function embed
* @param {EngineAPI.IApp} app
* @param {Configuration=} instanceConfig
* @returns {Embed}
* @example
* import { embed } from '@nebula.js/stardust'
* const n = embed(app);
* n.render({ id: 'abc' });
*/
function embed(app, instanceConfig) {
if (instanceConfig) {
return embed.createConfiguration(instanceConfig)(app);
}
let currentContext = {
...configuration.context,
translator: locale.translator,
};
const [root] = bootNebulaApp({
app,
context: currentContext,
});
const appTheme = appThemeFn({
themes: configuration.themes,
root,
});
const publicAPIs = {
galaxy: /** @lends Galaxy */ {
/** @type {Translator} */
translator: locale.translator,
// TODO - validate flags input
/** @type {Flags} */
flags: flagsFn(configuration.flags),
/** @type {string} */
deviceType: deviceTypeFn(configuration.context.deviceType),
/** @type {object} */
anything: configuration.anything,
},
theme: appTheme.externalAPI,
translator: locale.translator,
nebbie: null, // actual value is set further down
};
const halo = {
app,
root,
config: configuration,
public: publicAPIs,
context: currentContext,
types: null,
};
const types = typesFn({ halo });
configuration.types.forEach((t) =>
types.register(
{
name: t.name,
version: t.version,
},
{
meta: t.meta,
load: t.load,
}
)
);
let currentThemePromise = appTheme.setTheme(configuration.context.theme);
let selectionsApi = null;
let selectionsComponentReference = null;
/**
* @class
* @alias Embed
*/
const api = /** @lends Embed# */ {
/**
* Renders a visualization into an HTMLElement.
* @param {CreateConfig | GetConfig} cfg - The render configuration.
* @returns {Promise<Viz>} A controller to the rendered visualization.
* @example
* // render from existing object
* n.render({
* element: el,
* id: 'abcdef'
* });
* @example
* // render on the fly
* n.render({
* element: el,
* type: 'barchart',
* fields: ['Product', { qLibraryId: 'u378hn', type: 'measure' }]
* });
*/
render: async (cfg) => {
await currentThemePromise;
if (cfg.id) {
return get(cfg, halo);
}
return create(cfg, halo);
},
/**
* Updates the current context of this embed instance.
* Use this when you want to change some part of the current context, like theme.
* @param {Context} ctx - The context to update.
* @returns {Promise<undefined>}
* @example
* // change theme
* n.context({ theme: 'dark'});
* @example
* // limit constraints
* n.context({ constraints: { active: true } });
*/
context: async (ctx) => {
// filter valid values to avoid triggering unnecessary rerender
let changes;
['theme', 'language', 'constraints', 'keyboardNavigation'].forEach((key) => {
if (Object.prototype.hasOwnProperty.call(ctx, key) && ctx[key] !== currentContext[key]) {
if (!changes) {
changes = {};
}
changes[key] = ctx[key];
}
});
if (!changes) {
return;
}
currentContext = {
...currentContext,
...changes,
translator: locale.translator,
};
halo.context = currentContext;
if (changes.theme) {
currentThemePromise = appTheme.setTheme(changes.theme);
await currentThemePromise;
}
if (changes.language) {
halo.public.translator.language(changes.language);
}
root.context(currentContext);
},
/**
* Gets the app selections of this instance.
* @returns {Promise<AppSelections>}
* @example
* const selections = await n.selections();
* selections.mount(element);
*/
selections: async () => {
if (!selectionsApi) {
// const appSelections = await root.getAppSelections(); // Don't expose this for now
selectionsApi = /** @lends AppSelections# */ {
/**
* Mounts the app selection UI into the provided HTMLElement.
* @param {HTMLElement} element
* @example
* selections.mount(element);
*/
mount(element) {
if (selectionsComponentReference) {
if (__NEBULA_DEV__) {
console.error('Already mounted'); // eslint-disable-line no-console
}
return;
}
selectionsComponentReference = AppSelectionsPortal({
element,
app,
});
root.add(selectionsComponentReference);
},
/**
* Unmounts the app selection UI from the DOM.
* @example
* selections.unmount();
*/
unmount() {
if (selectionsComponentReference) {
root.remove(selectionsComponentReference);
selectionsComponentReference = null;
}
},
};
}
return selectionsApi;
},
/**
* Gets the listbox instance of the specified field
* @param {string|LibraryField} fieldIdentifier Fieldname as a string or a Library dimension
* @returns {Promise<FieldInstance>}
* @since 1.1.0
* @example
* const fieldInstance = await n.field("MyField");
* fieldInstance.mount(element, { title: "Hello Field"});
*/
field: async (fieldIdentifier) => {
const fieldName = typeof fieldIdentifier === 'string' ? fieldIdentifier : fieldIdentifier.qLibraryId;
if (!fieldName) {
throw new Error(`Field identifier must be provided`);
}
/**
* @typedef {function(function)} ReceiverFunction A callback function which receives another function as input.
*/
/**
* @class
* @alias FieldInstance
* @since 1.1.0
*/
const fieldSels = {
fieldName,
/**
* Mounts the field as a listbox into the provided HTMLElement.
* @param {HTMLElement} element
* @param {object=} options Settings for the embedded listbox
* @param {string=} options.title Custom title, defaults to fieldname
* @param {string=} [options.direction=ltr] Direction setting ltr|rtl.
* @param {string=} [options.listLayout=vertical] Layout direction vertical|horizontal
* @param {boolean=} [options.search=true] To show the search bar
* @param {boolean=} [options.toolbar=true] To show the toolbar
* @param {boolean=} [options.stateName="$"] Sets the state to make selections in
* @param {object=} [options.properties={}] Properties object to extend default properties with
* @param {object} [options.sessionModel] Use a custom sessionModel.
* @param {object} [options.selectionsApi] Use a custom selectionsApi to customize how values are selected.
* @param {ReceiverFunction} [options.update] A function which receives an update function which upon call will trigger a data fetch.
* @since 1.1.0
* @instance
* @example
* fieldInstance.mount(element);
*/
mount(element, options = {}) {
if (!element) {
throw new Error(`Element for ${fieldName} not provided`);
}
if (this._instance) {
throw new Error(`Field ${fieldName} already mounted`);
}
this._instance = ListBoxPortal({
element,
app,
fieldIdentifier,
options,
stateName: options.stateName || '$',
});
root.add(this._instance);
},
/**
* Unmounts the field listbox from the DOM.
* @since 1.1.0
* @instance
* @example
* listbox.unmount();
*/
unmount() {
if (this._instance) {
root.remove(this._instance);
this._instance = null;
}
},
};
return fieldSels;
},
/**
* Gets a list of registered visualization types and versions
* @function
* @returns {Array<Object>} types
* @example
* const types = n.getRegisteredTypes();
* // Contains
* //[
* // {
* // name: "barchart"
* // versions:[undefined, "1.2.0"]
* // }
* //]
*/
getRegisteredTypes: types.getList,
__DO_NOT_USE__: {
types,
},
};
halo.public.nebbie = api;
halo.types = types;
return api;
}
/**
* Creates a new `embed` scope bound to the specified `configuration`.
*
* The configuration is merged with all previous scopes.
* @memberof embed
* @param {Configuration} configuration - The configuration object
* @returns {embed}
* @example
* import { embed } from '@nebula.js/stardust';
* // create a 'master' config which registers all types
* const m = embed.createConfiguration({
* types: [{
* name: 'mekko',
* version: '1.0.0',
* load: () => Promise.resolve(mekko)
* }],
* });
*
* // create an alternate config with dark theme
* // and inherit the config from the previous
* const d = m.createConfiguration({
* theme: 'dark'
* });
*
* m(app).render({ type: 'mekko' }); // will render the object with default theme
* d(app).render({ type: 'mekko' }); // will render the object with 'dark' theme
* embed(app).render({ type: 'mekko' }); // will throw error since 'mekko' is not a register type on the default instance
*/
embed.createConfiguration = (c) => nuked(mergeConfigs(configuration, c));
embed.config = configuration;
return embed;
}
/**
* @typedef {any} ThemeJSON
*/
/**
* @interface ThemeInfo
* @property {string} id Theme identifier
* @property {function(): Promise<ThemeJSON>} load A function that should return a Promise that resolves to a raw JSON theme.
*/
export default nuked(DEFAULT_CONFIG);