code
stringlengths
2
1.05M
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function (config) { // Define changes to default configuration here. // For complete reference see: // http://docs.ckeditor.com/#!/api/CKEDITOR.config // The toolbar groups arrangement, optimized for two toolbar rows. config.toolbarGroups = [ { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'tools' }, { name: 'undo'}, { name: 'clipboard', groups: [ 'clipboard' ] }, { name: 'forms' }, '/', { name: 'basicstyles'}, { name: 'insert', groups: ['insert', 'others'] }, { name: 'links'}, { name: 'paragraph', groups: [ 'list', 'blocks', 'align', 'bidi' ] }, { name: 'styles' }, { name: 'colors' } ]; // Remove some buttons provided by the standard plugins, which are // not needed in the Standard(s) toolbar. config.removeButtons = 'Anchor,Table,SpecialChar,HorizontalRule,Underline,Subscript,Superscript,Strike'; // Set the most common block elements. config.format_tags = 'p;h1;h2;h3;pre'; // Simplify the dialog windows. config.removeDialogTabs = 'image:advanced;link:advanced'; CKEDITOR.config.simpleImageBrowserURL = '/images/all'; CKEDITOR.config.language = window.admin.locale; config.filebrowserImageUploadUrl = '/images/upload'; };
[db.config, db.config_anon].forEach(function(coll) { coll.find().forEach(function(o) { if (o.filter && o.filter.v && o.filter.v.length > 1) { coll.update({ _id: o._id }, { $push: { 'filter.v': NumberInt(7) } }); }; }); });
describe("", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("build/docs/examples/example-example51/index.html"); }); it('should toggle button', function() { expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); element(by.model('checked')).click(); expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); }); });
/*global device*/ var TrimFocusInput = Ember.TextField.extend({ focus: true, attributeBindings: ['autofocus'], autofocus: Ember.computed(function () { return (device.ios()) ? false : 'autofocus'; }), setFocus: function () { // This fix is required until Mobile Safari has reliable // autofocus, select() or focus() support if (this.focus && !device.ios()) { this.$().val(this.$().val()).focus(); } }.on('didInsertElement'), focusOut: function () { var text = this.$().val(); this.$().val(text.trim()); } }); export default TrimFocusInput;
/** * @author Ed Spencer * @aside guide stores * * The Store class encapsulates a client side cache of {@link Ext.data.Model Model} objects. Stores load * data via a {@link Ext.data.proxy.Proxy Proxy}, and also provide functions for {@link #sort sorting}, * {@link #filter filtering} and querying the {@link Ext.data.Model model} instances contained within it. * * Creating a Store is easy - we just tell it the Model and the Proxy to use to load and save its data: * * // Set up a {@link Ext.data.Model model} to use in our Store * Ext.define("User", { * extend: "Ext.data.Model", * config: { * fields: [ * {name: "firstName", type: "string"}, * {name: "lastName", type: "string"}, * {name: "age", type: "int"}, * {name: "eyeColor", type: "string"} * ] * } * }); * * var myStore = Ext.create("Ext.data.Store", { * model: "User", * proxy: { * type: "ajax", * url : "/users.json", * reader: { * type: "json", * rootProperty: "users" * } * }, * autoLoad: true * }); * * Ext.create("Ext.List", { * fullscreen: true, * store: myStore, * itemTpl: "{lastName}, {firstName} ({age})" * }); * * In the example above we configured an AJAX proxy to load data from the url '/users.json'. We told our Proxy * to use a {@link Ext.data.reader.Json JsonReader} to parse the response from the server into Model object - * {@link Ext.data.reader.Json see the docs on JsonReader} for details. * * The external data file, _/users.json_, is as follows: * * { * "success": true, * "users": [ * { * "firstName": "Tommy", * "lastName": "Maintz", * "age": 24, * "eyeColor": "green" * }, * { * "firstName": "Aaron", * "lastName": "Conran", * "age": 26, * "eyeColor": "blue" * }, * { * "firstName": "Jamie", * "lastName": "Avins", * "age": 37, * "eyeColor": "brown" * } * ] * } * * ## Inline data * * Stores can also load data inline. Internally, Store converts each of the objects we pass in as {@link #cfg-data} * into Model instances: * * @example * // Set up a model to use in our Store * Ext.define('User', { * extend: 'Ext.data.Model', * config: { * fields: [ * {name: 'firstName', type: 'string'}, * {name: 'lastName', type: 'string'}, * {name: 'age', type: 'int'}, * {name: 'eyeColor', type: 'string'} * ] * } * }); * * Ext.create("Ext.data.Store", { * storeId: "usersStore", * model: "User", * data : [ * {firstName: "Ed", lastName: "Spencer"}, * {firstName: "Tommy", lastName: "Maintz"}, * {firstName: "Aaron", lastName: "Conran"}, * {firstName: "Jamie", lastName: "Avins"} * ] * }); * * Ext.create("Ext.List", { * fullscreen: true, * store: "usersStore", * itemTpl: "{lastName}, {firstName}" * }); * * Loading inline data using the method above is great if the data is in the correct format already (e.g. it doesn't need * to be processed by a {@link Ext.data.reader.Reader reader}). If your inline data requires processing to decode the data structure, * use a {@link Ext.data.proxy.Memory MemoryProxy} instead (see the {@link Ext.data.proxy.Memory MemoryProxy} docs for an example). * * Additional data can also be loaded locally using {@link #method-add}. * * ## Loading Nested Data * * Applications often need to load sets of associated data - for example a CRM system might load a User and her Orders. * Instead of issuing an AJAX request for the User and a series of additional AJAX requests for each Order, we can load a nested dataset * and allow the Reader to automatically populate the associated models. Below is a brief example, see the {@link Ext.data.reader.Reader} intro * documentation for a full explanation: * * // Set up a model to use in our Store * Ext.define('User', { * extend: 'Ext.data.Model', * config: { * fields: [ * {name: 'name', type: 'string'}, * {name: 'id', type: 'int'} * ] * } * }); * * var store = Ext.create('Ext.data.Store', { * autoLoad: true, * model: "User", * proxy: { * type: 'ajax', * url : 'users.json', * reader: { * type: 'json', * rootProperty: 'users' * } * } * }); * * Ext.create("Ext.List", { * fullscreen: true, * store: store, * itemTpl: "{name} (id: {id})" * }); * * Which would consume a response like this: * * { * "users": [ * { * "id": 1, * "name": "Ed", * "orders": [ * { * "id": 10, * "total": 10.76, * "status": "invoiced" * }, * { * "id": 11, * "total": 13.45, * "status": "shipped" * } * ] * }, * { * "id": 3, * "name": "Tommy", * "orders": [ * ] * }, * { * "id": 4, * "name": "Jamie", * "orders": [ * { * "id": 12, * "total": 17.76, * "status": "shipped" * } * ] * } * ] * } * * See the {@link Ext.data.reader.Reader} intro docs for a full explanation. * * ## Filtering and Sorting * * Stores can be sorted and filtered - in both cases either remotely or locally. The {@link #sorters} and {@link #filters} are * held inside {@link Ext.util.MixedCollection MixedCollection} instances to make them easy to manage. Usually it is sufficient to * either just specify sorters and filters in the Store configuration or call {@link #sort} or {@link #filter}: * * // Set up a model to use in our Store * Ext.define('User', { * extend: 'Ext.data.Model', * config: { * fields: [ * {name: 'firstName', type: 'string'}, * {name: 'lastName', type: 'string'}, * {name: 'age', type: 'int'} * ] * } * }); * * var store = Ext.create("Ext.data.Store", { * autoLoad: true, * model: "User", * proxy: { * type: "ajax", * url : "users.json", * reader: { * type: "json", * rootProperty: "users" * } * }, * sorters: [ * { * property : "age", * direction: "DESC" * }, * { * property : "firstName", * direction: "ASC" * } * ], * filters: [ * { * property: "firstName", * value: /Jamie/ * } * ] * }); * * Ext.create("Ext.List", { * fullscreen: true, * store: store, * itemTpl: "{lastName}, {firstName} ({age})" * }); * * And the data file, _users.json_, is as follows: * * { * "success": true, * "users": [ * { * "firstName": "Tommy", * "lastName": "Maintz", * "age": 24 * }, * { * "firstName": "Aaron", * "lastName": "Conran", * "age": 26 * }, * { * "firstName": "Jamie", * "lastName": "Avins", * "age": 37 * } * ] * } * * The new Store will keep the configured sorters and filters in the MixedCollection instances mentioned above. By default, sorting * and filtering are both performed locally by the Store - see {@link #remoteSort} and {@link #remoteFilter} to allow the server to * perform these operations instead. * * Filtering and sorting after the Store has been instantiated is also easy. Calling {@link #filter} adds another filter to the Store * and automatically filters the dataset (calling {@link #filter} with no arguments simply re-applies all existing filters). Note that by * default your sorters are automatically reapplied if using local sorting. * * store.filter('eyeColor', 'Brown'); * * Change the sorting at any time by calling {@link #sort}: * * store.sort('height', 'ASC'); * * Note that all existing sorters will be removed in favor of the new sorter data (if {@link #sort} is called with no arguments, * the existing sorters are just reapplied instead of being removed). To keep existing sorters and add new ones, just add them * to the MixedCollection: * * store.sorters.add(new Ext.util.Sorter({ * property : 'shoeSize', * direction: 'ASC' * })); * * store.sort(); * * ## Registering with StoreManager * * Any Store that is instantiated with a {@link #storeId} will automatically be registered with the {@link Ext.data.StoreManager StoreManager}. * This makes it easy to reuse the same store in multiple views: * * // this store can be used several times * Ext.create('Ext.data.Store', { * model: 'User', * storeId: 'usersStore' * }); * * Ext.create('Ext.List', { * store: 'usersStore' * // other config goes here * }); * * Ext.create('Ext.view.View', { * store: 'usersStore' * // other config goes here * }); * * ## Further Reading * * Stores are backed up by an ecosystem of classes that enables their operation. To gain a full understanding of these * pieces and how they fit together, see: * * - {@link Ext.data.proxy.Proxy Proxy} - overview of what Proxies are and how they are used * - {@link Ext.data.Model Model} - the core class in the data package * - {@link Ext.data.reader.Reader Reader} - used by any subclass of {@link Ext.data.proxy.Server ServerProxy} to read a response */ Ext.define('Ext.data.Store', { alias: 'store.store', extend: 'Ext.Evented', requires: [ 'Ext.util.Collection', 'Ext.data.Operation', 'Ext.data.proxy.Memory', 'Ext.data.Model', 'Ext.data.StoreManager', 'Ext.util.Grouper' ], /** * @event addrecords * Fired when one or more new Model instances have been added to this Store. You should listen * for this event if you have to update a representation of the records in this store in your UI. * If you need the indices of the records that were added please use the store.indexOf(record) method. * @param {Ext.data.Store} store The store * @param {Ext.data.Model[]} records The Model instances that were added */ /** * @event removerecords * Fired when one or more Model instances have been removed from this Store. You should listen * for this event if you have to update a representation of the records in this store in your UI. * @param {Ext.data.Store} store The Store object * @param {Ext.data.Model[]} records The Model instances that was removed * @param {Number[]} indices The indices of the records that were removed. These indices already * take into account any potential earlier records that you remove. This means that if you loop * over the records, you can get its current index in your data representation from this array. */ /** * @event updaterecord * Fires when a Model instance has been updated * @param {Ext.data.Store} this * @param {Ext.data.Model} record The Model instance that was updated * @param {Number} newIndex If the update changed the index of the record (due to sorting for example), then * this gives you the new index in the store. * @param {Number} oldIndex If the update changed the index of the record (due to sorting for example), then * this gives you the old index in the store. * @param {Array} modifiedFieldNames An array containing the field names that have been modified since the * record was committed or created * @param {Object} modifiedValues An object where each key represents a field name that had it's value modified, * and where the value represents the old value for that field. To get the new value in a listener * you should use the {@link Ext.data.Model#get get} method. */ /** * @event update * @inheritdoc Ext.data.Store#updaterecord * @removed 2.0 Listen to #updaterecord instead. */ /** * @event refresh * Fires whenever the records in the Store have changed in a way that your representation of the records * need to be entirely refreshed. * @param {Ext.data.Store} this The data store * @param {Ext.util.Collection} data The data collection containing all the records */ /** * @event beforeload * Fires before a request is made for a new data object. If the beforeload handler returns false the load * action will be canceled. Note that you should not listen for this event in order to refresh the * data view. Use the {@link #refresh} event for this instead. * @param {Ext.data.Store} store This Store * @param {Ext.data.Operation} operation The Ext.data.Operation object that will be passed to the Proxy to * load the Store */ /** * @event load * Fires whenever records have been loaded into the store. Note that you should not listen * for this event in order to refresh the data view. Use the {@link #refresh} event for this instead. * @param {Ext.data.Store} this * @param {Ext.data.Model[]} records An array of records * @param {Boolean} successful `true` if the operation was successful. * @param {Ext.data.Operation} operation The associated operation. */ /** * @event write * Fires whenever a successful write has been made via the configured {@link #proxy Proxy} * @param {Ext.data.Store} store This Store * @param {Ext.data.Operation} operation The {@link Ext.data.Operation Operation} object that was used in * the write */ /** * @event beforesync * Fired before a call to {@link #sync} is executed. Return `false` from any listener to cancel the sync * @param {Object} options Hash of all records to be synchronized, broken down into create, update and destroy */ /** * @event clear * Fired after the {@link #removeAll} method is called. Note that you should not listen for this event in order * to refresh the data view. Use the {@link #refresh} event for this instead. * @param {Ext.data.Store} this * @return {Ext.data.Store} */ statics: { create: function(store) { if (!store.isStore) { if (!store.type) { store.type = 'store'; } store = Ext.createByAlias('store.' + store.type, store); } return store; } }, isStore: true, config: { /** * @cfg {String} storeId * Unique identifier for this store. If present, this Store will be registered with the {@link Ext.data.StoreManager}, * making it easy to reuse elsewhere. * @accessor */ storeId: undefined, /** * @cfg {Object[]/Ext.data.Model[]} data * Array of Model instances or data objects to load locally. See "Inline data" above for details. * @accessor */ data: null, /** * @cfg {Boolean/Object} [autoLoad=false] * If data is not specified, and if `autoLoad` is `true` or an Object, this store's load method is automatically called * after creation. If the value of `autoLoad` is an Object, this Object will be passed to the store's `load()` method. * @accessor */ autoLoad: null, /** * @cfg {Boolean} autoSync * `true` to automatically sync the Store with its Proxy after every edit to one of its Records. * @accessor */ autoSync: false, /** * @cfg {String} model * Returns Ext.data.Model and not a String. * Name of the {@link Ext.data.Model Model} associated with this store. * The string is used as an argument for {@link Ext.ModelManager#getModel}. * @accessor */ model: undefined, /** * @cfg {String/Ext.data.proxy.Proxy/Object} proxy The Proxy to use for this Store. This can be either a string, a config * object or a Proxy instance - see {@link #setProxy} for details. * @accessor */ proxy: undefined, /** * @cfg {Object[]} fields * Returns Ext.util.Collection not just an Object. * Use in place of specifying a {@link #model} configuration. The fields should be a * set of {@link Ext.data.Field} configuration objects. The store will automatically create a {@link Ext.data.Model} * with these fields. In general this configuration option should be avoided, it exists for the purposes of * backwards compatibility. For anything more complicated, such as specifying a particular id property or * associations, a {@link Ext.data.Model} should be defined and specified for the {@link #model} * config. * @accessor */ fields: null, /** * @cfg {Boolean} remoteSort * `true` to defer any sorting operation to the server. If `false`, sorting is done locally on the client. * * If this is set to `true`, you will have to manually call the {@link #method-load} method after you {@link #method-sort}, to retrieve the sorted * data from the server. * @accessor */ remoteSort: false, /** * @cfg {Boolean} remoteFilter * `true` to defer any filtering operation to the server. If `false`, filtering is done locally on the client. * * If this is set to `true`, you will have to manually call the {@link #method-load} method after you {@link #method-filter} to retrieve the filtered * data from the server. * @accessor */ remoteFilter: false, /** * @cfg {Boolean} remoteGroup * `true` to defer any grouping operation to the server. If `false`, grouping is done locally on the client. * @accessor */ remoteGroup: false, /** * @cfg {Object[]} filters * Array of {@link Ext.util.Filter Filters} for this store. This configuration is handled by the * {@link Ext.mixin.Filterable Filterable} mixin of the {@link Ext.util.Collection data} collection. * @accessor */ filters: null, /** * @cfg {Object[]} sorters * Array of {@link Ext.util.Sorter Sorters} for this store. This configuration is handled by the * {@link Ext.mixin.Sortable Sortable} mixin of the {@link Ext.util.Collection data} collection. * See also the {@link #sort} method. * @accessor */ sorters: null, /** * @cfg {Object} grouper * A configuration object for this Store's {@link Ext.util.Grouper grouper}. * * For example, to group a store's items by the first letter of the last name: * * Ext.define('People', { * extend: 'Ext.data.Store', * * config: { * fields: ['first_name', 'last_name'], * * grouper: { * groupFn: function(record) { * return record.get('last_name').substr(0, 1); * }, * sortProperty: 'last_name' * } * } * }); * * @accessor */ grouper: null, /** * @cfg {String} groupField * The (optional) field by which to group data in the store. Internally, grouping is very similar to sorting - the * groupField and {@link #groupDir} are injected as the first sorter (see {@link #sort}). Stores support a single * level of grouping, and groups can be fetched via the {@link #getGroups} method. * @accessor */ groupField: null, /** * @cfg {String} groupDir * The direction in which sorting should be applied when grouping. If you specify a grouper by using the {@link #groupField} * configuration, this will automatically default to "ASC" - the other supported value is "DESC" * @accessor */ groupDir: null, /** * @cfg {Function} getGroupString This function will be passed to the {@link #grouper} configuration as it's `groupFn`. * Note that this configuration is deprecated and grouper: `{groupFn: yourFunction}}` is preferred. * @deprecated * @accessor */ getGroupString: null, /** * @cfg {Number} pageSize * The number of records considered to form a 'page'. This is used to power the built-in * paging using the nextPage and previousPage functions. * @accessor */ pageSize: 25, /** * @cfg {Number} totalCount The total number of records in the full dataset, as indicated by a server. If the * server-side dataset contains 5000 records but only returns pages of 50 at a time, `totalCount` will be set to * 5000 and {@link #getCount} will return 50 */ totalCount: null, /** * @cfg {Boolean} clearOnPageLoad `true` to empty the store when loading another page via {@link #loadPage}, * {@link #nextPage} or {@link #previousPage}. Setting to `false` keeps existing records, allowing * large data sets to be loaded one page at a time but rendered all together. * @accessor */ clearOnPageLoad: true, modelDefaults: {}, /** * @cfg {Boolean} autoDestroy This is a private configuration used in the framework whether this Store * can be destroyed. * @private */ autoDestroy: false, /** * @cfg {Boolean} syncRemovedRecords This configuration allows you to disable the synchronization of * removed records on this Store. By default, when you call `removeAll()` or `remove()`, records will be added * to an internal removed array. When you then sync the Store, we send a destroy request for these records. * If you don't want this to happen, you can set this configuration to `false`. */ syncRemovedRecords: true, /** * @cfg {Boolean} destroyRemovedRecords This configuration allows you to prevent destroying record * instances when they are removed from this store and are not in any other store. */ destroyRemovedRecords: true }, /** * @property {Number} currentPage * The page that the Store has most recently loaded (see {@link #loadPage}) */ currentPage: 1, constructor: function(config) { config = config || {}; this.data = this._data = this.createDataCollection(); this.data.setSortRoot('data'); this.data.setFilterRoot('data'); this.removed = []; if (config.id && !config.storeId) { config.storeId = config.id; delete config.id; } // <deprecated product=touch since=2.0> // <debug> if (config.hasOwnProperty('sortOnLoad')) { Ext.Logger.deprecate( '[Ext.data.Store] sortOnLoad is always activated in Sencha Touch 2 so your Store is always fully ' + 'sorted after loading. The only exception is if you are using remoteSort and change sorting after ' + 'the Store as loaded, in which case you need to call store.load() to fetch the sorted data from the server.' ); } if (config.hasOwnProperty('filterOnLoad')) { Ext.Logger.deprecate( '[Ext.data.Store] filterOnLoad is always activated in Sencha Touch 2 so your Store is always fully ' + 'sorted after loading. The only exception is if you are using remoteFilter and change filtering after ' + 'the Store as loaded, in which case you need to call store.load() to fetch the filtered data from the server.' ); } if (config.hasOwnProperty('sortOnFilter')) { Ext.Logger.deprecate( '[Ext.data.Store] sortOnFilter is deprecated and is always effectively true when sorting and filtering locally' ); } // </debug> // </deprecated> this.initConfig(config); this.callParent(arguments); }, /** * @private * @return {Ext.util.Collection} */ createDataCollection: function() { return new Ext.util.Collection(function(record) { return record.getId(); }); }, applyStoreId: function(storeId) { if (storeId === undefined || storeId === null) { storeId = this.getUniqueId(); } return storeId; }, updateStoreId: function(storeId, oldStoreId) { if (oldStoreId) { Ext.data.StoreManager.unregister(this); } if (storeId) { Ext.data.StoreManager.register(this); } }, applyModel: function(model) { if (typeof model == 'string') { var registeredModel = Ext.data.ModelManager.getModel(model); if (!registeredModel) { Ext.Logger.error('Model with name "' + model + '" does not exist.'); } model = registeredModel; } if (model && !model.prototype.isModel && Ext.isObject(model)) { model = Ext.data.ModelManager.registerType(model.storeId || model.id || Ext.id(), model); } if (!model) { var fields = this.getFields(), data = this.config.data; if (!fields && data && data.length) { fields = Ext.Object.getKeys(data[0]); } if (fields) { model = Ext.define('Ext.data.Store.ImplicitModel-' + (this.getStoreId() || Ext.id()), { extend: 'Ext.data.Model', config: { fields: fields, useCache: false, proxy: this.getProxy() } }); this.implicitModel = true; } } if (!model && this.getProxy()) { model = this.getProxy().getModel(); } // <debug> if (!model) { Ext.Logger.warn('Unless you define your model through metadata, a store needs to have a model defined on either itself or on its proxy'); } // </debug> return model; }, updateModel: function(model) { var proxy = this.getProxy(); if (proxy && !proxy.getModel()) { proxy.setModel(model); } }, applyProxy: function(proxy, currentProxy) { proxy = Ext.factory(proxy, Ext.data.Proxy, currentProxy, 'proxy'); if (!proxy && this.getModel()) { proxy = this.getModel().getProxy(); } if (!proxy) { proxy = new Ext.data.proxy.Memory({ model: this.getModel() }); } if (proxy.isMemoryProxy) { this.setSyncRemovedRecords(false); } return proxy; }, updateProxy: function(proxy, oldProxy) { if (proxy) { if (!proxy.getModel()) { proxy.setModel(this.getModel()); } proxy.on('metachange', 'onMetaChange', this); } if (oldProxy) { proxy.un('metachange', 'onMetaChange', this); } }, /** * We are using applyData so that we can return nothing and prevent the `this.data` * property to be overridden. * @param data */ applyData: function(data) { var me = this, proxy; if (data) { proxy = me.getProxy(); if (proxy instanceof Ext.data.proxy.Memory) { proxy.setData(data); me.load(); return; } else { // We make it silent because we don't want to fire a refresh event me.removeAll(true); // This means we have to fire a clear event though me.fireEvent('clear', me); // We don't want to fire addrecords event since we will be firing // a refresh event later which will already take care of updating // any views bound to this store me.suspendEvents(); me.add(data); me.resumeEvents(); // We set this to true so isAutoLoading to try me.dataLoaded = true; } } else { me.removeAll(true); // This means we have to fire a clear event though me.fireEvent('clear', me); } me.fireEvent('refresh', me, me.data); }, clearData: function() { this.setData(null); }, addData: function(data) { var reader = this.getProxy().getReader(), resultSet = reader.read(data), records = resultSet.getRecords(); this.add(records); }, updateAutoLoad: function(autoLoad) { var proxy = this.getProxy(); if (autoLoad && (proxy && !proxy.isMemoryProxy)) { this.load(Ext.isObject(autoLoad) ? autoLoad : null); } }, /** * Returns `true` if the Store is set to {@link #autoLoad} or is a type which loads upon instantiation. * @return {Boolean} */ isAutoLoading: function() { var proxy = this.getProxy(); return (this.getAutoLoad() || (proxy && proxy.isMemoryProxy) || this.dataLoaded); }, updateGroupField: function(groupField) { var grouper = this.getGrouper(); if (groupField) { if (!grouper) { this.setGrouper({ property: groupField, direction: this.getGroupDir() || 'ASC' }); } else { grouper.setProperty(groupField); } } else if (grouper) { this.setGrouper(null); } }, updateGroupDir: function(groupDir) { var grouper = this.getGrouper(); if (grouper) { grouper.setDirection(groupDir); } }, applyGetGroupString: function(getGroupStringFn) { var grouper = this.getGrouper(); if (getGroupStringFn) { // <debug> Ext.Logger.warn('Specifying getGroupString on a store has been deprecated. Please use grouper: {groupFn: yourFunction}'); // </debug> if (grouper) { grouper.setGroupFn(getGroupStringFn); } else { this.setGrouper({ groupFn: getGroupStringFn }); } } else if (grouper) { this.setGrouper(null); } }, applyGrouper: function(grouper) { if (typeof grouper == 'string') { grouper = { property: grouper }; } else if (typeof grouper == 'function') { grouper = { groupFn: grouper }; } grouper = Ext.factory(grouper, Ext.util.Grouper); return grouper; }, updateGrouper: function(grouper, oldGrouper) { var data = this.data; if (oldGrouper) { data.removeSorter(oldGrouper); if (!grouper) { data.getSorters().removeSorter('isGrouper'); } } if (grouper) { data.insertSorter(0, grouper); if (!oldGrouper) { data.getSorters().addSorter({ direction: 'DESC', property: 'isGrouper', transform: function(value) { return (value === true) ? 1 : -1; } }); } } if (oldGrouper) { this.fireEvent('refresh', this, data); } }, /** * This method tells you if this store has a grouper defined on it. * @return {Boolean} `true` if this store has a grouper defined. */ isGrouped: function() { return !!this.getGrouper(); }, updateSorters: function(sorters) { var grouper = this.getGrouper(), data = this.data, autoSort = data.getAutoSort(); // While we remove/add sorters we don't want to automatically sort because we still need // to apply any field sortTypes as transforms on the Sorters after we have added them. data.setAutoSort(false); data.setSorters(sorters); if (grouper) { data.insertSorter(0, grouper); } this.updateSortTypes(); // Now we put back autoSort on the Collection to the value it had before. If it was // auto sorted, setting this back will cause it to sort right away. data.setAutoSort(autoSort); }, updateSortTypes: function() { var model = this.getModel(), fields = model && model.getFields(), data = this.data; // We loop over each sorter and set it's transform method to the every field's sortType. if (fields) { data.getSorters().each(function(sorter) { var property = sorter.getProperty(), field; if (!sorter.isGrouper && property && !sorter.getTransform()) { field = fields.get(property); if (field) { sorter.setTransform(field.getSortType()); } } }); } }, updateFilters: function(filters) { this.data.setFilters(filters); }, /** * Adds Model instance to the Store. This method accepts either: * * - An array of Model instances or Model configuration objects. * - Any number of Model instance or Model configuration object arguments. * * The new Model instances will be added at the end of the existing collection. * * Sample usage: * * myStore.add({some: 'data2'}, {some: 'other data2'}); * * @param {Ext.data.Model[]/Ext.data.Model...} model An array of Model instances * or Model configuration objects, or variable number of Model instance or config arguments. * @return {Ext.data.Model[]} The model instances that were added. */ add: function(records) { if (!Ext.isArray(records)) { records = Array.prototype.slice.call(arguments); } return this.insert(this.data.length, records); }, /** * Inserts Model instances into the Store at the given index and fires the {@link #add} event. * See also `{@link #add}`. * @param {Number} index The start index at which to insert the passed Records. * @param {Ext.data.Model[]} records An Array of Ext.data.Model objects to add to the cache. * @return {Object} */ insert: function(index, records) { if (!Ext.isArray(records)) { records = Array.prototype.slice.call(arguments, 1); } var me = this, sync = false, data = this.data, ln = records.length, Model = this.getModel(), modelDefaults = me.getModelDefaults(), added = false, i, record; records = records.slice(); for (i = 0; i < ln; i++) { record = records[i]; if (!record.isModel) { record = new Model(record); } // If we are adding a record that is already an instance which was still in the // removed array, then we remove it from the removed array else if (this.removed.indexOf(record) != -1) { Ext.Array.remove(this.removed, record); } record.set(modelDefaults); record.join(me); records[i] = record; // If this is a newly created record, then we might want to sync it later sync = sync || (record.phantom === true); } // Now we insert all these records in one go to the collection. Saves many function // calls to data.insert. Does however create two loops over the records we are adding. if (records.length === 1) { added = data.insert(index, records[0]); if (added) { added = [added]; } } else { added = data.insertAll(index, records); } if (added) { me.fireEvent('addrecords', me, added); } if (me.getAutoSync() && sync) { me.sync(); } return records; }, /** * Removes the given record from the Store, firing the `removerecords` event passing all the instances that are removed. * @param {Ext.data.Model/Ext.data.Model[]} records Model instance or array of instances to remove. */ remove: function (records) { if (records.isModel) { records = [records]; } var me = this, sync = false, i = 0, autoSync = this.getAutoSync(), syncRemovedRecords = me.getSyncRemovedRecords(), destroyRemovedRecords = this.getDestroyRemovedRecords(), ln = records.length, indices = [], removed = [], isPhantom, items = me.data.items, record, index; for (; i < ln; i++) { record = records[i]; if (me.data.contains(record)) { isPhantom = (record.phantom === true); index = items.indexOf(record); if (index !== -1) { removed.push(record); indices.push(index); } record.unjoin(me); me.data.remove(record); if (destroyRemovedRecords && !syncRemovedRecords && !record.stores.length) { record.destroy(); } else if (!isPhantom && syncRemovedRecords) { // don't push phantom records onto removed me.removed.push(record); } sync = sync || !isPhantom; } } me.fireEvent('removerecords', me, removed, indices); if (autoSync && sync) { me.sync(); } }, /** * Removes the model instance at the given index. * @param {Number} index The record index. */ removeAt: function(index) { var record = this.getAt(index); if (record) { this.remove(record); } }, /** * Remove all items from the store. * @param {Boolean} [silent] Prevent the `clear` event from being fired. */ removeAll: function(silent) { if (silent !== true && this.eventFiringSuspended !== true) { this.fireAction('clear', [this], 'doRemoveAll'); } else { this.doRemoveAll.call(this, true); } }, doRemoveAll: function (silent) { var me = this, destroyRemovedRecords = this.getDestroyRemovedRecords(), syncRemovedRecords = this.getSyncRemovedRecords(), records = me.data.all.slice(), ln = records.length, i, record; for (i = 0; i < ln; i++) { record = records[i]; record.unjoin(me); if (destroyRemovedRecords && !syncRemovedRecords && !record.stores.length) { record.destroy(); } else if (record.phantom !== true && syncRemovedRecords) { me.removed.push(record); } } me.data.clear(); if (silent !== true) { me.fireEvent('refresh', me, me.data); } if (me.getAutoSync()) { this.sync(); } }, /** * Calls the specified function for each of the {@link Ext.data.Model Records} in the cache. * * // Set up a model to use in our Store * Ext.define('User', { * extend: 'Ext.data.Model', * config: { * fields: [ * {name: 'firstName', type: 'string'}, * {name: 'lastName', type: 'string'} * ] * } * }); * * var store = Ext.create('Ext.data.Store', { * model: 'User', * data : [ * {firstName: 'Ed', lastName: 'Spencer'}, * {firstName: 'Tommy', lastName: 'Maintz'}, * {firstName: 'Aaron', lastName: 'Conran'}, * {firstName: 'Jamie', lastName: 'Avins'} * ] * }); * * store.each(function (item, index, length) { * console.log(item.get('firstName'), index); * }); * * @param {Function} fn The function to call. Returning `false` aborts and exits the iteration. * @param {Ext.data.Model} fn.item * @param {Number} fn.index * @param {Number} fn.length * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. * Defaults to the current {@link Ext.data.Model Record} in the iteration. */ each: function(fn, scope) { this.data.each(fn, scope); }, /** * Gets the number of cached records. Note that filtered records are not included in this count. * If using paging, this may not be the total size of the dataset. * @return {Number} The number of Records in the Store's cache. */ getCount: function() { return this.data.items.length || 0; }, /** * Gets the number of all cached records including the ones currently filtered. * If using paging, this may not be the total size of the dataset. * @return {Number} The number of all Records in the Store's cache. */ getAllCount: function () { return this.data.all.length || 0; }, /** * Get the Record at the specified index. * @param {Number} index The index of the Record to find. * @return {Ext.data.Model/undefined} The Record at the passed index. Returns `undefined` if not found. */ getAt: function(index) { return this.data.getAt(index); }, /** * Returns a range of Records between specified indices. Note that if the store is filtered, only filtered results * are returned. * @param {Number} [startIndex=0] (optional) The starting index. * @param {Number} [endIndex=-1] (optional) The ending index (defaults to the last Record in the Store). * @return {Ext.data.Model[]} An array of Records. */ getRange: function(start, end) { return this.data.getRange(start, end); }, /** * Get the Record with the specified id. * @param {String} id The id of the Record to find. * @return {Ext.data.Model/undefined} The Record with the passed id. Returns `undefined` if not found. */ getById: function(id) { return this.data.findBy(function(record) { return record.getId() == id; }); }, /** * Get the index within the cache of the passed Record. * @param {Ext.data.Model} record The Ext.data.Model object to find. * @return {Number} The index of the passed Record. Returns -1 if not found. */ indexOf: function(record) { return this.data.indexOf(record); }, /** * Get the index within the cache of the Record with the passed id. * @param {String} id The id of the Record to find. * @return {Number} The index of the Record. Returns -1 if not found. */ indexOfId: function(id) { return this.data.indexOfKey(id); }, /** * @private * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to. * @param {Ext.data.Model} record The model instance that was edited. * @param {String[]} modifiedFieldNames Array of field names changed during edit. * @param {Object} modified */ afterEdit: function(record, modifiedFieldNames, modified) { var me = this, data = me.data, currentId = modified[record.getIdProperty()] || record.getId(), currentIndex = data.keys.indexOf(currentId), newIndex; if (currentIndex === -1 && data.map[currentId] === undefined) { return; } if (me.getAutoSync()) { me.sync(); } if (currentId !== record.getId()) { data.replace(currentId, record); } else { data.replace(record); } newIndex = data.indexOf(record); if (currentIndex === -1 && newIndex !== -1) { me.fireEvent('addrecords', me, [record]); } else if (currentIndex !== -1 && newIndex === -1) { me.fireEvent('removerecords', me, [record], [currentIndex]); } else if (newIndex !== -1) { me.fireEvent('updaterecord', me, record, newIndex, currentIndex, modifiedFieldNames, modified); } }, /** * @private * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to. * @param {Ext.data.Model} record The model instance that was edited. */ afterReject: function(record) { var index = this.data.indexOf(record); this.fireEvent('updaterecord', this, record, index, index, [], {}); }, /** * @private * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to. * @param {Ext.data.Model} record The model instance that was edited. * @param {String[]} modifiedFieldNames * @param {Object} modified */ afterCommit: function(record, modifiedFieldNames, modified) { var me = this, data = me.data, currentId = modified[record.getIdProperty()] || record.getId(), currentIndex = data.keys.indexOf(currentId), newIndex; if (currentIndex === -1 && data.map[currentId] === undefined) { return; } if (currentId !== record.getId()) { data.replace(currentId, record); } else { data.replace(record); } newIndex = data.indexOf(record); if (currentIndex === -1 && newIndex !== -1) { me.fireEvent('addrecords', me, [record]); } else if (currentIndex !== -1 && newIndex === -1) { me.fireEvent('removerecords', me, [record], [currentIndex]); } else if (newIndex !== -1) { me.fireEvent('updaterecord', me, record, newIndex, currentIndex, modifiedFieldNames, modified); } }, /** * This gets called by a record after is gets erased from the server. * @param record * @private */ afterErase: function(record) { var me = this, data = me.data, index = data.indexOf(record); if (index !== -1) { data.remove(record); me.fireEvent('removerecords', me, [record], [index]); } }, applyRemoteFilter: function(value) { var proxy = this.getProxy(); return value || (proxy && proxy.isSQLProxy === true); }, applyRemoteSort: function(value) { var proxy = this.getProxy(); return value || (proxy && proxy.isSQLProxy === true); }, applyRemoteGroup: function(value) { var proxy = this.getProxy(); return value || (proxy && proxy.isSQLProxy === true); }, updateRemoteFilter: function(remoteFilter) { this.data.setAutoFilter(!remoteFilter); }, updateRemoteSort: function(remoteSort) { this.data.setAutoSort(!remoteSort); }, /** * Sorts the data in the Store by one or more of its properties. Example usage: * * // sort by a single field * myStore.sort('myField', 'DESC'); * * // sorting by multiple fields * myStore.sort([ * { * property : 'age', * direction: 'ASC' * }, * { * property : 'name', * direction: 'DESC' * } * ]); * * Internally, Store converts the passed arguments into an array of {@link Ext.util.Sorter} instances, and delegates * the actual sorting to its internal {@link Ext.util.Collection}. * * When passing a single string argument to sort, Store maintains a ASC/DESC toggler per field, so this code: * * store.sort('myField'); * store.sort('myField'); * * is equivalent to this code: * * store.sort('myField', 'ASC'); * store.sort('myField', 'DESC'); * * because Store handles the toggling automatically. * * If the {@link #remoteSort} configuration has been set to `true`, you will have to manually call the {@link #method-load} * method after you sort to retrieve the sorted data from the server. * * @param {String/Ext.util.Sorter[]} sorters Either a string name of one of the fields in this Store's configured * {@link Ext.data.Model Model}, or an array of sorter configurations. * @param {String} [defaultDirection=ASC] The default overall direction to sort the data by. * @param {String} where (Optional) This can be either `'prepend'` or `'append'`. If you leave this undefined * it will clear the current sorters. */ sort: function(sorters, defaultDirection, where) { var data = this.data, grouper = this.getGrouper(), autoSort = data.getAutoSort(); if (sorters) { // While we are adding sorters we don't want to sort right away // since we need to update sortTypes on the sorters. data.setAutoSort(false); if (typeof where === 'string') { if (where == 'prepend') { data.insertSorters(grouper ? 1 : 0, sorters, defaultDirection); } else { data.addSorters(sorters, defaultDirection); } } else { data.setSorters(null); if (grouper) { data.addSorters(grouper); } data.addSorters(sorters, defaultDirection); } this.updateSortTypes(); // Setting back autoSort to true (if it was like that before) will // instantly sort the data again. data.setAutoSort(autoSort); } if (!this.getRemoteSort()) { // If we haven't added any new sorters we have to manually call sort if (!sorters) { this.data.sort(); } this.fireEvent('sort', this, this.data, this.data.getSorters()); if (data.length) { this.fireEvent('refresh', this, this.data); } } }, /** * Filters the loaded set of records by a given set of filters. * * Filtering by single field: * * store.filter("email", /\.com$/); * * Using multiple filters: * * store.filter([ * {property: "email", value: /\.com$/}, * {filterFn: function(item) { return item.get("age") > 10; }} * ]); * * Using Ext.util.Filter instances instead of config objects * (note that we need to specify the {@link Ext.util.Filter#root root} config option in this case): * * store.filter([ * Ext.create('Ext.util.Filter', {property: "email", value: /\.com$/, root: 'data'}), * Ext.create('Ext.util.Filter', {filterFn: function(item) { return item.get("age") > 10; }, root: 'data'}) * ]); * * If the {@link #remoteFilter} configuration has been set to `true`, you will have to manually call the {@link #method-load} * method after you filter to retrieve the filtered data from the server. * * @param {Object[]/Ext.util.Filter[]/String} filters The set of filters to apply to the data. * These are stored internally on the store, but the filtering itself is done on the Store's * {@link Ext.util.MixedCollection MixedCollection}. See MixedCollection's * {@link Ext.util.MixedCollection#filter filter} method for filter syntax. * Alternatively, pass in a property string. * @param {String} [value] value to filter by (only if using a property string as the first argument). * @param {Boolean} [anyMatch=false] `true` to allow any match, false to anchor regex beginning with `^`. * @param {Boolean} [caseSensitive=false] `true` to make the filtering regex case sensitive. */ filter: function(property, value, anyMatch, caseSensitive) { var data = this.data, filter = null; if (property) { if (Ext.isFunction(property)) { filter = {filterFn: property}; } else if (Ext.isArray(property) || property.isFilter) { filter = property; } else { filter = { property : property, value : value, anyMatch : anyMatch, caseSensitive: caseSensitive, id : property }; } } if (this.getRemoteFilter()) { data.addFilters(filter); } else { data.filter(filter); this.fireEvent('filter', this, data, data.getFilters()); this.fireEvent('refresh', this, data); } }, /** * Filter by a function. The specified function will be called for each * Record in this Store. If the function returns `true` the Record is included, * otherwise it is filtered out. * @param {Function} fn The function to be called. It will be passed the following parameters: * @param {Ext.data.Model} fn.record The {@link Ext.data.Model record} * to test for filtering. Access field values using {@link Ext.data.Model#get}. * @param {Object} fn.id The ID of the Record passed. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. Defaults to this Store. */ filterBy: function(fn, scope) { var me = this, data = me.data, ln = data.length; data.filter({ filterFn: function(record) { return fn.call(scope || me, record, record.getId()); } }); this.fireEvent('filter', this, data, data.getFilters()); if (data.length !== ln) { this.fireEvent('refresh', this, data); } }, /** * Query the cached records in this Store using a filtering function. The specified function * will be called with each record in this Store. If the function returns `true` the record is * included in the results. * @param {Function} fn The function to be called. It will be passed the following parameters: * @param {Ext.data.Model} fn.record The {@link Ext.data.Model record} * to test for filtering. Access field values using {@link Ext.data.Model#get}. * @param {Object} fn.id The ID of the Record passed. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. Defaults to this Store. * @return {Ext.util.MixedCollection} Returns an Ext.util.MixedCollection of the matched records. */ queryBy: function(fn, scope) { return this.data.filterBy(fn, scope || this); }, /** * Reverts to a view of the Record cache with no filtering applied. * @param {Boolean} [suppressEvent=false] `true` to clear silently without firing the `refresh` event. */ clearFilter: function(suppressEvent) { var ln = this.data.length; if (suppressEvent) { this.suspendEvents(); } this.data.setFilters(null); if (suppressEvent) { this.resumeEvents(true); } else if (ln !== this.data.length) { this.fireEvent('refresh', this, this.data); } }, /** * Returns `true` if this store is currently filtered. * @return {Boolean} */ isFiltered : function () { return this.data.filtered; }, /** * Returns `true` if this store is currently sorted. * @return {Boolean} */ isSorted : function () { return this.data.sorted; }, getSorters: function() { var sorters = this.data.getSorters(); return (sorters) ? sorters.items : []; }, getFilters: function() { var filters = this.data.getFilters(); return (filters) ? filters.items : []; }, /** * Returns an array containing the result of applying the grouper to the records in this store. See {@link #groupField}, * {@link #groupDir} and {@link #grouper}. Example for a store containing records with a color field: * * var myStore = Ext.create('Ext.data.Store', { * groupField: 'color', * groupDir : 'DESC' * }); * * myStore.getGroups(); //returns: * [ * { * name: 'yellow', * children: [ * //all records where the color field is 'yellow' * ] * }, * { * name: 'red', * children: [ * //all records where the color field is 'red' * ] * } * ] * * @param {String} groupName (Optional) Pass in an optional `groupName` argument to access a specific group as defined by {@link #grouper}. * @return {Object/Object[]} The grouped data. */ getGroups: function(requestGroupString) { var records = this.data.items, length = records.length, grouper = this.getGrouper(), groups = [], pointers = {}, record, groupStr, group, i; // <debug> if (!grouper) { Ext.Logger.error('Trying to get groups for a store that has no grouper'); } // </debug> for (i = 0; i < length; i++) { record = records[i]; groupStr = grouper.getGroupString(record); group = pointers[groupStr]; if (group === undefined) { group = { name: groupStr, children: [] }; groups.push(group); pointers[groupStr] = group; } group.children.push(record); } return requestGroupString ? pointers[requestGroupString] : groups; }, /** * @param record * @return {null} */ getGroupString: function(record) { var grouper = this.getGrouper(); if (grouper) { return grouper.getGroupString(record); } return null; }, /** * Finds the index of the first matching Record in this store by a specific field value. * @param {String} fieldName The name of the Record field to test. * @param {String/RegExp} value Either a string that the field value * should begin with, or a RegExp to test against the field. * @param {Number} startIndex (optional) The index to start searching at. * @param {Boolean} anyMatch (optional) `true` to match any part of the string, not just the beginning. * @param {Boolean} caseSensitive (optional) `true` for case sensitive comparison. * @param {Boolean} [exactMatch=false] (optional) `true` to force exact match (^ and $ characters added to the regex). * @return {Number} The matched index or -1 */ find: function(fieldName, value, startIndex, anyMatch, caseSensitive, exactMatch) { var filter = Ext.create('Ext.util.Filter', { property: fieldName, value: value, anyMatch: anyMatch, caseSensitive: caseSensitive, exactMatch: exactMatch, root: 'data' }); return this.data.findIndexBy(filter.getFilterFn(), null, startIndex); }, /** * Finds the first matching Record in this store by a specific field value. * @param {String} fieldName The name of the Record field to test. * @param {String/RegExp} value Either a string that the field value * should begin with, or a RegExp to test against the field. * @param {Number} startIndex (optional) The index to start searching at. * @param {Boolean} anyMatch (optional) `true` to match any part of the string, not just the beginning. * @param {Boolean} caseSensitive (optional) `true` for case sensitive comparison. * @param {Boolean} [exactMatch=false] (optional) `true` to force exact match (^ and $ characters added to the regex). * @return {Ext.data.Model} The matched record or `null`. */ findRecord: function() { var me = this, index = me.find.apply(me, arguments); return index !== -1 ? me.getAt(index) : null; }, /** * Finds the index of the first matching Record in this store by a specific field value. * @param {String} fieldName The name of the Record field to test. * @param {Object} value The value to match the field against. * @param {Number} startIndex (optional) The index to start searching at. * @return {Number} The matched index or -1. */ findExact: function(fieldName, value, startIndex) { return this.data.findIndexBy(function(record) { return record.get(fieldName) === value; }, this, startIndex); }, /** * Find the index of the first matching Record in this Store by a function. * If the function returns `true` it is considered a match. * @param {Function} fn The function to be called. It will be passed the following parameters: * @param {Ext.data.Model} fn.record The {@link Ext.data.Model record} * to test for filtering. Access field values using {@link Ext.data.Model#get}. * @param {Object} fn.id The ID of the Record passed. * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. Defaults to this Store. * @param {Number} startIndex (optional) The index to start searching at. * @return {Number} The matched index or -1. */ findBy: function(fn, scope, startIndex) { return this.data.findIndexBy(fn, scope, startIndex); }, /** * Loads data into the Store via the configured {@link #proxy}. This uses the Proxy to make an * asynchronous call to whatever storage backend the Proxy uses, automatically adding the retrieved * instances into the Store and calling an optional callback if required. Example usage: * * store.load({ * callback: function(records, operation, success) { * // the {@link Ext.data.Operation operation} object contains all of the details of the load operation * console.log(records); * }, * scope: this * }); * * If only the callback and scope options need to be specified, then one can call it simply like so: * * store.load(function(records, operation, success) { * console.log('loaded records'); * }, this); * * @param {Object/Function} [options] config object, passed into the {@link Ext.data.Operation} object before loading. * @param {Object} [scope] Scope for the function. * @return {Object} */ load: function(options, scope) { var me = this, operation, currentPage = me.currentPage, pageSize = me.getPageSize(); options = options || {}; if (Ext.isFunction(options)) { options = { callback: options, scope: scope || this }; } if (me.getRemoteSort()) { options.sorters = options.sorters || this.getSorters(); } if (me.getRemoteFilter()) { options.filters = options.filters || this.getFilters(); } if (me.getRemoteGroup()) { options.grouper = options.grouper || this.getGrouper(); } Ext.applyIf(options, { page: currentPage, start: (currentPage - 1) * pageSize, limit: pageSize, addRecords: false, action: 'read', model: this.getModel() }); operation = Ext.create('Ext.data.Operation', options); if (me.fireEvent('beforeload', me, operation) !== false) { me.loading = true; me.getProxy().read(operation, me.onProxyLoad, me); } return me; }, /** * Returns `true` if the Store is currently performing a load operation. * @return {Boolean} `true` if the Store is currently loading. */ isLoading: function() { return Boolean(this.loading); }, /** * Returns `true` if the Store has been loaded. * @return {Boolean} `true` if the Store has been loaded. */ isLoaded: function() { return Boolean(this.loaded); }, /** * Synchronizes the Store with its Proxy. This asks the Proxy to batch together any new, updated * and deleted records in the store, updating the Store's internal representation of the records * as each operation completes. * @return {Object} * @return {Object} return.added * @return {Object} return.updated * @return {Object} return.removed */ sync: function() { var me = this, operations = {}, toCreate = me.getNewRecords(), toUpdate = me.getUpdatedRecords(), toDestroy = me.getRemovedRecords(), needsSync = false; if (toCreate.length > 0) { operations.create = toCreate; needsSync = true; } if (toUpdate.length > 0) { operations.update = toUpdate; needsSync = true; } if (toDestroy.length > 0) { operations.destroy = toDestroy; needsSync = true; } if (needsSync && me.fireEvent('beforesync', this, operations) !== false) { me.getProxy().batch({ operations: operations, listeners: me.getBatchListeners() }); } return { added: toCreate, updated: toUpdate, removed: toDestroy }; }, /** * Convenience function for getting the first model instance in the store. * @return {Ext.data.Model/undefined} The first model instance in the store, or `undefined`. */ first: function() { return this.data.first(); }, /** * Convenience function for getting the last model instance in the store. * @return {Ext.data.Model/undefined} The last model instance in the store, or `undefined`. */ last: function() { return this.data.last(); }, /** * Sums the value of `property` for each {@link Ext.data.Model record} between `start` * and `end` and returns the result. * @param {String} field The field in each record. * @return {Number} The sum. */ sum: function(field) { var total = 0, i = 0, records = this.data.items, len = records.length; for (; i < len; ++i) { total += records[i].get(field); } return total; }, /** * Gets the minimum value in the store. * @param {String} field The field in each record. * @return {Object/undefined} The minimum value, if no items exist, `undefined`. */ min: function(field) { var i = 1, records = this.data.items, len = records.length, value, min; if (len > 0) { min = records[0].get(field); } for (; i < len; ++i) { value = records[i].get(field); if (value < min) { min = value; } } return min; }, /** * Gets the maximum value in the store. * @param {String} field The field in each record. * @return {Object/undefined} The maximum value, if no items exist, `undefined`. */ max: function(field) { var i = 1, records = this.data.items, len = records.length, value, max; if (len > 0) { max = records[0].get(field); } for (; i < len; ++i) { value = records[i].get(field); if (value > max) { max = value; } } return max; }, /** * Gets the average value in the store. * @param {String} field The field in each record you want to get the average for. * @return {Number} The average value, if no items exist, 0. */ average: function(field) { var i = 0, records = this.data.items, len = records.length, sum = 0; if (records.length > 0) { for (; i < len; ++i) { sum += records[i].get(field); } return sum / len; } return 0; }, /** * @private * Returns an object which is passed in as the listeners argument to `proxy.batch` inside `this.sync`. * This is broken out into a separate function to allow for customization of the listeners. * @return {Object} The listeners object. * @return {Object} return.scope * @return {Object} return.exception * @return {Object} return.complete */ getBatchListeners: function() { return { scope: this, exception: this.onBatchException, complete: this.onBatchComplete }; }, /** * @private * Attached as the `complete` event listener to a proxy's Batch object. Iterates over the batch operations * and updates the Store's internal data MixedCollection. */ onBatchComplete: function(batch) { var me = this, operations = batch.operations, length = operations.length, i; for (i = 0; i < length; i++) { me.onProxyWrite(operations[i]); } }, onBatchException: function(batch, operation) { // //decide what to do... could continue with the next operation // batch.start(); // // //or retry the last operation // batch.retry(); }, /** * @private * Called internally when a Proxy has completed a load request. */ onProxyLoad: function(operation) { var me = this, records = operation.getRecords(), resultSet = operation.getResultSet(), successful = operation.wasSuccessful(); if (resultSet) { me.setTotalCount(resultSet.getTotal()); } if (successful) { this.fireAction('datarefresh', [this, this.data, operation], 'doDataRefresh'); } me.loaded = true; me.loading = false; me.fireEvent('load', this, records, successful, operation); //this is a callback that would have been passed to the 'read' function and is optional Ext.callback(operation.getCallback(), operation.getScope() || me, [records, operation, successful]); }, doDataRefresh: function(store, data, operation) { var records = operation.getRecords(), me = this, destroyRemovedRecords = me.getDestroyRemovedRecords(), currentRecords = data.all.slice(), ln = currentRecords.length, ln2 = records.length, ids = {}, i, record; if (operation.getAddRecords() !== true) { for (i = 0; i < ln2; i++) { ids[records[i].id] = true; } for (i = 0; i < ln; i++) { record = currentRecords[i]; record.unjoin(me); // If the record we are removing is not part of the records we are about to add to the store then handle // the destroying or removing of the record to avoid memory leaks. if (ids[record.id] !== true && destroyRemovedRecords && !record.stores.length) { record.destroy(); } } data.clear(); // This means we have to fire a clear event though me.fireEvent('clear', me); } if (records && records.length) { // Now lets add the records without firing an addrecords event me.suspendEvents(); me.add(records); me.resumeEvents(true); // true to discard the queue } me.fireEvent('refresh', me, data); }, /** * @private * Callback for any write Operation over the Proxy. Updates the Store's MixedCollection to reflect * the updates provided by the Proxy. */ onProxyWrite: function(operation) { var me = this, success = operation.wasSuccessful(), records = operation.getRecords(); switch (operation.getAction()) { case 'create': me.onCreateRecords(records, operation, success); break; case 'update': me.onUpdateRecords(records, operation, success); break; case 'destroy': me.onDestroyRecords(records, operation, success); break; } if (success) { me.fireEvent('write', me, operation); } //this is a callback that would have been passed to the 'create', 'update' or 'destroy' function and is optional Ext.callback(operation.getCallback(), operation.getScope() || me, [records, operation, success]); }, // These methods are now just template methods since updating the records etc is all taken care of // by the operation itself. onCreateRecords: function(records, operation, success) {}, onUpdateRecords: function(records, operation, success) {}, onDestroyRecords: function(records, operation, success) { this.removed = []; }, onMetaChange: function(data) { var model = this.getProxy().getModel(); if (!this.getModel() && model) { this.setModel(model); } /** * @event metachange * Fires whenever the server has sent back new metadata to reconfigure the Reader. * @param {Ext.data.Store} this * @param {Object} data The metadata sent back from the server. */ this.fireEvent('metachange', this, data); }, /** * Returns all Model instances that are either currently a phantom (e.g. have no id), or have an ID but have not * yet been saved on this Store (this happens when adding a non-phantom record from another Store into this one). * @return {Ext.data.Model[]} The Model instances. */ getNewRecords: function() { return this.data.filterBy(function(item) { // only want phantom records that are valid return item.phantom === true && item.isValid(); }).items; }, /** * Returns all Model instances that have been updated in the Store but not yet synchronized with the Proxy. * @return {Ext.data.Model[]} The updated Model instances. */ getUpdatedRecords: function() { return this.data.filterBy(function(item) { // only want dirty records, not phantoms that are valid return item.dirty === true && item.phantom !== true && item.isValid(); }).items; }, /** * Returns any records that have been removed from the store but not yet destroyed on the proxy. * @return {Ext.data.Model[]} The removed Model instances. */ getRemovedRecords: function() { return this.removed; }, // PAGING METHODS /** * Loads a given 'page' of data by setting the start and limit values appropriately. Internally this just causes a normal * load operation, passing in calculated `start` and `limit` params. * @param {Number} page The number of the page to load. * @param {Object} options See options for {@link #method-load}. * @param scope */ loadPage: function(page, options, scope) { if (typeof options === 'function') { options = { callback: options, scope: scope || this }; } var me = this, pageSize = me.getPageSize(), clearOnPageLoad = me.getClearOnPageLoad(); options = Ext.apply({}, options); me.currentPage = page; me.load(Ext.applyIf(options, { page: page, start: (page - 1) * pageSize, limit: pageSize, addRecords: !clearOnPageLoad })); }, /** * Loads the next 'page' in the current data set. * @param {Object} options See options for {@link #method-load}. */ nextPage: function(options) { this.loadPage(this.currentPage + 1, options); }, /** * Loads the previous 'page' in the current data set. * @param {Object} options See options for {@link #method-load}. */ previousPage: function(options) { this.loadPage(this.currentPage - 1, options); }, destroy: function() { this.clearData(); var proxy = this.getProxy(); if (proxy) { proxy.onDestroy(); } Ext.data.StoreManager.unregister(this); if (this.implicitModel && this.getModel()) { delete Ext.data.ModelManager.types[this.getModel().getName()]; } Ext.destroy(this.data); this.callParent(arguments); } // <deprecated product=touch since=2.0> ,onClassExtended: function(cls, data) { var prototype = this.prototype, defaultConfig = prototype.config, config = data.config || {}, key; // Convert deprecated properties in application into a config object for (key in defaultConfig) { if (key != "control" && key in data) { config[key] = data[key]; delete data[key]; // <debug warn> Ext.Logger.deprecate(key + ' is deprecated as a property directly on the ' + this.$className + ' prototype. Please put it inside the config object.'); // </debug> } } data.config = config; } }, function() { /** * Loads an array of data straight into the Store. * @param {Ext.data.Model[]/Object[]} data Array of data to load. Any non-model instances will be cast into model instances first. * @param {Boolean} append `true` to add the records to the existing records in the store, `false` to remove the old ones first. * @deprecated 2.0 Please use #add or #setData instead. * @method loadData */ this.override({ loadData: function(data, append) { Ext.Logger.deprecate("loadData is deprecated, please use either add or setData"); if (append) { this.add(data); } else { this.setData(data); } }, //@private doAddListener: function(name, fn, scope, options, order) { // <debug> switch(name) { case 'update': Ext.Logger.warn('The update event on Store has been removed. Please use the updaterecord event from now on.'); return this; case 'add': Ext.Logger.warn('The add event on Store has been removed. Please use the addrecords event from now on.'); return this; case 'remove': Ext.Logger.warn('The remove event on Store has been removed. Please use the removerecords event from now on.'); return this; case 'datachanged': Ext.Logger.warn('The datachanged event on Store has been removed. Please use the refresh event from now on.'); return this; break; } // </debug> return this.callParent(arguments); } }); /** * @member Ext.data.Store * @method loadRecords * @inheritdoc Ext.data.Store#add * @deprecated 2.0.0 Please use {@link #add} instead. */ Ext.deprecateMethod(this, 'loadRecords', 'add', "Ext.data.Store#loadRecords has been deprecated. Please use the add method."); // </deprecated> });
import React, { useRef, useEffect } from 'react'; import styles from './Page.module.scss'; type Props = { title?: string, children: React.Node }; const Page = ({ title, children }: Props) => { const pageRef = useRef(); useEffect(() => { pageRef.current.scrollIntoView(); }); return ( <div ref={pageRef} className={styles['page']}> <div className={styles['page__inner']}> { title && <h1 className={styles['page__title']}>{title}</h1>} <div className={styles['page__body']}> {children} </div> </div> </div> ); }; export default Page;
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'selectall', 'fo', { toolbar: 'Markera alt' } );
(function () { 'use strict'; angular.module('com.module.users') .run(function ($rootScope, gettextCatalog) { $rootScope.addMenu(gettextCatalog.getString('Users'), 'app.users.list', 'fa-user'); }); })();
/** * @author mrdoob / http://mrdoob.com/ */ THREE.GLTFLoader = function ( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; THREE.GLTFLoader.prototype = { constructor: THREE.GLTFLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.XHRLoader( scope.manager ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); }, onProgress, onError ); }, setCrossOrigin: function ( value ) { this.crossOrigin = value; }, parse: function ( json ) { function stringToArrayBuffer( string ) { var bytes = atob( string ); var buffer = new ArrayBuffer( bytes.length ); var bufferView = new Uint8Array( buffer ); for ( var i = 0; i < bytes.length; i ++ ) { bufferView[ i ] = bytes.charCodeAt( i ); } return buffer; } console.time( 'GLTFLoader' ); var library = { buffers: {}, bufferViews: {}, accessors: {}, textures: {}, materials: {}, meshes: {}, nodes: {}, scenes: {} }; // buffers var buffers = json.buffers; for ( var bufferId in buffers ) { var buffer = buffers[ bufferId ]; if ( buffer.type === 'arraybuffer' ) { var header = 'data:application/octet-stream;base64,'; if ( buffer.uri.indexOf( header ) === 0 ) { library.buffers[ bufferId ] = stringToArrayBuffer( buffer.uri.substr( header.length ) ); } } } // buffer views var bufferViews = json.bufferViews; for ( var bufferViewId in bufferViews ) { var bufferView = bufferViews[ bufferViewId ]; var arraybuffer = library.buffers[ bufferView.buffer ]; library.bufferViews[ bufferViewId ] = arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + bufferView.byteLength ); } // accessors var COMPONENT_TYPES = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array, }; var TYPE_SIZES = { 'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4, 'MAT2': 4, 'MAT3': 9, 'MAT4': 16 }; var accessors = json.accessors; for ( var accessorId in accessors ) { var accessor = accessors[ accessorId ]; var arraybuffer = library.bufferViews[ accessor.bufferView ]; var itemSize = TYPE_SIZES[ accessor.type ]; var TypedArray = COMPONENT_TYPES[ accessor.componentType ]; var array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize ); library.accessors[ accessorId ] = new THREE.BufferAttribute( array, itemSize ); } // textures var FILTERS = { 9728: THREE.NearestFilter, 9729: THREE.LinearFilter, 9984: THREE.NearestMipMapNearestFilter, 9985: THREE.LinearMipMapNearestFilter, 9986: THREE.NearestMipMapLinearFilter, 9987: THREE.LinearMipMapLinearFilter }; var WRAPPINGS = { 33071: THREE.ClampToEdgeWrapping, 33648: THREE.MirroredRepeatWrapping, 10497: THREE.RepeatWrapping }; var textures = json.textures; for ( var textureId in textures ) { var texture = textures[ textureId ]; var _texture = new THREE.Texture(); _texture.flipY = false; if ( texture.source ) { var source = json.images[ texture.source ]; _texture.image = new Image(); _texture.image.src = source.uri; _texture.needsUpdate = true; } if ( texture.sampler ) { var sampler = json.samplers[ texture.sampler ]; _texture.magFilter = FILTERS[ sampler.magFilter ]; _texture.minFilter = FILTERS[ sampler.minFilter ]; _texture.wrapS = WRAPPINGS[ sampler.wrapS ]; _texture.wrapT = WRAPPINGS[ sampler.wrapT ]; } library.textures[ textureId ] = _texture; } // materials var materials = json.materials; for ( var materialId in materials ) { var material = materials[ materialId ]; var _material = new THREE.MeshPhongMaterial(); _material.name = material.name; var values = material.values; if ( Array.isArray( values.diffuse ) ) { _material.color.fromArray( values.diffuse ); } else if ( typeof( values.diffuse ) === 'string' ) { _material.map = library.textures[ values.diffuse ]; } if ( Array.isArray( values.emission ) ) _material.emissive.fromArray( values.emission ); if ( Array.isArray( values.specular ) ) _material.specular.fromArray( values.specular ); if ( values.shininess !== undefined ) _material.shininess = values.shininess; library.materials[ materialId ] = _material; } // meshes var meshes = json.meshes; for ( var meshId in meshes ) { var mesh = meshes[ meshId ]; var group = new THREE.Group(); group.name = mesh.name; var primitives = mesh.primitives; for ( var i = 0; i < primitives.length; i ++ ) { var primitive = primitives[ i ]; var attributes = primitive.attributes; var geometry = new THREE.BufferGeometry(); if ( primitive.indices ) { geometry.setIndex( library.accessors[ primitive.indices ] ); } for ( var attributeId in attributes ) { var attribute = attributes[ attributeId ]; var bufferAttribute = library.accessors[ attribute ]; switch ( attributeId ) { case 'POSITION': geometry.addAttribute( 'position', bufferAttribute ); break; case 'NORMAL': geometry.addAttribute( 'normal', bufferAttribute ); break; case 'TEXCOORD_0': geometry.addAttribute( 'uv', bufferAttribute ); break; } } var material = library.materials[ primitive.material ]; group.add( new THREE.Mesh( geometry, material ) ); } library.meshes[ meshId ] = group; } // nodes var nodes = json.nodes; var matrix = new THREE.Matrix4(); for ( var nodeId in nodes ) { var node = nodes[ nodeId ]; var object = new THREE.Group(); object.name = node.name; if ( node.translation !== undefined ) { object.position.fromArray( node.translation ); } if ( node.rotation !== undefined ) { object.quaternion.fromArray( node.rotation ); } if ( node.scale !== undefined ) { object.scale.fromArray( node.scale ); } if ( node.matrix !== undefined ) { matrix.fromArray( node.matrix ); matrix.decompose( object.position, object.quaternion, object.scale ); } if ( node.meshes !== undefined ) { for ( var i = 0; i < node.meshes.length; i ++ ) { var meshId = node.meshes[ i ]; var group = library.meshes[ meshId ]; object.add( group.clone() ); } } library.nodes[ nodeId ] = object; } for ( var nodeId in nodes ) { var node = nodes[ nodeId ]; for ( var i = 0; i < node.children.length; i ++ ) { var child = node.children[ i ]; library.nodes[ nodeId ].add( library.nodes[ child ] ); } } // scenes var scenes = json.scenes; for ( var sceneId in scenes ) { var scene = scenes[ sceneId ]; var container = new THREE.Scene(); for ( var i = 0; i < scene.nodes.length; i ++ ) { var node = scene.nodes[ i ]; container.add( library.nodes[ node ] ); } library.scenes[ sceneId ] = container; } console.timeEnd( 'GLTFLoader' ); return { scene: library.scenes[ json.scene ] }; } };
Template.postsUpdate.events = { 'click #btnSave': function(e, t) { e.preventDefault(); Router.current()._post = true; Router.current().update(t); Router.current()._post = false; }, };
version https://git-lfs.github.com/spec/v1 oid sha256:bd106e80c0b1b3e195253b78fbf5ec70ee6bcdd03771332574beed7927d38e95 size 3501
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/Regular/Main.js * * Copyright (c) 2009-2016 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral'] = { directory: 'General/Regular', family: 'STIXGeneral', Ranges: [ [0xA0,0xFF,"Latin1Supplement"], [0x100,0x17F,"LatinExtendedA"], [0x180,0x24F,"LatinExtendedB"], [0x250,0x2AF,"IPAExtensions"], [0x2B0,0x2FF,"SpacingModLetters"], [0x300,0x36F,"CombDiacritMarks"], [0x370,0x3FF,"GreekAndCoptic"], [0x400,0x4FF,"Cyrillic"], [0x1D00,0x1DBF,"PhoneticExtensions"], [0x1E00,0x1EFF,"LatinExtendedAdditional"], [0x2000,0x206F,"GeneralPunctuation"], [0x2070,0x209F,"SuperAndSubscripts"], [0x20A0,0x20CF,"CurrencySymbols"], [0x20D0,0x20FF,"CombDiactForSymbols"], [0x2100,0x214F,"LetterlikeSymbols"], [0x2150,0x218F,"NumberForms"], [0x2190,0x21FF,"Arrows"], [0x2200,0x22FF,"MathOperators"], [0x2300,0x23FF,"MiscTechnical"], [0x2400,0x243F,"ControlPictures"], [0x2460,0x24FF,"EnclosedAlphanum"], [0x2500,0x257F,"BoxDrawing"], [0x2580,0x259F,"BlockElements"], [0x25A0,0x25FF,"GeometricShapes"], [0x2600,0x26FF,"MiscSymbols"], [0x2700,0x27BF,"Dingbats"], [0x27C0,0x27EF,"MiscMathSymbolsA"], [0x27F0,0x27FF,"SupplementalArrowsA"], [0x2900,0x297F,"SupplementalArrowsB"], [0x2980,0x29FF,"MiscMathSymbolsB"], [0x2A00,0x2AFF,"SuppMathOperators"], [0x2B00,0x2BFF,"MiscSymbolsAndArrows"], [0x3000,0x303F,"CJK"], [0x3040,0x309F,"Hiragana"], [0xA720,0xA7FF,"LatinExtendedD"], [0xFB00,0xFB4F,"AlphaPresentForms"], [0xFFF0,0xFFFF,"Specials"], [0x1D400,0x1D433,"MathBold"], [0x1D434,0x1D467,"MathItalic"], [0x1D468,0x1D49B,"MathBoldItalic"], [0x1D49C,0x1D4CF,"MathScript"], [0x1D4D0,0x1D503,"MathBoldScript"], [0x1D504,0x1D537,"Fraktur"], [0x1D538,0x1D56B,"BBBold"], [0x1D56C,0x1D59F,"BoldFraktur"], [0x1D5A0,0x1D5D3,"MathSS"], [0x1D5D4,0x1D607,"MathSSBold"], [0x1D608,0x1D63B,"MathSSItalic"], [0x1D63C,0x1D66F,"MathSSItalicBold"], [0x1D670,0x1D6A3,"MathTT"], [0x1D6A4,0x1D6A5,"ij"], [0x1D6A8,0x1D6E1,"GreekBold"], [0x1D6E2,0x1D71B,"GreekItalic"], [0x1D71C,0x1D755,"GreekBoldItalic"], [0x1D756,0x1D78F,"GreekSSBold"], [0x1D790,0x1D7C9,"GreekSSBoldItalic"], [0x1D7CE,0x1D7D7,"MathBold"], [0x1D7D8,0x1D7E1,"BBBold"], [0x1D7E2,0x1D7EB,"MathSS"], [0x1D7EC,0x1D7F6,"MathSSBold"], [0x1D7F6,0x1D7FF,"MathTT"] ], 0x20: [0,0,250,0,0], // SPACE 0x21: [676,9,333,130,236], // EXCLAMATION MARK 0x22: [676,-431,408,77,331], // QUOTATION MARK 0x23: [662,0,500,6,495], // NUMBER SIGN 0x24: [727,87,500,44,458], // DOLLAR SIGN 0x25: [706,19,747,61,686], // PERCENT SIGN 0x26: [676,13,778,42,750], // AMPERSAND 0x27: [676,-431,180,48,133], // APOSTROPHE 0x28: [676,177,333,48,304], // LEFT PARENTHESIS 0x29: [676,177,333,29,285], // RIGHT PARENTHESIS 0x2A: [676,-265,500,68,433], // ASTERISK 0x2B: [547,41,685,48,636], // PLUS SIGN 0x2C: [102,141,250,55,195], // COMMA 0x2D: [257,-194,333,39,285], // HYPHEN-MINUS 0x2E: [100,11,250,70,181], // FULL STOP 0x2F: [676,14,278,-9,287], // SOLIDUS 0x30: [676,14,500,24,476], // DIGIT ZERO 0x31: [676,0,500,111,394], // DIGIT ONE 0x32: [676,0,500,29,474], // DIGIT TWO 0x33: [676,14,500,41,431], // DIGIT THREE 0x34: [676,0,500,12,473], // DIGIT FOUR 0x35: [688,14,500,31,438], // DIGIT FIVE 0x36: [684,14,500,34,468], // DIGIT SIX 0x37: [662,8,500,20,449], // DIGIT SEVEN 0x38: [676,14,500,56,445], // DIGIT EIGHT 0x39: [676,22,500,30,459], // DIGIT NINE 0x3A: [459,11,278,81,192], // COLON 0x3B: [459,141,278,80,219], // SEMICOLON 0x3C: [534,24,685,56,621], // LESS-THAN SIGN 0x3D: [386,-120,685,48,637], // EQUALS SIGN 0x3E: [534,24,685,56,621], // GREATER-THAN SIGN 0x3F: [676,8,444,68,414], // QUESTION MARK 0x40: [676,14,921,116,809], // COMMERCIAL AT 0x41: [674,0,722,15,707], // LATIN CAPITAL LETTER A 0x42: [662,0,667,17,593], // LATIN CAPITAL LETTER B 0x43: [676,14,667,28,633], // LATIN CAPITAL LETTER C 0x44: [662,0,722,16,685], // LATIN CAPITAL LETTER D 0x45: [662,0,611,12,597], // LATIN CAPITAL LETTER E 0x46: [662,0,556,11,546], // LATIN CAPITAL LETTER F 0x47: [676,14,722,32,709], // LATIN CAPITAL LETTER G 0x48: [662,0,722,18,703], // LATIN CAPITAL LETTER H 0x49: [662,0,333,18,315], // LATIN CAPITAL LETTER I 0x4A: [662,14,373,-6,354], // LATIN CAPITAL LETTER J 0x4B: [662,0,722,33,723], // LATIN CAPITAL LETTER K 0x4C: [662,0,611,12,598], // LATIN CAPITAL LETTER L 0x4D: [662,0,889,12,864], // LATIN CAPITAL LETTER M 0x4E: [662,11,722,12,707], // LATIN CAPITAL LETTER N 0x4F: [676,14,722,34,688], // LATIN CAPITAL LETTER O 0x50: [662,0,557,16,542], // LATIN CAPITAL LETTER P 0x51: [676,177,722,34,701], // LATIN CAPITAL LETTER Q 0x52: [662,0,667,17,660], // LATIN CAPITAL LETTER R 0x53: [676,14,556,43,491], // LATIN CAPITAL LETTER S 0x54: [662,0,611,17,593], // LATIN CAPITAL LETTER T 0x55: [662,14,722,14,705], // LATIN CAPITAL LETTER U 0x56: [662,11,722,16,697], // LATIN CAPITAL LETTER V 0x57: [662,11,944,5,932], // LATIN CAPITAL LETTER W 0x58: [662,0,722,10,704], // LATIN CAPITAL LETTER X 0x59: [662,0,722,22,703], // LATIN CAPITAL LETTER Y 0x5A: [662,0,612,10,598], // LATIN CAPITAL LETTER Z 0x5B: [662,156,333,88,299], // LEFT SQUARE BRACKET 0x5C: [676,14,278,-9,287], // REVERSE SOLIDUS 0x5D: [662,156,333,34,245], // RIGHT SQUARE BRACKET 0x5E: [662,-297,469,24,446], // CIRCUMFLEX ACCENT 0x5F: [-75,125,500,0,500], // LOW LINE 0x60: [678,-507,333,18,242], // GRAVE ACCENT 0x61: [460,10,444,37,442], // LATIN SMALL LETTER A 0x62: [683,10,500,3,468], // LATIN SMALL LETTER B 0x63: [460,10,444,25,412], // LATIN SMALL LETTER C 0x64: [683,10,500,27,491], // LATIN SMALL LETTER D 0x65: [460,10,444,25,424], // LATIN SMALL LETTER E 0x66: [683,0,333,20,383], // LATIN SMALL LETTER F 0x67: [460,218,500,28,470], // LATIN SMALL LETTER G 0x68: [683,0,500,9,487], // LATIN SMALL LETTER H 0x69: [683,0,278,16,253], // LATIN SMALL LETTER I 0x6A: [683,218,278,-70,194], // LATIN SMALL LETTER J 0x6B: [683,0,500,7,505], // LATIN SMALL LETTER K 0x6C: [683,0,278,19,257], // LATIN SMALL LETTER L 0x6D: [460,0,778,16,775], // LATIN SMALL LETTER M 0x6E: [460,0,500,16,485], // LATIN SMALL LETTER N 0x6F: [460,10,500,29,470], // LATIN SMALL LETTER O 0x70: [460,217,500,5,470], // LATIN SMALL LETTER P 0x71: [460,217,500,24,488], // LATIN SMALL LETTER Q 0x72: [460,0,333,5,335], // LATIN SMALL LETTER R 0x73: [459,10,389,51,348], // LATIN SMALL LETTER S 0x74: [579,10,278,13,279], // LATIN SMALL LETTER T 0x75: [450,10,500,9,480], // LATIN SMALL LETTER U 0x76: [450,14,500,19,477], // LATIN SMALL LETTER V 0x77: [450,14,722,21,694], // LATIN SMALL LETTER W 0x78: [450,0,500,17,479], // LATIN SMALL LETTER X 0x79: [450,218,500,14,475], // LATIN SMALL LETTER Y 0x7A: [450,0,444,27,418], // LATIN SMALL LETTER Z 0x7B: [680,181,480,100,350], // LEFT CURLY BRACKET 0x7C: [676,14,200,67,133], // VERTICAL LINE 0x7D: [680,181,480,130,380], // RIGHT CURLY BRACKET 0x7E: [325,-183,541,40,502], // TILDE 0xA0: [0,0,250,0,0], // NO-BREAK SPACE 0xA8: [622,-523,333,18,316], // DIAERESIS 0xAC: [393,-115,600,48,552], // NOT SIGN 0xAF: [601,-547,333,11,322], // MACRON 0xB1: [502,87,685,48,637], // PLUS-MINUS SIGN 0xB7: [310,-199,250,70,181], // MIDDLE DOT 0xD7: [529,25,640,43,597], // MULTIPLICATION SIGN 0xF7: [516,10,564,30,534], // DIVISION SIGN 0x131: [460,0,278,16,253], // LATIN SMALL LETTER DOTLESS I 0x237: [460,218,278,-70,193], // LATIN SMALL LETTER DOTLESS J 0x2C6: [674,-507,333,11,322], // MODIFIER LETTER CIRCUMFLEX ACCENT 0x2C7: [674,-507,333,11,322], // CARON 0x2C9: [601,-547,334,11,322], // MODIFIER LETTER MACRON 0x2CA: [679,-509,333,93,320], // MODIFIER LETTER ACUTE ACCENT 0x2CB: [679,-509,333,22,249], // MODIFIER LETTER GRAVE ACCENT 0x2D8: [664,-507,335,27,308], // BREVE 0x2D9: [622,-523,333,118,217], // DOT ABOVE 0x2DC: [638,-532,333,1,331], // SMALL TILDE 0x300: [678,-507,0,-371,-147], // COMBINING GRAVE ACCENT 0x301: [678,-507,0,-371,-147], // COMBINING ACUTE ACCENT 0x302: [674,-507,0,-386,-75], // COMBINING CIRCUMFLEX ACCENT 0x303: [638,-532,0,-395,-65], // COMBINING TILDE 0x304: [601,-547,0,-385,-74], // COMBINING MACRON 0x306: [664,-507,0,-373,-92], // COMBINING BREVE 0x307: [622,-523,0,-280,-181], // COMBINING DOT ABOVE 0x308: [622,-523,0,-379,-81], // COMBINING DIAERESIS 0x30A: [711,-512,0,-329,-130], // COMBINING RING ABOVE 0x30B: [678,-507,0,-401,-22], // COMBINING DOUBLE ACUTE ACCENT 0x30C: [674,-507,0,-385,-74], // COMBINING CARON 0x338: [662,156,0,-380,31], // COMBINING LONG SOLIDUS OVERLAY 0x393: [662,0,587,11,577], // GREEK CAPITAL LETTER GAMMA 0x394: [674,0,722,48,675], // GREEK CAPITAL LETTER DELTA 0x398: [676,14,722,34,688], // GREEK CAPITAL LETTER THETA 0x39B: [674,0,702,15,687], // GREEK CAPITAL LETTER LAMDA 0x39E: [662,0,643,29,614], // GREEK CAPITAL LETTER XI 0x3A0: [662,0,722,18,703], // GREEK CAPITAL LETTER PI 0x3A3: [662,0,624,30,600], // GREEK CAPITAL LETTER SIGMA 0x3A5: [674,0,722,29,703], // GREEK CAPITAL LETTER UPSILON 0x3A6: [662,0,763,35,728], // GREEK CAPITAL LETTER PHI 0x3A8: [690,0,746,22,724], // GREEK CAPITAL LETTER PSI 0x3A9: [676,0,744,29,715], // GREEK CAPITAL LETTER OMEGA 0x2020: [676,149,500,59,442], // DAGGER 0x2021: [676,153,500,58,442], // DOUBLE DAGGER 0x2026: [100,11,1000,111,888], // HORIZONTAL ELLIPSIS 0x2032: [678,-402,289,75,214], // PRIME 0x203E: [820,-770,500,0,500], // OVERLINE 0x20D7: [760,-548,0,-453,-17], // COMBINING RIGHT ARROW ABOVE 0x2111: [695,34,762,45,711], // BLACK-LETTER CAPITAL I 0x2118: [547,217,826,52,799], // SCRIPT CAPITAL P 0x211C: [704,22,874,50,829], // BLACK-LETTER CAPITAL R 0x2135: [677,13,682,43,634], // ALEF SYMBOL 0x2190: [449,-58,926,71,857], // LEFTWARDS ARROW 0x2191: [662,156,511,60,451], // UPWARDS ARROW 0x2192: [448,-57,926,70,856], // RIGHTWARDS ARROW 0x2193: [662,156,511,60,451], // DOWNWARDS ARROW 0x2194: [449,-57,926,38,888], // LEFT RIGHT ARROW 0x2195: [730,224,511,60,451], // UP DOWN ARROW 0x2196: [662,156,926,70,856], // NORTH WEST ARROW 0x2197: [662,156,926,70,856], // NORTH EAST ARROW 0x2198: [662,156,926,70,856], // SOUTH EAST ARROW 0x2199: [662,156,926,70,856], // SOUTH WEST ARROW 0x21A6: [450,-57,926,70,857], // RIGHTWARDS ARROW FROM BAR 0x21A9: [553,-57,926,70,856], // LEFTWARDS ARROW WITH HOOK 0x21AA: [553,-57,926,70,856], // RIGHTWARDS ARROW WITH HOOK 0x21BC: [494,-220,955,54,901], // LEFTWARDS HARPOON WITH BARB UPWARDS 0x21BD: [286,-12,955,54,901], // LEFTWARDS HARPOON WITH BARB DOWNWARDS 0x21C0: [494,-220,955,54,901], // RIGHTWARDS HARPOON WITH BARB UPWARDS 0x21C1: [286,-12,955,54,901], // RIGHTWARDS HARPOON WITH BARB DOWNWARDS 0x21CC: [539,33,926,70,856], // RIGHTWARDS HARPOON OVER LEFTWARDS HARPOON 0x21D0: [551,45,926,60,866], // LEFTWARDS DOUBLE ARROW 0x21D1: [662,156,685,45,641], // UPWARDS DOUBLE ARROW 0x21D2: [551,45,926,60,866], // RIGHTWARDS DOUBLE ARROW 0x21D3: [662,156,685,45,641], // DOWNWARDS DOUBLE ARROW 0x21D4: [517,10,926,20,906], // LEFT RIGHT DOUBLE ARROW 0x21D5: [730,224,685,45,641], // UP DOWN DOUBLE ARROW 0x2200: [662,0,560,2,558], // FOR ALL 0x2202: [668,11,471,40,471], // PARTIAL DIFFERENTIAL 0x2203: [662,0,560,73,487], // THERE EXISTS 0x2205: [583,79,762,50,712], // EMPTY SET 0x2207: [662,12,731,63,667], // NABLA 0x2208: [531,27,685,60,625], // ELEMENT OF 0x2209: [662,157,685,60,625], // stix-negated (vert) set membership, variant 0x220B: [531,27,685,60,625], // CONTAINS AS MEMBER 0x220F: [763,259,1000,52,948], // N-ARY PRODUCT 0x2210: [763,259,1000,52,948], // N-ARY COPRODUCT 0x2211: [763,259,914,58,856], // N-ARY SUMMATION 0x2212: [286,-220,685,64,621], // MINUS SIGN 0x2213: [502,87,685,48,637], // MINUS-OR-PLUS SIGN 0x2215: [710,222,523,46,478], // DIVISION SLASH 0x2216: [411,-93,428,25,403], // SET MINUS 0x2217: [471,-33,523,67,457], // ASTERISK OPERATOR 0x2218: [387,-117,350,40,310], // RING OPERATOR 0x2219: [387,-117,350,40,310], // BULLET OPERATOR 0x221A: [973,259,928,112,963], // SQUARE ROOT 0x221D: [430,0,685,41,643], // PROPORTIONAL TO 0x221E: [430,0,926,70,854], // INFINITY 0x2220: [547,0,685,23,643], // ANGLE 0x2223: [690,189,266,100,166], // DIVIDES 0x2225: [690,189,523,129,394], // PARALLEL TO 0x2227: [536,29,620,31,589], // LOGICAL AND 0x2228: [536,29,620,31,589], // LOGICAL OR 0x2229: [536,31,620,48,572], // stix-intersection, serifs 0x222A: [536,31,620,48,572], // stix-union, serifs 0x222B: [824,320,459,32,639], // INTEGRAL 0x223C: [362,-148,685,48,637], // TILDE OPERATOR 0x2240: [547,42,286,35,249], // WREATH PRODUCT 0x2243: [445,-55,685,48,637], // ASYMPTOTICALLY EQUAL TO 0x2245: [532,27,685,48,637], // APPROXIMATELY EQUAL TO 0x2248: [475,-25,685,48,637], // ALMOST EQUAL TO 0x224D: [498,-8,685,48,637], // EQUIVALENT TO 0x2250: [611,-120,685,48,637], // APPROACHES THE LIMIT 0x2260: [662,156,685,48,637], // stix-not (vert) equals 0x2261: [478,-28,685,48,637], // IDENTICAL TO 0x2264: [609,103,685,64,629], // LESS-THAN OR EQUAL TO 0x2265: [609,103,685,64,629], // GREATER-THAN OR EQUAL TO 0x226A: [532,26,933,25,908], // MUCH LESS-THAN 0x226B: [532,26,933,25,908], // MUCH GREATER-THAN 0x227A: [532,26,685,64,621], // PRECEDES 0x227B: [532,26,685,64,621], // SUCCEEDS 0x227C: [628,120,685,64,621], // PRECEDES OR EQUAL TO 0x227D: [629,119,685,64,621], // SUCCEEDS OR EQUAL TO 0x2282: [531,25,685,64,621], // SUBSET OF 0x2283: [531,25,685,64,621], // SUPERSET OF 0x2286: [607,103,685,64,621], // SUBSET OF OR EQUAL TO 0x2287: [607,103,685,64,621], // SUPERSET OF OR EQUAL TO 0x228E: [536,31,620,48,572], // MULTISET UNION 0x2291: [607,103,685,64,621], // SQUARE IMAGE OF OR EQUAL TO 0x2292: [607,103,685,64,621], // SQUARE ORIGINAL OF OR EQUAL TO 0x2293: [536,31,620,48,572], // stix-square intersection, serifs 0x2294: [536,31,620,48,572], // stix-square union, serifs 0x2295: [623,119,842,50,792], // stix-circled plus (with rim) 0x2296: [623,119,842,50,792], // CIRCLED MINUS 0x2297: [623,119,842,50,792], // stix-circled times (with rim) 0x2298: [623,119,842,50,792], // CIRCLED DIVISION SLASH 0x2299: [583,79,762,50,712], // CIRCLED DOT OPERATOR 0x22A2: [662,0,685,64,621], // RIGHT TACK 0x22A3: [662,0,685,64,621], // LEFT TACK 0x22A4: [662,0,685,48,637], // DOWN TACK 0x22A5: [662,0,685,48,637], // UP TACK 0x22A8: [662,0,685,64,621], // TRUE 0x22C0: [763,259,924,54,870], // N-ARY LOGICAL AND 0x22C1: [763,259,924,54,870], // N-ARY LOGICAL OR 0x22C2: [778,254,924,94,830], // N-ARY INTERSECTION 0x22C3: [768,264,924,94,830], // N-ARY UNION 0x22C4: [488,-16,523,26,497], // DIAMOND OPERATOR 0x22C5: [313,-193,286,83,203], // DOT OPERATOR 0x22C6: [597,13,700,35,665], // STAR OPERATOR 0x22C8: [582,80,810,54,756], // BOWTIE 0x22EE: [606,104,511,192,319], // VERTICAL ELLIPSIS 0x22EF: [316,-189,926,108,818], // MIDLINE HORIZONTAL ELLIPSIS 0x22F1: [520,18,926,194,732], // DOWN RIGHT DIAGONAL ELLIPSIS 0x2308: [713,213,469,188,447], // LEFT CEILING 0x2309: [713,213,469,27,286], // RIGHT CEILING 0x230A: [713,213,469,188,447], // LEFT FLOOR 0x230B: [713,213,469,27,286], // RIGHT FLOOR 0x2322: [360,-147,1019,54,965], // stix-small down curve 0x2323: [360,-147,1019,54,965], // stix-small up curve 0x23AF: [286,-220,315,0,315], // HORIZONTAL LINE EXTENSION 0x23D0: [405,-101,511,222,288], // VERTICAL LINE EXTENSION (used to extend arrows) 0x25B3: [811,127,1145,35,1110], // WHITE UP-POINTING TRIANGLE 0x25B9: [555,50,660,80,605], // WHITE RIGHT-POINTING SMALL TRIANGLE 0x25BD: [811,127,1145,35,1110], // WHITE DOWN-POINTING TRIANGLE 0x25C3: [554,51,660,55,580], // WHITE LEFT-POINTING SMALL TRIANGLE 0x25EF: [785,282,1207,70,1137], // LARGE CIRCLE 0x2660: [609,99,685,34,651], // BLACK SPADE SUIT 0x2661: [603,105,685,34,651], // WHITE HEART SUIT 0x2662: [609,105,685,41,643], // WHITE DIAMOND SUIT 0x2663: [603,99,685,34,651], // BLACK CLUB SUIT 0x266D: [768,10,426,57,346], // MUSIC FLAT SIGN 0x266E: [768,181,426,75,350], // MUSIC NATURAL SIGN 0x266F: [768,181,426,41,386], // MUSIC SHARP SIGN 0x27E8: [713,213,400,77,335], // MATHEMATICAL LEFT ANGLE BRACKET 0x27E9: [713,213,400,65,323], // MATHEMATICAL RIGHT ANGLE BRACKET 0x27EE: [676,177,233,56,211], // MATHEMATICAL LEFT FLATTENED PARENTHESIS 0x27EF: [676,177,233,22,177], // MATHEMATICAL RIGHT FLATTENED PARENTHESIS 0x27F5: [449,-58,1574,55,1519], // LONG LEFTWARDS ARROW 0x27F6: [449,-57,1574,55,1519], // LONG RIGHTWARDS ARROW 0x27F7: [449,-57,1574,55,1519], // LONG LEFT RIGHT ARROW 0x27F8: [551,45,1574,55,1519], // LONG LEFTWARDS DOUBLE ARROW 0x27F9: [551,45,1574,55,1519], // LONG RIGHTWARDS DOUBLE ARROW 0x27FA: [517,10,1574,55,1519], // LONG LEFT RIGHT DOUBLE ARROW 0x27FB: [450,-57,1574,55,1519], // LONG LEFTWARDS ARROW FROM BAR 0x27FC: [450,-57,1574,55,1519], // LONG RIGHTWARDS ARROW FROM BAR 0x29F5: [710,222,523,46,478], // REVERSE SOLIDUS OPERATOR 0x2A00: [763,259,1126,53,1073], // N-ARY CIRCLED DOT OPERATOR 0x2A01: [763,259,1126,53,1073], // N-ARY CIRCLED PLUS OPERATOR 0x2A02: [763,259,1126,53,1073], // N-ARY CIRCLED TIMES OPERATOR 0x2A03: [768,264,924,94,830], // N-ARY UNION OPERATOR WITH DOT 0x2A04: [768,264,924,94,830], // N-ARY UNION OPERATOR WITH PLUS 0x2A05: [763,259,924,94,830], // N-ARY SQUARE INTERSECTION OPERATOR 0x2A06: [763,259,924,94,830], // N-ARY SQUARE UNION OPERATOR 0x2A3F: [662,0,694,30,664], // AMALGAMATION OR COPRODUCT 0x2AAF: [609,103,685,64,621], // PRECEDES ABOVE SINGLE-LINE EQUALS SIGN 0x2AB0: [609,103,685,64,621] // SUCCEEDS ABOVE SINGLE-LINE EQUALS SIGN }; MathJax.OutputJax["HTML-CSS"].initFont("STIXGeneral"); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Regular/Main.js");
/* * # Semantic - Dropdown * http://github.com/jlukic/semantic-ui/ * * * Copyright 2013 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { $.fn.sidebar = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), invokedResponse ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.sidebar.settings, parameters) : $.extend({}, $.fn.sidebar.settings), selector = settings.selector, className = settings.className, namespace = settings.namespace, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $body = $('body'), $head = $('head'), $style = $('style[title=' + namespace + ']'), element = this, instance = $module.data(moduleNamespace), module ; module = { initialize: function() { module.debug('Initializing sidebar', $module); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous module for', $module); $module .off(eventNamespace) .removeData(moduleNamespace) ; }, refresh: function() { module.verbose('Refreshing selector cache'); $style = $('style[title=' + namespace + ']'); }, attachEvents: function(selector, event) { var $toggle = $(selector) ; event = $.isFunction(module[event]) ? module[event] : module.toggle ; if($toggle.size() > 0) { module.debug('Attaching sidebar events to element', selector, event); $toggle .off(eventNamespace) .on('click' + eventNamespace, event) ; } else { module.error(error.notFound); } }, show: function() { module.debug('Showing sidebar'); if(module.is.closed()) { if(!settings.overlay) { module.pushPage(); } module.set.active(); } else { module.debug('Sidebar is already visible'); } }, hide: function() { if(module.is.open()) { if(!settings.overlay) { module.pullPage(); module.remove.pushed(); } module.remove.active(); } }, toggle: function() { if(module.is.closed()) { module.show(); } else { module.hide(); } }, pushPage: function() { var direction = module.get.direction(), distance = (module.is.vertical()) ? $module.outerHeight() : $module.outerWidth() ; if(settings.useCSS) { module.debug('Using CSS to animate body'); module.add.bodyCSS(direction, distance); module.set.pushed(); } else { module.animatePage(direction, distance, module.set.pushed); } }, pullPage: function() { var direction = module.get.direction() ; if(settings.useCSS) { module.debug('Resetting body position css'); module.remove.bodyCSS(); } else { module.debug('Resetting body position using javascript'); module.animatePage(direction, 0); } module.remove.pushed(); }, animatePage: function(direction, distance) { var animateSettings = {} ; animateSettings['padding-' + direction] = distance; module.debug('Using javascript to animate body', animateSettings); $body .animate(animateSettings, settings.duration, module.set.pushed) ; }, add: { bodyCSS: function(direction, distance) { var style ; if(direction !== className.bottom) { style = '' + '<style title="' + namespace + '">' + 'body.pushed {' + ' margin-' + direction + ': ' + distance + 'px !important;' + '}' + '</style>' ; } $head.append(style); module.debug('Adding body css to head', $style); } }, remove: { bodyCSS: function() { module.debug('Removing body css styles', $style); module.refresh(); $style.remove(); }, active: function() { $module.removeClass(className.active); }, pushed: function() { module.verbose('Removing body push state', module.get.direction()); $body .removeClass(className[ module.get.direction() ]) .removeClass(className.pushed) ; } }, set: { active: function() { $module.addClass(className.active); }, pushed: function() { module.verbose('Adding body push state', module.get.direction()); $body .addClass(className[ module.get.direction() ]) .addClass(className.pushed) ; } }, get: { direction: function() { if($module.hasClass(className.top)) { return className.top; } else if($module.hasClass(className.right)) { return className.right; } else if($module.hasClass(className.bottom)) { return className.bottom; } else { return className.left; } }, transitionEvent: function() { var element = document.createElement('element'), transitions = { 'transition' :'transitionend', 'OTransition' :'oTransitionEnd', 'MozTransition' :'transitionend', 'WebkitTransition' :'webkitTransitionEnd' }, transition ; for(transition in transitions){ if( element.style[transition] !== undefined ){ return transitions[transition]; } } } }, is: { open: function() { return $module.is(':animated') || $module.hasClass(className.active); }, closed: function() { return !module.is.open(); }, vertical: function() { return $module.hasClass(className.top); } }, setting: function(name, value) { if(value !== undefined) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else { settings[name] = value; } } else { return settings[name]; } }, internal: function(name, value) { if(value !== undefined) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else { module[name] = value; } } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Element' : element, 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 100); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.size() > 1) { title += ' ' + '(' + $allModules.size() + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && instance !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( instance[value] ) && (depth != maxDepth) ) { instance = instance[value]; } else if( $.isPlainObject( instance[camelCaseValue] ) && (depth != maxDepth) ) { instance = instance[camelCaseValue]; } else if( instance[value] !== undefined ) { found = instance[value]; return false; } else if( instance[camelCaseValue] !== undefined ) { found = instance[camelCaseValue]; return false; } else { module.error(error.method); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(invokedResponse)) { invokedResponse.push(response); } else if(typeof invokedResponse == 'string') { invokedResponse = [invokedResponse, response]; } else if(response !== undefined) { invokedResponse = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { module.destroy(); } module.initialize(); } }) ; return (invokedResponse !== undefined) ? invokedResponse : this ; }; $.fn.sidebar.settings = { name : 'Sidebar', namespace : 'sidebar', verbose : true, debug : true, performance : true, useCSS : true, overlay : false, duration : 300, side : 'left', onChange : function(){}, onShow : function(){}, onHide : function(){}, className: { active : 'active', pushed : 'pushed', top : 'top', left : 'left', right : 'right', bottom : 'bottom' }, error : { method : 'The method you called is not defined.', notFound : 'There were no elements that matched the specified selector' } }; })( jQuery, window , document );
// File: chapter9/timeAgoFilterSpec.js describe('timeAgo Filter', function() { beforeEach(module('filtersApp')); var filter; beforeEach(inject(function(timeAgoFilter) { filter = timeAgoFilter; })); it('should respond based on timestamp', function() { // The presence of new Date().getTime() makes it slightly // hard to unit test deterministicly. // Ideally, we would inject a dateProvider into the timeAgo // filter, but we are trying to keep it simple here // So going to assume that our tests are fast enough to // execute in mere milliseconds var currentTime = new Date().getTime(); currentTime -= 10000; expect(filter(currentTime)).toEqual('seconds ago'); var fewMinutesAgo = currentTime - 1000 * 60; expect(filter(fewMinutesAgo)).toEqual('minutes ago'); var fewHoursAgo = currentTime - 1000 * 60 * 68; expect(filter(fewHoursAgo)).toEqual('hours ago'); var fewDaysAgo = currentTime - 1000 * 60 * 60 * 26; expect(filter(fewDaysAgo)).toEqual('days ago'); var fewMonthsAgo = currentTime - 1000 * 60 * 60 * 24 * 32; expect(filter(fewMonthsAgo)).toEqual('months ago'); }); });
sampleTag`\xg`
/*! * Nestable jQuery Plugin - Copyright (c) 2014 Ramon Smit - https://github.com/RamonSmit/Nestable */ ; (function($, window, document, undefined) { var hasTouch = 'ontouchstart' in window; /** * Detect CSS pointer-events property * events are normally disabled on the dragging element to avoid conflicts * https://github.com/ausi/Feature-detection-technique-for-pointer-events/blob/master/modernizr-pointerevents.js */ var hasPointerEvents = (function() { var el = document.createElement('div'), docEl = document.documentElement; if(!('pointerEvents' in el.style)) { return false; } el.style.pointerEvents = 'auto'; el.style.pointerEvents = 'x'; docEl.appendChild(el); var supports = window.getComputedStyle && window.getComputedStyle(el, '').pointerEvents === 'auto'; docEl.removeChild(el); return !!supports; })(); var eStart = hasTouch ? 'touchstart' : 'mousedown', eMove = hasTouch ? 'touchmove' : 'mousemove', eEnd = hasTouch ? 'touchend' : 'mouseup', eCancel = hasTouch ? 'touchcancel' : 'mouseup'; var defaults = { contentCallback: function(item) {return item.content || '' ? item.content : item.id;}, listNodeName: 'ol', itemNodeName: 'li', handleNodeName: 'div', contentNodeName: 'span', rootClass: 'dd', listClass: 'dd-list', itemClass: 'dd-item', dragClass: 'dd-dragel', handleClass: 'dd-handle', contentClass: 'dd-content', collapsedClass: 'dd-collapsed', placeClass: 'dd-placeholder', noDragClass: 'dd-nodrag', noChildrenClass: 'dd-nochildren', emptyClass: 'dd-empty', expandBtnHTML: '<button class="dd-expand" data-action="expand" type="button">Expand</button>', collapseBtnHTML: '<button class="dd-collapse" data-action="collapse" type="button">Collapse</button>', group: 0, maxDepth: 5, threshold: 20, fixedDepth: false, //fixed item's depth fixed: false, includeContent: false, callback: function(l, e, p) {}, onDragStart: function(l, e, p) {}, listRenderer: function(children, options) { var html = '<' + options.listNodeName + ' class="' + options.listClass + '">'; html += children; html += '</' + options.listNodeName + '>'; return html; }, itemRenderer: function(item_attrs, content, children, options, item) { var item_attrs_string = $.map(item_attrs, function(value, key) { return ' ' + key + '="' + value + '"'; }).join(' '); var html = '<' + options.itemNodeName + item_attrs_string + '>'; html += '<' + options.handleNodeName + ' class="' + options.handleClass + '">'; html += '<' + options.contentNodeName + ' class="' + options.contentClass + '">'; html += content; html += '</' + options.contentNodeName + '>'; html += '</' + options.handleNodeName + '>'; html += children; html += '</' + options.itemNodeName + '>'; return html; } }; function Plugin(element, options) { this.w = $(document); this.el = $(element); if(!options) { options = defaults; } if(options.rootClass !== undefined && options.rootClass !== 'dd') { options.listClass = options.listClass ? options.listClass : options.rootClass + '-list'; options.itemClass = options.itemClass ? options.itemClass : options.rootClass + '-item'; options.dragClass = options.dragClass ? options.dragClass : options.rootClass + '-dragel'; options.handleClass = options.handleClass ? options.handleClass : options.rootClass + '-handle'; options.collapsedClass = options.collapsedClass ? options.collapsedClass : options.rootClass + '-collapsed'; options.placeClass = options.placeClass ? options.placeClass : options.rootClass + '-placeholder'; options.noDragClass = options.noDragClass ? options.noDragClass : options.rootClass + '-nodrag'; options.noChildrenClass = options.noChildrenClass ? options.noChildrenClass : options.rootClass + '-nochildren'; options.emptyClass = options.emptyClass ? options.emptyClass : options.rootClass + '-empty'; } this.options = $.extend({}, defaults, options); // build HTML from serialized JSON if passed if(this.options.json !== undefined) { this._build(); } this.init(); } Plugin.prototype = { init: function() { var list = this; list.reset(); list.el.data('nestable-group', this.options.group); list.placeEl = $('<div class="' + list.options.placeClass + '"/>'); $.each(this.el.find(list.options.itemNodeName), function(k, el) { var item = $(el), parent = item.parent(); list.setParent(item); if(parent.hasClass(list.options.collapsedClass)) { list.collapseItem(parent.parent()); } }); list.el.on('click', 'button', function(e) { if(list.dragEl || (!hasTouch && e.button !== 0)) { return; } var target = $(e.currentTarget), action = target.data('action'), item = target.parents(list.options.itemNodeName).eq(0); if(action === 'collapse') { list.collapseItem(item); } if(action === 'expand') { list.expandItem(item); } }); var onStartEvent = function(e) { var handle = $(e.target); if(!handle.hasClass(list.options.handleClass)) { if(handle.closest('.' + list.options.noDragClass).length) { return; } handle = handle.closest('.' + list.options.handleClass); } if(!handle.length || list.dragEl || (!hasTouch && e.which !== 1) || (hasTouch && e.touches.length !== 1)) { return; } e.preventDefault(); list.dragStart(hasTouch ? e.touches[0] : e); }; var onMoveEvent = function(e) { if(list.dragEl) { e.preventDefault(); list.dragMove(hasTouch ? e.touches[0] : e); } }; var onEndEvent = function(e) { if(list.dragEl) { e.preventDefault(); list.dragStop(hasTouch ? e.touches[0] : e); } }; if(hasTouch) { list.el[0].addEventListener(eStart, onStartEvent, false); window.addEventListener(eMove, onMoveEvent, false); window.addEventListener(eEnd, onEndEvent, false); window.addEventListener(eCancel, onEndEvent, false); } else { list.el.on(eStart, onStartEvent); list.w.on(eMove, onMoveEvent); list.w.on(eEnd, onEndEvent); } var destroyNestable = function() { if(hasTouch) { list.el[0].removeEventListener(eStart, onStartEvent, false); window.removeEventListener(eMove, onMoveEvent, false); window.removeEventListener(eEnd, onEndEvent, false); window.removeEventListener(eCancel, onEndEvent, false); } else { list.el.off(eStart, onStartEvent); list.w.off(eMove, onMoveEvent); list.w.off(eEnd, onEndEvent); } list.el.off('click'); list.el.unbind('destroy-nestable'); list.el.data("nestable", null); }; list.el.bind('destroy-nestable', destroyNestable); }, destroy: function () { this.el.trigger('destroy-nestable'); }, add: function (item) { var html = this._buildItem(item, this.options); $(this.el).children('.' + this.options.listClass).append(html); }, _build: function() { var json = this.options.json; if(typeof json === 'string') { json = JSON.parse(json); } $(this.el).html(this._buildList(json, this.options)); }, _buildList: function(items, options) { if(!items) { return ''; } var children = ''; var that = this; $.each(items, function(index, sub) { children += that._buildItem(sub, options); }); return options.listRenderer(children, options); }, _buildItem: function(item, options) { function escapeHtml(text) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; return text + "".replace(/[&<>"']/g, function(m) { return map[m]; }); } function filterClasses(classes) { var new_classes = {}; for(var k in classes) { // Remove duplicates new_classes[classes[k]] = classes[k]; } return new_classes; } function createClassesString(item, options) { var classes = item.classes || {}; if(typeof classes == 'string') { classes = [classes]; } var item_classes = filterClasses(classes); item_classes[options.itemClass] = options.itemClass; // create class string return $.map(item_classes, function(val) { return val; }).join(' '); } function createDataAttrs(attr) { attr = $.extend({}, attr); delete attr.children; delete attr.classes; delete attr.content; var data_attrs = {}; $.each(attr, function(key, value) { if(typeof value == 'object') { value = JSON.stringify(value); } data_attrs["data-" + key] = escapeHtml(value); }); return data_attrs; } var item_attrs = createDataAttrs(item); item_attrs["class"] = createClassesString(item, options); var content = options.contentCallback(item); var children = this._buildList(item.children, options); return options.itemRenderer(item_attrs, content, children, options, item); }, serialize: function() { var data, list = this, step = function(level) { var array = [], items = level.children(list.options.itemNodeName); items.each(function() { var li = $(this), item = $.extend({}, li.data()), sub = li.children(list.options.listNodeName); if(list.options.includeContent) { var content = li.find('.' + list.options.contentClass).html(); if(content) { item.content = content; } } if(sub.length) { item.children = step(sub); } array.push(item); }); return array; }; data = step(list.el.find(list.options.listNodeName).first()); return data; }, asNestedSet: function() { var list = this, o = list.options, depth = -1, ret = [], lft = 1; var items = list.el.find(o.listNodeName).first().children(o.itemNodeName); items.each(function () { lft = traverse(this, depth + 1, lft); }); ret = ret.sort(function(a,b){ return (a.lft - b.lft); }); return ret; function traverse(item, depth, lft) { var rgt = lft + 1, id, pid; if ($(item).children(o.listNodeName).children(o.itemNodeName).length > 0 ) { depth++; $(item).children(o.listNodeName).children(o.itemNodeName).each(function () { rgt = traverse($(this), depth, rgt); }); depth--; } id = parseInt($(item).attr('data-id')); pid = parseInt($(item).parent(o.listNodeName).parent(o.itemNodeName).attr('data-id')) || ''; if (id) { ret.push({"id": id, "parent_id": pid, "depth": depth, "lft": lft, "rgt": rgt}); } lft = rgt + 1; return lft; } }, returnOptions: function() { return this.options; }, serialise: function() { return this.serialize(); }, toHierarchy: function(options) { var o = $.extend({}, this.options, options), sDepth = o.startDepthCount || 0, ret = []; $(this.element).children(o.items).each(function() { var level = _recursiveItems(this); ret.push(level); }); return ret; function _recursiveItems(item) { var id = ($(item).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/)); if (id) { var currentItem = { "id": id[2] }; if ($(item).children(o.listType).children(o.items).length > 0) { currentItem.children = []; $(item).children(o.listType).children(o.items).each(function() { var level = _recursiveItems(this); currentItem.children.push(level); }); } return currentItem; } } }, toArray: function() { var o = $.extend({}, this.options, this), sDepth = o.startDepthCount || 0, ret = [], left = 2, list = this, element = list.el.find(list.options.listNodeName).first(); var items = element.children(list.options.itemNodeName); items.each(function() { left = _recursiveArray($(this), sDepth + 1, left); }); ret = ret.sort(function(a, b) { return (a.left - b.left); }); return ret; function _recursiveArray(item, depth, left) { var right = left + 1, id, pid; var new_item = item.children(o.options.listNodeName).children(o.options.itemNodeName); /// .data() if (item.children(o.options.listNodeName).children(o.options.itemNodeName).length > 0) { depth++; item.children(o.options.listNodeName).children(o.options.itemNodeName).each(function() { right = _recursiveArray($(this), depth, right); }); depth--; } id = item.data().id; if (depth === sDepth + 1) { pid = o.rootID; } else { var parentItem = (item.parent(o.options.listNodeName) .parent(o.options.itemNodeName) .data()); pid = parentItem.id; } if (id) { ret.push({ "id": id, "parent_id": pid, "depth": depth, "left": left, "right": right }); } left = right + 1; return left; } }, reset: function() { this.mouse = { offsetX: 0, offsetY: 0, startX: 0, startY: 0, lastX: 0, lastY: 0, nowX: 0, nowY: 0, distX: 0, distY: 0, dirAx: 0, dirX: 0, dirY: 0, lastDirX: 0, lastDirY: 0, distAxX: 0, distAxY: 0 }; this.moving = false; this.dragEl = null; this.dragRootEl = null; this.dragDepth = 0; this.hasNewRoot = false; this.pointEl = null; }, expandItem: function(li) { li.removeClass(this.options.collapsedClass); }, collapseItem: function(li) { var lists = li.children(this.options.listNodeName); if(lists.length) { li.addClass(this.options.collapsedClass); } }, expandAll: function() { var list = this; list.el.find(list.options.itemNodeName).each(function() { list.expandItem($(this)); }); }, collapseAll: function() { var list = this; list.el.find(list.options.itemNodeName).each(function() { list.collapseItem($(this)); }); }, setParent: function(li) { if(li.children(this.options.listNodeName).length) { // make sure NOT showing two or more sets data-action buttons li.children('[data-action]').remove(); li.prepend($(this.options.expandBtnHTML)); li.prepend($(this.options.collapseBtnHTML)); } }, unsetParent: function(li) { li.removeClass(this.options.collapsedClass); li.children('[data-action]').remove(); li.children(this.options.listNodeName).remove(); }, dragStart: function(e) { var mouse = this.mouse, target = $(e.target), dragItem = target.closest(this.options.itemNodeName); var position = {}; position.top = e.pageY; position.left = e.pageX; this.options.onDragStart.call(this, this.el, dragItem, position); this.placeEl.css('height', dragItem.height()); mouse.offsetX = e.pageX - dragItem.offset().left; mouse.offsetY = e.pageY - dragItem.offset().top; mouse.startX = mouse.lastX = e.pageX; mouse.startY = mouse.lastY = e.pageY; this.dragRootEl = this.el; this.dragEl = $(document.createElement(this.options.listNodeName)).addClass(this.options.listClass + ' ' + this.options.dragClass); this.dragEl.css('width', dragItem.outerWidth()); this.setIndexOfItem(dragItem); // fix for zepto.js //dragItem.after(this.placeEl).detach().appendTo(this.dragEl); dragItem.after(this.placeEl); dragItem[0].parentNode.removeChild(dragItem[0]); dragItem.appendTo(this.dragEl); $(document.body).append(this.dragEl); this.dragEl.css({ 'left': e.pageX - mouse.offsetX, 'top': e.pageY - mouse.offsetY }); // total depth of dragging item var i, depth, items = this.dragEl.find(this.options.itemNodeName); for(i = 0; i < items.length; i++) { depth = $(items[i]).parents(this.options.listNodeName).length; if(depth > this.dragDepth) { this.dragDepth = depth; } } }, setIndexOfItem: function(item, index) { if((typeof index) === 'undefined') { index = []; } index.unshift(item.index()); if($(item[0].parentNode)[0] !== this.dragRootEl[0]) { this.setIndexOfItem($(item[0].parentNode), index); } else { this.dragEl.data('indexOfItem', index); } }, restoreItemAtIndex: function(dragElement) { var indexArray = this.dragEl.data('indexOfItem'), currentEl = this.el; for(i = 0; i < indexArray.length; i++) { if((indexArray.length - 1) === parseInt(i)) { placeElement(currentEl, dragElement); return } currentEl = currentEl[0].children[indexArray[i]]; } function placeElement(currentEl, dragElement) { if(indexArray[indexArray.length - 1] === 0) { $(currentEl).prepend(dragElement.clone()); } else { $(currentEl.children[indexArray[indexArray.length - 1] - 1]).after(dragElement.clone()); } } }, dragStop: function(e) { // fix for zepto.js //this.placeEl.replaceWith(this.dragEl.children(this.options.itemNodeName + ':first').detach()); var el = this.dragEl.children(this.options.itemNodeName).first(); el[0].parentNode.removeChild(el[0]); this.placeEl.replaceWith(el); var position = {}; position.top = e.pageY; position.left = e.pageX; if(this.hasNewRoot) { if(this.options.fixed === true) { this.restoreItemAtIndex(el); } else { this.el.trigger('lostItem'); } this.dragRootEl.trigger('gainedItem'); } else { this.dragRootEl.trigger('change'); } this.dragEl.remove(); this.options.callback.call(this, this.dragRootEl, el, position); this.reset(); }, dragMove: function(e) { var list, parent, prev, next, depth, opt = this.options, mouse = this.mouse; this.dragEl.css({ 'left': e.pageX - mouse.offsetX, 'top': e.pageY - mouse.offsetY }); // mouse position last events mouse.lastX = mouse.nowX; mouse.lastY = mouse.nowY; // mouse position this events mouse.nowX = e.pageX; mouse.nowY = e.pageY; // distance mouse moved between events mouse.distX = mouse.nowX - mouse.lastX; mouse.distY = mouse.nowY - mouse.lastY; // direction mouse was moving mouse.lastDirX = mouse.dirX; mouse.lastDirY = mouse.dirY; // direction mouse is now moving (on both axis) mouse.dirX = mouse.distX === 0 ? 0 : mouse.distX > 0 ? 1 : -1; mouse.dirY = mouse.distY === 0 ? 0 : mouse.distY > 0 ? 1 : -1; // axis mouse is now moving on var newAx = Math.abs(mouse.distX) > Math.abs(mouse.distY) ? 1 : 0; // do nothing on first move if(!mouse.moving) { mouse.dirAx = newAx; mouse.moving = true; return; } // calc distance moved on this axis (and direction) if(mouse.dirAx !== newAx) { mouse.distAxX = 0; mouse.distAxY = 0; } else { mouse.distAxX += Math.abs(mouse.distX); if(mouse.dirX !== 0 && mouse.dirX !== mouse.lastDirX) { mouse.distAxX = 0; } mouse.distAxY += Math.abs(mouse.distY); if(mouse.dirY !== 0 && mouse.dirY !== mouse.lastDirY) { mouse.distAxY = 0; } } mouse.dirAx = newAx; /** * move horizontal */ if(mouse.dirAx && mouse.distAxX >= opt.threshold) { // reset move distance on x-axis for new phase mouse.distAxX = 0; prev = this.placeEl.prev(opt.itemNodeName); // increase horizontal level if previous sibling exists, is not collapsed, and can have children if(mouse.distX > 0 && prev.length && !prev.hasClass(opt.collapsedClass) && !prev.hasClass(opt.noChildrenClass)) { // cannot increase level when item above is collapsed list = prev.find(opt.listNodeName).last(); // check if depth limit has reached depth = this.placeEl.parents(opt.listNodeName).length; if(depth + this.dragDepth <= opt.maxDepth) { // create new sub-level if one doesn't exist if(!list.length) { list = $('<' + opt.listNodeName + '/>').addClass(opt.listClass); list.append(this.placeEl); prev.append(list); this.setParent(prev); } else { // else append to next level up list = prev.children(opt.listNodeName).last(); list.append(this.placeEl); } } } // decrease horizontal level if(mouse.distX < 0) { // we can't decrease a level if an item preceeds the current one next = this.placeEl.next(opt.itemNodeName); if(!next.length) { parent = this.placeEl.parent(); this.placeEl.closest(opt.itemNodeName).after(this.placeEl); if(!parent.children().length) { this.unsetParent(parent.parent()); } } } } var isEmpty = false; // find list item under cursor if(!hasPointerEvents) { this.dragEl[0].style.visibility = 'hidden'; } this.pointEl = $(document.elementFromPoint(e.pageX - document.body.scrollLeft, e.pageY - (window.pageYOffset || document.documentElement.scrollTop))); if(!hasPointerEvents) { this.dragEl[0].style.visibility = 'visible'; } if(this.pointEl.hasClass(opt.handleClass)) { this.pointEl = this.pointEl.closest(opt.itemNodeName); } if(this.pointEl.hasClass(opt.emptyClass)) { isEmpty = true; } else if(!this.pointEl.length || !this.pointEl.hasClass(opt.itemClass)) { return; } // find parent list of item under cursor var pointElRoot = this.pointEl.closest('.' + opt.rootClass), isNewRoot = this.dragRootEl.data('nestable-id') !== pointElRoot.data('nestable-id'); /** * move vertical */ if(!mouse.dirAx || isNewRoot || isEmpty) { // check if groups match if dragging over new root if(isNewRoot && opt.group !== pointElRoot.data('nestable-group')) { return; } // fixed item's depth, use for some list has specific type, eg:'Volume, Section, Chapter ...' if(this.options.fixedDepth && this.dragDepth + 1 !== this.pointEl.parents(opt.listNodeName).length) { return; } // check depth limit depth = this.dragDepth - 1 + this.pointEl.parents(opt.listNodeName).length; if(depth > opt.maxDepth) { return; } var before = e.pageY < (this.pointEl.offset().top + this.pointEl.height() / 2); parent = this.placeEl.parent(); // if empty create new list to replace empty placeholder if(isEmpty) { list = $(document.createElement(opt.listNodeName)).addClass(opt.listClass); list.append(this.placeEl); this.pointEl.replaceWith(list); } else if(before) { this.pointEl.before(this.placeEl); } else { this.pointEl.after(this.placeEl); } if(!parent.children().length) { this.unsetParent(parent.parent()); } if(!this.dragRootEl.find(opt.itemNodeName).length) { this.dragRootEl.append('<div class="' + opt.emptyClass + '"/>'); } // parent root list has changed this.dragRootEl = pointElRoot; if(isNewRoot) { this.hasNewRoot = this.el[0] !== this.dragRootEl[0]; } } } }; $.fn.nestable = function(params, val) { var lists = this, retval = this; if(!('Nestable' in window)) { window.Nestable = {}; Nestable.counter = 0; } lists.each(function() { var plugin = $(this).data("nestable"); if(!plugin) { Nestable.counter++; $(this).data("nestable", new Plugin(this, params)); $(this).data("nestable-id", Nestable.counter); } else { if(typeof params === 'string' && typeof plugin[params] === 'function') { if (typeof val !== 'undefined') { retval = plugin[params](val); }else{ retval = plugin[params](); } } } }); return retval || lists; }; })(window.jQuery || window.Zepto, window, document);
/** * @license * (c) 2009-2016 Michael Leibman * michael{dot}leibman{at}gmail{dot}com * http://github.com/mleibman/slickgrid * * Distributed under MIT license. * All rights reserved. * * SlickGrid v2.3 * * NOTES: * Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods. * This increases the speed dramatically, but can only be done safely because there are no event handlers * or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy() * and do proper cleanup. */ // make sure required JavaScript modules are loaded if (typeof jQuery === "undefined") { throw "SlickGrid requires jquery module to be loaded"; } if (!jQuery.fn.drag) { throw "SlickGrid requires jquery.event.drag module to be loaded"; } if (typeof Slick === "undefined") { throw "slick.core.js not loaded"; } (function ($) { // Slick.Grid $.extend(true, window, { Slick: { Grid: SlickGrid } }); // shared across all grids on the page var scrollbarDimensions; var maxSupportedCssHeight; // browser's breaking point ////////////////////////////////////////////////////////////////////////////////////////////// // SlickGrid class implementation (available as Slick.Grid) /** * Creates a new instance of the grid. * @class SlickGrid * @constructor * @param {Node} container Container node to create the grid in. * @param {Array,Object} data An array of objects for databinding. * @param {Array} columns An array of column definitions. * @param {Object} options Grid options. **/ function SlickGrid(container, data, columns, options) { // settings var defaults = { explicitInitialization: false, rowHeight: 25, defaultColumnWidth: 80, enableAddRow: false, leaveSpaceForNewRows: false, editable: false, autoEdit: true, enableCellNavigation: true, enableColumnReorder: true, asyncEditorLoading: false, asyncEditorLoadDelay: 100, forceFitColumns: false, enableAsyncPostRender: false, asyncPostRenderDelay: 50, enableAsyncPostRenderCleanup: false, asyncPostRenderCleanupDelay: 40, autoHeight: false, editorLock: Slick.GlobalEditorLock, showHeaderRow: false, headerRowHeight: 25, createFooterRow: false, showFooterRow: false, footerRowHeight: 25, showTopPanel: false, topPanelHeight: 25, formatterFactory: null, editorFactory: null, cellFlashingCssClass: "flashing", selectedCellCssClass: "selected", multiSelect: true, enableTextSelectionOnCells: false, dataItemColumnValueExtractor: null, fullWidthRows: false, multiColumnSort: false, defaultFormatter: defaultFormatter, forceSyncScrolling: false, addNewRowCssClass: "new-row" }; var columnDefaults = { name: "", resizable: true, sortable: false, minWidth: 30, rerenderOnResize: false, headerCssClass: null, defaultSortAsc: true, focusable: true, selectable: true }; // scroller var th; // virtual height var h; // real scrollable height var ph; // page height var n; // number of pages var cj; // "jumpiness" coefficient var page = 0; // current page var offset = 0; // current page offset var vScrollDir = 1; // private var initialized = false; var $container; var uid = "slickgrid_" + Math.round(1000000 * Math.random()); var self = this; var $focusSink, $focusSink2; var $headerScroller; var $headers; var $headerRow, $headerRowScroller, $headerRowSpacer; var $footerRow, $footerRowScroller, $footerRowSpacer; var $topPanelScroller; var $topPanel; var $viewport; var $canvas; var $style; var $boundAncestors; var stylesheet, columnCssRulesL, columnCssRulesR; var viewportH, viewportW; var canvasWidth; var viewportHasHScroll, viewportHasVScroll; var headerColumnWidthDiff = 0, headerColumnHeightDiff = 0, // border+padding cellWidthDiff = 0, cellHeightDiff = 0, jQueryNewWidthBehaviour = false; var absoluteColumnMinWidth; var tabbingDirection = 1; var activePosX; var activeRow, activeCell; var activeCellNode = null; var currentEditor = null; var serializedEditorValue; var editController; var rowsCache = {}; var renderedRows = 0; var numVisibleRows; var prevScrollTop = 0; var scrollTop = 0; var lastRenderedScrollTop = 0; var lastRenderedScrollLeft = 0; var prevScrollLeft = 0; var scrollLeft = 0; var selectionModel; var selectedRows = []; var plugins = []; var cellCssClasses = {}; var columnsById = {}; var sortColumns = []; var columnPosLeft = []; var columnPosRight = []; var pagingActive = false; var pagingIsLastPage = false; // async call handles var h_editorLoader = null; var h_render = null; var h_postrender = null; var h_postrenderCleanup = null; var postProcessedRows = {}; var postProcessToRow = null; var postProcessFromRow = null; var postProcessedCleanupQueue = []; var postProcessgroupId = 0; // perf counters var counter_rows_rendered = 0; var counter_rows_removed = 0; // These two variables work around a bug with inertial scrolling in Webkit/Blink on Mac. // See http://crbug.com/312427. var rowNodeFromLastMouseWheelEvent; // this node must not be deleted while inertial scrolling var zombieRowNodeFromLastMouseWheelEvent; // node that was hidden instead of getting deleted var zombieRowCacheFromLastMouseWheelEvent; // row cache for above node var zombieRowPostProcessedFromLastMouseWheelEvent; // post processing references for above node // store css attributes if display:none is active in container or parent var cssShow = { position: 'absolute', visibility: 'hidden', display: 'block' }; var $hiddenParents; var oldProps = []; ////////////////////////////////////////////////////////////////////////////////////////////// // Initialization function init() { $container = $(container); if ($container.length < 1) { throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM."); } cacheCssForHiddenInit(); // calculate these only once and share between grid instances maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight(); scrollbarDimensions = scrollbarDimensions || measureScrollbar(); options = $.extend({}, defaults, options); validateAndEnforceOptions(); columnDefaults.width = options.defaultColumnWidth; columnsById = {}; for (var i = 0; i < columns.length; i++) { var m = columns[i] = $.extend({}, columnDefaults, columns[i]); columnsById[m.id] = i; if (m.minWidth && m.width < m.minWidth) { m.width = m.minWidth; } if (m.maxWidth && m.width > m.maxWidth) { m.width = m.maxWidth; } } // validate loaded JavaScript modules against requested options if (options.enableColumnReorder && !$.fn.sortable) { throw new Error("SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded"); } editController = { "commitCurrentEdit": commitCurrentEdit, "cancelCurrentEdit": cancelCurrentEdit }; $container .empty() .css("overflow", "hidden") .css("outline", 0) .addClass(uid) .addClass("ui-widget"); // set up a positioning container if needed if (!/relative|absolute|fixed/.test($container.css("position"))) { $container.css("position", "relative"); } $focusSink = $("<div tabIndex='0' hideFocus style='position:fixed;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container); $headerScroller = $("<div class='slick-header ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container); $headers = $("<div class='slick-header-columns' style='left:-1000px' />").appendTo($headerScroller); $headers.width(getHeadersWidth()); $headerRowScroller = $("<div class='slick-headerrow ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container); $headerRow = $("<div class='slick-headerrow-columns' />").appendTo($headerRowScroller); $headerRowSpacer = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($headerRowScroller); $topPanelScroller = $("<div class='slick-top-panel-scroller ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container); $topPanel = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScroller); if (!options.showTopPanel) { $topPanelScroller.hide(); } if (!options.showHeaderRow) { $headerRowScroller.hide(); } $viewport = $("<div class='slick-viewport' style='width:100%;overflow:auto;outline:0;position:relative;;'>").appendTo($container); $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto"); $canvas = $("<div class='grid-canvas' />").appendTo($viewport); if (options.createFooterRow) { $footerRowScroller = $("<div class='slick-footerrow ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container); $footerRow = $("<div class='slick-footerrow-columns' />").appendTo($footerRowScroller); $footerRowSpacer = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($footerRowScroller); if (!options.showFooterRow) { $footerRowScroller.hide(); } } $focusSink2 = $focusSink.clone().appendTo($container); if (!options.explicitInitialization) { finishInitialization(); } } function finishInitialization() { if (!initialized) { initialized = true; viewportW = parseFloat($.css($container[0], "width", true)); // header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?) // calculate the diff so we can set consistent sizes measureCellPaddingAndBorder(); // for usability reasons, all text selection in SlickGrid is disabled // with the exception of input and textarea elements (selection must // be enabled there so that editors work as expected); note that // selection in grid cells (grid body) is already unavailable in // all browsers except IE disableSelection($headers); // disable all text selection in header (including input and textarea) if (!options.enableTextSelectionOnCells) { // disable text selection in grid cells except in input and textarea elements // (this is IE-specific, because selectstart event will only fire in IE) $viewport.on("selectstart.ui", function (event) { return $(event.target).is("input,textarea"); }); } updateColumnCaches(); createColumnHeaders(); setupColumnSort(); createCssRules(); resizeCanvas(); bindAncestorScrollEvents(); $container .on("resize.slickgrid", resizeCanvas); $viewport //.on("click", handleClick) .on("scroll", handleScroll); $headerScroller .on("contextmenu", handleHeaderContextMenu) .on("click", handleHeaderClick) .on("mouseenter", ".slick-header-column", handleHeaderMouseEnter) .on("mouseleave", ".slick-header-column", handleHeaderMouseLeave); $headerRowScroller .on("scroll", handleHeaderRowScroll); if (options.createFooterRow) { $footerRowScroller .on("scroll", handleFooterRowScroll); } $focusSink.add($focusSink2) .on("keydown", handleKeyDown); $canvas .on("keydown", handleKeyDown) .on("click", handleClick) .on("dblclick", handleDblClick) .on("contextmenu", handleContextMenu) .on("draginit", handleDragInit) .on("dragstart", {distance: 3}, handleDragStart) .on("drag", handleDrag) .on("dragend", handleDragEnd) .on("mouseenter", ".slick-cell", handleMouseEnter) .on("mouseleave", ".slick-cell", handleMouseLeave); // Work around http://crbug.com/312427. if (navigator.userAgent.toLowerCase().match(/webkit/) && navigator.userAgent.toLowerCase().match(/macintosh/)) { $canvas.on("mousewheel", handleMouseWheel); } restoreCssFromHiddenInit(); } } function cacheCssForHiddenInit() { // handle display:none on container or container parents $hiddenParents = $container.parents().addBack().not(':visible'); $hiddenParents.each(function() { var old = {}; for ( var name in cssShow ) { old[ name ] = this.style[ name ]; this.style[ name ] = cssShow[ name ]; } oldProps.push(old); }); } function restoreCssFromHiddenInit() { // finish handle display:none on container or container parents // - put values back the way they were $hiddenParents.each(function(i) { var old = oldProps[i]; for ( var name in cssShow ) { this.style[ name ] = old[ name ]; } }); } function registerPlugin(plugin) { plugins.unshift(plugin); plugin.init(self); } function unregisterPlugin(plugin) { for (var i = plugins.length; i >= 0; i--) { if (plugins[i] === plugin) { if (plugins[i].destroy) { plugins[i].destroy(); } plugins.splice(i, 1); break; } } } function setSelectionModel(model) { if (selectionModel) { selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged); if (selectionModel.destroy) { selectionModel.destroy(); } } selectionModel = model; if (selectionModel) { selectionModel.init(self); selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged); } } function getSelectionModel() { return selectionModel; } function getCanvasNode() { return $canvas[0]; } function measureScrollbar() { var $c = $("<div style='position:absolute; top:-10000px; left:-10000px; width:100px; height:100px; overflow:scroll;'></div>").appendTo("body"); var dim = { width: $c.width() - $c[0].clientWidth, height: $c.height() - $c[0].clientHeight }; $c.remove(); return dim; } function getHeadersWidth() { var headersWidth = 0; for (var i = 0, ii = columns.length; i < ii; i++) { var width = columns[i].width; headersWidth += width; } headersWidth += scrollbarDimensions.width; return Math.max(headersWidth, viewportW) + 1000; } function getCanvasWidth() { var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; var rowWidth = 0; var i = columns.length; while (i--) { rowWidth += columns[i].width; } return options.fullWidthRows ? Math.max(rowWidth, availableWidth) : rowWidth; } function updateCanvasWidth(forceColumnWidthsUpdate) { var oldCanvasWidth = canvasWidth; canvasWidth = getCanvasWidth(); if (canvasWidth != oldCanvasWidth) { $canvas.width(canvasWidth); $headerRow.width(canvasWidth); if (options.createFooterRow) { $footerRow.width(canvasWidth); } $headers.width(getHeadersWidth()); viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width); } var w=canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0); $headerRowSpacer.width(w); if (options.createFooterRow) { $footerRowSpacer.width(w); } if (canvasWidth != oldCanvasWidth || forceColumnWidthsUpdate) { applyColumnWidths(); } } function disableSelection($target) { if ($target && $target.jquery) { $target .attr("unselectable", "on") .css("MozUserSelect", "none") .on("selectstart.ui", function () { return false; }); // from jquery:ui.core.js 1.7.2 } } function getMaxSupportedCssHeight() { var supportedHeight = 1000000; // FF reports the height back but still renders blank after ~6M px var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000; var div = $("<div style='display:none' />").appendTo(document.body); while (true) { var test = supportedHeight * 2; div.css("height", test); if (test > testUpTo || div.height() !== test) { break; } else { supportedHeight = test; } } div.remove(); return supportedHeight; } // TODO: this is static. need to handle page mutation. function bindAncestorScrollEvents() { var elem = $canvas[0]; while ((elem = elem.parentNode) != document.body && elem != null) { // bind to scroll containers only if (elem == $viewport[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) { var $elem = $(elem); if (!$boundAncestors) { $boundAncestors = $elem; } else { $boundAncestors = $boundAncestors.add($elem); } $elem.on("scroll." + uid, handleActiveCellPositionChange); } } } function unbindAncestorScrollEvents() { if (!$boundAncestors) { return; } $boundAncestors.off("scroll." + uid); $boundAncestors = null; } function updateColumnHeader(columnId, title, toolTip) { if (!initialized) { return; } var idx = getColumnIndex(columnId); if (idx == null) { return; } var columnDef = columns[idx]; var $header = $headers.children().eq(idx); if ($header) { if (title !== undefined) { columns[idx].name = title; } if (toolTip !== undefined) { columns[idx].toolTip = toolTip; } trigger(self.onBeforeHeaderCellDestroy, { "node": $header[0], "column": columnDef, "grid": self }); $header .attr("title", toolTip || "") .children().eq(0).html(title); trigger(self.onHeaderCellRendered, { "node": $header[0], "column": columnDef, "grid": self }); } } function getHeaderRow() { return $headerRow[0]; } function getFooterRow() { return $footerRow[0]; } function getHeaderRowColumn(columnId) { var idx = getColumnIndex(columnId); var $header = $headerRow.children().eq(idx); return $header && $header[0]; } function getFooterRowColumn(columnId) { var idx = getColumnIndex(columnId); var $footer = $footerRow.children().eq(idx); return $footer && $footer[0]; } function createColumnHeaders() { function onMouseEnter() { $(this).addClass("ui-state-hover"); } function onMouseLeave() { $(this).removeClass("ui-state-hover"); } $headers.find(".slick-header-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headers.empty(); $headers.width(getHeadersWidth()); $headerRow.find(".slick-headerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headerRow.empty(); if (options.createFooterRow) { $footerRow.find(".slick-footerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef }); } }); $footerRow.empty(); } for (var i = 0; i < columns.length; i++) { var m = columns[i]; var header = $("<div class='ui-state-default slick-header-column' />") .html("<span class='slick-column-name'>" + m.name + "</span>") .width(m.width - headerColumnWidthDiff) .attr("id", "" + uid + m.id) .attr("title", m.toolTip || "") .data("column", m) .addClass(m.headerCssClass || "") .appendTo($headers); if (options.enableColumnReorder || m.sortable) { header .on('mouseenter', onMouseEnter) .on('mouseleave', onMouseLeave); } if (m.sortable) { header.addClass("slick-header-sortable"); header.append("<span class='slick-sort-indicator' />"); } trigger(self.onHeaderCellRendered, { "node": header[0], "column": m, "grid": self }); if (options.showHeaderRow) { var headerRowCell = $("<div class='ui-state-default slick-headerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .appendTo($headerRow); trigger(self.onHeaderRowCellRendered, { "node": headerRowCell[0], "column": m, "grid": self }); } if (options.createFooterRow && options.showFooterRow) { var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .appendTo($footerRow); trigger(self.onFooterRowCellRendered, { "node": footerRowCell[0], "column": m }); } } setSortColumns(sortColumns); setupColumnResize(); if (options.enableColumnReorder) { setupColumnReorder(); } } function setupColumnSort() { $headers.click(function (e) { // temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328) e.metaKey = e.metaKey || e.ctrlKey; if ($(e.target).hasClass("slick-resizable-handle")) { return; } var $col = $(e.target).closest(".slick-header-column"); if (!$col.length) { return; } var column = $col.data("column"); if (column.sortable) { if (!getEditorLock().commitCurrentEdit()) { return; } var sortOpts = null; var i = 0; for (; i < sortColumns.length; i++) { if (sortColumns[i].columnId == column.id) { sortOpts = sortColumns[i]; sortOpts.sortAsc = !sortOpts.sortAsc; break; } } if (e.metaKey && options.multiColumnSort) { if (sortOpts) { sortColumns.splice(i, 1); } } else { if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) { sortColumns = []; } if (!sortOpts) { sortOpts = { columnId: column.id, sortAsc: column.defaultSortAsc }; sortColumns.push(sortOpts); } else if (sortColumns.length == 0) { sortColumns.push(sortOpts); } } setSortColumns(sortColumns); if (!options.multiColumnSort) { trigger(self.onSort, { multiColumnSort: false, sortCol: column, sortAsc: sortOpts.sortAsc, grid: self}, e); } else { trigger(self.onSort, { multiColumnSort: true, sortCols: $.map(sortColumns, function(col) { return {sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc }; }), grid: self}, e); } } }); } function setupColumnReorder() { $headers.filter(":ui-sortable").sortable("destroy"); $headers.sortable({ containment: "parent", distance: 3, axis: "x", cursor: "default", tolerance: "intersection", helper: "clone", placeholder: "slick-sortable-placeholder ui-state-default slick-header-column", start: function (e, ui) { ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff); $(ui.helper).addClass("slick-header-column-active"); }, beforeStop: function (e, ui) { $(ui.helper).removeClass("slick-header-column-active"); }, stop: function (e) { if (!getEditorLock().commitCurrentEdit()) { $(this).sortable("cancel"); return; } var reorderedIds = $headers.sortable("toArray"); var reorderedColumns = []; for (var i = 0; i < reorderedIds.length; i++) { reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]); } setColumns(reorderedColumns); trigger(self.onColumnsReordered, {grid: self}); e.stopPropagation(); setupColumnResize(); } }); } function setupColumnResize() { var $col, j, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable; columnElements = $headers.children(); columnElements.find(".slick-resizable-handle").remove(); columnElements.each(function (i, e) { if (columns[i].resizable) { if (firstResizable === undefined) { firstResizable = i; } lastResizable = i; } }); if (firstResizable === undefined) { return; } columnElements.each(function (i, e) { if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) { return; } $col = $(e); $("<div class='slick-resizable-handle' />") .appendTo(e) .on("dragstart", function (e, dd) { if (!getEditorLock().commitCurrentEdit()) { return false; } pageX = e.pageX; $(this).parent().addClass("slick-header-column-active"); var shrinkLeewayOnRight = null, stretchLeewayOnRight = null; // lock each column's width option to current width columnElements.each(function (i, e) { columns[i].previousWidth = $(e).outerWidth(); }); if (options.forceFitColumns) { shrinkLeewayOnRight = 0; stretchLeewayOnRight = 0; // colums on right affect maxPageX/minPageX for (j = i + 1; j < columnElements.length; j++) { c = columns[j]; if (c.resizable) { if (stretchLeewayOnRight !== null) { if (c.maxWidth) { stretchLeewayOnRight += c.maxWidth - c.previousWidth; } else { stretchLeewayOnRight = null; } } shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } } var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0; for (j = 0; j <= i; j++) { // columns on left only affect minPageX c = columns[j]; if (c.resizable) { if (stretchLeewayOnLeft !== null) { if (c.maxWidth) { stretchLeewayOnLeft += c.maxWidth - c.previousWidth; } else { stretchLeewayOnLeft = null; } } shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } if (shrinkLeewayOnRight === null) { shrinkLeewayOnRight = 100000; } if (shrinkLeewayOnLeft === null) { shrinkLeewayOnLeft = 100000; } if (stretchLeewayOnRight === null) { stretchLeewayOnRight = 100000; } if (stretchLeewayOnLeft === null) { stretchLeewayOnLeft = 100000; } maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft); minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight); }) .on("drag", function (e, dd) { var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x; if (d < 0) { // shrink column x = d; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columnElements.length; j++) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } } } else { // stretch column x = d; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columnElements.length; j++) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } } } } } applyColumnHeaderWidths(); if (options.syncColumnCellResize) { applyColumnWidths(); } }) .on("dragend", function (e, dd) { var newWidth; $(this).parent().removeClass("slick-header-column-active"); for (j = 0; j < columnElements.length; j++) { c = columns[j]; newWidth = $(columnElements[j]).outerWidth(); if (c.previousWidth !== newWidth && c.rerenderOnResize) { invalidateAllRows(); } } updateCanvasWidth(true); render(); trigger(self.onColumnsResized, {grid: self}); }); }); } function getVBoxDelta($el) { var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; var delta = 0; $.each(p, function (n, val) { delta += parseFloat($el.css(val)) || 0; }); return delta; } function measureCellPaddingAndBorder() { var el; var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"]; var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; // jquery prior to version 1.8 handles .width setter/getter as a direct css write/read // jquery 1.8 changed .width to read the true inner element width if box-sizing is set to border-box, and introduced a setter for .outerWidth // so for equivalent functionality, prior to 1.8 use .width, and after use .outerWidth var verArray = $.fn.jquery.split('.'); jQueryNewWidthBehaviour = (verArray[0]==1 && verArray[1]>=8) || verArray[0] >=2; el = $("<div class='ui-state-default slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers); headerColumnWidthDiff = headerColumnHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { headerColumnWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { headerColumnHeightDiff += parseFloat(el.css(val)) || 0; }); } el.remove(); var r = $("<div class='slick-row' />").appendTo($canvas); el = $("<div class='slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r); cellWidthDiff = cellHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { cellWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { cellHeightDiff += parseFloat(el.css(val)) || 0; }); } r.remove(); absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff); } function createCssRules() { $style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head")); var rowHeight = (options.rowHeight - cellHeightDiff); var rules = [ "." + uid + " .slick-header-column { left: 1000px; }", "." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }", "." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }", "." + uid + " .slick-footerrow-columns { height:" + options.footerRowHeight + "px; }", "." + uid + " .slick-cell { height:" + rowHeight + "px; }", "." + uid + " .slick-row { height:" + options.rowHeight + "px; }" ]; for (var i = 0; i < columns.length; i++) { rules.push("." + uid + " .l" + i + " { }"); rules.push("." + uid + " .r" + i + " { }"); } if ($style[0].styleSheet) { // IE $style[0].styleSheet.cssText = rules.join(" "); } else { $style[0].appendChild(document.createTextNode(rules.join(" "))); } } function getColumnCssRules(idx) { if (!stylesheet) { var sheets = document.styleSheets; for (var i = 0; i < sheets.length; i++) { if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) { stylesheet = sheets[i]; break; } } if (!stylesheet) { throw new Error("Cannot find stylesheet."); } // find and cache column CSS rules columnCssRulesL = []; columnCssRulesR = []; var cssRules = (stylesheet.cssRules || stylesheet.rules); var matches, columnIdx; for (var i = 0; i < cssRules.length; i++) { var selector = cssRules[i].selectorText; if (matches = /\.l\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesL[columnIdx] = cssRules[i]; } else if (matches = /\.r\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesR[columnIdx] = cssRules[i]; } } } return { "left": columnCssRulesL[idx], "right": columnCssRulesR[idx] }; } function removeCssRules() { $style.remove(); stylesheet = null; } function destroy() { getEditorLock().cancelCurrentEdit(); trigger(self.onBeforeDestroy, {grid: self}); var i = plugins.length; while(i--) { unregisterPlugin(plugins[i]); } if (options.enableColumnReorder) { $headers.filter(":ui-sortable").sortable("destroy"); } unbindAncestorScrollEvents(); $container.off(".slickgrid"); removeCssRules(); $canvas.off("draginit dragstart dragend drag"); $container.empty().removeClass(uid); } ////////////////////////////////////////////////////////////////////////////////////////////// // General function trigger(evt, args, e) { e = e || new Slick.EventData(); args = args || {}; args.grid = self; return evt.notify(args, e, self); } function getEditorLock() { return options.editorLock; } function getEditController() { return editController; } function getColumnIndex(id) { return columnsById[id]; } function autosizeColumns() { var i, c, widths = [], shrinkLeeway = 0, total = 0, prevTotal, availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; for (i = 0; i < columns.length; i++) { c = columns[i]; widths.push(c.width); total += c.width; if (c.resizable) { shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth); } } // shrink prevTotal = total; while (total > availWidth && shrinkLeeway) { var shrinkProportion = (total - availWidth) / shrinkLeeway; for (i = 0; i < columns.length && total > availWidth; i++) { c = columns[i]; var width = widths[i]; if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) { continue; } var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth); var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1; shrinkSize = Math.min(shrinkSize, width - absMinWidth); total -= shrinkSize; shrinkLeeway -= shrinkSize; widths[i] -= shrinkSize; } if (prevTotal <= total) { // avoid infinite loop break; } prevTotal = total; } // grow prevTotal = total; while (total < availWidth) { var growProportion = availWidth / total; for (i = 0; i < columns.length && total < availWidth; i++) { c = columns[i]; var currentWidth = widths[i]; var growSize; if (!c.resizable || c.maxWidth <= currentWidth) { growSize = 0; } else { growSize = Math.min(Math.floor(growProportion * currentWidth) - currentWidth, (c.maxWidth - currentWidth) || 1000000) || 1; } total += growSize; widths[i] += (total <= availWidth ? growSize : 0); } if (prevTotal >= total) { // avoid infinite loop break; } prevTotal = total; } var reRender = false; for (i = 0; i < columns.length; i++) { if (columns[i].rerenderOnResize && columns[i].width != widths[i]) { reRender = true; } columns[i].width = widths[i]; } applyColumnHeaderWidths(); updateCanvasWidth(true); if (reRender) { invalidateAllRows(); render(); } } function applyColumnHeaderWidths() { if (!initialized) { return; } var h; for (var i = 0, headers = $headers.children(), ii = headers.length; i < ii; i++) { h = $(headers[i]); if (jQueryNewWidthBehaviour) { if (h.outerWidth() !== columns[i].width) { h.outerWidth(columns[i].width); } } else { if (h.width() !== columns[i].width - headerColumnWidthDiff) { h.width(columns[i].width - headerColumnWidthDiff); } } } updateColumnCaches(); } function applyColumnWidths() { var x = 0, w, rule; for (var i = 0; i < columns.length; i++) { w = columns[i].width; rule = getColumnCssRules(i); rule.left.style.left = x + "px"; rule.right.style.right = (canvasWidth - x - w) + "px"; x += columns[i].width; } } function setSortColumn(columnId, ascending) { setSortColumns([{ columnId: columnId, sortAsc: ascending}]); } function setSortColumns(cols) { sortColumns = cols; var headerColumnEls = $headers.children(); headerColumnEls .removeClass("slick-header-column-sorted") .find(".slick-sort-indicator") .removeClass("slick-sort-indicator-asc slick-sort-indicator-desc"); $.each(sortColumns, function(i, col) { if (col.sortAsc == null) { col.sortAsc = true; } var columnIndex = getColumnIndex(col.columnId); if (columnIndex != null) { headerColumnEls.eq(columnIndex) .addClass("slick-header-column-sorted") .find(".slick-sort-indicator") .addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc"); } }); } function getSortColumns() { return sortColumns; } function handleSelectedRangesChanged(e, ranges) { selectedRows = []; var hash = {}; for (var i = 0; i < ranges.length; i++) { for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) { if (!hash[j]) { // prevent duplicates selectedRows.push(j); hash[j] = {}; } for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) { if (canCellBeSelected(j, k)) { hash[j][columns[k].id] = options.selectedCellCssClass; } } } } setCellCssStyles(options.selectedCellCssClass, hash); trigger(self.onSelectedRowsChanged, {rows: getSelectedRows(), grid: self}, e); } function getColumns() { return columns; } function updateColumnCaches() { // Pre-calculate cell boundaries. columnPosLeft = []; columnPosRight = []; var x = 0; for (var i = 0, ii = columns.length; i < ii; i++) { columnPosLeft[i] = x; columnPosRight[i] = x + columns[i].width; x += columns[i].width; } } function setColumns(columnDefinitions) { columns = columnDefinitions; columnsById = {}; for (var i = 0; i < columns.length; i++) { var m = columns[i] = $.extend({}, columnDefaults, columns[i]); columnsById[m.id] = i; if (m.minWidth && m.width < m.minWidth) { m.width = m.minWidth; } if (m.maxWidth && m.width > m.maxWidth) { m.width = m.maxWidth; } } updateColumnCaches(); if (initialized) { invalidateAllRows(); createColumnHeaders(); removeCssRules(); createCssRules(); resizeCanvas(); applyColumnWidths(); handleScroll(); } } function getOptions() { return options; } function setOptions(args) { if (!getEditorLock().commitCurrentEdit()) { return; } makeActiveCellNormal(); if (options.enableAddRow !== args.enableAddRow) { invalidateRow(getDataLength()); } options = $.extend(options, args); validateAndEnforceOptions(); $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto"); render(); } function validateAndEnforceOptions() { if (options.autoHeight) { options.leaveSpaceForNewRows = false; } } function setData(newData, scrollToTop) { data = newData; invalidateAllRows(); updateRowCount(); if (scrollToTop) { scrollTo(0); } } function getData() { return data; } function getDataLength() { if (data.getLength) { return data.getLength(); } else { return data.length; } } function getDataLengthIncludingAddNew() { return getDataLength() + (!options.enableAddRow ? 0 : (!pagingActive || pagingIsLastPage ? 1 : 0) ); } function getDataItem(i) { if (data.getItem) { return data.getItem(i); } else { return data[i]; } } function getTopPanel() { return $topPanel[0]; } function setTopPanelVisibility(visible) { if (options.showTopPanel != visible) { options.showTopPanel = visible; if (visible) { $topPanelScroller.slideDown("fast", resizeCanvas); } else { $topPanelScroller.slideUp("fast", resizeCanvas); } } } function setHeaderRowVisibility(visible) { if (options.showHeaderRow != visible) { options.showHeaderRow = visible; if (visible) { $headerRowScroller.slideDown("fast", resizeCanvas); } else { $headerRowScroller.slideUp("fast", resizeCanvas); } } } function setFooterRowVisibility(visible) { if (options.showFooterRow != visible) { options.showFooterRow = visible; if (visible) { $footerRowScroller.slideDown("fast", resizeCanvas); } else { $footerRowScroller.slideUp("fast", resizeCanvas); } } } function getContainerNode() { return $container.get(0); } ////////////////////////////////////////////////////////////////////////////////////////////// // Rendering / Scrolling function getRowTop(row) { return options.rowHeight * row - offset; } function getRowFromPosition(y) { return Math.floor((y + offset) / options.rowHeight); } function scrollTo(y) { y = Math.max(y, 0); y = Math.min(y, th - viewportH + (viewportHasHScroll ? scrollbarDimensions.height : 0)); var oldOffset = offset; page = Math.min(n - 1, Math.floor(y / ph)); offset = Math.round(page * cj); var newScrollTop = y - offset; if (offset != oldOffset) { var range = getVisibleRange(newScrollTop); cleanupRows(range); updateRowPositions(); } if (prevScrollTop != newScrollTop) { vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1; $viewport[0].scrollTop = (lastRenderedScrollTop = scrollTop = prevScrollTop = newScrollTop); trigger(self.onViewportChanged, {grid: self}); } } function defaultFormatter(row, cell, value, columnDef, dataContext) { if (value == null) { return ""; } else { return (value + "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); } } function getFormatter(row, column) { var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); // look up by id, then index var columnOverrides = rowMetadata && rowMetadata.columns && (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]); return (columnOverrides && columnOverrides.formatter) || (rowMetadata && rowMetadata.formatter) || column.formatter || (options.formatterFactory && options.formatterFactory.getFormatter(column)) || options.defaultFormatter; } function getEditor(row, cell) { var column = columns[cell]; var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) { return columnMetadata[column.id].editor; } if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) { return columnMetadata[cell].editor; } return column.editor || (options.editorFactory && options.editorFactory.getEditor(column)); } function getDataItemValueForColumn(item, columnDef) { if (options.dataItemColumnValueExtractor) { return options.dataItemColumnValueExtractor(item, columnDef); } return item[columnDef.field]; } function appendRowHtml(stringArray, row, range, dataLength) { var d = getDataItem(row); var dataLoading = row < dataLength && !d; var rowCss = "slick-row" + (dataLoading ? " loading" : "") + (row === activeRow ? " active" : "") + (row % 2 == 1 ? " odd" : " even"); if (!d) { rowCss += " " + options.addNewRowCssClass; } var metadata = data.getItemMetadata && data.getItemMetadata(row); if (metadata && metadata.cssClasses) { rowCss += " " + metadata.cssClasses; } stringArray.push("<div class='ui-widget-content " + rowCss + "' style='top:" + getRowTop(row) + "px'>"); var colspan, m; for (var i = 0, ii = columns.length; i < ii; i++) { m = columns[i]; colspan = 1; if (metadata && metadata.columns) { var columnData = metadata.columns[m.id] || metadata.columns[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } // Do not render cells outside of the viewport. if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { if (columnPosLeft[i] > range.rightPx) { // All columns to the right are outside the range. break; } appendCellHtml(stringArray, row, i, colspan, d); } if (colspan > 1) { i += (colspan - 1); } } stringArray.push("</div>"); } function appendCellHtml(stringArray, row, cell, colspan, item) { // stringArray: stringBuilder containing the HTML parts // row, cell: row and column index // colspan: HTML colspan // item: grid data for row var m = columns[cell]; var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1) + (m.cssClass ? " " + m.cssClass : ""); if (row === activeRow && cell === activeCell) { cellCss += (" active"); } // TODO: merge them together in the setter for (var key in cellCssClasses) { if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) { cellCss += (" " + cellCssClasses[key][row][m.id]); } } stringArray.push("<div class='" + cellCss + "'>"); // if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet) if (item) { var value = getDataItemValueForColumn(item, m); stringArray.push(getFormatter(row, m)(row, cell, value, m, item)); } stringArray.push("</div>"); rowsCache[row].cellRenderQueue.push(cell); rowsCache[row].cellColSpans[cell] = colspan; } function cleanupRows(rangeToKeep) { for (var i in rowsCache) { if (((i = parseInt(i, 10)) !== activeRow) && (i < rangeToKeep.top || i > rangeToKeep.bottom)) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidate() { updateRowCount(); invalidateAllRows(); render(); } function invalidateAllRows() { if (currentEditor) { makeActiveCellNormal(); } for (var row in rowsCache) { removeRowFromCache(row); } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function queuePostProcessedRowForCleanup(cacheEntry, postProcessedRow, rowIdx) { postProcessgroupId++; // store and detach node for later async cleanup for (var columnIdx in postProcessedRow) { if (postProcessedRow.hasOwnProperty(columnIdx)) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cacheEntry.cellNodesByColumnIdx[ columnIdx | 0], columnIdx: columnIdx | 0, rowIdx: rowIdx }); } } postProcessedCleanupQueue.push({ actionType: 'R', groupId: postProcessgroupId, node: cacheEntry.rowNode }); $(cacheEntry.rowNode).detach(); } function queuePostProcessedCellForCleanup(cellnode, columnIdx, rowIdx) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cellnode, columnIdx: columnIdx, rowIdx: rowIdx }); $(cellnode).detach(); } function removeRowFromCache(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } if (rowNodeFromLastMouseWheelEvent === cacheEntry.rowNode) { cacheEntry.rowNode.style.display = 'none'; zombieRowNodeFromLastMouseWheelEvent = rowNodeFromLastMouseWheelEvent; zombieRowCacheFromLastMouseWheelEvent = cacheEntry; zombieRowPostProcessedFromLastMouseWheelEvent = postProcessedRows[row]; // ignore post processing cleanup in this case - it will be dealt with later } else { if (options.enableAsyncPostRenderCleanup && postProcessedRows[row]) { queuePostProcessedRowForCleanup(cacheEntry, postProcessedRows[row], row); } else { $canvas[0].removeChild(cacheEntry.rowNode); } } delete rowsCache[row]; delete postProcessedRows[row]; renderedRows--; counter_rows_removed++; } function invalidateRows(rows) { var i, rl; if (!rows || !rows.length) { return; } vScrollDir = 0; rl = rows.length; for (i = 0; i < rl; i++) { if (currentEditor && activeRow === rows[i]) { makeActiveCellNormal(); } if (rowsCache[rows[i]]) { removeRowFromCache(rows[i]); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidateRow(row) { invalidateRows([row]); } function updateCell(row, cell) { var cellNode = getCellNode(row, cell); if (!cellNode) { return; } var m = columns[cell], d = getDataItem(row); if (currentEditor && activeRow === row && activeCell === cell) { currentEditor.loadValue(d); } else { cellNode.innerHTML = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d) : ""; invalidatePostProcessingResults(row); } } function updateRow(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } ensureCellNodesInRowsCache(row); var d = getDataItem(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx], node = cacheEntry.cellNodesByColumnIdx[columnIdx]; if (row === activeRow && columnIdx === activeCell && currentEditor) { currentEditor.loadValue(d); } else if (d) { node.innerHTML = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d); } else { node.innerHTML = ""; } } invalidatePostProcessingResults(row); } function getViewportHeight() { return parseFloat($.css($container[0], "height", true)) - parseFloat($.css($container[0], "paddingTop", true)) - parseFloat($.css($container[0], "paddingBottom", true)) - parseFloat($.css($headerScroller[0], "height")) - getVBoxDelta($headerScroller) - (options.showTopPanel ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0) - (options.showHeaderRow ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0) - (options.createFooterRow && options.showFooterRow ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0); } function resizeCanvas() { if (!initialized) { return; } if (options.autoHeight) { viewportH = options.rowHeight * getDataLengthIncludingAddNew(); } else { viewportH = getViewportHeight(); } numVisibleRows = Math.ceil(viewportH / options.rowHeight); viewportW = parseFloat($.css($container[0], "width", true)); if (!options.autoHeight) { $viewport.height(viewportH); } if (options.forceFitColumns) { autosizeColumns(); } updateRowCount(); handleScroll(); // Since the width has changed, force the render() to reevaluate virtually rendered cells. lastRenderedScrollLeft = -1; render(); } function updatePagingStatusFromView( pagingInfo ) { pagingActive = (pagingInfo.pageSize !== 0); pagingIsLastPage = (pagingInfo.pageNum == pagingInfo.totalPages - 1); } function updateRowCount() { if (!initialized) { return; } var dataLength = getDataLength(); var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); var numberOfRows = dataLengthIncludingAddNew + (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0); var oldViewportHasVScroll = viewportHasVScroll; // with autoHeight, we do not need to accommodate the vertical scroll bar viewportHasVScroll = !options.autoHeight && (numberOfRows * options.rowHeight > viewportH); viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width); makeActiveCellNormal(); // remove the rows that are now outside of the data range // this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows var r1 = dataLength - 1; for (var i in rowsCache) { if (i > r1) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } if (activeCellNode && activeRow > r1) { resetActiveCell(); } var oldH = h; th = Math.max(options.rowHeight * numberOfRows, viewportH - scrollbarDimensions.height); if (th < maxSupportedCssHeight) { // just one page h = ph = th; n = 1; cj = 0; } else { // break into pages h = maxSupportedCssHeight; ph = h / 100; n = Math.floor(th / ph); cj = (th - h) / (n - 1); } if (h !== oldH) { $canvas.css("height", h); scrollTop = $viewport[0].scrollTop; } var oldScrollTopInRange = (scrollTop + offset <= th - viewportH); if (th == 0 || scrollTop == 0) { page = offset = 0; } else if (oldScrollTopInRange) { // maintain virtual position scrollTo(scrollTop + offset); } else { // scroll to bottom scrollTo(th - viewportH); } if (h != oldH && options.autoHeight) { resizeCanvas(); } if (options.forceFitColumns && oldViewportHasVScroll != viewportHasVScroll) { autosizeColumns(); } updateCanvasWidth(false); } function getVisibleRange(viewportTop, viewportLeft) { if (viewportTop == null) { viewportTop = scrollTop; } if (viewportLeft == null) { viewportLeft = scrollLeft; } return { top: getRowFromPosition(viewportTop), bottom: getRowFromPosition(viewportTop + viewportH) + 1, leftPx: viewportLeft, rightPx: viewportLeft + viewportW }; } function getRenderedRange(viewportTop, viewportLeft) { var range = getVisibleRange(viewportTop, viewportLeft); var buffer = Math.round(viewportH / options.rowHeight); var minBuffer = 3; if (vScrollDir == -1) { range.top -= buffer; range.bottom += minBuffer; } else if (vScrollDir == 1) { range.top -= minBuffer; range.bottom += buffer; } else { range.top -= minBuffer; range.bottom += minBuffer; } range.top = Math.max(0, range.top); range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom); range.leftPx -= viewportW; range.rightPx += viewportW; range.leftPx = Math.max(0, range.leftPx); range.rightPx = Math.min(canvasWidth, range.rightPx); return range; } function ensureCellNodesInRowsCache(row) { var cacheEntry = rowsCache[row]; if (cacheEntry) { if (cacheEntry.cellRenderQueue.length) { var lastChild = cacheEntry.rowNode.lastChild; while (cacheEntry.cellRenderQueue.length) { var columnIdx = cacheEntry.cellRenderQueue.pop(); cacheEntry.cellNodesByColumnIdx[columnIdx] = lastChild; lastChild = lastChild.previousSibling; } } } } function cleanUpCells(range, row) { var totalCellsRemoved = 0; var cacheEntry = rowsCache[row]; // Remove cells outside the range. var cellsToRemove = []; for (var i in cacheEntry.cellNodesByColumnIdx) { // I really hate it when people mess with Array.prototype. if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) { continue; } // This is a string, so it needs to be cast back to a number. i = i | 0; var colspan = cacheEntry.cellColSpans[i]; if (columnPosLeft[i] > range.rightPx || columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) { if (!(row == activeRow && i == activeCell)) { cellsToRemove.push(i); } } } var cellToRemove, node; postProcessgroupId++; while ((cellToRemove = cellsToRemove.pop()) != null) { node = cacheEntry.cellNodesByColumnIdx[cellToRemove]; if (options.enableAsyncPostRenderCleanup && postProcessedRows[row] && postProcessedRows[row][cellToRemove]) { queuePostProcessedCellForCleanup(node, cellToRemove, row); } else { cacheEntry.rowNode.removeChild(node); } delete cacheEntry.cellColSpans[cellToRemove]; delete cacheEntry.cellNodesByColumnIdx[cellToRemove]; if (postProcessedRows[row]) { delete postProcessedRows[row][cellToRemove]; } totalCellsRemoved++; } } function cleanUpAndRenderCells(range) { var cacheEntry; var stringArray = []; var processedRows = []; var cellsAdded; var totalCellsAdded = 0; var colspan; for (var row = range.top, btm = range.bottom; row <= btm; row++) { cacheEntry = rowsCache[row]; if (!cacheEntry) { continue; } // cellRenderQueue populated in renderRows() needs to be cleared first ensureCellNodesInRowsCache(row); cleanUpCells(range, row); // Render missing cells. cellsAdded = 0; var metadata = data.getItemMetadata && data.getItemMetadata(row); metadata = metadata && metadata.columns; var d = getDataItem(row); // TODO: shorten this loop (index? heuristics? binary search?) for (var i = 0, ii = columns.length; i < ii; i++) { // Cells to the right are outside the range. if (columnPosLeft[i] > range.rightPx) { break; } // Already rendered. if ((colspan = cacheEntry.cellColSpans[i]) != null) { i += (colspan > 1 ? colspan - 1 : 0); continue; } colspan = 1; if (metadata) { var columnData = metadata[columns[i].id] || metadata[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { appendCellHtml(stringArray, row, i, colspan, d); cellsAdded++; } i += (colspan > 1 ? colspan - 1 : 0); } if (cellsAdded) { totalCellsAdded += cellsAdded; processedRows.push(row); } } if (!stringArray.length) { return; } var x = document.createElement("div"); x.innerHTML = stringArray.join(""); var processedRow; var node; while ((processedRow = processedRows.pop()) != null) { cacheEntry = rowsCache[processedRow]; var columnIdx; while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) { node = x.lastChild; cacheEntry.rowNode.appendChild(node); cacheEntry.cellNodesByColumnIdx[columnIdx] = node; } } } function renderRows(range) { var parentNode = $canvas[0], stringArray = [], rows = [], needToReselectCell = false, dataLength = getDataLength(); for (var i = range.top, ii = range.bottom; i <= ii; i++) { if (rowsCache[i]) { continue; } renderedRows++; rows.push(i); // Create an entry right away so that appendRowHtml() can // start populatating it. rowsCache[i] = { "rowNode": null, // ColSpans of rendered cells (by column idx). // Can also be used for checking whether a cell has been rendered. "cellColSpans": [], // Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache(). "cellNodesByColumnIdx": [], // Column indices of cell nodes that have been rendered, but not yet indexed in // cellNodesByColumnIdx. These are in the same order as cell nodes added at the // end of the row. "cellRenderQueue": [] }; appendRowHtml(stringArray, i, range, dataLength); if (activeCellNode && activeRow === i) { needToReselectCell = true; } counter_rows_rendered++; } if (!rows.length) { return; } var x = document.createElement("div"); x.innerHTML = stringArray.join(""); for (var i = 0, ii = rows.length; i < ii; i++) { rowsCache[rows[i]].rowNode = parentNode.appendChild(x.firstChild); } if (needToReselectCell) { activeCellNode = getCellNode(activeRow, activeCell); } } function startPostProcessing() { if (!options.enableAsyncPostRender) { return; } clearTimeout(h_postrender); h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); } function startPostProcessingCleanup() { if (!options.enableAsyncPostRenderCleanup) { return; } clearTimeout(h_postrenderCleanup); h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } function invalidatePostProcessingResults(row) { // change status of columns to be re-rendered for (var columnIdx in postProcessedRows[row]) { if (postProcessedRows[row].hasOwnProperty(columnIdx)) { postProcessedRows[row][columnIdx] = 'C'; } } postProcessFromRow = Math.min(postProcessFromRow, row); postProcessToRow = Math.max(postProcessToRow, row); startPostProcessing(); } function updateRowPositions() { for (var row in rowsCache) { rowsCache[row].rowNode.style.top = getRowTop(row) + "px"; } } function render() { if (!initialized) { return; } var visible = getVisibleRange(); var rendered = getRenderedRange(); // remove rows no longer in the viewport cleanupRows(rendered); // add new rows & missing cells in existing rows if (lastRenderedScrollLeft != scrollLeft) { cleanUpAndRenderCells(rendered); } // render missing rows renderRows(rendered); postProcessFromRow = visible.top; postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom); startPostProcessing(); lastRenderedScrollTop = scrollTop; lastRenderedScrollLeft = scrollLeft; h_render = null; } function handleHeaderRowScroll() { var scrollLeft = $headerRowScroller[0].scrollLeft; if (scrollLeft != $viewport[0].scrollLeft) { $viewport[0].scrollLeft = scrollLeft; } } function handleFooterRowScroll() { var scrollLeft = $footerRowScroller[0].scrollLeft; if (scrollLeft != $viewport[0].scrollLeft) { $viewport[0].scrollLeft = scrollLeft; } } function handleScroll() { scrollTop = $viewport[0].scrollTop; scrollLeft = $viewport[0].scrollLeft; var vScrollDist = Math.abs(scrollTop - prevScrollTop); var hScrollDist = Math.abs(scrollLeft - prevScrollLeft); if (hScrollDist) { prevScrollLeft = scrollLeft; $headerScroller[0].scrollLeft = scrollLeft; $topPanelScroller[0].scrollLeft = scrollLeft; $headerRowScroller[0].scrollLeft = scrollLeft; if (options.createFooterRow) { $footerRowScroller[0].scrollLeft = scrollLeft; } } if (vScrollDist) { vScrollDir = prevScrollTop < scrollTop ? 1 : -1; prevScrollTop = scrollTop; // switch virtual pages if needed if (vScrollDist < viewportH) { scrollTo(scrollTop + offset); } else { var oldOffset = offset; if (h == viewportH) { page = 0; } else { page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph))); } offset = Math.round(page * cj); if (oldOffset != offset) { invalidateAllRows(); } } } if (hScrollDist || vScrollDist) { if (h_render) { clearTimeout(h_render); } if (Math.abs(lastRenderedScrollTop - scrollTop) > 20 || Math.abs(lastRenderedScrollLeft - scrollLeft) > 20) { if (options.forceSyncScrolling || ( Math.abs(lastRenderedScrollTop - scrollTop) < viewportH && Math.abs(lastRenderedScrollLeft - scrollLeft) < viewportW)) { render(); } else { h_render = setTimeout(render, 50); } trigger(self.onViewportChanged, {grid: self}); } } trigger(self.onScroll, {scrollLeft: scrollLeft, scrollTop: scrollTop, grid: self}); } function asyncPostProcessRows() { var dataLength = getDataLength(); while (postProcessFromRow <= postProcessToRow) { var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--; var cacheEntry = rowsCache[row]; if (!cacheEntry || row >= dataLength) { continue; } if (!postProcessedRows[row]) { postProcessedRows[row] = {}; } ensureCellNodesInRowsCache(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx]; var processedStatus = postProcessedRows[row][columnIdx]; // C=cleanup and re-render, R=rendered if (m.asyncPostRender && processedStatus !== 'R') { var node = cacheEntry.cellNodesByColumnIdx[columnIdx]; if (node) { m.asyncPostRender(node, row, getDataItem(row), m, (processedStatus === 'C')); } postProcessedRows[row][columnIdx] = 'R'; } } h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); return; } } function asyncPostProcessCleanupRows() { if (postProcessedCleanupQueue.length > 0) { var groupId = postProcessedCleanupQueue[0].groupId; // loop through all queue members with this groupID while (postProcessedCleanupQueue.length > 0 && postProcessedCleanupQueue[0].groupId == groupId) { var entry = postProcessedCleanupQueue.shift(); if (entry.actionType == 'R') { $(entry.node).remove(); } if (entry.actionType == 'C') { var column = columns[entry.columnIdx]; if (column.asyncPostRenderCleanup && entry.node) { // cleanup must also remove element column.asyncPostRenderCleanup(entry.node, entry.rowIdx, column); } } } // call this function again after the specified delay h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } } function updateCellCssStylesOnRenderedRows(addedHash, removedHash) { var node, columnId, addedRowHash, removedRowHash; for (var row in rowsCache) { removedRowHash = removedHash && removedHash[row]; addedRowHash = addedHash && addedHash[row]; if (removedRowHash) { for (columnId in removedRowHash) { if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).removeClass(removedRowHash[columnId]); } } } } if (addedRowHash) { for (columnId in addedRowHash) { if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).addClass(addedRowHash[columnId]); } } } } } } function addCellCssStyles(key, hash) { if (cellCssClasses[key]) { throw "addCellCssStyles: cell CSS hash with key '" + key + "' already exists."; } cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, null); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function removeCellCssStyles(key) { if (!cellCssClasses[key]) { return; } updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]); delete cellCssClasses[key]; trigger(self.onCellCssStylesChanged, { "key": key, "hash": null, "grid": self }); } function setCellCssStyles(key, hash) { var prevHash = cellCssClasses[key]; cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, prevHash); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function getCellCssStyles(key) { return cellCssClasses[key]; } function flashCell(row, cell, speed) { speed = speed || 100; if (rowsCache[row]) { var $cell = $(getCellNode(row, cell)); function toggleCellClass(times) { if (!times) { return; } setTimeout(function () { $cell.queue(function () { $cell.toggleClass(options.cellFlashingCssClass).dequeue(); toggleCellClass(times - 1); }); }, speed); } toggleCellClass(4); } } ////////////////////////////////////////////////////////////////////////////////////////////// // Interactivity function handleMouseWheel(e) { var rowNode = $(e.target).closest(".slick-row")[0]; if (rowNode != rowNodeFromLastMouseWheelEvent) { if (zombieRowNodeFromLastMouseWheelEvent && zombieRowNodeFromLastMouseWheelEvent != rowNode) { if (options.enableAsyncPostRenderCleanup && zombieRowPostProcessedFromLastMouseWheelEvent) { queuePostProcessedRowForCleanup(zombieRowCacheFromLastMouseWheelEvent, zombieRowPostProcessedFromLastMouseWheelEvent); } else { $canvas[0].removeChild(zombieRowNodeFromLastMouseWheelEvent); } zombieRowNodeFromLastMouseWheelEvent = null; zombieRowCacheFromLastMouseWheelEvent = null; zombieRowPostProcessedFromLastMouseWheelEvent = null; if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } rowNodeFromLastMouseWheelEvent = rowNode; } } function handleDragInit(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragInit, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } // if nobody claims to be handling drag'n'drop by stopping immediate propagation, // cancel out of it return false; } function handleDragStart(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragStart, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } return false; } function handleDrag(e, dd) { return trigger(self.onDrag, dd, e); } function handleDragEnd(e, dd) { trigger(self.onDragEnd, dd, e); } function handleKeyDown(e) { trigger(self.onKeyDown, {row: activeRow, cell: activeCell, grid: self}, e); var handled = e.isImmediatePropagationStopped(); var keyCode = Slick.keyCode; if (!handled) { if (!e.shiftKey && !e.altKey && !e.ctrlKey) { // editor may specify an array of keys to bubble if (options.editable && currentEditor && currentEditor.keyCaptureList) { if (currentEditor.keyCaptureList.indexOf( e.which ) > -1) { return; } } if (e.which == keyCode.ESCAPE) { if (!getEditorLock().isActive()) { return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event) } cancelEditAndSetFocus(); } else if (e.which == keyCode.PAGE_DOWN) { navigatePageDown(); handled = true; } else if (e.which == keyCode.PAGE_UP) { navigatePageUp(); handled = true; } else if (e.which == keyCode.LEFT) { handled = navigateLeft(); } else if (e.which == keyCode.RIGHT) { handled = navigateRight(); } else if (e.which == keyCode.UP) { handled = navigateUp(); } else if (e.which == keyCode.DOWN) { handled = navigateDown(); } else if (e.which == keyCode.TAB) { handled = navigateNext(); } else if (e.which == keyCode.ENTER) { if (options.editable) { if (currentEditor) { // adding new row if (activeRow === getDataLength()) { navigateDown(); } else { commitEditAndSetFocus(); } } else { if (getEditorLock().commitCurrentEdit()) { makeActiveCellEditable(); } } } handled = true; } } else if (e.which == keyCode.TAB && e.shiftKey && !e.ctrlKey && !e.altKey) { handled = navigatePrev(); } } if (handled) { // the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it e.stopPropagation(); e.preventDefault(); try { e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.) } // ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl" // (hitting control key only, nothing else), "Shift" (maybe others) catch (error) { } } } function handleClick(e) { if (!currentEditor) { // if this click resulted in some cell child node getting focus, // don't steal it back - keyboard events will still bubble up // IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly. if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) { setFocus(); } } var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onClick, {row: cell.row, cell: cell.cell, grid: self}, e); if (e.isImmediatePropagationStopped()) { return; } if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) { if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) { scrollRowIntoView(cell.row, false); setActiveCellInternal(getCellNode(cell.row, cell.cell)); } } } function handleContextMenu(e) { var $cell = $(e.target).closest(".slick-cell", $canvas); if ($cell.length === 0) { return; } // are we editing this cell? if (activeCellNode === $cell[0] && currentEditor !== null) { return; } trigger(self.onContextMenu, {grid: self}, e); } function handleDblClick(e) { var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onDblClick, {row: cell.row, cell: cell.cell, grid: self}, e); if (e.isImmediatePropagationStopped()) { return; } if (options.editable) { gotoCell(cell.row, cell.cell, true); } } function handleHeaderMouseEnter(e) { trigger(self.onHeaderMouseEnter, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderMouseLeave(e) { trigger(self.onHeaderMouseLeave, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderContextMenu(e) { var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); trigger(self.onHeaderContextMenu, {column: column, grid: self}, e); } function handleHeaderClick(e) { var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); if (column) { trigger(self.onHeaderClick, {column: column, grid: self}, e); } } function handleMouseEnter(e) { trigger(self.onMouseEnter, {grid: self}, e); } function handleMouseLeave(e) { trigger(self.onMouseLeave, {grid: self}, e); } function cellExists(row, cell) { return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length); } function getCellFromPoint(x, y) { var row = getRowFromPosition(y); var cell = 0; var w = 0; for (var i = 0; i < columns.length && w < x; i++) { w += columns[i].width; cell++; } if (cell < 0) { cell = 0; } return {row: row, cell: cell - 1}; } function getCellFromNode(cellNode) { // read column number from .l<columnNumber> CSS class var cls = /l\d+/.exec(cellNode.className); if (!cls) { throw "getCellFromNode: cannot get cell - " + cellNode.className; } return parseInt(cls[0].substr(1, cls[0].length - 1), 10); } function getRowFromNode(rowNode) { for (var row in rowsCache) { if (rowsCache[row].rowNode === rowNode) { return row | 0; } } return null; } function getCellFromEvent(e) { var $cell = $(e.target).closest(".slick-cell", $canvas); if (!$cell.length) { return null; } var row = getRowFromNode($cell[0].parentNode); var cell = getCellFromNode($cell[0]); if (row == null || cell == null) { return null; } else { return { "row": row, "cell": cell }; } } function getCellNodeBox(row, cell) { if (!cellExists(row, cell)) { return null; } var y1 = getRowTop(row); var y2 = y1 + options.rowHeight - 1; var x1 = 0; for (var i = 0; i < cell; i++) { x1 += columns[i].width; } var x2 = x1 + columns[cell].width; return { top: y1, left: x1, bottom: y2, right: x2 }; } ////////////////////////////////////////////////////////////////////////////////////////////// // Cell switching function resetActiveCell() { setActiveCellInternal(null, false); } function setFocus() { if (tabbingDirection == -1) { $focusSink[0].focus(); } else { $focusSink2[0].focus(); } } function scrollCellIntoView(row, cell, doPaging) { scrollRowIntoView(row, doPaging); var colspan = getColspan(row, cell); var left = columnPosLeft[cell], right = columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)], scrollRight = scrollLeft + viewportW; if (left < scrollLeft) { $viewport.scrollLeft(left); handleScroll(); render(); } else if (right > scrollRight) { $viewport.scrollLeft(Math.min(left, right - $viewport[0].clientWidth)); handleScroll(); render(); } } function setActiveCellInternal(newCell, opt_editMode) { if (activeCellNode !== null) { makeActiveCellNormal(); $(activeCellNode).removeClass("active"); if (rowsCache[activeRow]) { $(rowsCache[activeRow].rowNode).removeClass("active"); } } var activeCellChanged = (activeCellNode !== newCell); activeCellNode = newCell; if (activeCellNode != null) { activeRow = getRowFromNode(activeCellNode.parentNode); activeCell = activePosX = getCellFromNode(activeCellNode); if (opt_editMode == null) { opt_editMode = (activeRow == getDataLength()) || options.autoEdit; } $(activeCellNode).addClass("active"); $(rowsCache[activeRow].rowNode).addClass("active"); if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) { clearTimeout(h_editorLoader); if (options.asyncEditorLoading) { h_editorLoader = setTimeout(function () { makeActiveCellEditable(); }, options.asyncEditorLoadDelay); } else { makeActiveCellEditable(); } } } else { activeRow = activeCell = null; } if (activeCellChanged) { trigger(self.onActiveCellChanged, getActiveCell()); } } function clearTextSelection() { if (document.selection && document.selection.empty) { try { //IE fails here if selected element is not in dom document.selection.empty(); } catch (e) { } } else if (window.getSelection) { var sel = window.getSelection(); if (sel && sel.removeAllRanges) { sel.removeAllRanges(); } } } function isCellPotentiallyEditable(row, cell) { var dataLength = getDataLength(); // is the data for this row loaded? if (row < dataLength && !getDataItem(row)) { return false; } // are we in the Add New row? can we create new from this cell? if (columns[cell].cannotTriggerInsert && row >= dataLength) { return false; } // does this cell have an editor? if (!getEditor(row, cell)) { return false; } return true; } function makeActiveCellNormal() { if (!currentEditor) { return; } trigger(self.onBeforeCellEditorDestroy, {editor: currentEditor, grid: self}); currentEditor.destroy(); currentEditor = null; if (activeCellNode) { var d = getDataItem(activeRow); $(activeCellNode).removeClass("editable invalid"); if (d) { var column = columns[activeCell]; var formatter = getFormatter(activeRow, column); activeCellNode.innerHTML = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d, self); invalidatePostProcessingResults(activeRow); } } // if there previously was text selected on a page (such as selected text in the edit cell just removed), // IE can't set focus to anything else correctly if (navigator.userAgent.toLowerCase().match(/msie/)) { clearTextSelection(); } getEditorLock().deactivate(editController); } function makeActiveCellEditable(editor) { if (!activeCellNode) { return; } if (!options.editable) { throw "Grid : makeActiveCellEditable : should never get called when options.editable is false"; } // cancel pending async call if there is one clearTimeout(h_editorLoader); if (!isCellPotentiallyEditable(activeRow, activeCell)) { return; } var columnDef = columns[activeCell]; var item = getDataItem(activeRow); if (trigger(self.onBeforeEditCell, {row: activeRow, cell: activeCell, item: item, column: columnDef, grid: self}) === false) { setFocus(); return; } getEditorLock().activate(editController); $(activeCellNode).addClass("editable"); var useEditor = editor || getEditor(activeRow, activeCell); // don't clear the cell if a custom editor is passed through if (!editor && !useEditor.suppressClearOnEdit) { activeCellNode.innerHTML = ""; } currentEditor = new useEditor({ grid: self, gridPosition: absBox($container[0]), position: absBox(activeCellNode), container: activeCellNode, column: columnDef, item: item || {}, commitChanges: commitEditAndSetFocus, cancelChanges: cancelEditAndSetFocus }); if (item) { currentEditor.loadValue(item); } serializedEditorValue = currentEditor.serializeValue(); if (currentEditor.position) { handleActiveCellPositionChange(); } } function commitEditAndSetFocus() { // if the commit fails, it would do so due to a validation error // if so, do not steal the focus from the editor if (getEditorLock().commitCurrentEdit()) { setFocus(); if (options.autoEdit) { navigateDown(); } } } function cancelEditAndSetFocus() { if (getEditorLock().cancelCurrentEdit()) { setFocus(); } } function absBox(elem) { var box = { top: elem.offsetTop, left: elem.offsetLeft, bottom: 0, right: 0, width: $(elem).outerWidth(), height: $(elem).outerHeight(), visible: true}; box.bottom = box.top + box.height; box.right = box.left + box.width; // walk up the tree var offsetParent = elem.offsetParent; while ((elem = elem.parentNode) != document.body) { if (elem == null) break; if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") { box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight; } if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") { box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth; } box.left -= elem.scrollLeft; box.top -= elem.scrollTop; if (elem === offsetParent) { box.left += elem.offsetLeft; box.top += elem.offsetTop; offsetParent = elem.offsetParent; } box.bottom = box.top + box.height; box.right = box.left + box.width; } return box; } function getActiveCellPosition() { return absBox(activeCellNode); } function getGridPosition() { return absBox($container[0]) } function handleActiveCellPositionChange() { if (!activeCellNode) { return; } trigger(self.onActiveCellPositionChanged, {grid: self}); if (currentEditor) { var cellBox = getActiveCellPosition(); if (currentEditor.show && currentEditor.hide) { if (!cellBox.visible) { currentEditor.hide(); } else { currentEditor.show(); } } if (currentEditor.position) { currentEditor.position(cellBox); } } } function getCellEditor() { return currentEditor; } function getActiveCell() { if (!activeCellNode) { return null; } else { return {row: activeRow, cell: activeCell, grid: self}; } } function getActiveCellNode() { return activeCellNode; } function scrollRowIntoView(row, doPaging) { var rowAtTop = row * options.rowHeight; var rowAtBottom = (row + 1) * options.rowHeight - viewportH + (viewportHasHScroll ? scrollbarDimensions.height : 0); // need to page down? if ((row + 1) * options.rowHeight > scrollTop + viewportH + offset) { scrollTo(doPaging ? rowAtTop : rowAtBottom); render(); } // or page up? else if (row * options.rowHeight < scrollTop + offset) { scrollTo(doPaging ? rowAtBottom : rowAtTop); render(); } } function scrollRowToTop(row) { scrollTo(row * options.rowHeight); render(); } function scrollPage(dir) { var deltaRows = dir * numVisibleRows; scrollTo((getRowFromPosition(scrollTop) + deltaRows) * options.rowHeight); render(); if (options.enableCellNavigation && activeRow != null) { var row = activeRow + deltaRows; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); if (row >= dataLengthIncludingAddNew) { row = dataLengthIncludingAddNew - 1; } if (row < 0) { row = 0; } var cell = 0, prevCell = null; var prevActivePosX = activePosX; while (cell <= activePosX) { if (canCellBeActive(row, cell)) { prevCell = cell; } cell += getColspan(row, cell); } if (prevCell !== null) { setActiveCellInternal(getCellNode(row, prevCell)); activePosX = prevActivePosX; } else { resetActiveCell(); } } } function navigatePageDown() { scrollPage(1); } function navigatePageUp() { scrollPage(-1); } function getColspan(row, cell) { var metadata = data.getItemMetadata && data.getItemMetadata(row); if (!metadata || !metadata.columns) { return 1; } var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell]; var colspan = (columnData && columnData.colspan); if (colspan === "*") { colspan = columns.length - cell; } else { colspan = colspan || 1; } return colspan; } function findFirstFocusableCell(row) { var cell = 0; while (cell < columns.length) { if (canCellBeActive(row, cell)) { return cell; } cell += getColspan(row, cell); } return null; } function findLastFocusableCell(row) { var cell = 0; var lastFocusableCell = null; while (cell < columns.length) { if (canCellBeActive(row, cell)) { lastFocusableCell = cell; } cell += getColspan(row, cell); } return lastFocusableCell; } function gotoRight(row, cell, posX) { if (cell >= columns.length) { return null; } do { cell += getColspan(row, cell); } while (cell < columns.length && !canCellBeActive(row, cell)); if (cell < columns.length) { return { "row": row, "cell": cell, "posX": cell }; } return null; } function gotoLeft(row, cell, posX) { if (cell <= 0) { return null; } var firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell === null || firstFocusableCell >= cell) { return null; } var prev = { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; var pos; while (true) { pos = gotoRight(prev.row, prev.cell, prev.posX); if (!pos) { return null; } if (pos.cell >= cell) { return prev; } prev = pos; } } function gotoDown(row, cell, posX) { var prevCell; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); while (true) { if (++row >= dataLengthIncludingAddNew) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoUp(row, cell, posX) { var prevCell; while (true) { if (--row < 0) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoNext(row, cell, posX) { if (row == null && cell == null) { row = cell = posX = 0; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos = gotoRight(row, cell, posX); if (pos) { return pos; } var firstFocusableCell = null; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); while (++row < dataLengthIncludingAddNew) { firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell !== null) { return { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; } } return null; } function gotoPrev(row, cell, posX) { if (row == null && cell == null) { row = getDataLengthIncludingAddNew() - 1; cell = posX = columns.length - 1; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos; var lastSelectableCell; while (!pos) { pos = gotoLeft(row, cell, posX); if (pos) { break; } if (--row < 0) { return null; } cell = 0; lastSelectableCell = findLastFocusableCell(row); if (lastSelectableCell !== null) { pos = { "row": row, "cell": lastSelectableCell, "posX": lastSelectableCell }; } } return pos; } function navigateRight() { return navigate("right"); } function navigateLeft() { return navigate("left"); } function navigateDown() { return navigate("down"); } function navigateUp() { return navigate("up"); } function navigateNext() { return navigate("next"); } function navigatePrev() { return navigate("prev"); } /** * @param {string} dir Navigation direction. * @return {boolean} Whether navigation resulted in a change of active cell. */ function navigate(dir) { if (!options.enableCellNavigation) { return false; } if (!activeCellNode && dir != "prev" && dir != "next") { return false; } if (!getEditorLock().commitCurrentEdit()) { return true; } setFocus(); var tabbingDirections = { "up": -1, "down": 1, "left": -1, "right": 1, "prev": -1, "next": 1 }; tabbingDirection = tabbingDirections[dir]; var stepFunctions = { "up": gotoUp, "down": gotoDown, "left": gotoLeft, "right": gotoRight, "prev": gotoPrev, "next": gotoNext }; var stepFn = stepFunctions[dir]; var pos = stepFn(activeRow, activeCell, activePosX); if (pos) { var isAddNewRow = (pos.row == getDataLength()); scrollCellIntoView(pos.row, pos.cell, !isAddNewRow); setActiveCellInternal(getCellNode(pos.row, pos.cell)); activePosX = pos.posX; return true; } else { setActiveCellInternal(getCellNode(activeRow, activeCell)); return false; } } function getCellNode(row, cell) { if (rowsCache[row]) { ensureCellNodesInRowsCache(row); return rowsCache[row].cellNodesByColumnIdx[cell]; } return null; } function setActiveCell(row, cell) { if (!initialized) { return; } if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return; } if (!options.enableCellNavigation) { return; } scrollCellIntoView(row, cell, false); setActiveCellInternal(getCellNode(row, cell), false); } function canCellBeActive(row, cell) { if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.focusable === "boolean") { return rowMetadata.focusable; } var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable === "boolean") { return columnMetadata[columns[cell].id].focusable; } if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable === "boolean") { return columnMetadata[cell].focusable; } return columns[cell].focusable; } function canCellBeSelected(row, cell) { if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.selectable === "boolean") { return rowMetadata.selectable; } var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]); if (columnMetadata && typeof columnMetadata.selectable === "boolean") { return columnMetadata.selectable; } return columns[cell].selectable; } function gotoCell(row, cell, forceEdit) { if (!initialized) { return; } if (!canCellBeActive(row, cell)) { return; } if (!getEditorLock().commitCurrentEdit()) { return; } scrollCellIntoView(row, cell, false); var newCell = getCellNode(row, cell); // if selecting the 'add new' row, start editing right away setActiveCellInternal(newCell, forceEdit || (row === getDataLength()) || options.autoEdit); // if no editor was created, set the focus back on the grid if (!currentEditor) { setFocus(); } } ////////////////////////////////////////////////////////////////////////////////////////////// // IEditor implementation for the editor lock function commitCurrentEdit() { var item = getDataItem(activeRow); var column = columns[activeCell]; if (currentEditor) { if (currentEditor.isValueChanged()) { var validationResults = currentEditor.validate(); if (validationResults.valid) { if (activeRow < getDataLength()) { var editCommand = { row: activeRow, cell: activeCell, editor: currentEditor, serializedValue: currentEditor.serializeValue(), prevSerializedValue: serializedEditorValue, execute: function () { this.editor.applyValue(item, this.serializedValue); updateRow(this.row); trigger(self.onCellChange, { row: activeRow, cell: activeCell, item: item, grid: self }); }, undo: function () { this.editor.applyValue(item, this.prevSerializedValue); updateRow(this.row); trigger(self.onCellChange, { row: activeRow, cell: activeCell, item: item, grid: self }); } }; if (options.editCommandHandler) { makeActiveCellNormal(); options.editCommandHandler(item, column, editCommand); } else { editCommand.execute(); makeActiveCellNormal(); } } else { var newItem = {}; currentEditor.applyValue(newItem, currentEditor.serializeValue()); makeActiveCellNormal(); trigger(self.onAddNewRow, {item: newItem, column: column, grid: self}); } // check whether the lock has been re-acquired by event handlers return !getEditorLock().isActive(); } else { // Re-add the CSS class to trigger transitions, if any. $(activeCellNode).removeClass("invalid"); $(activeCellNode).width(); // force layout $(activeCellNode).addClass("invalid"); trigger(self.onValidationError, { editor: currentEditor, cellNode: activeCellNode, validationResults: validationResults, row: activeRow, cell: activeCell, column: column, grid: self }); currentEditor.focus(); return false; } } makeActiveCellNormal(); } return true; } function cancelCurrentEdit() { makeActiveCellNormal(); return true; } function rowsToRanges(rows) { var ranges = []; var lastCell = columns.length - 1; for (var i = 0; i < rows.length; i++) { ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell)); } return ranges; } function getSelectedRows() { if (!selectionModel) { throw "Selection model is not set"; } return selectedRows; } function setSelectedRows(rows) { if (!selectionModel) { throw "Selection model is not set"; } selectionModel.setSelectedRanges(rowsToRanges(rows)); } ////////////////////////////////////////////////////////////////////////////////////////////// // Debug this.debug = function () { var s = ""; s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered); s += ("\n" + "counter_rows_removed: " + counter_rows_removed); s += ("\n" + "renderedRows: " + renderedRows); s += ("\n" + "numVisibleRows: " + numVisibleRows); s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight); s += ("\n" + "n(umber of pages): " + n); s += ("\n" + "(current) page: " + page); s += ("\n" + "page height (ph): " + ph); s += ("\n" + "vScrollDir: " + vScrollDir); alert(s); }; // a debug helper to be able to access private members this.eval = function (expr) { return eval(expr); }; ////////////////////////////////////////////////////////////////////////////////////////////// // Public API $.extend(this, { "slickGridVersion": "2.3.0", // Events "onScroll": new Slick.Event(), "onSort": new Slick.Event(), "onHeaderMouseEnter": new Slick.Event(), "onHeaderMouseLeave": new Slick.Event(), "onHeaderContextMenu": new Slick.Event(), "onHeaderClick": new Slick.Event(), "onHeaderCellRendered": new Slick.Event(), "onBeforeHeaderCellDestroy": new Slick.Event(), "onHeaderRowCellRendered": new Slick.Event(), "onFooterRowCellRendered": new Slick.Event(), "onBeforeHeaderRowCellDestroy": new Slick.Event(), "onBeforeFooterRowCellDestroy": new Slick.Event(), "onMouseEnter": new Slick.Event(), "onMouseLeave": new Slick.Event(), "onClick": new Slick.Event(), "onDblClick": new Slick.Event(), "onContextMenu": new Slick.Event(), "onKeyDown": new Slick.Event(), "onAddNewRow": new Slick.Event(), "onValidationError": new Slick.Event(), "onViewportChanged": new Slick.Event(), "onColumnsReordered": new Slick.Event(), "onColumnsResized": new Slick.Event(), "onCellChange": new Slick.Event(), "onBeforeEditCell": new Slick.Event(), "onBeforeCellEditorDestroy": new Slick.Event(), "onBeforeDestroy": new Slick.Event(), "onActiveCellChanged": new Slick.Event(), "onActiveCellPositionChanged": new Slick.Event(), "onDragInit": new Slick.Event(), "onDragStart": new Slick.Event(), "onDrag": new Slick.Event(), "onDragEnd": new Slick.Event(), "onSelectedRowsChanged": new Slick.Event(), "onCellCssStylesChanged": new Slick.Event(), // Methods "registerPlugin": registerPlugin, "unregisterPlugin": unregisterPlugin, "getColumns": getColumns, "setColumns": setColumns, "getColumnIndex": getColumnIndex, "updateColumnHeader": updateColumnHeader, "setSortColumn": setSortColumn, "setSortColumns": setSortColumns, "getSortColumns": getSortColumns, "autosizeColumns": autosizeColumns, "getOptions": getOptions, "setOptions": setOptions, "getData": getData, "getDataLength": getDataLength, "getDataItem": getDataItem, "setData": setData, "getSelectionModel": getSelectionModel, "setSelectionModel": setSelectionModel, "getSelectedRows": getSelectedRows, "setSelectedRows": setSelectedRows, "getContainerNode": getContainerNode, "updatePagingStatusFromView": updatePagingStatusFromView, "render": render, "invalidate": invalidate, "invalidateRow": invalidateRow, "invalidateRows": invalidateRows, "invalidateAllRows": invalidateAllRows, "updateCell": updateCell, "updateRow": updateRow, "getViewport": getVisibleRange, "getRenderedRange": getRenderedRange, "resizeCanvas": resizeCanvas, "updateRowCount": updateRowCount, "scrollRowIntoView": scrollRowIntoView, "scrollRowToTop": scrollRowToTop, "scrollCellIntoView": scrollCellIntoView, "getCanvasNode": getCanvasNode, "focus": setFocus, "getCellFromPoint": getCellFromPoint, "getCellFromEvent": getCellFromEvent, "getActiveCell": getActiveCell, "setActiveCell": setActiveCell, "getActiveCellNode": getActiveCellNode, "getActiveCellPosition": getActiveCellPosition, "resetActiveCell": resetActiveCell, "editActiveCell": makeActiveCellEditable, "getCellEditor": getCellEditor, "getCellNode": getCellNode, "getCellNodeBox": getCellNodeBox, "canCellBeSelected": canCellBeSelected, "canCellBeActive": canCellBeActive, "navigatePrev": navigatePrev, "navigateNext": navigateNext, "navigateUp": navigateUp, "navigateDown": navigateDown, "navigateLeft": navigateLeft, "navigateRight": navigateRight, "navigatePageUp": navigatePageUp, "navigatePageDown": navigatePageDown, "gotoCell": gotoCell, "getTopPanel": getTopPanel, "setTopPanelVisibility": setTopPanelVisibility, "setHeaderRowVisibility": setHeaderRowVisibility, "getHeaderRow": getHeaderRow, "getHeaderRowColumn": getHeaderRowColumn, "setFooterRowVisibility": setFooterRowVisibility, "getFooterRow": getFooterRow, "getFooterRowColumn": getFooterRowColumn, "getGridPosition": getGridPosition, "flashCell": flashCell, "addCellCssStyles": addCellCssStyles, "setCellCssStyles": setCellCssStyles, "removeCellCssStyles": removeCellCssStyles, "getCellCssStyles": getCellCssStyles, "init": finishInitialization, "destroy": destroy, // IEditor implementation "getEditorLock": getEditorLock, "getEditController": getEditController }); init(); } }(jQuery));
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactModal"] = factory(require("react"), require("react-dom")); else root["ReactModal"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_3__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(3); var _reactDom2 = _interopRequireDefault(_reactDom); var _propTypes = __webpack_require__(4); var _propTypes2 = _interopRequireDefault(_propTypes); var _exenv = __webpack_require__(12); var _exenv2 = _interopRequireDefault(_exenv); var _elementClass = __webpack_require__(13); var _elementClass2 = _interopRequireDefault(_elementClass); var _ModalPortal = __webpack_require__(14); var _ModalPortal2 = _interopRequireDefault(_ModalPortal); var _ariaAppHider = __webpack_require__(18); var ariaAppHider = _interopRequireWildcard(_ariaAppHider); var _refCount = __webpack_require__(19); var refCount = _interopRequireWildcard(_refCount); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var EE = _exenv2.default; var renderSubtreeIntoContainer = _reactDom2.default.unstable_renderSubtreeIntoContainer; var SafeHTMLElement = EE.canUseDOM ? window.HTMLElement : {}; var AppElement = EE.canUseDOM ? document.body : { appendChild: function appendChild() {} }; function getParentElement(parentSelector) { return parentSelector(); } var Modal = function (_Component) { _inherits(Modal, _Component); function Modal() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Modal); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Modal.__proto__ || Object.getPrototypeOf(Modal)).call.apply(_ref, [this].concat(args))), _this), _this.removePortal = function () { _reactDom2.default.unmountComponentAtNode(_this.node); var parent = getParentElement(_this.props.parentSelector); parent.removeChild(_this.node); if (refCount.count() === 0) { (0, _elementClass2.default)(document.body).remove(_this.props.bodyOpenClassName); } }, _this.renderPortal = function (props) { if (props.isOpen || refCount.count() > 0) { (0, _elementClass2.default)(document.body).add(_this.props.bodyOpenClassName); } else { (0, _elementClass2.default)(document.body).remove(_this.props.bodyOpenClassName); } if (props.ariaHideApp) { ariaAppHider.toggle(props.isOpen, props.appElement); } _this.portal = renderSubtreeIntoContainer(_this, _react2.default.createElement(_ModalPortal2.default, _extends({ defaultStyles: Modal.defaultStyles }, props)), _this.node); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Modal, [{ key: 'componentDidMount', value: function componentDidMount() { this.node = document.createElement('div'); this.node.className = this.props.portalClassName; if (this.props.isOpen) refCount.add(this); var parent = getParentElement(this.props.parentSelector); parent.appendChild(this.node); this.renderPortal(this.props); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(newProps) { if (newProps.isOpen) refCount.add(this); if (!newProps.isOpen) refCount.remove(this); var currentParent = getParentElement(this.props.parentSelector); var newParent = getParentElement(newProps.parentSelector); if (newParent !== currentParent) { currentParent.removeChild(this.node); newParent.appendChild(this.node); } this.renderPortal(newProps); } }, { key: 'componentWillUpdate', value: function componentWillUpdate(newProps) { if (newProps.portalClassName !== this.props.portalClassName) { this.node.className = newProps.portalClassName; } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { var _this2 = this; if (!this.node) return; refCount.remove(this); if (this.props.ariaHideApp) { ariaAppHider.show(this.props.appElement); } var state = this.portal.state; var now = Date.now(); var closesAt = state.isOpen && this.props.closeTimeoutMS && (state.closesAt || now + this.props.closeTimeoutMS); if (closesAt) { if (!state.beforeClose) { this.portal.closeWithTimeout(); } setTimeout(function () { return _this2.removePortal; }, closesAt - now); } else { this.removePortal(); } } }, { key: 'render', value: function render() { return null; } }], [{ key: 'setAppElement', value: function setAppElement(element) { ariaAppHider.setElement(element || AppElement); } /* eslint-disable no-console */ }, { key: 'injectCSS', value: function injectCSS() { (undefined) !== "production" && console.warn('React-Modal: injectCSS has been deprecated ' + 'and no longer has any effect. It will be removed in a later version'); } /* eslint-enable no-console */ /* eslint-disable react/no-unused-prop-types */ /* eslint-enable react/no-unused-prop-types */ }]); return Modal; }(_react.Component); Modal.propTypes = { isOpen: _propTypes2.default.bool.isRequired, style: _propTypes2.default.shape({ content: _propTypes2.default.object, overlay: _propTypes2.default.object }), portalClassName: _propTypes2.default.string, bodyOpenClassName: _propTypes2.default.string, className: _propTypes2.default.oneOfType([_propTypes2.default.String, _propTypes2.default.object]), overlayClassName: _propTypes2.default.oneOfType([_propTypes2.default.String, _propTypes2.default.object]), appElement: _propTypes2.default.instanceOf(SafeHTMLElement), onAfterOpen: _propTypes2.default.func, onRequestClose: _propTypes2.default.func, closeTimeoutMS: _propTypes2.default.number, ariaHideApp: _propTypes2.default.bool, shouldCloseOnOverlayClick: _propTypes2.default.bool, parentSelector: _propTypes2.default.func, role: _propTypes2.default.string, contentLabel: _propTypes2.default.string.isRequired }; Modal.defaultProps = { isOpen: false, portalClassName: 'ReactModalPortal', bodyOpenClassName: 'ReactModal__Body--open', ariaHideApp: true, closeTimeoutMS: 0, shouldCloseOnOverlayClick: true, parentSelector: function parentSelector() { return document.body; } }; Modal.defaultStyles = { overlay: { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'rgba(255, 255, 255, 0.75)' }, content: { position: 'absolute', top: '40px', left: '40px', right: '40px', bottom: '40px', border: '1px solid #ccc', background: '#fff', overflow: 'auto', WebkitOverflowScrolling: 'touch', borderRadius: '4px', outline: 'none', padding: '20px' } }; exports.default = Modal; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ if ((undefined) !== 'production') { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = __webpack_require__(5)(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(11)(); } /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = __webpack_require__(6); var invariant = __webpack_require__(7); var warning = __webpack_require__(8); var ReactPropTypesSecret = __webpack_require__(9); var checkPropTypes = __webpack_require__(10); module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if ((undefined) !== 'production') { var manualPropTypeCallCache = {}; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } else if ((undefined) !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if (!manualPropTypeCallCache[cacheKey]) { warning( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { (undefined) !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { (undefined) !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }, /* 6 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if ((undefined) !== 'production') { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyFunction = __webpack_require__(6); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ((undefined) !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; /***/ }, /* 9 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; if ((undefined) !== 'production') { var invariant = __webpack_require__(7); var warning = __webpack_require__(8); var ReactPropTypesSecret = __webpack_require__(9); var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if ((undefined) !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } module.exports = checkPropTypes; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = __webpack_require__(6); var invariant = __webpack_require__(7); module.exports = function() { // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. function shim() { invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); }; shim.isRequired = shim; function getShim() { return shim; }; var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Based on code that is Copyright 2013-2015, Facebook, Inc. All rights reserved. */ (function () { 'use strict'; var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen }; if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function () { return ExecutionEnvironment; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module.exports) { module.exports = ExecutionEnvironment; } else { window.ExecutionEnvironment = ExecutionEnvironment; } }()); /***/ }, /* 13 */ /***/ function(module, exports) { module.exports = function(opts) { return new ElementClass(opts) } function indexOf(arr, prop) { if (arr.indexOf) return arr.indexOf(prop) for (var i = 0, len = arr.length; i < len; i++) if (arr[i] === prop) return i return -1 } function ElementClass(opts) { if (!(this instanceof ElementClass)) return new ElementClass(opts) var self = this if (!opts) opts = {} // similar doing instanceof HTMLElement but works in IE8 if (opts.nodeType) opts = {el: opts} this.opts = opts this.el = opts.el || document.body if (typeof this.el !== 'object') this.el = document.querySelector(this.el) } ElementClass.prototype.add = function(className) { var el = this.el if (!el) return if (el.className === "") return el.className = className var classes = el.className.split(' ') if (indexOf(classes, className) > -1) return classes classes.push(className) el.className = classes.join(' ') return classes } ElementClass.prototype.remove = function(className) { var el = this.el if (!el) return if (el.className === "") return var classes = el.className.split(' ') var idx = indexOf(classes, className) if (idx > -1) classes.splice(idx, 1) el.className = classes.join(' ') return classes } ElementClass.prototype.has = function(className) { var el = this.el if (!el) return var classes = el.className.split(' ') return indexOf(classes, className) > -1 } ElementClass.prototype.toggle = function(className) { var el = this.el if (!el) return if (this.has(className)) this.remove(className) else this.add(className) } /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(4); var _focusManager = __webpack_require__(15); var focusManager = _interopRequireWildcard(_focusManager); var _scopeTab = __webpack_require__(17); var _scopeTab2 = _interopRequireDefault(_scopeTab); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // so that our CSS is statically analyzable var CLASS_NAMES = { overlay: 'ReactModal__Overlay', content: 'ReactModal__Content' }; var TAB_KEY = 9; var ESC_KEY = 27; var ModalPortal = function (_Component) { _inherits(ModalPortal, _Component); function ModalPortal(props) { _classCallCheck(this, ModalPortal); var _this = _possibleConstructorReturn(this, (ModalPortal.__proto__ || Object.getPrototypeOf(ModalPortal)).call(this, props)); _this.setFocusAfterRender = function (focus) { _this.focusAfterRender = focus; }; _this.afterClose = function () { focusManager.returnFocus(); focusManager.teardownScopedFocus(); }; _this.open = function () { if (_this.state.afterOpen && _this.state.beforeClose) { clearTimeout(_this.closeTimer); _this.setState({ beforeClose: false }); } else { focusManager.setupScopedFocus(_this.node); focusManager.markForFocusLater(); _this.setState({ isOpen: true }, function () { _this.setState({ afterOpen: true }); if (_this.props.isOpen && _this.props.onAfterOpen) { _this.props.onAfterOpen(); } }); } }; _this.close = function () { if (_this.props.closeTimeoutMS > 0) { _this.closeWithTimeout(); } else { _this.closeWithoutTimeout(); } }; _this.focusContent = function () { return !_this.contentHasFocus() && _this.content.focus(); }; _this.closeWithTimeout = function () { var closesAt = Date.now() + _this.props.closeTimeoutMS; _this.setState({ beforeClose: true, closesAt: closesAt }, function () { _this.closeTimer = setTimeout(_this.closeWithoutTimeout, _this.state.closesAt - Date.now()); }); }; _this.closeWithoutTimeout = function () { _this.setState({ beforeClose: false, isOpen: false, afterOpen: false, closesAt: null }, _this.afterClose); }; _this.handleKeyDown = function (event) { if (event.keyCode === TAB_KEY) { (0, _scopeTab2.default)(_this.content, event); } if (event.keyCode === ESC_KEY) { event.preventDefault(); _this.requestClose(event); } }; _this.handleOverlayOnClick = function (event) { if (_this.shouldClose === null) { _this.shouldClose = true; } if (_this.shouldClose && _this.props.shouldCloseOnOverlayClick) { if (_this.ownerHandlesClose()) { _this.requestClose(event); } else { _this.focusContent(); } } _this.shouldClose = null; }; _this.handleContentOnClick = function () { _this.shouldClose = false; }; _this.requestClose = function (event) { return _this.ownerHandlesClose() && _this.props.onRequestClose(event); }; _this.ownerHandlesClose = function () { return _this.props.onRequestClose; }; _this.shouldBeClosed = function () { return !_this.state.isOpen && !_this.state.beforeClose; }; _this.contentHasFocus = function () { return document.activeElement === _this.content || _this.content.contains(document.activeElement); }; _this.buildClassName = function (which, additional) { var classNames = (typeof additional === 'undefined' ? 'undefined' : _typeof(additional)) === 'object' ? additional : { base: CLASS_NAMES[which], afterOpen: CLASS_NAMES[which] + '--after-open', beforeClose: CLASS_NAMES[which] + '--before-close' }; var className = classNames.base; if (_this.state.afterOpen) { className = className + ' ' + classNames.afterOpen; } if (_this.state.beforeClose) { className = className + ' ' + classNames.beforeClose; } return typeof additional === 'string' && additional ? className + ' ' + additional : className; }; _this.state = { afterOpen: false, beforeClose: false }; _this.shouldClose = null; return _this; } _createClass(ModalPortal, [{ key: 'componentDidMount', value: function componentDidMount() { // Focus needs to be set when mounting and already open if (this.props.isOpen) { this.setFocusAfterRender(true); this.open(); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(newProps) { // Focus only needs to be set once when the modal is being opened if (!this.props.isOpen && newProps.isOpen) { this.setFocusAfterRender(true); this.open(); } else if (this.props.isOpen && !newProps.isOpen) { this.close(); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { if (this.focusAfterRender) { this.focusContent(); this.setFocusAfterRender(false); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.closeTimer); } // Don't steal focus from inner elements }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, className = _props.className, overlayClassName = _props.overlayClassName, defaultStyles = _props.defaultStyles; var contentStyles = className ? {} : defaultStyles.content; var overlayStyles = overlayClassName ? {} : defaultStyles.overlay; return this.shouldBeClosed() ? _react2.default.createElement('div', null) : _react2.default.createElement( 'div', { ref: function ref(overlay) { _this2.overlay = overlay; }, className: this.buildClassName('overlay', overlayClassName), style: _extends({}, overlayStyles, this.props.style.overlay), onClick: this.handleOverlayOnClick }, _react2.default.createElement( 'div', { ref: function ref(content) { _this2.content = content; }, style: _extends({}, contentStyles, this.props.style.content), className: this.buildClassName('content', className), tabIndex: '-1', onKeyDown: this.handleKeyDown, onClick: this.handleContentOnClick, role: this.props.role, 'aria-label': this.props.contentLabel }, this.props.children ) ); } }]); return ModalPortal; }(_react.Component); ModalPortal.defaultProps = { style: { overlay: {}, content: {} } }; ModalPortal.propTypes = { isOpen: _propTypes.PropTypes.bool.isRequired, defaultStyles: _propTypes.PropTypes.shape({ content: _propTypes.PropTypes.object, overlay: _propTypes.PropTypes.object }), style: _propTypes.PropTypes.shape({ content: _propTypes.PropTypes.object, overlay: _propTypes.PropTypes.object }), className: _propTypes.PropTypes.oneOfType([_propTypes.PropTypes.String, _propTypes.PropTypes.object]), overlayClassName: _propTypes.PropTypes.oneOfType([_propTypes.PropTypes.String, _propTypes.PropTypes.object]), onAfterOpen: _propTypes.PropTypes.func, onRequestClose: _propTypes.PropTypes.func, closeTimeoutMS: _propTypes.PropTypes.number, shouldCloseOnOverlayClick: _propTypes.PropTypes.bool, role: _propTypes.PropTypes.string, contentLabel: _propTypes.PropTypes.string, children: _propTypes.PropTypes.node }; exports.default = ModalPortal; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.handleBlur = handleBlur; exports.handleFocus = handleFocus; exports.markForFocusLater = markForFocusLater; exports.returnFocus = returnFocus; exports.setupScopedFocus = setupScopedFocus; exports.teardownScopedFocus = teardownScopedFocus; var _tabbable = __webpack_require__(16); var _tabbable2 = _interopRequireDefault(_tabbable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var focusLaterElements = []; var modalElement = null; var needToFocus = false; function handleBlur() { needToFocus = true; } function handleFocus() { if (needToFocus) { needToFocus = false; if (!modalElement) { return; } // need to see how jQuery shims document.on('focusin') so we don't need the // setTimeout, firefox doesn't support focusin, if it did, we could focus // the element outside of a setTimeout. Side-effect of this implementation // is that the document.body gets focus, and then we focus our element right // after, seems fine. setTimeout(function () { if (modalElement.contains(document.activeElement)) { return; } var el = (0, _tabbable2.default)(modalElement)[0] || modalElement; el.focus(); }, 0); } } function markForFocusLater() { focusLaterElements.push(document.activeElement); } /* eslint-disable no-console */ function returnFocus() { var toFocus = null; try { toFocus = focusLaterElements.pop(); toFocus.focus(); return; } catch (e) { console.warn(['You tried to return focus to', toFocus, 'but it is not in the DOM anymore'].join(" ")); } } /* eslint-enable no-console */ function setupScopedFocus(element) { modalElement = element; if (window.addEventListener) { window.addEventListener('blur', handleBlur, false); document.addEventListener('focus', handleFocus, true); } else { window.attachEvent('onBlur', handleBlur); document.attachEvent('onFocus', handleFocus); } } function teardownScopedFocus() { modalElement = null; if (window.addEventListener) { window.removeEventListener('blur', handleBlur); document.removeEventListener('focus', handleFocus); } else { window.detachEvent('onBlur', handleBlur); document.detachEvent('onFocus', handleFocus); } } /***/ }, /* 16 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = findTabbableDescendants; /*! * Adapted from jQuery UI core * * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ var tabbableNode = /input|select|textarea|button|object/; function hidden(el) { return el.offsetWidth <= 0 && el.offsetHeight <= 0 || el.style.display === 'none'; } function visible(element) { var parentElement = element; while (parentElement) { if (parentElement === document.body) break; if (hidden(parentElement)) return false; parentElement = parentElement.parentNode; } return true; } function focusable(element, isTabIndexNotNaN) { var nodeName = element.nodeName.toLowerCase(); var res = tabbableNode.test(nodeName) && !element.disabled || (nodeName === "a" ? element.href || isTabIndexNotNaN : isTabIndexNotNaN); return res && visible(element); } function tabbable(element) { var tabIndex = element.getAttribute('tabindex'); if (tabIndex === null) tabIndex = undefined; var isTabIndexNaN = isNaN(tabIndex); return (isTabIndexNaN || tabIndex >= 0) && focusable(element, !isTabIndexNaN); } function findTabbableDescendants(element) { return [].slice.call(element.querySelectorAll('*'), 0).filter(tabbable); } /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = scopeTab; var _tabbable = __webpack_require__(16); var _tabbable2 = _interopRequireDefault(_tabbable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function scopeTab(node, event) { var tabbable = (0, _tabbable2.default)(node); if (!tabbable.length) { event.preventDefault(); return; } var finalTabbable = tabbable[event.shiftKey ? 0 : tabbable.length - 1]; var leavingFinalTabbable = finalTabbable === document.activeElement || // handle immediate shift+tab after opening with mouse node === document.activeElement; if (!leavingFinalTabbable) return; event.preventDefault(); var target = tabbable[event.shiftKey ? tabbable.length - 1 : 0]; target.focus(); } /***/ }, /* 18 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.setElement = setElement; exports.validateElement = validateElement; exports.hide = hide; exports.show = show; exports.toggle = toggle; exports.resetForTesting = resetForTesting; var globalElement = typeof document !== 'undefined' ? document.body : null; function setElement(element) { var useElement = element; if (typeof useElement === 'string') { var el = document.querySelectorAll(useElement); useElement = 'length' in el ? el[0] : el; } globalElement = useElement || globalElement; return globalElement; } function validateElement(appElement) { if (!appElement && !globalElement) { throw new Error(['react-modal: You must set an element with', '`Modal.setAppElement(el)` to make this accessible']); } } function hide(appElement) { validateElement(appElement); (appElement || globalElement).setAttribute('aria-hidden', 'true'); } function show(appElement) { validateElement(appElement); (appElement || globalElement).removeAttribute('aria-hidden'); } function toggle(shouldHide, appElement) { var apply = shouldHide ? hide : show; apply(appElement); } function resetForTesting() { globalElement = document.body; } /***/ }, /* 19 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.add = add; exports.remove = remove; exports.count = count; var modals = []; function add(element) { if (modals.indexOf(element) === -1) { modals.push(element); } } function remove(element) { var index = modals.indexOf(element); if (index === -1) { return; } modals.splice(index, 1); } function count() { return modals.length; } /***/ } /******/ ]) }); ;
Meteor.methods({ '2fa:disable'(code) { if (!Meteor.userId()) { throw new Meteor.Error('not-authorized'); } const user = Meteor.user(); const verified = RocketChat.TOTP.verify({ secret: user.services.totp.secret, token: code, userId: Meteor.userId(), backupTokens: user.services.totp.hashedBackup }); if (!verified) { return false; } return RocketChat.models.Users.disable2FAByUserId(Meteor.userId()); } });
var requestAnimFrame = (window.requestAnimationFrame || window.webkitAnimationFrame || function(cb) { setTimeout(cb, 1000 / 60); }); $(function() { if($('body').attr('id') != 'home') { return; } var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var w = $('body').width(); var h = $('.banner')[0].getBoundingClientRect().height; canvas.width = w; canvas.height = h; $('.banner').prepend(canvas); var last; var tris; var running = false; var MAX_SUBDIVIDE = 4; var EPSILON = 5; // generate a random color scheme for the page var COLOR_INDEX = Math.random() * 2 | 0; function vadd(v1, v2) { return [v1[0] + v2[0], v1[1] + v2[1]]; } function vsub(v1, v2) { return [v1[0] - v2[0], v1[1] - v2[1]]; } function vcopy(v) { return [v[0], v[1]]; } function vmul(v, scalar) { return [v[0] * scalar, v[1] * scalar]; } function vrotate(v, angle) { var cs = Math.cos(angle); var sn = Math.sin(angle); return [ v[0] * cs - v[1] * sn, v[0] * sn + v[1] * cs ]; } function vnormalize(v) { var l = v[0] * v[0] + v[1] * v[1]; if(l > 0) { l = 1 / Math.sqrt(l); return [v[0] * l, v[1] * l]; } return [0, 0]; } function vlength(v) { var l = v[0] * v[0] + v[1] * v[1]; return Math.sqrt(l); } function vequal(v1, v2) { return Math.abs(v1[0] - v2[0]) < EPSILON && Math.abs(v1[1] - v2[1]) < EPSILON; } function findPoint(point, cb) { var res; for(var i=0; i<tris.length; i++) { tris[i].findPoint(point, cb); } } function Spark(pos, dir, len, color) { this.pos = pos; this.origPos = vcopy(pos); this.dir = dir; this.len = len; this.finished = false; this.color = [color[0], color[1] + 60, color[2]]; } Spark.prototype.update = function(dt) { if(!this.finished) { this.pos[0] += this.dir[0] * dt * 700; this.pos[1] += this.dir[1] * dt * 700; findPoint(this.pos, function(collision) { if(Math.random() < .75) { collision.tri.startFire(collision.orient); } }); if(vlength(vsub(this.pos, this.origPos)) >= this.len + this.len / 3) { this.finished = true; } } }; Spark.prototype.render = function() { if(!this.finished) { ctx.strokeStyle = 'rgb(' + this.color.join(',') + ')'; ctx.beginPath(); ctx.moveTo(this.pos[0], this.pos[1]); ctx.lineTo(this.pos[0] - this.dir[0] * (this.len / 3), this.pos[1] - this.dir[1] * (this.len / 3)); ctx.stroke(); } }; function Triangle(v1, v2, v3, color, level) { this.v1 = v1; this.v2 = v2; this.v3 = v3; this.point = v2; this.color = color || [30, (Math.random() * 20 + 40) | 0, 20]; this.children = []; this.level = level || 0; this.sparks = []; this.bc = vsub(v3, v2); this.ba = vsub(v1, v2); this.bb = [Math.min(v1[0], v2[0], v3[0]), Math.min(v1[1], v2[1], v3[1]), Math.max(v1[0], v2[0], v3[0]), Math.max(v1[1], v2[1], v3[1])]; } Triangle.prototype.subdivide = function() { var level = this.level; if(Math.random() < Math.max(level - 2, 0) / MAX_SUBDIVIDE || level > MAX_SUBDIVIDE) { return; } var v1 = this.v1; var v2 = this.v2; var v3 = this.v3; var ac = [v3[0] - v1[0], v3[1] - v1[1]]; var mid = [v1[0] + ac[0] / 2.0, v1[1] + ac[1] / 2.0]; var color = [this.color[0], this.color[1] + ((Math.random() - .5) * 20 | 0), this.color[2]]; this.children = [new Triangle(v1, mid, v2, color, level + 1), new Triangle(v3, mid, v2, color, level + 1)]; this.children[0].subdivide(); this.children[1].subdivide(); return this; }; Triangle.prototype.render = function() { var v1 = this.v1; var v2 = this.v2; var v3 = this.v3; var color = this.color; if(!this.children.length) { ctx.beginPath(); ctx.moveTo(v1[0], v1[1]); ctx.lineTo(v2[0], v2[1]); ctx.lineTo(v3[0], v3[1]); ctx.fillStyle = ctx.strokeStyle = 'rgb(' + color.join(',') + ')'; ctx.fill(); ctx.stroke(); } this.children.forEach(function(child) { child.render(); }); }; Triangle.prototype.renderSparks = function() { for(var i=0, l=this.sparks.length; i<l; i++) { this.sparks[i].render(); } for(var i=0, l=this.children.length; i<l; i++) { this.children[i].renderSparks(); } }; Triangle.prototype.startFire = function(atPoint) { if(this.sparks.length) { return; } var v1, v2, v3; if(atPoint == 'v1') { v1 = this.v2; v2 = this.v1; v3 = this.v3; } else if(atPoint == 'v3') { v1 = this.v1; v2 = this.v3; v3 = this.v2; } else { v1 = this.v1; v2 = this.v2; v3 = this.v3; } var ba = this.ba; var bc = this.bc; this.sparks.push(new Spark(vcopy(v2), vnormalize(bc), vlength(bc), this.color)); this.sparks.push(new Spark(vcopy(v2), vnormalize(ba), vlength(ba), this.color)); }; Triangle.prototype.findPoint = function(point, cb) { if(this.children.length) { var bb = this.bb; if(point[0] >= bb[0] && point[1] >= bb[1] && point[0] <= bb[2] && point[1] <= bb[3]) { for(var i=0, l=this.children.length; i<l; i++) { this.children[i].findPoint(point, cb); } } } else { if(vequal(point, this.v1)) { cb({ tri: this, orient: 'v1' }); } else if(vequal(point, this.v2)) { return cb({ tri: this, orient: 'v2' }); } else if(vequal(point, this.v3)) { return cb({ tri: this, orient: 'v3' }); } } }; Triangle.prototype.update = function(dt) { var sparks = this.sparks; var allDone = true; for(var i=0, l=sparks.length; i<l; i++) { var spark = sparks[i]; spark.update(dt); allDone = allDone && spark.finished; } // Need to check to see if all of my sparks are out, and set a // timer to quench them. We set a timer because otherwise they // catch fire immediately because neighbors re-spark them. if(this.sparks.length && allDone && !this.quenchTimer) { this.quenchTimer = setTimeout(function() { this.sparks = []; }.bind(this), 1000); } if(this.dir) { this.v1 = vadd(this.v1, vmul(this.dir, dt)); this.v2 = vadd(this.v2, vmul(this.dir, dt)); this.v3 = vadd(this.v3, vmul(this.dir, dt)); } if(this.fadeOut) { this.color[0] = Math.max(this.color[0] - this.fadeOut * dt, 0) | 0; this.color[1] = Math.max(this.color[1] - this.fadeOut * dt, 0) | 0; this.color[2] = Math.max(this.color[2] - this.fadeOut * dt, 0) | 0; } var done = true; if(this.children.length) { for(var i=0, l=this.children.length; i<l; i++) { done = this.children[i].update(dt) && done; } } else { done = (!this.sparks.length && !this.fadeOut) || (this.fadeOut && this.color[0] == 0 && this.color[1] == 0 && this.color[2] == 0); } return done; }; Triangle.prototype.getRandomLeaf = function() { if(this.children.length) { return this.children[Math.random() * this.children.length | 0].getRandomLeaf(); } else { return this; } }; Triangle.prototype.shootOff = function(center) { this.sparks = []; if(this.children.length) { for(var i=0, l=this.children.length; i<l; i++) { this.children[i].shootOff(center); } } else { var ab = vnormalize(vsub(this.v1, center)); if(ab[0] < 0) { ab[0] = -1; } else { ab[0] = 1; } if(ab[1] < 0) { ab[1] = -1; } else { ab[1] = 1; } this.dir = vmul(vnormalize(ab), 500 * Math.random()); this.fadeOut = Math.random() * 100; } }; window.onscroll = function() { var y = window.pageYOffset || document.body.scrollTop; canvas.style.top = y / 2 + 'px'; }; function init() { tris = []; for(var x=0; x<w; x += h) { if(Math.random() < .5) { tris.push( (new Triangle([x, 0], [x + h, 0], [x + h, h])).subdivide(), (new Triangle([x, 0], [x, h], [x + h, h])).subdivide() ); } else { tris.push( (new Triangle([x, h], [x, 0], [x + h, 0])).subdivide(), (new Triangle([x, h], [x + h, h], [x + h, 0])).subdivide() ); } } tris[Math.random() * tris.length | 0].getRandomLeaf().startFire('v2'); } function render() { running = true; ctx.fillStyle = 'black'; ctx.fillRect(0, 0, canvas.width, canvas.height); var done = true; tris.forEach(function(tri) { done = tri.update(.016) && done; tri.render(); }); tris.forEach(function(tri) { tri.renderSparks(); }); if(!done) { requestAnimFrame(render); } else { running = false; } } init(); render(); // UI function showDownload() { window.scrollTo(0, 0); var rect = $('.banner canvas')[0].getBoundingClientRect(); tris.forEach(function(tri) { tri.shootOff([rect.width / 2, rect.height / 2]); }); $('.banner-screen').css({ opacity: 0, transition: 'opacity 1s' }); setTimeout(function() { $('.download-screen').css({ opacity: 1, transition: 'opacity .5s', zIndex: 10, height: rect.height }); $('.download-screen .col-sm-6').height(rect.height); }, 1000); if(!running) { render(); } } $('a.download').click(function(e) { e.preventDefault(); $(e.target).blur(); showDownload(); }); $('.download-screen a.close').click(function() { $('.download-screen').css({ opacity: 0, transition: 'opacity 1s' }); running = false; setTimeout(function() { init(); if(!running) { render(); } $('.download-screen').css({ zIndex: -10 }); $('.banner-screen').css({ opacity: 1 }); }, 1000); }); $('.download-screen').height(canvas.height); if(window.location.hash == '#download') { showDownload(); } }); function saveImage() { var canvas = $('canvas')[0]; var img = canvas.toDataURL('image/png'); var el = document.createElement('img'); el.src = img; document.body.appendChild(el); }
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX-Web/Latin/Bold/Main.js * * Copyright (c) 2013-2014 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXMathJax_Latin-bold'] = { directory: 'Latin/Bold', family: 'STIXMathJax_Latin', weight: 'bold', testString: '\u00A0\u00A1\u00A2\u00A4\u00A6\u00A9\u00AA\u00AB\u00AD\u00B2\u00B3\u00B6\u00B8\u00B9\u00BA', 0x20: [0,0,250,0,0], 0xA0: [0,0,250,0,0], 0xA1: [501,203,333,82,252], 0xA2: [588,140,500,53,458], 0xA4: [542,10,500,-26,526], 0xA6: [691,19,220,66,154], 0xA9: [691,19,747,26,721], 0xAA: [688,-397,300,-1,301], 0xAB: [415,-36,500,23,473], 0xAD: [287,-171,333,44,287], 0xB2: [688,-275,300,0,300], 0xB3: [688,-268,300,3,297], 0xB6: [676,186,639,60,579], 0xB8: [0,218,333,68,294], 0xB9: [688,-275,300,28,273], 0xBA: [688,-397,330,18,312], 0xBB: [415,-36,500,27,477], 0xBC: [688,12,750,28,743], 0xBD: [688,12,750,-7,775], 0xBE: [688,12,750,23,733], 0xBF: [501,201,500,55,443], 0xC0: [963,0,722,9,689], 0xC1: [963,0,722,9,689], 0xC2: [954,0,722,9,689], 0xC3: [924,0,722,9,689], 0xC4: [916,0,722,9,689], 0xC5: [1000,0,722,9,689], 0xC6: [676,0,1000,4,951], 0xC7: [691,218,722,49,687], 0xC8: [963,0,667,16,641], 0xC9: [963,0,667,16,641], 0xCA: [954,0,667,16,641], 0xCB: [916,0,667,16,641], 0xCC: [963,0,389,20,370], 0xCD: [963,0,389,20,370], 0xCE: [954,0,389,20,370], 0xCF: [916,0,389,20,370], 0xD0: [676,0,722,6,690], 0xD1: [924,18,722,16,701], 0xD2: [963,19,778,35,743], 0xD3: [963,19,778,35,743], 0xD4: [954,19,778,35,743], 0xD5: [924,19,778,35,743], 0xD6: [916,19,778,35,743], 0xD8: [737,74,778,35,743], 0xD9: [963,19,722,16,701], 0xDA: [963,19,722,16,701], 0xDB: [954,19,722,16,701], 0xDC: [916,19,722,16,701], 0xDD: [963,0,722,15,699], 0xDE: [676,0,611,16,600], 0xDF: [691,12,556,19,517], 0xE0: [713,14,500,25,488], 0xE1: [713,14,500,25,488], 0xE2: [704,14,500,25,488], 0xE3: [674,14,500,25,488], 0xE4: [666,14,500,25,488], 0xE5: [752,14,500,25,488], 0xE6: [473,14,722,33,694], 0xE7: [473,218,444,25,430], 0xE8: [713,14,444,25,427], 0xE9: [713,14,444,25,427], 0xEA: [704,14,444,25,427], 0xEB: [666,14,444,25,427], 0xEC: [713,0,278,14,257], 0xED: [713,0,278,15,258], 0xEE: [704,0,278,-29,308], 0xEF: [666,0,278,-29,310], 0xF1: [674,0,556,21,539], 0xF2: [713,14,500,25,476], 0xF3: [713,14,500,25,476], 0xF4: [704,14,500,25,476], 0xF5: [674,14,500,25,476], 0xF6: [666,14,500,25,476], 0xF8: [549,92,500,25,476], 0xF9: [713,14,556,16,538], 0xFA: [713,14,556,16,538], 0xFB: [704,14,556,16,538], 0xFC: [666,14,556,16,538], 0xFD: [713,205,500,16,482], 0xFE: [676,205,556,19,524], 0xFF: [666,205,500,16,482], 0x100: [810,0,722,9,689], 0x101: [600,14,500,25,488], 0x102: [901,0,722,9,689], 0x103: [691,14,500,25,488], 0x104: [690,205,722,9,721], 0x105: [473,205,500,25,569], 0x106: [923,19,722,49,687], 0x107: [713,14,444,25,430], 0x108: [914,19,722,49,687], 0x109: [704,14,444,25,430], 0x10A: [876,19,722,49,687], 0x10B: [666,14,444,25,430], 0x10C: [914,19,722,49,687], 0x10D: [704,14,444,25,430], 0x10E: [914,0,722,14,690], 0x10F: [709,14,680,25,710], 0x110: [676,0,722,6,690], 0x111: [676,14,556,25,534], 0x112: [810,0,667,16,641], 0x113: [600,14,444,25,427], 0x114: [901,0,667,16,641], 0x115: [691,14,444,25,427], 0x116: [876,0,667,16,641], 0x117: [666,14,444,25,427], 0x118: [676,205,667,16,641], 0x119: [473,205,444,25,435], 0x11A: [914,0,667,16,641], 0x11B: [704,14,444,25,427], 0x11C: [914,19,778,37,755], 0x11D: [704,206,500,28,483], 0x11E: [901,19,778,37,755], 0x11F: [691,206,500,28,483], 0x120: [876,19,778,37,755], 0x121: [666,206,500,28,483], 0x122: [691,378,778,37,755], 0x123: [863,206,500,28,483], 0x124: [914,0,778,21,759], 0x125: [914,0,556,15,534], 0x126: [676,0,778,21,759], 0x128: [884,0,389,14,379], 0x129: [674,0,278,-47,318], 0x12A: [810,0,389,20,370], 0x12B: [600,0,278,-25,305], 0x12C: [900,0,389,20,370], 0x12D: [691,0,278,-11,292], 0x12E: [676,205,389,20,389], 0x12F: [691,205,278,15,321], 0x130: [876,0,389,20,370], 0x132: [676,96,838,20,917], 0x133: [691,203,552,15,531], 0x134: [914,96,500,3,479], 0x135: [704,203,333,-57,335], 0x136: [676,378,778,30,769], 0x137: [676,378,556,22,543], 0x138: [470,0,600,19,627], 0x139: [923,0,667,19,638], 0x13A: [923,0,278,15,260], 0x13B: [676,378,667,19,638], 0x13C: [676,378,278,15,256], 0x13D: [691,0,667,19,638], 0x13E: [709,0,457,15,442], 0x13F: [676,0,667,19,638], 0x140: [676,0,414,15,441], 0x141: [676,0,667,18,638], 0x142: [676,0,278,-22,303], 0x143: [923,18,722,16,701], 0x144: [713,0,556,21,539], 0x145: [676,378,722,16,701], 0x146: [473,378,556,21,539], 0x147: [914,18,722,16,701], 0x148: [704,0,556,21,539], 0x149: [709,0,705,13,693], 0x14A: [676,96,732,14,712], 0x14B: [473,205,556,21,490], 0x14C: [810,19,778,35,743], 0x14D: [600,14,500,25,476], 0x14E: [901,19,778,35,743], 0x14F: [691,14,500,25,476], 0x150: [923,19,778,35,743], 0x151: [713,14,500,25,476], 0x152: [684,5,1000,22,981], 0x153: [473,14,722,22,696], 0x154: [923,0,722,26,716], 0x155: [713,0,444,28,434], 0x156: [676,378,722,26,716], 0x157: [473,378,444,28,434], 0x158: [914,0,722,26,716], 0x159: [704,0,444,28,434], 0x15A: [923,19,556,35,513], 0x15B: [713,14,389,25,364], 0x15C: [914,19,556,35,513], 0x15D: [704,14,389,22,361], 0x15E: [692,218,556,35,513], 0x15F: [473,218,389,25,361], 0x160: [914,19,556,35,513], 0x161: [704,14,389,22,361], 0x162: [676,218,667,31,636], 0x163: [630,218,333,19,332], 0x164: [914,0,667,31,636], 0x165: [709,12,415,19,445], 0x166: [676,0,667,31,636], 0x167: [630,12,333,17,332], 0x168: [886,19,722,16,701], 0x169: [674,14,556,16,538], 0x16A: [810,19,722,16,701], 0x16B: [600,14,556,16,538], 0x16C: [901,19,722,16,701], 0x16D: [691,14,556,16,538], 0x16E: [935,19,722,16,701], 0x16F: [740,14,556,16,538], 0x170: [923,19,722,16,701], 0x171: [713,14,556,16,538], 0x172: [676,205,722,16,701], 0x173: [461,205,556,16,547], 0x174: [914,15,1000,19,981], 0x175: [704,14,722,23,707], 0x176: [914,0,722,15,699], 0x177: [704,205,500,16,482], 0x178: [876,0,722,15,699], 0x179: [923,0,667,28,634], 0x17A: [713,0,444,21,420], 0x17B: [876,0,667,28,634], 0x17C: [666,0,444,21,420], 0x17D: [914,0,667,28,634], 0x17E: [704,0,444,21,420], 0x17F: [691,0,333,14,389], 0x180: [676,14,553,-28,516], 0x188: [576,14,568,30,574], 0x190: [686,4,610,38,587], 0x192: [706,155,500,0,498], 0x195: [676,10,797,14,767], 0x199: [691,0,533,12,533], 0x19A: [676,0,291,24,265], 0x19B: [666,0,536,60,526], 0x19E: [473,205,559,21,539], 0x1A0: [732,19,778,35,788], 0x1A1: [505,14,554,25,576], 0x1A5: [673,205,550,10,515], 0x1AA: [689,228,446,25,421], 0x1AB: [630,218,347,18,331], 0x1AD: [691,12,371,19,389], 0x1AF: [810,19,796,16,836], 0x1B0: [596,14,600,16,626], 0x1BA: [450,237,441,9,415], 0x1BB: [688,0,515,27,492], 0x1BE: [541,10,527,78,449], 0x1C0: [740,0,186,60,126], 0x1C1: [740,0,313,60,253], 0x1C2: [740,0,445,39,405], 0x1C3: [691,13,333,81,251], 0x1F0: [704,203,333,-57,335], 0x1FA: [972,0,722,9,689], 0x1FB: [923,14,500,25,488], 0x1FC: [923,0,1000,4,951], 0x1FD: [713,14,722,33,694], 0x1FE: [923,74,778,35,743], 0x1FF: [713,92,500,25,476], 0x1E80: [923,15,1000,19,981], 0x1E81: [713,14,722,23,707], 0x1E82: [923,15,1000,19,981], 0x1E83: [713,14,722,23,707], 0x1E84: [876,15,1000,19,981], 0x1E85: [666,14,722,23,707], 0x1EF2: [923,0,722,15,699], 0x1EF3: [713,205,500,16,482], 0xA792: [691,19,769,27,734], 0xFB00: [691,0,610,15,666], 0xFB01: [691,0,556,14,536], 0xFB02: [691,0,556,15,535], 0xFB03: [691,0,833,15,813], 0xFB04: [691,0,833,15,812] }; MathJax.Callback.Queue( ["initFont",MathJax.OutputJax["HTML-CSS"],"STIXMathJax_Latin-bold"], ["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Latin/Bold/Main.js"] );
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; const ListViewDataSource = require('ListViewDataSource'); const React = require('React'); const ScrollView = require('ScrollView'); const StaticRenderer = require('StaticRenderer'); class ListViewMock extends React.Component { static latestRef: ?ListViewMock; static defaultProps = { renderScrollComponent: (props) => <ScrollView {...props} />, } componentDidMount() { ListViewMock.latestRef = this; } render() { const {dataSource, renderFooter, renderHeader} = this.props; const rows = [renderHeader && renderHeader()]; const allRowIDs = dataSource.rowIdentities; for (let sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) { const sectionID = dataSource.sectionIdentities[sectionIdx]; const rowIDs = allRowIDs[sectionIdx]; for (let rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) { const rowID = rowIDs[rowIdx]; rows.push( <StaticRenderer key={rowID} shouldUpdate={true} render={this.props.renderRow.bind( null, dataSource.getRowData(sectionIdx, rowIdx), sectionID, rowID )} /> ); } } renderFooter && rows.push(renderFooter()); return this.props.renderScrollComponent({...this.props, children: rows}); } static DataSource = ListViewDataSource; } module.exports = ListViewMock;
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-color')) : typeof define === 'function' && define.amd ? define(['exports', 'd3-color'], factory) : (factory((global.d3_interpolate = {}),global.d3_color)); }(this, function (exports,d3Color) { 'use strict'; function constant(x) { return function() { return x; }; } function linear(a, d) { return function(t) { return a + t * d; }; } function exponential(a, b, y) { return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) { return Math.pow(a + t * b, y); }; } function hue(a, b) { var d = b - a; return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a); } function gamma(y) { return (y = +y) === 1 ? nogamma : function(a, b) { return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a); }; } function nogamma(a, b) { var d = b - a; return d ? linear(a, d) : constant(isNaN(a) ? b : a); } var rgb$1 = (function gamma$$(y) { var interpolateColor = gamma(y); function interpolateRgb(start, end) { var r = interpolateColor((start = d3Color.rgb(start)).r, (end = d3Color.rgb(end)).r), g = interpolateColor(start.g, end.g), b = interpolateColor(start.b, end.b), opacity = interpolateColor(start.opacity, end.opacity); return function(t) { start.r = r(t); start.g = g(t); start.b = b(t); start.opacity = opacity(t); return start + ""; }; } interpolateRgb.gamma = gamma$$; return interpolateRgb; })(1); // TODO sparse arrays? function array(a, b) { var x = [], c = [], na = a ? a.length : 0, nb = b ? b.length : 0, n0 = Math.min(na, nb), i; for (i = 0; i < n0; ++i) x.push(value(a[i], b[i])); for (; i < na; ++i) c[i] = a[i]; for (; i < nb; ++i) c[i] = b[i]; return function(t) { for (i = 0; i < n0; ++i) c[i] = x[i](t); return c; }; } function number(a, b) { return a = +a, b -= a, function(t) { return a + b * t; }; } function object(a, b) { var i = {}, c = {}, k; if (a === null || typeof a !== "object") a = {}; if (b === null || typeof b !== "object") b = {}; for (k in a) { if (k in b) { i[k] = value(a[k], b[k]); } else { c[k] = a[k]; } } for (k in b) { if (!(k in a)) { c[k] = b[k]; } } return function(t) { for (k in i) c[k] = i[k](t); return c; }; } var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; var reB = new RegExp(reA.source, "g"); function zero(b) { return function() { return b; }; } function one(b) { return function(t) { return b(t) + ""; }; } function string(a, b) { var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b am, // current match in a bm, // current match in b bs, // string preceding current number in b, if any i = -1, // index in s s = [], // string constants and placeholders q = []; // number interpolators // Coerce inputs to strings. a = a + "", b = b + ""; // Interpolate pairs of numbers in a & b. while ((am = reA.exec(a)) && (bm = reB.exec(b))) { if ((bs = bm.index) > bi) { // a string precedes the next number in b bs = b.slice(bi, bs); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match if (s[i]) s[i] += bm; // coalesce with previous string else s[++i] = bm; } else { // interpolate non-matching numbers s[++i] = null; q.push({i: i, x: number(am, bm)}); } bi = reB.lastIndex; } // Add remains of b. if (bi < b.length) { bs = b.slice(bi); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } // Special optimization for only a single match. // Otherwise, interpolate each of the numbers and rejoin the string. return s.length < 2 ? (q[0] ? one(q[0].x) : zero(b)) : (b = q.length, function(t) { for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); return s.join(""); }); } var values = [ function(a, b) { var t = typeof b, c; return (t === "string" ? ((c = d3Color.color(b)) ? (b = c, rgb$1) : string) : b instanceof d3Color.color ? rgb$1 : Array.isArray(b) ? array : t === "object" && isNaN(b) ? object : number)(a, b); } ]; function value(a, b) { var i = values.length, f; while (--i >= 0 && !(f = values[i](a, b))); return f; } function round(a, b) { return a = +a, b -= a, function(t) { return Math.round(a + b * t); }; } var rad2deg = 180 / Math.PI; var identity = {a: 1, b: 0, c: 0, d: 1, e: 0, f: 0}; var g; // Compute x-scale and normalize the first row. // Compute shear and make second row orthogonal to first. // Compute y-scale and normalize the second row. // Finally, compute the rotation. function Transform(string) { if (!g) g = document.createElementNS("http://www.w3.org/2000/svg", "g"); if (string) g.setAttribute("transform", string), t = g.transform.baseVal.consolidate(); var t, m = t ? t.matrix : identity, r0 = [m.a, m.b], r1 = [m.c, m.d], kx = normalize(r0), kz = dot(r0, r1), ky = normalize(combine(r1, r0, -kz)) || 0; if (r0[0] * r1[1] < r1[0] * r0[1]) { r0[0] *= -1; r0[1] *= -1; kx *= -1; kz *= -1; } this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * rad2deg; this.translate = [m.e, m.f]; this.scale = [kx, ky]; this.skew = ky ? Math.atan2(kz, ky) * rad2deg : 0; } function dot(a, b) { return a[0] * b[0] + a[1] * b[1]; } function normalize(a) { var k = Math.sqrt(dot(a, a)); if (k) a[0] /= k, a[1] /= k; return k; } function combine(a, b, k) { a[0] += k * b[0]; a[1] += k * b[1]; return a; } function pop(s) { return s.length ? s.pop() + "," : ""; } function translate(ta, tb, s, q) { if (ta[0] !== tb[0] || ta[1] !== tb[1]) { var i = s.push("translate(", null, ",", null, ")"); q.push({i: i - 4, x: number(ta[0], tb[0])}, {i: i - 2, x: number(ta[1], tb[1])}); } else if (tb[0] || tb[1]) { s.push("translate(" + tb + ")"); } } function rotate(ra, rb, s, q) { if (ra !== rb) { if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; // shortest path q.push({i: s.push(pop(s) + "rotate(", null, ")") - 2, x: number(ra, rb)}); } else if (rb) { s.push(pop(s) + "rotate(" + rb + ")"); } } function skew(wa, wb, s, q) { if (wa !== wb) { q.push({i: s.push(pop(s) + "skewX(", null, ")") - 2, x: number(wa, wb)}); } else if (wb) { s.push(pop(s) + "skewX(" + wb + ")"); } } function scale(ka, kb, s, q) { if (ka[0] !== kb[0] || ka[1] !== kb[1]) { var i = s.push(pop(s) + "scale(", null, ",", null, ")"); q.push({i: i - 4, x: number(ka[0], kb[0])}, {i: i - 2, x: number(ka[1], kb[1])}); } else if (kb[0] !== 1 || kb[1] !== 1) { s.push(pop(s) + "scale(" + kb + ")"); } } function transform(a, b) { var s = [], // string constants and placeholders q = []; // number interpolators a = new Transform(a), b = new Transform(b); translate(a.translate, b.translate, s, q); rotate(a.rotate, b.rotate, s, q); skew(a.skew, b.skew, s, q); scale(a.scale, b.scale, s, q); a = b = null; // gc return function(t) { var i = -1, n = q.length, o; while (++i < n) s[(o = q[i]).i] = o.x(t); return s.join(""); }; } var rho = Math.SQRT2; var rho2 = 2; var rho4 = 4; var epsilon2 = 1e-12; function cosh(x) { return ((x = Math.exp(x)) + 1 / x) / 2; } function sinh(x) { return ((x = Math.exp(x)) - 1 / x) / 2; } function tanh(x) { return ((x = Math.exp(2 * x)) - 1) / (x + 1); } // p0 = [ux0, uy0, w0] // p1 = [ux1, uy1, w1] function zoom(p0, p1) { var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; // Special case for u0 ≅ u1. if (d2 < epsilon2) { S = Math.log(w1 / w0) / rho; i = function(t) { return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(rho * t * S) ]; } } // General case. else { var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); S = (r1 - r0) / rho; i = function(t) { var s = t * S, coshr0 = cosh(r0), u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0)); return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / cosh(rho * s + r0) ]; } } i.duration = S * 1000; return i; } function interpolateHsl(start, end) { var h = hue((start = d3Color.hsl(start)).h, (end = d3Color.hsl(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } function interpolateHslLong(start, end) { var h = nogamma((start = d3Color.hsl(start)).h, (end = d3Color.hsl(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } function interpolateLab(start, end) { var l = nogamma((start = d3Color.lab(start)).l, (end = d3Color.lab(end)).l), a = nogamma(start.a, end.a), b = nogamma(start.b, end.b), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.l = l(t); start.a = a(t); start.b = b(t); start.opacity = opacity(t); return start + ""; }; } function interpolateHcl(start, end) { var h = hue((start = d3Color.hcl(start)).h, (end = d3Color.hcl(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.c = c(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } function interpolateHclLong(start, end) { var h = nogamma((start = d3Color.hcl(start)).h, (end = d3Color.hcl(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.c = c(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } var cubehelix$1 = (function gamma(y) { y = +y; function interpolateCubehelix(start, end) { var h = hue((start = d3Color.cubehelix(start)).h, (end = d3Color.cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(Math.pow(t, y)); start.opacity = opacity(t); return start + ""; }; } interpolateCubehelix.gamma = gamma; return interpolateCubehelix; })(1); var cubehelixLong = (function gamma(y) { y = +y; function interpolateCubehelixLong(start, end) { var h = nogamma((start = d3Color.cubehelix(start)).h, (end = d3Color.cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(Math.pow(t, y)); start.opacity = opacity(t); return start + ""; }; } interpolateCubehelixLong.gamma = gamma; return interpolateCubehelixLong; })(1); var version = "0.5.2"; exports.version = version; exports.interpolate = value; exports.interpolators = values; exports.interpolateArray = array; exports.interpolateNumber = number; exports.interpolateObject = object; exports.interpolateRound = round; exports.interpolateString = string; exports.interpolateTransform = transform; exports.interpolateZoom = zoom; exports.interpolateRgb = rgb$1; exports.interpolateHsl = interpolateHsl; exports.interpolateHslLong = interpolateHslLong; exports.interpolateLab = interpolateLab; exports.interpolateHcl = interpolateHcl; exports.interpolateHclLong = interpolateHclLong; exports.interpolateCubehelix = cubehelix$1; exports.interpolateCubehelixLong = cubehelixLong; }));
/** * Copyright (c) 2008-2011 The Open Source Geospatial Foundation * * Published under the BSD license. * See http://svn.geoext.org/core/trunk/geoext/license.txt for the full text * of the license. */ Ext.namespace("GeoExt.tree"); /** api: (define) * module = GeoExt.tree * class = LayerParamLoader * base_link = `Ext.util.Observable <http://dev.sencha.com/deploy/dev/docs/?class=Ext.util.Observable>`_ */ /** api: constructor * .. class:: LayerParamLoader * * A loader that creates children from its node's layer * (``OpenLayers.Layer.HTTPRequest``) by items in one of the values in * the layer's params object. */ GeoExt.tree.LayerParamLoader = function(config) { Ext.apply(this, config); this.addEvents( /** api: event[beforeload] * Triggered before loading children. Return false to avoid * loading children. * * Listener arguments: * * * loader - :class:`GeoExt.tree.LayerLoader` this loader * * node - ``Ex.tree.TreeNode`` the node that this loader is * configured with */ "beforeload", /** api: event[load] * Triggered after children were loaded. * * Listener arguments: * * * loader - :class:`GeoExt.tree.LayerLoader` this loader * * node - ``Ex.tree.TreeNode`` the node that this loader is * configured with */ "load" ); GeoExt.tree.LayerParamLoader.superclass.constructor.call(this); }; Ext.extend(GeoExt.tree.LayerParamLoader, Ext.util.Observable, { /** api: config[param] * ``String`` Key for a param (key-value pair in the params object of the * layer) that this loader uses to create childnodes from its items. The * value can either be an ``Array`` or a ``String``, delimited by the * character (or string) provided as ``delimiter`` config option. */ /** private: property[param] * ``String`` */ param: null, /** api: config[delimiter] * ``String`` Delimiter of the ``param``'s value's items. Default is * ``,`` (comma). If the ``param``'s value is an array, this property has * no effect. */ /** private: property[delimiter] * ``String`` */ delimiter: ",", /** private: method[load] * :param node: ``Ext.tree.TreeNode`` The node to add children to. * :param callback: ``Function`` */ load: function(node, callback) { if(this.fireEvent("beforeload", this, node)) { while (node.firstChild) { node.removeChild(node.firstChild); } var paramValue = (node.layer instanceof OpenLayers.Layer.HTTPRequest) && node.layer.params[this.param]; if(paramValue) { var items = (paramValue instanceof Array) ? paramValue.slice() : paramValue.split(this.delimiter); Ext.each(items, function(item, index, allItems) { this.addParamNode(item, allItems, node); }, this); } if(typeof callback == "function"){ callback(); } this.fireEvent("load", this, node); } }, /** private: method[addParamNode] * :param paramItem: ``String`` The param item that the child node will * represent. * :param allParamItems: ``Array`` The full list of param items. * :param node: :class:`GeoExt.tree.LayerNode`` The node that the param * node will be added to as child. * * Adds a child node representing a param value of the layer */ addParamNode: function(paramItem, allParamItems, node) { var child = this.createNode({ layer: node.layer, param: this.param, item: paramItem, allItems: allParamItems, delimiter: this.delimiter }); var sibling = node.item(0); if(sibling) { node.insertBefore(child, sibling); } else { node.appendChild(child); } }, /** api: method[createNode] * :param attr: ``Object`` attributes for the new node * * Override this function for custom TreeNode node implementation, or to * modify the attributes at creation time. */ createNode: function(attr){ if(this.baseAttrs){ Ext.apply(attr, this.baseAttrs); } if(typeof attr.uiProvider == 'string'){ attr.uiProvider = this.uiProviders[attr.uiProvider] || eval(attr.uiProvider); } attr.nodeType = attr.nodeType || "gx_layerparam"; return new Ext.tree.TreePanel.nodeTypes[attr.nodeType](attr); } });
/* global describe, it, expect, before */ var chai = require('chai') , authenticate = require('../../lib/middleware/authenticate') , Passport = require('../..').Passport; describe('middleware/authenticate', function() { describe('success with message set by route', function() { function Strategy() { } Strategy.prototype.authenticate = function(req, options) { var user = { id: '1', username: 'jaredhanson' }; this.success(user, { message: 'Welcome!' }); }; var passport = new Passport(); passport.use('success', new Strategy()); var request, response; before(function(done) { chai.connect.use('express', authenticate(passport, 'success', { successMessage: 'Login complete', successRedirect: 'http://www.example.com/account' })) .req(function(req) { request = req; req.session = {}; req.logIn = function(user, options, done) { this.user = user; done(); }; }) .end(function(res) { response = res; done(); }) .dispatch(); }); it('should set user', function() { expect(request.user).to.be.an('object'); expect(request.user.id).to.equal('1'); expect(request.user.username).to.equal('jaredhanson'); }); it('should add message to session', function() { expect(request.session.messages).to.have.length(1); expect(request.session.messages[0]).to.equal('Login complete'); }); it('should redirect', function() { expect(response.statusCode).to.equal(302); expect(response.getHeader('Location')).to.equal('http://www.example.com/account'); }); }); describe('success with message set by route that is added to messages', function() { function Strategy() { } Strategy.prototype.authenticate = function(req, options) { var user = { id: '1', username: 'jaredhanson' }; this.success(user, { message: 'Welcome!' }); }; var passport = new Passport(); passport.use('success', new Strategy()); var request, response; before(function(done) { chai.connect.use('express', authenticate(passport, 'success', { successMessage: 'Login complete', successRedirect: 'http://www.example.com/account' })) .req(function(req) { request = req; req.session = {}; req.session.messages = [ 'I exist!' ]; req.logIn = function(user, options, done) { this.user = user; done(); }; }) .end(function(res) { response = res; done(); }) .dispatch(); }); it('should set user', function() { expect(request.user).to.be.an('object'); expect(request.user.id).to.equal('1'); expect(request.user.username).to.equal('jaredhanson'); }); it('should add message to session', function() { expect(request.session.messages).to.have.length(2); expect(request.session.messages[0]).to.equal('I exist!'); expect(request.session.messages[1]).to.equal('Login complete'); }); it('should redirect', function() { expect(response.statusCode).to.equal(302); expect(response.getHeader('Location')).to.equal('http://www.example.com/account'); }); }); describe('success with message set by strategy', function() { function Strategy() { } Strategy.prototype.authenticate = function(req, options) { var user = { id: '1', username: 'jaredhanson' }; this.success(user, { message: 'Welcome!' }); }; var passport = new Passport(); passport.use('success', new Strategy()); var request, response; before(function(done) { chai.connect.use('express', authenticate(passport, 'success', { successMessage: true, successRedirect: 'http://www.example.com/account' })) .req(function(req) { request = req; req.session = {}; req.logIn = function(user, options, done) { this.user = user; done(); }; }) .end(function(res) { response = res; done(); }) .dispatch(); }); it('should set user', function() { expect(request.user).to.be.an('object'); expect(request.user.id).to.equal('1'); expect(request.user.username).to.equal('jaredhanson'); }); it('should add message to session', function() { expect(request.session.messages).to.have.length(1); expect(request.session.messages[0]).to.equal('Welcome!'); }); it('should redirect', function() { expect(response.statusCode).to.equal(302); expect(response.getHeader('Location')).to.equal('http://www.example.com/account'); }); }); describe('success with message set by strategy with extra info', function() { function Strategy() { } Strategy.prototype.authenticate = function(req, options) { var user = { id: '1', username: 'jaredhanson' }; this.success(user, { message: 'Welcome!', scope: 'read' }); }; var passport = new Passport(); passport.use('success', new Strategy()); var request, response; before(function(done) { chai.connect.use('express', authenticate(passport, 'success', { successMessage: true, successRedirect: 'http://www.example.com/account' })) .req(function(req) { request = req; req.session = {}; req.logIn = function(user, options, done) { this.user = user; done(); }; }) .end(function(res) { response = res; done(); }) .dispatch(); }); it('should set user', function() { expect(request.user).to.be.an('object'); expect(request.user.id).to.equal('1'); expect(request.user.username).to.equal('jaredhanson'); }); it('should add message to session', function() { expect(request.session.messages).to.have.length(1); expect(request.session.messages[0]).to.equal('Welcome!'); }); it('should redirect', function() { expect(response.statusCode).to.equal(302); expect(response.getHeader('Location')).to.equal('http://www.example.com/account'); }); }); });
describe('getting resources after init', function() { var resStore = { dev: { translation: { 'test': 'ok_from_dev' } }, en: { translation: { 'test': 'ok_from_en' } }, 'en-US': { translation: { 'test': 'ok_from_en-US' } } }; beforeEach(function(done) { i18n.init(i18n.functions.extend(opts, { resStore: resStore }), function() { done(); }); }); it('it should return resources for existing bundle', function() { var devTranslation = i18n.getResourceBundle('dev', 'translation'); var enTranslation = i18n.getResourceBundle('en', 'translation'); var enUSTranslation = i18n.getResourceBundle('en-US', 'translation'); expect(devTranslation.test).to.be('ok_from_dev'); expect(enTranslation.test).to.be('ok_from_en'); expect(enUSTranslation.test).to.be('ok_from_en-US'); }); it('it should return empty object for non-existing bundle', function() { var nonExisting = i18n.getResourceBundle('en-GB', 'translation'); expect(Object.keys(nonExisting).length).to.be(0); }); it('it should use default namespace when namespace argument is left out', function() { var enTranslation = i18n.getResourceBundle('en'); expect(enTranslation.test).to.be('ok_from_en'); }); it('it should return a clone of the resources', function() { var enTranslation = i18n.getResourceBundle('en'); enTranslation.test = 'ok_from_en_changed'; expect(enTranslation.test).to.be('ok_from_en_changed'); expect(resStore.en.translation.test).to.be('ok_from_en'); }); });
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import heroComponent from './hero.component'; let heroModule = angular.module('hero', [ uiRouter ]) .directive('hero', heroComponent); export default heroModule;
/*! * OOjs UI v0.20.1 * https://www.mediawiki.org/wiki/OOjs_UI * * Copyright 2011–2017 OOjs UI Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2017-03-28T22:19:29Z */ ( function ( OO ) { 'use strict'; /** * Toolbars are complex interface components that permit users to easily access a variety * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are * part of the toolbar, but not configured as tools. * * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert * image’), and an icon. * * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus} * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools. * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in * any order, but each can only appear once in the toolbar. * * The toolbar can be synchronized with the state of the external "application", like a text * editor's editing area, marking tools as active/inactive (e.g. a 'bold' tool would be shown as * active when the text cursor was inside bolded text) or enabled/disabled (e.g. a table caption * tool would be disabled while the user is not editing a table). A state change is signalled by * emitting the {@link #event-updateState 'updateState' event}, which calls Tools' * {@link OO.ui.Tool#onUpdateState onUpdateState method}. * * The following is an example of a basic toolbar. * * @example * // Example of a toolbar * // Create the toolbar * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'Toolbar example' ); * * // Define the tools that we're going to place in our toolbar * * // Create a class inheriting from OO.ui.Tool * function SearchTool() { * SearchTool.parent.apply( this, arguments ); * } * OO.inheritClass( SearchTool, OO.ui.Tool ); * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one * // of 'icon' and 'title' (displayed icon and text). * SearchTool.static.name = 'search'; * SearchTool.static.icon = 'search'; * SearchTool.static.title = 'Search...'; * // Defines the action that will happen when this tool is selected (clicked). * SearchTool.prototype.onSelect = function () { * $area.text( 'Search tool clicked!' ); * // Never display this tool as "active" (selected). * this.setActive( false ); * }; * SearchTool.prototype.onUpdateState = function () {}; * // Make this tool available in our toolFactory and thus our toolbar * toolFactory.register( SearchTool ); * * // Register two more tools, nothing interesting here * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * $area.text( 'Settings tool clicked!' ); * this.setActive( false ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * * // Register two more tools, nothing interesting here * function StuffTool() { * StuffTool.parent.apply( this, arguments ); * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'ellipsis'; * StuffTool.static.title = 'More stuff'; * StuffTool.prototype.onSelect = function () { * $area.text( 'More stuff tool clicked!' ); * this.setActive( false ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a * // little popup window (a PopupWidget). * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * } * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * // 'bar' tool groups display tools' icons only, side-by-side. * type: 'bar', * include: [ 'search', 'help' ] * }, * { * // 'list' tool groups display both the titles and icons, in a dropdown list. * type: 'list', * indicator: 'down', * label: 'More', * include: [ 'settings', 'stuff' ] * } * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here, * // since it's more complicated to use. (See the next example snippet on this page.) * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( 'body' ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * toolbar.emit( 'updateState' ); * * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of * {@link #event-updateState 'updateState' event}. * * @example * // Create the toolbar * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'Toolbar example' ); * * // Define the tools that we're going to place in our toolbar * * // Create a class inheriting from OO.ui.Tool * function SearchTool() { * SearchTool.parent.apply( this, arguments ); * } * OO.inheritClass( SearchTool, OO.ui.Tool ); * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one * // of 'icon' and 'title' (displayed icon and text). * SearchTool.static.name = 'search'; * SearchTool.static.icon = 'search'; * SearchTool.static.title = 'Search...'; * // Defines the action that will happen when this tool is selected (clicked). * SearchTool.prototype.onSelect = function () { * $area.text( 'Search tool clicked!' ); * // Never display this tool as "active" (selected). * this.setActive( false ); * }; * SearchTool.prototype.onUpdateState = function () {}; * // Make this tool available in our toolFactory and thus our toolbar * toolFactory.register( SearchTool ); * * // Register two more tools, nothing interesting here * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * $area.text( 'Settings tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * * // Register two more tools, nothing interesting here * function StuffTool() { * StuffTool.parent.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'ellipsis'; * StuffTool.static.title = 'More stuff'; * StuffTool.prototype.onSelect = function () { * $area.text( 'More stuff tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented. * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * } * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * // 'bar' tool groups display tools' icons only, side-by-side. * type: 'bar', * include: [ 'search', 'help' ] * }, * { * // 'menu' tool groups display both the titles and icons, in a dropdown menu. * // Menu label indicates which items are selected. * type: 'menu', * indicator: 'down', * include: [ 'settings', 'stuff' ] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( 'body' ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * toolbar.emit( 'updateState' ); * * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups * @param {Object} [config] Configuration options * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of * the toolbar. * @cfg {string} [position='top'] Whether the toolbar is positioned above ('top') or below ('bottom') content. */ OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolFactory ) && config === undefined ) { config = toolFactory; toolFactory = config.toolFactory; toolGroupFactory = config.toolGroupFactory; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.Toolbar.parent.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); OO.ui.mixin.GroupElement.call( this, config ); // Properties this.toolFactory = toolFactory; this.toolGroupFactory = toolGroupFactory; this.groups = []; this.tools = {}; this.position = config.position || 'top'; this.$bar = $( '<div>' ); this.$actions = $( '<div>' ); this.initialized = false; this.narrowThreshold = null; this.onWindowResizeHandler = this.onWindowResize.bind( this ); // Events this.$element .add( this.$bar ).add( this.$group ).add( this.$actions ) .on( 'mousedown keydown', this.onPointerDown.bind( this ) ); // Initialization this.$group.addClass( 'oo-ui-toolbar-tools' ); if ( config.actions ) { this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) ); } this.$bar .addClass( 'oo-ui-toolbar-bar' ) .append( this.$group, '<div style="clear:both"></div>' ); this.$element.addClass( 'oo-ui-toolbar oo-ui-toolbar-position-' + this.position ).append( this.$bar ); }; /* Setup */ OO.inheritClass( OO.ui.Toolbar, OO.ui.Element ); OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter ); OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement ); /* Events */ /** * @event updateState * * An 'updateState' event must be emitted on the Toolbar (by calling `toolbar.emit( 'updateState' )`) * every time the state of the application using the toolbar changes, and an update to the state of * tools is required. * * @param {...Mixed} data Application-defined parameters */ /* Methods */ /** * Get the tool factory. * * @return {OO.ui.ToolFactory} Tool factory */ OO.ui.Toolbar.prototype.getToolFactory = function () { return this.toolFactory; }; /** * Get the toolgroup factory. * * @return {OO.Factory} Toolgroup factory */ OO.ui.Toolbar.prototype.getToolGroupFactory = function () { return this.toolGroupFactory; }; /** * Handles mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.Toolbar.prototype.onPointerDown = function ( e ) { var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ), $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' ); if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) { return false; } }; /** * Handle window resize event. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.Toolbar.prototype.onWindowResize = function () { this.$element.toggleClass( 'oo-ui-toolbar-narrow', this.$bar.width() <= this.getNarrowThreshold() ); }; /** * Get the (lazily-computed) width threshold for applying the oo-ui-toolbar-narrow * class. * * @private * @return {number} Width threshold in pixels */ OO.ui.Toolbar.prototype.getNarrowThreshold = function () { if ( this.narrowThreshold === null ) { this.narrowThreshold = this.$group.width() + this.$actions.width(); } return this.narrowThreshold; }; /** * Sets up handles and preloads required information for the toolbar to work. * This must be called after it is attached to a visible document and before doing anything else. */ OO.ui.Toolbar.prototype.initialize = function () { if ( !this.initialized ) { this.initialized = true; $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler ); this.onWindowResize(); } }; /** * Set up the toolbar. * * The toolbar is set up with a list of toolgroup configurations that specify the type of * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list}) * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups. * * @param {Object.<string,Array>} groups List of toolgroup configurations * @param {Array|string} [groups.include] Tools to include in the toolgroup * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup */ OO.ui.Toolbar.prototype.setup = function ( groups ) { var i, len, type, group, items = [], defaultType = 'bar'; // Cleanup previous groups this.reset(); // Build out new groups for ( i = 0, len = groups.length; i < len; i++ ) { group = groups[ i ]; if ( group.include === '*' ) { // Apply defaults to catch-all groups if ( group.type === undefined ) { group.type = 'list'; } if ( group.label === undefined ) { group.label = OO.ui.msg( 'ooui-toolbar-more' ); } } // Check type has been registered type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType; items.push( this.getToolGroupFactory().create( type, this, group ) ); } this.addItems( items ); }; /** * Remove all tools and toolgroups from the toolbar. */ OO.ui.Toolbar.prototype.reset = function () { var i, len; this.groups = []; this.tools = {}; for ( i = 0, len = this.items.length; i < len; i++ ) { this.items[ i ].destroy(); } this.clearItems(); }; /** * Destroy the toolbar. * * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call * this method whenever you are done using a toolbar. */ OO.ui.Toolbar.prototype.destroy = function () { $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler ); this.reset(); this.$element.remove(); }; /** * Check if the tool is available. * * Available tools are ones that have not yet been added to the toolbar. * * @param {string} name Symbolic name of tool * @return {boolean} Tool is available */ OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) { return !this.tools[ name ]; }; /** * Prevent tool from being used again. * * @param {OO.ui.Tool} tool Tool to reserve */ OO.ui.Toolbar.prototype.reserveTool = function ( tool ) { this.tools[ tool.getName() ] = tool; }; /** * Allow tool to be used again. * * @param {OO.ui.Tool} tool Tool to release */ OO.ui.Toolbar.prototype.releaseTool = function ( tool ) { delete this.tools[ tool.getName() ]; }; /** * Get accelerator label for tool. * * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label * that describes the accelerator keys for the tool passed (by symbolic name) to the method. * * @param {string} name Symbolic name of tool * @return {string|undefined} Tool accelerator label if available */ OO.ui.Toolbar.prototype.getToolAccelerator = function () { return undefined; }; /** * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}. * Each tool is configured with a static name, title, and icon and is customized with the command to carry * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory}, * which creates the tools on demand. * * Every Tool subclass must implement two methods: * * - {@link #onUpdateState} * - {@link #onSelect} * * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup}, * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example. * * For more information, please see the [OOjs UI documentation on MediaWiki][1]. * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of * the {@link #static-title static title} property is used. * * The title is used in different ways depending on the type of toolgroup that contains the tool. The * title is used as a tooltip if the tool is part of a {@link OO.ui.BarToolGroup bar} toolgroup, or as the label text if the tool is * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup. * * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key * is associated with an action by the same name as the tool and accelerator functionality has been added to the application. * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method. */ OO.ui.Tool = function OoUiTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.Tool.parent.call( this, config ); // Properties this.toolGroup = toolGroup; this.toolbar = this.toolGroup.getToolbar(); this.active = false; this.$title = $( '<span>' ); this.$accel = $( '<span>' ); this.$link = $( '<a>' ); this.title = null; // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) ); // Events this.toolbar.connect( this, { updateState: 'onUpdateState' } ); // Initialization this.$title.addClass( 'oo-ui-tool-title' ); this.$accel .addClass( 'oo-ui-tool-accel' ) .prop( { // This may need to be changed if the key names are ever localized, // but for now they are essentially written in English dir: 'ltr', lang: 'en' } ); this.$link .addClass( 'oo-ui-tool-link' ) .append( this.$icon, this.$title, this.$accel ) .attr( 'role', 'button' ); this.$element .data( 'oo-ui-tool', this ) .addClass( 'oo-ui-tool ' + 'oo-ui-tool-name-' + this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' ) ) .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel ) .append( this.$link ); this.setTitle( config.title || this.constructor.static.title ); }; /* Setup */ OO.inheritClass( OO.ui.Tool, OO.ui.Widget ); OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.Tool.static.tagName = 'span'; /** * Symbolic name of tool. * * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can * also be used when adding tools to toolgroups. * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Tool.static.name = ''; /** * Symbolic name of the group. * * The group name is used to associate tools with each other so that they can be selected later by * a {@link OO.ui.ToolGroup toolgroup}. * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Tool.static.group = ''; /** * Tool title text or a function that returns title text. The value of the static property is overridden if the #title config option is used. * * @abstract * @static * @inheritable * @property {string|Function} */ OO.ui.Tool.static.title = ''; /** * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup. * Normally only the icon is displayed, or only the label if no icon is given. * * @static * @inheritable * @property {boolean} */ OO.ui.Tool.static.displayBothIconAndLabel = false; /** * Add tool to catch-all groups automatically. * * A catch-all group, which contains all tools that do not currently belong to a toolgroup, * can be included in a toolgroup using the wildcard selector, an asterisk (*). * * @static * @inheritable * @property {boolean} */ OO.ui.Tool.static.autoAddToCatchall = true; /** * Add tool to named groups automatically. * * By default, tools that are configured with a static ‘group’ property are added * to that group and will be selected when the symbolic name of the group is specified (e.g., when * toolgroups include tools by group name). * * @static * @property {boolean} * @inheritable */ OO.ui.Tool.static.autoAddToGroup = true; /** * Check if this tool is compatible with given data. * * This is a stub that can be overridden to provide support for filtering tools based on an * arbitrary piece of information (e.g., where the cursor is in a document). The implementation * must also call this method so that the compatibility check can be performed. * * @static * @inheritable * @param {Mixed} data Data to check * @return {boolean} Tool can be used with data */ OO.ui.Tool.static.isCompatibleWith = function () { return false; }; /* Methods */ /** * Handle the toolbar state being updated. This method is called when the * {@link OO.ui.Toolbar#event-updateState 'updateState' event} is emitted on the * {@link OO.ui.Toolbar Toolbar} that uses this tool, and should set the state of this tool * depending on application state (usually by calling #setDisabled to enable or disable the tool, * or #setActive to mark is as currently in-use or not). * * This is an abstract method that must be overridden in a concrete subclass. * * @method * @protected * @abstract */ OO.ui.Tool.prototype.onUpdateState = null; /** * Handle the tool being selected. This method is called when the user triggers this tool, * usually by clicking on its label/icon. * * This is an abstract method that must be overridden in a concrete subclass. * * @method * @protected * @abstract */ OO.ui.Tool.prototype.onSelect = null; /** * Check if the tool is active. * * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed * with the #setActive method. Additional CSS is applied to the tool to reflect the active state. * * @return {boolean} Tool is active */ OO.ui.Tool.prototype.isActive = function () { return this.active; }; /** * Make the tool appear active or inactive. * * This method should be called within #onSelect or #onUpdateState event handlers to make the tool * appear pressed or not. * * @param {boolean} state Make tool appear active */ OO.ui.Tool.prototype.setActive = function ( state ) { this.active = !!state; if ( this.active ) { this.$element.addClass( 'oo-ui-tool-active' ); this.setFlags( { progressive: true } ); } else { this.$element.removeClass( 'oo-ui-tool-active' ); this.setFlags( { progressive: false } ); } }; /** * Set the tool #title. * * @param {string|Function} title Title text or a function that returns text * @chainable */ OO.ui.Tool.prototype.setTitle = function ( title ) { this.title = OO.ui.resolveMsg( title ); this.updateTitle(); return this; }; /** * Get the tool #title. * * @return {string} Title text */ OO.ui.Tool.prototype.getTitle = function () { return this.title; }; /** * Get the tool's symbolic name. * * @return {string} Symbolic name of tool */ OO.ui.Tool.prototype.getName = function () { return this.constructor.static.name; }; /** * Update the title. */ OO.ui.Tool.prototype.updateTitle = function () { var titleTooltips = this.toolGroup.constructor.static.titleTooltips, accelTooltips = this.toolGroup.constructor.static.accelTooltips, accel = this.toolbar.getToolAccelerator( this.constructor.static.name ), tooltipParts = []; this.$title.text( this.title ); this.$accel.text( accel ); if ( titleTooltips && typeof this.title === 'string' && this.title.length ) { tooltipParts.push( this.title ); } if ( accelTooltips && typeof accel === 'string' && accel.length ) { tooltipParts.push( accel ); } if ( tooltipParts.length ) { this.$link.attr( 'title', tooltipParts.join( ' ' ) ); } else { this.$link.removeAttr( 'title' ); } }; /** * Destroy tool. * * Destroying the tool removes all event handlers and the tool’s DOM elements. * Call this method whenever you are done using a tool. */ OO.ui.Tool.prototype.destroy = function () { this.toolbar.disconnect( this ); this.$element.remove(); }; /** * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}. * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu}) * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}. * * Toolgroups can contain individual tools, groups of tools, or all available tools, as specified * using the `include` config option. See OO.ui.ToolFactory#extract on documentation of the format. * The options `exclude`, `promote`, and `demote` support the same formats. * * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general, * please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {Array|string} [include] List of tools to include in the toolgroup, see above. * @cfg {Array|string} [exclude] List of tools to exclude from the toolgroup, see above. * @cfg {Array|string} [promote] List of tools to promote to the beginning of the toolgroup, see above. * @cfg {Array|string} [demote] List of tools to demote to the end of the toolgroup, see above. * This setting is particularly useful when tools have been added to the toolgroup * en masse (e.g., via the catch-all selector). */ OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.ToolGroup.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, config ); // Properties this.toolbar = toolbar; this.tools = {}; this.pressed = null; this.autoDisabled = false; this.include = config.include || []; this.exclude = config.exclude || []; this.promote = config.promote || []; this.demote = config.demote || []; this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this ); // Events this.$element.on( { mousedown: this.onMouseKeyDown.bind( this ), mouseup: this.onMouseKeyUp.bind( this ), keydown: this.onMouseKeyDown.bind( this ), keyup: this.onMouseKeyUp.bind( this ), focus: this.onMouseOverFocus.bind( this ), blur: this.onMouseOutBlur.bind( this ), mouseover: this.onMouseOverFocus.bind( this ), mouseout: this.onMouseOutBlur.bind( this ) } ); this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } ); this.aggregate( { disable: 'itemDisable' } ); this.connect( this, { itemDisable: 'updateDisabled' } ); // Initialization this.$group.addClass( 'oo-ui-toolGroup-tools' ); this.$element .addClass( 'oo-ui-toolGroup' ) .append( this.$group ); this.populate(); }; /* Setup */ OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget ); OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement ); /* Events */ /** * @event update */ /* Static Properties */ /** * Show labels in tooltips. * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.titleTooltips = false; /** * Show acceleration labels in tooltips. * * Note: The OOjs UI library does not include an accelerator system, but does contain * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M'). * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.accelTooltips = false; /** * Automatically disable the toolgroup when all tools are disabled * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.autoDisable = true; /** * @abstract * @static * @inheritable * @property {string} */ OO.ui.ToolGroup.static.name = null; /* Methods */ /** * @inheritdoc */ OO.ui.ToolGroup.prototype.isDisabled = function () { return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments ); }; /** * @inheritdoc */ OO.ui.ToolGroup.prototype.updateDisabled = function () { var i, item, allDisabled = true; if ( this.constructor.static.autoDisable ) { for ( i = this.items.length - 1; i >= 0; i-- ) { item = this.items[ i ]; if ( !item.isDisabled() ) { allDisabled = false; break; } } this.autoDisabled = allDisabled; } OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments ); }; /** * Handle mouse down and key down events. * * @protected * @param {jQuery.Event} e Mouse down or key down event */ OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.pressed = this.getTargetTool( e ); if ( this.pressed ) { this.pressed.setActive( true ); this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true ); this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true ); } return false; } }; /** * Handle captured mouse up and key up events. * * @protected * @param {MouseEvent|KeyboardEvent} e Mouse up or key up event */ OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) { this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true ); this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true ); // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is // released, but since `this.pressed` will no longer be true, the second call will be ignored. this.onMouseKeyUp( e ); }; /** * Handle mouse up and key up events. * * @protected * @param {MouseEvent|KeyboardEvent} e Mouse up or key up event */ OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) { var tool = this.getTargetTool( e ); if ( !this.isDisabled() && this.pressed && this.pressed === tool && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.pressed.onSelect(); this.pressed = null; e.preventDefault(); e.stopPropagation(); } this.pressed = null; }; /** * Handle mouse over and focus events. * * @protected * @param {jQuery.Event} e Mouse over or focus event */ OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) { var tool = this.getTargetTool( e ); if ( this.pressed && this.pressed === tool ) { this.pressed.setActive( true ); } }; /** * Handle mouse out and blur events. * * @protected * @param {jQuery.Event} e Mouse out or blur event */ OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) { var tool = this.getTargetTool( e ); if ( this.pressed && this.pressed === tool ) { this.pressed.setActive( false ); } }; /** * Get the closest tool to a jQuery.Event. * * Only tool links are considered, which prevents other elements in the tool such as popups from * triggering tool group interactions. * * @private * @param {jQuery.Event} e * @return {OO.ui.Tool|null} Tool, `null` if none was found */ OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) { var tool, $item = $( e.target ).closest( '.oo-ui-tool-link' ); if ( $item.length ) { tool = $item.parent().data( 'oo-ui-tool' ); } return tool && !tool.isDisabled() ? tool : null; }; /** * Handle tool registry register events. * * If a tool is registered after the group is created, we must repopulate the list to account for: * * - a tool being added that may be included * - a tool already included being overridden * * @protected * @param {string} name Symbolic name of tool */ OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () { this.populate(); }; /** * Get the toolbar that contains the toolgroup. * * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup */ OO.ui.ToolGroup.prototype.getToolbar = function () { return this.toolbar; }; /** * Add and remove tools based on configuration. */ OO.ui.ToolGroup.prototype.populate = function () { var i, len, name, tool, toolFactory = this.toolbar.getToolFactory(), names = {}, add = [], remove = [], list = this.toolbar.getToolFactory().getTools( this.include, this.exclude, this.promote, this.demote ); // Build a list of needed tools for ( i = 0, len = list.length; i < len; i++ ) { name = list[ i ]; if ( // Tool exists toolFactory.lookup( name ) && // Tool is available or is already in this group ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] ) ) { // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before // creating it, but we can't call reserveTool() yet because we haven't created the tool. this.toolbar.tools[ name ] = true; tool = this.tools[ name ]; if ( !tool ) { // Auto-initialize tools on first use this.tools[ name ] = tool = toolFactory.create( name, this ); tool.updateTitle(); } this.toolbar.reserveTool( tool ); add.push( tool ); names[ name ] = true; } } // Remove tools that are no longer needed for ( name in this.tools ) { if ( !names[ name ] ) { this.tools[ name ].destroy(); this.toolbar.releaseTool( this.tools[ name ] ); remove.push( this.tools[ name ] ); delete this.tools[ name ]; } } if ( remove.length ) { this.removeItems( remove ); } // Update emptiness state if ( add.length ) { this.$element.removeClass( 'oo-ui-toolGroup-empty' ); } else { this.$element.addClass( 'oo-ui-toolGroup-empty' ); } // Re-add tools (moving existing ones to new locations) this.addItems( add ); // Disabled state may depend on items this.updateDisabled(); }; /** * Destroy toolgroup. */ OO.ui.ToolGroup.prototype.destroy = function () { var name; this.clearItems(); this.toolbar.getToolFactory().disconnect( this ); for ( name in this.tools ) { this.toolbar.releaseTool( this.tools[ name ] ); this.tools[ name ].disconnect( this ).destroy(); delete this.tools[ name ]; } this.$element.remove(); }; /** * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools}, * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example. * * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.Factory * @constructor */ OO.ui.ToolFactory = function OoUiToolFactory() { // Parent constructor OO.ui.ToolFactory.parent.call( this ); }; /* Setup */ OO.inheritClass( OO.ui.ToolFactory, OO.Factory ); /* Methods */ /** * Get tools from the factory * * @param {Array|string} [include] Included tools, see #extract for format * @param {Array|string} [exclude] Excluded tools, see #extract for format * @param {Array|string} [promote] Promoted tools, see #extract for format * @param {Array|string} [demote] Demoted tools, see #extract for format * @return {string[]} List of tools */ OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) { var i, len, included, promoted, demoted, auto = [], used = {}; // Collect included and not excluded tools included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) ); // Promotion promoted = this.extract( promote, used ); demoted = this.extract( demote, used ); // Auto for ( i = 0, len = included.length; i < len; i++ ) { if ( !used[ included[ i ] ] ) { auto.push( included[ i ] ); } } return promoted.concat( auto ).concat( demoted ); }; /** * Get a flat list of names from a list of names or groups. * * Normally, `collection` is an array of tool specifications. Tools can be specified in the * following ways: * * - To include an individual tool, use the symbolic name: `{ name: 'tool-name' }` or `'tool-name'`. * - To include all tools in a group, use the group name: `{ group: 'group-name' }`. (To assign the * tool to a group, use OO.ui.Tool.static.group.) * * Alternatively, to include all tools that are not yet assigned to any other toolgroup, use the * catch-all selector `'*'`. * * If `used` is passed, tool names that appear as properties in this object will be considered * already assigned, and will not be returned even if specified otherwise. The tool names extracted * by this function call will be added as new properties in the object. * * @private * @param {Array|string} collection List of tools, see above * @param {Object} [used] Object containing information about used tools, see above * @return {string[]} List of extracted tool names */ OO.ui.ToolFactory.prototype.extract = function ( collection, used ) { var i, len, item, name, tool, names = []; collection = !Array.isArray( collection ) ? [ collection ] : collection; for ( i = 0, len = collection.length; i < len; i++ ) { item = collection[ i ]; if ( item === '*' ) { for ( name in this.registry ) { tool = this.registry[ name ]; if ( // Only add tools by group name when auto-add is enabled tool.static.autoAddToCatchall && // Exclude already used tools ( !used || !used[ name ] ) ) { names.push( name ); if ( used ) { used[ name ] = true; } } } } else { // Allow plain strings as shorthand for named tools if ( typeof item === 'string' ) { item = { name: item }; } if ( OO.isPlainObject( item ) ) { if ( item.group ) { for ( name in this.registry ) { tool = this.registry[ name ]; if ( // Include tools with matching group tool.static.group === item.group && // Only add tools by group name when auto-add is enabled tool.static.autoAddToGroup && // Exclude already used tools ( !used || !used[ name ] ) ) { names.push( name ); if ( used ) { used[ name ] = true; } } } // Include tools with matching name and exclude already used tools } else if ( item.name && ( !used || !used[ item.name ] ) ) { names.push( item.name ); if ( used ) { used[ item.name ] = true; } } } } } return names; }; /** * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must * specify a symbolic name and be registered with the factory. The following classes are registered by * default: * * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’) * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’) * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’) * * See {@link OO.ui.Toolbar toolbars} for an example. * * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.Factory * @constructor */ OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() { var i, l, defaultClasses; // Parent constructor OO.Factory.call( this ); defaultClasses = this.constructor.static.getDefaultClasses(); // Register default toolgroups for ( i = 0, l = defaultClasses.length; i < l; i++ ) { this.register( defaultClasses[ i ] ); } }; /* Setup */ OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory ); /* Static Methods */ /** * Get a default set of classes to be registered on construction. * * @return {Function[]} Default classes */ OO.ui.ToolGroupFactory.static.getDefaultClasses = function () { return [ OO.ui.BarToolGroup, OO.ui.ListToolGroup, OO.ui.MenuToolGroup ]; }; /** * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured * with a static name, title, and icon, as well with as any popup configurations. Unlike other tools, popup tools do not require that developers specify * an #onSelect or #onUpdateState method, as these methods have been implemented already. * * // Example of a popup tool. When selected, a popup tool displays * // a popup window. * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * }; * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @abstract * @class * @extends OO.ui.Tool * @mixins OO.ui.mixin.PopupElement * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options */ OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Parent constructor OO.ui.PopupTool.parent.call( this, toolGroup, config ); // Mixin constructors OO.ui.mixin.PopupElement.call( this, config ); // Initialization this.popup.setPosition( toolGroup.getToolbar().position === 'bottom' ? 'above' : 'below' ); this.$element .addClass( 'oo-ui-popupTool' ) .append( this.popup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool ); OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement ); /* Methods */ /** * Handle the tool being selected. * * @inheritdoc */ OO.ui.PopupTool.prototype.onSelect = function () { if ( !this.isDisabled() ) { this.popup.toggle(); } this.setActive( false ); return false; }; /** * Handle the toolbar state being updated. * * @inheritdoc */ OO.ui.PopupTool.prototype.onUpdateState = function () { this.setActive( false ); }; /** * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools} * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list} * when the ToolGroupTool is selected. * * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere. * * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * }; * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.static.groupConfig = { * icon: 'settings', * label: 'ToolGroupTool', * include: [ 'setting1', 'setting2' ] * }; * toolFactory.register( SettingsTool ); * * For more information, please see the [OOjs UI documentation on MediaWiki][1]. * * Please note that this implementation is subject to change per [T74159] [2]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool * [2]: https://phabricator.wikimedia.org/T74159 * * @abstract * @class * @extends OO.ui.Tool * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options */ OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Parent constructor OO.ui.ToolGroupTool.parent.call( this, toolGroup, config ); // Properties this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig ); // Events this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } ); // Initialization this.$link.remove(); this.$element .addClass( 'oo-ui-toolGroupTool' ) .append( this.innerToolGroup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool ); /* Static Properties */ /** * Toolgroup configuration. * * The toolgroup configuration consists of the tools to include, as well as an icon and label * to use for the bar item. Tools can be included by symbolic name, group, or with the * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information. * * @property {Object.<string,Array>} */ OO.ui.ToolGroupTool.static.groupConfig = {}; /* Methods */ /** * Handle the tool being selected. * * @inheritdoc */ OO.ui.ToolGroupTool.prototype.onSelect = function () { this.innerToolGroup.setActive( !this.innerToolGroup.active ); return false; }; /** * Synchronize disabledness state of the tool with the inner toolgroup. * * @private * @param {boolean} disabled Element is disabled */ OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) { this.setDisabled( disabled ); }; /** * Handle the toolbar state being updated. * * @inheritdoc */ OO.ui.ToolGroupTool.prototype.onUpdateState = function () { this.setActive( false ); }; /** * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration. * * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for * more information. * @return {OO.ui.ListToolGroup} */ OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) { if ( group.include === '*' ) { // Apply defaults to catch-all groups if ( group.label === undefined ) { group.label = OO.ui.msg( 'ooui-toolbar-more' ); } } return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group ); }; /** * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup} * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over * the tool. * * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is * set up. * * @example * // Example of a BarToolGroup with two tools * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' ); * * // Define the tools that we're going to place in our toolbar * * // Create a class inheriting from OO.ui.Tool * function SearchTool() { * SearchTool.parent.apply( this, arguments ); * } * OO.inheritClass( SearchTool, OO.ui.Tool ); * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one * // of 'icon' and 'title' (displayed icon and text). * SearchTool.static.name = 'search'; * SearchTool.static.icon = 'search'; * SearchTool.static.title = 'Search...'; * // Defines the action that will happen when this tool is selected (clicked). * SearchTool.prototype.onSelect = function () { * $area.text( 'Search tool clicked!' ); * // Never display this tool as "active" (selected). * this.setActive( false ); * }; * SearchTool.prototype.onUpdateState = function () {}; * // Make this tool available in our toolFactory and thus our toolbar * toolFactory.register( SearchTool ); * * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a * // little popup window (a PopupWidget). * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * } * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * // 'bar' tool groups display tools by icon only * type: 'bar', * include: [ 'search', 'help' ] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( 'body' ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}. * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.ui.ToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options */ OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Parent constructor OO.ui.BarToolGroup.parent.call( this, toolbar, config ); // Initialization this.$element.addClass( 'oo-ui-barToolGroup' ); }; /* Setup */ OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.BarToolGroup.static.titleTooltips = true; /** * @static * @inheritdoc */ OO.ui.BarToolGroup.static.accelTooltips = true; /** * @static * @inheritdoc */ OO.ui.BarToolGroup.static.name = 'bar'; /** * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup} * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an * optional icon and label. This class can be used for other base classes that also use this functionality. * * @abstract * @class * @extends OO.ui.ToolGroup * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.ClippableElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {string} [header] Text to display at the top of the popup */ OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = $.extend( { indicator: toolbar.position === 'bottom' ? 'up' : 'down' }, config ); // Parent constructor OO.ui.PopupToolGroup.parent.call( this, toolbar, config ); // Properties this.active = false; this.dragging = false; this.onBlurHandler = this.onBlur.bind( this ); this.$handle = $( '<span>' ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, config ); OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) ); // Events this.$handle.on( { keydown: this.onHandleMouseKeyDown.bind( this ), keyup: this.onHandleMouseKeyUp.bind( this ), mousedown: this.onHandleMouseKeyDown.bind( this ), mouseup: this.onHandleMouseKeyUp.bind( this ) } ); // Initialization this.$handle .addClass( 'oo-ui-popupToolGroup-handle' ) .append( this.$icon, this.$label, this.$indicator ); // If the pop-up should have a header, add it to the top of the toolGroup. // Note: If this feature is useful for other widgets, we could abstract it into an // OO.ui.HeaderedElement mixin constructor. if ( config.header !== undefined ) { this.$group .prepend( $( '<span>' ) .addClass( 'oo-ui-popupToolGroup-header' ) .text( config.header ) ); } this.$element .addClass( 'oo-ui-popupToolGroup' ) .prepend( this.$handle ); }; /* Setup */ OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * @inheritdoc */ OO.ui.PopupToolGroup.prototype.setDisabled = function () { // Parent method OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments ); if ( this.isDisabled() && this.isElementAttached() ) { this.setActive( false ); } }; /** * Handle focus being lost. * * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object. * * @protected * @param {MouseEvent|KeyboardEvent} e Mouse up or key up event */ OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) { // Only deactivate when clicking outside the dropdown element if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) { this.setActive( false ); } }; /** * @inheritdoc */ OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) { // Only close toolgroup when a tool was actually selected if ( !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.setActive( false ); } return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e ); }; /** * Handle mouse up and key up events. * * @protected * @param {jQuery.Event} e Mouse up or key up event */ OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { return false; } }; /** * Handle mouse down and key down events. * * @protected * @param {jQuery.Event} e Mouse down or key down event */ OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.setActive( !this.active ); return false; } }; /** * Switch into 'active' mode. * * When active, the popup is visible. A mouseup event anywhere in the document will trigger * deactivation. * * @param {boolean} value The active state to set */ OO.ui.PopupToolGroup.prototype.setActive = function ( value ) { var containerWidth, containerLeft; value = !!value; if ( this.active !== value ) { this.active = value; if ( value ) { this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true ); this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler, true ); this.$clippable.css( 'left', '' ); // Try anchoring the popup to the left first this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' ); this.toggleClipping( true ); if ( this.isClippedHorizontally() ) { // Anchoring to the left caused the popup to clip, so anchor it to the right instead this.toggleClipping( false ); this.$element .removeClass( 'oo-ui-popupToolGroup-left' ) .addClass( 'oo-ui-popupToolGroup-right' ); this.toggleClipping( true ); } if ( this.isClippedHorizontally() ) { // Anchoring to the right also caused the popup to clip, so just make it fill the container containerWidth = this.$clippableScrollableContainer.width(); containerLeft = this.$clippableScrollableContainer.offset().left; this.toggleClipping( false ); this.$element.removeClass( 'oo-ui-popupToolGroup-right' ); this.$clippable.css( { left: -( this.$element.offset().left - containerLeft ), width: containerWidth } ); } } else { this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true ); this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler, true ); this.$element.removeClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right' ); this.toggleClipping( false ); } } }; /** * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup} * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured * with a label, icon, indicator, header, and title. * * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits * users to collapse the list again. * * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}. * * @example * // Example of a ListToolGroup * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // Configure and register two tools * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * this.setActive( false ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * // Register two more tools, nothing interesting here * function StuffTool() { * StuffTool.parent.apply( this, arguments ); * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'search'; * StuffTool.static.title = 'Change the world'; * StuffTool.prototype.onSelect = function () { * this.setActive( false ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * toolbar.setup( [ * { * // Configurations for list toolgroup. * type: 'list', * label: 'ListToolGroup', * icon: 'ellipsis', * title: 'This is the title, displayed when user moves the mouse over the list toolgroup', * header: 'This is the header', * include: [ 'settings', 'stuff' ], * allowCollapse: ['stuff'] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * frame.$element.append( * toolbar.$element * ); * $( 'body' ).append( frame.$element ); * // Build the toolbar. This must be done after the toolbar has been appended to the document. * toolbar.initialize(); * * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.ui.PopupToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that * are included in the toolgroup, but are not designated as collapsible, will always be displayed. * To open a collapsible list in its expanded state, set #expanded to 'true'. * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible. * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened. * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom. */ OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Properties (must be set before parent constructor, which calls #populate) this.allowCollapse = config.allowCollapse; this.forceExpand = config.forceExpand; this.expanded = config.expanded !== undefined ? config.expanded : false; this.collapsibleTools = []; // Parent constructor OO.ui.ListToolGroup.parent.call( this, toolbar, config ); // Initialization this.$element.addClass( 'oo-ui-listToolGroup' ); }; /* Setup */ OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.ListToolGroup.static.name = 'list'; /* Methods */ /** * @inheritdoc */ OO.ui.ListToolGroup.prototype.populate = function () { var i, len, allowCollapse = []; OO.ui.ListToolGroup.parent.prototype.populate.call( this ); // Update the list of collapsible tools if ( this.allowCollapse !== undefined ) { allowCollapse = this.allowCollapse; } else if ( this.forceExpand !== undefined ) { allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand ); } this.collapsibleTools = []; for ( i = 0, len = allowCollapse.length; i < len; i++ ) { if ( this.tools[ allowCollapse[ i ] ] !== undefined ) { this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] ); } } // Keep at the end, even when tools are added this.$group.append( this.getExpandCollapseTool().$element ); this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 ); this.updateCollapsibleState(); }; /** * Get the expand/collapse tool for this group * * @return {OO.ui.Tool} Expand collapse tool */ OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () { var ExpandCollapseTool; if ( this.expandCollapseTool === undefined ) { ExpandCollapseTool = function () { ExpandCollapseTool.parent.apply( this, arguments ); }; OO.inheritClass( ExpandCollapseTool, OO.ui.Tool ); ExpandCollapseTool.prototype.onSelect = function () { this.toolGroup.expanded = !this.toolGroup.expanded; this.toolGroup.updateCollapsibleState(); this.setActive( false ); }; ExpandCollapseTool.prototype.onUpdateState = function () { // Do nothing. Tool interface requires an implementation of this function. }; ExpandCollapseTool.static.name = 'more-fewer'; this.expandCollapseTool = new ExpandCollapseTool( this ); } return this.expandCollapseTool; }; /** * @inheritdoc */ OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) { // Do not close the popup when the user wants to show more/fewer tools if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which // hides the popup list when a tool is selected) and call ToolGroup's implementation directly. return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e ); } else { return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e ); } }; OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () { var i, len; this.getExpandCollapseTool() .setIcon( this.expanded ? 'collapse' : 'expand' ) .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) ); for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) { this.collapsibleTools[ i ].toggle( this.expanded ); } // Re-evaluate clipping, because our height has changed this.clip(); }; /** * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup} * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools}, * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected, * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header. * * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar * is set up. * * @example * // Example of a MenuToolGroup * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' ); * * // Define the tools that we're going to place in our toolbar * * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * $area.text( 'Settings tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * * function StuffTool() { * StuffTool.parent.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'ellipsis'; * StuffTool.static.title = 'More stuff'; * StuffTool.prototype.onSelect = function () { * $area.text( 'More stuff tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * type: 'menu', * header: 'This is the (optional) header', * title: 'This is the (optional) title', * include: [ 'settings', 'stuff' ] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( 'body' ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * toolbar.emit( 'updateState' ); * * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}. * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.ui.PopupToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options */ OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.MenuToolGroup.parent.call( this, toolbar, config ); // Events this.toolbar.connect( this, { updateState: 'onUpdateState' } ); // Initialization this.$element.addClass( 'oo-ui-menuToolGroup' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.MenuToolGroup.static.name = 'menu'; /* Methods */ /** * Handle the toolbar state being updated. * * When the state changes, the title of each active item in the menu will be joined together and * used as a label for the group. The label will be empty if none of the items are active. * * @private */ OO.ui.MenuToolGroup.prototype.onUpdateState = function () { var name, labelTexts = []; for ( name in this.tools ) { if ( this.tools[ name ].isActive() ) { labelTexts.push( this.tools[ name ].getTitle() ); } } this.setLabel( labelTexts.join( ', ' ) || ' ' ); }; }( OO ) );
import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; it("renders without crashing", () => { const div = document.createElement("div"); ReactDOM.render(<App />, div); });
import _extends from"@babel/runtime/helpers/esm/extends";import React from"react";import SvgIcon from"../SvgIcon";export default function createSvgIcon(e,t){const o=(o,r)=>React.createElement(SvgIcon,_extends({"data-testid":`${t}Icon`,ref:r},o),e);return"production"!==process.env.NODE_ENV&&(o.displayName=`${t}Icon`),o.muiName=SvgIcon.muiName,React.memo(React.forwardRef(o))};
"use strict"; module.exports = function (t, a) { a(t.call("AA", "aa"), 0, "Same"); a.ok(t.call("Amber", "zebra") < 0, "Less"); a.ok(t.call("Zebra", "amber") > 0, "Greater"); };
var core = require("../level3/core"); require("./node"); exports.dom = { living: { core: core } };
(function(root, factory) { if(typeof exports === 'object') { module.exports = factory(); } else if(typeof define === 'function' && define.amd) { define('GMaps', [], factory); } root.GMaps = factory(); }(this, function() { /*! * GMaps.js v0.4.11 * http://hpneo.github.com/gmaps/ * * Copyright 2014, Gustavo Leon * Released under the MIT License. */ if (!(typeof window.google === 'object' && window.google.maps)) { throw 'Google Maps API is required. Please register the following JavaScript library http://maps.google.com/maps/api/js?sensor=true.' } var extend_object = function(obj, new_obj) { var name; if (obj === new_obj) { return obj; } for (name in new_obj) { obj[name] = new_obj[name]; } return obj; }; var replace_object = function(obj, replace) { var name; if (obj === replace) { return obj; } for (name in replace) { if (obj[name] != undefined) { obj[name] = replace[name]; } } return obj; }; var array_map = function(array, callback) { var original_callback_params = Array.prototype.slice.call(arguments, 2), array_return = [], array_length = array.length, i; if (Array.prototype.map && array.map === Array.prototype.map) { array_return = Array.prototype.map.call(array, function(item) { callback_params = original_callback_params; callback_params.splice(0, 0, item); return callback.apply(this, callback_params); }); } else { for (i = 0; i < array_length; i++) { callback_params = original_callback_params; callback_params.splice(0, 0, array[i]); array_return.push(callback.apply(this, callback_params)); } } return array_return; }; var array_flat = function(array) { var new_array = [], i; for (i = 0; i < array.length; i++) { new_array = new_array.concat(array[i]); } return new_array; }; var coordsToLatLngs = function(coords, useGeoJSON) { var first_coord = coords[0], second_coord = coords[1]; if (useGeoJSON) { first_coord = coords[1]; second_coord = coords[0]; } return new google.maps.LatLng(first_coord, second_coord); }; var arrayToLatLng = function(coords, useGeoJSON) { var i; for (i = 0; i < coords.length; i++) { if (coords[i].length > 0 && typeof(coords[i][0]) == "object") { coords[i] = arrayToLatLng(coords[i], useGeoJSON); } else { coords[i] = coordsToLatLngs(coords[i], useGeoJSON); } } return coords; }; var getElementById = function(id, context) { var element, id = id.replace('#', ''); if ('jQuery' in this && context) { element = $("#" + id, context)[0]; } else { element = document.getElementById(id); }; return element; }; var findAbsolutePosition = function(obj) { var curleft = 0, curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft, curtop]; }; var GMaps = (function(global) { "use strict"; var doc = document; var GMaps = function(options) { if (!this) return new GMaps(options); options.zoom = options.zoom || 15; options.mapType = options.mapType || 'roadmap'; var self = this, i, events_that_hide_context_menu = ['bounds_changed', 'center_changed', 'click', 'dblclick', 'drag', 'dragend', 'dragstart', 'idle', 'maptypeid_changed', 'projection_changed', 'resize', 'tilesloaded', 'zoom_changed'], events_that_doesnt_hide_context_menu = ['mousemove', 'mouseout', 'mouseover'], options_to_be_deleted = ['el', 'lat', 'lng', 'mapType', 'width', 'height', 'markerClusterer', 'enableNewStyle'], container_id = options.el || options.div, markerClustererFunction = options.markerClusterer, mapType = google.maps.MapTypeId[options.mapType.toUpperCase()], map_center = new google.maps.LatLng(options.lat, options.lng), zoomControl = options.zoomControl || true, zoomControlOpt = options.zoomControlOpt || { style: 'DEFAULT', position: 'TOP_LEFT' }, zoomControlStyle = zoomControlOpt.style || 'DEFAULT', zoomControlPosition = zoomControlOpt.position || 'TOP_LEFT', panControl = options.panControl || true, mapTypeControl = options.mapTypeControl || true, scaleControl = options.scaleControl || true, streetViewControl = options.streetViewControl || true, overviewMapControl = overviewMapControl || true, map_options = {}, map_base_options = { zoom: this.zoom, center: map_center, mapTypeId: mapType }, map_controls_options = { panControl: panControl, zoomControl: zoomControl, zoomControlOptions: { style: google.maps.ZoomControlStyle[zoomControlStyle], position: google.maps.ControlPosition[zoomControlPosition] }, mapTypeControl: mapTypeControl, scaleControl: scaleControl, streetViewControl: streetViewControl, overviewMapControl: overviewMapControl }; if (typeof(options.el) === 'string' || typeof(options.div) === 'string') { this.el = getElementById(container_id, options.context); } else { this.el = container_id; } if (typeof(this.el) === 'undefined' || this.el === null) { throw 'No element defined.'; } window.context_menu = window.context_menu || {}; window.context_menu[self.el.id] = {}; this.controls = []; this.overlays = []; this.layers = []; // array with kml/georss and fusiontables layers, can be as many this.singleLayers = {}; // object with the other layers, only one per layer this.markers = []; this.polylines = []; this.routes = []; this.polygons = []; this.infoWindow = null; this.overlay_el = null; this.zoom = options.zoom; this.registered_events = {}; this.el.style.width = options.width || this.el.scrollWidth || this.el.offsetWidth; this.el.style.height = options.height || this.el.scrollHeight || this.el.offsetHeight; google.maps.visualRefresh = options.enableNewStyle; for (i = 0; i < options_to_be_deleted.length; i++) { delete options[options_to_be_deleted[i]]; } if(options.disableDefaultUI != true) { map_base_options = extend_object(map_base_options, map_controls_options); } map_options = extend_object(map_base_options, options); for (i = 0; i < events_that_hide_context_menu.length; i++) { delete map_options[events_that_hide_context_menu[i]]; } for (i = 0; i < events_that_doesnt_hide_context_menu.length; i++) { delete map_options[events_that_doesnt_hide_context_menu[i]]; } this.map = new google.maps.Map(this.el, map_options); if (markerClustererFunction) { this.markerClusterer = markerClustererFunction.apply(this, [this.map]); } var buildContextMenuHTML = function(control, e) { var html = '', options = window.context_menu[self.el.id][control]; for (var i in options){ if (options.hasOwnProperty(i)) { var option = options[i]; html += '<li><a id="' + control + '_' + i + '" href="#">' + option.title + '</a></li>'; } } if (!getElementById('gmaps_context_menu')) return; var context_menu_element = getElementById('gmaps_context_menu'); context_menu_element.innerHTML = html; var context_menu_items = context_menu_element.getElementsByTagName('a'), context_menu_items_count = context_menu_items.length, i; for (i = 0; i < context_menu_items_count; i++) { var context_menu_item = context_menu_items[i]; var assign_menu_item_action = function(ev){ ev.preventDefault(); options[this.id.replace(control + '_', '')].action.apply(self, [e]); self.hideContextMenu(); }; google.maps.event.clearListeners(context_menu_item, 'click'); google.maps.event.addDomListenerOnce(context_menu_item, 'click', assign_menu_item_action, false); } var position = findAbsolutePosition.apply(this, [self.el]), left = position[0] + e.pixel.x - 15, top = position[1] + e.pixel.y- 15; context_menu_element.style.left = left + "px"; context_menu_element.style.top = top + "px"; context_menu_element.style.display = 'block'; }; this.buildContextMenu = function(control, e) { if (control === 'marker') { e.pixel = {}; var overlay = new google.maps.OverlayView(); overlay.setMap(self.map); overlay.draw = function() { var projection = overlay.getProjection(), position = e.marker.getPosition(); e.pixel = projection.fromLatLngToContainerPixel(position); buildContextMenuHTML(control, e); }; } else { buildContextMenuHTML(control, e); } }; this.setContextMenu = function(options) { window.context_menu[self.el.id][options.control] = {}; var i, ul = doc.createElement('ul'); for (i in options.options) { if (options.options.hasOwnProperty(i)) { var option = options.options[i]; window.context_menu[self.el.id][options.control][option.name] = { title: option.title, action: option.action }; } } ul.id = 'gmaps_context_menu'; ul.style.display = 'none'; ul.style.position = 'absolute'; ul.style.minWidth = '100px'; ul.style.background = 'white'; ul.style.listStyle = 'none'; ul.style.padding = '8px'; ul.style.boxShadow = '2px 2px 6px #ccc'; doc.body.appendChild(ul); var context_menu_element = getElementById('gmaps_context_menu') google.maps.event.addDomListener(context_menu_element, 'mouseout', function(ev) { if (!ev.relatedTarget || !this.contains(ev.relatedTarget)) { window.setTimeout(function(){ context_menu_element.style.display = 'none'; }, 400); } }, false); }; this.hideContextMenu = function() { var context_menu_element = getElementById('gmaps_context_menu'); if (context_menu_element) { context_menu_element.style.display = 'none'; } }; var setupListener = function(object, name) { google.maps.event.addListener(object, name, function(e){ if (e == undefined) { e = this; } options[name].apply(this, [e]); self.hideContextMenu(); }); }; for (var ev = 0; ev < events_that_hide_context_menu.length; ev++) { var name = events_that_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } for (var ev = 0; ev < events_that_doesnt_hide_context_menu.length; ev++) { var name = events_that_doesnt_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } google.maps.event.addListener(this.map, 'rightclick', function(e) { if (options.rightclick) { options.rightclick.apply(this, [e]); } if(window.context_menu[self.el.id]['map'] != undefined) { self.buildContextMenu('map', e); } }); this.refresh = function() { google.maps.event.trigger(this.map, 'resize'); }; this.fitZoom = function() { var latLngs = [], markers_length = this.markers.length, i; for (i = 0; i < markers_length; i++) { if(typeof(this.markers[i].visible) === 'boolean' && this.markers[i].visible) { latLngs.push(this.markers[i].getPosition()); } } this.fitLatLngBounds(latLngs); }; this.fitLatLngBounds = function(latLngs) { var total = latLngs.length; var bounds = new google.maps.LatLngBounds(); for(var i=0; i < total; i++) { bounds.extend(latLngs[i]); } this.map.fitBounds(bounds); }; this.setCenter = function(lat, lng, callback) { this.map.panTo(new google.maps.LatLng(lat, lng)); if (callback) { callback(); } }; this.getElement = function() { return this.el; }; this.zoomIn = function(value) { value = value || 1; this.zoom = this.map.getZoom() + value; this.map.setZoom(this.zoom); }; this.zoomOut = function(value) { value = value || 1; this.zoom = this.map.getZoom() - value; this.map.setZoom(this.zoom); }; var native_methods = [], method; for (method in this.map) { if (typeof(this.map[method]) == 'function' && !this[method]) { native_methods.push(method); } } for (i=0; i < native_methods.length; i++) { (function(gmaps, scope, method_name) { gmaps[method_name] = function(){ return scope[method_name].apply(scope, arguments); }; })(this, this.map, native_methods[i]); } }; return GMaps; })(this); GMaps.prototype.createControl = function(options) { var control = document.createElement('div'); control.style.cursor = 'pointer'; if (options.disableDefaultStyles !== true) { control.style.fontFamily = 'Roboto, Arial, sans-serif'; control.style.fontSize = '11px'; control.style.boxShadow = 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px'; } for (var option in options.style) { control.style[option] = options.style[option]; } if (options.id) { control.id = options.id; } if (options.classes) { control.className = options.classes; } if (options.content) { control.innerHTML = options.content; } for (var ev in options.events) { (function(object, name) { google.maps.event.addDomListener(object, name, function(){ options.events[name].apply(this, [this]); }); })(control, ev); } control.index = 1; return control; }; GMaps.prototype.addControl = function(options) { var position = google.maps.ControlPosition[options.position.toUpperCase()]; delete options.position; var control = this.createControl(options); this.controls.push(control); this.map.controls[position].push(control); return control; }; GMaps.prototype.createMarker = function(options) { if (options.lat == undefined && options.lng == undefined && options.position == undefined) { throw 'No latitude or longitude defined.'; } var self = this, details = options.details, fences = options.fences, outside = options.outside, base_options = { position: new google.maps.LatLng(options.lat, options.lng), map: null }, marker_options = extend_object(base_options, options); delete marker_options.lat; delete marker_options.lng; delete marker_options.fences; delete marker_options.outside; var marker = new google.maps.Marker(marker_options); marker.fences = fences; if (options.infoWindow) { marker.infoWindow = new google.maps.InfoWindow(options.infoWindow); var info_window_events = ['closeclick', 'content_changed', 'domready', 'position_changed', 'zindex_changed']; for (var ev = 0; ev < info_window_events.length; ev++) { (function(object, name) { if (options.infoWindow[name]) { google.maps.event.addListener(object, name, function(e){ options.infoWindow[name].apply(this, [e]); }); } })(marker.infoWindow, info_window_events[ev]); } } var marker_events = ['animation_changed', 'clickable_changed', 'cursor_changed', 'draggable_changed', 'flat_changed', 'icon_changed', 'position_changed', 'shadow_changed', 'shape_changed', 'title_changed', 'visible_changed', 'zindex_changed']; var marker_events_with_mouse = ['dblclick', 'drag', 'dragend', 'dragstart', 'mousedown', 'mouseout', 'mouseover', 'mouseup']; for (var ev = 0; ev < marker_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(){ options[name].apply(this, [this]); }); } })(marker, marker_events[ev]); } for (var ev = 0; ev < marker_events_with_mouse.length; ev++) { (function(map, object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(me){ if(!me.pixel){ me.pixel = map.getProjection().fromLatLngToPoint(me.latLng) } options[name].apply(this, [me]); }); } })(this.map, marker, marker_events_with_mouse[ev]); } google.maps.event.addListener(marker, 'click', function() { this.details = details; if (options.click) { options.click.apply(this, [this]); } if (marker.infoWindow) { self.hideInfoWindows(); marker.infoWindow.open(self.map, marker); } }); google.maps.event.addListener(marker, 'rightclick', function(e) { e.marker = this; if (options.rightclick) { options.rightclick.apply(this, [e]); } if (window.context_menu[self.el.id]['marker'] != undefined) { self.buildContextMenu('marker', e); } }); if (marker.fences) { google.maps.event.addListener(marker, 'dragend', function() { self.checkMarkerGeofence(marker, function(m, f) { outside(m, f); }); }); } return marker; }; GMaps.prototype.addMarker = function(options) { var marker; if(options.hasOwnProperty('gm_accessors_')) { // Native google.maps.Marker object marker = options; } else { if ((options.hasOwnProperty('lat') && options.hasOwnProperty('lng')) || options.position) { marker = this.createMarker(options); } else { throw 'No latitude or longitude defined.'; } } marker.setMap(this.map); if(this.markerClusterer) { this.markerClusterer.addMarker(marker); } this.markers.push(marker); GMaps.fire('marker_added', marker, this); return marker; }; GMaps.prototype.addMarkers = function(array) { for (var i = 0, marker; marker=array[i]; i++) { this.addMarker(marker); } return this.markers; }; GMaps.prototype.hideInfoWindows = function() { for (var i = 0, marker; marker = this.markers[i]; i++){ if (marker.infoWindow) { marker.infoWindow.close(); } } }; GMaps.prototype.removeMarker = function(marker) { for (var i = 0; i < this.markers.length; i++) { if (this.markers[i] === marker) { this.markers[i].setMap(null); this.markers.splice(i, 1); if(this.markerClusterer) { this.markerClusterer.removeMarker(marker); } GMaps.fire('marker_removed', marker, this); break; } } return marker; }; GMaps.prototype.removeMarkers = function (collection) { var new_markers = []; if (typeof collection == 'undefined') { for (var i = 0; i < this.markers.length; i++) { this.markers[i].setMap(null); } this.markers = new_markers; } else { for (var i = 0; i < collection.length; i++) { if (this.markers.indexOf(collection[i]) > -1) { this.markers[i].setMap(null); } } for (var i = 0; i < this.markers.length; i++) { if (this.markers[i].getMap() != null) { new_markers.push(this.markers[i]); } } this.markers = new_markers; } }; GMaps.prototype.drawOverlay = function(options) { var overlay = new google.maps.OverlayView(), auto_show = true; overlay.setMap(this.map); if (options.auto_show != null) { auto_show = options.auto_show; } overlay.onAdd = function() { var el = document.createElement('div'); el.style.borderStyle = "none"; el.style.borderWidth = "0px"; el.style.position = "absolute"; el.style.zIndex = 100; el.innerHTML = options.content; overlay.el = el; if (!options.layer) { options.layer = 'overlayLayer'; } var panes = this.getPanes(), overlayLayer = panes[options.layer], stop_overlay_events = ['contextmenu', 'DOMMouseScroll', 'dblclick', 'mousedown']; overlayLayer.appendChild(el); for (var ev = 0; ev < stop_overlay_events.length; ev++) { (function(object, name) { google.maps.event.addDomListener(object, name, function(e){ if (navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) { e.cancelBubble = true; e.returnValue = false; } else { e.stopPropagation(); } }); })(el, stop_overlay_events[ev]); } google.maps.event.trigger(this, 'ready'); }; overlay.draw = function() { var projection = this.getProjection(), pixel = projection.fromLatLngToDivPixel(new google.maps.LatLng(options.lat, options.lng)); options.horizontalOffset = options.horizontalOffset || 0; options.verticalOffset = options.verticalOffset || 0; var el = overlay.el, content = el.children[0], content_height = content.clientHeight, content_width = content.clientWidth; switch (options.verticalAlign) { case 'top': el.style.top = (pixel.y - content_height + options.verticalOffset) + 'px'; break; default: case 'middle': el.style.top = (pixel.y - (content_height / 2) + options.verticalOffset) + 'px'; break; case 'bottom': el.style.top = (pixel.y + options.verticalOffset) + 'px'; break; } switch (options.horizontalAlign) { case 'left': el.style.left = (pixel.x - content_width + options.horizontalOffset) + 'px'; break; default: case 'center': el.style.left = (pixel.x - (content_width / 2) + options.horizontalOffset) + 'px'; break; case 'right': el.style.left = (pixel.x + options.horizontalOffset) + 'px'; break; } el.style.display = auto_show ? 'block' : 'none'; if (!auto_show) { options.show.apply(this, [el]); } }; overlay.onRemove = function() { var el = overlay.el; if (options.remove) { options.remove.apply(this, [el]); } else { overlay.el.parentNode.removeChild(overlay.el); overlay.el = null; } }; this.overlays.push(overlay); return overlay; }; GMaps.prototype.removeOverlay = function(overlay) { for (var i = 0; i < this.overlays.length; i++) { if (this.overlays[i] === overlay) { this.overlays[i].setMap(null); this.overlays.splice(i, 1); break; } } }; GMaps.prototype.removeOverlays = function() { for (var i = 0, item; item = this.overlays[i]; i++) { item.setMap(null); } this.overlays = []; }; GMaps.prototype.drawPolyline = function(options) { var path = [], points = options.path; if (points.length) { if (points[0][0] === undefined) { path = points; } else { for (var i=0, latlng; latlng=points[i]; i++) { path.push(new google.maps.LatLng(latlng[0], latlng[1])); } } } var polyline_options = { map: this.map, path: path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight, geodesic: options.geodesic, clickable: true, editable: false, visible: true }; if (options.hasOwnProperty("clickable")) { polyline_options.clickable = options.clickable; } if (options.hasOwnProperty("editable")) { polyline_options.editable = options.editable; } if (options.hasOwnProperty("icons")) { polyline_options.icons = options.icons; } if (options.hasOwnProperty("zIndex")) { polyline_options.zIndex = options.zIndex; } var polyline = new google.maps.Polyline(polyline_options); var polyline_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polyline_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polyline, polyline_events[ev]); } this.polylines.push(polyline); GMaps.fire('polyline_added', polyline, this); return polyline; }; GMaps.prototype.removePolyline = function(polyline) { for (var i = 0; i < this.polylines.length; i++) { if (this.polylines[i] === polyline) { this.polylines[i].setMap(null); this.polylines.splice(i, 1); GMaps.fire('polyline_removed', polyline, this); break; } } }; GMaps.prototype.removePolylines = function() { for (var i = 0, item; item = this.polylines[i]; i++) { item.setMap(null); } this.polylines = []; }; GMaps.prototype.drawCircle = function(options) { options = extend_object({ map: this.map, center: new google.maps.LatLng(options.lat, options.lng) }, options); delete options.lat; delete options.lng; var polygon = new google.maps.Circle(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); return polygon; }; GMaps.prototype.drawRectangle = function(options) { options = extend_object({ map: this.map }, options); var latLngBounds = new google.maps.LatLngBounds( new google.maps.LatLng(options.bounds[0][0], options.bounds[0][1]), new google.maps.LatLng(options.bounds[1][0], options.bounds[1][1]) ); options.bounds = latLngBounds; var polygon = new google.maps.Rectangle(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); return polygon; }; GMaps.prototype.drawPolygon = function(options) { var useGeoJSON = false; if(options.hasOwnProperty("useGeoJSON")) { useGeoJSON = options.useGeoJSON; } delete options.useGeoJSON; options = extend_object({ map: this.map }, options); if (useGeoJSON == false) { options.paths = [options.paths.slice(0)]; } if (options.paths.length > 0) { if (options.paths[0].length > 0) { options.paths = array_flat(array_map(options.paths, arrayToLatLng, useGeoJSON)); } } var polygon = new google.maps.Polygon(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); GMaps.fire('polygon_added', polygon, this); return polygon; }; GMaps.prototype.removePolygon = function(polygon) { for (var i = 0; i < this.polygons.length; i++) { if (this.polygons[i] === polygon) { this.polygons[i].setMap(null); this.polygons.splice(i, 1); GMaps.fire('polygon_removed', polygon, this); break; } } }; GMaps.prototype.removePolygons = function() { for (var i = 0, item; item = this.polygons[i]; i++) { item.setMap(null); } this.polygons = []; }; GMaps.prototype.getFromFusionTables = function(options) { var events = options.events; delete options.events; var fusion_tables_options = options, layer = new google.maps.FusionTablesLayer(fusion_tables_options); for (var ev in events) { (function(object, name) { google.maps.event.addListener(object, name, function(e) { events[name].apply(this, [e]); }); })(layer, ev); } this.layers.push(layer); return layer; }; GMaps.prototype.loadFromFusionTables = function(options) { var layer = this.getFromFusionTables(options); layer.setMap(this.map); return layer; }; GMaps.prototype.getFromKML = function(options) { var url = options.url, events = options.events; delete options.url; delete options.events; var kml_options = options, layer = new google.maps.KmlLayer(url, kml_options); for (var ev in events) { (function(object, name) { google.maps.event.addListener(object, name, function(e) { events[name].apply(this, [e]); }); })(layer, ev); } this.layers.push(layer); return layer; }; GMaps.prototype.loadFromKML = function(options) { var layer = this.getFromKML(options); layer.setMap(this.map); return layer; }; GMaps.prototype.addLayer = function(layerName, options) { //var default_layers = ['weather', 'clouds', 'traffic', 'transit', 'bicycling', 'panoramio', 'places']; options = options || {}; var layer; switch(layerName) { case 'weather': this.singleLayers.weather = layer = new google.maps.weather.WeatherLayer(); break; case 'clouds': this.singleLayers.clouds = layer = new google.maps.weather.CloudLayer(); break; case 'traffic': this.singleLayers.traffic = layer = new google.maps.TrafficLayer(); break; case 'transit': this.singleLayers.transit = layer = new google.maps.TransitLayer(); break; case 'bicycling': this.singleLayers.bicycling = layer = new google.maps.BicyclingLayer(); break; case 'panoramio': this.singleLayers.panoramio = layer = new google.maps.panoramio.PanoramioLayer(); layer.setTag(options.filter); delete options.filter; //click event if (options.click) { google.maps.event.addListener(layer, 'click', function(event) { options.click(event); delete options.click; }); } break; case 'places': this.singleLayers.places = layer = new google.maps.places.PlacesService(this.map); //search, nearbySearch, radarSearch callback, Both are the same if (options.search || options.nearbySearch || options.radarSearch) { var placeSearchRequest = { bounds : options.bounds || null, keyword : options.keyword || null, location : options.location || null, name : options.name || null, radius : options.radius || null, rankBy : options.rankBy || null, types : options.types || null }; if (options.radarSearch) { layer.radarSearch(placeSearchRequest, options.radarSearch); } if (options.search) { layer.search(placeSearchRequest, options.search); } if (options.nearbySearch) { layer.nearbySearch(placeSearchRequest, options.nearbySearch); } } //textSearch callback if (options.textSearch) { var textSearchRequest = { bounds : options.bounds || null, location : options.location || null, query : options.query || null, radius : options.radius || null }; layer.textSearch(textSearchRequest, options.textSearch); } break; } if (layer !== undefined) { if (typeof layer.setOptions == 'function') { layer.setOptions(options); } if (typeof layer.setMap == 'function') { layer.setMap(this.map); } return layer; } }; GMaps.prototype.removeLayer = function(layer) { if (typeof(layer) == "string" && this.singleLayers[layer] !== undefined) { this.singleLayers[layer].setMap(null); delete this.singleLayers[layer]; } else { for (var i = 0; i < this.layers.length; i++) { if (this.layers[i] === layer) { this.layers[i].setMap(null); this.layers.splice(i, 1); break; } } } }; var travelMode, unitSystem; GMaps.prototype.getRoutes = function(options) { switch (options.travelMode) { case 'bicycling': travelMode = google.maps.TravelMode.BICYCLING; break; case 'transit': travelMode = google.maps.TravelMode.TRANSIT; break; case 'driving': travelMode = google.maps.TravelMode.DRIVING; break; default: travelMode = google.maps.TravelMode.WALKING; break; } if (options.unitSystem === 'imperial') { unitSystem = google.maps.UnitSystem.IMPERIAL; } else { unitSystem = google.maps.UnitSystem.METRIC; } var base_options = { avoidHighways: false, avoidTolls: false, optimizeWaypoints: false, waypoints: [] }, request_options = extend_object(base_options, options); request_options.origin = /string/.test(typeof options.origin) ? options.origin : new google.maps.LatLng(options.origin[0], options.origin[1]); request_options.destination = /string/.test(typeof options.destination) ? options.destination : new google.maps.LatLng(options.destination[0], options.destination[1]); request_options.travelMode = travelMode; request_options.unitSystem = unitSystem; delete request_options.callback; delete request_options.error; var self = this, service = new google.maps.DirectionsService(); service.route(request_options, function(result, status) { if (status === google.maps.DirectionsStatus.OK) { for (var r in result.routes) { if (result.routes.hasOwnProperty(r)) { self.routes.push(result.routes[r]); } } if (options.callback) { options.callback(self.routes); } } else { if (options.error) { options.error(result, status); } } }); }; GMaps.prototype.removeRoutes = function() { this.routes = []; }; GMaps.prototype.getElevations = function(options) { options = extend_object({ locations: [], path : false, samples : 256 }, options); if (options.locations.length > 0) { if (options.locations[0].length > 0) { options.locations = array_flat(array_map([options.locations], arrayToLatLng, false)); } } var callback = options.callback; delete options.callback; var service = new google.maps.ElevationService(); //location request if (!options.path) { delete options.path; delete options.samples; service.getElevationForLocations(options, function(result, status) { if (callback && typeof(callback) === "function") { callback(result, status); } }); //path request } else { var pathRequest = { path : options.locations, samples : options.samples }; service.getElevationAlongPath(pathRequest, function(result, status) { if (callback && typeof(callback) === "function") { callback(result, status); } }); } }; GMaps.prototype.cleanRoute = GMaps.prototype.removePolylines; GMaps.prototype.drawRoute = function(options) { var self = this; this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints: options.waypoints, unitSystem: options.unitSystem, error: options.error, callback: function(e) { if (e.length > 0) { self.drawPolyline({ path: e[e.length - 1].overview_path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); if (options.callback) { options.callback(e[e.length - 1]); } } } }); }; GMaps.prototype.travelRoute = function(options) { if (options.origin && options.destination) { this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints : options.waypoints, error: options.error, callback: function(e) { //start callback if (e.length > 0 && options.start) { options.start(e[e.length - 1]); } //step callback if (e.length > 0 && options.step) { var route = e[e.length - 1]; if (route.legs.length > 0) { var steps = route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; options.step(step, (route.legs[0].steps.length - 1)); } } } //end callback if (e.length > 0 && options.end) { options.end(e[e.length - 1]); } } }); } else if (options.route) { if (options.route.legs.length > 0) { var steps = options.route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; options.step(step); } } } }; GMaps.prototype.drawSteppedRoute = function(options) { var self = this; if (options.origin && options.destination) { this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints : options.waypoints, error: options.error, callback: function(e) { //start callback if (e.length > 0 && options.start) { options.start(e[e.length - 1]); } //step callback if (e.length > 0 && options.step) { var route = e[e.length - 1]; if (route.legs.length > 0) { var steps = route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; self.drawPolyline({ path: step.path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); options.step(step, (route.legs[0].steps.length - 1)); } } } //end callback if (e.length > 0 && options.end) { options.end(e[e.length - 1]); } } }); } else if (options.route) { if (options.route.legs.length > 0) { var steps = options.route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; self.drawPolyline({ path: step.path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); options.step(step); } } } }; GMaps.Route = function(options) { this.origin = options.origin; this.destination = options.destination; this.waypoints = options.waypoints; this.map = options.map; this.route = options.route; this.step_count = 0; this.steps = this.route.legs[0].steps; this.steps_length = this.steps.length; this.polyline = this.map.drawPolyline({ path: new google.maps.MVCArray(), strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }).getPath(); }; GMaps.Route.prototype.getRoute = function(options) { var self = this; this.map.getRoutes({ origin : this.origin, destination : this.destination, travelMode : options.travelMode, waypoints : this.waypoints || [], error: options.error, callback : function() { self.route = e[0]; if (options.callback) { options.callback.call(self); } } }); }; GMaps.Route.prototype.back = function() { if (this.step_count > 0) { this.step_count--; var path = this.route.legs[0].steps[this.step_count].path; for (var p in path){ if (path.hasOwnProperty(p)){ this.polyline.pop(); } } } }; GMaps.Route.prototype.forward = function() { if (this.step_count < this.steps_length) { var path = this.route.legs[0].steps[this.step_count].path; for (var p in path){ if (path.hasOwnProperty(p)){ this.polyline.push(path[p]); } } this.step_count++; } }; GMaps.prototype.checkGeofence = function(lat, lng, fence) { return fence.containsLatLng(new google.maps.LatLng(lat, lng)); }; GMaps.prototype.checkMarkerGeofence = function(marker, outside_callback) { if (marker.fences) { for (var i = 0, fence; fence = marker.fences[i]; i++) { var pos = marker.getPosition(); if (!this.checkGeofence(pos.lat(), pos.lng(), fence)) { outside_callback(marker, fence); } } } }; GMaps.prototype.toImage = function(options) { var options = options || {}, static_map_options = {}; static_map_options['size'] = options['size'] || [this.el.clientWidth, this.el.clientHeight]; static_map_options['lat'] = this.getCenter().lat(); static_map_options['lng'] = this.getCenter().lng(); if (this.markers.length > 0) { static_map_options['markers'] = []; for (var i = 0; i < this.markers.length; i++) { static_map_options['markers'].push({ lat: this.markers[i].getPosition().lat(), lng: this.markers[i].getPosition().lng() }); } } if (this.polylines.length > 0) { var polyline = this.polylines[0]; static_map_options['polyline'] = {}; static_map_options['polyline']['path'] = google.maps.geometry.encoding.encodePath(polyline.getPath()); static_map_options['polyline']['strokeColor'] = polyline.strokeColor static_map_options['polyline']['strokeOpacity'] = polyline.strokeOpacity static_map_options['polyline']['strokeWeight'] = polyline.strokeWeight } return GMaps.staticMapURL(static_map_options); }; GMaps.staticMapURL = function(options){ var parameters = [], data, static_root = 'http://maps.googleapis.com/maps/api/staticmap'; if (options.url) { static_root = options.url; delete options.url; } static_root += '?'; var markers = options.markers; delete options.markers; if (!markers && options.marker) { markers = [options.marker]; delete options.marker; } var styles = options.styles; delete options.styles; var polyline = options.polyline; delete options.polyline; /** Map options **/ if (options.center) { parameters.push('center=' + options.center); delete options.center; } else if (options.address) { parameters.push('center=' + options.address); delete options.address; } else if (options.lat) { parameters.push(['center=', options.lat, ',', options.lng].join('')); delete options.lat; delete options.lng; } else if (options.visible) { var visible = encodeURI(options.visible.join('|')); parameters.push('visible=' + visible); } var size = options.size; if (size) { if (size.join) { size = size.join('x'); } delete options.size; } else { size = '630x300'; } parameters.push('size=' + size); if (!options.zoom && options.zoom !== false) { options.zoom = 15; } var sensor = options.hasOwnProperty('sensor') ? !!options.sensor : true; delete options.sensor; parameters.push('sensor=' + sensor); for (var param in options) { if (options.hasOwnProperty(param)) { parameters.push(param + '=' + options[param]); } } /** Markers **/ if (markers) { var marker, loc; for (var i=0; data=markers[i]; i++) { marker = []; if (data.size && data.size !== 'normal') { marker.push('size:' + data.size); delete data.size; } else if (data.icon) { marker.push('icon:' + encodeURI(data.icon)); delete data.icon; } if (data.color) { marker.push('color:' + data.color.replace('#', '0x')); delete data.color; } if (data.label) { marker.push('label:' + data.label[0].toUpperCase()); delete data.label; } loc = (data.address ? data.address : data.lat + ',' + data.lng); delete data.address; delete data.lat; delete data.lng; for(var param in data){ if (data.hasOwnProperty(param)) { marker.push(param + ':' + data[param]); } } if (marker.length || i === 0) { marker.push(loc); marker = marker.join('|'); parameters.push('markers=' + encodeURI(marker)); } // New marker without styles else { marker = parameters.pop() + encodeURI('|' + loc); parameters.push(marker); } } } /** Map Styles **/ if (styles) { for (var i = 0; i < styles.length; i++) { var styleRule = []; if (styles[i].featureType && styles[i].featureType != 'all' ) { styleRule.push('feature:' + styles[i].featureType); } if (styles[i].elementType && styles[i].elementType != 'all') { styleRule.push('element:' + styles[i].elementType); } for (var j = 0; j < styles[i].stylers.length; j++) { for (var p in styles[i].stylers[j]) { var ruleArg = styles[i].stylers[j][p]; if (p == 'hue' || p == 'color') { ruleArg = '0x' + ruleArg.substring(1); } styleRule.push(p + ':' + ruleArg); } } var rule = styleRule.join('|'); if (rule != '') { parameters.push('style=' + rule); } } } /** Polylines **/ function parseColor(color, opacity) { if (color[0] === '#'){ color = color.replace('#', '0x'); if (opacity) { opacity = parseFloat(opacity); opacity = Math.min(1, Math.max(opacity, 0)); if (opacity === 0) { return '0x00000000'; } opacity = (opacity * 255).toString(16); if (opacity.length === 1) { opacity += opacity; } color = color.slice(0,8) + opacity; } } return color; } if (polyline) { data = polyline; polyline = []; if (data.strokeWeight) { polyline.push('weight:' + parseInt(data.strokeWeight, 10)); } if (data.strokeColor) { var color = parseColor(data.strokeColor, data.strokeOpacity); polyline.push('color:' + color); } if (data.fillColor) { var fillcolor = parseColor(data.fillColor, data.fillOpacity); polyline.push('fillcolor:' + fillcolor); } var path = data.path; if (path.join) { for (var j=0, pos; pos=path[j]; j++) { polyline.push(pos.join(',')); } } else { polyline.push('enc:' + path); } polyline = polyline.join('|'); parameters.push('path=' + encodeURI(polyline)); } /** Retina support **/ var dpi = window.devicePixelRatio || 1; parameters.push('scale=' + dpi); parameters = parameters.join('&'); return static_root + parameters; }; GMaps.prototype.addMapType = function(mapTypeId, options) { if (options.hasOwnProperty("getTileUrl") && typeof(options["getTileUrl"]) == "function") { options.tileSize = options.tileSize || new google.maps.Size(256, 256); var mapType = new google.maps.ImageMapType(options); this.map.mapTypes.set(mapTypeId, mapType); } else { throw "'getTileUrl' function required."; } }; GMaps.prototype.addOverlayMapType = function(options) { if (options.hasOwnProperty("getTile") && typeof(options["getTile"]) == "function") { var overlayMapTypeIndex = options.index; delete options.index; this.map.overlayMapTypes.insertAt(overlayMapTypeIndex, options); } else { throw "'getTile' function required."; } }; GMaps.prototype.removeOverlayMapType = function(overlayMapTypeIndex) { this.map.overlayMapTypes.removeAt(overlayMapTypeIndex); }; GMaps.prototype.addStyle = function(options) { var styledMapType = new google.maps.StyledMapType(options.styles, { name: options.styledMapName }); this.map.mapTypes.set(options.mapTypeId, styledMapType); }; GMaps.prototype.setStyle = function(mapTypeId) { this.map.setMapTypeId(mapTypeId); }; GMaps.prototype.createPanorama = function(streetview_options) { if (!streetview_options.hasOwnProperty('lat') || !streetview_options.hasOwnProperty('lng')) { streetview_options.lat = this.getCenter().lat(); streetview_options.lng = this.getCenter().lng(); } this.panorama = GMaps.createPanorama(streetview_options); this.map.setStreetView(this.panorama); return this.panorama; }; GMaps.createPanorama = function(options) { var el = getElementById(options.el, options.context); options.position = new google.maps.LatLng(options.lat, options.lng); delete options.el; delete options.context; delete options.lat; delete options.lng; var streetview_events = ['closeclick', 'links_changed', 'pano_changed', 'position_changed', 'pov_changed', 'resize', 'visible_changed'], streetview_options = extend_object({visible : true}, options); for (var i = 0; i < streetview_events.length; i++) { delete streetview_options[streetview_events[i]]; } var panorama = new google.maps.StreetViewPanorama(el, streetview_options); for (var i = 0; i < streetview_events.length; i++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(){ options[name].apply(this); }); } })(panorama, streetview_events[i]); } return panorama; }; GMaps.prototype.on = function(event_name, handler) { return GMaps.on(event_name, this, handler); }; GMaps.prototype.off = function(event_name) { GMaps.off(event_name, this); }; GMaps.custom_events = ['marker_added', 'marker_removed', 'polyline_added', 'polyline_removed', 'polygon_added', 'polygon_removed', 'geolocated', 'geolocation_failed']; GMaps.on = function(event_name, object, handler) { if (GMaps.custom_events.indexOf(event_name) == -1) { return google.maps.event.addListener(object, event_name, handler); } else { var registered_event = { handler : handler, eventName : event_name }; object.registered_events[event_name] = object.registered_events[event_name] || []; object.registered_events[event_name].push(registered_event); return registered_event; } }; GMaps.off = function(event_name, object) { if (GMaps.custom_events.indexOf(event_name) == -1) { google.maps.event.clearListeners(object, event_name); } else { object.registered_events[event_name] = []; } }; GMaps.fire = function(event_name, object, scope) { if (GMaps.custom_events.indexOf(event_name) == -1) { google.maps.event.trigger(object, event_name, Array.prototype.slice.apply(arguments).slice(2)); } else { if(event_name in scope.registered_events) { var firing_events = scope.registered_events[event_name]; for(var i = 0; i < firing_events.length; i++) { (function(handler, scope, object) { handler.apply(scope, [object]); })(firing_events[i]['handler'], scope, object); } } } }; GMaps.geolocate = function(options) { var complete_callback = options.always || options.complete; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { options.success(position); if (complete_callback) { complete_callback(); } }, function(error) { options.error(error); if (complete_callback) { complete_callback(); } }, options.options); } else { options.not_supported(); if (complete_callback) { complete_callback(); } } }; GMaps.geocode = function(options) { this.geocoder = new google.maps.Geocoder(); var callback = options.callback; if (options.hasOwnProperty('lat') && options.hasOwnProperty('lng')) { options.latLng = new google.maps.LatLng(options.lat, options.lng); } delete options.lat; delete options.lng; delete options.callback; this.geocoder.geocode(options, function(results, status) { callback(results, status); }); }; //========================== // Polygon containsLatLng // https://github.com/tparkin/Google-Maps-Point-in-Polygon // Poygon getBounds extension - google-maps-extensions // http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js if (!google.maps.Polygon.prototype.getBounds) { google.maps.Polygon.prototype.getBounds = function(latLng) { var bounds = new google.maps.LatLngBounds(); var paths = this.getPaths(); var path; for (var p = 0; p < paths.getLength(); p++) { path = paths.getAt(p); for (var i = 0; i < path.getLength(); i++) { bounds.extend(path.getAt(i)); } } return bounds; }; } if (!google.maps.Polygon.prototype.containsLatLng) { // Polygon containsLatLng - method to determine if a latLng is within a polygon google.maps.Polygon.prototype.containsLatLng = function(latLng) { // Exclude points outside of bounds as there is no way they are in the poly var bounds = this.getBounds(); if (bounds !== null && !bounds.contains(latLng)) { return false; } // Raycast point in polygon method var inPoly = false; var numPaths = this.getPaths().getLength(); for (var p = 0; p < numPaths; p++) { var path = this.getPaths().getAt(p); var numPoints = path.getLength(); var j = numPoints - 1; for (var i = 0; i < numPoints; i++) { var vertex1 = path.getAt(i); var vertex2 = path.getAt(j); if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) { if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) { inPoly = !inPoly; } } j = i; } } return inPoly; }; } google.maps.LatLngBounds.prototype.containsLatLng = function(latLng) { return this.contains(latLng); }; google.maps.Marker.prototype.setFences = function(fences) { this.fences = fences; }; google.maps.Marker.prototype.addFence = function(fence) { this.fences.push(fence); }; google.maps.Marker.prototype.getId = function() { return this['__gm_id']; }; //========================== // Array indexOf // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { "use strict"; if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; } } return GMaps; }));
module.exports = function(hljs) { var VAR_IDENT_RE = '[a-z][a-zA-Z0-9_]*'; var CHAR = { className: 'char', begin: '\\$.{1}' }; var SYMBOL = { className: 'symbol', begin: '#' + hljs.UNDERSCORE_IDENT_RE }; return { keywords: 'self super nil true false thisContext', // only 6 contains: [ { className: 'comment', begin: '"', end: '"', relevance: 0 }, hljs.APOS_STRING_MODE, { className: 'class', begin: '\\b[A-Z][A-Za-z0-9_]*', relevance: 0 }, { className: 'method', begin: VAR_IDENT_RE + ':' }, hljs.C_NUMBER_MODE, SYMBOL, CHAR, { className: 'localvars', begin: '\\|\\s*((' + VAR_IDENT_RE + ')\\s*)+\\|' }, { className: 'array', begin: '\\#\\(', end: '\\)', contains: [ hljs.APOS_STRING_MODE, CHAR, hljs.C_NUMBER_MODE, SYMBOL ] } ] }; };
"use strict"; var inherits = require('util').inherits , f = require('util').format , toError = require('./utils').toError , getSingleProperty = require('./utils').getSingleProperty , formattedOrderClause = require('./utils').formattedOrderClause , handleCallback = require('./utils').handleCallback , Logger = require('mongodb-core').Logger , EventEmitter = require('events').EventEmitter , ReadPreference = require('./read_preference') , MongoError = require('mongodb-core').MongoError , Readable = require('stream').Readable || require('readable-stream').Readable , Define = require('./metadata') , CoreCursor = require('./cursor') , Query = require('mongodb-core').Query , CoreReadPreference = require('mongodb-core').ReadPreference; /** * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB * allowing for iteration over the results returned from the underlying query. It supports * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X * or higher stream * * **AGGREGATIONCURSOR Cannot directly be instantiated** * @example * var MongoClient = require('mongodb').MongoClient, * test = require('assert'); * // Connection url * var url = 'mongodb://localhost:27017/test'; * // Connect using MongoClient * MongoClient.connect(url, function(err, db) { * // Create a collection we want to drop later * var col = db.collection('createIndexExample1'); * // Insert a bunch of documents * col.insert([{a:1, b:1} * , {a:2, b:2}, {a:3, b:3} * , {a:4, b:4}], {w:1}, function(err, result) { * test.equal(null, err); * * // Show that duplicate records got dropped * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { * test.equal(null, err); * test.equal(4, items.length); * db.close(); * }); * }); * }); */ /** * Namespace provided by the browser. * @external Readable */ /** * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) * @class AggregationCursor * @extends external:Readable * @fires AggregationCursor#data * @fires AggregationCursor#end * @fires AggregationCursor#close * @fires AggregationCursor#readable * @return {AggregationCursor} an AggregationCursor instance. */ var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); var self = this; var state = AggregationCursor.INIT; var streamOptions = {}; // MaxTimeMS var maxTimeMS = null; // Get the promiseLibrary var promiseLibrary = options.promiseLibrary; // No promise library selected fall back if(!promiseLibrary) { promiseLibrary = typeof global.Promise == 'function' ? global.Promise : require('es6-promise').Promise; } // Set up Readable.call(this, {objectMode: true}); // Internal state this.s = { // MaxTimeMS maxTimeMS: maxTimeMS // State , state: state // Stream options , streamOptions: streamOptions // BSON , bson: bson // Namespae , ns: ns // Command , cmd: cmd // Options , options: options // Topology , topology: topology // Topology Options , topologyOptions: topologyOptions // Promise library , promiseLibrary: promiseLibrary } } /** * AggregationCursor stream data event, fired for each document in the cursor. * * @event AggregationCursor#data * @type {object} */ /** * AggregationCursor stream end event * * @event AggregationCursor#end * @type {null} */ /** * AggregationCursor stream close event * * @event AggregationCursor#close * @type {null} */ /** * AggregationCursor stream readable event * * @event AggregationCursor#readable * @type {null} */ // Inherit from Readable inherits(AggregationCursor, Readable); // Set the methods to inherit from prototype var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified']; // Extend the Cursor for(var name in CoreCursor.prototype) { AggregationCursor.prototype[name] = CoreCursor.prototype[name]; } var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true); /** * Set the batch size for the cursor. * @method * @param {number} value The batchSize for the cursor. * @throws {MongoError} * @return {AggregationCursor} */ AggregationCursor.prototype.batchSize = function(value) { if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true }); if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", drvier:true }); if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; this.setCursorBatchSize(value); return this; } define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a geoNear stage to the aggregation pipeline * @method * @param {object} document The geoNear stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.geoNear = function(document) { this.s.cmd.pipeline.push({$geoNear: document}); return this; } define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a group stage to the aggregation pipeline * @method * @param {object} document The group stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.group = function(document) { this.s.cmd.pipeline.push({$group: document}); return this; } define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a limit stage to the aggregation pipeline * @method * @param {number} value The state limit value. * @return {AggregationCursor} */ AggregationCursor.prototype.limit = function(value) { this.s.cmd.pipeline.push({$limit: value}); return this; } define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a match stage to the aggregation pipeline * @method * @param {object} document The match stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.match = function(document) { this.s.cmd.pipeline.push({$match: document}); return this; } define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a maxTimeMS stage to the aggregation pipeline * @method * @param {number} value The state maxTimeMS value. * @return {AggregationCursor} */ AggregationCursor.prototype.maxTimeMS = function(value) { if(this.s.topology.lastIsMaster().minWireVersion > 2) { this.s.cmd.maxTimeMS = value; } return this; } define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a out stage to the aggregation pipeline * @method * @param {number} destination The destination name. * @return {AggregationCursor} */ AggregationCursor.prototype.out = function(destination) { this.s.cmd.pipeline.push({$out: destination}); return this; } define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a project stage to the aggregation pipeline * @method * @param {object} document The project stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.project = function(document) { this.s.cmd.pipeline.push({$project: document}); return this; } define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a redact stage to the aggregation pipeline * @method * @param {object} document The redact stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.redact = function(document) { this.s.cmd.pipeline.push({$redact: document}); return this; } define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a skip stage to the aggregation pipeline * @method * @param {number} value The state skip value. * @return {AggregationCursor} */ AggregationCursor.prototype.skip = function(value) { this.s.cmd.pipeline.push({$skip: value}); return this; } define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a sort stage to the aggregation pipeline * @method * @param {object} document The sort stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.sort = function(document) { this.s.cmd.pipeline.push({$sort: document}); return this; } define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]}); /** * Add a unwind stage to the aggregation pipeline * @method * @param {number} field The unwind field name. * @return {AggregationCursor} */ AggregationCursor.prototype.unwind = function(field) { this.s.cmd.pipeline.push({$unwind: field}); return this; } define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]}); AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; // Inherited methods define.classMethod('toArray', {callback: true, promise:true}); define.classMethod('each', {callback: true, promise:false}); define.classMethod('forEach', {callback: true, promise:false}); define.classMethod('next', {callback: true, promise:true}); define.classMethod('close', {callback: true, promise:true}); define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); define.classMethod('rewind', {callback: false, promise:false}); define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); /** * Get the next available document from the cursor, returns null if no more documents are available. * @function AggregationCursor.prototype.next * @param {AggregationCursor~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ /** * Set the new batchSize of the cursor * @function AggregationCursor.prototype.setBatchSize * @param {number} value The new batchSize for the cursor * @return {null} */ /** * Get the batchSize of the cursor * @function AggregationCursor.prototype.batchSize * @param {number} value The current batchSize for the cursor * @return {null} */ /** * The callback format for results * @callback AggregationCursor~toArrayResultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {object[]} documents All the documents the satisfy the cursor. */ /** * Returns an array of documents. The caller is responsible for making sure that there * is enough memory to store the results. Note that the array only contain partial * results when this cursor had been previouly accessed. In that case, * cursor.rewind() can be used to reset the cursor. * @method AggregationCursor.prototype.toArray * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ /** * The callback format for results * @callback AggregationCursor~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {(object|null)} result The result object if the command was executed successfully. */ /** * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, * not all of the elements will be iterated if this cursor had been previouly accessed. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements * at any given time if batch size is specified. Otherwise, the caller is responsible * for making sure that the entire result can fit the memory. * @method AggregationCursor.prototype.each * @param {AggregationCursor~resultCallback} callback The result callback. * @throws {MongoError} * @return {null} */ /** * Close the cursor, sending a AggregationCursor command and emitting close. * @method AggregationCursor.prototype.close * @param {AggregationCursor~resultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ /** * Is the cursor closed * @method AggregationCursor.prototype.isClosed * @return {boolean} */ /** * Execute the explain for the cursor * @method AggregationCursor.prototype.explain * @param {AggregationCursor~resultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ /** * Clone the cursor * @function AggregationCursor.prototype.clone * @return {AggregationCursor} */ /** * Resets the cursor * @function AggregationCursor.prototype.rewind * @return {AggregationCursor} */ /** * The callback format for the forEach iterator method * @callback AggregationCursor~iteratorCallback * @param {Object} doc An emitted document for the iterator */ /** * The callback error format for the forEach iterator method * @callback AggregationCursor~endCallback * @param {MongoError} error An error instance representing the error during the execution. */ /* * Iterates over all the documents for this cursor using the iterator, callback pattern. * @method AggregationCursor.prototype.forEach * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. * @param {AggregationCursor~endCallback} callback The end callback. * @throws {MongoError} * @return {null} */ AggregationCursor.INIT = 0; AggregationCursor.OPEN = 1; AggregationCursor.CLOSED = 2; module.exports = AggregationCursor;
/// <reference path="jquery-1.6.2.js" /> /// <reference path="jquery-ui-1.8.11.js" /> /// <reference path="jquery.validate.js" /> /// <reference path="jquery.validate.unobtrusive.js" /> /// <reference path="knockout-2.0.0.debug.js" /> /// <reference path="modernizr-2.0.6-development-only.js" />
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalCafe = (props) => ( <SvgIcon {...props}> <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM2 21h18v-2H2v2z"/> </SvgIcon> ); MapsLocalCafe = pure(MapsLocalCafe); MapsLocalCafe.displayName = 'MapsLocalCafe'; MapsLocalCafe.muiName = 'SvgIcon'; export default MapsLocalCafe;
'use strict';/** * See {@link bootstrap} for more information. * @deprecated */ var browser_1 = require('angular2/platform/browser'); exports.bootstrap = browser_1.bootstrap; var angular_entrypoint_1 = require('angular2/src/core/angular_entrypoint'); exports.AngularEntrypoint = angular_entrypoint_1.AngularEntrypoint; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYm9vdHN0cmFwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiYW5ndWxhcjIvYm9vdHN0cmFwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7R0FHRztBQUNILHdCQUF3QiwyQkFBMkIsQ0FBQztBQUE1Qyx3Q0FBNEM7QUFDcEQsbUNBQWdDLHNDQUFzQyxDQUFDO0FBQS9ELG1FQUErRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogU2VlIHtAbGluayBib290c3RyYXB9IGZvciBtb3JlIGluZm9ybWF0aW9uLlxuICogQGRlcHJlY2F0ZWRcbiAqL1xuZXhwb3J0IHtib290c3RyYXB9IGZyb20gJ2FuZ3VsYXIyL3BsYXRmb3JtL2Jyb3dzZXInO1xuZXhwb3J0IHtBbmd1bGFyRW50cnlwb2ludH0gZnJvbSAnYW5ndWxhcjIvc3JjL2NvcmUvYW5ndWxhcl9lbnRyeXBvaW50JztcbiJdfQ==
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v7.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var utils_1 = require("../utils"); var context_1 = require("../context/context"); var cellRendererFactory_1 = require("./cellRendererFactory"); /** Class to use a cellRenderer. */ var CellRendererService = (function () { function CellRendererService() { } /** Uses a cellRenderer, and returns the cellRenderer object if it is a class implementing ICellRenderer. * @cellRendererKey: The cellRenderer to use. Can be: a) a class that we call 'new' on b) a function we call * or c) a string that we use to look up the cellRenderer. * @params: The params to pass to the cell renderer if it's a function or a class. * @eTarget: The DOM element we will put the results of the html element into * * @return: If options a, it returns the created class instance */ CellRendererService.prototype.useCellRenderer = function (cellRendererKey, eTarget, params) { var cellRenderer = this.lookUpCellRenderer(cellRendererKey); if (utils_1.Utils.missing(cellRenderer)) { // this is a bug in users config, they specified a cellRenderer that doesn't exist, // the factory already printed to console, so here we just skip return; } var resultFromRenderer; var iCellRendererInstance = null; this.checkForDeprecatedItems(cellRenderer); // we check if the class has the 'getGui' method to know if it's a component var rendererIsAComponent = this.doesImplementICellRenderer(cellRenderer); // if it's a component, we create and initialise it if (rendererIsAComponent) { var CellRendererClass = cellRenderer; iCellRendererInstance = new CellRendererClass(); this.context.wireBean(iCellRendererInstance); if (iCellRendererInstance.init) { iCellRendererInstance.init(params); } resultFromRenderer = iCellRendererInstance.getGui(); } else { // otherwise it's a function, so we just use it var cellRendererFunc = cellRenderer; resultFromRenderer = cellRendererFunc(params); } if (resultFromRenderer === null || resultFromRenderer === '') { return; } if (utils_1.Utils.isNodeOrElement(resultFromRenderer)) { // a dom node or element was returned, so add child eTarget.appendChild(resultFromRenderer); } else { // otherwise assume it was html, so just insert eTarget.innerHTML = resultFromRenderer; } return iCellRendererInstance; }; CellRendererService.prototype.checkForDeprecatedItems = function (cellRenderer) { if (cellRenderer && cellRenderer.renderer) { console.warn('ag-grid: colDef.cellRenderer should not be an object, it should be a string, function or class. this ' + 'changed in v4.1.x, please check the documentation on Cell Rendering, or if you are doing grouping, look at the grouping examples.'); } }; CellRendererService.prototype.doesImplementICellRenderer = function (cellRenderer) { // see if the class has a prototype that defines a getGui method. this is very rough, // but javascript doesn't have types, so is the only way! return cellRenderer.prototype && 'getGui' in cellRenderer.prototype; }; CellRendererService.prototype.lookUpCellRenderer = function (cellRendererKey) { if (typeof cellRendererKey === 'string') { return this.cellRendererFactory.getCellRenderer(cellRendererKey); } else { return cellRendererKey; } }; __decorate([ context_1.Autowired('cellRendererFactory'), __metadata('design:type', cellRendererFactory_1.CellRendererFactory) ], CellRendererService.prototype, "cellRendererFactory", void 0); __decorate([ context_1.Autowired('context'), __metadata('design:type', context_1.Context) ], CellRendererService.prototype, "context", void 0); CellRendererService = __decorate([ context_1.Bean('cellRendererService'), __metadata('design:paramtypes', []) ], CellRendererService); return CellRendererService; }()); exports.CellRendererService = CellRendererService;
'use strict'; AccordionController.$inject = ['$scope', '$attrs', 'accordionConfig']; DropdownToggleController.$inject = ['$scope', '$attrs', 'mediaQueries', '$element', '$position', '$timeout']; dropdownToggle.$inject = ['$document', '$window', '$location']; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /* * angular-foundation-6 * http://circlingthesun.github.io/angular-foundation-6/ * Version: 0.9.37 - 2016-06-14 * License: MIT * (c) */ function AccordionController($scope, $attrs, accordionConfig) { 'ngInject'; var $ctrl = this; // This array keeps track of the accordion groups $ctrl.groups = []; // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to $ctrl.closeOthers = function (openGroup) { var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers; if (closeOthers) { angular.forEach(this.groups, function (group) { if (group !== openGroup) { group.isOpen = false; } }); } }; // This is called from the accordion-group directive to add itself to the accordion $ctrl.addGroup = function (groupScope) { var that = this; this.groups.push(groupScope); }; // This is called from the accordion-group directive when to remove itself $ctrl.removeGroup = function (group) { var index = this.groups.indexOf(group); if (index !== -1) { this.groups.splice(index, 1); } }; } angular.module('mm.foundation.accordion', []).constant('accordionConfig', { closeOthers: true }).controller('AccordionController', AccordionController) // The accordion directive simply sets up the directive controller // and adds an accordion CSS class to itself element. .directive('accordion', function () { 'ngInject'; return { restrict: 'EA', controller: AccordionController, controllerAs: '$ctrl', transclude: true, replace: false, templateUrl: 'template/accordion/accordion.html' }; }) // The accordion-group directive indicates a block of html that will expand and collapse in an accordion .directive('accordionGroup', function () { 'ngInject'; return { require: { 'accordion': '^accordion' }, // We need this directive to be inside an accordion restrict: 'EA', transclude: true, // It transcludes the contents of the directive into the template replace: true, // The element containing the directive will be replaced with the template templateUrl: 'template/accordion/accordion-group.html', scope: {}, controllerAs: "$ctrl", bindToController: { heading: '@' }, // Create an isolated scope and interpolate the heading attribute onto this scope controller: ['$scope', '$attrs', '$parse', function accordionGroupController($scope, $attrs, $parse) { 'ngInject'; var $ctrl = this; $ctrl.isOpen = false; $ctrl.setHTMLHeading = function (element) { $ctrl.HTMLHeading = element; }; $ctrl.$onInit = function () { $ctrl.accordion.addGroup($ctrl); $scope.$on('$destroy', function (event) { $ctrl.accordion.removeGroup($ctrl); }); var getIsOpen; var setIsOpen; if ($attrs.isOpen) { getIsOpen = $parse($attrs.isOpen); setIsOpen = getIsOpen.assign; $scope.$parent.$watch(getIsOpen, function (value) { $ctrl.isOpen = !!value; }); } $scope.$watch(function () { return $ctrl.isOpen; }, function (value) { if (value) { $ctrl.accordion.closeOthers($ctrl); } setIsOpen && setIsOpen($scope.$parent, value); }); }; }] }; }) // Use accordion-heading below an accordion-group to provide a heading containing HTML // <accordion-group> // <accordion-heading>Heading containing HTML - <img src="..."></accordion-heading> // </accordion-group> .directive('accordionHeading', function () { 'ngInject'; return { restrict: 'EA', transclude: true, // Grab the contents to be used as the heading template: '', // In effect remove this element! replace: true, require: '^accordionGroup', link: function link(scope, element, attr, accordionGroupCtrl, transclude) { // Pass the heading to the accordion-group controller // so that it can be transcluded into the right place in the template // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat] accordionGroupCtrl.setHTMLHeading(transclude(scope, function () {})); } }; }) // Use in the accordion-group template to indicate where you want the heading to be transcluded // You must provide the property on the accordion-group controller that will hold the transcluded element // <div class="accordion-group"> // <div class="accordion-heading" ><a ... accordion-transclude="heading">...</a></div> // ... // </div> .directive('accordionTransclude', function () { 'ngInject'; return { require: '^accordionGroup', link: function link(scope, element, attr, accordionGroupController) { scope.$watch(function () { return accordionGroupController.HTMLHeading; }, function (heading) { if (heading) { element.html(''); element.append(heading); } }); } }; }); angular.module("mm.foundation.alert", []).controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) { 'ngInject'; $scope.closeable = 'close' in $attrs && typeof $attrs.close !== "undefined"; }]).directive('alert', function () { 'ngInject'; return { restrict: 'EA', controller: 'AlertController', templateUrl: 'template/alert/alert.html', transclude: true, replace: true, scope: { type: '=', close: '&' } }; }); angular.module('mm.foundation.bindHtml', []).directive('bindHtmlUnsafe', function () { 'ngInject'; return function (scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe); scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) { element.html(value || ''); }); }; }); angular.module('mm.foundation.buttons', []).constant('buttonConfig', { activeClass: 'hollow', toggleEvent: 'click' }).controller('ButtonsController', ['buttonConfig', function (buttonConfig) { this.activeClass = buttonConfig.activeClass; this.toggleEvent = buttonConfig.toggleEvent; }]).directive('btnRadio', function () { 'ngInject'; return { require: ['btnRadio', 'ngModel'], controller: 'ButtonsController', link: function link(scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; //model -> UI ngModelCtrl.$render = function () { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio))); }; //ui->model element.bind(buttonsCtrl.toggleEvent, function () { if (!element.hasClass(buttonsCtrl.activeClass)) { scope.$apply(function () { ngModelCtrl.$setViewValue(scope.$eval(attrs.btnRadio)); ngModelCtrl.$render(); }); } }); } }; }).directive('btnCheckbox', function () { 'ngInject'; return { require: ['btnCheckbox', 'ngModel'], controller: 'ButtonsController', link: function link(scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; function getTrueValue() { return getCheckboxValue(attrs.btnCheckboxTrue, true); } function getFalseValue() { return getCheckboxValue(attrs.btnCheckboxFalse, false); } function getCheckboxValue(attributeValue, defaultValue) { var val = scope.$eval(attributeValue); return angular.isDefined(val) ? val : defaultValue; } //model -> UI ngModelCtrl.$render = function () { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); }; //ui->model element.bind(buttonsCtrl.toggleEvent, function () { scope.$apply(function () { ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); ngModelCtrl.$render(); }); }); } }; }); angular.module('mm.foundation.dropdownMenu', []).directive('dropdownMenu', ['$compile', function ($compile) { 'ngInject'; return { bindToController: { disableHover: '=', disableClickOpen: '=', closingTime: '=' }, scope: {}, restrict: 'A', controllerAs: 'vm', controller: ['$scope', '$element', function controller($scope, $element) { 'ngInject'; var vm = this; }] }; }]).directive('li', ['$timeout', function ($timeout) { 'ngInject'; return { require: '?^^dropdownMenu', restrict: 'E', link: function link($scope, $element, $attrs, dropdownMenu) { if (!dropdownMenu) { return; } var ulChild = null; var children = $element[0].children; var mouseLeaveTimeout; for (var i = 0; i < children.length; i++) { var child = angular.element(children[i]); if (child[0].nodeName === 'UL' && child.hasClass('menu')) { ulChild = child; } } var topLevel = $element.parent()[0].hasAttribute('dropdown-menu'); if (!topLevel) { $element.addClass('is-submenu-item'); } if (ulChild) { ulChild.addClass('is-dropdown-submenu menu submenu vertical'); $element.addClass('is-dropdown-submenu-parent opens-right'); if (topLevel) { ulChild.addClass('first-sub'); } if (!dropdownMenu.disableHover) { $element.on('mouseenter', function () { $timeout.cancel(mouseLeaveTimeout); $element.parent().children().children().removeClass('js-dropdown-active'); ulChild.addClass('js-dropdown-active'); $element.addClass('is-active'); }); } $element.on('click', function () { ulChild.addClass('js-dropdown-active'); $element.addClass('is-active'); // $element.attr('data-is-click', 'true'); }); $element.on('mouseleave', function () { mouseLeaveTimeout = $timeout(function () { ulChild.removeClass('js-dropdown-active'); $element.removeClass('is-active'); }, dropdownMenu.closingTime ? dropdownMenu.closingTime : 500); }); } } }; }]); function DropdownToggleController($scope, $attrs, mediaQueries, $element, $position, $timeout) { 'ngInject'; var $ctrl = this; var hoverTimeout; var $body = angular.element(document.querySelector('body')); function close(e) { $ctrl.active = false; $ctrl.css = {}; if ($ctrl.closeOnClick) { $body.off('click', close); } $scope.$apply(); } $ctrl.$onInit = function init() { if ($ctrl.closeOnClick) { $element.on('click', function (e) { return e.stopPropagation(); }); } }; $ctrl.$onDestroy = function destroy() { if ($ctrl.closeOnClick) { $body.off('click', close); } }; $ctrl.css = {}; $ctrl.toggle = function () { $ctrl.active = !$ctrl.active; $ctrl.css = {}; if (!$ctrl.active) { return; } positionPane(2); if ($ctrl.closeOnClick) { $body.on('click', close); } }; $ctrl.mouseover = function () { $timeout.cancel(hoverTimeout); $ctrl.active = true; positionPane(1); }; $ctrl.mouseleave = function () { $timeout.cancel(hoverTimeout); hoverTimeout = $timeout(function () { $scope.$apply(function () { $ctrl.active = false; }); }, 250); }; function positionPane(offset) { var dropdownTrigger = angular.element($element[0].querySelector('toggle *:first-child')); // var dropdownWidth = dropdown.prop('offsetWidth'); var triggerPosition = $position.position(dropdownTrigger); $ctrl.css.top = triggerPosition.top + triggerPosition.height + offset + 'px'; if ($ctrl.paneAlign === 'center') { $ctrl.css.left = triggerPosition.left + triggerPosition.width / 2 + 'px'; $ctrl.css.transform = 'translateX(-50%)'; } else if ($ctrl.paneAlign === 'right') { $ctrl.css.left = triggerPosition.left + triggerPosition.width + 'px'; $ctrl.css.transform = 'translateX(-100%)'; } else { $ctrl.css.left = triggerPosition.left + 'px'; } } } function dropdownToggle($document, $window, $location) { 'ngInject'; return { scope: {}, restrict: 'EA', bindToController: { closeOnClick: '=', paneAlign: '@', toggleOnHover: '=' }, transclude: { 'toggle': 'toggle', 'pane': 'pane' }, templateUrl: 'template/dropdownToggle/dropdownToggle.html', controller: DropdownToggleController, controllerAs: '$ctrl' }; } /* * dropdownToggle - Provides dropdown menu functionality * @restrict class or attribute * @example: <a dropdown-toggle="#dropdown-menu">My Dropdown Menu</a> <ul id="dropdown-menu" class="f-dropdown"> <li ng-repeat="choice in dropChoices"> <a ng-href="{{choice.href}}">{{choice.text}}</a> </li> </ul> */ angular.module('mm.foundation.dropdownToggle', ['mm.foundation.position', 'mm.foundation.mediaQueries']).directive('dropdownToggle', dropdownToggle); angular.module('mm.foundation.mediaQueries', []).factory('matchMedia', ['$document', '$window', function ($document, $window) { 'ngInject'; // MatchMedia for IE <= 9 return $window.matchMedia || function (doc, undefined) { var bool = void 0; var docElem = doc.documentElement; var refNode = docElem.firstElementChild || docElem.firstChild; // fakeBody required for <FF4 when executed in <head> var fakeBody = doc.createElement('body'); var div = doc.createElement('div'); div.id = 'mq-test-1'; div.style.cssText = 'position:absolute;top:-100em'; fakeBody.style.background = 'none'; fakeBody.appendChild(div); return function (q) { div.innerHTML = '&shy;<style media="' + q + '"> #mq-test-1 { width: 42px; }</style>'; docElem.insertBefore(fakeBody, refNode); bool = div.offsetWidth === 42; docElem.removeChild(fakeBody); return { matches: bool, media: q }; }; }($document[0]); }]).factory('mediaQueries', ['$document', 'matchMedia', function ($document, matchMedia) { 'ngInject'; // Thank you: https://github.com/sindresorhus/query-string function parseStyleToObject(str) { var styleObject = {}; if (typeof str !== 'string') { return styleObject; } str = str.trim().slice(1, -1); // browsers re-quote string style values if (!str) { return styleObject; } styleObject = str.split('&').reduce(function (ret, param) { var parts = param.replace(/\+/g, ' ').split('='); var key = parts[0]; var val = parts[1]; key = decodeURIComponent(key); // missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters val = val === undefined ? null : decodeURIComponent(val); if (!ret.hasOwnProperty(key)) { ret[key] = val; } else if (Array.isArray(ret[key])) { ret[key].push(val); } else { ret[key] = [ret[key], val]; } return ret; }, {}); return styleObject; } var head = angular.element($document[0].querySelector('head')); head.append('<meta class="foundation-mq" />'); var extractedStyles = getComputedStyle(head[0].querySelector('meta.foundation-mq')).fontFamily; var namedQueries = parseStyleToObject(extractedStyles); var queries = []; for (var key in namedQueries) { queries.push({ name: key, value: 'only screen and (min-width: ' + namedQueries[key] + ')' }); } // Gets the media query of a breakpoint. function get(size) { for (var i in this.queries) { var query = this.queries[i]; if (size === query.name) return query.value; } return null; } function atLeast(size) { var query = get(size); if (query) { return window.matchMedia(query).matches; } return false; } // Gets the current breakpoint name by testing every breakpoint and returning the last one to match (the biggest one). function getCurrentSize() { var matched = void 0; for (var i = 0; i < queries.length; i++) { var query = queries[i]; if (matchMedia(query.value).matches) { matched = query; } } if ((typeof matched === 'undefined' ? 'undefined' : _typeof(matched)) === 'object') { return matched.name; } return matched; } return { getCurrentSize: getCurrentSize, atLeast: atLeast }; }]); angular.module('mm.foundation.modal', ['mm.foundation.mediaQueries']) /** * A helper, internal data structure that acts as a map but also allows getting / removing * elements in the LIFO order */ .factory('$$stackedMap', function () { 'ngInject'; return { createNew: function createNew() { var stack = []; return { add: function add(key, value) { stack.push({ key: key, value: value }); }, get: function get(key) { for (var i = 0; i < stack.length; i++) { if (key === stack[i].key) { return stack[i]; } } }, keys: function keys() { var keys = []; for (var i = 0; i < stack.length; i++) { keys.push(stack[i].key); } return keys; }, top: function top() { return stack[stack.length - 1]; }, remove: function remove(key) { var idx = -1; for (var i = 0; i < stack.length; i++) { if (key === stack[i].key) { idx = i; break; } } return stack.splice(idx, 1)[0]; }, removeTop: function removeTop() { return stack.splice(stack.length - 1, 1)[0]; }, length: function length() { return stack.length; } }; } }; }) /** * A helper directive for the $modal service. It creates a backdrop element. */ .directive('modalBackdrop', ['$modalStack', function ($modalStack) { 'ngInject'; return { restrict: 'EA', replace: true, templateUrl: 'template/modal/backdrop.html', link: function link(scope) { scope.close = function (evt) { var modal = $modalStack.getTop(); if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && evt.target === evt.currentTarget) { evt.preventDefault(); evt.stopPropagation(); $modalStack.dismiss(modal.key, 'backdrop click'); } }; } }; }]).directive('modalWindow', function () { 'ngInject'; return { restrict: 'EA', scope: { index: '@' }, replace: true, transclude: true, templateUrl: 'template/modal/window.html', link: function link(scope, element, attrs) { scope.windowClass = attrs.windowClass || ''; } }; }).factory('$modalStack', ['$window', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap', '$animate', '$q', 'mediaQueries', function ($window, $timeout, $document, $compile, $rootScope, $$stackedMap, $animate, $q, mediaQueries) { 'ngInject'; var OPENED_MODAL_CLASS = 'is-reveal-open'; var backdropDomEl = void 0; var backdropScope = void 0; var openedWindows = $$stackedMap.createNew(); var $modalStack = {}; function backdropIndex() { var topBackdropIndex = -1; var opened = openedWindows.keys(); for (var i = 0; i < opened.length; i++) { if (openedWindows.get(opened[i]).value.backdrop) { topBackdropIndex = i; } } return topBackdropIndex; } $rootScope.$watch(backdropIndex, function (newBackdropIndex) { if (backdropScope) { backdropScope.index = newBackdropIndex; } }); function resizeHandler() { var opened = openedWindows.keys(); var fixedPositiong = opened.length > 0; var body = $document.find('body').eq(0); for (var i = 0; i < opened.length; i++) { var modalPos = $modalStack.reposition(opened[i]); if (modalPos && modalPos.position !== 'fixed') { fixedPositiong = false; } } if (fixedPositiong) { body.addClass(OPENED_MODAL_CLASS); } else { body.removeClass(OPENED_MODAL_CLASS); } } function removeModalWindow(modalInstance) { var body = $document.find('body').eq(0); var modalWindow = openedWindows.get(modalInstance).value; // clean up the stack openedWindows.remove(modalInstance); // remove window DOM element $animate.leave(modalWindow.modalDomEl).then(function () { modalWindow.modalScope.$destroy(); }); checkRemoveBackdrop(); if (openedWindows.length() === 0) { body.removeClass(OPENED_MODAL_CLASS); angular.element($window).unbind('resize', resizeHandler); } } function checkRemoveBackdrop() { // remove backdrop if no longer needed if (backdropDomEl && backdropIndex() === -1) { (function () { var backdropScopeRef = backdropScope; $animate.leave(backdropDomEl).then(function () { if (backdropScopeRef) { backdropScopeRef.$destroy(); } backdropScopeRef = null; }); backdropDomEl = null; backdropScope = null; })(); } } function getModalCenter(modalInstance) { var options = modalInstance.options; var el = options.modalDomEl; var body = $document.find('body').eq(0); var windowWidth = body.clientWidth || $document[0].documentElement.clientWidth; var windowHeight = body.clientHeight || $document[0].documentElement.clientHeight; var width = el[0].offsetWidth; var height = el[0].offsetHeight; var left = parseInt((windowWidth - width) / 2, 10); var top = 0; if (height < windowHeight) { top = parseInt((windowHeight - height) / 4, 10); } // let fitsWindow = windowHeight >= top + height; // Alwats fits on mobile var fitsWindow = mediaQueries.getCurrentSize() === 'small'; // || (windowHeight >= top + height); // Disable annoying fixed positing for higher breakpoints var modalPos = options.modalPos = options.modalPos || {}; if (modalPos.windowHeight !== windowHeight) { modalPos.scrollY = $window.pageYOffset || 0; } if (modalPos.position !== 'fixed') { modalPos.top = fitsWindow ? top : top + modalPos.scrollY; } modalPos.left = left; modalPos.position = fitsWindow ? 'fixed' : 'absolute'; modalPos.windowHeight = windowHeight; return modalPos; } $document.bind('keydown', function (evt) { var modal = void 0; if (evt.which === 27) { modal = openedWindows.top(); if (modal && modal.value.keyboard) { $rootScope.$apply(function () { $modalStack.dismiss(modal.key); }); } } }); $modalStack.open = function (modalInstance, options) { modalInstance.options = { deferred: options.deferred, modalScope: options.scope, backdrop: options.backdrop, keyboard: options.keyboard }; openedWindows.add(modalInstance, modalInstance.options); var currBackdropIndex = backdropIndex(); if (currBackdropIndex >= 0 && !backdropDomEl) { backdropScope = $rootScope.$new(true); backdropScope.index = currBackdropIndex; backdropDomEl = $compile('<div modal-backdrop></div>')(backdropScope); } if (openedWindows.length() === 1) { angular.element($window).on('resize', resizeHandler); } var classes = []; if (options.windowClass) { classes.push(options.windowClass); } if (options.size) { classes.push(options.size); } var modalDomEl = angular.element('<div modal-window></div>').attr({ style: '\n visibility: visible;\n z-index: -1;\n display: block;\n ', 'window-class': classes.join(' '), index: openedWindows.length() - 1 }); modalDomEl.html(options.content); $compile(modalDomEl)(options.scope); openedWindows.top().value.modalDomEl = modalDomEl; return $timeout(function () { // let the directives kick in options.scope.$apply(); // Attach, measure, remove var body = $document.find('body').eq(0); body.prepend(modalDomEl); var modalPos = getModalCenter(modalInstance, true); modalDomEl.detach(); modalDomEl.attr({ style: '\n visibility: visible;\n top: ' + modalPos.top + 'px;\n left: ' + modalPos.left + 'px;\n display: block;\n position: ' + modalPos.position + ';\n ' }); var promises = []; if (backdropDomEl) { promises.push($animate.enter(backdropDomEl, body, body[0].lastChild)); } promises.push($animate.enter(modalDomEl, body, body[0].lastChild)); if (modalPos.position === 'fixed') { body.addClass(OPENED_MODAL_CLASS); } // Watch for modal resize // This allows for scrolling options.scope.$watch(function () { return modalDomEl[0].offsetHeight; }, resizeHandler); return $q.all(promises); }); }; $modalStack.reposition = function (modalInstance) { var modalWindow = openedWindows.get(modalInstance).value; if (modalWindow) { var modalDomEl = modalWindow.modalDomEl; var modalPos = getModalCenter(modalInstance); modalDomEl.css('top', modalPos.top + 'px'); modalDomEl.css('left', modalPos.left + 'px'); modalDomEl.css('position', modalPos.position); return modalPos; } return {}; }; $modalStack.close = function (modalInstance, result) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow) { modalWindow.value.deferred.resolve(result); removeModalWindow(modalInstance); } }; $modalStack.dismiss = function (modalInstance, reason) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow) { modalWindow.value.deferred.reject(reason); removeModalWindow(modalInstance); } }; $modalStack.dismissAll = function (reason) { var topModal = $modalStack.getTop(); while (topModal) { $modalStack.dismiss(topModal.key, reason); topModal = $modalStack.getTop(); } }; $modalStack.getTop = function () { return openedWindows.top(); }; return $modalStack; }]).provider('$modal', function () { 'ngInject'; var $modalProvider = { options: { backdrop: true, // can be also false or 'static' keyboard: true }, $get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack', function $get($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) { 'ngInject'; var $modal = {}; function getTemplatePromise(options) { if (options.template) { return $q.resolve(options.template); } return $http.get(options.templateUrl, { cache: $templateCache }).then(function (result) { return result.data; }); } function getResolvePromises(resolves) { var promisesArr = []; angular.forEach(resolves, function (value) { if (angular.isFunction(value) || angular.isArray(value)) { promisesArr.push($q.resolve($injector.invoke(value))); } }); return promisesArr; } $modal.open = function (modalOpts) { var modalResultDeferred = $q.defer(); var modalOpenedDeferred = $q.defer(); // prepare an instance of a modal to be injected into controllers and returned to a caller var modalInstance = { result: modalResultDeferred.promise, opened: modalOpenedDeferred.promise, close: function close(result) { $modalStack.close(modalInstance, result); }, dismiss: function dismiss(reason) { $modalStack.dismiss(modalInstance, reason); }, reposition: function reposition() { $modalStack.reposition(modalInstance); } }; // merge and clean up options var modalOptions = angular.extend({}, $modalProvider.options, modalOpts); modalOptions.resolve = modalOptions.resolve || {}; // verify options if (!modalOptions.template && !modalOptions.templateUrl) { throw new Error('One of template or templateUrl options is required.'); } var templateAndResolvePromise = $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve))); var openedPromise = templateAndResolvePromise.then(function (tplAndVars) { var modalScope = (modalOptions.scope || $rootScope).$new(); modalScope.$close = modalInstance.close; modalScope.$dismiss = modalInstance.dismiss; var ctrlInstance = void 0; var ctrlLocals = {}; var resolveIter = 1; // controllers if (modalOptions.controller) { ctrlLocals.$scope = modalScope; ctrlLocals.$modalInstance = modalInstance; angular.forEach(modalOptions.resolve, function (value, key) { ctrlLocals[key] = tplAndVars[resolveIter++]; }); ctrlInstance = $controller(modalOptions.controller, ctrlLocals); if (modalOptions.controllerAs) { modalScope[modalOptions.controllerAs] = ctrlInstance; } } return $modalStack.open(modalInstance, { scope: modalScope, deferred: modalResultDeferred, content: tplAndVars[0], backdrop: modalOptions.backdrop, keyboard: modalOptions.keyboard, windowClass: modalOptions.windowClass, size: modalOptions.size }); }, function (reason) { modalResultDeferred.reject(reason); return $q.reject(reason); }); openedPromise.then(function () { modalOpenedDeferred.resolve(true); }, function () { modalOpenedDeferred.reject(false); }); return modalInstance; }; return $modal; }] }; return $modalProvider; }); angular.module('mm.foundation.offcanvas', []).directive('offCanvasWrapper', ['$window', function ($window) { 'ngInject'; return { scope: {}, bindToController: { disableAutoClose: '=' }, controllerAs: 'vm', restrict: 'C', controller: ['$scope', '$element', function controller($scope, $element) { 'ngInject'; var $ctrl = this; var left = angular.element($element[0].querySelector('.position-left')); var right = angular.element($element[0].querySelector('.position-right')); var inner = angular.element($element[0].querySelector('.off-canvas-wrapper-inner')); // var overlay = angular.element(); js-off-canvas-exit var exitOverlay = angular.element('<div class="js-off-canvas-exit"></div>'); inner.append(exitOverlay); exitOverlay.on('click', function () { $ctrl.hide(); }); $ctrl.leftToggle = function () { inner && inner.toggleClass('is-off-canvas-open'); inner && inner.toggleClass('is-open-left'); left && left.toggleClass('is-open'); exitOverlay.addClass('is-visible'); // is-visible }; $ctrl.rightToggle = function () { inner && inner.toggleClass('is-off-canvas-open'); inner && inner.toggleClass('is-open-right'); right && right.toggleClass('is-open'); exitOverlay.addClass('is-visible'); }; $ctrl.hide = function () { inner && inner.removeClass('is-open-left'); inner && inner.removeClass('is-open-right'); left && left.removeClass('is-open'); right && right.removeClass('is-open'); inner && inner.removeClass('is-off-canvas-open'); exitOverlay.removeClass('is-visible'); }; var win = angular.element($window); win.bind('resize.body', $ctrl.hide); $scope.$on('$destroy', function () { win.unbind('resize.body', $ctrl.hide); }); }] }; }]).directive('leftOffCanvasToggle', function () { 'ngInject'; return { require: '^^offCanvasWrapper', restrict: 'C', link: function link($scope, element, attrs, offCanvasWrapper) { element.on('click', function () { offCanvasWrapper.leftToggle(); }); } }; }).directive('rightOffCanvasToggle', function () { 'ngInject'; return { require: '^^offCanvasWrapper', restrict: 'C', link: function link($scope, element, attrs, offCanvasWrapper) { element.on('click', function () { offCanvasWrapper.rightToggle(); }); } }; }).directive('offCanvas', function () { 'ngInject'; return { require: { 'offCanvasWrapper': '^^offCanvasWrapper' }, restrict: 'C', bindToController: {}, scope: {}, controllerAs: 'vm', controller: function controller() {} }; }).directive('li', function () { 'ngInject'; return { require: '?^^offCanvas', restrict: 'E', link: function link($scope, element, attrs, offCanvas) { if (!offCanvas || offCanvas.offCanvasWrapper.disableAutoClose) { return; } element.on('click', function () { offCanvas.offCanvasWrapper.hide(); }); } }; }); angular.module('mm.foundation.pagination', []).controller('PaginationController', ['$scope', '$attrs', '$parse', '$interpolate', function ($scope, $attrs, $parse, $interpolate) { var self = this, setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop; this.init = function (defaultItemsPerPage) { if ($attrs.itemsPerPage) { $scope.$parent.$watch($parse($attrs.itemsPerPage), function (value) { self.itemsPerPage = parseInt(value, 10); $scope.totalPages = self.calculateTotalPages(); }); } else { this.itemsPerPage = defaultItemsPerPage; } }; this.noPrevious = function () { return this.page === 1; }; this.noNext = function () { return this.page === $scope.totalPages; }; this.isActive = function (page) { return this.page === page; }; this.calculateTotalPages = function () { var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage); return Math.max(totalPages || 0, 1); }; this.getAttributeValue = function (attribute, defaultValue, interpolate) { return angular.isDefined(attribute) ? interpolate ? $interpolate(attribute)($scope.$parent) : $scope.$parent.$eval(attribute) : defaultValue; }; this.render = function () { this.page = parseInt($scope.page, 10) || 1; if (this.page > 0 && this.page <= $scope.totalPages) { $scope.pages = this.getPages(this.page, $scope.totalPages); } }; $scope.selectPage = function (page) { if (!self.isActive(page) && page > 0 && page <= $scope.totalPages) { $scope.page = page; $scope.onSelectPage({ page: page }); } }; $scope.$watch('page', function () { self.render(); }); $scope.$watch('totalItems', function () { $scope.totalPages = self.calculateTotalPages(); }); $scope.$watch('totalPages', function (value) { setNumPages($scope.$parent, value); // Readonly variable if (self.page > value) { $scope.selectPage(value); } else { self.render(); } }); }]).constant('paginationConfig', { itemsPerPage: 10, boundaryLinks: false, directionLinks: true, firstText: 'First', previousText: 'Previous', nextText: 'Next', lastText: 'Last', rotate: true }).directive('pagination', ['$parse', 'paginationConfig', function ($parse, paginationConfig) { 'ngInject'; return { restrict: 'EA', scope: { page: '=', totalItems: '=', onSelectPage: ' &' }, controller: 'PaginationController', templateUrl: 'template/pagination/pagination.html', replace: true, link: function link(scope, element, attrs, paginationCtrl) { // Setup configuration parameters var maxSize, boundaryLinks = paginationCtrl.getAttributeValue(attrs.boundaryLinks, paginationConfig.boundaryLinks), directionLinks = paginationCtrl.getAttributeValue(attrs.directionLinks, paginationConfig.directionLinks), firstText = paginationCtrl.getAttributeValue(attrs.firstText, paginationConfig.firstText, true), previousText = paginationCtrl.getAttributeValue(attrs.previousText, paginationConfig.previousText, true), nextText = paginationCtrl.getAttributeValue(attrs.nextText, paginationConfig.nextText, true), lastText = paginationCtrl.getAttributeValue(attrs.lastText, paginationConfig.lastText, true), rotate = paginationCtrl.getAttributeValue(attrs.rotate, paginationConfig.rotate); paginationCtrl.init(paginationConfig.itemsPerPage); if (attrs.maxSize) { scope.$parent.$watch($parse(attrs.maxSize), function (value) { maxSize = parseInt(value, 10); paginationCtrl.render(); }); } // Create page object used in template function makePage(number, text, isActive, isDisabled) { return { number: number, text: text, active: isActive, disabled: isDisabled }; } paginationCtrl.getPages = function (currentPage, totalPages) { var pages = []; // Default page limits var startPage = 1, endPage = totalPages; var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages; // recompute if maxSize if (isMaxSized) { if (rotate) { // Current page is displayed in the middle of the visible ones startPage = Math.max(currentPage - Math.floor(maxSize / 2), 1); endPage = startPage + maxSize - 1; // Adjust if limit is exceeded if (endPage > totalPages) { endPage = totalPages; startPage = endPage - maxSize + 1; } } else { // Visible pages are paginated with maxSize startPage = (Math.ceil(currentPage / maxSize) - 1) * maxSize + 1; // Adjust last page if limit is exceeded endPage = Math.min(startPage + maxSize - 1, totalPages); } } // Add page number links for (var number = startPage; number <= endPage; number++) { var page = makePage(number, number, paginationCtrl.isActive(number), false); pages.push(page); } // Add links to move between page sets if (isMaxSized && !rotate) { if (startPage > 1) { var previousPageSet = makePage(startPage - 1, '...', false, false); pages.unshift(previousPageSet); } if (endPage < totalPages) { var nextPageSet = makePage(endPage + 1, '...', false, false); pages.push(nextPageSet); } } // Add previous & next links if (directionLinks) { var previousPage = makePage(currentPage - 1, previousText, false, paginationCtrl.noPrevious()); pages.unshift(previousPage); var nextPage = makePage(currentPage + 1, nextText, false, paginationCtrl.noNext()); pages.push(nextPage); } // Add first & last links if (boundaryLinks) { var firstPage = makePage(1, firstText, false, paginationCtrl.noPrevious()); pages.unshift(firstPage); var lastPage = makePage(totalPages, lastText, false, paginationCtrl.noNext()); pages.push(lastPage); } return pages; }; } }; }]).constant('pagerConfig', { itemsPerPage: 10, previousText: '« Previous', nextText: 'Next »', align: true }).directive('pager', ['pagerConfig', function (pagerConfig) { 'ngInject'; return { restrict: 'EA', scope: { page: '=', totalItems: '=', onSelectPage: ' &' }, controller: 'PaginationController', templateUrl: 'template/pagination/pager.html', replace: true, link: function link(scope, element, attrs, paginationCtrl) { // Setup configuration parameters var previousText = paginationCtrl.getAttributeValue(attrs.previousText, pagerConfig.previousText, true), nextText = paginationCtrl.getAttributeValue(attrs.nextText, pagerConfig.nextText, true), align = paginationCtrl.getAttributeValue(attrs.align, pagerConfig.align); paginationCtrl.init(pagerConfig.itemsPerPage); // Create page object used in template function makePage(number, text, isDisabled, isPrevious, isNext) { return { number: number, text: text, disabled: isDisabled, previous: align && isPrevious, next: align && isNext }; } paginationCtrl.getPages = function (currentPage) { return [makePage(currentPage - 1, previousText, paginationCtrl.noPrevious(), true, false), makePage(currentPage + 1, nextText, paginationCtrl.noNext(), false, true)]; }; } }; }]); angular.module('mm.foundation.position', []) /** * A set of utility methods that can be use to retrieve position of DOM elements. * It is meant to be used where we need to absolute-position DOM elements in * relation to other, existing elements (this is the case for tooltips, popovers, * typeahead suggestions etc.). */ .factory('$position', ['$document', '$window', function ($document, $window) { 'ngInject'; function getStyle(el, cssprop) { if (el.currentStyle) { //IE return el.currentStyle[cssprop]; } else if ($window.getComputedStyle) { return $window.getComputedStyle(el)[cssprop]; } // finally try and get inline style return el.style[cssprop]; } /** * Checks if a given element is statically positioned * @param element - raw DOM element */ function isStaticPositioned(element) { return (getStyle(element, "position") || 'static') === 'static'; } /** * returns the closest, non-statically positioned parentOffset of a given element * @param element */ var parentOffsetEl = function parentOffsetEl(element) { var docDomEl = $document[0]; var offsetParent = element.offsetParent || docDomEl; while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent)) { offsetParent = offsetParent.offsetParent; } return offsetParent || docDomEl; }; return { /** * Provides read-only equivalent of jQuery's position function: * http://api.jquery.com/position/ */ position: function position(element) { var elBCR = this.offset(element); var offsetParentBCR = { top: 0, left: 0 }; var offsetParentEl = parentOffsetEl(element[0]); if (offsetParentEl != $document[0]) { offsetParentBCR = this.offset(angular.element(offsetParentEl)); offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop; offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft; } var boundingClientRect = element[0].getBoundingClientRect(); return { width: boundingClientRect.width || element.prop('offsetWidth'), height: boundingClientRect.height || element.prop('offsetHeight'), top: elBCR.top - offsetParentBCR.top, left: elBCR.left - offsetParentBCR.left }; }, /** * Provides read-only equivalent of jQuery's offset function: * http://api.jquery.com/offset/ */ offset: function offset(element) { var boundingClientRect = element[0].getBoundingClientRect(); return { width: boundingClientRect.width || element.prop('offsetWidth'), height: boundingClientRect.height || element.prop('offsetHeight'), top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop), left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft) }; } }; }]); angular.module('mm.foundation.progressbar', []).constant('progressConfig', { animate: true, max: 100 }).controller('ProgressController', ['$scope', '$attrs', 'progressConfig', '$animate', function ($scope, $attrs, progressConfig, $animate) { 'ngInject'; var self = this, bars = [], max = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : progressConfig.max, animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate; this.addBar = function (bar, element) { var oldValue = 0, index = bar.$parent.$index; if (angular.isDefined(index) && bars[index]) { oldValue = bars[index].value; } bars.push(bar); this.update(element, bar.value, oldValue); bar.$watch('value', function (value, oldValue) { if (value !== oldValue) { self.update(element, value, oldValue); } }); bar.$on('$destroy', function () { self.removeBar(bar); }); }; // Update bar element width this.update = function (element, newValue, oldValue) { var percent = this.getPercentage(newValue); if (animate) { element.css('width', this.getPercentage(oldValue) + '%'); $animate.animate(element, { 'width': this.getPercentage(oldValue) + '%' }, { width: percent + '%' }); // $transition(element, { // width: percent + '%' // }); } else { element.css({ 'transition': 'none', 'width': percent + '%' }); } }; this.removeBar = function (bar) { bars.splice(bars.indexOf(bar), 1); }; this.getPercentage = function (value) { return Math.round(100 * value / max); }; }]).directive('progress', function () { 'ngInject'; return { restrict: 'EA', replace: true, transclude: true, controller: 'ProgressController', require: 'progress', scope: {}, template: '<div class="progress" ng-transclude></div>' //templateUrl: 'template/progressbar/progress.html' // Works in AngularJS 1.2 }; }).directive('bar', function () { 'ngInject'; return { restrict: 'EA', replace: true, transclude: true, require: '^progress', scope: { value: '=', type: '@' }, templateUrl: 'template/progressbar/bar.html', link: function link(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, element); } }; }).directive('progressbar', function () { return { restrict: 'EA', replace: true, transclude: true, controller: 'ProgressController', scope: { value: '=', type: '@' }, templateUrl: 'template/progressbar/progressbar.html', link: function link(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, angular.element(element.children()[0])); } }; }); angular.module('mm.foundation.rating', []).constant('ratingConfig', { max: 5, stateOn: null, stateOff: null }).controller('RatingController', ['$scope', '$attrs', '$parse', 'ratingConfig', function ($scope, $attrs, $parse, ratingConfig) { this.maxRange = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max; this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn; this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff; this.createRateObjects = function (states) { var defaultOptions = { stateOn: this.stateOn, stateOff: this.stateOff }; for (var i = 0, n = states.length; i < n; i++) { states[i] = angular.extend({ index: i }, defaultOptions, states[i]); } return states; }; // Get objects used in template $scope.range = angular.isDefined($attrs.ratingStates) ? this.createRateObjects(angular.copy($scope.$parent.$eval($attrs.ratingStates))) : this.createRateObjects(new Array(this.maxRange)); $scope.rate = function (value) { if ($scope.value !== value && !$scope.readonly) { $scope.value = value; } }; $scope.enter = function (value) { if (!$scope.readonly) { $scope.val = value; } $scope.onHover({ value: value }); }; $scope.reset = function () { $scope.val = angular.copy($scope.value); $scope.onLeave(); }; $scope.$watch('value', function (value) { $scope.val = value; }); $scope.readonly = false; if ($attrs.readonly) { $scope.$parent.$watch($parse($attrs.readonly), function (value) { $scope.readonly = !!value; }); } }]).directive('rating', function () { return { restrict: 'EA', scope: { value: '=', onHover: '&', onLeave: '&' }, controller: 'RatingController', templateUrl: 'template/rating/rating.html', replace: true }; }); /** * @ngdoc overview * @name mm.foundation.tabs * * @description * AngularJS version of the tabs directive. */ angular.module('mm.foundation.tabs', []).controller('TabsetController', ['$scope', function TabsetCtrl($scope) { 'ngInject'; var ctrl = this; var tabs = ctrl.tabs = $scope.tabs = []; if (angular.isUndefined($scope.openOnLoad)) { $scope.openOnLoad = true; } ctrl.select = function (tab) { angular.forEach(tabs, function (tab) { tab.active = false; }); tab.active = true; }; ctrl.addTab = function addTab(tab) { tabs.push(tab); if ($scope.openOnLoad && (tabs.length === 1 || tab.active)) { ctrl.select(tab); } }; ctrl.removeTab = function removeTab(tab) { var index = tabs.indexOf(tab); //Select a new tab if the tab to be removed is selected if (tab.active && tabs.length > 1) { //If this is the last tab, select the previous tab. else, the next tab. var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1; ctrl.select(tabs[newActiveIndex]); } tabs.splice(index, 1); }; }]) /** * @ngdoc directive * @name mm.foundation.tabs.directive:tabset * @restrict EA * * @description * Tabset is the outer container for the tabs directive * * @param {boolean=} vertical Whether or not to use vertical styling for the tabs. * @param {boolean=} justified Whether or not to use justified styling for the tabs. * * @example <example module="mm.foundation"> <file name="index.html"> <tabset> <tab heading="Tab 1"><b>First</b> Content!</tab> <tab heading="Tab 2"><i>Second</i> Content!</tab> </tabset> <hr /> <tabset vertical="true"> <tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab> <tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab> </tabset> <tabset justified="true"> <tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab> <tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab> </tabset> </file> </example> */ .directive('tabset', function () { 'ngInject'; return { restrict: 'EA', transclude: true, replace: true, scope: { openOnLoad: '=?' }, controller: 'TabsetController', templateUrl: 'template/tabs/tabset.html', link: function link(scope, element, attrs) { scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; scope.type = angular.isDefined(attrs.type) ? scope.$parent.$eval(attrs.type) : 'tabs'; } }; }) /** * @ngdoc directive * @name mm.foundation.tabs.directive:tab * @restrict EA * * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link mm.foundation.tabs.directive:tabHeading tabHeading}. * @param {string=} select An expression to evaluate when the tab is selected. * @param {boolean=} active A binding, telling whether or not this tab is selected. * @param {boolean=} disabled A binding, telling whether or not this tab is disabled. * * @description * Creates a tab with a heading and content. Must be placed within a {@link mm.foundation.tabs.directive:tabset tabset}. * * @example <example module="mm.foundation"> <file name="index.html"> <div ng-controller="TabsDemoCtrl"> <button class="button small" ng-click="items[0].active = true"> Select item 1, using active binding </button> <button class="button small" ng-click="items[1].disabled = !items[1].disabled"> Enable/disable item 2, using disabled binding </button> <br /> <tabset> <tab heading="Tab 1">First Tab</tab> <tab select="alertMe()"> <tab-heading><i class="fa fa-bell"></i> Alert me!</tab-heading> Second Tab, with alert callback and html heading! </tab> <tab ng-repeat="item in items" heading="{{item.title}}" disabled="item.disabled" active="item.active"> {{item.content}} </tab> </tabset> </div> </file> <file name="script.js"> function TabsDemoCtrl($scope) { $scope.items = [ { title:"Dynamic Title 1", content:"Dynamic Item 0" }, { title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true } ]; $scope.alertMe = function() { setTimeout(function() { alert("You've selected the alert tab!"); }); }; }; </file> </example> */ /** * @ngdoc directive * @name mm.foundation.tabs.directive:tabHeading * @restrict EA * * @description * Creates an HTML heading for a {@link mm.foundation.tabs.directive:tab tab}. Must be placed as a child of a tab element. * * @example <example module="mm.foundation"> <file name="index.html"> <tabset> <tab> <tab-heading><b>HTML</b> in my titles?!</tab-heading> And some content, too! </tab> <tab> <tab-heading><i class="fa fa-heart"></i> Icon heading?!?</tab-heading> That's right. </tab> </tabset> </file> </example> */ .directive('tab', ['$parse', function ($parse) { 'ngInject'; return { require: '^tabset', restrict: 'EA', replace: true, templateUrl: 'template/tabs/tab.html', transclude: true, scope: { heading: '@', onSelect: '&select', //This callback is called in contentHeadingTransclude //once it inserts the tab's content into the dom onDeselect: '&deselect' }, controller: function controller() { //Empty controller so other directives can require being 'under' a tab }, compile: function compile(elm, attrs, transclude) { return function postLink(scope, elm, attrs, tabsetCtrl) { var getActive, setActive; if (attrs.active) { getActive = $parse(attrs.active); setActive = getActive.assign; scope.$parent.$watch(getActive, function updateActive(value, oldVal) { // Avoid re-initializing scope.active as it is already initialized // below. (watcher is called async during init with value === // oldVal) if (value !== oldVal) { scope.active = !!value; } }); scope.active = getActive(scope.$parent); } else { setActive = getActive = angular.noop; } scope.$watch('active', function (active) { if (!angular.isFunction(setActive)) { return; } // Note this watcher also initializes and assigns scope.active to the // attrs.active expression. setActive(scope.$parent, active); if (active) { tabsetCtrl.select(scope); scope.onSelect(); } else { scope.onDeselect(); } }); scope.disabled = false; if (attrs.disabled) { scope.$parent.$watch($parse(attrs.disabled), function (value) { scope.disabled = !!value; }); } scope.select = function () { if (!scope.disabled) { scope.active = true; } }; tabsetCtrl.addTab(scope); scope.$on('$destroy', function () { tabsetCtrl.removeTab(scope); }); //We need to transclude later, once the content container is ready. //when this link happens, we're inside a tab heading. scope.$transcludeFn = transclude; }; } }; }]).directive('tabHeadingTransclude', function () { 'ngInject'; return { restrict: 'A', require: '^tab', link: function link(scope, elm, attrs, tabCtrl) { scope.$watch('headingElement', function updateHeadingElement(heading) { if (heading) { elm.html(''); elm.append(heading); } }); } }; }).directive('tabContentTransclude', function () { 'ngInject'; return { restrict: 'A', require: '^tabset', link: function link(scope, elm, attrs) { var tab = scope.$eval(attrs.tabContentTransclude); //Now our tab is ready to be transcluded: both the tab heading area //and the tab content area are loaded. Transclude 'em both. tab.$transcludeFn(tab.$parent, function (contents) { angular.forEach(contents, function (node) { if (isTabHeading(node)) { //Let tabHeadingTransclude know. tab.headingElement = node; } else { elm.append(node); } }); }); } }; function isTabHeading(node) { return node.tagName && (node.hasAttribute('tab-heading') || node.hasAttribute('data-tab-heading') || node.tagName.toLowerCase() === 'tab-heading' || node.tagName.toLowerCase() === 'data-tab-heading'); } }); /** * The following features are still outstanding: animation as a * function, placement as a function, inside, support for more triggers than * just mouse enter/leave, html tooltips, and selector delegation. */ angular.module('mm.foundation.tooltip', ['mm.foundation.position', 'mm.foundation.bindHtml']) /** * The $tooltip service creates tooltip- and popover-like directives as well as * houses global options for them. */ .provider('$tooltip', function () { 'ngInject'; // The default options tooltip and popover. var defaultOptions = { placement: 'top', popupDelay: 0 }; // Default hide triggers for each show trigger var triggerMap = { 'mouseover': 'mouseout', 'click': 'click', 'focus': 'blur' }; // The options specified to the provider globally. var globalOptions = {}; /** * `options({})` allows global configuration of all tooltips in the * application. * * var app = angular.module( 'App', ['mm.foundation.tooltip'], function( $tooltipProvider ) { * // place tooltips left instead of top by default * $tooltipProvider.options( { placement: 'left' } ); * }); */ this.options = function (value) { angular.extend(globalOptions, value); }; /** * This allows you to extend the set of trigger mappings available. E.g.: * * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' ); */ this.setTriggers = function setTriggers(triggers) { angular.extend(triggerMap, triggers); }; /** * This is a helper function for translating camel-case to snake-case. */ function snake_case(name) { var regexp = /[A-Z]/g; var separator = '-'; return name.replace(regexp, function (letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } /** * Returns the actual instance of the $tooltip service. * TODO support multiple triggers */ this.$get = ['$window', '$compile', '$timeout', '$parse', '$document', '$position', '$interpolate', '$animate', function ($window, $compile, $timeout, $parse, $document, $position, $interpolate, $animate) { 'ngInject'; return function $tooltip(type, prefix, defaultTriggerShow) { var options = angular.extend({}, defaultOptions, globalOptions); /** * Returns an object of show and hide triggers. * * If a trigger is supplied, * it is used to show the tooltip; otherwise, it will use the `trigger` * option passed to the `$tooltipProvider.options` method; else it will * default to the trigger supplied to this directive factory. * * The hide trigger is based on the show trigger. If the `trigger` option * was passed to the `$tooltipProvider.options` method, it will use the * mapped trigger from `triggerMap` or the passed trigger if the map is * undefined; otherwise, it uses the `triggerMap` value of the show * trigger; else it will just use the show trigger. */ function getTriggers(trigger) { var show = trigger || options.trigger || defaultTriggerShow; var hide = triggerMap[show] || show; return { show: show, hide: hide }; } var directiveName = snake_case(type); var startSym = $interpolate.startSymbol(); var endSym = $interpolate.endSymbol(); var template = '<div ' + directiveName + '-popup ' + 'title="' + startSym + 'tt_title' + endSym + '" ' + 'content="' + startSym + 'tt_content' + endSym + '" ' + 'placement="' + startSym + 'tt_placement' + endSym + '" ' + 'is-open="tt_isOpen"' + '>' + '</div>'; return { restrict: 'EA', scope: true, compile: function compile(tElem) { var tooltipLinker = $compile(template); return function link(scope, element, attrs) { var tooltip; var transitionTimeout; var popupTimeout; var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false; var triggers = getTriggers(undefined); var hasRegisteredTriggers = false; var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']); var positionTooltip = function positionTooltip() { var position; var ttWidth; var ttHeight; var ttPosition; // Get the position of the directive element. position = appendToBody ? $position.offset(element) : $position.position(element); // Get the height and width of the tooltip so we can center it. ttWidth = tooltip.prop('offsetWidth'); ttHeight = tooltip.prop('offsetHeight'); // Calculate the tooltip's top and left coordinates to center it with // this directive. switch (scope.tt_placement) { case 'right': ttPosition = { top: position.top + position.height / 2 - ttHeight / 2, left: position.left + position.width + 10 }; break; case 'bottom': ttPosition = { top: position.top + position.height + 10, left: position.left }; break; case 'left': ttPosition = { top: position.top + position.height / 2 - ttHeight / 2, left: position.left - ttWidth - 10 }; break; default: ttPosition = { top: position.top - ttHeight - 10, left: position.left }; break; } ttPosition.top += 'px'; ttPosition.left += 'px'; // Now set the calculated positioning. tooltip.css(ttPosition); }; // By default, the tooltip is not open. // TODO add ability to start tooltip opened scope.tt_isOpen = false; function toggleTooltipBind() { if (!scope.tt_isOpen) { showTooltipBind(); } else { hideTooltipBind(); } } // Show the tooltip with delay if specified, otherwise show it immediately function showTooltipBind() { if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) { return; } if (scope.tt_popupDelay) { popupTimeout = $timeout(show, scope.tt_popupDelay, false); popupTimeout.then(function (reposition) { reposition(); }); } else { show()(); } } function hideTooltipBind() { scope.$apply(function () { hide(); }); } // Show the tooltip popup element. function show() { // Don't show empty tooltips. if (!scope.tt_content) { return angular.noop; } createTooltip(); // If there is a pending remove transition, we must cancel it, lest the // tooltip be mysteriously removed. if (transitionTimeout) { $timeout.cancel(transitionTimeout); } // Set the initial positioning. tooltip.css({ top: 0, left: 0 }); // Now we add it to the DOM because need some info about it. But it's not // visible yet anyway. if (appendToBody) { // $document.find('body').append(tooltip); // $document.find('body') $animate.enter(tooltip, $document.find('body')); } else { $animate.enter(tooltip, element.parent(), element); // element.after(tooltip); } positionTooltip(); // And show the tooltip. scope.tt_isOpen = true; scope.$digest(); // digest required as $apply is not called // Return positioning function as promise callback for correct // positioning after draw. return positionTooltip; } // Hide the tooltip popup element. function hide() { // First things first: we don't show it anymore. scope.tt_isOpen = false; //if tooltip is going to be shown after delay, we must cancel this $timeout.cancel(popupTimeout); removeTooltip(); } function createTooltip() { // There can only be one tooltip element per directive shown at once. if (tooltip) { removeTooltip(); } tooltip = tooltipLinker(scope, function () {}); // Get contents rendered into the tooltip scope.$digest(); } function removeTooltip() { if (tooltip) { $animate.leave(tooltip); // tooltip.remove(); tooltip = null; } } /** * Observe the relevant attributes. */ attrs.$observe(type, function (val) { scope.tt_content = val; if (!val && scope.tt_isOpen) { hide(); } }); attrs.$observe(prefix + 'Title', function (val) { scope.tt_title = val; }); attrs[prefix + 'Placement'] = attrs[prefix + 'Placement'] || null; attrs.$observe(prefix + 'Placement', function (val) { scope.tt_placement = angular.isDefined(val) && val ? val : options.placement; }); attrs[prefix + 'PopupDelay'] = attrs[prefix + 'PopupDelay'] || null; attrs.$observe(prefix + 'PopupDelay', function (val) { var delay = parseInt(val, 10); scope.tt_popupDelay = !isNaN(delay) ? delay : options.popupDelay; }); var unregisterTriggers = function unregisterTriggers() { if (hasRegisteredTriggers) { if (angular.isFunction(triggers.show)) { unregisterTriggerFunction(); } else { element.unbind(triggers.show, showTooltipBind); element.unbind(triggers.hide, hideTooltipBind); } } }; var unregisterTriggerFunction = function unregisterTriggerFunction() {}; attrs[prefix + 'Trigger'] = attrs[prefix + 'Trigger'] || null; attrs.$observe(prefix + 'Trigger', function (val) { unregisterTriggers(); unregisterTriggerFunction(); triggers = getTriggers(val); if (angular.isFunction(triggers.show)) { unregisterTriggerFunction = scope.$watch(function () { return triggers.show(scope, element, attrs); }, function (val) { return val ? $timeout(show) : $timeout(hide); }); } else { if (triggers.show === triggers.hide) { element.bind(triggers.show, toggleTooltipBind); } else { element.bind(triggers.show, showTooltipBind); element.bind(triggers.hide, hideTooltipBind); } } hasRegisteredTriggers = true; }); attrs.$observe(prefix + 'AppendToBody', function (val) { appendToBody = angular.isDefined(val) ? $parse(val)(scope) : appendToBody; }); // if a tooltip is attached to <body> we need to remove it on // location change as its parent scope will probably not be destroyed // by the change. if (appendToBody) { scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess() { if (scope.tt_isOpen) { hide(); } }); } // Make sure tooltip is destroyed and removed. scope.$on('$destroy', function onDestroyTooltip() { $timeout.cancel(transitionTimeout); $timeout.cancel(popupTimeout); unregisterTriggers(); unregisterTriggerFunction(); removeTooltip(); }); }; } }; }; }]; }).directive('tooltipPopup', function () { 'ngInject'; return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-popup.html' }; }).directive('tooltip', ['$tooltip', function ($tooltip) { 'ngInject'; return $tooltip('tooltip', 'tooltip', 'mouseover'); }]).directive('tooltipHtmlUnsafePopup', function () { return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html' }; }).directive('tooltipHtmlUnsafe', ['$tooltip', function ($tooltip) { 'ngInject'; return $tooltip('tooltipHtmlUnsafe', 'tooltip', 'mouseover'); }]); angular.module("mm.foundation", ["mm.foundation.accordion", "mm.foundation.alert", "mm.foundation.bindHtml", "mm.foundation.buttons", "mm.foundation.dropdownMenu", "mm.foundation.dropdownToggle", "mm.foundation.mediaQueries", "mm.foundation.modal", "mm.foundation.offcanvas", "mm.foundation.pagination", "mm.foundation.position", "mm.foundation.progressbar", "mm.foundation.rating", "mm.foundation.tabs", "mm.foundation.tooltip"]);
export { default } from './Tabs'; export { default as tabsClasses } from './tabsClasses'; export * from './tabsClasses';
/*! /support/test/css/transition 1.1.0 | http://nucleus.qoopido.com | (c) 2016 Dirk Lueth */ !function(){"use strict";function e(e,r){var t=e.defer(),n=r("transition");return n?t.resolve(n):t.reject(),t.pledge}provide(["/demand/pledge","../../css/property"],e)}(); //# sourceMappingURL=transition.js.map
// Generated by CoffeeScript 1.4.0 /* # # Opentip v2.4.1 # # More info at [www.opentip.org](http://www.opentip.org) # # Copyright (c) 2012, Matias Meno # Graphics by Tjandra Mayerhold # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # */ var Opentip, firstAdapter, i, mouseMoved, mousePosition, mousePositionObservers, position, vendors, _i, _len, _ref, __slice = [].slice, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, __hasProp = {}.hasOwnProperty; Opentip = (function() { Opentip.prototype.STICKS_OUT_TOP = 1; Opentip.prototype.STICKS_OUT_BOTTOM = 2; Opentip.prototype.STICKS_OUT_LEFT = 1; Opentip.prototype.STICKS_OUT_RIGHT = 2; Opentip.prototype["class"] = { container: "opentip-container", opentip: "opentip", header: "ot-header", content: "ot-content", loadingIndicator: "ot-loading-indicator", close: "ot-close", goingToHide: "ot-going-to-hide", hidden: "ot-hidden", hiding: "ot-hiding", goingToShow: "ot-going-to-show", showing: "ot-showing", visible: "ot-visible", loading: "ot-loading", ajaxError: "ot-ajax-error", fixed: "ot-fixed", showEffectPrefix: "ot-show-effect-", hideEffectPrefix: "ot-hide-effect-", stylePrefix: "style-" }; function Opentip(element, content, title, options) { var elementsOpentips, hideTrigger, methodToBind, optionSources, prop, styleName, _i, _j, _len, _len1, _ref, _ref1, _ref2, _tmpStyle, _this = this; this.id = ++Opentip.lastId; this.debug("Creating Opentip."); Opentip.tips.push(this); this.adapter = Opentip.adapter; elementsOpentips = this.adapter.data(element, "opentips") || []; elementsOpentips.push(this); this.adapter.data(element, "opentips", elementsOpentips); this.triggerElement = this.adapter.wrap(element); if (this.triggerElement.length > 1) { throw new Error("You can't call Opentip on multiple elements."); } if (this.triggerElement.length < 1) { throw new Error("Invalid element."); } this.loaded = false; this.loading = false; this.visible = false; this.waitingToShow = false; this.waitingToHide = false; this.currentPosition = { left: 0, top: 0 }; this.dimensions = { width: 100, height: 50 }; this.content = ""; this.redraw = true; this.currentObservers = { showing: false, visible: false, hiding: false, hidden: false }; options = this.adapter.clone(options); if (typeof content === "object") { options = content; content = title = void 0; } else if (typeof title === "object") { options = title; title = void 0; } if (title != null) { options.title = title; } if (content != null) { this.setContent(content); } if (options["extends"] == null) { if (options.style != null) { options["extends"] = options.style; } else { options["extends"] = Opentip.defaultStyle; } } optionSources = [options]; _tmpStyle = options; while (_tmpStyle["extends"]) { styleName = _tmpStyle["extends"]; _tmpStyle = Opentip.styles[styleName]; if (_tmpStyle == null) { throw new Error("Invalid style: " + styleName); } optionSources.unshift(_tmpStyle); if (!((_tmpStyle["extends"] != null) || styleName === "standard")) { _tmpStyle["extends"] = "standard"; } } options = (_ref = this.adapter).extend.apply(_ref, [{}].concat(__slice.call(optionSources))); options.hideTriggers = (function() { var _i, _len, _ref1, _results; _ref1 = options.hideTriggers; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { hideTrigger = _ref1[_i]; _results.push(hideTrigger); } return _results; })(); if (options.hideTrigger && options.hideTriggers.length === 0) { options.hideTriggers.push(options.hideTrigger); } _ref1 = ["tipJoint", "targetJoint", "stem"]; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { prop = _ref1[_i]; if (options[prop] && typeof options[prop] === "string") { options[prop] = new Opentip.Joint(options[prop]); } } if (options.ajax && (options.ajax === true || !options.ajax)) { if (this.adapter.tagName(this.triggerElement) === "A") { options.ajax = this.adapter.attr(this.triggerElement, "href"); } else { options.ajax = false; } } if (options.showOn === "click" && this.adapter.tagName(this.triggerElement) === "A") { this.adapter.observe(this.triggerElement, "click", function(e) { e.preventDefault(); e.stopPropagation(); return e.stopped = true; }); } if (options.target) { options.fixed = true; } if (options.stem === true) { options.stem = new Opentip.Joint(options.tipJoint); } if (options.target === true) { options.target = this.triggerElement; } else if (options.target) { options.target = this.adapter.wrap(options.target); } this.currentStem = options.stem; if (options.delay == null) { options.delay = options.showOn === "mouseover" ? 0.2 : 0; } if (options.targetJoint == null) { options.targetJoint = new Opentip.Joint(options.tipJoint).flip(); } this.showTriggers = []; this.showTriggersWhenVisible = []; this.hideTriggers = []; if (options.showOn && options.showOn !== "creation") { this.showTriggers.push({ element: this.triggerElement, event: options.showOn }); } if (options.ajaxCache != null) { options.cache = options.ajaxCache; delete options.ajaxCache; } this.options = options; this.bound = {}; _ref2 = ["prepareToShow", "prepareToHide", "show", "hide", "reposition"]; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { methodToBind = _ref2[_j]; this.bound[methodToBind] = (function(methodToBind) { return function() { return _this[methodToBind].apply(_this, arguments); }; })(methodToBind); } this.adapter.domReady(function() { _this.activate(); if (_this.options.showOn === "creation") { return _this.prepareToShow(); } }); } Opentip.prototype._setup = function() { var hideOn, hideTrigger, hideTriggerElement, i, _i, _j, _len, _len1, _ref, _ref1, _results; this.debug("Setting up the tooltip."); this._buildContainer(); this.hideTriggers = []; _ref = this.options.hideTriggers; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { hideTrigger = _ref[i]; hideTriggerElement = null; hideOn = this.options.hideOn instanceof Array ? this.options.hideOn[i] : this.options.hideOn; if (typeof hideTrigger === "string") { switch (hideTrigger) { case "trigger": hideOn = hideOn || "mouseout"; hideTriggerElement = this.triggerElement; break; case "tip": hideOn = hideOn || "mouseover"; hideTriggerElement = this.container; break; case "target": hideOn = hideOn || "mouseover"; hideTriggerElement = this.options.target; break; case "closeButton": break; default: throw new Error("Unknown hide trigger: " + hideTrigger + "."); } } else { hideOn = hideOn || "mouseover"; hideTriggerElement = this.adapter.wrap(hideTrigger); } if (hideTriggerElement) { this.hideTriggers.push({ element: hideTriggerElement, event: hideOn, original: hideTrigger }); } } _ref1 = this.hideTriggers; _results = []; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { hideTrigger = _ref1[_j]; _results.push(this.showTriggersWhenVisible.push({ element: hideTrigger.element, event: "mouseover" })); } return _results; }; Opentip.prototype._buildContainer = function() { this.container = this.adapter.create("<div id=\"opentip-" + this.id + "\" class=\"" + this["class"].container + " " + this["class"].hidden + " " + this["class"].stylePrefix + this.options.className + "\"></div>"); this.adapter.css(this.container, { position: "absolute" }); if (this.options.ajax) { this.adapter.addClass(this.container, this["class"].loading); } if (this.options.fixed) { this.adapter.addClass(this.container, this["class"].fixed); } if (this.options.showEffect) { this.adapter.addClass(this.container, "" + this["class"].showEffectPrefix + this.options.showEffect); } if (this.options.hideEffect) { return this.adapter.addClass(this.container, "" + this["class"].hideEffectPrefix + this.options.hideEffect); } }; Opentip.prototype._buildElements = function() { var headerElement, titleElement; this.tooltipElement = this.adapter.create("<div class=\"" + this["class"].opentip + "\"><div class=\"" + this["class"].header + "\"></div><div class=\"" + this["class"].content + "\"></div></div>"); this.backgroundCanvas = this.adapter.wrap(document.createElement("canvas")); this.adapter.css(this.backgroundCanvas, { position: "absolute" }); if (typeof G_vmlCanvasManager !== "undefined" && G_vmlCanvasManager !== null) { G_vmlCanvasManager.initElement(this.adapter.unwrap(this.backgroundCanvas)); } headerElement = this.adapter.find(this.tooltipElement, "." + this["class"].header); if (this.options.title) { titleElement = this.adapter.create("<h1></h1>"); this.adapter.update(titleElement, this.options.title, this.options.escapeTitle); this.adapter.append(headerElement, titleElement); } if (this.options.ajax && !this.loaded) { this.adapter.append(this.tooltipElement, this.adapter.create("<div class=\"" + this["class"].loadingIndicator + "\"><span>↻</span></div>")); } if (__indexOf.call(this.options.hideTriggers, "closeButton") >= 0) { this.closeButtonElement = this.adapter.create("<a href=\"javascript:undefined;\" class=\"" + this["class"].close + "\"><span>Close</span></a>"); this.adapter.append(headerElement, this.closeButtonElement); } this.adapter.append(this.container, this.backgroundCanvas); this.adapter.append(this.container, this.tooltipElement); this.adapter.append(document.body, this.container); this._newContent = true; return this.redraw = true; }; Opentip.prototype.setContent = function(content) { this.content = content; this._newContent = true; if (typeof this.content === "function") { this._contentFunction = this.content; this.content = ""; } else { this._contentFunction = null; } if (this.visible) { return this._updateElementContent(); } }; Opentip.prototype._updateElementContent = function() { var contentDiv; if (this._newContent || (!this.options.cache && this._contentFunction)) { contentDiv = this.adapter.find(this.container, "." + this["class"].content); if (contentDiv != null) { if (this._contentFunction) { this.debug("Executing content function."); this.content = this._contentFunction(this); } this.adapter.update(contentDiv, this.content, this.options.escapeContent); } this._newContent = false; } this._storeAndLockDimensions(); return this.reposition(); }; Opentip.prototype._storeAndLockDimensions = function() { var prevDimension; if (!this.container) { return; } prevDimension = this.dimensions; this.adapter.css(this.container, { width: "auto", left: "0px", top: "0px" }); this.dimensions = this.adapter.dimensions(this.container); this.dimensions.width += 1; this.adapter.css(this.container, { width: "" + this.dimensions.width + "px", top: "" + this.currentPosition.top + "px", left: "" + this.currentPosition.left + "px" }); if (!this._dimensionsEqual(this.dimensions, prevDimension)) { this.redraw = true; return this._draw(); } }; Opentip.prototype.activate = function() { return this._setupObservers("hidden", "hiding"); }; Opentip.prototype.deactivate = function() { this.debug("Deactivating tooltip."); this.hide(); return this._setupObservers("-showing", "-visible", "-hidden", "-hiding"); }; Opentip.prototype._setupObservers = function() { var observeOrStop, removeObserver, state, states, trigger, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _this = this; states = 1 <= arguments.length ? __slice.call(arguments, 0) : []; for (_i = 0, _len = states.length; _i < _len; _i++) { state = states[_i]; removeObserver = false; if (state.charAt(0) === "-") { removeObserver = true; state = state.substr(1); } if (this.currentObservers[state] === !removeObserver) { continue; } this.currentObservers[state] = !removeObserver; observeOrStop = function() { var args, _ref, _ref1; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; if (removeObserver) { return (_ref = _this.adapter).stopObserving.apply(_ref, args); } else { return (_ref1 = _this.adapter).observe.apply(_ref1, args); } }; switch (state) { case "showing": _ref = this.hideTriggers; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { trigger = _ref[_j]; observeOrStop(trigger.element, trigger.event, this.bound.prepareToHide); } observeOrStop((document.onresize != null ? document : window), "resize", this.bound.reposition); observeOrStop(window, "scroll", this.bound.reposition); break; case "visible": _ref1 = this.showTriggersWhenVisible; for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { trigger = _ref1[_k]; observeOrStop(trigger.element, trigger.event, this.bound.prepareToShow); } break; case "hiding": _ref2 = this.showTriggers; for (_l = 0, _len3 = _ref2.length; _l < _len3; _l++) { trigger = _ref2[_l]; observeOrStop(trigger.element, trigger.event, this.bound.prepareToShow); } break; case "hidden": break; default: throw new Error("Unknown state: " + state); } } return null; }; Opentip.prototype.prepareToShow = function() { this._abortHiding(); this._abortShowing(); if (this.visible) { return; } this.debug("Showing in " + this.options.delay + "s."); if (this.container == null) { this._setup(); } if (this.options.group) { Opentip._abortShowingGroup(this.options.group, this); } this.preparingToShow = true; this._setupObservers("-hidden", "-hiding", "showing"); this._followMousePosition(); this.reposition(); return this._showTimeoutId = this.setTimeout(this.bound.show, this.options.delay || 0); }; Opentip.prototype.show = function() { var _this = this; this._abortHiding(); if (this.visible) { return; } this._clearTimeouts(); if (!this._triggerElementExists()) { return this.deactivate(); } this.debug("Showing now."); if (this.container == null) { this._setup(); } if (this.options.group) { Opentip._hideGroup(this.options.group, this); } this.visible = true; this.preparingToShow = false; if (this.tooltipElement == null) { this._buildElements(); } this._updateElementContent(); if (this.options.ajax && (!this.loaded || !this.options.cache)) { this._loadAjax(); } this._searchAndActivateCloseButtons(); this._startEnsureTriggerElement(); this.adapter.css(this.container, { zIndex: Opentip.lastZIndex++ }); this._setupObservers("-hidden", "-hiding", "-showing", "-visible", "showing", "visible"); this.reposition(); this.adapter.removeClass(this.container, this["class"].hiding); this.adapter.removeClass(this.container, this["class"].hidden); this.adapter.addClass(this.container, this["class"].goingToShow); this.setCss3Style(this.container, { transitionDuration: "0s" }); this.defer(function() { var delay; if (!_this.visible || _this.preparingToHide) { return; } _this.adapter.removeClass(_this.container, _this["class"].goingToShow); _this.adapter.addClass(_this.container, _this["class"].showing); delay = 0; if (_this.options.showEffect && _this.options.showEffectDuration) { delay = _this.options.showEffectDuration; } _this.setCss3Style(_this.container, { transitionDuration: "" + delay + "s" }); _this._visibilityStateTimeoutId = _this.setTimeout(function() { _this.adapter.removeClass(_this.container, _this["class"].showing); return _this.adapter.addClass(_this.container, _this["class"].visible); }, delay); return _this._activateFirstInput(); }); return this._draw(); }; Opentip.prototype._abortShowing = function() { if (this.preparingToShow) { this.debug("Aborting showing."); this._clearTimeouts(); this._stopFollowingMousePosition(); this.preparingToShow = false; return this._setupObservers("-showing", "-visible", "hiding", "hidden"); } }; Opentip.prototype.prepareToHide = function() { this._abortShowing(); this._abortHiding(); if (!this.visible) { return; } this.debug("Hiding in " + this.options.hideDelay + "s"); this.preparingToHide = true; this._setupObservers("-showing", "visible", "-hidden", "hiding"); return this._hideTimeoutId = this.setTimeout(this.bound.hide, this.options.hideDelay); }; Opentip.prototype.hide = function() { var _this = this; this._abortShowing(); if (!this.visible) { return; } this._clearTimeouts(); this.debug("Hiding!"); this.visible = false; this.preparingToHide = false; this._stopEnsureTriggerElement(); this._setupObservers("-showing", "-visible", "-hiding", "-hidden", "hiding", "hidden"); if (!this.options.fixed) { this._stopFollowingMousePosition(); } if (!this.container) { return; } this.adapter.removeClass(this.container, this["class"].visible); this.adapter.removeClass(this.container, this["class"].showing); this.adapter.addClass(this.container, this["class"].goingToHide); this.setCss3Style(this.container, { transitionDuration: "0s" }); return this.defer(function() { var hideDelay; _this.adapter.removeClass(_this.container, _this["class"].goingToHide); _this.adapter.addClass(_this.container, _this["class"].hiding); hideDelay = 0; if (_this.options.hideEffect && _this.options.hideEffectDuration) { hideDelay = _this.options.hideEffectDuration; } _this.setCss3Style(_this.container, { transitionDuration: "" + hideDelay + "s" }); return _this._visibilityStateTimeoutId = _this.setTimeout(function() { _this.adapter.removeClass(_this.container, _this["class"].hiding); _this.adapter.addClass(_this.container, _this["class"].hidden); _this.setCss3Style(_this.container, { transitionDuration: "0s" }); if (_this.options.removeElementsOnHide) { _this.debug("Removing HTML elements."); _this.adapter.remove(_this.container); delete _this.container; return delete _this.tooltipElement; } }, hideDelay); }); }; Opentip.prototype._abortHiding = function() { if (this.preparingToHide) { this.debug("Aborting hiding."); this._clearTimeouts(); this.preparingToHide = false; return this._setupObservers("-hiding", "showing", "visible"); } }; Opentip.prototype.reposition = function() { var position, stem, _ref, _this = this; position = this.getPosition(); if (position == null) { return; } stem = this.options.stem; if (this.options.containInViewport) { _ref = this._ensureViewportContainment(position), position = _ref.position, stem = _ref.stem; } if (this._positionsEqual(position, this.currentPosition)) { return; } if (!(!this.options.stem || stem.eql(this.currentStem))) { this.redraw = true; } this.currentPosition = position; this.currentStem = stem; this._draw(); this.adapter.css(this.container, { left: "" + position.left + "px", top: "" + position.top + "px" }); return this.defer(function() { var rawContainer, redrawFix; rawContainer = _this.adapter.unwrap(_this.container); rawContainer.style.visibility = "hidden"; redrawFix = rawContainer.offsetHeight; return rawContainer.style.visibility = "visible"; }); }; Opentip.prototype.getPosition = function(tipJoint, targetJoint, stem) { var additionalHorizontal, additionalVertical, offsetDistance, position, stemLength, targetDimensions, targetPosition, unwrappedTarget, _ref; if (!this.container) { return; } if (tipJoint == null) { tipJoint = this.options.tipJoint; } if (targetJoint == null) { targetJoint = this.options.targetJoint; } position = {}; if (this.options.target) { targetPosition = this.adapter.offset(this.options.target); targetDimensions = this.adapter.dimensions(this.options.target); position = targetPosition; if (targetJoint.right) { unwrappedTarget = this.adapter.unwrap(this.options.target); if (unwrappedTarget.getBoundingClientRect != null) { position.left = unwrappedTarget.getBoundingClientRect().right + ((_ref = window.pageXOffset) != null ? _ref : document.body.scrollLeft); } else { position.left += targetDimensions.width; } } else if (targetJoint.center) { position.left += Math.round(targetDimensions.width / 2); } if (targetJoint.bottom) { position.top += targetDimensions.height; } else if (targetJoint.middle) { position.top += Math.round(targetDimensions.height / 2); } if (this.options.borderWidth) { if (this.options.tipJoint.left) { position.left += this.options.borderWidth; } if (this.options.tipJoint.right) { position.left -= this.options.borderWidth; } if (this.options.tipJoint.top) { position.top += this.options.borderWidth; } else if (this.options.tipJoint.bottom) { position.top -= this.options.borderWidth; } } } else { position = { top: mousePosition.y, left: mousePosition.x }; } if (this.options.autoOffset) { stemLength = this.options.stem ? this.options.stemLength : 0; offsetDistance = stemLength && this.options.fixed ? 2 : 10; additionalHorizontal = tipJoint.middle && !this.options.fixed ? 15 : 0; additionalVertical = tipJoint.center && !this.options.fixed ? 15 : 0; if (tipJoint.right) { position.left -= offsetDistance + additionalHorizontal; } else if (tipJoint.left) { position.left += offsetDistance + additionalHorizontal; } if (tipJoint.bottom) { position.top -= offsetDistance + additionalVertical; } else if (tipJoint.top) { position.top += offsetDistance + additionalVertical; } if (stemLength) { if (stem == null) { stem = this.options.stem; } if (stem.right) { position.left -= stemLength; } else if (stem.left) { position.left += stemLength; } if (stem.bottom) { position.top -= stemLength; } else if (stem.top) { position.top += stemLength; } } } position.left += this.options.offset[0]; position.top += this.options.offset[1]; if (tipJoint.right) { position.left -= this.dimensions.width; } else if (tipJoint.center) { position.left -= Math.round(this.dimensions.width / 2); } if (tipJoint.bottom) { position.top -= this.dimensions.height; } else if (tipJoint.middle) { position.top -= Math.round(this.dimensions.height / 2); } return position; }; Opentip.prototype._ensureViewportContainment = function(position) { var needsRepositioning, newSticksOut, originals, revertedX, revertedY, scrollOffset, stem, sticksOut, targetJoint, tipJoint, viewportDimensions, viewportPosition; stem = this.options.stem; originals = { position: position, stem: stem }; if (!(this.visible && position)) { return originals; } sticksOut = this._sticksOut(position); if (!(sticksOut[0] || sticksOut[1])) { return originals; } tipJoint = new Opentip.Joint(this.options.tipJoint); if (this.options.targetJoint) { targetJoint = new Opentip.Joint(this.options.targetJoint); } scrollOffset = this.adapter.scrollOffset(); viewportDimensions = this.adapter.viewportDimensions(); viewportPosition = [position.left - scrollOffset[0], position.top - scrollOffset[1]]; needsRepositioning = false; if (viewportDimensions.width >= this.dimensions.width) { if (sticksOut[0]) { needsRepositioning = true; switch (sticksOut[0]) { case this.STICKS_OUT_LEFT: tipJoint.setHorizontal("left"); if (this.options.targetJoint) { targetJoint.setHorizontal("right"); } break; case this.STICKS_OUT_RIGHT: tipJoint.setHorizontal("right"); if (this.options.targetJoint) { targetJoint.setHorizontal("left"); } } } } if (viewportDimensions.height >= this.dimensions.height) { if (sticksOut[1]) { needsRepositioning = true; switch (sticksOut[1]) { case this.STICKS_OUT_TOP: tipJoint.setVertical("top"); if (this.options.targetJoint) { targetJoint.setVertical("bottom"); } break; case this.STICKS_OUT_BOTTOM: tipJoint.setVertical("bottom"); if (this.options.targetJoint) { targetJoint.setVertical("top"); } } } } if (!needsRepositioning) { return originals; } if (this.options.stem) { stem = tipJoint; } position = this.getPosition(tipJoint, targetJoint, stem); newSticksOut = this._sticksOut(position); revertedX = false; revertedY = false; if (newSticksOut[0] && (newSticksOut[0] !== sticksOut[0])) { revertedX = true; tipJoint.setHorizontal(this.options.tipJoint.horizontal); if (this.options.targetJoint) { targetJoint.setHorizontal(this.options.targetJoint.horizontal); } } if (newSticksOut[1] && (newSticksOut[1] !== sticksOut[1])) { revertedY = true; tipJoint.setVertical(this.options.tipJoint.vertical); if (this.options.targetJoint) { targetJoint.setVertical(this.options.targetJoint.vertical); } } if (revertedX && revertedY) { return originals; } if (revertedX || revertedY) { if (this.options.stem) { stem = tipJoint; } position = this.getPosition(tipJoint, targetJoint, stem); } return { position: position, stem: stem }; }; Opentip.prototype._sticksOut = function(position) { var positionOffset, scrollOffset, sticksOut, viewportDimensions; scrollOffset = this.adapter.scrollOffset(); viewportDimensions = this.adapter.viewportDimensions(); positionOffset = [position.left - scrollOffset[0], position.top - scrollOffset[1]]; sticksOut = [false, false]; if (positionOffset[0] < 0) { sticksOut[0] = this.STICKS_OUT_LEFT; } else if (positionOffset[0] + this.dimensions.width > viewportDimensions.width) { sticksOut[0] = this.STICKS_OUT_RIGHT; } if (positionOffset[1] < 0) { sticksOut[1] = this.STICKS_OUT_TOP; } else if (positionOffset[1] + this.dimensions.height > viewportDimensions.height) { sticksOut[1] = this.STICKS_OUT_BOTTOM; } return sticksOut; }; Opentip.prototype._draw = function() { var backgroundCanvas, bulge, canvasDimensions, canvasPosition, closeButton, closeButtonInner, closeButtonOuter, ctx, drawCorner, drawLine, hb, position, stemBase, stemLength, _i, _len, _ref, _ref1, _ref2, _this = this; if (!(this.backgroundCanvas && this.redraw)) { return; } this.debug("Drawing background."); this.redraw = false; if (this.currentStem) { _ref = ["top", "right", "bottom", "left"]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { position = _ref[_i]; this.adapter.removeClass(this.container, "stem-" + position); } this.adapter.addClass(this.container, "stem-" + this.currentStem.horizontal); this.adapter.addClass(this.container, "stem-" + this.currentStem.vertical); } closeButtonInner = [0, 0]; closeButtonOuter = [0, 0]; if (__indexOf.call(this.options.hideTriggers, "closeButton") >= 0) { closeButton = new Opentip.Joint(((_ref1 = this.currentStem) != null ? _ref1.toString() : void 0) === "top right" ? "top left" : "top right"); closeButtonInner = [this.options.closeButtonRadius + this.options.closeButtonOffset[0], this.options.closeButtonRadius + this.options.closeButtonOffset[1]]; closeButtonOuter = [this.options.closeButtonRadius - this.options.closeButtonOffset[0], this.options.closeButtonRadius - this.options.closeButtonOffset[1]]; } canvasDimensions = this.adapter.clone(this.dimensions); canvasPosition = [0, 0]; if (this.options.borderWidth) { canvasDimensions.width += this.options.borderWidth * 2; canvasDimensions.height += this.options.borderWidth * 2; canvasPosition[0] -= this.options.borderWidth; canvasPosition[1] -= this.options.borderWidth; } if (this.options.shadow) { canvasDimensions.width += this.options.shadowBlur * 2; canvasDimensions.width += Math.max(0, this.options.shadowOffset[0] - this.options.shadowBlur * 2); canvasDimensions.height += this.options.shadowBlur * 2; canvasDimensions.height += Math.max(0, this.options.shadowOffset[1] - this.options.shadowBlur * 2); canvasPosition[0] -= Math.max(0, this.options.shadowBlur - this.options.shadowOffset[0]); canvasPosition[1] -= Math.max(0, this.options.shadowBlur - this.options.shadowOffset[1]); } bulge = { left: 0, right: 0, top: 0, bottom: 0 }; if (this.currentStem) { if (this.currentStem.left) { bulge.left = this.options.stemLength; } else if (this.currentStem.right) { bulge.right = this.options.stemLength; } if (this.currentStem.top) { bulge.top = this.options.stemLength; } else if (this.currentStem.bottom) { bulge.bottom = this.options.stemLength; } } if (closeButton) { if (closeButton.left) { bulge.left = Math.max(bulge.left, closeButtonOuter[0]); } else if (closeButton.right) { bulge.right = Math.max(bulge.right, closeButtonOuter[0]); } if (closeButton.top) { bulge.top = Math.max(bulge.top, closeButtonOuter[1]); } else if (closeButton.bottom) { bulge.bottom = Math.max(bulge.bottom, closeButtonOuter[1]); } } canvasDimensions.width += bulge.left + bulge.right; canvasDimensions.height += bulge.top + bulge.bottom; canvasPosition[0] -= bulge.left; canvasPosition[1] -= bulge.top; if (this.currentStem && this.options.borderWidth) { _ref2 = this._getPathStemMeasures(this.options.stemBase, this.options.stemLength, this.options.borderWidth), stemLength = _ref2.stemLength, stemBase = _ref2.stemBase; } backgroundCanvas = this.adapter.unwrap(this.backgroundCanvas); backgroundCanvas.width = canvasDimensions.width; backgroundCanvas.height = canvasDimensions.height; this.adapter.css(this.backgroundCanvas, { width: "" + backgroundCanvas.width + "px", height: "" + backgroundCanvas.height + "px", left: "" + canvasPosition[0] + "px", top: "" + canvasPosition[1] + "px" }); ctx = backgroundCanvas.getContext("2d"); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, backgroundCanvas.width, backgroundCanvas.height); ctx.beginPath(); ctx.fillStyle = this._getColor(ctx, this.dimensions, this.options.background, this.options.backgroundGradientHorizontal); ctx.lineJoin = "miter"; ctx.miterLimit = 500; hb = this.options.borderWidth / 2; if (this.options.borderWidth) { ctx.strokeStyle = this.options.borderColor; ctx.lineWidth = this.options.borderWidth; } else { stemLength = this.options.stemLength; stemBase = this.options.stemBase; } if (stemBase == null) { stemBase = 0; } drawLine = function(length, stem, first) { if (first) { ctx.moveTo(Math.max(stemBase, _this.options.borderRadius, closeButtonInner[0]) + 1 - hb, -hb); } if (stem) { ctx.lineTo(length / 2 - stemBase / 2, -hb); ctx.lineTo(length / 2, -stemLength - hb); return ctx.lineTo(length / 2 + stemBase / 2, -hb); } }; drawCorner = function(stem, closeButton, i) { var angle1, angle2, innerWidth, offset; if (stem) { ctx.lineTo(-stemBase + hb, 0 - hb); ctx.lineTo(stemLength + hb, -stemLength - hb); return ctx.lineTo(hb, stemBase - hb); } else if (closeButton) { offset = _this.options.closeButtonOffset; innerWidth = closeButtonInner[0]; if (i % 2 !== 0) { offset = [offset[1], offset[0]]; innerWidth = closeButtonInner[1]; } angle1 = Math.acos(offset[1] / _this.options.closeButtonRadius); angle2 = Math.acos(offset[0] / _this.options.closeButtonRadius); ctx.lineTo(-innerWidth + hb, -hb); return ctx.arc(hb - offset[0], -hb + offset[1], _this.options.closeButtonRadius, -(Math.PI / 2 + angle1), angle2, false); } else { ctx.lineTo(-_this.options.borderRadius + hb, -hb); return ctx.quadraticCurveTo(hb, -hb, hb, _this.options.borderRadius - hb); } }; ctx.translate(-canvasPosition[0], -canvasPosition[1]); ctx.save(); (function() { var cornerStem, i, lineLength, lineStem, positionIdx, positionX, positionY, rotation, _j, _ref3, _results; _results = []; for (i = _j = 0, _ref3 = Opentip.positions.length / 2; 0 <= _ref3 ? _j < _ref3 : _j > _ref3; i = 0 <= _ref3 ? ++_j : --_j) { positionIdx = i * 2; positionX = i === 0 || i === 3 ? 0 : _this.dimensions.width; positionY = i < 2 ? 0 : _this.dimensions.height; rotation = (Math.PI / 2) * i; lineLength = i % 2 === 0 ? _this.dimensions.width : _this.dimensions.height; lineStem = new Opentip.Joint(Opentip.positions[positionIdx]); cornerStem = new Opentip.Joint(Opentip.positions[positionIdx + 1]); ctx.save(); ctx.translate(positionX, positionY); ctx.rotate(rotation); drawLine(lineLength, lineStem.eql(_this.currentStem), i === 0); ctx.translate(lineLength, 0); drawCorner(cornerStem.eql(_this.currentStem), cornerStem.eql(closeButton), i); _results.push(ctx.restore()); } return _results; })(); ctx.closePath(); ctx.save(); if (this.options.shadow) { ctx.shadowColor = this.options.shadowColor; ctx.shadowBlur = this.options.shadowBlur; ctx.shadowOffsetX = this.options.shadowOffset[0]; ctx.shadowOffsetY = this.options.shadowOffset[1]; } ctx.fill(); ctx.restore(); if (this.options.borderWidth) { ctx.stroke(); } ctx.restore(); if (closeButton) { return (function() { var crossCenter, crossHeight, crossWidth, hcs, linkCenter; crossWidth = crossHeight = _this.options.closeButtonRadius * 2; if (closeButton.toString() === "top right") { linkCenter = [_this.dimensions.width - _this.options.closeButtonOffset[0], _this.options.closeButtonOffset[1]]; crossCenter = [linkCenter[0] + hb, linkCenter[1] - hb]; } else { linkCenter = [_this.options.closeButtonOffset[0], _this.options.closeButtonOffset[1]]; crossCenter = [linkCenter[0] - hb, linkCenter[1] - hb]; } ctx.translate(crossCenter[0], crossCenter[1]); hcs = _this.options.closeButtonCrossSize / 2; ctx.save(); ctx.beginPath(); ctx.strokeStyle = _this.options.closeButtonCrossColor; ctx.lineWidth = _this.options.closeButtonCrossLineWidth; ctx.lineCap = "round"; ctx.moveTo(-hcs, -hcs); ctx.lineTo(hcs, hcs); ctx.stroke(); ctx.beginPath(); ctx.moveTo(hcs, -hcs); ctx.lineTo(-hcs, hcs); ctx.stroke(); ctx.restore(); return _this.adapter.css(_this.closeButtonElement, { left: "" + (linkCenter[0] - hcs - _this.options.closeButtonLinkOverscan) + "px", top: "" + (linkCenter[1] - hcs - _this.options.closeButtonLinkOverscan) + "px", width: "" + (_this.options.closeButtonCrossSize + _this.options.closeButtonLinkOverscan * 2) + "px", height: "" + (_this.options.closeButtonCrossSize + _this.options.closeButtonLinkOverscan * 2) + "px" }); })(); } }; Opentip.prototype._getPathStemMeasures = function(outerStemBase, outerStemLength, borderWidth) { var angle, distanceBetweenTips, halfAngle, hb, rhombusSide, stemBase, stemLength; hb = borderWidth / 2; halfAngle = Math.atan((outerStemBase / 2) / outerStemLength); angle = halfAngle * 2; rhombusSide = hb / Math.sin(angle); distanceBetweenTips = 2 * rhombusSide * Math.cos(halfAngle); stemLength = hb + outerStemLength - distanceBetweenTips; if (stemLength < 0) { throw new Error("Sorry but your stemLength / stemBase ratio is strange."); } stemBase = (Math.tan(halfAngle) * stemLength) * 2; return { stemLength: stemLength, stemBase: stemBase }; }; Opentip.prototype._getColor = function(ctx, dimensions, color, horizontal) { var colorStop, gradient, i, _i, _len; if (horizontal == null) { horizontal = false; } if (typeof color === "string") { return color; } if (horizontal) { gradient = ctx.createLinearGradient(0, 0, dimensions.width, 0); } else { gradient = ctx.createLinearGradient(0, 0, 0, dimensions.height); } for (i = _i = 0, _len = color.length; _i < _len; i = ++_i) { colorStop = color[i]; gradient.addColorStop(colorStop[0], colorStop[1]); } return gradient; }; Opentip.prototype._searchAndActivateCloseButtons = function() { var element, _i, _len, _ref; _ref = this.adapter.findAll(this.container, "." + this["class"].close); for (_i = 0, _len = _ref.length; _i < _len; _i++) { element = _ref[_i]; this.hideTriggers.push({ element: this.adapter.wrap(element), event: "click" }); } if (this.currentObservers.showing) { this._setupObservers("-showing", "showing"); } if (this.currentObservers.visible) { return this._setupObservers("-visible", "visible"); } }; Opentip.prototype._activateFirstInput = function() { var input; input = this.adapter.unwrap(this.adapter.find(this.container, "input, textarea")); return input != null ? typeof input.focus === "function" ? input.focus() : void 0 : void 0; }; Opentip.prototype._followMousePosition = function() { if (!this.options.fixed) { return Opentip._observeMousePosition(this.bound.reposition); } }; Opentip.prototype._stopFollowingMousePosition = function() { if (!this.options.fixed) { return Opentip._stopObservingMousePosition(this.bound.reposition); } }; Opentip.prototype._clearShowTimeout = function() { return clearTimeout(this._showTimeoutId); }; Opentip.prototype._clearHideTimeout = function() { return clearTimeout(this._hideTimeoutId); }; Opentip.prototype._clearTimeouts = function() { clearTimeout(this._visibilityStateTimeoutId); this._clearShowTimeout(); return this._clearHideTimeout(); }; Opentip.prototype._triggerElementExists = function() { var el; el = this.adapter.unwrap(this.triggerElement); while (el.parentNode) { if (el.parentNode.tagName === "BODY") { return true; } el = el.parentNode; } return false; }; Opentip.prototype._loadAjax = function() { var _this = this; if (this.loading) { return; } this.loaded = false; this.loading = true; this.adapter.addClass(this.container, this["class"].loading); this.setContent(""); this.debug("Loading content from " + this.options.ajax); return this.adapter.ajax({ url: this.options.ajax, method: this.options.ajaxMethod, onSuccess: function(responseText) { _this.debug("Loading successful."); _this.adapter.removeClass(_this.container, _this["class"].loading); return _this.setContent(responseText); }, onError: function(error) { var message; message = _this.options.ajaxErrorMessage; _this.debug(message, error); _this.setContent(message); return _this.adapter.addClass(_this.container, _this["class"].ajaxError); }, onComplete: function() { _this.adapter.removeClass(_this.container, _this["class"].loading); _this.loading = false; _this.loaded = true; _this._searchAndActivateCloseButtons(); _this._activateFirstInput(); return _this.reposition(); } }); }; Opentip.prototype._ensureTriggerElement = function() { if (!this._triggerElementExists()) { this.deactivate(); return this._stopEnsureTriggerElement(); } }; Opentip.prototype._ensureTriggerElementInterval = 1000; Opentip.prototype._startEnsureTriggerElement = function() { var _this = this; return this._ensureTriggerElementTimeoutId = setInterval((function() { return _this._ensureTriggerElement(); }), this._ensureTriggerElementInterval); }; Opentip.prototype._stopEnsureTriggerElement = function() { return clearInterval(this._ensureTriggerElementTimeoutId); }; return Opentip; })(); vendors = ["khtml", "ms", "o", "moz", "webkit"]; Opentip.prototype.setCss3Style = function(element, styles) { var prop, value, vendor, vendorProp, _results; element = this.adapter.unwrap(element); _results = []; for (prop in styles) { if (!__hasProp.call(styles, prop)) continue; value = styles[prop]; if (element.style[prop] != null) { _results.push(element.style[prop] = value); } else { _results.push((function() { var _i, _len, _results1; _results1 = []; for (_i = 0, _len = vendors.length; _i < _len; _i++) { vendor = vendors[_i]; vendorProp = "" + (this.ucfirst(vendor)) + (this.ucfirst(prop)); if (element.style[vendorProp] != null) { _results1.push(element.style[vendorProp] = value); } else { _results1.push(void 0); } } return _results1; }).call(this)); } } return _results; }; Opentip.prototype.defer = function(func) { return setTimeout(func, 0); }; Opentip.prototype.setTimeout = function(func, seconds) { return setTimeout(func, seconds ? seconds * 1000 : 0); }; Opentip.prototype.ucfirst = function(string) { if (string == null) { return ""; } return string.charAt(0).toUpperCase() + string.slice(1); }; Opentip.prototype.dasherize = function(string) { return string.replace(/([A-Z])/g, function(_, character) { return "-" + (character.toLowerCase()); }); }; mousePositionObservers = []; mousePosition = { x: 0, y: 0 }; mouseMoved = function(e) { var observer, _i, _len, _results; mousePosition = Opentip.adapter.mousePosition(e); _results = []; for (_i = 0, _len = mousePositionObservers.length; _i < _len; _i++) { observer = mousePositionObservers[_i]; _results.push(observer()); } return _results; }; Opentip.followMousePosition = function() { return Opentip.adapter.observe(document.body, "mousemove", mouseMoved); }; Opentip._observeMousePosition = function(observer) { return mousePositionObservers.push(observer); }; Opentip._stopObservingMousePosition = function(removeObserver) { var observer; return mousePositionObservers = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = mousePositionObservers.length; _i < _len; _i++) { observer = mousePositionObservers[_i]; if (observer !== removeObserver) { _results.push(observer); } } return _results; })(); }; Opentip.Joint = (function() { function Joint(pointerString) { if (pointerString == null) { return; } if (pointerString instanceof Opentip.Joint) { pointerString = pointerString.toString(); } this.set(pointerString); this; } Joint.prototype.set = function(string) { string = string.toLowerCase(); this.setHorizontal(string); this.setVertical(string); return this; }; Joint.prototype.setHorizontal = function(string) { var i, valid, _i, _j, _len, _len1, _results; valid = ["left", "center", "right"]; for (_i = 0, _len = valid.length; _i < _len; _i++) { i = valid[_i]; if (~string.indexOf(i)) { this.horizontal = i.toLowerCase(); } } if (this.horizontal == null) { this.horizontal = "center"; } _results = []; for (_j = 0, _len1 = valid.length; _j < _len1; _j++) { i = valid[_j]; _results.push(this[i] = this.horizontal === i ? i : void 0); } return _results; }; Joint.prototype.setVertical = function(string) { var i, valid, _i, _j, _len, _len1, _results; valid = ["top", "middle", "bottom"]; for (_i = 0, _len = valid.length; _i < _len; _i++) { i = valid[_i]; if (~string.indexOf(i)) { this.vertical = i.toLowerCase(); } } if (this.vertical == null) { this.vertical = "middle"; } _results = []; for (_j = 0, _len1 = valid.length; _j < _len1; _j++) { i = valid[_j]; _results.push(this[i] = this.vertical === i ? i : void 0); } return _results; }; Joint.prototype.eql = function(pointer) { return (pointer != null) && this.horizontal === pointer.horizontal && this.vertical === pointer.vertical; }; Joint.prototype.flip = function() { var flippedIndex, positionIdx; positionIdx = Opentip.position[this.toString(true)]; flippedIndex = (positionIdx + 4) % 8; this.set(Opentip.positions[flippedIndex]); return this; }; Joint.prototype.toString = function(camelized) { var horizontal, vertical; if (camelized == null) { camelized = false; } vertical = this.vertical === "middle" ? "" : this.vertical; horizontal = this.horizontal === "center" ? "" : this.horizontal; if (vertical && horizontal) { if (camelized) { horizontal = Opentip.prototype.ucfirst(horizontal); } else { horizontal = " " + horizontal; } } return "" + vertical + horizontal; }; return Joint; })(); Opentip.prototype._positionsEqual = function(posA, posB) { return (posA != null) && (posB != null) && posA.left === posB.left && posA.top === posB.top; }; Opentip.prototype._dimensionsEqual = function(dimA, dimB) { return (dimA != null) && (dimB != null) && dimA.width === dimB.width && dimA.height === dimB.height; }; Opentip.prototype.debug = function() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; if (Opentip.debug && ((typeof console !== "undefined" && console !== null ? console.debug : void 0) != null)) { args.unshift("#" + this.id + " |"); return console.debug.apply(console, args); } }; Opentip.findElements = function() { var adapter, content, element, optionName, optionValue, options, _i, _len, _ref, _results; adapter = Opentip.adapter; _ref = adapter.findAll(document.body, "[data-ot]"); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { element = _ref[_i]; options = {}; content = adapter.data(element, "ot"); if (content === "" || content === "true" || content === "yes") { content = adapter.attr(element, "title"); adapter.attr(element, "title", ""); } content = content || ""; for (optionName in Opentip.styles.standard) { optionValue = adapter.data(element, "ot" + (Opentip.prototype.ucfirst(optionName))); if (optionValue != null) { if (optionValue === "yes" || optionValue === "true" || optionValue === "on") { optionValue = true; } else if (optionValue === "no" || optionValue === "false" || optionValue === "off") { optionValue = false; } options[optionName] = optionValue; } } _results.push(new Opentip(element, content, options)); } return _results; }; Opentip.version = "2.4.1"; Opentip.debug = false; Opentip.lastId = 0; Opentip.lastZIndex = 100; Opentip.tips = []; Opentip._abortShowingGroup = function(group, originatingOpentip) { var opentip, _i, _len, _ref, _results; _ref = Opentip.tips; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { opentip = _ref[_i]; if (opentip !== originatingOpentip && opentip.options.group === group) { _results.push(opentip._abortShowing()); } else { _results.push(void 0); } } return _results; }; Opentip._hideGroup = function(group, originatingOpentip) { var opentip, _i, _len, _ref, _results; _ref = Opentip.tips; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { opentip = _ref[_i]; if (opentip !== originatingOpentip && opentip.options.group === group) { _results.push(opentip.hide()); } else { _results.push(void 0); } } return _results; }; Opentip.adapters = {}; Opentip.adapter = null; firstAdapter = true; Opentip.addAdapter = function(adapter) { Opentip.adapters[adapter.name] = adapter; if (firstAdapter) { Opentip.adapter = adapter; adapter.domReady(Opentip.findElements); adapter.domReady(Opentip.followMousePosition); return firstAdapter = false; } }; Opentip.positions = ["top", "topRight", "right", "bottomRight", "bottom", "bottomLeft", "left", "topLeft"]; Opentip.position = {}; _ref = Opentip.positions; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { position = _ref[i]; Opentip.position[position] = i; } Opentip.styles = { standard: { "extends": null, title: void 0, escapeTitle: true, escapeContent: false, className: "standard", stem: true, delay: null, hideDelay: 0.1, fixed: false, showOn: "mouseover", hideTrigger: "trigger", hideTriggers: [], hideOn: null, removeElementsOnHide: false, offset: [0, 0], containInViewport: true, autoOffset: true, showEffect: "appear", hideEffect: "fade", showEffectDuration: 0.3, hideEffectDuration: 0.2, stemLength: 5, stemBase: 8, tipJoint: "top left", target: null, targetJoint: null, cache: true, ajax: false, ajaxMethod: "GET", ajaxErrorMessage: "There was a problem downloading the content.", group: null, style: null, background: "#fff18f", backgroundGradientHorizontal: false, closeButtonOffset: [5, 5], closeButtonRadius: 7, closeButtonCrossSize: 4, closeButtonCrossColor: "#d2c35b", closeButtonCrossLineWidth: 1.5, closeButtonLinkOverscan: 6, borderRadius: 5, borderWidth: 1, borderColor: "#f2e37b", shadow: true, shadowBlur: 10, shadowOffset: [3, 3], shadowColor: "rgba(0, 0, 0, 0.1)" }, glass: { "extends": "standard", className: "glass", background: [[0, "rgba(252, 252, 252, 0.8)"], [0.5, "rgba(255, 255, 255, 0.8)"], [0.5, "rgba(250, 250, 250, 0.9)"], [1, "rgba(245, 245, 245, 0.9)"]], borderColor: "#eee", closeButtonCrossColor: "rgba(0, 0, 0, 0.2)", borderRadius: 15, closeButtonRadius: 10, closeButtonOffset: [8, 8] }, dark: { "extends": "standard", className: "dark", borderRadius: 13, borderColor: "#444", closeButtonCrossColor: "rgba(240, 240, 240, 1)", shadowColor: "rgba(0, 0, 0, 0.3)", shadowOffset: [2, 2], background: [[0, "rgba(30, 30, 30, 0.7)"], [0.5, "rgba(30, 30, 30, 0.8)"], [0.5, "rgba(10, 10, 10, 0.8)"], [1, "rgba(10, 10, 10, 0.9)"]] }, alert: { "extends": "standard", className: "alert", borderRadius: 1, borderColor: "#AE0D11", closeButtonCrossColor: "rgba(255, 255, 255, 1)", shadowColor: "rgba(0, 0, 0, 0.3)", shadowOffset: [2, 2], background: [[0, "rgba(203, 15, 19, 0.7)"], [0.5, "rgba(203, 15, 19, 0.8)"], [0.5, "rgba(189, 14, 18, 0.8)"], [1, "rgba(179, 14, 17, 0.9)"]] } }; Opentip.defaultStyle = "standard"; if (typeof module !== "undefined" && module !== null) { module.exports = Opentip; } else { window.Opentip = Opentip; } // Generated by CoffeeScript 1.4.0 var Adapter, __hasProp = {}.hasOwnProperty, __slice = [].slice; Adapter = (function() { var dataValues, lastDataId; function Adapter() {} Adapter.prototype.name = "native"; Adapter.prototype.domReady = function(callback) { var add, doc, done, init, poll, pre, rem, root, top, win, _ref; done = false; top = true; win = window; doc = document; if ((_ref = doc.readyState) === "complete" || _ref === "loaded") { return callback(); } root = doc.documentElement; add = (doc.addEventListener ? "addEventListener" : "attachEvent"); rem = (doc.addEventListener ? "removeEventListener" : "detachEvent"); pre = (doc.addEventListener ? "" : "on"); init = function(e) { if (e.type === "readystatechange" && doc.readyState !== "complete") { return; } (e.type === "load" ? win : doc)[rem](pre + e.type, init, false); if (!done) { done = true; return callback(); } }; poll = function() { try { root.doScroll("left"); } catch (e) { setTimeout(poll, 50); return; } return init("poll"); }; if (doc.readyState !== "complete") { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch (_error) {} if (top) { poll(); } } doc[add](pre + "DOMContentLoaded", init, false); doc[add](pre + "readystatechange", init, false); return win[add](pre + "load", init, false); } }; Adapter.prototype.create = function(htmlString) { var div; div = document.createElement("div"); div.innerHTML = htmlString; return this.wrap(div.childNodes); }; Adapter.prototype.wrap = function(element) { var el; if (!element) { element = []; } else if (typeof element === "string") { element = this.find(document.body, element); element = element ? [element] : []; } else if (element instanceof NodeList) { element = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = element.length; _i < _len; _i++) { el = element[_i]; _results.push(el); } return _results; })(); } else if (!(element instanceof Array)) { element = [element]; } return element; }; Adapter.prototype.unwrap = function(element) { return this.wrap(element)[0]; }; Adapter.prototype.tagName = function(element) { return this.unwrap(element).tagName; }; Adapter.prototype.attr = function(element, attr, value) { if (arguments.length === 3) { return this.unwrap(element).setAttribute(attr, value); } else { return this.unwrap(element).getAttribute(attr); } }; lastDataId = 0; dataValues = {}; Adapter.prototype.data = function(element, name, value) { var dataId; dataId = this.attr(element, "data-id"); if (!dataId) { dataId = ++lastDataId; this.attr(element, "data-id", dataId); dataValues[dataId] = {}; } if (arguments.length === 3) { return dataValues[dataId][name] = value; } else { value = dataValues[dataId][name]; if (value != null) { return value; } value = this.attr(element, "data-" + (Opentip.prototype.dasherize(name))); if (value) { dataValues[dataId][name] = value; } return value; } }; Adapter.prototype.find = function(element, selector) { return this.unwrap(element).querySelector(selector); }; Adapter.prototype.findAll = function(element, selector) { return this.unwrap(element).querySelectorAll(selector); }; Adapter.prototype.update = function(element, content, escape) { element = this.unwrap(element); if (escape) { element.innerHTML = ""; return element.appendChild(document.createTextNode(content)); } else { return element.innerHTML = content; } }; Adapter.prototype.append = function(element, child) { var unwrappedChild, unwrappedElement; unwrappedChild = this.unwrap(child); unwrappedElement = this.unwrap(element); return unwrappedElement.appendChild(unwrappedChild); }; Adapter.prototype.remove = function(element) { var parentNode; element = this.unwrap(element); parentNode = element.parentNode; if (parentNode != null) { return parentNode.removeChild(element); } }; Adapter.prototype.addClass = function(element, className) { return this.unwrap(element).classList.add(className); }; Adapter.prototype.removeClass = function(element, className) { return this.unwrap(element).classList.remove(className); }; Adapter.prototype.css = function(element, properties) { var key, value, _results; element = this.unwrap(this.wrap(element)); _results = []; for (key in properties) { if (!__hasProp.call(properties, key)) continue; value = properties[key]; _results.push(element.style[key] = value); } return _results; }; Adapter.prototype.dimensions = function(element) { var dimensions, revert; element = this.unwrap(this.wrap(element)); dimensions = { width: element.offsetWidth, height: element.offsetHeight }; if (!(dimensions.width && dimensions.height)) { revert = { position: element.style.position || '', visibility: element.style.visibility || '', display: element.style.display || '' }; this.css(element, { position: "absolute", visibility: "hidden", display: "block" }); dimensions = { width: element.offsetWidth, height: element.offsetHeight }; this.css(element, revert); } return dimensions; }; Adapter.prototype.scrollOffset = function() { return [window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop]; }; Adapter.prototype.viewportDimensions = function() { return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }; }; Adapter.prototype.mousePosition = function(e) { var pos; pos = { x: 0, y: 0 }; if (e == null) { e = window.event; } if (e == null) { return; } try { if (e.pageX || e.pageY) { pos.x = e.pageX; pos.y = e.pageY; } else if (e.clientX || e.clientY) { pos.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; pos.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } } catch (e) { } return pos; }; Adapter.prototype.offset = function(element) { var offset; element = this.unwrap(element); offset = { top: element.offsetTop, left: element.offsetLeft }; while (element = element.offsetParent) { offset.top += element.offsetTop; offset.left += element.offsetLeft; if (element !== document.body) { offset.top -= element.scrollTop; offset.left -= element.scrollLeft; } } return offset; }; Adapter.prototype.observe = function(element, eventName, observer) { return this.unwrap(element).addEventListener(eventName, observer, false); }; Adapter.prototype.stopObserving = function(element, eventName, observer) { return this.unwrap(element).removeEventListener(eventName, observer, false); }; Adapter.prototype.ajax = function(options) { var request, _ref, _ref1; if (options.url == null) { throw new Error("No url provided"); } if (window.XMLHttpRequest) { request = new XMLHttpRequest; } else if (window.ActiveXObject) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } if (!request) { throw new Error("Can't create XMLHttpRequest"); } request.onreadystatechange = function() { if (request.readyState === 4) { try { if (request.status === 200) { if (typeof options.onSuccess === "function") { options.onSuccess(request.responseText); } } else { if (typeof options.onError === "function") { options.onError("Server responded with status " + request.status); } } } catch (e) { if (typeof options.onError === "function") { options.onError(e.message); } } return typeof options.onComplete === "function" ? options.onComplete() : void 0; } }; request.open((_ref = (_ref1 = options.method) != null ? _ref1.toUpperCase() : void 0) != null ? _ref : "GET", options.url); return request.send(); }; Adapter.prototype.clone = function(object) { var key, newObject, val; newObject = {}; for (key in object) { if (!__hasProp.call(object, key)) continue; val = object[key]; newObject[key] = val; } return newObject; }; Adapter.prototype.extend = function() { var key, source, sources, target, val, _i, _len; target = arguments[0], sources = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = sources.length; _i < _len; _i++) { source = sources[_i]; for (key in source) { if (!__hasProp.call(source, key)) continue; val = source[key]; target[key] = val; } } return target; }; return Adapter; })(); Opentip.addAdapter(new Adapter); // Modified by Matias Meno to work in IE8. // I removed the line 312, as proposed by someone on the google forum. // Copyright 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Known Issues: // // * Patterns are not implemented. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } var G_vmlCanvasManager_ = { init: function(opt_doc) { if (/MSIE/.test(navigator.userAgent) && !window.opera) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); } }, init_: function(doc) { // create xmlns if (!doc.namespaces['g_vml_']) { doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml', '#default#VML'); } if (!doc.namespaces['g_o_']) { doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office', '#default#VML'); } // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}' + 'g_vml_\\:*{behavior:url(#default#VML)}' + 'g_o_\\:*{behavior:url(#default#VML)}'; } // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.style.width = el.attributes.width.nodeValue + 'px'; el.getContext().clearRect(); break; case 'height': el.style.height = el.attributes.height.nodeValue + 'px'; el.getContext().clearRect(); break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var dec2hex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { dec2hex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } function processStyle(styleString) { var str, alpha = 1; styleString = String(styleString); if (styleString.substring(0, 3) == 'rgb') { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var guts = styleString.substring(start + 1, end).split(','); str = '#'; for (var i = 0; i < 3; i++) { str += dec2hex[Number(guts[i])]; } if (guts.length == 4 && styleString.substr(3, 1) == 'a') { alpha = guts[3]; } } else { str = styleString; } return {color: str, alpha: alpha}; } function processLineCap(lineCap) { switch (lineCap) { case 'butt': return 'flat'; case 'round': return 'round'; case 'square': default: return 'square'; } } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} surfaceElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(surfaceElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.canvas = surfaceElement; var el = surfaceElement.ownerDocument.createElement('div'); el.style.width = surfaceElement.clientWidth + 'px'; el.style.height = surfaceElement.clientHeight + 'px'; // el.style.overflow = 'hidden'; el.style.position = 'absolute'; surfaceElement.appendChild(el); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = this.getCoords_(aX, aY); var cp1 = this.getCoords_(aCP1x, aCP1y); var cp2 = this.getCoords_(aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = this.getCoords_(aCPx, aCPy); var p = this.getCoords_(aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = this.getCoords_(aX, aY); var pStart = this.getCoords_(xStart, yStart); var pEnd = this.getCoords_(xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = this.getCoords_(dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = this.getCoords_(dx + dw, dy); var c3 = this.getCoords_(dx, dy + dh); var c4 = this.getCoords_(dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');") } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px;"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var lineStr = []; var lineOpen = false; var a = processStyle(aFill ? this.fillStyle : this.strokeStyle); var color = a.color; var opacity = a.alpha * this.globalAlpha; var W = 10; var H = 10; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0 0" coordsize="', Z * W, ' ', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var i = 0; i < this.currentPath_.length; i++) { var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { var lineWidth = this.lineScale_ * this.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', this.lineJoin, '"', ' miterlimit="', this.miterLimit, '"', ' endcap="', processLineCap(this.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } else if (typeof this.fillStyle == 'object') { var fillStyle = this.fillStyle; var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / this.arcScaleX_; var y0 = fillStyle.y0_ / this.arcScaleY_; var x1 = fillStyle.x1_ / this.arcScaleX_; var y1 = fillStyle.y1_ / this.arcScaleY_; var p0 = this.getCoords_(x0, y0); var p1 = this.getCoords_(x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = this.getCoords_(fillStyle.x0_, fillStyle.y0_); var width = max.x - min.x; var height = max.y - min.y; focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= this.arcScaleX_ * Z; height /= this.arcScaleY_ * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * this.globalAlpha; var opacity2 = stops[length - 1].alpha * this.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else { lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fill = function() { this.stroke(true); } contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; /** * @private */ contextPrototype.getCoords_ = function(aX, aY) { var m = this.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 } }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); }; function matrixIsFinite(m) { for (var j = 0; j < 3; j++) { for (var k = 0; k < 2; k++) { if (!isFinite(m[j][k]) || isNaN(m[j][k])) { return false; } } } return true; } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function() { return new CanvasPattern_; }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_() {} // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; })(); } // if /* * classList.js: Cross-browser full element.classList implementation. * 2012-11-15 * * By Eli Grey, http://eligrey.com * Public Domain. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ /*global self, document, DOMException */ /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/ if (typeof document !== "undefined" && !("classList" in document.createElement("a"))) { (function (view) { "use strict"; if (!('HTMLElement' in view) && !('Element' in view)) return; var classListProp = "classList" , protoProp = "prototype" , elemCtrProto = (view.HTMLElement || view.Element)[protoProp] , objCtr = Object , strTrim = String[protoProp].trim || function () { return this.replace(/^\s+|\s+$/g, ""); } , arrIndexOf = Array[protoProp].indexOf || function (item) { var i = 0 , len = this.length ; for (; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; } // Vendors: please allow content code to instantiate DOMExceptions , DOMEx = function (type, message) { this.name = type; this.code = DOMException[type]; this.message = message; } , checkTokenAndGetIndex = function (classList, token) { if (token === "") { throw new DOMEx( "SYNTAX_ERR" , "An invalid or illegal string was specified" ); } if (/\s/.test(token)) { throw new DOMEx( "INVALID_CHARACTER_ERR" , "String contains an invalid character" ); } return arrIndexOf.call(classList, token); } , ClassList = function (elem) { var trimmedClasses = strTrim.call(elem.className) , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [] , i = 0 , len = classes.length ; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.className = this.toString(); }; } , classListProto = ClassList[protoProp] = [] , classListGetter = function () { return new ClassList(this); } ; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { token += ""; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false ; do { token = tokens[i] + ""; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.remove = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false ; do { token = tokens[i] + ""; var index = checkTokenAndGetIndex(this, token); if (index !== -1) { this.splice(index, 1); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.toggle = function (token, forse) { token += ""; var result = this.contains(token) , method = result ? forse !== true && "remove" : forse !== false && "add" ; if (method) { this[method](token); } return result; }; classListProto.toString = function () { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter , enumerable: true , configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true if (ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } }(self)); } !window.addEventListener && (function (WindowPrototype, DocumentPrototype, ElementPrototype, addEventListener, removeEventListener, dispatchEvent, registry) { WindowPrototype[addEventListener] = DocumentPrototype[addEventListener] = ElementPrototype[addEventListener] = function (type, listener) { var target = this; registry.unshift([target, type, listener, function (event) { event.currentTarget = target; event.preventDefault = function () { event.returnValue = false }; event.stopPropagation = function () { event.cancelBubble = true }; event.target = event.srcElement || target; listener.call(target, event); }]); this.attachEvent("on" + type, registry[0][3]); }; WindowPrototype[removeEventListener] = DocumentPrototype[removeEventListener] = ElementPrototype[removeEventListener] = function (type, listener) { for (var index = 0, register; register = registry[index]; ++index) { if (register[0] == this && register[1] == type && register[2] == listener) { return this.detachEvent("on" + type, registry.splice(index, 1)[0][3]); } } }; WindowPrototype[dispatchEvent] = DocumentPrototype[dispatchEvent] = ElementPrototype[dispatchEvent] = function (eventObject) { return this.fireEvent("on" + eventObject.type, eventObject); }; })(Window.prototype, HTMLDocument.prototype, Element.prototype, "addEventListener", "removeEventListener", "dispatchEvent", []);
/** * mixin issues * * Copyright 2012 Cloud9 IDE, Inc. * * This product includes software developed by * Cloud9 IDE, Inc (http://c9.io). * * Author: Mike de Boer <info@mikedeboer.nl> **/ "use strict"; var error = require("./../../error"); var Util = require("./../../util"); var issues = module.exports = { issues: {} }; (function() { /** section: github * issues#getAll(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - filter (String): Optional. Validation rule: ` ^(all|assigned|created|mentioned|subscribed)$ `. * - state (String): Optional. open, closed, or all Validation rule: ` ^(open|closed|all)$ `. * - labels (String): Optional. String list of comma separated Label names. Example: bug,ui,@high * - sort (String): Optional. Validation rule: ` ^(created|updated|comments)$ `. * - direction (String): Optional. Validation rule: ` ^(asc|desc)$ `. * - since (Date): Optional. Timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ * - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `. * - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `. **/ this.getAll = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#repoIssues(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - milestone (String): Optional. Validation rule: ` ^([0-9]+|none|\*)$ `. * - state (String): Optional. open, closed, or all Validation rule: ` ^(open|closed|all)$ `. * - assignee (String): Optional. String User login, `none` for Issues with no assigned User. `*` for Issues with any assigned User. * - mentioned (String): Optional. String User login. * - labels (String): Optional. String list of comma separated Label names. Example: bug,ui,@high * - sort (String): Optional. Validation rule: ` ^(created|updated|comments)$ `. * - direction (String): Optional. Validation rule: ` ^(asc|desc)$ `. * - since (Date): Optional. Timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ * - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `. * - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `. **/ this.repoIssues = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getRepoIssue(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - number (Number): Required. Validation rule: ` ^[0-9]+$ `. **/ this.getRepoIssue = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#create(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - title (String): Required. * - body (String): Optional. * - assignee (String): Optional. Login for the user that this issue should be assigned to. * - milestone (Number): Optional. Milestone to associate this issue with. Validation rule: ` ^[0-9]+$ `. * - labels (Json): Required. Array of strings - Labels to associate with this issue. **/ this.create = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#edit(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - number (Number): Required. Validation rule: ` ^[0-9]+$ `. * - title (String): Optional. * - body (String): Optional. * - assignee (String): Optional. Login for the user that this issue should be assigned to. * - milestone (Number): Optional. Milestone to associate this issue with. Validation rule: ` ^[0-9]+$ `. * - labels (Json): Optional. Array of strings - Labels to associate with this issue. * - state (String): Optional. open or closed Validation rule: ` ^(open|closed)$ `. **/ this.edit = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#repoComments(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - sort (String): Optional. Validation rule: ` ^(created|updated)$ `. * - direction (String): Optional. Validation rule: ` ^(asc|desc)$ `. * - since (Date): Optional. Timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ * - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `. * - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `. **/ this.repoComments = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getComments(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - number (Number): Required. Validation rule: ` ^[0-9]+$ `. * - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `. * - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `. **/ this.getComments = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getComment(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - id (String): Required. **/ this.getComment = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#createComment(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - number (Number): Required. Validation rule: ` ^[0-9]+$ `. * - body (String): Required. **/ this.createComment = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#editComment(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - id (String): Required. * - body (String): Required. **/ this.editComment = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#deleteComment(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - id (String): Required. **/ this.deleteComment = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getEvents(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - number (Number): Required. Validation rule: ` ^[0-9]+$ `. * - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `. * - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `. **/ this.getEvents = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getRepoEvents(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `. * - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `. **/ this.getRepoEvents = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getEvent(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - id (String): Required. **/ this.getEvent = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getLabels(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `. * - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `. **/ this.getLabels = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getLabel(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - name (String): Required. **/ this.getLabel = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#createLabel(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - name (String): Required. * - color (String): Required. 6 character hex code, without a leading #. **/ this.createLabel = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#updateLabel(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - name (String): Required. * - color (String): Required. 6 character hex code, without a leading #. **/ this.updateLabel = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#deleteLabel(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - name (String): Required. **/ this.deleteLabel = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getIssueLabels(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - number (Number): Required. Validation rule: ` ^[0-9]+$ `. **/ this.getIssueLabels = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getAllMilestones(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - state (String): Optional. Validation rule: ` ^(open|closed)$ `. * - sort (String): Optional. due_date, completeness, default: due_date Validation rule: ` ^(due_date|completeness)$ `. * - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `. * - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `. **/ this.getAllMilestones = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#getMilestone(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - number (Number): Required. Validation rule: ` ^[0-9]+$ `. **/ this.getMilestone = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#createMilestone(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - title (String): Required. * - state (String): Optional. Validation rule: ` ^(open|closed)$ `. * - description (String): Optional. * - due_on (Date): Optional. Timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ **/ this.createMilestone = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#updateMilestone(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - number (Number): Required. Validation rule: ` ^[0-9]+$ `. * - title (String): Required. * - state (String): Optional. Validation rule: ` ^(open|closed)$ `. * - description (String): Optional. * - due_on (Date): Optional. Timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ **/ this.updateMilestone = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * issues#deleteMilestone(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - user (String): Required. * - repo (String): Required. * - number (Number): Required. Validation rule: ` ^[0-9]+$ `. **/ this.deleteMilestone = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; }).call(issues.issues);
/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var fs = require('fs'), path = require('path'); function isRootDir(dir) { if (fs.existsSync(path.join(dir, 'www'))) { if (fs.existsSync(path.join(dir, 'config.xml'))) { // For sure is. if (fs.existsSync(path.join(dir, 'platforms'))) { return 2; } else { return 1; } } // Might be (or may be under platforms/). if (fs.existsSync(path.join(dir, 'www', 'config.xml'))) { return 1; } } return 0; } // Runs up the directory chain looking for a .cordova directory. // IF it is found we are in a Cordova project. // Omit argument to use CWD. function isCordova(dir) { if (!dir) { // Prefer PWD over cwd so that symlinked dirs within your PWD work correctly (CB-5687). var pwd = process.env.PWD; var cwd = process.cwd(); if (pwd && pwd != cwd && pwd != 'undefined') { return isCordova(pwd) || isCordova(cwd); } return isCordova(cwd); } var bestReturnValueSoFar = false; for (var i = 0; i < 1000; ++i) { var result = isRootDir(dir); if (result === 2) { return dir; } if (result === 1) { bestReturnValueSoFar = dir; } var parentDir = path.normalize(path.join(dir, '..')); // Detect fs root. if (parentDir == dir) { return bestReturnValueSoFar; } dir = parentDir; } console.error('Hit an unhandled case in CordovaCheck.isCordova'); return false; } module.exports = { findProjectRoot : isCordova };
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ /* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jshint globalstrict: false */ /* globals PDFJS */ // Initializing PDFJS global object (if still undefined) if (typeof PDFJS === 'undefined') { (typeof window !== 'undefined' ? window : this).PDFJS = {}; } PDFJS.version = '1.0.1179'; PDFJS.build = '5eedfff'; (function pdfjsWrapper() { // Use strict in our context only - users might not want it 'use strict'; /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ /* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL, Promise */ 'use strict'; var globalScope = (typeof window === 'undefined') ? this : window; var isWorker = (typeof window === 'undefined'); var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; var AnnotationType = { WIDGET: 1, TEXT: 2, LINK: 3 }; var StreamType = { UNKNOWN: 0, FLATE: 1, LZW: 2, DCT: 3, JPX: 4, JBIG: 5, A85: 6, AHX: 7, CCF: 8, RL: 9 }; var FontType = { UNKNOWN: 0, TYPE1: 1, TYPE1C: 2, CIDFONTTYPE0: 3, CIDFONTTYPE0C: 4, TRUETYPE: 5, CIDFONTTYPE2: 6, TYPE3: 7, OPENTYPE: 8, TYPE0: 9, MMTYPE1: 10 }; // The global PDFJS object exposes the API // In production, it will be declared outside a global wrapper // In development, it will be declared here if (!globalScope.PDFJS) { globalScope.PDFJS = {}; } globalScope.PDFJS.pdfBug = false; PDFJS.VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; // All the possible operations for an operator list. var OPS = PDFJS.OPS = { // Intentionally start from 1 so it is easy to spot bad operators that will be // 0's. dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, constructPath: 91 }; // A notice for devs. These are good for things that are helpful to devs, such // as warning that Workers were disabled, which is important to devs but not // end users. function info(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } // Non-fatal warnings. function warn(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } // Fatal errors that should trigger the fallback UI and halt execution by // throwing an exception. function error(msg) { // If multiple arguments were passed, pass them all to the log function. if (arguments.length > 1) { var logArguments = ['Error:']; logArguments.push.apply(logArguments, arguments); console.log.apply(console, logArguments); // Join the arguments into a single string for the lines below. msg = [].join.call(arguments, ' '); } else { console.log('Error: ' + msg); } console.log(backtrace()); UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown); throw new Error(msg); } function backtrace() { try { throw new Error(); } catch (e) { return e.stack ? e.stack.split('\n').slice(2).join('\n') : ''; } } function assert(cond, msg) { if (!cond) { error(msg); } } var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; var UnsupportedManager = PDFJS.UnsupportedManager = (function UnsupportedManagerClosure() { var listeners = []; return { listen: function (cb) { listeners.push(cb); }, notify: function (featureId) { warn('Unsupported feature "' + featureId + '"'); for (var i = 0, ii = listeners.length; i < ii; i++) { listeners[i](featureId); } } }; })(); // Combines two URLs. The baseUrl shall be absolute URL. If the url is an // absolute URL, it will be returned as is. function combineUrl(baseUrl, url) { if (!url) { return baseUrl; } if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) { return url; } var i; if (url.charAt(0) === '/') { // absolute path i = baseUrl.indexOf('://'); if (url.charAt(1) === '/') { ++i; } else { i = baseUrl.indexOf('/', i + 3); } return baseUrl.substring(0, i) + url; } else { // relative path var pathLength = baseUrl.length; i = baseUrl.lastIndexOf('#'); pathLength = i >= 0 ? i : pathLength; i = baseUrl.lastIndexOf('?', pathLength); pathLength = i >= 0 ? i : pathLength; var prefixLength = baseUrl.lastIndexOf('/', pathLength); return baseUrl.substring(0, prefixLength + 1) + url; } } // Validates if URL is safe and allowed, e.g. to avoid XSS. function isValidUrl(url, allowRelative) { if (!url) { return false; } // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1) // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url); if (!protocol) { return allowRelative; } protocol = protocol[0].toLowerCase(); switch (protocol) { case 'http': case 'https': case 'ftp': case 'mailto': case 'tel': return true; default: return false; } } PDFJS.isValidUrl = isValidUrl; function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } PDFJS.shadow = shadow; var PasswordResponses = PDFJS.PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = (function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; })(); PDFJS.PasswordException = PasswordException; var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; })(); PDFJS.UnknownErrorException = UnknownErrorException; var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; })(); PDFJS.InvalidPDFException = InvalidPDFException; var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; })(); PDFJS.MissingPDFException = MissingPDFException; var UnexpectedResponseException = (function UnexpectedResponseExceptionClosure() { function UnexpectedResponseException(msg, status) { this.name = 'UnexpectedResponseException'; this.message = msg; this.status = status; } UnexpectedResponseException.prototype = new Error(); UnexpectedResponseException.constructor = UnexpectedResponseException; return UnexpectedResponseException; })(); PDFJS.UnexpectedResponseException = UnexpectedResponseException; var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; })(); var MissingDataException = (function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; })(); var XRefParseException = (function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; })(); function bytesToString(bytes) { assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString'); var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToBytes(str) { assert(typeof str === 'string', 'Invalid argument for stringToBytes'); var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } function string32(value) { return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff); } function log2(x) { var n = 1, i = 0; while (x > n) { n <<= 1; i++; } return i; } function readInt8(data, start) { return (data[start] << 24) >> 24; } function readUint16(data, offset) { return (data[offset] << 8) | data[offset + 1]; } function readUint32(data, offset) { return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0; } // Lazy test the endianness of the platform // NOTE: This will be 'true' for simulated TypedArrays function isLittleEndian() { var buffer8 = new Uint8Array(2); buffer8[0] = 1; var buffer16 = new Uint16Array(buffer8.buffer); return (buffer16[0] === 1); } Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { return shadow(PDFJS, 'isLittleEndian', isLittleEndian()); } }); // Lazy test if the userAgant support CanvasTypedArrays function hasCanvasTypedArrays() { var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); var imageData = ctx.createImageData(1, 1); return (typeof imageData.data.buffer !== 'undefined'); } Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', { configurable: true, get: function PDFJS_hasCanvasTypedArrays() { return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays()); } }); var Uint32ArrayView = (function Uint32ArrayViewClosure() { function Uint32ArrayView(buffer, length) { this.buffer = buffer; this.byteLength = buffer.length; this.length = length === undefined ? (this.byteLength >> 2) : length; ensureUint32ArrayViewProps(this.length); } Uint32ArrayView.prototype = Object.create(null); var uint32ArrayViewSetters = 0; function createUint32ArrayProp(index) { return { get: function () { var buffer = this.buffer, offset = index << 2; return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0; }, set: function (value) { var buffer = this.buffer, offset = index << 2; buffer[offset] = value & 255; buffer[offset + 1] = (value >> 8) & 255; buffer[offset + 2] = (value >> 16) & 255; buffer[offset + 3] = (value >>> 24) & 255; } }; } function ensureUint32ArrayViewProps(length) { while (uint32ArrayViewSetters < length) { Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); uint32ArrayViewSetters++; } } return Uint32ArrayView; })(); var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = PDFJS.Util = (function UtilClosure() { function Util() {} var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids // creating many intermediate strings. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { rgbBuf[1] = r; rgbBuf[3] = g; rgbBuf[5] = b; return rgbBuf.join(''); }; // Concatenates two transformation matrices together and returns the result. Util.transform = function Util_transform(m1, m2) { return [ m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5] ]; }; // For 2d affine transforms Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; // Applies the transform to the rectangle and finds the minimum axially // aligned bounding box. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [ Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1]) ]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; // Apply a generic 3d matrix M on a 3-vector v: // | a b c | | X | // | d e f | x | Y | // | g h i | | Z | // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], // with v as [X,Y,Z] Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [ m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2] ]; }; // This calculation uses Singular Value Decomposition. // The SVD can be represented with formula A = USV. We are interested in the // matrix S here because it represents the scale values. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; // Multiply matrix m with its transpose. var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; // Solve the second degree polynomial to get roots. var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; // Scale values are the square roots of the eigenvalues. return [Math.sqrt(sx), Math.sqrt(sy)]; }; // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) // For coordinate systems whose origin lies in the bottom-left, this // means normalization to (BL,TR) ordering. For systems with origin in the // top-left, this means (TL,BR) ordering. Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); // clone rect if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; // Returns a rectangle [x1, y1, x2, y2] corresponding to the // intersection of rect1 and rect2. If no intersection, returns 'false' // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } // Order points along the axes var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); // X: first and second points belong to different rectangles? if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { // Intersection must be between second and third points result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } // Y: first and second points belong to different rectangles? if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { // Intersection must be between second and third points result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; Util.sign = function Util_sign(num) { return num < 0 ? -1 : 1; }; Util.appendToArray = function Util_appendToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function Util_prependToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function() { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; })(); /** * PDF page viewport created based on scale, rotation and offset. * @class * @alias PDFJS.PageViewport */ var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() { /** * @constructor * @private * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates. * @param scale {number} scale of the viewport. * @param rotation {number} rotations of the viewport in degrees. * @param offsetX {number} offset X * @param offsetY {number} offset Y * @param dontFlip {boolean} if true, axis Y will not be flipped. */ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; //case 0: default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY ]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ { /** * Clones viewport with additional properties. * @param args {Object} (optional) If specified, may contain the 'scale' or * 'rotation' properties to override the corresponding properties in * the cloned viewport. * @returns {PDFJS.PageViewport} Cloned viewport. */ clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, /** * Converts PDF point to the viewport coordinates. For examples, useful for * converting PDF location into canvas pixel coordinates. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the viewport coordinate space. * @see {@link convertToPdfPoint} * @see {@link convertToViewportRectangle} */ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, /** * Converts PDF rectangle to the viewport coordinates. * @param rect {Array} xMin, yMin, xMax and yMax coordinates. * @returns {Array} Contains corresponding coordinates of the rectangle * in the viewport coordinate space. * @see {@link convertToViewportPoint} */ convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, /** * Converts viewport coordinates to the PDF location. For examples, useful * for converting canvas pixel location into PDF one. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the PDF coordinate space. * @see {@link convertToViewportPoint} */ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; })(); var PDFStringTranslateTable = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC ]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { // UTF16BE BOM for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode( (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v === 'boolean'; } function isInt(v) { return typeof v === 'number' && ((v | 0) === v); } function isNum(v) { return typeof v === 'number'; } function isString(v) { return typeof v === 'string'; } function isName(v) { return v instanceof Name; } function isCmd(v, cmd) { return v instanceof Cmd && (cmd === undefined || v.cmd === cmd); } function isDict(v, type) { if (!(v instanceof Dict)) { return false; } if (!type) { return true; } var dictType = v.get('Type'); return isName(dictType) && dictType.name === type; } function isArray(v) { return v instanceof Array; } function isStream(v) { return typeof v === 'object' && v !== null && v.getBytes !== undefined; } function isArrayBuffer(v) { return typeof v === 'object' && v !== null && v.byteLength !== undefined; } function isRef(v) { return v instanceof Ref; } /** * Promise Capability object. * * @typedef {Object} PromiseCapability * @property {Promise} promise - A promise object. * @property {function} resolve - Fullfills the promise. * @property {function} reject - Rejects the promise. */ /** * Creates a promise capability object. * @alias PDFJS.createPromiseCapability * * @return {PromiseCapability} A capability object contains: * - a Promise, resolve and reject methods. */ function createPromiseCapability() { var capability = {}; capability.promise = new Promise(function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }); return capability; } PDFJS.createPromiseCapability = createPromiseCapability; /** * Polyfill for Promises: * The following promise implementation tries to generally implement the * Promise/A+ spec. Some notable differences from other promise libaries are: * - There currently isn't a seperate deferred and promise object. * - Unhandled rejections eventually show an error if they aren't handled. * * Based off of the work in: * https://bugzilla.mozilla.org/show_bug.cgi?id=810490 */ (function PromiseClosure() { if (globalScope.Promise) { // Promises existing in the DOM/Worker, checking presence of all/resolve if (typeof globalScope.Promise.all !== 'function') { globalScope.Promise.all = function (iterable) { var count = 0, results = [], resolve, reject; var promise = new globalScope.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); iterable.forEach(function (p, i) { count++; p.then(function (result) { results[i] = result; count--; if (count === 0) { resolve(results); } }, reject); }); if (count === 0) { resolve(results); } return promise; }; } if (typeof globalScope.Promise.resolve !== 'function') { globalScope.Promise.resolve = function (value) { return new globalScope.Promise(function (resolve) { resolve(value); }); }; } if (typeof globalScope.Promise.reject !== 'function') { globalScope.Promise.reject = function (reason) { return new globalScope.Promise(function (resolve, reject) { reject(reason); }); }; } if (typeof globalScope.Promise.prototype.catch !== 'function') { globalScope.Promise.prototype.catch = function (onReject) { return globalScope.Promise.prototype.then(undefined, onReject); }; } return; } var STATUS_PENDING = 0; var STATUS_RESOLVED = 1; var STATUS_REJECTED = 2; // In an attempt to avoid silent exceptions, unhandled rejections are // tracked and if they aren't handled in a certain amount of time an // error is logged. var REJECTION_TIMEOUT = 500; var HandlerManager = { handlers: [], running: false, unhandledRejections: [], pendingRejectionCheck: false, scheduleHandlers: function scheduleHandlers(promise) { if (promise._status === STATUS_PENDING) { return; } this.handlers = this.handlers.concat(promise._handlers); promise._handlers = []; if (this.running) { return; } this.running = true; setTimeout(this.runHandlers.bind(this), 0); }, runHandlers: function runHandlers() { var RUN_TIMEOUT = 1; // ms var timeoutAt = Date.now() + RUN_TIMEOUT; while (this.handlers.length > 0) { var handler = this.handlers.shift(); var nextStatus = handler.thisPromise._status; var nextValue = handler.thisPromise._value; try { if (nextStatus === STATUS_RESOLVED) { if (typeof handler.onResolve === 'function') { nextValue = handler.onResolve(nextValue); } } else if (typeof handler.onReject === 'function') { nextValue = handler.onReject(nextValue); nextStatus = STATUS_RESOLVED; if (handler.thisPromise._unhandledRejection) { this.removeUnhandeledRejection(handler.thisPromise); } } } catch (ex) { nextStatus = STATUS_REJECTED; nextValue = ex; } handler.nextPromise._updateStatus(nextStatus, nextValue); if (Date.now() >= timeoutAt) { break; } } if (this.handlers.length > 0) { setTimeout(this.runHandlers.bind(this), 0); return; } this.running = false; }, addUnhandledRejection: function addUnhandledRejection(promise) { this.unhandledRejections.push({ promise: promise, time: Date.now() }); this.scheduleRejectionCheck(); }, removeUnhandeledRejection: function removeUnhandeledRejection(promise) { promise._unhandledRejection = false; for (var i = 0; i < this.unhandledRejections.length; i++) { if (this.unhandledRejections[i].promise === promise) { this.unhandledRejections.splice(i); i--; } } }, scheduleRejectionCheck: function scheduleRejectionCheck() { if (this.pendingRejectionCheck) { return; } this.pendingRejectionCheck = true; setTimeout(function rejectionCheck() { this.pendingRejectionCheck = false; var now = Date.now(); for (var i = 0; i < this.unhandledRejections.length; i++) { if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) { var unhandled = this.unhandledRejections[i].promise._value; var msg = 'Unhandled rejection: ' + unhandled; if (unhandled.stack) { msg += '\n' + unhandled.stack; } warn(msg); this.unhandledRejections.splice(i); i--; } } if (this.unhandledRejections.length) { this.scheduleRejectionCheck(); } }.bind(this), REJECTION_TIMEOUT); } }; function Promise(resolver) { this._status = STATUS_PENDING; this._handlers = []; try { resolver.call(this, this._resolve.bind(this), this._reject.bind(this)); } catch (e) { this._reject(e); } } /** * Builds a promise that is resolved when all the passed in promises are * resolved. * @param {array} array of data and/or promises to wait for. * @return {Promise} New dependant promise. */ Promise.all = function Promise_all(promises) { var resolveAll, rejectAll; var deferred = new Promise(function (resolve, reject) { resolveAll = resolve; rejectAll = reject; }); var unresolved = promises.length; var results = []; if (unresolved === 0) { resolveAll(results); return deferred; } function reject(reason) { if (deferred._status === STATUS_REJECTED) { return; } results = []; rejectAll(reason); } for (var i = 0, ii = promises.length; i < ii; ++i) { var promise = promises[i]; var resolve = (function(i) { return function(value) { if (deferred._status === STATUS_REJECTED) { return; } results[i] = value; unresolved--; if (unresolved === 0) { resolveAll(results); } }; })(i); if (Promise.isPromise(promise)) { promise.then(resolve, reject); } else { resolve(promise); } } return deferred; }; /** * Checks if the value is likely a promise (has a 'then' function). * @return {boolean} true if value is thenable */ Promise.isPromise = function Promise_isPromise(value) { return value && typeof value.then === 'function'; }; /** * Creates resolved promise * @param value resolve value * @returns {Promise} */ Promise.resolve = function Promise_resolve(value) { return new Promise(function (resolve) { resolve(value); }); }; /** * Creates rejected promise * @param reason rejection value * @returns {Promise} */ Promise.reject = function Promise_reject(reason) { return new Promise(function (resolve, reject) { reject(reason); }); }; Promise.prototype = { _status: null, _value: null, _handlers: null, _unhandledRejection: null, _updateStatus: function Promise__updateStatus(status, value) { if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) { return; } if (status === STATUS_RESOLVED && Promise.isPromise(value)) { value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED)); return; } this._status = status; this._value = value; if (status === STATUS_REJECTED && this._handlers.length === 0) { this._unhandledRejection = true; HandlerManager.addUnhandledRejection(this); } HandlerManager.scheduleHandlers(this); }, _resolve: function Promise_resolve(value) { this._updateStatus(STATUS_RESOLVED, value); }, _reject: function Promise_reject(reason) { this._updateStatus(STATUS_REJECTED, reason); }, then: function Promise_then(onResolve, onReject) { var nextPromise = new Promise(function (resolve, reject) { this.resolve = resolve; this.reject = reject; }); this._handlers.push({ thisPromise: this, onResolve: onResolve, onReject: onReject, nextPromise: nextPromise }); HandlerManager.scheduleHandlers(this); return nextPromise; }, catch: function Promise_catch(onReject) { return this.then(undefined, onReject); } }; globalScope.Promise = Promise; })(); var StatTimer = (function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = {}; this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); // Remove timer from started so it can be called again. delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; // Find the longest name for padding purposes. var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; })(); PDFJS.createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } // Blob builder is deprecated in FF14 and removed in FF18. var bb = new MozBlobBuilder(); bb.append(data); return bb.getBlob(contentType); }; PDFJS.createObjectURL = (function createObjectURLClosure() { // Blob/createObjectURL is not available, falling back to data schema. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType) { if (!PDFJS.disableCreateObjectURL && typeof URL !== 'undefined' && URL.createObjectURL) { var blob = PDFJS.createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; var d4 = i + 2 < ii ? (b3 & 0x3F) : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; })(); function MessageHandler(name, comObj) { this.name = name; this.comObj = comObj; this.callbackIndex = 1; this.postMessageTransfers = true; var callbacksCapabilities = this.callbacksCapabilities = {}; var ah = this.actionHandler = {}; ah['console_log'] = [function ahConsoleLog(data) { console.log.apply(console, data); }]; ah['console_error'] = [function ahConsoleError(data) { console.error.apply(console, data); }]; ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) { UnsupportedManager.notify(data); }]; comObj.onmessage = function messageHandlerComObjOnMessage(event) { var data = event.data; if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacksCapabilities) { var callback = callbacksCapabilities[callbackId]; delete callbacksCapabilities[callbackId]; if ('error' in data) { callback.reject(data.error); } else { callback.resolve(data.data); } } else { error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { Promise.resolve().then(function () { return action[0].call(action[1], data.data); }).then(function (result) { comObj.postMessage({ isReply: true, callbackId: data.callbackId, data: result }); }, function (reason) { comObj.postMessage({ isReply: true, callbackId: data.callbackId, error: reason }); }); } else { action[0].call(action[1], data.data); } } else { error('Unknown action from worker: ' + data.action); } }; } MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, /** * Sends a message to the comObj to invoke the action with the supplied data. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers */ send: function messageHandlerSend(actionName, data, transfers) { var message = { action: actionName, data: data }; this.postMessage(message, transfers); }, /** * Sends a message to the comObj to invoke the action with the supplied data. * Expects that other side will callback with the response. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers. * @returns {Promise} Promise to be resolved with response data. */ sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) { var callbackId = this.callbackIndex++; var message = { action: actionName, data: data, callbackId: callbackId }; var capability = createPromiseCapability(); this.callbacksCapabilities[callbackId] = capability; try { this.postMessage(message, transfers); } catch (e) { capability.reject(e); } return capability.promise; }, /** * Sends raw message to the comObj. * @private * @param message {Object} Raw message. * @param transfers List of transfers/ArrayBuffers, or undefined. */ postMessage: function (message, transfers) { if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = (function loadJpegStream_onloadClosure() { objs.resolve(id, img); }); img.onerror = (function loadJpegStream_onerrorClosure() { objs.resolve(id, null); warn('Error during JPEG image loading'); }); img.src = imageUrl; } /** * The maximum allowed image size in total pixels e.g. width * height. Images * above this value will not be drawn. Use -1 for no limit. * @var {number} */ PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize); /** * The url of where the predefined Adobe CMaps are located. Include trailing * slash. * @var {string} */ PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); /** * Specifies if CMaps are binary packed. * @var {boolean} */ PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; /* * By default fonts are converted to OpenType fonts and loaded via font face * rules. If disabled, the font will be rendered using a built in font renderer * that constructs the glyphs with primitive path commands. * @var {boolean} */ PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace); /** * Path for image resources, mainly for annotation icons. Include trailing * slash. * @var {string} */ PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath); /** * Disable the web worker and run all code on the main thread. This will happen * automatically if the browser doesn't support workers or sending typed arrays * to workers. * @var {boolean} */ PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker); /** * Path and filename of the worker file. Required when the worker is enabled in * development mode. If unspecified in the production build, the worker will be * loaded based on the location of the pdf.js file. * @var {string} */ PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); /** * Disable range request loading of PDF files. When enabled and if the server * supports partial content requests then the PDF will be fetched in chunks. * Enabled (false) by default. * @var {boolean} */ PDFJS.disableRange = (PDFJS.disableRange === undefined ? false : PDFJS.disableRange); /** * Disable streaming of PDF file data. By default PDF.js attempts to load PDF * in chunks. This default behavior can be disabled. * @var {boolean} */ PDFJS.disableStream = (PDFJS.disableStream === undefined ? false : PDFJS.disableStream); /** * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js * will automatically keep fetching more data even if it isn't needed to display * the current page. This default behavior can be disabled. * * NOTE: It is also necessary to disable streaming, see above, * in order for disabling of pre-fetching to work correctly. * @var {boolean} */ PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch); /** * Enables special hooks for debugging PDF.js. * @var {boolean} */ PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); /** * Enables transfer usage in postMessage for ArrayBuffers. * @var {boolean} */ PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers); /** * Disables URL.createObjectURL usage. * @var {boolean} */ PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL); /** * Disables WebGL usage. * @var {boolean} */ PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL); /** * Enables CSS only zooming. * @var {boolean} */ PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom); /** * Controls the logging level. * The constants from PDFJS.VERBOSITY_LEVELS should be used: * - errors * - warnings [default] * - infos * @var {number} */ PDFJS.verbosity = (PDFJS.verbosity === undefined ? PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity); /** * The maximum supported canvas size in total pixels e.g. width * height. * The default value is 4096 * 4096. Use -1 for no limit. * @var {number} */ PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels); /** * Opens external links in a new window if enabled. The default behavior opens * external links in the PDF.js window. * @var {boolean} */ PDFJS.openExternalLinksInNewWindow = ( PDFJS.openExternalLinksInNewWindow === undefined ? false : PDFJS.openExternalLinksInNewWindow); /** * Document initialization / loading parameters object. * * @typedef {Object} DocumentInitParameters * @property {string} url - The URL of the PDF. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded, * use atob() to convert it to a binary string first. * @property {Object} httpHeaders - Basic authentication headers. * @property {boolean} withCredentials - Indicates whether or not cross-site * Access-Control requests should be made using credentials such as cookies * or authorization headers. The default is false. * @property {string} password - For decrypting password-protected PDFs. * @property {TypedArray} initialData - A typed array with the first portion or * all of the pdf data. Used by the extension since some data is already * loaded before the switch to range requests. * @property {number} length - The PDF file length. It's used for progress * reports and range requests operations. * @property {PDFDataRangeTransport} range */ /** * @typedef {Object} PDFDocumentStats * @property {Array} streamTypes - Used stream types in the document (an item * is set to true if specific stream ID was used in the document). * @property {Array} fontTypes - Used font type in the document (an item is set * to true if specific font ID was used in the document). */ /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) * is used, which means it must follow the same origin rules that any XHR does * e.g. No cross domain requests without CORS. * * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src * Can be a url to where a PDF is located, a typed array (Uint8Array) * already populated with data or parameter object. * * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used * if you want to manually serve range requests for data in the PDF. * * @param {function} passwordCallback (deprecated) It is used to request a * password if wrong or no password was provided. The callback receives two * parameters: function that needs to be called with new password and reason * (see {PasswordResponses}). * * @param {function} progressCallback (deprecated) It is used to be able to * monitor the loading progress of the PDF file (necessary to implement e.g. * a loading bar). The callback receives an {Object} with the properties: * {number} loaded and {number} total. * * @return {PDFDocumentLoadingTask} */ PDFJS.getDocument = function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) { var task = new PDFDocumentLoadingTask(); // Support of the obsolete arguments (for compatibility with API v1.0) if (pdfDataRangeTransport) { if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) { // Not a PDFDataRangeTransport instance, trying to add missing properties. pdfDataRangeTransport = Object.create(pdfDataRangeTransport); pdfDataRangeTransport.length = src.length; pdfDataRangeTransport.initialData = src.initialData; } src = Object.create(src); src.range = pdfDataRangeTransport; } task.onPassword = passwordCallback || null; task.onProgress = progressCallback || null; var workerInitializedCapability, transport; var source; if (typeof src === 'string') { source = { url: src }; } else if (isArrayBuffer(src)) { source = { data: src }; } else if (src instanceof PDFDataRangeTransport) { source = { range: src }; } else { if (typeof src !== 'object') { error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object'); } if (!src.url && !src.data && !src.range) { error('Invalid parameter object: need either .data, .range or .url'); } source = src; } var params = {}; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { // The full path is required in the 'url' field. params[key] = combineUrl(window.location.href, source[key]); continue; } else if (key === 'range') { continue; } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { // Converting string or array-like data to Uint8Array. var pdfBytes = source[key]; if (typeof pdfBytes === 'string') { params[key] = stringToBytes(pdfBytes); } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) { params[key] = new Uint8Array(pdfBytes); } else { error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.'); } continue; } params[key] = source[key]; } workerInitializedCapability = createPromiseCapability(); transport = new WorkerTransport(workerInitializedCapability, source.range); workerInitializedCapability.promise.then(function transportInitialized() { transport.fetchDocument(task, params); }); return task; }; /** * PDF document loading operation. * @class */ var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { /** @constructs PDFDocumentLoadingTask */ function PDFDocumentLoadingTask() { this._capability = createPromiseCapability(); /** * Callback to request a password if wrong or no password was provided. * The callback receives two parameters: function that needs to be called * with new password and reason (see {PasswordResponses}). */ this.onPassword = null; /** * Callback to be able to monitor the loading progress of the PDF file * (necessary to implement e.g. a loading bar). The callback receives * an {Object} with the properties: {number} loaded and {number} total. */ this.onProgress = null; } PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */ { /** * @return {Promise} */ get promise() { return this._capability.promise; }, // TODO add cancel or abort method /** * Registers callbacks to indicate the document loading completion. * * @param {function} onFulfilled The callback for the loading completion. * @param {function} onRejected The callback for the loading failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return PDFDocumentLoadingTask; })(); /** * Abstract class to support range requests file loading. * @class */ var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() { /** * @constructs PDFDataRangeTransport * @param {number} length * @param {Uint8Array} initialData */ function PDFDataRangeTransport(length, initialData) { this.length = length; this.initialData = initialData; this._rangeListeners = []; this._progressListeners = []; this._progressiveReadListeners = []; this._readyCapability = createPromiseCapability(); } PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */ { addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { this._rangeListeners.push(listener); }, addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { this._progressListeners.push(listener); }, addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { this._progressiveReadListeners.push(listener); }, onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { var listeners = this._rangeListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](begin, chunk); } }, onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { this._readyCapability.promise.then(function () { var listeners = this._progressListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](loaded); } }.bind(this)); }, onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { this._readyCapability.promise.then(function () { var listeners = this._progressiveReadListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](chunk); } }.bind(this)); }, transportReady: function PDFDataRangeTransport_transportReady() { this._readyCapability.resolve(); }, requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); } }; return PDFDataRangeTransport; })(); PDFJS.PDFDataRangeTransport = PDFDataRangeTransport; /** * Proxy to a PDFDocument in the worker thread. Also, contains commonly used * properties that can be read synchronously. * @class */ var PDFDocumentProxy = (function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport) { this.pdfInfo = pdfInfo; this.transport = transport; } PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ { /** * @return {number} Total number of pages the PDF contains. */ get numPages() { return this.pdfInfo.numPages; }, /** * @return {string} A unique ID to identify a PDF. Not guaranteed to be * unique. */ get fingerprint() { return this.pdfInfo.fingerprint; }, /** * @param {number} pageNumber The page number to get. The first page is 1. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy} * object. */ getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, /** * @param {{num: number, gen: number}} ref The page reference. Must have * the 'num' and 'gen' properties. * @return {Promise} A promise that is resolved with the page index that is * associated with the reference. */ getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named destinations to reference numbers. * * This can be slow for large documents: use getDestination instead */ getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, /** * @param {string} id The named destination to get. * @return {Promise} A promise that is resolved with all information * of the given named destination. */ getDestination: function PDFDocumentProxy_getDestination(id) { return this.transport.getDestination(id); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named attachments to their content. */ getAttachments: function PDFDocumentProxy_getAttachments() { return this.transport.getAttachments(); }, /** * @return {Promise} A promise that is resolved with an array of all the * JavaScript strings in the name tree. */ getJavaScript: function PDFDocumentProxy_getJavaScript() { return this.transport.getJavaScript(); }, /** * @return {Promise} A promise that is resolved with an {Array} that is a * tree outline (if it has one) of the PDF. The tree is in the format of: * [ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb array, * dest: dest obj, * items: array of more items like this * }, * ... * ]. */ getOutline: function PDFDocumentProxy_getOutline() { return this.transport.getOutline(); }, /** * @return {Promise} A promise that is resolved with an {Object} that has * info and metadata properties. Info is an {Object} filled with anything * available in the information dictionary and similarly metadata is a * {Metadata} object with information from the metadata section of the PDF. */ getMetadata: function PDFDocumentProxy_getMetadata() { return this.transport.getMetadata(); }, /** * @return {Promise} A promise that is resolved with a TypedArray that has * the raw data from the PDF. */ getData: function PDFDocumentProxy_getData() { return this.transport.getData(); }, /** * @return {Promise} A promise that is resolved when the document's data * is loaded. It is resolved with an {Object} that contains the length * property that indicates size of the PDF data in bytes. */ getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoCapability.promise; }, /** * @return {Promise} A promise this is resolved with current stats about * document structures (see {@link PDFDocumentStats}). */ getStats: function PDFDocumentProxy_getStats() { return this.transport.getStats(); }, /** * Cleans up resources allocated by the document, e.g. created @font-face. */ cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, /** * Destroys current document instance and terminates worker. */ destroy: function PDFDocumentProxy_destroy() { this.transport.destroy(); } }; return PDFDocumentProxy; })(); /** * Page text content. * * @typedef {Object} TextContent * @property {array} items - array of {@link TextItem} * @property {Object} styles - {@link TextStyles} objects, indexed by font * name. */ /** * Page text content part. * * @typedef {Object} TextItem * @property {string} str - text content. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {array} transform - transformation matrix. * @property {number} width - width in device space. * @property {number} height - height in device space. * @property {string} fontName - font name used by pdf.js for converted font. */ /** * Text style. * * @typedef {Object} TextStyle * @property {number} ascent - font ascent. * @property {number} descent - font descent. * @property {boolean} vertical - text is in vertical mode. * @property {string} fontFamily - possible font family */ /** * Page render parameters. * * @typedef {Object} RenderParameters * @property {Object} canvasContext - A 2D context of a DOM Canvas object. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by * calling of PDFPage.getViewport method. * @property {string} intent - Rendering intent, can be 'display' or 'print' * (default value is 'display'). * @property {Object} imageLayer - (optional) An object that has beginLayout, * endLayout and appendImage functions. * @property {function} continueCallback - (deprecated) A function that will be * called each time the rendering is paused. To continue * rendering call the function that is the first argument * to the callback. */ /** * PDF page operator list. * * @typedef {Object} PDFOperatorList * @property {Array} fnArray - Array containing the operator functions. * @property {Array} argsArray - Array containing the arguments of the * functions. */ /** * Proxy to a PDFPage in the worker thread. * @class */ var PDFPageProxy = (function PDFPageProxyClosure() { function PDFPageProxy(pageIndex, pageInfo, transport) { this.pageIndex = pageIndex; this.pageInfo = pageInfo; this.transport = transport; this.stats = new StatTimer(); this.stats.enabled = !!globalScope.PDFJS.enableStats; this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingDestroy = false; this.intentStates = {}; } PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ { /** * @return {number} Page number of the page. First page is 1. */ get pageNumber() { return this.pageIndex + 1; }, /** * @return {number} The number of degrees the page is rotated clockwise. */ get rotate() { return this.pageInfo.rotate; }, /** * @return {Object} The reference that points to this page. It has 'num' and * 'gen' properties. */ get ref() { return this.pageInfo.ref; }, /** * @return {Array} An array of the visible portion of the PDF page in the * user space units - [x1, y1, x2, y2]. */ get view() { return this.pageInfo.view; }, /** * @param {number} scale The desired scale of the viewport. * @param {number} rotate Degrees to rotate the viewport. If omitted this * defaults to the page rotation. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties * along with transforms required for rendering. */ getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0); }, /** * @return {Promise} A promise that is resolved with an {Array} of the * annotation objects. */ getAnnotations: function PDFPageProxy_getAnnotations() { if (this.annotationsPromise) { return this.annotationsPromise; } var promise = this.transport.getAnnotations(this.pageIndex); this.annotationsPromise = promise; return promise; }, /** * Begins the process of rendering a page to the desired context. * @param {RenderParameters} params Page render parameters. * @return {RenderTask} An object that contains the promise, which * is resolved when the page finishes rendering. */ render: function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingDestroy = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingDestroy) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingDestroy = true; } self._tryDestroy(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }, /** * @return {Promise} A promise resolved with an {@link PDFOperatorList} * object that represents page's operator list. */ getOperatorList: function PDFPageProxy_getOperatorList() { function operatorListChanged() { if (intentState.operatorList.lastChunk) { intentState.opListReadCapability.resolve(intentState.operatorList); } } var renderingIntent = 'oplist'; if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; if (!intentState.opListReadCapability) { var opListTask = {}; opListTask.operatorListChanged = operatorListChanged; intentState.receivingOperatorList = true; intentState.opListReadCapability = createPromiseCapability(); intentState.renderTasks = []; intentState.renderTasks.push(opListTask); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageIndex, intent: renderingIntent }); } return intentState.opListReadCapability.promise; }, /** * @return {Promise} That is resolved a {@link TextContent} * object that represent the page text content. */ getTextContent: function PDFPageProxy_getTextContent() { return this.transport.messageHandler.sendWithPromise('GetTextContent', { pageIndex: this.pageNumber - 1 }); }, /** * Destroys resources allocated by the page. */ destroy: function PDFPageProxy_destroy() { this.pendingDestroy = true; this._tryDestroy(); }, /** * For internal use only. Attempts to clean up if rendering is in a state * where that's possible. * @ignore */ _tryDestroy: function PDFPageProxy__destroy() { if (!this.pendingDestroy || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingDestroy = false; }, /** * For internal use only. * @ignore */ _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; // TODO Refactor RenderPageRequest to separate rendering // and operator list logic if (intentState.displayReadyCapability) { intentState.displayReadyCapability.resolve(transparency); } }, /** * For internal use only. * @ignore */ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryDestroy(); } } }; return PDFPageProxy; })(); /** * For internal use only. * @ignore */ var WorkerTransport = (function WorkerTransportClosure() { function WorkerTransport(workerInitializedCapability, pdfDataRangeTransport) { this.pdfDataRangeTransport = pdfDataRangeTransport; this.workerInitializedCapability = workerInitializedCapability; this.commonObjs = new PDFObjects(); this.loadingTask = null; this.pageCache = []; this.pagePromises = []; this.downloadInfoCapability = createPromiseCapability(); // If worker support isn't disabled explicit and the browser has worker // support, create a new web worker and test if it/the browser fullfills // all requirements to run parts of pdf.js in a web worker. // Right now, the requirement is, that an Uint8Array is still an Uint8Array // as it arrives on the worker. Chrome added this with version 15. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') { var workerSrc = PDFJS.workerSrc; if (!workerSrc) { error('No PDFJS.workerSrc specified'); } try { // Some versions of FF can't create a worker on localhost, see: // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 var worker = new Worker(workerSrc); var messageHandler = new MessageHandler('main', worker); this.messageHandler = messageHandler; messageHandler.on('test', function transportTest(data) { var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { this.worker = worker; if (!data.supportTransfers) { PDFJS.postMessageTransfers = false; } this.setupMessageHandler(messageHandler); workerInitializedCapability.resolve(); } else { this.setupFakeWorker(); } }.bind(this)); var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]); // Some versions of Opera throw a DATA_CLONE_ERR on serializing the // typed array. Also, checking if we can use transfers. try { messageHandler.send('test', testObj, [testObj.buffer]); } catch (ex) { info('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } return; } catch (e) { info('The worker has been disabled.'); } } // Either workers are disabled, not supported or have thrown an exception. // Thus, we fallback to a faked worker. this.setupFakeWorker(); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { this.pageCache = []; this.pagePromises = []; var self = this; this.messageHandler.sendWithPromise('Terminate', null).then(function () { FontLoader.clear(); if (self.worker) { self.worker.terminate(); } }); }, setupFakeWorker: function WorkerTransport_setupFakeWorker() { globalScope.PDFJS.disableWorker = true; if (!PDFJS.fakeWorkerFilesLoadedCapability) { PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability(); // In the developer build load worker_loader which in turn loads all the // other files and resolves the promise. In production only the // pdf.worker.js file is needed. Util.loadScript(PDFJS.workerSrc, function() { PDFJS.fakeWorkerFilesLoadedCapability.resolve(); }); } PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () { warn('Setting up fake worker.'); // If we don't use a worker, just post/sendMessage to the main thread. var fakeWorker = { postMessage: function WorkerTransport_postMessage(obj) { fakeWorker.onmessage({data: obj}); }, terminate: function WorkerTransport_terminate() {} }; var messageHandler = new MessageHandler('main', fakeWorker); this.setupMessageHandler(messageHandler); // If the main thread is our worker, setup the handling for the messages // the main thread sends to it self. PDFJS.WorkerMessageHandler.setup(messageHandler); this.workerInitializedCapability.resolve(); }.bind(this)); }, setupMessageHandler: function WorkerTransport_setupMessageHandler(messageHandler) { this.messageHandler = messageHandler; function updatePassword(password) { messageHandler.send('UpdatePassword', password); } var pdfDataRangeTransport = this.pdfDataRangeTransport; if (pdfDataRangeTransport) { pdfDataRangeTransport.addRangeListener(function(begin, chunk) { messageHandler.send('OnDataRange', { begin: begin, chunk: chunk }); }); pdfDataRangeTransport.addProgressListener(function(loaded) { messageHandler.send('OnDataProgress', { loaded: loaded }); }); pdfDataRangeTransport.addProgressiveReadListener(function(chunk) { messageHandler.send('OnDataRange', { chunk: chunk }); }); messageHandler.on('RequestDataRange', function transportDataRange(data) { pdfDataRangeTransport.requestDataRange(data.begin, data.end); }, this); } messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var pdfDocument = new PDFDocumentProxy(pdfInfo, this); this.pdfDocument = pdfDocument; this.loadingTask._capability.resolve(pdfDocument); }, this); messageHandler.on('NeedPassword', function transportNeedPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) { this.loadingTask._capability.reject( new InvalidPDFException(exception.message)); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(exception) { this.loadingTask._capability.reject( new MissingPDFException(exception.message)); }, this); messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) { this.loadingTask._capability.reject( new UnexpectedResponseException(exception.message, exception.status)); }, this); messageHandler.on('UnknownError', function transportUnknownError(exception) { this.loadingTask._capability.reject( new UnknownErrorException(exception.message, exception.details)); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoCapability.resolve(data); }, this); messageHandler.on('PDFManagerReady', function transportPage(data) { if (this.pdfDataRangeTransport) { this.pdfDataRangeTransport.transportReady(); } }, this); messageHandler.on('StartRenderPage', function transportRender(data) { var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; var font; if ('error' in exportedData) { var error = exportedData.error; warn('Error during font loading: ' + error); this.commonObjs.resolve(id, error); break; } else { font = new FontFaceObject(exportedData); } FontLoader.bind( [font], function fontReady(fontObjs) { this.commonObjs.resolve(id, font); }.bind(this) ); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; loadJpegStream(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); // heuristics that will allow not to store large data var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { var loadingTask = this.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('PageError', function transportError(data) { var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[data.intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.reject(data.error); } else { error(data.error); } }, this); messageHandler.on('JpegDecode', function(data) { var imageUrl = data[0]; var components = data[1]; if (components !== 3 && components !== 1) { return Promise.reject( new Error('Only 3 components or 1 component can be returned')); } return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = createScratchCanvas(width, height); var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components === 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components === 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } resolve({ data: buf, width: width, height: height}); }; img.onerror = function () { reject(new Error('JpegDecode failed to load image')); }; img.src = imageUrl; }); }); }, fetchDocument: function WorkerTransport_fetchDocument(loadingTask, source) { this.loadingTask = loadingTask; source.disableAutoFetch = PDFJS.disableAutoFetch; source.disableStream = PDFJS.disableStream; source.chunkedViewerLoading = !!this.pdfDataRangeTransport; if (this.pdfDataRangeTransport) { source.length = this.pdfDataRangeTransport.length; source.initialData = this.pdfDataRangeTransport.initialData; } this.messageHandler.send('GetDocRequest', { source: source, disableRange: PDFJS.disableRange, maxImageSize: PDFJS.maxImageSize, cMapUrl: PDFJS.cMapUrl, cMapPacked: PDFJS.cMapPacked, disableFontFace: PDFJS.disableFontFace, disableCreateObjectURL: PDFJS.disableCreateObjectURL, verbosity: PDFJS.verbosity }); }, getData: function WorkerTransport_getData() { return this.messageHandler.sendWithPromise('GetData', null); }, getPage: function WorkerTransport_getPage(pageNumber, capability) { if (pageNumber <= 0 || pageNumber > this.numPages || (pageNumber|0) !== pageNumber) { return Promise.reject(new Error('Invalid page request')); } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) { var page = new PDFPageProxy(pageIndex, pageInfo, this); this.pageCache[pageIndex] = page; return page; }.bind(this)); this.pagePromises[pageIndex] = promise; return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }); }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex) { return this.messageHandler.sendWithPromise('GetAnnotations', { pageIndex: pageIndex }); }, getDestinations: function WorkerTransport_getDestinations() { return this.messageHandler.sendWithPromise('GetDestinations', null); }, getDestination: function WorkerTransport_getDestination(id) { return this.messageHandler.sendWithPromise('GetDestination', { id: id } ); }, getAttachments: function WorkerTransport_getAttachments() { return this.messageHandler.sendWithPromise('GetAttachments', null); }, getJavaScript: function WorkerTransport_getJavaScript() { return this.messageHandler.sendWithPromise('GetJavaScript', null); }, getOutline: function WorkerTransport_getOutline() { return this.messageHandler.sendWithPromise('GetOutline', null); }, getMetadata: function WorkerTransport_getMetadata() { return this.messageHandler.sendWithPromise('GetMetadata', null). then(function transportMetadata(results) { return { info: results[0], metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null) }; }); }, getStats: function WorkerTransport_getStats() { return this.messageHandler.sendWithPromise('GetStats', null); }, startCleanup: function WorkerTransport_startCleanup() { this.messageHandler.sendWithPromise('Cleanup', null). then(function endCleanup() { for (var i = 0, ii = this.pageCache.length; i < ii; i++) { var page = this.pageCache[i]; if (page) { page.destroy(); } } this.commonObjs.clear(); FontLoader.clear(); }.bind(this)); } }; return WorkerTransport; })(); /** * A PDF document and page is built of many objects. E.g. there are objects * for fonts, images, rendering code and such. These objects might get processed * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. * @ignore */ var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = {}; } PDFObjects.prototype = { /** * Internal function. * Ensures there is an object defined for `objId`. */ ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { capability: createPromiseCapability(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this function throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this * function and the object is already resolved, the callback gets called * right away. */ get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { this.ensureObj(objId).capability.promise.then(callback); return null; } // If there isn't a callback, the user expects to get the resolved data // directly. var obj = this.objs[objId]; // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! if (!obj || !obj.resolved) { error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.capability.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } else { return objs[objId].resolved; } }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, /** * Returns the data of `objId` if object exists, null otherwise. */ getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }, clear: function PDFObjects_clear() { this.objs = {}; } }; return PDFObjects; })(); /** * Allows controlling of the rendering tasks. * @class */ var RenderTask = (function RenderTaskClosure() { function RenderTask(internalRenderTask) { this._internalRenderTask = internalRenderTask; /** * Callback for incremental rendering -- a function that will be called * each time the rendering is paused. To continue rendering call the * function that is the first argument to the callback. * @type {function} */ this.onContinue = null; } RenderTask.prototype = /** @lends RenderTask.prototype */ { /** * Promise for rendering task completion. * @return {Promise} */ get promise() { return this._internalRenderTask.capability.promise; }, /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will resolved when cancelled. */ cancel: function RenderTask_cancel() { this._internalRenderTask.cancel(); }, /** * Registers callbacks to indicate the rendering task completion. * * @param {function} onFulfilled The callback for the rendering completion. * @param {function} onRejected The callback for the rendering failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return RenderTask; })(); /** * For internal use only. * @ignore */ var InternalRenderTask = (function InternalRenderTaskClosure() { function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.cancelled = false; this.capability = createPromiseCapability(); this.task = new RenderTask(this); // caching this-bound methods this._continueBound = this._continue.bind(this); this._scheduleNextBound = this._scheduleNext.bind(this); this._nextBound = this._next.bind(this); } InternalRenderTask.prototype = { initalizeGraphics: function InternalRenderTask_initalizeGraphics(transparency) { if (this.cancelled) { return; } if (PDFJS.pdfBug && 'StepperManager' in globalScope && globalScope.StepperManager.enabled) { this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer); this.gfx.beginDrawing(params.viewport, transparency); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; this.callback('cancelled'); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continueBound; } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.task.onContinue) { this.task.onContinue.call(this.task, this._scheduleNextBound); } else { this._scheduleNext(); } }, _scheduleNext: function InternalRenderTask__scheduleNext() { window.requestAnimationFrame(this._nextBound); }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); this.callback(); } } } }; return InternalRenderTask; })(); var Metadata = PDFJS.Metadata = (function MetadataClosure() { function fixMetadata(meta) { return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0; i < bytes.length; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } return '>' + chars; }); } function Metadata(meta) { if (typeof meta === 'string') { // Ghostscript produces invalid metadata meta = fixMetadata(meta); var parser = new DOMParser(); meta = parser.parseFromString(meta, 'application/xml'); } else if (!(meta instanceof Document)) { error('Metadata: Invalid metadata object'); } this.metaDocument = meta; this.metadata = {}; this.parse(); } Metadata.prototype = { parse: function Metadata_parse() { var doc = this.metaDocument; var rdf = doc.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta> rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength; for (i = 0, length = children.length; i < length; i++) { desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') { entry = desc.childNodes[ii]; name = entry.nodeName.toLowerCase(); this.metadata[name] = entry.textContent.trim(); } } } }, get: function Metadata_get(name) { return this.metadata[name] || null; }, has: function Metadata_has(name) { return typeof this.metadata[name] !== 'undefined'; } }; return Metadata; })(); // <canvas> contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. // Minimal font size that would be used during canvas fillText operations. var MIN_FONT_SIZE = 16; // Maximum font size that would be used during canvas fillText operations. var MAX_FONT_SIZE = 100; var MAX_GROUP_SIZE = 4096; // Heuristic value used when enforcing minimum line widths. var MIN_WIDTH_FACTOR = 0.65; var COMPILE_TYPE3_GLYPHS = true; var MAX_SIZE_TO_COMPILE = 1000; var FULL_CHUNK_HEIGHT = 16; function createScratchCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } function addContextCurrentTransform(ctx) { // If the context doesn't expose a `mozCurrentTransform`, add a JS based on. if (!ctx.mozCurrentTransform) { // Store the original context ctx._scaleX = ctx._scaleX || 1.0; ctx._scaleY = ctx._scaleY || 1.0; ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { // Calculation done using WolframAlpha: // http://www.wolframalpha.com/input/? // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [ d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc ]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [ m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5] ]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [ m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * (-sinValue) + m[2] * cosValue, m[1] * (-sinValue) + m[3] * cosValue, m[4], m[5] ]; this._originalRotate(angle); }; } } var CachedCanvases = (function CachedCanvasesClosure() { var cache = {}; return { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (cache[id] !== undefined) { canvasEntry = cache[id]; canvasEntry.canvas.width = width; canvasEntry.canvas.height = height; // reset canvas transform for emulated mozCurrentTransform, if needed canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { var canvas = createScratchCanvas(width, height); var ctx = canvas.getContext('2d'); if (trackTransform) { addContextCurrentTransform(ctx); } cache[id] = canvasEntry = {canvas: canvas, context: ctx}; } return canvasEntry; }, clear: function () { for (var id in cache) { var canvasEntry = cache[id]; // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. canvasEntry.canvas.width = 0; canvasEntry.canvas.height = 0; delete cache[id]; } } }; })(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); // decodes bit-packed mask data var lineSize = (width + 7) & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = (elem & mask) ? 0 : 255; mask >>= 1; } } // finding iteresting points: every point is located between mask pixels, // so there will be points of the (width + 1)x(height + 1) grid. Every point // will have flags assigned based on neighboring mask pixels: // 4 | 8 // --P-- // 2 | 1 // We are interested only in points with the flags: // - outside corners: 1, 2, 4, 8; // - inside corners: 7, 11, 13, 14; // - and, intersections: 5, 10. var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } // 'sum' is the position of the current pixel configuration in the 'TYPES' // array (in order 8-1-2-4, so we can use '>>2' to shift the column). var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } // building outlines var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { // set new direction type = pp; // delete mark points[p] = 0; } else { // type is 5 or 10, ie, a crossing // set new direction type = pp & ((0x33 * type) >> 4); // set new type for "future hit" points[p] &= (type >> 2 | type << 2); } coords.push(p % width1); coords.push((p / width1) | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function(c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j+1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = (function CanvasExtraStateClosure() { function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; this.textMatrixScale = 1; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = TextRenderingMode.FILL; this.textRise = 0; // Default fore and background colors this.fillColor = '#000000'; this.strokeColor = '#000000'; this.patternFill = false; // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; // nonclonable field (see the save method below) this.old = old; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; })(); var CanvasGraphics = (function CanvasGraphicsClosure() { // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. var EXECUTION_TIME = 15; // Defines the number of steps before checking the execution time var EXECUTION_STEPS = 10; function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; // Patterns are painted relative to the initial page/form transform, see pdf // spec 8.7.2 NOTE 1. this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; if (canvasCtx) { addContextCurrentTransform(canvasCtx); } this.cachedGetSinglePixelWidth = null; } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } // Put the image data to the canvas in chunks, rather than putting the // whole image at once. This saves JS memory, because the ImageData object // is smaller. It also possibly saves C++ memory within the implementation // of putImageData(). (E.g. in Firefox we make two short-lived copies of // the data passed to putImageData()). |n| shouldn't be too small, however, // because too many putImageData() calls will slow things down. // // Note: as written, if the last chunk is partial, the putImageData() call // will (conceptually) put pixels past the bounds of the canvas. But // that's ok; any such pixels are ignored. var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; // There are multiple forms in which the pixel data can be passed, and // imgData.kind tells us which one this is. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { // Grayscale, 1 bit per pixel (i.e. black-and-white). var srcLength = src.byteLength; var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest); var dest32DataLength = dest32.length; var fullSrcDiff = (width + 7) >> 3; var white = 0xFFFFFFFF; var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = (srcByte & 128) ? white : black; dest32[destPos++] = (srcByte & 64) ? white : black; dest32[destPos++] = (srcByte & 32) ? white : black; dest32[destPos++] = (srcByte & 16) ? white : black; dest32[destPos++] = (srcByte & 8) ? white : black; dest32[destPos++] = (srcByte & 4) ? white : black; dest32[destPos++] = (srcByte & 2) ? white : black; dest32[destPos++] = (srcByte & 1) ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = (srcByte & mask) ? white : black; mask >>= 1; } } // We ran out of input. Make all remaining pixels transparent. while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else if (imgData.kind === ImageKind.RGBA_32BPP) { // RGBA, 32-bits per pixel. j = 0; elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; for (i = 0; i < fullChunks; i++) { dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, j); j += FULL_CHUNK_HEIGHT; } if (i < totalChunks) { elemsInThisChunk = width * partialChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); ctx.putImageData(chunkImgData, 0, j); } } else if (imgData.kind === ImageKind.RGB_24BPP) { // RGB, 24-bits per pixel. thisChunkHeight = FULL_CHUNK_HEIGHT; elemsInThisChunk = width * thisChunkHeight; for (i = 0; i < totalChunks; i++) { if (i >= fullChunks) { thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } destPos = 0; for (j = elemsInThisChunk; j--;) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. var destPos = 3; // alpha component offset for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = (elem & mask) ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } else if (sourceCtx.mozDashOffset !== undefined) { destCtx.mozDash = sourceCtx.mozDash; destCtx.mozDashOffset = sourceCtx.mozDashOffset; } } function composeSMaskBackdrop(bytes, r0, g0, b0) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i]; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 255) { var alpha_ = 255 - alpha; bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8; bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8; bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8; } } } function composeSMaskAlpha(maskData, layerData) { var length = maskData.length; var scale = 1 / 255; for (var i = 3; i < length; i += 4) { var alpha = maskData[i]; layerData[i] = (layerData[i] * alpha * scale) | 0; } } function composeSMaskLuminosity(maskData, layerData) { var length = maskData.length; for (var i = 3; i < length; i += 4) { var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 (maskData[i - 2] * 152) + // * 0.59 .... (maskData[i - 1] * 28); // * 0.11 .... layerData[i] = (layerData[i] * y) >> 16; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop) { var hasBackdrop = !!backdrop; var r0 = hasBackdrop ? backdrop[0] : 0; var g0 = hasBackdrop ? backdrop[1] : 0; var b0 = hasBackdrop ? backdrop[2] : 0; var composeFn; if (subtype === 'Luminosity') { composeFn = composeSMaskLuminosity; } else { composeFn = composeSMaskAlpha; } // processing image in chunks to save memory var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); if (hasBackdrop) { composeSMaskBackdrop(maskData.data, r0, g0, b0); } composeFn(maskData.data, layerData.data); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop = smask.backdrop || null; if (WebGLUtils.isEnabled) { var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {subtype: smask.subtype, backdrop: backdrop}); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) { // For pdfs that use blend modes we have to clear the canvas else certain // blend modes can look wrong since we'd be blending with a white // backdrop. The problem with a transparent backdrop though is we then // don't get sub pixel anti aliasing on text, so we fill with white if // we can. var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; if (transparency) { this.ctx.clearRect(0, 0, width, height); } else { this.ctx.mozOpaque = true; this.ctx.save(); this.ctx.fillStyle = 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); } var transform = viewport.transform; this.ctx.save(); this.ctx.transform.apply(this.ctx, transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList( operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; // Sometimes the OperatorList to execute is empty. if (argsArrayLen === i) { return i; } var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function'); var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; var steps = 0; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; while (true) { if (stepper !== undefined && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId[0] === 'g' && depObjId[1] === '_'; var objsPool = common ? commonObjs : objs; // If the promise isn't resolved yet, add the continueCallback // to the promise and bail out. if (!objsPool.isResolved(depObjId)) { objsPool.get(depObjId, continueCallback); return i; } } } i++; // If the entire operatorList was executed, stop as were done. if (i === argsArrayLen) { return i; } // If the execution took longer then a certain amount of time and // `continueCallback` is specified, interrupt the execution. if (chunkOperations && ++steps > EXECUTION_STEPS) { if (Date.now() > endTime) { continueCallback(); return i; } steps = 0; } // If the operatorList isn't executed completely yet OR the execution // time was short enough, do another execution round. } }, endDrawing: function CanvasGraphics_endDrawing() { this.ctx.restore(); CachedCanvases.clear(); WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, // Graphics state setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { // Maybe if we one day fully support color spaces this will be important // for now we can ignore. // TODO set rendering intent? }, setFlatness: function CanvasGraphics_setFlatness(flatness) { // There's no way to control this with canvas, but we can safely ignore. // TODO set flatness? }, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': if (value && value.name && (value.name !== 'Normal')) { var mode = value.name.replace(/([A-Z])/g, function(c) { return '-' + c.toLowerCase(); } ).substring(1); this.ctx.globalCompositeOperation = mode; if (this.ctx.globalCompositeOperation !== mode) { warn('globalCompositeOperation "' + mode + '" is not supported'); } } else { this.ctx.globalCompositeOperation = 'source-over'; } break; case 'SMask': if (this.current.activeSMask) { this.endSMaskGroup(); } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = CachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); this.current.activeSMask = null; }, restore: function CanvasGraphics_restore() { if (this.stateStack.length !== 0) { if (this.current.activeSMask !== null) { this.endSMaskGroup(); } this.current = this.stateStack.pop(); this.ctx.restore(); this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); this.cachedGetSinglePixelWidth = null; }, // Path constructPath: function CanvasGraphics_constructPath(ops, args) { var ctx = this.ctx; var current = this.current; var x = current.x, y = current.y; for (var i = 0, j = 0, ii = ops.length; i < ii; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } var xw = x + width; var yh = y + height; this.ctx.moveTo(x, y); this.ctx.lineTo(xw, y); this.ctx.lineTo(xw, yh); this.ctx.lineTo(x, yh); this.ctx.lineTo(x, y); this.ctx.closePath(); break; case OPS.moveTo: x = args[j++]; y = args[j++]; ctx.moveTo(x, y); break; case OPS.lineTo: x = args[j++]; y = args[j++]; ctx.lineTo(x, y); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); j += 6; break; case OPS.curveTo2: ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); x = args[j + 2]; y = args[j + 3]; j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); j += 4; break; case OPS.closePath: ctx.closePath(); break; } } current.setCurrentPoint(x, y); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; // Prevent drawing too thin lines by enforcing a minimum line width. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { // for patterns, we transform to pattern space, calculate // the pattern, call stroke, and restore to user space ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var needRestore = false; if (isPatternFill) { ctx.save(); ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.fill(); ctx.mozFillRule = 'nonzero'; } else { try { ctx.fill('evenodd'); } catch (ex) { // shouldn't really happen, but browsers might think differently ctx.fill(); } } this.pendingEOFill = false; } else { ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.textMatrixScale = 1; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { var paths = this.pendingTextPaths; var ctx = this.ctx; if (paths === undefined) { ctx.beginPath(); return; } ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { error('Can\'t find font for ' + fontRefName); } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); // A valid matrix needs all main diagonal elements to be non-zero // This also ensures we bypass FF bugzilla bug #719844. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { warn('Invalid font matrix for font ' + fontRefName); } // The spec for Tf (setFont) says that 'size' specifies the font 'scale', // and in some docs this can be negative (inverted x-y axes). if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.isType3Font) { return; // we don't need ctx.font for Type3 fonts } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; // Some font backends cannot handle fonts below certain size. // Keeping the font at minimal size and using the fontSizeScale to change // the current transformation matrix before the fillText/strokeText. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.textMatrixScale = Math.sqrt(a * a + b * b); this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, paintChar: function CanvasGraphics_paintChar(character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var textRenderingMode = current.textRenderingMode; var fontSize = current.fontSize / current.fontSizeScale; var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { // Checks if anti-aliasing is enabled when scaled text is painted. // On Windows GDI scaled fonts looks bad. var ctx = document.createElement('canvas').getContext('2d'); ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return shadow(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var current = this.current; var font = current.font; if (font.isType3Font) { return this.showType3Text(glyphs); } var fontSize = current.fontSize; if (fontSize === 0) { return; } var ctx = this.ctx; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var defaultVMetrics = font.defaultVMetrics; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (fontDirection > 0) { ctx.scale(textHScale, -1); } else { ctx.scale(textHScale, 1); } var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { this.cachedGetSinglePixelWidth = null; lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; } } else { lineWidth /= scale; } if (fontSizeScale !== 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break x += fontDirection * wordSpacing; continue; } else if (isNum(glyph)) { x += -glyph * fontSize * 0.001; continue; } var restoreNeeded = false; var character = glyph.fontChar; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; var width = glyph.width; if (vertical) { var vmetric, vx, vy; vmetric = glyph.vmetric || defaultVMetrics; vx = glyph.vmetric ? vmetric[1] : width * 0.5; vx = -vx * widthAdvanceScale; vy = vmetric[2] * widthAdvanceScale; width = vmetric ? -vmetric[0] : width; scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) { // some standard fonts may not have the exact width, trying to // rescale per character var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; } if (simpleFillText && !accent) { // common case ctx.fillText(character, scaledX, scaledY); } else { this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } } var charWidth = width * widthAdvanceScale + charSpacing * fontDirection; x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); }, showType3Text: function CanvasGraphics_showType3Text(glyphs) { // Type3 fonts - each glyph is a "mini-PDF" var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontDirection = current.fontDirection; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; var i, glyph, width; if (isTextInvisible || fontSize === 0) { return; } ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, fontDirection); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (glyph === null) { // word break this.ctx.translate(wordSpacing, 0); current.x += wordSpacing * textHScale; continue; } else if (isNum(glyph)) { var spacingLength = -glyph * 0.001 * fontSize; this.ctx.translate(spacingLength, 0); current.x += spacingLength * textHScale; continue; } var operatorList = font.charProcOperatorList[glyph.operatorListId]; if (!operatorList) { warn('Type3 character \"' + glyph.operatorListId + '\" is not available'); continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); width = transformed[0] * fontSize + charSpacing; ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; }, // Type3 fonts setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { // TODO According to the spec we're also suppose to ignore any operators // that set color or include images while processing this type3 font. this.ctx.rect(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, // Color getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) { var pattern; if (IR[0] === 'TilingPattern') { var color = IR[1]; pattern = new TilingPattern(IR, color, this.ctx, this.objs, this.commonObjs, this.baseTransform); } else { pattern = getShadingPatternFromIR(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { this.current.strokeColor = this.getColorN_Pattern(arguments); }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { this.current.fillColor = this.getColorN_Pattern(arguments); this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = getShadingPatternFromIR(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); var br = Util.applyTransform([0, height], inv); var ul = Util.applyTransform([width, 0], inv); var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { // HACK to draw the gradient onto an infinite rectangle. // PDF gradients are drawn across the entire image while // Canvas only allows gradients to be drawn in a rectangle // The following bug should allow us to remove this. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, // Images beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (isArray(matrix) && 6 === matrix.length) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (isArray(bbox) && 4 === bbox.length) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.ctx.rect(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; // TODO non-isolated groups - according to Rik at adobe non-isolated // group results aren't usually that different and they even have tools // that ignore this setting. Notes from Rik on implmenting: // - When you encounter an transparency group, create a new canvas with // the dimensions of the bbox // - copy the content from the previous canvas to the new canvas // - draw as usual // - remove the backdrop alpha: // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha // value of your transparency group and 'alphaBackdrop' the alpha of the // backdrop // - remove background color: // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew) if (!group.isolated) { info('TODO: Support non-isolated groups.'); } // TODO knockout - supposedly possible with the clever use of compositing // modes. if (group.knockout) { warn('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } assert(group.bbox, 'Bounding box is required.'); // Based on the current transform figure out how big the bounding box // will actually be. var bounds = Util.getAxialAlignedBoundingBox( group.bbox, currentCtx.mozCurrentTransform); // Clip the bounding box to the current canvas. var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; // Use ceil in case we're between sizes so we don't create canvas that is // too small and make the canvas at least 1x1 pixels. var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { // Using two cache entries is case if masks are used one after another. cacheId += '_smask_' + ((this.smaskCounter++) % 2); } var scratchCanvas = CachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; // Since we created a new canvas that is just the size of the bounding box // we have to translate the group ctx. groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { // Saving state and cached mask to be used in setGState. this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop }); } else { // Setup the current ctx so when the group is popped we draw it at the // right location. currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } // The transparency group inherits all off the current graphics state // except the blend mode, soft mask, and alpha constants. copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); // Turn off image smoothing to avoid sub pixel interpolation which can // look kind of blurry for some pdfs. if (this.ctx.imageSmoothingEnabled !== undefined) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); this.current = new CanvasExtraState(); }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); if (isArray(rect) && 4 === rect.length) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.ctx.rect(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { warn('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; // scale the image to the unit square ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height}); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); // scale the image to the unit square ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; // instanceof HTMLElement does not work in jsdom node.js module if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; // Vertial or horizontal scaling shall not be more than 2 to not loose the // pixels during drawImage operation, painting on the temporary canvas(es) // that are twice smaller in size while ((widthScale > 2 && paintWidth > 1) || (heightScale > 2 && paintHeight > 1)) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, // Marked content markPoint: function CanvasGraphics_markPoint(tag) { // TODO Marked content. }, markPointProps: function CanvasGraphics_markPointProps(tag, properties) { // TODO Marked content. }, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { // TODO Marked content. }, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( tag, properties) { // TODO Marked content. }, endMarkedContent: function CanvasGraphics_endMarkedContent() { // TODO Marked content. }, // Compatibility beginCompat: function CanvasGraphics_beginCompat() { // TODO ignore undefined operators (should we do that anyway?) }, endCompat: function CanvasGraphics_endCompat() { // TODO stop ignoring undefined operators }, // Helper functions consumePath: function CanvasGraphics_consumePath() { var ctx = this.ctx; if (this.pendingClip) { if (this.pendingClip === EO_CLIP) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.clip(); ctx.mozFillRule = 'nonzero'; } else { try { ctx.clip('evenodd'); } catch (ex) { // shouldn't really happen, but browsers might think differently ctx.clip(); } } } else { ctx.clip(); } this.pendingClip = null; } ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { if (this.cachedGetSinglePixelWidth === null) { var inverse = this.ctx.mozCurrentTransformInverse; // max of the current horizontal and vertical scale this.cachedGetSinglePixelWidth = Math.sqrt(Math.max( (inverse[0] * inverse[0] + inverse[1] * inverse[1]), (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); } return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [ transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5] ]; } }; for (var op in OPS) { CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; })(); var WebGLUtils = (function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generateGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache,canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); // Create a textures var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); // count triangle points var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } // transfer data var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = (ps.length / cols) | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[i]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } // draw if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { if (smaskCache && smaskCache.canvas) { smaskCache.canvas.width = 0; smaskCache.canvas.height = 0; } if (figuresCache && figuresCache.canvas) { figuresCache.canvas.width = 0; figuresCache.canvas.height = 0; } smaskCache = null; figuresCache = null; } return { get isEnabled() { if (PDFJS.disableWebGL) { return false; } var enabled = false; try { generateGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; })(); var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = (function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { // Very basic Gouraud-shaded triangle rasterization algorithm. var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = (car - (car - cbr) * k) | 0; bytes[j++] = (cag - (cag - cbg) * k) | 0; bytes[j++] = (cab - (cab - cbb) * k) | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: error('illigal figure'); break; } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor) { // we will increase scale on some weird factor to let antialiasing take // care of "rough" edges var EXPECTED_SCALE = 1.1; // MAX_PATTERN_SIZE is used to avoid OOM situation. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var canvas, tmpCanvas, i, ii; if (WebGLUtils.isEnabled) { canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); // https://bugzilla.mozilla.org/show_bug.cgi?id=972126 tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false); tmpCanvas.context.drawImage(canvas, 0, 0); canvas = tmpCanvas.canvas; } else { tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, 0, 0); canvas = tmpCanvas.canvas; } return {canvas: canvas, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY}; } return createMeshCanvas; })(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { //var type = raw[1]; var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; //var bbox = raw[7]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var scale; if (shadingFill) { scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); } else { // Obtain scale from matrix and current transformation matrix. scale = Util.singularValueDecompose2dScale(owner.baseTransform); if (matrix) { var matrixScale = Util.singularValueDecompose2dScale(matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } // Rasterizing on the main thread since sending/queue large canvases // might cause OOM. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = (function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) { this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.objs = objs; this.commonObjs = commonObjs; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var objs = this.objs; var commonObjs = this.commonObjs; info('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; // we want the canvas to be as large as the step size var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; // Obtain scale from matrix and current transformation matrix. var matrixScale = Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = Util.singularValueDecompose2dScale( this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; // MAX_PATTERN_SIZE is used to avoid OOM situation. // Use width and height values that are as close as possible to the end // result when the pattern is used. Too low value makes the pattern look // blurry. Too large value makes it look too crispy. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); // transform coordinates to pattern space var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (bbox && isArray(bbox) && bbox.length === 4) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) { switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: var cssColor = Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; })(); PDFJS.disableFontFace = false; var FontLoader = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG'); if (!styleElement) { styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG'; document.documentElement.getElementsByTagName('head')[0].appendChild( styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG'); if (styleElement) { styleElement.parentNode.removeChild(styleElement); } this.nativeFontFaces.forEach(function(nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and // height. return shadow(this, 'loadTestFont', atob( 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==' )); }, loadTestFontId: 0, loadingContext: { requests: [], nextRequestId: 0 }, isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() { if (isWorker) { return false; } // User agent string sniffing is bad, but there is no reliable way to tell // if font is fully loaded and ready to be used with canvas. var userAgent = window.navigator.userAgent; var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent); if (m && m[1] >= 14) { return true; } // TODO other browsers if (userAgent === 'node') { return true; } return false; })(), nativeFontFaces: [], isFontLoadingAPISupported: !isWorker && !!document.fonts, addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) { this.nativeFontFaces.push(nativeFontFace); document.fonts.add(nativeFontFace); }, bind: function fontLoaderBind(fonts, callback) { assert(!isWorker, 'bind() shall be called from main thread'); var rules = []; var fontsToLoad = []; var fontLoadPromises = []; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; // Add the font to the DOM only once or skip if the font // is already loaded. if (font.attached || font.loading === false) { continue; } font.attached = true; if (this.isFontLoadingAPISupported) { var nativeFontFace = font.createNativeFontFace(); if (nativeFontFace) { fontLoadPromises.push(nativeFontFace.loaded); } } else { var rule = font.bindDOM(); if (rule) { rules.push(rule); fontsToLoad.push(font); } } } var request = FontLoader.queueLoadingCallback(callback); if (this.isFontLoadingAPISupported) { Promise.all(fontsToLoad).then(function() { request.complete(); }); } else if (rules.length > 0 && !this.isSyncFontLoadingSupported) { FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }, queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { assert(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); // sending all completed requests in order how they were queued while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = FontLoader.loadingContext; var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++); var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }, prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { /** Hack begin */ // There's currently no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is // ready. It's assumed fonts are loaded in order, so add a known test // font after the desired fonts and then test for the loading of that // test font. function int32(data, offset) { return (data.charCodeAt(offset) << 24) | (data.charCodeAt(offset + 1) << 16) | (data.charCodeAt(offset + 2) << 8) | (data.charCodeAt(offset + 3) & 0xff); } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; // With setTimeout clamping this gives the font ~100ms to load. if(called > 30) { warn('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; // Chromium seems to cache fonts based on a hash of the actual font data, // so the font must be modified for each load test else it will appear to // be loaded already. // TODO: This could maybe be made faster by avoiding the btoa of the full // font by splitting it in chunks before hand and padding the font id. var data = this.loadTestFont; var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum) data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); // CFF checksum is important for IE, adjusting it var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X' var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0; } if (i < loadTestFontId.length) { // align to 4 bytes boundary checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i)) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; FontLoader.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function() { document.body.removeChild(div); request.complete(); }); /** Hack end */ } }; var FontFaceObject = (function FontFaceObjectClosure() { function FontFaceObject(name, file, properties) { this.compiledGlyphs = {}; if (arguments.length === 1) { // importing translated data var data = arguments[0]; for (var i in data) { this[i] = data[i]; } return; } } FontFaceObject.prototype = { createNativeFontFace: function FontFaceObject_createNativeFontFace() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var nativeFontFace = new FontFace(this.loadedName, this.data, {}); FontLoader.addNativeFontFace(nativeFontFace); if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this); } return nativeFontFace; }, bindDOM: function FontFaceObject_bindDOM() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var data = bytesToString(new Uint8Array(this.data)); var fontName = this.loadedName; // Add the font-face rule to the document var url = ('url(data:' + this.mimetype + ';base64,' + window.btoa(data) + ');'); var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; FontLoader.insertRule(rule); if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this, url); } return rule; }, getPathGenerator: function FontLoader_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var js = objs.get(this.loadedName + '_path_' + character); /*jshint -W054 */ this.compiledGlyphs[character] = new Function('c', 'size', js); } return this.compiledGlyphs[character]; } }; return FontFaceObject; })(); var ANNOT_MIN_SIZE = 10; // px var AnnotationUtils = (function AnnotationUtilsClosure() { // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont() function setTextStyles(element, item, fontObj) { var style = element.style; style.fontSize = item.fontSize + 'px'; style.direction = item.fontDirection < 0 ? 'rtl': 'ltr'; if (!fontObj) { return; } style.fontWeight = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); style.fontStyle = fontObj.italic ? 'italic' : 'normal'; var fontName = fontObj.loadedName; var fontFamily = fontName ? '"' + fontName + '", ' : ''; // Use a reasonable default font if the font doesn't specify a fallback var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } function initContainer(item, drawBorder) { var container = document.createElement('section'); var cstyle = container.style; var width = item.rect[2] - item.rect[0]; var height = item.rect[3] - item.rect[1]; var bWidth = item.borderWidth || 0; if (bWidth) { width = width - 2 * bWidth; height = height - 2 * bWidth; cstyle.borderWidth = bWidth + 'px'; var color = item.color; if (drawBorder && color) { cstyle.borderStyle = 'solid'; cstyle.borderColor = Util.makeCssRgb(Math.round(color[0] * 255), Math.round(color[1] * 255), Math.round(color[2] * 255)); } } cstyle.width = width + 'px'; cstyle.height = height + 'px'; return container; } function getHtmlElementForTextWidgetAnnotation(item, commonObjs) { var element = document.createElement('div'); var width = item.rect[2] - item.rect[0]; var height = item.rect[3] - item.rect[1]; element.style.width = width + 'px'; element.style.height = height + 'px'; element.style.display = 'table'; var content = document.createElement('div'); content.textContent = item.fieldValue; var textAlignment = item.textAlignment; content.style.textAlign = ['left', 'center', 'right'][textAlignment]; content.style.verticalAlign = 'middle'; content.style.display = 'table-cell'; var fontObj = item.fontRefName ? commonObjs.getData(item.fontRefName) : null; setTextStyles(content, item, fontObj); element.appendChild(content); return element; } function getHtmlElementForTextAnnotation(item) { var rect = item.rect; // sanity check because of OOo-generated PDFs if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) { rect[3] = rect[1] + ANNOT_MIN_SIZE; } if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) { rect[2] = rect[0] + (rect[3] - rect[1]); // make it square } var container = initContainer(item, false); container.className = 'annotText'; var image = document.createElement('img'); image.style.height = container.style.height; image.style.width = container.style.width; var iconName = item.name; image.src = PDFJS.imageResourcesPath + 'annotation-' + iconName.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({type: iconName}); var contentWrapper = document.createElement('div'); contentWrapper.className = 'annotTextContentWrapper'; contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px'; contentWrapper.style.top = '-10px'; var content = document.createElement('div'); content.className = 'annotTextContent'; content.setAttribute('hidden', true); var i, ii; if (item.hasBgColor) { var color = item.color; // Enlighten the color (70%) var BACKGROUND_ENLIGHT = 0.7; var r = BACKGROUND_ENLIGHT * (1.0 - color[0]) + color[0]; var g = BACKGROUND_ENLIGHT * (1.0 - color[1]) + color[1]; var b = BACKGROUND_ENLIGHT * (1.0 - color[2]) + color[2]; content.style.backgroundColor = Util.makeCssRgb((r * 255) | 0, (g * 255) | 0, (b * 255) | 0); } var title = document.createElement('h1'); var text = document.createElement('p'); title.textContent = item.title; if (!item.content && !item.title) { content.setAttribute('hidden', true); } else { var e = document.createElement('span'); var lines = item.content.split(/(?:\r\n?|\n)/); for (i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; e.appendChild(document.createTextNode(line)); if (i < (ii - 1)) { e.appendChild(document.createElement('br')); } } text.appendChild(e); var pinned = false; var showAnnotation = function showAnnotation(pin) { if (pin) { pinned = true; } if (content.hasAttribute('hidden')) { container.style.zIndex += 1; content.removeAttribute('hidden'); } }; var hideAnnotation = function hideAnnotation(unpin) { if (unpin) { pinned = false; } if (!content.hasAttribute('hidden') && !pinned) { container.style.zIndex -= 1; content.setAttribute('hidden', true); } }; var toggleAnnotation = function toggleAnnotation() { if (pinned) { hideAnnotation(true); } else { showAnnotation(true); } }; image.addEventListener('click', function image_clickHandler() { toggleAnnotation(); }, false); image.addEventListener('mouseover', function image_mouseOverHandler() { showAnnotation(); }, false); image.addEventListener('mouseout', function image_mouseOutHandler() { hideAnnotation(); }, false); content.addEventListener('click', function content_clickHandler() { hideAnnotation(true); }, false); } content.appendChild(title); content.appendChild(text); contentWrapper.appendChild(content); container.appendChild(image); container.appendChild(contentWrapper); return container; } function getHtmlElementForLinkAnnotation(item) { var container = initContainer(item, true); container.className = 'annotLink'; var link = document.createElement('a'); link.href = link.title = item.url || ''; if (item.url && PDFJS.openExternalLinksInNewWindow) { link.target = '_blank'; } container.appendChild(link); return container; } function getHtmlElement(data, objs) { switch (data.annotationType) { case AnnotationType.WIDGET: return getHtmlElementForTextWidgetAnnotation(data, objs); case AnnotationType.TEXT: return getHtmlElementForTextAnnotation(data); case AnnotationType.LINK: return getHtmlElementForLinkAnnotation(data); default: throw new Error('Unsupported annotationType: ' + data.annotationType); } } return { getHtmlElement: getHtmlElement }; })(); PDFJS.AnnotationUtils = AnnotationUtils; var SVG_DEFAULTS = { fontStyle: 'normal', fontWeight: 'normal', fillColor: '#000000' }; var convertImgDataToPng = (function convertImgDataToPngClosure() { var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); var CHUNK_WRAPPER_SIZE = 12; var crcTable = new Int32Array(256); for (var i = 0; i < 256; i++) { var c = i; for (var h = 0; h < 8; h++) { if (c & 1) { c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff); } else { c = (c >> 1) & 0x7fffffff; } } crcTable[i] = c; } function crc32(data, start, end) { var crc = -1; for (var i = start; i < end; i++) { var a = (crc ^ data[i]) & 0xff; var b = crcTable[a]; crc = (crc >>> 8) ^ b; } return crc ^ -1; } function writePngChunk(type, body, data, offset) { var p = offset; var len = body.length; data[p] = len >> 24 & 0xff; data[p + 1] = len >> 16 & 0xff; data[p + 2] = len >> 8 & 0xff; data[p + 3] = len & 0xff; p += 4; data[p] = type.charCodeAt(0) & 0xff; data[p + 1] = type.charCodeAt(1) & 0xff; data[p + 2] = type.charCodeAt(2) & 0xff; data[p + 3] = type.charCodeAt(3) & 0xff; p += 4; data.set(body, p); p += body.length; var crc = crc32(data, offset + 4, p); data[p] = crc >> 24 & 0xff; data[p + 1] = crc >> 16 & 0xff; data[p + 2] = crc >> 8 & 0xff; data[p + 3] = crc & 0xff; } function adler32(data, start, end) { var a = 1; var b = 0; for (var i = start; i < end; ++i) { a = (a + (data[i] & 0xff)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } function encode(imgData, kind) { var width = imgData.width; var height = imgData.height; var bitDepth, colorType, lineSize; var bytes = imgData.data; switch (kind) { case ImageKind.GRAYSCALE_1BPP: colorType = 0; bitDepth = 1; lineSize = (width + 7) >> 3; break; case ImageKind.RGB_24BPP: colorType = 2; bitDepth = 8; lineSize = width * 3; break; case ImageKind.RGBA_32BPP: colorType = 6; bitDepth = 8; lineSize = width * 4; break; default: throw new Error('invalid format'); } // prefix every row with predictor 0 var literals = new Uint8Array((1 + lineSize) * height); var offsetLiterals = 0, offsetBytes = 0; var y, i; for (y = 0; y < height; ++y) { literals[offsetLiterals++] = 0; // no prediction literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); offsetBytes += lineSize; offsetLiterals += lineSize; } if (kind === ImageKind.GRAYSCALE_1BPP) { // inverting for B/W offsetLiterals = 0; for (y = 0; y < height; y++) { offsetLiterals++; // skipping predictor for (i = 0; i < lineSize; i++) { literals[offsetLiterals++] ^= 0xFF; } } } var ihdr = new Uint8Array([ width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, // bit depth colorType, // color type 0x00, // compression method 0x00, // filter method 0x00 // interlace method ]); var len = literals.length; var maxBlockLength = 0xFFFF; var deflateBlocks = Math.ceil(len / maxBlockLength); var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); var pi = 0; idat[pi++] = 0x78; // compression method and flags idat[pi++] = 0x9c; // flags var pos = 0; while (len > maxBlockLength) { // writing non-final DEFLATE blocks type 0 and length of 65535 idat[pi++] = 0x00; idat[pi++] = 0xff; idat[pi++] = 0xff; idat[pi++] = 0x00; idat[pi++] = 0x00; idat.set(literals.subarray(pos, pos + maxBlockLength), pi); pi += maxBlockLength; pos += maxBlockLength; len -= maxBlockLength; } // writing non-final DEFLATE blocks type 0 idat[pi++] = 0x01; idat[pi++] = len & 0xff; idat[pi++] = len >> 8 & 0xff; idat[pi++] = (~len & 0xffff) & 0xff; idat[pi++] = (~len & 0xffff) >> 8 & 0xff; idat.set(literals.subarray(pos), pi); pi += literals.length - pos; var adler = adler32(literals, 0, literals.length); // checksum idat[pi++] = adler >> 24 & 0xff; idat[pi++] = adler >> 16 & 0xff; idat[pi++] = adler >> 8 & 0xff; idat[pi++] = adler & 0xff; // PNG will consists: header, IHDR+data, IDAT+data, and IEND. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + ihdr.length + idat.length; var data = new Uint8Array(pngLength); var offset = 0; data.set(PNG_HEADER, offset); offset += PNG_HEADER.length; writePngChunk('IHDR', ihdr, data, offset); offset += CHUNK_WRAPPER_SIZE + ihdr.length; writePngChunk('IDATA', idat, data, offset); offset += CHUNK_WRAPPER_SIZE + idat.length; writePngChunk('IEND', new Uint8Array(0), data, offset); return PDFJS.createObjectURL(data, 'image/png'); } return function convertImgDataToPng(imgData) { var kind = (imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind); return encode(imgData, kind); }; })(); var SVGExtraState = (function SVGExtraStateClosure() { function SVGExtraState() { this.fontSizeScale = 1; this.fontWeight = SVG_DEFAULTS.fontWeight; this.fontSize = 0; this.textMatrix = IDENTITY_MATRIX; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRise = 0; // Default foreground and background colors this.fillColor = SVG_DEFAULTS.fillColor; this.strokeColor = '#000000'; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.lineJoin = ''; this.lineCap = ''; this.miterLimit = 0; this.dashArray = []; this.dashPhase = 0; this.dependencies = []; // Clipping this.clipId = ''; this.pendingClip = false; this.maskId = ''; } SVGExtraState.prototype = { clone: function SVGExtraState_clone() { return Object.create(this); }, setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return SVGExtraState; })(); var SVGGraphics = (function SVGGraphicsClosure() { function createScratchSVG(width, height) { var NS = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(NS, 'svg:svg'); svg.setAttributeNS(null, 'version', '1.1'); svg.setAttributeNS(null, 'width', width + 'px'); svg.setAttributeNS(null, 'height', height + 'px'); svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height); return svg; } function opListToTree(opList) { var opTree = []; var tmp = []; var opListLen = opList.length; for (var x = 0; x < opListLen; x++) { if (opList[x].fn === 'save') { opTree.push({'fnId': 92, 'fn': 'group', 'items': []}); tmp.push(opTree); opTree = opTree[opTree.length - 1].items; continue; } if(opList[x].fn === 'restore') { opTree = tmp.pop(); } else { opTree.push(opList[x]); } } return opTree; } /** * Formats float number. * @param value {number} number to format. * @returns {string} */ function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); } /** * Formats transform matrix. The standard rotation, scale and translate * matrices are replaced by their shorter forms, and for identity matrix * returns empty string to save the memory. * @param m {Array} matrix to format. * @returns {string} */ function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } function SVGGraphics(commonObjs, objs) { this.current = new SVGExtraState(); this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix this.transformStack = []; this.extraStack = []; this.commonObjs = commonObjs; this.objs = objs; this.pendingEOFill = false; this.embedFonts = false; this.embeddedFonts = {}; this.cssStyle = null; } var NS = 'http://www.w3.org/2000/svg'; var XML_NS = 'http://www.w3.org/XML/1998/namespace'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var clipCount = 0; var maskCount = 0; SVGGraphics.prototype = { save: function SVGGraphics_save() { this.transformStack.push(this.transformMatrix); var old = this.current; this.extraStack.push(old); this.current = old.clone(); }, restore: function SVGGraphics_restore() { this.transformMatrix = this.transformStack.pop(); this.current = this.extraStack.pop(); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.pgrp.appendChild(this.tgrp); }, group: function SVGGraphics_group(items) { this.save(); this.executeOpTree(items); this.restore(); }, loadDependencies: function SVGGraphics_loadDependencies(operatorList) { var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var argsArray = operatorList.argsArray; var self = this; for (var i = 0; i < fnArrayLen; i++) { if (OPS.dependency === fnArray[i]) { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var obj = deps[n]; var common = obj.substring(0, 2) === 'g_'; var promise; if (common) { promise = new Promise(function(resolve) { self.commonObjs.get(obj, resolve); }); } else { promise = new Promise(function(resolve) { self.objs.get(obj, resolve); }); } this.current.dependencies.push(promise); } } } return Promise.all(this.current.dependencies); }, transform: function SVGGraphics_transform(a, b, c, d, e, f) { var transformMatrix = [a, b, c, d, e, f]; this.transformMatrix = PDFJS.Util.transform(this.transformMatrix, transformMatrix); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, getSVG: function SVGGraphics_getSVG(operatorList, viewport) { this.svg = createScratchSVG(viewport.width, viewport.height); this.viewport = viewport; return this.loadDependencies(operatorList).then(function () { this.transformMatrix = IDENTITY_MATRIX; this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform)); this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.defs = document.createElementNS(NS, 'svg:defs'); this.pgrp.appendChild(this.defs); this.pgrp.appendChild(this.tgrp); this.svg.appendChild(this.pgrp); var opTree = this.convertOpList(operatorList); this.executeOpTree(opTree); return this.svg; }.bind(this)); }, convertOpList: function SVGGraphics_convertOpList(operatorList) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var REVOPS = []; var opList = []; for (var op in OPS) { REVOPS[OPS[op]] = op; } for (var x = 0; x < fnArrayLen; x++) { var fnId = fnArray[x]; opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]}); } return opListToTree(opList); }, executeOpTree: function SVGGraphics_executeOpTree(opTree) { var opTreeLen = opTree.length; for(var x = 0; x < opTreeLen; x++) { var fn = opTree[x].fn; var fnId = opTree[x].fnId; var args = opTree[x].args; switch (fnId | 0) { case OPS.beginText: this.beginText(); break; case OPS.setLeading: this.setLeading(args); break; case OPS.setLeadingMoveText: this.setLeadingMoveText(args[0], args[1]); break; case OPS.setFont: this.setFont(args); break; case OPS.showText: this.showText(args[0]); break; case OPS.showSpacedText: this.showText(args[0]); break; case OPS.endText: this.endText(); break; case OPS.moveText: this.moveText(args[0], args[1]); break; case OPS.setCharSpacing: this.setCharSpacing(args[0]); break; case OPS.setWordSpacing: this.setWordSpacing(args[0]); break; case OPS.setTextMatrix: this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.setLineWidth: this.setLineWidth(args[0]); break; case OPS.setLineJoin: this.setLineJoin(args[0]); break; case OPS.setLineCap: this.setLineCap(args[0]); break; case OPS.setMiterLimit: this.setMiterLimit(args[0]); break; case OPS.setFillRGBColor: this.setFillRGBColor(args[0], args[1], args[2]); break; case OPS.setStrokeRGBColor: this.setStrokeRGBColor(args[0], args[1], args[2]); break; case OPS.setDash: this.setDash(args[0], args[1]); break; case OPS.setGState: this.setGState(args[0]); break; case OPS.fill: this.fill(); break; case OPS.eoFill: this.eoFill(); break; case OPS.stroke: this.stroke(); break; case OPS.fillStroke: this.fillStroke(); break; case OPS.eoFillStroke: this.eoFillStroke(); break; case OPS.clip: this.clip('nonzero'); break; case OPS.eoClip: this.clip('evenodd'); break; case OPS.paintSolidColorImageMask: this.paintSolidColorImageMask(); break; case OPS.paintJpegXObject: this.paintJpegXObject(args[0], args[1], args[2]); break; case OPS.paintImageXObject: this.paintImageXObject(args[0]); break; case OPS.paintInlineImageXObject: this.paintInlineImageXObject(args[0]); break; case OPS.paintImageMaskXObject: this.paintImageMaskXObject(args[0]); break; case OPS.paintFormXObjectBegin: this.paintFormXObjectBegin(args[0], args[1]); break; case OPS.paintFormXObjectEnd: this.paintFormXObjectEnd(); break; case OPS.closePath: this.closePath(); break; case OPS.closeStroke: this.closeStroke(); break; case OPS.closeFillStroke: this.closeFillStroke(); break; case OPS.nextLine: this.nextLine(); break; case OPS.transform: this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.constructPath: this.constructPath(args[0], args[1]); break; case OPS.endPath: this.endPath(); break; case 92: this.group(opTree[x].items); break; default: warn('Unimplemented method '+ fn); break; } } }, setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { this.current.wordSpacing = wordSpacing; }, setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { this.current.charSpacing = charSpacing; }, nextLine: function SVGGraphics_nextLine() { this.moveText(0, this.current.leading); }, setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { var current = this.current; this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.txtElement = document.createElementNS(NS, 'svg:text'); current.txtElement.appendChild(current.tspan); }, beginText: function SVGGraphics_beginText() { this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; this.current.textMatrix = IDENTITY_MATRIX; this.current.lineMatrix = IDENTITY_MATRIX; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.txtElement = document.createElementNS(NS, 'svg:text'); this.current.txtgrp = document.createElementNS(NS, 'svg:g'); this.current.xcoords = []; }, moveText: function SVGGraphics_moveText(x, y) { var current = this.current; this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); }, showText: function SVGGraphics_showText(glyphs) { var current = this.current; var font = current.font; var fontSize = current.fontSize; if (fontSize === 0) { return; } var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break x += fontDirection * wordSpacing; continue; } else if (isNum(glyph)) { x += -glyph * fontSize * 0.001; continue; } current.xcoords.push(current.x + x * textHScale); var width = glyph.width; var character = glyph.fontChar; var charWidth = width * widthAdvanceScale + charSpacing * fontDirection; x += charWidth; current.tspan.textContent += character; } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' ')); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); } if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); } if (current.fillColor !== SVG_DEFAULTS.fillColor) { current.tspan.setAttributeNS(null, 'fill', current.fillColor); } current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)' ); current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); current.txtElement.appendChild(current.tspan); current.txtgrp.appendChild(current.txtElement); this.tgrp.appendChild(current.txtElement); }, setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, addFontStyle: function SVGGraphics_addFontStyle(fontObj) { if (!this.cssStyle) { this.cssStyle = document.createElementNS(NS, 'svg:style'); this.cssStyle.setAttributeNS(null, 'type', 'text/css'); this.defs.appendChild(this.cssStyle); } var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype); this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n'; }, setFont: function SVGGraphics_setFont(details) { var current = this.current; var fontObj = this.commonObjs.get(details[0]); var size = details[1]; this.current.font = fontObj; if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) { this.addFontStyle(fontObj); this.embeddedFonts[fontObj.loadedName] = fontObj; } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } current.fontSize = size; current.fontFamily = fontObj.loadedName; current.fontWeight = bold; current.fontStyle = italic; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.xcoords = []; }, endText: function SVGGraphics_endText() { if (this.current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, // Path properties setLineWidth: function SVGGraphics_setLineWidth(width) { this.current.lineWidth = width; }, setLineCap: function SVGGraphics_setLineCap(style) { this.current.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function SVGGraphics_setLineJoin(style) { this.current.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function SVGGraphics_setMiterLimit(limit) { this.current.miterLimit = limit; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.xcoords = []; }, setDash: function SVGGraphics_setDash(dashArray, dashPhase) { this.current.dashArray = dashArray; this.current.dashPhase = dashPhase; }, constructPath: function SVGGraphics_constructPath(ops, args) { var current = this.current; var x = current.x, y = current.y; current.path = document.createElementNS(NS, 'svg:path'); var d = []; var opLength = ops.length; for (var i = 0, j = 0; i < opLength; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; var xw = x + width; var yh = y + height; d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z'); break; case OPS.moveTo: x = args[j++]; y = args[j++]; d.push('M', pf(x), pf(y)); break; case OPS.lineTo: x = args[j++]; y = args[j++]; d.push('L', pf(x) , pf(y)); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); j += 6; break; case OPS.curveTo2: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); j += 4; break; case OPS.closePath: d.push('Z'); break; } } current.path.setAttributeNS(null, 'd', d.join(' ')); current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap); current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px'); current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' ')); current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px'); current.path.setAttributeNS(null, 'fill', 'none'); this.tgrp.appendChild(current.path); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } // Saving a reference in current.element so that it can be addressed // in 'fill' and 'stroke' current.element = current.path; current.setCurrentPoint(x, y); }, endPath: function SVGGraphics_endPath() { var current = this.current; if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, clip: function SVGGraphics_clip(type) { var current = this.current; // Add current path to clipping path current.clipId = 'clippath' + clipCount; clipCount++; this.clippath = document.createElementNS(NS, 'svg:clipPath'); this.clippath.setAttributeNS(null, 'id', current.clipId); var clipElement = current.element.cloneNode(); if (type === 'evenodd') { clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); } else { clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); } this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.clippath.appendChild(clipElement); this.defs.appendChild(this.clippath); // Create a new group with that attribute current.pendingClip = true; this.cgrp = document.createElementNS(NS, 'svg:g'); this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')'); this.pgrp.appendChild(this.cgrp); }, closePath: function SVGGraphics_closePath() { var current = this.current; var d = current.path.getAttributeNS(null, 'd'); d += 'Z'; current.path.setAttributeNS(null, 'd', d); }, setLeading: function SVGGraphics_setLeading(leading) { this.current.leading = -leading; }, setTextRise: function SVGGraphics_setTextRise(textRise) { this.current.textRise = textRise; }, setHScale: function SVGGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setGState: function SVGGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': break; case 'FL': break; case 'Font': this.setFont(value); break; case 'CA': break; case 'ca': break; case 'BM': break; case 'SMask': break; } } }, fill: function SVGGraphics_fill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); }, stroke: function SVGGraphics_stroke() { var current = this.current; current.element.setAttributeNS(null, 'stroke', current.strokeColor); current.element.setAttributeNS(null, 'fill', 'none'); }, eoFill: function SVGGraphics_eoFill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); }, fillStroke: function SVGGraphics_fillStroke() { // Order is important since stroke wants fill to be none. // First stroke, then if fill needed, it will be overwritten. this.stroke(); this.fill(); }, eoFillStroke: function SVGGraphics_eoFillStroke() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fillStroke(); }, closeStroke: function SVGGraphics_closeStroke() { this.closePath(); this.stroke(); }, closeFillStroke: function SVGGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() { var current = this.current; var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', '1px'); rect.setAttributeNS(null, 'height', '1px'); rect.setAttributeNS(null, 'fill', current.fillColor); this.tgrp.appendChild(rect); }, paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { var current = this.current; var imgObj = this.objs.get(objId); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); imgEl.setAttributeNS(null, 'width', imgObj.width + 'px'); imgEl.setAttributeNS(null, 'height', imgObj.height + 'px'); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-h)); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); this.tgrp.appendChild(imgEl); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageXObject: function SVGGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) { var current = this.current; var width = imgData.width; var height = imgData.height; var imgSrc = convertImgDataToPng(imgData); var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', '0'); cliprect.setAttributeNS(null, 'y', '0'); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); current.element = cliprect; this.clip('nonzero'); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-height)); imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')'); if (mask) { mask.appendChild(imgEl); } else { this.tgrp.appendChild(imgEl); } if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) { var current = this.current; var width = imgData.width; var height = imgData.height; var fillColor = current.fillColor; current.maskId = 'mask' + maskCount++; var mask = document.createElementNS(NS, 'svg:mask'); mask.setAttributeNS(null, 'id', current.maskId); var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', pf(width)); rect.setAttributeNS(null, 'height', pf(height)); rect.setAttributeNS(null, 'fill', fillColor); rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')'); this.defs.appendChild(mask); this.tgrp.appendChild(rect); this.paintInlineImageXObject(imgData, mask); }, paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); if (isArray(matrix) && matrix.length === 6) { this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } if (isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', bbox[0]); cliprect.setAttributeNS(null, 'y', bbox[1]); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); this.endPath(); } }, paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() { this.restore(); } }; return SVGGraphics; })(); PDFJS.SVGGraphics = SVGGraphics; }).call((typeof window === 'undefined') ? this : window); if (!PDFJS.workerSrc && typeof document !== 'undefined') { // workerSrc is not set -- using last script url to define default location PDFJS.workerSrc = (function () { 'use strict'; var scriptTagContainer = document.body || document.getElementsByTagName('head')[0]; var pdfjsSrc = scriptTagContainer.lastChild.src; return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js'); })(); }
var Skeleton = (function() { /********* Model *********/ function Model(attributes) { // Make sure initialized if(!(this instanceof Model)) { return new Model(attributes); } if(!(attributes && attributes.defaults)) { throw new Error('A "defaults" field must be passed'); } // model class function model(options) { let _attrs = Object.assign({}, attributes.defaults) || {}; this.get = function(attr) { return _attrs[attr] || null; } this.set = function() { if(arguments.length === 2) { _attrs[arguments[0]] = arguments[1]; } else if(arguments.length === 1) { let obj = arguments[0]; for(let key in obj) { _attrs[key] = obj[key]; } } else { throw new Error('Error on setting a value'); } } // get json representation of the model this.toJSON = function() { return _attrs; } // set attributes for(let opt in options) { this.set(opt, options[opt]); } // call init if(attributes && attributes.init) { attributes.init.call(this); } } // set additional methods to model for(let attr in attributes) { if(attr !== 'init' && attr !== 'defaults') { model.prototype[attr] = attributes[attr]; } } return model; } /********** View **********/ function List(attributes) { // Make sure initialized if(!(this instanceof List)) { return new List(attributes); } const re = /{{\s*((\w+\.?\w+?)*\s*\|?\s*\w+)\s*}}/g; const re_loop = /{{\s*#\s*((\w+\.?\w+?)*\s*\|?\s*\w+)\s*}}/g; let _index = 0; let _listeners = { // Each array contains functions to run push: [], remove: [], filter: [], sort: [], pushAll: [], removeAll: [], edit: [] }; let _customFilters = { upper(txt) { return txt.toUpperCase(); }, lower(txt) { return txt.toLowerCase(); }, capitalize(txt) { return txt.charAt(0).toUpperCase() + txt.slice(1).toLowerCase(); }, currency(txt) { return '$' + txt; }, json(txt) { try { txt = JSON.stringify(txt); } catch(e) { throw new Error('The argument passed can not be stringified to a json string'); } return txt; } }; let _model = attributes && attributes.model; let _element = document.getElementById(attributes && attributes.element); let _template; let temp = attributes && attributes.template; if(typeof(temp) === 'string') { _template = temp; } else if(typeof(temp) === 'object') { if(!temp.templateId) { throw new Error('Template must be a string, or an object with "templateId" field'); } else { _template = document.getElementById(temp.templateId).innerHTML; } } if(!_model) { throw new Error('A model must be supplied'); } if(!_element) { throw new Error('An element must be supplied, provided by its id'); } if(!_template) { throw new Error('A template id or string must be supplied'); } let self = this; let _collection = {}; // {index: model} // get collection of model types this.getCollection = function() { return Object.keys(_collection).map(index => _collection[index]); } // get collection of objects this.models = function() { return Object.keys(_collection).map(index => _collection[index].toJSON()); } // append array of objects that // represent models to the list this.pushAll = function(models) { models.forEach(model => { model.index = _generateIndex(); _collection[model.index] = new _model(model); }); _element.innerHTML += _renderTemplate(); _notifyListeners('pushAll', this.models()); } // push to end of the list this.push = function(model) { _addModel(model, 'push'); } // push to begining of the list this.unshift = function(model) { _addModel(model, 'unshift'); } // remove single model and return it this.remove = function(index) { if(!_collection[index]) { return; } let model = _collection[index]; delete _collection[index]; _removeModelAndRender(index); _notifyListeners('remove', model); return model; } // get max index this.lastIndex = function() { if(this.size() === 0) { return -1; } return _index-1; } // get min index this.firstIndex = function() { let indexes = Object.keys(_collection); if(!indexes.length) return -1; return Math.min.apply(null, indexes); } // clear list and notify listeners this.removeAll = function() { _collection = {}; _element.innerHTML = ''; _notifyListeners('removeAll'); } // get model object by index this.get = function(index) { if(!_collection[index]) { return null; } return _collection[index].toJSON(); } // get number of models in the list this.size = function() { return Object.keys(_collection).length; } // filter models and render this.filter = function(cbk) { let coll = this.models().filter(cbk); _element.innerHTML = _renderTemplate(coll); _notifyListeners('filter', coll); return coll; } // sort models and render this.sort = function(sorter) { sorter = sorter || function(a,b){return a.index - b.index;}; let sorted = this.models().sort(sorter); let sortedCollection = {}; sorted.forEach(model => { sortedCollection[model.index] = _collection[model.index]; }); _collection = sortedCollection; _element.innerHTML = _renderTemplate(sorted); // render _notifyListeners('sort', sorted); return sorted; } // go over models this.forEach = function(cbk) { this.models().forEach(cbk); } // edit a field in the model and replace it in the list this.edit = function(index, options) { if(!options) { return; } let model = _collection[index]; for(let key in options) { model.set(key, options[key]); } let modelJSON = model.toJSON(); let html = _renderLoop(_renderModel(modelJSON), modelJSON); let newEl = _htmlToElement(html); _replaceModel(index, newEl); // render _notifyListeners('edit', modelJSON); } // add filter to be used by pipe in the template this.addFilter = function(filterName, filterCbk) { if(typeof(filterName) !== 'string') { throw new Error('Filter name must be a string'); } if(typeof(filterCbk) !== 'function') { throw new Error('Filter callback must be a function'); } _customFilters[filterName] = filterCbk; } // subscribe to event this.subscribe = function() { if(arguments.length === 1 && typeof(arguments[0]) === 'function') { let listener = arguments[0]; _listeners['push'].push(listener); _listeners['remove'].push(listener); return () => { // unsubscription unsubscribe('push', listener); unsubscribe('remove', listener); } } else if(arguments.length === 2) { let type = arguments[0]; let listener = arguments[1]; if(Array.isArray(type)) { type.forEach(t => { if(_listeners[t]) { _listeners[t].push(listener); } else { throw new Error('type ' + t + ' is not a possible type. possible types: "push", "remove", "filter", "sort", "edit", "pushAll", "removeAll"'); } }); return () => type.forEach(t => unsubscribe(t, listener)) // unsubscription } else { if(_listeners[type]) { _listeners[type].push(listener); return () => unsubscribe(type, listener) // unsubscription } throw new Error('type ' + type + ' is not a possible type. possible types: "push", "remove", "filter", "sort", "edit", "pushAll", "removeAll"'); } } else { throw new Error('You should pass a callback function or a type "push" or "remove" and a callback to subscribe'); } // Give a way to unsubscribe function unsubscribe(type, listener) { for(let i=0; i<_listeners[type].length; i++) { if(_listeners[type][i] === listener) { _listeners[type].splice(i,1); break; } } } } /**************************** List Private Functions ***************************/ function _notifyListeners(type, param) { if(!type) { _listeners.push.forEach(listener => listener(param)); _listeners.remove.forEach(listener => listener(param)); } else if(_listeners[type]) { _listeners[type].forEach(listener => listener(param)); } else { throw new Error('The type passed is not a possible type'); } } function _addModel(model, method) { if(!(model instanceof _model)) { model = new _model(model); } let index = _generateIndex(); model.set('index', index); let modelJSON = model.toJSON(); _collection[index] = model; _updateSingleModelView(modelJSON, method); _notifyListeners('push', modelJSON); } function _replaceModel(index, newEl) { let attr = '[data-id="' + index + '"]'; let el = _element.querySelector(attr); if(!el) { throw new Error('Make sure your you set a "data-id" attribute to each model'); } _element.replaceChild(newEl, el); } function _updateSingleModelView(model, method) { let el = _htmlToElement(_renderLoop(_renderModel(model), model)); if(method === 'push') { _element.appendChild(el); } else if(method === 'unshift') { _element.insertBefore(el, _element.childNodes[0]); } else { throw new Error('unknown method passed to "_updateSingleModelView"'); } } function _removeModelAndRender(index) { let attr = '[data-id="' + index + '"]'; let el = _element.querySelector(attr); if(!el) { throw new Error('Make sure your you set a "data-id" attribute to each model'); } el.remove(); } function _renderTemplate(coll) { let collection = coll || self.models(); let templateString = ''; collection.forEach(model => { templateString += _renderLoop(_renderModel(model), model); }); return templateString; } function _renderLoop(template, model) { let el = _htmlToElement(template); let domElements = el.querySelectorAll('[data-loop]'); if(!domElements || !domElements.length) // no data-loop return template; Array.prototype.slice.call(domElements).forEach((dElement,i) => { let attr = dElement.getAttribute('data-loop').trim(); let arr = model[attr]; if(!arr) { // no attribute in model throw new Error(attr + ' attribute does not appear in model'); } if(!Array.isArray(arr)) { throw new Error(attr + '\'s value must be an array'); } let dElementHtml = _elementToHtml(dElement); let temp = ''; arr.forEach(obj => { temp += dElementHtml.replace(re_loop, (str,g) => { if(g.indexOf('|') !== -1) { return _filterize(obj, g); } return _resolveNestedObject(obj, g); }); }); template = template.replace(dElementHtml, temp); }); return template; } function _renderModel(model) { let temp = _template; temp = temp.replace(re, (str,g) => { if(g.indexOf('|') !== -1) { return _filterize(model, g); } return _resolveNestedObject(model, g); }); return temp; } function _filterize(model, g) { let parts = g.split('|'); let txt = parts[0].trim(); let filter = parts[1].trim(); let txtToRender = _resolveNestedObject(model, txt); // resolve nested object if(!txtToRender) { throw new Error('Please check the expression "' + txt + '" you passed in the template'); } if(_customFilters[filter]) { return _customFilters[filter](txtToRender); } throw new Error('The filter you are using does not exist. Please use "addFilter" function to create it.'); } function _resolveNestedObject(model, input) { if(input === 'this') return model; let nestedObjectArray = input.split('.'); if(nestedObjectArray.length === 1) { return model[input]; } else { let txtToRender = model[nestedObjectArray[0].trim()]; for(var i=1; i<nestedObjectArray.length; i++) { txtToRender = txtToRender[nestedObjectArray[i].trim()]; } return txtToRender; } } function _generateIndex() { return _index++; } function _elementToHtml(el) { let div = document.createElement('div'); div.appendChild(el); return div.innerHTML; } function _htmlToElement(html) { let div = document.createElement('div'); div.innerHTML = html; return div.firstElementChild; } } /*************************************** Skeleton Storage Helper Functions ***************************************/ function _stringifyValue(value) { try { value = JSON.stringify(value); return value; } catch(e) { return value; } } function _parseValue(value) { try { value = JSON.parse(value); return value; } catch(e) { return value; } } /*********************** Skeleton Storage ***********************/ let storage = { save() { if(window.localStorage) { if(arguments.length === 2) { let key = arguments[0]; let value = arguments[1]; if(typeof(key) !== 'string') { throw new Error('First item must be a string'); } value = _stringifyValue(value); window.localStorage.setItem(key, value); } else if(arguments.length === 1 && typeof(arguments[0]) === 'object') { let pairs = arguments[0]; for(let key in pairs) { let value = pairs[key]; value = _stringifyValue(value); window.localStorage.setItem(key, value); } } else { throw new Error('Method save must get key an value, or an object of keys and values'); } } }, fetch(key) { if(window.localStorage) { let value = window.localStorage.getItem(key); if(!value) { return null; } return _parseValue(value); } }, clear() { if(window.localStorage) { window.localStorage.clear(); } } } /************************* Skeleton Form/Input ************************/ let inputObservables = {}; // {id: element} let formObservables = {}; // {name: observablesObject} function input(id, cbk, evt='keyup') { let el = document.getElementById(id); if(!el) { throw new Error(`The id '${id}' does not match any dom element`); } if(el.nodeName !== 'INPUT' && el.nodeName !== 'TEXTAREA') { throw new Error(`The id '${id}' must match an input or textarea element`); } inputObservables[id] = el; if(cbk) { el.addEventListener(evt, cbk); } } input.get = (id) => { let el = inputObservables[id]; if(!el) { throw new Error(`The id '${id}' was not set to be cached. Please use the 'input' function first`); } return el.value; } input.set = (id, val) => { let el = inputObservables[id]; if(!el) { throw new Error(`The id '${id}' was not set to be cached. Please use the 'input' function first`); } el.value = val; } input.clear = (id) => { if(id) { inputObservables[id].value = ''; } else { Object.keys(inputObservables).forEach(id => input.set(id, '')); } } function form(options) { if(!options.name) { throw new Error('Skeleton.form must recieve a "name" field with the form\'s name'); } let name = options.name; let form = document.querySelector(`form[name='${name}']`); if(!form) { throw new Error('No form element with name ' + name); } let formObj = {}; formObj.name = options.name; let inputs = options.inputs; if(inputs) { for(let key in inputs) { let id = inputs[key]; let el = form.querySelector(`#${id}`); if(!el) { throw new Error('No element with id ' + id); } if(el.nodeName !== 'INPUT' && el.nodeName !== 'TEXTAREA') { throw new Error(`The id '${id}' must match an input or textarea element`); } formObj[key] = el; } } if(!options.submit) { throw new Error('"submit" button id must be supplied'); } if(!options.onSubmit) { throw new Error('"onSubmit" method must be supplied'); } let submitButton = document.getElementById(options.submit); if(!submitButton) { throw new Error('Id passed as submit button id does not exist'); } formObservables[name] = formObj; // set form to form observables submitButton.addEventListener('click', (e) => { e.preventDefault(); options.onSubmit.call(formObservables[name], e); }); } form.clear = (name) => { let obs = formObservables[name]; if(!obs) { throw new Error(`The name ${name} is not recognized as a form name`); } for(let key in obs) { let el = obs[key]; if(el.nodeName && (el.nodeName === 'INPUT' || el.nodeName === 'TEXTAREA')) { el.value = ''; } } } /******************** Skeleton Bind ********************/ function bind(textNodeId) { let txtNode = document.getElementById(textNodeId); if(!txtNode) { throw new Error(textNodeId + ' id does not match any element'); } return { to() { let ids = Array.prototype.slice.call(arguments); let inputElements = ids.map(inputElementId => { let inputNode = document.getElementById(inputElementId); if(!inputNode || !(inputNode.nodeName === 'INPUT' || inputNode.nodeName === 'TEXTAREA')) { throw new Error(inputElementId + ' id does not match any element or the element it matches is not input or textarea element'); } return inputNode; }); return { exec(cbkFunc, evt='keyup') { for(let i=0; i<inputElements.length; i++) { let inputNode = inputElements[i]; inputNode.addEventListener(evt, (e) => { let values = inputElements.map(el => { let value = el.value; if(!value) { return ''; } return value; }); txtNode.textContent = cbkFunc.apply(null, values); }); } } } } } } /************ Return ************/ return { Model, List, storage, form, input, bind } })();
/*!*************************************************** * mark.js v8.1.1 * https://github.com/julmot/mark.js * Copyright (c) 2014–2016, Julian Motz * Released under the MIT license https://git.io/vwTVl *****************************************************/ "use strict"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function (factory, window, document) { if (typeof define === "function" && define.amd) { define([], function () { return factory(window, document); }); } else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) { module.exports = factory(window, document); } else { factory(window, document); } })(function (window, document) { var Mark = function () { function Mark(ctx) { _classCallCheck(this, Mark); this.ctx = ctx; } _createClass(Mark, [{ key: "log", value: function log(msg) { var level = arguments.length <= 1 || arguments[1] === undefined ? "debug" : arguments[1]; var log = this.opt.log; if (!this.opt.debug) { return; } if ((typeof log === "undefined" ? "undefined" : _typeof(log)) === "object" && typeof log[level] === "function") { log[level]("mark.js: " + msg); } } }, { key: "escapeStr", value: function escapeStr(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } }, { key: "createRegExp", value: function createRegExp(str) { str = this.escapeStr(str); if (Object.keys(this.opt.synonyms).length) { str = this.createSynonymsRegExp(str); } if (this.opt.diacritics) { str = this.createDiacriticsRegExp(str); } str = this.createMergedBlanksRegExp(str); str = this.createAccuracyRegExp(str); return str; } }, { key: "createSynonymsRegExp", value: function createSynonymsRegExp(str) { var syn = this.opt.synonyms, sens = this.opt.caseSensitive ? "" : "i"; for (var index in syn) { if (syn.hasOwnProperty(index)) { var value = syn[index], k1 = this.escapeStr(index), k2 = this.escapeStr(value); str = str.replace(new RegExp("(" + k1 + "|" + k2 + ")", "gm" + sens), "(" + k1 + "|" + k2 + ")"); } } return str; } }, { key: "createDiacriticsRegExp", value: function createDiacriticsRegExp(str) { var sens = this.opt.caseSensitive ? "" : "i", dct = this.opt.caseSensitive ? ["aàáâãäåāą", "AÀÁÂÃÄÅĀĄ", "cçćč", "CÇĆČ", "dđď", "DĐĎ", "eèéêëěēę", "EÈÉÊËĚĒĘ", "iìíîïī", "IÌÍÎÏĪ", "lł", "LŁ", "nñňń", "NÑŇŃ", "oòóôõöøō", "OÒÓÔÕÖØŌ", "rř", "RŘ", "sšś", "SŠŚ", "tť", "TŤ", "uùúûüůū", "UÙÚÛÜŮŪ", "yÿý", "YŸÝ", "zžżź", "ZŽŻŹ"] : ["aÀÁÂÃÄÅàáâãäåĀāąĄ", "cÇçćĆčČ", "dđĐďĎ", "eÈÉÊËèéêëěĚĒēęĘ", "iÌÍÎÏìíîïĪī", "lłŁ", "nÑñňŇńŃ", "oÒÓÔÕÖØòóôõöøŌō", "rřŘ", "sŠšśŚ", "tťŤ", "uÙÚÛÜùúûüůŮŪū", "yŸÿýÝ", "zŽžżŻźŹ"]; var handled = []; str.split("").forEach(function (ch) { dct.every(function (dct) { if (dct.indexOf(ch) !== -1) { if (handled.indexOf(dct) > -1) { return false; } str = str.replace(new RegExp("[" + dct + "]", "gm" + sens), "[" + dct + "]"); handled.push(dct); } return true; }); }); return str; } }, { key: "createMergedBlanksRegExp", value: function createMergedBlanksRegExp(str) { return str.replace(/[\s]+/gmi, "[\\s]*"); } }, { key: "createAccuracyRegExp", value: function createAccuracyRegExp(str) { var _this = this; var acc = this.opt.accuracy, val = typeof acc === "string" ? acc : acc.value, ls = typeof acc === "string" ? [] : acc.limiters, lsJoin = ""; ls.forEach(function (limiter) { lsJoin += "|" + _this.escapeStr(limiter); }); switch (val) { case "partially": return "()(" + str + ")"; case "complementary": return "()([^\\s" + lsJoin + "]*" + str + "[^\\s" + lsJoin + "]*)"; case "exactly": return "(^|\\s" + lsJoin + ")(" + str + ")(?=$|\\s" + lsJoin + ")"; } } }, { key: "getSeparatedKeywords", value: function getSeparatedKeywords(sv) { var _this2 = this; var stack = []; sv.forEach(function (kw) { if (!_this2.opt.separateWordSearch) { if (kw.trim() && stack.indexOf(kw) === -1) { stack.push(kw); } } else { kw.split(" ").forEach(function (kwSplitted) { if (kwSplitted.trim() && stack.indexOf(kwSplitted) === -1) { stack.push(kwSplitted); } }); } }); return { "keywords": stack.sort(function (a, b) { return b.length - a.length; }), "length": stack.length }; } }, { key: "getTextNodes", value: function getTextNodes(cb) { var _this3 = this; var val = "", nodes = []; this.iterator.forEachNode(NodeFilter.SHOW_TEXT, function (node) { nodes.push({ start: val.length, end: (val += node.textContent).length, node: node }); }, function (node) { if (_this3.matchesExclude(node.parentNode, true)) { return NodeFilter.FILTER_REJECT; } else { return NodeFilter.FILTER_ACCEPT; } }, function () { cb({ value: val, nodes: nodes }); }); } }, { key: "matchesExclude", value: function matchesExclude(el, exclM) { var excl = this.opt.exclude.concat(["script", "style", "title", "head", "html"]); if (exclM) { excl = excl.concat(["*[data-markjs='true']"]); } return DOMIterator.matches(el, excl); } }, { key: "wrapRangeInTextNode", value: function wrapRangeInTextNode(node, start, end) { var hEl = !this.opt.element ? "mark" : this.opt.element, startNode = node.splitText(start), ret = startNode.splitText(end - start); var repl = document.createElement(hEl); repl.setAttribute("data-markjs", "true"); if (this.opt.className) { repl.setAttribute("class", this.opt.className); } repl.textContent = startNode.textContent; startNode.parentNode.replaceChild(repl, startNode); return ret; } }, { key: "wrapRangeInMappedTextNode", value: function wrapRangeInMappedTextNode(dict, start, end, filterCb, eachCb) { var _this4 = this; dict.nodes.every(function (n, i) { var sibl = dict.nodes[i + 1]; if (typeof sibl === "undefined" || sibl.start > start) { var _ret = function () { var s = start - n.start, e = (end > n.end ? n.end : end) - n.start; if (filterCb(n.node)) { n.node = _this4.wrapRangeInTextNode(n.node, s, e); var startStr = dict.value.substr(0, n.start), endStr = dict.value.substr(e + n.start); dict.value = startStr + endStr; dict.nodes.forEach(function (k, j) { if (j >= i) { if (dict.nodes[j].start > 0 && j !== i) { dict.nodes[j].start -= e; } dict.nodes[j].end -= e; } }); end -= e; eachCb(n.node.previousSibling, n.start); if (end > n.end) { start = n.end; } else { return { v: false }; } } }(); if ((typeof _ret === "undefined" ? "undefined" : _typeof(_ret)) === "object") return _ret.v; } return true; }); } }, { key: "wrapMatches", value: function wrapMatches(regex, custom, filterCb, eachCb, endCb) { var _this5 = this; var matchIdx = custom ? 0 : 2; this.getTextNodes(function (dict) { dict.nodes.forEach(function (node) { node = node.node; var match = void 0; while ((match = regex.exec(node.textContent)) !== null) { if (!filterCb(match[matchIdx], node)) { continue; } var pos = match.index; if (!custom) { pos += match[matchIdx - 1].length; } node = _this5.wrapRangeInTextNode(node, pos, pos + match[matchIdx].length); eachCb(node.previousSibling); regex.lastIndex = 0; } }); endCb(); }); } }, { key: "wrapMatchesAcrossElements", value: function wrapMatchesAcrossElements(regex, custom, filterCb, eachCb, endCb) { var _this6 = this; var matchIdx = custom ? 0 : 2; this.getTextNodes(function (dict) { var match = void 0; while ((match = regex.exec(dict.value)) !== null) { var start = match.index; if (!custom) { start += match[matchIdx - 1].length; } var end = start + match[matchIdx].length; _this6.wrapRangeInMappedTextNode(dict, start, end, function (node) { return filterCb(match[matchIdx], node); }, function (node, lastIndex) { regex.lastIndex = lastIndex; eachCb(node); }); } endCb(); }); } }, { key: "unwrapMatches", value: function unwrapMatches(node) { var parent = node.parentNode; var docFrag = document.createDocumentFragment(); while (node.firstChild) { docFrag.appendChild(node.removeChild(node.firstChild)); } parent.replaceChild(docFrag, node); parent.normalize(); } }, { key: "markRegExp", value: function markRegExp(regexp, opt) { var _this7 = this; this.opt = opt; this.log("Searching with expression \"" + regexp + "\""); var totalMatches = 0; var eachCb = function eachCb(element) { totalMatches++; _this7.opt.each(element); }; var fn = "wrapMatches"; if (this.opt.acrossElements) { fn = "wrapMatchesAcrossElements"; } this[fn](regexp, true, function (match, node) { return _this7.opt.filter(node, match, totalMatches); }, eachCb, function () { if (totalMatches === 0) { _this7.opt.noMatch(regexp); } _this7.opt.done(totalMatches); }); } }, { key: "mark", value: function mark(sv, opt) { var _this8 = this; this.opt = opt; var _getSeparatedKeywords = this.getSeparatedKeywords(typeof sv === "string" ? [sv] : sv); var kwArr = _getSeparatedKeywords.keywords; var kwArrLen = _getSeparatedKeywords.length; var sens = this.opt.caseSensitive ? "" : "i"; var totalMatches = 0, fn = "wrapMatches"; if (this.opt.acrossElements) { fn = "wrapMatchesAcrossElements"; } if (kwArrLen === 0) { this.opt.done(totalMatches); return; } var handler = function handler(kw) { var regex = new RegExp(_this8.createRegExp(kw), "gm" + sens), matches = 0; _this8.log("Searching with expression \"" + regex + "\""); _this8[fn](regex, false, function (term, node) { return _this8.opt.filter(node, kw, totalMatches, matches); }, function (element) { matches++; totalMatches++; _this8.opt.each(element); }, function () { if (matches === 0) { _this8.opt.noMatch(kw); } if (kwArr[kwArrLen - 1] === kw) { _this8.opt.done(totalMatches); } else { handler(kwArr[kwArr.indexOf(kw) + 1]); } }); }; handler(kwArr[0]); } }, { key: "unmark", value: function unmark(opt) { var _this9 = this; this.opt = opt; var sel = this.opt.element ? this.opt.element : "*"; sel += "[data-markjs]"; if (this.opt.className) { sel += "." + this.opt.className; } this.log("Removal selector \"" + sel + "\""); this.iterator.forEachNode(NodeFilter.SHOW_ELEMENT, function (node) { _this9.unwrapMatches(node); }, function (node) { var matchesSel = DOMIterator.matches(node, sel), matchesExclude = _this9.matchesExclude(node, false); if (!matchesSel || matchesExclude) { return NodeFilter.FILTER_REJECT; } else { return NodeFilter.FILTER_ACCEPT; } }, this.opt.done); } }, { key: "opt", set: function set(val) { this._opt = _extends({}, { "element": "", "className": "", "exclude": [], "iframes": false, "separateWordSearch": true, "diacritics": true, "synonyms": {}, "accuracy": "partially", "acrossElements": false, "each": function each() {}, "noMatch": function noMatch() {}, "filter": function filter() { return true; }, "done": function done() {}, "debug": false, "log": window.console, "caseSensitive": false }, val); }, get: function get() { return this._opt; } }, { key: "iterator", get: function get() { if (!this._iterator) { this._iterator = new DOMIterator(this.ctx, this.opt.iframes, this.opt.exclude); } return this._iterator; } }]); return Mark; }(); var DOMIterator = function () { function DOMIterator(ctx) { var iframes = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; var exclude = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; _classCallCheck(this, DOMIterator); this.ctx = ctx; this.iframes = iframes; this.exclude = exclude; } _createClass(DOMIterator, [{ key: "getContexts", value: function getContexts() { var ctx = void 0; if (typeof this.ctx === "undefined" || !this.ctx) { ctx = []; } else if (NodeList.prototype.isPrototypeOf(this.ctx)) { ctx = Array.prototype.slice.call(this.ctx); } else if (Array.isArray(this.ctx)) { ctx = this.ctx; } else { ctx = [this.ctx]; } var filteredCtx = []; ctx.forEach(function (ctx) { var isDescendant = filteredCtx.filter(function (contexts) { return contexts.contains(ctx); }).length > 0; if (filteredCtx.indexOf(ctx) === -1 && !isDescendant) { filteredCtx.push(ctx); } }); return filteredCtx; } }, { key: "getIframeContents", value: function getIframeContents(ifr, successFn) { var errorFn = arguments.length <= 2 || arguments[2] === undefined ? function () {} : arguments[2]; var doc = void 0; try { var ifrWin = ifr.contentWindow; doc = ifrWin.document; if (!ifrWin || !doc) { throw new Error("iframe inaccessible"); } } catch (e) { errorFn(); } if (doc) { successFn(doc); } } }, { key: "onIframeReady", value: function onIframeReady(ifr, successFn, errorFn) { var _this10 = this; try { (function () { var ifrWin = ifr.contentWindow, bl = "about:blank", compl = "complete", isBlank = function isBlank() { var src = ifr.getAttribute("src").trim(), href = ifrWin.location.href; return href === bl && src !== bl && src; }, observeOnload = function observeOnload() { var listener = function listener() { try { if (!isBlank()) { ifr.removeEventListener("load", listener); _this10.getIframeContents(ifr, successFn, errorFn); } } catch (e) { errorFn(); } }; ifr.addEventListener("load", listener); }; if (ifrWin.document.readyState === compl) { if (isBlank()) { observeOnload(); } else { _this10.getIframeContents(ifr, successFn, errorFn); } } else { observeOnload(); } })(); } catch (e) { errorFn(); } } }, { key: "waitForIframes", value: function waitForIframes(ctx, done) { var _this11 = this; var eachCalled = 0; this.forEachIframe(ctx, function () { return true; }, function (ifr) { eachCalled++; _this11.waitForIframes(ifr.querySelector("html"), function () { if (! --eachCalled) { done(); } }); }, function (handled) { if (!handled) { done(); } }); } }, { key: "forEachIframe", value: function forEachIframe(ctx, filter, each) { var _this12 = this; var end = arguments.length <= 3 || arguments[3] === undefined ? function () {} : arguments[3]; var ifr = ctx.querySelectorAll("iframe"), open = ifr.length, handled = 0; ifr = Array.prototype.slice.call(ifr); var checkEnd = function checkEnd() { if (--open <= 0) { end(handled); } }; if (!open) { checkEnd(); } ifr.forEach(function (ifr) { if (DOMIterator.matches(ifr, _this12.exclude)) { checkEnd(); } else { _this12.onIframeReady(ifr, function (con) { if (filter(ifr)) { handled++; each(con); } checkEnd(); }, checkEnd); } }); } }, { key: "createIterator", value: function createIterator(ctx, whatToShow, filter) { return document.createNodeIterator(ctx, whatToShow, filter, false); } }, { key: "createInstanceOnIframe", value: function createInstanceOnIframe(contents) { return new DOMIterator(contents.querySelector("html"), this.iframes); } }, { key: "compareNodeIframe", value: function compareNodeIframe(node, prevNode, ifr) { var compCurr = node.compareDocumentPosition(ifr), prev = Node.DOCUMENT_POSITION_PRECEDING; if (compCurr & prev) { if (prevNode !== null) { var compPrev = prevNode.compareDocumentPosition(ifr), after = Node.DOCUMENT_POSITION_FOLLOWING; if (compPrev & after) { return true; } } else { return true; } } return false; } }, { key: "getIteratorNode", value: function getIteratorNode(itr) { var prevNode = itr.previousNode(); var node = void 0; if (prevNode === null) { node = itr.nextNode(); } else { node = itr.nextNode() && itr.nextNode(); } return { prevNode: prevNode, node: node }; } }, { key: "checkIframeFilter", value: function checkIframeFilter(node, prevNode, currIfr, ifr) { var key = false, handled = false; ifr.forEach(function (ifrDict, i) { if (ifrDict.val === currIfr) { key = i; handled = ifrDict.handled; } }); if (this.compareNodeIframe(node, prevNode, currIfr)) { if (key === false && !handled) { ifr.push({ val: currIfr, handled: true }); } else if (key !== false && !handled) { ifr[key].handled = true; } return true; } if (key === false) { ifr.push({ val: currIfr, handled: false }); } return false; } }, { key: "handleOpenIframes", value: function handleOpenIframes(ifr, whatToShow, eCb, fCb) { var _this13 = this; ifr.forEach(function (ifrDict) { if (!ifrDict.handled) { _this13.getIframeContents(ifrDict.val, function (con) { _this13.createInstanceOnIframe(con).forEachNode(whatToShow, eCb, fCb); }); } }); } }, { key: "iterateThroughNodes", value: function iterateThroughNodes(whatToShow, ctx, eachCb, filterCb, doneCb) { var _this14 = this; var itr = this.createIterator(ctx, whatToShow, filterCb); var ifr = [], node = void 0, prevNode = void 0, retrieveNodes = function retrieveNodes() { var _getIteratorNode = _this14.getIteratorNode(itr); prevNode = _getIteratorNode.prevNode; node = _getIteratorNode.node; return node; }; while (retrieveNodes()) { if (this.iframes) { this.forEachIframe(ctx, function (currIfr) { return _this14.checkIframeFilter(node, prevNode, currIfr, ifr); }, function (con) { _this14.createInstanceOnIframe(con).forEachNode(whatToShow, eachCb, filterCb); }); } eachCb(node); } if (this.iframes) { this.handleOpenIframes(ifr, whatToShow, eachCb, filterCb); } doneCb(); } }, { key: "forEachNode", value: function forEachNode(whatToShow, each, filter) { var _this15 = this; var done = arguments.length <= 3 || arguments[3] === undefined ? function () {} : arguments[3]; var contexts = this.getContexts(); var open = contexts.length; if (!open) { done(); } contexts.forEach(function (ctx) { var ready = function ready() { _this15.iterateThroughNodes(whatToShow, ctx, each, filter, function () { if (--open <= 0) { done(); } }); }; if (_this15.iframes) { _this15.waitForIframes(ctx, ready); } else { ready(); } }); } }], [{ key: "matches", value: function matches(element, selector) { var selectors = typeof selector === "string" ? [selector] : selector, fn = element.matches || element.matchesSelector || element.msMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.webkitMatchesSelector; if (fn) { var match = false; selectors.every(function (sel) { if (fn.call(element, sel)) { match = true; return false; } return true; }); return match; } else { return false; } } }]); return DOMIterator; }(); window.Mark = function (ctx) { var _this16 = this; var instance = new Mark(ctx); this.mark = function (sv, opt) { instance.mark(sv, opt); return _this16; }; this.markRegExp = function (sv, opt) { instance.markRegExp(sv, opt); return _this16; }; this.unmark = function (opt) { instance.unmark(opt); return _this16; }; return this; }; return window.Mark; }, window, document);
/*! angular-multi-select 7.4.6 */ "use strict";var angular_multi_select=angular.module("angular-multi-select");angular_multi_select.run(["$templateCache",function(a){var b=a.get("angular-multi-select.tpl");b=b.replace(/(class="(?:.*?)ams-item-text(?:.*?)")/gi,'$1 ng-click="item[amsc.INTERNAL_KEY_CHILDREN_LEAFS] === 0 && amse.toggle_check_node(item) || amse.toggle_open_node(item)"'),a.put("angular-multi-select.tpl",b)}]);
/*! Hammer.JS - v1.0.10 - 2014-03-28 * http://eightmedia.github.io/hammer.js * * Copyright (c) 2014 Jorik Tangelder <j.tangelder@gmail.com>; * Licensed under the MIT license */ (function(window, undefined) { 'use strict'; /** * Hammer * use this to create instances * @param {HTMLElement} element * @param {Object} options * @returns {Hammer.Instance} * @constructor */ var Hammer = function(element, options) { return new Hammer.Instance(element, options || {}); }; Hammer.VERSION = '1.0.10'; // default settings Hammer.defaults = { // add styles and attributes to the element to prevent the browser from doing // its native behavior. this doesnt prevent the scrolling, but cancels // the contextmenu, tap highlighting etc // set to false to disable this stop_browser_behavior: { // this also triggers onselectstart=false for IE userSelect : 'none', // this makes the element blocking in IE10>, you could experiment with the value // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241 touchAction : 'none', touchCallout : 'none', contentZooming : 'none', userDrag : 'none', tapHighlightColor: 'rgba(0,0,0,0)' } // // more settings are defined per gesture at /gestures // }; // detect touchevents Hammer.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled; Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window); // dont use mouseevents on mobile devices Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i; Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && window.navigator.userAgent.match(Hammer.MOBILE_REGEX); // eventtypes per touchevent (start, move, end) // are filled by Event.determineEventTypes on setup Hammer.EVENT_TYPES = {}; // interval in which Hammer recalculates current velocity in ms Hammer.UPDATE_VELOCITY_INTERVAL = 16; // hammer document where the base events are added at Hammer.DOCUMENT = window.document; // define these also as vars, for better minification // direction defines var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down'; var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left'; var DIRECTION_UP = Hammer.DIRECTION_UP = 'up'; var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right'; // pointer type var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse'; var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch'; var POINTER_PEN = Hammer.POINTER_PEN = 'pen'; // touch event defines var EVENT_START = Hammer.EVENT_START = 'start'; var EVENT_MOVE = Hammer.EVENT_MOVE = 'move'; var EVENT_END = Hammer.EVENT_END = 'end'; // plugins and gestures namespaces Hammer.plugins = Hammer.plugins || {}; Hammer.gestures = Hammer.gestures || {}; // if the window events are set... Hammer.READY = false; /** * setup events to detect gestures on the document */ function setup() { if(Hammer.READY) { return; } // find what eventtypes we add listeners to Event.determineEventTypes(); // Register all gestures inside Hammer.gestures Utils.each(Hammer.gestures, function(gesture){ Detection.register(gesture); }); // Add touch events on the document Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect); Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect); // Hammer is ready...! Hammer.READY = true; } var Utils = Hammer.utils = { /** * extend method, * also used for cloning when dest is an empty object * @param {Object} dest * @param {Object} src * @parm {Boolean} merge do a merge * @returns {Object} dest */ extend: function extend(dest, src, merge) { for(var key in src) { if(dest[key] !== undefined && merge) { continue; } dest[key] = src[key]; } return dest; }, /** * for each * @param obj * @param iterator */ each: function each(obj, iterator, context) { var i, o; // native forEach on arrays if ('forEach' in obj) { obj.forEach(iterator, context); } // arrays else if(obj.length !== undefined) { for(i=-1; (o=obj[++i]);) { if (iterator.call(context, o, i, obj) === false) { return; } } } // objects else { for(i in obj) { if(obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj) === false) { return; } } } }, /** * find if a string contains the needle * @param {String} src * @param {String} needle * @returns {Boolean} found */ inStr: function inStr(src, needle) { return src.indexOf(needle) > -1; }, /** * find if a node is in the given parent * used for event delegation tricks * @param {HTMLElement} node * @param {HTMLElement} parent * @returns {boolean} has_parent */ hasParent: function hasParent(node, parent) { while(node) { if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @param {Array} touches * @returns {Object} center pageXY clientXY */ getCenter: function getCenter(touches) { var pageX = [] , pageY = [] , clientX = [] , clientY = [] , min = Math.min , max = Math.max; // no need to loop when only one touch if(touches.length === 1) { return { pageX: touches[0].pageX, pageY: touches[0].pageY, clientX: touches[0].clientX, clientY: touches[0].clientY }; } Utils.each(touches, function(touch) { pageX.push(touch.pageX); pageY.push(touch.pageY); clientX.push(touch.clientX); clientY.push(touch.clientY); }); return { pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2, pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2, clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2, clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2 }; }, /** * calculate the velocity between two points * @param {Number} delta_time * @param {Number} delta_x * @param {Number} delta_y * @returns {Object} velocity */ getVelocity: function getVelocity(delta_time, delta_x, delta_y) { return { x: Math.abs(delta_x / delta_time) || 0, y: Math.abs(delta_y / delta_time) || 0 }; }, /** * calculate the angle between two coordinates * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} angle */ getAngle: function getAngle(touch1, touch2) { var x = touch2.clientX - touch1.clientX , y = touch2.clientY - touch1.clientY; return Math.atan2(y, x) * 180 / Math.PI; }, /** * angle to direction define * @param {Touch} touch1 * @param {Touch} touch2 * @returns {String} direction constant, like DIRECTION_LEFT */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.clientX - touch2.clientX) , y = Math.abs(touch1.clientY - touch2.clientY); if(x >= y) { return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN; }, /** * calculate the distance between two touches * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.clientX - touch1.clientX , y = touch2.clientY - touch1.clientY; return Math.sqrt((x * x) + (y * y)); }, /** * calculate the scale factor between two touchLists (fingers) * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start * @param {Array} end * @returns {Number} scale */ getScale: function getScale(start, end) { // need two fingers... if(start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }, /** * calculate the rotation degrees between two touchLists (fingers) * @param {Array} start * @param {Array} end * @returns {Number} rotation */ getRotation: function getRotation(start, end) { // need two fingers if(start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }, /** * boolean if the direction is vertical * @param {String} direction * @returns {Boolean} is_vertical */ isVertical: function isVertical(direction) { return direction == DIRECTION_UP || direction == DIRECTION_DOWN; }, /** * toggle browser default behavior with css props * @param {HtmlElement} element * @param {Object} css_props * @param {Boolean} toggle */ toggleDefaultBehavior: function toggleDefaultBehavior(element, css_props, toggle) { if(!css_props || !element || !element.style) { return; } // with css properties for modern browsers Utils.each(['webkit', 'moz', 'Moz', 'ms', 'o', ''], function setStyle(vendor) { Utils.each(css_props, function(value, prop) { // vender prefix at the property if(vendor) { prop = vendor + prop.substring(0, 1).toUpperCase() + prop.substring(1); } // set the style if(prop in element.style) { element.style[prop] = !toggle && value; } }); }); var false_fn = function(){ return false; }; // also the disable onselectstart if(css_props.userSelect == 'none') { element.onselectstart = !toggle && false_fn; } // and disable ondragstart if(css_props.userDrag == 'none') { element.ondragstart = !toggle && false_fn; } } }; /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * @param {HTMLElement} element * @param {Object} [options={}] * @returns {Hammer.Instance} * @constructor */ Hammer.Instance = function(element, options) { var self = this; // setup HammerJS window events and register all gestures // this also sets up the default options setup(); this.element = element; // start/stop detection option this.enabled = true; // merge options this.options = Utils.extend( Utils.extend({}, Hammer.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.stop_browser_behavior) { Utils.toggleDefaultBehavior(this.element, this.options.stop_browser_behavior, false); } // start detection on touchstart this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) { if(self.enabled) { Detection.startDetect(self, ev); } }); // keep a list of user event handlers which needs to be removed when calling 'dispose' this.eventHandlers = []; // return instance return this; }; Hammer.Instance.prototype = { /** * bind events to the instance * @param {String} gesture * @param {Function} handler * @returns {Hammer.Instance} */ on: function onEvent(gesture, handler) { var gestures = gesture.split(' '); Utils.each(gestures, function(gesture) { this.element.addEventListener(gesture, handler, false); this.eventHandlers.push({ gesture: gesture, handler: handler }); }, this); return this; }, /** * unbind events to the instance * @param {String} gesture * @param {Function} handler * @returns {Hammer.Instance} */ off: function offEvent(gesture, handler) { var gestures = gesture.split(' ') , i, eh; Utils.each(gestures, function(gesture) { this.element.removeEventListener(gesture, handler, false); // remove the event handler from the internal list for(i=-1; (eh=this.eventHandlers[++i]);) { if(eh.gesture === gesture && eh.handler === handler) { this.eventHandlers.splice(i, 1); } } }, this); return this; }, /** * trigger gesture event * @param {String} gesture * @param {Object} [eventData] * @returns {Hammer.Instance} */ trigger: function triggerEvent(gesture, eventData) { // optional if(!eventData) { eventData = {}; } // create DOM event var event = Hammer.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(Utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @param {Boolean} state * @returns {Hammer.Instance} */ enable: function enable(state) { this.enabled = state; return this; }, /** * dispose this hammer instance * @returns {Hammer.Instance} */ dispose: function dispose() { var i, eh; // undo all changes made by stop_browser_behavior if(this.options.stop_browser_behavior) { Utils.toggleDefaultBehavior(this.element, this.options.stop_browser_behavior, true); } // unbind all custom event handlers for(i=-1; (eh=this.eventHandlers[++i]);) { this.element.removeEventListener(eh.gesture, eh.handler, false); } this.eventHandlers = []; // unbind the start event listener Event.unbindDom(this.element, Hammer.EVENT_TYPES[EVENT_START], this.eventStartHandler); return null; } }; /** * this holds the last move event, * used to fix empty touchend issue * see the onTouch event for an explanation * @type {Object} */ var last_move_event = null; /** * when the mouse is hold down, this is true * @type {Boolean} */ var should_detect = false; /** * when touch events have been fired, this is true * @type {Boolean} */ var touch_triggered = false; var Event = Hammer.event = { /** * simple addEventListener * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ bindDom: function(element, type, handler) { var types = type.split(' '); Utils.each(types, function(type){ element.addEventListener(type, handler, false); }); }, /** * simple removeEventListener * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ unbindDom: function(element, type, handler) { var types = type.split(' '); Utils.each(types, function(type){ element.removeEventListener(type, handler, false); }); }, /** * touch events with mouse fallback * @param {HTMLElement} element * @param {String} eventType like EVENT_MOVE * @param {Function} handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; var bindDomOnTouch = function bindDomOnTouch(ev) { var srcEventType = ev.type.toLowerCase(); // onmouseup, but when touchend has been fired we do nothing. // this is for touchdevices which also fire a mouseup on touchend if(Utils.inStr(srcEventType, 'mouse') && touch_triggered) { return; } // mousebutton must be down or a touch event else if(Utils.inStr(srcEventType, 'touch') || // touch events are always on screen Utils.inStr(srcEventType, 'pointerdown') || // pointerevents touch (Utils.inStr(srcEventType, 'mouse') && ev.which === 1) // mouse is pressed ) { should_detect = true; } // mouse isn't pressed else if(Utils.inStr(srcEventType, 'mouse') && !ev.which) { should_detect = false; } // we are in a touch event, set the touch triggered bool to true, // this for the conflicts that may occur on ios and android if(Utils.inStr(srcEventType, 'touch') || Utils.inStr(srcEventType, 'pointer')) { touch_triggered = true; } // count the total touches on the screen var count_touches = 0; // when touch has been triggered in this detection session // and we are now handling a mouse event, we stop that to prevent conflicts if(should_detect) { // update pointerevent if(Hammer.HAS_POINTEREVENTS && eventType != EVENT_END) { count_touches = PointerEvent.updatePointer(eventType, ev); } // touch else if(Utils.inStr(srcEventType, 'touch')) { count_touches = ev.touches.length; } // mouse else if(!touch_triggered) { count_touches = Utils.inStr(srcEventType, 'up') ? 0 : 1; } // if we are in a end event, but when we remove one touch and // we still have enough, set eventType to move if(count_touches > 0 && eventType == EVENT_END) { eventType = EVENT_MOVE; } // no touches, force the end event else if(!count_touches) { eventType = EVENT_END; } // store the last move event if(count_touches || last_move_event === null) { last_move_event = ev; } // trigger the handler handler.call(Detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev) ); // remove pointerevent from list if(Hammer.HAS_POINTEREVENTS && eventType == EVENT_END) { count_touches = PointerEvent.updatePointer(eventType, ev); } } // on the end we reset everything if(!count_touches) { last_move_event = null; should_detect = false; touch_triggered = false; PointerEvent.reset(); } }; this.bindDom(element, Hammer.EVENT_TYPES[eventType], bindDomOnTouch); // return the bound function to be able to unbind it later return bindDomOnTouch; }, /** * we have different events for each device/browser * determine what we need and set them in the Hammer.EVENT_TYPES constant */ determineEventTypes: function determineEventTypes() { // determine the eventtype we want to set var types; // pointerEvents magic if(Hammer.HAS_POINTEREVENTS) { types = PointerEvent.getEvents(); } // on Android, iOS, blackberry, windows mobile we dont want any mouseevents else if(Hammer.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel']; } // for non pointer events browsers and mixed browsers, // like chrome on windows8 touch laptop else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup']; } Hammer.EVENT_TYPES[EVENT_START] = types[0]; Hammer.EVENT_TYPES[EVENT_MOVE] = types[1]; Hammer.EVENT_TYPES[EVENT_END] = types[2]; }, /** * create touchlist depending on the event * @param {Object} ev * @param {String} eventType used by the fakemultitouch plugin */ getTouchList: function getTouchList(ev/*, eventType*/) { // get the fake pointerEvent touchlist if(Hammer.HAS_POINTEREVENTS) { return PointerEvent.getTouchList(); } // get the touchlist if(ev.touches) { return ev.touches; } // make fake touchlist from mouse position ev.identifier = 1; return [ev]; }, /** * collect event data for Hammer js * @param {HTMLElement} element * @param {String} eventType like EVENT_MOVE * @param {Object} eventData */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = POINTER_TOUCH; if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) { pointerType = POINTER_MOUSE; } return { center : Utils.getCenter(touches), timeStamp : Date.now(), target : ev.target, touches : touches, eventType : eventType, pointerType: pointerType, srcEvent : ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { var srcEvent = this.srcEvent; srcEvent.preventManipulation && srcEvent.preventManipulation(); srcEvent.preventDefault && srcEvent.preventDefault(); }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return Detection.stopDetect(); } }; } }; var PointerEvent = Hammer.PointerEvent = { /** * holds all pointers * @type {Object} */ pointers: {}, /** * get a list of pointers * @returns {Array} touchlist */ getTouchList: function getTouchList() { var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Utils.each(this.pointers, function(pointer){ touchlist.push(pointer); }); return touchlist; }, /** * update the position of a pointer * @param {String} type EVENT_END * @param {Object} pointerEvent */ updatePointer: function updatePointer(type, pointerEvent) { if(type == EVENT_END) { delete this.pointers[pointerEvent.pointerId]; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } // it's save to use Object.keys, since pointerEvents are only in newer browsers return Object.keys(this.pointers).length; }, /** * check if ev matches pointertype * @param {String} pointerType POINTER_MOUSE * @param {PointerEvent} ev */ matchType: function matchType(pointerType, ev) { if(!ev.pointerType) { return false; } var pt = ev.pointerType , types = {}; types[POINTER_MOUSE] = (pt === POINTER_MOUSE); types[POINTER_TOUCH] = (pt === POINTER_TOUCH); types[POINTER_PEN] = (pt === POINTER_PEN); return types[pointerType]; }, /** * get events */ getEvents: function getEvents() { return [ 'pointerdown MSPointerDown', 'pointermove MSPointerMove', 'pointerup pointercancel MSPointerUp MSPointerCancel' ]; }, /** * reset the list */ reset: function resetList() { this.pointers = {}; } }; var Detection = Hammer.detection = { // contains all registred Hammer.gestures in the correct order gestures: [], // data of the current Hammer.gesture detection session current : null, // the previous Hammer.gesture session data // is a full clone of the previous gesture.current object previous: null, // when this becomes true, no gestures are fired stopped : false, /** * start Hammer.gesture detection * @param {Hammer.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a Hammer.gesture detection on an element if(this.current) { return; } this.stopped = false; // holds current session this.current = { inst : inst, // reference to HammerInstance we're working for startEvent : Utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent : false, // last eventData lastVelocityEvent : false, // last eventData for velocity. velocity : false, // current velocity name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * Hammer.gesture detection * @param {Object} eventData */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // hammer instance and instance options var inst = this.current.inst, inst_options = inst.options; // call Hammer.gesture handlers Utils.each(this.gestures, function triggerGesture(gesture) { // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false && inst.enabled !== false ) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, inst) === false) { this.stopDetect(); return false; } } }, this); // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // end event, but not the last touch, so dont stop if(eventData.eventType == EVENT_END && !eventData.touches.length - 1) { this.stopDetect(); } return eventData; }, /** * clear the Hammer.gesture vars * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected * to stop other Hammer.gestures from being fired */ stopDetect: function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = Utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }, /** * calculate velocity * @param {Object} ev * @param {Number} delta_time * @param {Number} delta_x * @param {Number} delta_y */ getVelocityData: function getVelocityData(ev, delta_time, delta_x, delta_y) { var cur = this.current , velocityEv = cur.lastVelocityEvent , velocity = cur.velocity; // calculate velocity every x ms if (velocityEv && ev.timeStamp - velocityEv.timeStamp > Hammer.UPDATE_VELOCITY_INTERVAL) { velocity = Utils.getVelocity(ev.timeStamp - velocityEv.timeStamp, ev.center.clientX - velocityEv.center.clientX, ev.center.clientY - velocityEv.center.clientY); cur.lastVelocityEvent = ev; } else if(!cur.velocity) { velocity = Utils.getVelocity(delta_time, delta_x, delta_y); cur.lastVelocityEvent = ev; } cur.velocity = velocity; ev.velocityX = velocity.x; ev.velocityY = velocity.y; }, /** * calculate interim angle and direction * @param {Object} ev */ getInterimData: function getInterimData(ev) { var lastEvent = this.current.lastEvent , angle , direction; // end events (e.g. dragend) don't have useful values for interimDirection & interimAngle // because the previous event has exactly the same coordinates // so for end events, take the previous values of interimDirection & interimAngle // instead of recalculating them and getting a spurious '0' if(ev.eventType == EVENT_END) { angle = lastEvent && lastEvent.interimAngle; direction = lastEvent && lastEvent.interimDirection; } else { angle = lastEvent && Utils.getAngle(lastEvent.center, ev.center); direction = lastEvent && Utils.getDirection(lastEvent.center, ev.center); } ev.interimAngle = angle; ev.interimDirection = direction; }, /** * extend eventData for Hammer.gestures * @param {Object} evData * @returns {Object} evData */ extendEventData: function extendEventData(ev) { var cur = this.current , startEv = cur.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(ev.touches.length != startEv.touches.length || ev.touches === startEv.touches) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; Utils.each(ev.touches, function(touch) { startEv.touches.push(Utils.extend({}, touch)); }); } var delta_time = ev.timeStamp - startEv.timeStamp , delta_x = ev.center.clientX - startEv.center.clientX , delta_y = ev.center.clientY - startEv.center.clientY; this.getVelocityData(ev, delta_time, delta_x, delta_y); this.getInterimData(ev); Utils.extend(ev, { startEvent: startEv, deltaTime : delta_time, deltaX : delta_x, deltaY : delta_y, distance : Utils.getDistance(startEv.center, ev.center), angle : Utils.getAngle(startEv.center, ev.center), direction : Utils.getDirection(startEv.center, ev.center), scale : Utils.getScale(startEv.touches, ev.touches), rotation : Utils.getRotation(startEv.touches, ev.touches) }); return ev; }, /** * register new gesture * @param {Object} gesture object, see gestures.js for documentation * @returns {Array} gestures */ register: function register(gesture) { // add an enable gesture options if there is no given var options = gesture.defaults || {}; if(options[gesture.name] === undefined) { options[gesture.name] = true; } // extend Hammer default options with the Hammer.gesture options Utils.extend(Hammer.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add Hammer.gesture to the list this.gestures.push(gesture); // sort the list by index this.gestures.sort(function(a, b) { if(a.index < b.index) { return -1; } if(a.index > b.index) { return 1; } return 0; }); return this.gestures; } }; /** * Drag * Move with x fingers (default 1) around on the page. Blocking the scrolling when * moving left and right is a good practice. When all the drag events are blocking * you disable scrolling on that area. * @events drag, drapleft, dragright, dragup, dragdown */ Hammer.gestures.Drag = { name : 'drag', index : 50, defaults : { drag_min_distance : 10, // Set correct_for_drag_min_distance to true to make the starting point of the drag // be calculated from where the drag was triggered, not from where the touch started. // Useful to avoid a jerk-starting drag, which can make fine-adjustments // through dragging difficult, and be visually unappealing. correct_for_drag_min_distance: true, // set 0 for unlimited, but this can conflict with transform drag_max_touches : 1, // prevent default browser behavior when dragging occurs // be careful with it, it makes the element a blocking element // when you are using the drag gesture, it is a good practice to set this true drag_block_horizontal : false, drag_block_vertical : false, // drag_lock_to_axis keeps the drag gesture on the axis that it started on, // It disallows vertical directions if the initial direction was horizontal, and vice versa. drag_lock_to_axis : false, // drag lock only kicks in when distance > drag_lock_min_distance // This way, locking occurs only when the distance has become large enough to reliably determine the direction drag_lock_min_distance : 25 }, triggered: false, handler : function dragGesture(ev, inst) { var cur = Detection.current; // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(cur.name != this.name && this.triggered) { inst.trigger(this.name + 'end', ev); this.triggered = false; return; } // max touches if(inst.options.drag_max_touches > 0 && ev.touches.length > inst.options.drag_max_touches) { return; } switch(ev.eventType) { case EVENT_START: this.triggered = false; break; case EVENT_MOVE: // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.distance < inst.options.drag_min_distance && cur.name != this.name) { return; } var startCenter = cur.startEvent.center; // we are dragging! if(cur.name != this.name) { cur.name = this.name; if(inst.options.correct_for_drag_min_distance && ev.distance > 0) { // When a drag is triggered, set the event center to drag_min_distance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.drag_min_distance / ev.distance); startCenter.pageX += ev.deltaX * factor; startCenter.pageY += ev.deltaY * factor; startCenter.clientX += ev.deltaX * factor; startCenter.clientY += ev.deltaY * factor; // recalculate event data using new start point ev = Detection.extendEventData(ev); } } // lock drag to axis? if(cur.lastEvent.drag_locked_to_axis || ( inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance <= ev.distance )) { ev.drag_locked_to_axis = true; } var last_direction = cur.lastEvent.direction; if(ev.drag_locked_to_axis && last_direction !== ev.direction) { // keep direction on the axis that the drag gesture started on if(Utils.isVertical(last_direction)) { ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name + 'start', ev); this.triggered = true; } // trigger events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); var is_vertical = Utils.isVertical(ev.direction); // block the browser events if((inst.options.drag_block_vertical && is_vertical) || (inst.options.drag_block_horizontal && !is_vertical)) { ev.preventDefault(); } break; case EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name + 'end', ev); } this.triggered = false; break; } } }; /** * Hold * Touch stays at the same place for x time * @events hold */ Hammer.gestures.Hold = { name : 'hold', index : 10, defaults: { hold_timeout : 500, hold_threshold: 2 }, timer : null, handler : function holdGesture(ev, inst) { switch(ev.eventType) { case EVENT_START: // clear any running timers clearTimeout(this.timer); // set the gesture so we can check in the timeout if it still is Detection.current.name = this.name; // set timer and if after the timeout it still is hold, // we trigger the hold event this.timer = setTimeout(function() { if(Detection.current.name == 'hold') { inst.trigger('hold', ev); } }, inst.options.hold_timeout); break; // when you move or end we clear the timer case EVENT_MOVE: if(ev.distance > inst.options.hold_threshold) { clearTimeout(this.timer); } break; case EVENT_END: clearTimeout(this.timer); break; } } }; /** * Release * Called as last, tells the user has released the screen * @events release */ Hammer.gestures.Release = { name : 'release', index : Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == EVENT_END) { inst.trigger(this.name, ev); } } }; /** * Swipe * triggers swipe events when the end velocity is above the threshold * for best usage, set prevent_default (on the drag gesture) to true * @events swipe, swipeleft, swiperight, swipeup, swipedown */ Hammer.gestures.Swipe = { name : 'swipe', index : 40, defaults: { swipe_min_touches: 1, swipe_max_touches: 1, swipe_velocity : 0.7 }, handler : function swipeGesture(ev, inst) { if(ev.eventType == EVENT_END) { // max touches if(ev.touches.length < inst.options.swipe_min_touches || ev.touches.length > inst.options.swipe_max_touches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > inst.options.swipe_velocity || ev.velocityY > inst.options.swipe_velocity) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * Tap/DoubleTap * Quick touch at a place or double at the same place * @events tap, doubletap */ Hammer.gestures.Tap = { name : 'tap', index : 100, defaults: { tap_max_touchtime : 250, tap_max_distance : 10, tap_always : true, doubletap_distance: 20, doubletap_interval: 300 }, has_moved: false, handler : function tapGesture(ev, inst) { var prev, since_prev, did_doubletap; // reset moved state if(ev.eventType == EVENT_START) { this.has_moved = false; } // Track the distance we've moved. If it's above the max ONCE, remember that (fixes #406). else if(ev.eventType == EVENT_MOVE && !this.moved) { this.has_moved = (ev.distance > inst.options.tap_max_distance); } else if(ev.eventType == EVENT_END && ev.srcEvent.type != 'touchcancel' && ev.deltaTime < inst.options.tap_max_touchtime && !this.has_moved) { // previous gesture, for the double tap since these are two different gesture detections prev = Detection.previous; since_prev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp; did_doubletap = false; // check if double tap if(prev && prev.name == 'tap' && (since_prev && since_prev < inst.options.doubletap_interval) && ev.distance < inst.options.doubletap_distance) { inst.trigger('doubletap', ev); did_doubletap = true; } // do a single tap if(!did_doubletap || inst.options.tap_always) { Detection.current.name = 'tap'; inst.trigger(Detection.current.name, ev); } } } }; /** * Touch * Called as first, tells the user has touched the screen * @events touch */ Hammer.gestures.Touch = { name : 'touch', index : -Infinity, defaults: { // call preventDefault at touchstart, and makes the element blocking by // disabling the scrolling of the page, but it improves gestures like // transforming and dragging. // be careful with using this, it can be very annoying for users to be stuck // on the page prevent_default : false, // disable mouse events, so only touch (or pen!) input triggers events prevent_mouseevents: false }, handler : function touchGesture(ev, inst) { if(inst.options.prevent_mouseevents && ev.pointerType == POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.prevent_default) { ev.preventDefault(); } if(ev.eventType == EVENT_START) { inst.trigger(this.name, ev); } } }; /** * Transform * User want to scale or rotate with 2 fingers * @events transform, pinch, pinchin, pinchout, rotate */ Hammer.gestures.Transform = { name : 'transform', index : 45, defaults : { // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 transform_min_scale : 0.01, // rotation in degrees transform_min_rotation : 1, // prevent default browser behavior when two touches are on the screen // but it makes the element a blocking element // when you are using the transform gesture, it is a good practice to set this true transform_always_block : false, // ensures that all touches occurred within the instance element transform_within_instance: false }, triggered: false, handler : function transformGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(Detection.current.name != this.name && this.triggered) { inst.trigger(this.name + 'end', ev); this.triggered = false; return; } // at least multitouch if(ev.touches.length < 2) { return; } // prevent default when two fingers are on the screen if(inst.options.transform_always_block) { ev.preventDefault(); } // check if all touches occurred within the instance element if(inst.options.transform_within_instance) { for(var i=-1; ev.touches[++i];) { if(!Utils.hasParent(ev.touches[i].target, inst.element)) { return; } } } switch(ev.eventType) { case EVENT_START: this.triggered = false; break; case EVENT_MOVE: var scale_threshold = Math.abs(1 - ev.scale); var rotation_threshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scale_threshold < inst.options.transform_min_scale && rotation_threshold < inst.options.transform_min_rotation) { return; } // we are transforming! Detection.current.name = this.name; // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name + 'start', ev); this.triggered = true; } inst.trigger(this.name, ev); // basic transform event // trigger rotate event if(rotation_threshold > inst.options.transform_min_rotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scale_threshold > inst.options.transform_min_scale) { inst.trigger('pinch', ev); inst.trigger('pinch' + (ev.scale<1 ? 'in' : 'out'), ev); } break; case EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name + 'end', ev); } this.triggered = false; break; } } }; // AMD export if(typeof define == 'function' && define.amd) { define(function(){ return Hammer; }); } // commonjs export else if(typeof module == 'object' && module.exports) { module.exports = Hammer; } // browser export else { window.Hammer = Hammer; } })(window);
//>>built define("dojox/rpc/JsonRest",["dojo","dojox","dojox/json/ref","dojox/rpc/Rest"],function(_1,_2){ var _3=[]; var _4=_2.rpc.Rest; var jr; function _5(_6,_7,_8,_9){ var _a=_7.ioArgs&&_7.ioArgs.xhr&&_7.ioArgs.xhr.getResponseHeader("Last-Modified"); if(_a&&_4._timeStamps){ _4._timeStamps[_9]=_a; } var _b=_6._schema&&_6._schema.hrefProperty; if(_b){ _2.json.ref.refAttribute=_b; } _8=_8&&_2.json.ref.resolveJson(_8,{defaultId:_9,index:_4._index,timeStamps:_a&&_4._timeStamps,time:_a,idPrefix:_6._store.allowNoTrailingSlash?_6.servicePath+"/":_6.servicePath.replace(/[^\/]*$/,""),idAttribute:jr.getIdAttribute(_6),schemas:jr.schemas,loader:jr._loader,idAsRef:_6.idAsRef,assignAbsoluteIds:true}); _2.json.ref.refAttribute="$ref"; return _8; }; jr=_2.rpc.JsonRest={serviceClass:_2.rpc.Rest,conflictDateHeader:"If-Unmodified-Since",commit:function(_c){ _c=_c||{}; var _d=[]; var _e={}; var _f=[]; for(var i=0;i<_3.length;i++){ var _10=_3[i]; var _11=_10.object; var old=_10.old; var _12=false; if(!(_c.service&&(_11||old)&&(_11||old).__id.indexOf(_c.service.servicePath))&&_10.save){ delete _11.__isDirty; if(_11){ if(old){ var _13; if((_13=_11.__id.match(/(.*)#.*/))){ _11=_4._index[_13[1]]; } if(!(_11.__id in _e)){ _e[_11.__id]=_11; if(_c.incrementalUpdates&&!_13){ var _14=(typeof _c.incrementalUpdates=="function"?_c.incrementalUpdates:function(){ _14={}; for(var j in _11){ if(_11.hasOwnProperty(j)){ if(_11[j]!==old[j]){ _14[j]=_11[j]; } }else{ if(old.hasOwnProperty(j)){ return null; } } } return _14; })(_11,old); } if(_14){ _d.push({method:"post",target:_11,content:_14}); }else{ _d.push({method:"put",target:_11,content:_11}); } } }else{ var _15=jr.getServiceAndId(_11.__id).service; var _16=jr.getIdAttribute(_15); if((_16 in _11)&&!_c.alwaysPostNewItems){ _d.push({method:"put",target:_11,content:_11}); }else{ _d.push({method:"post",target:{__id:_15.servicePath},content:_11}); } } }else{ if(old){ _d.push({method:"delete",target:old}); } } _f.push(_10); _3.splice(i--,1); } } _1.connect(_c,"onError",function(){ if(_c.revertOnError!==false){ var _17=_3; _3=_f; var _18=0; jr.revert(); _3=_17; }else{ _1.forEach(_f,function(obj){ jr.changing(obj.object,!obj.object); }); } }); jr.sendToServer(_d,_c); return _d; },sendToServer:function(_19,_1a){ var _1b; var _1c=_1.xhr; var _1d=_19.length; var i,_1e; var _1f; var _20=this.conflictDateHeader; _1.xhr=function(_21,_22){ _22.headers=_22.headers||{}; _22.headers["Transaction"]=_19.length-1==i?"commit":"open"; if(_20&&_1f){ _22.headers[_20]=_1f; } if(_1e){ _22.headers["Content-ID"]="<"+_1e+">"; } return _1c.apply(_1,arguments); }; for(i=0;i<_19.length;i++){ var _23=_19[i]; _2.rpc.JsonRest._contentId=_23.content&&_23.content.__id; var _24=_23.method=="post"; _1f=_23.method=="put"&&_4._timeStamps[_23.content.__id]; if(_1f){ _4._timeStamps[_23.content.__id]=(new Date())+""; } _1e=_24&&_2.rpc.JsonRest._contentId; var _25=jr.getServiceAndId(_23.target.__id); var _26=_25.service; var dfd=_23.deferred=_26[_23.method](_25.id.replace(/#/,""),_2.json.ref.toJson(_23.content,false,_26.servicePath,true)); (function(_27,dfd,_28){ dfd.addCallback(function(_29){ try{ var _2a=dfd.ioArgs.xhr&&dfd.ioArgs.xhr.getResponseHeader("Location"); if(_2a){ var _2b=_2a.match(/(^\w+:\/\/)/)&&_2a.indexOf(_28.servicePath); _2a=_2b>0?_2a.substring(_2b):(_28.servicePath+_2a).replace(/^(.*\/)?(\w+:\/\/)|[^\/\.]+\/\.\.\/|^.*\/(\/)/,"$2$3"); _27.__id=_2a; _4._index[_2a]=_27; } _29=_5(_28,dfd,_29,_27&&_27.__id); } catch(e){ } if(!(--_1d)){ if(_1a.onComplete){ _1a.onComplete.call(_1a.scope,_19); } } return _29; }); })(_23.content,dfd,_26); dfd.addErrback(function(_2c){ _1d=-1; _1a.onError.call(_1a.scope,_2c); }); } _1.xhr=_1c; },getDirtyObjects:function(){ return _3; },revert:function(_2d){ for(var i=_3.length;i>0;){ i--; var _2e=_3[i]; var _2f=_2e.object; var old=_2e.old; var _30=_2.data._getStoreForItem(_2f||old); if(!(_2d&&(_2f||old)&&(_2f||old).__id.indexOf(_2d.servicePath))){ if(_2f&&old){ for(var j in old){ if(old.hasOwnProperty(j)&&_2f[j]!==old[j]){ if(_30){ _30.onSet(_2f,j,_2f[j],old[j]); } _2f[j]=old[j]; } } for(j in _2f){ if(!old.hasOwnProperty(j)){ if(_30){ _30.onSet(_2f,j,_2f[j]); } delete _2f[j]; } } }else{ if(!old){ if(_30){ _30.onDelete(_2f); } }else{ if(_30){ _30.onNew(old); } } } delete (_2f||old).__isDirty; _3.splice(i,1); } } },changing:function(_31,_32){ if(!_31.__id){ return; } _31.__isDirty=true; for(var i=0;i<_3.length;i++){ var _33=_3[i]; if(_31==_33.object){ if(_32){ _33.object=false; if(!this._saveNotNeeded){ _33.save=true; } } return; } } var old=_31 instanceof Array?[]:{}; for(i in _31){ if(_31.hasOwnProperty(i)){ old[i]=_31[i]; } } _3.push({object:!_32&&_31,old:old,save:!this._saveNotNeeded}); },deleteObject:function(_34){ this.changing(_34,true); },getConstructor:function(_35,_36){ if(typeof _35=="string"){ var _37=_35; _35=new _2.rpc.Rest(_35,true); this.registerService(_35,_37,_36); } if(_35._constructor){ return _35._constructor; } _35._constructor=function(_38){ var _39=this; var _3a=arguments; var _3b; var _3c; function _3d(_3e){ if(_3e){ _3d(_3e["extends"]); _3b=_3e.properties; for(var i in _3b){ var _3f=_3b[i]; if(_3f&&(typeof _3f=="object")&&("default" in _3f)){ _39[i]=_3f["default"]; } } } if(_3e&&_3e.prototype&&_3e.prototype.initialize){ _3c=true; _3e.prototype.initialize.apply(_39,_3a); } }; _3d(_35._schema); if(!_3c&&_38&&typeof _38=="object"){ _1.mixin(_39,_38); } var _40=jr.getIdAttribute(_35); _4._index[this.__id=this.__clientId=_35.servicePath+(this[_40]||Math.random().toString(16).substring(2,14)+"@"+((_2.rpc.Client&&_2.rpc.Client.clientId)||"client"))]=this; if(_2.json.schema&&_3b){ _2.json.schema.mustBeValid(_2.json.schema.validate(this,_35._schema)); } _3.push({object:this,save:true}); }; return _1.mixin(_35._constructor,_35._schema,{load:_35}); },fetch:function(_41){ var _42=jr.getServiceAndId(_41); return this.byId(_42.service,_42.id); },getIdAttribute:function(_43){ var _44=_43._schema; var _45; if(_44){ if(!(_45=_44._idAttr)){ for(var i in _44.properties){ if(_44.properties[i].identity||(_44.properties[i].link=="self")){ _44._idAttr=_45=i; } } } } return _45||"id"; },getServiceAndId:function(_46){ var _47=""; for(var _48 in jr.services){ if((_46.substring(0,_48.length)==_48)&&(_48.length>=_47.length)){ _47=_48; } } if(_47){ return {service:jr.services[_47],id:_46.substring(_47.length)}; } var _49=_46.match(/^(.*\/)([^\/]*)$/); return {service:new jr.serviceClass(_49[1],true),id:_49[2]}; },services:{},schemas:{},registerService:function(_4a,_4b,_4c){ _4b=_4a.servicePath=_4b||_4a.servicePath; _4a._schema=jr.schemas[_4b]=_4c||_4a._schema||{}; jr.services[_4b]=_4a; },byId:function(_4d,id){ var _4e,_4f=_4._index[(_4d.servicePath||"")+id]; if(_4f&&!_4f._loadObject){ _4e=new _1.Deferred(); _4e.callback(_4f); return _4e; } return this.query(_4d,id); },query:function(_50,id,_51){ var _52=_50(id,_51); _52.addCallback(function(_53){ if(_53.nodeType&&_53.cloneNode){ return _53; } return _5(_50,_52,_53,typeof id!="string"||(_51&&(_51.start||_51.count))?undefined:id); }); return _52; },_loader:function(_54){ var _55=jr.getServiceAndId(this.__id); var _56=this; jr.query(_55.service,_55.id).addBoth(function(_57){ if(_57==_56){ delete _57.$ref; delete _57._loadObject; }else{ _56._loadObject=function(_58){ _58(_57); }; } _54(_57); }); },isDirty:function(_59,_5a){ if(!_59){ if(_5a){ return _1.some(_3,function(_5b){ return _2.data._getStoreForItem(_5b.object||_5b.old)==_5a; }); } return !!_3.length; } return _59.__isDirty; }}; return _2.rpc.JsonRest; });
/** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactLegacyElement */ "use strict"; var ReactCurrentOwner = require('ReactCurrentOwner'); var invariant = require('invariant'); var monitorCodeUse = require('monitorCodeUse'); var warning = require('warning'); var legacyFactoryLogs = {}; function warnForLegacyFactoryCall() { if (!ReactLegacyElementFactory._isLegacyCallWarningEnabled) { return; } var owner = ReactCurrentOwner.current; var name = owner && owner.constructor ? owner.constructor.displayName : ''; if (!name) { name = 'Something'; } if (legacyFactoryLogs.hasOwnProperty(name)) { return; } legacyFactoryLogs[name] = true; warning( false, name + ' is calling a React component directly. ' + 'Use a factory or JSX instead. See: http://fb.me/react-legacyfactory' ); monitorCodeUse('react_legacy_factory_call', { version: 3, name: name }); } function warnForPlainFunctionType(type) { var isReactClass = type.prototype && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; if (isReactClass) { warning( false, 'Did not expect to get a React class here. Use `Component` instead ' + 'of `Component.type` or `this.constructor`.' ); } else { if (!type._reactWarnedForThisType) { try { type._reactWarnedForThisType = true; } catch (x) { // just incase this is a frozen object or some special object } monitorCodeUse( 'react_non_component_in_jsx', { version: 3, name: type.name } ); } warning( false, 'This JSX uses a plain function. Only React components are ' + 'valid in React\'s JSX transform.' ); } } function warnForNonLegacyFactory(type) { warning( false, 'Do not pass React.DOM.' + type.type + ' to JSX or createFactory. ' + 'Use the string "' + type.type + '" instead.' ); } /** * Transfer static properties from the source to the target. Functions are * rebound to have this reflect the original source. */ function proxyStaticMethods(target, source) { if (typeof source !== 'function') { return; } for (var key in source) { if (source.hasOwnProperty(key)) { var value = source[key]; if (typeof value === 'function') { var bound = value.bind(source); // Copy any properties defined on the function, such as `isRequired` on // a PropTypes validator. for (var k in value) { if (value.hasOwnProperty(k)) { bound[k] = value[k]; } } target[key] = bound; } else { target[key] = value; } } } } // We use an object instead of a boolean because booleans are ignored by our // mocking libraries when these factories gets mocked. var LEGACY_MARKER = {}; var NON_LEGACY_MARKER = {}; var ReactLegacyElementFactory = {}; ReactLegacyElementFactory.wrapCreateFactory = function(createFactory) { var legacyCreateFactory = function(type) { if (typeof type !== 'function') { // Non-function types cannot be legacy factories return createFactory(type); } if (type.isReactNonLegacyFactory) { // This is probably a factory created by ReactDOM we unwrap it to get to // the underlying string type. It shouldn't have been passed here so we // warn. if (__DEV__) { warnForNonLegacyFactory(type); } return createFactory(type.type); } if (type.isReactLegacyFactory) { // This is probably a legacy factory created by ReactCompositeComponent. // We unwrap it to get to the underlying class. return createFactory(type.type); } if (__DEV__) { warnForPlainFunctionType(type); } // Unless it's a legacy factory, then this is probably a plain function, // that is expecting to be invoked by JSX. We can just return it as is. return type; }; return legacyCreateFactory; }; ReactLegacyElementFactory.wrapCreateElement = function(createElement) { var legacyCreateElement = function(type, props, children) { if (typeof type !== 'function') { // Non-function types cannot be legacy factories return createElement.apply(this, arguments); } var args; if (type.isReactNonLegacyFactory) { // This is probably a factory created by ReactDOM we unwrap it to get to // the underlying string type. It shouldn't have been passed here so we // warn. if (__DEV__) { warnForNonLegacyFactory(type); } args = Array.prototype.slice.call(arguments, 0); args[0] = type.type; return createElement.apply(this, args); } if (type.isReactLegacyFactory) { // This is probably a legacy factory created by ReactCompositeComponent. // We unwrap it to get to the underlying class. if (type._isMockFunction) { // If this is a mock function, people will expect it to be called. We // will actually call the original mock factory function instead. This // future proofs unit testing that assume that these are classes. type.type._mockedReactClassConstructor = type; } args = Array.prototype.slice.call(arguments, 0); args[0] = type.type; return createElement.apply(this, args); } if (__DEV__) { warnForPlainFunctionType(type); } // This is being called with a plain function we should invoke it // immediately as if this was used with legacy JSX. return type.apply(null, Array.prototype.slice.call(arguments, 1)); }; return legacyCreateElement; }; ReactLegacyElementFactory.wrapFactory = function(factory) { invariant( typeof factory === 'function', 'This is suppose to accept a element factory' ); var legacyElementFactory = function(config, children) { // This factory should not be called when JSX is used. Use JSX instead. if (__DEV__) { warnForLegacyFactoryCall(); } return factory.apply(this, arguments); }; proxyStaticMethods(legacyElementFactory, factory.type); legacyElementFactory.isReactLegacyFactory = LEGACY_MARKER; legacyElementFactory.type = factory.type; return legacyElementFactory; }; // This is used to mark a factory that will remain. E.g. we're allowed to call // it as a function. However, you're not suppose to pass it to createElement // or createFactory, so it will warn you if you do. ReactLegacyElementFactory.markNonLegacyFactory = function(factory) { factory.isReactNonLegacyFactory = NON_LEGACY_MARKER; return factory; }; // Checks if a factory function is actually a legacy factory pretending to // be a class. ReactLegacyElementFactory.isValidFactory = function(factory) { // TODO: This will be removed and moved into a class validator or something. return typeof factory === 'function' && factory.isReactLegacyFactory === LEGACY_MARKER; }; ReactLegacyElementFactory.isValidClass = function(factory) { if (__DEV__) { warning( false, 'isValidClass is deprecated and will be removed in a future release. ' + 'Use a more specific validator instead.' ); } return ReactLegacyElementFactory.isValidFactory(factory); }; ReactLegacyElementFactory._isLegacyCallWarningEnabled = true; module.exports = ReactLegacyElementFactory;
'use strict'; /* jshint -W030 */ var chai = require('chai') , expect = chai.expect , Support = require(__dirname + '/../support') , current = Support.sequelize; describe(Support.getTestDialectTeaser('Model'), function() { var Project = current.define('project') , User = current.define('user') , Company; var scopes = { complexFunction: function(value) { return { where: [(value + ' IN (SELECT foobar FROM some_sql_function(foo.bar))')] }; }, somethingTrue: { where: { something: true, somethingElse: 42 }, limit: 5 }, somethingFalse: { where: { something: false } }, users: { include: [ { model: User } ] }, alsoUsers: { include: [ { model: User, where: { something: 42}} ] }, projects: { include: [Project] }, noArgs: function () { // This does not make much sense, since it does not actually need to be in a function, // In reality it could be used to do for example new Date or random in the scope - but we want it deterministic return { where: { other_value: 7 } }; }, actualValue: function(value) { return { where: { other_value: value } }; }, }; Company = current.define('company', {}, { defaultScope: { include: [Project], where: { active: true } }, scopes: scopes }); describe('.scope', function () { it('should apply default scope', function () { expect(Company.$scope).to.deep.equal({ include: [{ model: Project }], where: { active: true } }); }); it('should be able to unscope', function () { expect(Company.scope(null).$scope).to.be.empty; expect(Company.unscoped().$scope).to.be.empty; }); it('should be able to merge scopes', function() { expect(Company.scope('somethingTrue', 'somethingFalse').$scope).to.deep.equal({ where: { something: false, somethingElse: 42 }, limit: 5 }); }); it('should support multiple, coexistent scoped models', function () { var scoped1 = Company.scope('somethingTrue') , scoped2 = Company.scope('somethingFalse'); expect(scoped1.$scope).to.deep.equal(scopes.somethingTrue); expect(scoped2.$scope).to.deep.equal(scopes.somethingFalse); }); it('should work with function scopes', function () { expect(Company.scope({method: ['actualValue', 11]}).$scope).to.deep.equal({ where: { other_value: 11 } }); expect(Company.scope('noArgs').$scope).to.deep.equal({ where: { other_value: 7 } }); }); it('should be able to merge two scoped includes', function () { expect(Company.scope('users', 'projects').$scope).to.deep.equal({ include: [ { model: User }, { model: Project } ] }); }); it('should be able to override the default scope', function() { expect(Company.scope('somethingTrue').$scope).to.deep.equal(scopes.somethingTrue); }); it('should be able to combine default with another scope', function () { expect(Company.scope(['defaultScope', {method: ['actualValue', 11]}]).$scope).to.deep.equal({ include: [{ model: Project }], where: { active: true, other_value: 11 } }); }); it('should be able to use raw queries', function () { expect(Company.scope([{method: ['complexFunction', 'qux']}]).$scope).to.deep.equal({ where: [ 'qux IN (SELECT foobar FROM some_sql_function(foo.bar))' ] }); }); it('should override the default scope', function () { expect(Company.scope(['defaultScope', {method: ['complexFunction', 'qux']}]).$scope).to.deep.equal({ include: [{ model: Project }], where: [ 'qux IN (SELECT foobar FROM some_sql_function(foo.bar))' ] }); }); it('should emit an error for scopes that dont exist', function() { expect(function () { Company.scope('doesntexist'); }).to.throw('Invalid scope doesntexist called.'); }); }); describe('addScope', function () { it('works if the model does not have any initial scopes', function () { var Model = current.define('model'); expect(function () { Model.addScope('anything', {}); }).not.to.throw(); }); it('allows me to add a new scope', function () { expect(function () { Company.scope('newScope'); }).to.throw('Invalid scope newScope called.'); Company.addScope('newScope', { where: { this: 'that' }, include: [Project] }); expect(Company.scope('newScope').$scope).to.deep.equal({ where: { this: 'that' }, include: [{ model: Project }] }); }); it('warns me when overriding an existing scope', function () { expect(function () { Company.addScope('somethingTrue', {}); }).to.throw('The scope somethingTrue already exists. Pass { override: true } as options to silence this error'); }); it('allows me to override an existing scope', function () { Company.addScope('somethingTrue', { where: { something: false } }, { override: true }); expect(Company.scope('somethingTrue').$scope).to.deep.equal({ where: { something: false }, }); }); it('warns me when overriding an existing default scope', function () { expect(function () { Company.addScope('defaultScope', {}); }).to.throw('The scope defaultScope already exists. Pass { override: true } as options to silence this error'); }); it('allows me to override a default scope', function () { Company.addScope('defaultScope', { include: [Project] }, { override: true }); expect(Company.$scope).to.deep.equal({ include: [{ model: Project }] }); }); }); describe('$injectScope', function () { it('should be able to merge scope and where', function () { var scope = { where: { something: true, somethingElse: 42 }, limit: 15, offset: 3 }; var options = { where: { something: false }, limit: 9 }; current.Model.$injectScope(scope, options); expect(options).to.deep.equal({ where: { something: false, somethingElse: 42 }, limit: 9, offset: 3 }); }); it('should be able to overwrite multiple scopes with the same include', function () { var scope = { include: [ { model: Project, where: { something: false }}, { model: Project, where: { something: true }} ] }; var options = {}; current.Model.$injectScope(scope, options); expect(options.include).to.have.length(1); expect(options.include[0]).to.deep.equal({ model: Project, where: { something: true }}); }); it('should be able to override scoped include', function () { var scope = { include: [{ model: Project, where: { something: false }}] }; var options = { include: [{ model: Project, where: { something: true }}] }; current.Model.$injectScope(scope, options); expect(options.include).to.have.length(1); expect(options.include[0]).to.deep.equal({ model: Project, where: { something: true }}); }); it('should be able to merge aliassed includes with the same model', function () { var scope = { include: [{model: User, as: 'someUser'}] }; var options = { include: [{model: User, as: 'otherUser'}] }; current.Model.$injectScope(scope, options); expect(options.include).to.have.length(2); expect(options.include[0]).to.deep.equal({model: User, as: 'otherUser'}); expect(options.include[1]).to.deep.equal({model: User, as: 'someUser'}); }); it('should be able to merge scoped include with include in find', function () { var scope = { include: [ { model: Project, where: { something: false }} ] }; var options = { include: [ { model: User, where: { something: true }} ] }; current.Model.$injectScope(scope, options); expect(options.include).to.have.length(2); expect(options.include[0]).to.deep.equal({ model: User, where: { something: true }}); expect(options.include[1]).to.deep.equal({ model: Project, where: { something: false }}); }); }); });
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.structs.SetTest'); goog.setTestOnly('goog.structs.SetTest'); goog.require('goog.iter'); goog.require('goog.structs'); goog.require('goog.structs.Set'); goog.require('goog.testing.jsunit'); var Set = goog.structs.Set; function stringifySet(s) { return goog.structs.getValues(s).join(''); } function testGetCount() { var s = new Set; var a = new String('a'); s.add(a); var b = new String('b'); s.add(b); var c = new String('c'); s.add(c); assertEquals('count, should be 3', s.getCount(), 3); var d = new String('d'); s.add(d); assertEquals('count, should be 4', s.getCount(), 4); s.remove(d); assertEquals('count, should be 3', s.getCount(), 3); s = new Set; s.add('a'); s.add('b'); s.add('c'); assertEquals('count, should be 3', s.getCount(), 3); s.add('d'); assertEquals('count, should be 4', s.getCount(), 4); s.remove('d'); assertEquals('count, should be 3', s.getCount(), 3); } function testGetValues() { var s = new Set; var a = new String('a'); s.add(a); var b = new String('b'); s.add(b); var c = new String('c'); s.add(c); var d = new String('d'); s.add(d); assertEquals(s.getValues().join(''), 'abcd'); var s = new Set; s.add('a'); s.add('b'); s.add('c'); s.add('d'); assertEquals(s.getValues().join(''), 'abcd'); } function testContains() { var s = new Set; var a = new String('a'); s.add(a); var b = new String('b'); s.add(b); var c = new String('c'); s.add(c); var d = new String('d'); s.add(d); var e = new String('e'); assertTrue("contains, Should contain 'a'", s.contains(a)); assertFalse("contains, Should not contain 'e'", s.contains(e)); s = new Set; s.add('a'); s.add('b'); s.add('c'); s.add('d'); assertTrue("contains, Should contain 'a'", s.contains('a')); assertFalse("contains, Should not contain 'e'", s.contains('e')); } function testContainsFunctionValue() { var s = new Set; var fn1 = function() {}; assertFalse(s.contains(fn1)); s.add(fn1); assertTrue(s.contains(fn1)); var fn2 = function() {}; assertFalse(s.contains(fn2)); s.add(fn2); assertTrue(s.contains(fn2)); assertEquals(s.getCount(), 2); } function testContainsAll() { var set = new Set([1, 2, 3]); assertTrue('{1, 2, 3} contains []', set.containsAll([])); assertTrue('{1, 2, 3} contains [1]', set.containsAll([1])); assertTrue('{1, 2, 3} contains [1, 1]', set.containsAll([1, 1])); assertTrue('{1, 2, 3} contains [3, 2, 1]', set.containsAll([3, 2, 1])); assertFalse("{1, 2, 3} doesn't contain [4]", set.containsAll([4])); assertFalse("{1, 2, 3} doesn't contain [1, 4]", set.containsAll([1, 4])); assertTrue('{1, 2, 3} contains {a: 1}', set.containsAll({a: 1})); assertFalse("{1, 2, 3} doesn't contain {a: 4}", set.containsAll({a: 4})); assertTrue('{1, 2, 3} contains {1}', set.containsAll(new Set([1]))); assertFalse("{1, 2, 3} doesn't contain {4}", set.containsAll(new Set([4]))); } function testIntersection() { var emptySet = new Set; assertTrue( 'intersection of empty set and [] should be empty', emptySet.intersection([]).isEmpty()); assertIntersection( 'intersection of 2 empty sets should be empty', emptySet, new Set(), new Set()); var abcdSet = new Set(); abcdSet.add('a'); abcdSet.add('b'); abcdSet.add('c'); abcdSet.add('d'); assertTrue( 'intersection of populated set and [] should be empty', abcdSet.intersection([]).isEmpty()); assertIntersection( 'intersection of populated set and empty set should be empty', abcdSet, new Set(), new Set()); var bcSet = new Set(['b', 'c']); assertIntersection( 'intersection of [a,b,c,d] and [b,c]', abcdSet, bcSet, bcSet); var bceSet = new Set(['b', 'c', 'e']); assertIntersection( 'intersection of [a,b,c,d] and [b,c,e]', abcdSet, bceSet, bcSet); } function testDifference() { var emptySet = new Set; assertTrue( 'difference of empty set and [] should be empty', emptySet.difference([]).isEmpty()); assertTrue( 'difference of 2 empty sets should be empty', emptySet.difference(new Set()).isEmpty()); var abcdSet = new Set(['a', 'b', 'c', 'd']); assertTrue( 'difference of populated set and [] should be the populated set', abcdSet.difference([]).equals(abcdSet)); assertTrue( 'difference of populated set and empty set should be the populated set', abcdSet.difference(new Set()).equals(abcdSet)); assertTrue( 'difference of two identical sets should be the empty set', abcdSet.difference(abcdSet).equals(new Set())); var bcSet = new Set(['b', 'c']); assertTrue( 'difference of [a,b,c,d] and [b,c] shoule be [a,d]', abcdSet.difference(bcSet).equals(new Set(['a', 'd']))); assertTrue( 'difference of [b,c] and [a,b,c,d] should be the empty set', bcSet.difference(abcdSet).equals(new Set())); var xyzSet = new Set(['x', 'y', 'z']); assertTrue( 'difference of [a,b,c,d] and [x,y,z] should be the [a,b,c,d]', abcdSet.difference(xyzSet).equals(abcdSet)); } /** * Helper function to assert intersection is commutative. */ function assertIntersection(msg, set1, set2, expectedIntersection) { assertTrue( msg + ': set1->set2', set1.intersection(set2).equals(expectedIntersection)); assertTrue( msg + ': set2->set1', set2.intersection(set1).equals(expectedIntersection)); } function testRemoveAll() { assertRemoveAll('removeAll of empty set from empty set', [], [], []); assertRemoveAll( 'removeAll of empty set from populated set', ['a', 'b', 'c', 'd'], [], ['a', 'b', 'c', 'd']); assertRemoveAll( 'removeAll of [a,d] from [a,b,c,d]', ['a', 'b', 'c', 'd'], ['a', 'd'], ['b', 'c']); assertRemoveAll( 'removeAll of [b,c] from [a,b,c,d]', ['a', 'b', 'c', 'd'], ['b', 'c'], ['a', 'd']); assertRemoveAll( 'removeAll of [b,c,e] from [a,b,c,d]', ['a', 'b', 'c', 'd'], ['b', 'c', 'e'], ['a', 'd']); assertRemoveAll( 'removeAll of [a,b,c,d] from [a,d]', ['a', 'd'], ['a', 'b', 'c', 'd'], []); assertRemoveAll( 'removeAll of [a,b,c,d] from [b,c]', ['b', 'c'], ['a', 'b', 'c', 'd'], []); assertRemoveAll( 'removeAll of [a,b,c,d] from [b,c,e]', ['b', 'c', 'e'], ['a', 'b', 'c', 'd'], ['e']); } /** * Helper function to test removeAll. */ function assertRemoveAll(msg, elements1, elements2, expectedResult) { var set1 = new Set(elements1); var set2 = new Set(elements2); set1.removeAll(set2); assertTrue( msg + ': set1 count increased after removeAll', elements1.length >= set1.getCount()); assertEquals( msg + ': set2 count changed after removeAll', elements2.length, set2.getCount()); assertTrue(msg + ': wrong set1 after removeAll', set1.equals(expectedResult)); assertIntersection( msg + ': non-empty intersection after removeAll', set1, set2, []); } function testAdd() { var s = new Set; var a = new String('a'); var b = new String('b'); s.add(a); assertTrue(s.contains(a)); s.add(b); assertTrue(s.contains(b)); s = new Set; s.add('a'); assertTrue(s.contains('a')); s.add('b'); assertTrue(s.contains('b')); s.add(null); assertTrue('contains null', s.contains(null)); assertFalse('does not contain "null"', s.contains('null')); } function testClear() { var s = new Set; var a = new String('a'); s.add(a); var b = new String('b'); s.add(b); var c = new String('c'); s.add(c); var d = new String('d'); s.add(d); s.clear(); assertTrue('cleared so it should be empty', s.isEmpty()); assertTrue("cleared so it should not contain 'a' key", !s.contains(a)); s = new Set; s.add('a'); s.add('b'); s.add('c'); s.add('d'); s.clear(); assertTrue('cleared so it should be empty', s.isEmpty()); assertTrue("cleared so it should not contain 'a' key", !s.contains('a')); } function testAddAll() { var s = new Set; var a = new String('a'); var b = new String('b'); var c = new String('c'); var d = new String('d'); s.addAll([a, b, c, d]); assertTrue('addAll so it should not be empty', !s.isEmpty()); assertTrue("addAll so it should contain 'c' key", s.contains(c)); var s2 = new Set; s2.addAll(s); assertTrue('addAll so it should not be empty', !s2.isEmpty()); assertTrue("addAll so it should contain 'c' key", s2.contains(c)); s = new Set; s.addAll(['a', 'b', 'c', 'd']); assertTrue('addAll so it should not be empty', !s.isEmpty()); assertTrue("addAll so it should contain 'c' key", s.contains('c')); s2 = new Set; s2.addAll(s); assertTrue('addAll so it should not be empty', !s2.isEmpty()); assertTrue("addAll so it should contain 'c' key", s2.contains('c')); } function testConstructor() { var s = new Set; var a = new String('a'); s.add(a); var b = new String('b'); s.add(b); var c = new String('c'); s.add(c); var d = new String('d'); s.add(d); var s2 = new Set(s); assertFalse('constr with Set so it should not be empty', s2.isEmpty()); assertTrue('constr with Set so it should contain c', s2.contains(c)); s = new Set; s.add('a'); s.add('b'); s.add('c'); s.add('d'); s2 = new Set(s); assertFalse('constr with Set so it should not be empty', s2.isEmpty()); assertTrue('constr with Set so it should contain c', s2.contains('c')); } function testClone() { var s = new Set; var a = new String('a'); s.add(a); var b = new String('b'); s.add(b); var c = new String('c'); s.add(c); var d = new String('d'); s.add(d); var s2 = s.clone(); assertFalse('clone so it should not be empty', s2.isEmpty()); assertTrue("clone so it should contain 'c' key", s2.contains(c)); var s = new Set; s.add('a'); s.add('b'); s.add('c'); s.add('d'); s2 = s.clone(); assertFalse('clone so it should not be empty', s2.isEmpty()); assertTrue("clone so it should contain 'c' key", s2.contains('c')); } /** * Helper method for testEquals(). * @param {Object} a First element to use in the tests. * @param {Object} b Second element to use in the tests. * @param {Object} c Third element to use in the tests. * @param {Object} d Fourth element to use in the tests. */ function helperForTestEquals(a, b, c, d) { var s = new Set([a, b, c]); assertTrue('set == itself', s.equals(s)); assertTrue('set == same set', s.equals(new Set([a, b, c]))); assertTrue('set == its clone', s.equals(s.clone())); assertTrue('set == array of same elements', s.equals([a, b, c])); assertTrue( 'set == array of same elements in different order', s.equals([c, b, a])); assertFalse('set != empty set', s.equals(new Set)); assertFalse('set != its subset', s.equals(new Set([a, c]))); assertFalse('set != its superset', s.equals(new Set([a, b, c, d]))); assertFalse('set != different set', s.equals(new Set([b, c, d]))); assertFalse('set != its subset as array', s.equals([a, c])); assertFalse('set != its superset as array', s.equals([a, b, c, d])); assertFalse('set != different set as array', s.equals([b, c, d])); assertFalse('set != [a, b, c, c]', s.equals([a, b, c, c])); assertFalse('set != [a, b, b]', s.equals([a, b, b])); assertFalse('set != [a, a]', s.equals([a, a])); } function testEquals() { helperForTestEquals(1, 2, 3, 4); helperForTestEquals('a', 'b', 'c', 'd'); helperForTestEquals( new String('a'), new String('b'), new String('c'), new String('d')); } /** * Helper method for testIsSubsetOf(). * @param {Object} a First element to use in the tests. * @param {Object} b Second element to use in the tests. * @param {Object} c Third element to use in the tests. * @param {Object} d Fourth element to use in the tests. */ function helperForTestIsSubsetOf(a, b, c, d) { var s = new Set([a, b, c]); assertTrue('set <= itself', s.isSubsetOf(s)); assertTrue('set <= same set', s.isSubsetOf(new Set([a, b, c]))); assertTrue('set <= its clone', s.isSubsetOf(s.clone())); assertTrue('set <= array of same elements', s.isSubsetOf([a, b, c])); assertTrue( 'set <= array of same elements in different order', s.equals([c, b, a])); assertTrue('set <= Set([a, b, c, d])', s.isSubsetOf(new Set([a, b, c, d]))); assertTrue('set <= [a, b, c, d]', s.isSubsetOf([a, b, c, d])); assertTrue('set <= [a, b, c, c]', s.isSubsetOf([a, b, c, c])); assertFalse('set !<= Set([a, b])', s.isSubsetOf(new Set([a, b]))); assertFalse('set !<= [a, b]', s.isSubsetOf([a, b])); assertFalse('set !<= Set([c, d])', s.isSubsetOf(new Set([c, d]))); assertFalse('set !<= [c, d]', s.isSubsetOf([c, d])); assertFalse('set !<= Set([a, c, d])', s.isSubsetOf(new Set([a, c, d]))); assertFalse('set !<= [a, c, d]', s.isSubsetOf([a, c, d])); assertFalse('set !<= [a, a, b]', s.isSubsetOf([a, a, b])); assertFalse('set !<= [a, a, b, b]', s.isSubsetOf([a, a, b, b])); } function testIsSubsetOf() { helperForTestIsSubsetOf(1, 2, 3, 4); helperForTestIsSubsetOf('a', 'b', 'c', 'd'); helperForTestIsSubsetOf( new String('a'), new String('b'), new String('c'), new String('d')); } function testForEach() { var s = new Set; var a = new String('a'); s.add(a); var b = new String('b'); s.add(b); var c = new String('c'); s.add(c); var d = new String('d'); s.add(d); var str = ''; goog.structs.forEach(s, function(val, key, set) { assertUndefined(key); assertEquals(s, set); str += val; }); assertEquals(str, 'abcd'); s = new Set; s.add('a'); s.add('b'); s.add('c'); s.add('d'); str = ''; goog.structs.forEach(s, function(val, key, set) { assertUndefined(key); assertEquals(s, set); str += val; }); assertEquals(str, 'abcd'); } function testFilter() { var s = new Set; var a = new Number(0); s.add(a); var b = new Number(1); s.add(b); var c = new Number(2); s.add(c); var d = new Number(3); s.add(d); var s2 = goog.structs.filter(s, function(val, key, set) { assertUndefined(key); assertEquals(s, set); return val > 1; }); assertEquals(stringifySet(s2), '23'); s = new Set; s.add(0); s.add(1); s.add(2); s.add(3); s2 = goog.structs.filter(s, function(val, key, set) { assertUndefined(key); assertEquals(s, set); return val > 1; }); assertEquals(stringifySet(s2), '23'); } function testSome() { var s = new Set; var a = new Number(0); s.add(a); var b = new Number(1); s.add(b); var c = new Number(2); s.add(c); var d = new Number(3); s.add(d); var b = goog.structs.some(s, function(val, key, s2) { assertUndefined(key); assertEquals(s, s2); return val > 1; }); assertTrue(b); var b = goog.structs.some(s, function(val, key, s2) { assertUndefined(key); assertEquals(s, s2); return val > 100; }); assertFalse(b); s = new Set; s.add(0); s.add(1); s.add(2); s.add(3); b = goog.structs.some(s, function(val, key, s2) { assertUndefined(key); assertEquals(s, s2); return val > 1; }); assertTrue(b); b = goog.structs.some(s, function(val, key, s2) { assertUndefined(key); assertEquals(s, s2); return val > 100; }); assertFalse(b); } function testEvery() { var s = new Set; var a = new Number(0); s.add(a); var b = new Number(1); s.add(b); var c = new Number(2); s.add(c); var d = new Number(3); s.add(d); var b = goog.structs.every(s, function(val, key, s2) { assertUndefined(key); assertEquals(s, s2); return val >= 0; }); assertTrue(b); b = goog.structs.every(s, function(val, key, s2) { assertUndefined(key); assertEquals(s, s2); return val > 1; }); assertFalse(b); s = new Set; s.add(0); s.add(1); s.add(2); s.add(3); b = goog.structs.every(s, function(val, key, s2) { assertUndefined(key); assertEquals(s, s2); return val >= 0; }); assertTrue(b); b = goog.structs.every(s, function(val, key, s2) { assertUndefined(key); assertEquals(s, s2); return val > 1; }); assertFalse(b); } function testIterator() { var s = new Set; s.add(0); s.add(1); s.add(2); s.add(3); s.add(4); assertEquals('01234', goog.iter.join(s, '')); s.remove(1); s.remove(3); assertEquals('024', goog.iter.join(s, '')); }
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.ui.MenuButtonRendererTest'); goog.setTestOnly('goog.ui.MenuButtonRendererTest'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.State'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classlist'); goog.require('goog.testing.jsunit'); goog.require('goog.testing.ui.rendererasserts'); goog.require('goog.ui.MenuButton'); goog.require('goog.ui.MenuButtonRenderer'); goog.require('goog.userAgent'); var decoratedButton; var renderedButton; var savedRootTree; function setUp() { savedRootTree = goog.dom.getElement('root').cloneNode(true); decoratedButton = null; renderedButton = null; } function tearDown() { if (decoratedButton) { decoratedButton.dispose(); } if (renderedButton) { renderedButton.dispose(); } var root = goog.dom.getElement('root'); root.parentNode.replaceChild(savedRootTree, root); } function testRendererWithTextContent() { renderedButton = new goog.ui.MenuButton('Foo'); renderOnParent(renderedButton); checkButtonCaption(renderedButton); checkAriaState(renderedButton); decoratedButton = new goog.ui.MenuButton(); decorateDemoButton(decoratedButton); checkButtonCaption(decoratedButton); checkAriaState(decoratedButton); assertButtonsEqual(); } function testRendererWithNodeContent() { renderedButton = new goog.ui.MenuButton( goog.dom.createDom(goog.dom.TagName.DIV, null, 'Foo')); renderOnParent(renderedButton); var contentEl = renderedButton.getContentElement(); if (goog.userAgent.IE || goog.userAgent.OPERA) { assertHTMLEquals('<div unselectable="on">Foo</div>', contentEl.innerHTML); } else { assertHTMLEquals('<div>Foo</div>', contentEl.innerHTML); } assertTrue(hasInlineBlock(contentEl)); } function testSetContent() { renderedButton = new goog.ui.MenuButton(); renderOnParent(renderedButton); var contentEl = renderedButton.getContentElement(); assertHTMLEquals('', contentEl.innerHTML); renderedButton.setContent('Foo'); contentEl = renderedButton.getContentElement(); assertHTMLEquals('Foo', contentEl.innerHTML); assertTrue(hasInlineBlock(contentEl)); renderedButton.setContent( goog.dom.createDom(goog.dom.TagName.DIV, null, 'Bar')); contentEl = renderedButton.getContentElement(); assertHTMLEquals('<div>Bar</div>', contentEl.innerHTML); renderedButton.setContent('Foo'); contentEl = renderedButton.getContentElement(); assertHTMLEquals('Foo', contentEl.innerHTML); } function assertButtonsEqual() { assertHTMLEquals( 'Rendered button and decorated button produced different HTML!', renderedButton.getElement().innerHTML, decoratedButton.getElement().innerHTML); } /** * Render the given button as a child of 'parent'. * @param {goog.ui.Button} button A button with content 'Foo'. */ function renderOnParent(button) { button.render(goog.dom.getElement('parent')); } /** * Decaorate the button with id 'button'. * @param {goog.ui.Button} button A button with no content. */ function decorateDemoButton(button) { button.decorate(goog.dom.getElement('decoratedButton')); } /** * Verify that the button's caption is never the direct * child of an inline-block element. * @param {goog.ui.Button} button A button. */ function checkButtonCaption(button) { var contentElement = button.getContentElement(); assertEquals('Foo', contentElement.innerHTML); assertTrue(hasInlineBlock(contentElement)); assert(hasInlineBlock(contentElement.parentNode)); button.setContent('Bar'); contentElement = button.getContentElement(); assertEquals('Bar', contentElement.innerHTML); assertTrue(hasInlineBlock(contentElement)); assert(hasInlineBlock(contentElement.parentNode)); } /** * Verify that the menu button has the correct ARIA attributes * @param {goog.ui.Button} button A button. */ function checkAriaState(button) { assertEquals( 'menu buttons should have default aria-expanded == false', 'false', goog.a11y.aria.getState( button.getElement(), goog.a11y.aria.State.EXPANDED)); button.setOpen(true); assertEquals( 'menu buttons should not aria-expanded == true after ' + 'opening', 'true', goog.a11y.aria.getState( button.getElement(), goog.a11y.aria.State.EXPANDED)); } function hasInlineBlock(el) { return goog.dom.classlist.contains(el, 'goog-inline-block'); } function testDoesntCallGetCssClassInConstructor() { goog.testing.ui.rendererasserts.assertNoGetCssClassCallsInConstructor( goog.ui.MenuButtonRenderer); }
/*! Facebox dialog module (for jQuery Dirty Forms) | v2.0.0-beta00008 | github.com/snikch/jquery.dirtyforms (c) 2015 Shad Storhaug License MIT */ (function($, window, document, undefined) { // Can't use ECMAScript 5's strict mode because several apps // including ASP.NET trace the stack via arguments.caller.callee // and Firefox dies if you try to trace through "use strict" call chains. // See jQuery issue (#13335) // Support: Firefox 18+ //"use strict"; $.DirtyForms.dialog = { // Custom properties and methods to allow overriding (may differ per dialog) title: 'Are you sure you want to do that?', proceedButtonClass: '', proceedButtonText: 'Leave This Page', stayButtonClass: '', stayButtonText: 'Stay Here', // Typical Dirty Forms Properties and Methods // Selector for stashing the content of another dialog. stashSelector: '#facebox .content', open: function (choice, message, ignoreClass) { var content = '<h1>' + this.title + '</h1>' + '<p>' + message + '</p>' + '<p>' + '<a href="#" class="dirty-proceed ' + ignoreClass + ' ' + this.proceedButtonClass + '">' + this.proceedButtonText + '</a>' + '<a href="#" class="dirty-stay ' + ignoreClass + ' ' + this.stayButtonClass + '">' + this.stayButtonText + '</a>' + '</p>'; $.facebox(content); // Bind Events choice.bindEnterKey = true; choice.staySelector = '#facebox .dirty-stay, #facebox .close, #facebox_overlay'; choice.proceedSelector = '#facebox .dirty-proceed'; if (choice.isDF1) { var close = function (decision) { return function (e) { if (e.type !== 'keydown' || (e.type === 'keydown' && (e.which == 27 || e.which == 13))) { // Facebox hack: If we call close when returning from the stash, the // stash dialog will close, so we guard against calling close in that case. if (!$.DirtyForms.dialogStash) { $(document).trigger('close.facebox'); } decision(e); } }; }; var decidingCancel = $.DirtyForms.decidingCancel; $(document).bind('keydown.facebox', close(decidingCancel)); $(choice.staySelector).click(close(decidingCancel)); $(choice.proceedSelector).click(close($.DirtyForms.decidingContinue)); } }, close: function (continuing, unstashing) { // Facebox hack: If we call close when returning from the stash, the // stash dialog will close, so we guard against calling close in that case. if (!unstashing) { $(document).trigger('close.facebox'); } }, stash: function () { var isDF1 = typeof $.DirtyForms.isDeciding === 'function', $fb = $('#facebox'), $content = $fb.find('.content'); // Store the DOM state as actual HTML DOM values $content.find('datalist,select,textarea,input').not('[type="button"],[type="submit"],[type="reset"],[type="image"]').each(function () { storeFieldValue($(this)); }); return ($.trim($fb.html()) === '' || $fb.css('display') != 'block') ? false : isDF1 ? $content.clone(true) : $content.children().clone(true); }, unstash: function (stash, ev) { $.facebox(stash); }, // Support for Dirty Forms < 2.0 fire: function (message, title) { this.title = title; this.open({ isDF1: true }, message, $.DirtyForms.ignoreClass); }, selector: $.DirtyForms.dialog.stashSelector, // Support for Dirty Forms < 1.2 bind: function () { }, refire: function (content, ev) { this.unstash(content, ev); } }; var storeFieldValue = function ($field) { if ($field.is('select,datalist')) { $field.find('option').each(function () { var $option = $(this); if ($option.is(':selected')) { $option.attr('selected', 'selected'); } else { $option.removeAttr('selected'); } }); } else if ($field.is(":checkbox,:radio")) { if ($field.is(':checked')) { $field.attr('checked', 'checked'); } else { $field.removeAttr('checked'); } } else if ($field.is('textarea')) { $field.text($field.val()); } else { $field.attr('value', $field.val()); } }; })(jQuery, window, document);
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object for the * Lithuanian language. */ /**#@+ @type String @example */ /** * Contains the dictionary of language entries. * @namespace */ CKEDITOR.lang['lt'] = { /** * The language reading direction. Possible values are "rtl" for * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right * languages (like English). * @default 'ltr' */ dir : 'ltr', /* * Screenreader titles. Please note that screenreaders are not always capable * of reading non-English words. So be careful while translating it. */ editorTitle : 'Pilnas redaktorius, %1', editorHelp : 'Spauskite ALT 0 dėl pagalbos', // ARIA descriptions. toolbars : 'Redaktoriaus įrankiai', editor : 'Pilnas redaktorius', // Toolbar buttons without dialogs. source : 'Šaltinis', newPage : 'Naujas puslapis', save : 'Išsaugoti', preview : 'Peržiūra', cut : 'Iškirpti', copy : 'Kopijuoti', paste : 'Įdėti', print : 'Spausdinti', underline : 'Pabrauktas', bold : 'Pusjuodis', italic : 'Kursyvas', selectAll : 'Pažymėti viską', removeFormat : 'Panaikinti formatą', strike : 'Perbrauktas', subscript : 'Apatinis indeksas', superscript : 'Viršutinis indeksas', horizontalrule : 'Įterpti horizontalią liniją', pagebreak : 'Įterpti puslapių skirtuką', pagebreakAlt : 'Puslapio skirtukas', unlink : 'Panaikinti nuorodą', undo : 'Atšaukti', redo : 'Atstatyti', // Common messages and labels. common : { browseServer : 'Naršyti po serverį', url : 'URL', protocol : 'Protokolas', upload : 'Siųsti', uploadSubmit : 'Siųsti į serverį', image : 'Vaizdas', flash : 'Flash', form : 'Forma', checkbox : 'Žymimasis langelis', radio : 'Žymimoji akutė', textField : 'Teksto laukas', textarea : 'Teksto sritis', hiddenField : 'Nerodomas laukas', button : 'Mygtukas', select : 'Atrankos laukas', imageButton : 'Vaizdinis mygtukas', notSet : '<nėra nustatyta>', id : 'Id', name : 'Vardas', langDir : 'Teksto kryptis', langDirLtr : 'Iš kairės į dešinę (LTR)', langDirRtl : 'Iš dešinės į kairę (RTL)', langCode : 'Kalbos kodas', longDescr : 'Ilgas aprašymas URL', cssClass : 'Stilių lentelės klasės', advisoryTitle : 'Konsultacinė antraštė', cssStyle : 'Stilius', ok : 'OK', cancel : 'Nutraukti', close : 'Uždaryti', preview : 'Peržiūrėti', generalTab : 'Bendros savybės', advancedTab : 'Papildomas', validateNumberFailed : 'Ši reikšmė nėra skaičius.', confirmNewPage : 'Visas neišsaugotas turinys bus prarastas. Ar tikrai norite įkrauti naują puslapį?', confirmCancel : 'Kai kurie parametrai pasikeitė. Ar tikrai norite užverti langą?', options : 'Parametrai', target : 'Tikslinė nuoroda', targetNew : 'Naujas langas (_blank)', targetTop : 'Viršutinis langas (_top)', targetSelf : 'Esamas langas (_self)', targetParent : 'Paskutinis langas (_parent)', langDirLTR : 'Iš kairės į dešinę (LTR)', langDirRTL : 'Iš dešinės į kairę (RTL)', styles : 'Stilius', cssClasses : 'Stilių klasės', width : 'Plotis', height : 'Aukštis', align : 'Lygiuoti', alignLeft : 'Kairę', alignRight : 'Dešinę', alignCenter : 'Centrą', alignTop : 'Viršūnę', alignMiddle : 'Vidurį', alignBottom : 'Apačią', invalidValue : 'Invalid value.', // MISSING invalidHeight : 'Aukštis turi būti nurodytas skaičiais.', invalidWidth : 'Plotis turi būti nurodytas skaičiais.', invalidCssLength : 'Reikšmė nurodyta "%1" laukui, turi būti teigiamas skaičius su arba be tinkamo CSS matavimo vieneto (px, %, in, cm, mm, em, ex, pt arba pc).', invalidHtmlLength : 'Reikšmė nurodyta "%1" laukui, turi būti teigiamas skaičius su arba be tinkamo HTML matavimo vieneto (px arba %).', invalidInlineStyle : 'Reikšmė nurodyta vidiniame stiliuje turi būti sudaryta iš vieno šių reikšmių "vardas : reikšmė", atskirta kabliataškiais.', cssLengthTooltip : 'Įveskite reikšmę pikseliais arba skaičiais su tinkamu CSS vienetu (px, %, in, cm, mm, em, ex, pt arba pc).', // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, netinkamas</span>' }, contextmenu : { options : 'Kontekstinio meniu parametrai' }, // Special char dialog. specialChar : { toolbar : 'Įterpti specialų simbolį', title : 'Pasirinkite specialų simbolį', options : 'Specialaus simbolio nustatymai' }, // Link dialog. link : { toolbar : 'Įterpti/taisyti nuorodą', other : '<kitas>', menu : 'Taisyti nuorodą', title : 'Nuoroda', info : 'Nuorodos informacija', target : 'Paskirties vieta', upload : 'Siųsti', advanced : 'Papildomas', type : 'Nuorodos tipas', toUrl : 'Nuoroda', toAnchor : 'Žymė šiame puslapyje', toEmail : 'El.paštas', targetFrame : '<kadras>', targetPopup : '<išskleidžiamas langas>', targetFrameName : 'Paskirties kadro vardas', targetPopupName : 'Paskirties lango vardas', popupFeatures : 'Išskleidžiamo lango savybės', popupResizable : 'Kintamas dydis', popupStatusBar : 'Būsenos juosta', popupLocationBar: 'Adreso juosta', popupToolbar : 'Mygtukų juosta', popupMenuBar : 'Meniu juosta', popupFullScreen : 'Visas ekranas (IE)', popupScrollBars : 'Slinkties juostos', popupDependent : 'Priklausomas (Netscape)', popupLeft : 'Kairė pozicija', popupTop : 'Viršutinė pozicija', id : 'Id', langDir : 'Teksto kryptis', langDirLTR : 'Iš kairės į dešinę (LTR)', langDirRTL : 'Iš dešinės į kairę (RTL)', acccessKey : 'Prieigos raktas', name : 'Vardas', langCode : 'Teksto kryptis', tabIndex : 'Tabuliavimo indeksas', advisoryTitle : 'Konsultacinė antraštė', advisoryContentType : 'Konsultacinio turinio tipas', cssClasses : 'Stilių lentelės klasės', charset : 'Susietų išteklių simbolių lentelė', styles : 'Stilius', rel : 'Sąsajos', selectAnchor : 'Pasirinkite žymę', anchorName : 'Pagal žymės vardą', anchorId : 'Pagal žymės Id', emailAddress : 'El.pašto adresas', emailSubject : 'Žinutės tema', emailBody : 'Žinutės turinys', noAnchors : '(Šiame dokumente žymių nėra)', noUrl : 'Prašome įvesti nuorodos URL', noEmail : 'Prašome įvesti el.pašto adresą' }, // Anchor dialog anchor : { toolbar : 'Įterpti/modifikuoti žymę', menu : 'Žymės savybės', title : 'Žymės savybės', name : 'Žymės vardas', errorName : 'Prašome įvesti žymės vardą', remove : 'Pašalinti žymę' }, // List style dialog list: { numberedTitle : 'Skaitmeninio sąrašo nustatymai', bulletedTitle : 'Ženklelinio sąrašo nustatymai', type : 'Rūšis', start : 'Pradžia', validateStartNumber :'Sąrašo pradžios skaitmuo turi būti sveikas skaičius.', circle : 'Apskritimas', disc : 'Diskas', square : 'Kvadratas', none : 'Niekas', notset : '<nenurodytas>', armenian : 'Armėniški skaitmenys', georgian : 'Gruziniški skaitmenys (an, ban, gan, t.t)', lowerRoman : 'Mažosios Romėnų (i, ii, iii, iv, v, t.t)', upperRoman : 'Didžiosios Romėnų (I, II, III, IV, V, t.t)', lowerAlpha : 'Mažosios Alpha (a, b, c, d, e, t.t)', upperAlpha : 'Didžiosios Alpha (A, B, C, D, E, t.t)', lowerGreek : 'Mažosios Graikų (alpha, beta, gamma, t.t)', decimal : 'Dešimtainis (1, 2, 3, t.t)', decimalLeadingZero : 'Dešimtainis su nuliu priekyje (01, 02, 03, t.t)' }, // Find And Replace Dialog findAndReplace : { title : 'Surasti ir pakeisti', find : 'Rasti', replace : 'Pakeisti', findWhat : 'Surasti tekstą:', replaceWith : 'Pakeisti tekstu:', notFoundMsg : 'Nurodytas tekstas nerastas.', findOptions : 'Paieškos nustatymai', matchCase : 'Skirti didžiąsias ir mažąsias raides', matchWord : 'Atitikti pilną žodį', matchCyclic : 'Sutampantis cikliškumas', replaceAll : 'Pakeisti viską', replaceSuccessMsg : '%1 sutapimas(ų) buvo pakeisti.' }, // Table Dialog table : { toolbar : 'Lentelė', title : 'Lentelės savybės', menu : 'Lentelės savybės', deleteTable : 'Šalinti lentelę', rows : 'Eilutės', columns : 'Stulpeliai', border : 'Rėmelio dydis', widthPx : 'taškais', widthPc : 'procentais', widthUnit : 'pločio vienetas', cellSpace : 'Tarpas tarp langelių', cellPad : 'Trapas nuo langelio rėmo iki teksto', caption : 'Antraštė', summary : 'Santrauka', headers : 'Antraštės', headersNone : 'Nėra', headersColumn : 'Pirmas stulpelis', headersRow : 'Pirma eilutė', headersBoth : 'Abu', invalidRows : 'Skaičius turi būti didesnis nei 0.', invalidCols : 'Skaičius turi būti didesnis nei 0.', invalidBorder : 'Reikšmė turi būti nurodyta skaičiumi.', invalidWidth : 'Reikšmė turi būti nurodyta skaičiumi.', invalidHeight : 'Reikšmė turi būti nurodyta skaičiumi.', invalidCellSpacing : 'Reikšmė turi būti nurodyta skaičiumi.', invalidCellPadding : 'Reikšmė turi būti nurodyta skaičiumi.', cell : { menu : 'Langelis', insertBefore : 'Įterpti langelį prieš', insertAfter : 'Įterpti langelį po', deleteCell : 'Šalinti langelius', merge : 'Sujungti langelius', mergeRight : 'Sujungti su dešine', mergeDown : 'Sujungti su apačia', splitHorizontal : 'Skaidyti langelį horizontaliai', splitVertical : 'Skaidyti langelį vertikaliai', title : 'Cell nustatymai', cellType : 'Cell rūšis', rowSpan : 'Eilučių Span', colSpan : 'Stulpelių Span', wordWrap : 'Sutraukti raides', hAlign : 'Horizontalus lygiavimas', vAlign : 'Vertikalus lygiavimas', alignBaseline : 'Apatinė linija', bgColor : 'Fono spalva', borderColor : 'Rėmelio spalva', data : 'Data', header : 'Antraštė', yes : 'Taip', no : 'Ne', invalidWidth : 'Reikšmė turi būti skaičius.', invalidHeight : 'Reikšmė turi būti skaičius.', invalidRowSpan : 'Reikšmė turi būti skaičius.', invalidColSpan : 'Reikšmė turi būti skaičius.', chooseColor : 'Pasirinkite' }, row : { menu : 'Eilutė', insertBefore : 'Įterpti eilutę prieš', insertAfter : 'Įterpti eilutę po', deleteRow : 'Šalinti eilutes' }, column : { menu : 'Stulpelis', insertBefore : 'Įterpti stulpelį prieš', insertAfter : 'Įterpti stulpelį po', deleteColumn : 'Šalinti stulpelius' } }, // Button Dialog. button : { title : 'Mygtuko savybės', text : 'Tekstas (Reikšmė)', type : 'Tipas', typeBtn : 'Mygtukas', typeSbm : 'Siųsti', typeRst : 'Išvalyti' }, // Checkbox and Radio Button Dialogs. checkboxAndRadio : { checkboxTitle : 'Žymimojo langelio savybės', radioTitle : 'Žymimosios akutės savybės', value : 'Reikšmė', selected : 'Pažymėtas' }, // Form Dialog. form : { title : 'Formos savybės', menu : 'Formos savybės', action : 'Veiksmas', method : 'Metodas', encoding : 'Kodavimas' }, // Select Field Dialog. select : { title : 'Atrankos lauko savybės', selectInfo : 'Informacija', opAvail : 'Galimos parinktys', value : 'Reikšmė', size : 'Dydis', lines : 'eilučių', chkMulti : 'Leisti daugeriopą atranką', opText : 'Tekstas', opValue : 'Reikšmė', btnAdd : 'Įtraukti', btnModify : 'Modifikuoti', btnUp : 'Aukštyn', btnDown : 'Žemyn', btnSetValue : 'Laikyti pažymėta reikšme', btnDelete : 'Trinti' }, // Textarea Dialog. textarea : { title : 'Teksto srities savybės', cols : 'Ilgis', rows : 'Plotis' }, // Text Field Dialog. textfield : { title : 'Teksto lauko savybės', name : 'Vardas', value : 'Reikšmė', charWidth : 'Ilgis simboliais', maxChars : 'Maksimalus simbolių skaičius', type : 'Tipas', typeText : 'Tekstas', typePass : 'Slaptažodis' }, // Hidden Field Dialog. hidden : { title : 'Nerodomo lauko savybės', name : 'Vardas', value : 'Reikšmė' }, // Image Dialog. image : { title : 'Vaizdo savybės', titleButton : 'Vaizdinio mygtuko savybės', menu : 'Vaizdo savybės', infoTab : 'Vaizdo informacija', btnUpload : 'Siųsti į serverį', upload : 'Nusiųsti', alt : 'Alternatyvus Tekstas', lockRatio : 'Išlaikyti proporciją', resetSize : 'Atstatyti dydį', border : 'Rėmelis', hSpace : 'Hor.Erdvė', vSpace : 'Vert.Erdvė', alertUrl : 'Prašome įvesti vaizdo URL', linkTab : 'Nuoroda', button2Img : 'Ar norite mygtuką paversti paprastu paveiksliuku?', img2Button : 'Ar norite paveiksliuką paversti mygtuku?', urlMissing : 'Paveiksliuko nuorodos nėra.', validateBorder : 'Reikšmė turi būti sveikas skaičius.', validateHSpace : 'Reikšmė turi būti sveikas skaičius.', validateVSpace : 'Reikšmė turi būti sveikas skaičius.' }, // Flash Dialog flash : { properties : 'Flash savybės', propertiesTab : 'Nustatymai', title : 'Flash savybės', chkPlay : 'Automatinis paleidimas', chkLoop : 'Ciklas', chkMenu : 'Leisti Flash meniu', chkFull : 'Leisti per visą ekraną', scale : 'Mastelis', scaleAll : 'Rodyti visą', scaleNoBorder : 'Be rėmelio', scaleFit : 'Tikslus atitikimas', access : 'Skripto priėjimas', accessAlways : 'Visada', accessSameDomain: 'Tas pats domenas', accessNever : 'Niekada', alignAbsBottom : 'Absoliučią apačią', alignAbsMiddle : 'Absoliutų vidurį', alignBaseline : 'Apatinę liniją', alignTextTop : 'Teksto viršūnę', quality : 'Kokybė', qualityBest : 'Geriausia', qualityHigh : 'Gera', qualityAutoHigh : 'Automatiškai Gera', qualityMedium : 'Vidutinė', qualityAutoLow : 'Automatiškai Žema', qualityLow : 'Žema', windowModeWindow: 'Langas', windowModeOpaque: 'Nepermatomas', windowModeTransparent : 'Permatomas', windowMode : 'Lango režimas', flashvars : 'Flash kintamieji', bgcolor : 'Fono spalva', hSpace : 'Hor.Erdvė', vSpace : 'Vert.Erdvė', validateSrc : 'Prašome įvesti nuorodos URL', validateHSpace : 'HSpace turi būti skaičius.', validateVSpace : 'VSpace turi būti skaičius.' }, // Speller Pages Dialog spellCheck : { toolbar : 'Rašybos tikrinimas', title : 'Tikrinti klaidas', notAvailable : 'Atleiskite, šiuo metu servisas neprieinamas.', errorLoading : 'Klaida įkraunant servisą: %s.', notInDic : 'Žodyne nerastas', changeTo : 'Pakeisti į', btnIgnore : 'Ignoruoti', btnIgnoreAll : 'Ignoruoti visus', btnReplace : 'Pakeisti', btnReplaceAll : 'Pakeisti visus', btnUndo : 'Atšaukti', noSuggestions : '- Nėra pasiūlymų -', progress : 'Vyksta rašybos tikrinimas...', noMispell : 'Rašybos tikrinimas baigtas: Nerasta rašybos klaidų', noChanges : 'Rašybos tikrinimas baigtas: Nėra pakeistų žodžių', oneChange : 'Rašybos tikrinimas baigtas: Vienas žodis pakeistas', manyChanges : 'Rašybos tikrinimas baigtas: Pakeista %1 žodžių', ieSpellDownload : 'Rašybos tikrinimas neinstaliuotas. Ar Jūs norite jį dabar atsisiųsti?' }, smiley : { toolbar : 'Veideliai', title : 'Įterpti veidelį', options : 'Šypsenėlių nustatymai' }, elementsPath : { eleLabel : 'Elemento kelias', eleTitle : '%1 elementas' }, numberedlist : 'Numeruotas sąrašas', bulletedlist : 'Suženklintas sąrašas', indent : 'Padidinti įtrauką', outdent : 'Sumažinti įtrauką', justify : { left : 'Lygiuoti kairę', center : 'Centruoti', right : 'Lygiuoti dešinę', block : 'Lygiuoti abi puses' }, blockquote : 'Citata', clipboard : { title : 'Įdėti', cutError : 'Jūsų naršyklės saugumo nustatymai neleidžia redaktoriui automatiškai įvykdyti iškirpimo operacijų. Tam prašome naudoti klaviatūrą (Ctrl/Cmd+X).', copyError : 'Jūsų naršyklės saugumo nustatymai neleidžia redaktoriui automatiškai įvykdyti kopijavimo operacijų. Tam prašome naudoti klaviatūrą (Ctrl/Cmd+C).', pasteMsg : 'Žemiau esančiame įvedimo lauke įdėkite tekstą, naudodami klaviatūrą (<STRONG>Ctrl/Cmd+V</STRONG>) ir paspauskite mygtuką <STRONG>OK</STRONG>.', securityMsg : 'Dėl jūsų naršyklės saugumo nustatymų, redaktorius negali tiesiogiai pasiekti laikinosios atminties. Jums reikia nukopijuoti dar kartą į šį langą.', pasteArea : 'Įkelti dalį' }, pastefromword : { confirmCleanup : 'Tekstas, kurį įkeliate yra kopijuojamas iš Word. Ar norite jį išvalyti prieš įkeliant?', toolbar : 'Įdėti iš Word', title : 'Įdėti iš Word', error : 'Dėl vidinių sutrikimų, nepavyko išvalyti įkeliamo teksto' }, pasteText : { button : 'Įdėti kaip gryną tekstą', title : 'Įdėti kaip gryną tekstą' }, templates : { button : 'Šablonai', title : 'Turinio šablonai', options : 'Template Options', insertOption : 'Pakeisti dabartinį turinį pasirinktu šablonu', selectPromptMsg : 'Pasirinkite norimą šabloną<br>(<b>Dėmesio!</b> esamas turinys bus prarastas):', emptyListMsg : '(Šablonų sąrašas tuščias)' }, showBlocks : 'Rodyti blokus', stylesCombo : { label : 'Stilius', panelTitle : 'Stilių formatavimas', panelTitle1 : 'Blokų stiliai', panelTitle2 : 'Vidiniai stiliai', panelTitle3 : 'Objektų stiliai' }, format : { label : 'Šrifto formatas', panelTitle : 'Šrifto formatas', tag_p : 'Normalus', tag_pre : 'Formuotas', tag_address : 'Kreipinio', tag_h1 : 'Antraštinis 1', tag_h2 : 'Antraštinis 2', tag_h3 : 'Antraštinis 3', tag_h4 : 'Antraštinis 4', tag_h5 : 'Antraštinis 5', tag_h6 : 'Antraštinis 6', tag_div : 'Normalus (DIV)' }, div : { title : 'Sukurti Div elementą', toolbar : 'Sukurti Div elementą', cssClassInputLabel : 'Stilių klasės', styleSelectLabel : 'Stilius', IdInputLabel : 'Id', languageCodeInputLabel : ' Kalbos kodas', inlineStyleInputLabel : 'Vidiniai stiliai', advisoryTitleInputLabel : 'Patariamas pavadinimas', langDirLabel : 'Kalbos nurodymai', langDirLTRLabel : 'Iš kairės į dešinę (LTR)', langDirRTLLabel : 'Iš dešinės į kairę (RTL)', edit : 'Redaguoti Div', remove : 'Pašalinti Div' }, iframe : { title : 'IFrame nustatymai', toolbar : 'IFrame', noUrl : 'Nurodykite iframe nuorodą', scrolling : 'Įjungti slankiklius', border : 'Rodyti rėmelį' }, font : { label : 'Šriftas', voiceLabel : 'Šriftas', panelTitle : 'Šriftas' }, fontSize : { label : 'Šrifto dydis', voiceLabel : 'Šrifto dydis', panelTitle : 'Šrifto dydis' }, colorButton : { textColorTitle : 'Teksto spalva', bgColorTitle : 'Fono spalva', panelTitle : 'Spalva', auto : 'Automatinis', more : 'Daugiau spalvų...' }, colors : { '000' : 'Juoda', '800000' : 'Kaštoninė', '8B4513' : 'Tamsiai ruda', '2F4F4F' : 'Pilka tamsaus šiferio', '008080' : 'Teal', '000080' : 'Karinis', '4B0082' : 'Indigo', '696969' : 'Tamsiai pilka', 'B22222' : 'Ugnies', 'A52A2A' : 'Ruda', 'DAA520' : 'Aukso', '006400' : 'Tamsiai žalia', '40E0D0' : 'Turquoise', '0000CD' : 'Vidutinė mėlyna', '800080' : 'Violetinė', '808080' : 'Pilka', 'F00' : 'Raudona', 'FF8C00' : 'Tamsiai oranžinė', 'FFD700' : 'Auksinė', '008000' : 'Žalia', '0FF' : 'Žydra', '00F' : 'Mėlyna', 'EE82EE' : 'Violetinė', 'A9A9A9' : 'Dim Gray', 'FFA07A' : 'Light Salmon', 'FFA500' : 'Oranžinė', 'FFFF00' : 'Geltona', '00FF00' : 'Citrinų', 'AFEEEE' : 'Pale Turquoise', 'ADD8E6' : 'Šviesiai mėlyna', 'DDA0DD' : 'Plum', 'D3D3D3' : 'Šviesiai pilka', 'FFF0F5' : 'Lavender Blush', 'FAEBD7' : 'Antique White', 'FFFFE0' : 'Šviesiai geltona', 'F0FFF0' : 'Honeydew', 'F0FFFF' : 'Azure', 'F0F8FF' : 'Alice Blue', 'E6E6FA' : 'Lavender', 'FFF' : 'Balta' }, scayt : { title : 'Tikrinti klaidas kai rašoma', opera_title : 'Nepalaikoma naršyklėje Opera', enable : 'Įjungti SCAYT', disable : 'Išjungti SCAYT', about : 'Apie SCAYT', toggle : 'Perjungti SCAYT', options : 'Parametrai', langs : 'Kalbos', moreSuggestions : 'Daugiau patarimų', ignore : 'Ignoruoti', ignoreAll : 'Ignoruoti viską', addWord : 'Pridėti žodį', emptyDic : 'Žodyno vardas neturėtų būti tuščias.', optionsTab : 'Parametrai', allCaps : 'Ignoruoti visas didžiąsias raides', ignoreDomainNames : 'Ignoruoti domenų vardus', mixedCase : 'Ignoruoti maišyto dydžio raides', mixedWithDigits : 'Ignoruoti raides su skaičiais', languagesTab : 'Kalbos', dictionariesTab : 'Žodynai', dic_field_name : 'Žodyno pavadinimas', dic_create : 'Sukurti', dic_restore : 'Atstatyti', dic_delete : 'Ištrinti', dic_rename : 'Pervadinti', dic_info : 'Paprastai žodynas yra saugojamas sausainėliuose (cookies), kurių dydis, bet kokiu atveju, yra apribotas. Esant sausainėlių apimties pervišiui, viskas bus saugoma serveryje. Jei norite iš kart viską saugoti serveryje, turite sugalvoti žodynui pavadinimą. Jei jau turite žodyną, įrašykite pavadinimą ir nuspauskite Atstatyti mygtuką.', aboutTab : 'Apie' }, about : { title : 'Apie CKEditor', dlgTitle : 'Apie CKEditor', help : 'Patikrinkite $1 dėl pagalbos.', userGuide : 'CKEditor Vartotojo Gidas', moreInfo : 'Dėl licencijavimo apsilankykite mūsų svetainėje:', copy : 'Copyright &copy; $1. Visos teiss saugomos.' }, maximize : 'Išdidinti', minimize : 'Sumažinti', fakeobjects : { anchor : 'Žymė', flash : 'Flash animacija', iframe : 'IFrame', hiddenfield : 'Paslėptas laukas', unknown : 'Nežinomas objektas' }, resize : 'Pavilkite, kad pakeistumėte dydį', colordialog : { title : 'Pasirinkite spalvą', options : 'Spalvos nustatymai', highlight : 'Paryškinti', selected : 'Pasirinkta spalva', clear : 'Išvalyti' }, toolbarCollapse : 'Apjungti įrankių juostą', toolbarExpand : 'Išplėsti įrankių juostą', toolbarGroups : { document : 'Dokumentas', clipboard : 'Atmintinė/Atgal', editing : 'Redagavimas', forms : 'Formos', basicstyles : 'Pagrindiniai stiliai', paragraph : 'Paragrafas', links : 'Nuorodos', insert : 'Įterpti', styles : 'Stiliai', colors : 'Spalvos', tools : 'Įrankiai' }, bidi : { ltr : 'Tekstas iš kairės į dešinę', rtl : 'Tekstas iš dešinės į kairę' }, docprops : { label : 'Dokumento savybės', title : 'Dokumento savybės', design : 'Išdėstymas', meta : 'Meta duomenys', chooseColor : 'Pasirinkite', other : '<kitas>', docTitle : 'Puslapio antraštė', charset : 'Simbolių kodavimo lentelė', charsetOther : 'Kita simbolių kodavimo lentelė', charsetASCII : 'ASCII', charsetCE : 'Centrinės Europos', charsetCT : 'Tradicinės kinų (Big5)', charsetCR : 'Kirilica', charsetGR : 'Graikų', charsetJP : 'Japonų', charsetKR : 'Korėjiečių', charsetTR : 'Turkų', charsetUN : 'Unikodas (UTF-8)', charsetWE : 'Vakarų Europos', docType : 'Dokumento tipo antraštė', docTypeOther : 'Kita dokumento tipo antraštė', xhtmlDec : 'Įtraukti XHTML deklaracijas', bgColor : 'Fono spalva', bgImage : 'Fono paveikslėlio nuoroda (URL)', bgFixed : 'Neslenkantis fonas', txtColor : 'Teksto spalva', margin : 'Puslapio kraštinės', marginTop : 'Viršuje', marginLeft : 'Kairėje', marginRight : 'Dešinėje', marginBottom : 'Apačioje', metaKeywords : 'Dokumento indeksavimo raktiniai žodžiai (atskirti kableliais)', metaDescription : 'Dokumento apibūdinimas', metaAuthor : 'Autorius', metaCopyright : 'Autorinės teisės', previewHtml : '<p>Tai yra <strong>pavyzdinis tekstas</strong>. Jūs naudojate <a href="javascript:void(0)">CKEditor</a>.</p>' } };
Template.main.onCreated(function() { RocketChat.tooltip.init(); });
/*! * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 * @version 4.1.1 * * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced * features including the FileReader API. * * The plugin drastically enhances the HTML file input to preview multiple files on the client before * upload. In addition it provides the ability to preview content of images, text, videos, audio, html, * flash and other objects. It also offers the ability to upload and delete files using AJAX, and add * files in batches (i.e. preview, append, or remove before upload). * * Author: Kartik Visweswaran * Copyright: 2014, Kartik Visweswaran, Krajee.com * For more JQuery plugins visit http://plugins.krajee.com * For more Yii related demos visit http://demos.krajee.com */ (function ($) { var isIE = function(ver) { var div = document.createElement("div"), status; div.innerHTML = "<!--[if IE " + ver + "]><i></i><![endif]-->"; status = (div.getElementsByTagName("i").length == 1); document.body.appendChild(div); div.parentNode.removeChild(div); return status; }, hasFileAPISupport = function () { return window.File && window.FileReader; }, hasDragDropSupport = function() { var $div = document.createElement('div'); return !isIE(9) && (('draggable' in $div) || ('ondragstart' in $div && 'ondrop' in $div)); }, hasFileUploadSupport = function () { return hasFileAPISupport && window.FormData; }, addCss = function($el, css) { $el.removeClass(css).addClass(css); }, STYLE_SETTING = 'style="width:{width};height:{height};"', OBJECT_PARAMS = ' <param name="controller" value="true" />\n' + ' <param name="allowFullScreen" value="true" />\n' + ' <param name="allowScriptAccess" value="always" />\n' + ' <param name="autoPlay" value="false" />\n' + ' <param name="autoStart" value="false" />\n'+ ' <param name="quality" value="high" />\n', DEFAULT_PREVIEW = '<div class="file-preview-other">\n' + ' <i class="glyphicon glyphicon-file"></i>\n' + ' </div>'; var defaultFileActionSettings = { removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>', removeClass: 'btn btn-xs btn-default', removeTitle: 'Remove file', uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>', uploadClass: 'btn btn-xs btn-default', uploadTitle: 'Upload file', indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>', indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign file-icon-large text-success"></i>', indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>', indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>', indicatorNewTitle: 'Not uploaded yet', indicatorSuccessTitle: 'Uploaded', indicatorErrorTitle: 'Upload Error', indicatorLoadingTitle: 'Uploading ...' }; var defaultLayoutTemplates = { main1: '{preview}\n' + '<div class="kv-upload-progress hide"></div>\n' + '<div class="input-group {class}">\n' + ' {caption}\n' + ' <div class="input-group-btn">\n' + ' {remove}\n' + ' {cancel}\n' + ' {upload}\n' + ' {browse}\n' + ' </div>\n' + '</div>', main2: '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n', preview: '<div class="file-preview {class}">\n' + ' <div class="close fileinput-remove">&times;</div>\n' + ' <div class="{dropClass}">\n' + ' <div class="file-preview-thumbnails">\n' + ' </div>\n' + ' <div class="clearfix"></div>' + ' <div class="file-preview-status text-center text-success"></div>\n' + ' <div class="kv-fileinput-error"></div>\n' + ' </div>\n' + '</div>', icon: '<span class="glyphicon glyphicon-file kv-caption-icon"></span>', caption: '<div tabindex="-1" class="form-control file-caption {class}">\n' + ' <div class="file-caption-name"></div>\n' + '</div>', modal: '<div id="{id}" class="modal fade">\n' + ' <div class="modal-dialog modal-lg">\n' + ' <div class="modal-content">\n' + ' <div class="modal-header">\n' + ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' + ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' + ' </div>\n' + ' <div class="modal-body">\n' + ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' + ' </div>\n' + ' </div>\n' + ' </div>\n' + '</div>', progress: '<div class="progress">\n' + ' <div class="progress-bar progress-bar-success progress-bar-striped text-center" role="progressbar" aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' + ' {percent}%\n' + ' </div>\n' + '</div>', footer: '<div class="file-thumbnail-footer">\n' + ' <div class="file-caption-name" style="width:{width}">{caption}</div>\n' + ' {actions}\n' + '</div>', actions: '<div class="file-actions">\n' + ' <div class="file-footer-buttons">\n' + ' {upload}{delete}' + ' </div>\n' + ' <div class="file-upload-indicator" tabindex="-1" title="{indicatorTitle}">{indicator}</div>\n' + ' <div class="clearfix"></div>\n' + '</div>', actionDelete: '<button type="button" class="kv-file-remove {removeClass}" title="{removeTitle}"{dataUrl}{dataKey}>{removeIcon}</button>\n', actionUpload: '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">{uploadIcon}</button>\n' }; var defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object']; var defaultPreviewTemplates = { generic: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' + ' {content}\n' + ' {footer}\n' + '</div>\n', html: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' + ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' </object>\n' + ' {footer}\n' + '</div>', image: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' + ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' + ' {footer}\n' + '</div>\n', text: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' + ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' + ' {data}\n' + ' </div>\n' + ' {footer}\n' + '</div>\n', video: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' <video width="{width}" height="{height}" controls>\n' + ' <source src="{data}" type="{type}">\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' </video>\n' + ' {footer}\n' + '</div>\n', audio: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' <audio controls>\n' + ' <source src="{data}" type="{type}">\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' </audio>\n' + ' {footer}\n' + '</div>\n', flash: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' + ' </object>\n' + ' {footer}\n' + '</div>\n', object: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' + ' <param name="movie" value="{caption}" />\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' + ' </object>\n' + ' {footer}\n' + '</div>', other: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' {footer}\n' + '</div>', }; var defaultPreviewSettings = { image: {width: "auto", height: "160px"}, html: {width: "213px", height: "160px"}, text: {width: "160px", height: "160px"}, video: {width: "213px", height: "160px"}, audio: {width: "213px", height: "80px"}, flash: {width: "213px", height: "160px"}, object: {width: "160px", height: "160px"}, other: {width: "160px", height: "160px"} }; var defaultFileTypeSettings = { image: function(vType, vName) { return (typeof vType !== "undefined") ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i); }, html: function(vType, vName) { return (typeof vType !== "undefined") ? vType == 'text/html' : vName.match(/\.(htm|html)$/i); }, text: function(vType, vName) { return typeof vType !== "undefined" && vType.match('text.*') || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i); }, video: function (vType, vName) { return typeof vType !== "undefined" && vType.match(/\.video\/(ogg|mp4|webm)$/i) || vName.match(/\.(og?|mp4|webm)$/i); }, audio: function (vType, vName) { return typeof vType !== "undefined" && vType.match(/\.audio\/(ogg|mp3|wav)$/i) || vName.match(/\.(ogg|mp3|wav)$/i); }, flash: function (vType, vName) { return typeof vType !== "undefined" && vType == 'application/x-shockwave-flash' || vName.match(/\.(swf)$/i); }, object: function (vType, vName) { return true; }, other: function (vType, vName) { return true; }, }; var isEmpty = function (value, trim) { return value === null || value === undefined || value == [] || value === '' || trim && $.trim(value) === ''; }, isArray = function (a) { return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]'; }, isSet = function (needle, haystack) { return (typeof haystack == 'object' && needle in haystack); }, getValue = function (options, param, value) { return (isEmpty(options) || isEmpty(options[param])) ? value : options[param]; }, getElement = function (options, param, value) { return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]); }, uniqId = function () { return Math.round(new Date().getTime() + (Math.random() * 100)); }, htmlEncode = function(str) { return String(str) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); }, vUrl = window.URL || window.webkitURL; var FileInput = function (element, options) { this.$element = $(element); if (hasFileAPISupport() || isIE(9)) { this.init(options); this.listen(); } else { this.$element.removeClass('file-loading'); } }; FileInput.prototype = { constructor: FileInput, init: function (options) { var self = this, $el = self.$element; for (key in options) { self[key] = options[key]; } if (isEmpty(self.allowedPreviewTypes)) { self.allowedPreviewTypes = defaultPreviewTypes; } self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data'; self.reader = null; self.isIE9 = isIE(9); self.isIE10 = isIE(10); self.filestack = []; self.ajaxRequests = []; self.isError = false; self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled; self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly'); self.isUploadable = hasFileUploadSupport && !isEmpty(self.uploadUrl); self.slug = typeof options.slugCallback == "function" ? options.slugCallback : self.slugDefault; self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2'); self.captionTemplate = self.getLayoutTemplate('caption'); self.previewGenericTemplate = self.getPreviewTemplate('generic'); if (isEmpty(self.$element.attr('id'))) { self.$element.attr('id', uniqId()); } if (typeof self.$container == 'undefined') { self.$container = self.createContainer(); } else { self.refreshContainer(); } self.$progress = self.$container.find('.kv-upload-progress'); self.$btnUpload = self.$container.find('.kv-fileinput-upload') self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption')); self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name')); self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview')); self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails')); self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status')); self.$errorContainer = getElement(options, 'elErrorContainer', self.$previewContainer.find('.kv-fileinput-error')); if (!isEmpty(self.msgErrorClass)) { addCss(self.$errorContainer, self.msgErrorClass); } self.$errorContainer.hide(); self.initialPreviewContent = ''; var content = self.initialPreview; self.initialPreviewCount = isArray(content) ? content.length : (content.length > 0 ? content.split(self.initialPreviewDelimiter).length : 0); self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings); self.previewInitId = "preview-" + uniqId(); self.initPreview(); self.initPreviewDeletes(); self.original = { preview: self.$preview.html(), caption: self.$caption.html() }; self.autoSizeCaption(); self.options = options; self.setFileDropZoneTitle(); self.uploadCount = 0; self.uploadPercent = 0; self.$element.removeClass('file-loading'); }, getLayoutTemplate: function(t) { var self = this; return isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t]; }, getPreviewTemplate: function(t) { var self = this; return isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t]; }, listen: function () { var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile; $el.on('change', $.proxy(self.change, self)); $(window).on('resize', function() { setTimeout(function() { self.autoSizeCaption(); }, 100); }); $btnFile.on('click', function (ev) { self.$element.trigger('filebrowse'); if (self.isError && !self.isUploadable) { self.clear(false); } $cap.focus(); }); $el.closest('form').on('reset', $.proxy(self.reset, self)); self.$container.on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self)); self.$container.on('click', '.fileinput-cancel', $.proxy(self.cancel, self)); if (self.isUploadable && self.dropZoneEnabled && self.showPreview) { self.initDragDrop(); } if (!self.isUploadable) { return; } self.$container.find('.kv-fileinput-upload').on('click', function(e) { if (!self.isUploadable) { return; } e.preventDefault(); var totLen = self.getFileStack().length; if (self.isDisabled || $(this).hasClass('disabled') || !isEmpty($(this).attr('disabled')) || totLen == 0) { return; } self.resetUpload(); self.$progress.removeClass('hide'); self.uploadCount = 0; self.uploadPercent = 0; var i, len = self.filestack.length, template = self.getLayoutTemplate('progress'); setTimeout(function() { self.lock(); self.setProgress(0); if ((self.uploadAsync || totLen == 1) && self.showPreview) { for (i = 0; i < len; i++) { if (self.filestack[i] !== undefined) { self.upload(i, true); } } return; } self.uploadBatch(); }, 100); }); }, setProgress: function(percent) { var self = this, template = self.getLayoutTemplate('progress'), pct = Math.min(percent, 100); self.$progress.html(template.replace(/\{percent\}/g, pct)); }, lock: function() { var self = this; self.resetErrors(); self.disable(); if (self.showRemove) { addCss(self.$container.find('.fileinput-remove'), 'hide'); } if (self.showCancel) { self.$container.find('.fileinput-cancel').removeClass('hide'); } self.$element.trigger('filelock', [self.filestack]); }, unlock: function() { var self = this; self.enable(); if (self.showCancel) { addCss(self.$container.find('.fileinput-cancel'), 'hide'); } if (self.showRemove) { self.$container.find('.fileinput-remove').removeClass('hide'); } self.$element.trigger('fileunlock', [self.filestack]); }, refresh: function (options) { var self = this, $el = self.$element, params = (arguments.length) ? $.extend(self.options, options) : self.options; $el.off(); self.init(params); var $zone = self.$container.find('.file-drop-zone'); $el.on('change', $.proxy(self.change, self)); $zone.off('dragenter dragover drop'); self.$(document).off('dragenter dragover drop'); self.setFileDropZoneTitle(); }, initDragDrop: function() { var self = this, $zone = self.$container.find('.file-drop-zone'); $zone.off('dragenter dragover drop'); $(document).off('dragenter dragover drop'); $zone.on('dragenter dragover', function (e) { e.stopPropagation(); e.preventDefault(); if (self.isDisabled) { return; } addCss($(this), 'highlighted'); }); $zone.on('dragleave', function (e) { e.stopPropagation(); e.preventDefault(); if (self.isDisabled) { return; } $(this).removeClass('highlighted'); }); $zone.on('drop', function (e) { e.preventDefault(); if (self.isDisabled) { return; } self.change(e, 'dragdrop'); $(this).removeClass('highlighted'); }); $(document).on('dragenter dragover drop', function (e) { e.stopPropagation(); e.preventDefault(); }); }, setFileDropZoneTitle: function() { var self = this, $zone = self.$container.find('.file-drop-zone'); $zone.find('.' + self.dropZoneTitleClass).remove(); if (!self.isUploadable || !self.showPreview || $zone.length == 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) { return; } if ($zone.find('.file-preview-frame').length == 0) { $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>'); } self.$container.removeClass('file-input-new'); }, initFileActions: function() { var self = this; self.$preview.find('.kv-file-remove').each(function() { var $el = $(this), $frame = $el.closest('.file-preview-frame'), ind = $frame.attr('data-fileindex'); $el.off('click').on('click', function() { $frame.fadeOut('slow', function() { self.filestack[ind] = undefined; self.clearObjects($frame); $frame.remove(); var filestack = self.getFileStack(), len = filestack.length, chk = self.$container.find('.file-preview-initial').length; if (len == 0 && chk == 0) { self.original.preview = ''; self.reset(); } else { var n = self.initialPreviewCount + len, cap = n > 1 ? self.msgSelected.replace(/\{n\}/g, n) : filestack[0].name; self.setCaption(cap); } }); }); }); self.$preview.find('.kv-file-upload').each(function() { var $el = $(this); $el.off('click').on('click', function() { var $frame = $el.closest('.file-preview-frame'), ind = $frame.attr('data-fileindex'); self.upload(ind); }); }); }, renderInitFileFooter: function(i) { var self = this, hasConfig = self.initialPreviewConfig.length > 0, template = self.getLayoutTemplate('footer'); if (hasConfig && !isEmpty(self.initialPreviewConfig[i])) { var config = self.initialPreviewConfig[i], caption = ('caption' in config) ? config.caption : '', width = ('width' in config) ? config.width : 'auto', url = ('url' in config) ? config.url : false, key = ('key' in config) ? config.key : null, disabled = url === false ? true : false, actions = self.initialPreviewShowDelete ? self.renderFileActions(false, true, disabled, url, key) : '', footer = template.replace(/\{actions\}/g, actions); return footer.replace(/\{caption\}/g, caption).replace(/\{width\}/g, width) .replace(/\{indicator\}/g, '').replace(/\{indicatorTitle\}/g, ''); } return ''; }, renderFileFooter: function(caption, width) { var self = this, config = self.fileActionSettings, template = self.getLayoutTemplate('footer'); if (self.isUploadable) { var footer = template.replace(/\{actions\}/g, self.renderFileActions(true, true, false, false, false)); return footer.replace(/\{caption\}/g, caption).replace(/\{width\}/g, width) .replace(/\{indicator\}/g, config.indicatorNew).replace(/\{indicatorTitle\}/g, config.indicatorNewTitle); } else { return template.replace(/\{actions\}/g, '').replace(/\{caption\}/g, caption).replace(/\{width\}/g, width) .replace(/\{indicator\}/g, '').replace(/\{indicatorTitle\}/g, ''); } return ''; }, renderFileActions: function(showUpload, showDelete, disabled, url, key) { if (!showUpload && !showDelete) { return ''; } var self = this, vUrl = url == false ? '' : ' data-url="' + url + '"', vKey = key == false ? '' : ' data-key="' + key + '"', btnDelete = self.getLayoutTemplate('actionDelete'), btnUpload = '', template = self.getLayoutTemplate('actions'), config = self.fileActionSettings, removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass; btnDelete = btnDelete .replace(/\{removeClass\}/g, removeClass) .replace(/\{removeIcon\}/g, config.removeIcon) .replace(/\{removeTitle\}/g, config.removeTitle) .replace(/\{dataUrl\}/g, vUrl) .replace(/\{dataKey\}/g, vKey); if (showUpload) { btnUpload = self.getLayoutTemplate('actionUpload') .replace(/\{uploadClass\}/g, config.uploadClass) .replace(/\{uploadIcon\}/g, config.uploadIcon) .replace(/\{uploadTitle\}/g, config.uploadTitle); } return template .replace(/\{delete\}/g, btnDelete) .replace(/\{upload\}/g, btnUpload); }, getInitialPreview: function(template, content, i) { var self = this, ind = 'init_' + i, previewId = self.previewInitId + '-' + ind; footer = self.renderInitFileFooter(i, false); return template .replace(/\{previewId\}/g, previewId) .replace(/\{frameClass\}/g, ' file-preview-initial') .replace(/\{fileindex\}/g, ind) .replace(/\{content\}/g, content) .replace(/\{footer\}/g, footer); }, initPreview: function () { var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount, cap = self.initialCaption.length, previewId = self.previewInitId + '-init_' + i; caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, len); if (isArray(content) && len > 0) { for (var i = 0; i < len; i++) { html += self.getInitialPreview(self.previewGenericTemplate, content[i], i); } if (len > 1 && cap == 0) { caption = self.msgSelected.replace(/\{n\}/g, len); } } else { if (len > 0) { var fileList = content.split(self.initialPreviewDelimiter); for (var i = 0; i < len; i++) { html += self.getInitialPreview(self.previewGenericTemplate, content[i], i); } if (len > 1 && cap == 0) { caption = self.msgSelected.replace(/\{n\}/g, len); } } else { if (cap > 0) { self.setCaption(caption); return; } else { return; } } } self.initialPreviewContent = html; self.$preview.html(html); self.setCaption(caption); self.$container.removeClass('file-input-new'); }, initPreviewDeletes: function() { var self = this, resetProgress = function() { if (self.$preview.find('.kv-file-remove').length == 0) { self.reset(); } }; self.$preview.find('.kv-file-remove').each(function() { var $el = $(this), $frame = $el.closest('.file-preview-frame'), vUrl = $el.attr('data-url'), vKey = $el.attr('data-key'), $content = $(self.initialPreviewContent); if (vUrl === undefined || vKey === undefined) { return; } $el.off('click').on('click', function() { $.ajax({ url: vUrl, type: 'POST', dataType: 'json', data: {key: vKey}, beforeSend: function() { addCss($frame, 'file-uploading'); addCss($el, 'disabled'); self.$element.trigger('filepredelete', [vKey]); }, success: function(data, textStatus, jqXHR) { setTimeout(function() { if(typeof data.error === 'undefined') { self.$element.trigger('filedeleted', [vKey]); } else { self.showError(data.error, null, $el.attr('id'), key, 'filedeleteerror'); resetProgress(); } $frame.removeClass('file-uploading').addClass('file-deleted'); $frame.fadeOut('slow', function() { self.clearObjects($frame); $frame.remove(); var $content = $(document.createElement('div')).html(self.original.preview); $content.find('.file-preview-frame').each(function() { var $el = $(this); if ($el.find('.kv-file-remove').attr('data-key') == vKey) { $el.remove(); } }); self.initialPreviewContent = $content.html(); if (self.initialPreviewCount > 0) { self.initialPreviewCount--; } var caption = (self.initialCaption.length > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, self.initialPreviewCount); self.original.preview = $content.html(); self.setCaption(caption); self.original.caption = self.$caption.html(); $content.remove(); resetProgress(); }); }, 100); }, error: function(jqXHR, textStatus, errorThrown) { self.showError(errorThrown, null, $el.attr('id'), key, 'filedeleteerror'); $frame.removeClass('file-uploading'); resetProgress(); } }); }); }); }, clearObjects: function($el) { $el.find('video audio').each(function() { this.pause(); delete(this); $(this).remove(); }); $el.find('img object div').each(function() { delete(this); $(this).remove(); }); }, clearFileInput: function() { var self = this, $el = self.$element; if (isEmpty($el.val())) { return; } // Fix for IE ver < 11, that does not clear file inputs // Requires a sequence of steps to prevent IE crashing but // still allow clearing of the file input. if (self.isIE9 || self.isIE10) { var $srcFrm = $el.closest('form'), $tmpFrm = $(document.createElement('form')), $tmpEl = $(document.createElement('div')); $el.before($tmpEl); if ($srcFrm.length) { $srcFrm.after($tmpFrm); } else { $tmpEl.after($tmpFrm); } $tmpFrm.append($el).trigger('reset'); $tmpEl.before($el).remove(); $tmpFrm.remove(); } else { // normal input clear behavior for other sane browsers $el.val(''); } }, resetUpload: function() { var self = this; self.uploadCount = 0; self.uploadPercent = 0; self.$btnUpload.removeAttr('disabled'); self.setProgress(0); addCss(self.$progress, 'hide'); self.resetErrors(false); self.ajaxRequests = []; }, cancel: function() { var self = this, xhr = self.ajaxRequests, len = xhr.length; if (len > 0) { for (i = 0; i < len; i++) { xhr[i].abort(); } self.$preview.find('file-preview-frame').each(function() { $thumb = $(this), ind = $thumb.attr('data-fileindex'); $thumb.removeClass('file-uploading'); if (self.filestack[ind] !== undefined) { $thumb.find('.kv-file-upload').removeClass('disabled'); $thumb.find('.kv-file-upload').removeClass('disabled'); } }); self.unlock(); } }, clear: function () { var self = this, e = arguments.length && arguments[0]; if (!self.isIE9 && self.reader instanceof FileReader) { self.reader.abort(); } self.$btnUpload.removeAttr('disabled'); self.resetUpload(); self.filestack = []; self.autoSizeCaption(); self.clearFileInput(); self.resetErrors(true); if (e !== false) { self.$element.trigger('change'); self.$element.trigger('fileclear'); } if (self.overwriteInitial) { self.initialPreviewCount = 0; self.initialPreviewContent = ''; } if (!self.overwriteInitial && self.initialPreviewContent.length > 0) { self.showFileIcon(); self.$preview.html(self.original.preview); self.$caption.html(self.original.caption); self.initPreviewDeletes(); self.$container.removeClass('file-input-new'); } else { self.$preview.find('.file-preview-frame').each(function() { self.clearObjects($(this)); }); self.$preview.html(''); var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.original.caption : ''; self.$caption.html(cap); self.$caption.attr('title', ''); addCss(self.$container, 'file-input-new'); } if (self.$container.find('.file-preview-frame').length == 0) { self.initialCaption = ''; self.original.caption = ''; self.$caption.html(''); self.$captionContainer.find('.kv-caption-icon').hide(); } self.hideFileIcon(); self.$element.trigger('filecleared'); self.$captionContainer.focus(); self.setFileDropZoneTitle(); }, reset: function () { var self = this; self.clear(false); self.$preview.html(self.original.preview); self.$caption.html(self.original.caption); self.$container.find('.fileinput-filename').text(''); self.$element.trigger('filereset'); if (self.initialPreview.length > 0) { self.$container.removeClass('file-input-new'); } self.setFileDropZoneTitle(); if (self.isUploadable) { self.resetUpload(); } self.filestack = []; }, disable: function (e) { var self = this; self.isDisabled = true; self.$element.attr('disabled', 'disabled'); self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled"); self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true); self.initDragDrop(); }, enable: function (e) { var self = this; self.isDisabled = false; self.$element.removeAttr('disabled'); self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled"); self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled"); self.initDragDrop(); }, uploadExtra: function(fd) { var self = this; if (self.uploadExtraData.length == 0) { return; } $.each(self.uploadExtraData, function(key, value) { if (!isEmpty(key) && !isEmpty(value)) { fd.append(key, value); } }); }, initXhr: function(xhrobj) { var self = this; if (xhrobj.upload) { xhrobj.upload.addEventListener('progress', function(event) { var pct = 0, position = event.loaded || event.position, total = event.total; if (event.lengthComputable) { pct = Math.ceil(position / total * 98); } self.uploadPercent = Math.max(pct, self.uploadPercent); //Set progress self.setProgress(self.uploadPercent); }, false); } return xhrobj; }, upload: function(i) { var self = this, files = self.getFileStack(), formdata = new FormData(), previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'), $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings; if ($btnUpload.hasClass('disabled')) { return; } var percent, total = files.length, allFiles = arguments.length > 1, setIndicator = function (icon, msg) { $indicator.html(config[icon]); $indicator.attr('title', config[msg]); }, updateProgress = function() { if (self.$preview.find('file-uploading').length == 0) { self.unlock(); } if (!allFiles) { return; } self.uploadCount++; var pct = total > 0 ? Math.ceil(self.uploadCount * 100/total) : 0; self.uploadPercent = Math.max(pct, self.uploadPercent); self.setProgress(self.uploadPercent); self.initPreviewDeletes(); }, resetActions = function() { $btnUpload.removeClass('disabled'); $btnDelete.removeClass('disabled'); $thumb.removeClass('file-uploading'); }; formdata.append(self.uploadFileAttr, files[i]); formdata.append('file_id', i); self.uploadExtra(formdata); self.ajaxRequests.push($.ajax({ xhr: function() { var xhrobj = $.ajaxSettings.xhr(); return self.initXhr(xhrobj); }, url: self.uploadUrl, type: 'POST', dataType: 'json', data: formdata, cache: false, processData: false, contentType: false, beforeSend: function() { setIndicator('indicatorLoading', 'indicatorLoadingTitle'); addCss($thumb, 'file-uploading'); addCss($btnUpload, 'disabled'); addCss($btnDelete, 'disabled'); if (!allFiles) { self.lock(); } self.$element.trigger('filepreupload', [formdata, previewId, i]) }, success: function(data, textStatus, jqXHR) { setTimeout(function() { if(typeof data.error === 'undefined') { setIndicator('indicatorSuccess', 'indicatorSuccessTitle'); $btnUpload.hide(); $btnDelete.hide(); self.filestack[i] = undefined; self.$element.trigger('fileuploaded', [formdata, previewId, i]); } else { setIndicator('indicatorError', 'indicatorErrorTitle'); self.showUploadError(data.error, formdata, previewId, i, 'fileuploaderror'); } updateProgress(); resetActions(); }, 100); }, error: function(jqXHR, textStatus, errorThrown) { setIndicator('indicatorError', 'indicatorErrorTitle'); if (allFiles) { var cap = files[i].name; self.showUploadError('<b>' + cap + '</b>: ' + errorThrown, formdata, previewId, i, 'fileuploaderror'); } else { self.showUploadError(errorThrown, formdata, previewId, i, 'fileuploaderror'); } updateProgress(); resetActions(); } })); }, uploadBatch: function() { var self = this, files = self.filestack, total = files.length, config = self.fileActionSettings; formdata = new FormData(), setIndicator = function (i, icon, msg) { $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator'), $indicator.html(config[icon]); $indicator.attr('title', config[msg]); }, setAllUploaded = function() { $.each(files, function(key, data) { self.filestack[key] = undefined; }); }; $.each(files, function(key, data) { if (files[key] !== undefined) { formdata.append(self.uploadFileAttr, files[key]); } }); self.uploadExtra(formdata); $.ajax({ xhr: function() { var xhrobj = $.ajaxSettings.xhr(); return self.initXhr(xhrobj); }, url: self.uploadUrl, type: 'POST', dataType: 'json', data: formdata, cache: false, processData: false, contentType: false, beforeSend: function() { addCss(self.$preview.find('.file-preview-frame'), 'file-uploading'); self.lock(); }, success: function(data, textStatus, jqXHR) { setTimeout(function() { var keys = isEmpty(data.errorkeys) ? [] : data.errorkeys; if(typeof data.error === 'undefined' || isEmpty(data.error)) { setAllUploaded(); if (self.showPreview) { self.$preview.find('.kv-file-upload').hide(); self.$preview.find('.kv-file-remove').hide(); self.$preview.find('.file-preview-frame').each(function() { var $thumb = $(this), key = $thumb.attr('data-fileindex'); setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle'); $thumb.removeClass('file-uploading'); }); } else { self.reset(); } } else { self.$preview.find('.file-preview-frame').each(function() { var $thumb = $(this), key = $thumb.attr('data-fileindex'); if (keys.length == 0) { $thumb.removeClass('file-uploading'); setIndicator(key, 'indicatorError', 'indicatorErrorTitle'); return; } if ($.inArray(key, keys)) { setIndicator(key, 'indicatorError', 'indicatorErrorTitle'); } else { var $upload = $thumb.find('.kv-file-upload'), $remove = $thumb.find('.kv-file-remove'); addCss($upload, 'disabled'); addCss($remove, 'disabled'); $upload.hide(); $remove.hide(); $thumb.removeClass('file-uploading'); setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle'); self.filestack[key] = undefined; } }); self.showUploadError(data.error, formdata, null, null, 'filebatchuploaderror'); } }, 100); }, complete: function () { self.setProgress(100); self.unlock(); }, error: function(jqXHR, textStatus, errorThrown) { self.showUploadError(errorThrown, formdata, null, null, 'filebatchuploaderror'); self.uploadFileCount = total - 1; self.$preview.find('.file-preview-frame').removeClass('file-uploading'); } }); }, hideFileIcon: function () { if (this.overwriteInitial) { this.$captionContainer.find('.kv-caption-icon').hide(); } }, showFileIcon: function () { this.$captionContainer.find('.kv-caption-icon').show(); }, resetErrors: function (fade) { var self = this, $error = self.$errorContainer; self.isError = false; self.$container.removeClass('has-error'); $error.html(''); if (fade) { $error.fadeOut('slow'); } else { $error.hide(); } }, showUploadError: function (msg, file, previewId, index) { var self = this, $error = self.$errorContainer, $el = self.$element, ev = arguments.length > 4 ? arguments[4] : 'fileerror'; if ($error.find('ul').length == 0) { $error.html('<ul class="text-left"><li>' + msg + '</li></ul>'); } else { $error.find('ul').append('<li>' + msg + '</li>'); } $error.fadeIn(800); $el.trigger(ev, [file, previewId, index]); addCss(self.$container, 'has-error'); return true; }, showError: function (msg, file, previewId, index) { var self = this, $error = self.$errorContainer, $el = self.$element, ev = arguments.length > 4 ? arguments[4] : 'fileerror'; $error.html(msg); $error.fadeIn(800); $el.trigger(ev, [file, previewId, index]); if (!self.isUploadable) { self.clearFileInput(); } addCss(self.$container, 'has-error'); self.$btnUpload.attr('disabled', true); return true; }, errorHandler: function (evt, caption) { var self = this; switch (evt.target.error.code) { case evt.target.error.NOT_FOUND_ERR: self.addError(self.msgFileNotFound.replace(/\{name\}/g, caption)); break; case evt.target.error.NOT_READABLE_ERR: self.addError(self.msgFileNotReadable.replace(/\{name\}/g, caption)); break; case evt.target.error.ABORT_ERR: self.addError(self.msgFilePreviewAborted.replace(/\{name\}/g, caption)); break; default: self.addError(self.msgFilePreviewError.replace(/\{name\}/g, caption)); } }, parseFileType: function(file) { var isValid, vType; for (var i = 0; i < defaultPreviewTypes.length; i++) { cat = defaultPreviewTypes[i]; isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat]; vType = isValid(file.type, file.name) ? cat : ''; if (vType != '') { return vType; } } return 'other'; }, previewDefault: function(file, previewId) { var self = this; if (!self.showPreview) { return; } var data = vUrl.createObjectURL(file), $obj = $('#' + previewId), config = self.previewSettings.other, footer = self.isUploadable ? self.renderFileFooter(file.name, config.width) : self.renderFileFooter(file.name, config.width, false), previewOtherTemplate = self.getPreviewTemplate('other'), ind = previewId.slice(previewId.lastIndexOf('-') + 1), frameClass = ''; if (arguments.length > 2) { var $err = $(self.msgValidationError); frameClass = ' btn disabled'; footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>'; } self.$preview.append("\n" + previewOtherTemplate .replace(/\{previewId\}/g, previewId) .replace(/\{frameClass\}/g, frameClass) .replace(/\{fileindex\}/g, ind) .replace(/\{caption\}/g, self.slug(file.name)) .replace(/\{width\}/g, config.width) .replace(/\{height\}/g, config.height) .replace(/\{type\}/g, file.type) .replace(/\{data\}/g, data) .replace(/\{footer\}/g, footer)); $obj.on('load', function(e) { vUrl.revokeObjectURL($obj.attr('data')); }); }, previewFile: function(file, theFile, previewId, data) { var self = this; if (!self.showPreview) { return; } var cat = self.parseFileType(file), caption = self.slug(file.name), data, obj, content, types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, fType = file.type, template = isSet(cat, self.previewTemplates) ? self.previewTemplates[cat] : defaultPreviewTemplates[cat], config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat], wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, $preview = self.$preview, chkTypes = types.indexOf(cat) >=0, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)), footer = self.renderFileFooter(caption, config.width), ind = previewId.slice(previewId.lastIndexOf('-') + 1); if (chkTypes && chkMimes) { if (cat == 'text') { var strText = htmlEncode(theFile.target.result); vUrl.revokeObjectURL(data); if (strText.length > wrapLen) { var id = 'text-' + uniqId(), height = window.innerHeight * .75, modal = self.getLayoutTemplate('modal') .replace(/\{id\}/g, id) .replace(/\{title\}/g, caption) .replace(/\{height\}/g, height) .replace(/\{body\}/g, strText); wrapInd = wrapInd .replace(/\{title\}/g, caption) .replace(/\{dialog\}/g, "$('#" + id + "').modal('show')"); strText = strText.substring(0, (wrapLen - 1)) + wrapInd; } content = template .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption) .replace(/\{frameClass\}/g, '') .replace(/\{type\}/g, file.type).replace(/\{width\}/g, config.width) .replace(/\{height\}/g, config.height).replace(/\{data\}/g, strText) .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind) + modal; } else { content = template .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption) .replace(/\{frameClass\}/g, '') .replace(/\{type\}/g, file.type).replace(/\{data\}/g, data) .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height) .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind); } $preview.append("\n" + content); self.autoSizeImage(previewId); } else { self.previewDefault(file, previewId); } }, slugDefault: function (text) { return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w-.\\\/ ]+/g,''); }, getFileStack: function() { var size = 0, self = this; return self.filestack.filter(function(n){ return n != undefined }); }, readFiles: function (files) { this.reader = new FileReader(); var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader, $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType, wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings, isText = isSet('text', settings) ? settings['text'] : defaultFileTypeSettings['text'], ctr = self.filestack.length, throwError = function(msg, file, previewId, index) { self.previewDefault(file, previewId, true); return self.isUploadable ? self.showUploadError(msg, file, previewId, index) : self.showError(msg, file, previewId, index); }; function readFile(i) { if (isEmpty($el.attr('multiple'))) { numFiles = 1; } if (i >= numFiles) { $container.removeClass('loading'); $status.html(''); return; } var node = ctr + i, previewId = previewInitId + "-" + node, file = files[i], caption = self.slug(file.name), fileSize = (file.size ? file.size : 0) / 1000, checkFile, previewData = vUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk, fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '), fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', '), fileExtExpr = isEmpty(fileExt) ? '' : new RegExp('\\.(' + fileExt.join('|') + ')$', 'i'); fileSize = fileSize.toFixed(2); if (self.maxFileSize > 0 && fileSize > self.maxFileSize) { msg = self.msgSizeTooLarge.replace(/\{name\}/g, caption).replace(/\{size\}/g, fileSize).replace(/\{maxSize\}/g, self.maxFileSize); self.isError = throwError(msg, file, previewId, i); return; } if (!isEmpty(fileTypes) && isArray(fileTypes)) { for (j = 0; j < fileTypes.length; j++) { typ = fileTypes[j]; checkFile = settings[typ]; chk = (checkFile !== undefined && checkFile(file.type, caption)); fileCount += isEmpty(chk) ? 0 : chk.length; } if (fileCount == 0) { msg = self.msgInvalidFileType.replace(/\{name\}/g, caption).replace(/\{types\}/g, strTypes); self.isError = throwError(msg, file, previewId, i); return; } } if (fileCount == 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) { chk = caption.match(fileExtExpr); fileCount += isEmpty(chk) ? 0 : chk.length; if (fileCount == 0) { msg = self.msgInvalidFileExtension.replace(/\{name\}/g, caption).replace(/\{extensions\}/g, strExt); self.isError = throwError(msg, file, previewId, i); return; } } if (!self.showPreview) { self.filestack.push(file); setTimeout(readFile(i + 1), 100); $el.trigger('fileloaded', [file, previewId, i]); return; } if ($preview.length > 0 && typeof FileReader !== "undefined") { $status.html(msgLoading.replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)); $container.addClass('loading'); reader.onerror = function (evt) { self.errorHandler(evt, caption); }; reader.onload = function (theFile) { self.previewFile(file, theFile, previewId, previewData); self.initFileActions(); }; reader.onloadend = function (e) { var msg = msgProgress .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles) .replace(/\{percent\}/g, 100).replace(/\{name\}/g, caption); setTimeout(function () { $status.html(msg); vUrl.revokeObjectURL(previewData); }, 100); setTimeout(function () { readFile(i + 1); self.updateFileDetails(numFiles); }, 100); $el.trigger('fileloaded', [file, previewId, i]); }; reader.onprogress = function (data) { if (data.lengthComputable) { var progress = parseInt(((data.loaded / data.total) * 100), 10); var msg = msgProgress .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles) .replace(/\{percent\}/g, progress).replace(/\{name\}/g, caption); setTimeout(function () { $status.html(msg); }, 100); } }; if (isText(file.type, caption)) { reader.readAsText(file, self.textEncoding); } else { reader.readAsArrayBuffer(file); } } else { self.previewDefault(file, previewId); setTimeout(function() { readFile(i + 1); self.updateFileDetails(numFiles); }, 100); $el.trigger('fileloaded', [file, previewId, i]); } self.filestack.push(file); } readFile(0); self.updateFileDetails(numFiles, false); }, updateFileDetails: function(numFiles) { var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(), name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles; numFiles = self.initialPreviewCount + n, log = n > 1 ? msgSelected.replace(/\{n\}/g, numFiles) : label; if (self.isError) { self.$previewContainer.removeClass('loading'); self.$previewStatus.html(''); self.$captionContainer.find('.kv-caption-icon').hide(); log = self.msgValidationError; } else { self.showFileIcon(); } self.setCaption(log); self.$container.removeClass('file-input-new'); if (arguments.length == 1) { $el.trigger('fileselect', [numFiles, label]); } }, change: function (e) { var self = this, $el = self.$element, label = self.slug($el.val()), total = 0, $preview = self.$preview, isDragDrop = arguments.length > 1, files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, msgSelected = self.msgSelected, numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles, ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr != 0), throwError = function(msg, file, previewId, index) { return self.isUploadable ? self.showUploadError(msg, file, previewId, index) : self.showError(msg, file, previewId, index); }; self.resetUpload(); self.hideFileIcon(); self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove(); if (isDragDrop) { tfiles = files; } else { if (e.target.files === undefined) { tfiles = e.target && e.target.value ? [ {name: e.target.value.replace(/^.+\\/, '')} ] : []; } else { tfiles = e.target.files; } } if (isEmpty(tfiles) || tfiles.length === 0) { if (!isAjaxUpload) { self.clear(false); } $el.trigger('fileselectnone'); return; } self.resetErrors(); if (!isAjaxUpload) { if (!self.overwriteInitial) { $preview.html(self.initialPreviewContent); } else { $preview.html(''); } } var total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length; if (self.maxFileCount > 0 && total > self.maxFileCount) { var msg = self.msgFilesTooMany.replace(/\{m\}/g, self.maxFileCount).replace(/\{n\}/g, total); self.isError = throwError(msg, null, null, null); self.$captionContainer.find('.kv-caption-icon').hide(); self.$caption.html(self.msgValidationError); self.$container.removeClass('file-input-new'); return; } if (!self.isIE9) { self.readFiles(files); } else { self.updateFileDetails(1); } self.reader = null; }, autoSizeImage: function(previewId) { var self = this, $preview = self.$preview, $thumb = $preview.find("#" + previewId), $img = $thumb.find('img'); if (!$img.length) { return; } $img.on('load', function() { var w1 = $thumb.width(), w2 = $preview.width(); if (w1 > w2) { $img.css('width', '100%'); $thumb.css('width', '97%'); } var $cap = $img.closest('.file-preview-frame').find('.file-caption-name'); if ($cap.length) { $cap.width($img.width()); $cap.attr('title', $cap.text()); } self.$element.trigger('fileimageloaded', previewId); }); }, autoSizeCaption: function() { var self = this; if (self.$caption.length == 0 || !self.autoFitCaption) { return; } self.$caption.css('width', 0); setTimeout(function() { var w = self.$captionContainer.width(); self.$caption.css('width', 0.98 * w); }, 100); }, setCaption: function(content) { var self = this, title = $('<div>' + content + '</div>').text(), icon = self.layoutTemplates['icon'], out = icon + title; if (self.$caption.length == 0) { return; } self.$caption.html(out); self.$caption.attr('title', title); self.autoSizeCaption(); }, initBrowse: function ($container) { var self = this; self.$btnFile = $container.find('.btn-file'); self.$btnFile.append(self.$element); }, createContainer: function () { var self = this; var $container = $(document.createElement("span")).attr({"class": 'file-input file-input-new'}).html(self.renderMain()); self.$element.before($container); self.initBrowse($container); return $container; }, refreshContainer: function () { var self = this, $container = self.$container; $container.before(self.$element); $container.html(self.renderMain()); self.initBrowse($container); }, renderMain: function () { var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '';; var preview = self.showPreview ? self.getLayoutTemplate('preview') .replace(/\{class\}/g, self.previewClass) .replace(/\{dropClass\}/g, dropCss) : ''; var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass; var caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption'); return self.mainTemplate.replace(/\{class\}/g, self.mainClass). replace(/\{preview\}/g, preview). replace(/\{caption\}/g, caption). replace(/\{upload\}/g, self.renderUpload()). replace(/\{remove\}/g, self.renderRemove()). replace(/\{cancel\}/g, self.renderCancel()). replace(/\{browse\}/g, self.renderBrowse()); }, renderBrowse: function () { var self = this, css = self.browseClass + ' btn-file', status = ''; if (self.isDisabled) { status = ' disabled '; } return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>'; }, renderRemove: function () { var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = ''; if (!self.showRemove) { return ''; } if (self.isDisabled) { status = ' disabled '; } return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>'; }, renderCancel: function () { var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button', status = ''; if (!self.showCancel) { return ''; } return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>'; }, renderUpload: function () { var self = this, css = self.uploadClass + ' kv-fileinput-upload', content = '', status = ''; if (!self.showUpload) { return ''; } if (self.isDisabled) { status = ' disabled '; } if (!self.isUploadable || self.isDisabled) { content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>'; } else { content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>'; } return content; } } //FileInput plugin definition $.fn.fileinput = function (option) { if (!hasFileAPISupport() && !isIE(9)) { return; } var args = Array.apply(null, arguments); args.shift(); return this.each(function () { var $this = $(this), data = $this.data('fileinput'), options = typeof option === 'object' && option; if (!data) { $this.data('fileinput', (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data())))); } if (typeof option === 'string') { data[option].apply(data, args); } }); }; $.fn.fileinput.defaults = { showCaption: true, showPreview: true, showRemove: true, showUpload: true, showCancel: true, autoFitCaption: true, mainClass: '', previewClass: '', captionClass: '', mainTemplate: null, initialCaption: '', initialPreview: '', initialPreviewCount: 0, initialPreviewDelimiter: '*$$*', initialPreviewConfig: [], initialPreviewShowDelete: true, overwriteInitial: true, layoutTemplates: defaultLayoutTemplates, previewTemplates: defaultPreviewTemplates, allowedPreviewTypes: defaultPreviewTypes, allowedPreviewMimeTypes: null, allowedFileTypes: null, allowedFileExtensions: null, previewSettings: defaultPreviewSettings, fileTypeSettings: defaultFileTypeSettings, browseLabel: 'Browse &hellip;', browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;', browseClass: 'btn btn-primary', removeLabel: 'Remove', removeTitle: 'Clear selected files', removeIcon: '<i class="glyphicon glyphicon-trash"></i> ', removeClass: 'btn btn-default', cancelLabel: 'Cancel', cancelTitle: 'Abort ongoing upload', cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ', cancelClass: 'btn btn-default', uploadLabel: 'Upload', uploadTitle: 'Upload selected files', uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ', uploadClass: 'btn btn-default', uploadUrl: null, uploadExtraData: [], uploadAsync: true, maxFileSize: 0, maxFileCount: 0, msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!', msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!', msgFileNotFound: 'File "{name}" not found!', msgFileNotReadable: 'File "{name}" is not readable.', msgFilePreviewAborted: 'File preview aborted for "{name}".', msgFilePreviewError: 'An error occurred while reading the file "{name}".', msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.', msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.', msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>', msgErrorClass: 'file-error-message', msgLoading: 'Loading file {index} of {files} &hellip;', msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.', msgSelected: '{n} files selected', previewFileType: 'image', wrapTextLength: 250, wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>', elCaptionContainer: null, elCaptionText: null, elPreviewContainer: null, elPreviewImage: null, elPreviewStatus: null, elErrorContainer: null, slugCallback: null, dropZoneEnabled: true, dropZoneTitle: 'Drag & drop files here &hellip;', dropZoneTitleClass: 'file-drop-zone-title', fileActionSettings: {}, textEncoding: 'UTF-8' }; /** * Convert automatically file inputs with class 'file' * into a bootstrap fileinput control. */ $(document).ready(function () { var $input = $('input.file[type=file]'), count = $input.attr('type') != null ? $input.length : 0; if (count > 0) { $input.fileinput(); } }); $.fn.fileinput.Constructor = FileInput; })(window.jQuery);
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.2.1 * @link http://www.ag-grid.com/ * @license MIT */ var utils_1 = require('../utils'); var eventService_1 = require("../eventService"); var Component = (function () { function Component(template) { this.destroyFunctions = []; this.childComponents = []; if (template) { this.eGui = utils_1.Utils.loadTemplate(template); } } Component.prototype.setTemplate = function (template) { this.eGui = utils_1.Utils.loadTemplate(template); }; Component.prototype.addEventListener = function (eventType, listener) { if (!this.localEventService) { this.localEventService = new eventService_1.EventService(); } this.localEventService.addEventListener(eventType, listener); }; Component.prototype.removeEventListener = function (eventType, listener) { if (this.localEventService) { this.localEventService.removeEventListener(eventType, listener); } }; Component.prototype.dispatchEvent = function (eventType, event) { if (this.localEventService) { this.localEventService.dispatchEvent(eventType, event); } }; Component.prototype.getGui = function () { return this.eGui; }; Component.prototype.queryForHtmlElement = function (cssSelector) { return this.eGui.querySelector(cssSelector); }; Component.prototype.queryForHtmlInputElement = function (cssSelector) { return this.eGui.querySelector(cssSelector); }; Component.prototype.appendChild = function (newChild) { if (utils_1.Utils.isNodeOrElement(newChild)) { this.eGui.appendChild(newChild); } else { var childComponent = newChild; this.eGui.appendChild(childComponent.getGui()); this.childComponents.push(childComponent); } }; Component.prototype.setVisible = function (visible) { utils_1.Utils.addOrRemoveCssClass(this.eGui, 'ag-hidden', !visible); }; Component.prototype.destroy = function () { this.childComponents.forEach(function (childComponent) { return childComponent.destroy(); }); this.destroyFunctions.forEach(function (func) { return func(); }); }; Component.prototype.addGuiEventListener = function (event, listener) { var _this = this; this.getGui().addEventListener(event, listener); this.destroyFunctions.push(function () { return _this.getGui().removeEventListener(event, listener); }); }; Component.prototype.addDestroyableEventListener = function (eElement, event, listener) { if (eElement instanceof HTMLElement) { eElement.addEventListener(event, listener); } else { eElement.addEventListener(event, listener); } this.destroyFunctions.push(function () { if (eElement instanceof HTMLElement) { eElement.removeEventListener(event, listener); } else { eElement.removeEventListener(event, listener); } }); }; Component.prototype.addDestroyFunc = function (func) { this.destroyFunctions.push(func); }; return Component; })(); exports.Component = Component;
/** * Generate the node required for the info display * @param {object} oSettings dataTables settings object * @returns {node} Information element * @memberof DataTable#oApi */ function _fnFeatureHtmlInfo ( oSettings ) { var nInfo = document.createElement( 'div' ); nInfo.className = oSettings.oClasses.sInfo; /* Actions that are to be taken once only for this feature */ if ( !oSettings.aanFeatures.i ) { /* Add draw callback */ oSettings.aoDrawCallback.push( { "fn": _fnUpdateInfo, "sName": "information" } ); /* Add id */ nInfo.id = oSettings.sTableId+'_info'; } oSettings.nTable.setAttribute( 'aria-describedby', oSettings.sTableId+'_info' ); return nInfo; } /** * Update the information elements in the display * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnUpdateInfo ( oSettings ) { /* Show information about the table */ if ( !oSettings.oFeatures.bInfo || oSettings.aanFeatures.i.length === 0 ) { return; } var oLang = oSettings.oLanguage, iStart = oSettings._iDisplayStart+1, iEnd = oSettings.fnDisplayEnd(), iMax = oSettings.fnRecordsTotal(), iTotal = oSettings.fnRecordsDisplay(), sOut; if ( iTotal === 0 ) { /* Empty record set */ sOut = oLang.sInfoEmpty; } else { /* Normal record set */ sOut = oLang.sInfo; } if ( iTotal != iMax ) { /* Record set after filtering */ sOut += ' ' + oLang.sInfoFiltered; } // Convert the macros sOut += oLang.sInfoPostFix; sOut = _fnInfoMacros( oSettings, sOut ); if ( oLang.fnInfoCallback !== null ) { sOut = oLang.fnInfoCallback.call( oSettings.oInstance, oSettings, iStart, iEnd, iMax, iTotal, sOut ); } var n = oSettings.aanFeatures.i; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { $(n[i]).html( sOut ); } } function _fnInfoMacros ( oSettings, str ) { var iStart = oSettings._iDisplayStart+1, sStart = oSettings.fnFormatNumber( iStart ), iEnd = oSettings.fnDisplayEnd(), sEnd = oSettings.fnFormatNumber( iEnd ), iTotal = oSettings.fnRecordsDisplay(), sTotal = oSettings.fnFormatNumber( iTotal ), iMax = oSettings.fnRecordsTotal(), sMax = oSettings.fnFormatNumber( iMax ); // When infinite scrolling, we are always starting at 1. _iDisplayStart is used only // internally if ( oSettings.oScroll.bInfinite ) { sStart = oSettings.fnFormatNumber( 1 ); } return str. replace(/_START_/g, sStart). replace(/_END_/g, sEnd). replace(/_TOTAL_/g, sTotal). replace(/_MAX_/g, sMax); }
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'preview', 'he', { preview: 'תצוגה מקדימה' });
describe('WaitsForBlock', function () { var env, suite, timeout, spec, message, onComplete, fakeTimer; beforeEach(function() { env = new jasmine.Env(); env.updateInterval = 0; suite = new jasmine.Suite(env, 'suite 1'); timeout = 1000; spec = new jasmine.Spec(env, suite); message = "some error message"; onComplete = jasmine.createSpy("onComplete"); }); describe("jasmine.VERBOSE", function() { var jasmineVerboseOriginal; beforeEach(function() { jasmineVerboseOriginal = jasmine.VERBOSE; spyOn(env.reporter, 'log'); }); it('do not show information if jasmine.VERBOSE is set to false', function () { jasmine.VERBOSE = false; var latchFunction = function() { return true; }; var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec); expect(env.reporter.log).not.toHaveBeenCalled(); block.execute(onComplete); expect(env.reporter.log).not.toHaveBeenCalled(); jasmine.VERBOSE = jasmineVerboseOriginal; }); it('show information if jasmine.VERBOSE is set to true', function () { jasmine.VERBOSE = true; var latchFunction = function() { return true; }; var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec); expect(env.reporter.log).not.toHaveBeenCalled(); block.execute(onComplete); expect(env.reporter.log).toHaveBeenCalled(); jasmine.VERBOSE = jasmineVerboseOriginal; }); }); it('onComplete should be called if the latchFunction returns true', function () { var latchFunction = function() { return true; }; var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec); expect(onComplete).not.toHaveBeenCalled(); block.execute(onComplete); expect(onComplete).toHaveBeenCalled(); }); it('latchFunction should run in same scope as spec', function () { var result; var latchFunction = function() { result = this.scopedValue; }; spec.scopedValue = 'foo'; var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec); block.execute(onComplete); expect(result).toEqual('foo'); }); it('should fail spec and call onComplete if there is an error in the latchFunction', function() { var latchFunction = jasmine.createSpy('latchFunction').andThrow('some error'); spyOn(spec, 'fail'); var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec); block.execute(onComplete); expect(spec.fail).toHaveBeenCalledWith('some error'); expect(onComplete).toHaveBeenCalled(); }); describe("if latchFunction returns false", function() { var latchFunction, fakeTimer; beforeEach(function() { latchFunction = jasmine.createSpy('latchFunction').andReturn(false); fakeTimer = new jasmine.FakeTimer(); env.setTimeout = fakeTimer.setTimeout; env.clearTimeout = fakeTimer.clearTimeout; env.setInterval = fakeTimer.setInterval; env.clearInterval = fakeTimer.clearInterval; }); it('latchFunction should be retried after 10 ms', function () { var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec); expect(latchFunction).not.toHaveBeenCalled(); block.execute(onComplete); expect(latchFunction.callCount).toEqual(1); fakeTimer.tick(5); expect(latchFunction.callCount).toEqual(1); fakeTimer.tick(5); expect(latchFunction.callCount).toEqual(2); }); it('onComplete should be called if latchFunction returns true before timeout', function () { var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec); expect(onComplete).not.toHaveBeenCalled(); block.execute(onComplete); expect(onComplete).not.toHaveBeenCalled(); latchFunction.andReturn(true); fakeTimer.tick(100); expect(onComplete).toHaveBeenCalled(); }); it('spec should fail with the passed message if the timeout is reached (and not call onComplete)', function () { spyOn(spec, 'fail'); var block = new jasmine.WaitsForBlock(env, timeout, latchFunction, message, spec); block.execute(onComplete); expect(spec.fail).not.toHaveBeenCalled(); fakeTimer.tick(timeout); expect(spec.fail).toHaveBeenCalled(); var failMessage = spec.fail.mostRecentCall.args[0].message; expect(failMessage).toMatch(message); expect(onComplete).toHaveBeenCalled(); }); }); });
"\ux";
/*! formstone v0.8.5 [cookie.js] 2015-09-10 | MIT License | formstone.it */ !function(a,b){"use strict";function c(b,c,h){if("object"===a.type(b))g=a.extend(g,b);else if(h=a.extend({},g,h||{}),"undefined"!==a.type(b)){if("undefined"===a.type(c))return e(b);null===c?f(b):d(b,c,h)}return null}function d(b,c,d){var e=!1,f=new Date;d.expires&&"number"===a.type(d.expires)&&(f.setTime(f.getTime()+d.expires),e=f.toGMTString());var g=d.domain?"; domain="+d.domain:"",i=e?"; expires="+e:"",j=e?"; max-age="+d.expires/1e3:"",k=d.path?"; path="+d.path:"",l=d.secure?"; secure":"";h.cookie=b+"="+c+i+j+g+k+l}function e(a){for(var b=a+"=",c=h.cookie.split(";"),d=0;d<c.length;d++){for(var e=c[d];" "===e.charAt(0);)e=e.substring(1,e.length);if(0===e.indexOf(b))return e.substring(b.length,e.length)}return null}function f(a){d(a,"",{expires:-6048e5})}var g=(b.Plugin("cookie",{utilities:{_delegate:c}}),{domain:null,expires:6048e5,path:null,secure:null}),h=b.document}(jQuery,Formstone);
tinyMCE.addI18n('ur.paste_dlg',{"word_title":"Use CTRL+V on your keyboard to paste the text into the window.","text_linebreaks":"Keep linebreaks","text_title":"Use CTRL+V on your keyboard to paste the text into the window."});
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Should=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ var should = require('./should'); should .use(require('./ext/assert')) .use(require('./ext/chain')) .use(require('./ext/bool')) .use(require('./ext/number')) .use(require('./ext/eql')) .use(require('./ext/type')) .use(require('./ext/string')) .use(require('./ext/property')) .use(require('./ext/error')) .use(require('./ext/match')) .use(require('./ext/browser/jquery')) .use(require('./ext/deprecated')); module.exports = should; },{"./ext/assert":3,"./ext/bool":4,"./ext/browser/jquery":5,"./ext/chain":6,"./ext/deprecated":7,"./ext/eql":8,"./ext/error":9,"./ext/match":10,"./ext/number":11,"./ext/property":12,"./ext/string":13,"./ext/type":14,"./should":15}],2:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ // Taken from node's assert module, because it sucks // and exposes next to nothing useful. var util = require('./util'); module.exports = _deepEqual; var pSlice = Array.prototype.slice; function _deepEqual(actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (util.isBuffer(actual) && util.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (!util.isObject(actual) && !util.isObject(expected)) { return actual == expected; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } } function objEquiv (a, b) { if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (util.isArguments(a)) { if (!util.isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } try{ var ka = Object.keys(a), kb = Object.keys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } },{"./util":16}],3:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ var util = require('../util') , assert = require('assert') , AssertionError = assert.AssertionError; module.exports = function(should) { var i = should.format; /** * Expose assert to should * * This allows you to do things like below * without require()ing the assert module. * * should.equal(foo.bar, undefined); * */ util.merge(should, assert); /** * Assert _obj_ exists, with optional message. * * @param {*} obj * @param {String} [msg] * @api public */ should.exist = should.exists = function(obj, msg) { if(null == obj) { throw new AssertionError({ message: msg || ('expected ' + i(obj) + ' to exist'), stackStartFunction: should.exist }); } }; /** * Asserts _obj_ does not exist, with optional message. * * @param {*} obj * @param {String} [msg] * @api public */ should.not = {}; should.not.exist = should.not.exists = function(obj, msg) { if(null != obj) { throw new AssertionError({ message: msg || ('expected ' + i(obj) + ' to not exist'), stackStartFunction: should.not.exist }); } }; }; },{"../util":16,"assert":17}],4:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ module.exports = function(should, Assertion) { Assertion.add('true', function() { this.is.exactly(true); }, true); Assertion.alias('true', 'True'); Assertion.add('false', function() { this.is.exactly(false); }, true); Assertion.alias('false', 'False'); Assertion.add('ok', function() { this.params = { operator: 'to be truthy' }; this.assert(this.obj); }, true); }; },{}],5:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /*! * Portions copyright (c) 2010, 2011, 2012 Wojciech Zawistowski, Travis Jeffery * From the jasmine-jquery project under the MIT License. */ var util = require('../../util'); module.exports = function(should, Assertion) { var i = should.format; var $ = this.jQuery || this.$; /* Otherwise, node's util.inspect loops hangs */ if (typeof HTMLElement !== "undefined" && HTMLElement && !HTMLElement.prototype.inspect) { HTMLElement.prototype.inspect = function () { return this.outerHTML; }; } if (typeof jQuery !== "undefined" && jQuery && !jQuery.prototype.inspect) { jQuery.fn.inspect = function () { var elementList = this.toArray().map(function (e) { return util.inspect(e); }).join(", "); if (this.selector) { return "SELECTOR(" + this.selector + ") matching " + this.length + " elements" + (elementList.length ? ": " + elementList : ""); } else { return elementList; } }; } function jQueryAttributeTestHelper(method, singular, plural, nameOrHash, value) { var keys = util.isObject(nameOrHash) ? Object.keys(nameOrHash) : [nameOrHash]; var allRelevantAttributes = keys.reduce(function (memo, key) { var value = $(this.obj)[method](key); if (typeof value !== 'undefined') { memo[key] = value; } return memo; }.bind(this), {}); if (arguments.length === 4 && util.isObject(nameOrHash)) { this.params = { operator: 'to have ' + plural + ' ' + i(nameOrHash) }; allRelevantAttributes.should.have.properties(nameOrHash); } else if (arguments.length === 4) { this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) }; allRelevantAttributes.should.have.property(nameOrHash); } else { this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) + ' with value ' + i(value) }; allRelevantAttributes.should.have.property(nameOrHash, value); } } var browserTagCaseIndependentHtml = function (html) { return $('<div/>').append(html).html(); }; var addJqPredicateAssertion = function (predicate, nameOverride, operatorOverride) { Assertion.add(nameOverride || predicate, function() { this.params = { operator: 'to be ' + (operatorOverride || predicate) }; this.assert($(this.obj).is(':' + predicate)); }, true); } Assertion.add('className', function(className) { this.params = { operator: 'to have class ' + className }; this.assert($(this.obj).hasClass(className)); }); Assertion.add('css', function(css) { this.params = { operator: 'to have css ' + i(css) }; for (var prop in css) { var value = css[prop]; if (value === 'auto' && $(this.obj).get(0).style[prop] === 'auto') { continue; } $(this.obj).css(prop).should.eql(value); } }); addJqPredicateAssertion('visible'); addJqPredicateAssertion('hidden'); addJqPredicateAssertion('selected'); addJqPredicateAssertion('checked'); addJqPredicateAssertion('disabled'); addJqPredicateAssertion('empty', 'emptyJq'); addJqPredicateAssertion('focus', 'focused', 'focused'); Assertion.add('inDOM', function() { this.params = { operator: 'to be in the DOM' }; this.assert($.contains(document.documentElement, $(this.obj)[0])); }, true); Assertion.add('exist', function() { this.params = { operator: 'to exist' }; $(this.obj).should.not.have.length(0); }, true); Assertion.add('attr', function() { var args = [ 'attr', 'attribute', 'attributes' ].concat(Array.prototype.slice.call(arguments, 0)); jQueryAttributeTestHelper.apply(this, args); }); Assertion.add('prop', function() { var args = [ 'prop', 'property', 'properties' ].concat(Array.prototype.slice.call(arguments, 0)); jQueryAttributeTestHelper.apply(this, args); }); Assertion.add('elementId', function(id) { this.params = { operator: 'to have ID ' + i(id) }; this.obj.should.have.attr('id', id); }); Assertion.add('html', function(html) { this.params = { operator: 'to have HTML ' + i(html) }; $(this.obj).html().should.eql(browserTagCaseIndependentHtml(html)); }); Assertion.add('containHtml', function(html) { this.params = { operator: 'to contain HTML ' + i(html) }; $(this.obj).html().indexOf(browserTagCaseIndependentHtml(html)).should.be.above(-1); }); Assertion.add('text', function(text) { this.params = { operator: 'to have text ' + i(text) }; var trimmedText = $.trim($(this.obj).text()); if (util.isRegExp(text)) { trimmedText.should.match(text); } else { trimmedText.should.eql(text); } }); Assertion.add('containText', function(text) { this.params = { operator: 'to contain text ' + i(text) }; var trimmedText = $.trim($(this.obj).text()); if (util.isRegExp(text)) { trimmedText.should.match(text); } else { trimmedText.indexOf(text).should.be.above(-1); } }); Assertion.add('value', function(val) { this.params = { operator: 'to have value ' + i(val) }; $(this.obj).val().should.eql(val); }); Assertion.add('data', function() { var args = [ 'data', 'data', 'data' ].concat(Array.prototype.slice.call(arguments, 0)); jQueryAttributeTestHelper.apply(this, args); }); Assertion.add('containElement', function(target) { this.params = { operator: 'to contain ' + $(target).inspect() }; $(this.obj).find(target).should.not.have.length(0); }); Assertion.add('matchedBy', function(selector) { this.params = { operator: 'to be matched by selector ' + selector }; $(this.obj).filter(selector).should.not.have.length(0); }); Assertion.add('handle', function(event) { this.params = { operator: 'to handle ' + event }; var events = $._data($(this.obj).get(0), "events"); if (!events || !event || typeof event !== "string") { return this.assert(false); } var namespaces = event.split("."), eventType = namespaces.shift(), sortedNamespaces = namespaces.slice(0).sort(), namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); if (events[eventType] && namespaces.length) { for (var i = 0; i < events[eventType].length; i++) { var namespace = events[eventType][i].namespace; if (namespaceRegExp.test(namespace)) { return; } } } else { events.should.have.property(eventType); events[eventType].should.not.have.length(0); return; } this.assert(false); }); Assertion.add('handleWith', function(eventName, eventHandler) { this.params = { operator: 'to handle ' + eventName + ' with ' + eventHandler }; var normalizedEventName = eventName.split('.')[0], stack = $._data($(this.obj).get(0), "events")[normalizedEventName]; for (var i = 0; i < stack.length; i++) { if (stack[i].handler == eventHandler) { return; } } this.assert(false); }); }; },{"../../util":16}],6:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ module.exports = function(should, Assertion) { function addLink(name) { Object.defineProperty(Assertion.prototype, name, { get: function() { return this; } }); } ['an', 'of', 'a', 'and', 'be', 'have', 'with', 'is', 'which', 'the'].forEach(addLink); }; },{}],7:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ var util = require('../util'), eql = require('../eql'); module.exports = function(should, Assertion) { var i = should.format; Assertion.add('include', function(obj, description) { if(!Array.isArray(this.obj) && !util.isString(this.obj)) { this.params = { operator: 'to include an object equal to ' + i(obj), message: description }; var cmp = {}; for(var key in obj) cmp[key] = this.obj[key]; this.assert(eql(cmp, obj)); } else { this.params = { operator: 'to include ' + i(obj), message: description }; this.assert(~this.obj.indexOf(obj)); } }); Assertion.add('includeEql', function(obj, description) { this.params = { operator: 'to include an object equal to ' + i(obj), message: description }; this.assert(this.obj.some(function(item) { return eql(obj, item); })); }); }; },{"../eql":2,"../util":16}],8:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ var eql = require('../eql'); module.exports = function(should, Assertion) { Assertion.add('eql', function(val, description) { this.params = { operator: 'to equal', expected: val, showDiff: true, message: description }; this.assert(eql(val, this.obj)); }); Assertion.add('equal', function(val, description) { this.params = { operator: 'to be', expected: val, showDiff: true, message: description }; this.assert(val === this.obj); }); Assertion.alias('equal', 'exactly'); }; },{"../eql":2}],9:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ module.exports = function(should, Assertion) { var i = should.format; Assertion.add('throw', function(message) { var fn = this.obj , err = {} , errorInfo = '' , ok = true; try { fn(); ok = false; } catch(e) { err = e; } if(ok) { if('string' == typeof message) { ok = message == err.message; } else if(message instanceof RegExp) { ok = message.test(err.message); } else if('function' == typeof message) { ok = err instanceof message; } if(message && !ok) { if('string' == typeof message) { errorInfo = " with a message matching '" + message + "', but got '" + err.message + "'"; } else if(message instanceof RegExp) { errorInfo = " with a message matching " + message + ", but got '" + err.message + "'"; } else if('function' == typeof message) { errorInfo = " of type " + message.name + ", but got " + err.constructor.name; } } else { errorInfo = " (got " + i(err) + ")"; } } this.params = { operator: 'to throw exception' + errorInfo }; this.assert(ok); }); Assertion.alias('throw', 'throwError'); }; },{}],10:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ var util = require('../util'), eql = require('../eql'); module.exports = function(should, Assertion) { var i = should.format; Assertion.add('match', function(other, description) { this.params = { operator: 'to match ' + i(other), message: description }; if(!eql(this.obj, other)) { if(util.isRegExp(other)) { // something - regex if(util.isString(this.obj)) { this.assert(other.exec(this.obj)); } else if(Array.isArray(this.obj)) { this.obj.forEach(function(item) { this.assert(other.exec(item));// should we try to convert to String and exec? }, this); } else if(util.isObject(this.obj)) { var notMatchedProps = [], matchedProps = []; util.forOwn(this.obj, function(value, name) { if(other.exec(value)) matchedProps.push(i(name)); else notMatchedProps.push(i(name)); }, this); if(notMatchedProps.length) this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', '); if(matchedProps.length) this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', '); this.assert(notMatchedProps.length == 0); } // should we try to convert to String and exec? } else if(util.isFunction(other)) { var res; try { res = other(this.obj); } catch(e) { if(e instanceof should.AssertionError) { this.params.operator += '\n\t' + e.message; } throw e; } if(res instanceof Assertion) { this.params.operator += '\n\t' + res.getMessage(); } //if we throw exception ok - it is used .should inside if(util.isBoolean(res)) { this.assert(res); // if it is just boolean function assert on it } } else if(util.isObject(other)) { // try to match properties (for Object and Array) notMatchedProps = []; matchedProps = []; util.forOwn(other, function(value, key) { try { this.obj[key].should.match(value); matchedProps.push(key); } catch(e) { if(e instanceof should.AssertionError) { notMatchedProps.push(key); } else { throw e; } } }, this); if(notMatchedProps.length) this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', '); if(matchedProps.length) this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', '); this.assert(notMatchedProps.length == 0); } else { this.assert(false); } } }); Assertion.add('matchEach', function(other, description) { this.params = { operator: 'to match each ' + i(other), message: description }; var f = other; if(util.isRegExp(other)) f = function(it) { return !!other.exec(it); }; else if(!util.isFunction(other)) f = function(it) { return eql(it, other); }; util.forOwn(this.obj, function(value, key) { var res = f(value, key); //if we throw exception ok - it is used .should inside if(util.isBoolean(res)) { this.assert(res); // if it is just boolean function assert on it } }, this); }); }; },{"../eql":2,"../util":16}],11:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ module.exports = function(should, Assertion) { Assertion.add('NaN', function() { this.params = { operator: 'to be NaN' }; this.assert(this.obj !== this.obj); }, true); Assertion.add('Infinity', function() { this.params = { operator: 'to be Infinity' }; this.is.a.Number .and.not.a.NaN .and.assert(!isFinite(this.obj)); }, true); Assertion.add('within', function(start, finish, description) { this.params = { operator: 'to be within ' + start + '..' + finish, message: description }; this.assert(this.obj >= start && this.obj <= finish); }); Assertion.add('approximately', function(value, delta, description) { this.params = { operator: 'to be approximately ' + value + " ±" + delta, message: description }; this.assert(Math.abs(this.obj - value) <= delta); }); Assertion.add('above', function(n, description) { this.params = { operator: 'to be above ' + n, message: description }; this.assert(this.obj > n); }); Assertion.add('below', function(n, description) { this.params = { operator: 'to be below ' + n, message: description }; this.assert(this.obj < n); }); Assertion.alias('above', 'greaterThan'); Assertion.alias('below', 'lessThan'); }; },{}],12:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ var util = require('../util'), eql = require('../eql'); var aSlice = Array.prototype.slice; module.exports = function(should, Assertion) { var i = should.format; Assertion.add('enumerable', function(name, val) { this.params = { operator:"to have enumerable property '"+name+"'" }; this.assert(this.obj.propertyIsEnumerable(name)); if(arguments.length > 1){ this.params.operator += " equal to '"+val+"'"; this.assert(eql(val, this.obj[name])); } }); Assertion.add('property', function(name, val) { if(arguments.length > 1) { var p = {}; p[name] = val; this.have.properties(p); } else { this.have.properties(name); } this.obj = this.obj[name]; }); Assertion.add('properties', function(names) { var values = {}; if(arguments.length > 1) { names = aSlice.call(arguments); } else if(!Array.isArray(names)) { if(util.isString(names)) { names = [names]; } else { values = names; names = Object.keys(names); } } var obj = Object(this.obj), missingProperties = []; //just enumerate properties and check if they all present names.forEach(function(name) { if(!(name in obj)) missingProperties.push(i(name)); }); var props = missingProperties; if(props.length === 0) { props = names.map(i); } else if(this.one) { props = names.filter(function(name) { return missingProperties.indexOf(i(name)) < 0; }).map(i); } var operator = (props.length === 1 ? 'to have property ' : 'to have '+(this.one? 'any of ' : '')+'properties ') + props.join(', '); this.params = { operator: operator }; //check that all properties presented //or if we request one of them that at least one them presented this.assert(missingProperties.length === 0 || (this.one && missingProperties.length != names.length)); // check if values in object matched expected var valueCheckNames = Object.keys(values); if(valueCheckNames.length) { var wrongValues = []; props = []; // now check values, as there we have all properties valueCheckNames.forEach(function(name) { var value = values[name]; if(!eql(obj[name], value)) { wrongValues.push(i(name) + ' of ' + i(value) + ' (got ' + i(obj[name]) + ')'); } else { props.push(i(name) + ' of ' + i(value)); } }); if((wrongValues.length !== 0 && !this.one) || (this.one && props.length === 0)) { props = wrongValues; } operator = (props.length === 1 ? 'to have property ' : 'to have '+(this.one? 'any of ' : '')+'properties ') + props.join(', '); this.params = { operator: operator }; //if there is no not matched values //or there is at least one matched this.assert(wrongValues.length === 0 || (this.one && wrongValues.length != valueCheckNames.length)); } }); Assertion.add('length', function(n, description) { this.have.property('length', n, description); }); Assertion.alias('length', 'lengthOf'); var hasOwnProperty = Object.prototype.hasOwnProperty; Assertion.add('ownProperty', function(name, description) { this.params = { operator: 'to have own property ' + i(name), message: description }; this.assert(hasOwnProperty.call(this.obj, name)); this.obj = this.obj[name]; }); Assertion.alias('ownProperty', 'hasOwnProperty'); Assertion.add('empty', function() { this.params = { operator: 'to be empty' }; if(util.isString(this.obj) || Array.isArray(this.obj) || util.isArguments(this.obj)) { this.have.property('length', 0); } else { var obj = Object(this.obj); // wrap to reference for booleans and numbers for(var prop in obj) { this.have.not.ownProperty(prop); } } }, true); Assertion.add('keys', function(keys) { if(arguments.length > 1) keys = aSlice.call(arguments); else if(arguments.length === 1 && util.isString(keys)) keys = [ keys ]; else if(arguments.length === 0) keys = []; var obj = Object(this.obj); // first check if some keys are missing var missingKeys = []; keys.forEach(function(key) { if(!hasOwnProperty.call(this.obj, key)) missingKeys.push(i(key)); }, this); // second check for extra keys var extraKeys = []; Object.keys(obj).forEach(function(key) { if(keys.indexOf(key) < 0) { extraKeys.push(i(key)); } }); var verb = keys.length === 0 ? 'to be empty' : 'to have ' + (keys.length === 1 ? 'key ' : 'keys '); this.params = { operator: verb + keys.map(i).join(', ')}; if(missingKeys.length > 0) this.params.operator += '\n\tmissing keys: ' + missingKeys.join(', '); if(extraKeys.length > 0) this.params.operator += '\n\textra keys: ' + extraKeys.join(', '); this.assert(missingKeys.length === 0 && extraKeys.length === 0); }); Assertion.alias("keys", "key"); Assertion.add('containEql', function(other) { this.params = { operator: 'to contain ' + i(other) }; var obj = this.obj; if(Array.isArray(obj)) { this.assert(obj.some(function(item) { return eql(item, other); })); } else if(util.isString(obj)) { // expect obj to be string this.assert(obj.indexOf(String(other)) >= 0); } else if(util.isObject(obj)) { // object contains object case util.forOwn(other, function(value, key) { obj.should.have.property(key, value); }); } else { //other uncovered cases this.assert(false); } }); Assertion.add('containDeep', function(other) { this.params = { operator: 'to contain ' + i(other) }; var obj = this.obj; if(Array.isArray(obj)) { if(Array.isArray(other)) { var otherIdx = 0; obj.forEach(function(item) { try { should(item).not.be.Null.and.containDeep(other[otherIdx]); otherIdx++; } catch(e) { if(e instanceof should.AssertionError) { return; } throw e; } }); this.assert(otherIdx == other.length); //search array contain other as sub sequence } else { this.assert(false); } } else if(util.isString(obj)) {// expect other to be string this.assert(obj.indexOf(String(other)) >= 0); } else if(util.isObject(obj)) {// object contains object case if(util.isObject(other)) { util.forOwn(other, function(value, key) { should(obj[key]).not.be.Null.and.containDeep(value); }); } else {//one of the properties contain value this.assert(false); } } else { this.eql(other); } }); }; },{"../eql":2,"../util":16}],13:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ module.exports = function(should, Assertion) { Assertion.add('startWith', function(str, description) { this.params = { operator: 'to start with ' + should.format(str), message: description }; this.assert(0 === this.obj.indexOf(str)); }); Assertion.add('endWith', function(str, description) { this.params = { operator: 'to end with ' + should.format(str), message: description }; this.assert(this.obj.indexOf(str, this.obj.length - str.length) >= 0); }); }; },{}],14:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ var util = require('../util'); module.exports = function(should, Assertion) { Assertion.add('Number', function() { this.params = { operator: 'to be a number' }; this.assert(util.isNumber(this.obj)); }, true); Assertion.add('arguments', function() { this.params = { operator: 'to be arguments' }; this.assert(util.isArguments(this.obj)); }, true); Assertion.add('type', function(type, description) { this.params = { operator: 'to have type ' + type, message: description }; (typeof this.obj).should.be.exactly(type, description); }); Assertion.add('instanceof', function(constructor, description) { this.params = { operator: 'to be an instance of ' + constructor.name, message: description }; this.assert(Object(this.obj) instanceof constructor); }); Assertion.add('Function', function() { this.params = { operator: 'to be a function' }; this.assert(util.isFunction(this.obj)); }, true); Assertion.add('Object', function() { this.params = { operator: 'to be an object' }; this.assert(util.isObject(this.obj)); }, true); Assertion.add('String', function() { this.params = { operator: 'to be a string' }; this.assert(util.isString(this.obj)); }, true); Assertion.add('Array', function() { this.params = { operator: 'to be an array' }; this.assert(Array.isArray(this.obj)); }, true); Assertion.add('Boolean', function() { this.params = { operator: 'to be a boolean' }; this.assert(util.isBoolean(this.obj)); }, true); Assertion.add('Error', function() { this.params = { operator: 'to be an error' }; this.assert(util.isError(this.obj)); }, true); Assertion.add('null', function() { this.params = { operator: 'to be null' }; this.assert(this.obj === null); }, true); Assertion.alias('null', 'Null'); Assertion.alias('instanceof', 'instanceOf'); }; },{"../util":16}],15:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ var util = require('./util') , AssertionError = util.AssertionError , inspect = util.inspect; /** * Our function should * @param obj * @returns {Assertion} */ var should = function(obj) { return new Assertion(util.isWrapperType(obj) ? obj.valueOf(): obj); }; /** * Initialize a new `Assertion` with the given _obj_. * * @param {*} obj * @api private */ var Assertion = should.Assertion = function Assertion(obj) { this.obj = obj; }; /** Way to extend Assertion function. It uses some logic to define only positive assertions and itself rule with negative assertion. All actions happen in subcontext and this method take care about negation. Potentially we can add some more modifiers that does not depends from state of assertion. */ Assertion.add = function(name, f, isGetter) { var prop = {}; prop[isGetter ? 'get' : 'value'] = function() { var context = new Assertion(this.obj); context.copy = context.copyIfMissing; context.one = this.one; try { f.apply(context, arguments); } catch(e) { //copy data from sub context to this this.copy(context); //check for fail if(e instanceof should.AssertionError) { //negative fail if(this.negate) { this.obj = context.obj; this.negate = false; return this; } this.assert(false); } // throw if it is another exception throw e; } //copy data from sub context to this this.copy(context); if(this.negate) { this.assert(false); } this.obj = context.obj; this.negate = false; return this; }; Object.defineProperty(Assertion.prototype, name, prop); }; Assertion.alias = function(from, to) { var desc = Object.getOwnPropertyDescriptor(Assertion.prototype, from); if(!desc) throw new Error('Alias ' + from + ' -> ' + to + ' could not be created as ' + from + ' not defined'); Object.defineProperty(Assertion.prototype, to, desc); }; should.AssertionError = AssertionError; should.format = function (value) { if(util.isDate(value) && typeof value.inspect !== 'function') return value.toISOString(); //show millis in dates return inspect(value, { depth: null }); }; should.use = function(f) { f(this, Assertion); return this; }; /** * Expose should to external world. */ exports = module.exports = should; /** * Expose api via `Object#should`. * * @api public */ Object.defineProperty(Object.prototype, 'should', { set: function(){}, get: function(){ return should(this); }, configurable: true }); Assertion.prototype = { constructor: Assertion, assert: function(expr) { if(expr) return; var params = this.params; var msg = params.message, generatedMessage = false; if(!msg) { msg = this.getMessage(); generatedMessage = true; } var err = new AssertionError({ message: msg , actual: this.obj , expected: params.expected , stackStartFunction: this.assert }); err.showDiff = params.showDiff; err.operator = params.operator; err.generatedMessage = generatedMessage; throw err; }, getMessage: function() { return 'expected ' + ('obj' in this.params ? this.params.obj: should.format(this.obj)) + (this.negate ? ' not ': ' ') + this.params.operator + ('expected' in this.params ? ' ' + should.format(this.params.expected) : ''); }, copy: function(other) { this.params = other.params; }, copyIfMissing: function(other) { if(!this.params) this.params = other.params; }, /** * Negation modifier. * * @api public */ get not() { this.negate = !this.negate; return this; }, /** * Any modifier - it affect on execution of sequenced assertion to do not check all, but any of * * @api public */ get any() { this.one = true; return this; } }; },{"./util":16}],16:[function(require,module,exports){ /*! * Should * Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Check if given obj just a primitive type wrapper * @param {Object} obj * @returns {boolean} * @api private */ exports.isWrapperType = function(obj) { return isNumber(obj) || isString(obj) || isBoolean(obj); }; /** * Merge object b with object a. * * var a = { foo: 'bar' } * , b = { bar: 'baz' }; * * utils.merge(a, b); * // => { foo: 'bar', bar: 'baz' } * * @param {Object} a * @param {Object} b * @return {Object} * @api private */ exports.merge = function(a, b){ if (a && b) { for (var key in b) { a[key] = b[key]; } } return a; }; function isNumber(arg) { return typeof arg === 'number' || arg instanceof Number; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string' || arg instanceof String; } function isBoolean(arg) { return typeof arg === 'boolean' || arg instanceof Boolean; } exports.isBoolean = isBoolean; exports.isString = isString; function isBuffer(arg) { return typeof Buffer !== 'undefined' && arg instanceof Buffer; } exports.isBuffer = isBuffer; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function objectToString(o) { return Object.prototype.toString.call(o); } function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isArguments(object) { return objectToString(object) === '[object Arguments]'; } exports.isArguments = isArguments; exports.isFunction = function(arg) { return typeof arg === 'function' || arg instanceof Function; }; function isError(e) { return (isObject(e) && objectToString(e) === '[object Error]') || (e instanceof Error); } exports.isError = isError; exports.inspect = require('util').inspect; exports.AssertionError = require('assert').AssertionError; var hasOwnProperty = Object.prototype.hasOwnProperty; exports.forOwn = function(obj, f, context) { for(var prop in obj) { if(hasOwnProperty.call(obj, prop)) { f.call(context, obj[prop], prop); } } }; },{"assert":17,"util":20}],17:[function(require,module,exports){ // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // when used in node, this will actually load the util module we depend on // versus loading the builtin util module as happens otherwise // this is a bug in node module loading as far as I am concerned var util = require('util/'); var pSlice = Array.prototype.slice; var hasOwn = Object.prototype.hasOwnProperty; // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // non v8 browsers so we can have a stacktrace var err = new Error(); if (err.stack) { var out = err.stack; // try to strip useless frames var fn_name = stackStartFunction.name; var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { // once we have located the function frame // we need to strip out everything before it (and its line) var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (util.isUndefined(value)) { return '' + value; } if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { return value.toString(); } if (util.isFunction(value) || util.isRegExp(value)) { return value.toString(); } return value; } function truncate(s, n) { if (util.isString(s)) { return s.length < n ? s : s.slice(0, n); } else { return s; } } function getMessage(self) { return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + self.operator + ' ' + truncate(JSON.stringify(self.expected, replacer), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; function _deepEqual(actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (util.isBuffer(actual) && util.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (!util.isObject(actual) && !util.isObject(expected)) { return actual == expected; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } try { var ka = objectKeys(a), kb = objectKeys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } else if (actual instanceof expected) { return true; } else if (expected.call({}, actual) === true) { return true; } return false; } function _throws(shouldThrow, block, expected, message) { var actual; if (util.isString(expected)) { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } if (!shouldThrow && expectedException(actual, expected)) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; assert.ifError = function(err) { if (err) {throw err;}}; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; },{"util/":20}],18:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],19:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],20:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } },{"./support/isBuffer":19,"inherits":18}]},{},[1]) (1) });
module.exports = 2;
function weekSelectPlugin(pluginConfig) { return function (fp) { var days = void 0; function onDayHover(event) { if (!event.target.classList.contains("flatpickr-day")) return; dayIndex = Array.prototype.indexOf.call(days, event.target); fp.weekStartDay = days[7 * Math.floor(dayIndex / 7)].dateObj; fp.weekEndDay = days[7 * Math.ceil(dayIndex / 7) - 1].dateObj; for (var i = days.length; i--;) { var date = days[i].dateObj; if (date > fp.weekEndDay || date < fp.weekStartDay) days[i].classList.remove("inRange");else days[i].classList.add("inRange"); } } function highlightWeek() { for (var i = days.length; i--;) { var date = days[i].dateObj; if (date >= fp.weekStartDay && date <= fp.weekEndDay) days[i].classList.add("week", "selected"); } } function clearHover() { for (var i = days.length; i--;) { days[i].classList.remove("inRange"); } } function formatDate(format, date) { return "Week #" + fp.config.getWeek(date) + ", " + date.getFullYear(); } return { formatDate: formatDate, onChange: highlightWeek, onMonthChange: highlightWeek, onClose: clearHover, onParseConfig: function onParseConfig() { fp.config.mode = "single"; fp.config.enableTime = false; }, onReady: [function () { days = fp.days.childNodes; }, function () { return fp.days.addEventListener("mouseover", onDayHover); }, highlightWeek] }; }; } if (typeof module !== "undefined") module.exports = weekSelectPlugin;
YUI.add('model-list', function(Y) { /** Provides an API for managing an ordered list of Model instances. @submodule model-list @since 3.4.0 **/ /** Provides an API for managing an ordered list of Model instances. In addition to providing convenient `add`, `create`, `reset`, and `remove` methods for managing the models in the list, ModelLists are also bubble targets for events on the model instances they contain. This means, for example, that you can add several models to a list, and then subscribe to the `*:change` event on the list to be notified whenever any model in the list changes. ModelLists also maintain sort order efficiently as models are added and removed, based on a custom `comparator` function you may define (if no comparator is defined, models are sorted in insertion order). @class ModelList @extends Base @uses ArrayList @constructor @since 3.4.0 **/ var AttrProto = Y.Attribute.prototype, Lang = Y.Lang, YArray = Y.Array, /** Fired when a model is added to the list. Listen to the `on` phase of this event to be notified before a model is added to the list. Calling `e.preventDefault()` during the `on` phase will prevent the model from being added. Listen to the `after` phase of this event to be notified after a model has been added to the list. @event add @param {Model} model The model being added. @param {Number} index The index at which the model will be added. @preventable _defAddFn **/ EVT_ADD = 'add', /** Fired when an error occurs, such as when an attempt is made to add a duplicate model to the list, or when a sync layer response can't be parsed. @event error @param {Any} error Error message, object, or exception generated by the error. Calling `toString()` on this should result in a meaningful error message. @param {String} src Source of the error. May be one of the following (or any custom error source defined by a ModelList subclass): * `add`: Error while adding a model (probably because it's already in the list and can't be added again). The model in question will be provided as the `model` property on the event facade. * `parse`: An error parsing a JSON response. The response in question will be provided as the `response` property on the event facade. * `remove`: Error while removing a model (probably because it isn't in the list and can't be removed). The model in question will be provided as the `model` property on the event facade. **/ EVT_ERROR = 'error'; /** Fired when the list is completely reset via the `reset()` method or sorted via the `sort()` method. Listen to the `on` phase of this event to be notified before the list is reset. Calling `e.preventDefault()` during the `on` phase will prevent the list from being reset. Listen to the `after` phase of this event to be notified after the list has been reset. @event reset @param {Model[]} models Array of the list's new models after the reset. @param {String} src Source of the event. May be either `'reset'` or `'sort'`. @preventable _defResetFn **/ EVT_RESET = 'reset', /** Fired when a model is removed from the list. Listen to the `on` phase of this event to be notified before a model is removed from the list. Calling `e.preventDefault()` during the `on` phase will prevent the model from being removed. Listen to the `after` phase of this event to be notified after a model has been removed from the list. @event remove @param {Model} model The model being removed. @param {int} index The index of the model being removed. @preventable _defRemoveFn **/ EVT_REMOVE = 'remove'; function ModelList() { ModelList.superclass.constructor.apply(this, arguments); } Y.ModelList = Y.extend(ModelList, Y.Base, { // -- Public Properties ---------------------------------------------------- /** The `Model` class or subclass of the models in this list. This property is `null` by default, and is intended to be overridden in a subclass or specified as a config property at instantiation time. It will be used to create model instances automatically based on attribute hashes passed to the `add()`, `create()`, and `reset()` methods. @property model @type Model @default `null` **/ model: null, // -- Lifecycle Methods ---------------------------------------------------- initializer: function (config) { config || (config = {}); var model = this.model = config.model || this.model; this.publish(EVT_ADD, {defaultFn: this._defAddFn}); this.publish(EVT_RESET, {defaultFn: this._defResetFn}); this.publish(EVT_REMOVE, {defaultFn: this._defRemoveFn}); if (model) { this.after('*:idChange', this._afterIdChange); } else { Y.log('No model class specified.', 'warn', 'model-list'); } this._clear(); }, destructor: function () { YArray.each(this._items, this._detachList, this); }, // -- Public Methods ------------------------------------------------------- /** Adds the specified model or array of models to this list. @example // Add a single model instance. list.add(new Model({foo: 'bar'})); // Add a single model, creating a new instance automatically. list.add({foo: 'bar'}); // Add multiple models, creating new instances automatically. list.add([ {foo: 'bar'}, {baz: 'quux'} ]); @method add @param {Model|Model[]|Object|Object[]} models Models to add. May be existing model instances or hashes of model attributes, in which case new model instances will be created from the hashes. @param {Object} [options] Data to be mixed into the event facade of the `add` event(s) for the added models. @param {Boolean} [options.silent=false] If `true`, no `add` event(s) will be fired. @return {Model|Model[]} Added model or array of added models. **/ add: function (models, options) { if (Lang.isArray(models)) { return YArray.map(models, function (model) { return this._add(model, options); }, this); } else { return this._add(models, options); } }, /** Define this method to provide a function that takes a model as a parameter and returns a value by which that model should be sorted relative to other models in this list. By default, no comparator is defined, meaning that models will not be sorted (they'll be stored in the order they're added). @example var list = new Y.ModelList({model: Y.Model}); list.comparator = function (model) { return model.get('id'); // Sort models by id. }; @method comparator @param {Model} model Model being sorted. @return {Number|String} Value by which the model should be sorted relative to other models in this list. **/ // comparator is not defined by default /** Creates or updates the specified model on the server, then adds it to this list if the server indicates success. @method create @param {Model|Object} model Model to create. May be an existing model instance or a hash of model attributes, in which case a new model instance will be created from the hash. @param {Object} [options] Options to be passed to the model's `sync()` and `set()` methods and mixed into the `add` event when the model is added to the list. @param {Boolean} [options.silent=false] If `true`, no `add` event(s) will be fired. @param {callback} [callback] Called when the sync operation finishes. @param {Error} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be falsy. @param {mixed} callback.response The server's response. @return {Model} Created model. **/ create: function (model, options, callback) { var self = this; // Allow callback as second arg. if (typeof options === 'function') { callback = options; options = {}; } if (!(model instanceof Y.Model)) { model = new this.model(model); } return model.save(options, function (err) { if (!err) { self.add(model, options); } callback && callback.apply(null, arguments); }); }, /** If _name_ refers to an attribute on this ModelList instance, returns the value of that attribute. Otherwise, returns an array containing the values of the specified attribute from each model in this list. @method get @param {String} name Attribute name or object property path. @return {Any|Array} Attribute value or array of attribute values. @see Model.get() **/ get: function (name) { if (this.attrAdded(name)) { return AttrProto.get.apply(this, arguments); } return this.invoke('get', name); }, /** If _name_ refers to an attribute on this ModelList instance, returns the HTML-escaped value of that attribute. Otherwise, returns an array containing the HTML-escaped values of the specified attribute from each model in this list. The values are escaped using `Escape.html()`. @method getAsHTML @param {String} name Attribute name or object property path. @return {String|String[]} HTML-escaped value or array of HTML-escaped values. @see Model.getAsHTML() **/ getAsHTML: function (name) { if (this.attrAdded(name)) { return Y.Escape.html(AttrProto.get.apply(this, arguments)); } return this.invoke('getAsHTML', name); }, /** If _name_ refers to an attribute on this ModelList instance, returns the URL-encoded value of that attribute. Otherwise, returns an array containing the URL-encoded values of the specified attribute from each model in this list. The values are encoded using the native `encodeURIComponent()` function. @method getAsURL @param {String} name Attribute name or object property path. @return {String|String[]} URL-encoded value or array of URL-encoded values. @see Model.getAsURL() **/ getAsURL: function (name) { if (this.attrAdded(name)) { return encodeURIComponent(AttrProto.get.apply(this, arguments)); } return this.invoke('getAsURL', name); }, /** Returns the model with the specified _clientId_, or `null` if not found. @method getByClientId @param {String} clientId Client id. @return {Model} Model, or `null` if not found. **/ getByClientId: function (clientId) { return this._clientIdMap[clientId] || null; }, /** Returns the model with the specified _id_, or `null` if not found. Note that models aren't expected to have an id until they're saved, so if you're working with unsaved models, it may be safer to call `getByClientId()`. @method getById @param {String} id Model id. @return {Model} Model, or `null` if not found. **/ getById: function (id) { return this._idMap[id] || null; }, /** Calls the named method on every model in the list. Any arguments provided after _name_ will be passed on to the invoked method. @method invoke @param {String} name Name of the method to call on each model. @param {Any} [args*] Zero or more arguments to pass to the invoked method. @return {Array} Array of return values, indexed according to the index of the model on which the method was called. **/ invoke: function (name /*, args* */) { var args = [this._items, name].concat(YArray(arguments, 1, true)); return YArray.invoke.apply(YArray, args); }, /** Returns the model at the specified _index_. @method item @param {int} index Index of the model to fetch. @return {Model} The model at the specified index, or `undefined` if there isn't a model there. **/ // item() is inherited from ArrayList. /** Loads this list of models from the server. This method delegates to the `sync()` method to perform the actual load operation, which is an asynchronous action. Specify a _callback_ function to be notified of success or failure. If the load operation succeeds, a `reset` event will be fired. @method load @param {Object} [options] Options to be passed to `sync()` and to `reset()` when adding the loaded models. It's up to the custom sync implementation to determine what options it supports or requires, if any. @param {callback} [callback] Called when the sync operation finishes. @param {Error} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be falsy. @param {mixed} callback.response The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an array of model attribute hashes. @chainable **/ load: function (options, callback) { var self = this; // Allow callback as only arg. if (typeof options === 'function') { callback = options; options = {}; } this.sync('read', options, function (err, response) { if (!err) { self.reset(self.parse(response), options); } callback && callback.apply(null, arguments); }); return this; }, /** Executes the specified function on each model in this list and returns an array of the function's collected return values. @method map @param {Function} fn Function to execute on each model. @param {Model} fn.model Current model being iterated. @param {int} fn.index Index of the current model in the list. @param {Model[]} fn.models Array of models being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Array} Array of return values from _fn_. **/ map: function (fn, thisObj) { return YArray.map(this._items, fn, thisObj); }, /** Called to parse the _response_ when the list is loaded from the server. This method receives a server _response_ and is expected to return an array of model attribute hashes. The default implementation assumes that _response_ is either an array of attribute hashes or a JSON string that can be parsed into an array of attribute hashes. If _response_ is a JSON string and either `Y.JSON` or the native `JSON` object are available, it will be parsed automatically. If a parse error occurs, an `error` event will be fired and the model will not be updated. You may override this method to implement custom parsing logic if necessary. @method parse @param {mixed} response Server response. @return {Object[]} Array of model attribute hashes. **/ parse: function (response) { if (typeof response === 'string') { try { return Y.JSON.parse(response) || []; } catch (ex) { this.fire(EVT_ERROR, { error : ex, response: response, src : 'parse' }); return null; } } return response || []; }, /** Removes the specified model or array of models from this list. @method remove @param {Model|Model[]} models Models to remove. @param {Object} [options] Data to be mixed into the event facade of the `remove` event(s) for the removed models. @param {Boolean} [options.silent=false] If `true`, no `remove` event(s) will be fired. @return {Model|Model[]} Removed model or array of removed models. **/ remove: function (models, options) { if (Lang.isArray(models)) { return YArray.map(models, function (model) { return this._remove(model, options); }, this); } else { return this._remove(models, options); } }, /** Completely replaces all models in the list with those specified, and fires a single `reset` event. Use `reset` when you want to add or remove a large number of items at once without firing `add` or `remove` events for each one. @method reset @param {Model[]|Object[]} [models] Models to add. May be existing model instances or hashes of model attributes, in which case new model instances will be created from the hashes. Calling `reset()` without passing in any models will clear the list. @param {Object} [options] Data to be mixed into the event facade of the `reset` event. @param {Boolean} [options.silent=false] If `true`, no `reset` event will be fired. @chainable **/ reset: function (models, options) { models || (models = []); options || (options = {}); var facade = Y.merge(options, { src : 'reset', models: YArray.map(models, function (model) { return model instanceof Y.Model ? model : new this.model(model); }, this) }); // Sort the models in the facade before firing the reset event. if (this.comparator) { facade.models.sort(Y.bind(this._sort, this)); } options.silent ? this._defResetFn(facade) : this.fire(EVT_RESET, facade); return this; }, /** Forcibly re-sorts the list. Usually it shouldn't be necessary to call this method since the list maintains its sort order when items are added and removed, but if you change the `comparator` function after items are already in the list, you'll need to re-sort. @method sort @param {Object} [options] Data to be mixed into the event facade of the `reset` event. @param {Boolean} [options.silent=false] If `true`, no `reset` event will be fired. @chainable **/ sort: function (options) { var models = this._items.concat(), facade; if (!this.comparator) { return this; } options || (options = {}); models.sort(Y.bind(this._sort, this)); facade = Y.merge(options, { models: models, src : 'sort' }); options.silent ? this._defResetFn(facade) : this.fire(EVT_RESET, facade); return this; }, /** Override this method to provide a custom persistence implementation for this list. The default method just calls the callback without actually doing anything. This method is called internally by `load()`. @method sync @param {String} action Sync action to perform. May be one of the following: * `create`: Store a list of newly-created models for the first time. * `delete`: Delete a list of existing models. * `read` : Load a list of existing models. * `update`: Update a list of existing models. Currently, model lists only make use of the `read` action, but other actions may be used in future versions. @param {Object} [options] Sync options. It's up to the custom sync implementation to determine what options it supports or requires, if any. @param {callback} [callback] Called when the sync operation finishes. @param {Error} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be falsy. @param {mixed} [callback.response] The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an array of model attribute hashes. **/ sync: function (/* action, options, callback */) { var callback = YArray(arguments, 0, true).pop(); if (typeof callback === 'function') { callback(); } }, /** Returns an array containing the models in this list. @method toArray @return {Array} Array containing the models in this list. **/ toArray: function () { return this._items.concat(); }, /** Returns an array containing attribute hashes for each model in this list, suitable for being passed to `Y.JSON.stringify()`. Under the hood, this method calls `toJSON()` on each model in the list and pushes the results into an array. @method toJSON @return {Object[]} Array of model attribute hashes. @see Model.toJSON() **/ toJSON: function () { return this.map(function (model) { return model.toJSON(); }); }, // -- Protected Methods ---------------------------------------------------- /** Adds the specified _model_ if it isn't already in this list. @method _add @param {Model|Object} model Model or object to add. @param {Object} [options] Data to be mixed into the event facade of the `add` event for the added model. @param {Boolean} [options.silent=false] If `true`, no `add` event will be fired. @return {Model} The added model. @protected **/ _add: function (model, options) { var facade; options || (options = {}); if (!(model instanceof Y.Model)) { model = new this.model(model); } if (this._clientIdMap[model.get('clientId')]) { this.fire(EVT_ERROR, { error: 'Model is already in the list.', model: model, src : 'add' }); return; } facade = Y.merge(options, { index: this._findIndex(model), model: model }); options.silent ? this._defAddFn(facade) : this.fire(EVT_ADD, facade); return model; }, /** Adds this list as a bubble target for the specified model's events. @method _attachList @param {Model} model Model to attach to this list. @protected **/ _attachList: function (model) { // Attach this list and make it a bubble target for the model. model.lists.push(this); model.addTarget(this); }, /** Clears all internal state and the internal list of models, returning this list to an empty state. Automatically detaches all models in the list. @method _clear @protected **/ _clear: function () { YArray.each(this._items, this._detachList, this); this._clientIdMap = {}; this._idMap = {}; this._items = []; }, /** Removes this list as a bubble target for the specified model's events. @method _detachList @param {Model} model Model to detach. @protected **/ _detachList: function (model) { var index = YArray.indexOf(model.lists, this); if (index > -1) { model.lists.splice(index, 1); model.removeTarget(this); } }, /** Returns the index at which the given _model_ should be inserted to maintain the sort order of the list. @method _findIndex @param {Model} model The model being inserted. @return {int} Index at which the model should be inserted. @protected **/ _findIndex: function (model) { var comparator = this.comparator, items = this._items, max = items.length, min = 0, item, middle, needle; if (!comparator || !items.length) { return items.length; } needle = comparator(model); // Perform an iterative binary search to determine the correct position // based on the return value of the `comparator` function. while (min < max) { middle = (min + max) >> 1; // Divide by two and discard remainder. item = items[middle]; if (comparator(item) < needle) { min = middle + 1; } else { max = middle; } } return min; }, /** Removes the specified _model_ if it's in this list. @method _remove @param {Model} model Model to remove. @param {Object} [options] Data to be mixed into the event facade of the `remove` event for the removed model. @param {Boolean} [options.silent=false] If `true`, no `remove` event will be fired. @return {Model} Removed model. @protected **/ _remove: function (model, options) { var index = this.indexOf(model), facade; options || (options = {}); if (index === -1) { this.fire(EVT_ERROR, { error: 'Model is not in the list.', model: model, src : 'remove' }); return; } facade = Y.merge(options, { index: index, model: model }); options.silent ? this._defRemoveFn(facade) : this.fire(EVT_REMOVE, facade); return model; }, /** Array sort function used by `sort()` to re-sort the models in the list. @method _sort @param {Model} a First model to compare. @param {Model} b Second model to compare. @return {Number} `-1` if _a_ is less than _b_, `0` if equal, `1` if greater. @protected **/ _sort: function (a, b) { var aValue = this.comparator(a), bValue = this.comparator(b); return aValue < bValue ? -1 : (aValue > bValue ? 1 : 0); }, // -- Event Handlers ------------------------------------------------------- /** Updates the model maps when a model's `id` attribute changes. @method _afterIdChange @param {EventFacade} e @protected **/ _afterIdChange: function (e) { e.prevVal && delete this._idMap[e.prevVal]; e.newVal && (this._idMap[e.newVal] = e.target); }, // -- Default Event Handlers ----------------------------------------------- /** Default event handler for `add` events. @method _defAddFn @param {EventFacade} e @protected **/ _defAddFn: function (e) { var model = e.model, id = model.get('id'); this._clientIdMap[model.get('clientId')] = model; if (id) { this._idMap[id] = model; } this._attachList(model); this._items.splice(e.index, 0, model); }, /** Default event handler for `remove` events. @method _defRemoveFn @param {EventFacade} e @protected **/ _defRemoveFn: function (e) { var model = e.model, id = model.get('id'); this._detachList(model); delete this._clientIdMap[model.get('clientId')]; if (id) { delete this._idMap[id]; } this._items.splice(e.index, 1); }, /** Default event handler for `reset` events. @method _defResetFn @param {EventFacade} e @protected **/ _defResetFn: function (e) { // When fired from the `sort` method, we don't need to clear the list or // add any models, since the existing models are sorted in place. if (e.src === 'sort') { this._items = e.models.concat(); return; } this._clear(); if (e.models.length) { this.add(e.models, {silent: true}); } } }, { NAME: 'modelList' }); Y.augment(ModelList, Y.ArrayList); }, '@VERSION@' ,{requires:['array-extras', 'array-invoke', 'arraylist', 'base-build', 'escape', 'json-parse', 'model']});
/** * @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ jQuery(function($) { var treeselectmenu = $('div#treeselectmenu').html(); $('.treeselect li').each(function() { $li = $(this); $div = $li.find('div.treeselect-item:first'); // Add icons $li.prepend('<span class="pull-left icon-"></span>'); // Append clearfix $div.after('<div class="clearfix"></div>'); if ($li.find('ul.treeselect-sub').length) { // Add classes to Expand/Collapse icons $li.find('span.icon-').addClass('treeselect-toggle icon-minus'); // Append drop down menu in nodes $div.find('label:first').after(treeselectmenu); if (!$li.find('ul.treeselect-sub ul.treeselect-sub').length) { $li.find('div.treeselect-menu-expand').remove(); } } }); // Takes care of the Expand/Collapse of a node $('span.treeselect-toggle').click(function() { $i = $(this); // Take care of parent UL if ($i.parent().find('ul.treeselect-sub').is(':visible')) { $i.removeClass('icon-minus').addClass('icon-plus'); $i.parent().find('ul.treeselect-sub').hide(); $i.parent().find('ul.treeselect-sub i.treeselect-toggle').removeClass('icon-minus').addClass('icon-plus'); } else { $i.removeClass('icon-plus').addClass('icon-minus'); $i.parent().find('ul.treeselect-sub').show(); $i.parent().find('ul.treeselect-sub i.treeselect-toggle').removeClass('icon-plus').addClass('icon-minus'); } }); // Takes care of the filtering $('#treeselectfilter').keyup(function() { var text = $(this).val().toLowerCase(); var hidden = 0; $("#noresultsfound").hide(); var $list_elements = $('.treeselect li'); $list_elements.each(function() { if ($(this).text().toLowerCase().indexOf(text) == -1) { $(this).hide(); hidden++; } else { $(this).show(); } }); if(hidden == $list_elements.length) { $("#noresultsfound").show(); } }); // Checks all checkboxes the tree $('#treeCheckAll').click(function() { $('.treeselect input').attr('checked', 'checked'); }); // Unchecks all checkboxes the tree $('#treeUncheckAll').click(function() { $('.treeselect input').attr('checked', false); }); // Checks all checkboxes the tree $('#treeExpandAll').click(function() { $('ul.treeselect ul.treeselect-sub').show(); $('ul.treeselect i.treeselect-toggle').removeClass('icon-plus').addClass('icon-minus'); }); // Unchecks all checkboxes the tree $('#treeCollapseAll').click(function() { $('ul.treeselect ul.treeselect-sub').hide(); $('ul.treeselect i.treeselect-toggle').removeClass('icon-minus').addClass('icon-plus'); }); // Take care of children check/uncheck all $('a.checkall').click(function() { $(this).parents().eq(5).find('ul.treeselect-sub input').attr('checked', 'checked'); }); $('a.uncheckall').click(function() { $(this).parents().eq(5).find('ul.treeselect-sub input').attr('checked', false); }); // Take care of children toggle all $('a.expandall').click(function() { var $parent = $(this).parents().eq(6); $parent.find('ul.treeselect-sub').show(); $parent.find('ul.treeselect-sub i.treeselect-toggle').removeClass('icon-plus').addClass('icon-minus'); }); $('a.collapseall').click(function() { var $parent = $(this).parents().eq(6); $parent.find('li ul.treeselect-sub').hide(); $parent.find('li i.treeselect-toggle').removeClass('icon-minus').addClass('icon-plus'); }); });
'use strict'; function ClassList (el) { var classNames = (this.className && this.className.split(' ')) || []; for (var i = 0; i < classNames.length; i++) { this.push(classNames[i]); } this._updateClassName = function () { el.className = this.join(' '); } } ClassList.prototype = []; ClassList.prototype.add = function (className) { if (!this.contains(className)) { this.push(className); this._updateClassName(); } } ClassList.prototype.contains = function (className) { var found = false; for (var i = 0; i < this.length; i++) { if (this[i] === className) { found = true; break; } } } ClassList.prototype.remove = function (className) { for (var i = 0; i < this.length; i++) { if (classNames[i] === className) { this.splice(i, 1); this._updateClassName(); } } } function HTMLElement (options) { this.childNodes = []; this.style = {}; for (var key in options) { this[key] = options[key]; } } HTMLElement.prototype.render = function () { var attributes = []; var hasChildren = false; var content = ''; for (var key in this) { if (!this.hasOwnProperty(key)) { continue; } if (key === 'childNodes') { if (this.childNodes.length) { hasChildren = true; } } else if (key === 'innerHTML') { content = this.innerHTML; } else if (key === 'style') { var styles = ''; for (var styleName in this.style) { styles += styleName + ':' + this.style[styleName] + ';'; } if (styles && styles.length) { attributes.push('style="' + styles + '"'); } } else if (key === 'textContent') { content = this.textContent; } else if (key !== 'view' && key !== 'tagName' && key !== 'parentNode') { attributes.push(key + '="' + this[key] + '"'); } } if (hasChildren) { if (attributes.length) { return '<' + this.tagName + ' ' + attributes.join('') + '>' + this.childNodes.map(childRenderer).join('') + '</' + this.tagName + '>' } else { return '<' + this.tagName + '>' + this.childNodes.map(childRenderer).join('') + '</' + this.tagName + '>' } } else if (content) { return '<' + this.tagName + '>' + content + '</' + this.tagName + '>'; } else { return '<' + this.tagName + '>'; } } HTMLElement.prototype.addEventListener = function () {} HTMLElement.prototype.removeEventListener = function () {} HTMLElement.prototype.appendChild = function (child) { child.parentNode = this; for (var i = 0; i < this.childNodes.length; i++) { if (this.childNodes[i] === child) { this.childNodes.splice(i, 1); } } this.childNodes.push(child); } HTMLElement.prototype.insertBefore = function (child, before) { child.parentNode = this; for (var i = 0; i < this.childNodes.length; i++) { if (this.childNodes[i] === before) { this.childNodes.splice(i++, 0, child); } else if (this.childNodes[i] === child) { this.childNodes.splice(i, 1); } } } HTMLElement.prototype.removeChild = function (child) { child.parentNode = null; for (var i = 0; i < this.childNodes.length; i++) { if (this.childNodes[i] === child) { this.childNodes.splice(i, 1); } } } Object.defineProperties(HTMLElement.prototype, { classList: { get: function () { return new ClassList(this); } }, firstChild: { get: function () { return this.childNodes[0]; } }, nextSibling: { get: function () { var siblings = this.parentNode.childNodes; for (var i = 0; i < siblings.length; i++) { if (siblings[i] === this) { return siblings[i + 1]; } } } } }); function childRenderer (child) { return child.render(); } var ease = { linear: linear, quadIn: quadIn, quadOut: quadOut, quadInOut: quadInOut, cubicIn: cubicIn, cubicOut: cubicOut, cubicInOut: cubicInOut, quartIn: quartIn, quartOut: quartOut, quartInOut: quartInOut, quintIn: quintIn, quintOut: quintOut, quintInOut: quintInOut, bounceIn: bounceIn, bounceOut: bounceOut, bounceInOut: bounceInOut }; function linear (t) { return t; } function quadIn (t) { return Math.pow(t, 2); } function quadOut (t) { return 1 - quadIn(1 - t); } function quadInOut (t) { if (t < 0.5) { return quadIn(t * 2) / 2; } return 1 - quadIn((1 - t) * 2) / 2; } function cubicIn (t) { return Math.pow(t, 3); } function cubicOut (t) { return 1 - cubicIn(1 - t); } function cubicInOut (t) { if (t < 0.5) { return cubicIn(t * 2) / 2; } return 1 - cubicIn((1 - t) * 2) / 2; } function quartIn (t) { return Math.pow(t, 4); } function quartOut (t) { return 1 - quartIn(1 - t); } function quartInOut (t) { if (t < 0.5) { return quartIn(t * 2) / 2; } return 1 - quartIn((1 - t) * 2) / 2; } function quintIn (t) { return Math.pow(t, 5); } function quintOut (t) { return 1 - quintOut(1 - t); } function quintInOut (t) { if (t < 0.5) { return quintIn(t * 2) / 2; } return 1 - quintIn((1 - t) * 2) / 2; } function bounceOut (t) { var s = 7.5625; var p = 2.75; if (t < 1 / p) { return s * t * t; } if (t < 2 / p) { t -= 1.5 / p; return s * t * t + 0.75; } if (t < 2.5 / p) { t -= 2.25 / p; return s * t * t + 0.9375; } t -= 2.625 / p; return s * t * t + 0.984375; } function bounceIn (t) { return 1 - bounceOut(1 - t); } function bounceInOut (t) { if (t < 0.5) { return bounceIn(t * 2) / 2; } return 1 - bounceIn((1 - t) * 2) / 2; } function each (array, iterator) { for (var i = 0; i < array.length; i++) { iterator(array[i], i); } } function shuffle (array) { if (!array || !array.length) { return array; } for (var i = array.length - 1; i > 0; i--) { var rnd = Math.random() * i | 0; var temp = array[i]; array[i] = array[rnd]; array[rnd] = temp; } return array; } function inherits (Class, SuperClass) { Class.prototype = Object.create(SuperClass.prototype, { constructor: { value: Class } }); } function define (target, properties) { for (var propertyName in properties) { Object.defineProperty(target, propertyName, { value: properties[propertyName] }); } } function extend (target, properties) { for (var propertyName in properties) { target[propertyName] = properties[propertyName]; } return target; } function extendable (Class) { Class.extend = function extend (options) { function ExtendedClass (data) { if (!(this instanceof ExtendedClass)) { return new ExtendedClass(data); } Class.call(this, options, data); } inherits(ExtendedClass, Class); return ExtendedClass; }; } var style = (typeof document !== 'undefined') ? (document.createElement('p').style) : {}; var prefixes = ['webkit', 'moz', 'Moz', 'ms', 'o']; var memoized = {}; function prefix (propertyName) { if (typeof memoized[propertyName] !== 'undefined') { return memoized[propertyName]; } if (typeof style[propertyName] !== 'undefined') { memoized[propertyName] = propertyName; return propertyName; } var camelCase = propertyName[0].toUpperCase() + propertyName.slice(1); for (var i = 0, len = prefixes.length; i < len; i++) { var test = prefixes[i] + camelCase; if (typeof style[test] !== 'undefined') { memoized[propertyName] = test; return test; } } } function el (tagName, attributes) { attributes = attributes || {}; if (attributes.svg) { var element = document.createElementNS("http://www.w3.org/2000/svg", "svg") } else { var element = document.createElement(tagName || 'div'); } for (var key in attributes) { if (key === 'text') { element.textContent = attributes.text; } else if (key === 'svg') { continue; } else if (key === 'style') { var styles = attributes.style.split(';'); for (var i = 0; i < styles.length; i++) { var styleParts = styles[i].split(':'); if (styleParts.length > 1) { element.style[styleParts[0].trim()] = styleParts[1].trim(); } } } else if (key === 'html') { element.innerHTML = attributes[key]; } else { element[key] = attributes[key]; } } return element; } function Observable (options) { Object.defineProperty(this, 'listeners', { enumerable: false, value: {}, writable: true }); for (var key in options) { this[key] = options[key]; } } define(Observable.prototype, { on: function (eventName, handler) { if (typeof this.listeners[eventName] === 'undefined') { this.listeners[eventName] = []; } this.listeners[eventName].push({ handler: handler, one: false }); return this; }, one: function (eventName, handler) { if (!this.listeners[eventName]) this.listeners[eventName] = []; this.listeners[eventName].push({ handler: handler, one: true }); return this; }, trigger: function (eventName) { var listeners = this.listeners[eventName]; if (!listeners) { return this; } var args = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } for (i = 0; i < listeners.length; i++) { listeners[i].handler.apply(this, args); if (listeners[i].one) { listeners.splice(i--, 1); } } return this; }, off: function (name, handler) { if (typeof name === 'undefined') { this.listeners = {}; } else if (typeof handler === 'undefined') { this.listeners[name] = []; } else { var listeners = this.listeners[name]; if (!listeners) { return this; } for (var i = 0; i < listeners.length; i++) { if (listeners[i].handler === handler) { listeners.splice(i--, 1); } } } return this; } }); function observable (options) { return new Observable(options); } var EVENT = 'init inited mount mounted unmount unmounted sort sorted update updated destroy'.split(' ').reduce(function (obj, name) { obj[name] = name; return obj; }, {}); function View (options, data) { if (!(this instanceof View)) { return new View(options, data); } Observable.call(this); options = options || {}; this.el = null; this.eventListeners = []; this.listeners = {}; if (window.HTMLElement && (options instanceof window.HTMLElement)) { this.el = options; } else { for (var key in options) { if (EVENT[key]) { this.on(key, options[key]); } else if (key === 'text' && !options.el) { this.el = document.createTextNode(options.text || ''); } else if (key === 'el') { if (typeof options.el === 'string') { this.el = document.createElement(options.el); if (options.text) this.el.textContent = options.text; if (options.html) this.el.innerHTML = options.html; } else if (options.el instanceof Array) { this.el = el(options.el[0], options.el[1]); } else { this.el = options.el; } } else { this[key] = options[key]; } } } this.trigger(EVENT.init, data); if (!this.el) { this.el = document.createElement('div'); } this.el.view = this; this.trigger(EVENT.inited, data); } inherits(View, Observable); define(View.prototype, { setAttr: function (attributeName, value) { if (this.el[attributeName] !== value) { this.el[attributeName] = value; } return this; }, setClass: function (className, value) { if (this.el.classList.contains(className) !== value) { if (value) { this.el.classList.add(className); } else { this.el.classList.remove(className); } } return this; }, setStyle: function (propertyName, value) { if (this.el.style[propertyName] !== value) { this.el.style[propertyName] = value; } return this; }, setText: function (text) { if (this.el.textContent !== text) { this.el.textContent = text; } return this; }, setHTML: function (html) { if (this.el.innerHTML !== html) { this.el.innerHTML = html; } return this; }, addListener: function (listenerName, handler, useCapture) { var view = this; var listener = { name: listenerName, handler: handler, proxy: function (e) { handler.call(view, e); } }; if (!this.eventListeners) this.eventListeners = []; this.eventListeners.push(listener); this.el.addEventListener(listenerName, listener.proxy, useCapture); return this; }, removeListener: function (listenerName, handler) { var listeners = this.eventListeners; if (!listeners) { return this; } if (typeof listenerName === 'undefined') { for (var i = 0; i < listeners.length; i++) { this.el.removeEventListener(listeners[i].proxy); } this.listeners = []; } else if (typeof handler === 'undefined') { for (var i = 0; i < listeners.length; i++) { if (listeners[i].name === listenerName) { listeners.splice(i--, 1); } } } else { for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; if (listener.name === listenerName && handler === listener.handler) { listeners.splice(i--, 1); } } } return this; }, addChild: function (child) { if (child.views) { child.parent = this; return this.setChildren(child.views); } var sorting = false; if (child.parent) { sorting = true; child.trigger(EVENT.sort); } else { child.trigger(EVENT.mount); } this.el.appendChild(child.el); child.parent = this; if (sorting) { child.trigger(EVENT.sorted); } else { child.trigger(EVENT.mounted); } return this; }, addBefore: function (child, before) { var sorting = false; if (child.parent) { sorting = true; child.trigger(EVENT.sort); } else { child.trigger(EVENT.mount); } this.el.insertBefore(child.el, before.el || before); child.parent = this; if (sorting) { child.trigger(EVENT.sorted); } else { child.trigger(EVENT.mounted); } return this; }, addAfter: function (child, after) { var afterEl = after.el || after; var nextAfterEl = afterEl.nextSibling; if (nextAfterEl) { this.addBefore(child, nextAfterEl); } else { this.addChild(child); } }, setChildren: function (views) { if (views.views) { views.parent = this; return this.setChildren(views.views); } var traverse = this.el.firstChild; for (var i = 0; i < views.length; i++) { var view = views[i]; if (traverse === view.el) { traverse = traverse.nextSibling; continue; } if (traverse) { this.addBefore(view, traverse); } else { this.addChild(view); } } while (traverse) { var next = traverse.nextSibling; if (traverse.view) { traverse.view.parent.removeChild(traverse.view); } else { this.el.removeChild(traverse); } traverse = next; } return this; }, removeChild: function (child) { if (!child.parent) { return this; } child.trigger(EVENT.unmount); this.el.removeChild(child.el); child.parent = null; child.trigger(EVENT.unmounted); return this; }, update: function (data) { this.trigger(EVENT.update, data); }, destroy: function () { this.trigger(EVENT.destroy); if (this.parent) this.parent.removeChild(this); var traverse = this.el.firstChild; while (traverse) { if (traverse.view) { traverse.view.destroy(); } else { this.el.removeChild(traverse); } traverse = this.el.firstChild; } this.off(); this.removeListener(); } }); extendable(View); var view = View; var EVENT$1 = 'init inited update updated destroy'.split(' ').reduce(function (obj, key) { obj[key] = key; return obj; }, {}); function ViewList (options) { if (!(this instanceof ViewList)) { return new ViewList(options); } Observable.call(this); this.lookup = {}; this.views = []; if (typeof options === 'function') { this.View = options; } else { for (var key in options) { if (EVENT$1[key]) { this.on(key, options[key]); } else { this[key] = options[key]; } } } this.trigger(EVENT$1.init); this.trigger(EVENT$1.inited); } inherits(ViewList, Observable); define(ViewList.prototype, { update: function (data) { this.trigger(EVENT$1.update, data); var viewList = this; var views = new Array(data.length); var lookup = {}; var currentViews = this.views; var currentLookup = this.lookup; var key = this.key; for (var i = 0; i < data.length; i++) { var item = data[i]; var id = key && item[key]; var ViewClass = this.View || this.view || View; var view = (key ? currentLookup[id] : currentViews[i]) || new ViewClass(); if (key) lookup[id] = view; views[i] = view; view.update(item); } if (key) { for (var id in currentLookup) { if (!lookup[id]) { currentLookup[id].destroy(); } } } else { for (var i = views.length; i < currentViews.length; i++) { currentViews[i].destroy(); } } this.views = views; this.lookup = lookup; if (this.parent) this.parent.setChildren(views); this.trigger(EVENT$1.updated); }, destroy: function () { this.trigger(EVENT$1.destroy); this.update([]); this.off(); } }); extendable(ViewList); var viewlist = ViewList; var viewList = ViewList; var hasRequestAnimationFrame = typeof requestAnimationFrame !== 'undefined'; function raf (callback) { if (hasRequestAnimationFrame) { return requestAnimationFrame(callback); } else { return setTimeout(callback, 1000 / 60); } } raf.cancel = function cancel (id) { if (hasRequestAnimationFrame) { cancelAnimationFrame(id); } else { clearTimeout(id); } }; var requestedAnimationFrames = []; var ticking$1; function baf (callback) { requestedAnimationFrames.push(callback); if (ticking$1) return; ticking$1 = raf(function () { ticking$1 = false; var animationFrames = requestedAnimationFrames.splice(0, requestedAnimationFrames.length); for (var i = 0; i < animationFrames.length; i++) { animationFrames[i](); } }); } baf.cancel = function cancel (cb) { for (var i = 0; i < requestedAnimationFrames.length; i++) { if (requestedAnimationFrames[i] === cb) { requestedAnimationFrames.splice(i--, 1); } } }; var animations = []; var ticking; function Animation (options) { Observable.call(this); var delay = options.delay || 0; var duration = options.duration || 0; var easing = options.easing || 'quadOut'; var init = options.init; var start = options.start; var progress = options.progress; var end = options.end; var now = Date.now(); this.startTime = now + delay; this.endTime = this.startTime + duration; this.easing = ease[easing]; this.started = false; if (init) this.on('init', init); if (start) this.on('start', start); if (progress) this.on('progress', progress); if (end) this.on('end', end); // add animation animations.push(this); this.trigger('init'); if (!ticking) { // start ticking ticking = true; baf(tick); } } inherits(Animation, Observable); define(Animation.prototype, { destroy: function () { for (var i = 0; i < animations.length; i++) { if (animations[i] === this) { animations.splice(i, 1); return; } } } }); function animation (options) { return new Animation(options); } function tick () { var now = Date.now(); if (!animations.length) { // stop ticking ticking = false; return; } for (var i = 0; i < animations.length; i++) { var animation = animations[i]; if (now < animation.startTime) { // animation not yet started.. continue; } if (!animation.started) { // animation starts animation.started = true; animation.trigger('start'); } // animation progress var t = (now - animation.startTime) / (animation.endTime - animation.startTime); if (t > 1) { t = 1; } animation.trigger('progress', animation.easing(t), t); if (now > animation.endTime) { // animation ended animation.trigger('end'); animations.splice(i--, 1); continue; } } baf(tick); } function renderer (handler) { var nextRender = noOp; var nextData = null; var rendering = false; return function needRender (data) { if (rendering) { nextRender = needRender; nextData = data; data = data; return; } rendering = true; handler(function () { rendering = false; var _nextRender = nextRender; var _nextData = nextData; nextRender = noOp; nextData = null; _nextRender(_nextData); }, data); } } function noOp () {}; var has3d; function translate (x, y, z) { if (typeof has3d === 'undefined') { has3d = check3d(); } if (has3d || z) { return 'translate3d(' + (x || 0) + ', ' + (y || 0) + ', ' + (z || 0) + ')'; } else { return 'translate(' + (x || 0) + ', ' + (y || 0) + ')'; } } function check3d () { var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); if (!isMobile) { return false; } var transform = prefix('transform'); var $p = document.createElement('p'); document.body.appendChild($p); $p.style[transform] = 'translate3d(1px,1px,1px)'; has3d = $p.style[transform]; if (typeof has3d !== 'undefined' && has3d !== null && has3d.length && has3d !== 'none') { has3d = true; } else { has3d = false; } document.body.removeChild($p); return has3d; } global.document = { createElement (tagName) { return new HTMLElement({ tagName: tagName }); } }; global.window = {} global.navigator = { userAgent: '' } var server = true; View.prototype.render = function () { return this.el.render(); } exports.server = server; exports.ease = ease; exports.el = el; exports.prefix = prefix; exports.View = View; exports.view = view; exports.ViewList = ViewList; exports.viewlist = viewlist; exports.viewList = viewList; exports.Animation = Animation; exports.animation = animation; exports.Observable = Observable; exports.observable = observable; exports.each = each; exports.shuffle = shuffle; exports.inherits = inherits; exports.define = define; exports.extend = extend; exports.extendable = extendable; exports.renderer = renderer; exports.translate = translate; exports.baf = baf; exports.raf = raf;
/*! * Qoopido.js library v3.2.5, 2014-5-18 * https://github.com/dlueth/qoopido.js * (c) 2014 Dirk Lueth * Dual licensed under MIT and GPL */ !function(e,t){if(t.register){var r=[];Object.defineProperties||r.push("./defineproperties"),t.register("polyfill/object/create",e,r)}else(t.modules=t.modules||{})["polyfill/object/create"]=e()}(function(){"use strict";return Object.create||(Object.create=function(e,t){function r(){}if("object"!=typeof e)throw new TypeError;r.prototype=e;var o=new r;if(e&&(o.constructor=r),arguments.length>1){if(t!==Object(t))throw new TypeError;Object.defineProperties(o,t)}return o}),!0},window.qoopido=window.qoopido||{});
/*! jQuery-Impromptu - v5.2.2 - 2014-01-29 * http://trentrichardson.com/Impromptu * Copyright (c) 2014 Trent Richardson; Licensed MIT */ (function($) { "use strict"; /** * setDefaults - Sets the default options * @param message String/Object - String of html or Object of states * @param options Object - Options to set the prompt * @return jQuery - container with overlay and prompt */ $.prompt = function(message, options) { // only for backwards compat, to be removed in future version if(options !== undefined && options.classes !== undefined && typeof options.classes === 'string'){ options = { box: options.classes }; } $.prompt.options = $.extend({},$.prompt.defaults,options); $.prompt.currentPrefix = $.prompt.options.prefix; // Be sure any previous timeouts are destroyed if($.prompt.timeout){ clearTimeout($.prompt.timeout); } $.prompt.timeout = false; var opts = $.prompt.options, $body = $(document.body), $window = $(window); //build the box and fade var msgbox = '<div class="'+ $.prompt.options.prefix +'box '+ opts.classes.box +'">'; if(opts.useiframe && ($('object, applet').length > 0)) { msgbox += '<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+ opts.prefix +'fade '+ opts.classes.fade +'"></iframe>'; } else { msgbox +='<div class="'+ opts.prefix +'fade '+ opts.classes.fade +'"></div>'; } msgbox += '<div class="'+ opts.prefix +' '+ opts.classes.prompt +'">'+ '<form action="javascript:false;" onsubmit="return false;" class="'+ opts.prefix +'form">'+ '<div class="'+ opts.prefix +'close '+ opts.classes.close +'">'+ opts.closeText +'</div>'+ '<div class="'+ opts.prefix +'states"></div>'+ '</form>'+ '</div>'+ '</div>'; $.prompt.jqib = $(msgbox).appendTo($body); $.prompt.jqi = $.prompt.jqib.children('.'+ opts.prefix);//.data('jqi',opts); $.prompt.jqif = $.prompt.jqib.children('.'+ opts.prefix +'fade'); //if a string was passed, convert to a single state if(message.constructor === String){ message = { state0: { title: opts.title, html: message, buttons: opts.buttons, position: opts.position, focus: opts.focus, defaultButton: opts.defaultButton, submit: opts.submit } }; } //build the states $.prompt.options.states = {}; var k,v; for(k in message){ v = $.extend({},$.prompt.defaults.state,{name:k},message[k]); $.prompt.addState(v.name, v); if($.prompt.currentStateName === ''){ $.prompt.currentStateName = v.name; } } //Events $.prompt.jqi.on('click', '.'+ opts.prefix +'buttons button', function(e){ var $t = $(this), $state = $t.parents('.'+ opts.prefix +'state'), stateobj = $.prompt.options.states[$state.data('jqi-name')], msg = $state.children('.'+ opts.prefix +'message'), clicked = stateobj.buttons[$t.text()] || stateobj.buttons[$t.html()], forminputs = {}; // if for some reason we couldn't get the value if(clicked === undefined){ for(var i in stateobj.buttons){ if(stateobj.buttons[i].title === $t.text() || stateobj.buttons[i].title === $t.html()){ clicked = stateobj.buttons[i].value; } } } //collect all form element values from all states. $.each($.prompt.jqi.children('form').serializeArray(),function(i,obj){ if (forminputs[obj.name] === undefined) { forminputs[obj.name] = obj.value; } else if (typeof forminputs[obj.name] === Array || typeof forminputs[obj.name] === 'object') { forminputs[obj.name].push(obj.value); } else { forminputs[obj.name] = [forminputs[obj.name],obj.value]; } }); // trigger an event var promptsubmite = new $.Event('impromptu:submit'); promptsubmite.stateName = stateobj.name; promptsubmite.state = $state; $state.trigger(promptsubmite, [clicked, msg, forminputs]); if(!promptsubmite.isDefaultPrevented()){ $.prompt.close(true, clicked,msg,forminputs); } }); // if the fade is clicked blink the prompt var fadeClicked = function(){ if(opts.persistent){ var offset = (opts.top.toString().indexOf('%') >= 0? ($window.height()*(parseInt(opts.top,10)/100)) : parseInt(opts.top,10)), top = parseInt($.prompt.jqi.css('top').replace('px',''),10) - offset; //$window.scrollTop(top); $('html,body').animate({ scrollTop: top }, 'fast', function(){ var i = 0; $.prompt.jqib.addClass(opts.prefix +'warning'); var intervalid = setInterval(function(){ $.prompt.jqib.toggleClass(opts.prefix +'warning'); if(i++ > 1){ clearInterval(intervalid); $.prompt.jqib.removeClass(opts.prefix +'warning'); } }, 100); }); } else { $.prompt.close(true); } }; // listen for esc or tab keys var keyDownEventHandler = function(e){ var key = (window.event) ? event.keyCode : e.keyCode; //escape key closes if(key === 27) { fadeClicked(); } //enter key pressed trigger the default button if its not on it, ignore if it is a textarea if(key === 13){ var $defBtn = $.prompt.getCurrentState().find('.'+ opts.prefix +'defaultbutton'); var $tgt = $(e.target); if($tgt.is('textarea,.'+opts.prefix+'button') === false && $defBtn.length > 0){ e.preventDefault(); $defBtn.click(); } } //constrain tabs, tabs should iterate through the state and not leave if (key === 9){ var $inputels = $('input,select,textarea,button',$.prompt.getCurrentState()); var fwd = !e.shiftKey && e.target === $inputels[$inputels.length-1]; var back = e.shiftKey && e.target === $inputels[0]; if (fwd || back) { setTimeout(function(){ if (!$inputels){ return; } var el = $inputels[back===true ? $inputels.length-1 : 0]; if (el){ el.focus(); } },10); return false; } } }; $.prompt.position(); $.prompt.style(); $.prompt.jqif.click(fadeClicked); $window.resize({animate:false}, $.prompt.position); $.prompt.jqi.find('.'+ opts.prefix +'close').click($.prompt.close); $.prompt.jqib.on("keydown",keyDownEventHandler) .on('impromptu:loaded', opts.loaded) .on('impromptu:close', opts.close) .on('impromptu:statechanging', opts.statechanging) .on('impromptu:statechanged', opts.statechanged); // Show it $.prompt.jqif[opts.show](opts.overlayspeed); $.prompt.jqi[opts.show](opts.promptspeed, function(){ var $firstState = $.prompt.jqi.find('.'+ opts.prefix +'states .'+ opts.prefix +'state').eq(0); $.prompt.goToState($firstState.data('jqi-name')); $.prompt.jqib.trigger('impromptu:loaded'); }); // Timeout if(opts.timeout > 0){ $.prompt.timeout = setTimeout(function(){ $.prompt.close(true); },opts.timeout); } return $.prompt.jqib; }; $.prompt.defaults = { prefix:'jqi', classes: { box: '', fade: '', prompt: '', close: '', title: '', message: '', buttons: '', button: '', defaultButton: '' }, title: '', closeText: '&times;', buttons: { Ok: true }, loaded: function(e){}, submit: function(e,v,m,f){}, close: function(e,v,m,f){}, statechanging: function(e, from, to){}, statechanged: function(e, to){}, opacity: 0.6, zIndex: 999, overlayspeed: 'slow', promptspeed: 'fast', show: 'fadeIn', focus: 0, defaultButton: 0, useiframe: false, top: '15%', position: { container: null, x: null, y: null, arrow: null, width: null }, persistent: true, timeout: 0, states: {}, state: { name: null, title: '', html: '', buttons: { Ok: true }, focus: 0, defaultButton: 0, position: { container: null, x: null, y: null, arrow: null, width: null }, submit: function(e,v,m,f){ return true; } } }; /** * currentPrefix String - At any time this show be the prefix * of the current prompt ex: "jqi" */ $.prompt.currentPrefix = $.prompt.defaults.prefix; /** * currentStateName String - At any time this is the current state * of the current prompt ex: "state0" */ $.prompt.currentStateName = ""; /** * setDefaults - Sets the default options * @param o Object - Options to set as defaults * @return void */ $.prompt.setDefaults = function(o) { $.prompt.defaults = $.extend({}, $.prompt.defaults, o); }; /** * setStateDefaults - Sets the default options for a state * @param o Object - Options to set as defaults * @return void */ $.prompt.setStateDefaults = function(o) { $.prompt.defaults.state = $.extend({}, $.prompt.defaults.state, o); }; /** * position - Repositions the prompt (Used internally) * @return void */ $.prompt.position = function(e){ var restoreFx = $.fx.off, $state = $.prompt.getCurrentState(), stateObj = $.prompt.options.states[$state.data('jqi-name')], pos = stateObj? stateObj.position : undefined, $window = $(window), bodyHeight = document.body.scrollHeight, //$(document.body).outerHeight(true), windowHeight = $(window).height(), documentHeight = $(document).height(), height = bodyHeight > windowHeight ? bodyHeight : windowHeight, top = parseInt($window.scrollTop(),10) + ($.prompt.options.top.toString().indexOf('%') >= 0? (windowHeight*(parseInt($.prompt.options.top,10)/100)) : parseInt($.prompt.options.top,10)); // when resizing the window turn off animation if(e !== undefined && e.data.animate === false){ $.fx.off = true; } $.prompt.jqib.css({ position: "absolute", height: height, width: "100%", top: 0, left: 0, right: 0, bottom: 0 }); $.prompt.jqif.css({ position: "fixed", height: height, width: "100%", top: 0, left: 0, right: 0, bottom: 0 }); // tour positioning if(pos && pos.container){ var offset = $(pos.container).offset(); if($.isPlainObject(offset) && offset.top !== undefined){ $.prompt.jqi.css({ position: "absolute" }); $.prompt.jqi.animate({ top: offset.top + pos.y, left: offset.left + pos.x, marginLeft: 0, width: (pos.width !== undefined)? pos.width : null }); top = (offset.top + pos.y) - ($.prompt.options.top.toString().indexOf('%') >= 0? (windowHeight*(parseInt($.prompt.options.top,10)/100)) : parseInt($.prompt.options.top,10)); $('html,body').animate({ scrollTop: top }, 'slow', 'swing', function(){}); } } // custom state width animation else if(pos && pos.width){ $.prompt.jqi.css({ position: "absolute", left: '50%' }); $.prompt.jqi.animate({ top: pos.y || top, left: pos.x || '50%', marginLeft: ((pos.width/2)*-1), width: pos.width }); } // standard prompt positioning else{ $.prompt.jqi.css({ position: "absolute", top: top, left: '50%',//$window.width()/2, marginLeft: (($.prompt.jqi.outerWidth(false)/2)*-1) }); } // restore fx settings if(e !== undefined && e.data.animate === false){ $.fx.off = restoreFx; } }; /** * style - Restyles the prompt (Used internally) * @return void */ $.prompt.style = function(){ $.prompt.jqif.css({ zIndex: $.prompt.options.zIndex, display: "none", opacity: $.prompt.options.opacity }); $.prompt.jqi.css({ zIndex: $.prompt.options.zIndex+1, display: "none" }); $.prompt.jqib.css({ zIndex: $.prompt.options.zIndex }); }; /** * get - Get the prompt * @return jQuery - the prompt */ $.prompt.get = function(state) { return $('.'+ $.prompt.currentPrefix); }; /** * addState - Injects a state into the prompt * @param statename String - Name of the state * @param stateobj Object - options for the state * @param afterState String - selector of the state to insert after * @return jQuery - the newly created state */ $.prompt.addState = function(statename, stateobj, afterState) { var state = "", $state = null, arrow = "", title = "", opts = $.prompt.options, $jqistates = $('.'+ $.prompt.currentPrefix +'states'), defbtn,k,v,i=0; stateobj = $.extend({},$.prompt.defaults.state, {name:statename}, stateobj); if(stateobj.position.arrow !== null){ arrow = '<div class="'+ opts.prefix + 'arrow '+ opts.prefix + 'arrow'+ stateobj.position.arrow +'"></div>'; } if(stateobj.title && stateobj.title !== ''){ title = '<div class="lead '+ opts.prefix + 'title '+ opts.classes.title +'">'+ stateobj.title +'</div>'; } state += '<div id="'+ opts.prefix +'state_'+ statename +'" class="'+ opts.prefix + 'state" data-jqi-name="'+ statename +'" style="display:none;">'+ arrow + title + '<div class="'+ opts.prefix +'message '+ opts.classes.message +'">' + stateobj.html +'</div>'+ '<div class="'+ opts.prefix +'buttons '+ opts.classes.buttons +'"'+ ($.isEmptyObject(stateobj.buttons)? 'style="display:none;"':'') +'>'; for(k in stateobj.buttons){ v = stateobj.buttons[k], defbtn = stateobj.focus === i || (isNaN(stateobj.focus) && stateobj.defaultButton === i) ? ($.prompt.currentPrefix + 'defaultbutton ' + opts.classes.defaultButton) : ''; if(typeof v === 'object'){ state += '<button class="'+ opts.classes.button +' '+ $.prompt.currentPrefix + 'button '+ defbtn; if(typeof v.classes !== "undefined"){ state += ' '+ ($.isArray(v.classes)? v.classes.join(' ') : v.classes) + ' '; } state += '" name="' + opts.prefix + '_' + statename + '_button' + v.title.replace(/[^a-z0-9]+/gi,'') + '" id="' + opts.prefix + '_' + statename + '_button' + v.title.replace(/[^a-z0-9]+/gi,'') + '" value="' + v.value + '">' + v.title + '</button>'; } else { state += '<button class="'+ $.prompt.currentPrefix + 'button '+ opts.classes.button +' '+ defbtn +'" name="' + opts.prefix + '_' + statename + '_button' + k.replace(/[^a-z0-9]+/gi,'') + '" id="' + opts.prefix + '_' + statename + '_button' + k.replace(/[^a-z0-9]+/gi,'') + '" value="' + v + '">' + k + '</button>'; } i++; } state += '</div></div>'; $state = $(state); $state.on('impromptu:submit', stateobj.submit); if(afterState !== undefined){ $jqistates.find('#'+ $.prompt.currentPrefix +'state_'+ afterState).after($state); } else{ $jqistates.append($state); } $.prompt.options.states[statename] = stateobj; return $state; }; /** * removeState - Removes a state from the promt * @param state String - Name of the state * @return Boolean - returns true on success, false on failure */ $.prompt.removeState = function(state) { var $state = $.prompt.getState(state), rm = function(){ $state.remove(); }; if($state.length === 0){ return false; } // transition away from it before deleting if($state.css('display') !== 'none'){ if($state.next().length > 0){ $.prompt.nextState(rm); } else{ $.prompt.prevState(rm); } } else{ $state.slideUp('slow', rm); } return true; }; /** * getState - Get the state by its name * @param state String - Name of the state * @return jQuery - the state */ $.prompt.getState = function(state) { return $('#'+ $.prompt.currentPrefix +'state_'+ state); }; $.prompt.getStateContent = function(state) { return $.prompt.getState(state); }; /** * getCurrentState - Get the current visible state * @return jQuery - the current visible state */ $.prompt.getCurrentState = function() { return $.prompt.getState($.prompt.getCurrentStateName()); }; /** * getCurrentStateName - Get the name of the current visible state * @return String - the current visible state's name */ $.prompt.getCurrentStateName = function() { return $.prompt.currentStateName; }; /** * goToState - Goto the specified state * @param state String - name of the state to transition to * @param subState Boolean - true to be a sub state within the currently open state * @param callback Function - called when the transition is complete * @return jQuery - the newly active state */ $.prompt.goToState = function(state, subState, callback) { var $jqi = $.prompt.get(), jqiopts = $.prompt.options, $state = $.prompt.getState(state), stateobj = jqiopts.states[$state.data('jqi-name')], promptstatechanginge = new $.Event('impromptu:statechanging'); // subState can be ommitted if(typeof subState === 'function'){ callback = subState; subState = false; } $.prompt.jqib.trigger(promptstatechanginge, [$.prompt.getCurrentStateName(), state]); if(!promptstatechanginge.isDefaultPrevented() && $state.length > 0){ $.prompt.jqi.find('.'+ $.prompt.currentPrefix +'parentstate').removeClass($.prompt.currentPrefix +'parentstate'); if(subState){ // hide any open substates // get rid of any substates $.prompt.jqi.find('.'+ $.prompt.currentPrefix +'substate').not($state) .slideUp(jqiopts.promptspeed) .removeClass('.'+ $.prompt.currentPrefix +'substate') .find('.'+ $.prompt.currentPrefix +'arrow').hide(); // add parent state class so it can be visible, but blocked $.prompt.jqi.find('.'+ $.prompt.currentPrefix +'state:visible').addClass($.prompt.currentPrefix +'parentstate'); // add substate class so we know it will be smaller $state.addClass($.prompt.currentPrefix +'substate'); } else{ // hide any open states $.prompt.jqi.find('.'+ $.prompt.currentPrefix +'state').not($state) .slideUp(jqiopts.promptspeed) .find('.'+ $.prompt.currentPrefix +'arrow').hide(); } $.prompt.currentStateName = stateobj.name; $state.slideDown(jqiopts.promptspeed,function(){ var $t = $(this); // if focus is a selector, find it, else its button index if(typeof(stateobj.focus) === 'string'){ $t.find(stateobj.focus).eq(0).focus(); } else{ $t.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus(); } $t.find('.'+ $.prompt.currentPrefix +'arrow').show(jqiopts.promptspeed); if (typeof callback === 'function'){ $.prompt.jqib.on('impromptu:statechanged', callback); } $.prompt.jqib.trigger('impromptu:statechanged', [state]); if (typeof callback === 'function'){ $.prompt.jqib.off('impromptu:statechanged', callback); } }); if(!subState){ $.prompt.position(); } } return $state; }; /** * nextState - Transition to the next state * @param callback Function - called when the transition is complete * @return jQuery - the newly active state */ $.prompt.nextState = function(callback) { var $next = $('#'+ $.prompt.currentPrefix +'state_'+ $.prompt.getCurrentStateName()).next(); if($next.length > 0){ $.prompt.goToState( $next.attr('id').replace($.prompt.currentPrefix +'state_',''), callback ); } return $next; }; /** * prevState - Transition to the previous state * @param callback Function - called when the transition is complete * @return jQuery - the newly active state */ $.prompt.prevState = function(callback) { var $prev = $('#'+ $.prompt.currentPrefix +'state_'+ $.prompt.getCurrentStateName()).prev(); if($prev.length > 0){ $.prompt.goToState( $prev.attr('id').replace($.prompt.currentPrefix +'state_',''), callback ); } return $prev; }; /** * close - Closes the prompt * @param callback Function - called when the transition is complete * @param clicked String - value of the button clicked (only used internally) * @param msg jQuery - The state message body (only used internally) * @param forvals Object - key/value pairs of all form field names and values (only used internally) * @return jQuery - the newly active state */ $.prompt.close = function(callCallback, clicked, msg, formvals){ if($.prompt.timeout){ clearTimeout($.prompt.timeout); $.prompt.timeout = false; } if($.prompt.jqib){ $.prompt.jqib.fadeOut('fast',function(){ $.prompt.jqib.trigger('impromptu:close', [clicked,msg,formvals]); $.prompt.jqib.remove(); $(window).off('resize',$.prompt.position); }); } }; /** * Enable using $('.selector').prompt({}); * This will grab the html within the prompt as the prompt message */ $.fn.prompt = function(options){ if(options === undefined){ options = {}; } if(options.withDataAndEvents === undefined){ options.withDataAndEvents = false; } $.prompt($(this).clone(options.withDataAndEvents).html(),options); }; })(jQuery);
require('../../../modules/es7.string.match-all'); module.exports = require('../../../modules/_entry-virtual')('String').matchAll;
/*! * Bootstrap-select v1.6.0 (http://silviomoreto.github.io/bootstrap-select/) * * Copyright 2013-2014 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Nessuna selezione', noneResultsText: 'Nessun risultato', countSelectedText: 'Selezionati {0} di {1}', maxOptionsText: ['Limite raggiunto ({n} {var} max)', 'Limite del gruppo raggiunto ({n} {var} max)', ['elementi', 'elemento']], multipleSeparator: ', ' }; }(jQuery));
"use strict"; var Query = require('../connection/commands').Query , retrieveBSON = require('../connection/utils').retrieveBSON , f = require('util').format , MongoError = require('../error') , getReadPreference = require('./shared').getReadPreference; var BSON = retrieveBSON(), Long = BSON.Long; var WireProtocol = function(legacyWireProtocol) { this.legacyWireProtocol = legacyWireProtocol; } // // Execute a write operation var executeWrite = function(pool, bson, type, opsField, ns, ops, options, callback) { if(ops.length == 0) throw new MongoError("insert must contain at least one document"); if(typeof options == 'function') { callback = options; options = {}; options = options || {}; } // Split the ns up to get db and collection var p = ns.split("."); var d = p.shift(); // Options var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; var writeConcern = options.writeConcern; // return skeleton var writeCommand = {}; writeCommand[type] = p.join('.'); writeCommand[opsField] = ops; writeCommand.ordered = ordered; // Did we specify a write concern if(writeConcern && Object.keys(writeConcern).length > 0) { writeCommand.writeConcern = writeConcern; } // If we have collation passed in if(options.collation) { for(var i = 0; i < writeCommand[opsField].length; i++) { if(!writeCommand[opsField][i].collation) { writeCommand[opsField][i].collation = options.collation; } } } // Do we have bypassDocumentValidation set, then enable it on the write command if(typeof options.bypassDocumentValidation == 'boolean') { writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; } // Options object var opts = { command: true }; var queryOptions = { checkKeys : false, numberToSkip: 0, numberToReturn: 1 }; if(type == 'insert') queryOptions.checkKeys = true; // Ensure we support serialization of functions if(options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; // Do not serialize the undefined fields if(options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; try { // Create write command var cmd = new Query(bson, f("%s.$cmd", d), writeCommand, queryOptions); // Execute command pool.write(cmd, opts, callback); } catch(err) { callback(err); } } // // Needs to support legacy mass insert as well as ordered/unordered legacy // emulation // WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) { executeWrite(pool, bson, 'insert', 'documents', ns, ops, options, callback); } WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) { executeWrite(pool, bson, 'update', 'updates', ns, ops, options, callback); } WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) { executeWrite(pool, bson, 'delete', 'deletes', ns, ops, options, callback); } WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callback) { // Build command namespace var parts = ns.split(/\./); // Command namespace var commandns = f('%s.$cmd', parts.shift()); // Create getMore command var killcursorCmd = { killCursors: parts.join('.'), cursors: [cursorId] } // Build Query object var query = new Query(bson, commandns, killcursorCmd, { numberToSkip: 0, numberToReturn: -1 , checkKeys: false, returnFieldSelector: null }); // Set query flags query.slaveOk = true; // Kill cursor callback var killCursorCallback = function(err, result) { if(err) { if(typeof callback != 'function') return; return callback(err); } // Result var r = result.message; // If we have a timed out query or a cursor that was killed if((r.responseFlags & (1 << 0)) != 0) { if(typeof callback != 'function') return; return callback(new MongoError("cursor killed or timed out"), null); } if(!Array.isArray(r.documents) || r.documents.length == 0) { if(typeof callback != 'function') return; return callback(new MongoError(f('invalid killCursors result returned for cursor id %s', cursorId))); } // Return the result if(typeof callback == 'function') { callback(null, r.documents[0]); } } // Execute the kill cursor command if(pool && pool.isConnected()) { pool.write(query, { command: true }, killCursorCallback); } } WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, options, callback) { options = options || {}; // Build command namespace var parts = ns.split(/\./); // Command namespace var commandns = f('%s.$cmd', parts.shift()); // Create getMore command var getMoreCmd = { getMore: cursorState.cursorId, collection: parts.join('.'), batchSize: Math.abs(batchSize) } if(cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS == 'number') { getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; } // Build Query object var query = new Query(bson, commandns, getMoreCmd, { numberToSkip: 0, numberToReturn: -1 , checkKeys: false, returnFieldSelector: null }); // Set query flags query.slaveOk = true; // Query callback var queryCallback = function(err, result) { if(err) return callback(err); // Get the raw message var r = result.message; // If we have a timed out query or a cursor that was killed if((r.responseFlags & (1 << 0)) != 0) { return callback(new MongoError("cursor killed or timed out"), null); } // Raw, return all the extracted documents if(raw) { cursorState.documents = r.documents; cursorState.cursorId = r.cursorId; return callback(null, r.documents); } // We have an error detected if(r.documents[0].ok == 0) { return callback(MongoError.create(r.documents[0])); } // Ensure we have a Long valid cursor id var cursorId = typeof r.documents[0].cursor.id == 'number' ? Long.fromNumber(r.documents[0].cursor.id) : r.documents[0].cursor.id; // Set all the values cursorState.documents = r.documents[0].cursor.nextBatch; cursorState.cursorId = cursorId; // Return the result callback(null, r.documents[0], r.connection); } // Query options var queryOptions = { command: true }; // If we have a raw query decorate the function if(raw) { queryOptions.raw = raw; } // Add the result field needed queryOptions.documentsReturnedIn = 'nextBatch'; // Check if we need to promote longs if(typeof cursorState.promoteLongs == 'boolean') { queryOptions.promoteLongs = cursorState.promoteLongs; } if(typeof cursorState.promoteValues == 'boolean') { queryCallback.promoteValues = cursorState.promoteValues; } if(typeof cursorState.promoteBuffers == 'boolean') { queryCallback.promoteBuffers = cursorState.promoteBuffers; } // Write out the getMore command connection.write(query, queryOptions, queryCallback); } WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { // Establish type of command if(cmd.find) { // Create the find command var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options) // Mark the cmd as virtual cmd.virtual = false; // Signal the documents are in the firstBatch value query.documentsReturnedIn = 'firstBatch'; // Return the query return query; } else if(cursorState.cursorId != null) { return; } else if(cmd) { return setupCommand(bson, ns, cmd, cursorState, topology, options); } else { throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); } } // // Command // { // find: ns // , query: <object> // , limit: <n> // , fields: <object> // , skip: <n> // , hint: <string> // , explain: <boolean> // , snapshot: <boolean> // , batchSize: <n> // , returnKey: <boolean> // , maxScan: <n> // , min: <n> // , max: <n> // , showDiskLoc: <boolean> // , comment: <string> // , maxTimeMS: <n> // , raw: <boolean> // , readPreference: <ReadPreference> // , tailable: <boolean> // , oplogReplay: <boolean> // , noCursorTimeout: <boolean> // , awaitdata: <boolean> // , exhaust: <boolean> // , partial: <boolean> // } // FIND/GETMORE SPEC // { // “find”: <string>, // “filter”: { ... }, // “sort”: { ... }, // “projection”: { ... }, // “hint”: { ... }, // “skip”: <int>, // “limit”: <int>, // “batchSize”: <int>, // “singleBatch”: <bool>, // “comment”: <string>, // “maxScan”: <int>, // “maxTimeMS”: <int>, // “max”: { ... }, // “min”: { ... }, // “returnKey”: <bool>, // “showRecordId”: <bool>, // “snapshot”: <bool>, // “tailable”: <bool>, // “oplogReplay”: <bool>, // “noCursorTimeout”: <bool>, // “awaitData”: <bool>, // “partial”: <bool>, // “$readPreference”: { ... } // } // // Execute a find command var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { // Ensure we have at least some options options = options || {}; // Get the readPreference var readPreference = getReadPreference(cmd, options); // Set the optional batchSize cursorState.batchSize = cmd.batchSize || cursorState.batchSize; // Build command namespace var parts = ns.split(/\./); // Command namespace var commandns = f('%s.$cmd', parts.shift()); // Build actual find command var findCmd = { find: parts.join('.') }; // I we provided a filter if(cmd.query) { // Check if the user is passing in the $query parameter if(cmd.query['$query']) { findCmd.filter = cmd.query['$query']; } else { findCmd.filter = cmd.query; } } // Sort value var sortValue = cmd.sort; // Handle issue of sort being an Array if(Array.isArray(sortValue)) { var sortObject = {}; if(sortValue.length > 0 && !Array.isArray(sortValue[0])) { var sortDirection = sortValue[1]; // Translate the sort order text if(sortDirection == 'asc') { sortDirection = 1; } else if(sortDirection == 'desc') { sortDirection = -1; } // Set the sort order sortObject[sortValue[0]] = sortDirection; } else { for(var i = 0; i < sortValue.length; i++) { sortDirection = sortValue[i][1]; // Translate the sort order text if(sortDirection == 'asc') { sortDirection = 1; } else if(sortDirection == 'desc') { sortDirection = -1; } // Set the sort order sortObject[sortValue[i][0]] = sortDirection; } } sortValue = sortObject; } // Add sort to command if(cmd.sort) findCmd.sort = sortValue; // Add a projection to the command if(cmd.fields) findCmd.projection = cmd.fields; // Add a hint to the command if(cmd.hint) findCmd.hint = cmd.hint; // Add a skip if(cmd.skip) findCmd.skip = cmd.skip; // Add a limit if(cmd.limit) findCmd.limit = cmd.limit; // Add a batchSize if(typeof cmd.batchSize == 'number') findCmd.batchSize = Math.abs(cmd.batchSize); // Check if we wish to have a singleBatch if(cmd.limit < 0) { findCmd.limit = Math.abs(cmd.limit); findCmd.singleBatch = true; } // If we have comment set if(cmd.comment) findCmd.comment = cmd.comment; // If we have maxScan if(cmd.maxScan) findCmd.maxScan = cmd.maxScan; // If we have maxTimeMS set if(cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; // If we have min if(cmd.min) findCmd.min = cmd.min; // If we have max if(cmd.max) findCmd.max = cmd.max; // If we have returnKey set if(cmd.returnKey) findCmd.returnKey = cmd.returnKey; // If we have showDiskLoc set if(cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; // If we have snapshot set if(cmd.snapshot) findCmd.snapshot = cmd.snapshot; // If we have tailable set if(cmd.tailable) findCmd.tailable = cmd.tailable; // If we have oplogReplay set if(cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; // If we have noCursorTimeout set if(cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; // If we have awaitData set if(cmd.awaitData) findCmd.awaitData = cmd.awaitData; if(cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; // If we have partial set if(cmd.partial) findCmd.partial = cmd.partial; // If we have collation passed in if(cmd.collation) findCmd.collation = cmd.collation; // If we have explain, we need to rewrite the find command // to wrap it in the explain command if(cmd.explain) { findCmd = { explain: findCmd } } // Did we provide a readConcern if(cmd.readConcern) findCmd.readConcern = cmd.readConcern; // Set up the serialize and ignoreUndefined fields var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; // We have a Mongos topology, check if we need to add a readPreference if(topology.type == 'mongos' && readPreference && readPreference.preference != 'primary') { findCmd = { '$query': findCmd, '$readPreference': readPreference.toJSON() }; } // Build Query object var query = new Query(bson, commandns, findCmd, { numberToSkip: 0, numberToReturn: 1 , checkKeys: false, returnFieldSelector: null , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined }); // Set query flags query.slaveOk = readPreference.slaveOk(); // Return the query return query; } // // Set up a command cursor var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { // Set empty options object options = options || {} // Get the readPreference var readPreference = getReadPreference(cmd, options); // Final query var finalCmd = {}; for(var name in cmd) { finalCmd[name] = cmd[name]; } // Build command namespace var parts = ns.split(/\./); // Serialize functions var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; // Set up the serialize and ignoreUndefined fields var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; // We have a Mongos topology, check if we need to add a readPreference if(topology.type == 'mongos' && readPreference && readPreference.preference != 'primary') { finalCmd = { '$query': finalCmd, '$readPreference': readPreference.toJSON() }; } // Build Query object var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { numberToSkip: 0, numberToReturn: -1 , checkKeys: false, serializeFunctions: serializeFunctions , ignoreUndefined: ignoreUndefined }); // Set query flags query.slaveOk = readPreference.slaveOk(); // Return the query return query; } module.exports = WireProtocol;
/** * Text range module for Rangy. * Text-based manipulation and searching of ranges and selections. * * Features * * - Ability to move range boundaries by character or word offsets * - Customizable word tokenizer * - Ignores text nodes inside <script> or <style> elements or those hidden by CSS display and visibility properties * - Range findText method to search for text or regex within the page or within a range. Flags for whole words and case * sensitivity * - Selection and range save/restore as text offsets within a node * - Methods to return visible text within a range or selection * - innerText method for elements * * References * * https://www.w3.org/Bugs/Public/show_bug.cgi?id=13145 * http://aryeh.name/spec/innertext/innertext.html * http://dvcs.w3.org/hg/editing/raw-file/tip/editing.html * * Part of Rangy, a cross-browser JavaScript range and selection library * https://github.com/timdown/rangy * * Depends on Rangy core. * * Copyright 2015, Tim Down * Licensed under the MIT license. * Version: 1.3.0 * Build date: 10 May 2015 */ /** * Problem: handling of trailing spaces before line breaks is handled inconsistently between browsers. * * First, a <br>: this is relatively simple. For the following HTML: * * 1 <br>2 * * - IE and WebKit render the space, include it in the selection (i.e. when the content is selected and pasted into a * textarea, the space is present) and allow the caret to be placed after it. * - Firefox does not acknowledge the space in the selection but it is possible to place the caret after it. * - Opera does not render the space but has two separate caret positions on either side of the space (left and right * arrow keys show this) and includes the space in the selection. * * The other case is the line break or breaks implied by block elements. For the following HTML: * * <p>1 </p><p>2<p> * * - WebKit does not acknowledge the space in any way * - Firefox, IE and Opera as per <br> * * One more case is trailing spaces before line breaks in elements with white-space: pre-line. For the following HTML: * * <p style="white-space: pre-line">1 * 2</p> * * - Firefox and WebKit include the space in caret positions * - IE does not support pre-line up to and including version 9 * - Opera ignores the space * - Trailing space only renders if there is a non-collapsed character in the line * * Problem is whether Rangy should ever acknowledge the space and if so, when. Another problem is whether this can be * feature-tested */ (function(factory, root) { if (typeof define == "function" && define.amd) { // AMD. Register as an anonymous module with a dependency on Rangy. define(["./rangy-core"], factory); } else if (typeof module != "undefined" && typeof exports == "object") { // Node/CommonJS style module.exports = factory( require("rangy") ); } else { // No AMD or CommonJS support so we use the rangy property of root (probably the global variable) factory(root.rangy); } })(function(rangy) { rangy.createModule("TextRange", ["WrappedSelection"], function(api, module) { var UNDEF = "undefined"; var CHARACTER = "character", WORD = "word"; var dom = api.dom, util = api.util; var extend = util.extend; var createOptions = util.createOptions; var getBody = dom.getBody; var spacesRegex = /^[ \t\f\r\n]+$/; var spacesMinusLineBreaksRegex = /^[ \t\f\r]+$/; var allWhiteSpaceRegex = /^[\t-\r \u0085\u00A0\u1680\u180E\u2000-\u200B\u2028\u2029\u202F\u205F\u3000]+$/; var nonLineBreakWhiteSpaceRegex = /^[\t \u00A0\u1680\u180E\u2000-\u200B\u202F\u205F\u3000]+$/; var lineBreakRegex = /^[\n-\r\u0085\u2028\u2029]$/; var defaultLanguage = "en"; var isDirectionBackward = api.Selection.isDirectionBackward; // Properties representing whether trailing spaces inside blocks are completely collapsed (as they are in WebKit, // but not other browsers). Also test whether trailing spaces before <br> elements are collapsed. var trailingSpaceInBlockCollapses = false; var trailingSpaceBeforeBrCollapses = false; var trailingSpaceBeforeBlockCollapses = false; var trailingSpaceBeforeLineBreakInPreLineCollapses = true; (function() { var el = dom.createTestElement(document, "<p>1 </p><p></p>", true); var p = el.firstChild; var sel = api.getSelection(); sel.collapse(p.lastChild, 2); sel.setStart(p.firstChild, 0); trailingSpaceInBlockCollapses = ("" + sel).length == 1; el.innerHTML = "1 <br />"; sel.collapse(el, 2); sel.setStart(el.firstChild, 0); trailingSpaceBeforeBrCollapses = ("" + sel).length == 1; el.innerHTML = "1 <p>1</p>"; sel.collapse(el, 2); sel.setStart(el.firstChild, 0); trailingSpaceBeforeBlockCollapses = ("" + sel).length == 1; dom.removeNode(el); sel.removeAllRanges(); })(); /*----------------------------------------------------------------------------------------------------------------*/ // This function must create word and non-word tokens for the whole of the text supplied to it function defaultTokenizer(chars, wordOptions) { var word = chars.join(""), result, tokenRanges = []; function createTokenRange(start, end, isWord) { tokenRanges.push( { start: start, end: end, isWord: isWord } ); } // Match words and mark characters var lastWordEnd = 0, wordStart, wordEnd; while ( (result = wordOptions.wordRegex.exec(word)) ) { wordStart = result.index; wordEnd = wordStart + result[0].length; // Create token for non-word characters preceding this word if (wordStart > lastWordEnd) { createTokenRange(lastWordEnd, wordStart, false); } // Get trailing space characters for word if (wordOptions.includeTrailingSpace) { while ( nonLineBreakWhiteSpaceRegex.test(chars[wordEnd]) ) { ++wordEnd; } } createTokenRange(wordStart, wordEnd, true); lastWordEnd = wordEnd; } // Create token for trailing non-word characters, if any exist if (lastWordEnd < chars.length) { createTokenRange(lastWordEnd, chars.length, false); } return tokenRanges; } function convertCharRangeToToken(chars, tokenRange) { var tokenChars = chars.slice(tokenRange.start, tokenRange.end); var token = { isWord: tokenRange.isWord, chars: tokenChars, toString: function() { return tokenChars.join(""); } }; for (var i = 0, len = tokenChars.length; i < len; ++i) { tokenChars[i].token = token; } return token; } function tokenize(chars, wordOptions, tokenizer) { var tokenRanges = tokenizer(chars, wordOptions); var tokens = []; for (var i = 0, tokenRange; tokenRange = tokenRanges[i++]; ) { tokens.push( convertCharRangeToToken(chars, tokenRange) ); } return tokens; } var defaultCharacterOptions = { includeBlockContentTrailingSpace: true, includeSpaceBeforeBr: true, includeSpaceBeforeBlock: true, includePreLineTrailingSpace: true, ignoreCharacters: "" }; function normalizeIgnoredCharacters(ignoredCharacters) { // Check if character is ignored var ignoredChars = ignoredCharacters || ""; // Normalize ignored characters into a string consisting of characters in ascending order of character code var ignoredCharsArray = (typeof ignoredChars == "string") ? ignoredChars.split("") : ignoredChars; ignoredCharsArray.sort(function(char1, char2) { return char1.charCodeAt(0) - char2.charCodeAt(0); }); /// Convert back to a string and remove duplicates return ignoredCharsArray.join("").replace(/(.)\1+/g, "$1"); } var defaultCaretCharacterOptions = { includeBlockContentTrailingSpace: !trailingSpaceBeforeLineBreakInPreLineCollapses, includeSpaceBeforeBr: !trailingSpaceBeforeBrCollapses, includeSpaceBeforeBlock: !trailingSpaceBeforeBlockCollapses, includePreLineTrailingSpace: true }; var defaultWordOptions = { "en": { wordRegex: /[a-z0-9]+('[a-z0-9]+)*/gi, includeTrailingSpace: false, tokenizer: defaultTokenizer } }; var defaultFindOptions = { caseSensitive: false, withinRange: null, wholeWordsOnly: false, wrap: false, direction: "forward", wordOptions: null, characterOptions: null }; var defaultMoveOptions = { wordOptions: null, characterOptions: null }; var defaultExpandOptions = { wordOptions: null, characterOptions: null, trim: false, trimStart: true, trimEnd: true }; var defaultWordIteratorOptions = { wordOptions: null, characterOptions: null, direction: "forward" }; function createWordOptions(options) { var lang, defaults; if (!options) { return defaultWordOptions[defaultLanguage]; } else { lang = options.language || defaultLanguage; defaults = {}; extend(defaults, defaultWordOptions[lang] || defaultWordOptions[defaultLanguage]); extend(defaults, options); return defaults; } } function createNestedOptions(optionsParam, defaults) { var options = createOptions(optionsParam, defaults); if (defaults.hasOwnProperty("wordOptions")) { options.wordOptions = createWordOptions(options.wordOptions); } if (defaults.hasOwnProperty("characterOptions")) { options.characterOptions = createOptions(options.characterOptions, defaultCharacterOptions); } return options; } /*----------------------------------------------------------------------------------------------------------------*/ /* DOM utility functions */ var getComputedStyleProperty = dom.getComputedStyleProperty; // Create cachable versions of DOM functions // Test for old IE's incorrect display properties var tableCssDisplayBlock; (function() { var table = document.createElement("table"); var body = getBody(document); body.appendChild(table); tableCssDisplayBlock = (getComputedStyleProperty(table, "display") == "block"); body.removeChild(table); })(); var defaultDisplayValueForTag = { table: "table", caption: "table-caption", colgroup: "table-column-group", col: "table-column", thead: "table-header-group", tbody: "table-row-group", tfoot: "table-footer-group", tr: "table-row", td: "table-cell", th: "table-cell" }; // Corrects IE's "block" value for table-related elements function getComputedDisplay(el, win) { var display = getComputedStyleProperty(el, "display", win); var tagName = el.tagName.toLowerCase(); return (display == "block" && tableCssDisplayBlock && defaultDisplayValueForTag.hasOwnProperty(tagName)) ? defaultDisplayValueForTag[tagName] : display; } function isHidden(node) { var ancestors = getAncestorsAndSelf(node); for (var i = 0, len = ancestors.length; i < len; ++i) { if (ancestors[i].nodeType == 1 && getComputedDisplay(ancestors[i]) == "none") { return true; } } return false; } function isVisibilityHiddenTextNode(textNode) { var el; return textNode.nodeType == 3 && (el = textNode.parentNode) && getComputedStyleProperty(el, "visibility") == "hidden"; } /*----------------------------------------------------------------------------------------------------------------*/ // "A block node is either an Element whose "display" property does not have // resolved value "inline" or "inline-block" or "inline-table" or "none", or a // Document, or a DocumentFragment." function isBlockNode(node) { return node && ((node.nodeType == 1 && !/^(inline(-block|-table)?|none)$/.test(getComputedDisplay(node))) || node.nodeType == 9 || node.nodeType == 11); } function getLastDescendantOrSelf(node) { var lastChild = node.lastChild; return lastChild ? getLastDescendantOrSelf(lastChild) : node; } function containsPositions(node) { return dom.isCharacterDataNode(node) || !/^(area|base|basefont|br|col|frame|hr|img|input|isindex|link|meta|param)$/i.test(node.nodeName); } function getAncestors(node) { var ancestors = []; while (node.parentNode) { ancestors.unshift(node.parentNode); node = node.parentNode; } return ancestors; } function getAncestorsAndSelf(node) { return getAncestors(node).concat([node]); } function nextNodeDescendants(node) { while (node && !node.nextSibling) { node = node.parentNode; } if (!node) { return null; } return node.nextSibling; } function nextNode(node, excludeChildren) { if (!excludeChildren && node.hasChildNodes()) { return node.firstChild; } return nextNodeDescendants(node); } function previousNode(node) { var previous = node.previousSibling; if (previous) { node = previous; while (node.hasChildNodes()) { node = node.lastChild; } return node; } var parent = node.parentNode; if (parent && parent.nodeType == 1) { return parent; } return null; } // Adpated from Aryeh's code. // "A whitespace node is either a Text node whose data is the empty string; or // a Text node whose data consists only of one or more tabs (0x0009), line // feeds (0x000A), carriage returns (0x000D), and/or spaces (0x0020), and whose // parent is an Element whose resolved value for "white-space" is "normal" or // "nowrap"; or a Text node whose data consists only of one or more tabs // (0x0009), carriage returns (0x000D), and/or spaces (0x0020), and whose // parent is an Element whose resolved value for "white-space" is "pre-line"." function isWhitespaceNode(node) { if (!node || node.nodeType != 3) { return false; } var text = node.data; if (text === "") { return true; } var parent = node.parentNode; if (!parent || parent.nodeType != 1) { return false; } var computedWhiteSpace = getComputedStyleProperty(node.parentNode, "whiteSpace"); return (/^[\t\n\r ]+$/.test(text) && /^(normal|nowrap)$/.test(computedWhiteSpace)) || (/^[\t\r ]+$/.test(text) && computedWhiteSpace == "pre-line"); } // Adpated from Aryeh's code. // "node is a collapsed whitespace node if the following algorithm returns // true:" function isCollapsedWhitespaceNode(node) { // "If node's data is the empty string, return true." if (node.data === "") { return true; } // "If node is not a whitespace node, return false." if (!isWhitespaceNode(node)) { return false; } // "Let ancestor be node's parent." var ancestor = node.parentNode; // "If ancestor is null, return true." if (!ancestor) { return true; } // "If the "display" property of some ancestor of node has resolved value "none", return true." if (isHidden(node)) { return true; } return false; } function isCollapsedNode(node) { var type = node.nodeType; return type == 7 /* PROCESSING_INSTRUCTION */ || type == 8 /* COMMENT */ || isHidden(node) || /^(script|style)$/i.test(node.nodeName) || isVisibilityHiddenTextNode(node) || isCollapsedWhitespaceNode(node); } function isIgnoredNode(node, win) { var type = node.nodeType; return type == 7 /* PROCESSING_INSTRUCTION */ || type == 8 /* COMMENT */ || (type == 1 && getComputedDisplay(node, win) == "none"); } /*----------------------------------------------------------------------------------------------------------------*/ // Possibly overengineered caching system to prevent repeated DOM calls slowing everything down function Cache() { this.store = {}; } Cache.prototype = { get: function(key) { return this.store.hasOwnProperty(key) ? this.store[key] : null; }, set: function(key, value) { return this.store[key] = value; } }; var cachedCount = 0, uncachedCount = 0; function createCachingGetter(methodName, func, objProperty) { return function(args) { var cache = this.cache; if (cache.hasOwnProperty(methodName)) { cachedCount++; return cache[methodName]; } else { uncachedCount++; var value = func.call(this, objProperty ? this[objProperty] : this, args); cache[methodName] = value; return value; } }; } /*----------------------------------------------------------------------------------------------------------------*/ function NodeWrapper(node, session) { this.node = node; this.session = session; this.cache = new Cache(); this.positions = new Cache(); } var nodeProto = { getPosition: function(offset) { var positions = this.positions; return positions.get(offset) || positions.set(offset, new Position(this, offset)); }, toString: function() { return "[NodeWrapper(" + dom.inspectNode(this.node) + ")]"; } }; NodeWrapper.prototype = nodeProto; var EMPTY = "EMPTY", NON_SPACE = "NON_SPACE", UNCOLLAPSIBLE_SPACE = "UNCOLLAPSIBLE_SPACE", COLLAPSIBLE_SPACE = "COLLAPSIBLE_SPACE", TRAILING_SPACE_BEFORE_BLOCK = "TRAILING_SPACE_BEFORE_BLOCK", TRAILING_SPACE_IN_BLOCK = "TRAILING_SPACE_IN_BLOCK", TRAILING_SPACE_BEFORE_BR = "TRAILING_SPACE_BEFORE_BR", PRE_LINE_TRAILING_SPACE_BEFORE_LINE_BREAK = "PRE_LINE_TRAILING_SPACE_BEFORE_LINE_BREAK", TRAILING_LINE_BREAK_AFTER_BR = "TRAILING_LINE_BREAK_AFTER_BR", INCLUDED_TRAILING_LINE_BREAK_AFTER_BR = "INCLUDED_TRAILING_LINE_BREAK_AFTER_BR"; extend(nodeProto, { isCharacterDataNode: createCachingGetter("isCharacterDataNode", dom.isCharacterDataNode, "node"), getNodeIndex: createCachingGetter("nodeIndex", dom.getNodeIndex, "node"), getLength: createCachingGetter("nodeLength", dom.getNodeLength, "node"), containsPositions: createCachingGetter("containsPositions", containsPositions, "node"), isWhitespace: createCachingGetter("isWhitespace", isWhitespaceNode, "node"), isCollapsedWhitespace: createCachingGetter("isCollapsedWhitespace", isCollapsedWhitespaceNode, "node"), getComputedDisplay: createCachingGetter("computedDisplay", getComputedDisplay, "node"), isCollapsed: createCachingGetter("collapsed", isCollapsedNode, "node"), isIgnored: createCachingGetter("ignored", isIgnoredNode, "node"), next: createCachingGetter("nextPos", nextNode, "node"), previous: createCachingGetter("previous", previousNode, "node"), getTextNodeInfo: createCachingGetter("textNodeInfo", function(textNode) { var spaceRegex = null, collapseSpaces = false; var cssWhitespace = getComputedStyleProperty(textNode.parentNode, "whiteSpace"); var preLine = (cssWhitespace == "pre-line"); if (preLine) { spaceRegex = spacesMinusLineBreaksRegex; collapseSpaces = true; } else if (cssWhitespace == "normal" || cssWhitespace == "nowrap") { spaceRegex = spacesRegex; collapseSpaces = true; } return { node: textNode, text: textNode.data, spaceRegex: spaceRegex, collapseSpaces: collapseSpaces, preLine: preLine }; }, "node"), hasInnerText: createCachingGetter("hasInnerText", function(el, backward) { var session = this.session; var posAfterEl = session.getPosition(el.parentNode, this.getNodeIndex() + 1); var firstPosInEl = session.getPosition(el, 0); var pos = backward ? posAfterEl : firstPosInEl; var endPos = backward ? firstPosInEl : posAfterEl; /* <body><p>X </p><p>Y</p></body> Positions: body:0:"" p:0:"" text:0:"" text:1:"X" text:2:TRAILING_SPACE_IN_BLOCK text:3:COLLAPSED_SPACE p:1:"" body:1:"\n" p:0:"" text:0:"" text:1:"Y" A character is a TRAILING_SPACE_IN_BLOCK iff: - There is no uncollapsed character after it within the visible containing block element A character is a TRAILING_SPACE_BEFORE_BR iff: - There is no uncollapsed character after it preceding a <br> element An element has inner text iff - It is not hidden - It contains an uncollapsed character All trailing spaces (pre-line, before <br>, end of block) require definite non-empty characters to render. */ while (pos !== endPos) { pos.prepopulateChar(); if (pos.isDefinitelyNonEmpty()) { return true; } pos = backward ? pos.previousVisible() : pos.nextVisible(); } return false; }, "node"), isRenderedBlock: createCachingGetter("isRenderedBlock", function(el) { // Ensure that a block element containing a <br> is considered to have inner text var brs = el.getElementsByTagName("br"); for (var i = 0, len = brs.length; i < len; ++i) { if (!isCollapsedNode(brs[i])) { return true; } } return this.hasInnerText(); }, "node"), getTrailingSpace: createCachingGetter("trailingSpace", function(el) { if (el.tagName.toLowerCase() == "br") { return ""; } else { switch (this.getComputedDisplay()) { case "inline": var child = el.lastChild; while (child) { if (!isIgnoredNode(child)) { return (child.nodeType == 1) ? this.session.getNodeWrapper(child).getTrailingSpace() : ""; } child = child.previousSibling; } break; case "inline-block": case "inline-table": case "none": case "table-column": case "table-column-group": break; case "table-cell": return "\t"; default: return this.isRenderedBlock(true) ? "\n" : ""; } } return ""; }, "node"), getLeadingSpace: createCachingGetter("leadingSpace", function(el) { switch (this.getComputedDisplay()) { case "inline": case "inline-block": case "inline-table": case "none": case "table-column": case "table-column-group": case "table-cell": break; default: return this.isRenderedBlock(false) ? "\n" : ""; } return ""; }, "node") }); /*----------------------------------------------------------------------------------------------------------------*/ function Position(nodeWrapper, offset) { this.offset = offset; this.nodeWrapper = nodeWrapper; this.node = nodeWrapper.node; this.session = nodeWrapper.session; this.cache = new Cache(); } function inspectPosition() { return "[Position(" + dom.inspectNode(this.node) + ":" + this.offset + ")]"; } var positionProto = { character: "", characterType: EMPTY, isBr: false, /* This method: - Fully populates positions that have characters that can be determined independently of any other characters. - Populates most types of space positions with a provisional character. The character is finalized later. */ prepopulateChar: function() { var pos = this; if (!pos.prepopulatedChar) { var node = pos.node, offset = pos.offset; var visibleChar = "", charType = EMPTY; var finalizedChar = false; if (offset > 0) { if (node.nodeType == 3) { var text = node.data; var textChar = text.charAt(offset - 1); var nodeInfo = pos.nodeWrapper.getTextNodeInfo(); var spaceRegex = nodeInfo.spaceRegex; if (nodeInfo.collapseSpaces) { if (spaceRegex.test(textChar)) { // "If the character at position is from set, append a single space (U+0020) to newdata and advance // position until the character at position is not from set." // We also need to check for the case where we're in a pre-line and we have a space preceding a // line break, because such spaces are collapsed in some browsers if (offset > 1 && spaceRegex.test(text.charAt(offset - 2))) { } else if (nodeInfo.preLine && text.charAt(offset) === "\n") { visibleChar = " "; charType = PRE_LINE_TRAILING_SPACE_BEFORE_LINE_BREAK; } else { visibleChar = " "; //pos.checkForFollowingLineBreak = true; charType = COLLAPSIBLE_SPACE; } } else { visibleChar = textChar; charType = NON_SPACE; finalizedChar = true; } } else { visibleChar = textChar; charType = UNCOLLAPSIBLE_SPACE; finalizedChar = true; } } else { var nodePassed = node.childNodes[offset - 1]; if (nodePassed && nodePassed.nodeType == 1 && !isCollapsedNode(nodePassed)) { if (nodePassed.tagName.toLowerCase() == "br") { visibleChar = "\n"; pos.isBr = true; charType = COLLAPSIBLE_SPACE; finalizedChar = false; } else { pos.checkForTrailingSpace = true; } } // Check the leading space of the next node for the case when a block element follows an inline // element or text node. In that case, there is an implied line break between the two nodes. if (!visibleChar) { var nextNode = node.childNodes[offset]; if (nextNode && nextNode.nodeType == 1 && !isCollapsedNode(nextNode)) { pos.checkForLeadingSpace = true; } } } } pos.prepopulatedChar = true; pos.character = visibleChar; pos.characterType = charType; pos.isCharInvariant = finalizedChar; } }, isDefinitelyNonEmpty: function() { var charType = this.characterType; return charType == NON_SPACE || charType == UNCOLLAPSIBLE_SPACE; }, // Resolve leading and trailing spaces, which may involve prepopulating other positions resolveLeadingAndTrailingSpaces: function() { if (!this.prepopulatedChar) { this.prepopulateChar(); } if (this.checkForTrailingSpace) { var trailingSpace = this.session.getNodeWrapper(this.node.childNodes[this.offset - 1]).getTrailingSpace(); if (trailingSpace) { this.isTrailingSpace = true; this.character = trailingSpace; this.characterType = COLLAPSIBLE_SPACE; } this.checkForTrailingSpace = false; } if (this.checkForLeadingSpace) { var leadingSpace = this.session.getNodeWrapper(this.node.childNodes[this.offset]).getLeadingSpace(); if (leadingSpace) { this.isLeadingSpace = true; this.character = leadingSpace; this.characterType = COLLAPSIBLE_SPACE; } this.checkForLeadingSpace = false; } }, getPrecedingUncollapsedPosition: function(characterOptions) { var pos = this, character; while ( (pos = pos.previousVisible()) ) { character = pos.getCharacter(characterOptions); if (character !== "") { return pos; } } return null; }, getCharacter: function(characterOptions) { this.resolveLeadingAndTrailingSpaces(); var thisChar = this.character, returnChar; // Check if character is ignored var ignoredChars = normalizeIgnoredCharacters(characterOptions.ignoreCharacters); var isIgnoredCharacter = (thisChar !== "" && ignoredChars.indexOf(thisChar) > -1); // Check if this position's character is invariant (i.e. not dependent on character options) and return it // if so if (this.isCharInvariant) { returnChar = isIgnoredCharacter ? "" : thisChar; return returnChar; } var cacheKey = ["character", characterOptions.includeSpaceBeforeBr, characterOptions.includeBlockContentTrailingSpace, characterOptions.includePreLineTrailingSpace, ignoredChars].join("_"); var cachedChar = this.cache.get(cacheKey); if (cachedChar !== null) { return cachedChar; } // We need to actually get the character now var character = ""; var collapsible = (this.characterType == COLLAPSIBLE_SPACE); var nextPos, previousPos; var gotPreviousPos = false; var pos = this; function getPreviousPos() { if (!gotPreviousPos) { previousPos = pos.getPrecedingUncollapsedPosition(characterOptions); gotPreviousPos = true; } return previousPos; } // Disallow a collapsible space that is followed by a line break or is the last character if (collapsible) { // Allow a trailing space that we've previously determined should be included if (this.type == INCLUDED_TRAILING_LINE_BREAK_AFTER_BR) { character = "\n"; } // Disallow a collapsible space that follows a trailing space or line break, or is the first character, // or follows a collapsible included space else if (thisChar == " " && (!getPreviousPos() || previousPos.isTrailingSpace || previousPos.character == "\n" || (previousPos.character == " " && previousPos.characterType == COLLAPSIBLE_SPACE))) { } // Allow a leading line break unless it follows a line break else if (thisChar == "\n" && this.isLeadingSpace) { if (getPreviousPos() && previousPos.character != "\n") { character = "\n"; } else { } } else { nextPos = this.nextUncollapsed(); if (nextPos) { if (nextPos.isBr) { this.type = TRAILING_SPACE_BEFORE_BR; } else if (nextPos.isTrailingSpace && nextPos.character == "\n") { this.type = TRAILING_SPACE_IN_BLOCK; } else if (nextPos.isLeadingSpace && nextPos.character == "\n") { this.type = TRAILING_SPACE_BEFORE_BLOCK; } if (nextPos.character == "\n") { if (this.type == TRAILING_SPACE_BEFORE_BR && !characterOptions.includeSpaceBeforeBr) { } else if (this.type == TRAILING_SPACE_BEFORE_BLOCK && !characterOptions.includeSpaceBeforeBlock) { } else if (this.type == TRAILING_SPACE_IN_BLOCK && nextPos.isTrailingSpace && !characterOptions.includeBlockContentTrailingSpace) { } else if (this.type == PRE_LINE_TRAILING_SPACE_BEFORE_LINE_BREAK && nextPos.type == NON_SPACE && !characterOptions.includePreLineTrailingSpace) { } else if (thisChar == "\n") { if (nextPos.isTrailingSpace) { if (this.isTrailingSpace) { } else if (this.isBr) { nextPos.type = TRAILING_LINE_BREAK_AFTER_BR; if (getPreviousPos() && previousPos.isLeadingSpace && !previousPos.isTrailingSpace && previousPos.character == "\n") { nextPos.character = ""; } else { nextPos.type = INCLUDED_TRAILING_LINE_BREAK_AFTER_BR; } } } else { character = "\n"; } } else if (thisChar == " ") { character = " "; } else { } } else { character = thisChar; } } else { } } } if (ignoredChars.indexOf(character) > -1) { character = ""; } this.cache.set(cacheKey, character); return character; }, equals: function(pos) { return !!pos && this.node === pos.node && this.offset === pos.offset; }, inspect: inspectPosition, toString: function() { return this.character; } }; Position.prototype = positionProto; extend(positionProto, { next: createCachingGetter("nextPos", function(pos) { var nodeWrapper = pos.nodeWrapper, node = pos.node, offset = pos.offset, session = nodeWrapper.session; if (!node) { return null; } var nextNode, nextOffset, child; if (offset == nodeWrapper.getLength()) { // Move onto the next node nextNode = node.parentNode; nextOffset = nextNode ? nodeWrapper.getNodeIndex() + 1 : 0; } else { if (nodeWrapper.isCharacterDataNode()) { nextNode = node; nextOffset = offset + 1; } else { child = node.childNodes[offset]; // Go into the children next, if children there are if (session.getNodeWrapper(child).containsPositions()) { nextNode = child; nextOffset = 0; } else { nextNode = node; nextOffset = offset + 1; } } } return nextNode ? session.getPosition(nextNode, nextOffset) : null; }), previous: createCachingGetter("previous", function(pos) { var nodeWrapper = pos.nodeWrapper, node = pos.node, offset = pos.offset, session = nodeWrapper.session; var previousNode, previousOffset, child; if (offset == 0) { previousNode = node.parentNode; previousOffset = previousNode ? nodeWrapper.getNodeIndex() : 0; } else { if (nodeWrapper.isCharacterDataNode()) { previousNode = node; previousOffset = offset - 1; } else { child = node.childNodes[offset - 1]; // Go into the children next, if children there are if (session.getNodeWrapper(child).containsPositions()) { previousNode = child; previousOffset = dom.getNodeLength(child); } else { previousNode = node; previousOffset = offset - 1; } } } return previousNode ? session.getPosition(previousNode, previousOffset) : null; }), /* Next and previous position moving functions that filter out - Hidden (CSS visibility/display) elements - Script and style elements */ nextVisible: createCachingGetter("nextVisible", function(pos) { var next = pos.next(); if (!next) { return null; } var nodeWrapper = next.nodeWrapper, node = next.node; var newPos = next; if (nodeWrapper.isCollapsed()) { // We're skipping this node and all its descendants newPos = nodeWrapper.session.getPosition(node.parentNode, nodeWrapper.getNodeIndex() + 1); } return newPos; }), nextUncollapsed: createCachingGetter("nextUncollapsed", function(pos) { var nextPos = pos; while ( (nextPos = nextPos.nextVisible()) ) { nextPos.resolveLeadingAndTrailingSpaces(); if (nextPos.character !== "") { return nextPos; } } return null; }), previousVisible: createCachingGetter("previousVisible", function(pos) { var previous = pos.previous(); if (!previous) { return null; } var nodeWrapper = previous.nodeWrapper, node = previous.node; var newPos = previous; if (nodeWrapper.isCollapsed()) { // We're skipping this node and all its descendants newPos = nodeWrapper.session.getPosition(node.parentNode, nodeWrapper.getNodeIndex()); } return newPos; }) }); /*----------------------------------------------------------------------------------------------------------------*/ var currentSession = null; var Session = (function() { function createWrapperCache(nodeProperty) { var cache = new Cache(); return { get: function(node) { var wrappersByProperty = cache.get(node[nodeProperty]); if (wrappersByProperty) { for (var i = 0, wrapper; wrapper = wrappersByProperty[i++]; ) { if (wrapper.node === node) { return wrapper; } } } return null; }, set: function(nodeWrapper) { var property = nodeWrapper.node[nodeProperty]; var wrappersByProperty = cache.get(property) || cache.set(property, []); wrappersByProperty.push(nodeWrapper); } }; } var uniqueIDSupported = util.isHostProperty(document.documentElement, "uniqueID"); function Session() { this.initCaches(); } Session.prototype = { initCaches: function() { this.elementCache = uniqueIDSupported ? (function() { var elementsCache = new Cache(); return { get: function(el) { return elementsCache.get(el.uniqueID); }, set: function(elWrapper) { elementsCache.set(elWrapper.node.uniqueID, elWrapper); } }; })() : createWrapperCache("tagName"); // Store text nodes keyed by data, although we may need to truncate this this.textNodeCache = createWrapperCache("data"); this.otherNodeCache = createWrapperCache("nodeName"); }, getNodeWrapper: function(node) { var wrapperCache; switch (node.nodeType) { case 1: wrapperCache = this.elementCache; break; case 3: wrapperCache = this.textNodeCache; break; default: wrapperCache = this.otherNodeCache; break; } var wrapper = wrapperCache.get(node); if (!wrapper) { wrapper = new NodeWrapper(node, this); wrapperCache.set(wrapper); } return wrapper; }, getPosition: function(node, offset) { return this.getNodeWrapper(node).getPosition(offset); }, getRangeBoundaryPosition: function(range, isStart) { var prefix = isStart ? "start" : "end"; return this.getPosition(range[prefix + "Container"], range[prefix + "Offset"]); }, detach: function() { this.elementCache = this.textNodeCache = this.otherNodeCache = null; } }; return Session; })(); /*----------------------------------------------------------------------------------------------------------------*/ function startSession() { endSession(); return (currentSession = new Session()); } function getSession() { return currentSession || startSession(); } function endSession() { if (currentSession) { currentSession.detach(); } currentSession = null; } /*----------------------------------------------------------------------------------------------------------------*/ // Extensions to the rangy.dom utility object extend(dom, { nextNode: nextNode, previousNode: previousNode }); /*----------------------------------------------------------------------------------------------------------------*/ function createCharacterIterator(startPos, backward, endPos, characterOptions) { // Adjust the end position to ensure that it is actually reached if (endPos) { if (backward) { if (isCollapsedNode(endPos.node)) { endPos = startPos.previousVisible(); } } else { if (isCollapsedNode(endPos.node)) { endPos = endPos.nextVisible(); } } } var pos = startPos, finished = false; function next() { var charPos = null; if (backward) { charPos = pos; if (!finished) { pos = pos.previousVisible(); finished = !pos || (endPos && pos.equals(endPos)); } } else { if (!finished) { charPos = pos = pos.nextVisible(); finished = !pos || (endPos && pos.equals(endPos)); } } if (finished) { pos = null; } return charPos; } var previousTextPos, returnPreviousTextPos = false; return { next: function() { if (returnPreviousTextPos) { returnPreviousTextPos = false; return previousTextPos; } else { var pos, character; while ( (pos = next()) ) { character = pos.getCharacter(characterOptions); if (character) { previousTextPos = pos; return pos; } } return null; } }, rewind: function() { if (previousTextPos) { returnPreviousTextPos = true; } else { throw module.createError("createCharacterIterator: cannot rewind. Only one position can be rewound."); } }, dispose: function() { startPos = endPos = null; } }; } var arrayIndexOf = Array.prototype.indexOf ? function(arr, val) { return arr.indexOf(val); } : function(arr, val) { for (var i = 0, len = arr.length; i < len; ++i) { if (arr[i] === val) { return i; } } return -1; }; // Provides a pair of iterators over text positions, tokenized. Transparently requests more text when next() // is called and there is no more tokenized text function createTokenizedTextProvider(pos, characterOptions, wordOptions) { var forwardIterator = createCharacterIterator(pos, false, null, characterOptions); var backwardIterator = createCharacterIterator(pos, true, null, characterOptions); var tokenizer = wordOptions.tokenizer; // Consumes a word and the whitespace beyond it function consumeWord(forward) { var pos, textChar; var newChars = [], it = forward ? forwardIterator : backwardIterator; var passedWordBoundary = false, insideWord = false; while ( (pos = it.next()) ) { textChar = pos.character; if (allWhiteSpaceRegex.test(textChar)) { if (insideWord) { insideWord = false; passedWordBoundary = true; } } else { if (passedWordBoundary) { it.rewind(); break; } else { insideWord = true; } } newChars.push(pos); } return newChars; } // Get initial word surrounding initial position and tokenize it var forwardChars = consumeWord(true); var backwardChars = consumeWord(false).reverse(); var tokens = tokenize(backwardChars.concat(forwardChars), wordOptions, tokenizer); // Create initial token buffers var forwardTokensBuffer = forwardChars.length ? tokens.slice(arrayIndexOf(tokens, forwardChars[0].token)) : []; var backwardTokensBuffer = backwardChars.length ? tokens.slice(0, arrayIndexOf(tokens, backwardChars.pop().token) + 1) : []; function inspectBuffer(buffer) { var textPositions = ["[" + buffer.length + "]"]; for (var i = 0; i < buffer.length; ++i) { textPositions.push("(word: " + buffer[i] + ", is word: " + buffer[i].isWord + ")"); } return textPositions; } return { nextEndToken: function() { var lastToken, forwardChars; // If we're down to the last token, consume character chunks until we have a word or run out of // characters to consume while ( forwardTokensBuffer.length == 1 && !(lastToken = forwardTokensBuffer[0]).isWord && (forwardChars = consumeWord(true)).length > 0) { // Merge trailing non-word into next word and tokenize forwardTokensBuffer = tokenize(lastToken.chars.concat(forwardChars), wordOptions, tokenizer); } return forwardTokensBuffer.shift(); }, previousStartToken: function() { var lastToken, backwardChars; // If we're down to the last token, consume character chunks until we have a word or run out of // characters to consume while ( backwardTokensBuffer.length == 1 && !(lastToken = backwardTokensBuffer[0]).isWord && (backwardChars = consumeWord(false)).length > 0) { // Merge leading non-word into next word and tokenize backwardTokensBuffer = tokenize(backwardChars.reverse().concat(lastToken.chars), wordOptions, tokenizer); } return backwardTokensBuffer.pop(); }, dispose: function() { forwardIterator.dispose(); backwardIterator.dispose(); forwardTokensBuffer = backwardTokensBuffer = null; } }; } function movePositionBy(pos, unit, count, characterOptions, wordOptions) { var unitsMoved = 0, currentPos, newPos = pos, charIterator, nextPos, absCount = Math.abs(count), token; if (count !== 0) { var backward = (count < 0); switch (unit) { case CHARACTER: charIterator = createCharacterIterator(pos, backward, null, characterOptions); while ( (currentPos = charIterator.next()) && unitsMoved < absCount ) { ++unitsMoved; newPos = currentPos; } nextPos = currentPos; charIterator.dispose(); break; case WORD: var tokenizedTextProvider = createTokenizedTextProvider(pos, characterOptions, wordOptions); var next = backward ? tokenizedTextProvider.previousStartToken : tokenizedTextProvider.nextEndToken; while ( (token = next()) && unitsMoved < absCount ) { if (token.isWord) { ++unitsMoved; newPos = backward ? token.chars[0] : token.chars[token.chars.length - 1]; } } break; default: throw new Error("movePositionBy: unit '" + unit + "' not implemented"); } // Perform any necessary position tweaks if (backward) { newPos = newPos.previousVisible(); unitsMoved = -unitsMoved; } else if (newPos && newPos.isLeadingSpace && !newPos.isTrailingSpace) { // Tweak the position for the case of a leading space. The problem is that an uncollapsed leading space // before a block element (for example, the line break between "1" and "2" in the following HTML: // "1<p>2</p>") is considered to be attached to the position immediately before the block element, which // corresponds with a different selection position in most browsers from the one we want (i.e. at the // start of the contents of the block element). We get round this by advancing the position returned to // the last possible equivalent visible position. if (unit == WORD) { charIterator = createCharacterIterator(pos, false, null, characterOptions); nextPos = charIterator.next(); charIterator.dispose(); } if (nextPos) { newPos = nextPos.previousVisible(); } } } return { position: newPos, unitsMoved: unitsMoved }; } function createRangeCharacterIterator(session, range, characterOptions, backward) { var rangeStart = session.getRangeBoundaryPosition(range, true); var rangeEnd = session.getRangeBoundaryPosition(range, false); var itStart = backward ? rangeEnd : rangeStart; var itEnd = backward ? rangeStart : rangeEnd; return createCharacterIterator(itStart, !!backward, itEnd, characterOptions); } function getRangeCharacters(session, range, characterOptions) { var chars = [], it = createRangeCharacterIterator(session, range, characterOptions), pos; while ( (pos = it.next()) ) { chars.push(pos); } it.dispose(); return chars; } function isWholeWord(startPos, endPos, wordOptions) { var range = api.createRange(startPos.node); range.setStartAndEnd(startPos.node, startPos.offset, endPos.node, endPos.offset); return !range.expand("word", { wordOptions: wordOptions }); } function findTextFromPosition(initialPos, searchTerm, isRegex, searchScopeRange, findOptions) { var backward = isDirectionBackward(findOptions.direction); var it = createCharacterIterator( initialPos, backward, initialPos.session.getRangeBoundaryPosition(searchScopeRange, backward), findOptions.characterOptions ); var text = "", chars = [], pos, currentChar, matchStartIndex, matchEndIndex; var result, insideRegexMatch; var returnValue = null; function handleMatch(startIndex, endIndex) { var startPos = chars[startIndex].previousVisible(); var endPos = chars[endIndex - 1]; var valid = (!findOptions.wholeWordsOnly || isWholeWord(startPos, endPos, findOptions.wordOptions)); return { startPos: startPos, endPos: endPos, valid: valid }; } while ( (pos = it.next()) ) { currentChar = pos.character; if (!isRegex && !findOptions.caseSensitive) { currentChar = currentChar.toLowerCase(); } if (backward) { chars.unshift(pos); text = currentChar + text; } else { chars.push(pos); text += currentChar; } if (isRegex) { result = searchTerm.exec(text); if (result) { matchStartIndex = result.index; matchEndIndex = matchStartIndex + result[0].length; if (insideRegexMatch) { // Check whether the match is now over if ((!backward && matchEndIndex < text.length) || (backward && matchStartIndex > 0)) { returnValue = handleMatch(matchStartIndex, matchEndIndex); break; } } else { insideRegexMatch = true; } } } else if ( (matchStartIndex = text.indexOf(searchTerm)) != -1 ) { returnValue = handleMatch(matchStartIndex, matchStartIndex + searchTerm.length); break; } } // Check whether regex match extends to the end of the range if (insideRegexMatch) { returnValue = handleMatch(matchStartIndex, matchEndIndex); } it.dispose(); return returnValue; } function createEntryPointFunction(func) { return function() { var sessionRunning = !!currentSession; var session = getSession(); var args = [session].concat( util.toArray(arguments) ); var returnValue = func.apply(this, args); if (!sessionRunning) { endSession(); } return returnValue; }; } /*----------------------------------------------------------------------------------------------------------------*/ // Extensions to the Rangy Range object function createRangeBoundaryMover(isStart, collapse) { /* Unit can be "character" or "word" Options: - includeTrailingSpace - wordRegex - tokenizer - collapseSpaceBeforeLineBreak */ return createEntryPointFunction( function(session, unit, count, moveOptions) { if (typeof count == UNDEF) { count = unit; unit = CHARACTER; } moveOptions = createNestedOptions(moveOptions, defaultMoveOptions); var boundaryIsStart = isStart; if (collapse) { boundaryIsStart = (count >= 0); this.collapse(!boundaryIsStart); } var moveResult = movePositionBy(session.getRangeBoundaryPosition(this, boundaryIsStart), unit, count, moveOptions.characterOptions, moveOptions.wordOptions); var newPos = moveResult.position; this[boundaryIsStart ? "setStart" : "setEnd"](newPos.node, newPos.offset); return moveResult.unitsMoved; } ); } function createRangeTrimmer(isStart) { return createEntryPointFunction( function(session, characterOptions) { characterOptions = createOptions(characterOptions, defaultCharacterOptions); var pos; var it = createRangeCharacterIterator(session, this, characterOptions, !isStart); var trimCharCount = 0; while ( (pos = it.next()) && allWhiteSpaceRegex.test(pos.character) ) { ++trimCharCount; } it.dispose(); var trimmed = (trimCharCount > 0); if (trimmed) { this[isStart ? "moveStart" : "moveEnd"]( "character", isStart ? trimCharCount : -trimCharCount, { characterOptions: characterOptions } ); } return trimmed; } ); } extend(api.rangePrototype, { moveStart: createRangeBoundaryMover(true, false), moveEnd: createRangeBoundaryMover(false, false), move: createRangeBoundaryMover(true, true), trimStart: createRangeTrimmer(true), trimEnd: createRangeTrimmer(false), trim: createEntryPointFunction( function(session, characterOptions) { var startTrimmed = this.trimStart(characterOptions), endTrimmed = this.trimEnd(characterOptions); return startTrimmed || endTrimmed; } ), expand: createEntryPointFunction( function(session, unit, expandOptions) { var moved = false; expandOptions = createNestedOptions(expandOptions, defaultExpandOptions); var characterOptions = expandOptions.characterOptions; if (!unit) { unit = CHARACTER; } if (unit == WORD) { var wordOptions = expandOptions.wordOptions; var startPos = session.getRangeBoundaryPosition(this, true); var endPos = session.getRangeBoundaryPosition(this, false); var startTokenizedTextProvider = createTokenizedTextProvider(startPos, characterOptions, wordOptions); var startToken = startTokenizedTextProvider.nextEndToken(); var newStartPos = startToken.chars[0].previousVisible(); var endToken, newEndPos; if (this.collapsed) { endToken = startToken; } else { var endTokenizedTextProvider = createTokenizedTextProvider(endPos, characterOptions, wordOptions); endToken = endTokenizedTextProvider.previousStartToken(); } newEndPos = endToken.chars[endToken.chars.length - 1]; if (!newStartPos.equals(startPos)) { this.setStart(newStartPos.node, newStartPos.offset); moved = true; } if (newEndPos && !newEndPos.equals(endPos)) { this.setEnd(newEndPos.node, newEndPos.offset); moved = true; } if (expandOptions.trim) { if (expandOptions.trimStart) { moved = this.trimStart(characterOptions) || moved; } if (expandOptions.trimEnd) { moved = this.trimEnd(characterOptions) || moved; } } return moved; } else { return this.moveEnd(CHARACTER, 1, expandOptions); } } ), text: createEntryPointFunction( function(session, characterOptions) { return this.collapsed ? "" : getRangeCharacters(session, this, createOptions(characterOptions, defaultCharacterOptions)).join(""); } ), selectCharacters: createEntryPointFunction( function(session, containerNode, startIndex, endIndex, characterOptions) { var moveOptions = { characterOptions: characterOptions }; if (!containerNode) { containerNode = getBody( this.getDocument() ); } this.selectNodeContents(containerNode); this.collapse(true); this.moveStart("character", startIndex, moveOptions); this.collapse(true); this.moveEnd("character", endIndex - startIndex, moveOptions); } ), // Character indexes are relative to the start of node toCharacterRange: createEntryPointFunction( function(session, containerNode, characterOptions) { if (!containerNode) { containerNode = getBody( this.getDocument() ); } var parent = containerNode.parentNode, nodeIndex = dom.getNodeIndex(containerNode); var rangeStartsBeforeNode = (dom.comparePoints(this.startContainer, this.endContainer, parent, nodeIndex) == -1); var rangeBetween = this.cloneRange(); var startIndex, endIndex; if (rangeStartsBeforeNode) { rangeBetween.setStartAndEnd(this.startContainer, this.startOffset, parent, nodeIndex); startIndex = -rangeBetween.text(characterOptions).length; } else { rangeBetween.setStartAndEnd(parent, nodeIndex, this.startContainer, this.startOffset); startIndex = rangeBetween.text(characterOptions).length; } endIndex = startIndex + this.text(characterOptions).length; return { start: startIndex, end: endIndex }; } ), findText: createEntryPointFunction( function(session, searchTermParam, findOptions) { // Set up options findOptions = createNestedOptions(findOptions, defaultFindOptions); // Create word options if we're matching whole words only if (findOptions.wholeWordsOnly) { // We don't ever want trailing spaces for search results findOptions.wordOptions.includeTrailingSpace = false; } var backward = isDirectionBackward(findOptions.direction); // Create a range representing the search scope if none was provided var searchScopeRange = findOptions.withinRange; if (!searchScopeRange) { searchScopeRange = api.createRange(); searchScopeRange.selectNodeContents(this.getDocument()); } // Examine and prepare the search term var searchTerm = searchTermParam, isRegex = false; if (typeof searchTerm == "string") { if (!findOptions.caseSensitive) { searchTerm = searchTerm.toLowerCase(); } } else { isRegex = true; } var initialPos = session.getRangeBoundaryPosition(this, !backward); // Adjust initial position if it lies outside the search scope var comparison = searchScopeRange.comparePoint(initialPos.node, initialPos.offset); if (comparison === -1) { initialPos = session.getRangeBoundaryPosition(searchScopeRange, true); } else if (comparison === 1) { initialPos = session.getRangeBoundaryPosition(searchScopeRange, false); } var pos = initialPos; var wrappedAround = false; // Try to find a match and ignore invalid ones var findResult; while (true) { findResult = findTextFromPosition(pos, searchTerm, isRegex, searchScopeRange, findOptions); if (findResult) { if (findResult.valid) { this.setStartAndEnd(findResult.startPos.node, findResult.startPos.offset, findResult.endPos.node, findResult.endPos.offset); return true; } else { // We've found a match that is not a whole word, so we carry on searching from the point immediately // after the match pos = backward ? findResult.startPos : findResult.endPos; } } else if (findOptions.wrap && !wrappedAround) { // No result found but we're wrapping around and limiting the scope to the unsearched part of the range searchScopeRange = searchScopeRange.cloneRange(); pos = session.getRangeBoundaryPosition(searchScopeRange, !backward); searchScopeRange.setBoundary(initialPos.node, initialPos.offset, backward); wrappedAround = true; } else { // Nothing found and we can't wrap around, so we're done return false; } } } ), pasteHtml: function(html) { this.deleteContents(); if (html) { var frag = this.createContextualFragment(html); var lastChild = frag.lastChild; this.insertNode(frag); this.collapseAfter(lastChild); } } }); /*----------------------------------------------------------------------------------------------------------------*/ // Extensions to the Rangy Selection object function createSelectionTrimmer(methodName) { return createEntryPointFunction( function(session, characterOptions) { var trimmed = false; this.changeEachRange(function(range) { trimmed = range[methodName](characterOptions) || trimmed; }); return trimmed; } ); } extend(api.selectionPrototype, { expand: createEntryPointFunction( function(session, unit, expandOptions) { this.changeEachRange(function(range) { range.expand(unit, expandOptions); }); } ), move: createEntryPointFunction( function(session, unit, count, options) { var unitsMoved = 0; if (this.focusNode) { this.collapse(this.focusNode, this.focusOffset); var range = this.getRangeAt(0); if (!options) { options = {}; } options.characterOptions = createOptions(options.characterOptions, defaultCaretCharacterOptions); unitsMoved = range.move(unit, count, options); this.setSingleRange(range); } return unitsMoved; } ), trimStart: createSelectionTrimmer("trimStart"), trimEnd: createSelectionTrimmer("trimEnd"), trim: createSelectionTrimmer("trim"), selectCharacters: createEntryPointFunction( function(session, containerNode, startIndex, endIndex, direction, characterOptions) { var range = api.createRange(containerNode); range.selectCharacters(containerNode, startIndex, endIndex, characterOptions); this.setSingleRange(range, direction); } ), saveCharacterRanges: createEntryPointFunction( function(session, containerNode, characterOptions) { var ranges = this.getAllRanges(), rangeCount = ranges.length; var rangeInfos = []; var backward = rangeCount == 1 && this.isBackward(); for (var i = 0, len = ranges.length; i < len; ++i) { rangeInfos[i] = { characterRange: ranges[i].toCharacterRange(containerNode, characterOptions), backward: backward, characterOptions: characterOptions }; } return rangeInfos; } ), restoreCharacterRanges: createEntryPointFunction( function(session, containerNode, saved) { this.removeAllRanges(); for (var i = 0, len = saved.length, range, rangeInfo, characterRange; i < len; ++i) { rangeInfo = saved[i]; characterRange = rangeInfo.characterRange; range = api.createRange(containerNode); range.selectCharacters(containerNode, characterRange.start, characterRange.end, rangeInfo.characterOptions); this.addRange(range, rangeInfo.backward); } } ), text: createEntryPointFunction( function(session, characterOptions) { var rangeTexts = []; for (var i = 0, len = this.rangeCount; i < len; ++i) { rangeTexts[i] = this.getRangeAt(i).text(characterOptions); } return rangeTexts.join(""); } ) }); /*----------------------------------------------------------------------------------------------------------------*/ // Extensions to the core rangy object api.innerText = function(el, characterOptions) { var range = api.createRange(el); range.selectNodeContents(el); var text = range.text(characterOptions); return text; }; api.createWordIterator = function(startNode, startOffset, iteratorOptions) { var session = getSession(); iteratorOptions = createNestedOptions(iteratorOptions, defaultWordIteratorOptions); var startPos = session.getPosition(startNode, startOffset); var tokenizedTextProvider = createTokenizedTextProvider(startPos, iteratorOptions.characterOptions, iteratorOptions.wordOptions); var backward = isDirectionBackward(iteratorOptions.direction); return { next: function() { return backward ? tokenizedTextProvider.previousStartToken() : tokenizedTextProvider.nextEndToken(); }, dispose: function() { tokenizedTextProvider.dispose(); this.next = function() {}; } }; }; /*----------------------------------------------------------------------------------------------------------------*/ api.noMutation = function(func) { var session = getSession(); func(session); endSession(); }; api.noMutation.createEntryPointFunction = createEntryPointFunction; api.textRange = { isBlockNode: isBlockNode, isCollapsedWhitespaceNode: isCollapsedWhitespaceNode, createPosition: createEntryPointFunction( function(session, node, offset) { return session.getPosition(node, offset); } ) }; }); return rangy; }, this);
// noop
import React from 'react'; import {render} from 'react-dom'; import BeverageList from './BeverageList'; import OrderList from './OrderList'; const beverages = [{ id: 1, name: 'Espresso', type: 'Coffee', price: [{ size: 'tall', cost: 1.95 }, { size: 'grande', cost: 2.05 }, { size: 'venti', cost: 2.35 }] },{ id: 2, name: 'Latte', type: 'Coffee', price: [{ size: 'tall', cost: 3.40 }, { size: 'grande', cost: 4.45 }, { size: 'venti', cost: 4.65 }] },{ id: 3, name: 'Cappuccino', type: 'Coffee', price: [{ size: 'tall', cost: 3.15 }, { size: 'grande', cost: 3.75 }, { size: 'venti', cost: 4.15 }] },{ id: 4, name: 'Green Tea', type: 'Tea', price: [{ size: 'tall', cost: 3.45 }, { size: 'grande', cost: 4.25 }, { size: 'venti', cost: 4.45 }] },{ id: 5, name: 'Hot Tea', type: 'Tea', price: [{ size: 'grande', cost: 1.95 }] }] class App extends React.Component { constructor(props) { super(); this.state = { totalAmount: 0, orderedList: [] }; } addToOrderList(beverage) { var total = Math.round((this.state.totalAmount + beverage.props.price.cost) * 100) / 100; let price = beverage.props.price.cost; let name = beverage.props.name; let type = beverage.props.type; let size = beverage.props.price.size; let id = Date.now(); //using date timestamp for ID, TOBE UPDATED console.log(this.state.totalAmount + ' + ' + beverage.props.price.cost + ' = ' + total); this.setState({ totalAmount: total, orderedList: this.state.orderedList.concat({price, type, name, size, id}) }); } submitOrder() { event.preventDefault(); } render() { return ( <div> <h1>Drink List</h1> <BeverageList beverages={this.props.beverages} addToOrderList={this.addToOrderList.bind(this)}/> <form onSubmit={this.submitOrder.bind(this)}> <h1>Ordered List ({this.state.orderedList.length})</h1> <OrderList orderedList={this.state.orderedList} /> <br/> <div>Total Amount: ${this.state.totalAmount}</div> <button type="submit">Order</button> </form> </div> ) } } render(<App beverages={beverages}/>, document.getElementById('app'));
class Plugin_Actionbar_View_Button extends View_Browser { getIconPath() { var instance = this.model.get('instance'); if (!instance) { return undefined; } var icon = instance.get('icon'), button_type = this.model.get('button_type'); switch (button_type) { case Plugin_Enum_ButtonTypes.ABILITY: return HTTP_Enum_AssetPaths.IMAGES.ICONS.ABILITIES + icon + '.png'; case Plugin_Enum_ButtonTypes.ITEM: return HTTP_Enum_AssetPaths.IMAGES.ICONS.ITEMS + icon + '.png'; default: throw new Error('invalid button type: ' + button_type); } } getTemplateData() { var instance = this.model.get('instance'), name, description, disabled = false, has_tooltip = true; if (instance) { name = instance.get('name'); description = instance.get('description'); } else { name = ''; description = ''; disabled = true; has_tooltip = false; } return { name: name, description: description, icon: this.getIconPath(), disabled: disabled, has_tooltip: has_tooltip }; } handleLastUsedChange() { var cooldown = this.model.get('instance').get('cooldown'); var properties = { width: '0%' }; this.elements.progress.css('width', '100%').stop().animate( properties, cooldown * Enum_Time_Intervals.ONE_SECOND, 'linear' ); } activate() { this.model.activate(); } handleDragStart(event) { var instance = this.model.get('instance'); if (!instance) { return false; } var transfer = event.originalEvent.dataTransfer; transfer.setData('button_type', this.model.get('button_type')); transfer.setData('button_instance', instance); transfer.setData('button_target', instance.get('id')); transfer.setData('button_id', this.model.get('id')); var icon = this.elements.icon; var image = Client_Utility_Resizer.resize( icon[0], icon.width(), icon.height() ); event.originalEvent.dataTransfer.setDragImage( image, 24, 24 ); this.$el.addClass('dragging'); } handleDragEnd(event) { if (event.originalEvent.dataTransfer.dropEffect === 'none') { this.model.set({ button_type: null, target: null, instance: null }); } this.$el.removeClass('dragging'); } handleInstanceChange() { var instance = this.model.get('instance'), prior_instance = this.model.previous('instance'); if (prior_instance) { prior_instance.off('change:last_used', this.handleLastUsedChange, this); prior_instance.off('change:cooldown', this.handleCooldownChange, this); } if (instance) { instance.on('change:last_used', this.handleLastUsedChange, this); instance.on('change:cooldown', this.handleCooldownChange, this); } this.handleLastUsedChange(); this.handleCooldownChange(); this.elements.icon.attr('src', this.getIconPath() || ''); } handleLoadingChange() { var loading = this.model.get('loading'); this.$el.toggleClass('loading', loading); } handleCooldownChange() { var cooldown = this.model.get('instance').get('cooldown') || ''; this.elements.cooldown.html(cooldown); } handleDisabledChange() { var disabled = this.model.get('disabled'); this.$el.toggleClass('disabled', disabled); } initEvents() { this.$el.on('dragstart', this.handleDragStart.bind(this)); this.$el.on('dragend', this.handleDragEnd.bind(this)); this.$el.on('click', this.activate.bind(this)); this.listenTo(this.model, 'change:instance', this.handleInstanceChange); this.listenTo(this.model, 'change:loading', this.handleLoadingChange); this.listenTo(this.model, 'change:disabled', this.handleDisabledChange); this.handleInstanceChange(); this.handleLoadingChange(); this.handleDisabledChange(); } initElements() { super.initElements(); this.addElements({ icon: this.$el.find('[data-ui="icon"]'), progress: this.$el.find('[data-ui="progress"]'), cooldown: this.$el.find('[data-ui="cooldown"]') }); } } ObjectHelper.extend(Plugin_Actionbar_View_Button.prototype, { template: Plugin_Actionbar_Template_Button }); module.exports = Plugin_Actionbar_View_Button;
'use strict'; const fontnik = require('fontnik'); const queue = require('d3-queue').queue; const zlib = require('zlib'); /** * Make all metadata (codepoints) and SDF PBFs necessary for Mapbox GL fontstacks. * @param {Object} opts Options object with required `font` and `filetype` properties, and any optional parameters. * @param {Buffer} opts.font The font file as a `Buffer`. * @param {string} opts.filetype Type of font (e.g. `'.ttf'` or `'.otf'`). * @param {number} [opts.concurrency] Concurrency to use when processing font into PBFs. If `undefined`, concurrency is unbounded. * @param {function(err, result)} callback Callback takes arguments (`error`, `result`). * * **Callback `result`:** * * `{string}` `name` The name of this font (concatenated family_name + style_name). * * `{Array}` `stack` An array of `{name: filename, data: buffer}` objects with SDF PBFs covering points 0-65535. * * `{Object}` `metadata` An object where `data` is a stringified codepoints result. * * `{name: string, data: Buffer}` `original` An object containing the original font file (named `"original{.filetype}"`) * */ function makeGlyphs(opts, callback) { // undefined (unset concurrency) means unbounded concurrency in d3-queue const q = queue(opts.concurrency); if (!(opts.font instanceof Buffer)) throw new Error('opts.font must be a Buffer'); if (typeof opts.filetype !== 'string') throw new Error('opts.filetype must be a String'); if (!(callback instanceof Function)) throw new Error('Callback must be a Function'); fontnik.load(opts.font, (err, faces) => { if (err) { return callback(err); } if (faces.length > 1) { return callback(new Error('Multiple faces in a font are not yet supported.')); } const metadata = faces[0]; for (let i = 0; i < 65536; (i = i + 256)) { q.defer(writeGlyphs, opts.font, i, Math.min(i + 255, 65535)); } q.awaitAll((err, results) => { if (err) return callback(err); return callback(null, { name: metadata.style_name ? [metadata.family_name, metadata.style_name].join(' ') : metadata.family_name, stack: results, metadata: Object.keys(metadata).reduce((prev, key) => { if (key !== 'points') { prev[key] = metadata[key]; } return prev; }, {}), codepoints: metadata.points, original: { name: 'original' + opts.filetype, data: opts.font } }); }); }); } function writeGlyphs(font, start, end, done) { fontnik.range({ font: font, start: start, end: end }, (err, data) => { if (err) { return done(err); } const name = [start, '-', end, '.pbf'].join(''); zlib.gzip(data, (err, res) => { if (err) { return done(err); } const result = { name: name, data: res }; return done(null, result); }); }); } module.exports = { makeGlyphs: makeGlyphs, writeGlyphs: writeGlyphs // exported only for testing };
'use strict'; module.exports = ['$http', 'Contact', defaultContacts]; function defaultContacts($http, Contact) { return { get: function () { return $http.get('data/defaults.json').then(function (resp) { var contacts = []; angular.forEach(resp.data, function (attributes) { contacts.push(new Contact(attributes)); }); return contacts; }); } }; }
export type CounterItem = { id: string, value: number, title?: string } export type CounterItems = Array<CounterItem>
module.exports = new (require('../..'))();
// Jiffy Gruntfile // Originally created by generator-angular 0.11.1 // // Run 'grunt' for building and 'grunt serve' for preview. // Use 'grunt test' to run the unit tests with karma. // Use 'grunt docs' to generate doc. Then, run 'node webserver.js' and open in a browser (http://localhost/docs). 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Configurable paths for the application var appConfig = { app: require('./bower.json').appPath || 'app', dist: 'dist' }; // Define the configuration for all the tasks grunt.initConfig({ // Project settings jiffy: appConfig, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] }, js: { files: ['<%= jiffy.app %>/scripts/{,*/}*.js'], tasks: ['newer:jshint:all'], options: { livereload: '<%= connect.options.livereload %>' } }, jsTest: { files: ['test/spec/{,*/}*.js'], tasks: ['newer:jshint:test', 'karma'] }, styles: { files: ['<%= jiffy.app %>/styles/{,*/}*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= jiffy.app %>/{,*/}*.html', '.tmp/styles/{,*/}*.css', '<%= jiffy.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= jiffy.app %>/file-definitions/{,*/}*.{json,txt}' ] } }, // The actual grunt server settings connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true, middleware: function (connect) { return [ connect.static('.tmp'), connect().use( '/bower_components', connect.static('./bower_components') ), connect().use( '/app/styles', connect.static('./app/styles') ), connect.static(appConfig.app) ]; } } }, test: { options: { port: 9001, middleware: function (connect) { return [ connect.static('.tmp'), connect.static('test'), connect().use( '/bower_components', connect.static('./bower_components') ), connect.static(appConfig.app) ]; } } }, dist: { options: { open: true, base: '<%= jiffy.dist %>' } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: { src: [ 'Gruntfile.js', '<%= jiffy.app %>/scripts/{,*/}*.js' ] }, test: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/spec/{,*/}*.js'] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= jiffy.dist %>/{,*/}*', '!<%= jiffy.dist %>/.git{,*/}*' ] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, server: { options: { map: true, }, files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the app wiredep: { app: { src: ['<%= jiffy.app %>/index.html'], ignorePath: /\.\.\// }, test: { devDependencies: true, src: '<%= karma.unit.configFile %>', ignorePath: /\.\.\//, fileTypes:{ js: { block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi, detect: { js: /'(.*\.js)'/gi }, replace: { js: '\'{{filePath}}\',' } } } } }, // Renames files for browser caching purposes filerev: { dist: { src: [ '<%= jiffy.dist %>/scripts/{,*/}*.js', '<%= jiffy.dist %>/styles/{,*/}*.css', '<%= jiffy.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= jiffy.dist %>/styles/fonts/*' ] } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: '<%= jiffy.app %>/index.html', options: { dest: '<%= jiffy.dist %>', flow: { html: { steps: { js: ['concat', 'uglifyjs'], css: ['cssmin'] }, post: {} } } } }, // Performs rewrites based on filerev and the useminPrepare configuration usemin: { html: ['<%= jiffy.dist %>/{,*/}*.html'], css: ['<%= jiffy.dist %>/styles/{,*/}*.css'], options: { assetsDirs: [ '<%= jiffy.dist %>', '<%= jiffy.dist %>/images', '<%= jiffy.dist %>/styles' ] } }, // The following *-min tasks will produce minified files in the dist folder // By default, your `index.html`'s <!-- Usemin block --> will take care of // minification. These next options are pre-configured if you do not wish // to use the Usemin blocks. // cssmin: { // dist: { // files: { // '<%= jiffy.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css' // ] // } // } // }, // uglify: { // dist: { // files: { // '<%= jiffy.dist %>/scripts/scripts.js': [ // '<%= jiffy.dist %>/scripts/scripts.js' // ] // } // } // }, // concat: { // dist: {} // }, imagemin: { dist: { files: [{ expand: true, cwd: '<%= jiffy.app %>/images', src: '{,*/}*.{png,jpg,jpeg,gif}', dest: '<%= jiffy.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= jiffy.app %>/images', src: '{,*/}*.svg', dest: '<%= jiffy.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseWhitespace: true, conservativeCollapse: true, collapseBooleanAttributes: true, removeCommentsFromCDATA: true, removeOptionalTags: true }, files: [{ expand: true, cwd: '<%= jiffy.dist %>', src: ['*.html', 'views/{,*/}*.html'], dest: '<%= jiffy.dist %>' }] } }, // ng-annotate tries to make the code safe for minification automatically // by using the Angular long form for dependency injection. ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= jiffy.dist %>/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= jiffy.app %>', dest: '<%= jiffy.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', '*.html', 'views/{,*/}*.html', 'images/{,*/}*.{webp}', 'styles/fonts/{,*/}*.*', 'file-definitions/{,*/}*.*' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= jiffy.dist %>/images', src: ['generated/*'] }, { expand: true, cwd: 'bower_components/bootstrap/dist', src: 'fonts/*', dest: '<%= jiffy.dist %>' }] }, styles: { expand: true, cwd: '<%= jiffy.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, // Run some tasks in parallel to speed up the build process concurrent: { server: [ 'copy:styles' ], test: [ 'copy:styles' ], dist: [ 'copy:styles', 'imagemin', 'svgmin' ] }, // Test settings karma: { unit: { configFile: 'test/karma.conf.js', singleRun: true } }, // Ngdocs settings ngdocs: { options: { dest: 'docs', html5Mode: true }, api: { src: ['app/**/*.js', 'app/scripts/index.ngdoc'], title: 'Jiffy Documentation' } } }); grunt.registerTask('serve', 'Compile then start a connect web server', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'wiredep', 'concurrent:server', 'autoprefixer:server', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve:' + target]); }); grunt.registerTask('test', [ 'clean:server', 'wiredep', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma' ]); grunt.registerTask('build', [ 'clean:dist', 'wiredep', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'ngAnnotate', 'copy:dist', 'cdnify', 'cssmin', 'uglify', 'filerev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); grunt.registerTask('docs', [ 'clean', 'ngdocs' ]); };
'use strict'; var mapRequire = require('map-require'); var _ = require('lodash'); var is = require('is-predicate'); var path = require('path'); var fs = require('fs'); var PHOTOS_PATH = path.join(__dirname, '..', 'public', 'images', 'speakers'); function appendPhoto(speaker) { // filename of image is var fname = speaker.name.trim().toLowerCase().replace(' ', '') + '.jpg'; if (fs.existsSync(path.join(PHOTOS_PATH, fname))) { return _.extend({ image: fname }, speaker); } return speaker; } function map(meetup) { return _.defaults({ speakers: meetup.speakers.map(appendPhoto) }, meetup); } var meetups = module.exports = mapRequire(path.join(__dirname, '..', 'speakers'), map); // newest at the beginning meetups.sort(function(a, b) { return is.less(a.date, b.date); }); /** * Finds the next meetup based on a given date * * @param {Date} d * * return {Object} - a meetup object */ meetups.findNext = function (d) { var found = _.find(meetups, function(meetup) { return ['getFullYear', 'getMonth'].every(function(fn) { return is.equal(meetup.date[fn](), d[fn]()); }); }); if (!found) return null; // meetup is from the past, get next one by adding a month if (is.less(found.date.getDate(), d.getDate())) { return meetups[meetups.indexOf(found) - 1]; } return found; };
var util = require('util'), webutil = require('../util/web'), Tab = require('../client/tab').Tab, fs = require('fs'); var SettingsGatewayTab = function() { Tab.call(this); }; util.inherits(SettingsGatewayTab, Tab); SettingsGatewayTab.prototype.tabName = 'settingsgateway'; SettingsGatewayTab.prototype.mainMenu = 'settingsgateway'; SettingsGatewayTab.prototype.generateHtml = function() { return require('../../templates/tabs/settingsgateway.jade')(); }; SettingsGatewayTab.prototype.angular = function(module) { module.controller('SettingsGatewayCtrl', ['$scope', 'rpId', 'rpKeychain', 'rpNetwork', function ($scope, id, keychain, network) { if (!id.loginStatus) id.goId(); // Used in offline mode if (!$scope.fee) { $scope.fee = Options.max_tx_network_fee; } // from new Ripple lib var RemoteFlags = { // AccountRoot account_root: { PasswordSpent: 0x00010000, // password set fee is spent RequireDestTag: 0x00020000, // require a DestinationTag for payments RequireAuth: 0x00040000, // require a authorization to hold IOUs DisallowXRP: 0x00080000, // disallow sending XRP DisableMaster: 0x00100000, // force regular key DefaultRipple: 0x00800000, NoFreeze: 0x00200000, // permanently disallowed freezing trustlines GlobalFreeze: 0x00400000 // trustlines globally frozen }, // Offer offer: { Passive: 0x00010000, Sell: 0x00020000 // offer was placed as a sell }, // Ripple tate state: { LowReserve: 0x00010000, // entry counts toward reserve HighReserve: 0x00020000, LowAuth: 0x00040000, HighAuth: 0x00080000, LowNoRipple: 0x00100000, HighNoRipple: 0x00200000 } }; var Transaction = { set_clear_flags : { AccountSet: { asfRequireDest: 1, asfRequireAuth: 2, asfDisallowXRP: 3, asfDisableMaster: 4, asfAccountTxnID: 5, asfNoFreeze: 6, asfGlobalFreeze: 7, asfDefaultRipple: 8 } } }; $scope.options = Options; $scope.optionsBackup = $.extend(true, {}, Options); $scope.edit = { advanced_feature_switch: false, defaultRippleFlag: false, defaultRippleFlagSaving: false, requireAuthFlag: false, requireAuthFlagSaving: false, globalFreezeFlag: false, globalFreezeFlagSaving: false }; // Initialize the notification object $scope.success = {}; $scope.saveBlob = function() { // Save in local storage if (!store.disabled) { store.set('ripple_settings', JSON.stringify($scope.options)); } $scope.editBlob = false; }; $scope.saveTransaction = function(tx) { var sequenceNumber = (Number(tx.tx_json.Sequence)); var sequenceLength = sequenceNumber.toString().length; var txnName = $scope.userBlob.data.account_id + '-' + new Array(10 - sequenceLength + 1).join('0') + sequenceNumber + '.txt'; var txData = JSON.stringify({ tx_json: tx.tx_json, hash: $scope.hash, tx_blob: $scope.signedTransaction }); var fileName = $scope.userBlob.data.defaultDirectory + '/' + txnName; fs.writeFile(fileName, txData, function(err) { $scope.$apply(function() { $scope.fileName = fileName; console.log('saved file'); if (err) { console.log('Error saving transaction: ', JSON.stringify(err)); $scope.error = true; } else { $scope.saved = true; } }); }); }; $scope.addFlag = function(type) { if (!_.includes(['defaultRippleFlag', 'requireAuthFlag', 'globalFreezeFlag'], type)) { return; } var tx = network.remote.transaction(); tx.accountSet(id.account, Transaction.set_clear_flags.AccountSet['asf' + type.charAt(0).toUpperCase() + type.slice(1, -4)]); tx.tx_json.Sequence = Number($scope.sequence); $scope.incrementSequence(); tx.tx_json.Fee = $scope.fee; keychain.requestSecret(id.account, id.username, function(err, secret) { if (err) { console.log('Error: ', err); $scope.edit[type] = false; return; } tx.secret(secret); tx.complete(); $scope.signedTransaction = tx.sign().serialize().to_hex(); $scope.txJSON = JSON.stringify(tx.tx_json); $scope.hash = tx.hash('HASH_TX_ID', false, undefined); $scope.offlineSettingsChange = true; $scope.edit[type] = false; if ($scope.userBlob.data.defaultDirectory) { $scope.saveTransaction(tx); } }); }; $scope.removeFlag = function(type) { if (!_.includes(['defaultRippleFlag', 'requireAuthFlag', 'globalFreezeFlag'], type)) { return; } var tx = network.remote.transaction(); tx.accountSet(id.account, undefined, Transaction.set_clear_flags.AccountSet['asf' + type.charAt(0).toUpperCase() + type.slice(1, -4)]); tx.tx_json.Sequence = Number($scope.sequence); $scope.incrementSequence(); tx.tx_json.Fee = $scope.fee; keychain.requestSecret(id.account, id.username, function(err, secret) { if (err) { console.log('Error: ', err); $scope.edit[type] = false; return; } tx.secret(secret); tx.complete(); $scope.signedTransaction = tx.sign().serialize().to_hex(); $scope.txJSON = JSON.stringify(tx.tx_json); $scope.hash = tx.hash('HASH_TX_ID', false, undefined); $scope.offlineSettingsChange = true; $scope.edit[type] = false; if ($scope.userBlob.data.defaultDirectory) { $scope.saveTransaction(tx); } }); }; $scope.saveSetting = function(type) { switch (type) { case 'advanced_feature_switch': $scope.saveBlob(); break; case 'defaultRippleFlag': // Need to set flag on account_root only when chosen option is different from current setting if ($scope.currentDefaultRipplingFlagSetting !== $scope.isDefaultRippleFlagEnabled) { $scope.edit.defaultRippleFlagSaving = true; var tx = network.remote.transaction(); !$scope.isDefaultRippleFlagEnabled ? tx.accountSet(id.account, undefined, Transaction.set_clear_flags.AccountSet.asfDefaultRipple) : tx.accountSet(id.account, Transaction.set_clear_flags.AccountSet.asfDefaultRipple); tx.on('success', function(res) { $scope.$apply(function() { $scope.edit.defaultRippleFlagSaving = false; $scope.load_notification('defaultRippleUpdated'); }); }); tx.on('error', function(res) { console.warn(res); $scope.$apply(function() { $scope.edit.defaultRippleFlagSaving = false; }); }); keychain.requestSecret(id.account, id.username, function(err, secret) { if (err) { console.log('Error: ', err); $scope.isDefaultRippleFlagEnabled = !$scope.isDefaultRippleFlagEnabled; $scope.edit.defaultRippleFlagSaving = false; return; } tx.secret(secret); tx.submit(); }); } break; case 'requireAuthFlag': // Need to set flag on account_root only when chosen option is different from current setting if ($scope.currentRequireAuthFlagSetting !== $scope.isRequireAuthFlagEnabled) { $scope.edit.requireAuthFlagSaving = true; var tx = network.remote.transaction(); !$scope.isRequireAuthFlagEnabled ? tx.accountSet(id.account, undefined, Transaction.set_clear_flags.AccountSet.asfRequireAuth) : tx.accountSet(id.account, Transaction.set_clear_flags.AccountSet.asfRequireAuth); tx.on('success', function(res) { $scope.$apply(function() { $scope.edit.requireAuthFlagSaving = false; $scope.load_notification('requireAuthUpdated'); }); }); tx.on('error', function(res) { console.warn(res); $scope.$apply(function() { $scope.edit.requireAuthFlagSaving = false; $scope.engine_result = res.engine_result; $scope.engine_result_message = res.engine_result_message; $scope.load_notification('requireAuthFailed'); }); }); keychain.requestSecret(id.account, id.username, function(err, secret) { if (err) { console.log('Error: ', err); $scope.isRequireAuthFlagEnabled = !$scope.isRequireAuthFlagEnabled; $scope.edit.requireAuthFlagSaving = false; return; } tx.secret(secret); tx.submit(); }); } break; case 'globalFreezeFlag': // Need to set flag on account_root only when chosen option is different from current setting if ($scope.currentGlobalFreezeFlagSetting !== $scope.isGlobalFreezeFlagEnabled) { $scope.edit.globalFreezeFlagSaving = true; var tx = network.remote.transaction(); // One call is for adding the globalFreeze flag and one is for removing it !$scope.isGlobalFreezeFlagEnabled ? tx.accountSet(id.account, undefined, Transaction.set_clear_flags.AccountSet.asfGlobalFreeze) : tx.accountSet(id.account, Transaction.set_clear_flags.AccountSet.asfGlobalFreeze); tx.on('success', function(res) { $scope.$apply(function() { $scope.edit.globalFreezeFlagSaving = false; $scope.load_notification('globalFreezeUpdated'); }); }); tx.on('error', function(res) { console.warn(res); $scope.$apply(function() { $scope.edit.globalFreezeFlagSaving = false; $scope.engine_result = res.engine_result; $scope.engine_result_message = res.engine_result_message; $scope.load_notification('globalFreezeFailed'); }); }); keychain.requestSecret(id.account, id.username, function(err, secret) { if (err) { console.log('Error: ', err); $scope.isGlobalFreezeFlagEnabled = !$scope.isGlobalFreezeFlagEnabled; $scope.edit.globalFreezeFlagSaving = false; return; } tx.secret(secret); tx.submit(); }); } break; default: $scope.saveBlob(); } $scope.edit[type] = false; // Notify the user $scope.success[type] = true; }; $scope.cancelEdit = function(type) { $scope.edit[type] = false; $scope.options[type] = $scope.optionsBackup[type]; }; $scope.$watch('account', function() { // Check if account has DefaultRipple flag set $scope.isDefaultRippleFlagEnabled = !!($scope.account.Flags & RemoteFlags.account_root.DefaultRipple); $scope.currentDefaultRipplingFlagSetting = $scope.isDefaultRippleFlagEnabled; // Check if account has RequireAuth flag set $scope.isRequireAuthFlagEnabled = !!($scope.account.Flags & RemoteFlags.account_root.RequireAuth); $scope.currentRequireAuthFlagSetting = $scope.isRequireAuthFlagEnabled; // Check if account has GlobalFreeze flag set $scope.isGlobalFreezeFlagEnabled = !!($scope.account.Flags & RemoteFlags.account_root.GlobalFreeze); $scope.currentGlobalFreezeFlagSetting = $scope.isGlobalFreezeFlagEnabled; }, true); }]); }; module.exports = SettingsGatewayTab;
"use strict"; function warning (message) { var index = 1; var args = arguments; console.warn("Warning: " + message.replace(/%s/g, function () { return args[index++]; })); } module.exports = warning;
"use strict"; /* * Commands.js * This file contains the RPC methods used by signalr */ var Commands = { SendMessage: function (chat, model) { var text = $('#messageInput').val(); if (true) {//if (model.Connected()) { if (text[0] == '/') { Commands.SendCommand(chat, model, text); } else { chat.server.message(model.GameId, model.CurrentScene().Name, $('#messageInput').val(), false); } $('#messageInput').val('').focus(); } }, SendCommand: function (chat, model, text) { // TODO: add more commands var firstSpace = text.indexOf(' '); if (text[1] == 'e') { chat.server.message(model.GameId, 'default', text.substring(firstSpace), true); } else { chat.server.rollDice(model.GameId, 'default', text.substring(firstSpace)); } }, RecieveMessage: function (model, scene, message) { var foundChannel = {}; var s = model.Scenes(); for (var i = 0; i < s.length; i++) { console.log(s[i].Name); if (s[i].Name == scene) { console.log("scene found!"); foundChannel = s[i]; } console.log(message); var l = ko.mapping.fromJS(message); console.log(l); foundChannel.Log.push(message); } }, JoinScene: function (model, scene) { console.log(scene); var s = new Scene(scene.Name); model.Scenes.push(s); if (model.Scenes().length == 1) { model.CurrentScene(s); } }, NewUser : function(model, user) { model.Users.push(ko.mapping.fromJS(user, Mapping)); }, RemoveUser : function(model, user) { model.Users.remove(ko.mapping.fromJS(user)); }, }
var Backbone = require('backbone'); var jquery = require('jquery'); Backbone.$ = jquery; var Bot = Backbone.Model.extend({ }); module.exports = Bot;
var foxieData = require("foxie-data") function closeMatch(iterate, ext) { var fileExt = "."+iterate.split(".").pop(); if (fileExt == ext) return true; else return false; } function $class(themeName) { this.make = function (res, themePath) { this.tmpArr = [] this.themeName = themePath.split("/").pop() this.tmpArr[this.themeName] = {} var styles = this.tmpArr[this.themeName]["styles"] = {} var scripts = this.tmpArr[this.themeName]["scripts"] = {} var data = this.tmpArr[this.themeName]["data"] = {} var plain = this.tmpArr[this.themeName]["plain"] = {} var templates = this.tmpArr[this.themeName]["templates"] = {} var images = this.tmpArr[this.themeName]["images"] = {} styles["scss"] = [] styles["less"] = [] styles["styl"] = [] styles["css"] = [] data["json"] = [] data["yml"] = [] data["xml"] = [] scripts["js"] = [] plain["txt"] = [] plain["md"] = [] templates["jade"] = [] templates["handlebars"] = [] templates["ejs"] = [] templates["html"] = [] images["jpeg"] = [] images["png"] = [] images["gif"] = [] images["ico"] = [] for(i in res){//sort into groups if(closeMatch(res[i],".scss")) styles["scss"].push(res[i]) if(closeMatch(res[i],".less")) styles["less"].push(res[i]) if(closeMatch(res[i],".styl")) styles["styl"].push(res[i]) if(closeMatch(res[i],".css")) styles["css"].push(res[i]) if(closeMatch(res[i],".json")) data["json"].push(res[i]) if(closeMatch(res[i],".yml")) data["yml"].push(res[i]) if(closeMatch(res[i],".xml")) data["xml"].push(res[i]) if(closeMatch(res[i],".js")) scripts["js"].push(res[i]) if(closeMatch(res[i],".txt")) plain["txt"].push(res[i]) if(closeMatch(res[i],".md")) plain["md"].push(res[i]) if(closeMatch(res[i],".jade")) templates["jade"].push(res[i]) if(closeMatch(res[i],".ejs")) templates["ejs"].push(res[i]) if(closeMatch(res[i],".hbs")) templates["handlebars"].push(res[i]) if(closeMatch(res[i],".html")) templates["html"].push(res[i]) if(closeMatch(res[i],".htm")) templates["html"].push(res[i]) if(closeMatch(res[i],".jpeg")) images["jpeg"].push(res[i]) if(closeMatch(res[i],".jpg")) images["jpeg"].push(res[i]) if(closeMatch(res[i],".png")) images["png"].push(res[i]) if(closeMatch(res[i],".gif")) images["gif"].push(res[i]) if(closeMatch(res[i],".ico")) images["ico"].push(res[i]) } var handlerPath = "../handlers"; //do specific things for each file type require(handlerPath+"/templates.js")(templates,foxieData.temp,themeName) require(handlerPath+"/images.js")(images) require(handlerPath+"/plain.js")(plain) require(handlerPath+"/scripts.js")(scripts) require(handlerPath+"/styles.js")(styles,themeName) require(handlerPath+"/data.js")(data) } } module.exports = function(res,themePath,themeName){ var manifest = new $class(themeName) manifest.make(res,themePath) }
'use strict'; describe('The nontriviality assumption', function() { it('should hold', function() { expect(true).to.be.true; }); });
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { List } from 'material-ui/List'; import FollowingList from './presentation/FollowingList'; import CircularProgress from 'material-ui/CircularProgress'; import { getFollowing } from '../../actions/followingActions'; function loadData(props) { props.getFollowing(); } class FollowingPage extends React.Component { componentDidMount() { loadData(this.props); } render() { const { users, isFetching } = this.props; const styles = { circularProgress: { margin: "auto", width: "10%", padding: "20px", }, }; return ( <div> { isFetching ? <div style={styles.circularProgress}> <CircularProgress size={1} /> </div> : <List> {users.map(user => <FollowingList key={user.id} user={user} /> )} </List> } </div> ); } } FollowingPage.propTypes = { getFollowing: PropTypes.func.isRequired, users: PropTypes.array.isRequired, isFetching: PropTypes.bool.isRequired, }; function mapStateToProps(state, ownProps) { return { users: state.following.users, isFetching: state.following.isFetching, }; } export default connect(mapStateToProps, { getFollowing })(FollowingPage);
import executeInSeries from '../utils/executeInSeries'; import wait from '../utils/wait'; export default (userConfig) => () => { const defaultConfig = { delay: 10, // delay in milliseconds between each wave nb: 100, // number of waves to execute (can be overridden in params) }; const config = { ...defaultConfig, ...userConfig }; let stopped = false; const bySpeciesStrategy = async (newGremlins) => { const { nb, delay } = config; const gremlins = [...newGremlins]; // clone the array to avoid modifying the original for (let gremlinIndex in gremlins) { const gremlin = gremlins[gremlinIndex]; for (let i = 0; i < nb; i++) { await wait(delay); if (stopped) { return Promise.resolve(); } await executeInSeries([gremlin], []); } } return Promise.resolve(); }; bySpeciesStrategy.stop = () => { stopped = true; }; return bySpeciesStrategy; };
LitJS.extendWith({ panelWrap : function(elements,title,collapsible,id,collapsed) { if (collapsible || collapsed) //if the element is not collapsible/collapsed, there's nowhere to display the tooltip, and no reason to display one { var headingEl = elements.headingEl if (!headingEl) throw new Error("Heading element must be specified for tooltip") var codeEl = elements.codeEl if (!codeEl) throw new Error("Code element (pre) must be specified for tooltip extension") Tipped.create(headingEl,$(codeEl).clone()) //create the tooltip, anc cloning the code element to display the code in the tooltip } } })
/* The MIT License (MIT) Copyright (c) 2015 Frédéric Bolvin | https://github.com/Fensterbank Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function () { var datipi = function (inputField) { var currentDateTime, container, btnPreviousMonth, btnNextMonth, headline, calendar, clock, hours, minutes, style, months, weekdays; /** * Pad a given number below 10 with a preceding zero * @param number * @returns {string} */ function pad(number) { var r = String(number); if ( r.length === 1 ) { r = '0' + r; } return r; } /** * Add a css class to an element's class list. Alternative for classList.add, which does not exist in IE9 * @param element * @param className */ function addClass(element, className) { var classes = element.className.split(' '); if (classes.indexOf(className) == -1) { classes.push(className); } element.className = classes.join(' '); } /** * Remove a css class from an element's class list. Alternative for classList.remove, which does not exist in IE9 * @param element * @param className */ function removeClass(element, className) { var classes = element.className.split(' '); var index = classes.indexOf(className); if (index != -1) { classes.splice(index, 1); } element.className = classes.join(' '); } /** * Reset the picker by preparing elements without recreating all new * Is called, when the same picker is opened more than once */ function reset() { clock.style.display = 'none'; container.style.display = 'block'; removeClass(calendar, 'datipi-circle-hidden'); calendar.style.display = 'block'; btnPreviousMonth.style.display = 'inline-block'; btnNextMonth.style.display = 'inline-block'; if (hours != null) { hours.setAttribute('style', ''); hours.className = 'datipi-circle-selector datipi-hours'; } if (minutes != null) { minutes.setAttribute('style', ''); minutes.className = 'datipi-minutes datipi-circle-hidden'; } initCalendar(); } /** * Initialize the main container with its elements */ function initContainer() { // If the container already exists, make the needed elements visible if (container != null) { reset(); return; } container = document.createElement('div'); container.className = 'datipi-container'; // Header containing headline and buttons var head = document.createElement('div'); head.className = 'datipi-head'; // Button left btnPreviousMonth = document.createElement('div'); btnPreviousMonth.className = 'datipi-switch'; btnPreviousMonth.innerHTML = '◀'; btnPreviousMonth.addEventListener('click', onPreviousMonth); // Headline containing text, e.g. current month headline = document.createElement('div'); headline.className = 'datipi-headline'; // Button right; btnNextMonth = document.createElement('div'); btnNextMonth.className = 'datipi-switch'; btnNextMonth.innerHTML = '▶'; btnNextMonth.addEventListener('click', onNextMonth); // Calendar container for month selection calendar = document.createElement('div'); calendar.className = 'datipi-calendar datipi-circle-selector'; // Clock container for time selection clock = document.createElement('div'); clock.className = 'datipi-clock'; // Fill the calendar with the current month days initCalendar(); // Append all childs to DOM head.appendChild(btnPreviousMonth); head.appendChild(headline); head.appendChild(btnNextMonth); container.appendChild(head); container.appendChild(calendar); container.appendChild(clock); inputField.parentElement.appendChild(container); } /** * Initialize the calendar with the current date, create and render all day picker elements * Is called on each month change */ function initCalendar() { var firstDayOfMonth = new Date(currentDateTime.getFullYear(), currentDateTime.getMonth(), 1); var lastDayOfMonth = new Date(currentDateTime.getFullYear(), currentDateTime.getMonth() + 1, 0); // Set headline content headline.innerHTML = formatDate(currentDateTime, 'headline'); // Create elements for calendar var table = document.createElement('table') var thead = document.createElement('thead'); var headRow = document.createElement('tr'); // Fill header row with weekdays weekdays.forEach(function (weekDay) { var cell = document.createElement('th'); cell.innerHTML = weekDay; headRow.appendChild(cell); }); var tbody = document.createElement('tbody'); // Calculate the first rendered day of the current view. // We always begin with a sunday, which can be before first day of month var firstDayOfCalendar = new Date(firstDayOfMonth); while (firstDayOfCalendar.getDay() != 0) { firstDayOfCalendar.setDate(firstDayOfCalendar.getDate() - 1); } // Fill the calendar month with elements var currentRenderDate = new Date(firstDayOfCalendar); var i = 0; var row = document.createElement('tr'); var current = formatDate(currentDateTime, 'date'); var cell; while (currentRenderDate <= lastDayOfMonth) { if (i == 7) { i = 0; tbody.appendChild(row); row = document.createElement('tr'); } var currentString = formatDate(currentRenderDate, 'date'); cell = document.createElement('td'); cell.innerHTML = currentRenderDate.getDate().toString(); // This is the selected date. Mark it if (currentString == current) { addClass(cell, 'selected'); } // The day is not in the current month. Mark it if (currentRenderDate.getMonth() != lastDayOfMonth.getMonth()) { addClass(cell, 'outerMonth'); } cell.setAttribute('data-date' , currentString); cell.addEventListener('click', onDateSelect); row.appendChild(cell); // Prepare next step currentRenderDate.setDate(currentRenderDate.getDate() + 1); i++; } // Each row should have the same amount of cells. // Create empty cells if needed. for (i; i < 7; i++) { cell = document.createElement('td'); cell.innerHTML = '&nbsp;'; row.appendChild(cell); } tbody.appendChild(row); thead.appendChild(headRow); table.appendChild(thead); table.appendChild(tbody); // Clear calendar and add new table calendar.innerHTML = ''; calendar.appendChild(table); } /** * Initialize the clock with the selectable tick elements * Must be called only once */ function initClock() { if (clock.children.length > 0) return; // ToDo: Calculate this somehow var clockHours = { '00': { left: '87px', top: '7px' }, '1': { left: '114px', top: '40.2346px', bigger: true }, '2': { left: '133.765px', top: '60px', bigger: true }, '3': { left: '141px', top: '87px', bigger: true }, '4': { left: '133.765px', top: '114px', bigger: true }, '5': { left: '114px', top: '133.765px', bigger: true }, '6': { left: '87px', top: '141px', bigger: true }, '7': { left: '60px', top: '133.765px', bigger: true }, '8': { left: '40.2346px', top: '114px', bigger: true }, '9': { left: '33px', top: '87px', bigger: true }, '10': { left: '40.2346px', top: '60px', bigger: true }, '11': { left: '60px', top: '40.2346px', bigger: true }, '12': { left: '87px', top: '33px', bigger: true }, '13': { left: '127px', top: '17.718px'}, '14': { left: '156.282px', top: '47px'}, '15': { left: '167px', top: '87px'}, '16': { left: '156.282px', top: '127px'}, '17': { left: '127px', top: '156.282px'}, '18': { left: '87px', top: '167px'}, '19': { left: '47px', top: '156.282px'}, '20': { left: '17.718px', top: '127px'}, '21': { left: '7px', top: '87px'}, '22': { left: '17.718px', top: '47px'}, '23': { left: '47px', top: '17.718px'} }; // ToDo: Calculate this somehow var clockMinutes = { '00': { left: '87px', top: '7px', bigger: true }, '05': { left: '127px', top: '17.718px', bigger: true }, '10': { left: '156.282px', top: '47px', bigger: true }, '15': { left: '167px', top: '87px', bigger: true }, '20': { left: '156.282px', top: '127px', bigger: true }, '25': { left: '127px', top: '156.282px', bigger: true }, '30': { left: '87px', top: '167px', bigger: true }, '35': { left: '47px', top: '156.282px', bigger: true }, '40': { left: '17.718px', top: '127px', bigger: true }, '45': { left: '7px', top: '87px', bigger: true }, '50': { left: '17.718px', top: '47px', bigger: true }, '55': { left: '47px', top: '17.718px', bigger: true } }; // Create hours container hours = document.createElement('div'); hours.setAttribute('style', ''); hours.className = 'datipi-circle-selector datipi-hours'; fillTickElements(hours, clockHours, onHourTickSelect); // Create minutes container minutes = document.createElement('div'); minutes.setAttribute('style', ''); minutes.className = 'datipi-minutes datipi-circle-hidden'; fillTickElements(minutes, clockMinutes, onMinutesTickSelect); // Clear clock and append child elements clock.innerHTML = ''; clock.appendChild(hours); clock.appendChild(minutes); } /** * Initialize all language strings in current user language (if possible) * ToDo: Make it support more languages! */ function initLanguage() { months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; weekdays = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']; } /** * Formats the date in different formats using format keyword * @param dateTime * @param format * @returns {string} */ function formatDate(dateTime, format) { switch (format) { case 'headline': return months[dateTime.getMonth()] + ' ' + dateTime.getFullYear(); case 'date': return dateTime.getFullYear() + '-' + pad(dateTime.getMonth() + 1) + '-' + pad(dateTime.getDate()); case 'full': return dateTime.getFullYear() + '-' + pad(dateTime.getMonth() + 1) + '-' + pad(dateTime.getDate()) + ' ' + pad(dateTime.getHours()) + ':' + pad(dateTime.getMinutes()); } } /** * Fill the given container with tick elements predefined in the given dictionary and append event listener * @param container * @param dictionary * @param clickCallback */ function fillTickElements(container, dictionary, clickCallback) { var num, obj, elem; for (num in dictionary) { obj = dictionary[num]; elem = document.createElement('div'); elem.innerHTML = num; elem.setAttribute('style', 'top:' + obj.top + ';left:' + obj.left); addClass(elem, 'datipi-tick'); if (obj.bigger) { addClass(elem, 'datipi-bigger'); } if (clickCallback != null) { elem.addEventListener('click', clickCallback); } container.appendChild(elem); } } /** * Set the input field value to the current selected date and time */ function updateInputValue() { inputField.value = formatDate(currentDateTime, 'full'); } /** * ###################################################################### * EVENTS */ /** * Is called, when the input field gets focus */ function onInputFocus(event) { // Only do something, if picker isn't opened if (container == null || container.style.display != 'block') { var val = inputField.value; if (val == null || val == '') { currentDateTime = new Date(); } else { // Try to parse the input field value as a predefined current datetime value try { val = val.replace(' ', 'T'); var parts = val.split('T'); if (parts[parts.length - 1].split(':').length == 2) { val += ':00'; } currentDateTime = new Date(val); } catch (e) { currentDateTime = new Date(); } } // Initialize the container with the current month initContainer(); var rect = this.getBoundingClientRect(); container.style.position = 'absolute'; container.style.top = (rect.top + rect.height) + 'px'; container.style.left = rect.left + 'px'; } // The outside click event should not occur event.stopPropagation(); } /** * Is called, when a day is selected. Next step is to select an hour value */ function onDateSelect(event) { // Initialize the clock, if not already done initClock(); var dateArray = this.getAttribute('data-date').split('-'); currentDateTime.setFullYear(parseInt(dateArray[0]), parseInt(dateArray[1])-1, parseInt(dateArray[2])); btnPreviousMonth.style.display = 'none'; btnNextMonth.style.display = 'none'; addClass(calendar, 'datipi-circle-hidden'); window.setTimeout(function () { calendar.style.display = 'none'; headline.innerHTML = 'Select Hour'; clock.style.display = 'block'; }, 350); updateInputValue(); // The outside click event should not occur event.stopPropagation(); } /** * Is called, when a hour is selected. Next step is to select a minute value. */ function onHourTickSelect(event) { headline.innerHTML = 'Select Minutes'; var parent = this.parentElement; currentDateTime.setHours(parseInt(this.innerHTML)); updateInputValue(); addClass(parent, 'datipi-circle-hidden'); removeClass(minutes, 'datipi-circle-hidden'); addClass(minutes, 'datipi-circle-selector'); window.setTimeout(function () { parent.style.display = 'none'; minutes.style.visibility = 'visible'; }, 350); // The outside click event should not occur event.stopPropagation(); } /** * Is called, when a minute is selected. Last step, close the container and update the text box */ function onMinutesTickSelect(event) { currentDateTime.setMinutes(parseInt(this.innerHTML)); container.style.display = 'none'; updateInputValue(); // The outside click event should not occur event.stopPropagation(); } /** * Is called, when the left button is clicked */ function onPreviousMonth(event) { currentDateTime.setMonth(currentDateTime.getMonth() - 1); initCalendar(); // The outside click event should not occur event.stopPropagation(); } /** * Is called, when the right button is clicked */ function onNextMonth(event) { currentDateTime.setMonth(currentDateTime.getMonth() + 1); initCalendar(); // The outside click event should not occur event.stopPropagation(); } function onDocumentClick(e) { if (container != null) { var target = (e && e.target) || (event && event.srcElement); var display = 'none'; while (target.parentNode) { if (target == container || target == inputField) { display = 'block'; break; } target = target.parentNode; } container.style.display = display; } } /** * ###################################################################### * CONSTRUCTOR */ initLanguage(); if (inputField.tagName != 'INPUT') throw 'Error! Only input fields are allowed as date time picker.'; // Event handlers document.addEventListener('click', onDocumentClick); inputField.addEventListener('focus', onInputFocus); }; // Initiate DaTiPi input fields when DOM is ready var ready = false; // Listen for "DOMContentLoaded" document.addEventListener("DOMContentLoaded", init); // Listen for "onreadystatechange" document.onreadystatechange = init; // Listen for "load" document.addEventListener("load", init); // Gets called after any one of the above is triggered. function init() { if (!ready) { ready = true; initElements(); } } function initElements() { var elements = document.querySelectorAll('input.datipi'); for (var i = 0; i < elements.length; i++) { new DATIPI(elements[i]); } } window.DATIPI = datipi; })();
version https://git-lfs.github.com/spec/v1 oid sha256:40d0e59d5fe1ac99c283f7c3ce8c5fda1c372c4991d26565e75dd8d388a8768d size 2166
version https://git-lfs.github.com/spec/v1 oid sha256:cbaaf8e9006e2770060226d4468296a458c65a3c150e55da4ad4e937811c0af3 size 1067062
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u092e.\u092a\u0942.", "\u092e.\u0928\u0902." ], "DAY": [ "\u0906\u0926\u093f\u0924\u094d\u092f\u0935\u093e\u0930", "\u0938\u094b\u092e\u0935\u093e\u0930", "\u092e\u0902\u0917\u0933\u093e\u0930", "\u092c\u0941\u0927\u0935\u093e\u0930", "\u0917\u0941\u0930\u0941\u0935\u093e\u0930", "\u0936\u0941\u0915\u094d\u0930\u0935\u093e\u0930", "\u0936\u0928\u093f\u0935\u093e\u0930" ], "MONTH": [ "\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940", "\u092b\u0947\u092c\u094d\u0930\u0941\u0935\u093e\u0930\u0940", "\u092e\u093e\u0930\u094d\u091a", "\u090f\u092a\u094d\u0930\u093f\u0932", "\u092e\u0947", "\u091c\u0942\u0928", "\u091c\u0941\u0932\u0948", "\u0913\u0917\u0938\u094d\u091f", "\u0938\u0947\u092a\u094d\u091f\u0947\u0902\u092c\u0930", "\u0913\u0915\u094d\u091f\u094b\u092c\u0930", "\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930", "\u0921\u093f\u0938\u0947\u0902\u092c\u0930" ], "SHORTDAY": [ "\u0930\u0935\u093f", "\u0938\u094b\u092e", "\u092e\u0902\u0917\u0933", "\u092c\u0941\u0927", "\u0917\u0941\u0930\u0941", "\u0936\u0941\u0915\u094d\u0930", "\u0936\u0928\u093f" ], "SHORTMONTH": [ "\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940", "\u092b\u0947\u092c\u094d\u0930\u0941\u0935\u093e\u0930\u0940", "\u092e\u093e\u0930\u094d\u091a", "\u090f\u092a\u094d\u0930\u093f\u0932", "\u092e\u0947", "\u091c\u0942\u0928", "\u091c\u0941\u0932\u0948", "\u0913\u0917\u0938\u094d\u091f", "\u0938\u0947\u092a\u094d\u091f\u0947\u0902\u092c\u0930", "\u0913\u0915\u094d\u091f\u094b\u092c\u0930", "\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930", "\u0921\u093f\u0938\u0947\u0902\u092c\u0930" ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "dd-MM-y h:mm:ss a", "mediumDate": "dd-MM-y", "mediumTime": "h:mm:ss a", "short": "d-M-yy h:mm a", "shortDate": "d-M-yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20b9", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 2, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 2, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0-", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "kok-in", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);