From 2dd6a0255071aecc39f2f21e02c98f20177898bc Mon Sep 17 00:00:00 2001 From: Darren Date: Wed, 18 Jul 2012 16:12:14 +0100 Subject: [PATCH] Initial backbone_ui commit --- client_backbone/backbone-git.js | 1260 ++++++++++++++++++++++++++ client_backbone/index.html | 51 ++ client_backbone/jquery-1.7.1.min.js | 4 + client_backbone/model.js | 282 ++++++ client_backbone/model_application.js | 221 +++++ client_backbone/model_gateway.js | 406 +++++++++ client_backbone/style.css | 147 +++ client_backbone/underscore-min.js | 31 + client_backbone/utils.js | 604 ++++++++++++ client_backbone/view.js | 296 ++++++ 10 files changed, 3302 insertions(+) create mode 100644 client_backbone/backbone-git.js create mode 100644 client_backbone/index.html create mode 100644 client_backbone/jquery-1.7.1.min.js create mode 100644 client_backbone/model.js create mode 100644 client_backbone/model_application.js create mode 100644 client_backbone/model_gateway.js create mode 100644 client_backbone/style.css create mode 100644 client_backbone/underscore-min.js create mode 100644 client_backbone/utils.js create mode 100644 client_backbone/view.js diff --git a/client_backbone/backbone-git.js b/client_backbone/backbone-git.js new file mode 100644 index 0000000..80c1fc3 --- /dev/null +++ b/client_backbone/backbone-git.js @@ -0,0 +1,1260 @@ +// Backbone.js 0.5.3 +// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. +// Backbone may be freely distributed under the MIT license. +// For all details and documentation: +// http://backbonejs.org + +(function(){ + + // Initial Setup + // ------------- + + // Save a reference to the global object (`window` in the browser, `global` + // on the server). + var root = this; + + // Save the previous value of the `Backbone` variable, so that it can be + // restored later on, if `noConflict` is used. + var previousBackbone = root.Backbone; + + // Create a local reference to slice/splice. + var slice = Array.prototype.slice; + var splice = Array.prototype.splice; + + // The top-level namespace. All public Backbone classes and modules will + // be attached to this. Exported for both CommonJS and the browser. + var Backbone; + if (typeof exports !== 'undefined') { + Backbone = exports; + } else { + Backbone = root.Backbone = {}; + } + + // Current version of the library. Keep in sync with `package.json`. + Backbone.VERSION = '0.5.3'; + + // Require Underscore, if we're on the server, and it's not already present. + var _ = root._; + if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); + + // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable. + var $ = root.jQuery || root.Zepto || root.ender; + + // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable + // to its previous owner. Returns a reference to this Backbone object. + Backbone.noConflict = function() { + root.Backbone = previousBackbone; + return this; + }; + + // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option + // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and + // set a `X-Http-Method-Override` header. + Backbone.emulateHTTP = false; + + // Turn on `emulateJSON` to support legacy servers that can't deal with direct + // `application/json` requests ... will encode the body as + // `application/x-www-form-urlencoded` instead and will send the model in a + // form param named `model`. + Backbone.emulateJSON = false; + + // Backbone.Events + // ----------------- + + // A module that can be mixed in to *any object* in order to provide it with + // custom events. You may bind with `on` or remove with `off` callback functions + // to an event; trigger`-ing an event fires all callbacks in succession. + // + // var object = {}; + // _.extend(object, Backbone.Events); + // object.on('expand', function(){ alert('expanded'); }); + // object.trigger('expand'); + // + Backbone.Events = { + + // Bind an event, specified by a string name, `ev`, to a `callback` + // function. Passing `"all"` will bind the callback to all events fired. + on: function(events, callback, context) { + var ev; + events = events.split(/\s+/); + var calls = this._callbacks || (this._callbacks = {}); + while (ev = events.shift()) { + // Create an immutable callback list, allowing traversal during + // modification. The tail is an empty object that will always be used + // as the next node. + var list = calls[ev] || (calls[ev] = {}); + var tail = list.tail || (list.tail = list.next = {}); + tail.callback = callback; + tail.context = context; + list.tail = tail.next = {}; + } + return this; + }, + + // Remove one or many callbacks. If `context` is null, removes all callbacks + // with that function. If `callback` is null, removes all callbacks for the + // event. If `ev` is null, removes all bound callbacks for all events. + off: function(events, callback, context) { + var ev, calls, node; + if (!events) { + delete this._callbacks; + } else if (calls = this._callbacks) { + events = events.split(/\s+/); + while (ev = events.shift()) { + node = calls[ev]; + delete calls[ev]; + if (!callback || !node) continue; + // Create a new list, omitting the indicated event/context pairs. + while ((node = node.next) && node.next) { + if (node.callback === callback && + (!context || node.context === context)) continue; + this.on(ev, node.callback, node.context); + } + } + } + return this; + }, + + // Trigger an event, firing all bound callbacks. Callbacks are passed the + // same arguments as `trigger` is, apart from the event name. + // Listening for `"all"` passes the true event name as the first argument. + trigger: function(events) { + var event, node, calls, tail, args, all, rest; + if (!(calls = this._callbacks)) return this; + all = calls['all']; + (events = events.split(/\s+/)).push(null); + // Save references to the current heads & tails. + while (event = events.shift()) { + if (all) events.push({next: all.next, tail: all.tail, event: event}); + if (!(node = calls[event])) continue; + events.push({next: node.next, tail: node.tail}); + } + // Traverse each list, stopping when the saved tail is reached. + rest = slice.call(arguments, 1); + while (node = events.pop()) { + tail = node.tail; + args = node.event ? [node.event].concat(rest) : rest; + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, args); + } + } + return this; + } + + }; + + // Aliases for backwards compatibility. + Backbone.Events.bind = Backbone.Events.on; + Backbone.Events.unbind = Backbone.Events.off; + + // Backbone.Model + // -------------- + + // Create a new model, with defined attributes. A client id (`cid`) + // is automatically generated and assigned for you. + Backbone.Model = function(attributes, options) { + var defaults; + attributes || (attributes = {}); + if (options && options.parse) attributes = this.parse(attributes); + if (defaults = getValue(this, 'defaults')) { + attributes = _.extend({}, defaults, attributes); + } + if (options && options.collection) this.collection = options.collection; + this.attributes = {}; + this._escapedAttributes = {}; + this.cid = _.uniqueId('c'); + if (!this.set(attributes, {silent: true})) { + throw new Error("Can't create an invalid model"); + } + this._changed = false; + this._previousAttributes = _.clone(this.attributes); + this.initialize.apply(this, arguments); + }; + + // Attach all inheritable methods to the Model prototype. + _.extend(Backbone.Model.prototype, Backbone.Events, { + + // Has the item been changed since the last `"change"` event? + _changed: false, + + // The default name for the JSON `id` attribute is `"id"`. MongoDB and + // CouchDB users may want to set this to `"_id"`. + idAttribute: 'id', + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Return a copy of the model's `attributes` object. + toJSON: function() { + return _.clone(this.attributes); + }, + + // Get the value of an attribute. + get: function(attr) { + return this.attributes[attr]; + }, + + // Get the HTML-escaped value of an attribute. + escape: function(attr) { + var html; + if (html = this._escapedAttributes[attr]) return html; + var val = this.attributes[attr]; + return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val); + }, + + // Returns `true` if the attribute contains a value that is not null + // or undefined. + has: function(attr) { + return this.attributes[attr] != null; + }, + + // Set a hash of model attributes on the object, firing `"change"` unless + // you choose to silence it. + set: function(key, value, options) { + var attrs, attr, val; + if (_.isObject(key) || key == null) { + attrs = key; + options = value; + } else { + attrs = {}; + attrs[key] = value; + } + + // Extract attributes and options. + options || (options = {}); + if (!attrs) return this; + if (attrs instanceof Backbone.Model) attrs = attrs.attributes; + if (options.unset) for (var attr in attrs) attrs[attr] = void 0; + var now = this.attributes, escaped = this._escapedAttributes; + + // Run validation. + if (this.validate && !this._performValidation(attrs, options)) return false; + + // Check for changes of `id`. + if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; + + // We're about to start triggering change events. + var alreadyChanging = this._changing; + this._changing = true; + + // Update attributes. + var changes = {}; + for (attr in attrs) { + val = attrs[attr]; + if (!_.isEqual(now[attr], val) || (options.unset && (attr in now))) { + delete escaped[attr]; + this._changed = true; + changes[attr] = val; + } + options.unset ? delete now[attr] : now[attr] = val; + } + + // Fire `change:attribute` events. + for (var attr in changes) { + if (!options.silent) this.trigger('change:' + attr, this, changes[attr], options); + } + + // Fire the `"change"` event, if the model has been changed. + if (!alreadyChanging) { + if (!options.silent && this._changed) this.change(options); + this._changing = false; + } + return this; + }, + + // Remove an attribute from the model, firing `"change"` unless you choose + // to silence it. `unset` is a noop if the attribute doesn't exist. + unset: function(attr, options) { + (options || (options = {})).unset = true; + return this.set(attr, null, options); + }, + + // Clear all attributes on the model, firing `"change"` unless you choose + // to silence it. + clear: function(options) { + (options || (options = {})).unset = true; + return this.set(_.clone(this.attributes), options); + }, + + // Fetch the model from the server. If the server's representation of the + // model differs from its current attributes, they will be overriden, + // triggering a `"change"` event. + fetch: function(options) { + options = options ? _.clone(options) : {}; + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + if (!model.set(model.parse(resp, xhr), options)) return false; + if (success) success(model, resp); + }; + options.error = Backbone.wrapError(options.error, model, options); + return (this.sync || Backbone.sync).call(this, 'read', this, options); + }, + + // Set a hash of model attributes, and sync the model to the server. + // If the server returns an attributes hash that differs, the model's + // state will be `set` again. + save: function(key, value, options) { + var attrs; + if (_.isObject(key) || key == null) { + attrs = key; + options = value; + } else { + attrs = {}; + attrs[key] = value; + } + + options = options ? _.clone(options) : {}; + if (attrs && !this[options.wait ? '_performValidation' : 'set'](attrs, options)) return false; + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + var serverAttrs = model.parse(resp, xhr); + if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); + if (!model.set(serverAttrs, options)) return false; + if (success) { + success(model, resp); + } else { + model.trigger('sync', model, resp, options); + } + }; + options.error = Backbone.wrapError(options.error, model, options); + var method = this.isNew() ? 'create' : 'update'; + return (this.sync || Backbone.sync).call(this, method, this, options); + }, + + // Destroy this model on the server if it was already persisted. + // Optimistically removes the model from its collection, if it has one. + // If `wait: true` is passed, waits for the server to respond before removal. + destroy: function(options) { + options = options ? _.clone(options) : {}; + var model = this; + var success = options.success; + + var triggerDestroy = function() { + model.trigger('destroy', model, model.collection, options); + }; + + if (this.isNew()) return triggerDestroy(); + options.success = function(resp) { + if (options.wait) triggerDestroy(); + if (success) { + success(model, resp); + } else { + model.trigger('sync', model, resp, options); + } + }; + options.error = Backbone.wrapError(options.error, model, options); + var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options); + if (!options.wait) triggerDestroy(); + return xhr; + }, + + // Default URL for the model's representation on the server -- if you're + // using Backbone's restful methods, override this to change the endpoint + // that will be called. + url: function() { + var base = getValue(this.collection, 'url') || getValue(this, 'urlRoot') || urlError(); + if (this.isNew()) return base; + return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); + }, + + // **parse** converts a response into the hash of attributes to be `set` on + // the model. The default implementation is just to pass the response along. + parse: function(resp, xhr) { + return resp; + }, + + // Create a new model with identical attributes to this one. + clone: function() { + return new this.constructor(this.attributes); + }, + + // A model is new if it has never been saved to the server, and lacks an id. + isNew: function() { + return this.id == null; + }, + + // Call this method to manually fire a `change` event for this model. + // Calling this will cause all objects observing the model to update. + change: function(options) { + this.trigger('change', this, options); + this._previousAttributes = _.clone(this.attributes); + this._changed = false; + }, + + // Determine if the model has changed since the last `"change"` event. + // If you specify an attribute name, determine if that attribute has changed. + hasChanged: function(attr) { + if (attr) return !_.isEqual(this._previousAttributes[attr], this.attributes[attr]); + return this._changed; + }, + + // Return an object containing all the attributes that have changed, or + // false if there are no changed attributes. Useful for determining what + // parts of a view need to be updated and/or what attributes need to be + // persisted to the server. Unset attributes will be set to undefined. + changedAttributes: function(now) { + if (!this._changed) return false; + now || (now = this.attributes); + var changed = false, old = this._previousAttributes; + for (var attr in now) { + if (_.isEqual(old[attr], now[attr])) continue; + (changed || (changed = {}))[attr] = now[attr]; + } + for (var attr in old) { + if (!(attr in now)) (changed || (changed = {}))[attr] = void 0; + } + return changed; + }, + + // Get the previous value of an attribute, recorded at the time the last + // `"change"` event was fired. + previous: function(attr) { + if (!attr || !this._previousAttributes) return null; + return this._previousAttributes[attr]; + }, + + // Get all of the attributes of the model at the time of the previous + // `"change"` event. + previousAttributes: function() { + return _.clone(this._previousAttributes); + }, + + // Run validation against a set of incoming attributes, returning `true` + // if all is well. If a specific `error` callback has been passed, + // call that instead of firing the general `"error"` event. + _performValidation: function(attrs, options) { + var newAttrs = _.extend({}, this.attributes, attrs); + var error = this.validate(newAttrs, options); + if (error) { + if (options.error) { + options.error(this, error, options); + } else { + this.trigger('error', this, error, options); + } + return false; + } + return true; + } + + }); + + // Backbone.Collection + // ------------------- + + // Provides a standard collection class for our sets of models, ordered + // or unordered. If a `comparator` is specified, the Collection will maintain + // its models in sort order, as they're added and removed. + Backbone.Collection = function(models, options) { + options || (options = {}); + if (options.comparator) this.comparator = options.comparator; + this._reset(); + this.initialize.apply(this, arguments); + if (models) this.reset(models, {silent: true, parse: options.parse}); + }; + + // Define the Collection's inheritable methods. + _.extend(Backbone.Collection.prototype, Backbone.Events, { + + // The default model for a collection is just a **Backbone.Model**. + // This should be overridden in most cases. + model: Backbone.Model, + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // The JSON representation of a Collection is an array of the + // models' attributes. + toJSON: function() { + return this.map(function(model){ return model.toJSON(); }); + }, + + // Add a model, or list of models to the set. Pass **silent** to avoid + // firing the `add` event for every new model. + add: function(models, options) { + var i, index, length, model, cids = {}; + options || (options = {}); + models = _.isArray(models) ? models.slice() : [models]; + + // Begin by turning bare objects into model references, and preventing + // invalid models or duplicate models from being added. + for (i = 0, length = models.length; i < length; i++) { + if (!(model = models[i] = this._prepareModel(models[i], options))) { + throw new Error("Can't add an invalid model to a collection"); + } + var hasId = model.id != null; + if (this._byCid[model.cid] || (hasId && this._byId[model.id])) { + throw new Error("Can't add the same model to a collection twice"); + } + } + + // Listen to added models' events, and index models for lookup by + // `id` and by `cid`. + for (i = 0; i < length; i++) { + (model = models[i]).on('all', this._onModelEvent, this); + this._byCid[model.cid] = model; + if (model.id != null) this._byId[model.id] = model; + cids[model.cid] = true; + } + + // Insert models into the collection, re-sorting if needed, and triggering + // `add` events unless silenced. + this.length += length; + index = options.at != null ? options.at : this.models.length; + splice.apply(this.models, [index, 0].concat(models)); + if (this.comparator) this.sort({silent: true}); + if (options.silent) return this; + for (i = 0, length = this.models.length; i < length; i++) { + if (!cids[(model = this.models[i]).cid]) continue; + options.index = i; + model.trigger('add', model, this, options); + } + return this; + }, + + // Remove a model, or a list of models from the set. Pass silent to avoid + // firing the `remove` event for every model removed. + remove: function(models, options) { + var i, l, index, model; + options || (options = {}); + models = _.isArray(models) ? models.slice() : [models]; + for (i = 0, l = models.length; i < l; i++) { + model = this.getByCid(models[i]) || this.get(models[i]); + if (!model) continue; + delete this._byId[model.id]; + delete this._byCid[model.cid]; + index = this.indexOf(model); + this.models.splice(index, 1); + this.length--; + if (!options.silent) { + options.index = index; + model.trigger('remove', model, this, options); + } + this._removeReference(model); + } + return this; + }, + + // Get a model from the set by id. + get: function(id) { + if (id == null) return null; + return this._byId[id.id != null ? id.id : id]; + }, + + // Get a model from the set by client id. + getByCid: function(cid) { + return cid && this._byCid[cid.cid || cid]; + }, + + // Get the model at the given index. + at: function(index) { + return this.models[index]; + }, + + // Force the collection to re-sort itself. You don't need to call this under + // normal circumstances, as the set will maintain sort order as each item + // is added. + sort: function(options) { + options || (options = {}); + if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); + var boundComparator = _.bind(this.comparator, this); + if (this.comparator.length == 1) { + this.models = this.sortBy(boundComparator); + } else { + this.models.sort(boundComparator); + } + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Pluck an attribute from each model in the collection. + pluck: function(attr) { + return _.map(this.models, function(model){ return model.get(attr); }); + }, + + // When you have more items than you want to add or remove individually, + // you can reset the entire set with a new list of models, without firing + // any `add` or `remove` events. Fires `reset` when finished. + reset: function(models, options) { + models || (models = []); + options || (options = {}); + for (var i = 0, l = this.models.length; i < l; i++) { + this._removeReference(this.models[i]); + } + this._reset(); + this.add(models, {silent: true, parse: options.parse}); + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Fetch the default set of models for this collection, resetting the + // collection when they arrive. If `add: true` is passed, appends the + // models to the collection instead of resetting. + fetch: function(options) { + options = options ? _.clone(options) : {}; + if (options.parse === undefined) options.parse = true; + var collection = this; + var success = options.success; + options.success = function(resp, status, xhr) { + collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); + if (success) success(collection, resp); + }; + options.error = Backbone.wrapError(options.error, collection, options); + return (this.sync || Backbone.sync).call(this, 'read', this, options); + }, + + // Create a new instance of a model in this collection. Add the model to the + // collection immediately, unless `wait: true` is passed, in which case we + // wait for the server to agree. + create: function(model, options) { + var coll = this; + options = options ? _.clone(options) : {}; + model = this._prepareModel(model, options); + if (!model) return false; + if (!options.wait) coll.add(model, options); + var success = options.success; + options.success = function(nextModel, resp, xhr) { + if (options.wait) coll.add(nextModel, options); + if (success) { + success(nextModel, resp); + } else { + nextModel.trigger('sync', model, resp, options); + } + }; + model.save(null, options); + return model; + }, + + // **parse** converts a response into a list of models to be added to the + // collection. The default implementation is just to pass it through. + parse: function(resp, xhr) { + return resp; + }, + + // Proxy to _'s chain. Can't be proxied the same way the rest of the + // underscore methods are proxied because it relies on the underscore + // constructor. + chain: function () { + return _(this.models).chain(); + }, + + // Reset all internal state. Called when the collection is reset. + _reset: function(options) { + this.length = 0; + this.models = []; + this._byId = {}; + this._byCid = {}; + }, + + // Prepare a model or hash of attributes to be added to this collection. + _prepareModel: function(model, options) { + if (!(model instanceof Backbone.Model)) { + var attrs = model; + options.collection = this; + model = new this.model(attrs, options); + if (model.validate && !model._performValidation(model.attributes, options)) model = false; + } else if (!model.collection) { + model.collection = this; + } + return model; + }, + + // Internal method to remove a model's ties to a collection. + _removeReference: function(model) { + if (this == model.collection) { + delete model.collection; + } + model.off('all', this._onModelEvent, this); + }, + + // Internal method called every time a model in the set fires an event. + // Sets need to update their indexes when models change ids. All other + // events simply proxy through. "add" and "remove" events that originate + // in other collections are ignored. + _onModelEvent: function(ev, model, collection, options) { + if ((ev == 'add' || ev == 'remove') && collection != this) return; + if (ev == 'destroy') { + this.remove(model, options); + } + if (model && ev === 'change:' + model.idAttribute) { + delete this._byId[model.previous(model.idAttribute)]; + this._byId[model.id] = model; + } + this.trigger.apply(this, arguments); + } + + }); + + // Underscore methods that we want to implement on the Collection. + var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', + 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', + 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', + 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf', + 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy']; + + // Mix in each Underscore method as a proxy to `Collection#models`. + _.each(methods, function(method) { + Backbone.Collection.prototype[method] = function() { + return _[method].apply(_, [this.models].concat(_.toArray(arguments))); + }; + }); + + // Backbone.Router + // ------------------- + + // Routers map faux-URLs to actions, and fire events when routes are + // matched. Creating a new one sets its `routes` hash, if not set statically. + Backbone.Router = function(options) { + options || (options = {}); + if (options.routes) this.routes = options.routes; + this._bindRoutes(); + this.initialize.apply(this, arguments); + }; + + // Cached regular expressions for matching named param parts and splatted + // parts of route strings. + var namedParam = /:\w+/g; + var splatParam = /\*\w+/g; + var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; + + // Set up all inheritable **Backbone.Router** properties and methods. + _.extend(Backbone.Router.prototype, Backbone.Events, { + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Manually bind a single named route to a callback. For example: + // + // this.route('search/:query/p:num', 'search', function(query, num) { + // ... + // }); + // + route: function(route, name, callback) { + Backbone.history || (Backbone.history = new Backbone.History); + if (!_.isRegExp(route)) route = this._routeToRegExp(route); + if (!callback) callback = this[name]; + Backbone.history.route(route, _.bind(function(fragment) { + var args = this._extractParameters(route, fragment); + callback && callback.apply(this, args); + this.trigger.apply(this, ['route:' + name].concat(args)); + Backbone.history.trigger('route', this, name, args); + }, this)); + }, + + // Simple proxy to `Backbone.history` to save a fragment into the history. + navigate: function(fragment, options) { + Backbone.history.navigate(fragment, options); + }, + + // Bind all defined routes to `Backbone.history`. We have to reverse the + // order of the routes here to support behavior where the most general + // routes can be defined at the bottom of the route map. + _bindRoutes: function() { + if (!this.routes) return; + var routes = []; + for (var route in this.routes) { + routes.unshift([route, this.routes[route]]); + } + for (var i = 0, l = routes.length; i < l; i++) { + this.route(routes[i][0], routes[i][1], this[routes[i][1]]); + } + }, + + // Convert a route string into a regular expression, suitable for matching + // against the current location hash. + _routeToRegExp: function(route) { + route = route.replace(escapeRegExp, '\\$&') + .replace(namedParam, '([^\/]+)') + .replace(splatParam, '(.*?)'); + return new RegExp('^' + route + '$'); + }, + + // Given a route, and a URL fragment that it matches, return the array of + // extracted parameters. + _extractParameters: function(route, fragment) { + return route.exec(fragment).slice(1); + } + + }); + + // Backbone.History + // ---------------- + + // Handles cross-browser history management, based on URL fragments. If the + // browser does not support `onhashchange`, falls back to polling. + Backbone.History = function() { + this.handlers = []; + _.bindAll(this, 'checkUrl'); + }; + + // Cached regex for cleaning leading hashes and slashes . + var routeStripper = /^[#\/]/; + + // Cached regex for detecting MSIE. + var isExplorer = /msie [\w.]+/; + + // Has the history handling already been started? + var historyStarted = false; + + // Set up all inheritable **Backbone.History** properties and methods. + _.extend(Backbone.History.prototype, Backbone.Events, { + + // The default interval to poll for hash changes, if necessary, is + // twenty times a second. + interval: 50, + + // Get the cross-browser normalized URL fragment, either from the URL, + // the hash, or the override. + getFragment: function(fragment, forcePushState) { + if (fragment == null) { + if (this._hasPushState || forcePushState) { + fragment = window.location.pathname; + var search = window.location.search; + if (search) fragment += search; + } else { + fragment = window.location.hash; + } + } + fragment = decodeURIComponent(fragment.replace(routeStripper, '')); + if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length); + return fragment; + }, + + // Start the hash change handling, returning `true` if the current URL matches + // an existing route, and `false` otherwise. + start: function(options) { + + // Figure out the initial configuration. Do we need an iframe? + // Is pushState desired ... is it available? + if (historyStarted) throw new Error("Backbone.history has already been started"); + this.options = _.extend({}, {root: '/'}, this.options, options); + this._wantsHashChange = this.options.hashChange !== false; + this._wantsPushState = !!this.options.pushState; + this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState); + var fragment = this.getFragment(); + var docMode = document.documentMode; + var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); + if (oldIE) { + this.iframe = $(''); + t.iframe.attr('src', a.attr('href')); + t.div.append(t.iframe); + t.show(); + break; + } + return false; + + } + }, + */ + + { + name: "nick_colour", + onaddmsg: function (event, opts) { + if (!event.msg) { + return event; + } + + //if (typeof kiwi.front.tabviews[event.tabview].nick_colours === 'undefined') { + // kiwi.front.tabviews[event.tabview].nick_colours = {}; + //} + + //if (typeof kiwi.front.tabviews[event.tabview].nick_colours[event.nick] === 'undefined') { + // kiwi.front.tabviews[event.tabview].nick_colours[event.nick] = this.randColour(); + //} + + //var c = kiwi.front.tabviews[event.tabview].nick_colours[event.nick]; + var c = this.randColour(); + event.nick = '' + event.nick + ''; + + return event; + }, + + + + randColour: function () { + var h = this.rand(-250, 0), + s = this.rand(30, 100), + l = this.rand(20, 70); + return 'hsl(' + h + ',' + s + '%,' + l + '%)'; + }, + + + rand: function (min, max) { + return parseInt(Math.random() * (max - min + 1), 10) + min; + } + }, + + { + name: "kiwitest", + oninit: function (event, opts) { + console.log('registering namespace'); + $(gateway).bind("kiwi.lol.browser", function (e, data) { + console.log('YAY kiwitest'); + console.log(data); + }); + } + } +]; + + + + + + + +/** +* @namespace +*/ +kiwi.plugs = {}; +/** +* Loaded plugins +*/ +kiwi.plugs.loaded = {}; +/** +* Load a plugin +* @param {Object} plugin The plugin to be loaded +* @returns {Boolean} True on success, false on failure +*/ +kiwi.plugs.loadPlugin = function (plugin) { + var plugin_ret; + if (typeof plugin.name !== 'string') { + return false; + } + + plugin_ret = kiwi.plugs.run('plugin_load', {plugin: plugin}); + if (typeof plugin_ret === 'object') { + kiwi.plugs.loaded[plugin_ret.plugin.name] = plugin_ret.plugin; + kiwi.plugs.loaded[plugin_ret.plugin.name].local_data = new kiwi.dataStore('kiwi_plugin_' + plugin_ret.plugin.name); + } + kiwi.plugs.run('init', {}, {run_only: plugin_ret.plugin.name}); + + return true; +}; + +/** +* Unload a plugin +* @param {String} plugin_name The name of the plugin to unload +*/ +kiwi.plugs.unloadPlugin = function (plugin_name) { + if (typeof kiwi.plugs.loaded[plugin_name] !== 'object') { + return; + } + + kiwi.plugs.run('unload', {}, {run_only: plugin_name}); + delete kiwi.plugs.loaded[plugin_name]; +}; + + + +/** +* Run an event against all loaded plugins +* @param {String} event_name The name of the event +* @param {Object} event_data The data to pass to the plugin +* @param {Object} opts Options +* @returns {Object} Event data, possibly modified by the plugins +*/ +kiwi.plugs.run = function (event_name, event_data, opts) { + var ret = event_data, + ret_tmp, + plugin_name; + + // Set some defaults if not provided + event_data = (typeof event_data === 'undefined') ? {} : event_data; + opts = (typeof opts === 'undefined') ? {} : opts; + + for (plugin_name in kiwi.plugs.loaded) { + // If we're only calling 1 plugin, make sure it's that one + if (typeof opts.run_only === 'string' && opts.run_only !== plugin_name) { + continue; + } + + if (typeof kiwi.plugs.loaded[plugin_name]['on' + event_name] === 'function') { + try { + ret_tmp = kiwi.plugs.loaded[plugin_name]['on' + event_name](ret, opts); + if (ret_tmp === null) { + return null; + } + ret = ret_tmp; + + if (typeof ret.event_bubbles === 'boolean' && ret.event_bubbles === false) { + delete ret.event_bubbles; + return ret; + } + } catch (e) { + } + } + } + + return ret; +}; + + + +/** +* @constructor +* @param {String} data_namespace The namespace for the data store +*/ +kiwi.dataStore = function (data_namespace) { + var namespace = data_namespace; + + this.get = function (key) { + return $.jStorage.get(data_namespace + '_' + key); + }; + + this.set = function (key, value) { + return $.jStorage.set(data_namespace + '_' + key, value); + }; +}; + +kiwi.data = new kiwi.dataStore('kiwi'); + + + + +/* + * jQuery jStorage plugin + * https://github.com/andris9/jStorage/ + */ +(function(f){if(!f||!(f.toJSON||Object.toJSON||window.JSON)){throw new Error("jQuery, MooTools or Prototype needs to be loaded before jStorage!")}var g={},d={jStorage:"{}"},h=null,j=0,l=f.toJSON||Object.toJSON||(window.JSON&&(JSON.encode||JSON.stringify)),e=f.evalJSON||(window.JSON&&(JSON.decode||JSON.parse))||function(m){return String(m).evalJSON()},i=false;_XMLService={isXML:function(n){var m=(n?n.ownerDocument||n:0).documentElement;return m?m.nodeName!=="HTML":false},encode:function(n){if(!this.isXML(n)){return false}try{return new XMLSerializer().serializeToString(n)}catch(m){try{return n.xml}catch(o){}}return false},decode:function(n){var m=("DOMParser" in window&&(new DOMParser()).parseFromString)||(window.ActiveXObject&&function(p){var q=new ActiveXObject("Microsoft.XMLDOM");q.async="false";q.loadXML(p);return q}),o;if(!m){return false}o=m.call("DOMParser" in window&&(new DOMParser())||window,n,"text/xml");return this.isXML(o)?o:false}};function k(){if("localStorage" in window){try{if(window.localStorage){d=window.localStorage;i="localStorage"}}catch(p){}}else{if("globalStorage" in window){try{if(window.globalStorage){d=window.globalStorage[window.location.hostname];i="globalStorage"}}catch(o){}}else{h=document.createElement("link");if(h.addBehavior){h.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(h);h.load("jStorage");var n="{}";try{n=h.getAttribute("jStorage")}catch(m){}d.jStorage=n;i="userDataBehavior"}else{h=null;return}}}b()}function b(){if(d.jStorage){try{g=e(String(d.jStorage))}catch(m){d.jStorage="{}"}}else{d.jStorage="{}"}j=d.jStorage?String(d.jStorage).length:0}function c(){try{d.jStorage=l(g);if(h){h.setAttribute("jStorage",d.jStorage);h.save("jStorage")}j=d.jStorage?String(d.jStorage).length:0}catch(m){}}function a(m){if(!m||(typeof m!="string"&&typeof m!="number")){throw new TypeError("Key name must be string or numeric")}return true}f.jStorage={version:"0.1.5.1",set:function(m,n){a(m);if(_XMLService.isXML(n)){n={_is_xml:true,xml:_XMLService.encode(n)}}g[m]=n;c();return n},get:function(m,n){a(m);if(m in g){if(g[m]&&typeof g[m]=="object"&&g[m]._is_xml&&g[m]._is_xml){return _XMLService.decode(g[m].xml)}else{return g[m]}}return typeof(n)=="undefined"?null:n},deleteKey:function(m){a(m);if(m in g){delete g[m];c();return true}return false},flush:function(){g={};c();return true},storageObj:function(){function m(){}m.prototype=g;return new m()},index:function(){var m=[],n;for(n in g){if(g.hasOwnProperty(n)){m.push(n)}}return m},storageSize:function(){return j},currentBackend:function(){return i},storageAvailable:function(){return !!i},reInit:function(){var m,o;if(h&&h.addBehavior){m=document.createElement("link");h.parentNode.replaceChild(m,h);h=m;h.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(h);h.load("jStorage");o="{}";try{o=h.getAttribute("jStorage")}catch(n){}d.jStorage=o;i="userDataBehavior"}b()}};k()})(window.jQuery||window.$); \ No newline at end of file diff --git a/client_backbone/view.js b/client_backbone/view.js new file mode 100644 index 0000000..a7172c9 --- /dev/null +++ b/client_backbone/view.js @@ -0,0 +1,296 @@ +/*jslint white:true, regexp: true, nomen: true, devel: true, undef: true, browser: true, continue: true, sloppy: true, forin: true, newcap: true, plusplus: true, maxerr: 50, indent: 4 */ +/*global kiwi */ + +kiwi.view = {}; + +kiwi.view.MemberList = Backbone.View.extend({ + tagName: "ul", + events: { + "click .nick": "nickClick" + }, + initialize: function (options) { + this.model.bind('all', this.render, this); + $(this.el).appendTo('#memberlists'); + }, + render: function () { + var $this = $(this.el); + $this.empty(); + this.model.forEach(function (member) { + $('
  • ' + member.get("prefix") + '' + member.get("nick") + '
  • ').appendTo($this).data('member', member); + }); + }, + nickClick: function (x) { + console.log(x); + }, + show: function () { + $('#memberlists').children().removeClass('active'); + $(this.el).addClass('active'); + } +}); + +kiwi.view.Panel = Backbone.View.extend({ + tagName: "div", + className: "messages", + events: { + "click .chan": "chanClick" + }, + initialize: function (options) { + this.initializePanel(options); + }, + + initializePanel: function (options) { + this.$el.css('display', 'none'); + + this.$container = $('#panels .container1'); + this.$el.appendTo(this.$container); + + this.model.bind('msg', this.newMsg, this); + this.msg_count = 0; + + this.model.set({"view": this}, {"silent": true}); + }, + + render: function () { + var $this = $(this.el); + $this.empty(); + this.model.get("backscroll").forEach(this.newMsg); + }, + newMsg: function (msg) { + // TODO: make sure that the message pane is scrolled to the bottom (Or do we? ~Darren) + var re, line_msg, $this = this.$el; + + // Make the channels clickable + // TODO: HTML parsing may be going into the model.. move this? + re = new RegExp('\\B(' + kiwi.gateway.channel_prefix + '[^ ,.\\007]+)', 'g'); + msg.msg = msg.msg.replace(re, function (match) { + return '' + match + ''; + }); + + // Build up and add the line + line_msg = '
    <%- time %>
    <%- nick %>
    <%= msg %>
    '; + $this.append(_.template(line_msg, msg)); + + // Make sure our DOM isn't getting too large (Acts as scrollback) + this.msg_count++; + if (this.msg_count > 250) { + $('.msg:first', this.div).remove(); + this.msg_count--; + } + }, + chanClick: function (x) { + console.log(x); + }, + show: function () { + var $this = this.$el; + + // Hide all other panels and show this one + this.$container.children().css('display', 'none'); + $this.css('display', 'block'); + + // Show this panels memberlist + var members = this.model.get("members"); + if (members) { + members.view.show(); + } else { + // Memberlist not found for this panel, hide any active ones + $('#memberlists').children().removeClass('active'); + } + + // TODO: Why is kiwi.app not defined when this is fist called :/ + if (kiwi.app) { + kiwi.app.setCurrentTopic(this.model.get("topic") || ""); + } + + kiwi.current_panel = this.model; + } +}); + +kiwi.view.Channel = kiwi.view.Panel.extend({ + initialize: function (options) { + this.initializePanel(options); + this.model.bind('change:topic', this.topic, this); + }, + + topic: function (topic) { + if (typeof topic !== 'string' || !topic) { + topic = this.model.get("topic"); + } + + this.model.addMsg('', '=== Topic for ' + this.model.get('name') + ' is: ' + topic, 'topic'); + if ($(this.el).css('display') === 'block') { + // TODO: Update the active topic bar + //kiwi.front.ui.setTopicText(this.model.get("topic")); + } + } +}); + +kiwi.view.Tabs = Backbone.View.extend({ + events: { + "click li": "tabClick" + }, + initialize: function () { + this.model.on("add", this.panelAdded, this); + this.model.on("remove", this.panelRemoved, this); + this.model.on("reset", this.render, this); + }, + render: function () { + var that = this; + $this = $(this.el); + $this.empty(); + + // Add the server tab first + $('
  • ' + kiwi.gateway.get('name') + '
  • ') + .data('panel_id', this.model.server.cid) + .appendTo($this); + + this.model.forEach(function (panel) { + // If this si the server panel, ignor as it's already added + if (panel == that.model.server) return; + + $('
  • ' + panel.get("name") + '
  • ') + .data('panel_id', panel.cid) + .appendTo($this); + }); + }, + + panelAdded: function (panel) { + panel.tab = $('
  • ' + panel.get("name") + '
  • '); + panel.tab.data('panel_id', panel.cid) + .appendTo(this.$el); + }, + panelRemoved: function (panel) { + $(panel.tab).remove(); + panel.view.remove(); + panel.destroy(); + }, + + tabClick: function (e) { + this.$el.children().removeClass('active'); + + var panel = this.model.getByCid($(e.currentTarget).data('panel_id')); + if (!panel) { + // A panel wasn't found for this tab... wadda fuck + return; + } + + panel.tab.addClass('active'); + panel.view.show(); + } +}); + + + +kiwi.view.ControlBox = Backbone.View.extend({ + that: this, + + buffer: [], // Stores previously run commands + buffer_pos: 0, // The current position in the buffer + + events: { + 'keydown input': 'process' + }, + + initialize: function () { + that = this; + + kiwi.gateway.bind('change:nick', function () { + $('.nick', that.$el).text(this.get('nick')); + }); + }, + + process: function (ev) { + var inp = $(ev.currentTarget); + + switch (true) { + case (ev.keyCode === 13): // return + this.processInput(inp.val()); + + this.buffer.push(inp.val()); + this.buffer_pos = this.buffer.length; + + inp.val(''); + + break; + + case (ev.keyCode === 38): // up + if (this.buffer_pos > 0) { + this.buffer_pos--; + inp.val(this.buffer[this.buffer_pos]); + } + break; + + case (ev.keyCode === 40): + if (this.buffer_pos < this.buffer.length) { + this.buffer_pos++; + inp.val(this.buffer[this.buffer_pos]); + } + } + }, + + + processInput: function (command_raw) { + var command, + params = command_raw.split(' '); + + // Extract the command and parameters + if (params[0][0] === '/') { + command = params[0].substr(1).toLowerCase(); + params = params.splice(1); + } else { + command = 'msg'; + } + + // Trigger the command events + this.trigger('command', {command: command, params: params}); + this.trigger('command_' + command, {command: command, params: params}); + } +}); + + + + + +// This *may* be needed in future +kiwi.view.Application = Backbone.View.extend({ + initialize: function () { + $(window).resize(this.doLayout); + $('#toolbar').resize(this.doLayout); + $('#controlbox').resize(this.doLayout); + + this.doLayout(); + + $(window).keydown(this.setKeyFocus); + }, + + + // Globally shift focus to the command input box on a keypress + setKeyFocus: function (ev) { + // If we're copying text, don't shift focus + if (ev.ctrlKey || ev.altKey) { + return; + } + + // If we're typing into an input box somewhere, ignore + if (ev.srcElement.tagName.toLowerCase() === 'input') { + return; + } + + $('#controlbox .inp').focus(); + }, + + + doLayout: function () { + var el_panels = $('#panels'); + var el_memberlists = $('#memberlists'); + var el_toolbar = $('#toolbar'); + var el_controlbox = $('#controlbox'); + + var css_heights = { + top: el_toolbar.outerHeight(true), + bottom: el_controlbox.outerHeight(true) + }; + + el_panels.css(css_heights); + el_memberlists.css(css_heights); + } +}); \ No newline at end of file -- 2.25.1