Skip to content

Instantly share code, notes, and snippets.

@djensen47
Last active January 23, 2017 20:51
Show Gist options
  • Save djensen47/189d785171367280c7f79a3fe30b6f23 to your computer and use it in GitHub Desktop.
Save djensen47/189d785171367280c7f79a3fe30b6f23 to your computer and use it in GitHub Desktop.
A custom attribute for aurelia-materialize-bridge for "native" autocomplete.
<md-input
mdx-autocomplete="values.bind: values; min-char: 2; max-results: 5; value-id.two-way: valueId"
md-label="Test"
md-value.bind="test"></md-input>
/**
* mdx-autocomplete.js
*
* License: The MIT License
*
* Copyright 2017 David Jensen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import {inject, customAttribute, bindable, BindingEngine} from 'aurelia-framework';
import {DOM} from 'aurelia-pal';
@customAttribute('mdx-autocomplete')
@inject(Element, BindingEngine)
export class MdxAutocompleteCustomAttribute {
@bindable values = [];
@bindable minChar = 1;
@bindable maxResults = Infinity;
@bindable valueId;
/** @type {Element} */
dropdown;
/** @type {Element} */
element;
/** @type {BindingEngine} */
bindingEngine;
selected = false;
isStringValues = true;
styleDropdown = 'width: 100%; position: absolute; opacity: 1; margin-top: -21px; left: 0px;';
constructor(element, bindingEngine) {
this.element = element;
this.bindingEngine = bindingEngine;
}
attached() {
//this attribute can only be used with md-input
if (this.element.tagName.toLowerCase() === 'md-input') {
this.viewModel = this.element.au.controller.viewModel;
this.input = this.viewModel.input;
} else {
throw new Error('mdx-autocomplete must be attached to an md-input element');
}
//subscribe to mdValue on the viewModel
this.subscription = this.bindingEngine
.propertyObserver(this.viewModel, 'mdValue')
.subscribe(this.mdValueChanged.bind(this));
this.insertDropdown();
}
insertDropdown() {
this.dropdown = DOM.createElement('ul');
this.dropdown.className = 'dropdown-content';
this.dropdown.setAttribute('style', `${this.styleDropdown} display: none;`);
// this.element.insertAdjacentElement('afterend', this.dropdown);
this.element.appendChild(this.dropdown);
this.element.addEventListener('blur', (evt) => {
this.hideDropdown();
});
}
addDropdownItem(label, search, id) {
var item = DOM.createElement('li');
var link = DOM.createElement('a');
const filter = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
link.innerHTML = !filter ? label : label.replace(new RegExp(filter), `<strong style="color: black;">${search}</strong>`);
link.addEventListener('mousedown', (evt) => {
evt.preventDefault();
this.selected = true;
if (!id) {
this.viewModel.mdValue = label;
} else {
this.valueId = id;
}
this.hideDropdown();
});
item.appendChild(link);
this.dropdown.appendChild(item);
}
clearDropdown() {
while(this.dropdown.hasChildNodes()) {
this.dropdown.removeChild(this.dropdown.firstChild);
}
}
hideDropdown() {
this.dropdown.setAttribute('style', `${this.styleDropdown} display: none;`);
}
showDropdown() {
this.dropdown.setAttribute('style', `${this.styleDropdown} display: block;`);
}
detached() {
this.subscription.dispose();
}
valuesChanged(newValues, oldValues) {
if (newValues.length > 0) {
this.isStringValues = typeof newValues[0] === 'string';
}
}
valueIdChanged(newValue, oldValue) {
if (!newValue) return;
const item = this.values.find((item) => {
return newValue === item.id;
});
if (item) {
this.viewModel.mdValue = item.label;
this.hideDropdown();
}
}
mdValueChanged(newValue, oldValue) {
this.clearDropdown();
if (newValue.length < this.minChar) {
this.hideDropdown();
return;
}
if (this.selected) {
this.selected = false;
return;
}
this.valueId = '';
var filtered = this.values.filter(value => {
let label = value;
if (typeof value === 'object') {
label = value.label;
}
const filter = newValue.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
return label.match(new RegExp(filter, 'i'));
});
for (let i = 0; i < Math.min(this.maxResults, filtered.length); i++) {
let item = filtered[i];
if (typeof item === 'string') {
this.addDropdownItem(item, newValue);
} else if (typeof item === 'object') {
this.addDropdownItem(item.label, newValue, item.id);
}
}
//if there is an exact match for a string list item, then hide the dropdown
// the case for a match on valueId is already handled above
if (filtered.length === 1 && this.isStringValues) {
this.hideDropdown();
} else {
this.showDropdown();
}
}
}
@djensen47
Copy link
Author

I put the license in there in case somebody needs to use this in an environment where such things are needed (i.e., almost any business).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment