sygnal 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/component.js DELETED
@@ -1,1324 +0,0 @@
1
- 'use strict';
2
-
3
- var _excluded = ["state", "sygnalFactory", "id"];
4
-
5
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
6
-
7
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
8
-
9
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
10
-
11
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
12
-
13
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
14
-
15
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
16
-
17
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
18
-
19
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
20
-
21
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
22
-
23
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
24
-
25
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
26
-
27
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
28
-
29
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30
-
31
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
32
-
33
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
34
-
35
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
36
-
37
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
38
-
39
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
40
-
41
- function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
42
-
43
- import isolate from '@cycle/isolate';
44
- import collection from './collection.js';
45
- import switchable from './switchable.js';
46
- import { StateSource } from '@cycle/state';
47
- import { default as xs, Stream } from 'xstream';
48
- import { default as delay } from 'xstream/extra/delay.js';
49
- import { default as concat } from 'xstream/extra/concat.js';
50
- import debounce from 'xstream/extra/debounce.js';
51
- import { default as dropRepeats } from 'xstream/extra/dropRepeats.js'; // import syntax has bugs for xstream in Node context
52
- // this attempts to normalize to work in both Node and browser
53
- // if (!xs.never && xs.default && xs.default.never) {
54
- // xs.never = xs.default.never
55
- // xs.merge = xs.default.merge
56
- // xs.of = xs.default.of
57
- // }
58
- // const concat = (Concat && Concat.default) ? Concat.default : Concat
59
- // const delay = (Delay && Delay.default) ? Delay.default : Delay
60
- // const dropRepeats = (DropRepeats && DropRepeats.default) ? DropRepeats.default : DropRepeats
61
-
62
- var ENVIRONMENT = typeof window != 'undefined' && window || process && process.env || {};
63
- var REQUEST_SELECTOR_METHOD = 'request';
64
- var BOOTSTRAP_ACTION = 'BOOTSTRAP';
65
- var INITIALIZE_ACTION = 'INITIALIZE';
66
- var HYDRATE_ACTION = 'HYDRATE';
67
- var IS_ROOT_COMPONENT = true;
68
- export var ABORT = '~#~#~ABORT~#~#~';
69
- export default function component(opts) {
70
- var name = opts.name,
71
- sources = opts.sources,
72
- isolateOpts = opts.isolateOpts,
73
- _opts$stateSourceName = opts.stateSourceName,
74
- stateSourceName = _opts$stateSourceName === void 0 ? 'STATE' : _opts$stateSourceName;
75
-
76
- if (sources && _typeof(sources) !== 'object') {
77
- throw new Error('Sources must be a Cycle.js sources object:', name);
78
- }
79
-
80
- var fixedIsolateOpts;
81
-
82
- if (typeof isolateOpts == 'string') {
83
- fixedIsolateOpts = _defineProperty({}, stateSourceName, isolateOpts);
84
- } else {
85
- if (isolateOpts === true) {
86
- fixedIsolateOpts = {};
87
- } else {
88
- fixedIsolateOpts = isolateOpts;
89
- }
90
- }
91
-
92
- var currySources = typeof sources === 'undefined';
93
-
94
- if (_typeof(fixedIsolateOpts) == 'object') {
95
- var wrapped = function wrapped(sources) {
96
- var fixedOpts = _objectSpread(_objectSpread({}, opts), {}, {
97
- sources: sources
98
- });
99
-
100
- return new Component(fixedOpts).sinks;
101
- };
102
-
103
- return currySources ? isolate(wrapped, fixedIsolateOpts) : isolate(wrapped, fixedIsolateOpts)(sources);
104
- } else {
105
- return currySources ? function (sources) {
106
- return new Component(_objectSpread(_objectSpread({}, opts), {}, {
107
- sources: sources
108
- })).sinks;
109
- } : new Component(opts).sinks;
110
- }
111
- }
112
-
113
- var Component = /*#__PURE__*/function () {
114
- // [ PASSED PARAMETERS ]
115
- // name
116
- // sources
117
- // intent
118
- // request
119
- // model
120
- // response
121
- // view
122
- // children
123
- // initialState
124
- // calculated
125
- // storeCalculatedInState
126
- // DOMSourceName
127
- // stateSourceName
128
- // requestSourceName
129
- // [ PRIVATE / CALCULATED VALUES ]
130
- // sourceNames
131
- // intent$
132
- // action$
133
- // model$
134
- // response$
135
- // sendResponse$
136
- // children$
137
- // vdom$
138
- // subComponentSink$
139
- // [ INSTANTIATED STREAM OPERATOR ]
140
- // log
141
- // [ OUTPUT ]
142
- // sinks
143
- function Component(_ref) {
144
- var _this = this;
145
-
146
- var _ref$name = _ref.name,
147
- name = _ref$name === void 0 ? 'NO NAME' : _ref$name,
148
- sources = _ref.sources,
149
- intent = _ref.intent,
150
- request = _ref.request,
151
- model = _ref.model,
152
- response = _ref.response,
153
- view = _ref.view,
154
- _ref$children = _ref.children,
155
- children = _ref$children === void 0 ? {} : _ref$children,
156
- _ref$components = _ref.components,
157
- components = _ref$components === void 0 ? {} : _ref$components,
158
- initialState = _ref.initialState,
159
- calculated = _ref.calculated,
160
- _ref$storeCalculatedI = _ref.storeCalculatedInState,
161
- storeCalculatedInState = _ref$storeCalculatedI === void 0 ? true : _ref$storeCalculatedI,
162
- _ref$DOMSourceName = _ref.DOMSourceName,
163
- DOMSourceName = _ref$DOMSourceName === void 0 ? 'DOM' : _ref$DOMSourceName,
164
- _ref$stateSourceName = _ref.stateSourceName,
165
- stateSourceName = _ref$stateSourceName === void 0 ? 'STATE' : _ref$stateSourceName,
166
- _ref$requestSourceNam = _ref.requestSourceName,
167
- requestSourceName = _ref$requestSourceNam === void 0 ? 'HTTP' : _ref$requestSourceNam;
168
-
169
- _classCallCheck(this, Component);
170
-
171
- if (!sources || _typeof(sources) != 'object') throw new Error('Missing or invalid sources');
172
- this.name = name;
173
- this.sources = sources;
174
- this.intent = intent;
175
- this.request = request;
176
- this.model = model;
177
- this.response = response;
178
- this.view = view;
179
- this.children = children;
180
- this.components = components;
181
- this.initialState = initialState;
182
- this.calculated = calculated;
183
- this.storeCalculatedInState = storeCalculatedInState;
184
- this.DOMSourceName = DOMSourceName;
185
- this.stateSourceName = stateSourceName;
186
- this.requestSourceName = requestSourceName;
187
- this.sourceNames = Object.keys(sources);
188
- this.isSubComponent = this.sourceNames.includes('props$');
189
- var state$ = sources[stateSourceName] && sources[stateSourceName].stream;
190
-
191
- if (state$) {
192
- this.currentState = initialState || {};
193
- this.sources[this.stateSourceName] = new StateSource(state$.map(function (val) {
194
- _this.currentState = val;
195
- return val;
196
- }));
197
- }
198
-
199
- if (IS_ROOT_COMPONENT && typeof this.intent === 'undefined' && typeof this.model === 'undefined') {
200
- this.initialState = initialState || true;
201
-
202
- this.intent = function (_) {
203
- return {
204
- __NOOP_ACTION__: xs.never()
205
- };
206
- };
207
-
208
- this.model = {
209
- __NOOP_ACTION__: function __NOOP_ACTION__(state) {
210
- return state;
211
- }
212
- };
213
- }
214
-
215
- IS_ROOT_COMPONENT = false;
216
- this.log = makeLog(name);
217
- this.initIntent$();
218
- this.initAction$();
219
- this.initResponse$();
220
- this.initState();
221
- this.initModel$();
222
- this.initSendResponse$();
223
- this.initChildren$();
224
- this.initSubComponentSink$();
225
- this.initVdom$();
226
- this.initSinks();
227
- }
228
-
229
- _createClass(Component, [{
230
- key: "initIntent$",
231
- value: function initIntent$() {
232
- if (!this.intent) {
233
- return;
234
- }
235
-
236
- if (typeof this.intent != 'function') {
237
- throw new Error('Intent must be a function');
238
- }
239
-
240
- this.intent$ = this.intent(this.sources);
241
-
242
- if (!(this.intent$ instanceof Stream) && _typeof(this.intent$) != 'object') {
243
- throw new Error('Intent must return either an action$ stream or map of event streams');
244
- }
245
- }
246
- }, {
247
- key: "initAction$",
248
- value: function initAction$() {
249
- var requestSource = this.sources && this.sources[this.requestSourceName] || null;
250
-
251
- if (!this.intent$) {
252
- this.action$ = xs.never();
253
- return;
254
- }
255
-
256
- var runner;
257
-
258
- if (this.intent$ instanceof Stream) {
259
- runner = this.intent$;
260
- } else {
261
- var mapped = Object.entries(this.intent$).map(function (_ref2) {
262
- var _ref3 = _slicedToArray(_ref2, 2),
263
- type = _ref3[0],
264
- data$ = _ref3[1];
265
-
266
- return data$.map(function (data) {
267
- return {
268
- type: type,
269
- data: data
270
- };
271
- });
272
- });
273
- runner = xs.merge.apply(xs, [xs.never()].concat(_toConsumableArray(mapped)));
274
- }
275
-
276
- var action$ = runner instanceof Stream ? runner : runner.apply && runner(this.sources) || xs.never();
277
- var wrapped$ = concat(xs.of({
278
- type: BOOTSTRAP_ACTION
279
- }), action$).compose(delay(10));
280
- var initialApiData;
281
-
282
- if (requestSource && typeof requestSource.select == 'function') {
283
- initialApiData = requestSource.select('initial').flatten();
284
- } else {
285
- initialApiData = xs.never();
286
- }
287
-
288
- var hydrate$ = initialApiData.map(function (data) {
289
- return {
290
- type: HYDRATE_ACTION,
291
- data: data
292
- };
293
- });
294
- this.action$ = xs.merge(wrapped$, hydrate$).compose(this.log(function (_ref4) {
295
- var type = _ref4.type;
296
- return "Action triggered: <".concat(type, ">");
297
- }));
298
- }
299
- }, {
300
- key: "initResponse$",
301
- value: function initResponse$() {
302
- var _this2 = this;
303
-
304
- if (typeof this.request == 'undefined') {
305
- return;
306
- } else if (_typeof(this.request) != 'object') {
307
- throw new Error('The request parameter must be an object');
308
- }
309
-
310
- var router$ = this.sources[this.requestSourceName];
311
- var methods = Object.entries(this.request);
312
- var wrapped = methods.reduce(function (acc, _ref5) {
313
- var _ref6 = _slicedToArray(_ref5, 2),
314
- method = _ref6[0],
315
- routes = _ref6[1];
316
-
317
- var _method = method.toLowerCase();
318
-
319
- if (typeof router$[_method] != 'function') {
320
- throw new Error('Invalid method in request object:', method);
321
- }
322
-
323
- var entries = Object.entries(routes);
324
- var mapped = entries.reduce(function (acc, _ref7) {
325
- var _ref8 = _slicedToArray(_ref7, 2),
326
- route = _ref8[0],
327
- action = _ref8[1];
328
-
329
- var routeString = "[".concat(_method.toUpperCase(), "]:").concat(route || 'none');
330
-
331
- var actionType = _typeof(action);
332
-
333
- if (actionType === 'undefined') {
334
- throw new Error("Action for '".concat(route, "' route in request object not specified"));
335
- } else if (actionType !== 'string' && actionType !== 'function') {
336
- throw new Error("Invalid action for '".concat(route, "' route: expecting string or function"));
337
- }
338
-
339
- var actionString = actionType === 'function' ? '[ FUNCTION ]' : "< ".concat(action, " >");
340
- console.log("[".concat(_this2.name, "] Adding ").concat(_this2.requestSourceName, " route:"), _method.toUpperCase(), "'".concat(route, "' <").concat(actionString, ">"));
341
-
342
- var route$ = router$[_method](route).compose(dropRepeats(function (a, b) {
343
- return a.id == b.id;
344
- })).map(function (req) {
345
- if (!req || !req.id) {
346
- throw new Error("No id found in request: ".concat(routeString));
347
- }
348
-
349
- try {
350
- var _reqId = req.id;
351
- var params = req.params;
352
- var body = req.body;
353
- var cookies = req.cookies;
354
- var type = actionType === 'function' ? 'FUNCTION' : action;
355
- var data = {
356
- params: params,
357
- body: body,
358
- cookies: cookies,
359
- req: req
360
- };
361
- var obj = {
362
- type: type,
363
- data: body,
364
- req: req,
365
- _reqId: _reqId,
366
- _action: type
367
- };
368
- var timestamp = new Date().toISOString();
369
- var ip = req.get ? req.get('host') : '0.0.0.0';
370
- console.log("".concat(timestamp, " ").concat(ip, " ").concat(req.method, " ").concat(req.url));
371
-
372
- if (ENVIRONMENT.DEBUG) {
373
- _this2.action$.setDebugListener({
374
- next: function next(_ref9) {
375
- var type = _ref9.type;
376
- return console.log("[".concat(_this2.name, "] Action from ").concat(_this2.requestSourceName, " request: <").concat(type, ">"));
377
- }
378
- });
379
- }
380
-
381
- if (actionType === 'function') {
382
- var enhancedState = _this2.addCalculated(_this2.currentState);
383
-
384
- var result = action(enhancedState, req);
385
- return xs.of(_objectSpread(_objectSpread({}, obj), {}, {
386
- data: result
387
- }));
388
- } else {
389
- _this2.action$.shamefullySendNext(obj);
390
-
391
- var sourceEntries = Object.entries(_this2.sources);
392
- var responses = sourceEntries.reduce(function (acc, _ref10) {
393
- var _ref11 = _slicedToArray(_ref10, 2),
394
- name = _ref11[0],
395
- source = _ref11[1];
396
-
397
- if (!source || typeof source[REQUEST_SELECTOR_METHOD] != 'function') return acc;
398
- var selected$ = source[REQUEST_SELECTOR_METHOD](_reqId);
399
- return [].concat(_toConsumableArray(acc), [selected$]);
400
- }, []);
401
- return xs.merge.apply(xs, _toConsumableArray(responses));
402
- }
403
- } catch (err) {
404
- console.error(err);
405
- }
406
- }).flatten();
407
-
408
- return [].concat(_toConsumableArray(acc), [route$]);
409
- }, []);
410
- var mapped$ = xs.merge.apply(xs, _toConsumableArray(mapped));
411
- return [].concat(_toConsumableArray(acc), [mapped$]);
412
- }, []);
413
- this.response$ = xs.merge.apply(xs, _toConsumableArray(wrapped)).compose(this.log(function (res) {
414
- if (res._action) return "[".concat(_this2.requestSourceName, "] response data received for Action: <").concat(res._action, ">");
415
- return "[".concat(_this2.requestSourceName, "] response data received from FUNCTION");
416
- }));
417
-
418
- if (typeof this.response != 'undefined' && typeof this.response$ == 'undefined') {
419
- throw new Error('Cannot have a response parameter without a request parameter');
420
- }
421
- }
422
- }, {
423
- key: "initState",
424
- value: function initState() {
425
- var _this3 = this;
426
-
427
- if (this.model != undefined) {
428
- if (this.model[INITIALIZE_ACTION] === undefined) {
429
- this.model[INITIALIZE_ACTION] = _defineProperty({}, this.stateSourceName, function (_, data) {
430
- return _objectSpread({}, _this3.addCalculated(data));
431
- });
432
- } else {
433
- Object.keys(this.model[INITIALIZE_ACTION]).forEach(function (name) {
434
- if (name !== _this3.stateSourceName) {
435
- console.warn("".concat(INITIALIZE_ACTION, " can only be used with the ").concat(_this3.stateSourceName, " source... disregarding ").concat(name));
436
- delete _this3.model[INITIALIZE_ACTION][name];
437
- }
438
- });
439
- }
440
- }
441
- }
442
- }, {
443
- key: "initModel$",
444
- value: function initModel$() {
445
- var _this4 = this;
446
-
447
- if (typeof this.model == 'undefined') {
448
- this.model$ = this.sourceNames.reduce(function (a, s) {
449
- a[s] = xs.never();
450
- return a;
451
- }, {});
452
- return;
453
- }
454
-
455
- var initial = {
456
- type: INITIALIZE_ACTION,
457
- data: this.initialState
458
- };
459
- var shimmed$ = this.initialState ? concat(xs.of(initial), this.action$).compose(delay(0)) : this.action$;
460
- var onState = this.makeOnAction(shimmed$, true, this.action$);
461
- var onNormal = this.makeOnAction(this.action$, false, this.action$);
462
- var modelEntries = Object.entries(this.model);
463
- var reducers = {};
464
- modelEntries.forEach(function (entry) {
465
- var _entry = _slicedToArray(entry, 2),
466
- action = _entry[0],
467
- sinks = _entry[1];
468
-
469
- if (typeof sinks === 'function') {
470
- sinks = _defineProperty({}, _this4.stateSourceName, sinks);
471
- }
472
-
473
- if (_typeof(sinks) !== 'object') {
474
- throw new Error("Entry for each action must be an object: ".concat(_this4.name, " ").concat(action));
475
- }
476
-
477
- var sinkEntries = Object.entries(sinks);
478
- sinkEntries.forEach(function (entry) {
479
- var _entry2 = _slicedToArray(entry, 2),
480
- sink = _entry2[0],
481
- reducer = _entry2[1];
482
-
483
- var isStateSink = sink == _this4.stateSourceName;
484
- var on = isStateSink ? onState : onNormal;
485
- var onned = on(action, reducer);
486
- var wrapped = onned.compose(_this4.log(function (data) {
487
- if (isStateSink) {
488
- return "State reducer added: <".concat(action, ">");
489
- } else {
490
- var extra = data && (data.type || data.command || data.name || data.key || Array.isArray(data) && 'Array' || data);
491
- return "Data sent to [".concat(sink, "]: <").concat(action, "> ").concat(extra);
492
- }
493
- }));
494
-
495
- if (Array.isArray(reducers[sink])) {
496
- reducers[sink].push(wrapped);
497
- } else {
498
- reducers[sink] = [wrapped];
499
- }
500
- });
501
- });
502
- var model$ = Object.entries(reducers).reduce(function (acc, entry) {
503
- var _entry3 = _slicedToArray(entry, 2),
504
- sink = _entry3[0],
505
- streams = _entry3[1];
506
-
507
- acc[sink] = xs.merge.apply(xs, [xs.never()].concat(_toConsumableArray(streams)));
508
- return acc;
509
- }, {});
510
- this.model$ = model$;
511
- }
512
- }, {
513
- key: "initSendResponse$",
514
- value: function initSendResponse$() {
515
- var _this5 = this;
516
-
517
- var responseType = _typeof(this.response);
518
-
519
- if (responseType != 'function' && responseType != 'undefined') {
520
- throw new Error('The response parameter must be a function');
521
- }
522
-
523
- if (responseType == 'undefined') {
524
- if (this.response$) {
525
- this.response$.subscribe({
526
- next: this.log(function (_ref12) {
527
- var _reqId = _ref12._reqId,
528
- _action = _ref12._action;
529
- return "Unhandled response for request: ".concat(_action, " ").concat(_reqId);
530
- })
531
- });
532
- }
533
-
534
- this.sendResponse$ = xs.never();
535
- return;
536
- }
537
-
538
- var selectable = {
539
- select: function select(actions) {
540
- if (typeof actions == 'undefined') return _this5.response$;
541
- if (!Array.isArray(actions)) actions = [actions];
542
- return _this5.response$.filter(function (_ref13) {
543
- var _action = _ref13._action;
544
- return actions.length > 0 ? _action === 'FUNCTION' || actions.includes(_action) : true;
545
- });
546
- }
547
- };
548
- var out = this.response(selectable);
549
-
550
- if (_typeof(out) != 'object') {
551
- throw new Error('The response function must return an object');
552
- }
553
-
554
- var entries = Object.entries(out);
555
- var out$ = entries.reduce(function (acc, _ref14) {
556
- var _ref15 = _slicedToArray(_ref14, 2),
557
- command = _ref15[0],
558
- response$ = _ref15[1];
559
-
560
- var mapped$ = response$.map(function (_ref16) {
561
- var _reqId = _ref16._reqId,
562
- _action = _ref16._action,
563
- data = _ref16.data;
564
-
565
- if (!_reqId) {
566
- throw new Error("No request id found for response for: ".concat(command));
567
- }
568
-
569
- return {
570
- _reqId: _reqId,
571
- _action: _action,
572
- command: command,
573
- data: data
574
- };
575
- });
576
- return [].concat(_toConsumableArray(acc), [mapped$]);
577
- }, []);
578
- this.sendResponse$ = xs.merge.apply(xs, _toConsumableArray(out$)).compose(this.log(function (_ref17) {
579
- var _reqId = _ref17._reqId,
580
- _action = _ref17._action;
581
- return "[".concat(_this5.requestSourceName, "] response sent for: <").concat(_action, ">");
582
- }));
583
- }
584
- }, {
585
- key: "initChildren$",
586
- value: function initChildren$() {
587
- var _this6 = this;
588
-
589
- var initial = this.sourceNames.reduce(function (acc, name) {
590
- if (name == _this6.DOMSourceName) {
591
- acc[name] = {};
592
- } else {
593
- acc[name] = [];
594
- }
595
-
596
- return acc;
597
- }, {});
598
- this.children$ = Object.entries(this.children).reduce(function (acc, _ref18) {
599
- var _ref19 = _slicedToArray(_ref18, 2),
600
- childName = _ref19[0],
601
- childFactory = _ref19[1];
602
-
603
- var child$ = childFactory(_this6.sources);
604
-
605
- _this6.sourceNames.forEach(function (source) {
606
- if (source == _this6.DOMSourceName) {
607
- acc[source][childName] = child$[source];
608
- } else {
609
- acc[source].push(child$[source]);
610
- }
611
- });
612
-
613
- return acc;
614
- }, initial);
615
- }
616
- }, {
617
- key: "initSubComponentSink$",
618
- value: function initSubComponentSink$() {
619
- var _this7 = this;
620
-
621
- var subComponentSink$ = xs.create({
622
- start: function start(listener) {
623
- _this7.newSubComponentSinks = listener.next.bind(listener);
624
- },
625
- stop: function stop(_) {}
626
- });
627
- subComponentSink$.subscribe({
628
- next: function next(_) {
629
- return _;
630
- }
631
- });
632
- this.subComponentSink$ = subComponentSink$.filter(function (sinks) {
633
- return Object.keys(sinks).length > 0;
634
- });
635
- }
636
- }, {
637
- key: "initVdom$",
638
- value: function initVdom$() {
639
- var _this8 = this;
640
-
641
- if (typeof this.view != 'function') {
642
- this.vdom$ = xs.of(null);
643
- return;
644
- }
645
-
646
- var state = this.sources[this.stateSourceName];
647
-
648
- var renderParams = _objectSpread({}, this.children$[this.DOMSourceName]);
649
-
650
- var enhancedState = state && state.isolateSource(state, {
651
- get: function get(state) {
652
- return _this8.addCalculated(state);
653
- }
654
- });
655
- var stateStream = enhancedState && enhancedState.stream || xs.never();
656
- renderParams.state = stateStream;
657
- renderParams[this.stateSourceName] = stateStream;
658
-
659
- if (this.sources.props$) {
660
- renderParams.props = this.sources.props$;
661
- }
662
-
663
- if (this.sources.children$) {
664
- renderParams.children = this.sources.children$;
665
- }
666
-
667
- var pulled = Object.entries(renderParams).reduce(function (acc, _ref20) {
668
- var _ref21 = _slicedToArray(_ref20, 2),
669
- name = _ref21[0],
670
- stream = _ref21[1];
671
-
672
- acc.names.push(name);
673
- acc.streams.push(stream);
674
- return acc;
675
- }, {
676
- names: [],
677
- streams: []
678
- });
679
- var merged = xs.combine.apply(xs, _toConsumableArray(pulled.streams));
680
- var throttled = merged.compose(debounce(5)).map(function (arr) {
681
- return pulled.names.reduce(function (acc, name, index) {
682
- acc[name] = arr[index];
683
- return acc;
684
- }, {});
685
- });
686
- var componentNames = Object.keys(this.components);
687
- var subComponentRenderedProxy$ = xs.create();
688
- var vDom$ = throttled.map(function (params) {
689
- return params;
690
- }).map(this.view).map(function (vDom) {
691
- return vDom || {
692
- sel: 'div',
693
- data: {},
694
- children: []
695
- };
696
- });
697
- var componentInstances$ = vDom$.fold(function (previousComponents, vDom) {
698
- var foundComponents = getComponents(vDom, componentNames);
699
- var entries = Object.entries(foundComponents);
700
- var rootEntry = {
701
- '::ROOT::': vDom
702
- };
703
-
704
- if (entries.length === 0) {
705
- return rootEntry;
706
- }
707
-
708
- var sinkArrsByType = {};
709
- var newComponents = entries.reduce(function (acc, _ref22) {
710
- var _ref23 = _slicedToArray(_ref22, 2),
711
- id = _ref23[0],
712
- el = _ref23[1];
713
-
714
- var componentName = el.sel;
715
- var data = el.data;
716
- var props = data.props || {};
717
- var children = el.children || [];
718
- var isCollection = data.isCollection || false;
719
- var isSwitchable = data.isSwitchable || false;
720
-
721
- if (previousComponents[id]) {
722
- var entry = previousComponents[id];
723
- acc[id] = entry;
724
- entry.props$.shamefullySendNext(props);
725
- entry.children$.shamefullySendNext(children);
726
- return acc;
727
- }
728
-
729
- var factory = componentName === 'sygnal-factory' ? props.sygnalFactory : _this8.components[componentName] || props.sygnalFactory;
730
-
731
- if (!factory && !isCollection && !isSwitchable) {
732
- if (componentName === 'sygnal-factory') throw new Error("Component not found on element with Capitalized selector and nameless function: JSX transpilation replaces selectors starting with upper case letters with functions in-scope with the same name, Sygnal cannot see the name of the resulting component.");
733
- throw new Error("Component not found: ".concat(componentName));
734
- }
735
-
736
- var props$ = xs.create().startWith(props);
737
- var children$ = xs.create().startWith(children);
738
- var stateSource = new StateSource(_this8.sources[_this8.stateSourceName].stream.startWith(_this8.currentState));
739
- var sink$;
740
- var preventStateUpdates = true;
741
-
742
- if (isCollection) {
743
- var _objectSpread3;
744
-
745
- var field, lense;
746
-
747
- var stateGetter = function stateGetter(state) {
748
- var arr = state[field];
749
- if (typeof arr === 'undefined') return;
750
-
751
- if (!Array.isArray(arr)) {
752
- var label = typeof data.props.of === 'string' ? data.props.of : 'components';
753
- console.warn("Collection of ".concat(label, " does not have a valid array in the 'for' property: expects either an array or a string of the name of an array property on the state"));
754
- return [];
755
- }
756
-
757
- return arr;
758
- };
759
-
760
- if (typeof props["for"] === 'undefined') {
761
- lense = {
762
- get: function get(state) {
763
- if (!Array.isArray(state)) {
764
- console.warn("Collection sub-component of ".concat(_this8.name, " has no 'for' attribute and the parent state is not an array: Provide a 'for' attribute with either an array or the name of a state property containing an array"));
765
- return [];
766
- }
767
-
768
- return state;
769
- },
770
- set: function set(oldState, newState) {
771
- return newState;
772
- }
773
- };
774
- preventStateUpdates = false;
775
- } else if (typeof props["for"] === 'string') {
776
- field = props["for"];
777
- lense = {
778
- get: stateGetter,
779
- set: function set(state, arr) {
780
- if (_this8.calculated && field in _this8.calculated) {
781
- console.warn("Collection sub-component of ".concat(_this8.name, " attempted to update state on a calculated field '").concat(field, "': Update ignored"));
782
- return state;
783
- }
784
-
785
- return _objectSpread(_objectSpread({}, state), {}, _defineProperty({}, field, arr));
786
- }
787
- };
788
- preventStateUpdates = false;
789
- } else {
790
- field = 'for';
791
- stateSource = new StateSource(props$.remember());
792
- lense = {
793
- get: stateGetter,
794
- set: function set(state, arr) {
795
- return state;
796
- }
797
- };
798
- }
799
-
800
- var sources = _objectSpread(_objectSpread({}, _this8.sources), {}, (_objectSpread3 = {}, _defineProperty(_objectSpread3, _this8.stateSourceName, stateSource), _defineProperty(_objectSpread3, "props$", props$), _defineProperty(_objectSpread3, "children$", children$), _objectSpread3));
801
-
802
- var _factory = typeof data.props.of === 'function' ? data.props.of : _this8.components[data.props.of];
803
-
804
- sink$ = collection(_factory, lense, {
805
- container: null
806
- })(sources);
807
-
808
- if (_typeof(sink$) !== 'object') {
809
- throw new Error('Invalid sinks returned from component factory of collection element');
810
- }
811
- } else if (isSwitchable) {
812
- var _objectSpread5;
813
-
814
- var stateField = data.props.state;
815
- var isolateSwitchable = false;
816
-
817
- var _lense;
818
-
819
- if (typeof stateField === 'string') {
820
- isolateSwitchable = true;
821
- _lense = {
822
- get: function get(state) {
823
- return state[stateField];
824
- },
825
- set: function set(oldState, newState) {
826
- if (_this8.calculated && stateField in _this8.calculated) {
827
- console.warn("Switchable sub-component of ".concat(_this8.name, " attempted to update state on a calculated field '").concat(stateField, "': Update ignored"));
828
- return oldState;
829
- }
830
-
831
- return _objectSpread(_objectSpread({}, oldState), {}, _defineProperty({}, stateField, newState));
832
- }
833
- };
834
- preventStateUpdates = false;
835
- } else if (typeof stateField === 'undefined') {
836
- isolateSwitchable = true;
837
- _lense = {
838
- get: function get(state) {
839
- return state;
840
- },
841
- set: function set(oldState, newState) {
842
- return newState;
843
- }
844
- };
845
- preventStateUpdates = false;
846
- } else if (_typeof(stateField) === 'object') {
847
- stateSource = new StateSource(props$.map(function (props) {
848
- return props.state;
849
- }));
850
- } else {
851
- throw new Error("Invalid state provided to collection sub-component of ".concat(_this8.name, ": Expecting string, object, or none, but found ").concat(_typeof(stateField)));
852
- }
853
-
854
- var switchableComponents = data.props.of;
855
-
856
- var _sources = _objectSpread(_objectSpread({}, _this8.sources), {}, (_objectSpread5 = {}, _defineProperty(_objectSpread5, _this8.stateSourceName, stateSource), _defineProperty(_objectSpread5, "props$", props$), _defineProperty(_objectSpread5, "children$", children$), _objectSpread5));
857
-
858
- if (isolateSwitchable) {
859
- sink$ = isolate(switchable(switchableComponents, props$.map(function (props) {
860
- return props.current;
861
- })), _defineProperty({}, _this8.stateSourceName, _lense))(_sources);
862
- } else {
863
- sink$ = switchable(switchableComponents, props$.map(function (props) {
864
- return props.current;
865
- }))(_sources);
866
- }
867
-
868
- if (_typeof(sink$) !== 'object') {
869
- throw new Error('Invalid sinks returned from component factory of switchable element');
870
- }
871
- } else {
872
- var stateProp = props.state,
873
- sygnalFactory = props.sygnalFactory,
874
- _id = props.id,
875
- sanitizedProps = _objectWithoutProperties(props, _excluded);
876
-
877
- if (typeof stateProp === 'undefined' && (_typeof(sanitizedProps) !== 'object' || Object.keys(sanitizedProps).length === 0)) {
878
- var _objectSpread6;
879
-
880
- var _sources2 = _objectSpread(_objectSpread({}, _this8.sources), {}, (_objectSpread6 = {}, _defineProperty(_objectSpread6, _this8.stateSourceName, stateSource), _defineProperty(_objectSpread6, "props$", xs.never().startWith(null)), _defineProperty(_objectSpread6, "children$", children$), _objectSpread6));
881
-
882
- sink$ = factory(_sources2);
883
- preventStateUpdates = false;
884
- } else {
885
- var _objectSpread7;
886
-
887
- var _lense2 = function _lense2(props) {
888
- var state = props.state;
889
- if (typeof state === 'undefined') return props;
890
- if (_typeof(state) !== 'object') return state;
891
-
892
- var copy = _objectSpread({}, props);
893
-
894
- delete copy.state;
895
- return _objectSpread(_objectSpread({}, copy), state);
896
- };
897
-
898
- stateSource = new StateSource(props$.map(_lense2));
899
-
900
- var _sources3 = _objectSpread(_objectSpread({}, _this8.sources), {}, (_objectSpread7 = {}, _defineProperty(_objectSpread7, _this8.stateSourceName, stateSource), _defineProperty(_objectSpread7, "props$", props$), _defineProperty(_objectSpread7, "children$", children$), _objectSpread7));
901
-
902
- sink$ = factory(_sources3);
903
- }
904
-
905
- if (_typeof(sink$) !== 'object') {
906
- var name = componentName === 'sygnal-factory' ? 'custom element' : componentName;
907
- throw new Error('Invalid sinks returned from component factory:', name);
908
- }
909
- }
910
-
911
- if (preventStateUpdates) {
912
- var originalStateSink = sink$[_this8.stateSourceName];
913
- sink$[_this8.stateSourceName] = originalStateSink.filter(function (state) {
914
- console.warn('State update attempt from component with inderect link to state: Components with state set through HTML properties/attributes cannot update application state directly');
915
- return false;
916
- });
917
- }
918
-
919
- var originalDOMSink = sink$[_this8.DOMSourceName].remember();
920
-
921
- var repeatChecker = function repeatChecker(a, b) {
922
- var aa = JSON.stringify(a);
923
- var bb = JSON.stringify(b);
924
- return aa === bb;
925
- };
926
-
927
- sink$[_this8.DOMSourceName] = stateSource.stream.compose(dropRepeats(repeatChecker)).map(function (state) {
928
- subComponentRenderedProxy$.shamefullySendNext(null);
929
- return originalDOMSink;
930
- }).compose(debounce(10)).flatten().remember();
931
- acc[id] = {
932
- sink$: sink$,
933
- props$: props$,
934
- children$: children$
935
- };
936
- Object.entries(sink$).map(function (_ref24) {
937
- var _ref25 = _slicedToArray(_ref24, 2),
938
- name = _ref25[0],
939
- stream = _ref25[1];
940
-
941
- sinkArrsByType[name] || (sinkArrsByType[name] = []);
942
- if (name !== _this8.DOMSourceName) sinkArrsByType[name].push(stream);
943
- });
944
- return acc;
945
- }, rootEntry);
946
- var mergedSinksByType = Object.entries(sinkArrsByType).reduce(function (acc, _ref26) {
947
- var _ref27 = _slicedToArray(_ref26, 2),
948
- name = _ref27[0],
949
- streamArr = _ref27[1];
950
-
951
- if (streamArr.length === 0) return acc;
952
- acc[name] = streamArr.length === 1 ? streamArr[0] : xs.merge.apply(xs, _toConsumableArray(streamArr));
953
- return acc;
954
- }, {});
955
-
956
- _this8.newSubComponentSinks(mergedSinksByType); // subComponentRenderedProxy$.shamefullySendNext(null)
957
-
958
-
959
- return newComponents;
960
- }, {});
961
- this.vdom$ = xs.combine(subComponentRenderedProxy$.startWith(null), componentInstances$).map(function (_ref28) {
962
- var _ref29 = _slicedToArray(_ref28, 2),
963
- _ = _ref29[0],
964
- components = _ref29[1];
965
-
966
- var root = components['::ROOT::'];
967
- var ids = [];
968
- var entries = Object.entries(components).filter(function (_ref30) {
969
- var _ref31 = _slicedToArray(_ref30, 1),
970
- id = _ref31[0];
971
-
972
- return id !== '::ROOT::';
973
- });
974
-
975
- if (entries.length === 0) {
976
- return xs.of(root);
977
- }
978
-
979
- var vdom$ = entries.map(function (_ref32) {
980
- var _ref33 = _slicedToArray(_ref32, 2),
981
- id = _ref33[0],
982
- val = _ref33[1];
983
-
984
- ids.push(id);
985
- return val.sink$[_this8.DOMSourceName].startWith(undefined);
986
- });
987
- if (vdom$.length === 0) return xs.of(root);
988
- return xs.combine.apply(xs, _toConsumableArray(vdom$)).compose(debounce(5)).map(function (vdoms) {
989
- var withIds = vdoms.reduce(function (acc, vdom, index) {
990
- acc[ids[index]] = vdom;
991
- return acc;
992
- }, {});
993
- var rootCopy = deepCopyVdom(root);
994
- var injected = injectComponents(rootCopy, withIds, componentNames);
995
- return injected;
996
- });
997
- }).flatten().filter(function (val) {
998
- return !!val;
999
- }).compose(debounce(5)).remember().compose(this.log('View Rendered'));
1000
- }
1001
- }, {
1002
- key: "initSinks",
1003
- value: function initSinks() {
1004
- var _this9 = this;
1005
-
1006
- this.sinks = this.sourceNames.reduce(function (acc, name) {
1007
- if (name == _this9.DOMSourceName) return acc;
1008
- var subComponentSink$ = _this9.subComponentSink$ ? _this9.subComponentSink$.map(function (sinks) {
1009
- return sinks[name];
1010
- }).filter(function (sink) {
1011
- return !!sink;
1012
- }).flatten() : xs.never();
1013
-
1014
- if (name === _this9.stateSourceName) {
1015
- acc[name] = xs.merge.apply(xs, [_this9.model$[name] || xs.never(), subComponentSink$, _this9.sources[_this9.stateSourceName].stream.filter(function (_) {
1016
- return false;
1017
- })].concat(_toConsumableArray(_this9.children$[name])));
1018
- } else {
1019
- acc[name] = xs.merge.apply(xs, [_this9.model$[name] || xs.never(), subComponentSink$].concat(_toConsumableArray(_this9.children$[name])));
1020
- }
1021
-
1022
- return acc;
1023
- }, {});
1024
- this.sinks[this.DOMSourceName] = this.vdom$;
1025
- this.sinks[this.requestSourceName] = xs.merge(this.sendResponse$, this.sinks[this.requestSourceName]);
1026
- }
1027
- }, {
1028
- key: "makeOnAction",
1029
- value: function makeOnAction(action$) {
1030
- var _this10 = this;
1031
-
1032
- var isStateSink = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1033
- var rootAction$ = arguments.length > 2 ? arguments[2] : undefined;
1034
- rootAction$ = rootAction$ || action$;
1035
- return function (name, reducer) {
1036
- var filtered$ = action$.filter(function (_ref34) {
1037
- var type = _ref34.type;
1038
- return type == name;
1039
- });
1040
- var returnStream$;
1041
-
1042
- if (typeof reducer === 'function') {
1043
- returnStream$ = filtered$.map(function (action) {
1044
- var next = function next(type, data) {
1045
- var _reqId = action._reqId || action.req && action.req.id;
1046
-
1047
- var _data = _reqId ? _typeof(data) == 'object' ? _objectSpread(_objectSpread({}, data), {}, {
1048
- _reqId: _reqId,
1049
- _action: name
1050
- }) : {
1051
- data: data,
1052
- _reqId: _reqId,
1053
- _action: name
1054
- } : data; // put the "next" action request at the end of the event loop so the "current" action completes first
1055
-
1056
-
1057
- setTimeout(function () {
1058
- // push the "next" action request into the action$ stream
1059
- rootAction$.shamefullySendNext({
1060
- type: type,
1061
- data: _data
1062
- });
1063
- }, 10);
1064
- };
1065
-
1066
- var data = action.data;
1067
- if (data && data.data && data._reqId) data = data.data;
1068
-
1069
- if (isStateSink) {
1070
- return function (state) {
1071
- var _state = _this10.isSubComponent ? _this10.currentState : state;
1072
-
1073
- var enhancedState = _this10.addCalculated(_state);
1074
-
1075
- var newState = reducer(enhancedState, data, next, action.req);
1076
- if (newState == ABORT) return _state;
1077
- return _this10.cleanupCalculated(newState);
1078
- };
1079
- } else {
1080
- var enhancedState = _this10.addCalculated(_this10.currentState);
1081
-
1082
- var reduced = reducer(enhancedState, data, next, action.req);
1083
-
1084
- var type = _typeof(reduced);
1085
-
1086
- var _reqId = action._reqId || action.req && action.req.id;
1087
-
1088
- if (['string', 'number', 'boolean', 'function'].includes(type)) return reduced;
1089
- if (type == 'object') return _objectSpread(_objectSpread({}, reduced), {}, {
1090
- _reqId: _reqId,
1091
- _action: name
1092
- });
1093
-
1094
- if (type == 'undefined') {
1095
- console.warn("'undefined' value sent to ".concat(name));
1096
- return reduced;
1097
- }
1098
-
1099
- throw new Error("Invalid reducer type for ".concat(name, " ").concat(type));
1100
- }
1101
- }).filter(function (result) {
1102
- return result != ABORT;
1103
- });
1104
- } else if (reducer === undefined || reducer === true) {
1105
- returnStream$ = filtered$.map(function (_ref35) {
1106
- var data = _ref35.data;
1107
- return data;
1108
- });
1109
- } else {
1110
- var value = reducer;
1111
- returnStream$ = filtered$.mapTo(value);
1112
- }
1113
-
1114
- return returnStream$;
1115
- };
1116
- }
1117
- }, {
1118
- key: "addCalculated",
1119
- value: function addCalculated(state) {
1120
- if (!this.calculated || _typeof(state) !== 'object') return state;
1121
- if (_typeof(this.calculated) !== 'object') throw new Error("'calculated' parameter must be an object mapping calculated state field named to functions");
1122
- var entries = Object.entries(this.calculated);
1123
- var calculated = entries.reduce(function (acc, _ref36) {
1124
- var _ref37 = _slicedToArray(_ref36, 2),
1125
- field = _ref37[0],
1126
- fn = _ref37[1];
1127
-
1128
- if (typeof fn !== 'function') throw new Error("Missing or invalid calculator function for calculated field '".concat(field));
1129
-
1130
- try {
1131
- acc[field] = fn(state);
1132
- } catch (e) {
1133
- console.warn("Calculated field '".concat(field, "' threw an error during calculation: ").concat(e.message));
1134
- }
1135
-
1136
- return acc;
1137
- }, {});
1138
- return _objectSpread(_objectSpread({}, state), calculated);
1139
- }
1140
- }, {
1141
- key: "cleanupCalculated",
1142
- value: function cleanupCalculated(state) {
1143
- var _this11 = this;
1144
-
1145
- if (this.storeCalculatedInState) return this.addCalculated(state);
1146
- if (!this.calculated || !state || _typeof(state) !== 'object') return state;
1147
- var keys = Object.keys(this.calculated);
1148
-
1149
- var copy = _objectSpread({}, state);
1150
-
1151
- keys.forEach(function (key) {
1152
- if (_this11.initialState && typeof _this11.initialState[key] !== 'undefined') {
1153
- copy[key] = _this11.initialState[key];
1154
- } else {
1155
- delete copy[key];
1156
- }
1157
- });
1158
- return copy;
1159
- }
1160
- }]);
1161
-
1162
- return Component;
1163
- }();
1164
- /**
1165
- * factory to create a logging function meant to be used inside of an xstream .compose()
1166
- *
1167
- * @param {String} context name of the component or file to be prepended to any messages
1168
- * @return {Function}
1169
- *
1170
- * returned function accepts either a `String` of `Function`
1171
- * `String` values will be logged to `console` as is
1172
- * `Function` values will be called with the current `stream` value and the result will be logged to `console`
1173
- * all output will be prepended with the `context` (ex. "[CONTEXT] My output")
1174
- * ONLY outputs if the global `DEBUG` variable is set to `true`
1175
- */
1176
-
1177
-
1178
- function makeLog(context) {
1179
- return function (msg) {
1180
- var fixedMsg = typeof msg === 'function' ? msg : function (_) {
1181
- return msg;
1182
- };
1183
- return function (stream) {
1184
- return stream.debug(function (msg) {
1185
- if (ENVIRONMENT.DEBUG == 'true' || ENVIRONMENT.DEBUG === true) {
1186
- console.log("[".concat(context, "] ").concat(fixedMsg(msg)));
1187
- }
1188
- });
1189
- };
1190
- };
1191
- }
1192
-
1193
- function getComponents(currentElement, componentNames) {
1194
- var _currentElement$data, _currentElement$data2, _currentElement$data3;
1195
-
1196
- var depth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
1197
- var index = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
1198
- if (!currentElement) return {};
1199
- if ((_currentElement$data = currentElement.data) !== null && _currentElement$data !== void 0 && _currentElement$data.componentsProcessed) return {};
1200
- if (depth === 0) currentElement.data.componentsProcessed = true;
1201
- var sel = currentElement.sel;
1202
- var isCollection = sel && sel.toLowerCase() === 'collection';
1203
- var isSwitchable = sel && sel.toLowerCase() === 'switchable';
1204
- var isComponent = sel && ['collection', 'switchable', 'sygnal-factory'].concat(_toConsumableArray(componentNames)).includes(currentElement.sel) || typeof ((_currentElement$data2 = currentElement.data) === null || _currentElement$data2 === void 0 ? void 0 : (_currentElement$data3 = _currentElement$data2.props) === null || _currentElement$data3 === void 0 ? void 0 : _currentElement$data3.sygnalFactory) === 'function';
1205
- var props = currentElement.data && currentElement.data.props || {};
1206
- var attrs = currentElement.data && currentElement.data.attrs || {};
1207
- var children = currentElement.children || [];
1208
- var found = {};
1209
-
1210
- if (isComponent) {
1211
- var id = getComponentIdFromElement(currentElement, depth, index);
1212
-
1213
- if (isCollection) {
1214
- var _currentElement$data4;
1215
-
1216
- if (!props.of) throw new Error("Collection element missing required 'component' property");
1217
- if (typeof props.of !== 'string' && typeof props.of !== 'function') throw new Error("Invalid 'component' property of collection element: found ".concat(_typeof(props.of), " requires string or component factory function"));
1218
- if (typeof props.of !== 'function' && !componentNames.includes(props.of)) throw new Error("Specified component for collection not found: ".concat(props.of));
1219
- if (typeof attrs["for"] !== 'undefined' && !(typeof attrs["for"] === 'string' || Array.isArray(attrs["for"]))) console.warn("No valid array found in the 'value' property of collection ".concat(typeof props.of === 'string' ? props.of : 'function component', ": no collection components will be created"));
1220
- currentElement.data.isCollection = true;
1221
- (_currentElement$data4 = currentElement.data).props || (_currentElement$data4.props = {});
1222
- currentElement.data.props["for"] = attrs["for"];
1223
- currentElement.data.attrs = undefined;
1224
- } else if (isSwitchable) {
1225
- if (!props.of) throw new Error("Switchable element missing required 'of' property");
1226
- if (_typeof(props.of) !== 'object') throw new Error("Invalid 'components' property of switchable element: found ".concat(_typeof(props.of), " requires object mapping names to component factories"));
1227
- var switchableComponents = Object.values(props.of);
1228
- if (!switchableComponents.every(function (comp) {
1229
- return typeof comp === 'function';
1230
- })) throw new Error("One or more components provided to switchable element is not a valid component factory");
1231
- if (!props.current || typeof props.current !== 'string' && typeof props.current !== 'function') throw new Error("Missing or invalid 'current' property for switchable element: found '".concat(_typeof(props.current), "' requires string or function"));
1232
- var switchableComponentNames = Object.keys(props.of);
1233
- if (!switchableComponentNames.includes(props.current)) throw new Error("Component '".concat(props.current, "' not found in switchable element"));
1234
- currentElement.data.isSwitchable = true;
1235
- } else {}
1236
-
1237
- found[id] = currentElement;
1238
- }
1239
-
1240
- if (children.length > 0) {
1241
- children.map(function (child, i) {
1242
- return getComponents(child, componentNames, depth + 1, i);
1243
- }).forEach(function (child) {
1244
- Object.entries(child).forEach(function (_ref38) {
1245
- var _ref39 = _slicedToArray(_ref38, 2),
1246
- id = _ref39[0],
1247
- el = _ref39[1];
1248
-
1249
- return found[id] = el;
1250
- });
1251
- });
1252
- }
1253
-
1254
- return found;
1255
- }
1256
-
1257
- function injectComponents(currentElement, components, componentNames) {
1258
- var _currentElement$data5, _currentElement$data6, _currentElement$data7, _currentElement$data8, _currentElement$data9;
1259
-
1260
- var depth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
1261
- var index = arguments.length > 4 ? arguments[4] : undefined;
1262
- if (!currentElement) return;
1263
- if ((_currentElement$data5 = currentElement.data) !== null && _currentElement$data5 !== void 0 && _currentElement$data5.componentsInjected) return currentElement;
1264
- if (depth === 0 && currentElement.data) currentElement.data.componentsInjected = true;
1265
- var sel = currentElement.sel || 'NO SELECTOR';
1266
- var isComponent = ['collection', 'switchable', 'sygnal-factory'].concat(_toConsumableArray(componentNames)).includes(sel) || typeof ((_currentElement$data6 = currentElement.data) === null || _currentElement$data6 === void 0 ? void 0 : (_currentElement$data7 = _currentElement$data6.props) === null || _currentElement$data7 === void 0 ? void 0 : _currentElement$data7.sygnalFactory) === 'function';
1267
- var isCollection = currentElement === null || currentElement === void 0 ? void 0 : (_currentElement$data8 = currentElement.data) === null || _currentElement$data8 === void 0 ? void 0 : _currentElement$data8.isCollection;
1268
- var isSwitchable = currentElement === null || currentElement === void 0 ? void 0 : (_currentElement$data9 = currentElement.data) === null || _currentElement$data9 === void 0 ? void 0 : _currentElement$data9.isSwitchable;
1269
- var props = currentElement.data && currentElement.data.props || {};
1270
- var children = currentElement.children || [];
1271
-
1272
- if (isComponent) {
1273
- var id = getComponentIdFromElement(currentElement, depth, index);
1274
- var _component = components[id];
1275
-
1276
- if (isCollection) {
1277
- currentElement.sel = 'div';
1278
- currentElement.children = Array.isArray(_component) ? _component : [_component];
1279
- return currentElement;
1280
- } else if (isSwitchable) {
1281
- return _component;
1282
- } else {
1283
- return _component;
1284
- }
1285
- } else if (children.length > 0) {
1286
- currentElement.children = children.map(function (child, i) {
1287
- return injectComponents(child, components, componentNames, depth + 1, i);
1288
- }).flat();
1289
- return currentElement;
1290
- } else {
1291
- return currentElement;
1292
- }
1293
- }
1294
-
1295
- var selMap = new Map();
1296
-
1297
- function getComponentIdFromElement(el, depth, index) {
1298
- var sel = el.sel;
1299
- var name = typeof sel === 'string' ? sel : 'functionComponent';
1300
- var base = selMap.get(sel);
1301
-
1302
- if (!base) {
1303
- var date = Date.now();
1304
- var rand = Math.floor(Math.random() * 10000);
1305
- base = "".concat(date, "-").concat(rand);
1306
- selMap.set(sel, base);
1307
- }
1308
-
1309
- var uid = "".concat(base, "-").concat(depth, "-").concat(index);
1310
- var props = el.data && el.data.props || {};
1311
- var id = props.id && JSON.stringify(props.id) || uid;
1312
- var fullId = "".concat(name, "::").concat(id);
1313
- return fullId;
1314
- }
1315
-
1316
- function deepCopyVdom(obj) {
1317
- if (typeof obj === 'undefined') return obj;
1318
- return _objectSpread(_objectSpread({}, obj), {}, {
1319
- children: Array.isArray(obj.children) ? obj.children.map(deepCopyVdom) : undefined,
1320
- data: obj.data && _objectSpread(_objectSpread({}, obj.data), {}, {
1321
- componentsInjected: false
1322
- })
1323
- });
1324
- }