From: Jordan Augé <jordan.auge@lip6.fr> Date: Thu, 8 Aug 2013 13:14:16 +0000 (+0200) Subject: manifold: imprved plugin class with helpers for naming HTML tags in plugins X-Git-Tag: myslice-0.2-1~70 X-Git-Url: http://git.onelab.eu/?a=commitdiff_plain;h=f7419e1b9bedd90e390fa27bf7d7868db617caee;p=unfold.git manifold: imprved plugin class with helpers for naming HTML tags in plugins plugins: improved active_filters, attempt for using templates in JS third-party: added mustache.js for js templating --- diff --git a/Makefile b/Makefile index 73f0bf95..235336b7 100644 --- a/Makefile +++ b/Makefile @@ -93,6 +93,9 @@ THIRD-PARTY-RESOURCES += $(shell ls third-party/jquery-notify/ui.notify.css) THIRD-PARTY-RESOURCES += $(shell ls third-party/codemirror-3.15/lib/codemirror.js) THIRD-PARTY-RESOURCES += $(shell ls third-party/codemirror-3.15/lib/codemirror.css) THIRD-PARTY-RESOURCES += $(shell ls third-party/codemirror-3.15/mode/sql/sql.js) +# Mustache.js +THIRD-PARTY-RESOURCES += $(shell ls third-party/mustache/mustache.js) + thirdparty-js: @find $(THIRD-PARTY-RESOURCES) -name '*.js' diff --git a/manifold/css/manifold.css b/manifold/css/manifold.css new file mode 100644 index 00000000..42c034d3 --- /dev/null +++ b/manifold/css/manifold.css @@ -0,0 +1,4 @@ +.template { + visibility: hidden; + position: absolute; +} diff --git a/manifold/js/manifold.js b/manifold/js/manifold.js index 01c55310..667ad34b 100644 --- a/manifold/js/manifold.js +++ b/manifold/js/manifold.js @@ -128,6 +128,8 @@ var manifold = { * Helper functions **************************************************************************/ + separator: '__', + spin_presets: {}, spin: function(locator, active /*= true */) { diff --git a/manifold/js/plugin.js b/manifold/js/plugin.js index 11aefad5..5d3df742 100644 --- a/manifold/js/plugin.js +++ b/manifold/js/plugin.js @@ -83,13 +83,50 @@ var Plugin = Class.extend({ default_options: {}, - speak: function(msg){ - // You have direct access to the associated and cached jQuery element - this.$element.append('<p>'+msg+'</p>'); + id: function() + { + var ret = this.options.plugin_uuid; + for (var i = 0; i < arguments.length; i++) { + ret = ret + manifold.separator + arguments[i]; + } + return ret; + }, + + el: function() + { + if (arguments.length == 0) { + return $('#' + this.id()); + } else { + // We make sure to search _inside_ the dom tag of the plugin + return $('#' + this.id.apply(this, arguments), this.el()); + } + }, + + els: function(cls) + { + return $('.' + cls, this.el()); + }, + + id_from_filter: function(filter, use_value) + { + use_value = typeof use_value !== 'undefined' ? use_value : true; + + var key = filter[0]; + var op = filter[1]; + var value = filter[2]; + var op_str = this.getOperatorLabel(op); + var s = manifold.separator; + + if (use_value) { + return 'filter' + s + key + s + op_str + s + value; + } else { + return 'filter' + s + key + s + op_str; + } }, - register: function() { - // Registers the plugin to jQuery + str_from_filter: function(filter) + { + return filter[0] + ' ' + filter[1] + ' ' + filter[2]; }, }); diff --git a/plugins/active_filters/active_filters.html b/plugins/active_filters/active_filters.html index 21e361ef..a722d4a2 100644 --- a/plugins/active_filters/active_filters.html +++ b/plugins/active_filters/active_filters.html @@ -1,15 +1,24 @@ -<div id='myActiveFilters' style='clear:both;'> - <div id='{{domid}}-template' class='filterButton' style='float:left;margin-bottom:10px;visibility: hidden;'> - <span id='{{domid}}-template-filter'>KEY OP VALUE</span> +<div id='{{domid}}__myActiveFilters' style='clear:both;'> + + <!-- TEMPLATE --> + <div id='{{domid}}__template' class='template'> + <div id='{% templatetag openvariable %} id {% templatetag closevariable %}' class='filterButton' style='float:left;margin-bottom:10px;'> + <span>{% templatetag openvariable %} span {% templatetag closevariable %}</span> + <img src='/all-static/img/details_close.png' class='closeButton' style='padding-left:3px;'/> + </div> </div> + {% for filter in filters %} - <div id='{{domid}}-filter-{{filter.key}}{{filter.op_str}}{{filter.value}}' class='filterButton' style='float:left;margin-bottom:10px;visibility: hidden;'> - <span id='{{domid}}-template-filter'>{{filter.key}}{{filter.op}}{{filter.value}}</span> + <div id='{{domid}}__filter__{{filter.key}}{{filter.op_str}}{{filter.value}}' class='filterButton' style='float:left;margin-bottom:10px;'> + <span>{{filter.key}}__{{filter.op}}__{{filter.value}}</span> + <img src='/all-static/img/details_close.png' class='closeButton' style='padding-left:3px;'/> </div> {% endfor %} + </div> <div id='clearFilters' class='paging_full_numbers' style='clear:both;'> <span class='paginate_button'>Clear</span> </div> + <div style='clear:both;'></div> diff --git a/plugins/active_filters/active_filters.js b/plugins/active_filters/active_filters.js index 792c6e95..2adfd0e7 100644 --- a/plugins/active_filters/active_filters.js +++ b/plugins/active_filters/active_filters.js @@ -11,11 +11,17 @@ init: function(options, element) { this._super(options, element); - this.listen_query(options.query_uuid); + this.els('closeButton').click(function() { + manifold.raise_event(options.query_uuid, FILTER_REMOVED, filter); + }); - $("#clearFilters").click(function () { + this.el('clearFilters').click(function () { manifold.raise_event(options.query_uuid, CLEAR_FILTERS); }); + this.check_and_hide_clear_button(); + + this.listen_query(options.query_uuid); + }, // This should be provided in the API @@ -39,51 +45,69 @@ } }, - // Visual actions on the component + show_clear_button: function() + { + this.el('clearFilters').show(); + } + + hide_clear_button: function() + { + this.el('clearFilters').hide(); + } + + check_and_hide_clear_button: function() + { + // Count the number of filter _inside_ the current plugin + var count = this.els('filterButton').length; + if (count == 1) { // Including the template + jQuery("#clearFilters").hide(); + } + } - clear_filters: function() { - $("#clearFilters").hide(); + clear_filters: function() + { + // XXX We need to remove all filter but template + this.hide_clear_button(); }, - on_filter_added: function(filter) { - var key = filter[0]; - var op = filter[1]; - var value = filter[2]; - var op_str = this.getOperatorLabel(op); - var id = 'filter_' + key + "_" + op_str; - - // Add a button for a filter - $('#myActiveFilters').append("<div id='" + id + "' class='filterButton' style='float:left;margin-bottom:10px;'/>"); - $('#' + id).append(key + op + value); - - // Add a close button to remove the filter - $('#' + id).append("<img id='close-" + id + "' src='/all-static/img/details_close.png' class='closeButton' style='padding-left:3px;'/>"); + add_filter: function(filter) + { + var template = this.el('template').html(); + var ctx = { + id: this.id(this.id_from_filter(filter, false)), + span: this.str_from_filter(filter) + }; + var output = Mustache.render(template, ctx); + + this.el('myActiveFilters').append(output); + // Add an event on click on the close button, call function removeFilter - $('#close-' + id).click(function(event) { - manifold.raise_event(options.query_uuid, FILTER_REMOVED, filter); + var self = this; + this.els('closeButton').last().click(function() { + manifold.raise_event(self.options.query_uuid, FILTER_REMOVED, filter); }); - // If there are active filters, then show the clear filters button - $("#clearFilters").show(); + + this.show_clear_button(); + }, + + remove_filter = function(filter) + { + this.el(this.id_from_filter(filter, false)).remove(); + this.check_and_hide_clear_button(); }, - on_filter_removed: function(filter) { - var key = filter[0]; - var op = filter[1]; - var value = filter[2]; - var op_str = this.getOperatorLabel(op); - var id = 'filter_' + key + "_" + op_str; + /* Events */ - $('#' + id).remove() - // Count the number of filter _inside_ the current plugin - count = $('.filterButton', $('#myActiveFilters')).length; - if (count == 0) { - jQuery("#clearFilters").hide(); - } + on_filter_added: function(filter) { + this.add_filter(filter); }, - on_filter_clear: function(filter) { - $("#clearFilters").hide(); + on_filter_removed: function(filter) { + this.remove_filter(filter); + }, + on_filter_clear: function(filter) { + this.clear_filters(); }, }); diff --git a/plugins/active_filters/details_close.png b/plugins/active_filters/details_close.png new file mode 100644 index 00000000..fcc23c63 Binary files /dev/null and b/plugins/active_filters/details_close.png differ diff --git a/plugins/active_filters/details_open.png b/plugins/active_filters/details_open.png new file mode 100644 index 00000000..6f034d0f Binary files /dev/null and b/plugins/active_filters/details_open.png differ diff --git a/plugins/googlemap/googlemap.js b/plugins/googlemap/googlemap.js index 9963abfc..c9d39232 100644 --- a/plugins/googlemap/googlemap.js +++ b/plugins/googlemap/googlemap.js @@ -290,9 +290,6 @@ case FILTER_ADDED: case FILTER_REMOVED: case CLEAR_FILTERS: - // XXX Here we might need to maintain the list of filters ! - /* Process updates in filters / current_query must be updated before this call for filtering ! */ - object.table.fnDraw(); break; // Fields diff --git a/third-party/mustache/mustache.js b/third-party/mustache/mustache.js new file mode 100644 index 00000000..bee26f96 --- /dev/null +++ b/third-party/mustache/mustache.js @@ -0,0 +1,536 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +(function (root, factory) { + if (typeof exports === "object" && exports) { + factory(exports); // CommonJS + } else { + var mustache = {}; + factory(mustache); + if (typeof define === "function" && define.amd) { + define(mustache); // AMD + } else { + root.Mustache = mustache; // <script> + } + } +}(this, function (mustache) { + + var whiteRe = /\s*/; + var spaceRe = /\s+/; + var nonSpaceRe = /\S/; + var eqRe = /\s*=/; + var curlyRe = /\s*\}/; + var tagRe = /#|\^|\/|>|\{|&|=|!/; + + // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577 + // See https://github.com/janl/mustache.js/issues/189 + var RegExp_test = RegExp.prototype.test; + function testRegExp(re, string) { + return RegExp_test.call(re, string); + } + + function isWhitespace(string) { + return !testRegExp(nonSpaceRe, string); + } + + var Object_toString = Object.prototype.toString; + var isArray = Array.isArray || function (obj) { + return Object_toString.call(obj) === '[object Array]'; + }; + + function escapeRegExp(string) { + return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); + } + + var entityMap = { + "&": "&", + "<": "<", + ">": ">", + '"': '"', + "'": ''', + "/": '/' + }; + + function escapeHtml(string) { + return String(string).replace(/[&<>"'\/]/g, function (s) { + return entityMap[s]; + }); + } + + function Scanner(string) { + this.string = string; + this.tail = string; + this.pos = 0; + } + + /** + * Returns `true` if the tail is empty (end of string). + */ + Scanner.prototype.eos = function () { + return this.tail === ""; + }; + + /** + * Tries to match the given regular expression at the current position. + * Returns the matched text if it can match, the empty string otherwise. + */ + Scanner.prototype.scan = function (re) { + var match = this.tail.match(re); + + if (match && match.index === 0) { + this.tail = this.tail.substring(match[0].length); + this.pos += match[0].length; + return match[0]; + } + + return ""; + }; + + /** + * Skips all text until the given regular expression can be matched. Returns + * the skipped string, which is the entire tail if no match can be made. + */ + Scanner.prototype.scanUntil = function (re) { + var match, pos = this.tail.search(re); + + switch (pos) { + case -1: + match = this.tail; + this.pos += this.tail.length; + this.tail = ""; + break; + case 0: + match = ""; + break; + default: + match = this.tail.substring(0, pos); + this.tail = this.tail.substring(pos); + this.pos += pos; + } + + return match; + }; + + function Context(view, parent) { + this.view = view || {}; + this.parent = parent; + this._cache = {}; + } + + Context.make = function (view) { + return (view instanceof Context) ? view : new Context(view); + }; + + Context.prototype.push = function (view) { + return new Context(view, this); + }; + + Context.prototype.lookup = function (name) { + var value = this._cache[name]; + + if (!value) { + if (name == '.') { + value = this.view; + } else { + var context = this; + + while (context) { + if (name.indexOf('.') > 0) { + value = context.view; + var names = name.split('.'), i = 0; + while (value && i < names.length) { + value = value[names[i++]]; + } + } else { + value = context.view[name]; + } + + if (value != null) break; + + context = context.parent; + } + } + + this._cache[name] = value; + } + + if (typeof value === 'function') value = value.call(this.view); + + return value; + }; + + function Writer() { + this.clearCache(); + } + + Writer.prototype.clearCache = function () { + this._cache = {}; + this._partialCache = {}; + }; + + Writer.prototype.compile = function (template, tags) { + var fn = this._cache[template]; + + if (!fn) { + var tokens = mustache.parse(template, tags); + fn = this._cache[template] = this.compileTokens(tokens, template); + } + + return fn; + }; + + Writer.prototype.compilePartial = function (name, template, tags) { + var fn = this.compile(template, tags); + this._partialCache[name] = fn; + return fn; + }; + + Writer.prototype.getPartial = function (name) { + if (!(name in this._partialCache) && this._loadPartial) { + this.compilePartial(name, this._loadPartial(name)); + } + + return this._partialCache[name]; + }; + + Writer.prototype.compileTokens = function (tokens, template) { + var self = this; + return function (view, partials) { + if (partials) { + if (typeof partials === 'function') { + self._loadPartial = partials; + } else { + for (var name in partials) { + self.compilePartial(name, partials[name]); + } + } + } + + return renderTokens(tokens, self, Context.make(view), template); + }; + }; + + Writer.prototype.render = function (template, view, partials) { + return this.compile(template)(view, partials); + }; + + /** + * Low-level function that renders the given `tokens` using the given `writer` + * and `context`. The `template` string is only needed for templates that use + * higher-order sections to extract the portion of the original template that + * was contained in that section. + */ + function renderTokens(tokens, writer, context, template) { + var buffer = ''; + + var token, tokenValue, value; + for (var i = 0, len = tokens.length; i < len; ++i) { + token = tokens[i]; + tokenValue = token[1]; + + switch (token[0]) { + case '#': + value = context.lookup(tokenValue); + + if (typeof value === 'object') { + if (isArray(value)) { + for (var j = 0, jlen = value.length; j < jlen; ++j) { + buffer += renderTokens(token[4], writer, context.push(value[j]), template); + } + } else if (value) { + buffer += renderTokens(token[4], writer, context.push(value), template); + } + } else if (typeof value === 'function') { + var text = template == null ? null : template.slice(token[3], token[5]); + value = value.call(context.view, text, function (template) { + return writer.render(template, context); + }); + if (value != null) buffer += value; + } else if (value) { + buffer += renderTokens(token[4], writer, context, template); + } + + break; + case '^': + value = context.lookup(tokenValue); + + // Use JavaScript's definition of falsy. Include empty arrays. + // See https://github.com/janl/mustache.js/issues/186 + if (!value || (isArray(value) && value.length === 0)) { + buffer += renderTokens(token[4], writer, context, template); + } + + break; + case '>': + value = writer.getPartial(tokenValue); + if (typeof value === 'function') buffer += value(context); + break; + case '&': + value = context.lookup(tokenValue); + if (value != null) buffer += value; + break; + case 'name': + value = context.lookup(tokenValue); + if (value != null) buffer += mustache.escape(value); + break; + case 'text': + buffer += tokenValue; + break; + } + } + + return buffer; + } + + /** + * Forms the given array of `tokens` into a nested tree structure where + * tokens that represent a section have two additional items: 1) an array of + * all tokens that appear in that section and 2) the index in the original + * template that represents the end of that section. + */ + function nestTokens(tokens) { + var tree = []; + var collector = tree; + var sections = []; + + var token; + for (var i = 0, len = tokens.length; i < len; ++i) { + token = tokens[i]; + switch (token[0]) { + case '#': + case '^': + sections.push(token); + collector.push(token); + collector = token[4] = []; + break; + case '/': + var section = sections.pop(); + section[5] = token[2]; + collector = sections.length > 0 ? sections[sections.length - 1][4] : tree; + break; + default: + collector.push(token); + } + } + + return tree; + } + + /** + * Combines the values of consecutive text tokens in the given `tokens` array + * to a single token. + */ + function squashTokens(tokens) { + var squashedTokens = []; + + var token, lastToken; + for (var i = 0, len = tokens.length; i < len; ++i) { + token = tokens[i]; + if (token) { + if (token[0] === 'text' && lastToken && lastToken[0] === 'text') { + lastToken[1] += token[1]; + lastToken[3] = token[3]; + } else { + lastToken = token; + squashedTokens.push(token); + } + } + } + + return squashedTokens; + } + + function escapeTags(tags) { + return [ + new RegExp(escapeRegExp(tags[0]) + "\\s*"), + new RegExp("\\s*" + escapeRegExp(tags[1])) + ]; + } + + /** + * Breaks up the given `template` string into a tree of token objects. If + * `tags` is given here it must be an array with two string values: the + * opening and closing tags used in the template (e.g. ["<%", "%>"]). Of + * course, the default is to use mustaches (i.e. Mustache.tags). + */ + function parseTemplate(template, tags) { + template = template || ''; + tags = tags || mustache.tags; + + if (typeof tags === 'string') tags = tags.split(spaceRe); + if (tags.length !== 2) throw new Error('Invalid tags: ' + tags.join(', ')); + + var tagRes = escapeTags(tags); + var scanner = new Scanner(template); + + var sections = []; // Stack to hold section tokens + var tokens = []; // Buffer to hold the tokens + var spaces = []; // Indices of whitespace tokens on the current line + var hasTag = false; // Is there a {{tag}} on the current line? + var nonSpace = false; // Is there a non-space char on the current line? + + // Strips all whitespace tokens array for the current line + // if there was a {{#tag}} on it and otherwise only space. + function stripSpace() { + if (hasTag && !nonSpace) { + while (spaces.length) { + delete tokens[spaces.pop()]; + } + } else { + spaces = []; + } + + hasTag = false; + nonSpace = false; + } + + var start, type, value, chr, token; + while (!scanner.eos()) { + start = scanner.pos; + + // Match any text between tags. + value = scanner.scanUntil(tagRes[0]); + if (value) { + for (var i = 0, len = value.length; i < len; ++i) { + chr = value.charAt(i); + + if (isWhitespace(chr)) { + spaces.push(tokens.length); + } else { + nonSpace = true; + } + + tokens.push(['text', chr, start, start + 1]); + start += 1; + + // Check for whitespace on the current line. + if (chr == '\n') stripSpace(); + } + } + + // Match the opening tag. + if (!scanner.scan(tagRes[0])) break; + hasTag = true; + + // Get the tag type. + type = scanner.scan(tagRe) || 'name'; + scanner.scan(whiteRe); + + // Get the tag value. + if (type === '=') { + value = scanner.scanUntil(eqRe); + scanner.scan(eqRe); + scanner.scanUntil(tagRes[1]); + } else if (type === '{') { + value = scanner.scanUntil(new RegExp('\\s*' + escapeRegExp('}' + tags[1]))); + scanner.scan(curlyRe); + scanner.scanUntil(tagRes[1]); + type = '&'; + } else { + value = scanner.scanUntil(tagRes[1]); + } + + // Match the closing tag. + if (!scanner.scan(tagRes[1])) throw new Error('Unclosed tag at ' + scanner.pos); + + token = [type, value, start, scanner.pos]; + tokens.push(token); + + if (type === '#' || type === '^') { + sections.push(token); + } else if (type === '/') { + // Check section nesting. + if (sections.length === 0) throw new Error('Unopened section "' + value + '" at ' + start); + var openSection = sections.pop(); + if (openSection[1] !== value) throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); + } else if (type === 'name' || type === '{' || type === '&') { + nonSpace = true; + } else if (type === '=') { + // Set the tags for the next time around. + tags = value.split(spaceRe); + if (tags.length !== 2) throw new Error('Invalid tags at ' + start + ': ' + tags.join(', ')); + tagRes = escapeTags(tags); + } + } + + // Make sure there are no open sections when we're done. + var openSection = sections.pop(); + if (openSection) throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); + + tokens = squashTokens(tokens); + + return nestTokens(tokens); + } + + mustache.name = "mustache.js"; + mustache.version = "0.7.2"; + mustache.tags = ["{{", "}}"]; + + mustache.Scanner = Scanner; + mustache.Context = Context; + mustache.Writer = Writer; + + mustache.parse = parseTemplate; + + // Export the escaping function so that the user may override it. + // See https://github.com/janl/mustache.js/issues/244 + mustache.escape = escapeHtml; + + // All Mustache.* functions use this writer. + var defaultWriter = new Writer(); + + /** + * Clears all cached templates and partials in the default writer. + */ + mustache.clearCache = function () { + return defaultWriter.clearCache(); + }; + + /** + * Compiles the given `template` to a reusable function using the default + * writer. + */ + mustache.compile = function (template, tags) { + return defaultWriter.compile(template, tags); + }; + + /** + * Compiles the partial with the given `name` and `template` to a reusable + * function using the default writer. + */ + mustache.compilePartial = function (name, template, tags) { + return defaultWriter.compilePartial(name, template, tags); + }; + + /** + * Compiles the given array of tokens (the output of a parse) to a reusable + * function using the default writer. + */ + mustache.compileTokens = function (tokens, template) { + return defaultWriter.compileTokens(tokens, template); + }; + + /** + * Renders the `template` with the given `view` and `partials` using the + * default writer. + */ + mustache.render = function (template, view, partials) { + return defaultWriter.render(template, view, partials); + }; + + // This is here for backwards compatibility with 0.4.x. + mustache.to_html = function (template, view, partials, send) { + var result = mustache.render(template, view, partials); + + if (typeof send === "function") { + send(result); + } else { + return result; + } + }; + +})); diff --git a/views/templates/base.html b/views/templates/base.html index c297ea5f..155ab2d6 100644 --- a/views/templates/base.html +++ b/views/templates/base.html @@ -15,8 +15,10 @@ {% insert_str prelude "js/messages-runtime.js" %} {% insert_str prelude "js/class.js" %} {% insert_str prelude "js/plugin_helper.js" %} +{% insert_str prelude "js/mustache.js" %} {% insert_str prelude "js/plugin.js" %} {% insert_str prelude "js/manifold.js" %} +{% insert_str prelude "css/manifold.css" %} <body> {% block container %} <div id="container">