aboutsummaryrefslogtreecommitdiff
path: root/node_modules/montage/core/core.js
blob: 9109b772cd049c97dcd52a284bcb43fdd0fafdd8 (plain)
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
/* <copyright>
 This file contains proprietary software owned by Motorola Mobility, Inc.<br/>
 No rights, expressed or implied, whatsoever to this software are provided by Motorola Mobility, Inc. hereunder.<br/>
 (c) Copyright 2011 Motorola Mobility, Inc.  All Rights Reserved.
 </copyright> */
/**
 @module montage/core/core
 @requires montage/core/shim
 @requires montage/core/uuid
 @requires montage/core/event/binding
 @requires montage/core/event/event-manager
 */
require("core/shim/object");
require("core/shim/array");
require("core/extras/object");
require("core/extras/array");
require("core/extras/string");

var ATTRIBUTE_PROPERTIES = "AttributeProperties",
    UNDERSCORE = "_",
    PROTO = "__proto__",
    VALUE = "value",
    ENUMERABLE = "enumerable",
    DISTINCT = "distinct",
    SERIALIZABLE = "serializable",
    MODIFY = "modify";

/**
 @private
 */
var Array_prototype = Array.prototype;

/**
 @private
 */
var Object_prototype = Object.prototype;

/**
 @class module:montage/core/core.Montage
 */
var Montage = exports.Montage = {};

/**
     Creates a new Montage object.
     @function module:montage/core/core.Montage.create
     @param {Object} aPrototype The prototype object to create the new object from. If not specified, the prototype is the Montage prototype.
     @param {Object} [propertyDescriptor] An object that contains the initial properties and values for the new object.
     @returns The new object
     @example
     <caption>Creating a "empty" Montage object, using Montage as the prototype</caption>
     var alpha = Montage.create();
     @example
     <caption>Creating a new Montage component with a property descriptor object.</caption>
     var Button = Montage.create(Component , {
        state: {
            value: null
        }
     });
     */
Object.defineProperty(Montage, "create", {
    configurable: true,
    value: function(aPrototype, propertyDescriptor) {
        if (!propertyDescriptor) {

            var newObject = Object.create(typeof aPrototype === "undefined" ? this : aPrototype);

            if (typeof newObject.didCreate === "function") {
                newObject.didCreate();
            }

            return newObject;
        } else {
            var result = Object.create(aPrototype);
            Montage.defineProperties(result, propertyDescriptor);
            return result;
        }
    }
});

var extendedPropertyAttributes = [SERIALIZABLE];

// Extended property attributes, the property name format is "_" + attributeName + "AttributeProperties"
/**
@member external:Object#extendedPropertyAttributes
*/
extendedPropertyAttributes.forEach(function(name) {
    Object.defineProperty(Object.prototype, UNDERSCORE + name + ATTRIBUTE_PROPERTIES, {
        enumerable: false,
        configurable: false,
        writable: false,
        value: {}
    });
});

/**
     Defines a property on a Montage object.
     @function module:montage/core/core.Montage.defineProperty
     @param {Object} obj The object on which to define the property.
     @param {String} prop The name of the property to define, or modify.
     @param {Object} descriptor A descriptor object that defines the properties being defined or modified.
     @example
     Montage.defineProperty(Object.prototype, "_eventListenerDescriptors", {
     enumerable: false,
     serializable: true,
     value: null,
     writable: true
     });
     */
Object.defineProperty(Montage, "defineProperty", {

    value: function(obj, prop, descriptor) {

        var dependencies = descriptor.dependencies,
            isValueDescriptor = (VALUE in descriptor);

        if (DISTINCT in descriptor && !isValueDescriptor) {
            throw ("Cannot use distinct attribute on non-value property '" + prop + "'");
        }


        //reset defaults appropriately for framework.
        if (PROTO in descriptor) {
            descriptor.__proto__ = (isValueDescriptor ? (typeof descriptor.value === "function" ? _defaultFunctionValueProperty : _defaultObjectValueProperty) : _defaultAccessorProperty);
        } else {
            var defaults;
            if (isValueDescriptor) {
                if (typeof descriptor.value === "function") {
                    defaults = _defaultFunctionValueProperty;
                } else {
                    defaults = _defaultObjectValueProperty;
                }
            } else {
                defaults = _defaultAccessorProperty;
            }
            for (var key in defaults) {
                if (!(key in descriptor)) {
                    descriptor[key] = defaults[key];
                }
            }
        }


        if (!descriptor.hasOwnProperty(ENUMERABLE) && prop.charAt(0) === UNDERSCORE) {
            descriptor.enumerable = false;
        }
        if (dependencies) {
            var i = 0,
                independentProperty;

            for (; (independentProperty = dependencies[i]); i++) {
                Montage.addDependencyToProperty(obj, independentProperty, prop);
            }

        }

        if (SERIALIZABLE in descriptor) {
            // get the _serializableAttributeProperties property or creates it through the entire chain if missing.
            getAttributeProperties(obj, SERIALIZABLE)[prop] = descriptor.serializable;
        }

        //this is added to enable value properties with [] or Objects that are new for every instance
        if (descriptor.distinct === true && typeof descriptor.value === "object") {
            (function(prop,internalProperty, value, obj) {
                Object.defineProperty(obj, internalProperty, {
                    enumerable: false,
                    configurable: true,
                    writable: true,
                    value: null
                });
                if (value.constructor === Object && Object.getPrototypeOf(value) === Object_prototype) {
                    // we have an object literal {...}
                    if (Object.keys(value).length !== 0) {
                        Object.defineProperty(obj, prop, {
                            configurable: true,
                            get: function() {
                                //Special case for object to copy the values
                                var returnValue = this[internalProperty];
                                if (!returnValue) {
                                    var k;
                                    returnValue = {};
                                    for (k in value) {
                                        returnValue[k] = value[k];
                                    }
                                    this[internalProperty] = returnValue;
                                }
                                return returnValue;
                            },
                            set: function(value) {
                                this[internalProperty] = value;
                            }
                        });
                    } else {
                        Object.defineProperty(obj, prop, {
                            configurable: true,
                            get: function() {
                                return this[internalProperty] || (this[internalProperty] = {});
                            },
                            set: function(value) {
                                this[internalProperty] = value;
                            }
                        });
                    }

                } else if ((value.__proto__ || Object.getPrototypeOf(value)) === Array_prototype) {
                    // we have an array literal [...]
                    if (value.length !== 0) {
                        Object.defineProperty(obj, prop, {
                            configurable: true,
                            get: function() {
                                //Special case for object to copy the values
                                var returnValue = this[internalProperty];
                                if (!returnValue) {
                                    var i, k;
                                    returnValue = [];
                                    for (i = 0; typeof (k = value[i]) !== "undefined"; i++) {
                                        returnValue[i] = k;
                                    }
                                    this[internalProperty] = returnValue;
                                }
                                return returnValue;
                            },
                            set: function(value) {
                                this[internalProperty] = value;
                            }
                        });

                    } else {
                        Object.defineProperty(obj, prop, {
                            configurable: true,
                            get: function() {
                                //Special case for array as isArray fails
                                //Object_prototype.toString.call(Object.create([].__proto)) !== "[object Array]"
                                return this[internalProperty] || (this[internalProperty] = []);
                            },
                            set: function(value) {
                                this[internalProperty] = value;
                            }
                        });
                    }
                    //This case is to deal with objects that are created with a constructor
                } else if (value.constructor.prototype === Object.getPrototypeOf(value)) {
                    Object.defineProperty(obj, prop, {
                        configurable: true,
                        get: function() {
                            //Special case for object to copy the values
                            var returnValue = this[internalProperty];
                            if (!returnValue) {
                                var k;
                                returnValue = new value.constructor;
                                for (k in value) {
                                    returnValue[k] = value[k];
                                }
                                this[internalProperty] = returnValue;
                            }
                            return returnValue;
                        },
                        set: function(value) {
                            this[internalProperty] = value;
                        }
                    });


                } else {
                    Object.defineProperty(obj, prop, {
                        configurable: true,
                        get: function() {
                            return this[internalProperty] || (this[internalProperty] = Object.create(value.__proto__ || Object.getPrototypeOf(value)));
                        },
                        set: function(value) {
                            this[internalProperty] = value;
                        }
                    });
                }
            })(prop, UNDERSCORE + prop, descriptor.value, obj);

        } else {
            return Object.defineProperty(obj, prop, descriptor);
        }
    }});

/**
     Description Defines one or more new properties to an object, or modifies existing properties on the object.
     @function module:montage/core/core.Montage.defineProperties
     @param {Object} obj The object to which the properties are added.
     @param {Object} properties An object that contains one or more property descriptor objects.
     */
Object.defineProperty(Montage, "defineProperties", {value: function(obj, properties) {
    for (var property in properties) {
        if ("_bindingDescriptors" !== property) {
            this.defineProperty(obj, property, properties[property]);
        }
    }
    return obj;
}});

/**
 @private
 */
var _defaultAccessorProperty = {
    enumerable: true,
    configurable: true
};
/**
 @private
 */
var _defaultObjectValueProperty = {
    writable: true,
    enumerable: true,
    configurable: true
};

/**
 @private
 */
var _defaultFunctionValueProperty = {
    writable: true,
    enumerable: false,
    configurable: true
};

/**
     Adds a dependent property to another property's collection of dependencies.
     When the value of a dependent property changes, it generates a <code>change@independentProperty</code> event.
     @function module:montage/core/core.Montage.addDependencyToProperty
     @param {Object} obj The object containing the dependent and independent properties.
     @param {String} independentProperty The name of the object's independent property.
     @param {String} dependentProperty The name of the object's dependent property.
     */
Montage.defineProperty(Montage, "addDependencyToProperty", { value: function(obj, independentProperty, dependentProperty) {

    // TODO optimize this so we don't keep checking over and over again
    if (!obj._dependenciesForProperty) {
        obj._dependenciesForProperty = {};
    }

    if (!obj._dependenciesForProperty[dependentProperty]) {
        obj._dependenciesForProperty[dependentProperty] = [];
    }

    obj._dependenciesForProperty[dependentProperty].push(independentProperty);
}});


/**
     Removes a dependent property from another property's collection of dependent properties.
     When the value of a dependent property changes, it generates a <code>change@independentProperty</code> event.
     @function module:montage/core/core.Montage.removeDependencyFromProperty
     @param {Object} obj The object containing the dependent and independent properties.
     @param {String} independentProperty The name of the object's independent property.
     @param {String} dependentProperty The name of the object's dependent property that you want to remove.
     */
Montage.defineProperty(Montage, "removeDependencyFromProperty", {value: function(obj, independentProperty, dependentProperty) {
    if (!obj._dependenciesForProperty) {
        return;
    }

    var dependencies = obj._dependenciesForProperty[dependentProperty];
    if (dependencies) {
        dependencies = dependencies.filter(function(element) {
            return (element !== independentProperty);
        });
    }

}});

function getAttributeProperties(proto, attributeName) {
    var attributePropertyName = UNDERSCORE + attributeName + ATTRIBUTE_PROPERTIES;

    if (proto.hasOwnProperty(attributePropertyName)) {
        return proto[attributePropertyName];
    } else {
        return Object.defineProperty(proto, attributePropertyName, {
            enumerable: false, configurable: false, writable: false,
            value: Object.create(getAttributeProperties(Object.getPrototypeOf(proto), attributeName))
        })[attributePropertyName];
    }
}

/**
     Returns the names of serializable properties belonging to Montage object.
     @function module:montage/core/core.Montage.getSerializablePropertyNames
     @param {Object} anObject A Montage object.
     @returns {Array} An array containing the names of the serializable properties belonging to <code>anObject</code>.
     */
Montage.defineProperty(Montage, "getSerializablePropertyNames", {value: function(anObject) {

    var propertyNames = [],
        attributes = anObject._serializableAttributeProperties;

    if (attributes) {
        for (var name in attributes) {
            if (attributes[name]) {
                propertyNames.push(name);
            }
        }
    }

    return propertyNames;
}});

/**
     Returns the attribute of a property belonging to an object.
     @function module:montage/core/core.Montage.getPropertyAttribute
     @param {Object} anObject A object.
     @param {String} propertyName The name of a property belonging to <code>anObject</code>.
     @param {String} attributeName The name of a property's attribute.
     @returns attributes array
     */
Montage.defineProperty(Montage, "getPropertyAttribute", {value: function(anObject, propertyName, attributeName) {

    var attributePropertyName = UNDERSCORE + attributeName + ATTRIBUTE_PROPERTIES,
        attributes = anObject[attributePropertyName];

    if (attributes) {
        return attributes[propertyName];
    }
}});

 /**
     @function module:montage/core/core.Montage.getPropertyAttributes
     @param {Object} anObject An object.
     @param {String} attributeName The attribute name.
     @returns {Object} TODO getPropertyAttributes returns description
     */
Montage.defineProperty(Montage, "getPropertyAttributes", {value: function(anObject, attributeName) {
    var attributeValues = {},
        attributePropertyName = UNDERSCORE + attributeName + ATTRIBUTE_PROPERTIES,
        attributes = anObject[attributePropertyName];

    if (!attributes) {
        return;
    }

    for (var name in attributes) {
        attributeValues[name] = attributes[name];
    }

    return attributeValues;
}});

var _instanceMetadataDescriptor = {
    isInstance: {value: true}
};

var _functionInstanceMetadataDescriptor = {
    objectName: {value: "Function"},
    isInstance: {value: true}
};

/**
     @function module:montage/core/core.Montage.getInfoForObject
     @param {Object} object An object.
     @returns {Object} object._montage_metadata
     */
Montage.defineProperty(Montage, "getInfoForObject", {
    value: function(object) {
        var metadata;
        var instanceMetadataDescriptor;

        if (hasOwnProperty.call(object, "_montage_metadata")) {
            return object._montage_metadata;
        } else {
            metadata = object._montage_metadata || (object.constructor && object.constructor._montage_metadata) || null;
            if (object.constructor === Function) {
                instanceMetadataDescriptor = _functionInstanceMetadataDescriptor;
            } else {
                instanceMetadataDescriptor = _instanceMetadataDescriptor;
            }
            try {
                return Object.defineProperty(object, "_montage_metadata", {
                    enumerable: false,
                    // this object needs to be overriden by the SerializationCompiler because this particular code might be executed on an exported object before the Compiler takes action, for instance, if this function is called within the module definition itself (happens with __core__).
                    writable: true,
                    value: Object.create(metadata, instanceMetadataDescriptor)
                })._montage_metadata;
            } catch(e) {
                // NOTE Safari (as of Version 5.0.2 (6533.18.5, r78685)
                // doesn't seem to allow redefining an existing property on a DOM Element
                return (object._montage_metadata = Object.create(metadata, instanceMetadataDescriptor));
            }
        }
    }
});
/**
    @function module:montage/core/core.Montage.doNothing
    @default function
    */

Object.defineProperty(Montage, "doNothing", {
    value: function() {
    }
});

/**
    @function module:montage/core/core.Montage#self
    @default function
    @returns itself
    */
Object.defineProperty(Montage, "self", {
    value: function() {
        return this;
    }
});

/**
    @private
    */
Object.defineProperty(Montage, "__OBJECT_COUNT", {
    value: 0,
    writable: true
});


// TODO figure out why this code only works in this module.  Attempts to move
// it to core/extras/object resulted in _uuid becoming enumerable and tests
// breaking.

var UUID = require("core/uuid");

var hasOwnProperty = Object.prototype.hasOwnProperty;

var uuidGetGenerator = function() {

    var uuid = UUID.generate(),
        info = Montage.getInfoForObject(this);
    try {
        if (info !== null && info.isInstance === false) {
            this._uuid = uuid;
            Object.defineProperty(this, "uuid", {
                get: function() {
                    if (this.hasOwnProperty("uuid")) {
                        // we are calling uuid on the prototype
                        return this._uuid;
                    } else {
                        // we are calling uuid on instance of this prototype
                        return uuidGetGenerator.call(this);
                    }
                }
            });
        } else {
            //This is needed to workaround some bugs in Safari where re-defining uuid doesn't work for DOMWindow.
            if (info.isInstance) {
                Object.defineProperty(this, "uuid", {
                    configurable: true,
                    enumerable: false,
                    writable: false,
                    value: uuid
                });
            }
            //This is really because re-defining the property on DOMWindow actually doesn't work, so the original property with the getter is still there and return this._uuid if there.
            if (this instanceof Element || !info.isInstance || !(VALUE in Object.getOwnPropertyDescriptor(this, "uuid")) || !(PROTO in this /* lame way to detect IE */)) {
                //This is needed to workaround some bugs in Safari where re-defining uuid doesn't work for DOMWindow.
                this._uuid = uuid;
            }
        }
    } catch(e) {
        // NOTE Safari (as of Version 5.0.2 (6533.18.5, r78685)
        // doesn't seem to allow redefining an existing property on a DOM Element
        // Still want to redefine the property where possible for speed
        this._uuid = uuid;
    }

    return uuid;
};

var defaultUuidGet = function defaultUuidGet() {
    return (hasOwnProperty.call(this, "_uuid") ? this._uuid : uuidGetGenerator.call(this));
};

/**
     @private
     */
Object.defineProperty(Object.prototype, "_uuid", {
    enumerable: false,
    value: null,
    writable: true
});

/**
     Contains an object's unique ID.
     @member external:Object#uuid
     @default null
     */
Object.defineProperty(Object.prototype, "uuid", {
    configurable: true,
    get: defaultUuidGet,
    set: function() {
    }
});

Montage.defineProperty(Montage, "identifier", {
    value: null,
    serializable: true
});

/**
     Returns true if two objects are equal, otherwise returns false.
     @function module:montage/core/core.Montage#equals
     @param {Object} anObject The object to compare for equality.
     @returns {Boolean} Returns <code>true</code> if the calling object and <code>anObject</code> are identical and their <code>uuid</code> properties are also equal. Otherwise, returns <code>false</code>.
     */
Object.defineProperty(Montage, "equals", {
    value: function(anObject) {
        return this === anObject || this.uuid === anObject.uuid;
    }
});



/*
 * If it exists this method calls the method named with the identifier prefix.
 * Example: If the name parameter is "shouldDoSomething" and the caller's identifier is "bob", then
 * this method will try and call "bobShouldDoSomething"
*/

/**
 * @function module:montage/core/core.Montage#callDelegateMethod
 * @param {string} name
 */
Object.defineProperty(Montage, "callDelegateMethod", {
    value: function(name) {
        var delegate = this.delegate, delegateFunctionName, delegateFunction;
        if (typeof this.identifier === "string") {
            delegateFunctionName = this.identifier + name.toCapitalized();
            if (delegate && typeof (delegateFunction = delegate[delegateFunctionName]) === "function") {
                // remove first argument
                Array_prototype.shift.call(arguments);
                return delegateFunction.apply(delegate, arguments);
            }
        }

        if (delegate && typeof (delegateFunction = delegate[name]) === "function") {
            // remove first argument
            Array_prototype.shift.call(arguments);
            return delegateFunction.apply(delegate, arguments);
        }
    }
});