rasti 1.1.3 → 2.0.0-alpha.1
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/README.md +24 -28
- package/dist/rasti.js +14 -4
- package/dist/rasti.min.js +1 -1
- package/es/Component.js +445 -0
- package/es/Emitter.js +29 -11
- package/es/Model.js +35 -26
- package/es/View.js +23 -39
- package/es/index.js +2 -1
- package/lib/Component.js +449 -0
- package/lib/Emitter.js +29 -11
- package/lib/Model.js +35 -26
- package/lib/View.js +23 -39
- package/lib/index.js +2 -0
- package/package.json +4 -2
- package/src/Component.js +434 -0
- package/src/Emitter.js +29 -11
- package/src/Model.js +35 -26
- package/src/View.js +23 -39
- package/src/index.js +2 -1
package/lib/Component.js
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
exports.__esModule = true;
|
|
4
|
+
exports["default"] = void 0;
|
|
5
|
+
var _View2 = _interopRequireDefault(require("./View"));
|
|
6
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
|
|
7
|
+
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
|
|
8
|
+
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
|
|
9
|
+
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
|
|
10
|
+
// This options keys will be extended on view instance.
|
|
11
|
+
var componentOptions = {
|
|
12
|
+
key: true,
|
|
13
|
+
state: true,
|
|
14
|
+
onCreate: true,
|
|
15
|
+
onChange: true,
|
|
16
|
+
onRender: true
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/*
|
|
20
|
+
* Helper function. Extract attributes from html tag
|
|
21
|
+
* @param text {string} html text
|
|
22
|
+
* @return {object} Object with keys / values representing attributes.
|
|
23
|
+
*/
|
|
24
|
+
var getAttributes = function getAttributes(text) {
|
|
25
|
+
var attributes = {};
|
|
26
|
+
var re = /([a-z]+)=?(\S+)?/gi;
|
|
27
|
+
var result;
|
|
28
|
+
while ((result = re.exec(text)) !== null) {
|
|
29
|
+
attributes[result[1]] = result[2] ? result[2].replace(/'|"/g, '') : true;
|
|
30
|
+
}
|
|
31
|
+
return attributes;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/*
|
|
35
|
+
* Helper function. If first arg is a placeholder for an expression, return the expression.
|
|
36
|
+
*/
|
|
37
|
+
var getExpression = function getExpression(placeholder, expressions) {
|
|
38
|
+
var match = placeholder.match(new RegExp(Component.EXPRESSION_PLACEHOLDER_TEMPLATE('(\\d+)')));
|
|
39
|
+
return match && match[1] ? expressions[match[1]] : placeholder;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/*
|
|
43
|
+
* Helper function. If expression is a function, call it with context and args.
|
|
44
|
+
*/
|
|
45
|
+
var evalExpression = function evalExpression(expression, context) {
|
|
46
|
+
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
|
|
47
|
+
args[_key - 2] = arguments[_key];
|
|
48
|
+
}
|
|
49
|
+
return typeof expression === 'function' ? expression.apply(context, args) : expression;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Components are a special kind of `View` that is designed to be easily composable,
|
|
54
|
+
* making it simple to add child views and build complex user interfaces.<br />
|
|
55
|
+
* Unlike views, which are render-agnostic, components have a specific set of rendering
|
|
56
|
+
* guidelines that allow for a more declarative development style.<br />
|
|
57
|
+
* Components are defined with the `create` static method, which takes a tagged template.
|
|
58
|
+
* @module
|
|
59
|
+
* @extends Rasti.View
|
|
60
|
+
* @param {object} options Object containing options. The following keys will be merged to `this`: model, state, key, onDestroy, onRender, onCreate, onChange.
|
|
61
|
+
* @property {string} key A unique key to identify the component. Used to recycle child components.
|
|
62
|
+
* @property {object} model A `Rasti.Model` or any emitter object containing data and business logic.
|
|
63
|
+
* @property {object} state A `Rasti.Model` or any emitter object containing data and business logic, to be used as internal state.
|
|
64
|
+
* @example
|
|
65
|
+
* import { Component, Model } from 'rasti';
|
|
66
|
+
* // Create Timer component.
|
|
67
|
+
* const Timer = Component.create`
|
|
68
|
+
* <div>
|
|
69
|
+
* Seconds: <span>${({ model }) => model.seconds}</span>
|
|
70
|
+
* </div>
|
|
71
|
+
* `;
|
|
72
|
+
* // Create model to store seconds.
|
|
73
|
+
* const model = new Model({ seconds: 0 });
|
|
74
|
+
* // Mount timer on body.
|
|
75
|
+
* Timer.mount({ model }, document.body);
|
|
76
|
+
* // Increment `model.seconds` every second.
|
|
77
|
+
* setInterval(() => model.seconds++, 1000);
|
|
78
|
+
*/
|
|
79
|
+
var Component = /*#__PURE__*/function (_View) {
|
|
80
|
+
_inheritsLoose(Component, _View);
|
|
81
|
+
function Component() {
|
|
82
|
+
var _this;
|
|
83
|
+
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
84
|
+
_this = _View.call(this, options) || this;
|
|
85
|
+
// Extend "this" with options, mapping componentOptions keys.
|
|
86
|
+
Object.keys(options).forEach(function (key) {
|
|
87
|
+
if (componentOptions[key]) _this[key] = options[key];
|
|
88
|
+
});
|
|
89
|
+
// Store options by default.
|
|
90
|
+
_this.options = options;
|
|
91
|
+
// Ensure id.
|
|
92
|
+
_this.id = _this.attributes.id ?
|
|
93
|
+
// If id is provided, evaluate it.
|
|
94
|
+
evalExpression(_this.attributes.id, _assertThisInitialized(_this), _assertThisInitialized(_this)) :
|
|
95
|
+
// Generate a unique id and set it as id attribute.
|
|
96
|
+
Component.ID_TEMPLATE(_this.uid);
|
|
97
|
+
// Bind onChange to this to be used as listener.
|
|
98
|
+
// Store bound version, so it can be removed on onDestroy method.
|
|
99
|
+
_this.onChange = _this.onChange.bind(_assertThisInitialized(_this));
|
|
100
|
+
// Listen to model changes and call onChange.
|
|
101
|
+
if (_this.model) _this.model.on('change', _this.onChange);
|
|
102
|
+
if (_this.state) _this.state.on('change', _this.onChange);
|
|
103
|
+
// Call life cycle method.
|
|
104
|
+
_this.onCreate.apply(_assertThisInitialized(_this), arguments);
|
|
105
|
+
return _this;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/*
|
|
109
|
+
* Override. We don't want to ensure an element on instantiation.
|
|
110
|
+
* We will provide it later.
|
|
111
|
+
*/
|
|
112
|
+
var _proto = Component.prototype;
|
|
113
|
+
_proto.ensureElement = function ensureElement() {
|
|
114
|
+
// If el is provided, delegate events.
|
|
115
|
+
if (this.el) this.delegateEvents();
|
|
116
|
+
};
|
|
117
|
+
_proto.findElement = function findElement(parent) {
|
|
118
|
+
return (parent || document).querySelector("#" + this.id);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/*
|
|
122
|
+
* Used internally on the render process. Attach the view to the dom element.
|
|
123
|
+
*/;
|
|
124
|
+
_proto.hydrate = function hydrate(parent) {
|
|
125
|
+
var _this2 = this;
|
|
126
|
+
this.el = this.findElement(parent);
|
|
127
|
+
this.delegateEvents();
|
|
128
|
+
this.children.forEach(function (child) {
|
|
129
|
+
return child.hydrate(_this2.el);
|
|
130
|
+
});
|
|
131
|
+
this.onRender.call(this);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/*
|
|
135
|
+
* Override. Add some custom logic to super `destroy` method.
|
|
136
|
+
*/;
|
|
137
|
+
_proto.destroy = function destroy(options) {
|
|
138
|
+
_View.prototype.destroy.call(this, options);
|
|
139
|
+
// Stop listening to `change`.
|
|
140
|
+
// Set destroyed flag to prevent a last render after destroyed. TODO: Review
|
|
141
|
+
if (this.model) this.model.off('change', this.onChange);
|
|
142
|
+
if (this.state) this.state.off('change', this.onChange);
|
|
143
|
+
this.destroyed = true;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Lifecycle method. Called when the view is created at the end of the constructor.
|
|
148
|
+
* @param options {object} The view options.
|
|
149
|
+
*/;
|
|
150
|
+
_proto.onCreate = function onCreate() {}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Lifecycle method. Called when model emits `change` event.
|
|
154
|
+
* By default calls render method.
|
|
155
|
+
* This method should be extended with custom logic.
|
|
156
|
+
* Maybe comparing new attributes with previous ones and calling
|
|
157
|
+
* render when needed. Or doing some dom transformation.
|
|
158
|
+
* @param model {Rasti.Model}
|
|
159
|
+
* @param key {string}
|
|
160
|
+
* @param value {any}
|
|
161
|
+
*/;
|
|
162
|
+
_proto.onChange = function onChange() {
|
|
163
|
+
this.render();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Lifecycle method. Called when the view is rendered.
|
|
168
|
+
*/;
|
|
169
|
+
_proto.onRender = function onRender() {}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Lifecycle method. Called when the view is destroyed.
|
|
173
|
+
*/;
|
|
174
|
+
_proto.onDestroy = function onDestroy() {}
|
|
175
|
+
|
|
176
|
+
/*
|
|
177
|
+
* Replace expressions.
|
|
178
|
+
*/;
|
|
179
|
+
_proto.replaceExpressions = function replaceExpressions(string, addChild) {
|
|
180
|
+
var _this3 = this;
|
|
181
|
+
return string.replace(new RegExp(Component.EXPRESSION_PLACEHOLDER_TEMPLATE('(\\d+)'), 'g'), function (match) {
|
|
182
|
+
var expression = getExpression(match, _this3.template.expressions);
|
|
183
|
+
// Eval expression. Pass view as argument.
|
|
184
|
+
var result = evalExpression(expression, _this3, _this3);
|
|
185
|
+
// Treat all expressions as arrays.
|
|
186
|
+
var results = result instanceof Array ? result : [result];
|
|
187
|
+
// Replace expression with the result of the evaluation.
|
|
188
|
+
return results.reduce(function (out, result) {
|
|
189
|
+
var parsed;
|
|
190
|
+
// If result is true, replace it with a placeholder.
|
|
191
|
+
if (result === true) parsed = Component.TRUE_PLACEHOLDER;
|
|
192
|
+
// If result is false, replace it with a placeholder.
|
|
193
|
+
else if (result === false) parsed = Component.FALSE_PLACEHOLDER;
|
|
194
|
+
// Replace null or undefined with empty string.
|
|
195
|
+
else if (result === null || typeof result === 'undefined') parsed = '';
|
|
196
|
+
// If result is a view, call addChild callback.
|
|
197
|
+
else if (result && typeof result.render === 'function') parsed = addChild(result);
|
|
198
|
+
// Return expression itself.
|
|
199
|
+
else parsed = result;
|
|
200
|
+
// Concatenate expressions.
|
|
201
|
+
return out + parsed;
|
|
202
|
+
}, '');
|
|
203
|
+
})
|
|
204
|
+
// Replace `attribute="true"` with `attribute`
|
|
205
|
+
.replace(new RegExp("([a-z]+)=[\"|']" + Component.TRUE_PLACEHOLDER + "[\"|']", 'g'), '$1')
|
|
206
|
+
// Replace `attribute="false"` with empty string.
|
|
207
|
+
.replace(new RegExp("([a-z]+)=[\"|']" + Component.FALSE_PLACEHOLDER + "[\"|']", 'g'), '')
|
|
208
|
+
// Replace rest of false expressions with empty string.
|
|
209
|
+
.replace(new RegExp(Component.FALSE_PLACEHOLDER, 'g'), '');
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/*
|
|
213
|
+
* Treat the whole view as a HTML string.
|
|
214
|
+
*/;
|
|
215
|
+
_proto.toString = function toString() {
|
|
216
|
+
var _this4 = this;
|
|
217
|
+
// Normally there won't be any children, but if there are, destroy them.
|
|
218
|
+
this.destroyChildren();
|
|
219
|
+
// Add id to template including root element (this.el) as part of it.
|
|
220
|
+
var tpl = this.attributes.id ? this.template.outer : this.template.outer.replace(/^<([a-z]+)/, "<$1 id=\"" + this.id + "\"");
|
|
221
|
+
// Replace expressions.
|
|
222
|
+
return this.replaceExpressions(tpl, function (component) {
|
|
223
|
+
// Add child component.
|
|
224
|
+
return _this4.addChild(component);
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/*
|
|
229
|
+
* View render method.
|
|
230
|
+
*/;
|
|
231
|
+
_proto.render = function render() {
|
|
232
|
+
var _this5 = this;
|
|
233
|
+
// Prevent a last re render if view is already destroyed.
|
|
234
|
+
if (this.destroyed) return this;
|
|
235
|
+
// If "this.el" is not present,
|
|
236
|
+
// create a new element according "this.tag"
|
|
237
|
+
// and "this.attributes".
|
|
238
|
+
if (!this.el) {
|
|
239
|
+
this.el = this.createElement(this.tag);
|
|
240
|
+
this.delegateEvents();
|
|
241
|
+
}
|
|
242
|
+
// Set `this.el` attributes.
|
|
243
|
+
Object.keys(this.attributes).forEach(function (key) {
|
|
244
|
+
// Omit changing id.
|
|
245
|
+
if (key === 'id') return;
|
|
246
|
+
// Evaluate attribute value.
|
|
247
|
+
var value = evalExpression(_this5.attributes[key], _this5, _this5);
|
|
248
|
+
// Transform bool attribute values
|
|
249
|
+
if (value === false) {
|
|
250
|
+
// Remove false attributes.
|
|
251
|
+
_this5.el.removeAttribute(key);
|
|
252
|
+
} else {
|
|
253
|
+
if (value === true) value = '';
|
|
254
|
+
_this5.el.setAttribute(key, value);
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
// Check for `template.inner`.
|
|
259
|
+
// Root element may be a self enclosed tag element without innerHTML.
|
|
260
|
+
if (this.template.inner) {
|
|
261
|
+
var previousChildren = this.children;
|
|
262
|
+
this.children = [];
|
|
263
|
+
var nextChildren = [];
|
|
264
|
+
var recycledChildren = [];
|
|
265
|
+
|
|
266
|
+
// Replace expressions.
|
|
267
|
+
// Set html text inside `this.el`. Make it part of the dom.
|
|
268
|
+
this.el.innerHTML = this.replaceExpressions(this.template.inner, function (component) {
|
|
269
|
+
var out = component;
|
|
270
|
+
// Check if child already exists.
|
|
271
|
+
var found = component.key && previousChildren.find(function (previousChild) {
|
|
272
|
+
return previousChild.key === component.key;
|
|
273
|
+
});
|
|
274
|
+
if (found) {
|
|
275
|
+
// If child already exists, replace it html by its root element.
|
|
276
|
+
out = "<" + found.tag + " id=\"" + found.id + "\"></" + found.tag + ">";
|
|
277
|
+
// Add child to recycled children.
|
|
278
|
+
recycledChildren.push(found);
|
|
279
|
+
// Destroy new child component. Use recycled one instead.
|
|
280
|
+
component.destroy();
|
|
281
|
+
} else {
|
|
282
|
+
// Not found. Add new child component.
|
|
283
|
+
nextChildren.push(component);
|
|
284
|
+
}
|
|
285
|
+
// Component html.
|
|
286
|
+
return out;
|
|
287
|
+
});
|
|
288
|
+
// Add new children. Hydrate them.
|
|
289
|
+
nextChildren.forEach(function (nextChild) {
|
|
290
|
+
_this5.addChild(nextChild).hydrate(_this5.el);
|
|
291
|
+
});
|
|
292
|
+
// Replace children root elements with recycled components.
|
|
293
|
+
recycledChildren.forEach(function (recycledChild) {
|
|
294
|
+
_this5.el.replaceChild(_this5.addChild(recycledChild).el, recycledChild.findElement(_this5.el));
|
|
295
|
+
});
|
|
296
|
+
// Destroy unused children.
|
|
297
|
+
previousChildren.forEach(function (previousChild) {
|
|
298
|
+
var found = recycledChildren.indexOf(previousChild) > -1;
|
|
299
|
+
if (!found) previousChild.destroy();
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
// Call onRender lifecycle method.
|
|
303
|
+
this.onRender.call(this);
|
|
304
|
+
// Return this for chaining.
|
|
305
|
+
return this;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Helper method used to extend a `Component`, creating a subclass.
|
|
310
|
+
* @static
|
|
311
|
+
* @param {object} object Object containing methods to be added to the new `Component` subclass. Also can be a function that receives the parent prototype and returns an object.
|
|
312
|
+
*/;
|
|
313
|
+
Component.extend = function extend(object) {
|
|
314
|
+
var Current = this;
|
|
315
|
+
var Extended = /*#__PURE__*/function (_Current) {
|
|
316
|
+
_inheritsLoose(Extended, _Current);
|
|
317
|
+
function Extended() {
|
|
318
|
+
return _Current.apply(this, arguments) || this;
|
|
319
|
+
}
|
|
320
|
+
return Extended;
|
|
321
|
+
}(Current);
|
|
322
|
+
Object.assign(Extended.prototype, typeof object === 'function' ? object(Current.prototype) : object);
|
|
323
|
+
return Extended;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Mount the component into the dom.
|
|
328
|
+
* It instantiate the Component view using options,
|
|
329
|
+
* appends its element into the DOM (if `el` is provided).
|
|
330
|
+
* And returns the view instance.
|
|
331
|
+
* @static
|
|
332
|
+
* @param {object} options The view options.
|
|
333
|
+
* @param {node} el Dom element to append the view element.
|
|
334
|
+
* @param {boolean} hydrate If true, the view will use existing html.
|
|
335
|
+
* @return {Rasti.Component}
|
|
336
|
+
*/;
|
|
337
|
+
Component.mount = function mount() {
|
|
338
|
+
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
339
|
+
var el = arguments.length > 1 ? arguments[1] : undefined;
|
|
340
|
+
var hydrate = arguments.length > 2 ? arguments[2] : undefined;
|
|
341
|
+
// Instantiate view.
|
|
342
|
+
var view = new this(options);
|
|
343
|
+
|
|
344
|
+
// If `el` is passed, mount component.
|
|
345
|
+
if (el) {
|
|
346
|
+
if (hydrate) {
|
|
347
|
+
view.toString();
|
|
348
|
+
} else {
|
|
349
|
+
var fragment = document.createElement('template');
|
|
350
|
+
// Add html text into element inner html.
|
|
351
|
+
fragment.innerHTML = view;
|
|
352
|
+
// Add to dom.
|
|
353
|
+
el.appendChild(fragment.content);
|
|
354
|
+
}
|
|
355
|
+
view.hydrate(el);
|
|
356
|
+
}
|
|
357
|
+
return view;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Takes a tagged template containing an HTML string,
|
|
361
|
+
* and returns a new `Component` class.
|
|
362
|
+
* - The template outer tag and attributes will be used to create the view's root element.
|
|
363
|
+
* - Boolean attributes should be passed in the form of `attribute="${() => true}"`.
|
|
364
|
+
* - Event handlers should be passed, at the root element, in the form of `onEventName=${{'selector' : listener }}`. Where `selector` is a css selector. The event will be delegated to the view's root element.
|
|
365
|
+
* - The template inner HTML will be used as the view's template.
|
|
366
|
+
* - Template interpolations that are functions will be evaluated on the render process. Receiving the view instance as argument. And being bound to it.
|
|
367
|
+
* - If the function returns `null`, `undefined`, `false` or empty string, the interpolation won't render any content.
|
|
368
|
+
* - If the function returns a component instance, it will be added as a child component.
|
|
369
|
+
* - If the function returns an array, each item will be evaluated as above.
|
|
370
|
+
* @static
|
|
371
|
+
* @param {string} HTML template for the component.
|
|
372
|
+
* @return {Rasti.Component}
|
|
373
|
+
*/;
|
|
374
|
+
Component.create = function create(strings) {
|
|
375
|
+
for (var _len2 = arguments.length, expressions = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
|
|
376
|
+
expressions[_key2 - 1] = arguments[_key2];
|
|
377
|
+
}
|
|
378
|
+
var parts = [];
|
|
379
|
+
// Replace functions and objects interpolations with `{number}`.
|
|
380
|
+
// Where `number` is the index on expressions array.
|
|
381
|
+
strings.forEach(function (string, i) {
|
|
382
|
+
// Add string part.
|
|
383
|
+
parts.push(string);
|
|
384
|
+
// Add expression placeholder for later or expression eval.
|
|
385
|
+
if (expressions[i]) {
|
|
386
|
+
parts.push(typeof expressions[i] === 'function' || typeof expressions[i] === 'object' ? Component.EXPRESSION_PLACEHOLDER_TEMPLATE(i) : expressions[i]);
|
|
387
|
+
}
|
|
388
|
+
});
|
|
389
|
+
// Create output text for main template.
|
|
390
|
+
var main = parts.join('').trim().replace(/\n/g, '');
|
|
391
|
+
// Extract outer tag, attributes and inner html.
|
|
392
|
+
var result = main.match(/^<([a-z]+)(.*?)>(.*)<\/\1>$/) || main.match(/^<([a-z]+)(.*?)\/>$/);
|
|
393
|
+
// Remove events listeners.
|
|
394
|
+
var string = main.replace(/on([A-Z]{1}[a-z]+)+=[^>\s]+/g, '');
|
|
395
|
+
// Parse attributes from html text into an object.
|
|
396
|
+
var attributes = getAttributes(result[2]);
|
|
397
|
+
// Events to be delegated.
|
|
398
|
+
var events = {};
|
|
399
|
+
// Filter events. To generate events object.
|
|
400
|
+
// Generate attributes object, replace placeholders with expressions.
|
|
401
|
+
attributes = Object.keys(attributes).reduce(function (out, key) {
|
|
402
|
+
// Is Event?
|
|
403
|
+
var matchKey = key.match(/on(([A-Z]{1}[a-z]+)+)/);
|
|
404
|
+
// Is placeholder for function or object?
|
|
405
|
+
// Get expression or value.
|
|
406
|
+
var value = getExpression(attributes[key], expressions);
|
|
407
|
+
// Is event handler. Add to events object.
|
|
408
|
+
if (matchKey && matchKey[1]) {
|
|
409
|
+
var eventType = matchKey[1].toLowerCase();
|
|
410
|
+
Object.keys(value).forEach(function (selector) {
|
|
411
|
+
return events["" + eventType + (selector === '&' ? '' : " " + selector)] = value[selector];
|
|
412
|
+
});
|
|
413
|
+
return out;
|
|
414
|
+
}
|
|
415
|
+
// Is attribute. Add to attributes object.
|
|
416
|
+
out[key] = value;
|
|
417
|
+
return out;
|
|
418
|
+
}, {});
|
|
419
|
+
var Current = this;
|
|
420
|
+
// Create subclass for this component.
|
|
421
|
+
return Current.extend({
|
|
422
|
+
// Set events.
|
|
423
|
+
events: events,
|
|
424
|
+
// Set attributes.
|
|
425
|
+
attributes: attributes,
|
|
426
|
+
// Set template data.
|
|
427
|
+
template: {
|
|
428
|
+
// Template including root element (this.el) as part of the template.
|
|
429
|
+
outer: string,
|
|
430
|
+
// Template for innerHTML of root element.
|
|
431
|
+
inner: result[3],
|
|
432
|
+
// Template expressions.
|
|
433
|
+
expressions: expressions
|
|
434
|
+
},
|
|
435
|
+
// Set root element tag.
|
|
436
|
+
tag: result[1]
|
|
437
|
+
});
|
|
438
|
+
};
|
|
439
|
+
return Component;
|
|
440
|
+
}(_View2["default"]);
|
|
441
|
+
exports["default"] = Component;
|
|
442
|
+
Component.ID_TEMPLATE = function (uid) {
|
|
443
|
+
return "rasti-component-" + uid;
|
|
444
|
+
};
|
|
445
|
+
Component.EXPRESSION_PLACEHOLDER_TEMPLATE = function (idx) {
|
|
446
|
+
return "__RASTI_EXPRESSION{" + idx + "}";
|
|
447
|
+
};
|
|
448
|
+
Component.TRUE_PLACEHOLDER = '__RASTI_TRUE';
|
|
449
|
+
Component.FALSE_PLACEHOLDER = '__RASTI_FALSE';
|
package/lib/Emitter.js
CHANGED
|
@@ -3,23 +3,41 @@
|
|
|
3
3
|
exports.__esModule = true;
|
|
4
4
|
exports["default"] = void 0;
|
|
5
5
|
/**
|
|
6
|
-
* Emitter is a class that
|
|
7
|
-
*
|
|
6
|
+
* `Emitter` is a class that provides an easy way to implement the observer pattern
|
|
7
|
+
* in your applications.<br />
|
|
8
|
+
* It can be extended to create new classes that have the ability to emit and bind custom named events.<br />
|
|
9
|
+
* Emitter is used by `Model` and `View` classes, which inherit from it to implement
|
|
10
|
+
* event-driven functionality.
|
|
11
|
+
*
|
|
8
12
|
* @module
|
|
9
13
|
* @example
|
|
10
14
|
* import { Emitter } from 'rasti';
|
|
11
|
-
* //
|
|
12
|
-
* class
|
|
15
|
+
* // Custom cart
|
|
16
|
+
* class ShoppingCart extends Emitter {
|
|
13
17
|
* constructor() {
|
|
14
|
-
* super()
|
|
15
|
-
*
|
|
16
|
-
*
|
|
18
|
+
* super();
|
|
19
|
+
* this.items = [];
|
|
20
|
+
* }
|
|
21
|
+
*
|
|
22
|
+
* addItem(item) {
|
|
23
|
+
* this.items.push(item);
|
|
24
|
+
* // Emit a custom event called `itemAdded`.
|
|
25
|
+
* // Pass the added item as an argument to the event listener.
|
|
26
|
+
* this.emit('itemAdded', item);
|
|
17
27
|
* }
|
|
18
28
|
* }
|
|
19
|
-
* //
|
|
20
|
-
* const
|
|
21
|
-
* //
|
|
22
|
-
*
|
|
29
|
+
* // Create an instance of ShoppingCart and Logger
|
|
30
|
+
* const cart = new ShoppingCart();
|
|
31
|
+
* // Listen to the `itemAdded` event and log the added item using the logger.
|
|
32
|
+
* cart.on('itemAdded', (item) => {
|
|
33
|
+
* console.log(`Item added to cart: ${item.name} - Price: $${item.price}`);
|
|
34
|
+
* });
|
|
35
|
+
* // Simulate adding items to the cart
|
|
36
|
+
* const item1 = { name : 'Smartphone', price : 1000 };
|
|
37
|
+
* const item2 = { name : 'Headphones', price : 150 };
|
|
38
|
+
*
|
|
39
|
+
* cart.addItem(item1); // Output: "Item added to cart: Smartphone - Price: $1000"
|
|
40
|
+
* cart.addItem(item2); // Output: "Item added to cart: Headphones - Price: $150"
|
|
23
41
|
*/
|
|
24
42
|
var Emitter = /*#__PURE__*/function () {
|
|
25
43
|
function Emitter() {}
|
package/lib/Model.js
CHANGED
|
@@ -11,37 +11,46 @@ function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Objec
|
|
|
11
11
|
* - Orchestrates data and business logic.
|
|
12
12
|
* - Emits events when data changes.
|
|
13
13
|
*
|
|
14
|
-
* A Model manages an internal table of data attributes
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* And a setter, which sets the model property in `this.attributes` and emits `change` and `change:attribute` events.
|
|
14
|
+
* A `Model` manages an internal table of data attributes and triggers change events when any of its data is modified.<br />
|
|
15
|
+
* Models may handle syncing data with a persistence layer. To design your models, create atomic, reusable objects
|
|
16
|
+
* that contain all the necessary functions for manipulating their specific data.<br />
|
|
17
|
+
* Models should be easily passed throughout your app and used anywhere the corresponding data is needed.<br />
|
|
18
|
+
* Rasti models stores its attributes in `this.attributes`, which is extended from `this.defaults` and the
|
|
19
|
+
* constructor `attrs` parameter. For every attribute, a getter is generated to retrieve the model property
|
|
20
|
+
* from `this.attributes`, and a setter is created to set the model property in `this.attributes` and emit `change`
|
|
21
|
+
* and `change:attribute` events.
|
|
23
22
|
* @module
|
|
23
|
+
* @extends Rasti.Emitter
|
|
24
24
|
* @param {object} attrs Object containing model attributes to extend `this.attributes`. Getters and setters are generated for `this.attributtes`, in order to emit `change` events.
|
|
25
25
|
* @example
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* //
|
|
31
|
-
*
|
|
26
|
+
* import { Model } from 'rasti';
|
|
27
|
+
* // Product model
|
|
28
|
+
* class ProductModel extends Model {
|
|
29
|
+
* preinitialize() {
|
|
30
|
+
* // The Product model has `name` and `price` default attributes.
|
|
31
|
+
* // `defaults` will extend `this.attributes`.
|
|
32
|
+
* // Getters and setters are generated for `this.attributes`,
|
|
33
|
+
* // in order to emit `change` events.
|
|
34
|
+
* this.defaults = {
|
|
35
|
+
* name: '',
|
|
36
|
+
* price: 0
|
|
37
|
+
* };
|
|
38
|
+
* }
|
|
39
|
+
*
|
|
40
|
+
* setDiscount(discountPercentage) {
|
|
41
|
+
* // Apply a discount to the price property.
|
|
42
|
+
* // This will call a setter that will update `price` in `this.attributes`,
|
|
43
|
+
* // and emit `change` and `change:price` events.
|
|
44
|
+
* const discount = this.price * (discountPercentage / 100);
|
|
45
|
+
* this.price -= discount;
|
|
32
46
|
* }
|
|
33
47
|
* }
|
|
34
|
-
* //
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* const todo = new TodoModel({ title : 'Learn Rasti' });
|
|
41
|
-
* // Listen to `change:completed` event.
|
|
42
|
-
* todo.on('change:completed', () => console.log('Completed:', todo.completed));
|
|
43
|
-
* // Complete todo.
|
|
44
|
-
* todo.toggle(); // Completed: true
|
|
48
|
+
* // Create a product instance with a name and price.
|
|
49
|
+
* const product = new ProductModel({ name: 'Smartphone', price: 1000 });
|
|
50
|
+
* // Listen to the `change:price` event.
|
|
51
|
+
* product.on('change:price', () => console.log('New Price:', product.price));
|
|
52
|
+
* // Apply a 10% discount to the product.
|
|
53
|
+
* product.setDiscount(10); // Output: "New Price: 900"
|
|
45
54
|
*/
|
|
46
55
|
var Model = /*#__PURE__*/function (_Emitter) {
|
|
47
56
|
_inheritsLoose(Model, _Emitter);
|
package/lib/View.js
CHANGED
|
@@ -23,13 +23,15 @@ var viewOptions = {
|
|
|
23
23
|
* - Handles user input and interactivity.
|
|
24
24
|
* - Sends captured input to the model.
|
|
25
25
|
*
|
|
26
|
-
* A View is an atomic
|
|
27
|
-
*
|
|
28
|
-
* Models must be unaware of views.
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
26
|
+
* A `View` is an atomic unit of the user interface that can render the data from a specific model or multiple models.
|
|
27
|
+
* However, views can also be independent and have no associated data.<br />
|
|
28
|
+
* Models must be unaware of views. Views, on the other hand, may render model data and listen to the change events
|
|
29
|
+
* emitted by the models to re-render themselves based on changes.<br />
|
|
30
|
+
* Each `View` has a root element, `this.el`, which is used for event delegation.<br />
|
|
31
|
+
* All element lookups are scoped to this element, and any rendering or DOM manipulations should be done inside it.
|
|
32
|
+
* If `this.el` is not present, an element will be created using `this.tag` (defaulting to div) and `this.attributes`.
|
|
32
33
|
* @module
|
|
34
|
+
* @extends Rasti.Emitter
|
|
33
35
|
* @param {object} options Object containing options. The following keys will be merged to `this`: el, tag, attributes, events, model, template, onDestroy.
|
|
34
36
|
* @property {node} el Every view has a root element, `this.el`. If not present it will be created.
|
|
35
37
|
* @property {string} tag If `this.el` is not present, an element will be created using `this.tag`. Default is `div`.
|
|
@@ -38,43 +40,25 @@ var viewOptions = {
|
|
|
38
40
|
* @property {object} model A `Rasti.Model` or any object containing data and business logic.
|
|
39
41
|
* @property {function} template A function that receives data and returns a markup string (html for example).
|
|
40
42
|
* @example
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
+
* import { View } from 'rasti';
|
|
44
|
+
*
|
|
45
|
+
* class Timer extends View {
|
|
43
46
|
* constructor(options) {
|
|
44
47
|
* super(options);
|
|
45
|
-
* //
|
|
46
|
-
* this.
|
|
47
|
-
* // Listen to model
|
|
48
|
-
* this.model.on('change:
|
|
48
|
+
* // Create model to store internal state. Set `seconds` attribute into 0.
|
|
49
|
+
* this.model = new Model({ seconds : 0 });
|
|
50
|
+
* // Listen to changes in model `seconds` attribute and re render.
|
|
51
|
+
* this.model.on('change:seconds', this.render.bind(this));
|
|
52
|
+
* // Increment model `seconds` attribute every 1000 milliseconds.
|
|
53
|
+
* this.interval = setInterval(() => this.model.seconds++, 1000);
|
|
49
54
|
* }
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
* }
|
|
54
|
-
* // Listener method. Called when button is clicked.
|
|
55
|
-
* onClickIncrement() {
|
|
56
|
-
* // Increment count on model.
|
|
57
|
-
* this.model.count++;
|
|
55
|
+
*
|
|
56
|
+
* template(model) {
|
|
57
|
+
* return `Seconds: <span>${model.seconds}</span>`;
|
|
58
58
|
* }
|
|
59
59
|
* }
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
* // Call `onClickIncrement` when button is clicked.
|
|
63
|
-
* events : {
|
|
64
|
-
* 'click button' : 'onClickIncrement'
|
|
65
|
-
* },
|
|
66
|
-
* // View's template.
|
|
67
|
-
* template : (model) => `
|
|
68
|
-
* <div>The count is: ${model.count}</div>
|
|
69
|
-
* <button>Increment</button>
|
|
70
|
-
* `
|
|
71
|
-
* });
|
|
72
|
-
* // Model.
|
|
73
|
-
* const model = new Model({ count : 0 });
|
|
74
|
-
* // Instantiate CounterView.
|
|
75
|
-
* const counterView = new CounterView({ model });
|
|
76
|
-
* // Add to DOM.
|
|
77
|
-
* document.body.appendChild(counterView.render().el);
|
|
60
|
+
* // Render view and append view's element into body.
|
|
61
|
+
* document.body.appendChild(new Timer().render().el);
|
|
78
62
|
*/
|
|
79
63
|
var View = /*#__PURE__*/function (_Emitter) {
|
|
80
64
|
_inheritsLoose(View, _Emitter);
|
|
@@ -147,7 +131,7 @@ var View = /*#__PURE__*/function (_Emitter) {
|
|
|
147
131
|
// Remove `this.el` if "options.remove" is true.
|
|
148
132
|
if (remove) this.removeElement();
|
|
149
133
|
// Call onDestroy lifecycle method
|
|
150
|
-
this.onDestroy();
|
|
134
|
+
this.onDestroy.apply(this, arguments);
|
|
151
135
|
}
|
|
152
136
|
|
|
153
137
|
/**
|