@qlibs/utils 1.0.2

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.
package/README.md ADDED
@@ -0,0 +1,98 @@
1
+ ## usePromiseAllData
2
+ ```
3
+ const {
4
+ isLoadingPromiseAllData: isLoading,
5
+ promiseAllData,
6
+ fetchPromiseAllData,
7
+ } = usePromiseAllData<IPromiseAllData>({
8
+ httpRequest: httpRequest as any,
9
+ endpoints: [
10
+ {
11
+ endpoint: '/users/' + params.userId,
12
+ returnKey: 'user',
13
+ },
14
+ {
15
+ endpoint: selectedProgram?.programId
16
+ ? `evaluation-calculator/${selectedProgram?.programId}/${params.userId}`
17
+ : `evaluation-calculator/${params.userId}`,
18
+ returnKey: 'competencies',
19
+ },
20
+ ],
21
+ });
22
+
23
+ useEffect(() => {
24
+ fetchPromiseAllData();
25
+ }, []);
26
+ ```
27
+
28
+ ## useAdditionalDataForList
29
+ ```
30
+ const { isLoadingAdditionalData, additionalData } =
31
+ useAdditionalDataForList<IAdditionalData>({
32
+ httpRequest: httpRequest as any,
33
+ id: 'attendanceId',
34
+ data,
35
+ injects: [
36
+ {
37
+ injectedId: 'userId',
38
+ endpoint: '/users?filterStatus=active&roles=talent&userIds=',
39
+ endpointId: 'userId',
40
+ returnKey: 'user',
41
+ },
42
+ props.type === 'EVENT' ? {
43
+ injectedId: 'eventId',
44
+ endpoint: '/event?eventIds=',
45
+ endpointId: 'eventId',
46
+ returnKey: 'event',
47
+ } : {injectedId: '', endpoint: '', returnKey: '', endpointId: ''},
48
+ ].filter(item => item?.injectedId),
49
+ });
50
+ ```
51
+
52
+ ## TRACK ME
53
+ ### How to use TrackMe
54
+ ```
55
+ const {insertData} = useTrackData();
56
+ const location = useLocation()
57
+
58
+ <TrackMe
59
+ appName='QLIBS'
60
+ userId='QLIBS_userId'
61
+ userData={{name: 'QLIBS_user_name'}}
62
+ processUpload={(
63
+ activities: IActivity[],
64
+ onSuccess: (ids: number[]) => void
65
+ ) => {
66
+ console.info('before onSuccess activities', activities);
67
+ onSuccess(activities.map(item => (item as any).activityId));
68
+ }}
69
+ location={location}
70
+ autoUploadConfig={{
71
+ intervalInMs: 5000,
72
+ }}
73
+ isDemo={true}
74
+ />
75
+ ```
76
+
77
+ ```
78
+ useTrackerIndexedDB({
79
+ appName: "PROJECT_NAME",
80
+ userId: user.userId,
81
+ userData: user,
82
+ processUpload: (activities: IActivity[], onSuccess: (ids: number[]) => void) => {
83
+ httpRequest
84
+ .post(process.env.REACT_APP_API_URL_TRACKME || '', { bulk: activities })
85
+ .then((res: any) => {
86
+ onSuccess((res.data.payload || []).map((item: any) => item.activityId));
87
+ })
88
+ .catch((err) => {
89
+ message.error(getErrorMessage(err));
90
+ });
91
+ },
92
+ });
93
+ ```
94
+
95
+ ### How to don't track me
96
+ ```
97
+ <button data-trackme="false">WILL NOT TRACKED</button>
98
+ ```
@@ -0,0 +1,2 @@
1
+ export * from "./utils/index";
2
+ export * from "./types/index";
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./utils/index"), exports);
18
+ __exportStar(require("./types/index"), exports);
@@ -0,0 +1,33 @@
1
+ export type ConfigState = {
2
+ sidebarCollapsed: boolean;
3
+ counterBatch: number;
4
+ };
5
+ export type ConfigValue = {
6
+ configId: string;
7
+ key: string;
8
+ value: string;
9
+ createdAt: string;
10
+ updatedAt: string;
11
+ };
12
+ export interface BaseResponseProps<T> {
13
+ code: string;
14
+ message: string;
15
+ payload: T;
16
+ }
17
+ export interface BaseResponsePaginationProps<T> {
18
+ code: string;
19
+ message: string;
20
+ payload: {
21
+ count: number;
22
+ prev: string;
23
+ next: string;
24
+ results: Array<T>;
25
+ };
26
+ }
27
+ export interface DefaultQuery {
28
+ limit?: number;
29
+ offset?: number;
30
+ }
31
+ export declare const initialConfig: ConfigState;
32
+ export type ResponseConfig = BaseResponseProps<ConfigValue>;
33
+ export type ResponseConfigPagination = BaseResponsePaginationProps<ConfigValue>;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initialConfig = void 0;
4
+ exports.initialConfig = {
5
+ sidebarCollapsed: false,
6
+ counterBatch: 0,
7
+ };
@@ -0,0 +1 @@
1
+ export * from './config.type';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./config.type"), exports);
@@ -0,0 +1,3 @@
1
+ export declare function saveToken(token: string): void;
2
+ export declare function getToken(): string;
3
+ export declare function removeToken(): void;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.saveToken = saveToken;
4
+ exports.getToken = getToken;
5
+ exports.removeToken = removeToken;
6
+ const APP_AUTH_TOKEN = 'APP_AUTH_TOKEN';
7
+ function saveToken(token) {
8
+ return localStorage.setItem(APP_AUTH_TOKEN, token);
9
+ }
10
+ function getToken() {
11
+ return localStorage.getItem(APP_AUTH_TOKEN);
12
+ }
13
+ function removeToken() {
14
+ return localStorage.removeItem(APP_AUTH_TOKEN);
15
+ }
@@ -0,0 +1,19 @@
1
+ export declare const thisYear: number;
2
+ export declare const formatDate: (date: any, dateFormat?: string) => string;
3
+ export declare const formatUrlParams: (value: string) => string;
4
+ export declare const SHORT_DAYS_IN_WEEK: string[];
5
+ export declare const LIST_MONTH: string[];
6
+ export declare const LIST_MONTH_IN: string[];
7
+ export declare const LIST_MONTH_SHORT: string[];
8
+ export declare function getDateString(date: Date | string | undefined, format?: 'long' | 'short', formatMonth?: 'long' | 'short'): string;
9
+ export declare function getDateTimeString(date: Date | string | undefined, format?: 'long' | 'short', formatMonth?: 'long' | 'short', returning?: {
10
+ year?: boolean;
11
+ month?: boolean;
12
+ date?: boolean;
13
+ time?: boolean;
14
+ }): string;
15
+ export declare function getDateRangeString(startAt: Date | string | undefined, endAt: Date | string | undefined, format?: 'long' | 'short', formatMonth?: 'long' | 'short'): string;
16
+ export declare function getDateTimeRangeString(startAt: Date | string | undefined, endAt: Date | string | undefined, format?: 'long' | 'short', formatMonth?: 'long' | 'short'): string;
17
+ export declare const toAcceptableApiFormat: (s?: string) => string;
18
+ export declare const getAge: (dateString?: string, base?: string) => number;
19
+ export declare const evnDate: (date: string) => string;
@@ -0,0 +1,286 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.evnDate = exports.getAge = exports.toAcceptableApiFormat = exports.LIST_MONTH_SHORT = exports.LIST_MONTH_IN = exports.LIST_MONTH = exports.SHORT_DAYS_IN_WEEK = exports.formatUrlParams = exports.formatDate = exports.thisYear = void 0;
7
+ exports.getDateString = getDateString;
8
+ exports.getDateTimeString = getDateTimeString;
9
+ exports.getDateRangeString = getDateRangeString;
10
+ exports.getDateTimeRangeString = getDateTimeRangeString;
11
+ const moment_1 = __importDefault(require("moment"));
12
+ const date = new Date();
13
+ exports.thisYear = date.getFullYear();
14
+ const formatDate = (date, dateFormat) => {
15
+ if (!dateFormat) {
16
+ dateFormat = 'DD MMMM YYYY';
17
+ }
18
+ if (date) {
19
+ const formated = (0, moment_1.default)(new Date(date)).format(dateFormat);
20
+ return formated;
21
+ }
22
+ return '';
23
+ };
24
+ exports.formatDate = formatDate;
25
+ const formatUrlParams = (value) => {
26
+ const param = value.split(' ').join('-').toLowerCase();
27
+ return param;
28
+ };
29
+ exports.formatUrlParams = formatUrlParams;
30
+ exports.SHORT_DAYS_IN_WEEK = [
31
+ 'Sun',
32
+ 'Mon',
33
+ 'Tue',
34
+ 'Wed',
35
+ 'Thu',
36
+ 'Fri',
37
+ 'Sat',
38
+ ];
39
+ exports.LIST_MONTH = [
40
+ 'January',
41
+ 'February',
42
+ 'March',
43
+ 'April',
44
+ 'May',
45
+ 'June',
46
+ 'July',
47
+ 'August',
48
+ 'September',
49
+ 'October',
50
+ 'November',
51
+ 'December',
52
+ ];
53
+ exports.LIST_MONTH_IN = [
54
+ 'Januari',
55
+ 'Februari',
56
+ 'Maret',
57
+ 'April',
58
+ 'Mei',
59
+ 'Juni',
60
+ 'Juli',
61
+ 'Agustus',
62
+ 'September',
63
+ 'October',
64
+ 'November',
65
+ 'Desember',
66
+ ];
67
+ exports.LIST_MONTH_SHORT = [
68
+ 'Jan',
69
+ 'Feb',
70
+ 'Mar',
71
+ 'Apr',
72
+ 'May',
73
+ 'Jun',
74
+ 'Jul',
75
+ 'Aug',
76
+ 'Sept',
77
+ 'Oct',
78
+ 'Nov',
79
+ 'Dec',
80
+ ];
81
+ const LIST_DAY = [
82
+ 'Minggu',
83
+ 'Senin',
84
+ 'Selasa',
85
+ 'Rabu',
86
+ 'Kamis',
87
+ "Jum'at",
88
+ 'Sabtu',
89
+ ];
90
+ function getDateString(date, format = 'long', formatMonth = 'long') {
91
+ if (!date) {
92
+ return '-';
93
+ }
94
+ if (typeof date === 'string') {
95
+ date = new Date(date);
96
+ }
97
+ const dayText = LIST_DAY[date.getDay()];
98
+ const dateText = date.getDate();
99
+ const monthText = formatMonth === 'long'
100
+ ? exports.LIST_MONTH[date.getMonth()]
101
+ : exports.LIST_MONTH_SHORT[date.getMonth()];
102
+ const yearText = date.getFullYear();
103
+ if (format === 'short') {
104
+ return dateText + ' ' + monthText + ' ' + yearText;
105
+ }
106
+ else {
107
+ return dayText + ', ' + dateText + ' ' + monthText + ' ' + yearText;
108
+ }
109
+ }
110
+ function getDateTimeString(date, format = 'long', formatMonth = 'long', returning) {
111
+ if (!date) {
112
+ return '-';
113
+ }
114
+ if (typeof date === 'string') {
115
+ date = new Date(date);
116
+ }
117
+ let hours = date.getHours();
118
+ let hoursText = '';
119
+ if (hours < 10) {
120
+ hoursText = '0' + String(hours);
121
+ }
122
+ else {
123
+ hoursText = String(hours);
124
+ }
125
+ let minutes = date.getMinutes();
126
+ let minutesText = '';
127
+ if (minutes < 10) {
128
+ minutesText = '0' + String(minutes);
129
+ }
130
+ else {
131
+ minutesText = String(minutes);
132
+ }
133
+ const dayText = LIST_DAY[date.getDay()];
134
+ const dateText = date.getDate();
135
+ const monthText = formatMonth === 'long'
136
+ ? exports.LIST_MONTH[date.getMonth()]
137
+ : exports.LIST_MONTH_SHORT[date.getMonth()];
138
+ const yearText = date.getFullYear();
139
+ let dtString = [dateText, monthText, yearText, hoursText + ':' + minutesText];
140
+ if (returning) {
141
+ dtString = [];
142
+ if (returning.date) {
143
+ dtString.push(dateText);
144
+ }
145
+ if (returning.month) {
146
+ dtString.push(monthText);
147
+ }
148
+ if (returning.year) {
149
+ dtString.push(yearText);
150
+ }
151
+ if (returning.time) {
152
+ dtString.push(hoursText + ':' + minutesText);
153
+ }
154
+ }
155
+ if (format === 'long') {
156
+ dtString.unshift(dayText + ', ');
157
+ }
158
+ return dtString.join(' ');
159
+ }
160
+ function getDateRangeString(startAt, endAt, format = 'short', formatMonth = 'long') {
161
+ if (startAt && !endAt) {
162
+ return getDateString(startAt, format, formatMonth);
163
+ }
164
+ else if (!startAt && endAt) {
165
+ return getDateString(endAt, format, formatMonth);
166
+ }
167
+ else if (startAt &&
168
+ endAt &&
169
+ new Date(startAt).getTime() === new Date(endAt).getTime()) {
170
+ return getDateString(startAt, format, formatMonth);
171
+ }
172
+ else if (startAt && endAt) {
173
+ const dateStartAt = new Date(startAt);
174
+ const dateStartAtYear = dateStartAt.getFullYear();
175
+ const dateStartAtMonth = dateStartAt.getMonth();
176
+ const dateStartAtDate = dateStartAt.getDate();
177
+ const dateEndAt = new Date(endAt);
178
+ const dateEndAtYear = dateEndAt.getFullYear();
179
+ const dateEndAtMonth = dateEndAt.getMonth();
180
+ const dateEndAtDate = dateEndAt.getDate();
181
+ if (dateStartAtYear === dateEndAtYear) {
182
+ if (dateStartAtMonth === dateEndAtMonth) {
183
+ if (dateStartAtDate === dateEndAtDate) {
184
+ return getDateString(startAt, format, formatMonth);
185
+ }
186
+ else {
187
+ return (dateStartAtDate + ' - ' + getDateString(endAt, format, formatMonth));
188
+ }
189
+ }
190
+ else {
191
+ return (dateStartAtDate +
192
+ ' ' +
193
+ (formatMonth === 'long'
194
+ ? exports.LIST_MONTH[dateStartAtMonth]
195
+ : exports.LIST_MONTH_SHORT[dateStartAtMonth]) +
196
+ ' - ' +
197
+ getDateString(endAt, format, formatMonth));
198
+ }
199
+ }
200
+ return (getDateString(startAt, format, formatMonth) +
201
+ ' - ' +
202
+ getDateString(endAt, format, formatMonth));
203
+ }
204
+ else {
205
+ return '-';
206
+ }
207
+ }
208
+ function getDateTimeRangeString(startAt, endAt, format = 'short', formatMonth = 'long') {
209
+ if (startAt && !endAt) {
210
+ return getDateTimeString(startAt, format, formatMonth);
211
+ }
212
+ else if (!startAt && endAt) {
213
+ return getDateTimeString(endAt, format, formatMonth);
214
+ }
215
+ else if (startAt &&
216
+ endAt &&
217
+ new Date(startAt).getTime() === new Date(endAt).getTime()) {
218
+ return getDateTimeString(startAt, format, formatMonth);
219
+ }
220
+ else if (startAt && endAt) {
221
+ const dateStartAt = new Date(startAt);
222
+ const dateStartAtYear = dateStartAt.getFullYear();
223
+ const dateStartAtMonth = dateStartAt.getMonth();
224
+ const dateStartAtDate = dateStartAt.getDate();
225
+ const dateEndAt = new Date(endAt);
226
+ const dateEndAtYear = dateEndAt.getFullYear();
227
+ const dateEndAtMonth = dateEndAt.getMonth();
228
+ const dateEndAtDate = dateEndAt.getDate();
229
+ if (dateStartAtYear === dateEndAtYear) {
230
+ if (dateStartAtMonth === dateEndAtMonth) {
231
+ if (dateStartAtDate === dateEndAtDate) {
232
+ return (getDateTimeString(startAt, format, formatMonth, {
233
+ date: true,
234
+ month: true,
235
+ year: true,
236
+ }) +
237
+ ', ' +
238
+ getDateTimeString(startAt, format, formatMonth, { time: true }) +
239
+ '-' +
240
+ getDateTimeString(endAt, format, formatMonth, { time: true }));
241
+ }
242
+ else {
243
+ return (getDateTimeString(startAt, format, formatMonth) +
244
+ ' - ' +
245
+ getDateTimeString(endAt, format, formatMonth));
246
+ }
247
+ }
248
+ else {
249
+ return (getDateTimeString(startAt, format, formatMonth) +
250
+ ' - ' +
251
+ getDateTimeString(endAt, format, formatMonth));
252
+ }
253
+ }
254
+ return (getDateTimeString(startAt, format, formatMonth) +
255
+ ' - ' +
256
+ getDateTimeString(endAt, format, formatMonth));
257
+ }
258
+ else {
259
+ return '-';
260
+ }
261
+ }
262
+ const toAcceptableApiFormat = (s) => {
263
+ return s
264
+ ? new Date(s).toJSON().slice(0, 10).split('-').reverse().join('-')
265
+ : s;
266
+ };
267
+ exports.toAcceptableApiFormat = toAcceptableApiFormat;
268
+ const getAge = (dateString, base) => {
269
+ const baseDate = base ? new Date(base) : new Date();
270
+ const birthDate = dateString ? new Date(dateString) : new Date();
271
+ let age = baseDate.getFullYear() - birthDate.getFullYear();
272
+ const m = baseDate.getMonth() - birthDate.getMonth();
273
+ if (m < 0 || (m === 0 && baseDate.getDate() < birthDate.getDate())) {
274
+ age--;
275
+ }
276
+ return age;
277
+ };
278
+ exports.getAge = getAge;
279
+ const evnDate = (date) => {
280
+ const cleanDate = date.split(' ')[0];
281
+ return (0, moment_1.default)(cleanDate).format(cleanDate.split('-')[2] === cleanDate.split('-')[2] &&
282
+ cleanDate !== cleanDate
283
+ ? 'MMM D'
284
+ : 'MMM D YYYY');
285
+ };
286
+ exports.evnDate = evnDate;
@@ -0,0 +1,17 @@
1
+ export declare function getErrorMessage(err: any, config?: {
2
+ showFullErrorMessage?: boolean;
3
+ }): string;
4
+ export declare function getErrorCode(err: any): any;
5
+ export declare function getErrors(err: any): any;
6
+ export declare function getStandardError(err: any, config?: {
7
+ triggerFormValidation?: boolean;
8
+ formRef?: any;
9
+ showToast?: boolean;
10
+ toastFunction?: any;
11
+ showFullErrorMessage?: boolean;
12
+ }): {
13
+ message: string | null;
14
+ code: string | null;
15
+ errors: any[] | null;
16
+ };
17
+ export declare function handleFormValidation(errors: any[], formRef: any): void;
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getErrorMessage = getErrorMessage;
4
+ exports.getErrorCode = getErrorCode;
5
+ exports.getErrors = getErrors;
6
+ exports.getStandardError = getStandardError;
7
+ exports.handleFormValidation = handleFormValidation;
8
+ function getErrorMessage(err, config) {
9
+ let errMessage = 'Failed. Please try again.';
10
+ console.info('err', err);
11
+ if (err && typeof err === 'string') {
12
+ errMessage = err;
13
+ }
14
+ else if (err && err.response) {
15
+ if (err.response.data && err.response.data.message) {
16
+ errMessage = err.response.data.message;
17
+ errMessage = handleAdditionalErrorMessage(errMessage, err.response.data.errors);
18
+ }
19
+ else if (err.response.message) {
20
+ errMessage = err.response.message;
21
+ errMessage = handleAdditionalErrorMessage(errMessage, err.response.errors);
22
+ }
23
+ else {
24
+ errMessage = JSON.stringify(err);
25
+ }
26
+ }
27
+ else if (err && err.data) {
28
+ if (err.data && err.data.message) {
29
+ errMessage = err.data.message;
30
+ errMessage = handleAdditionalErrorMessage(errMessage, err.data.errors);
31
+ }
32
+ else {
33
+ errMessage = JSON.stringify(err);
34
+ }
35
+ }
36
+ else if (err.message) {
37
+ errMessage = err.message;
38
+ errMessage = handleAdditionalErrorMessage(errMessage, err.errors);
39
+ }
40
+ else if (err.statusText) {
41
+ errMessage = err.statusText;
42
+ }
43
+ else {
44
+ errMessage = JSON.stringify(err);
45
+ }
46
+ if (!(config === null || config === void 0 ? void 0 : config.showFullErrorMessage) && errMessage.length > 52) {
47
+ errMessage = errMessage.substring(0, 50) + '...';
48
+ }
49
+ return errMessage;
50
+ }
51
+ function handleAdditionalErrorMessage(originalMessage, errors) {
52
+ if (errors && errors.length > 0) {
53
+ return `${originalMessage} (${errors
54
+ .map((error) => error.message)
55
+ .join(', ')})`;
56
+ }
57
+ return originalMessage;
58
+ }
59
+ function getErrorCode(err) {
60
+ let errorCode;
61
+ console.info('err', err);
62
+ if (err && typeof err === 'string') {
63
+ errorCode = err;
64
+ }
65
+ else if (err && err.response) {
66
+ if (err.response.data && err.response.data.code) {
67
+ errorCode = err.response.data.code;
68
+ }
69
+ else if (err.response.code) {
70
+ errorCode = err.response.code;
71
+ }
72
+ else {
73
+ }
74
+ }
75
+ else if (err && err.data) {
76
+ if (err.data && err.data.message) {
77
+ }
78
+ else {
79
+ }
80
+ }
81
+ else if (err.message) {
82
+ }
83
+ else if (err.statusText) {
84
+ }
85
+ else {
86
+ }
87
+ return errorCode;
88
+ }
89
+ function getErrors(err) {
90
+ let errors = null;
91
+ console.info('err', err);
92
+ if (err && typeof err === 'string') {
93
+ }
94
+ else if (err && err.response) {
95
+ if (err.response.data && err.response.data.errors) {
96
+ errors = err.response.data.errors;
97
+ }
98
+ else if (err.response.errors) {
99
+ errors = err.response.errors;
100
+ }
101
+ }
102
+ else if (err && err.data) {
103
+ if (err.data && err.data.errors) {
104
+ errors = err.data.errors;
105
+ }
106
+ }
107
+ else if (err.errors) {
108
+ errors = err.errors;
109
+ }
110
+ return errors;
111
+ }
112
+ function getStandardError(err, config) {
113
+ const message = getErrorMessage(err, { showFullErrorMessage: config === null || config === void 0 ? void 0 : config.showFullErrorMessage });
114
+ const code = getErrorCode(err);
115
+ const errors = getErrors(err);
116
+ if (config === null || config === void 0 ? void 0 : config.triggerFormValidation) {
117
+ handleFormValidation(errors || [], config.formRef);
118
+ }
119
+ if ((config === null || config === void 0 ? void 0 : config.showToast) && (config === null || config === void 0 ? void 0 : config.toastFunction)) {
120
+ config.toastFunction.error(message);
121
+ }
122
+ return {
123
+ code,
124
+ message,
125
+ errors,
126
+ };
127
+ }
128
+ function handleFormValidation(errors, formRef) {
129
+ if (!formRef)
130
+ return;
131
+ if (!errors)
132
+ return;
133
+ if (errors.length === 0)
134
+ return;
135
+ const fields = [];
136
+ for (const error of errors) {
137
+ if (error.path && error.type === 'unique violation') {
138
+ fields.push({
139
+ name: error.path,
140
+ errors: [`${error.value} already exist`],
141
+ });
142
+ }
143
+ else if (error.path) {
144
+ fields.push({
145
+ name: error.path,
146
+ errors: [error.message],
147
+ });
148
+ }
149
+ }
150
+ if (fields) {
151
+ formRef.setFields(fields);
152
+ }
153
+ }
@@ -0,0 +1,6 @@
1
+ export type TypeRule = Array<"required" | "email" | "phoneNumber" | "letter-and-space" | "password" | "numeric" | "nik" | "subdomain">;
2
+ export declare function generateFormRules(formName: string, rules: TypeRule): Array<{
3
+ required?: boolean;
4
+ message: string;
5
+ pattern?: any;
6
+ }>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateFormRules = generateFormRules;
4
+ function generateFormRules(formName, rules) {
5
+ const formRules = [];
6
+ if (rules.includes("required")) {
7
+ formRules.push({
8
+ required: true,
9
+ message: `${formName} is required.`,
10
+ });
11
+ }
12
+ if (rules.includes("email")) {
13
+ formRules.push({
14
+ pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
15
+ message: `format ${formName} harus valid.`,
16
+ });
17
+ }
18
+ if (rules.includes("phoneNumber")) {
19
+ formRules.push({
20
+ pattern: /^[0-9+ -]+$/,
21
+ message: `${formName} hanya diisi angka.`,
22
+ });
23
+ }
24
+ if (rules.includes("letter-and-space")) {
25
+ formRules.push({
26
+ pattern: /^[a-zA-Z ']+$/,
27
+ message: `${formName} hanya diisi huruf.`,
28
+ });
29
+ }
30
+ if (rules.includes("password")) {
31
+ formRules.push({
32
+ pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?.,+-=/;:"<>&])[A-Za-z\d@$!%*#?.,+-=/;:"<>&]{8,}$/,
33
+ message: `${formName} minimum 8 karakter (huruf, angka and karakter spesial)`,
34
+ });
35
+ }
36
+ if (rules.includes("numeric")) {
37
+ formRules.push({
38
+ pattern: /^[0-9]+$/,
39
+ message: `${formName} hanya diisi angka.`,
40
+ });
41
+ }
42
+ if (rules.includes("nik")) {
43
+ formRules.push({
44
+ pattern: /^[0-9]{16}$/,
45
+ message: `${formName} harus terdiri dari 16 angka.`,
46
+ });
47
+ }
48
+ if (rules.includes("subdomain")) {
49
+ formRules.push({
50
+ pattern: /^[0-9a-zA-Z-]+$/,
51
+ message: `${formName} only contain alphabet, numeric and dash.`,
52
+ });
53
+ }
54
+ return formRules;
55
+ }
@@ -0,0 +1 @@
1
+ export declare function generateQueryString(params?: any): string;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateQueryString = generateQueryString;
4
+ function generateQueryString(params) {
5
+ if (!params)
6
+ return '';
7
+ const query = Object.keys(params)
8
+ .filter((key) => {
9
+ if (Array.isArray(params[key])) {
10
+ return params[key].length > 0;
11
+ }
12
+ else {
13
+ return !!params[key];
14
+ }
15
+ })
16
+ .map((key) => {
17
+ if (params[key]) {
18
+ return key + '=' + params[key];
19
+ }
20
+ return null;
21
+ })
22
+ .join('&');
23
+ return query && '?' + query;
24
+ }
@@ -0,0 +1,12 @@
1
+ export declare const getFileImageDimension: (file: string | Blob | any) => Promise<{
2
+ width: number;
3
+ height: number;
4
+ }>;
5
+ export declare function imageResize(file: File | Blob | any, maxWidth?: number, maxFileSize?: number, originalFileName?: string): Promise<File | Blob>;
6
+ export declare function isImageMoreThanXMB(file: File | Blob, maxFileSize: number): boolean;
7
+ export declare function bytesToMB(sizeInBytes: number): number;
8
+ export declare function isImage(file: File | Blob): any;
9
+ export declare const getBase64: (file: File) => Promise<string>;
10
+ export declare function fileListToBase64(fileList: any[]): Promise<string[]>;
11
+ export declare function getFile(newFile: any): any;
12
+ export declare function isPhotoDataOK(item: any): boolean;
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getBase64 = exports.getFileImageDimension = void 0;
7
+ exports.imageResize = imageResize;
8
+ exports.isImageMoreThanXMB = isImageMoreThanXMB;
9
+ exports.bytesToMB = bytesToMB;
10
+ exports.isImage = isImage;
11
+ exports.fileListToBase64 = fileListToBase64;
12
+ exports.getFile = getFile;
13
+ exports.isPhotoDataOK = isPhotoDataOK;
14
+ const image_blob_reduce_1 = __importDefault(require("image-blob-reduce"));
15
+ const pica_1 = __importDefault(require("pica"));
16
+ const getFileImageDimension = (file) => {
17
+ return new Promise(async (resolve) => {
18
+ var fr = new FileReader();
19
+ fr.onload = function () {
20
+ var img = new Image();
21
+ img.onload = function () {
22
+ resolve({
23
+ width: img.width,
24
+ height: img.height,
25
+ });
26
+ };
27
+ img.src = fr.result;
28
+ };
29
+ fr.readAsDataURL(file);
30
+ });
31
+ };
32
+ exports.getFileImageDimension = getFileImageDimension;
33
+ async function imageResize(file, maxWidth, maxFileSize, originalFileName) {
34
+ if (!maxWidth) {
35
+ maxWidth = 1000;
36
+ }
37
+ console.info('original file', file);
38
+ const pica = (0, pica_1.default)({ features: ['js', 'wasm', 'cib'] });
39
+ console.info('pica', pica);
40
+ const reduce = new image_blob_reduce_1.default({ pica });
41
+ console.info('reduce', reduce);
42
+ let res = await reduce.toBlob(file, {
43
+ max: maxWidth !== null && maxWidth !== void 0 ? maxWidth : 1000,
44
+ });
45
+ console.info('res', res);
46
+ const resFile = new File([res], file.name ||
47
+ file.name ||
48
+ originalFileName ||
49
+ 'compressed_image');
50
+ console.info('resFile', resFile);
51
+ console.info('resFile.type', resFile.type);
52
+ if (isImageMoreThanXMB(resFile, maxFileSize ? maxFileSize : 2)) {
53
+ console.info('resizing again... width: ' + (maxWidth - 100), resFile);
54
+ return imageResize(resFile, maxWidth - 100, maxFileSize, file.name || file.name || 'compressed_image');
55
+ }
56
+ return resFile;
57
+ }
58
+ function isImageMoreThanXMB(file, maxFileSize) {
59
+ console.info('isImageMoreThanXMB', file);
60
+ console.info('isImageMoreThanXMB - size', file.size);
61
+ console.info('isImageMoreThanXMB - maxFileSize', maxFileSize);
62
+ const res = (file.size || 0) / 1024 / 1024 > maxFileSize;
63
+ console.info('isImageMoreThanXMB - res', res);
64
+ return res;
65
+ }
66
+ function bytesToMB(sizeInBytes) {
67
+ return Math.ceil(sizeInBytes / 1024 / 1024);
68
+ }
69
+ function isImage(file) {
70
+ var _a, _b, _c, _d, _e, _f;
71
+ return (file.type === 'image/png' ||
72
+ file.type === 'image/jpeg' ||
73
+ ((_a = file.name) === null || _a === void 0 ? void 0 : _a.toLowerCase().endsWith('.png')) ||
74
+ ((_b = file.name) === null || _b === void 0 ? void 0 : _b.toLowerCase().endsWith('.jpg')) ||
75
+ ((_c = file.name) === null || _c === void 0 ? void 0 : _c.toLowerCase().endsWith('.jpeg')) ||
76
+ file.mimeType === 'image/png' ||
77
+ file.mimeType === 'image/jpeg' ||
78
+ ((_d = file.originalName) === null || _d === void 0 ? void 0 : _d.toLowerCase().endsWith('.png')) ||
79
+ ((_e = file.originalName) === null || _e === void 0 ? void 0 : _e.toLowerCase().endsWith('.jpg')) ||
80
+ ((_f = file.originalName) === null || _f === void 0 ? void 0 : _f.toLowerCase().endsWith('.jpeg')) ||
81
+ !!file.thumbUrl);
82
+ }
83
+ const getBase64 = (file) => new Promise((resolve, reject) => {
84
+ const reader = new FileReader();
85
+ reader.readAsDataURL(file);
86
+ reader.onload = () => resolve(reader.result);
87
+ reader.onerror = (error) => reject(error);
88
+ });
89
+ exports.getBase64 = getBase64;
90
+ async function fileListToBase64(fileList) {
91
+ const promises = [];
92
+ for (let i = 0; i < fileList.length; i++) {
93
+ const file = getFile(fileList[i]);
94
+ if (file) {
95
+ promises.push((0, exports.getBase64)(file));
96
+ }
97
+ else {
98
+ promises.push(new Promise((resolve) => {
99
+ resolve(fileList[i].url);
100
+ }));
101
+ }
102
+ }
103
+ return (await Promise.all(promises));
104
+ }
105
+ function getFile(newFile) {
106
+ if (isImage(newFile) && newFile.originFileObj) {
107
+ return newFile.originFileObj;
108
+ }
109
+ else {
110
+ return null;
111
+ }
112
+ }
113
+ function isPhotoDataOK(item) {
114
+ if (typeof item === 'object') {
115
+ if (item.error) {
116
+ return false;
117
+ }
118
+ else {
119
+ return true;
120
+ }
121
+ }
122
+ else {
123
+ return false;
124
+ }
125
+ }
@@ -0,0 +1,11 @@
1
+ export * from './auth';
2
+ export * from './datetime';
3
+ export * from './errorHandler';
4
+ export * from './formRules';
5
+ export * from './generateQueryString';
6
+ export * from './image';
7
+ export * from './name';
8
+ export * from './order';
9
+ export * from './pagination';
10
+ export * from './price';
11
+ export * from './text';
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./auth"), exports);
18
+ __exportStar(require("./datetime"), exports);
19
+ __exportStar(require("./errorHandler"), exports);
20
+ __exportStar(require("./formRules"), exports);
21
+ __exportStar(require("./generateQueryString"), exports);
22
+ __exportStar(require("./image"), exports);
23
+ __exportStar(require("./name"), exports);
24
+ __exportStar(require("./order"), exports);
25
+ __exportStar(require("./pagination"), exports);
26
+ __exportStar(require("./price"), exports);
27
+ __exportStar(require("./text"), exports);
@@ -0,0 +1,6 @@
1
+ export declare const getInitialName: (name: string) => string;
2
+ export declare const generateFullName: (names: {
3
+ firstName?: string;
4
+ middleName?: string;
5
+ lastName?: string;
6
+ }) => string;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateFullName = exports.getInitialName = void 0;
4
+ const getInitialName = (name) => {
5
+ const split = name.split(' ');
6
+ let start = 0;
7
+ let initial = [];
8
+ if (split.length > 1) {
9
+ while (start <= 1) {
10
+ initial.push(split[start].charAt(0));
11
+ start++;
12
+ }
13
+ }
14
+ else {
15
+ initial.push(split[0].substring(0, 2));
16
+ }
17
+ return initial.join('').toUpperCase();
18
+ };
19
+ exports.getInitialName = getInitialName;
20
+ const generateFullName = (names) => {
21
+ let concated = [];
22
+ if (names.firstName) {
23
+ concated.push(names.firstName);
24
+ }
25
+ if (names.middleName) {
26
+ concated.push(names.middleName);
27
+ }
28
+ if (names.lastName) {
29
+ concated.push(names.lastName);
30
+ }
31
+ return concated.join(' ');
32
+ };
33
+ exports.generateFullName = generateFullName;
@@ -0,0 +1 @@
1
+ export declare function calculateAddDayForFirstOrder(): number;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateAddDayForFirstOrder = calculateAddDayForFirstOrder;
4
+ function calculateAddDayForFirstOrder() {
5
+ let addDay = 1;
6
+ const now = new Date();
7
+ if (now.getHours() > 12) {
8
+ addDay = 2;
9
+ }
10
+ else if (now.getHours() === 12) {
11
+ if (now.getMinutes() > 0) {
12
+ addDay = 2;
13
+ }
14
+ }
15
+ return addDay;
16
+ }
@@ -0,0 +1,29 @@
1
+ export declare const PAGE_SIZE_OPTIONS: string[];
2
+ export type IPagination = {
3
+ page: number;
4
+ perPage: number;
5
+ totalData: number;
6
+ countPage: number;
7
+ prev: string;
8
+ next: string;
9
+ };
10
+ export declare const INITIAL_PAGINATION: IPagination;
11
+ export type IQuery = {
12
+ offset?: number;
13
+ limit?: number;
14
+ };
15
+ export declare const INITIAL_QUERY: {
16
+ offset: number;
17
+ limit: number;
18
+ };
19
+ export type IPayloadPagination<ResultItem> = {
20
+ next: string;
21
+ prev: string;
22
+ count: number;
23
+ results: Array<ResultItem>;
24
+ };
25
+ export interface IHttpResponse<Payload> {
26
+ code: string;
27
+ message: string;
28
+ payload: Payload;
29
+ }
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.INITIAL_QUERY = exports.INITIAL_PAGINATION = exports.PAGE_SIZE_OPTIONS = void 0;
4
+ exports.PAGE_SIZE_OPTIONS = ['10', '20', '50'];
5
+ exports.INITIAL_PAGINATION = {
6
+ page: 1,
7
+ perPage: 25,
8
+ totalData: 0,
9
+ countPage: 1,
10
+ next: '',
11
+ prev: '',
12
+ };
13
+ exports.INITIAL_QUERY = {
14
+ offset: 0,
15
+ limit: 25,
16
+ };
@@ -0,0 +1,5 @@
1
+ export declare function formatCurrency(amount: number, currencySymbol?: string, thousandSep?: string, decimalSep?: string, showDecimal?: boolean): string;
2
+ export declare function formatCurrencyIndonesia(amount: number): string;
3
+ export declare function formatCurrencyRangeIndonesia(amountStart: number, amountEnd?: number): string;
4
+ export declare function parseCurrency(currencyString: string, thousandSep?: string, decimalSep?: string): number;
5
+ export default function thousandSeparator(x: number | string): string;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatCurrency = formatCurrency;
4
+ exports.formatCurrencyIndonesia = formatCurrencyIndonesia;
5
+ exports.formatCurrencyRangeIndonesia = formatCurrencyRangeIndonesia;
6
+ exports.parseCurrency = parseCurrency;
7
+ exports.default = thousandSeparator;
8
+ function formatCurrency(amount, currencySymbol = '$', thousandSep = ',', decimalSep = '.', showDecimal = true) {
9
+ console.info('formatCurrency', amount);
10
+ if (typeof amount === 'string')
11
+ amount = Number(amount);
12
+ if (!amount)
13
+ amount = 0;
14
+ const [intPart, decPart] = amount.toFixed(2).split('.');
15
+ let intPartWithSep = '';
16
+ for (let i = intPart.length - 1, j = 0; i >= 0; i--, j++) {
17
+ if (j > 0 && j % 3 === 0) {
18
+ intPartWithSep = thousandSep + intPartWithSep;
19
+ }
20
+ intPartWithSep = intPart[i] + intPartWithSep;
21
+ }
22
+ return currencySymbol + intPartWithSep + (showDecimal ? decimalSep + decPart : '');
23
+ }
24
+ function formatCurrencyIndonesia(amount) {
25
+ return formatCurrency(amount, 'Rp', '.', ',', false);
26
+ }
27
+ function formatCurrencyRangeIndonesia(amountStart, amountEnd) {
28
+ if (amountStart === amountEnd) {
29
+ return formatCurrencyIndonesia(amountStart);
30
+ }
31
+ else if (amountStart && amountEnd) {
32
+ return (formatCurrencyIndonesia(amountStart) +
33
+ ' - ' +
34
+ formatCurrencyIndonesia(amountEnd));
35
+ }
36
+ else if (amountStart) {
37
+ return formatCurrencyIndonesia(amountStart) + ' - unlimited';
38
+ }
39
+ else if (amountEnd) {
40
+ return 'up to ' + formatCurrencyIndonesia(amountEnd);
41
+ }
42
+ else {
43
+ return '';
44
+ }
45
+ }
46
+ function parseCurrency(currencyString, thousandSep = ',', decimalSep = '.') {
47
+ if (!currencyString)
48
+ currencyString = '';
49
+ const cleanedString = thousandSep === ','
50
+ ? currencyString.replace(/[^\d.-]/g, '')
51
+ : currencyString.replace(/[^\d,-]/g, '');
52
+ const [intPart, decPart] = cleanedString.split(decimalSep);
53
+ const numberWithDecimal = intPart + (decPart ? decimalSep + decPart : '');
54
+ return parseFloat(numberWithDecimal);
55
+ }
56
+ function thousandSeparator(x) {
57
+ return x && (x === null || x === void 0 ? void 0 : x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.'));
58
+ }
@@ -0,0 +1,15 @@
1
+ export declare function capitalizeFirstLetter(text: string): string;
2
+ export type ReadableTextConfig = {
3
+ style?: 'lowercase' | 'uppercase' | 'capital-first-word';
4
+ disableUnderscoreToSpace?: boolean;
5
+ disableDashToSpace?: boolean;
6
+ };
7
+ export declare function showReadableText(str: string, config?: ReadableTextConfig): string;
8
+ export declare function convertHtmlToText(htmlText: string): string;
9
+ export declare function convertSlugToText(slug: string): string;
10
+ export declare function convertTextToRupiah(text: string): string;
11
+ export declare function exportToCamelCase(str: string): string;
12
+ export declare const getYouTubeId: (url?: string) => string;
13
+ export declare function limitDescription(text: any, limit?: number): any;
14
+ export declare function replaceDashWithSpace(word: string): string;
15
+ export declare function replaceUnderscoreWithSpace(word: string): string;
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getYouTubeId = void 0;
7
+ exports.capitalizeFirstLetter = capitalizeFirstLetter;
8
+ exports.showReadableText = showReadableText;
9
+ exports.convertHtmlToText = convertHtmlToText;
10
+ exports.convertSlugToText = convertSlugToText;
11
+ exports.convertTextToRupiah = convertTextToRupiah;
12
+ exports.exportToCamelCase = exportToCamelCase;
13
+ exports.limitDescription = limitDescription;
14
+ exports.replaceDashWithSpace = replaceDashWithSpace;
15
+ exports.replaceUnderscoreWithSpace = replaceUnderscoreWithSpace;
16
+ const price_1 = __importDefault(require("./price"));
17
+ function capitalizeFirstLetter(text) {
18
+ return text.charAt(0).toUpperCase() + text.slice(1);
19
+ }
20
+ function showReadableText(str, config) {
21
+ var _a, _b;
22
+ if (!str) {
23
+ return '';
24
+ }
25
+ if (!(config && config.disableDashToSpace)) {
26
+ str = replaceDashWithSpace(str);
27
+ }
28
+ if (!(config && config.disableUnderscoreToSpace)) {
29
+ str = str.replace(/_/g, ' ');
30
+ }
31
+ if (config && config.style === 'lowercase') {
32
+ str = str.toLowerCase();
33
+ }
34
+ else if (config && config.style === 'uppercase') {
35
+ str = str.toUpperCase();
36
+ }
37
+ else {
38
+ str = ((_a = str.charAt(0)) === null || _a === void 0 ? void 0 : _a.toUpperCase()) + ((_b = str.toLowerCase()) === null || _b === void 0 ? void 0 : _b.slice(1));
39
+ }
40
+ return str;
41
+ }
42
+ function convertHtmlToText(htmlText) {
43
+ return htmlText.replace(/<[^>]+>/g, " ");
44
+ }
45
+ function convertSlugToText(slug) {
46
+ let text = slug.split("-").join(" ");
47
+ return capitalizeFirstLetter(text);
48
+ }
49
+ function convertTextToRupiah(text) {
50
+ return `Rp ${(0, price_1.default)(text)}`;
51
+ }
52
+ function exportToCamelCase(str) {
53
+ return str
54
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
55
+ return index == 0 ? word.toLowerCase() : word.toUpperCase();
56
+ })
57
+ .replace(/\s+/g, "");
58
+ }
59
+ const getYouTubeId = (url) => {
60
+ if (!url)
61
+ return undefined;
62
+ let match = url.match(/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube(-nocookie)?\.com|youtu.be))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/);
63
+ return match === null || match === void 0 ? void 0 : match[6];
64
+ };
65
+ exports.getYouTubeId = getYouTubeId;
66
+ function limitDescription(text, limit = 200) {
67
+ const words = text.split(" ");
68
+ if (words.length > limit) {
69
+ const truncatedWords = words.slice(0, limit);
70
+ const truncatedText = truncatedWords.join(" ") + "...";
71
+ return truncatedText;
72
+ }
73
+ return text;
74
+ }
75
+ function replaceDashWithSpace(word) {
76
+ const splitter = word.split('-');
77
+ let wordReturn = '';
78
+ splitter.map((word) => {
79
+ const lower = word.toLowerCase().slice(1);
80
+ const capital = word.charAt(0).toUpperCase();
81
+ wordReturn = wordReturn + ` ${capital}${lower}`;
82
+ });
83
+ return wordReturn;
84
+ }
85
+ function replaceUnderscoreWithSpace(word) {
86
+ const splitter = word.split(/[ ,_]+/);
87
+ let wordReturn = '';
88
+ splitter.map((word) => {
89
+ const lower = word.toLowerCase().slice(1);
90
+ const capital = word.charAt(0).toUpperCase();
91
+ wordReturn = wordReturn + ` ${capital}${lower}`;
92
+ });
93
+ return wordReturn;
94
+ }
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@qlibs/utils",
3
+ "version": "1.0.2",
4
+ "description": "",
5
+ "author": "QBIT Developer",
6
+ "license": "MIT",
7
+ "url": "https://github.com/qbit-tech/qlibs-utils",
8
+ "main": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "files": [
11
+ "/dist"
12
+ ],
13
+ "scripts": {
14
+ "build": "rimraf -rf dist && tsc -p tsconfig.json",
15
+ "format": "prettier --write \"**/*.ts\"",
16
+ "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
17
+ "start": "craco start",
18
+ "prepublish:npm": "npm run build",
19
+ "publish:npm": "npm publish --access public",
20
+ "prepublish:next": "npm run build",
21
+ "publish:next": "npm publish --access public --tag next",
22
+ "test:e2e": "jest --config ./tests/jest-e2e.json --runInBand",
23
+ "prerelease": "npm run build",
24
+ "release": "release-it",
25
+ "prepare": "husky install && npm run build"
26
+ },
27
+ "dependencies": {
28
+ "husky": "^8.0.3",
29
+ "image-blob-reduce": "^4.1.0",
30
+ "immutability-helper": "^3.1.1",
31
+ "moment": "^2.30.1",
32
+ "pica": "^9.0.1",
33
+ "release-it": "16.1.5",
34
+ "rimraf": "5.0.1"
35
+ },
36
+ "devDependencies": {
37
+ "typescript": "^5.7.2"
38
+ },
39
+ "publishConfig": {
40
+ "registry": "https://registry.npmjs.org"
41
+ },
42
+ "browserslist": {
43
+ "production": [
44
+ ">0.2%",
45
+ "not dead",
46
+ "not op_mini all"
47
+ ],
48
+ "development": [
49
+ "last 1 chrome version",
50
+ "last 1 firefox version",
51
+ "last 1 safari version"
52
+ ]
53
+ }
54
+ }