Skip to content
This repository was archived by the owner on Aug 7, 2020. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"angular": ">=1.6.x",
"angular-aria": ">=1.6.x",
"angular-sanitize": ">=1.6.x",
"bloodhound-js": "^1.2.3",
"clipboard": "^2.0.1",
"escape-string-regexp": "^1.0.5",
"flatpickr": "^4.5.2",
Expand Down
2 changes: 2 additions & 0 deletions packages/oui-angular/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ActionMenu from "@ovh-ui/oui-action-menu";
import Autocomplete from "@ovh-ui/oui-autocomplete";
import BackButton from "@ovh-ui/oui-back-button";
import Button from "@ovh-ui/oui-button";
import Calendar from "@ovh-ui/oui-calendar";
Expand Down Expand Up @@ -40,6 +41,7 @@ import Tooltip from "@ovh-ui/oui-tooltip";
export default angular
.module("oui", [
ActionMenu,
Autocomplete,
BackButton,
Button,
Calendar,
Expand Down
1 change: 1 addition & 0 deletions packages/oui-angular/src/index.spec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import "@ovh-ui/common/test-utils";

loadTests(require.context("../../oui-action-menu/src/", true, /.*((\.spec)|(index))$/));
loadTests(require.context("../../oui-autocomplete/src/", true, /.*((\.spec)|(index))$/));
loadTests(require.context("../../oui-back-button/src/", true, /.*((\.spec)|(index))$/));
loadTests(require.context("../../oui-button/src/", true, /.*((\.spec)|(index))$/));
loadTests(require.context("../../oui-calendar/src/", true, /.*((\.spec)|(index))$/));
Expand Down
83 changes: 83 additions & 0 deletions packages/oui-autocomplete/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Autocomplete

<component-status cx-design="complete" ux="rc"></component-status>

## Usage

### Basic

#### Array of strings

```html:preview
<input type="text" class="oui-input oui-input_inline"
placeholder="Search country name"
ng-model="$ctrl.modelStrings"
oui-autocomplete="$ctrl.suggestionStrings">
```

#### Array of objects

```html:preview
<input type="text" class="oui-input oui-input_inline"
placeholder="Search country name"
ng-model="$ctrl.modelObjects"
oui-autocomplete="$ctrl.suggestionObjects"
oui-autocomplete-property="country.name">
```

### Events

**Note**: If you want to access the parameters inside `on-select` callback, you need to use `value` variable as below.
It will return the corresponding value from your array of suggestions.

```html:preview
<input type="text" class="oui-input oui-input_inline"
placeholder="Search country name"
ng-model="$ctrl.modelOnSelect"
oui-autocomplete="$ctrl.suggestionObjects"
oui-autocomplete-property="country.name"
oui-autocomplete-on-select="$ctrl.selectedValue = value">
<div class="oui-doc-preview-only">
<p><strong>model value:</strong> {{$ctrl.modelOnSelect | json}}</p>
<p><strong>onSelect 'value' value:</strong> {{$ctrl.selectedValue | json}}</p>
</div>
```

## Variants

### Search

See [Search](#!/oui-angular/search) component.

```html:preview
<oui-search
model="$ctrl.modelSearch"
autocomplete="$ctrl.suggestionObjects"
autocomplete-property="country.name"
placeholder="Search country name">
</oui-search>
```

## API

| Attribute | Type | Binding | One-time binding | Values | Default | Description
| ---- | ---- | ---- | ---- | ---- | ---- | ----
| `oui-autocomplete` | array | < | no | n/a | n/a | array of suggestions
| `oui-autocomplete-options` | object | <? | yes | n/a | n/a | options of autocomplete
| `oui-autocomplete-property` | string | @? | no | n/a | n/a | property path used to get value from suggestion
| `oui-autocomplete-on-select` | function | & | no | n/a | n/a | handler triggered when suggestion is selected

## Configuration

The autocomplete can be globally configured with a provider.

```js
angular.module("myModule", [
"oui.autocomplete"
]).config(ouiAutocompleteConfigurationProvider => {
ouiAutocompleteConfigurationProvider.setOptions({ // default options
debounceDelay: 500,
minLength: 2
});
});
```
11 changes: 11 additions & 0 deletions packages/oui-autocomplete/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "@ovh-ui/oui-autocomplete",
"version": "1.0.0",
"main": "./src/index.js",
"license": "BSD-3-Clause",
"author": "OVH SAS",
"dependencies": {
"bloodhound-js": "^1.2.3",
"popper.js": "^1.14.4"
}
}
251 changes: 251 additions & 0 deletions packages/oui-autocomplete/src/autocomplete.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
import Bloodhound from "bloodhound-js";
import debounce from "lodash/debounce";
import get from "lodash/get";
import merge from "lodash/merge";
import Popper from "popper.js";
import template from "./autocomplete.html";

const KEYBOARD_KEYS = {
TAB: 9,
SHIFT: 16,
ESC: 27,
UP: 38,
DOWN: 40
};

export default class {
constructor ($compile, $document, $element, $scope, $timeout, ouiAutocompleteConfiguration) {
"ngInject";

this.$compile = $compile;
this.$document = $document;
this.$element = $element;
this.$timeout = $timeout;
this.$scope = $scope;
this.providerOptions = ouiAutocompleteConfiguration.options;
}

createDatalist () {
const input = this.$element[0];
const autocomplete = this.$element.next()[0];

// Let Popper.js position the datalist
this.popper = new Popper(input, autocomplete, {
placement: "bottom-start"
});

this.triggerWidth = `${this.popper.reference.clientWidth}px`;
}

openDatalist (datum) {
if (!datum.length) {
this.closeDatalist();
return;
}

this.$timeout(() => {
// Refresh keyboard navigation
this.navItems = undefined;
this.navIndex = undefined;

this.datalist = datum;
this.isOpen = true;

// Init keyboard navigation
if (!this.isNavigable) {
this.isNavigable = true;
this.$document
.one("click", () => this.closeDatalist())
.on("keydown", (e) => this.triggerKeyHandler(e))
.on("keyup", (e) => delete this.keys[e.which]);
}
});
}

closeDatalist () {
this.$timeout(() => {
this.datalist = [];
this.isOpen = false;

// Clear keyboard navigation
if (this.isNavigable) {
this.isNavigable = false;
this.keys = {};

this.$document
.off("click")
.off("keydown")
.off("keyup");
}
});
}

initSearchEngine (suggestions) {
if (!this.engine && angular.isArray(suggestions)) {
this.engine = new Bloodhound({
local: suggestions,
datumTokenizer: (datum) => {
const value = this.getProperty(datum);
return Bloodhound.tokenizers.whitespace(value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});

this.engine.initialize();

// Watch model value for search engine
this.$scope.$watch(
() => this.model.$modelValue,
debounce(
(value) => this.searchQuery(value),
this.options.debounceDelay
)
);
}
}

updateSearchEngine (suggestions) {
if (this.engine && angular.isArray(suggestions)) {
this.engine.clear();
this.engine.local = suggestions;
this.engine.initialize(true);
}
}

searchQuery (query) {
if (angular.isString(query) && query !== this.selectedValue) {
this.$timeout(() => {
if (query.length >= this.options.minLength) {
this.engine.search(
query,
(datum) => this.openDatalist(datum), // Sync
(datum) => this.openDatalist(datum) // Async
);
} else if (this.isOpen) {
this.closeDatalist();
}

// Needed for highlight filter
this.query = query;
});
}
}

updateValue (value) {
this.$element[0].focus();
this.selectedValue = this.getProperty(value);
this.closeDatalist();

// Update value and notify model change
this.model.$setViewValue(this.selectedValue);
this.model.$render();

// Callback
this.onSelect({
value: angular.copy(value) // Clean $$hashKey
});
}

getProperty (item) {
return get(item, this.property, item);
}

focusNavItem (direction) {
if (angular.isUndefined(this.navItems)) {
this.navItems = this.autocomplete.find("button");
this.navItems.push(this.$element[0]);
this.navLastIndex = this.navItems.length - 1;
}

// Set index of trigger input if undefined
if (angular.isUndefined(this.navIndex)) {
this.navIndex = this.navLastIndex;
}

if (direction === "next") {
this.navIndex = this.navIndex >= this.navLastIndex ? 0 : this.navIndex + 1;
} else if (direction === "prev") {
this.navIndex = this.navIndex <= 0 ? this.navLastIndex : this.navIndex - 1;
}

this.navItems[this.navIndex].focus();
}

triggerKeyHandler (e) {
if (this.isNavigable) {
const key = e.which;

if ([
KEYBOARD_KEYS.TAB,
KEYBOARD_KEYS.SHIFT,
KEYBOARD_KEYS.UP,
KEYBOARD_KEYS.DOWN,
KEYBOARD_KEYS.ESC
].indexOf(key) > -1) {
e.preventDefault();
e.stopPropagation();

// Add key in array for key combination
this.keys[key] = true;

if (
(this.keys[KEYBOARD_KEYS.TAB] && !this.keys[KEYBOARD_KEYS.SHIFT]) ||
this.keys[KEYBOARD_KEYS.DOWN]
) {
// Move Down
this.focusNavItem("next");
} else if (
(this.keys[KEYBOARD_KEYS.TAB] && this.keys[KEYBOARD_KEYS.SHIFT]) ||
this.keys[KEYBOARD_KEYS.UP]
) {
// Move Up
this.focusNavItem("prev");
} else if (this.keys[KEYBOARD_KEYS.ESC]) {
// Escape
this.closeDatalist();
}
}
}
}

$onChanges (changes) {
if (changes.suggestions && changes.suggestions.currentValue) {
this.updateSearchEngine(changes.suggestions.currentValue);
}
}

$onInit () {
this.id = `ouiAutocomplete${this.$scope.$id}`;
this.options = merge(this.providerOptions, this.options);
this.keys = {};

this.initSearchEngine(this.suggestions);
}

$postLink () {
this.$timeout(() => {
// Create a new scope to compile the autocomplete next to the input
const autocompleteScope = angular.extend(this.$scope.$new(true), { $autocompleteCtrl: this });
this.autocomplete = this.$compile(template)(autocompleteScope);

this.$element
.attr("autocomplete", "off")
.attr("list", this.id)
.one("focus", () => this.createDatalist()) // One time bind to create the popper helper
.on("click", (e) => e.stopPropagation()) // Avoid click propagation on $element
.after(this.autocomplete); // Add compiled template after $element
});
}

$onDestroy () {
if (this.engine) {
this.engine.clear();
}

if (this.isNavigable) {
this.$element
.off("click")
.off("keydown");
}
}
}
21 changes: 21 additions & 0 deletions packages/oui-autocomplete/src/autocomplete.directive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import controller from "./autocomplete.controller";

export default () => {
"ngInject";

return {
restrict: "A",
require: {
model: "ngModel"
},
scope: true,
bindToController: {
suggestions: "<ouiAutocomplete",
options: "<?ouiAutocompleteOptions",
property: "@?ouiAutocompleteProperty",
onSelect: "&ouiAutocompleteOnSelect"
},
controller,
controllerAs: "$autocompleteCtrl"
};
};
Loading