Hello!'
+ )
diff --git a/demo/demo_widgets/admin.py b/demo/demo_widgets/admin.py
new file mode 100644
index 000000000..58c9908d9
--- /dev/null
+++ b/demo/demo_widgets/admin.py
@@ -0,0 +1,8 @@
+from django.contrib import admin
+
+from widgy.admin import WidgyAdmin
+
+from demo.demo_widgets.models import I18NThing
+
+
+admin.site.register(I18NThing, WidgyAdmin)
diff --git a/demo/demo_widgets/migrations/0001_initial.py b/demo/demo_widgets/migrations/0001_initial.py
index cecc392d1..90d830c18 100644
--- a/demo/demo_widgets/migrations/0001_initial.py
+++ b/demo/demo_widgets/migrations/0001_initial.py
@@ -6,6 +6,9 @@
class Migration(SchemaMigration):
+ depends_on = [
+ ('widgy', '0001_initial'),
+ ]
def forwards(self, orm):
# Adding model 'SiteListCalloutContent'
@@ -45,4 +48,4 @@ def backwards(self, orm):
}
}
- complete_apps = ['demo_widgets']
\ No newline at end of file
+ complete_apps = ['demo_widgets']
diff --git a/demo/demo_widgets/migrations/0002_auto__add_twocontentlayout.py b/demo/demo_widgets/migrations/0002_auto__add_twocontentlayout.py
new file mode 100644
index 000000000..3c7705f63
--- /dev/null
+++ b/demo/demo_widgets/migrations/0002_auto__add_twocontentlayout.py
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+ def forwards(self, orm):
+ # Adding model 'TwoContentLayout'
+ db.create_table('demo_widgets_twocontentlayout', (
+ ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+ ))
+ db.send_create_signal('demo_widgets', ['TwoContentLayout'])
+
+
+ def backwards(self, orm):
+ # Deleting model 'TwoContentLayout'
+ db.delete_table('demo_widgets_twocontentlayout')
+
+
+ models = {
+ 'contenttypes.contenttype': {
+ 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+ 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+ },
+ 'demo_widgets.sitelistcalloutcontent': {
+ 'Meta': {'object_name': 'SiteListCalloutContent'},
+ 'header': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
+ },
+ 'demo_widgets.twocontentlayout': {
+ 'Meta': {'object_name': 'TwoContentLayout'},
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
+ },
+ 'widgy.node': {
+ 'Meta': {'object_name': 'Node'},
+ 'content_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+ 'depth': ('django.db.models.fields.PositiveIntegerField', [], {}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'numchild': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
+ 'path': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+ }
+ }
+
+ complete_apps = ['demo_widgets']
\ No newline at end of file
diff --git a/demo/demo_widgets/migrations/0003_auto__del_sitelistcalloutcontent__add_i18nthing.py b/demo/demo_widgets/migrations/0003_auto__del_sitelistcalloutcontent__add_i18nthing.py
new file mode 100644
index 000000000..7e951d1da
--- /dev/null
+++ b/demo/demo_widgets/migrations/0003_auto__del_sitelistcalloutcontent__add_i18nthing.py
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+ def forwards(self, orm):
+ # Deleting model 'SiteListCalloutContent'
+ db.delete_table('demo_widgets_sitelistcalloutcontent')
+
+ # Adding model 'I18NThing'
+ db.create_table('demo_widgets_i18nthing', (
+ ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+ ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
+ ('description', self.gf('widgy.db.fields.WidgyField')(to=orm['widgy.Node'], null=True, on_delete=models.SET_NULL, blank=True)),
+ ))
+ db.send_create_signal('demo_widgets', ['I18NThing'])
+
+
+ def backwards(self, orm):
+ # Adding model 'SiteListCalloutContent'
+ db.create_table('demo_widgets_sitelistcalloutcontent', (
+ ('header', self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True)),
+ ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+ ))
+ db.send_create_signal('demo_widgets', ['SiteListCalloutContent'])
+
+ # Deleting model 'I18NThing'
+ db.delete_table('demo_widgets_i18nthing')
+
+
+ models = {
+ 'contenttypes.contenttype': {
+ 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+ 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+ },
+ 'demo_widgets.i18nthing': {
+ 'Meta': {'object_name': 'I18NThing'},
+ 'description': ('widgy.db.fields.WidgyField', [], {'to': "orm['widgy.Node']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+ },
+ 'demo_widgets.twocontentlayout': {
+ 'Meta': {'object_name': 'TwoContentLayout'},
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
+ },
+ 'widgy.node': {
+ 'Meta': {'object_name': 'Node'},
+ 'content_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+ 'depth': ('django.db.models.fields.PositiveIntegerField', [], {}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'is_frozen': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'numchild': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
+ 'path': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+ }
+ }
+
+ complete_apps = ['demo_widgets']
\ No newline at end of file
diff --git a/demo/demo_widgets/models.py b/demo/demo_widgets/models.py
index 7bae45e05..a1817c7f7 100644
--- a/demo/demo_widgets/models.py
+++ b/demo/demo_widgets/models.py
@@ -1,6 +1,53 @@
-from widgy.contrib.list_content_widget.models import ListContentBase
-from django.contrib.sites.models import Site
+from django.db import models
+from django.conf import settings
+from django.utils.translation import ugettext_lazy as _
+from widgy import registry
+from widgy.db.fields import WidgyField
+from widgy.contrib.page_builder.models import Layout, MainContent, Accordion
-class SiteListCalloutContent(ListContentBase):
- model = Site
+
+class TwoContentLayout(Layout):
+ default_children = [
+ ('main1', MainContent, (), {}),
+ ('main2', MainContent, (), {}),
+ ]
+
+ class Meta:
+ verbose_name = 'Two Content Layout'
+
+registry.register(TwoContentLayout)
+
+
+class DemoAccordion(Accordion):
+ class Meta:
+ proxy = True
+ verbose_name = 'Accordion'
+
+ def valid_parent_of(self, cls, obj=None):
+ if obj and obj in self.get_children():
+ return True
+ else:
+ sup = super(DemoAccordion, self).valid_parent_of(cls)
+ if isinstance(self.get_root(), TwoContentLayout):
+ return sup and len(self.get_children()) < 2
+ else:
+ return sup
+
+registry.unregister(Accordion)
+registry.register(DemoAccordion)
+
+
+class I18NThing(models.Model):
+ name = models.CharField(_('name'), max_length=255)
+
+ description = WidgyField(
+ site=settings.WIDGY_MEZZANINE_SITE,
+ verbose_name=_('description'),
+ root_choices=(
+ 'widgy_i18n.I18NLayoutContainer',
+ ))
+
+ class Meta:
+ verbose_name = _('event')
+ verbose_name_plural = _('events')
diff --git a/demo/demo_widgets/tests.py b/demo/demo_widgets/tests.py
deleted file mode 100644
index 501deb776..000000000
--- a/demo/demo_widgets/tests.py
+++ /dev/null
@@ -1,16 +0,0 @@
-"""
-This file demonstrates writing tests using the unittest module. These will pass
-when you run "manage.py test".
-
-Replace this with more appropriate tests for your application.
-"""
-
-from django.test import TestCase
-
-
-class SimpleTest(TestCase):
- def test_basic_addition(self):
- """
- Tests that 1 + 1 always equals 2.
- """
- self.assertEqual(1 + 1, 2)
diff --git a/demo/demo_widgets/views.py b/demo/demo_widgets/views.py
deleted file mode 100644
index 60f00ef0e..000000000
--- a/demo/demo_widgets/views.py
+++ /dev/null
@@ -1 +0,0 @@
-# Create your views here.
diff --git a/demo/manage.py b/demo/manage.py
new file mode 100755
index 000000000..a406c7b5c
--- /dev/null
+++ b/demo/manage.py
@@ -0,0 +1,9 @@
+#!/usr/bin/env python
+import os, sys
+
+if __name__ == "__main__":
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings")
+
+ from django.core.management import execute_from_command_line
+
+ execute_from_command_line(sys.argv)
diff --git a/media/.gitkeep b/demo/media/.gitkeep
similarity index 100%
rename from media/.gitkeep
rename to demo/media/.gitkeep
diff --git a/demo/public/css/bootstrap.css b/demo/public/css/bootstrap.css
index fdba77f55..799b9cf33 100644
--- a/demo/public/css/bootstrap.css
+++ b/demo/public/css/bootstrap.css
@@ -1778,7 +1778,7 @@ table .span24 {
*margin-right: .3em;
line-height: 14px;
vertical-align: text-top;
- background-image: url("/img/glyphicons-halflings.png");
+ background-image: url("../img/glyphicons-halflings.png");
background-position: 14px 14px;
background-repeat: no-repeat;
}
@@ -1789,7 +1789,7 @@ table .span24 {
}
.icon-white {
- background-image: url("/img/glyphicons-halflings-white.png");
+ background-image: url("../img/glyphicons-halflings-white.png");
}
.icon-glass {
diff --git a/demo/public/js/backbone.js b/demo/public/js/backbone.js
deleted file mode 100644
index 3373c952b..000000000
--- a/demo/public/js/backbone.js
+++ /dev/null
@@ -1,1431 +0,0 @@
-// Backbone.js 0.9.2
-
-// (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.9.2';
-
- // 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;
-
- // Set the JavaScript library that will be used for DOM manipulation and
- // Ajax calls (a.k.a. the `$` variable). By default Backbone will use: jQuery,
- // Zepto, or Ender; but the `setDomLibrary()` method lets you inject an
- // alternate JavaScript library (or a mock library for testing your views
- // outside of a browser).
- Backbone.setDomLibrary = function(lib) {
- $ = lib;
- };
-
- // 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
- // -----------------
-
- // Regular expression used to split event strings
- var eventSplitter = /\s+/;
-
- // 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');
- //
- var Events = Backbone.Events = {
-
- // Bind one or more space separated events, `events`, to a `callback`
- // function. Passing `"all"` will bind the callback to all events fired.
- on: function(events, callback, context) {
-
- var calls, event, node, tail, list;
- if (!callback) return this;
- events = events.split(eventSplitter);
- calls = this._callbacks || (this._callbacks = {});
-
- // Create an immutable callback list, allowing traversal during
- // modification. The tail is an empty object that will always be used
- // as the next node.
- while (event = events.shift()) {
- list = calls[event];
- node = list ? list.tail : {};
- node.next = tail = {};
- node.context = context;
- node.callback = callback;
- calls[event] = {tail: tail, next: list ? list.next : node};
- }
-
- 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 `events` is null, removes all bound callbacks for all events.
- off: function(events, callback, context) {
- var event, calls, node, tail, cb, ctx;
-
- // No events, or removing *all* events.
- if (!(calls = this._callbacks)) return;
- if (!(events || callback || context)) {
- delete this._callbacks;
- return this;
- }
-
- // Loop through the listed events and contexts, splicing them out of the
- // linked list of callbacks if appropriate.
- events = events ? events.split(eventSplitter) : _.keys(calls);
- while (event = events.shift()) {
- node = calls[event];
- delete calls[event];
- if (!node || !(callback || context)) continue;
- // Create a new list, omitting the indicated callbacks.
- tail = node.tail;
- while ((node = node.next) !== tail) {
- cb = node.callback;
- ctx = node.context;
- if ((callback && cb !== callback) || (context && ctx !== context)) {
- this.on(event, cb, ctx);
- }
- }
- }
-
- return this;
- },
-
- // Trigger one or many events, firing all bound callbacks. Callbacks are
- // passed the same arguments as `trigger` is, apart from the event name
- // (unless you're listening on `"all"`, which will cause your callback to
- // receive the true name of the event 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(eventSplitter);
- rest = slice.call(arguments, 1);
-
- // For each event, walk through the linked list of callbacks twice,
- // first to trigger the event, then to trigger any `"all"` callbacks.
- while (event = events.shift()) {
- if (node = calls[event]) {
- tail = node.tail;
- while ((node = node.next) !== tail) {
- node.callback.apply(node.context || this, rest);
- }
- }
- if (node = all) {
- tail = node.tail;
- args = [event].concat(rest);
- while ((node = node.next) !== tail) {
- node.callback.apply(node.context || this, args);
- }
- }
- }
-
- return this;
- }
-
- };
-
- // Aliases for backwards compatibility.
- Events.bind = Events.on;
- Events.unbind = Events.off;
-
- // Backbone.Model
- // --------------
-
- // Create a new model, with defined attributes. A client id (`cid`)
- // is automatically generated and assigned for you.
- var Model = 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');
- this.changed = {};
- this._silent = {};
- this._pending = {};
- this.set(attributes, {silent: true});
- // Reset change tracking.
- this.changed = {};
- this._silent = {};
- this._pending = {};
- this._previousAttributes = _.clone(this.attributes);
- this.initialize.apply(this, arguments);
- };
-
- // Attach all inheritable methods to the Model prototype.
- _.extend(Model.prototype, Events, {
-
- // A hash of attributes whose current and previous value differ.
- changed: null,
-
- // A hash of attributes that have silently changed since the last time
- // `change` was called. Will become pending attributes on the next call.
- _silent: null,
-
- // A hash of attributes that have changed since the last `'change'` event
- // began.
- _pending: null,
-
- // 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(options) {
- 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.get(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.get(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;
-
- // Handle both `"key", value` and `{key: value}` -style arguments.
- 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 Model) attrs = attrs.attributes;
- if (options.unset) for (attr in attrs) attrs[attr] = void 0;
-
- // Run validation.
- if (!this._validate(attrs, options)) return false;
-
- // Check for changes of `id`.
- if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
-
- var changes = options.changes = {};
- var now = this.attributes;
- var escaped = this._escapedAttributes;
- var prev = this._previousAttributes || {};
-
- // For each `set` attribute...
- for (attr in attrs) {
- val = attrs[attr];
-
- // If the new and current value differ, record the change.
- if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) {
- delete escaped[attr];
- (options.silent ? this._silent : changes)[attr] = true;
- }
-
- // Update or delete the current value.
- options.unset ? delete now[attr] : now[attr] = val;
-
- // If the new and previous value differ, record the change. If not,
- // then remove changes for this attribute.
- if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) {
- this.changed[attr] = val;
- if (!options.silent) this._pending[attr] = true;
- } else {
- delete this.changed[attr];
- delete this._pending[attr];
- }
- }
-
- // Fire the `"change"` events.
- if (!options.silent) this.change(options);
- 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, current;
-
- // Handle both `("key", value)` and `({key: value})` -style calls.
- if (_.isObject(key) || key == null) {
- attrs = key;
- options = value;
- } else {
- attrs = {};
- attrs[key] = value;
- }
- options = options ? _.clone(options) : {};
-
- // If we're "wait"-ing to set changed attributes, validate early.
- if (options.wait) {
- if (!this._validate(attrs, options)) return false;
- current = _.clone(this.attributes);
- }
-
- // Regular saves `set` attributes before persisting to the server.
- var silentOptions = _.extend({}, options, {silent: true});
- if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) {
- return false;
- }
-
- // After a successful server-side save, the client is (optionally)
- // updated with the server-side state.
- var model = this;
- var success = options.success;
- options.success = function(resp, status, xhr) {
- var serverAttrs = model.parse(resp, xhr);
- if (options.wait) {
- delete 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);
- }
- };
-
- // Finish configuring and sending the Ajax request.
- options.error = Backbone.wrapError(options.error, model, options);
- var method = this.isNew() ? 'create' : 'update';
- var xhr = (this.sync || Backbone.sync).call(this, method, this, options);
- if (options.wait) this.set(current, silentOptions);
- return xhr;
- },
-
- // 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()) {
- triggerDestroy();
- return false;
- }
-
- 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, 'urlRoot') || getValue(this.collection, 'url') || 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 and
- // a `"change:attribute"` event for each changed attribute.
- // Calling this will cause all objects observing the model to update.
- change: function(options) {
- options || (options = {});
- var changing = this._changing;
- this._changing = true;
-
- // Silent changes become pending changes.
- for (var attr in this._silent) this._pending[attr] = true;
-
- // Silent changes are triggered.
- var changes = _.extend({}, options.changes, this._silent);
- this._silent = {};
- for (var attr in changes) {
- this.trigger('change:' + attr, this, this.get(attr), options);
- }
- if (changing) return this;
-
- // Continue firing `"change"` events while there are pending changes.
- while (!_.isEmpty(this._pending)) {
- this._pending = {};
- this.trigger('change', this, options);
- // Pending and silent changes still remain.
- for (var attr in this.changed) {
- if (this._pending[attr] || this._silent[attr]) continue;
- delete this.changed[attr];
- }
- this._previousAttributes = _.clone(this.attributes);
- }
-
- this._changing = false;
- return this;
- },
-
- // 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 (!arguments.length) return !_.isEmpty(this.changed);
- return _.has(this.changed, attr);
- },
-
- // 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.
- // You can also pass an attributes object to diff against the model,
- // determining if there *would be* a change.
- changedAttributes: function(diff) {
- if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
- var val, changed = false, old = this._previousAttributes;
- for (var attr in diff) {
- if (_.isEqual(old[attr], (val = diff[attr]))) continue;
- (changed || (changed = {}))[attr] = val;
- }
- return changed;
- },
-
- // Get the previous value of an attribute, recorded at the time the last
- // `"change"` event was fired.
- previous: function(attr) {
- if (!arguments.length || !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);
- },
-
- // Check if the model is currently in a valid state. It's only possible to
- // get into an *invalid* state if you're using silent changes.
- isValid: function() {
- return !this.validate(this.attributes);
- },
-
- // Run validation against the next complete set of model attributes,
- // returning `true` if all is well. If a specific `error` callback has
- // been passed, call that instead of firing the general `"error"` event.
- _validate: function(attrs, options) {
- if (options.silent || !this.validate) return true;
- attrs = _.extend({}, this.attributes, attrs);
- var error = this.validate(attrs, options);
- if (!error) return true;
- if (options && options.error) {
- options.error(this, error, options);
- } else {
- this.trigger('error', this, error, options);
- }
- return false;
- }
-
- });
-
- // 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.
- var Collection = Backbone.Collection = function(models, options) {
- options || (options = {});
- if (options.model) this.model = options.model;
- 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(Collection.prototype, Events, {
-
- // The default model for a collection is just a **Backbone.Model**.
- // This should be overridden in most cases.
- model: 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(options) {
- return this.map(function(model){ return model.toJSON(options); });
- },
-
- // 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, cid, id, cids = {}, ids = {}, dups = [];
- 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");
- }
- cid = model.cid;
- id = model.id;
- if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) {
- dups.push(i);
- continue;
- }
- cids[cid] = ids[id] = model;
- }
-
- // Remove duplicates.
- i = dups.length;
- while (i--) {
- models.splice(dups[i], 1);
- }
-
- // Listen to added models' events, and index models for lookup by
- // `id` and by `cid`.
- for (i = 0, length = models.length; 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;
- }
-
- // 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;
- },
-
- // Add a model to the end of the collection.
- push: function(model, options) {
- model = this._prepareModel(model, options);
- this.add(model, options);
- return model;
- },
-
- // Remove a model from the end of the collection.
- pop: function(options) {
- var model = this.at(this.length - 1);
- this.remove(model, options);
- return model;
- },
-
- // Add a model to the beginning of the collection.
- unshift: function(model, options) {
- model = this._prepareModel(model, options);
- this.add(model, _.extend({at: 0}, options));
- return model;
- },
-
- // Remove a model from the beginning of the collection.
- shift: function(options) {
- var model = this.at(0);
- this.remove(model, options);
- return model;
- },
-
- // Get a model from the set by id.
- get: function(id) {
- if (id == null) return void 0;
- 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];
- },
-
- // Return models with matching attributes. Useful for simple cases of `filter`.
- where: function(attrs) {
- if (_.isEmpty(attrs)) return [];
- return this.filter(function(model) {
- for (var key in attrs) {
- if (attrs[key] !== model.get(key)) return false;
- }
- return true;
- });
- },
-
- // 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, _.extend({silent: true}, options));
- 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) {
- options || (options = {});
- if (!(model instanceof Model)) {
- var attrs = model;
- options.collection = this;
- model = new this.model(attrs, options);
- if (!model._validate(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(event, model, collection, options) {
- if ((event == 'add' || event == 'remove') && collection != this) return;
- if (event == 'destroy') {
- this.remove(model, options);
- }
- if (model && event === '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) {
- 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.
- var Router = 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(Router.prototype, 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 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));
- return 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.
- var History = 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?
- History.started = false;
-
- // Set up all inheritable **Backbone.History** properties and methods.
- _.extend(History.prototype, Events, {
-
- // The default interval to poll for hash changes, if necessary, is
- // twenty times a second.
- interval: 50,
-
- // Gets the true hash value. Cannot use location.hash directly due to bug
- // in Firefox where location.hash will always be decoded.
- getHash: function(windowOverride) {
- var loc = windowOverride ? windowOverride.location : window.location;
- var match = loc.href.match(/#(.*)$/);
- return match ? match[1] : '';
- },
-
- // 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 = this.getHash();
- }
- }
- if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length);
- return fragment.replace(routeStripper, '');
- },
-
- // Start the hash change handling, returning `true` if the current URL matches
- // an existing route, and `false` otherwise.
- start: function(options) {
- if (History.started) throw new Error("Backbone.history has already been started");
- History.started = true;
-
- // Figure out the initial configuration. Do we need an iframe?
- // Is pushState desired ... is it available?
- 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 = $('').hide().appendTo('body')[0].contentWindow;
- this.navigate(fragment);
- }
-
- // Depending on whether we're using pushState or hashes, and whether
- // 'onhashchange' is supported, determine how we check the URL state.
- if (this._hasPushState) {
- $(window).bind('popstate', this.checkUrl);
- } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
- $(window).bind('hashchange', this.checkUrl);
- } else if (this._wantsHashChange) {
- this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
- }
-
- // Determine if we need to change the base url, for a pushState link
- // opened by a non-pushState browser.
- this.fragment = fragment;
- var loc = window.location;
- var atRoot = loc.pathname == this.options.root;
-
- // If we've started off with a route from a `pushState`-enabled browser,
- // but we're currently in a browser that doesn't support it...
- if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
- this.fragment = this.getFragment(null, true);
- window.location.replace(this.options.root + '#' + this.fragment);
- // Return immediately as browser will do redirect to new url
- return true;
-
- // Or if we've started out with a hash-based route, but we're currently
- // in a browser where it could be `pushState`-based instead...
- } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
- this.fragment = this.getHash().replace(routeStripper, '');
- window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
- }
-
- if (!this.options.silent) {
- return this.loadUrl();
- }
- },
-
- // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
- // but possibly useful for unit testing Routers.
- stop: function() {
- $(window).unbind('popstate', this.checkUrl).unbind('hashchange', this.checkUrl);
- clearInterval(this._checkUrlInterval);
- History.started = false;
- },
-
- // Add a route to be tested when the fragment changes. Routes added later
- // may override previous routes.
- route: function(route, callback) {
- this.handlers.unshift({route: route, callback: callback});
- },
-
- // Checks the current URL to see if it has changed, and if it has,
- // calls `loadUrl`, normalizing across the hidden iframe.
- checkUrl: function(e) {
- var current = this.getFragment();
- if (current == this.fragment && this.iframe) current = this.getFragment(this.getHash(this.iframe));
- if (current == this.fragment) return false;
- if (this.iframe) this.navigate(current);
- this.loadUrl() || this.loadUrl(this.getHash());
- },
-
- // Attempt to load the current URL fragment. If a route succeeds with a
- // match, returns `true`. If no defined routes matches the fragment,
- // returns `false`.
- loadUrl: function(fragmentOverride) {
- var fragment = this.fragment = this.getFragment(fragmentOverride);
- var matched = _.any(this.handlers, function(handler) {
- if (handler.route.test(fragment)) {
- handler.callback(fragment);
- return true;
- }
- });
- return matched;
- },
-
- // Save a fragment into the hash history, or replace the URL state if the
- // 'replace' option is passed. You are responsible for properly URL-encoding
- // the fragment in advance.
- //
- // The options object can contain `trigger: true` if you wish to have the
- // route callback be fired (not usually desirable), or `replace: true`, if
- // you wish to modify the current URL without adding an entry to the history.
- navigate: function(fragment, options) {
- if (!History.started) return false;
- if (!options || options === true) options = {trigger: options};
- var frag = (fragment || '').replace(routeStripper, '');
- if (this.fragment == frag) return;
-
- // If pushState is available, we use it to set the fragment as a real URL.
- if (this._hasPushState) {
- if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
- this.fragment = frag;
- window.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, frag);
-
- // If hash changes haven't been explicitly disabled, update the hash
- // fragment to store history.
- } else if (this._wantsHashChange) {
- this.fragment = frag;
- this._updateHash(window.location, frag, options.replace);
- if (this.iframe && (frag != this.getFragment(this.getHash(this.iframe)))) {
- // Opening and closing the iframe tricks IE7 and earlier to push a history entry on hash-tag change.
- // When replace is true, we don't want this.
- if(!options.replace) this.iframe.document.open().close();
- this._updateHash(this.iframe.location, frag, options.replace);
- }
-
- // If you've told us that you explicitly don't want fallback hashchange-
- // based history, then `navigate` becomes a page refresh.
- } else {
- window.location.assign(this.options.root + fragment);
- }
- if (options.trigger) this.loadUrl(fragment);
- },
-
- // Update the hash location, either replacing the current entry, or adding
- // a new one to the browser history.
- _updateHash: function(location, fragment, replace) {
- if (replace) {
- location.replace(location.toString().replace(/(javascript:|#).*$/, '') + '#' + fragment);
- } else {
- location.hash = fragment;
- }
- }
- });
-
- // Backbone.View
- // -------------
-
- // Creating a Backbone.View creates its initial element outside of the DOM,
- // if an existing element is not provided...
- var View = Backbone.View = function(options) {
- this.cid = _.uniqueId('view');
- this._configure(options || {});
- this._ensureElement();
- this.initialize.apply(this, arguments);
- this.delegateEvents();
- };
-
- // Cached regex to split keys for `delegate`.
- var delegateEventSplitter = /^(\S+)\s*(.*)$/;
-
- // List of view options to be merged as properties.
- var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
-
- // Set up all inheritable **Backbone.View** properties and methods.
- _.extend(View.prototype, Events, {
-
- // The default `tagName` of a View's element is `"div"`.
- tagName: 'div',
-
- // jQuery delegate for element lookup, scoped to DOM elements within the
- // current view. This should be prefered to global lookups where possible.
- $: function(selector) {
- return this.$el.find(selector);
- },
-
- // Initialize is an empty function by default. Override it with your own
- // initialization logic.
- initialize: function(){},
-
- // **render** is the core function that your view should override, in order
- // to populate its element (`this.el`), with the appropriate HTML. The
- // convention is for **render** to always return `this`.
- render: function() {
- return this;
- },
-
- // Remove this view from the DOM. Note that the view isn't present in the
- // DOM by default, so calling this method may be a no-op.
- remove: function() {
- this.$el.remove();
- return this;
- },
-
- // For small amounts of DOM Elements, where a full-blown template isn't
- // needed, use **make** to manufacture elements, one at a time.
- //
- // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
- //
- make: function(tagName, attributes, content) {
- var el = document.createElement(tagName);
- if (attributes) $(el).attr(attributes);
- if (content) $(el).html(content);
- return el;
- },
-
- // Change the view's element (`this.el` property), including event
- // re-delegation.
- setElement: function(element, delegate) {
- if (this.$el) this.undelegateEvents();
- this.$el = (element instanceof $) ? element : $(element);
- this.el = this.$el[0];
- if (delegate !== false) this.delegateEvents();
- return this;
- },
-
- // Set callbacks, where `this.events` is a hash of
- //
- // *{"event selector": "callback"}*
- //
- // {
- // 'mousedown .title': 'edit',
- // 'click .button': 'save'
- // 'click .open': function(e) { ... }
- // }
- //
- // pairs. Callbacks will be bound to the view, with `this` set properly.
- // Uses event delegation for efficiency.
- // Omitting the selector binds the event to `this.el`.
- // This only works for delegate-able events: not `focus`, `blur`, and
- // not `change`, `submit`, and `reset` in Internet Explorer.
- delegateEvents: function(events) {
- if (!(events || (events = getValue(this, 'events')))) return;
- this.undelegateEvents();
- for (var key in events) {
- var method = events[key];
- if (!_.isFunction(method)) method = this[events[key]];
- if (!method) throw new Error('Method "' + events[key] + '" does not exist');
- var match = key.match(delegateEventSplitter);
- var eventName = match[1], selector = match[2];
- method = _.bind(method, this);
- eventName += '.delegateEvents' + this.cid;
- if (selector === '') {
- this.$el.bind(eventName, method);
- } else {
- this.$el.delegate(selector, eventName, method);
- }
- }
- },
-
- // Clears all callbacks previously bound to the view with `delegateEvents`.
- // You usually don't need to use this, but may wish to if you have multiple
- // Backbone views attached to the same DOM element.
- undelegateEvents: function() {
- this.$el.unbind('.delegateEvents' + this.cid);
- },
-
- // Performs the initial configuration of a View with a set of options.
- // Keys with special meaning *(model, collection, id, className)*, are
- // attached directly to the view.
- _configure: function(options) {
- if (this.options) options = _.extend({}, this.options, options);
- for (var i = 0, l = viewOptions.length; i < l; i++) {
- var attr = viewOptions[i];
- if (options[attr]) this[attr] = options[attr];
- }
- this.options = options;
- },
-
- // Ensure that the View has a DOM element to render into.
- // If `this.el` is a string, pass it through `$()`, take the first
- // matching element, and re-assign it to `el`. Otherwise, create
- // an element from the `id`, `className` and `tagName` properties.
- _ensureElement: function() {
- if (!this.el) {
- var attrs = getValue(this, 'attributes') || {};
- if (this.id) attrs.id = this.id;
- if (this.className) attrs['class'] = this.className;
- this.setElement(this.make(this.tagName, attrs), false);
- } else {
- this.setElement(this.el, false);
- }
- }
-
- });
-
- // The self-propagating extend function that Backbone classes use.
- var extend = function (protoProps, classProps) {
- var child = inherits(this, protoProps, classProps);
- child.extend = this.extend;
- return child;
- };
-
- // Set up inheritance for the model, collection, and view.
- Model.extend = Collection.extend = Router.extend = View.extend = extend;
-
- // Backbone.sync
- // -------------
-
- // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
- var methodMap = {
- 'create': 'POST',
- 'update': 'PUT',
- 'delete': 'DELETE',
- 'read': 'GET'
- };
-
- // Override this function to change the manner in which Backbone persists
- // models to the server. You will be passed the type of request, and the
- // model in question. By default, makes a RESTful Ajax request
- // to the model's `url()`. Some possible customizations could be:
- //
- // * Use `setTimeout` to batch rapid-fire updates into a single request.
- // * Send up the models as XML instead of JSON.
- // * Persist models via WebSockets instead of Ajax.
- //
- // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
- // as `POST`, with a `_method` parameter containing the true HTTP method,
- // as well as all requests with the body as `application/x-www-form-urlencoded`
- // instead of `application/json` with the model in a param named `model`.
- // Useful when interfacing with server-side languages like **PHP** that make
- // it difficult to read the body of `PUT` requests.
- Backbone.sync = function(method, model, options) {
- var type = methodMap[method];
-
- // Default options, unless specified.
- options || (options = {});
-
- // Default JSON-request options.
- var params = {type: type, dataType: 'json'};
-
- // Ensure that we have a URL.
- if (!options.url) {
- params.url = getValue(model, 'url') || urlError();
- }
-
- // Ensure that we have the appropriate request data.
- if (!options.data && model && (method == 'create' || method == 'update')) {
- params.contentType = 'application/json';
- params.data = JSON.stringify(model.toJSON());
- }
-
- // For older servers, emulate JSON by encoding the request into an HTML-form.
- if (Backbone.emulateJSON) {
- params.contentType = 'application/x-www-form-urlencoded';
- params.data = params.data ? {model: params.data} : {};
- }
-
- // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
- // And an `X-HTTP-Method-Override` header.
- if (Backbone.emulateHTTP) {
- if (type === 'PUT' || type === 'DELETE') {
- if (Backbone.emulateJSON) params.data._method = type;
- params.type = 'POST';
- params.beforeSend = function(xhr) {
- xhr.setRequestHeader('X-HTTP-Method-Override', type);
- };
- }
- }
-
- // Don't process data on a non-GET request.
- if (params.type !== 'GET' && !Backbone.emulateJSON) {
- params.processData = false;
- }
-
- // Make the request, allowing the user to override any Ajax options.
- return $.ajax(_.extend(params, options));
- };
-
- // Wrap an optional error callback with a fallback error event.
- Backbone.wrapError = function(onError, originalModel, options) {
- return function(model, resp) {
- resp = model === originalModel ? resp : model;
- if (onError) {
- onError(originalModel, resp, options);
- } else {
- originalModel.trigger('error', originalModel, resp, options);
- }
- };
- };
-
- // Helpers
- // -------
-
- // Shared empty constructor function to aid in prototype-chain creation.
- var ctor = function(){};
-
- // Helper function to correctly set up the prototype chain, for subclasses.
- // Similar to `goog.inherits`, but uses a hash of prototype properties and
- // class properties to be extended.
- var inherits = function(parent, protoProps, staticProps) {
- var child;
-
- // The constructor function for the new subclass is either defined by you
- // (the "constructor" property in your `extend` definition), or defaulted
- // by us to simply call the parent's constructor.
- if (protoProps && protoProps.hasOwnProperty('constructor')) {
- child = protoProps.constructor;
- } else {
- child = function(){ parent.apply(this, arguments); };
- }
-
- // Inherit class (static) properties from parent.
- _.extend(child, parent);
-
- // Set the prototype chain to inherit from `parent`, without calling
- // `parent`'s constructor function.
- ctor.prototype = parent.prototype;
- child.prototype = new ctor();
-
- // Add prototype properties (instance properties) to the subclass,
- // if supplied.
- if (protoProps) _.extend(child.prototype, protoProps);
-
- // Add static properties to the constructor function, if supplied.
- if (staticProps) _.extend(child, staticProps);
-
- // Correctly set child's `prototype.constructor`.
- child.prototype.constructor = child;
-
- // Set a convenience property in case the parent's prototype is needed later.
- child.__super__ = parent.prototype;
-
- return child;
- };
-
- // Helper function to get a value from a Backbone object as a property
- // or as a function.
- var getValue = function(object, prop) {
- if (!(object && object[prop])) return null;
- return _.isFunction(object[prop]) ? object[prop]() : object[prop];
- };
-
- // Throw an error when a URL is needed, and none is supplied.
- var urlError = function() {
- throw new Error('A "url" property or function must be specified');
- };
-
-}).call(this);
diff --git a/demo/public/js/backbone.min.js b/demo/public/js/backbone.min.js
deleted file mode 100644
index c1c0d4fff..000000000
--- a/demo/public/js/backbone.min.js
+++ /dev/null
@@ -1,38 +0,0 @@
-// Backbone.js 0.9.2
-
-// (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(){var l=this,y=l.Backbone,z=Array.prototype.slice,A=Array.prototype.splice,g;g="undefined"!==typeof exports?exports:l.Backbone={};g.VERSION="0.9.2";var f=l._;!f&&"undefined"!==typeof require&&(f=require("underscore"));var i=l.jQuery||l.Zepto||l.ender;g.setDomLibrary=function(a){i=a};g.noConflict=function(){l.Backbone=y;return this};g.emulateHTTP=!1;g.emulateJSON=!1;var p=/\s+/,k=g.Events={on:function(a,b,c){var d,e,f,g,j;if(!b)return this;a=a.split(p);for(d=this._callbacks||(this._callbacks=
-{});e=a.shift();)f=(j=d[e])?j.tail:{},f.next=g={},f.context=c,f.callback=b,d[e]={tail:g,next:j?j.next:f};return this},off:function(a,b,c){var d,e,h,g,j,q;if(e=this._callbacks){if(!a&&!b&&!c)return delete this._callbacks,this;for(a=a?a.split(p):f.keys(e);d=a.shift();)if(h=e[d],delete e[d],h&&(b||c))for(g=h.tail;(h=h.next)!==g;)if(j=h.callback,q=h.context,b&&j!==b||c&&q!==c)this.on(d,j,q);return this}},trigger:function(a){var b,c,d,e,f,g;if(!(d=this._callbacks))return this;f=d.all;a=a.split(p);for(g=
-z.call(arguments,1);b=a.shift();){if(c=d[b])for(e=c.tail;(c=c.next)!==e;)c.callback.apply(c.context||this,g);if(c=f){e=c.tail;for(b=[b].concat(g);(c=c.next)!==e;)c.callback.apply(c.context||this,b)}}return this}};k.bind=k.on;k.unbind=k.off;var o=g.Model=function(a,b){var c;a||(a={});b&&b.parse&&(a=this.parse(a));if(c=n(this,"defaults"))a=f.extend({},c,a);b&&b.collection&&(this.collection=b.collection);this.attributes={};this._escapedAttributes={};this.cid=f.uniqueId("c");this.changed={};this._silent=
-{};this._pending={};this.set(a,{silent:!0});this.changed={};this._silent={};this._pending={};this._previousAttributes=f.clone(this.attributes);this.initialize.apply(this,arguments)};f.extend(o.prototype,k,{changed:null,_silent:null,_pending:null,idAttribute:"id",initialize:function(){},toJSON:function(){return f.clone(this.attributes)},get:function(a){return this.attributes[a]},escape:function(a){var b;if(b=this._escapedAttributes[a])return b;b=this.get(a);return this._escapedAttributes[a]=f.escape(null==
-b?"":""+b)},has:function(a){return null!=this.get(a)},set:function(a,b,c){var d,e;f.isObject(a)||null==a?(d=a,c=b):(d={},d[a]=b);c||(c={});if(!d)return this;d instanceof o&&(d=d.attributes);if(c.unset)for(e in d)d[e]=void 0;if(!this._validate(d,c))return!1;this.idAttribute in d&&(this.id=d[this.idAttribute]);var b=c.changes={},h=this.attributes,g=this._escapedAttributes,j=this._previousAttributes||{};for(e in d){a=d[e];if(!f.isEqual(h[e],a)||c.unset&&f.has(h,e))delete g[e],(c.silent?this._silent:
-b)[e]=!0;c.unset?delete h[e]:h[e]=a;!f.isEqual(j[e],a)||f.has(h,e)!=f.has(j,e)?(this.changed[e]=a,c.silent||(this._pending[e]=!0)):(delete this.changed[e],delete this._pending[e])}c.silent||this.change(c);return this},unset:function(a,b){(b||(b={})).unset=!0;return this.set(a,null,b)},clear:function(a){(a||(a={})).unset=!0;return this.set(f.clone(this.attributes),a)},fetch:function(a){var a=a?f.clone(a):{},b=this,c=a.success;a.success=function(d,e,f){if(!b.set(b.parse(d,f),a))return!1;c&&c(b,d)};
-a.error=g.wrapError(a.error,b,a);return(this.sync||g.sync).call(this,"read",this,a)},save:function(a,b,c){var d,e;f.isObject(a)||null==a?(d=a,c=b):(d={},d[a]=b);c=c?f.clone(c):{};if(c.wait){if(!this._validate(d,c))return!1;e=f.clone(this.attributes)}a=f.extend({},c,{silent:!0});if(d&&!this.set(d,c.wait?a:c))return!1;var h=this,i=c.success;c.success=function(a,b,e){b=h.parse(a,e);if(c.wait){delete c.wait;b=f.extend(d||{},b)}if(!h.set(b,c))return false;i?i(h,a):h.trigger("sync",h,a,c)};c.error=g.wrapError(c.error,
-h,c);b=this.isNew()?"create":"update";b=(this.sync||g.sync).call(this,b,this,c);c.wait&&this.set(e,a);return b},destroy:function(a){var a=a?f.clone(a):{},b=this,c=a.success,d=function(){b.trigger("destroy",b,b.collection,a)};if(this.isNew())return d(),!1;a.success=function(e){a.wait&&d();c?c(b,e):b.trigger("sync",b,e,a)};a.error=g.wrapError(a.error,b,a);var e=(this.sync||g.sync).call(this,"delete",this,a);a.wait||d();return e},url:function(){var a=n(this,"urlRoot")||n(this.collection,"url")||t();
-return this.isNew()?a:a+("/"==a.charAt(a.length-1)?"":"/")+encodeURIComponent(this.id)},parse:function(a){return a},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return null==this.id},change:function(a){a||(a={});var b=this._changing;this._changing=!0;for(var c in this._silent)this._pending[c]=!0;var d=f.extend({},a.changes,this._silent);this._silent={};for(c in d)this.trigger("change:"+c,this,this.get(c),a);if(b)return this;for(;!f.isEmpty(this._pending);){this._pending=
-{};this.trigger("change",this,a);for(c in this.changed)!this._pending[c]&&!this._silent[c]&&delete this.changed[c];this._previousAttributes=f.clone(this.attributes)}this._changing=!1;return this},hasChanged:function(a){return!arguments.length?!f.isEmpty(this.changed):f.has(this.changed,a)},changedAttributes:function(a){if(!a)return this.hasChanged()?f.clone(this.changed):!1;var b,c=!1,d=this._previousAttributes,e;for(e in a)if(!f.isEqual(d[e],b=a[e]))(c||(c={}))[e]=b;return c},previous:function(a){return!arguments.length||
-!this._previousAttributes?null:this._previousAttributes[a]},previousAttributes:function(){return f.clone(this._previousAttributes)},isValid:function(){return!this.validate(this.attributes)},_validate:function(a,b){if(b.silent||!this.validate)return!0;var a=f.extend({},this.attributes,a),c=this.validate(a,b);if(!c)return!0;b&&b.error?b.error(this,c,b):this.trigger("error",this,c,b);return!1}});var r=g.Collection=function(a,b){b||(b={});b.model&&(this.model=b.model);b.comparator&&(this.comparator=b.comparator);
-this._reset();this.initialize.apply(this,arguments);a&&this.reset(a,{silent:!0,parse:b.parse})};f.extend(r.prototype,k,{model:o,initialize:function(){},toJSON:function(a){return this.map(function(b){return b.toJSON(a)})},add:function(a,b){var c,d,e,g,i,j={},k={},l=[];b||(b={});a=f.isArray(a)?a.slice():[a];c=0;for(d=a.length;c content "),
+ 'content'
+ )
+
+ self.assertContainsSameWords(
+ html_to_plaintext(" content content content content2 content Bucket: {{ self.title }} {{ content.inherits_from.title }} {{ content.inherits_from.content }} {{ self.meta.verbose_name }} Title: {{ self.inherits_from.title }} Content: {{ self.inherits_from.content }} Button Text: {{ self.inherits_from.button_text }} Button href: {{ self.inherits_from.button_href }}
-
- {{ self.meta.verbose_name }} Two Column Layout s around
+ // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
+ // phrase emphasis, and spans. The list of tags we're looking for is
+ // hard-coded:
+ var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
+ var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
+
+ // First, look for nested blocks, e.g.:
+ // tags around block-level tags.
+ text = _HashHTMLBlocks(text);
+ text = _FormParagraphs(text, doNotUnhash);
+
+ return text;
+ }
+
+ function _RunSpanGamut(text) {
+ //
+ // These are all the transformations that occur *within* block-level
+ // tags like paragraphs, headers, and list items.
+ //
+
+ text = _DoCodeSpans(text);
+ text = _EscapeSpecialCharsWithinTagAttributes(text);
+ text = _EncodeBackslashEscapes(text);
+
+ // Process anchor and image tags. Images must come first,
+ // because ![foo][f] looks like an anchor.
+ text = _DoImages(text);
+ text = _DoAnchors(text);
+
+ // Make links out of things like ` Just type tags
+ //
+
+ // Strip leading and trailing lines:
+ text = text.replace(/^\n+/g, "");
+ text = text.replace(/\n+$/g, "");
+
+ var grafs = text.split(/\n{2,}/g);
+ var grafsOut = [];
+
+ var markerRe = /~K(\d+)K/;
+
+ //
+ // Wrap tags.
+ //
+ var end = grafs.length;
+ for (var i = 0; i < end; i++) {
+ var str = grafs[i];
+
+ // if this is an HTML marker, copy it
+ if (markerRe.test(str)) {
+ grafsOut.push(str);
+ }
+ else if (/\S/.test(str)) {
+ str = _RunSpanGamut(str);
+ str = str.replace(/^([ \t]*)/g, " ");
+ str += " Insert Hyperlink http://example.com/ \"optional title\" Insert Image http://example.com/images/diagram.jpg \"optional title\" {% trans "Title" %}: {{ self.title|default:"" }} {% trans "Caption" %}: {{ self.caption|default:"" }} {{ self.title }}:
+ {% page_menu "pages/menus/breadcrumb.html" %}
+ The requested content cannot be loaded. '+a.lang.wsc.errorLoading.replace(/%s/g,a.config.wsc_customLoaderScript)+" {{ field.help_text }} {{ self.meta.verbose_name }} {% templatetag openvariable %} content {% templatetag closevariable %}
+{% load i18n %}
+ {% trans "There are no commits yet, nothing to reset to" %} {% trans "This will irrevocably destroy all uncommited changes. Are you sure?" %} {% trans "Nothing has changed — no need to reset." %} {% trans 'Your changes were successfully erased.' %}
+Unknown Widget Type: {{ self.content_type.app_label }}.{{ self.content_type.model }}
+'),
+ 'image description'
+ )
+
+ self.assertContainsSameWords(
+ html_to_plaintext('
'),
+ 'content image description'
+ )
+
+ def test_other_attributes(self):
+ self.assertContainsSameWords(
+ html_to_plaintext('example.com'),
+ 'example.com'
+ )
+
+ self.assertContainsSameWords(
+ html_to_plaintext('content'),
+ 'content'
+ )
+
+ self.assertContainsSameWords(
+ html_to_plaintext('content'),
+ 'content'
+ )
diff --git a/tests/runtests.py b/tests/runtests.py
new file mode 100755
index 000000000..8bf742ed0
--- /dev/null
+++ b/tests/runtests.py
@@ -0,0 +1,241 @@
+#! /usr/bin/env python
+import os
+import shutil
+import sys
+import tempfile
+from operator import itemgetter
+
+from widgy import contrib
+try:
+ import six
+except ImportError:
+ from django.utils import six
+
+
+def upath(path):
+ """
+ Always return a unicode path.
+ """
+ if not six.PY3:
+ fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
+ return path.decode(fs_encoding)
+ return path
+
+CONTRIB_DIR_NAME = 'widgy.contrib'
+MODEL_TESTS_DIR_NAME = 'modeltests'
+REGRESSION_TESTS_DIR_NAME = 'regressiontests'
+
+TEST_TEMPLATE_DIR = 'templates'
+
+RUNTESTS_DIR = os.path.dirname(upath(__file__))
+CONTRIB_DIR = os.path.dirname(upath(contrib.__file__))
+MODEL_TEST_DIR = os.path.join(RUNTESTS_DIR, MODEL_TESTS_DIR_NAME)
+REGRESSION_TEST_DIR = os.path.join(RUNTESTS_DIR, REGRESSION_TESTS_DIR_NAME)
+TEMP_DIR = tempfile.mkdtemp(prefix='django_')
+os.environ['DJANGO_TEST_TEMP_DIR'] = TEMP_DIR
+
+REGRESSION_SUBDIRS_TO_SKIP = []
+
+ALWAYS_INSTALLED_APPS = [
+ 'django.contrib.contenttypes',
+ 'django.contrib.auth',
+ 'django.contrib.sites',
+ 'django.contrib.sessions',
+ 'django.contrib.messages',
+ 'django.contrib.admin',
+ 'django.contrib.staticfiles',
+ "mezzanine.boot",
+ "mezzanine.conf",
+ "mezzanine.core",
+ "mezzanine.generic",
+ "mezzanine.pages",
+ "mezzanine.forms",
+ # blog is affected by https://code.djangoproject.com/ticket/12728
+ # "mezzanine.blog",
+ "widgy",
+ "treebeard",
+ "compressor",
+ "argonauts",
+ "filer",
+ "south",
+]
+
+def get_test_modules():
+ modules = []
+ for loc, dirpath in (
+ (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR),
+ (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR),
+ (CONTRIB_DIR_NAME, CONTRIB_DIR)):
+ for f in os.listdir(dirpath):
+ if (f.startswith('__init__') or
+ f.startswith('.') or
+ # Python 3 byte code dirs (PEP 3147)
+ f == '__pycache__' or
+ f.startswith('sql') or
+ os.path.basename(f) in REGRESSION_SUBDIRS_TO_SKIP):
+ continue
+ files = os.listdir(os.path.join(dirpath, f))
+ # skip directories with no python files
+ for file in files:
+ if file.endswith('.py'):
+ modules.append((loc, f))
+ break
+ return modules
+
+def setup(verbosity, test_labels):
+ from django.conf import settings
+ state = {
+ 'INSTALLED_APPS': settings.INSTALLED_APPS,
+ 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
+ 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
+ 'USE_I18N': settings.USE_I18N,
+ 'LOGIN_URL': settings.LOGIN_URL,
+ 'LANGUAGE_CODE': settings.LANGUAGE_CODE,
+ 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES,
+ 'STATIC_URL': settings.STATIC_URL,
+ 'STATIC_ROOT': settings.STATIC_ROOT,
+ }
+
+ # Redirect some settings for the duration of these tests.
+ settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
+ settings.ROOT_URLCONF = 'urls'
+ settings.STATIC_URL = '/static/'
+ settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static')
+ settings.MEDIA_URL = '/media/'
+ settings.MEDIA_ROOT = os.path.join(TEMP_DIR, 'media')
+ settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),)
+ settings.USE_I18N = True
+ settings.LANGUAGE_CODE = 'en'
+ settings.LOGIN_URL = 'django.contrib.auth.views.login'
+ settings.MIDDLEWARE_CLASSES = (
+ 'django.contrib.sessions.middleware.SessionMiddleware',
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
+ 'django.contrib.messages.middleware.MessageMiddleware',
+ 'django.middleware.common.CommonMiddleware',
+ )
+ settings.SITE_ID = 1
+ settings.WIDGY_MEZZANINE_SITE = 'modeltests.core_tests.widgy_config.widgy_site'
+ settings.DAISYDIFF_JAR_PATH = os.path.join(os.path.dirname(__file__),
+ '..', 'bin', 'daisydiff', 'daisydiff.jar')
+
+
+ # mezzanine junk
+ settings.PACKAGE_NAME_FILEBROWSER = "filebrowser_safe"
+ from mezzanine.utils.conf import set_dynamic_settings
+ set_dynamic_settings(vars(settings._wrapped))
+
+ # mezzanine sets this to a tuple, but we need ot to be a list
+ settings.INSTALLED_APPS = list(settings.INSTALLED_APPS)
+
+ # Load all the ALWAYS_INSTALLED_APPS.
+ # (This import statement is intentionally delayed until after we
+ # access settings because of the USE_I18N dependency.)
+ from django.db.models.loading import get_apps, load_app
+ get_apps()
+
+ # Load all the test model apps.
+ test_labels_set = set([label.split('.')[0] for label in test_labels])
+ test_modules = get_test_modules()
+
+ # easy_thumbnails changes how it does migrations
+ import easy_thumbnails
+
+ if easy_thumbnails.VERSION >= 2:
+ SOUTH_MIGRATION_MODULES = {
+ 'easy_thumbnails': 'easy_thumbnails.south_migrations',
+ }
+
+ for module_dir, module_name in test_modules:
+ module_label = '.'.join([module_dir, module_name])
+ # if the module was named on the command line, or
+ # no modules were named (i.e., run all), import
+ # this module and add it to the list to test.
+ if not test_labels or module_name in test_labels_set:
+ if verbosity >= 2:
+ print("Importing application %s" % module_name)
+ mod = load_app(module_label)
+ if mod:
+ if module_label not in settings.INSTALLED_APPS:
+ settings.INSTALLED_APPS.append(module_label)
+
+ return state
+
+def teardown(state):
+ from django.conf import settings
+ # Removing the temporary TEMP_DIR. Ensure we pass in unicode
+ # so that it will successfully remove temp trees containing
+ # non-ASCII filenames on Windows. (We're assuming the temp dir
+ # name itself does not contain non-ASCII characters.)
+ shutil.rmtree(six.text_type(TEMP_DIR))
+ # Restore the old settings.
+ for key, value in state.items():
+ setattr(settings, key, value)
+
+def django_tests(verbosity, interactive, failfast, test_labels):
+ from django.conf import settings
+
+ state = setup(verbosity, test_labels)
+ extra_tests = []
+
+ # must be imported after settings are set up
+ from south.management.commands import patch_for_test_db_setup
+ patch_for_test_db_setup()
+
+ # Run the test suite, including the extra validation tests.
+ from django.test.utils import get_runner
+ if not hasattr(settings, 'TEST_RUNNER'):
+ settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
+ TestRunner = get_runner(settings)
+
+ test_runner = TestRunner(verbosity=verbosity, interactive=interactive,
+ failfast=failfast)
+ failures = test_runner.run_tests(test_labels, extra_tests=extra_tests)
+
+ teardown(state)
+ return failures
+
+if __name__ == "__main__":
+ from optparse import OptionParser
+ usage = "%prog [options] [module module module ...]"
+ parser = OptionParser(usage=usage)
+ parser.add_option(
+ '-v', '--verbosity', action='store', dest='verbosity', default='1',
+ type='choice', choices=['0', '1', '2', '3'],
+ help='Verbosity level; 0=minimal output, 1=normal output, 2=all '
+ 'output')
+ parser.add_option(
+ '--noinput', action='store_false', dest='interactive', default=True,
+ help='Tells Django to NOT prompt the user for input of any kind.')
+ parser.add_option(
+ '--failfast', action='store_true', dest='failfast', default=False,
+ help='Tells Django to stop running the test suite after first failed '
+ 'test.')
+ parser.add_option(
+ '--settings',
+ help='Python path to settings module, e.g. "myproject.settings". If '
+ 'this isn\'t provided, the DJANGO_SETTINGS_MODULE environment '
+ 'variable will be used.')
+ parser.add_option(
+ '--liveserver', action='store', dest='liveserver', default=None,
+ help='Overrides the default address where the live server (used with '
+ 'LiveServerTestCase) is expected to run from. The default value '
+ 'is localhost:8081.'),
+ options, args = parser.parse_args()
+ if not args:
+ # apps to test
+ args = map(itemgetter(1), get_test_modules()) + ['widgy']
+ if options.settings:
+ os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
+ elif "DJANGO_SETTINGS_MODULE" not in os.environ:
+ parser.error("DJANGO_SETTINGS_MODULE is not set in the environment. "
+ "Set it or use --settings.")
+ else:
+ options.settings = os.environ['DJANGO_SETTINGS_MODULE']
+
+ if options.liveserver is not None:
+ os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = options.liveserver
+
+ failures = django_tests(int(options.verbosity), options.interactive,
+ options.failfast, args)
+ if failures:
+ sys.exit(bool(failures))
diff --git a/tests/test_multidb.py b/tests/test_multidb.py
new file mode 100644
index 000000000..ce730d82f
--- /dev/null
+++ b/tests/test_multidb.py
@@ -0,0 +1,27 @@
+import os
+
+from test_sqlite import *
+
+engine = os.getenv('DATABASE_ENGINE')
+if engine == 'mysql':
+ DATABASES = {
+ "default": {
+ "ENGINE": "django.db.backends.mysql",
+ "NAME": "widgy",
+ "USER": "root",
+ "PASSWORD": "",
+ "HOST": "",
+ }
+ }
+elif engine == 'postgres':
+ DATABASES = {
+ "default": {
+ "ENGINE": "django.db.backends.postgresql_psycopg2",
+ "NAME": "widgy",
+ "USER": "postgres",
+ }
+ }
+elif engine == 'sqlite':
+ pass
+elif engine:
+ assert False, "%r is not a valid DATABASE_ENGINE" % engine
diff --git a/tests/test_sqlite.py b/tests/test_sqlite.py
new file mode 100644
index 000000000..f5f33d672
--- /dev/null
+++ b/tests/test_sqlite.py
@@ -0,0 +1,37 @@
+# This is an example test settings file for use with the Django test suite.
+#
+# The 'sqlite3' backend requires only the ENGINE setting (an in-
+# memory database will be used). All other backends will require a
+# NAME and potentially authentication information. See the
+# following section in the docs for more information:
+#
+# https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/
+#
+# The different databases that Django supports behave differently in certain
+# situations, so it is recommended to run the test suite against as many
+# database backends as possible. You may want to create a separate settings
+# file for each of the backends you test against.
+import os
+
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': '',
+ },
+}
+
+SECRET_KEY = "widgy_tests_secret_key"
+# To speed up tests under SQLite we use the MD5 hasher as the default one.
+# This should not be needed under other databases, as the relative speedup
+# is only marginal there.
+PASSWORD_HASHERS = (
+ 'django.contrib.auth.hashers.MD5PasswordHasher',
+ 'django.contrib.auth.hashers.SHA1PasswordHasher',
+)
+
+SOUTH_TESTS_MIGRATE = os.environ.get('SOUTH_TESTS_MIGRATE', False)
+
+URLCONF_INCLUDE_CHOICES = tuple()
+TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
+
+MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
diff --git a/tests/urls.py b/tests/urls.py
new file mode 100644
index 000000000..7848af96a
--- /dev/null
+++ b/tests/urls.py
@@ -0,0 +1,17 @@
+from django.conf.urls import patterns, include, url
+
+from django.contrib import admin
+admin.autodiscover()
+
+
+def dummy_view(*args, **kwargs):
+ pass
+
+
+urlpatterns = patterns('',
+ url('^core_tests/', include('modeltests.core_tests.urls')),
+ url("^admin/", include(admin.site.urls)),
+ url('^widgy-mezzanine/', include('widgy.contrib.widgy_mezzanine.urls')),
+ # mezzanine.pages.views.page reverses the 'home' url.
+ url('^$', dummy_view, name='home'),
+)
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 000000000..1a75f6e96
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,111 @@
+[tox]
+envlist=py27-dj14,py27-dj15,py26-dj14,py26-dj15,py27-dj16
+
+[testenv]
+commands=/usr/bin/env make test
+
+[testenv:py27-dj14]
+basepython=python2.7
+deps =
+ Django==1.4
+
+[testenv:py27-dj15]
+basepython=python2.7
+deps =
+ https://www.djangoproject.com/download/1.5c1/tarball/
+
+[testenv:py26-dj14]
+basepython=python2.6
+deps =
+ Django==1.4
+
+[testenv:py26-dj15]
+basepython=python2.6
+deps =
+ https://www.djangoproject.com/download/1.5c1/tarball/
+
+[testenv:py27-dj16]
+basepython=python2.7
+deps =
+ --editable=git+https://github.com/django/django@master#egg=django
+
+[testenv:py26-dj15-mysql]
+basepython=python2.6
+deps =
+ https://www.djangoproject.com/download/1.5c1/tarball/
+ MySQL-python==1.2.3
+setenv =
+ DATABASE_ENGINE=mysql
+
+[testenv:py27-dj15-mysql]
+basepython=python2.7
+deps =
+ https://www.djangoproject.com/download/1.5c1/tarball/
+ MySQL-python==1.2.3
+setenv =
+ DATABASE_ENGINE=mysql
+
+[testenv:py27-dj14-mysql]
+basepython=python2.7
+deps =
+ Django==1.4
+ MySQL-python==1.2.3
+setenv =
+ DATABASE_ENGINE=mysql
+
+[testenv:py27-dj16-mysql]
+basepython=python2.7
+deps =
+ --editable=git+https://github.com/django/django@master#egg=django
+ MySQL-python==1.2.3
+setenv =
+ DATABASE_ENGINE=mysql
+
+[testenv:py26-dj14-mysql]
+basepython=python2.6
+deps =
+ Django==1.4
+ MySQL-python==1.2.3
+setenv =
+ DATABASE_ENGINE=mysql
+
+
+[testenv:py26-dj15-postgres]
+basepython=python2.6
+deps =
+ https://www.djangoproject.com/download/1.5c1/tarball/
+ psycopg2
+setenv =
+ DATABASE_ENGINE=postgres
+
+[testenv:py27-dj15-postgres]
+basepython=python2.7
+deps =
+ https://www.djangoproject.com/download/1.5c1/tarball/
+ psycopg2
+setenv =
+ DATABASE_ENGINE=postgres
+
+[testenv:py27-dj14-postgres]
+basepython=python2.7
+deps =
+ Django==1.4
+ psycopg2
+setenv =
+ DATABASE_ENGINE=postgres
+
+[testenv:py26-dj14-postgres]
+basepython=python2.6
+deps =
+ Django==1.4
+ psycopg2
+setenv =
+ DATABASE_ENGINE=postgres
+
+[testenv:py27-dj16-postgres]
+basepython=python2.7
+deps =
+ --editable=git+https://github.com/django/django@master#egg=django
+ psycopg2
+setenv =
+ DATABASE_ENGINE=postgres
diff --git a/urlconf_include/middleware.py b/urlconf_include/middleware.py
deleted file mode 100644
index 5985d2916..000000000
--- a/urlconf_include/middleware.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import imp
-import re
-
-from django.utils.importlib import import_module
-from django.conf import settings
-from django.conf.urls.defaults import include, url, patterns
-
-from .models import UrlconfIncludePage
-
-class PatchUrlconfMiddleware(object):
- def process_request(self, request):
- urlconf_pages = list(UrlconfIncludePage.objects.all())
- urlconf_pages.sort(key=lambda p: len(p.slug))
-
- root_urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
- if isinstance(root_urlconf, basestring):
- root_urlconf = import_module(getattr(request, 'urlconf', settings.ROOT_URLCONF))
-
- new_urlconf = imp.new_module('urlconf')
- new_urlconf.urlpatterns = patterns('')
- for page in urlconf_pages:
- new_urlconf.urlpatterns.extend(patterns('',
- url('^' + re.escape(page.slug) + '/', include(page.urlconf_name))))
- new_urlconf.urlpatterns.extend(root_urlconf.urlpatterns)
-
- if hasattr(root_urlconf, 'handler404'):
- new_urlconf.handler404 = root_urlconf.handler404
- if hasattr(root_urlconf, 'handler500'):
- new_urlconf.handler500 = root_urlconf.handler500
-
- request.urlconf = new_urlconf
diff --git a/urlconf_include/models.py b/urlconf_include/models.py
deleted file mode 100644
index 77e500842..000000000
--- a/urlconf_include/models.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from django.db import models
-from django.core import urlresolvers
-
-from mezzanine.pages.page_processors import processor_for
-from mezzanine.pages.models import Page
-
-class UrlconfIncludePage(Page):
- urlconf_name = models.CharField(max_length=255)
-
- def can_add(self, request):
- return False
diff --git a/urlconf_include/tests.py b/urlconf_include/tests.py
deleted file mode 100644
index 501deb776..000000000
--- a/urlconf_include/tests.py
+++ /dev/null
@@ -1,16 +0,0 @@
-"""
-This file demonstrates writing tests using the unittest module. These will pass
-when you run "manage.py test".
-
-Replace this with more appropriate tests for your application.
-"""
-
-from django.test import TestCase
-
-
-class SimpleTest(TestCase):
- def test_basic_addition(self):
- """
- Tests that 1 + 1 always equals 2.
- """
- self.assertEqual(1 + 1, 2)
diff --git a/urlconf_include/views.py b/urlconf_include/views.py
deleted file mode 100644
index 60f00ef0e..000000000
--- a/urlconf_include/views.py
+++ /dev/null
@@ -1 +0,0 @@
-# Create your views here.
diff --git a/widgy/__init__.py b/widgy/__init__.py
index e69de29bb..14bee5b40 100644
--- a/widgy/__init__.py
+++ b/widgy/__init__.py
@@ -0,0 +1,83 @@
+import traceback
+import sys
+
+from django.core.exceptions import ImproperlyConfigured
+from django.core.signals import request_started
+
+
+class BaseRegistry(set):
+ deferred_exception = None
+
+ def register(self, model):
+ from django.db import models
+ if model in self:
+ self.defer_exception(ImproperlyConfigured(
+ "You cannot register the same model ('{0}') twice.".format(model)
+ ))
+ if not issubclass(model, models.Model):
+ raise ImproperlyConfigured(("{0} is not a subclass of django.db.models.Model, "
+ "so it cannot be registered").format(model))
+ if model._meta.abstract:
+ raise ImproperlyConfigured("You cannot register the abstract class {0}".format(model))
+ self.add(model)
+
+ # allow use as a decorator
+ return model
+
+ def unregister(self, model):
+ try:
+ self.remove(model)
+ except KeyError as e:
+ self.defer_exception(e)
+
+ def defer_exception(self, exception):
+ # XXX: this is a terrible hack to improve error reporting.
+ #
+ # Raising an exception here results in some awful error
+ # reporting when models.py modules have ImportError. Django
+ # will import the models module more than once, meaning
+ # classes will get registered more than once, and if we
+ # raise an exception here, you get an ImproperlyConfigured
+ # instead of the ImportError that would help you find the
+ # problem. See https://code.djangoproject.com/ticket/20839.
+ self.deferred_exception = exception
+ # sys._getframe(1) == skip defer_exception's frame, because it's
+ # not interesting
+ self.stacktrace = ''.join(traceback.format_stack(sys._getframe(1)))
+ # We need an opportunity to raise the exception. Anything will
+ # work as long as it happens after model loading. It'd be nice
+ # if it happened during validation and didn't wait until the
+ # first request, but there's no way to hook into that.
+ #
+ # The handler can't be registered in BaseRegistry.__init__
+ # because the tests import this module before settings are
+ # configured, and the signal can't be imported without settings.
+ def handler(**kwargs):
+ self.raise_deferred_exception()
+ request_started.disconnect(handler)
+ request_started.connect(handler, weak=False)
+
+ def raise_deferred_exception(self):
+ if self.deferred_exception:
+ # six.reraise doesn't keep the whole stack, so print a
+ # stacktrace to help find the error.
+ sys.stderr.write(self.stacktrace)
+ try:
+ raise self.deferred_exception
+ finally:
+ self.deferred_exception = None
+
+
+class Registry(BaseRegistry):
+ def register(self, content):
+ from widgy.models import Content
+ if not issubclass(content, Content):
+ raise ImproperlyConfigured(
+ "{0} is not a subclass of Content, so it cannot be registered".format(content)
+ )
+ return super(Registry, self).register(content)
+
+
+registry = Registry()
+register = registry.register
+unregister = registry.unregister
diff --git a/widgy/admin.py b/widgy/admin.py
index aafe970cc..58ba89951 100644
--- a/widgy/admin.py
+++ b/widgy/admin.py
@@ -1,16 +1,29 @@
from django.contrib.admin import ModelAdmin
-from widgy.forms import WidgyFormMixin
+from django.core.exceptions import PermissionDenied
+
+from widgy.forms import WidgyForm
+
+
+class AuthorizedAdminMixin(object):
+ def _has_permission(self, request, obj=None):
+ try:
+ self.get_site().authorize_view(request, self)
+ return True
+ except PermissionDenied:
+ return False
+
+ def has_add_permission(self, request, obj=None):
+ return super(AuthorizedAdminMixin, self).has_add_permission(request, obj) and self._has_permission(request, obj)
+
+ def has_change_permission(self, request, obj=None):
+ return super(AuthorizedAdminMixin, self).has_change_permission(request, obj) and self._has_permission(request, obj)
+
+ def has_delete_permission(self, request, obj=None):
+ return super(AuthorizedAdminMixin, self).has_delete_permission(request, obj) and self._has_permission(request, obj)
class WidgyAdmin(ModelAdmin):
"""
- Model Admin for models which will have a widgy tree under them
+ Base class for ModelAdmins whose models contain WidgyFields.
"""
- def get_form(self, request, obj=None, **kwargs):
- form = super(WidgyAdmin, self).get_form(request, obj, **kwargs)
-
- if not issubclass(form, WidgyAdmin):
- class form(WidgyFormMixin, form):
- pass
-
- return form
+ form = WidgyForm
diff --git a/widgy/cats.py b/widgy/cats.py
new file mode 100644
index 000000000..91c1ec22f
--- /dev/null
+++ b/widgy/cats.py
@@ -0,0 +1,105 @@
+# * ,MMM8&&&. *
+# MMMM88&&&&& .
+# MMMM88&&&&&&&
+# * MMM88&&&&&&&&
+# MMM88&&&&&&&&
+# 'MMM88&&&&&&'
+# 'MMM8&&&' *
+# |\___/|
+# ) ( . '
+# =\ /=
+# )===( *
+# / \
+# | |
+# / \
+# \ /
+# _/\_/\_/\__ _/_/\_/\_/\_/\_/\_/\_/\_/\_/\_
+# | | | |( ( | | | | | | | | | |
+# | | | | ) ) | | | | | | | | | |
+# | | | |(_( | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# * ,MMM8&&&. *
+# MMMM88&&&&& .
+# MMMM88&&&&&&&
+# * MMM88&&&&&&&&
+# MMM88&&&&&&&&
+# 'MMM88&&&&&&'
+# 'MMM8&&&' *
+# |\___/|
+# =) ^Y^ (= . '
+# \ ^ /
+# )=*=( *
+# / \
+# | |
+# /| | | |\
+# \| | |_|/\
+# /\_/\_//_// ___/\_/\_/\_/\_/\_/\_/\_/\_/\_
+# | | | | \_) | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# * ,MMM8&&&. *
+# MMMM88&&&&& .
+# MMMM88&&&&&&&
+# * MMM88&&&&&&&&
+# MMM88&&&&&&&&
+# 'MMM88&&&&&&'
+# 'MMM8&&&' * _
+# |\___/| \\
+# =) ^Y^ (= |\_/| || '
+# \ ^ / )a a '._.-""""-. //
+# )=*=( =\T_= / ~ ~ \//
+# / \ `"`\ ~ / ~ /
+# | | |~ \ | ~/
+# /| | | |\ \ ~/- \ ~\
+# \| | |_|/| || | // /`
+# /\__/\_//_// __//\_/\_/\_((_|\((_//\_/\_/\_
+# | | | | \_) | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# | | | | | | | | | | | | | | |
+# * ,MMM8&&&. *
+# MMMM88&&&&& .
+# MMMM88&&&&&&&
+# * MMM88&&&&&&&&
+# MMM88&&&&&&&&
+# 'MMM88&&&&&&'
+# 'MMM8&&&' *
+# |\___/| /\___/\
+# ) ( ) ~( . '
+# =\ /= =\~ /=
+# )===( ) ~ (
+# / \ / \
+# | | ) ~ (
+# / \ / ~ \
+# \ / \~ ~/
+# _/\_/\_/\__ _/_/\_/\__~__/_/\_/\_/\_/\_/\_
+# | | | |( ( | | | )) | | | | | |
+# | | | | ) ) | | |//| | | | | | |
+# | | | |(_( | | (( | | | | | | |
+# | | | | | | | |\)| | | | | | |
+# | | | | | | | | | | | | | | |
+# * ,MMM8&&&. *
+# MMMM88&&&&& .
+# MMMM88&&&&&&&
+# * MMM88&&&&&&&&
+# MMM88&&&&&&&&
+# 'MMM88&&&&&&'
+# 'MMM8&&&' *
+# /\/|_ __/\\
+# / -\ /- ~\ . '
+# \ = Y =T_ = /
+# )==*(` `) ~ \
+# / \ / \
+# | | ) ~ (
+# / \ / ~ \
+# \ / \~ ~/
+# _/\_/\_/\__ _/_/\_/\__~__/_/\_/\_/\_/\_/\_
+# | | | | ) ) | | | (( | | | | | |
+# | | | |( ( | | | \\ | | | | | |
+# | | | | )_) | | | |))| | | | | |
+# | | | | | | | | (/ | | | | | |
+# | | | | | | | | | | | | | | |
diff --git a/widgy/conf/plugin_template/admin.py b/widgy/conf/plugin_template/admin.py
deleted file mode 100644
index ad433036c..000000000
--- a/widgy/conf/plugin_template/admin.py
+++ /dev/null
@@ -1,4 +0,0 @@
-from {{ plugin_name }}.models import *
-from widgy.admin import WidgyAdmin
-
-## Register Here ##
diff --git a/widgy/conf/plugin_template/models.py b/widgy/conf/plugin_template/models.py
deleted file mode 100644
index acdb0ad58..000000000
--- a/widgy/conf/plugin_template/models.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""
-Models for Widgy plugin: {{ plugin_name }}
-"""
-from django.db import models
-from widgy.models import Content
diff --git a/widgy/conf/plugin_template/static/widgy/js/components/widgy.example/component.js b/widgy/conf/plugin_template/static/widgy/js/components/widgy.example/component.js
deleted file mode 100644
index 5c5f251fb..000000000
--- a/widgy/conf/plugin_template/static/widgy/js/components/widgy.example/component.js
+++ /dev/null
@@ -1,15 +0,0 @@
-define([ 'widgy.contents', 'widgets/widgets'
- ], function(
- contents,
- widgets) {
-
- var ContentView = widgets.WidgetView.extend({
- editorClass: widgets.EditorView
- });
-
- var ExampleContent = contents.Content.extend({
- viewClass: ContentView
- });
-
- return ExampleContent;
-});
diff --git a/widgy/conf/plugin_template/templates/widgy/widgy.example/example.html b/widgy/conf/plugin_template/templates/widgy/widgy.example/example.html
deleted file mode 100644
index 3bbe8c6d4..000000000
--- a/widgy/conf/plugin_template/templates/widgy/widgy.example/example.html
+++ /dev/null
@@ -1,3 +0,0 @@
-
-
-
diff --git a/widgy/contrib/cms/templates/widgy/widgy.imagecontent/preview.html b/widgy/contrib/cms/templates/widgy/widgy.imagecontent/preview.html
deleted file mode 100644
index 2785e2cde..000000000
--- a/widgy/contrib/cms/templates/widgy/widgy.imagecontent/preview.html
+++ /dev/null
@@ -1,4 +0,0 @@
-
+
+
+
+{% endblock %}
diff --git a/widgy/contrib/form_builder/templates/widgy/form_builder/form/preview.html b/widgy/contrib/form_builder/templates/widgy/form_builder/form/preview.html
new file mode 100644
index 000000000..1d305b46e
--- /dev/null
+++ b/widgy/contrib/form_builder/templates/widgy/form_builder/form/preview.html
@@ -0,0 +1,8 @@
+{% extends "widgy/mixins/tabbed/preview.html" %}
+{% load i18n %}
+{% block title %}
+{{ block.super }}
+{% if self.submission_count %}
+ {% trans 'view submissions' %}
+{% endif %}
+{% endblock %}
diff --git a/widgy/contrib/form_builder/templates/widgy/form_builder/form/render.html b/widgy/contrib/form_builder/templates/widgy/form_builder/form/render.html
new file mode 100644
index 000000000..e4e189e72
--- /dev/null
+++ b/widgy/contrib/form_builder/templates/widgy/form_builder/form/render.html
@@ -0,0 +1,10 @@
+{% load widgy_tags %}
+
+{% if success %}
+ {% render self.children.meta.children.message %}
+{% else %}
+
+{% endif %}
diff --git a/widgy/contrib/form_builder/templates/widgy/form_builder/form_email.html b/widgy/contrib/form_builder/templates/widgy/form_builder/form_email.html
new file mode 100644
index 000000000..61f7c5c34
--- /dev/null
+++ b/widgy/contrib/form_builder/templates/widgy/form_builder/form_email.html
@@ -0,0 +1,13 @@
+{{ self.content|safe }}
+{% if self.include_form_data %}
+
+ {% for ident, header in headers.items %}
+
+
+
+ {% for row in rows %}
+ {{ header }}
+ {% endfor %}
+
+ {% for ident, value in row.items %}
+
+ {% endfor %}
+
+ {{ value }}
+ {% endfor %}
+ Form Data
+
+
+{% for label, value in data %}
+
+{% endif %}
diff --git a/widgy/contrib/form_builder/templates/widgy/form_builder/formfield/render.html b/widgy/contrib/form_builder/templates/widgy/form_builder/formfield/render.html
new file mode 100644
index 000000000..7f693b7a3
--- /dev/null
+++ b/widgy/contrib/form_builder/templates/widgy/form_builder/formfield/render.html
@@ -0,0 +1,9 @@
+{% if field.is_hidden %}{{ field }}{% else %}
+
+
+{% endfor %}
+{{ label }}
+ {{ value|linebreaksbr }}
+ {{ content.header }}
-
- {{#list}}
{{ content.header }}
-
- {% for item in list %}
-
- tags get encoded.
+ //
+
+ // This will only happen if makeHtml on the same converter instance is called from a plugin hook.
+ // Don't do that.
+ if (g_urls)
+ throw new Error("Recursive call to converter.makeHtml");
+
+ // Create the private state objects.
+ g_urls = new SaveHash();
+ g_titles = new SaveHash();
+ g_html_blocks = [];
+ g_list_level = 0;
+
+ text = pluginHooks.preConversion(text);
+
+ // attacklab: Replace ~ with ~T
+ // This lets us use tilde as an escape char to avoid md5 hashes
+ // The choice of character is arbitray; anything that isn't
+ // magic in Markdown will work.
+ text = text.replace(/~/g, "~T");
+
+ // attacklab: Replace $ with ~D
+ // RegExp interprets $ as a special character
+ // when it's in a replacement string
+ text = text.replace(/\$/g, "~D");
+
+ // Standardize line endings
+ text = text.replace(/\r\n/g, "\n"); // DOS to Unix
+ text = text.replace(/\r/g, "\n"); // Mac to Unix
+
+ // Make sure text begins and ends with a couple of newlines:
+ text = "\n\n" + text + "\n\n";
+
+ // Convert all tabs to spaces.
+ text = _Detab(text);
+
+ // Strip any lines consisting only of spaces and tabs.
+ // This makes subsequent regexen easier to write, because we can
+ // match consecutive blank lines with /\n+/ instead of something
+ // contorted like /[ \t]*\n+/ .
+ text = text.replace(/^[ \t]+$/mg, "");
+
+ // Turn block-level HTML blocks into hash entries
+ text = _HashHTMLBlocks(text);
+
+ // Strip link definitions, store in hashes.
+ text = _StripLinkDefinitions(text);
+
+ text = _RunBlockGamut(text);
+
+ text = _UnescapeSpecialChars(text);
+
+ // attacklab: Restore dollar signs
+ text = text.replace(/~D/g, "$$");
+
+ // attacklab: Restore tildes
+ text = text.replace(/~T/g, "~");
+
+ text = pluginHooks.postConversion(text);
+
+ g_html_blocks = g_titles = g_urls = null;
+
+ return text;
+ };
+
+ function _StripLinkDefinitions(text) {
+ //
+ // Strips link definitions from text, stores the URLs and titles in
+ // hash references.
+ //
+
+ // Link defs are in the form: ^[id]: url "optional title"
+
+ /*
+ text = text.replace(/
+ ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
+ [ \t]*
+ \n? // maybe *one* newline
+ [ \t]*
+ (\S+?)>? // url = $2
+ (?=\s|$) // lookahead for whitespace instead of the lookbehind removed below
+ [ \t]*
+ \n? // maybe one newline
+ [ \t]*
+ ( // (potential) title = $3
+ (\n*) // any lines skipped = $4 attacklab: lookbehind removed
+ [ \t]+
+ ["(]
+ (.+?) // title = $5
+ [")]
+ [ \t]*
+ )? // title is optional
+ (?:\n+|$)
+ /gm, function(){...});
+ */
+
+ text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*(\S+?)>?(?=\s|$)[ \t]*\n?[ \t]*((\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm,
+ function (wholeMatch, m1, m2, m3, m4, m5) {
+ m1 = m1.toLowerCase();
+ g_urls.set(m1, _EncodeAmpsAndAngles(m2)); // Link IDs are case-insensitive
+ if (m4) {
+ // Oops, found blank lines, so it's not a title.
+ // Put back the parenthetical statement we stole.
+ return m3;
+ } else if (m5) {
+ g_titles.set(m1, m5.replace(/"/g, """));
+ }
+
+ // Completely remove the definition from the text
+ return "";
+ }
+ );
+
+ return text;
+ }
+
+ function _HashHTMLBlocks(text) {
+
+ // Hashify HTML blocks:
+ // We only want to do this for block-level HTML tags, such as headers,
+ // lists, and tables. That's because we still want to wrap
. It was easier to make a special case than
+ // to make the other regex more complicated.
+
+ /*
+ text = text.replace(/
+ \n // Starting after a blank line
+ [ ]{0,3}
+ ( // save in $1
+ (<(hr) // start tag = $2
+ \b // word break
+ ([^<>])*?
+ \/?>) // the matching end tag
+ [ \t]*
+ (?=\n{2,}) // followed by a blank line
+ )
+ /g,hashElement);
+ */
+ text = text.replace(/\n[ ]{0,3}((<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g, hashElement);
+
+ // Special case for standalone HTML comments:
+
+ /*
+ text = text.replace(/
+ \n\n // Starting after a blank line
+ [ ]{0,3} // attacklab: g_tab_width - 1
+ ( // save in $1
+ -]|-[^>])(?:[^-]|-[^-])*)--) // see http://www.w3.org/TR/html-markup/syntax.html#comments and http://meta.stackoverflow.com/q/95256
+ >
+ [ \t]*
+ (?=\n{2,}) // followed by a blank line
+ )
+ /g,hashElement);
+ */
+ text = text.replace(/\n\n[ ]{0,3}(-]|-[^>])(?:[^-]|-[^-])*)--)>[ \t]*(?=\n{2,}))/g, hashElement);
+
+ // PHP and ASP-style processor instructions (...?> and <%...%>)
+
+ /*
+ text = text.replace(/
+ (?:
+ \n\n // Starting after a blank line
+ )
+ ( // save in $1
+ [ ]{0,3} // attacklab: g_tab_width - 1
+ (?:
+ <([?%]) // $2
+ [^\r]*?
+ \2>
+ )
+ [ \t]*
+ (?=\n{2,}) // followed by a blank line
+ )
+ /g,hashElement);
+ */
+ text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g, hashElement);
+
+ return text;
+ }
+
+ function hashElement(wholeMatch, m1) {
+ var blockText = m1;
+
+ // Undo double lines
+ blockText = blockText.replace(/^\n+/, "");
+
+ // strip trailing blank lines
+ blockText = blockText.replace(/\n+$/g, "");
+
+ // Replace the element text with a marker ("~KxK" where x is its key)
+ blockText = "\n\n~K" + (g_html_blocks.push(blockText) - 1) + "K\n\n";
+
+ return blockText;
+ }
+
+ function _RunBlockGamut(text, doNotUnhash) {
+ //
+ // These are all the transformations that form block-level
+ // tags like paragraphs, headers, and list items.
+ //
+ text = _DoHeaders(text);
+
+ // Do Horizontal Rules:
+ var replacement = "
\n";
+ text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, replacement);
+ text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm, replacement);
+ text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, replacement);
+
+ text = _DoLists(text);
+ text = _DoCodeBlocks(text);
+ text = _DoBlockQuotes(text);
+
+ // We already ran _HashHTMLBlocks() before, in Markdown(), but that
+ // was to escape raw HTML in the original Markdown source. This time,
+ // we're escaping the markup we've just created, so that we don't wrap
+ //
\n");
+
+ return text;
+ }
+
+ function _EscapeSpecialCharsWithinTagAttributes(text) {
+ //
+ // Within tags -- meaning between < and > -- encode [\ ` * _] so they
+ // don't conflict with their use in Markdown for code, italics and strong.
+ //
+
+ // Build a regex to find HTML tags and comments. See Friedl's
+ // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
+
+ // SE: changed the comment part of the regex
+
+ var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|-]|-[^>])(?:[^-]|-[^-])*)--)>)/gi;
+
+ text = text.replace(regex, function (wholeMatch) {
+ var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, "$1`");
+ tag = escapeCharacters(tag, wholeMatch.charAt(1) == "!" ? "\\`*_/" : "\\`*_"); // also escape slashes in comments to prevent autolinking there -- http://meta.stackoverflow.com/questions/95987
+ return tag;
+ });
+
+ return text;
+ }
+
+ function _DoAnchors(text) {
+ //
+ // Turn Markdown link shortcuts into XHTML tags.
+ //
+ //
+ // First, handle reference-style links: [link text] [id]
+ //
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ \[
+ (
+ (?:
+ \[[^\]]*\] // allow brackets nested one level
+ |
+ [^\[] // or anything else
+ )*
+ )
+ \]
+
+ [ ]? // one optional space
+ (?:\n[ ]*)? // one optional newline followed by spaces
+
+ \[
+ (.*?) // id = $3
+ \]
+ )
+ ()()()() // pad remaining backreferences
+ /g, writeAnchorTag);
+ */
+ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeAnchorTag);
+
+ //
+ // Next, inline-style links: [link text](url "optional title")
+ //
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ \[
+ (
+ (?:
+ \[[^\]]*\] // allow brackets nested one level
+ |
+ [^\[\]] // or anything else
+ )*
+ )
+ \]
+ \( // literal paren
+ [ \t]*
+ () // no id, so leave $3 empty
+ ( // href = $4
+ (?:
+ \([^)]*\) // allow one level of (correctly nested) parens (think MSDN)
+ |
+ [^()\s]
+ )*?
+ )>?
+ [ \t]*
+ ( // $5
+ (['"]) // quote char = $6
+ (.*?) // Title = $7
+ \6 // matching quote
+ [ \t]* // ignore any spaces/tabs between closing quote and )
+ )? // title is optional
+ \)
+ )
+ /g, writeAnchorTag);
+ */
+
+ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()((?:\([^)]*\)|[^()\s])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeAnchorTag);
+
+ //
+ // Last, handle reference-style shortcuts: [link text]
+ // These must come last in case you've also got [link test][1]
+ // or [link test](/foo)
+ //
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ \[
+ ([^\[\]]+) // link text = $2; can't contain '[' or ']'
+ \]
+ )
+ ()()()()() // pad rest of backreferences
+ /g, writeAnchorTag);
+ */
+ text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
+
+ return text;
+ }
+
+ function writeAnchorTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
+ if (m7 == undefined) m7 = "";
+ var whole_match = m1;
+ var link_text = m2.replace(/:\/\//g, "~P"); // to prevent auto-linking withing the link. will be converted back after the auto-linker runs
+ var link_id = m3.toLowerCase();
+ var url = m4;
+ var title = m7;
+
+ if (url == "") {
+ if (link_id == "") {
+ // lower-case and turn embedded newlines into spaces
+ link_id = link_text.toLowerCase().replace(/ ?\n/g, " ");
+ }
+ url = "#" + link_id;
+
+ if (g_urls.get(link_id) != undefined) {
+ url = g_urls.get(link_id);
+ if (g_titles.get(link_id) != undefined) {
+ title = g_titles.get(link_id);
+ }
+ }
+ else {
+ if (whole_match.search(/\(\s*\)$/m) > -1) {
+ // Special case for explicit empty url
+ url = "";
+ } else {
+ return whole_match;
+ }
+ }
+ }
+ url = encodeProblemUrlChars(url);
+ url = escapeCharacters(url, "*_");
+ var result = "" + link_text + "";
+
+ return result;
+ }
+
+ function _DoImages(text) {
+ //
+ // Turn Markdown image shortcuts into tags.
+ //
+
+ //
+ // First, handle reference-style labeled images: ![alt text][id]
+ //
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ !\[
+ (.*?) // alt text = $2
+ \]
+
+ [ ]? // one optional space
+ (?:\n[ ]*)? // one optional newline followed by spaces
+
+ \[
+ (.*?) // id = $3
+ \]
+ )
+ ()()()() // pad rest of backreferences
+ /g, writeImageTag);
+ */
+ text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag);
+
+ //
+ // Next, handle inline images: 
+ // Don't forget: encode * and _
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ !\[
+ (.*?) // alt text = $2
+ \]
+ \s? // One optional whitespace character
+ \( // literal paren
+ [ \t]*
+ () // no id, so leave $3 empty
+ (\S+?)>? // src url = $4
+ [ \t]*
+ ( // $5
+ (['"]) // quote char = $6
+ (.*?) // title = $7
+ \6 // matching quote
+ [ \t]*
+ )? // title is optional
+ \)
+ )
+ /g, writeImageTag);
+ */
+ text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeImageTag);
+
+ return text;
+ }
+
+ function attributeEncode(text) {
+ // unconditionally replace angle brackets here -- what ends up in an attribute (e.g. alt or title)
+ // never makes sense to have verbatim HTML in it (and the sanitizer would totally break it)
+ return text.replace(/>/g, ">").replace(/";
+
+ return result;
+ }
+
+ function _DoHeaders(text) {
+
+ // Setext-style headers:
+ // Header 1
+ // ========
+ //
+ // Header 2
+ // --------
+ //
+ text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
+ function (wholeMatch, m1) { return "
" + _RunSpanGamut(m1) + "
\n\n"; }
+ );
+
+ text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
+ function (matchFound, m1) { return "" + _RunSpanGamut(m1) + "
\n\n"; }
+ );
+
+ // atx-style headers:
+ // # Header 1
+ // ## Header 2
+ // ## Header 2 with closing hashes ##
+ // ...
+ // ###### Header 6
+ //
+
+ /*
+ text = text.replace(/
+ ^(\#{1,6}) // $1 = string of #'s
+ [ \t]*
+ (.+?) // $2 = Header text
+ [ \t]*
+ \#* // optional closing #'s (not counted)
+ \n+
+ /gm, function() {...});
+ */
+
+ text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
+ function (wholeMatch, m1, m2) {
+ var h_level = m1.length;
+ return "` blocks.
+ //
+
+ /*
+ text = text.replace(/
+ (?:\n\n|^)
+ ( // $1 = the code block -- one or more lines, starting with a space/tab
+ (?:
+ (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
+ .*\n+
+ )+
+ )
+ (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
+ /g ,function(){...});
+ */
+
+ // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
+ text += "~0";
+
+ text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
+ function (wholeMatch, m1, m2) {
+ var codeblock = m1;
+ var nextChar = m2;
+
+ codeblock = _EncodeCode(_Outdent(codeblock));
+ codeblock = _Detab(codeblock);
+ codeblock = codeblock.replace(/^\n+/g, ""); // trim leading newlines
+ codeblock = codeblock.replace(/\n+$/g, ""); // trim trailing whitespace
+
+ codeblock = "
";
+
+ return "\n\n" + codeblock + "\n\n" + nextChar;
+ }
+ );
+
+ // attacklab: strip sentinel
+ text = text.replace(/~0/, "");
+
+ return text;
+ }
+
+ function hashBlock(text) {
+ text = text.replace(/(^\n+|\n+$)/g, "");
+ return "\n\n~K" + (g_html_blocks.push(text) - 1) + "K\n\n";
+ }
+
+ function _DoCodeSpans(text) {
+ //
+ // * Backtick quotes are used for " + codeblock + "\n spans.
+ //
+ // * You can use multiple backticks as the delimiters if you want to
+ // include literal backticks in the code span. So, this input:
+ //
+ // Just type ``foo `bar` baz`` at the prompt.
+ //
+ // Will translate to:
+ //
+ // foo `bar` baz at the prompt.`bar` ...
+ //
+
+ /*
+ text = text.replace(/
+ (^|[^\\]) // Character before opening ` can't be a backslash
+ (`+) // $2 = Opening run of `
+ ( // $3 = The code block
+ [^\r]*?
+ [^`] // attacklab: work around lack of lookbehind
+ )
+ \2 // Matching closer
+ (?!`)
+ /gm, function(){...});
+ */
+
+ text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
+ function (wholeMatch, m1, m2, m3, m4) {
+ var c = m3;
+ c = c.replace(/^([ \t]*)/g, ""); // leading whitespace
+ c = c.replace(/[ \t]*$/g, ""); // trailing whitespace
+ c = _EncodeCode(c);
+ c = c.replace(/:\/\//g, "~P"); // to prevent auto-linking. Not necessary in code *blocks*, but in code spans. Will be converted back after the auto-linker runs.
+ return m1 + "" + c + "";
+ }
+ );
+
+ return text;
+ }
+
+ function _EncodeCode(text) {
+ //
+ // Encode/escape certain characters inside Markdown code runs.
+ // The point is that in code, these characters are literals,
+ // and lose their special Markdown meanings.
+ //
+ // Encode all ampersands; HTML entities are not
+ // entities within a Markdown code span.
+ text = text.replace(/&/g, "&");
+
+ // Do the angle bracket song and dance:
+ text = text.replace(//g, ">");
+
+ // Now, escape characters that are magic in Markdown:
+ text = escapeCharacters(text, "\*_{}[]\\", false);
+
+ // jj the line above breaks this:
+ //---
+
+ //* Item
+
+ // 1. Subitem
+
+ // special char: *
+ //---
+
+ return text;
+ }
+
+ function _DoItalicsAndBold(text) {
+
+ // must go first:
+ text = text.replace(/([\W_]|^)(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\2([\W_]|$)/g,
+ "$1$3$4");
+
+ text = text.replace(/([\W_]|^)(\*|_)(?=\S)([^\r\*_]*?\S)\2([\W_]|$)/g,
+ "$1$3$4");
+
+ return text;
+ }
+
+ function _DoBlockQuotes(text) {
+
+ /*
+ text = text.replace(/
+ ( // Wrap whole match in $1
+ (
+ ^[ \t]*>[ \t]? // '>' at the start of a line
+ .+\n // rest of the first line
+ (.+\n)* // subsequent consecutive lines
+ \n* // blanks
+ )+
+ )
+ /gm, function(){...});
+ */
+
+ text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
+ function (wholeMatch, m1) {
+ var bq = m1;
+
+ // attacklab: hack around Konqueror 3.5.4 bug:
+ // "----------bug".replace(/^-/g,"") == "bug"
+
+ bq = bq.replace(/^[ \t]*>[ \t]?/gm, "~0"); // trim one level of quoting
+
+ // attacklab: clean up hack
+ bq = bq.replace(/~0/g, "");
+
+ bq = bq.replace(/^[ \t]+$/gm, ""); // trim whitespace-only lines
+ bq = _RunBlockGamut(bq); // recurse
+
+ bq = bq.replace(/(^|\n)/g, "$1 ");
+ // These leading spaces screw with content, so we need to fix that:
+ bq = bq.replace(
+ /(\s*
[^\r]+?<\/pre>)/gm,
+ function (wholeMatch, m1) {
+ var pre = m1;
+ // attacklab: hack around Konqueror 3.5.4 bug:
+ pre = pre.replace(/^ /mg, "~0");
+ pre = pre.replace(/~0/g, "");
+ return pre;
+ });
+
+ return hashBlock("\n" + bq + "\n
");
+ }
+ );
+ return text;
+ }
+
+ function _FormParagraphs(text, doNotUnhash) {
+ //
+ // Params:
+ // $text - string to process with html Ctrl+Q",
+ quoteexample: "Blockquote",
+
+ code: "Code Sample
Ctrl+K",
+ codeexample: "enter code here",
+
+ image: "Image Ctrl+G",
+ imagedescription: "enter image description here",
+ imagedialog: "
Need free image hosting? Ctrl+O",
+ ulist: "Bulleted List
Ctrl+U",
+ litem: "List item",
+
+ heading: "Heading
/
Ctrl+H",
+ headingexample: "Heading",
+
+ hr: "Horizontal Rule
Ctrl+R",
+
+ undo: "Undo - Ctrl+Z",
+ redo: "Redo - Ctrl+Y",
+ redomac: "Redo - Ctrl+Shift+Z",
+
+ help: "Markdown Editing Help"
+ };
+
+
+ // -------------------------------------------------------------------
+ // YOUR CHANGES GO HERE
+ //
+ // I've tried to localize the things you are likely to change to
+ // this area.
+ // -------------------------------------------------------------------
+
+ // The default text that appears in the dialog input box when entering
+ // links.
+ var imageDefaultText = "http://";
+ var linkDefaultText = "http://";
+
+ // -------------------------------------------------------------------
+ // END OF YOUR CHANGES
+ // -------------------------------------------------------------------
+
+ // options, if given, can have the following properties:
+ // options.helpButton = { handler: yourEventHandler }
+ // options.strings = { italicexample: "slanted text" }
+ // `yourEventHandler` is the click handler for the help button.
+ // If `options.helpButton` isn't given, not help button is created.
+ // `options.strings` can have any or all of the same properties as
+ // `defaultStrings` above, so you can just override some string displayed
+ // to the user on a case-by-case basis, or translate all strings to
+ // a different language.
+ //
+ // For backwards compatibility reasons, the `options` argument can also
+ // be just the `helpButton` object, and `strings.help` can also be set via
+ // `helpButton.title`. This should be considered legacy.
+ //
+ // The constructed editor object has the methods:
+ // - getConverter() returns the markdown converter object that was passed to the constructor
+ // - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op.
+ // - refreshPreview() forces the preview to be updated. This method is only available after run() was called.
+ Markdown.Editor = function (markdownConverter, textarea, preview, buttonBar, options) {
+
+ options = options || {};
+
+ if (typeof options.handler === "function") { //backwards compatible behavior
+ options = { helpButton: options };
+ }
+ options.strings = options.strings || {};
+ if (options.helpButton) {
+ options.strings.help = options.strings.help || options.helpButton.title;
+ }
+ var getString = function (identifier) { return options.strings[identifier] || defaultsStrings[identifier]; }
+
+ var postfix = idPostfix++;
+
+ var hooks = this.hooks = new Markdown.HookCollection();
+ hooks.addNoop("onPreviewRefresh"); // called with no arguments after the preview has been refreshed
+ hooks.addNoop("postBlockquoteCreation"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text
+ hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates
+ * its own image insertion dialog, this hook should return true, and the callback should be called with the chosen
+ * image url (or null if the user cancelled). If this hook returns false, the default dialog will be used.
+ */
+
+ this.getConverter = function () { return markdownConverter; }
+
+ var that = this,
+ panels;
+
+ this.run = function () {
+ if (panels)
+ return; // already initialized
+
+ panels = new PanelCollection(textarea, preview, buttonBar);
+ var commandManager = new CommandManager(hooks, getString);
+ var previewManager = new PreviewManager(markdownConverter, panels, function () { hooks.onPreviewRefresh(); });
+ var undoManager, uiManager;
+
+ if (!/\?noundo/.test(doc.location.href)) {
+ undoManager = new UndoManager(function () {
+ previewManager.refresh();
+ if (uiManager) // not available on the first call
+ uiManager.setUndoRedoButtonStates();
+ }, panels);
+ this.textOperation = function (f) {
+ undoManager.setCommandMode();
+ f();
+ that.refreshPreview();
+ }
+ }
+
+ uiManager = new UIManager(postfix, panels, undoManager, previewManager, commandManager, options.helpButton, getString);
+ uiManager.setUndoRedoButtonStates();
+
+ var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); };
+
+ forceRefresh();
+ };
+
+ }
+
+ // before: contains all the text in the input box BEFORE the selection.
+ // after: contains all the text in the input box AFTER the selection.
+ function Chunks() { }
+
+ // startRegex: a regular expression to find the start tag
+ // endRegex: a regular expresssion to find the end tag
+ Chunks.prototype.findTags = function (startRegex, endRegex) {
+
+ var chunkObj = this;
+ var regex;
+
+ if (startRegex) {
+
+ regex = util.extendRegExp(startRegex, "", "$");
+
+ this.before = this.before.replace(regex,
+ function (match) {
+ chunkObj.startTag = chunkObj.startTag + match;
+ return "";
+ });
+
+ regex = util.extendRegExp(startRegex, "^", "");
+
+ this.selection = this.selection.replace(regex,
+ function (match) {
+ chunkObj.startTag = chunkObj.startTag + match;
+ return "";
+ });
+ }
+
+ if (endRegex) {
+
+ regex = util.extendRegExp(endRegex, "", "$");
+
+ this.selection = this.selection.replace(regex,
+ function (match) {
+ chunkObj.endTag = match + chunkObj.endTag;
+ return "";
+ });
+
+ regex = util.extendRegExp(endRegex, "^", "");
+
+ this.after = this.after.replace(regex,
+ function (match) {
+ chunkObj.endTag = match + chunkObj.endTag;
+ return "";
+ });
+ }
+ };
+
+ // If remove is false, the whitespace is transferred
+ // to the before/after regions.
+ //
+ // If remove is true, the whitespace disappears.
+ Chunks.prototype.trimWhitespace = function (remove) {
+ var beforeReplacer, afterReplacer, that = this;
+ if (remove) {
+ beforeReplacer = afterReplacer = "";
+ } else {
+ beforeReplacer = function (s) { that.before += s; return ""; }
+ afterReplacer = function (s) { that.after = s + that.after; return ""; }
+ }
+
+ this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer);
+ };
+
+
+ Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) {
+
+ if (nLinesBefore === undefined) {
+ nLinesBefore = 1;
+ }
+
+ if (nLinesAfter === undefined) {
+ nLinesAfter = 1;
+ }
+
+ nLinesBefore++;
+ nLinesAfter++;
+
+ var regexText;
+ var replacementText;
+
+ // chrome bug ... documented at: http://meta.stackoverflow.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985
+ if (navigator.userAgent.match(/Chrome/)) {
+ "X".match(/()./);
+ }
+
+ this.selection = this.selection.replace(/(^\n*)/, "");
+
+ this.startTag = this.startTag + re.$1;
+
+ this.selection = this.selection.replace(/(\n*$)/, "");
+ this.endTag = this.endTag + re.$1;
+ this.startTag = this.startTag.replace(/(^\n*)/, "");
+ this.before = this.before + re.$1;
+ this.endTag = this.endTag.replace(/(\n*$)/, "");
+ this.after = this.after + re.$1;
+
+ if (this.before) {
+
+ regexText = replacementText = "";
+
+ while (nLinesBefore--) {
+ regexText += "\\n?";
+ replacementText += "\n";
+ }
+
+ if (findExtraNewlines) {
+ regexText = "\\n*";
+ }
+ this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
+ }
+
+ if (this.after) {
+
+ regexText = replacementText = "";
+
+ while (nLinesAfter--) {
+ regexText += "\\n?";
+ replacementText += "\n";
+ }
+ if (findExtraNewlines) {
+ regexText = "\\n*";
+ }
+
+ this.after = this.after.replace(new re(regexText, ""), replacementText);
+ }
+ };
+
+ // end of Chunks
+
+ // A collection of the important regions on the page.
+ // Cached so we don't have to keep traversing the DOM.
+ // Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around
+ // this issue:
+ // Internet explorer has problems with CSS sprite buttons that use HTML
+ // lists. When you click on the background image "button", IE will
+ // select the non-existent link text and discard the selection in the
+ // textarea. The solution to this is to cache the textarea selection
+ // on the button's mousedown event and set a flag. In the part of the
+ // code where we need to grab the selection, we check for the flag
+ // and, if it's set, use the cached area instead of querying the
+ // textarea.
+ //
+ // This ONLY affects Internet Explorer (tested on versions 6, 7
+ // and 8) and ONLY on button clicks. Keyboard shortcuts work
+ // normally since the focus never leaves the textarea.
+ //
+ // edited by Rocky Meza
+ // don't use an because we don't have control over IDs.
+ function PanelCollection(textarea, preview, buttonBar) {
+ this.buttonBar = buttonBar;
+ this.preview = preview;
+ this.input = textarea;
+ };
+
+ // Returns true if the DOM element is visible, false if it's hidden.
+ // Checks if display is anything other than none.
+ util.isVisible = function (elem) {
+
+ if (window.getComputedStyle) {
+ // Most browsers
+ return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
+ }
+ else if (elem.currentStyle) {
+ // IE
+ return elem.currentStyle["display"] !== "none";
+ }
+ };
+
+
+ // Adds a listener callback to a DOM element which is fired on a specified
+ // event.
+ util.addEvent = function (elem, event, listener) {
+ if (elem.attachEvent) {
+ // IE only. The "on" is mandatory.
+ elem.attachEvent("on" + event, listener);
+ }
+ else {
+ // Other browsers.
+ elem.addEventListener(event, listener, false);
+ }
+ };
+
+
+ // Removes a listener callback from a DOM element which is fired on a specified
+ // event.
+ util.removeEvent = function (elem, event, listener) {
+ if (elem.detachEvent) {
+ // IE only. The "on" is mandatory.
+ elem.detachEvent("on" + event, listener);
+ }
+ else {
+ // Other browsers.
+ elem.removeEventListener(event, listener, false);
+ }
+ };
+
+ // Converts \r\n and \r to \n.
+ util.fixEolChars = function (text) {
+ text = text.replace(/\r\n/g, "\n");
+ text = text.replace(/\r/g, "\n");
+ return text;
+ };
+
+ // Extends a regular expression. Returns a new RegExp
+ // using pre + regex + post as the expression.
+ // Used in a few functions where we have a base
+ // expression and we want to pre- or append some
+ // conditions to it (e.g. adding "$" to the end).
+ // The flags are unchanged.
+ //
+ // regex is a RegExp, pre and post are strings.
+ util.extendRegExp = function (regex, pre, post) {
+
+ if (pre === null || pre === undefined) {
+ pre = "";
+ }
+ if (post === null || post === undefined) {
+ post = "";
+ }
+
+ var pattern = regex.toString();
+ var flags;
+
+ // Replace the flags with empty space and store them.
+ pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) {
+ flags = flagsPart;
+ return "";
+ });
+
+ // Remove the slash delimiters on the regular expression.
+ pattern = pattern.replace(/(^\/|\/$)/g, "");
+ pattern = pre + pattern + post;
+
+ return new re(pattern, flags);
+ }
+
+ // UNFINISHED
+ // The assignment in the while loop makes jslint cranky.
+ // I'll change it to a better loop later.
+ position.getTop = function (elem, isInner) {
+ var result = elem.offsetTop;
+ if (!isInner) {
+ while (elem = elem.offsetParent) {
+ result += elem.offsetTop;
+ }
+ }
+ return result;
+ };
+
+ position.getHeight = function (elem) {
+ return elem.offsetHeight || elem.scrollHeight;
+ };
+
+ position.getWidth = function (elem) {
+ return elem.offsetWidth || elem.scrollWidth;
+ };
+
+ position.getPageSize = function () {
+
+ var scrollWidth, scrollHeight;
+ var innerWidth, innerHeight;
+
+ // It's not very clear which blocks work with which browsers.
+ if (self.innerHeight && self.scrollMaxY) {
+ scrollWidth = doc.body.scrollWidth;
+ scrollHeight = self.innerHeight + self.scrollMaxY;
+ }
+ else if (doc.body.scrollHeight > doc.body.offsetHeight) {
+ scrollWidth = doc.body.scrollWidth;
+ scrollHeight = doc.body.scrollHeight;
+ }
+ else {
+ scrollWidth = doc.body.offsetWidth;
+ scrollHeight = doc.body.offsetHeight;
+ }
+
+ if (self.innerHeight) {
+ // Non-IE browser
+ innerWidth = self.innerWidth;
+ innerHeight = self.innerHeight;
+ }
+ else if (doc.documentElement && doc.documentElement.clientHeight) {
+ // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
+ innerWidth = doc.documentElement.clientWidth;
+ innerHeight = doc.documentElement.clientHeight;
+ }
+ else if (doc.body) {
+ // Other versions of IE
+ innerWidth = doc.body.clientWidth;
+ innerHeight = doc.body.clientHeight;
+ }
+
+ var maxWidth = Math.max(scrollWidth, innerWidth);
+ var maxHeight = Math.max(scrollHeight, innerHeight);
+ return [maxWidth, maxHeight, innerWidth, innerHeight];
+ };
+
+ // Handles pushing and popping TextareaStates for undo/redo commands.
+ // I should rename the stack variables to list.
+ function UndoManager(callback, panels) {
+
+ var undoObj = this;
+ var undoStack = []; // A stack of undo states
+ var stackPtr = 0; // The index of the current state
+ var mode = "none";
+ var lastState; // The last state
+ var timer; // The setTimeout handle for cancelling the timer
+ var inputStateObj;
+
+ // Set the mode for later logic steps.
+ var setMode = function (newMode, noSave) {
+ if (mode != newMode) {
+ mode = newMode;
+ if (!noSave) {
+ saveState();
+ }
+ }
+
+ if (!uaSniffed.isIE || mode != "moving") {
+ timer = setTimeout(refreshState, 1);
+ }
+ else {
+ inputStateObj = null;
+ }
+ };
+
+ var refreshState = function (isInitialState) {
+ inputStateObj = new TextareaState(panels, isInitialState);
+ timer = undefined;
+ };
+
+ this.setCommandMode = function () {
+ mode = "command";
+ saveState();
+ timer = setTimeout(refreshState, 0);
+ };
+
+ this.canUndo = function () {
+ return stackPtr > 1;
+ };
+
+ this.canRedo = function () {
+ if (undoStack[stackPtr + 1]) {
+ return true;
+ }
+ return false;
+ };
+
+ // Removes the last state and restores it.
+ this.undo = function () {
+
+ if (undoObj.canUndo()) {
+ if (lastState) {
+ // What about setting state -1 to null or checking for undefined?
+ lastState.restore();
+ lastState = null;
+ }
+ else {
+ undoStack[stackPtr] = new TextareaState(panels);
+ undoStack[--stackPtr].restore();
+
+ if (callback) {
+ callback();
+ }
+ }
+ }
+
+ mode = "none";
+ panels.input.focus();
+ refreshState();
+ };
+
+ // Redo an action.
+ this.redo = function () {
+
+ if (undoObj.canRedo()) {
+
+ undoStack[++stackPtr].restore();
+
+ if (callback) {
+ callback();
+ }
+ }
+
+ mode = "none";
+ panels.input.focus();
+ refreshState();
+ };
+
+ // Push the input area state to the stack.
+ var saveState = function () {
+ var currState = inputStateObj || new TextareaState(panels);
+
+ if (!currState) {
+ return false;
+ }
+ if (mode == "moving") {
+ if (!lastState) {
+ lastState = currState;
+ }
+ return;
+ }
+ if (lastState) {
+ if (undoStack[stackPtr - 1].text != lastState.text) {
+ undoStack[stackPtr++] = lastState;
+ }
+ lastState = null;
+ }
+ undoStack[stackPtr++] = currState;
+ undoStack[stackPtr + 1] = null;
+ if (callback) {
+ callback();
+ }
+ };
+
+ var handleCtrlYZ = function (event) {
+
+ var handled = false;
+
+ if (event.ctrlKey || event.metaKey) {
+
+ // IE and Opera do not support charCode.
+ var keyCode = event.charCode || event.keyCode;
+ var keyCodeChar = String.fromCharCode(keyCode);
+
+ switch (keyCodeChar.toLowerCase()) {
+
+ case "y":
+ undoObj.redo();
+ handled = true;
+ break;
+
+ case "z":
+ if (!event.shiftKey) {
+ undoObj.undo();
+ }
+ else {
+ undoObj.redo();
+ }
+ handled = true;
+ break;
+ }
+ }
+
+ if (handled) {
+ if (event.preventDefault) {
+ event.preventDefault();
+ }
+ if (window.event) {
+ window.event.returnValue = false;
+ }
+ return;
+ }
+ };
+
+ // Set the mode depending on what is going on in the input area.
+ var handleModeChange = function (event) {
+
+ if (!event.ctrlKey && !event.metaKey) {
+
+ var keyCode = event.keyCode;
+
+ if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
+ // 33 - 40: page up/dn and arrow keys
+ // 63232 - 63235: page up/dn and arrow keys on safari
+ setMode("moving");
+ }
+ else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
+ // 8: backspace
+ // 46: delete
+ // 127: delete
+ setMode("deleting");
+ }
+ else if (keyCode == 13) {
+ // 13: Enter
+ setMode("newlines");
+ }
+ else if (keyCode == 27) {
+ // 27: escape
+ setMode("escape");
+ }
+ else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
+ // 16-20 are shift, etc.
+ // 91: left window key
+ // I think this might be a little messed up since there are
+ // a lot of nonprinting keys above 20.
+ setMode("typing");
+ }
+ }
+ };
+
+ var setEventHandlers = function () {
+ util.addEvent(panels.input, "keypress", function (event) {
+ // keyCode 89: y
+ // keyCode 90: z
+ if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
+ event.preventDefault();
+ }
+ });
+
+ var handlePaste = function () {
+ if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) {
+ if (timer == undefined) {
+ mode = "paste";
+ saveState();
+ refreshState();
+ }
+ }
+ };
+
+ util.addEvent(panels.input, "keydown", handleCtrlYZ);
+ util.addEvent(panels.input, "keydown", handleModeChange);
+ util.addEvent(panels.input, "mousedown", function () {
+ setMode("moving");
+ });
+
+ panels.input.onpaste = handlePaste;
+ panels.input.ondrop = handlePaste;
+ };
+
+ var init = function () {
+ setEventHandlers();
+ refreshState(true);
+ saveState();
+ };
+
+ init();
+ }
+
+ // end of UndoManager
+
+ // The input textarea state/contents.
+ // This is used to implement undo/redo by the undo manager.
+ function TextareaState(panels, isInitialState) {
+
+ // Aliases
+ var stateObj = this;
+ var inputArea = panels.input;
+ this.init = function () {
+ if (!util.isVisible(inputArea)) {
+ return;
+ }
+ if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box
+ return;
+ }
+
+ this.setInputAreaSelectionStartEnd();
+ this.scrollTop = inputArea.scrollTop;
+ if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
+ this.text = inputArea.value;
+ }
+
+ }
+
+ // Sets the selected text in the input box after we've performed an
+ // operation.
+ this.setInputAreaSelection = function () {
+
+ if (!util.isVisible(inputArea)) {
+ return;
+ }
+
+ if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) {
+
+ inputArea.focus();
+ inputArea.selectionStart = stateObj.start;
+ inputArea.selectionEnd = stateObj.end;
+ inputArea.scrollTop = stateObj.scrollTop;
+ }
+ else if (doc.selection) {
+
+ if (doc.activeElement && doc.activeElement !== inputArea) {
+ return;
+ }
+
+ inputArea.focus();
+ var range = inputArea.createTextRange();
+ range.moveStart("character", -inputArea.value.length);
+ range.moveEnd("character", -inputArea.value.length);
+ range.moveEnd("character", stateObj.end);
+ range.moveStart("character", stateObj.start);
+ range.select();
+ }
+ };
+
+ this.setInputAreaSelectionStartEnd = function () {
+
+ if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) {
+
+ stateObj.start = inputArea.selectionStart;
+ stateObj.end = inputArea.selectionEnd;
+ }
+ else if (doc.selection) {
+
+ stateObj.text = util.fixEolChars(inputArea.value);
+
+ // IE loses the selection in the textarea when buttons are
+ // clicked. On IE we cache the selection. Here, if something is cached,
+ // we take it.
+ var range = panels.ieCachedRange || doc.selection.createRange();
+
+ var fixedRange = util.fixEolChars(range.text);
+ var marker = "\x07";
+ var markedRange = marker + fixedRange + marker;
+ range.text = markedRange;
+ var inputText = util.fixEolChars(inputArea.value);
+
+ range.moveStart("character", -markedRange.length);
+ range.text = fixedRange;
+
+ stateObj.start = inputText.indexOf(marker);
+ stateObj.end = inputText.lastIndexOf(marker) - marker.length;
+
+ var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
+
+ if (len) {
+ range.moveStart("character", -fixedRange.length);
+ while (len--) {
+ fixedRange += "\n";
+ stateObj.end += 1;
+ }
+ range.text = fixedRange;
+ }
+
+ if (panels.ieCachedRange)
+ stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange
+
+ panels.ieCachedRange = null;
+
+ this.setInputAreaSelection();
+ }
+ };
+
+ // Restore this state into the input area.
+ this.restore = function () {
+
+ if (stateObj.text != undefined && stateObj.text != inputArea.value) {
+ inputArea.value = stateObj.text;
+ }
+ this.setInputAreaSelection();
+ inputArea.scrollTop = stateObj.scrollTop;
+ };
+
+ // Gets a collection of HTML chunks from the inptut textarea.
+ this.getChunks = function () {
+
+ var chunk = new Chunks();
+ chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
+ chunk.startTag = "";
+ chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
+ chunk.endTag = "";
+ chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
+ chunk.scrollTop = stateObj.scrollTop;
+
+ return chunk;
+ };
+
+ // Sets the TextareaState properties given a chunk of markdown.
+ this.setChunks = function (chunk) {
+
+ chunk.before = chunk.before + chunk.startTag;
+ chunk.after = chunk.endTag + chunk.after;
+
+ this.start = chunk.before.length;
+ this.end = chunk.before.length + chunk.selection.length;
+ this.text = chunk.before + chunk.selection + chunk.after;
+ this.scrollTop = chunk.scrollTop;
+ };
+ this.init();
+ };
+
+ function PreviewManager(converter, panels, previewRefreshCallback) {
+
+ var managerObj = this;
+ var timeout;
+ var elapsedTime;
+ var oldInputText;
+ var maxDelay = 3000;
+ var startType = "delayed"; // The other legal value is "manual"
+
+ // Adds event listeners to elements
+ var setupEvents = function (inputElem, listener) {
+
+ util.addEvent(inputElem, "input", listener);
+ inputElem.onpaste = listener;
+ inputElem.ondrop = listener;
+
+ util.addEvent(inputElem, "keypress", listener);
+ util.addEvent(inputElem, "keydown", listener);
+ };
+
+ var getDocScrollTop = function () {
+
+ var result = 0;
+
+ if (window.innerHeight) {
+ result = window.pageYOffset;
+ }
+ else
+ if (doc.documentElement && doc.documentElement.scrollTop) {
+ result = doc.documentElement.scrollTop;
+ }
+ else
+ if (doc.body) {
+ result = doc.body.scrollTop;
+ }
+
+ return result;
+ };
+
+ var makePreviewHtml = function () {
+
+ // If there is no registered preview panel
+ // there is nothing to do.
+ if (!panels.preview)
+ return;
+
+
+ var text = panels.input.value;
+ if (text && text == oldInputText) {
+ return; // Input text hasn't changed.
+ }
+ else {
+ oldInputText = text;
+ }
+
+ var prevTime = new Date().getTime();
+
+ text = converter.makeHtml(text);
+
+ // Calculate the processing time of the HTML creation.
+ // It's used as the delay time in the event listener.
+ var currTime = new Date().getTime();
+ elapsedTime = currTime - prevTime;
+
+ pushPreviewHtml(text);
+ };
+
+ // setTimeout is already used. Used as an event listener.
+ var applyTimeout = function () {
+
+ if (timeout) {
+ clearTimeout(timeout);
+ timeout = undefined;
+ }
+
+ if (startType !== "manual") {
+
+ var delay = 0;
+
+ if (startType === "delayed") {
+ delay = elapsedTime;
+ }
+
+ if (delay > maxDelay) {
+ delay = maxDelay;
+ }
+ timeout = setTimeout(makePreviewHtml, delay);
+ }
+ };
+
+ var getScaleFactor = function (panel) {
+ if (panel.scrollHeight <= panel.clientHeight) {
+ return 1;
+ }
+ return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
+ };
+
+ var setPanelScrollTops = function () {
+ if (panels.preview) {
+ panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview);
+ }
+ };
+
+ this.refresh = function (requiresRefresh) {
+
+ if (requiresRefresh) {
+ oldInputText = "";
+ makePreviewHtml();
+ }
+ else {
+ applyTimeout();
+ }
+ };
+
+ this.processingTime = function () {
+ return elapsedTime;
+ };
+
+ var isFirstTimeFilled = true;
+
+ // IE doesn't let you use innerHTML if the element is contained somewhere in a table
+ // (which is the case for inline editing) -- in that case, detach the element, set the
+ // value, and reattach. Yes, that *is* ridiculous.
+ var ieSafePreviewSet = function (text) {
+ var preview = panels.preview;
+ var parent = preview.parentNode;
+ var sibling = preview.nextSibling;
+ parent.removeChild(preview);
+ preview.innerHTML = text;
+ if (!sibling)
+ parent.appendChild(preview);
+ else
+ parent.insertBefore(preview, sibling);
+ }
+
+ var nonSuckyBrowserPreviewSet = function (text) {
+ panels.preview.innerHTML = text;
+ }
+
+ var previewSetter;
+
+ var previewSet = function (text) {
+ if (previewSetter)
+ return previewSetter(text);
+
+ try {
+ nonSuckyBrowserPreviewSet(text);
+ previewSetter = nonSuckyBrowserPreviewSet;
+ } catch (e) {
+ previewSetter = ieSafePreviewSet;
+ previewSetter(text);
+ }
+ };
+
+ var pushPreviewHtml = function (text) {
+
+ var emptyTop = position.getTop(panels.input) - getDocScrollTop();
+
+ if (panels.preview) {
+ previewSet(text);
+ previewRefreshCallback();
+ }
+
+ setPanelScrollTops();
+
+ if (isFirstTimeFilled) {
+ isFirstTimeFilled = false;
+ return;
+ }
+
+ var fullTop = position.getTop(panels.input) - getDocScrollTop();
+
+ if (uaSniffed.isIE) {
+ setTimeout(function () {
+ window.scrollBy(0, fullTop - emptyTop);
+ }, 0);
+ }
+ else {
+ window.scrollBy(0, fullTop - emptyTop);
+ }
+ };
+
+ var init = function () {
+
+ setupEvents(panels.input, applyTimeout);
+ makePreviewHtml();
+
+ if (panels.preview) {
+ panels.preview.scrollTop = 0;
+ }
+ };
+
+ init();
+ };
+
+ // Creates the background behind the hyperlink text entry box.
+ // And download dialog
+ // Most of this has been moved to CSS but the div creation and
+ // browser-specific hacks remain here.
+ ui.createBackground = function () {
+
+ var background = doc.createElement("div"),
+ style = background.style;
+
+ background.className = "wmd-prompt-background";
+
+ style.position = "absolute";
+ style.top = "0";
+
+ style.zIndex = "1000";
+
+ if (uaSniffed.isIE) {
+ style.filter = "alpha(opacity=50)";
+ }
+ else {
+ style.opacity = "0.5";
+ }
+
+ var pageSize = position.getPageSize();
+ style.height = pageSize[1] + "px";
+
+ if (uaSniffed.isIE) {
+ style.left = doc.documentElement.scrollLeft;
+ style.width = doc.documentElement.clientWidth;
+ }
+ else {
+ style.left = "0";
+ style.width = "100%";
+ }
+
+ doc.body.appendChild(background);
+ return background;
+ };
+
+ // This simulates a modal dialog box and asks for the URL when you
+ // click the hyperlink or image buttons.
+ //
+ // text: The html for the input box.
+ // defaultInputText: The default value that appears in the input box.
+ // callback: The function which is executed when the prompt is dismissed, either via OK or Cancel.
+ // It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel
+ // was chosen).
+ ui.prompt = function (text, defaultInputText, callback) {
+
+ // These variables need to be declared at this level since they are used
+ // in multiple functions.
+ var dialog; // The dialog box.
+ var input; // The text box where you enter the hyperlink.
+
+
+ if (defaultInputText === undefined) {
+ defaultInputText = "";
+ }
+
+ // Used as a keydown event handler. Esc dismisses the prompt.
+ // Key code 27 is ESC.
+ var checkEscape = function (key) {
+ var code = (key.charCode || key.keyCode);
+ if (code === 27) {
+ close(true);
+ }
+ };
+
+ // Dismisses the hyperlink input box.
+ // isCancel is true if we don't care about the input text.
+ // isCancel is false if we are going to keep the text.
+ var close = function (isCancel) {
+ util.removeEvent(doc.body, "keydown", checkEscape);
+ var text = input.value;
+
+ if (isCancel) {
+ text = null;
+ }
+ else {
+ // Fixes common pasting errors.
+ text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://');
+ if (!/^(?:https?|ftp):\/\//.test(text))
+ text = 'http://' + text;
+ }
+
+ dialog.parentNode.removeChild(dialog);
+
+ callback(text);
+ return false;
+ };
+
+
+
+ // Create the text input box form/window.
+ var createDialog = function () {
+
+ // The main dialog box.
+ dialog = doc.createElement("div");
+ dialog.className = "wmd-prompt-dialog";
+ dialog.style.padding = "10px;";
+ dialog.style.position = "fixed";
+ dialog.style.width = "400px";
+ dialog.style.zIndex = "1001";
+
+ // The dialog text.
+ var question = doc.createElement("div");
+ question.innerHTML = text;
+ question.style.padding = "5px";
+ dialog.appendChild(question);
+
+ // The web form container for the text box and buttons.
+ var form = doc.createElement("form"),
+ style = form.style;
+ form.onsubmit = function () { return close(false); };
+ style.padding = "0";
+ style.margin = "0";
+ style.cssFloat = "left";
+ style.width = "100%";
+ style.textAlign = "center";
+ style.position = "relative";
+ dialog.appendChild(form);
+
+ // The input text box
+ input = doc.createElement("input");
+ input.type = "text";
+ input.value = defaultInputText;
+ style = input.style;
+ style.display = "block";
+ style.width = "80%";
+ style.marginLeft = style.marginRight = "auto";
+ form.appendChild(input);
+
+ // The ok button
+ var okButton = doc.createElement("input");
+ okButton.type = "button";
+ okButton.onclick = function () { return close(false); };
+ okButton.value = "OK";
+ style = okButton.style;
+ style.margin = "10px";
+ style.display = "inline";
+ style.width = "7em";
+
+
+ // The cancel button
+ var cancelButton = doc.createElement("input");
+ cancelButton.type = "button";
+ cancelButton.onclick = function () { return close(true); };
+ cancelButton.value = "Cancel";
+ style = cancelButton.style;
+ style.margin = "10px";
+ style.display = "inline";
+ style.width = "7em";
+
+ form.appendChild(okButton);
+ form.appendChild(cancelButton);
+
+ util.addEvent(doc.body, "keydown", checkEscape);
+ dialog.style.top = "50%";
+ dialog.style.left = "50%";
+ dialog.style.display = "block";
+ if (uaSniffed.isIE_5or6) {
+ dialog.style.position = "absolute";
+ dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
+ dialog.style.left = "50%";
+ }
+ doc.body.appendChild(dialog);
+
+ // This has to be done AFTER adding the dialog to the form if you
+ // want it to be centered.
+ dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
+ dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
+
+ };
+
+ // Why is this in a zero-length timeout?
+ // Is it working around a browser bug?
+ setTimeout(function () {
+
+ createDialog();
+
+ var defTextLen = defaultInputText.length;
+ if (input.selectionStart !== undefined) {
+ input.selectionStart = 0;
+ input.selectionEnd = defTextLen;
+ }
+ else if (input.createTextRange) {
+ var range = input.createTextRange();
+ range.collapse(false);
+ range.moveStart("character", -defTextLen);
+ range.moveEnd("character", defTextLen);
+ range.select();
+ }
+
+ input.focus();
+ }, 0);
+ };
+
+ function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions, getString) {
+
+ var inputBox = panels.input,
+ buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements.
+
+ makeSpritedButtonRow();
+
+ var keyEvent = "keydown";
+ if (uaSniffed.isOpera) {
+ keyEvent = "keypress";
+ }
+
+ util.addEvent(inputBox, keyEvent, function (key) {
+
+ // Check to see if we have a button key and, if so execute the callback.
+ if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) {
+
+ var keyCode = key.charCode || key.keyCode;
+ var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
+
+ switch (keyCodeStr) {
+ case "b":
+ doClick(buttons.bold);
+ break;
+ case "i":
+ doClick(buttons.italic);
+ break;
+ case "l":
+ doClick(buttons.link);
+ break;
+ case "q":
+ doClick(buttons.quote);
+ break;
+ case "k":
+ doClick(buttons.code);
+ break;
+ case "g":
+ doClick(buttons.image);
+ break;
+ case "o":
+ doClick(buttons.olist);
+ break;
+ case "u":
+ doClick(buttons.ulist);
+ break;
+ case "h":
+ doClick(buttons.heading);
+ break;
+ case "r":
+ doClick(buttons.hr);
+ break;
+ case "y":
+ doClick(buttons.redo);
+ break;
+ case "z":
+ if (key.shiftKey) {
+ doClick(buttons.redo);
+ }
+ else {
+ doClick(buttons.undo);
+ }
+ break;
+ default:
+ return;
+ }
+
+
+ if (key.preventDefault) {
+ key.preventDefault();
+ }
+
+ if (window.event) {
+ window.event.returnValue = false;
+ }
+ }
+ });
+
+ // Auto-indent on shift-enter
+ util.addEvent(inputBox, "keyup", function (key) {
+ if (key.shiftKey && !key.ctrlKey && !key.metaKey) {
+ var keyCode = key.charCode || key.keyCode;
+ // Character 13 is Enter
+ if (keyCode === 13) {
+ var fakeButton = {};
+ fakeButton.textOp = bindCommand("doAutoindent");
+ doClick(fakeButton);
+ }
+ }
+ });
+
+ // special handler because IE clears the context of the textbox on ESC
+ if (uaSniffed.isIE) {
+ util.addEvent(inputBox, "keydown", function (key) {
+ var code = key.keyCode;
+ if (code === 27) {
+ return false;
+ }
+ });
+ }
+
+
+ // Perform the button's action.
+ function doClick(button) {
+
+ inputBox.focus();
+
+ if (button.textOp) {
+
+ if (undoManager) {
+ undoManager.setCommandMode();
+ }
+
+ var state = new TextareaState(panels);
+
+ if (!state) {
+ return;
+ }
+
+ var chunks = state.getChunks();
+
+ // Some commands launch a "modal" prompt dialog. Javascript
+ // can't really make a modal dialog box and the WMD code
+ // will continue to execute while the dialog is displayed.
+ // This prevents the dialog pattern I'm used to and means
+ // I can't do something like this:
+ //
+ // var link = CreateLinkDialog();
+ // makeMarkdownLink(link);
+ //
+ // Instead of this straightforward method of handling a
+ // dialog I have to pass any code which would execute
+ // after the dialog is dismissed (e.g. link creation)
+ // in a function parameter.
+ //
+ // Yes this is awkward and I think it sucks, but there's
+ // no real workaround. Only the image and link code
+ // create dialogs and require the function pointers.
+ var fixupInputArea = function () {
+
+ inputBox.focus();
+
+ if (chunks) {
+ state.setChunks(chunks);
+ }
+
+ state.restore();
+ previewManager.refresh();
+ };
+
+ var noCleanup = button.textOp(chunks, fixupInputArea);
+
+ if (!noCleanup) {
+ fixupInputArea();
+ }
+
+ }
+
+ if (button.execute) {
+ button.execute(undoManager);
+ }
+ };
+
+ function setupButton(button, isEnabled) {
+
+ var normalYShift = "0px";
+ var disabledYShift = "-20px";
+ var highlightYShift = "-40px";
+ var image = button.getElementsByTagName("span")[0];
+ if (isEnabled) {
+ image.style.backgroundPosition = button.XShift + " " + normalYShift;
+ button.onmouseover = function () {
+ image.style.backgroundPosition = this.XShift + " " + highlightYShift;
+ };
+
+ button.onmouseout = function () {
+ image.style.backgroundPosition = this.XShift + " " + normalYShift;
+ };
+
+ // IE tries to select the background image "button" text (it's
+ // implemented in a list item) so we have to cache the selection
+ // on mousedown.
+ if (uaSniffed.isIE) {
+ button.onmousedown = function () {
+ if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection
+ return;
+ }
+ panels.ieCachedRange = document.selection.createRange();
+ panels.ieCachedScrollTop = panels.input.scrollTop;
+ };
+ }
+
+ if (!button.isHelp) {
+ button.onclick = function () {
+ if (this.onmouseout) {
+ this.onmouseout();
+ }
+ doClick(this);
+ return false;
+ }
+ }
+ }
+ else {
+ image.style.backgroundPosition = button.XShift + " " + disabledYShift;
+ button.onmouseover = button.onmouseout = button.onclick = function () { };
+ }
+ }
+
+ function bindCommand(method) {
+ if (typeof method === "string")
+ method = commandManager[method];
+ return function () { method.apply(commandManager, arguments); }
+ }
+
+ function makeSpritedButtonRow() {
+
+ var buttonBar = panels.buttonBar;
+
+ var normalYShift = "0px";
+ var disabledYShift = "-20px";
+ var highlightYShift = "-40px";
+
+ var buttonRow = document.createElement("ul");
+ buttonRow.id = "wmd-button-row" + postfix;
+ buttonRow.className = 'wmd-button-row';
+ buttonRow = buttonBar.appendChild(buttonRow);
+ var xPosition = 0;
+ var makeButton = function (id, title, XShift, textOp) {
+ var button = document.createElement("li");
+ button.className = "wmd-button";
+ button.style.left = xPosition + "px";
+ xPosition += 25;
+ var buttonImage = document.createElement("span");
+ button.id = id + postfix;
+ button.appendChild(buttonImage);
+ button.title = title;
+ button.XShift = XShift;
+ if (textOp)
+ button.textOp = textOp;
+ setupButton(button, true);
+ buttonRow.appendChild(button);
+ return button;
+ };
+ var makeSpacer = function (num) {
+ var spacer = document.createElement("li");
+ spacer.className = "wmd-spacer wmd-spacer" + num;
+ spacer.id = "wmd-spacer" + num + postfix;
+ buttonRow.appendChild(spacer);
+ xPosition += 25;
+ }
+
+ buttons.bold = makeButton("wmd-bold-button", getString("bold"), "0px", bindCommand("doBold"));
+ buttons.italic = makeButton("wmd-italic-button", getString("italic"), "-20px", bindCommand("doItalic"));
+ makeSpacer(1);
+ buttons.link = makeButton("wmd-link-button", getString("link"), "-40px", bindCommand(function (chunk, postProcessing) {
+ return this.doLinkOrImage(chunk, postProcessing, false);
+ }));
+ buttons.quote = makeButton("wmd-quote-button", getString("quote"), "-60px", bindCommand("doBlockquote"));
+ buttons.code = makeButton("wmd-code-button", getString("code"), "-80px", bindCommand("doCode"));
+ buttons.image = makeButton("wmd-image-button", getString("image"), "-100px", bindCommand(function (chunk, postProcessing) {
+ return this.doLinkOrImage(chunk, postProcessing, true);
+ }));
+ makeSpacer(2);
+ buttons.olist = makeButton("wmd-olist-button", getString("olist"), "-120px", bindCommand(function (chunk, postProcessing) {
+ this.doList(chunk, postProcessing, true);
+ }));
+ buttons.ulist = makeButton("wmd-ulist-button", getString("ulist"), "-140px", bindCommand(function (chunk, postProcessing) {
+ this.doList(chunk, postProcessing, false);
+ }));
+ buttons.heading = makeButton("wmd-heading-button", getString("heading"), "-160px", bindCommand("doHeading"));
+ buttons.hr = makeButton("wmd-hr-button", getString("hr"), "-180px", bindCommand("doHorizontalRule"));
+ makeSpacer(3);
+ buttons.undo = makeButton("wmd-undo-button", getString("undo"), "-200px", null);
+ buttons.undo.execute = function (manager) { if (manager) manager.undo(); };
+
+ var redoTitle = /win/.test(nav.platform.toLowerCase()) ?
+ getString("redo") :
+ getString("redomac"); // mac and other non-Windows platforms
+
+ buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null);
+ buttons.redo.execute = function (manager) { if (manager) manager.redo(); };
+
+ if (helpOptions) {
+ var helpButton = document.createElement("li");
+ var helpButtonImage = document.createElement("span");
+ helpButton.appendChild(helpButtonImage);
+ helpButton.className = "wmd-button wmd-help-button";
+ helpButton.id = "wmd-help-button" + postfix;
+ helpButton.XShift = "-240px";
+ helpButton.isHelp = true;
+ helpButton.style.right = "0px";
+ helpButton.title = getString("help");
+ helpButton.onclick = helpOptions.handler;
+
+ setupButton(helpButton, true);
+ buttonRow.appendChild(helpButton);
+ buttons.help = helpButton;
+ }
+
+ setUndoRedoButtonStates();
+ }
+
+ function setUndoRedoButtonStates() {
+ if (undoManager) {
+ setupButton(buttons.undo, undoManager.canUndo());
+ setupButton(buttons.redo, undoManager.canRedo());
+ }
+ };
+
+ this.setUndoRedoButtonStates = setUndoRedoButtonStates;
+
+ }
+
+ function CommandManager(pluginHooks, getString) {
+ this.hooks = pluginHooks;
+ this.getString = getString;
+ }
+
+ var commandProto = CommandManager.prototype;
+
+ // The markdown symbols - 4 spaces = code, > = blockquote, etc.
+ commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
+
+ // Remove markdown symbols from the chunk selection.
+ commandProto.unwrap = function (chunk) {
+ var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g");
+ chunk.selection = chunk.selection.replace(txt, "$1 $2");
+ };
+
+ commandProto.wrap = function (chunk, len) {
+ this.unwrap(chunk);
+ var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"),
+ that = this;
+
+ chunk.selection = chunk.selection.replace(regex, function (line, marked) {
+ if (new re("^" + that.prefixes, "").test(line)) {
+ return line;
+ }
+ return marked + "\n";
+ });
+
+ chunk.selection = chunk.selection.replace(/\s+$/, "");
+ };
+
+ commandProto.doBold = function (chunk, postProcessing) {
+ return this.doBorI(chunk, postProcessing, 2, this.getString("boldexample"));
+ };
+
+ commandProto.doItalic = function (chunk, postProcessing) {
+ return this.doBorI(chunk, postProcessing, 1, this.getString("italicexample"));
+ };
+
+ // chunk: The selected region that will be enclosed with */**
+ // nStars: 1 for italics, 2 for bold
+ // insertText: If you just click the button without highlighting text, this gets inserted
+ commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) {
+
+ // Get rid of whitespace and fixup newlines.
+ chunk.trimWhitespace();
+ chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
+
+ // Look for stars before and after. Is the chunk already marked up?
+ // note that these regex matches cannot fail
+ var starsBefore = /(\**$)/.exec(chunk.before)[0];
+ var starsAfter = /(^\**)/.exec(chunk.after)[0];
+
+ var prevStars = Math.min(starsBefore.length, starsAfter.length);
+
+ // Remove stars if we have to since the button acts as a toggle.
+ if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
+ chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
+ chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
+ }
+ else if (!chunk.selection && starsAfter) {
+ // It's not really clear why this code is necessary. It just moves
+ // some arbitrary stuff around.
+ chunk.after = chunk.after.replace(/^([*_]*)/, "");
+ chunk.before = chunk.before.replace(/(\s?)$/, "");
+ var whitespace = re.$1;
+ chunk.before = chunk.before + starsAfter + whitespace;
+ }
+ else {
+
+ // In most cases, if you don't have any selected text and click the button
+ // you'll get a selected, marked up region with the default text inserted.
+ if (!chunk.selection && !starsAfter) {
+ chunk.selection = insertText;
+ }
+
+ // Add the true markup.
+ var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
+ chunk.before = chunk.before + markup;
+ chunk.after = markup + chunk.after;
+ }
+
+ return;
+ };
+
+ commandProto.stripLinkDefs = function (text, defsToAdd) {
+
+ text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
+ function (totalMatch, id, link, newlines, title) {
+ defsToAdd[id] = totalMatch.replace(/\s*$/, "");
+ if (newlines) {
+ // Strip the title and return that separately.
+ defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
+ return newlines + title;
+ }
+ return "";
+ });
+
+ return text;
+ };
+
+ commandProto.addLinkDef = function (chunk, linkDef) {
+
+ var refNumber = 0; // The current reference number
+ var defsToAdd = {}; //
+ // Start with a clean slate by removing all previous link definitions.
+ chunk.before = this.stripLinkDefs(chunk.before, defsToAdd);
+ chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd);
+ chunk.after = this.stripLinkDefs(chunk.after, defsToAdd);
+
+ var defs = "";
+ var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
+
+ var addDefNumber = function (def) {
+ refNumber++;
+ def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
+ defs += "\n" + def;
+ };
+
+ // note that
+ // a) the recursive call to getLink cannot go infinite, because by definition
+ // of regex, inner is always a proper substring of wholeMatch, and
+ // b) more than one level of nesting is neither supported by the regex
+ // nor making a lot of sense (the only use case for nesting is a linked image)
+ var getLink = function (wholeMatch, before, inner, afterInner, id, end) {
+ inner = inner.replace(regex, getLink);
+ if (defsToAdd[id]) {
+ addDefNumber(defsToAdd[id]);
+ return before + inner + afterInner + refNumber + end;
+ }
+ return wholeMatch;
+ };
+
+ chunk.before = chunk.before.replace(regex, getLink);
+
+ if (linkDef) {
+ addDefNumber(linkDef);
+ }
+ else {
+ chunk.selection = chunk.selection.replace(regex, getLink);
+ }
+
+ var refOut = refNumber;
+
+ chunk.after = chunk.after.replace(regex, getLink);
+
+ if (chunk.after) {
+ chunk.after = chunk.after.replace(/\n*$/, "");
+ }
+ if (!chunk.after) {
+ chunk.selection = chunk.selection.replace(/\n*$/, "");
+ }
+
+ chunk.after += "\n\n" + defs;
+
+ return refOut;
+ };
+
+ // takes the line as entered into the add link/as image dialog and makes
+ // sure the URL and the optinal title are "nice".
+ function properlyEncoded(linkdef) {
+ return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) {
+ link = link.replace(/\?.*$/, function (querypart) {
+ return querypart.replace(/\+/g, " "); // in the query string, a plus and a space are identical
+ });
+ link = decodeURIComponent(link); // unencode first, to prevent double encoding
+ link = encodeURI(link).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
+ link = link.replace(/\?.*$/, function (querypart) {
+ return querypart.replace(/\+/g, "%2b"); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded
+ });
+ if (title) {
+ title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, "");
+ title = title.replace(/"/g, "quot;").replace(/\(/g, "(").replace(/\)/g, ")").replace(//g, ">");
+ }
+ return title ? link + ' "' + title + '"' : link;
+ });
+ }
+
+ commandProto.doLinkOrImage = function (chunk, postProcessing, isImage) {
+
+ chunk.trimWhitespace();
+ chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
+ var background;
+
+ if (chunk.endTag.length > 1 && chunk.startTag.length > 0) {
+
+ chunk.startTag = chunk.startTag.replace(/!?\[/, "");
+ chunk.endTag = "";
+ this.addLinkDef(chunk, null);
+
+ }
+ else {
+
+ // We're moving start and end tag back into the selection, since (as we're in the else block) we're not
+ // *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the
+ // link text. linkEnteredCallback takes care of escaping any brackets.
+ chunk.selection = chunk.startTag + chunk.selection + chunk.endTag;
+ chunk.startTag = chunk.endTag = "";
+
+ if (/\n\n/.test(chunk.selection)) {
+ this.addLinkDef(chunk, null);
+ return;
+ }
+ var that = this;
+ // The function to be executed when you enter a link and press OK or Cancel.
+ // Marks up the link and adds the ref.
+ var linkEnteredCallback = function (link) {
+
+ background.parentNode.removeChild(background);
+
+ if (link !== null) {
+ // ( $1
+ // [^\\] anything that's not a backslash
+ // (?:\\\\)* an even number (this includes zero) of backslashes
+ // )
+ // (?= followed by
+ // [[\]] an opening or closing bracket
+ // )
+ //
+ // In other words, a non-escaped bracket. These have to be escaped now to make sure they
+ // don't count as the end of the link or similar.
+ // Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets),
+ // the bracket in one match may be the "not a backslash" character in the next match, so it
+ // should not be consumed by the first match.
+ // The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the
+ // start of the string, so this also works if the selection begins with a bracket. We cannot solve
+ // this by anchoring with ^, because in the case that the selection starts with two brackets, this
+ // would mean a zero-width match at the start. Since zero-width matches advance the string position,
+ // the first bracket could then not act as the "not a backslash" for the second.
+ chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1);
+
+ var linkDef = " [999]: " + properlyEncoded(link);
+
+ var num = that.addLinkDef(chunk, linkDef);
+ chunk.startTag = isImage ? "![" : "[";
+ chunk.endTag = "][" + num + "]";
+
+ if (!chunk.selection) {
+ if (isImage) {
+ chunk.selection = that.getString("imagedescription");
+ }
+ else {
+ chunk.selection = that.getString("linkdescription");
+ }
+ }
+ }
+ postProcessing();
+ };
+
+ background = ui.createBackground();
+
+ if (isImage) {
+ if (!this.hooks.insertImageDialog(linkEnteredCallback))
+ ui.prompt(this.getString("imagedialog"), imageDefaultText, linkEnteredCallback);
+ }
+ else {
+ ui.prompt(this.getString("linkdialog"), linkDefaultText, linkEnteredCallback);
+ }
+ return true;
+ }
+ };
+
+ // When making a list, hitting shift-enter will put your cursor on the next line
+ // at the current indent level.
+ commandProto.doAutoindent = function (chunk, postProcessing) {
+
+ var commandMgr = this,
+ fakeSelection = false;
+
+ chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
+ chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
+ chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
+
+ // There's no selection, end the cursor wasn't at the end of the line:
+ // The user wants to split the current list item / code line / blockquote line
+ // (for the latter it doesn't really matter) in two. Temporarily select the
+ // (rest of the) line to achieve this.
+ if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) {
+ chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) {
+ chunk.selection = wholeMatch;
+ return "";
+ });
+ fakeSelection = true;
+ }
+
+ if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) {
+ if (commandMgr.doList) {
+ commandMgr.doList(chunk);
+ }
+ }
+ if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) {
+ if (commandMgr.doBlockquote) {
+ commandMgr.doBlockquote(chunk);
+ }
+ }
+ if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
+ if (commandMgr.doCode) {
+ commandMgr.doCode(chunk);
+ }
+ }
+
+ if (fakeSelection) {
+ chunk.after = chunk.selection + chunk.after;
+ chunk.selection = "";
+ }
+ };
+
+ commandProto.doBlockquote = function (chunk, postProcessing) {
+
+ chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
+ function (totalMatch, newlinesBefore, text, newlinesAfter) {
+ chunk.before += newlinesBefore;
+ chunk.after = newlinesAfter + chunk.after;
+ return text;
+ });
+
+ chunk.before = chunk.before.replace(/(>[ \t]*)$/,
+ function (totalMatch, blankLine) {
+ chunk.selection = blankLine + chunk.selection;
+ return "";
+ });
+
+ chunk.selection = chunk.selection.replace(/^(\s|>)+$/, "");
+ chunk.selection = chunk.selection || this.getString("quoteexample");
+
+ // The original code uses a regular expression to find out how much of the
+ // text *directly before* the selection already was a blockquote:
+
+ /*
+ if (chunk.before) {
+ chunk.before = chunk.before.replace(/\n?$/, "\n");
+ }
+ chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
+ function (totalMatch) {
+ chunk.startTag = totalMatch;
+ return "";
+ });
+ */
+
+ // This comes down to:
+ // Go backwards as many lines a possible, such that each line
+ // a) starts with ">", or
+ // b) is almost empty, except for whitespace, or
+ // c) is preceeded by an unbroken chain of non-empty lines
+ // leading up to a line that starts with ">" and at least one more character
+ // and in addition
+ // d) at least one line fulfills a)
+ //
+ // Since this is essentially a backwards-moving regex, it's susceptible to
+ // catstrophic backtracking and can cause the browser to hang;
+ // see e.g. http://meta.stackoverflow.com/questions/9807.
+ //
+ // Hence we replaced this by a simple state machine that just goes through the
+ // lines and checks for a), b), and c).
+
+ var match = "",
+ leftOver = "",
+ line;
+ if (chunk.before) {
+ var lines = chunk.before.replace(/\n$/, "").split("\n");
+ var inChain = false;
+ for (var i = 0; i < lines.length; i++) {
+ var good = false;
+ line = lines[i];
+ inChain = inChain && line.length > 0; // c) any non-empty line continues the chain
+ if (/^>/.test(line)) { // a)
+ good = true;
+ if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain
+ inChain = true;
+ } else if (/^[ \t]*$/.test(line)) { // b)
+ good = true;
+ } else {
+ good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain
+ }
+ if (good) {
+ match += line + "\n";
+ } else {
+ leftOver += match + line;
+ match = "\n";
+ }
+ }
+ if (!/(^|\n)>/.test(match)) { // d)
+ leftOver += match;
+ match = "";
+ }
+ }
+
+ chunk.startTag = match;
+ chunk.before = leftOver;
+
+ // end of change
+
+ if (chunk.after) {
+ chunk.after = chunk.after.replace(/^\n?/, "\n");
+ }
+
+ chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
+ function (totalMatch) {
+ chunk.endTag = totalMatch;
+ return "";
+ }
+ );
+
+ var replaceBlanksInTags = function (useBracket) {
+
+ var replacement = useBracket ? "> " : "";
+
+ if (chunk.startTag) {
+ chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
+ function (totalMatch, markdown) {
+ return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
+ });
+ }
+ if (chunk.endTag) {
+ chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
+ function (totalMatch, markdown) {
+ return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
+ });
+ }
+ };
+
+ if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) {
+ this.wrap(chunk, SETTINGS.lineLength - 2);
+ chunk.selection = chunk.selection.replace(/^/gm, "> ");
+ replaceBlanksInTags(true);
+ chunk.skipLines();
+ } else {
+ chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
+ this.unwrap(chunk);
+ replaceBlanksInTags(false);
+
+ if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) {
+ chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
+ }
+
+ if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) {
+ chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n");
+ }
+ }
+
+ chunk.selection = this.hooks.postBlockquoteCreation(chunk.selection);
+
+ if (!/\n/.test(chunk.selection)) {
+ chunk.selection = chunk.selection.replace(/^(> *)/,
+ function (wholeMatch, blanks) {
+ chunk.startTag += blanks;
+ return "";
+ });
+ }
+ };
+
+ commandProto.doCode = function (chunk, postProcessing) {
+
+ var hasTextBefore = /\S[ ]*$/.test(chunk.before);
+ var hasTextAfter = /^[ ]*\S/.test(chunk.after);
+
+ // Use 'four space' markdown if the selection is on its own
+ // line or is multiline.
+ if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) {
+
+ chunk.before = chunk.before.replace(/[ ]{4}$/,
+ function (totalMatch) {
+ chunk.selection = totalMatch + chunk.selection;
+ return "";
+ });
+
+ var nLinesBack = 1;
+ var nLinesForward = 1;
+
+ if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
+ nLinesBack = 0;
+ }
+ if (/^\n(\t|[ ]{4,})/.test(chunk.after)) {
+ nLinesForward = 0;
+ }
+
+ chunk.skipLines(nLinesBack, nLinesForward);
+
+ if (!chunk.selection) {
+ chunk.startTag = " ";
+ chunk.selection = this.getString("codeexample");
+ }
+ else {
+ if (/^[ ]{0,3}\S/m.test(chunk.selection)) {
+ if (/\n/.test(chunk.selection))
+ chunk.selection = chunk.selection.replace(/^/gm, " ");
+ else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior
+ chunk.before += " ";
+ }
+ else {
+ chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
+ }
+ }
+ }
+ else {
+ // Use backticks (`) to delimit the code block.
+
+ chunk.trimWhitespace();
+ chunk.findTags(/`/, /`/);
+
+ if (!chunk.startTag && !chunk.endTag) {
+ chunk.startTag = chunk.endTag = "`";
+ if (!chunk.selection) {
+ chunk.selection = this.getString("codeexample");
+ }
+ }
+ else if (chunk.endTag && !chunk.startTag) {
+ chunk.before += chunk.endTag;
+ chunk.endTag = "";
+ }
+ else {
+ chunk.startTag = chunk.endTag = "";
+ }
+ }
+ };
+
+ commandProto.doList = function (chunk, postProcessing, isNumberedList) {
+
+ // These are identical except at the very beginning and end.
+ // Should probably use the regex extension function to make this clearer.
+ var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
+ var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
+
+ // The default bullet is a dash but others are possible.
+ // This has nothing to do with the particular HTML bullet,
+ // it's just a markdown bullet.
+ var bullet = "-";
+
+ // The number in a numbered list.
+ var num = 1;
+
+ // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
+ var getItemPrefix = function () {
+ var prefix;
+ if (isNumberedList) {
+ prefix = " " + num + ". ";
+ num++;
+ }
+ else {
+ prefix = " " + bullet + " ";
+ }
+ return prefix;
+ };
+
+ // Fixes the prefixes of the other list items.
+ var getPrefixedItem = function (itemText) {
+
+ // The numbering flag is unset when called by autoindent.
+ if (isNumberedList === undefined) {
+ isNumberedList = /^\s*\d/.test(itemText);
+ }
+
+ // Renumber/bullet the list element.
+ itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
+ function (_) {
+ return getItemPrefix();
+ });
+
+ return itemText;
+ };
+
+ chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
+
+ if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) {
+ chunk.before += chunk.startTag;
+ chunk.startTag = "";
+ }
+
+ if (chunk.startTag) {
+
+ var hasDigits = /\d+[.]/.test(chunk.startTag);
+ chunk.startTag = "";
+ chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
+ this.unwrap(chunk);
+ chunk.skipLines();
+
+ if (hasDigits) {
+ // Have to renumber the bullet points if this is a numbered list.
+ chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
+ }
+ if (isNumberedList == hasDigits) {
+ return;
+ }
+ }
+
+ var nLinesUp = 1;
+
+ chunk.before = chunk.before.replace(previousItemsRegex,
+ function (itemText) {
+ if (/^\s*([*+-])/.test(itemText)) {
+ bullet = re.$1;
+ }
+ nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
+ return getPrefixedItem(itemText);
+ });
+
+ if (!chunk.selection) {
+ chunk.selection = this.getString("litem");
+ }
+
+ var prefix = getItemPrefix();
+
+ var nLinesDown = 1;
+
+ chunk.after = chunk.after.replace(nextItemsRegex,
+ function (itemText) {
+ nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
+ return getPrefixedItem(itemText);
+ });
+
+ chunk.trimWhitespace(true);
+ chunk.skipLines(nLinesUp, nLinesDown, true);
+ chunk.startTag = prefix;
+ var spaces = prefix.replace(/./g, " ");
+ this.wrap(chunk, SETTINGS.lineLength - spaces.length);
+ chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
+
+ };
+
+ commandProto.doHeading = function (chunk, postProcessing) {
+
+ // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
+ chunk.selection = chunk.selection.replace(/\s+/g, " ");
+ chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
+
+ // If we clicked the button with no selected text, we just
+ // make a level 2 hash header around some default text.
+ if (!chunk.selection) {
+ chunk.startTag = "## ";
+ chunk.selection = this.getString("headingexample");
+ chunk.endTag = " ##";
+ return;
+ }
+
+ var headerLevel = 0; // The existing header level of the selected text.
+
+ // Remove any existing hash heading markdown and save the header level.
+ chunk.findTags(/#+[ ]*/, /[ ]*#+/);
+ if (/#+/.test(chunk.startTag)) {
+ headerLevel = re.lastMatch.length;
+ }
+ chunk.startTag = chunk.endTag = "";
+
+ // Try to get the current header level by looking for - and = in the line
+ // below the selection.
+ chunk.findTags(null, /\s?(-+|=+)/);
+ if (/=+/.test(chunk.endTag)) {
+ headerLevel = 1;
+ }
+ if (/-+/.test(chunk.endTag)) {
+ headerLevel = 2;
+ }
+
+ // Skip to the next line so we can create the header markdown.
+ chunk.startTag = chunk.endTag = "";
+ chunk.skipLines(1, 1);
+
+ // We make a level 2 header if there is no current header.
+ // If there is a header level, we substract one from the header level.
+ // If it's already a level 1 header, it's removed.
+ var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
+
+ if (headerLevelToCreate > 0) {
+
+ // The button only creates level 1 and 2 underline headers.
+ // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
+ var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
+ var len = chunk.selection.length;
+ if (len > SETTINGS.lineLength) {
+ len = SETTINGS.lineLength;
+ }
+ chunk.endTag = "\n";
+ while (len--) {
+ chunk.endTag += headerChar;
+ }
+ }
+ };
+
+ commandProto.doHorizontalRule = function (chunk, postProcessing) {
+ chunk.startTag = "----------\n";
+ chunk.selection = "";
+ chunk.skipLines(2, 1, true);
+ }
+
+
+})();
diff --git a/widgy/contrib/page_builder/static/widgy/js/components/markdown/lib/Markdown.Sanitizer.js b/widgy/contrib/page_builder/static/widgy/js/components/markdown/lib/Markdown.Sanitizer.js
new file mode 100644
index 000000000..cc5826fa8
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/js/components/markdown/lib/Markdown.Sanitizer.js
@@ -0,0 +1,108 @@
+(function () {
+ var output, Converter;
+ if (typeof exports === "object" && typeof require === "function") { // we're in a CommonJS (e.g. Node.js) module
+ output = exports;
+ Converter = require("./Markdown.Converter").Converter;
+ } else {
+ output = window.Markdown;
+ Converter = output.Converter;
+ }
+
+ output.getSanitizingConverter = function () {
+ var converter = new Converter();
+ converter.hooks.chain("postConversion", sanitizeHtml);
+ converter.hooks.chain("postConversion", balanceTags);
+ return converter;
+ }
+
+ function sanitizeHtml(html) {
+ return html.replace(/<[^>]*>?/gi, sanitizeTag);
+ }
+
+ // (tags that can be opened/closed) | (tags that stand alone)
+ var basic_tag_whitelist = /^(<\/?(b|blockquote|code|del|dd|dl|dt|em|h1|h2|h3|i|kbd|li|ol|p|pre|s|sup|sub|strong|strike|ul)>|<(br|hr)\s?\/?>)$/i;
+ // |
+ var a_white = /^(]+")?\s?>|<\/a>)$/i;
+
+ // ]*")?(\stitle="[^"<>]*")?\s?\/?>)$/i;
+
+ function sanitizeTag(tag) {
+ if (tag.match(basic_tag_whitelist) || tag.match(a_white) || tag.match(img_white))
+ return tag;
+ else
+ return "";
+ }
+
+ ///
";
+ var match;
+ var tagpaired = [];
+ var tagremove = [];
+ var needsRemoval = false;
+
+ // loop through matched tags in forward order
+ for (var ctag = 0; ctag < tagcount; ctag++) {
+ tagname = tags[ctag].replace(/<\/?(\w+).*/, "$1");
+ // skip any already paired tags
+ // and skip tags in our ignore list; assume they're self-closed
+ if (tagpaired[ctag] || ignoredtags.search("<" + tagname + ">") > -1)
+ continue;
+
+ tag = tags[ctag];
+ match = -1;
+
+ if (!/^<\//.test(tag)) {
+ // this is an opening tag
+ // search forwards (next tags), look for closing tags
+ for (var ntag = ctag + 1; ntag < tagcount; ntag++) {
+ if (!tagpaired[ntag] && tags[ntag] == "" + tagname + ">") {
+ match = ntag;
+ break;
+ }
+ }
+ }
+
+ if (match == -1)
+ needsRemoval = tagremove[ctag] = true; // mark for removal
+ else
+ tagpaired[match] = true; // mark paired
+ }
+
+ if (!needsRemoval)
+ return html;
+
+ // delete all orphaned tags from the string
+
+ var ctag = 0;
+ html = html.replace(re, function (match) {
+ var res = tagremove[ctag] ? "" : match;
+ ctag++;
+ return res;
+ });
+ return html;
+ }
+})();
diff --git a/widgy/contrib/page_builder/static/widgy/js/components/markdown/lib/pagedown.css b/widgy/contrib/page_builder/static/widgy/js/components/markdown/lib/pagedown.css
new file mode 100644
index 000000000..62594fbc7
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/js/components/markdown/lib/pagedown.css
@@ -0,0 +1,114 @@
+.wmd-panel
+{
+ margin-left: 25%;
+ margin-right: 25%;
+ width: 50%;
+ min-width: 500px;
+}
+
+.wmd-button-bar
+{
+ width: 100%;
+ background-color: Silver;
+}
+
+.wmd-input
+{
+ height: 300px;
+ width: 100%;
+ background-color: Gainsboro;
+ border: 1px solid DarkGray;
+}
+
+.wmd-preview
+{
+ background-color: #c0e0ff;
+}
+
+.wmd-button-row
+{
+ position: relative;
+ margin-left: 5px;
+ margin-right: 5px;
+ margin-bottom: 5px;
+ margin-top: 10px;
+ padding: 0px;
+ height: 20px;
+}
+
+.wmd-spacer
+{
+ width: 1px;
+ height: 20px;
+ margin-left: 14px;
+
+ position: absolute;
+ background-color: Silver;
+ display: inline-block;
+ list-style: none;
+}
+
+.wmd-button {
+ width: 20px;
+ height: 20px;
+ padding-left: 2px;
+ padding-right: 3px;
+ position: absolute;
+ display: inline-block;
+ list-style: none;
+ cursor: pointer;
+}
+
+.wmd-button > span {
+ background-image: url(wmd-buttons.png);
+ background-repeat: no-repeat;
+ background-position: 0px 0px;
+ width: 20px;
+ height: 20px;
+ display: inline-block;
+}
+
+.wmd-spacer1
+{
+ left: 50px;
+}
+.wmd-spacer2
+{
+ left: 175px;
+}
+.wmd-spacer3
+{
+ left: 300px;
+}
+
+
+
+
+.wmd-prompt-background
+{
+ background-color: Black;
+}
+
+.wmd-prompt-dialog
+{
+ border: 1px solid #999999;
+ background-color: #F5F5F5;
+}
+
+.wmd-prompt-dialog > div {
+ font-size: 0.8em;
+ font-family: arial, helvetica, sans-serif;
+}
+
+
+.wmd-prompt-dialog > form > input[type="text"] {
+ border: 1px solid #999999;
+ color: black;
+}
+
+.wmd-prompt-dialog > form > input[type="button"]{
+ border: 1px solid #888888;
+ font-family: trebuchet MS, helvetica, sans-serif;
+ font-size: 0.8em;
+ font-weight: bold;
+}
diff --git a/widgy/contrib/page_builder/static/widgy/js/components/markdown/lib/wmd-buttons.png b/widgy/contrib/page_builder/static/widgy/js/components/markdown/lib/wmd-buttons.png
new file mode 100644
index 000000000..50b370903
Binary files /dev/null and b/widgy/contrib/page_builder/static/widgy/js/components/markdown/lib/wmd-buttons.png differ
diff --git a/widgy/contrib/page_builder/static/widgy/js/components/table/component.js b/widgy/contrib/page_builder/static/widgy/js/components/table/component.js
new file mode 100644
index 000000000..eb9c1634d
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/js/components/table/component.js
@@ -0,0 +1,37 @@
+define([ 'underscore', 'jquery', 'components/widget/component' ], function(_, $, widget) {
+
+ var TableView = widget.View.extend({
+ initialize: function() {
+ widget.View.prototype.initialize.apply(this, arguments);
+
+ _.bindAll(this,
+ 'block',
+ 'unblock',
+ 'refresh'
+ );
+ },
+
+ block: function() {
+ if ( ! this.overlay )
+ this.overlay = $('').appendTo(this.el);
+ },
+
+ unblock: function() {
+ if ( this.overlay ) {
+ this.overlay.remove();
+ delete this.overlay;
+ }
+ },
+
+ refresh: function(options) {
+ this.node.fetch(_.extend({
+ app: this.app,
+ success: this.unblock
+ }, options));
+ }
+ });
+
+ return _.extend({}, widget, {
+ View: TableView
+ });
+});
diff --git a/widgy/contrib/page_builder/static/widgy/js/components/tableheader/component.js b/widgy/contrib/page_builder/static/widgy/js/components/tableheader/component.js
new file mode 100644
index 000000000..d4b88c967
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/js/components/tableheader/component.js
@@ -0,0 +1,42 @@
+define([ 'underscore', 'lib/q', 'components/widget/component' ], function(_, Q, widget) {
+
+ var TableHeaderView = widget.View.extend({
+ initialize: function() {
+ widget.View.prototype.initialize.apply(this, arguments);
+
+ this
+ .listenTo(this.collection, 'destroy_child', this.parent.block)
+ .listenTo(this.collection, 'destroy', this.parent.refresh)
+ .listenTo(this.collection, 'receive_child', this.parent.block)
+ .listenTo(this.collection, 'sort', this.moveColumn);
+ },
+
+ moveColumn: function(collection, options) {
+ // Avoid recursion.
+ if ( options && options.moveColumn )
+ return;
+
+ this.parent.refresh({moveColumn: true, resort: true});
+ },
+
+ addChild: function() {
+ var parent = this,
+ table = this.parent,
+ promise = this.addChildPromise.apply(this, arguments);
+
+ if ( promise ) {
+ promise.then(function(node_view) {
+ return Q(table.refresh({sort_silently: true})).then(function() {
+ parent.resortChildren();
+ });
+ }).done();
+ }
+
+ return promise;
+ }
+ });
+
+ return _.extend({}, widget, {
+ View: TableHeaderView
+ });
+});
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/accordion.js b/widgy/contrib/page_builder/static/widgy/page_builder/accordion.js
new file mode 100644
index 000000000..02407b207
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/accordion.js
@@ -0,0 +1,17 @@
+/* adapted from
+ * http://zogovic.com/post/21784525226/simple-html5-details-polyfill
+ */
+jQuery(function($) {
+ var supported = 'open' in document.createElement('details');
+
+ if ( ! supported ) {
+ $(document.body).addClass('no-details');
+ $('summary').on('click', function(event) {
+ var $details = $(this).parents('details');
+ if ( $details.attr('open') || $details.hasClass('open') )
+ $details.removeAttr('open').removeClass('open');
+ else
+ $details.attr('open', true).addClass('open');
+ });
+ }
+});
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/accordion.scss b/widgy/contrib/page_builder/static/widgy/page_builder/accordion.scss
new file mode 100644
index 000000000..93fb34708
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/accordion.scss
@@ -0,0 +1,24 @@
+.no-details details {
+ > * {
+ position: absolute;
+ visibility: hidden;
+ }
+
+ > summary, &[open] > * {
+ position: static;
+ visibility: visible;
+ }
+
+
+ > summary {
+ display: block;
+ &:before {
+ content: "\25ba"; // BLACK RIGHT-POINTING TRIANGLE
+ padding-right: 5px;
+ }
+ }
+
+ &[open] > summary:before {
+ content:"\25bc"; // BLACK DOWN-POINTING TRIANGLE
+ }
+}
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/admin.scss b/widgy/contrib/page_builder/static/widgy/page_builder/admin.scss
new file mode 100644
index 000000000..a4376c3a7
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/admin.scss
@@ -0,0 +1,20 @@
+@import "/widgy/css/widgy_common.scss";
+
+li.node,
+li.shelfItem {
+ @include node-icon("page_builder.accordion", "../image/widget-accordion.png");
+ @include node-icon("page_builder.buttonwidget", "../image/widget-button.png");
+ @include node-icon("page_builder.calloutwidget", "../image/widget-callout.png");
+ @include node-icon("page_builder.figure", "../image/widget-figure.png");
+ @include node-icon("page_builder.googlemap", "../image/widget-google-map.png");
+ @include node-icon("page_builder.html", "../image/widget-html.png");
+ @include node-icon("page_builder.image", "../image/widget-image.gif");
+ @include node-icon("page_builder.markdown", "../image/widget-code.gif");
+ @include node-icon("page_builder.section", "../image/widget-section.png");
+ @include node-icon("page_builder.tableheaderdata", "../image/widget-tablecolumn.png");
+ @include node-icon("page_builder.table", "../image/widget-table.gif");
+ @include node-icon("page_builder.tablerow", "../image/widget-tablerow.png");
+ @include node-icon("page_builder.tabs", "../image/widget-tab.png");
+ @include node-icon("page_builder.video", "../image/widget-video.gif");
+ @include node-icon("page_builder.unsafehtml", "../image/widget-skull-and-crossbones.png");
+}
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/figure.scss b/widgy/contrib/page_builder/static/widgy/page_builder/figure.scss
new file mode 100644
index 000000000..01470c296
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/figure.scss
@@ -0,0 +1,22 @@
+figure {
+ display: block;
+
+ &.left {
+ display: inline;
+ float: left;
+ }
+ &.right {
+ display: inline;
+ float: right;
+ }
+ &.center {
+ margin: 0 auto;
+ float: none;
+ }
+ figcaption {
+ text-align: center;
+ .title {
+ display: block;
+ }
+ }
+}
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/googlemap.scss b/widgy/contrib/page_builder/static/widgy/page_builder/googlemap.scss
new file mode 100644
index 000000000..2def9cf81
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/googlemap.scss
@@ -0,0 +1,12 @@
+.googleMap {
+ iframe {
+ display: block;
+ width: 100%;
+ height: 400px;
+ }
+
+ a {
+ color: #0000ff;
+ font-size: 75%;
+ }
+}
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/html.admin.scss b/widgy/contrib/page_builder/static/widgy/page_builder/html.admin.scss
new file mode 100644
index 000000000..bade9547a
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/html.admin.scss
@@ -0,0 +1,38 @@
+.widgy .node.html {
+ .htmlOutput {
+ @include html;
+ display: block !important;
+ float: none !important;
+ width: auto !important;
+
+ code {
+ font-family: monospace;
+ }
+
+ ul {
+ list-style: disc;
+ padding: 0px 0px 0px 30px !important;
+
+ li {
+ list-style-type: disc;
+ }
+
+ ol, ol li {
+ list-style-type: decimal;
+ }
+ }
+
+ ol {
+ list-style: decimal;
+ padding: 0px 0px 0px 30px !important;
+
+ li {
+ list-style-type: decimal;
+ }
+
+ ul, ul li {
+ list-style-type: disc;
+ }
+ }
+ }
+}
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/html.scss b/widgy/contrib/page_builder/static/widgy/page_builder/html.scss
new file mode 100644
index 000000000..4a29abce1
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/html.scss
@@ -0,0 +1,11 @@
+.cke_editable, .htmlOutput {
+ @each $i in 'left' 'center' 'right' 'justify' {
+ .align-#{$i} {
+ text-align: $i;
+ }
+ }
+
+ @for $i from 1 through 5 {
+ .text-indent-#{$i} { text-indent: 10px * $i; }
+ }
+}
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/image.admin.scss b/widgy/contrib/page_builder/static/widgy/page_builder/image.admin.scss
new file mode 100644
index 000000000..473b972c5
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/image.admin.scss
@@ -0,0 +1,36 @@
+.widgy .node.image {
+ .widget_editor {
+ .formField {
+ position: relative;
+
+ label {
+ display: none;
+ }
+
+ a {
+ img {
+ float: left;
+ margin-right: 10px;
+ }
+ }
+
+ span {
+ float: left;
+
+ }
+
+ a.related-lookup {
+ position: absolute;
+ height: 10px;
+ left: 53px;
+ top: 25px;
+ }
+
+ input {
+ float: left;
+ margin-top: 6px;
+ width: 86%;
+ }
+ }
+ }
+}
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/table-theme.admin.scss b/widgy/contrib/page_builder/static/widgy/page_builder/table-theme.admin.scss
new file mode 100644
index 000000000..bfa2d2a14
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/table-theme.admin.scss
@@ -0,0 +1,226 @@
+
+// Theme
+.widgy .table {
+ .invisible > .widget > .nodeChildren {
+ > .node_drop_target {
+ margin-left: 60px;
+ margin-right: 0;
+ }
+ }
+ .node.tablerow,
+ .node.tableheader {
+ border: 0px;
+ padding: 0px 0px 0px 60px;
+ overflow: visible;
+
+ > .widget > .nodeChildren {
+ border: 0px;
+
+ > .tabledata,
+ > .node.tableheaderdata {
+ @include rounded(0px);
+
+ > div.widget {
+ min-height: 20px;
+
+ > p.drag-row {
+ display: none;
+ }
+ }
+ }
+
+ // Regular editors within table cells
+ li {
+ div.widget {
+ p.drag-row {
+ span.dragHandle {
+ font-size: 13px;
+ left: 2px;
+ position: absolute;
+ top: 3px;
+ }
+
+ span.title {
+ display: none;
+ }
+
+ button {
+ font-size: 9px;
+ line-height: 9px;
+ height: 15px;
+ margin: 2px 3px 0px 0px;
+ padding: 0px;
+ width: 15px;
+
+ i {
+ width: 1em;
+ }
+
+ &.edit {
+ right: 22px;
+ }
+
+ span {
+ display: none;
+ }
+ }
+ }
+
+ textarea {
+ height: 40px;
+ }
+ }
+ }
+ }
+ }
+
+ .node.tablerow {
+ margin: 0px;
+
+ > div.widget {
+ > p.drag-row {
+ height: 0px;
+ min-height: 0px;
+ padding: 0px;
+
+ span.dragHandle {
+ font-size: 14px;
+ left: -20px;
+ position: absolute;
+ top: 3px;
+ }
+
+ button.delete {
+ font-size: 9px;
+ line-height: 9px;
+ height: 15px;
+ padding: 0px;
+ position: absolute;
+ top: 3px;
+ left: -40px;
+ width: 15px;
+ z-index: 10;
+
+ i {
+ width: 1em;
+ }
+
+ span {
+ display: none;
+ }
+ }
+
+ button.edit {
+ font-size: 9px;
+ line-height: 9px;
+ height: 15px;
+ padding: 0px;
+ position: absolute;
+ top: 3px;
+ left: -60px;
+ width: 15px;
+ z-index: 10;
+
+ i {
+ width: 1em;
+ }
+
+ span {
+ display: none;
+ }
+ }
+ }
+
+ }
+ }
+
+ .node.tableheader {
+ margin: 0 1em;
+
+ > div.widget {
+ > p.drag-row {
+ background: white;
+ padding: 0px;
+ position: relative;
+
+ span.dragHandle {
+ font-size: 15px;
+ left: 0px;
+ top: 2px;
+ }
+
+ span.title {
+ display: block;
+ font-size: 13px;
+ line-height: 22px;
+ padding: 0px;
+ }
+
+ button.delete {
+ font-size: 9px;
+ line-height: 1em;
+ padding: 1px;
+ position: absolute;
+ top: 4px;
+ right: 4px;
+ width: 15px;
+ z-index: 10;
+
+ i {
+ width: 1em;
+ }
+ }
+ }
+
+ .nodeChildren {
+ .tableheaderdata {
+ @include rounded(0px);
+ min-width: $table-cell-min-width;
+
+ > div.widget {
+ > p.drag-row {
+ background: white;
+ padding: 0px;
+ position: relative;
+
+ span.dragHandle {
+ font-size: 15px;
+ left: 0px;
+ top: 2px;
+ }
+
+ span.title {
+ color: $grey;
+ display: block;
+ font-size: 11px;
+ line-height: 22px;
+ padding: 0px;
+ }
+
+ button.delete {
+ font-size: 9px;
+ line-height: 9px;
+ padding: 0px;
+ position: absolute;
+ top: 3px;
+ right: 3px;
+ height: 15px;
+ width: 15px;
+ z-index: 10;
+
+ i {
+ width: 1em;
+ }
+ }
+ }
+
+ // regular editors within table header cells
+ ul.nodeChildren {
+ width: auto !important;
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/table.admin.scss b/widgy/contrib/page_builder/static/widgy/page_builder/table.admin.scss
new file mode 100644
index 000000000..e40f0b3e0
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/table.admin.scss
@@ -0,0 +1,30 @@
+@import "/widgy/css/widgy_common.scss";
+
+$table-cell-min-width: 120px;
+
+// Layout
+.widgy {
+ .table {
+ overflow: visible;
+
+ > .widget > .nodeChildren {
+ overflow-x: auto;
+ overflow-y: hidden;
+ }
+ }
+
+ .node.tableheader, .node.tablerow {
+ @extend %horizontalChildren;
+ }
+
+ .tableheaderdata, .tabledata {
+ min-width: $table-cell-min-width;
+
+ .nodeChildren {
+ width: auto !important;
+ }
+ }
+}
+
+@import "table-theme.admin.scss";
+
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/tabs.js b/widgy/contrib/page_builder/static/widgy/page_builder/tabs.js
new file mode 100644
index 000000000..2cd2ba0f8
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/tabs.js
@@ -0,0 +1,23 @@
+jQuery(function($) {
+ $('.tabify .tabs a').bind('click', function() {
+ var href = $(this).attr('href'),
+ tabify = $(this).closest('.tabify'),
+ tabContent = tabify.find(href).first();
+ tabify.children('.tabs').find('a').removeClass('active'); // clear the active tabs
+ tabify.children('.tabs').find('a[href=' + href + ']').addClass('active'); // activate the clicked tab
+ tabify.children('.tabContent').removeClass('active'); // clear the active content
+ tabContent.addClass('active'); // show the clicked content
+ // Change the hash without scrolling
+ tabContent.attr('id', '');
+ window.location.hash = href;
+ tabContent.attr('id', href.substr(1)); // remove the sharp
+ return false;
+ });
+
+ //|
+ //| If there's a #tab in the URL, CLICK ON THAT TAB!!!
+ //|
+ if(window.location.hash) {
+ $('.tabs a[href="' + window.location.hash + '"]').click();
+ }
+});
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/tabs.scss b/widgy/contrib/page_builder/static/widgy/page_builder/tabs.scss
new file mode 100644
index 000000000..6808a9c65
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/tabs.scss
@@ -0,0 +1,10 @@
+.tabify {
+ .tabContent {
+ display: none;
+ padding: 10px 10px;
+
+ &.active {
+ display: block;
+ }
+ }
+}
diff --git a/widgy/contrib/page_builder/static/widgy/page_builder/video.scss b/widgy/contrib/page_builder/static/widgy/page_builder/video.scss
new file mode 100644
index 000000000..0cd289746
--- /dev/null
+++ b/widgy/contrib/page_builder/static/widgy/page_builder/video.scss
@@ -0,0 +1,4 @@
+iframe.video {
+ width: 560px;
+ height: 315px;
+}
diff --git a/widgy/contrib/page_builder/templates/page_builder/ckeditor_widget.html b/widgy/contrib/page_builder/templates/page_builder/ckeditor_widget.html
new file mode 100644
index 000000000..95cabae81
--- /dev/null
+++ b/widgy/contrib/page_builder/templates/page_builder/ckeditor_widget.html
@@ -0,0 +1,17 @@
+{% load argonauts %}
+
+{{ textarea }}
+
+
diff --git a/widgy/contrib/page_builder/templates/page_builder/datetime_widget.html b/widgy/contrib/page_builder/templates/page_builder/datetime_widget.html
new file mode 100644
index 000000000..00ebcd9ac
--- /dev/null
+++ b/widgy/contrib/page_builder/templates/page_builder/datetime_widget.html
@@ -0,0 +1,14 @@
+{{ widget }}
+
diff --git a/widgy/contrib/page_builder/templates/widgy/page_builder/accordion/render.html b/widgy/contrib/page_builder/templates/widgy/page_builder/accordion/render.html
new file mode 100644
index 000000000..33a0ffb8e
--- /dev/null
+++ b/widgy/contrib/page_builder/templates/widgy/page_builder/accordion/render.html
@@ -0,0 +1,9 @@
+{% load widgy_tags %}
+
+{{ widgy.owner }}
+
+ {% render self.get_children.0 %}
+
+{% endif %}
+{% endspaceless %}{% endblock %}
diff --git a/widgy/contrib/page_builder/templates/widgy/page_builder/googlemap/render.html b/widgy/contrib/page_builder/templates/widgy/page_builder/googlemap/render.html
new file mode 100644
index 000000000..a1102af9f
--- /dev/null
+++ b/widgy/contrib/page_builder/templates/widgy/page_builder/googlemap/render.html
@@ -0,0 +1,5 @@
+{% load i18n %}
+
diff --git a/widgy/contrib/page_builder/templates/widgy/page_builder/html/preview.html b/widgy/contrib/page_builder/templates/widgy/page_builder/html/preview.html
new file mode 100644
index 000000000..6812b79bb
--- /dev/null
+++ b/widgy/contrib/page_builder/templates/widgy/page_builder/html/preview.html
@@ -0,0 +1,6 @@
+{% extends "widgy/preview.html" %}
+{% block content %}
+
+ {% else %}
+
+ {% endif %}
+{% endblock %}
diff --git a/widgy/contrib/page_builder/templates/widgy/page_builder/image/render.html b/widgy/contrib/page_builder/templates/widgy/page_builder/image/render.html
new file mode 100644
index 000000000..c57c751e6
--- /dev/null
+++ b/widgy/contrib/page_builder/templates/widgy/page_builder/image/render.html
@@ -0,0 +1,5 @@
+{% load thumbnail_libs %}
+
+{% sorl_thumbnail self.image.file.name "500x500" upscale=False as im %}
+
+{% endthumbnail %}
diff --git a/widgy/contrib/page_builder/templates/widgy/page_builder/markdown/preview.html b/widgy/contrib/page_builder/templates/widgy/page_builder/markdown/preview.html
new file mode 100644
index 000000000..b40f2838e
--- /dev/null
+++ b/widgy/contrib/page_builder/templates/widgy/page_builder/markdown/preview.html
@@ -0,0 +1,7 @@
+{% extends "widgy/preview.html" %}
+{% load widgy_tags %}
+{% block content %}
+
{{ self.title }}
+
+ {% for child in self.get_children %}
+ {% render child %}
+ {% endfor %}
+
+
diff --git a/widgy/contrib/page_builder/templates/widgy/page_builder/tabs/render.html b/widgy/contrib/page_builder/templates/widgy/page_builder/tabs/render.html
new file mode 100644
index 000000000..05a660826
--- /dev/null
+++ b/widgy/contrib/page_builder/templates/widgy/page_builder/tabs/render.html
@@ -0,0 +1,18 @@
+{% load widgy_tags %}
+
+
+ {% for tab in self.get_children %}
+
+
+
+ {% with section_behavior='tabs' %}
+ {% for tab in self.get_children %}
+
+ {% if has_absolute_url %}
+
+{% endblock %}
diff --git a/widgy/contrib/page_builder/tests.py b/widgy/contrib/page_builder/tests.py
new file mode 100644
index 000000000..c2d2556f9
--- /dev/null
+++ b/widgy/contrib/page_builder/tests.py
@@ -0,0 +1,219 @@
+from django.test import TestCase
+from django.utils import unittest
+
+from widgy.site import WidgySite
+from widgy.models import Node
+from widgy.exceptions import ParentChildRejection
+
+from widgy.contrib.page_builder.models import (Table, TableRow,
+ TableHeaderData, TableHeader, TableBody)
+from widgy.contrib.page_builder.forms import CKEditorField
+
+
+widgy_site = WidgySite()
+
+
+def refetch(c):
+ return Node.objects.get(pk=c.node.pk).content
+
+
+class TestTableWidget(TestCase):
+ def setUp(self):
+ self.table = Table.add_root(widgy_site)
+
+ def test_add_column(self):
+ self.table.body.add_child(widgy_site, TableRow)
+ self.table.body.add_child(widgy_site, TableRow)
+ self.assertEqual(len(self.table.body.get_children()[0].get_children()), 0)
+ self.assertEqual(len(self.table.body.get_children()[1].get_children()), 0)
+
+ self.table.header.add_child(widgy_site, TableHeaderData)
+
+ self.assertEqual(len(self.table.body.get_children()[0].get_children()), 1)
+ self.assertEqual(len(self.table.body.get_children()[1].get_children()), 1)
+
+ def test_add_column_front(self):
+ row_1 = self.table.body.add_child(widgy_site, TableRow)
+ row_2 = self.table.body.add_child(widgy_site, TableRow)
+
+ th1 = self.table.header.add_child(widgy_site, TableHeaderData)
+
+ cell_1 = row_1.get_children()[0]
+ cell_2 = row_2.get_children()[0]
+
+ th2 = th1.add_sibling(widgy_site, TableHeaderData)
+
+ self.assertEqual(len(self.table.body.get_children()[0].get_children()), 2)
+ self.assertEqual(len(self.table.body.get_children()[1].get_children()), 2)
+ self.assertEqual(refetch(row_1).get_children()[1], cell_1)
+ self.assertEqual(refetch(row_2).get_children()[1], cell_2)
+
+ def test_three_columns(self):
+ row_1 = self.table.body.add_child(widgy_site, TableRow)
+
+ th1 = self.table.header.add_child(widgy_site, TableHeaderData)
+ th2 = th1.add_sibling(widgy_site, TableHeaderData)
+
+ cell_1 = row_1.get_children()[0]
+ cell_2 = row_1.get_children()[1]
+
+ th3 = th1.add_sibling(widgy_site, TableHeaderData)
+
+ self.assertEqual(len(self.table.body.get_children()[0].get_children()), 3)
+ self.assertEqual(refetch(row_1).get_children()[0], cell_1)
+ self.assertEqual(refetch(row_1).get_children()[2], cell_2)
+
+ def test_three_columns_front(self):
+ row_1 = self.table.body.add_child(widgy_site, TableRow)
+
+ th1 = self.table.header.add_child(widgy_site, TableHeaderData)
+ th2 = th1.add_sibling(widgy_site, TableHeaderData)
+
+ cell_1 = row_1.get_children()[0]
+ cell_2 = row_1.get_children()[1]
+
+ th3 = th2.add_sibling(widgy_site, TableHeaderData)
+
+ self.assertEqual(len(self.table.body.get_children()[0].get_children()), 3)
+ self.assertEqual(refetch(row_1).get_children()[1], cell_1)
+ self.assertEqual(refetch(row_1).get_children()[2], cell_2)
+
+ def test_add_row(self):
+ self.table.header.add_child(widgy_site, TableHeaderData)
+ self.table.header.add_child(widgy_site, TableHeaderData)
+ self.table.body.add_child(widgy_site, TableRow)
+ self.assertEqual(len(self.table.body.get_children()[0].get_children()), 2)
+
+ self.table.body.add_child(widgy_site, TableRow)
+
+ self.assertEqual(len(self.table.body.get_children()[1].get_children()), 2)
+
+ def test_reorder(self):
+ th1 = self.table.header.add_child(widgy_site, TableHeaderData)
+ th2 = self.table.header.add_child(widgy_site, TableHeaderData)
+ first_row = self.table.body.add_child(widgy_site, TableRow)
+ second_row = self.table.body.add_child(widgy_site, TableRow)
+
+ first_row_before = [i.pk for i in first_row.get_children()]
+ second_row_before = [i.pk for i in second_row.get_children()]
+
+ self.assertEqual(th1.get_next_sibling(), th2)
+
+ th2.reposition(widgy_site, right=th1, parent=None)
+
+ first_row, second_row = refetch(first_row), refetch(second_row)
+ self.assertEqual(first_row_before, list(reversed([i.pk for i in first_row.get_children()])))
+ self.assertEqual(second_row_before, list(reversed([i.pk for i in second_row.get_children()])))
+ self.assertEqual(refetch(th2).get_next_sibling(), th1)
+ self.assertEqual(refetch(th1).get_next_sibling(), None)
+
+ def test_reorder_right_null(self):
+ th1 = self.table.header.add_child(widgy_site, TableHeaderData)
+ th2 = self.table.header.add_child(widgy_site, TableHeaderData)
+ first_row = self.table.body.add_child(widgy_site, TableRow)
+ second_row = self.table.body.add_child(widgy_site, TableRow)
+
+ first_row_before = [i.pk for i in first_row.get_children()]
+ second_row_before = [i.pk for i in second_row.get_children()]
+
+ th1.reposition(widgy_site, right=None, parent=th1.get_parent())
+ first_row, second_row = refetch(first_row), refetch(second_row)
+
+ self.assertEqual(first_row_before, list(reversed([i.pk for i in first_row.get_children()])))
+ self.assertEqual(second_row_before, list(reversed([i.pk for i in second_row.get_children()])))
+ self.assertEqual(refetch(th1).get_next_sibling(), None)
+
+ def test_delete_column(self):
+ th1 = self.table.header.add_child(widgy_site, TableHeaderData)
+ th2 = self.table.header.add_child(widgy_site, TableHeaderData)
+ first_row = self.table.body.add_child(widgy_site, TableRow)
+ second_row = self.table.body.add_child(widgy_site, TableRow)
+
+ self.assertEqual(len(first_row.get_children()), 2)
+ self.assertEqual(len(second_row.get_children()), 2)
+
+ th1.delete()
+
+ first_row, second_row = refetch(first_row), refetch(second_row)
+ self.assertEqual(len(first_row.get_children()), 1)
+ self.assertEqual(len(second_row.get_children()), 1)
+
+ def test_compatibility(self):
+ def invalid(parent, child_class):
+ with self.assertRaises(ParentChildRejection):
+ parent.add_child(widgy_site, child_class)
+
+ # i don't know why these aren't raising
+ # invalid(self.table, TableHeader)
+ # invalid(self.table, TableBody)
+ invalid(self.table.header, TableRow)
+ invalid(self.table.body, TableHeaderData)
+
+ row = self.table.body.add_child(widgy_site, TableRow)
+ invalid(row, TableRow)
+ invalid(row, TableHeaderData)
+
+ def test_table_inside_of_table(self):
+ # this mainly exercises TableElement.table
+ self.table.header.add_child(widgy_site, TableHeaderData)
+ tr = self.table.body.add_child(widgy_site, TableRow)
+ td = tr.get_children()[0]
+ table2 = td.add_child(widgy_site, Table)
+ table2_tr = table2.body.add_child(widgy_site, TableRow)
+
+ # the outer table has 1 column, the inside should have 0
+ self.assertEqual(tr.get_children(), [td])
+ self.assertEqual(table2_tr.get_children(), [])
+
+ def test_move_rows(self):
+ table1 = self.table
+ table2 = Table.add_root(widgy_site)
+
+ table1.header.add_child(widgy_site, TableHeaderData)
+ table2.header.add_child(widgy_site, TableHeaderData)
+ row = table2.body.add_child(widgy_site, TableRow)
+
+ self.assertEqual(table2.body.get_children(), [row])
+ self.assertEqual(table1.body.get_children(), [])
+ # a row can be moved to another table with the same number of rows
+ row.reposition(widgy_site, parent=table1.body)
+ self.assertEqual(table1.body.get_children(), [row])
+ self.assertEqual(table2.body.get_children(), [])
+
+ # but not a table with a different number of rows
+ table2.header.add_child(widgy_site, TableHeaderData)
+ with self.assertRaises(ParentChildRejection):
+ row.reposition(widgy_site, parent=table2.body)
+
+
+class TestHtmlCleaning(TestCase):
+ def test_it(self):
+ """
+ Make sure some common XSS vectors are filtered
+ """
+
+ test_cases = [
+ ('-->', '">', '', '
+{% endfor %}
+{% endcompress %}
+{% endblock %}
+
+{% block seo_description %}{{ page.description }}{% endblock %}
+{% block seo_keywords %}{{ page.keywords_string }}{% endblock %}
+
+{% block breadcrumb %}
+ {% trans "Page History" %}
+
+ {% for commit in commits %}
+
+{{ commit.message|linebreaks }}
+ {% endif %}
+
Please try again later.").attr({
+ 'id' : 'fancybox-img',
+ 'src' : imgPreloader.src,
+ 'alt' : selectedOpts.title
+ }).appendTo( tmp );
+
+ _show();
+ },
+
+ _show = function() {
+ var pos, equal;
+
+ loading.hide();
+
+ if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
+ $.event.trigger('fancybox-cancel');
+
+ busy = false;
+ return;
+ }
+
+ busy = true;
+
+ $(content.add( overlay )).unbind();
+
+ $(window).unbind("resize.fb scroll.fb");
+ $(document).unbind('keydown.fb');
+
+ if (wrap.is(":visible") && currentOpts.titlePosition !== 'outside') {
+ wrap.css('height', wrap.height());
+ }
+
+ currentArray = selectedArray;
+ currentIndex = selectedIndex;
+ currentOpts = selectedOpts;
+
+ if (currentOpts.overlayShow) {
+ overlay.css({
+ 'background-color' : currentOpts.overlayColor,
+ 'opacity' : currentOpts.overlayOpacity,
+ 'cursor' : currentOpts.hideOnOverlayClick ? 'pointer' : 'auto',
+ 'height' : $(document).height()
+ });
+
+ if (!overlay.is(':visible')) {
+ if (isIE6) {
+ $('select:not(#fancybox-tmp select)').filter(function() {
+ return this.style.visibility !== 'hidden';
+ }).css({'visibility' : 'hidden'}).one('fancybox-cleanup', function() {
+ this.style.visibility = 'inherit';
+ });
+ }
+
+ overlay.show();
+ }
+ } else {
+ overlay.hide();
+ }
+
+ final_pos = _get_zoom_to();
+
+ _process_title();
+
+ if (wrap.is(":visible")) {
+ $( close.add( nav_left ).add( nav_right ) ).hide();
+
+ pos = wrap.position(),
+
+ start_pos = {
+ top : pos.top,
+ left : pos.left,
+ width : wrap.width(),
+ height : wrap.height()
+ };
+
+ equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height);
+
+ content.fadeTo(currentOpts.changeFade, 0.3, function() {
+ var finish_resizing = function() {
+ content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);
+ };
+
+ $.event.trigger('fancybox-change');
+
+ content
+ .empty()
+ .removeAttr('filter')
+ .css({
+ 'border-width' : currentOpts.padding,
+ 'width' : final_pos.width - currentOpts.padding * 2,
+ 'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
+ });
+
+ if (equal) {
+ finish_resizing();
+
+ } else {
+ fx.prop = 0;
+
+ $(fx).animate({prop: 1}, {
+ duration : currentOpts.changeSpeed,
+ easing : currentOpts.easingChange,
+ step : _draw,
+ complete : finish_resizing
+ });
+ }
+ });
+
+ return;
+ }
+
+ wrap.removeAttr("style");
+
+ content.css('border-width', currentOpts.padding);
+
+ if (currentOpts.transitionIn == 'elastic') {
+ start_pos = _get_zoom_from();
+
+ content.html( tmp.contents() );
+
+ wrap.show();
+
+ if (currentOpts.opacity) {
+ final_pos.opacity = 0;
+ }
+
+ fx.prop = 0;
+
+ $(fx).animate({prop: 1}, {
+ duration : currentOpts.speedIn,
+ easing : currentOpts.easingIn,
+ step : _draw,
+ complete : _finish
+ });
+
+ return;
+ }
+
+ if (currentOpts.titlePosition == 'inside' && titleHeight > 0) {
+ title.show();
+ }
+
+ content
+ .css({
+ 'width' : final_pos.width - currentOpts.padding * 2,
+ 'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
+ })
+ .html( tmp.contents() );
+
+ wrap
+ .css(final_pos)
+ .fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish );
+ },
+
+ _format_title = function(title) {
+ if (title && title.length) {
+ if (currentOpts.titlePosition == 'float') {
+ return '
';
+ }
+
+ return '' + title + ' ',setup:function(){this.getElement().$.src=
+a.logotype;this.getElement().getParent().setStyles({"text-align":"left"})}}]},{type:"select",id:"list_of_suggestions",labelStyle:"font: 12px/25px arial, sans-serif;",size:"6",inputStyle:"width: 140px; height: auto;",items:[["loading..."]],onShow:function(){p=this},onHide:function(){this.clear()},onChange:function(){a.textNode.SpellTab.setValue(this.getValue())}}]}]}]},{type:"hbox",id:"rightCol",align:"right",width:"50%",children:[{type:"vbox",id:"rightCol_col__left",widths:["50%","50%","50%","50%"],
+children:[{type:"button",id:"ChangeTo",label:a.LocalizationButton.ChangeTo.text,title:"Change to",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id);a.LocalizationButton.ChangeTo.instance=this},onClick:c},{type:"button",id:"ChangeAll",label:a.LocalizationButton.ChangeAll.text,title:"Change All",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id);a.LocalizationButton.ChangeAll.instance=this},onClick:c},{type:"button",id:"AddWord",
+label:a.LocalizationButton.AddWord.text,title:"Add word",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id);a.LocalizationButton.AddWord.instance=this},onClick:c},{type:"button",id:"FinishChecking",label:a.LocalizationButton.FinishChecking.text,title:"Finish Checking",style:"width: 100%;margin-top: 9px;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id);a.LocalizationButton.FinishChecking.instance=this},onClick:c}]},{type:"vbox",id:"rightCol_col__right",
+widths:["50%","50%","50%"],children:[{type:"button",id:"IgnoreWord",label:a.LocalizationButton.IgnoreWord.text,title:"Ignore word",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id);a.LocalizationButton.IgnoreWord.instance=this},onClick:c},{type:"button",id:"IgnoreAllWords",label:a.LocalizationButton.IgnoreAllWords.text,title:"Ignore all words",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id);a.LocalizationButton.IgnoreAllWords.instance=
+this},onClick:c},{type:"button",id:"option",label:a.LocalizationButton.Options.text,title:"Option",style:"width: 100%;",onLoad:function(){a.LocalizationButton.Options.instance=this;"file:"==document.location.protocol&&this.disable()},onClick:function(){"file:"==document.location.protocol?alert("WSC: Options functionality is disabled when runing from file system"):b.openDialog("options")}}]}]}]},{type:"hbox",id:"BlockFinishChecking",style:"width:560px; margin: 0 auto;",widths:["70%","30%"],onShow:function(){this.getElement().hide()},
+onHide:l,children:[{type:"hbox",id:"leftCol",align:"left",width:"70%",children:[{type:"vbox",id:"rightCol1",setup:function(){this.getChild()[0].getElement().$.src=a.logotype;this.getChild()[0].getElement().getParent().setStyles({"text-align":"center"})},children:[{type:"html",id:"logo",html:'
'}]}]},{type:"hbox",id:"rightCol",align:"right",width:"30%",children:[{type:"vbox",
+id:"rightCol_col__left",children:[{type:"button",id:"Option_button",label:a.LocalizationButton.Options.text,title:"Option",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id);"file:"==document.location.protocol&&this.disable()},onClick:function(){"file:"==document.location.protocol?alert("WSC: Options functionality is disabled when runing from file system"):b.openDialog("options")}},{type:"button",id:"FinishChecking",label:a.LocalizationButton.FinishChecking.text,
+title:"Finish Checking",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onClick:c}]}]}]}]},{id:"GrammTab",label:"Grammar",accessKey:"G",elements:[{type:"html",id:"banner",label:"banner",style:"",html:""},{type:"html",id:"Content",label:"GrammarContent",html:"",setup:function(){var b=a.iframeNumber+"_"+a.dialog._.currentTabId,c=document.getElementById(b);a.targetFromFrame[b]=c.contentWindow}},{type:"vbox",id:"bottomGroup",style:"width:560px; margin: 0 auto;",
+children:[{type:"hbox",id:"leftCol",widths:["66%","34%"],children:[{type:"vbox",children:[{type:"text",id:"text",label:"Change to:",labelLayout:"horizontal",labelStyle:"font: 12px/25px arial, sans-serif;",inputStyle:"float: right; width: 200px;","default":"",onShow:function(){a.textNode.GrammTab=this},onHide:function(){this.reset()}},{type:"html",id:"html_text",html:"",
+onShow:function(){a.textNodeInfo.GrammTab=this}},{type:"html",id:"radio",html:"",onShow:function(){a.grammerSuggest=this}}]},{type:"vbox",children:[{type:"button",id:"ChangeTo",label:"Change to",title:"Change to",style:"width: 133px; float: right;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onClick:c},{type:"button",id:"IgnoreWord",label:"Ignore word",title:"Ignore word",style:"width: 133px; float: right;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},
+onClick:c},{type:"button",id:"IgnoreAllWords",label:"Ignore Problem",title:"Ignore Problem",style:"width: 133px; float: right;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onClick:c},{type:"button",id:"FinishChecking",label:"Finish Checking",title:"Finish Checking",style:"width: 133px; float: right; margin-top: 9px;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onClick:c}]}]}]},{type:"hbox",id:"BlockFinishChecking",style:"width:560px; margin: 0 auto;",
+widths:["70%","30%"],onShow:function(){this.getElement().hide()},onHide:l,children:[{type:"hbox",id:"leftCol",align:"left",width:"70%",children:[{type:"vbox",id:"rightCol1",children:[{type:"html",id:"logo",html:'
',setup:function(){this.getElement().$.src=a.logotype;this.getElement().getParent().setStyles({"text-align":"center"})}}]}]},{type:"hbox",id:"rightCol",align:"right",
+width:"30%",children:[{type:"vbox",id:"rightCol_col__left",children:[{type:"button",id:"FinishChecking",label:"Finish Checking",title:"Finish Checking",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onClick:c}]}]}]}]},{id:"Thesaurus",label:"Thesaurus",accessKey:"T",elements:[{type:"html",id:"banner",label:"banner",style:"",html:""},{type:"html",id:"Content",label:"spellContent",html:"",setup:function(){var b=a.iframeNumber+"_"+a.dialog._.currentTabId,
+c=document.getElementById(b);a.targetFromFrame[b]=c.contentWindow}},{type:"vbox",id:"bottomGroup",style:"width:560px; margin: -10px auto; overflow: hidden;",children:[{type:"hbox",widths:["75%","25%"],children:[{type:"vbox",children:[{type:"hbox",widths:["65%","35%"],children:[{type:"text",id:"ChangeTo",label:"Change to:",labelLayout:"horizontal",inputStyle:"width: 160px;",labelStyle:"font: 12px/25px arial, sans-serif;","default":"",onShow:function(){a.textNode.Thesaurus=this},onHide:function(){this.reset()}},
+{type:"button",id:"ChangeTo",label:"Change to",title:"Change to",style:"width: 121px; margin-top: 1px;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onClick:c}]},{type:"hbox",children:[{type:"select",id:"categories",label:"Categories:",labelStyle:"font: 12px/25px arial, sans-serif;",size:"5",inputStyle:"width: 180px; height: auto;",items:[],onShow:function(){a.selectNode.categories=this},onHide:function(){this.clear()},onChange:function(){a.buildOptionSynonyms(this.getValue())}},
+{type:"select",id:"synonyms",label:"Synonyms:",labelStyle:"font: 12px/25px arial, sans-serif;",size:"5",inputStyle:"width: 180px; height: auto;",items:[],onShow:function(){a.selectNode.synonyms=this;a.textNode.Thesaurus.setValue(this.getValue())},onHide:function(){this.clear()},onChange:function(){a.textNode.Thesaurus.setValue(this.getValue())}}]}]},{type:"vbox",width:"120px",style:"margin-top:46px;",children:[{type:"html",id:"logotype",label:"WebSpellChecker.net",html:'
',
+setup:function(){this.getElement().$.src=a.logotype;this.getElement().getParent().setStyles({"text-align":"center"})}},{type:"button",id:"FinishChecking",label:"Finish Checking",title:"Finish Checking",style:"width: 121px; float: right; margin-top: 9px;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onClick:c}]}]}]},{type:"hbox",id:"BlockFinishChecking",style:"width:560px; margin: 0 auto;",widths:["70%","30%"],onShow:function(){this.getElement().hide()},children:[{type:"hbox",
+id:"leftCol",align:"left",width:"70%",children:[{type:"vbox",id:"rightCol1",children:[{type:"html",id:"logo",html:'
',setup:function(){this.getElement().$.src=a.logotype;this.getElement().getParent().setStyles({"text-align":"center"})}}]}]},{type:"hbox",id:"rightCol",align:"right",width:"30%",children:[{type:"vbox",id:"rightCol_col__left",children:[{type:"button",id:"FinishChecking",
+label:"Finish Checking",title:"Finish Checking",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onClick:c}]}]}]}]}]}});CKEDITOR.dialog.add("options",function(){var b=null,c={},d={},f=null,g=null;e.cookie.get("udn");e.cookie.get("osp");var h=function(){g=this.getElement().getAttribute("title-cmd");var a=[];a[0]=d.IgnoreAllCapsWords;a[1]=d.IgnoreWordsNumbers;a[2]=d.IgnoreMixedCaseWords;a[3]=d.IgnoreDomainNames;a=a.toString().replace(/,/g,"");e.cookie.set("osp",
+a);e.cookie.set("udnCmd",g?g:"ignore");"delete"!=g&&(a="",""!==j.getValue()&&(a=j.getValue()),e.cookie.set("udn",a));e.postMessage.send({id:"options_dic_send"})},i=function(){f.getElement().setHtml(a.LocalizationComing.error);f.getElement().show()};return{title:a.LocalizationComing.Options,minWidth:430,minHeight:130,resizable:CKEDITOR.DIALOG_RESIZE_NONE,contents:[{id:"OptionsTab",label:"Options",accessKey:"O",elements:[{type:"hbox",id:"options_error",children:[{type:"html",style:"display: block;text-align: center;white-space: normal!important; font-size: 12px;color:red",
+html:"",onShow:function(){f=this}}]},{type:"vbox",id:"Options_content",children:[{type:"hbox",id:"Options_manager",widths:["52%","48%"],children:[{type:"fieldset",label:"Spell Checking Options",style:"border: none;margin-top: 13px;padding: 10px 0 10px 10px",onShow:function(){this.getInputElement().$.children[0].innerHTML=a.LocalizationComing.SpellCheckingOptions},children:[{type:"vbox",id:"Options_checkbox",children:[{type:"checkbox",id:"IgnoreAllCapsWords",label:"Ignore All-Caps Words",
+labelStyle:"margin-left: 5px; font: 12px/16px arial, sans-serif;display: inline-block;white-space: normal;",style:"float:left; min-height: 16px;","default":"",onClick:function(){d[this.id]=!this.getValue()?0:1}},{type:"checkbox",id:"IgnoreWordsNumbers",label:"Ignore Words with Numbers",labelStyle:"margin-left: 5px; font: 12px/16px arial, sans-serif;display: inline-block;white-space: normal;",style:"float:left; min-height: 16px;","default":"",onClick:function(){d[this.id]=!this.getValue()?0:1}},{type:"checkbox",
+id:"IgnoreMixedCaseWords",label:"Ignore Mixed-Case Words",labelStyle:"margin-left: 5px; font: 12px/16px arial, sans-serif;display: inline-block;white-space: normal;",style:"float:left; min-height: 16px;","default":"",onClick:function(){d[this.id]=!this.getValue()?0:1}},{type:"checkbox",id:"IgnoreDomainNames",label:"Ignore Domain Names",labelStyle:"margin-left: 5px; font: 12px/16px arial, sans-serif;display: inline-block;white-space: normal;",style:"float:left; min-height: 16px;","default":"",onClick:function(){d[this.id]=
+!this.getValue()?0:1}}]}]},{type:"vbox",id:"Options_DictionaryName",children:[{type:"text",id:"DictionaryName",style:"margin-bottom: 10px",label:"Dictionary Name:",labelLayout:"vertical",labelStyle:"font: 12px/25px arial, sans-serif;","default":"",onLoad:function(){j=this;this.setValue(a.userDictionaryName?a.userDictionaryName:(e.cookie.get("udn"),this.getValue()))},onShow:function(){j=this;this.setValue(!e.cookie.get("udn")?this.getValue():e.cookie.get("udn"));this.setLabel(a.LocalizationComing.DictionaryName)},
+onHide:function(){this.reset()}},{type:"hbox",id:"Options_buttons",children:[{type:"vbox",id:"Options_leftCol_col",widths:["50%","50%"],children:[{type:"button",id:"create",label:"Create",title:"Create",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onShow:function(){this.getElement().setText(a.LocalizationComing.Create)},onClick:h},{type:"button",id:"restore",label:"Restore",title:"Restore",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",
+this.id)},onShow:function(){this.getElement().setText(a.LocalizationComing.Restore)},onClick:h}]},{type:"vbox",id:"Options_rightCol_col",widths:["50%","50%"],children:[{type:"button",id:"rename",label:"Rename",title:"Rename",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",this.id)},onShow:function(){this.getElement().setText(a.LocalizationComing.Rename)},onClick:h},{type:"button",id:"delete",label:"Remove",title:"Remove",style:"width: 100%;",onLoad:function(){this.getElement().setAttribute("title-cmd",
+this.id)},onShow:function(){this.getElement().setText(a.LocalizationComing.Remove)},onClick:h}]}]}]}]},{type:"hbox",id:"Options_text",children:[{type:"html",style:"text-align: justify;margin-top: 15px;white-space: normal!important; font-size: 12px;color:#777;",html:"
get_templates_hierarchy
+
+
+
diff --git a/widgy/templates/widgy/diff.html b/widgy/templates/widgy/diff.html
new file mode 100644
index 000000000..87d0af5ab
--- /dev/null
+++ b/widgy/templates/widgy/diff.html
@@ -0,0 +1,20 @@
+{% extends "base.html" %}{% load compress staticfiles %}
+{% block body %}
+{% compress css %}
+{# designers -- when you get to this, feel free to completely remove this #}
+{# css file and write your own #}
+
+{% endcompress %}
+
+{{ diff|safe }}
+{% endblock %}
diff --git a/widgy/templates/widgy/edit.html b/widgy/templates/widgy/edit.html
new file mode 100644
index 000000000..2c4d88c5a
--- /dev/null
+++ b/widgy/templates/widgy/edit.html
@@ -0,0 +1,18 @@
+{% load i18n %}
+
diff --git a/widgy/templates/widgy/edit_form.html b/widgy/templates/widgy/edit_form.html
deleted file mode 100644
index e0da8d73b..000000000
--- a/widgy/templates/widgy/edit_form.html
+++ /dev/null
@@ -1,7 +0,0 @@
-
diff --git a/widgy/templates/widgy/field_as_div.html b/widgy/templates/widgy/field_as_div.html
new file mode 100644
index 000000000..b3eefe10b
--- /dev/null
+++ b/widgy/templates/widgy/field_as_div.html
@@ -0,0 +1,13 @@
+{% if field.is_hidden %}
+ {{ field }}
+{% else %}
+
+
+
+ {% for call in calls %}
+ {% ifchanged call.templates %}
+ Class
+ Templates
+ Used
+
+
+ {% endifchanged %}
+ {% endfor %}
+{{ call.cls_name }}
+ {% for template in call.templates %}
+ {{ template }}{% if not forloop.last %}, {% endif %}
+ {% endfor %}
+ {{ call.used }}
+ {{ permission_error_message }}
+ {% endblock %}
+ {% else %}
+ {% block popup-content %}
+ {% endblock %}
+ {% endif %}
+
+ {% block widgy_tools %}
+ {% get_action_links owner node as links %}
+ {% for link in links %}
+
+
+{% endblock %}
+
+
+{% compress js %}
+
+
+
+
+{% endcompress %}
+
+
diff --git a/widgy/templatetags/thumbnail_libs.py b/widgy/templatetags/thumbnail_libs.py
new file mode 100644
index 000000000..68f179639
--- /dev/null
+++ b/widgy/templatetags/thumbnail_libs.py
@@ -0,0 +1,47 @@
+from django import template
+
+from sorl.thumbnail.conf import settings
+from sorl.thumbnail import default
+from sorl.thumbnail.images import ImageFile
+from sorl.thumbnail.parsers import parse_geometry
+
+register = template.Library()
+
+
+@register.tag
+def sorl_thumbnail(*args, **kwargs):
+ from sorl.thumbnail.templatetags.thumbnail import thumbnail
+ return thumbnail(*args, **kwargs)
+
+
+@register.tag
+def easy_thumbnail(*args, **kwargs):
+ from easy_thumbnails.templatetags.thumbnail import thumbnail
+ return thumbnail(*args, **kwargs)
+
+
+@register.filter
+def sorl_margin(file_, geometry_string):
+ """
+ This is copied from sorl/thumbnail/templatetags/thumbnail.py because of
+ problems with importing it. This should be removed when we remove
+ easy_thumbnail.
+
+ Returns the calculated margin for an image and geometry
+ """
+ if not file_ or settings.THUMBNAIL_DUMMY:
+ return 'auto'
+ margin = [0, 0, 0, 0]
+ image_file = default.kvstore.get_or_set(ImageFile(file_))
+ x, y = parse_geometry(geometry_string, image_file.ratio)
+ ex = x - image_file.x
+ margin[3] = ex / 2
+ margin[1] = ex / 2
+ if ex % 2:
+ margin[1] += 1
+ ey = y - image_file.y
+ margin[0] = ey / 2
+ margin[2] = ey / 2
+ if ey % 2:
+ margin[2] += 1
+ return ' '.join([ '%spx' % n for n in margin ])
diff --git a/widgy/templatetags/widgy_tags.py b/widgy/templatetags/widgy_tags.py
index 6765b7e70..796e453be 100644
--- a/widgy/templatetags/widgy_tags.py
+++ b/widgy/templatetags/widgy_tags.py
@@ -1,46 +1,102 @@
from django import template
+from django.conf import settings
+from django.utils.safestring import mark_safe
+
+import markdown
+
+from widgy.utils import fancy_import, update_context
register = template.Library()
-class VerbatimNode(template.Node):
- def __init__(self, content):
- self.content = content
+@register.simple_tag(takes_context=True)
+def render(context, node):
+ return node.render(context)
+
- def render(self, context):
- return self.content
+@register.filter
+def scss_files(site):
+ try:
+ site = getattr(settings, site)
+ except AttributeError:
+ pass
+ site = fancy_import(site)
-@register.tag
-def verbatim(parser, token):
- """
- Stops the template engine from rendering the contents of this block tag.
+ return site.scss_files
- Usage::
- {% verbatim %}
- {% don't process this %}
- {% endverbatim %}
+@register.filter
+def js_files(site):
+ try:
+ site = getattr(settings, site)
+ except AttributeError:
+ pass
- You can also designate a specific closing tag block (allowing the
- unrendered use of ``{% endverbatim %}``)::
+ site = fancy_import(site)
- {% verbatim myblock %}
- ...
- {% endverbatim myblock %}
- """
- nodelist = parser.parse(('endverbatim',))
- parser.delete_first_token()
- return VerbatimNode(nodelist.render(template.Context()))
+ return site.js_files
+
+
+@register.filter(name='markdown')
+def mdown(value):
+ value = markdown.markdown(
+ value,
+ extensions=['sane_lists'],
+ safe_mode='escape',
+ )
+
+ return mark_safe(value)
@register.simple_tag(takes_context=True)
-def render(context, content):
- # AttributeError is consumed by the templating engine so we make it an
- # AssertionError
- assert hasattr(content, 'render')
- assert 'request' in context, "Widgy rendering requires that request is in context."
- if not hasattr(content, '_children'):
- content.prefetch_tree()
-
- return content.render(context)
+def render_root(context, owner, field_name):
+ """
+ Renders `root_node` _unless_ `root_node_override` is in the context, in
+ which case the override is rendered instead.
+
+ `root_node_override` is used for stuff like preview, when a view wants to
+ specify exactly what root node to use.
+ """
+ root_node = context.get('root_node_override')
+ field = owner._meta.get_field_by_name(field_name)[0]
+ with update_context(context, {'root_node_override': None}):
+ return field.render(owner, context=context, node=root_node)
+
+
+@register.simple_tag
+def reverse_site_url(site, view_string, *args, **kwargs):
+ """
+ We would be tempted to use
+ {% url site.view kwarg=value kwarg2=value2 %}
+ but site.view actually returns a callable (the view itself). The Django
+ template variable resolver tries to call it, which fails and resolves
+ `site.view' as an empty string.
+ """
+ view = getattr(site, view_string)
+ return site.reverse(view, args=args, kwargs=kwargs)
+
+
+@register.assignment_tag(takes_context=True)
+def has_change_permission(context, site, obj):
+ return site.has_change_permission(context['request'], obj)
+
+
+@register.assignment_tag(takes_context=True)
+def has_add_permission(context, site, obj):
+ return site.has_add_permission(context['request'], obj)
+
+
+@register.assignment_tag(takes_context=True)
+def has_delete_permission(context, site, obj):
+ return site.has_delete_permission(context['request'], obj)
+
+
+@register.assignment_tag
+def get_action_links(owner, root_node):
+ try:
+ get_action_links = owner.get_action_links
+ except AttributeError:
+ return []
+ else:
+ return get_action_links(root_node)
diff --git a/widgy/tests.py b/widgy/tests.py
deleted file mode 100644
index 173f2ea09..000000000
--- a/widgy/tests.py
+++ /dev/null
@@ -1,152 +0,0 @@
-from django.test import TestCase
-
-from widgy.models import ContentPage, TwoColumnLayout, Bucket, TextContent
-
-
-class TwoColumnLayoutTest(TestCase):
- def setUp(self):
- page = ContentPage.objects.create(
- title='test page'
- )
- page.root_node = TwoColumnLayout.add_root().node
- page.save()
- self.page = page
-
- def test_layout_bucket_creation(self):
- """
- Tests that buckets ar auto-created correctly on layouts.
- """
- page = self.page
-
- self.assertTrue(isinstance(page.root_node.get_children()[0].content, Bucket))
- self.assertTrue(isinstance(page.root_node.get_children()[1].content, Bucket))
-
-
-class TreeFetchingOptimization(TestCase):
- def setUp(self):
- page = ContentPage.objects.create(
- title='test page'
- )
- page.root_node = TwoColumnLayout.add_root().node
- page.save()
-
- for i in range(7):
- page.root_node.content.left_bucket.content.add_child(TextContent,
- content='yay %s' % i
- )
- for i in range(5):
- page.root_node.content.right_bucket.content.add_child(TextContent,
- content='yay right bucket %s' % i
- )
-
- self.page = page
-
- def test_layout_bucket_creation(self):
- """
- Ensures that the manual tree building is accurately building the
- same tree in the same ordes that the mp_tree api would build
- """
- page = self.page
-
- root = page.root_node
- root.prefetch_tree()
-
- def test_children(parent):
- children = parent._children
- del parent._children
- self.assertTrue(children == list(parent.get_children()))
- parent._children = children
-
- descendents = [root]
- while descendents:
- descendent = descendents.pop()
- descendents += descendent.get_children()
- test_children(descendent)
-
-
-
-from django.contrib.auth.models import User
-import json
-from pprint import pprint
-
-from widgy.models import TwoColumnLayout, Node
-from widgy.views import extract_id
-
-class HttpTestCase(TestCase):
- def setUp(self):
- u = User.objects.create_user(
- username='testuser',
- email='asdf@example.com',
- password='asdfasdf',
- )
- u.is_superuser = True
- u.save()
- self.client.login(username=u.username, password='asdfasdf')
- self.user = u
-
- def json_request(self, method, url, data=None):
- method = getattr(self.client, method)
- if method == self.client.get:
- encode = lambda x: x
- else:
- encode = json.dumps
- if data:
- resp = method(url, encode(data), content_type='application/json')
- else:
- resp = method(url, content_type='application/json')
-
- assert resp['Content-Type'] == 'application/json'
-
- return resp
-
- def __getattr__(self, attr):
- if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch'):
- return lambda *args, **kwargs: self.json_request(attr, *args, **kwargs)
- else:
- return super(HttpTestCase, self).__getattr__(attr)
-
-class TestApi(HttpTestCase):
- def setUp(self):
- super(TestApi, self).setUp()
-
- # widgy always has a root node
- self.root_node = TwoColumnLayout.add_root().node
- self.node_url = '/admin/widgy/node/'
-
- def test_textcontent_available(self):
- available_children = json.loads(self.get(self.root_node.to_json()['available_children_url']).content)
- assert 'widgy.textcontent' in [i['__class__'] for i in available_children]
-
- def test_add_child(self):
- bucket = self.root_node.to_json()['children'][0]
- db_bucket = Node.objects.get(id=extract_id(bucket['url']))
- assert db_bucket.get_children_count() == 0
-
- new_child = self.post(self.node_url, {
- '__class__': 'widgy.textcontent',
- 'parent_id': bucket['url'],
- 'right_id': None,
- })
- assert new_child.status_code == 201
- new_child = json.loads(new_child.content)
- assert new_child['parent_id'] == bucket['url']
- assert new_child['content']['__class__'] == 'widgy.textcontent'
-
- db_bucket = Node.objects.get(id=extract_id(bucket['url']))
- assert db_bucket.get_children_count() == 1
-
-
- new_child['content']['content'] = 'foobar'
- r = self.put(new_child['content']['url'], new_child['content'])
- assert r.status_code == 200
-
- r = self.get(new_child['content']['url'])
- assert r.status_code == 200
- textcontent = json.loads(r.content)
- assert textcontent['content'] == 'foobar'
-
- # move the node to the other bucket
-
- new_child['parent_id'] = self.root_node.to_json()['children'][1]['url']
- r = self.put(new_child['url'], new_child)
- assert r.status_code == 200
diff --git a/widgy/urls.py b/widgy/urls.py
deleted file mode 100644
index e4ceb9395..000000000
--- a/widgy/urls.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from django.conf.urls import patterns, include, url
-from django.conf import settings
-
-urlpatterns = patterns('widgy.views',
- url('^node/$', 'node'),
- url('^node/(?P