-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathutils.ts
More file actions
510 lines (447 loc) · 15.8 KB
/
utils.ts
File metadata and controls
510 lines (447 loc) · 15.8 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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// get the first key of given object that points to given value
import { Ref } from 'vue';
import { Dayjs } from 'dayjs';
import { i18nType } from '@/composables/i18n';
import {
CustomEventData,
Coloring,
EventPopup,
HTMLElementEvent,
CalendarEvent,
PydanticException,
User,
Alert,
ListResponse,
Availability,
Appointment,
} from '@/models';
import { BookingStatus } from './definitions';
/**
* Convert ISO weekday (1=Monday, 7=Sunday) to dayjs weekday (0=Sunday, 1=Monday, etc.)
* @param isoDay - ISO weekday number (1-7)
* @returns dayjs weekday number (0-6)
*/
export const isoWeekdayToDayjs = (isoDay: number): number => {
return isoDay === 7 ? 0 : isoDay;
};
/**
* Calculate the start of week for a given date based on user's preferred start of week.
* @param date - Dayjs date object
* @param startOfWeekIso - ISO weekday format: 1=Monday, 2=Tuesday, ..., 7=Sunday
* @returns Dayjs object representing the start of the week
*/
export const getStartOfWeek = (date: Dayjs, startOfWeekIso: number): Dayjs => {
// Convert ISO format (1=Monday, 7=Sunday) to dayjs format (0=Sunday, 1=Monday)
const startOfWeekDayjs = isoWeekdayToDayjs(startOfWeekIso);
// Get current day of week (0=Sunday, 1=Monday, ..., 6=Saturday)
const currentDay = date.day();
// Calculate the difference to get to the start of week
const diff = (currentDay - startOfWeekDayjs + 7) % 7;
return date.subtract(diff, 'day').startOf('day');
};
/**
* Calculate the end of week for a given date based on user's preferred start of week.
* @param date - Dayjs date object
* @param startOfWeekIso - ISO weekday format: 1=Monday, 2=Tuesday, ..., 7=Sunday
* @returns Dayjs object representing the end of the week
*/
export const getEndOfWeek = (date: Dayjs, startOfWeekIso: number): Dayjs => {
// Get the start of week and add 6 days to get the end of week
const weekStart = getStartOfWeek(date, startOfWeekIso);
return weekStart.add(6, 'day').endOf('day');
};
/**
* Lowercases the first character of a string
*/
export const lcFirst = (s: string): string => {
if (typeof s !== 'string' || !s) {
return '';
}
return s[0].toLowerCase() + s.slice(1);
};
// Rotate the elements of an array for <n> steps. Works in both directions (n can be negative).
export const arrayRotate = <T>(a: T[], n: number): T[] => {
a.push(...a.splice(0, (-n % a.length + a.length) % a.length));
return a;
}
// Convert a numeric enum to an object for key-value iteration
export const enumToObject = (e: object): { [key in string]: number } => {
const o = {};
Object.keys(e).filter((v) => isNaN(Number(v))).forEach((k) => o[lcFirst(k)] = e[k]);
return o;
};
// find a key by a given value and return it
export const keyByValue = (o: object, v: number|string, isEnum = false): number|string => {
const e = isEnum ? enumToObject(o) : o;
return Object.keys(e).find((k) => e[k] === v);
};
// create event color for border and background, inherited from calendar color attribute
export const eventColor = (event: CustomEventData, placeholder: boolean): Coloring => {
const color = {
border: null,
background: null,
};
// color appointment slots
if (!placeholder) {
color.border = event.calendar_color;
color.background = event.calendar_color;
// keep solid background only for slots with attendee
if (!event.attendee && !event.remote) {
color.background += '22';
}
}
return color;
};
// create initials from given name
export const initials = (name: string): string => {
if (name) {
const parts = name.toUpperCase().split(' ');
return parts.length > 1
? parts[0][0] + parts.at(-1)[0]
: name[0];
}
return '';
};
// file download
export const download = (data: BlobPart, filename: string, contenttype: string = 'text/plain'): void => {
const a = document.createElement('a');
const file = new Blob([data], { type: `${contenttype};charset=UTF-8`, endings: 'native' });
// TODO: use fetch or similar to programmatically trigger a download
const url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
};
// handle time format, return dayjs format string
// can be either set by the user (local storage) or detected from system.
// This functions works independent from Pinia stores so that
// it can be called even if stores are not initialized yet.
export const timeFormat = (): string => {
const fallbackFormat = import.meta.env?.VITE_DEFAULT_HOUR_FORMAT ?? 12;
const user = JSON.parse(localStorage?.getItem('tba/user') ?? '{}') as User;
let use12HourTime = null;
try {
use12HourTime = Intl.DateTimeFormat(window.navigator.language, { hour: 'numeric' }).resolvedOptions()?.hour12 ?? null;
} catch (_e: RangeError|any) {
// Catch any range error raised by invalid language/locale codes and pass
}
// `.hour12` is an optional value and can be undefined (we cast it as null.) So default to our env value, and if not null use it.
let detected = fallbackFormat;
if (use12HourTime !== null) {
detected = use12HourTime ? 12 : 24;
}
const format = Number(user.settings?.timeFormat ?? detected);
return format === 24 ? 'HH:mm' : 'hh:mma';
};
// Check if we already have a local user preferred language
// Otherwise just use the navigators language.
// This functions works independent from Pinia stores so that
// it can be called even if stores are not initialized yet.
export const defaultLocale = () => {
const user = JSON.parse(localStorage?.getItem('tba/user') ?? '{}') as User;
return user?.settings?.language ?? navigator.language.split('-')[0];
};
// event popup handling
export const initialEventPopupData: EventPopup = {
event: null,
display: 'none',
top: 0,
left: 'initial',
position: 'right',
};
// calculate properties of event popup for given element and show popup
export const showEventPopup = (el: HTMLElementEvent, event: CalendarEvent, position: string = 'right'): EventPopup => {
const obj = { ...initialEventPopupData };
obj.event = event;
obj.display = 'block';
// Get viewport dimensions
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
// Estimate popup dimensions (based on EventPopup component)
const popupWidth = 384; // max-w-sm = 384px
const popupHeight = 120; // Estimated height based on content
const offset = 4; // Gap between trigger and popup
// Calculate trigger element position relative to viewport using getBoundingClientRect
// This works correctly with position: fixed on the popup
const triggerRect = el.target.getBoundingClientRect();
const triggerLeft = triggerRect.left;
const triggerRight = triggerRect.right;
const triggerTop = triggerRect.top;
const triggerCenterY = triggerTop + triggerRect.height / 2;
const triggerCenterX = triggerLeft + triggerRect.width / 2;
// Determine optimal position based on available space
let optimalPosition = position;
if (position === 'right' || !position) {
// Check if popup would overflow right edge
if (triggerRight + popupWidth + offset > viewportWidth) {
// Check if left position would work (popup will be positioned at trigger's left edge)
if (triggerLeft >= popupWidth + offset) {
optimalPosition = 'left';
} else {
// Fall back to top position
optimalPosition = 'top';
}
}
} else if (position === 'left') {
// Check if popup would overflow left edge (popup will be positioned at trigger's left edge)
if (triggerLeft < popupWidth + offset) {
// Check if right position would work
if (triggerRight + popupWidth + offset <= viewportWidth) {
optimalPosition = 'right';
} else {
// Fall back to top position
optimalPosition = 'top';
}
}
} else if (position === 'top') {
// Check if popup would overflow top edge
if (triggerTop - popupHeight - offset < 0) {
// Try right position first
if (triggerRight + popupWidth + offset <= viewportWidth) {
optimalPosition = 'right';
} else if (triggerLeft - popupWidth - offset >= 0) {
optimalPosition = 'left';
}
}
}
// Additional check: if popup would overflow bottom edge, try to adjust
if (triggerTop + popupHeight + offset > viewportHeight) {
// If we're positioned to the right or left and would overflow bottom, try top
if (optimalPosition === 'right' || optimalPosition === 'left') {
if (triggerTop - popupHeight - offset >= 0) {
optimalPosition = 'top';
}
}
}
// Set position based on optimal position using viewport-relative coordinates
// These work correctly with position: fixed on the popup
if (optimalPosition === 'right') {
obj.top = `${triggerCenterY}px`;
obj.left = `${triggerRight + offset}px`;
} else if (optimalPosition === 'left') {
obj.top = `${triggerCenterY}px`;
obj.left = `${triggerLeft - offset}px`;
} else if (optimalPosition === 'top') {
obj.top = `${triggerTop - offset}px`;
obj.left = `${triggerCenterX}px`;
}
// Store the optimal position for the component to use
obj.position = optimalPosition;
return obj;
};
/**
* via: https://stackoverflow.com/a/11868398
*/
export const getAccessibleColor = (hexcolor: string): string => {
const r = parseInt(hexcolor.substring(1, 3), 16);
const g = parseInt(hexcolor.substring(3, 5), 16);
const b = parseInt(hexcolor.substring(5, 7), 16);
const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
return (yiq >= 160) ? 'black' : 'white';
};
/**
* Helper function to parse hex color to RGB values
* @param hexcolor - Hex color string (with or without #)
* @returns Object with r, g, b values or null if invalid
*/
const parseHexToRgb = (hexcolor: string): { r: number, g: number, b: number } | null => {
if (!hexcolor) return null;
// Remove # if present
const hex = hexcolor.replace('#', '');
// Validate hex format (6 characters)
if (hex.length !== 6) return null;
// Parse r, g, b values
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
return { r, g, b };
};
/**
* Darken a hex color by a given percentage
* @param hexcolor - Hex color string (with or without #)
* @param percent - Amount to darken (0-100, default 20)
*/
export const darkenColor = (hexcolor: string, percent: number = 20): string => {
const rgb = parseHexToRgb(hexcolor);
if (!rgb) return hexcolor;
// Calculate darkened values
const darkenFactor = (100 - percent) / 100;
const newR = Math.round(rgb.r * darkenFactor);
const newG = Math.round(rgb.g * darkenFactor);
const newB = Math.round(rgb.b * darkenFactor);
// Convert back to hex and ensure two digits
const toHex = (n: number) => n.toString(16).padStart(2, '0');
return `#${toHex(newR)}${toHex(newG)}${toHex(newB)}`;
};
/**
* Convert a hex color to rgba with specified alpha
* @param hexcolor - Hex color string (with or without #)
* @param alpha - Alpha value (0-1)
*/
export const hexToRgba = (hexcolor: string, alpha: number = 1): string => {
const rgb = parseHexToRgb(hexcolor);
if (!rgb) return hexcolor;
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`;
};
/**
* Handles Pydantic errors, returns a form-level error message
* or null if the error has to do with individual fields
*/
export const handleFormError = (i18n: i18nType, formRef: Ref, errObj: PydanticException): Alert => {
const unknownError = i18n('error.somethingWentWrong');
if (!errObj) {
return { title: unknownError };
}
const fields = formRef.value.elements as HTMLFormControlsCollection;
const { detail } = errObj;
if (Array.isArray(detail)) {
detail.forEach((err) => {
const name = err?.loc[1];
if (name) {
// Could either be in the context, or as a general message
const msg = err?.ctx?.reason ?? err.msg;
fields[name].setCustomValidity(msg);
}
});
} else if (typeof detail === 'string') { // HttpException errors are just strings
return { title: detail };
} else {
return {
title: detail?.message ?? unknownError,
details: detail?.reason,
};
}
// Finally report it!
formRef.value.reportValidity();
return null;
};
/**
* Clears any existing form errors
* @param formRef
*/
export const clearFormErrors = (formRef: Ref) => {
const { elements } = formRef.value;
// HTMLCollection doesn't support .forEach lol
for (const element of elements) {
element.setCustomValidity('');
}
};
export const sleep = async (timeMs: number) => new Promise((resolve) => { window.setTimeout(resolve, timeMs); });
/**
* Retrieve all the items from a ListResponse route staggered by 250ms per page.
* @param requestFn
* @param perPage
* @param pageError
*/
export const staggerRetrieve = async (requestFn: any, perPage: number, pageError?: Ref<Alert>) => {
// Load the first page to get the total amount of pages
const response: ListResponse = await requestFn({
page: 1,
per_page: perPage,
});
const { data } = response;
if (!data.value?.page_meta) {
pageError.value = {
title: 'Remote request error',
details: 'There was a problem loading the list. Please try again.',
};
return null;
}
const { page, total_pages: totalPages } = data.value.page_meta;
const { items } = data.value;
let itemList = [...items];
const promises = [];
// Queue up the remainder of the pages as promises
for (let i = page + 1; i < totalPages + 1; i += 1) {
promises.push((async () => {
// Stagger calls to avoid overloading the db
await sleep(250 * i);
return requestFn({
page: i,
per_page: perPage,
});
})());
}
// Execute them all at once
const promiseResponses = await Promise.all(promises);
promiseResponses.forEach((_response) => {
const { data: _data } = _response;
// We don't have page info in this context, so just display a generic error...
if (!_data.value?.items) {
pageError.value = {
title: 'Remote request error',
details: 'There was a problem loading some items. Please refresh and try again.',
};
return;
}
itemList = itemList.concat(_data.value?.items ?? []);
});
return itemList;
};
/**
* Calculate number of minutes from formatted time string.
* @param formattedTime A string of format HH:MM
*/
export const hhmmToMinutes = (formattedTime: string | Dayjs): number => {
if (typeof formattedTime === 'object') {
formattedTime = formattedTime.format('HH:mm');
}
const [hours, minutes] = formattedTime.split(':');
return (Number(hours) * 60 + Number(minutes));
};
/**
* Calculate number of minutes from formatted time string.
* @param formattedTime A string of format HH:MM
*/
export const minutesToHhmm = (minutes: number): string => {
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
};
/**
* Compare two availabilities by their start time
*/
export const compareAvailabilityStart = (a: Availability, b: Availability) => {
return hhmmToMinutes(a.start_time) - hhmmToMinutes(b.start_time)
};
/**
* Kill all references to arrays or objects within the given entity and return a deep clone
*/
export const deepClone = (entity: any): any => {
return JSON.parse(JSON.stringify(entity));
};
/**
* Return true if the Appointment is not confirmed by the owner yet
*/
export const isUnconfirmed = (a: Appointment): boolean => {
return a.slots[0].booking_status === BookingStatus.Requested;
};
export default {
keyByValue,
arrayRotate,
eventColor,
initials,
download,
timeFormat,
defaultLocale,
initialEventPopupData,
showEventPopup,
getAccessibleColor,
darkenColor,
hexToRgba,
handleFormError,
sleep,
hhmmToMinutes,
minutesToHhmm,
compareAvailabilityStart,
deepClone,
isUnconfirmed,
isoWeekdayToDayjs,
getStartOfWeek,
getEndOfWeek,
};