]> git.immae.eu Git - github/shaarli/Shaarli.git/commitdiff
Upgrade awesomplete + fix multiple autocompletion fields
authorArthurHoaro <arthur@hoa.ro>
Sat, 14 Jan 2017 15:13:32 +0000 (16:13 +0100)
committerArthurHoaro <arthur@hoa.ro>
Mon, 27 Feb 2017 19:01:54 +0000 (20:01 +0100)
inc/awesomplete-multiple-tags.js
inc/awesomplete.js
inc/awesomplete.min.js

index 4cc8429f474d9781bac6938157b956148b8dfa2f..faecb417858e3dd05487d5f3e7000f4d602a7bda 100644 (file)
@@ -1,13 +1,16 @@
 var awp = Awesomplete.$;
-awesomplete = new Awesomplete(awp('input[data-multiple]'), {
-    filter: function(text, input) {
-        return Awesomplete.FILTER_CONTAINS(text, input.match(/[^ ]*$/)[0]);
-    },
-    replace: function(text) {
-        var before = this.input.value.match(/^.+ \s*|/)[0];
-        this.input.value = before + text + " ";
-    },
-    minChars: 1
+var autocompleteFields = document.querySelectorAll('input[data-multiple]');
+[].forEach.call(autocompleteFields, function(autocompleteField) {
+    awesomplete = new Awesomplete(awp(autocompleteField), {
+        filter: function (text, input) {
+            return Awesomplete.FILTER_CONTAINS(text, input.match(/[^ ]*$/)[0]);
+        },
+        replace: function (text) {
+            var before = this.input.value.match(/^.+ \s*|/)[0];
+            this.input.value = before + text + " ";
+        },
+        minChars: 1
+    })
 });
 
 /**
index fae550e250f3e5c00a04bc0b28e50827ed4bce05..32f49e5b4c703a178f22ed4a67f6be43731328fe 100644 (file)
 
         // Setup
 
+        this.isOpened = false;
+
         this.input = $(input);
+        this.input.setAttribute("autocomplete", "off");
         this.input.setAttribute("aria-autocomplete", "list");
 
         o = o || {};
 
-        configure.call(this, {
+        configure(this, {
             minChars: 2,
             maxItems: 10,
             autoFirst: false,
+            data: _.DATA,
             filter: _.FILTER_CONTAINS,
             sort: _.SORT_BYLENGTH,
-            item: function (text, input) {
-                return $.create("li", {
-                    innerHTML: text.replace(RegExp($.regExpEscape(input.trim()), "gi"), "<mark>$&</mark>"),
-                    "aria-selected": "false"
-                });
-            },
-            replace: function (text) {
-                this.input.value = text;
-            }
+            item: _.ITEM,
+            replace: _.REPLACE
         }, o);
 
         this.index = -1;
@@ -44,7 +41,7 @@
         });
 
         this.ul = $.create("ul", {
-            hidden: "",
+            hidden: "hidden",
             inside: this.container
         });
 
@@ -60,7 +57,7 @@
 
         $.bind(this.input, {
             "input": this.evaluate.bind(this),
-            "blur": this.close.bind(this),
+            "blur": this.close.bind(this, { reason: "blur" }),
             "keydown": function(evt) {
                 var c = evt.keyCode;
 
@@ -72,7 +69,7 @@
                         me.select();
                     }
                     else if (c === 27) { // Esc
-                        me.close();
+                        me.close({ reason: "esc" });
                     }
                     else if (c === 38 || c === 40) { // Down/Up arrow
                         evt.preventDefault();
@@ -82,7 +79,7 @@
             }
         });
 
-        $.bind(this.input.form, {"submit": this.close.bind(this)});
+        $.bind(this.input.form, {"submit": this.close.bind(this, { reason: "submit" })});
 
         $.bind(this.ul, {"mousedown": function(evt) {
             var li = evt.target;
                     li = li.parentNode;
                 }
 
-                if (li) {
-                    me.select(li);
+                if (li && evt.button === 0) {  // Only select on left click
+                    evt.preventDefault();
+                    me.select(li, evt.target);
                 }
             }
         }});
 
         if (this.input.hasAttribute("list")) {
-            this.list = "#" + input.getAttribute("list");
-            input.removeAttribute("list");
+            this.list = "#" + this.input.getAttribute("list");
+            this.input.removeAttribute("list");
         }
         else {
             this.list = this.input.getAttribute("data-list") || o.list || [];
                 list = $(list);
 
                 if (list && list.children) {
-                    this._list = slice.apply(list.children).map(function (el) {
-                        return el.innerHTML.trim();
+                    var items = [];
+                    slice.apply(list.children).forEach(function (el) {
+                        if (!el.disabled) {
+                            var text = el.textContent.trim();
+                            var value = el.value || text;
+                            var label = el.label || text;
+                            if (value !== "") {
+                                items.push({ label: label, value: value });
+                            }
+                        }
                     });
+                    this._list = items;
                 }
             }
 
         },
 
         get opened() {
-            return this.ul && this.ul.getAttribute("hidden") == null;
+            return this.isOpened;
         },
 
-        close: function () {
+        close: function (o) {
+            if (!this.opened) {
+                return;
+            }
+
             this.ul.setAttribute("hidden", "");
+            this.isOpened = false;
             this.index = -1;
 
-            $.fire(this.input, "awesomplete-close");
+            $.fire(this.input, "awesomplete-close", o || {});
         },
 
         open: function () {
             this.ul.removeAttribute("hidden");
+            this.isOpened = true;
 
             if (this.autoFirst && this.index === -1) {
                 this.goto(0);
 
         next: function () {
             var count = this.ul.children.length;
-
-            this.goto(this.index < count - 1? this.index + 1 : -1);
+            this.goto(this.index < count - 1 ? this.index + 1 : (count ? 0 : -1) );
         },
 
         previous: function () {
             var count = this.ul.children.length;
+            var pos = this.index - 1;
 
-            this.goto(this.selected? this.index - 1 : count - 1);
+            this.goto(this.selected && pos !== -1 ? pos : count - 1);
         },
 
         // Should not be used, highlights specific item without any checks!
             if (i > -1 && lis.length > 0) {
                 lis[i].setAttribute("aria-selected", "true");
                 this.status.textContent = lis[i].textContent;
-            }
 
-            $.fire(this.input, "awesomplete-highlight");
+                // scroll to highlighted element in case parent's height is fixed
+                this.ul.scrollTop = lis[i].offsetTop - this.ul.clientHeight + lis[i].clientHeight;
+
+                $.fire(this.input, "awesomplete-highlight", {
+                    text: this.suggestions[this.index]
+                });
+            }
         },
 
-        select: function (selected) {
-            selected = selected || this.ul.children[this.index];
+        select: function (selected, origin) {
+            if (selected) {
+                this.index = $.siblingIndex(selected);
+            } else {
+                selected = this.ul.children[this.index];
+            }
 
             if (selected) {
-                var prevented;
+                var suggestion = this.suggestions[this.index];
 
-                $.fire(this.input, "awesomplete-select", {
-                    text: selected.textContent,
-                    preventDefault: function () {
-                        prevented = true;
-                    }
+                var allowed = $.fire(this.input, "awesomplete-select", {
+                    text: suggestion,
+                    origin: origin || selected
                 });
 
-                if (!prevented) {
-                    this.replace(selected.textContent);
-                    this.close();
-                    $.fire(this.input, "awesomplete-selectcomplete");
+                if (allowed) {
+                    this.replace(suggestion);
+                    this.close({ reason: "select" });
+                    $.fire(this.input, "awesomplete-selectcomplete", {
+                        text: suggestion
+                    });
                 }
             }
         },
                 // Populate list with options that match
                 this.ul.innerHTML = "";
 
-                this._list
+                this.suggestions = this._list
+                    .map(function(item) {
+                        return new Suggestion(me.data(item, value));
+                    })
                     .filter(function(item) {
                         return me.filter(item, value);
                     })
                     .sort(this.sort)
-                    .every(function(text, i) {
-                        me.ul.appendChild(me.item(text, value));
+                    .slice(0, this.maxItems);
 
-                        return i < me.maxItems - 1;
-                    });
+                this.suggestions.forEach(function(text) {
+                    me.ul.appendChild(me.item(text, value));
+                });
 
                 if (this.ul.children.length === 0) {
-                    this.close();
+                    this.close({ reason: "nomatches" });
                 } else {
                     this.open();
                 }
             }
             else {
-                this.close();
+                this.close({ reason: "nomatches" });
             }
         }
     };
         return a < b? -1 : 1;
     };
 
+    _.ITEM = function (text, input) {
+        var html = input.trim() === '' ? text : text.replace(RegExp($.regExpEscape(input.trim()), "gi"), "<mark>$&</mark>");
+        return $.create("li", {
+            innerHTML: html,
+            "aria-selected": "false"
+        });
+    };
+
+    _.REPLACE = function (text) {
+        this.input.value = text.value;
+    };
+
+    _.DATA = function (item/*, input*/) { return item; };
+
 // Private functions
 
-    function configure(properties, o) {
+    function Suggestion(data) {
+        var o = Array.isArray(data)
+            ? { label: data[0], value: data[1] }
+            : typeof data === "object" && "label" in data && "value" in data ? data : { label: data, value: data };
+
+        this.label = o.label || o.value;
+        this.value = o.value;
+    }
+    Object.defineProperty(Suggestion.prototype = Object.create(String.prototype), "length", {
+        get: function() { return this.label.length; }
+    });
+    Suggestion.prototype.toString = Suggestion.prototype.valueOf = function () {
+        return "" + this.label;
+    };
+
+    function configure(instance, properties, o) {
         for (var i in properties) {
             var initial = properties[i],
-                attrValue = this.input.getAttribute("data-" + i.toLowerCase());
+                attrValue = instance.input.getAttribute("data-" + i.toLowerCase());
 
             if (typeof initial === "number") {
-                this[i] = +attrValue;
+                instance[i] = parseInt(attrValue);
             }
             else if (initial === false) { // Boolean options must be false by default anyway
-                this[i] = attrValue !== null;
+                instance[i] = attrValue !== null;
             }
             else if (initial instanceof Function) {
-                this[i] = null;
+                instance[i] = null;
             }
             else {
-                this[i] = attrValue;
+                instance[i] = attrValue;
             }
 
-            this[i] = this[i] || o[i] || initial;
+            if (!instance[i] && instance[i] !== 0) {
+                instance[i] = (i in o)? o[i] : initial;
+            }
         }
     }
 
             evt[j] = properties[j];
         }
 
-        target.dispatchEvent(evt);
+        return target.dispatchEvent(evt);
     };
 
     $.regExpEscape = function (s) {
         return s.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
-    }
+    };
+
+    $.siblingIndex = function (el) {
+        /* eslint-disable no-cond-assign */
+        for (var i = 0; el = el.previousElementSibling; i++);
+        return i;
+    };
 
 // Initialization
 
     function init() {
         $$("input.awesomplete").forEach(function (input) {
-            new Awesomplete(input);
+            new _(input);
         });
     }
 
 // Are we in a browser? Check for Document constructor
-    if (typeof Document !== 'undefined') {
+    if (typeof Document !== "undefined") {
         // DOM already loaded?
         if (document.readyState !== "loading") {
             init();
     _.$$ = $$;
 
 // Make sure to export Awesomplete on self when in a browser
-    if (typeof self !== 'undefined') {
+    if (typeof self !== "undefined") {
         self.Awesomplete = _;
     }
 
 // Expose Awesomplete as a CJS module
-    if (typeof exports === 'object') {
+    if (typeof module === "object" && module.exports) {
         module.exports = _;
     }
 
     return _;
 
-}());
+}());
\ No newline at end of file
index 3bfb05e8558710e29fa6d79f4204f21819be7387..cd08c9490612b884699275f20f946d5851e87d3e 100644 (file)
@@ -1,10 +1,3 @@
 // Awesomplete - Lea Verou - MIT license
-(function(){function m(a,b){for(var c in a){var f=a[c],e=this.input.getAttribute("data-"+c.toLowerCase());this[c]="number"===typeof f?+e:!1===f?null!==e:f instanceof Function?null:e;this[c]=this[c]||b[c]||f}}function d(a,b){return"string"===typeof a?(b||document).querySelector(a):a||null}function h(a,b){return k.call((b||document).querySelectorAll(a))}function l(){h("input.awesomplete").forEach(function(a){new Awesomplete(a)})}var g=self.Awesomplete=function(a,b){var c=this;this.input=d(a);this.input.setAttribute("aria-autocomplete",
-    "list");b=b||{};m.call(this,{minChars:2,maxItems:10,autoFirst:!1,filter:g.FILTER_CONTAINS,sort:g.SORT_BYLENGTH,item:function(a,b){return d.create("li",{innerHTML:a.replace(RegExp(d.regExpEscape(b.trim()),"gi"),"<mark>$&</mark>"),"aria-selected":"false"})},replace:function(a){this.input.value=a}},b);this.index=-1;this.container=d.create("div",{className:"awesomplete",around:a});this.ul=d.create("ul",{hidden:"",inside:this.container});this.status=d.create("span",{className:"visually-hidden",role:"status",
-    "aria-live":"assertive","aria-relevant":"additions",inside:this.container});d.bind(this.input,{input:this.evaluate.bind(this),blur:this.close.bind(this),keydown:function(a){var b=a.keyCode;if(c.opened)if(13===b&&c.selected)a.preventDefault(),c.select();else if(27===b)c.close();else if(38===b||40===b)a.preventDefault(),c[38===b?"previous":"next"]()}});d.bind(this.input.form,{submit:this.close.bind(this)});d.bind(this.ul,{mousedown:function(a){a=a.target;if(a!==this){for(;a&&!/li/i.test(a.nodeName);)a=
-    a.parentNode;a&&c.select(a)}}});this.input.hasAttribute("list")?(this.list="#"+a.getAttribute("list"),a.removeAttribute("list")):this.list=this.input.getAttribute("data-list")||b.list||[];g.all.push(this)};g.prototype={set list(a){Array.isArray(a)?this._list=a:"string"===typeof a&&-1<a.indexOf(",")?this._list=a.split(/\s*,\s*/):(a=d(a))&&a.children&&(this._list=k.apply(a.children).map(function(a){return a.innerHTML.trim()}));document.activeElement===this.input&&this.evaluate()},get selected(){return-1<
-this.index},get opened(){return this.ul&&null==this.ul.getAttribute("hidden")},close:function(){this.ul.setAttribute("hidden","");this.index=-1;d.fire(this.input,"awesomplete-close")},open:function(){this.ul.removeAttribute("hidden");this.autoFirst&&-1===this.index&&this.goto(0);d.fire(this.input,"awesomplete-open")},next:function(){this.goto(this.index<this.ul.children.length-1?this.index+1:-1)},previous:function(){var a=this.ul.children.length;this.goto(this.selected?this.index-1:a-1)},goto:function(a){var b=
-    this.ul.children;this.selected&&b[this.index].setAttribute("aria-selected","false");this.index=a;-1<a&&0<b.length&&(b[a].setAttribute("aria-selected","true"),this.status.textContent=b[a].textContent)},select:function(a){if(a=a||this.ul.children[this.index]){var b;d.fire(this.input,"awesomplete-select",{text:a.textContent,preventDefault:function(){b=!0}});b||(this.replace(a.textContent),this.close(),d.fire(this.input,"awesomplete-selectcomplete"))}},evaluate:function(){var a=this,b=this.input.value;
-    b.length>=this.minChars&&0<this._list.length?(this.index=-1,this.ul.innerHTML="",this._list.filter(function(c){return a.filter(c,b)}).sort(this.sort).every(function(c,d){a.ul.appendChild(a.item(c,b));return d<a.maxItems-1}),0===this.ul.children.length?this.close():this.open()):this.close()}};g.all=[];g.FILTER_CONTAINS=function(a,b){return RegExp(d.regExpEscape(b.trim()),"i").test(a)};g.FILTER_STARTSWITH=function(a,b){return RegExp("^"+d.regExpEscape(b.trim()),"i").test(a)};g.SORT_BYLENGTH=function(a,
-                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           b){return a.length!==b.length?a.length-b.length:a<b?-1:1};var k=Array.prototype.slice;d.create=function(a,b){var c=document.createElement(a),f;for(f in b){var e=b[f];"inside"===f?d(e).appendChild(c):"around"===f?(e=d(e),e.parentNode.insertBefore(c,e),c.appendChild(e)):f in c?c[f]=e:c.setAttribute(f,e)}return c};d.bind=function(a,b){if(a)for(var c in b){var d=b[c];c.split(/\s+/).forEach(function(b){a.addEventListener(b,d)})}};d.fire=function(a,b,c){var d=document.createEvent("HTMLEvents");d.initEvent(b,
-    !0,!0);for(var e in c)d[e]=c[e];a.dispatchEvent(d)};d.regExpEscape=function(a){return a.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&")};"loading"!==document.readyState?l():document.addEventListener("DOMContentLoaded",l);g.$=d;g.$$=h})();
+!function(){function t(t){var e=Array.isArray(t)?{label:t[0],value:t[1]}:"object"==typeof t&&"label"in t&&"value"in t?t:{label:t,value:t};this.label=e.label||e.value,this.value=e.value}function e(t,e,i){for(var n in e){var s=e[n],r=t.input.getAttribute("data-"+n.toLowerCase());"number"==typeof s?t[n]=parseInt(r):s===!1?t[n]=null!==r:s instanceof Function?t[n]=null:t[n]=r,t[n]||0===t[n]||(t[n]=n in i?i[n]:s)}}function i(t,e){return"string"==typeof t?(e||document).querySelector(t):t||null}function n(t,e){return o.call((e||document).querySelectorAll(t))}function s(){n("input.awesomplete").forEach(function(t){new r(t)})}var r=function(t,n){var s=this;this.isOpened=!1,this.input=i(t),this.input.setAttribute("autocomplete","off"),this.input.setAttribute("aria-autocomplete","list"),n=n||{},e(this,{minChars:2,maxItems:10,autoFirst:!1,data:r.DATA,filter:r.FILTER_CONTAINS,sort:r.SORT_BYLENGTH,item:r.ITEM,replace:r.REPLACE},n),this.index=-1,this.container=i.create("div",{className:"awesomplete",around:t}),this.ul=i.create("ul",{hidden:"hidden",inside:this.container}),this.status=i.create("span",{className:"visually-hidden",role:"status","aria-live":"assertive","aria-relevant":"additions",inside:this.container}),i.bind(this.input,{input:this.evaluate.bind(this),blur:this.close.bind(this,{reason:"blur"}),keydown:function(t){var e=t.keyCode;s.opened&&(13===e&&s.selected?(t.preventDefault(),s.select()):27===e?s.close({reason:"esc"}):38!==e&&40!==e||(t.preventDefault(),s[38===e?"previous":"next"]()))}}),i.bind(this.input.form,{submit:this.close.bind(this,{reason:"submit"})}),i.bind(this.ul,{mousedown:function(t){var e=t.target;if(e!==this){for(;e&&!/li/i.test(e.nodeName);)e=e.parentNode;e&&0===t.button&&(t.preventDefault(),s.select(e,t.target))}}}),this.input.hasAttribute("list")?(this.list="#"+this.input.getAttribute("list"),this.input.removeAttribute("list")):this.list=this.input.getAttribute("data-list")||n.list||[],r.all.push(this)};r.prototype={set list(t){if(Array.isArray(t))this._list=t;else if("string"==typeof t&&t.indexOf(",")>-1)this._list=t.split(/\s*,\s*/);else if(t=i(t),t&&t.children){var e=[];o.apply(t.children).forEach(function(t){if(!t.disabled){var i=t.textContent.trim(),n=t.value||i,s=t.label||i;""!==n&&e.push({label:s,value:n})}}),this._list=e}document.activeElement===this.input&&this.evaluate()},get selected(){return this.index>-1},get opened(){return this.isOpened},close:function(t){this.opened&&(this.ul.setAttribute("hidden",""),this.isOpened=!1,this.index=-1,i.fire(this.input,"awesomplete-close",t||{}))},open:function(){this.ul.removeAttribute("hidden"),this.isOpened=!0,this.autoFirst&&this.index===-1&&this.goto(0),i.fire(this.input,"awesomplete-open")},next:function(){var t=this.ul.children.length;this.goto(this.index<t-1?this.index+1:t?0:-1)},previous:function(){var t=this.ul.children.length,e=this.index-1;this.goto(this.selected&&e!==-1?e:t-1)},goto:function(t){var e=this.ul.children;this.selected&&e[this.index].setAttribute("aria-selected","false"),this.index=t,t>-1&&e.length>0&&(e[t].setAttribute("aria-selected","true"),this.status.textContent=e[t].textContent,i.fire(this.input,"awesomplete-highlight",{text:this.suggestions[this.index]}))},select:function(t,e){if(t?this.index=i.siblingIndex(t):t=this.ul.children[this.index],t){var n=this.suggestions[this.index],s=i.fire(this.input,"awesomplete-select",{text:n,origin:e||t});s&&(this.replace(n),this.close({reason:"select"}),i.fire(this.input,"awesomplete-selectcomplete",{text:n}))}},evaluate:function(){var e=this,i=this.input.value;i.length>=this.minChars&&this._list.length>0?(this.index=-1,this.ul.innerHTML="",this.suggestions=this._list.map(function(n){return new t(e.data(n,i))}).filter(function(t){return e.filter(t,i)}).sort(this.sort).slice(0,this.maxItems),this.suggestions.forEach(function(t){e.ul.appendChild(e.item(t,i))}),0===this.ul.children.length?this.close({reason:"nomatches"}):this.open()):this.close({reason:"nomatches"})}},r.all=[],r.FILTER_CONTAINS=function(t,e){return RegExp(i.regExpEscape(e.trim()),"i").test(t)},r.FILTER_STARTSWITH=function(t,e){return RegExp("^"+i.regExpEscape(e.trim()),"i").test(t)},r.SORT_BYLENGTH=function(t,e){return t.length!==e.length?t.length-e.length:t<e?-1:1},r.ITEM=function(t,e){var n=""===e?t:t.replace(RegExp(i.regExpEscape(e.trim()),"gi"),"<mark>$&</mark>");return i.create("li",{innerHTML:n,"aria-selected":"false"})},r.REPLACE=function(t){this.input.value=t.value},r.DATA=function(t){return t},Object.defineProperty(t.prototype=Object.create(String.prototype),"length",{get:function(){return this.label.length}}),t.prototype.toString=t.prototype.valueOf=function(){return""+this.label};var o=Array.prototype.slice;return i.create=function(t,e){var n=document.createElement(t);for(var s in e){var r=e[s];if("inside"===s)i(r).appendChild(n);else if("around"===s){var o=i(r);o.parentNode.insertBefore(n,o),n.appendChild(o)}else s in n?n[s]=r:n.setAttribute(s,r)}return n},i.bind=function(t,e){if(t)for(var i in e){var n=e[i];i.split(/\s+/).forEach(function(e){t.addEventListener(e,n)})}},i.fire=function(t,e,i){var n=document.createEvent("HTMLEvents");n.initEvent(e,!0,!0);for(var s in i)n[s]=i[s];return t.dispatchEvent(n)},i.regExpEscape=function(t){return t.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&")},i.siblingIndex=function(t){for(var e=0;t=t.previousElementSibling;e++);return e},"undefined"!=typeof Document&&("loading"!==document.readyState?s():document.addEventListener("DOMContentLoaded",s)),r.$=i,r.$$=n,"undefined"!=typeof self&&(self.Awesomplete=r),"object"==typeof module&&module.exports&&(module.exports=r),r}();
+//# sourceMappingURL=awesomplete.min.js.map
\ No newline at end of file