autocomplete.js
2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/**
* Creates tribute.js autocompleters.
*
* @package WPZincDashboardWidget
* @author WP Zinc
*/
var wpzinc_autocompleters = [];
/**
* Sets up tribute.js autocompleters based on the
* configuration stored in the localized wpzinc_autocomplete
* global variable.
*
* Once setup, wp_zinc_autocomplete_initialize() can be used to initialize
* them. They don't need to be setup again.
*
* @since 1.0.0
*/
function wp_zinc_autocomplete_setup() {
wpzinc_autocompleters = [];
wpzinc_autocomplete.forEach(
function( autocompleter, i ) {
// Build collection.
var collection = [];
autocompleter.triggers.forEach(
function( trigger, j ) {
// Don't include the opening trigger in the return value when selected.
// This prevents e.g. {{something} when { is the trigger.
trigger.selectTemplate = function( item ) {
return item.original.value;
};
// Check where values are sourced from for this trigger.
if ( 'url' in trigger ) {
// Configure remote datasource.
trigger.values = function( text, cb ) {
// Build form data.
data = new FormData();
data.append( 'action', trigger.action );
data.append( 'nonce', trigger.nonce );
data.append( 'search', text );
// Send AJAX request.
fetch(
trigger.url,
{
method: trigger.method,
credentials: 'same-origin',
body: data
}
).then(
function( response ) {
return response.json();
}
).then(
function( result ) {
cb( result.data );
}
).catch(
function( error ) {
console.error( error );
}
);
}
}
// Add to collection.
collection.push( trigger );
}
);
// Initialize autocompleter.
var tribute = new Tribute(
{
collection: collection
}
);
// Store in array.
wpzinc_autocompleters.push(
{
fields: autocompleter.fields,
instance: tribute
}
);
}
);
}
/**
* Attaches all tribute.js autocompleters
*
* @since 1.0.0
*/
function wp_zinc_autocomplete_initialize() {
wpzinc_autocompleters.forEach(
function( autocompleter, i ) {
autocompleter.fields.forEach(
function( field, j ) {
autocompleter.instance.attach( document.querySelectorAll( field ) );
}
);
}
);
}
/**
* Detaches all tribute.js autocompleters
*
* @since 1.0.0
*/
function wp_zinc_autocomplete_destroy() {
wpzinc_autocompleters.forEach(
function( autocompleter, i ) {
autocompleter.fields.forEach(
function( field, j ) {
autocompleter.instance.detach( document.querySelectorAll( field ) );
}
);
}
);
wpzinc_autocompleters = [];
}
// Setup and initialize.
wp_zinc_autocomplete_setup();
wp_zinc_autocomplete_initialize();