@fleetbase/ember-core 0.2.8 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,8 +38,12 @@ export default class AppCacheService extends Service {
38
38
  return this;
39
39
  }
40
40
 
41
- @action get(key) {
42
- return this.localCache.get(`${this.cachePrefix}${dasherize(key)}`);
41
+ @action get(key, defaultValue = null) {
42
+ const value = this.localCache.get(`${this.cachePrefix}${dasherize(key)}`);
43
+ if (value === undefined) {
44
+ return defaultValue;
45
+ }
46
+ return value;
43
47
  }
44
48
 
45
49
  @action has(key) {
@@ -0,0 +1,263 @@
1
+ import Service, { inject as service } from '@ember/service';
2
+ import Evented from '@ember/object/evented';
3
+ import { tracked } from '@glimmer/tracking';
4
+ import { isArray } from '@ember/array';
5
+ import { task } from 'ember-concurrency';
6
+ import { all } from 'rsvp';
7
+
8
+ export default class ChatService extends Service.extend(Evented) {
9
+ @service store;
10
+ @service currentUser;
11
+ @service appCache;
12
+ @tracked channels = [];
13
+ @tracked openChannels = [];
14
+
15
+ openChannel(chatChannelRecord) {
16
+ if (this.openChannels.includes(chatChannelRecord)) {
17
+ return;
18
+ }
19
+ this.openChannels.pushObject(chatChannelRecord);
20
+ this.rememberOpenedChannel(chatChannelRecord);
21
+ this.trigger('chat.opened', chatChannelRecord);
22
+ }
23
+
24
+ closeChannel(chatChannelRecord) {
25
+ const index = this.openChannels.findIndex((_) => _.id === chatChannelRecord.id);
26
+ if (index >= 0) {
27
+ this.openChannels.removeAt(index);
28
+ this.trigger('chat.closed', chatChannelRecord);
29
+ }
30
+ this.forgetOpenedChannel(chatChannelRecord);
31
+ }
32
+
33
+ rememberOpenedChannel(chatChannelRecord) {
34
+ let openedChats = this.appCache.get('open-chats', []);
35
+ if (isArray(openedChats) && !openedChats.includes(chatChannelRecord.id)) {
36
+ openedChats.pushObject(chatChannelRecord.id);
37
+ } else {
38
+ openedChats = [chatChannelRecord.id];
39
+ }
40
+ this.appCache.set('open-chats', openedChats);
41
+ }
42
+
43
+ forgetOpenedChannel(chatChannelRecord) {
44
+ let openedChats = this.appCache.get('open-chats', []);
45
+ if (isArray(openedChats)) {
46
+ openedChats.removeObject(chatChannelRecord.id);
47
+ } else {
48
+ openedChats = [];
49
+ }
50
+ this.appCache.set('open-chats', openedChats);
51
+ }
52
+
53
+ restoreOpenedChats() {
54
+ const openedChats = this.appCache.get('open-chats', []);
55
+ if (isArray(openedChats)) {
56
+ const findAll = openedChats.map((id) => this.store.findRecord('chat-channel', id));
57
+ return all(findAll).then((openedChatRecords) => {
58
+ if (isArray(openedChatRecords)) {
59
+ for (let i = 0; i < openedChatRecords.length; i++) {
60
+ const chatChannelRecord = openedChatRecords[i];
61
+ this.openChannel(chatChannelRecord);
62
+ }
63
+ }
64
+ return openedChatRecords;
65
+ });
66
+ }
67
+
68
+ return [];
69
+ }
70
+
71
+ getOpenChannels() {
72
+ return this.openChannels;
73
+ }
74
+
75
+ createChatChannel(name) {
76
+ const chatChannelRecord = this.store.createRecord('chat-channel', { name });
77
+ return chatChannelRecord.save().finally(() => {
78
+ this.trigger('chat.created', chatChannelRecord);
79
+ });
80
+ }
81
+
82
+ deleteChatChannel(chatChannelRecord) {
83
+ return chatChannelRecord.destroyRecord().finally(() => {
84
+ this.trigger('chat.deleted', chatChannelRecord);
85
+ });
86
+ }
87
+
88
+ updateChatChannel(chatChannelRecord, props = {}) {
89
+ chatChannelRecord.setProperties(props);
90
+ return chatChannelRecord.save().finally(() => {
91
+ this.trigger('chat.updated', chatChannelRecord);
92
+ });
93
+ }
94
+
95
+ addParticipant(chatChannelRecord, userRecord) {
96
+ const chatParticipant = this.store.createRecord('chat-participant', {
97
+ chat_channel_uuid: chatChannelRecord.id,
98
+ user_uuid: userRecord.id,
99
+ });
100
+ return chatParticipant.save().finally(() => {
101
+ this.trigger('chat.added_participant', chatParticipant, chatChannelRecord);
102
+ });
103
+ }
104
+
105
+ removeParticipant(chatChannelRecord, chatParticipant) {
106
+ return chatParticipant.destroyRecord().finally(() => {
107
+ this.trigger('chat.removed_participant', chatParticipant, chatChannelRecord);
108
+ });
109
+ }
110
+
111
+ async sendMessage(chatChannelRecord, senderRecord, messageContent = '', attachments = []) {
112
+ const chatMessage = this.store.createRecord('chat-message', {
113
+ chat_channel_uuid: chatChannelRecord.id,
114
+ sender_uuid: senderRecord.id,
115
+ content: messageContent,
116
+ attachment_files: attachments,
117
+ });
118
+
119
+ return chatMessage
120
+ .save()
121
+ .then((chatMessageRecord) => {
122
+ if (chatChannelRecord.doesntExistsInFeed('message', chatMessageRecord)) {
123
+ chatChannelRecord.feed.pushObject({
124
+ type: 'message',
125
+ created_at: chatMessageRecord.created_at,
126
+ data: chatMessageRecord.serialize(),
127
+ record: chatMessageRecord,
128
+ });
129
+ }
130
+ return chatMessageRecord;
131
+ })
132
+ .finally(() => {
133
+ this.trigger('chat.feed_updated', chatMessage, chatChannelRecord);
134
+ this.trigger('chat.message_created', chatMessage, chatChannelRecord);
135
+ });
136
+ }
137
+
138
+ deleteMessage(chatMessageRecord) {
139
+ return chatMessageRecord.destroyRecord().finally(() => {
140
+ this.trigger('chat.feed_updated', chatMessageRecord);
141
+ this.trigger('chat.message_deleted', chatMessageRecord);
142
+ });
143
+ }
144
+
145
+ insertChatMessageFromSocket(chatChannelRecord, data) {
146
+ // normalize and create record
147
+ const normalized = this.store.normalize('chat-message', data);
148
+ const record = this.store.push(normalized);
149
+
150
+ // make sure it doesn't exist in feed already
151
+ if (chatChannelRecord.existsInFeed('message', record)) {
152
+ return;
153
+ }
154
+
155
+ // create feed item
156
+ const item = {
157
+ type: 'message',
158
+ created_at: record.created_at,
159
+ data,
160
+ record,
161
+ };
162
+
163
+ // add item to feed
164
+ chatChannelRecord.feed.pushObject(item);
165
+
166
+ // trigger event
167
+ this.trigger('chat.feed_updated', record, chatChannelRecord);
168
+ this.trigger('chat.message_created', record, chatChannelRecord);
169
+ }
170
+
171
+ insertChatLogFromSocket(chatChannelRecord, data) {
172
+ // normalize and create record
173
+ const normalized = this.store.normalize('chat-log', data);
174
+ const record = this.store.push(normalized);
175
+
176
+ // make sure it doesn't exist in feed already
177
+ if (chatChannelRecord.existsInFeed('log', record)) {
178
+ return;
179
+ }
180
+
181
+ // create feed item
182
+ const item = {
183
+ type: 'log',
184
+ created_at: record.created_at,
185
+ data,
186
+ record,
187
+ };
188
+
189
+ // add item to feed
190
+ chatChannelRecord.feed.pushObject(item);
191
+
192
+ // trigger event
193
+ this.trigger('chat.feed_updated', record, chatChannelRecord);
194
+ this.trigger('chat.log_created', record, chatChannelRecord);
195
+ }
196
+
197
+ insertChatAttachmentFromSocket(chatChannelRecord, data) {
198
+ // normalize and create record
199
+ const normalized = this.store.normalize('chat-attachment', data);
200
+ const record = this.store.push(normalized);
201
+
202
+ // Find the chat message the record belongs to in the feed
203
+ const chatMessage = chatChannelRecord.feed.find((item) => {
204
+ return item.type === 'message' && item.record.id === record.chat_message_uuid;
205
+ });
206
+
207
+ // If we have the chat message then we can insert it to attachments
208
+ // This should work because chat message will always be created before the chat attachment
209
+ if (chatMessage) {
210
+ // Make sure the attachment isn't already attached to the message
211
+ const isNotAttached = chatMessage.record.attachments.find((attachment) => attachment.id === record.id) === undefined;
212
+ if (isNotAttached) {
213
+ chatMessage.record.attachments.pushObject(record);
214
+ // trigger event
215
+ this.trigger('chat.feed_updated', record, chatChannelRecord);
216
+ this.trigger('chat.attachment_created', record, chatChannelRecord);
217
+ }
218
+ }
219
+ }
220
+
221
+ insertChatReceiptFromSocket(chatChannelRecord, data) {
222
+ // normalize and create record
223
+ const normalized = this.store.normalize('chat-receipt', data);
224
+ const record = this.store.push(normalized);
225
+
226
+ // Find the chat message the record belongs to in the feed
227
+ const chatMessage = chatChannelRecord.feed.find((item) => {
228
+ return item.type === 'message' && item.record.id === record.chat_message_uuid;
229
+ });
230
+
231
+ // If we have the chat message then we can insert it to receipts
232
+ // This should work because chat message will always be created before the chat receipt
233
+ if (chatMessage) {
234
+ // Make sure the receipt isn't already attached to the message
235
+ const isNotAttached = chatMessage.record.receipts.find((receipt) => receipt.id === record.id) === undefined;
236
+ if (isNotAttached) {
237
+ chatMessage.record.receipts.pushObject(record);
238
+ // trigger event
239
+ this.trigger('chat.receipt_created', record, chatChannelRecord);
240
+ }
241
+ }
242
+ }
243
+
244
+ @task *loadMessages(chatChannelRecord) {
245
+ const messages = yield this.store.query('chat-message', { chat_channel_uuid: chatChannelRecord.id });
246
+ chatChannelRecord.set('messages', messages);
247
+ return messages;
248
+ }
249
+
250
+ @task *loadChannels(options = {}) {
251
+ const params = options.params || {};
252
+ const channels = yield this.store.query('chat-channel', params);
253
+ if (isArray(channels)) {
254
+ this.channels = channels;
255
+ }
256
+
257
+ if (typeof options.withChannels === 'function') {
258
+ options.withChannels(channels);
259
+ }
260
+
261
+ return channels;
262
+ }
263
+ }
@@ -198,25 +198,29 @@ export default class CrudService extends Service {
198
198
 
199
199
  // set the model uri endpoint
200
200
  const modelEndpoint = dasherize(pluralize(modelName));
201
+ const exportParams = options.params ?? {};
201
202
 
202
203
  this.modalsManager.show('modals/export-form', {
203
204
  title: `Export ${pluralize(modelName)}`,
204
205
  acceptButtonText: 'Download',
205
206
  modalClass: 'modal-sm',
207
+ format: 'xlsx',
206
208
  formatOptions: ['csv', 'xlsx', 'xls', 'html', 'pdf'],
207
209
  setFormat: ({ target }) => {
208
210
  this.modalsManager.setOption('format', target.value || null);
209
211
  },
210
212
  confirm: (modal, done) => {
211
- const format = modal.getOption('format') || 'xlsx';
213
+ const format = modal.getOption('format') ?? 'xlsx';
212
214
  modal.startLoading();
213
215
  return this.fetch
214
216
  .download(
215
217
  `${modelEndpoint}/export`,
216
218
  {
217
219
  format,
220
+ ...exportParams,
218
221
  },
219
222
  {
223
+ method: 'POST',
220
224
  fileName: `${modelEndpoint}-${formatDate(new Date(), 'yyyy-MM-dd-HH:mm')}.${format}`,
221
225
  }
222
226
  )
@@ -15,6 +15,7 @@ import corslite from '../utils/corslite';
15
15
  import getMimeType from '../utils/get-mime-type';
16
16
  import download from '../utils/download';
17
17
  import getUserOptions from '../utils/get-user-options';
18
+ import isEmptyObject from '../utils/is-empty-object';
18
19
  import fetch from 'fetch';
19
20
 
20
21
  if (isBlank(config.API.host)) {
@@ -339,7 +340,7 @@ export default class FetchService extends Service {
339
340
  return this.cachedGet(...arguments);
340
341
  }
341
342
 
342
- const urlParams = !isBlank(query) ? new URLSearchParams(query).toString() : '';
343
+ const urlParams = !isEmptyObject(query) ? new URLSearchParams(query).toString() : '';
343
344
 
344
345
  return this.request(`${path}${urlParams ? '?' + urlParams : ''}`, 'GET', {}, options);
345
346
  }
@@ -506,7 +507,7 @@ export default class FetchService extends Service {
506
507
  let version = options?.version ?? 'v1';
507
508
  let host = options?.host ?? `https://${options?.subdomain ?? 'routing'}.fleetbase.io`;
508
509
  let route = coordinates.map((coords) => coords.join(',')).join(';');
509
- let params = !isBlank(query) ? new URLSearchParams(query).toString() : '';
510
+ let params = !isEmptyObject(query) ? new URLSearchParams(query).toString() : '';
510
511
  let path = `${host}/${service}/${version}/${profile}/${route}`;
511
512
  let url = `${path}${params ? '?' + params : ''}`;
512
513
 
@@ -598,13 +599,25 @@ export default class FetchService extends Service {
598
599
  */
599
600
  download(path, query = {}, options = {}) {
600
601
  const headers = Object.assign(this.getHeaders(), options.headers ?? {});
602
+ const method = options.method ?? 'GET';
603
+ const credentials = options.credentials ?? this.credentials;
604
+ const baseUrl = `${options.host || this.host}/${options.namespace || this.namespace}`;
605
+ const isReadOnlyRequest = ['GET', 'HEAD'].includes(method.toUpperCase());
606
+ const params = isReadOnlyRequest && !isEmptyObject(query) ? `?${new URLSearchParams(query).toString()}` : '';
607
+ const body = !isReadOnlyRequest ? JSON.stringify(query) : {};
608
+ const fetchOptions = {
609
+ method,
610
+ credentials,
611
+ headers,
612
+ };
613
+
614
+ // Only supply body to fetch if not GET or HEAD request
615
+ if (!isReadOnlyRequest) {
616
+ fetchOptions.body = body;
617
+ }
601
618
 
602
619
  return new Promise((resolve, reject) => {
603
- return fetch(`${options.host || this.host}/${options.namespace || this.namespace}/${path}?${!isBlank(query) ? new URLSearchParams(query).toString() : ''}`, {
604
- method: 'GET',
605
- credentials: options.credentials || this.credentials,
606
- headers,
607
- })
620
+ return fetch(`${baseUrl}/${path}${params}`, fetchOptions)
608
621
  .then((response) => {
609
622
  options.fileName = this.getFilenameFromResponse(response, options.fileName);
610
623
  options.mimeType = this.getMimeTypeFromResponse(response, options.mimeType);
@@ -75,9 +75,10 @@ export default class LoaderService extends Service {
75
75
  }
76
76
 
77
77
  const loadingMessage = typeof options.loadingMessage === 'string' ? options.loadingMessage : 'Loading...';
78
- const opacity = typeof options.opacity === 'number' ? options.opacity : 0.1;
78
+ const opacity = typeof options.opacity === 'number' ? options.opacity : 0;
79
79
  const isDarkMode = document.body.dataset.theme ? document.body.dataset.theme === 'dark' : true;
80
80
  const preserveTargetPosition = options.preserveTargetPosition === true;
81
+ const loaderContainerClass = options.loaderContainerClass ?? '';
81
82
 
82
83
  if (!preserveTargetPosition) {
83
84
  target.style.position = 'relative';
@@ -86,7 +87,7 @@ export default class LoaderService extends Service {
86
87
  let loader = document.createElement('div');
87
88
  loader.classList.add('overloader');
88
89
  loader.style.backgroundColor = isDarkMode ? `rgba(128, 128, 128, ${opacity})` : `rgba(249, 250, 251, ${opacity})`;
89
- loader.innerHTML = `<div class="flex items-center justify-center text-center">
90
+ loader.innerHTML = `<div class="loader-container flex items-center justify-center text-center ${loaderContainerClass}">
90
91
  <div>
91
92
  <svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" role="img" focusable="false" aria-hidden="true" data-icon="spinner-third" data-prefix="fad" id="ember240" class="svg-inline--fa fa-spinner-third fa-w-16 fa-spin ember-view text-sky-500 fa-spin-800ms mr-3"><g class="fa-group"><path class="fa-secondary" fill="currentColor" d="M478.71 364.58zm-22 6.11l-27.83-15.9a15.92 15.92 0 0 1-6.94-19.2A184 184 0 1 1 256 72c5.89 0 11.71.29 17.46.83-.74-.07-1.48-.15-2.23-.21-8.49-.69-15.23-7.31-15.23-15.83v-32a16 16 0 0 1 15.34-16C266.24 8.46 261.18 8 256 8 119 8 8 119 8 256s111 248 248 248c98 0 182.42-56.95 222.71-139.42-4.13 7.86-14.23 10.55-22 6.11z"></path><path class="fa-primary" fill="currentColor" d="M271.23 72.62c-8.49-.69-15.23-7.31-15.23-15.83V24.73c0-9.11 7.67-16.78 16.77-16.17C401.92 17.18 504 124.67 504 256a246 246 0 0 1-25 108.24c-4 8.17-14.37 11-22.26 6.45l-27.84-15.9c-7.41-4.23-9.83-13.35-6.2-21.07A182.53 182.53 0 0 0 440 256c0-96.49-74.27-175.63-168.77-183.38z"></path></g>
92
93
  </svg>
@@ -1,6 +1,7 @@
1
1
  import Service from '@ember/service';
2
2
  import { tracked } from '@glimmer/tracking';
3
3
  import { isBlank } from '@ember/utils';
4
+ import { later } from '@ember/runloop';
4
5
  import toBoolean from '../utils/to-boolean';
5
6
  import config from 'ember-get-config';
6
7
 
@@ -29,22 +30,28 @@ export default class SocketService extends Service {
29
30
  }
30
31
 
31
32
  async listen(channelId, callback) {
32
- const channel = this.socket.subscribe(channelId);
33
-
34
- // Track channel
35
- this.channels.pushObject(channel);
36
-
37
- // Listen to channel for events
38
- await channel.listener('subscribe').once();
39
-
40
- // Listen for channel subscription
41
- (async () => {
42
- for await (let output of channel) {
43
- if (typeof callback === 'function') {
44
- callback(output);
45
- }
46
- }
47
- })();
33
+ later(
34
+ this,
35
+ async () => {
36
+ const channel = this.socket.subscribe(channelId);
37
+
38
+ // Track channel
39
+ this.channels.pushObject(channel);
40
+
41
+ // Listen to channel for events
42
+ await channel.listener('subscribe').once();
43
+
44
+ // Listen for channel subscription
45
+ (async () => {
46
+ for await (let output of channel) {
47
+ if (typeof callback === 'function') {
48
+ callback(output);
49
+ }
50
+ }
51
+ })();
52
+ },
53
+ 300
54
+ );
48
55
  }
49
56
 
50
57
  closeChannels() {
@@ -993,7 +993,10 @@ export default class UniverseService extends Service.extend(Evented) {
993
993
  const index = this._getOption(options, 'index', 0);
994
994
  const onClick = this._getOption(options, 'onClick', null);
995
995
  const section = this._getOption(options, 'section', null);
996
+ const iconComponent = this._getOption(options, 'iconComponent', null);
997
+ const iconComponentOptions = this._getOption(options, 'iconComponentOptions', {});
996
998
  const iconSize = this._getOption(options, 'iconSize', null);
999
+ const iconPrefix = this._getOption(options, 'iconPrefix', null);
997
1000
  const iconClass = this._getOption(options, 'iconClass', null);
998
1001
  const itemClass = this._getOption(options, 'class', null);
999
1002
  const inlineClass = this._getOption(options, 'inlineClass', null);
@@ -1024,7 +1027,10 @@ export default class UniverseService extends Service.extend(Evented) {
1024
1027
  index,
1025
1028
  section,
1026
1029
  onClick,
1030
+ iconComponent,
1031
+ iconComponentOptions,
1027
1032
  iconSize,
1033
+ iconPrefix,
1028
1034
  iconClass,
1029
1035
  class: itemClass,
1030
1036
  inlineClass,
@@ -91,10 +91,11 @@ export default function download(data, strFileName, strMimeType) {
91
91
  anchor.className = 'download-js-link';
92
92
  anchor.innerHTML = 'downloading...';
93
93
  anchor.style.display = 'none';
94
- anchor.addEventListener('click', function (e) {
94
+ function handleClick(e) {
95
95
  e.stopPropagation();
96
- this.removeEventListener('click', arguments.callee);
97
- });
96
+ anchor.removeEventListener('click', handleClick);
97
+ }
98
+ anchor.addEventListener('click', handleClick);
98
99
  document.body.appendChild(anchor);
99
100
  later(
100
101
  this,
@@ -0,0 +1,3 @@
1
+ export default function isEmptyObject(obj) {
2
+ return Object.keys(obj).length === 0 && obj.constructor === Object;
3
+ }
@@ -0,0 +1 @@
1
+ export { default } from '@fleetbase/ember-core/services/chat';
@@ -0,0 +1 @@
1
+ export { default } from '@fleetbase/ember-core/utils/is-empty-object';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fleetbase/ember-core",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "description": "Provides all the core services, decorators and utilities for building a Fleetbase extension for the Console.",
5
5
  "keywords": [
6
6
  "fleetbase-core",