@amimpact/willy-utils 4.4.0 → 4.5.1

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 CHANGED
@@ -1,15 +1,3 @@
1
1
  # Utils
2
2
 
3
3
  Verschillende helpers functies
4
-
5
- ## Installatie
6
- ```sh
7
- npm install @amimpact/willy-utils --save
8
- yarn add @amimpact/willy-utils
9
- ```
10
-
11
- ## Implementatie
12
- ```javascript
13
- import { $, $$ } from '@amimpact/willy-utils';
14
- ```
15
-
package/package.json CHANGED
@@ -1,39 +1,23 @@
1
1
  {
2
- "name": "@amimpact/willy-utils",
3
- "version": "4.4.0",
4
- "description": "Javascript utils",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "scripts": {
8
- "build": "tsc",
9
- "publish:prerelease": "npm version prerelease --preid beta && npm publish --tag beta",
10
- "publish:prepatch": "npm version prepatch --preid beta && npm publish --tag beta",
11
- "publish:patch": "npm version patch && npm publish",
12
- "publish:preminor": "npm version preminor --preid beta && npm publish --tag beta",
13
- "publish:minor": "npm version minor && npm publish",
14
- "postpublish": "git push origin --all; git push origin --tags",
15
- "preversion": "npm run build",
16
- "watch": "onchange src/* -- npm run build"
17
- },
18
- "repository": {
19
- "type": "git",
20
- "url": "git+ssh://git@bitbucket.org/amimpact/willy-utils.git"
21
- },
22
- "keywords": [],
23
- "author": "a&m impact",
24
- "license": "MIT",
25
- "bugs": {
26
- "url": "https://bitbucket.org/amimpact/willy-utils/issues"
27
- },
28
- "homepage": "https://bitbucket.org/amimpact/willy-utils#readme",
29
- "devDependencies": {
30
- "@types/resize-observer-browser": "^0.1.7",
31
- "browserify": "17.0.0",
32
- "onchange": "7.1.0",
33
- "typescript": "4.7.3"
34
- },
35
- "dependencies": {
36
- "date-fns": "2.28.0",
37
- "date-fns-tz": "1.3.4"
38
- }
2
+ "name": "@amimpact/willy-utils",
3
+ "version": "4.5.1",
4
+ "description": "Javascript utils",
5
+ "scripts": {
6
+ "publish:prerelease": "npm version prerelease --preid beta && npm publish --tag beta",
7
+ "publish:prepatch": "npm version prepatch --preid beta && npm publish --tag beta",
8
+ "publish:patch": "npm version patch && npm publish",
9
+ "publish:preminor": "npm version preminor --preid beta && npm publish --tag beta",
10
+ "publish:minor": "npm version minor && npm publish",
11
+ "postpublish": "git push origin --all; git push origin --tags"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+ssh://git@bitbucket.org/amimpact/willy-utils.git"
16
+ },
17
+ "author": "a&m impact",
18
+ "license": "MIT",
19
+ "bugs": {
20
+ "url": "https://bitbucket.org/amimpact/willy-utils/issues"
21
+ },
22
+ "homepage": "https://bitbucket.org/amimpact/willy-utils#readme"
39
23
  }
package/src/cookie.ts ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Create Cookie
3
+ * source: http://www.quirksmode.org/js/cookies.html
4
+ */
5
+ export const createCookie = (
6
+ name: string,
7
+ value: string | boolean,
8
+ days?: number,
9
+ ) => {
10
+ let expires = '';
11
+
12
+ if (days) {
13
+ const date = new Date();
14
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
15
+ expires = `; expires=${date.toUTCString()}`;
16
+ }
17
+
18
+ document.cookie = `${name}=${value}${expires}; path=/`;
19
+ };
20
+
21
+ /**
22
+ * Read Cookie
23
+ * source: http://www.quirksmode.org/js/cookies.html
24
+ */
25
+ export const readCookie = (name: string) => {
26
+ const nameEQ = `${name}=`;
27
+ const ca = document.cookie.split(';');
28
+
29
+ for (let i = 0; i < ca.length; i++) {
30
+ let c = ca[i];
31
+
32
+ while (c.charAt(0) === ' ') {
33
+ c = c.substring(1, c.length);
34
+ }
35
+
36
+ if (c.indexOf(nameEQ) === 0) {
37
+ return c.substring(nameEQ.length, c.length);
38
+ }
39
+ }
40
+ return null;
41
+ };
42
+
43
+ /**
44
+ * Erase Cookie
45
+ * source: http://www.quirksmode.org/js/cookies.html
46
+ */
47
+ export const eraseCookie = (name: string) => {
48
+ createCookie(name, '', -1);
49
+ };
package/src/date.ts ADDED
@@ -0,0 +1,304 @@
1
+ import {
2
+ format,
3
+ formatDistance,
4
+ formatDistanceStrict,
5
+ formatDuration,
6
+ isBefore,
7
+ subDays,
8
+ } from 'date-fns';
9
+ import { nl } from 'date-fns/locale';
10
+ import { fromZonedTime } from 'date-fns-tz';
11
+ import { parse as parseISO } from './includes/tinyduration';
12
+
13
+ /**
14
+ * Momenteel beschikbare locales
15
+ * Engels is default (leeg)
16
+ */
17
+ const availableLocales = {
18
+ en: '',
19
+ nl: nl,
20
+ };
21
+
22
+ /**
23
+ * Dates uit Craft mooi formatteren
24
+ *
25
+ * @param {Object} dateObject
26
+ * @param {Object} options
27
+ */
28
+ export interface CraftDate {
29
+ date: string;
30
+ timezone: string;
31
+ timezone_type: number;
32
+ }
33
+
34
+ export interface FormatCraftDateOptions {
35
+ /**
36
+ * Eigen formaat mee kunnen geven
37
+ *
38
+ * @type {string}
39
+ * @memberof FormatCraftDateOptions
40
+ */
41
+ format: string;
42
+
43
+ /**
44
+ * i18n Locale mee kunnen geven
45
+ *
46
+ * @type {string}
47
+ * @memberof FormatCraftDateOptions
48
+ */
49
+ locale: string;
50
+
51
+ /**
52
+ * Amerikaans formaat maken om in Craft op te kunnen slaan, anders Nederlands
53
+ *
54
+ * @type {boolean}
55
+ * @memberof FormatCraftDateOptions
56
+ */
57
+ systemFormat: boolean;
58
+
59
+ /**
60
+ * Datum ook tonen
61
+ *
62
+ * @type {boolean}
63
+ * @memberof FormatCraftDateOptions
64
+ */
65
+ showTime: boolean;
66
+ }
67
+
68
+ /**
69
+ * Opties voor formatDateFromNow
70
+ */
71
+ export interface FormatDateFromNowOptions {
72
+ /**
73
+ * Toon 'geleden' bij in de datum
74
+ *
75
+ * @type {boolean}
76
+ * @memberof FormatDateFromNowOptions
77
+ */
78
+ addSuffix: boolean;
79
+
80
+ /**
81
+ * Secondes ook tonen
82
+ *
83
+ * @type {boolean}
84
+ * @memberof FormatDateFromNowOptions
85
+ */
86
+ includeSeconds: boolean;
87
+
88
+ /**
89
+ * Toon datum voor oudere items
90
+ *
91
+ * @type {boolean}
92
+ * @memberof FormatDateFromNowOptions
93
+ */
94
+ showDateForOld: boolean;
95
+
96
+ /**
97
+ * Format voor hoe de data getoont wordt
98
+ *
99
+ * @type {string}
100
+ * @memberof FormatDateFromNowOptions
101
+ */
102
+ showDateForOldFormat: string;
103
+
104
+ /**
105
+ * Aantal dagen voor bovenstaan item
106
+ *
107
+ * @type {number}
108
+ * @memberof FormatDateFromNowOptions
109
+ */
110
+ numberOfDaysShowDateForOld: number;
111
+
112
+ /**
113
+ * Toon datum in strict format, dus niet 'ongeveer' bijv
114
+ * https://date-fns.org/v2.0.0-alpha.27/docs/formatDistanceStrict
115
+ *
116
+ * @type {boolean}
117
+ * @memberof FormatDateFromNowOptions
118
+ */
119
+ strict: boolean;
120
+
121
+ /**
122
+ * Welke locale is default
123
+ *
124
+ * @type {any}
125
+ * @memberof FormatDateFromNowOptions
126
+ */
127
+ locale: any;
128
+ }
129
+
130
+ /**
131
+ * Opties voor parseISODuration
132
+ */
133
+ export interface parseISODurationOptions {
134
+ /**
135
+ * Geef de duration als humanReadable terug
136
+ * https://date-fns.org/v2.16.1/docs/formatDuration
137
+ *
138
+ * @type {boolean}
139
+ * @memberof parseISODurationOptions
140
+ */
141
+ humanReadable: boolean;
142
+ }
143
+
144
+ /**
145
+ * Format date object uit Craft naar iets leesbaars
146
+ *
147
+ * @param {CraftDate} dateObject
148
+ * @param {FormatCraftDateOptions} options
149
+ */
150
+ export const formatCraftDate = (dateObject: CraftDate, options: FormatCraftDateOptions) => {
151
+ let dateFormat = options && options.systemFormat ? 'yyyy-MM-dd' : 'dd-MM-yyyy';
152
+ let localeString = 'nl';
153
+
154
+ if (options && options.showTime) {
155
+ dateFormat += ' HH:mm';
156
+ }
157
+
158
+ // Eigen format mee kunnen geven
159
+ if (options && options.format) {
160
+ dateFormat = options.format;
161
+ }
162
+
163
+ // Locale mee kunnen geven
164
+ if (options && options.locale) {
165
+ localeString = options.locale;
166
+ }
167
+
168
+ if (!dateObject || !dateObject.date) {
169
+ return '';
170
+ }
171
+
172
+ /**
173
+ * De date uit Craft heeft het volgende format: "2019-11-14 08:00:00.000000"
174
+ * Safari begrijpt dit niet en geeft dan een NaN met new Date(date)
175
+ * Safari begrijpt het wel als alle - vervangen worden door /, en het laatste gedeelte achter de punt weg is
176
+ */
177
+ const dateToFormat = dateObject.date.replace(/-/g, '/').split('.')[0];
178
+
179
+ // De spatie tussen datum en tijd vervangen door 'T', anders snapt IE het niet
180
+ return format(new Date(dateToFormat), dateFormat, {
181
+ locale: availableLocales[localeString],
182
+ });
183
+ };
184
+
185
+ /**
186
+ * Datum formatteren naar "x minuten etc. geleden"
187
+ * @param {date, timezone, timezone_type} dateObject
188
+ */
189
+ export const formatDateFromNow = (dateObject: CraftDate, options: FormatDateFromNowOptions) => {
190
+ const defaultOptions: FormatDateFromNowOptions = {
191
+ addSuffix: true,
192
+ includeSeconds: true,
193
+ showDateForOld: false,
194
+ showDateForOldFormat: 'dd-MM-yyyy',
195
+ numberOfDaysShowDateForOld: 7,
196
+ strict: false,
197
+ locale: nl,
198
+ };
199
+
200
+ let opts = defaultOptions;
201
+ if (options) {
202
+ opts = (<any>Object).assign({}, defaultOptions, options);
203
+ }
204
+
205
+ if (!dateObject || !dateObject.date) {
206
+ return '';
207
+ }
208
+
209
+ const parsed = fromZonedTime(dateObject.date, dateObject.timezone);
210
+
211
+ /**
212
+ * Datum tonen voor ouder dan x tijd
213
+ */
214
+ if (
215
+ opts.showDateForOld &&
216
+ isBefore(parsed, subDays(new Date(), opts.numberOfDaysShowDateForOld))
217
+ ) {
218
+ return format(new Date(dateObject.date.replace(' ', 'T')), opts.showDateForOldFormat, {
219
+ locale: availableLocales[opts.locale],
220
+ });
221
+ } else {
222
+ const formatDistanceOptions = {
223
+ includeSeconds: opts.includeSeconds,
224
+ addSuffix: opts.addSuffix,
225
+ locale: availableLocales[opts.locale],
226
+ };
227
+
228
+ /**
229
+ * De postdate moet bepaald worden met timezone erbij. Anders krijg je in Engeland bijv de melding 'over ongeveer een uur'
230
+ * Daarom moet date-fns wel de posttime getransformeerd hebben tot de lokale timezone
231
+ */
232
+ if (opts.strict) {
233
+ return formatDistanceStrict(parsed, new Date(), formatDistanceOptions);
234
+ } else {
235
+ return formatDistance(parsed, new Date(), formatDistanceOptions);
236
+ }
237
+ }
238
+ };
239
+
240
+ /**
241
+ * New date maken op basis van timezone
242
+ * @param {date, timezone, timezone_type} dateObject
243
+ */
244
+ export const formatNewDate = (dateObject: CraftDate) => {
245
+ if (!dateObject || !dateObject.date) {
246
+ return '';
247
+ }
248
+
249
+ /**
250
+ * De date uit Craft heeft het volgende format: "2019-11-14 08:00:00.000000"
251
+ * Safari begrijpt dit niet en geeft dan een NaN met new Date(date)
252
+ * Safari begrijpt het wel als alle - vervangen worden door /, en het laatste gedeelte achter de punt weg is
253
+ */
254
+ // const dateString = dateObject.date.replace(/-/g, '/').split('.')[0];
255
+
256
+ const parsed = fromZonedTime(dateObject.date, dateObject.timezone);
257
+
258
+ return new Date(parsed);
259
+ };
260
+
261
+ /**
262
+ * Convert datum
263
+ * @param {Date} date
264
+ */
265
+ export const formatUTCDate = (date: Date) => {
266
+ const d = new Date(date);
267
+
268
+ return new Date(
269
+ Date.UTC(
270
+ d.getFullYear(),
271
+ d.getMonth(),
272
+ d.getDate(),
273
+ d.getHours(),
274
+ d.getMinutes(),
275
+ d.getSeconds(),
276
+ ),
277
+ );
278
+ };
279
+
280
+ /**
281
+ * ISO duration naar object ombuigen. Bijv P4W
282
+ * @param {string} duration
283
+ * @param {parseISODurationOptions} options
284
+ */
285
+ export const parseISODuration = (duration: string, options: parseISODurationOptions) => {
286
+ const defaultOptions: parseISODurationOptions = {
287
+ humanReadable: false,
288
+ };
289
+
290
+ let opts = defaultOptions;
291
+ if (options) {
292
+ opts = (<any>Object).assign({}, defaultOptions, options);
293
+ }
294
+
295
+ const durationObject = parseISO(duration);
296
+
297
+ if (opts.humanReadable) {
298
+ return formatDuration(durationObject, {
299
+ locale: nl,
300
+ });
301
+ }
302
+
303
+ return durationObject;
304
+ };
package/src/form.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Creeert een FormData object vanuit een object
3
+ * https://gist.github.com/ghinda/8442a57f22099bdb2e34#gistcomment-2719686
4
+ *
5
+ * @param {Object} data
6
+ * @param {FormData} form
7
+ * @param {String} namespace
8
+ */
9
+ export const convertObjectToFormData = (
10
+ data: object | null = {},
11
+ form: FormData | null = null,
12
+ namespace: string = '',
13
+ ) => {
14
+ const model = { ...data };
15
+ const formData = form || new FormData();
16
+
17
+ for (const propertyName in model) {
18
+ if (
19
+ !Object.prototype.hasOwnProperty.call(model, propertyName) ||
20
+ ((model[propertyName] === null || model[propertyName] === undefined) &&
21
+ typeof model[propertyName] !== 'string')
22
+ ) {
23
+ continue;
24
+ }
25
+
26
+ const formKey = namespace ? `${namespace}[${propertyName}]` : propertyName;
27
+
28
+ // Date
29
+ if (model[propertyName] instanceof Date) {
30
+ formData.append(formKey, model[propertyName].toISOString());
31
+ }
32
+ // File
33
+ else if (model[propertyName] instanceof File) {
34
+ formData.append(formKey, model[propertyName]);
35
+
36
+ // Array
37
+ } else if (model[propertyName] instanceof Array) {
38
+ if (model[propertyName].length === 0) {
39
+ formData.append(formKey, '');
40
+ } else {
41
+ model[propertyName].forEach((element: unknown, index: number) => {
42
+ const tempFormKey = `${formKey}[${index}]`;
43
+
44
+ if (element instanceof File) {
45
+ formData.append(tempFormKey, element);
46
+ } else {
47
+ if (typeof element === 'object') {
48
+ convertObjectToFormData(element, formData, tempFormKey);
49
+ } else {
50
+ formData.append(tempFormKey, element?.toString() || '');
51
+ }
52
+ }
53
+ });
54
+ }
55
+
56
+ // Object en geen File
57
+ } else if (
58
+ typeof model[propertyName] === 'object' &&
59
+ !(model[propertyName] instanceof File)
60
+ ) {
61
+ convertObjectToFormData(model[propertyName], formData, formKey);
62
+ } else {
63
+ const val = model[propertyName];
64
+ const formDataValue = typeof val === 'boolean' ? (val ? '1' : '0') : val;
65
+
66
+ formData.append(formKey, formDataValue.toString());
67
+ }
68
+ }
69
+
70
+ // for (let propertyName in files) {
71
+ // if (files.hasOwnProperty(propertyName)) {
72
+ // // formData.append(propertyName, files[propertyName]);
73
+ // formData.append(`fields[${propertyName}]`, files[propertyName]);
74
+ // }
75
+ // }
76
+
77
+ return formData;
78
+ };