/
thingsSearch.ts
309 lines (279 loc) · 8.91 KB
/
thingsSearch.ts
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
/* eslint-disable require-jsdoc */
/* eslint-disable new-cap */
/* eslint-disable no-invalid-this */
/* eslint-disable arrow-parens */
import { JSONPath } from 'jsonpath-plus';
import * as API from '../api.js';
import * as Environments from '../environments/environments.js';
import * as Utils from '../utils.js';
import * as Fields from './fields.js';
import * as Things from './things.js';
import * as ThingsSSE from './thingsSSE.js';
let lastSearch = '';
let theSearchCursor;
const dom = {
thingsTableHead: null,
thingsTableBody: null,
searchFilterEdit: null,
favIcon: null,
};
const observers = [];
export function addChangeListener(observer) {
observers.push(observer);
}
function notifyAll(thingIds = null, fields = null) {
observers.forEach(observer => observer.call(null, thingIds, fields));
}
export async function ready() {
Things.addChangeListener(onThingChanged);
ThingsSSE.addChangeListener(updateTableRow);
Utils.getAllElementsById(dom);
dom.thingsTableBody.addEventListener('click', onThingsTableClicked);
}
function onThingsTableClicked(event) {
if (event.target && event.target.nodeName === 'TD') {
const row = event.target.parentNode;
if (row.id === 'searchThingsMore') {
row.style.pointerEvents = 'none';
event.stopImmediatePropagation();
searchThings(dom.searchFilterEdit.value, true);
} else {
if (Things.theThing && Things.theThing.thingId === row.id) {
event.stopImmediatePropagation();
Things.setTheThing(null);
} else {
Things.refreshThing(row.id, null);
}
}
}
}
/**
* Tests if the search filter is an RQL. If yes, things search is called otherwise just things get
* @param {String} filter search filter string containing an RQL or a thingId
*/
export function searchTriggered(filter) {
lastSearch = filter;
const regex = /^(eq\(|ne\(|gt\(|ge\(|lt\(|le\(|in\(|like\(|ilike\(|exists\(|and\(|or\(|not\().*/;
if (filter === '' || regex.test(filter)) {
searchThings(filter);
} else {
getThings([filter]);
}
}
/**
* Gets the list of pinned things
*/
export function pinnedTriggered() {
lastSearch = 'pinned';
dom.searchFilterEdit.value = null;
dom.favIcon.classList.replace('bi-star-fill', 'bi-star');
getThings(Environments.current()['pinnedThings']);
}
/**
* Performs the last search by the user using the last used filter.
* If the user used pinned things last time, the pinned things are reloaded
*/
export function performLastSearch() {
if (lastSearch === 'pinned') {
pinnedTriggered();
} else {
searchTriggered(lastSearch);
}
}
/**
* Gets things from Ditto by thingIds and fills the UI with the result
* @param {Array} thingIds Array of thingIds
*/
export function getThings(thingIds) {
dom.thingsTableBody.innerHTML = '';
const fieldsQueryParameter = Fields.getQueryParameter();
if (thingIds.length > 0) {
API.callDittoREST('GET',
`/things?${fieldsQueryParameter}&ids=${thingIds}&option=sort(%2BthingId)`)
.then((thingJsonArray) => {
fillThingsTable(thingJsonArray);
notifyAll(thingIds, fieldsQueryParameter);
})
.catch((error) => {
resetAndClearViews();
notifyAll();
});
} else {
resetAndClearViews();
notifyAll();
}
}
function resetAndClearViews(retainThing = false) {
theSearchCursor = null;
dom.thingsTableHead.innerHTML = '';
dom.thingsTableBody.innerHTML = '';
if (!retainThing) {
Things.setTheThing(null);
}
}
/**
* Calls Ditto search api and fills UI with the result
* @param {String} filter Ditto search filter (rql)
* @param {boolean} isMore (optional) use cursor from previous search for additional pages
*/
function searchThings(filter, isMore = false) {
document.body.style.cursor = 'progress';
const namespaces = Environments.current().searchNamespaces;
const fieldsQueryParameter = Fields.getQueryParameter();
API.callDittoREST('GET',
'/search/things?' + fieldsQueryParameter +
((filter && filter !== '') ? '&filter=' + encodeURIComponent(filter) : '') +
((namespaces && namespaces !== '') ? '&namespaces=' + namespaces : '') +
'&option=sort(%2BthingId)' +
// ',size(3)' +
(isMore ? ',cursor(' + theSearchCursor + ')' : ''), null, null
).then((searchResult) => {
if (isMore) {
removeMoreFromThingList();
} else {
resetAndClearViews(true);
}
fillThingsTable(searchResult.items);
checkMorePages(searchResult);
if (!isMore) {
notifyAll(searchResult.items.map(thingJson => thingJson.thingId), fieldsQueryParameter);
}
}).catch((error) => {
resetAndClearViews();
notifyAll();
}).finally(() => {
document.body.style.cursor = 'default';
});
function checkMorePages(searchResult) {
if (searchResult['cursor']) {
addMoreToThingList();
theSearchCursor = searchResult.cursor;
} else {
theSearchCursor = null;
}
}
function addMoreToThingList() {
const moreCell = dom.thingsTableBody.insertRow().insertCell(-1);
moreCell.innerHTML = 'load more...';
moreCell.colSpan = dom.thingsTableBody.rows[0].childElementCount;
moreCell.style.textAlign = 'center';
moreCell.style.cursor = 'pointer';
moreCell.disabled = true;
moreCell.style.color = '#3a8c9a';
moreCell.parentNode.id = 'searchThingsMore';
}
}
/**
* remove the "more" line from the things table
*/
export function removeMoreFromThingList() {
const moreRow = document.getElementById('searchThingsMore');
if (moreRow) {
moreRow.parentNode.removeChild(moreRow);
}
}
/**
* Fills the things table UI with the given things
* @param {Array} thingsList Array of thing json objects
*/
function fillThingsTable(thingsList) {
const activeFields = Environments.current().fieldList.filter((f) => f.active);
fillHeaderRow();
let thingSelected = false;
thingsList.forEach((item, t) => {
const row = dom.thingsTableBody.insertRow();
fillBodyRow(row, item);
});
if (!thingSelected) {
Things.setTheThing(null);
}
function fillHeaderRow() {
dom.thingsTableHead.innerHTML = '';
// Utils.addCheckboxToRow(dom.thingsTableHead, 'checkboxHead', false, null);
Utils.insertHeaderCell(dom.thingsTableHead, '');
Utils.insertHeaderCell(dom.thingsTableHead, 'Thing ID');
activeFields.forEach((field) => {
Utils.insertHeaderCell(dom.thingsTableHead, field['label'] ? field.label : field.path);
});
}
function fillBodyRow(row, item) {
row.id = item.thingId;
if (Things.theThing && (item.thingId === Things.theThing.thingId)) {
thingSelected = true;
row.classList.add('table-active');
}
Utils.addCheckboxToRow(
row,
item.thingId,
Environments.current().pinnedThings.includes(item.thingId),
togglePinnedThing,
);
Utils.addCellToRow(row, beautifyId(item.thingId), item.thingId);
activeFields.forEach((field) => {
let path = field.path.replace(/\//g, '.');
if (path.charAt(0) !== '.') {
path = '$.' + path;
}
const elem = JSONPath({
json: item,
path: path,
});
Utils.addCellToRow(row, elem.length !== 0 ? elem[0] : '').setAttribute('jsonPath', path);
});
}
function beautifyId(longId) {
const uuidRegex = /([0-9a-f]{7})[0-9a-f]-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;
let result = longId;
if (Environments.current()['shortenUUID']) {
result = result.replace(uuidRegex, '$1');
}
if (Environments.current()['defaultNamespace']) {
result = result.replace(Environments.current()['defaultNamespace'], 'dn');
}
return result;
}
}
function togglePinnedThing(evt) {
if (evt.target.checked) {
Environments.current().pinnedThings.push(this.id);
} else {
const index = Environments.current().pinnedThings.indexOf(this.id);
if (index > -1) {
Environments.current().pinnedThings.splice(index, 1);
}
}
Environments.environmentsJsonChanged('pinnedThings');
}
function onThingChanged(thingJson) {
if (!thingJson) {
Utils.tableAdjustSelection(dom.thingsTableBody, () => false);
}
}
export function updateTableRow(thingUpdateJson) {
const row = document.getElementById(thingUpdateJson.thingId) as HTMLTableRowElement;
console.assert(row !== null, 'Unexpected thingId for table update. thingId was not loaded before');
Array.from(row.cells).forEach((cell) => {
const path = cell.getAttribute('jsonPath');
if (path) {
const elem = JSONPath({
json: thingUpdateJson,
path: path,
});
if (elem.length !== 0) {
cell.innerHTML = elem[0];
}
}
});
}