-
Notifications
You must be signed in to change notification settings - Fork 215
/
things.js
287 lines (253 loc) · 8.54 KB
/
things.js
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
/* eslint-disable require-jsdoc */
/*
* 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 new-cap */
/* eslint-disable no-invalid-this */
import {JSONPath} from 'https://cdn.jsdelivr.net/npm/jsonpath-plus@5.0.3/dist/index-browser-esm.min.js';
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';
export let theThing;
let theSearchCursor;
let thingJsonEditor;
const observers = [];
const dom = {
thingsTableHead: null,
thingsTableBody: null,
thingDetails: null,
thingId: null,
tabModifyThing: null,
searchFilterEdit: null,
};
/**
* Adds a listener function for the currently selected thing
* @param {function} observer function that will be called if the current thing was changed
*/
export function addChangeListener(observer) {
observers.push(observer);
}
/**
* Initializes components. Should be called after DOMContentLoaded event
*/
export async function ready() {
Utils.getAllElementsById(dom);
thingJsonEditor = ace.edit('thingJsonEditor');
thingJsonEditor.session.setMode('ace/mode/json');
dom.searchFilterEdit.onchange = removeMoreFromThingList;
document.getElementById('createThing').onclick = () => {
API.callDittoREST('POST', '/things', {})
.then((data) => {
refreshThing(data.thingId);
getThings([data.thingId]);
});
};
document.getElementById('putThing').onclick = clickModifyThing('PUT');
document.getElementById('deleteThing').onclick = clickModifyThing('DELETE');
dom.thingsTableBody.addEventListener('click', (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, theSearchCursor);
} else {
refreshThing(row.id);
}
}
});
document.querySelector('a[data-bs-target="#tabModifyThing"]').addEventListener('shown.bs.tab', (event) => {
thingJsonEditor.renderer.updateFull();
});
dom.searchFilterEdit.focus();
};
/**
* 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();
thingsList.forEach((item, t) => {
const row = dom.thingsTableBody.insertRow();
fillBodyRow(row, item);
});
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 (theThing && (item.thingId === theThing.thingId)) {
row.classList.add('table-active');
};
Utils.addCheckboxToRow(
row,
item.thingId,
Environments.current().pinnedThings.includes(item.thingId),
togglePinnedThing,
);
row.insertCell(-1).innerHTML = item.thingId;
activeFields.forEach((field) => {
let path = field.path.replace(/\//g, '.');
if (path.charAt(0) !== '.') {
path = '$.' + path;
}
const elem = JSONPath({
json: item,
path: path,
});
row.insertCell(-1).innerHTML = elem.length !== 0 ? elem[0] : '';
});
}
};
/**
* Calls Ditto search api and fills UI with the result
* @param {String} filter Ditto search filter (rql)
* @param {String} cursor (optional) cursor returned from things search for additional pages
*/
export function searchThings(filter, cursor) {
if (cursor) {
removeMoreFromThingList();
} else {
theSearchCursor = null;
dom.thingsTableBody.innerHTML = '';
}
document.body.style.cursor = 'progress';
API.callDittoREST('GET',
'/search/things?' + Fields.getQueryParameter() +
((filter && filter != '') ? '&filter=' + encodeURIComponent(filter) : '') +
'&option=sort(%2BthingId)' +
// ',size(3)' +
(cursor ? ',cursor(' + cursor + ')' : ''),
).then((searchResult) => {
fillThingsTable(searchResult.items);
checkMorePages(searchResult);
}).catch((error) => {
// nothing to do if search failed
}).finally(() => {
document.body.style.cursor = 'default';
});
};
/**
* 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 = '';
if (thingIds.length > 0) {
API.callDittoREST('GET',
`/things?${Fields.getQueryParameter()}&ids=${thingIds}&option=sort(%2BthingId)`,
).then(fillThingsTable);
};
};
/**
* Returns a click handler for Update thing and delete thing
* @param {String} method PUT or DELETE
* @return {function} Click handler function
*/
function clickModifyThing(method) {
return function() {
Utils.assert(dom.thingId.value, 'Thing ID is empty');
API.callDittoREST(method,
'/things/' + dom.thingId.value,
method === 'PUT' ? JSON.parse(thingJsonEditor.getValue()) : null,
).then(() => {
// todo: perform last things table update
method === 'PUT' ? refreshThing(dom.thingId.value) : searchThings();
});
};
};
/**
* Load thing from Ditto and update all UI components
* @param {String} thingId ThingId
*/
export function refreshThing(thingId) {
API.callDittoREST('GET',
`/things/${thingId}?fields=thingId%2Cattributes%2Cfeatures%2C_created%2C_modified%2C_revision%2C_policy`)
.then((thing) => setTheThing(thing));
};
/**
* Update all UI components for the given Thing
* @param {Object} thingJson Thing json
*/
export function setTheThing(thingJson) {
theThing = thingJson;
// Update fields of Thing table
dom.thingDetails.innerHTML = '';
Utils.addTableRow(dom.thingDetails, 'thingId', theThing.thingId, null, true);
Utils.addTableRow(dom.thingDetails, 'policyId', theThing._policy.policyId, null, true);
Utils.addTableRow(dom.thingDetails, 'revision', theThing._revision, null, true);
Utils.addTableRow(dom.thingDetails, 'created', theThing._created, null, true);
Utils.addTableRow(dom.thingDetails, 'modified', theThing._modified, null, true);
// Update edit thing area
dom.thingId.value = theThing.thingId;
const thingCopy = JSON.parse(JSON.stringify(theThing));
delete thingCopy['_revision'];
delete thingCopy['_created'];
delete thingCopy['_modified'];
delete thingCopy['_policy'];
thingCopy.policyId = theThing._policy.policyId;
thingJsonEditor.setValue(JSON.stringify(thingCopy, null, 2));
observers.forEach((observer) => observer.call(null, theThing));
}
/**
* Updates UI depepending on existing additional pages on Ditto things search
* @param {Object} searchResult Result from Ditto thing search
*/
function checkMorePages(searchResult) {
if (searchResult['cursor']) {
addMoreToThingList();
theSearchCursor = searchResult.cursor;
} else {
theSearchCursor = null;
}
}
/**
* Adds a clickable "more" line to the things table UI
*/
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
*/
function removeMoreFromThingList() {
const moreRow = document.getElementById('searchThingsMore');
if (moreRow) {
moreRow.parentNode.removeChild(moreRow);
}
}
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();
};