@jsb188/app 1.1.8 → 1.1.9

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.
@@ -1,12 +1,12 @@
1
- import i18n from '../i18n/index.ts';
2
- import type { AddressObj } from '../types/other.d.ts';
1
+ import i18n from "../i18n/index.ts";
2
+ import type { AddressObj } from "../types/other.d.ts";
3
3
 
4
4
  /**
5
5
  * Combine list of class names
6
6
  */
7
7
 
8
8
  export function cn(...classNames: (string | boolean | undefined | null)[]) {
9
- return classNames.filter(Boolean).join(' ');
9
+ return classNames.filter(Boolean).join(" ");
10
10
  }
11
11
 
12
12
  /**
@@ -14,25 +14,25 @@ export function cn(...classNames: (string | boolean | undefined | null)[]) {
14
14
  */
15
15
 
16
16
  export function shortenToSpace(
17
- str: string,
18
- len: number = 100,
19
- ellipsis: string = '...',
17
+ str: string,
18
+ len: number = 100,
19
+ ellipsis: string = "...",
20
20
  ): string {
21
- if (!str || str.length < len) {
22
- return str;
23
- }
21
+ if (!str || str.length < len) {
22
+ return str;
23
+ }
24
24
 
25
- const trimmed = str.substring(0, len);
26
- const spaceIndex = trimmed.lastIndexOf(' ');
25
+ const trimmed = str.substring(0, len);
26
+ const spaceIndex = trimmed.lastIndexOf(" ");
27
27
 
28
- if (spaceIndex < 0) {
29
- return trimmed.substring(0, len) + ellipsis;
30
- }
28
+ if (spaceIndex < 0) {
29
+ return trimmed.substring(0, len) + ellipsis;
30
+ }
31
31
 
32
- return (
33
- trimmed.substring(0, Math.min(trimmed.length, spaceIndex)) +
34
- ellipsis
35
- );
32
+ return (
33
+ trimmed.substring(0, Math.min(trimmed.length, spaceIndex)) +
34
+ ellipsis
35
+ );
36
36
  }
37
37
 
38
38
  /**
@@ -40,38 +40,65 @@ export function shortenToSpace(
40
40
  */
41
41
 
42
42
  export function guessFirstName(str: string, len: number = 40): string {
43
- let shortened = str?.replace(/^(a|an|the|da|de|that|there|this|than|then)\b/i, '')?.trim() || '';
44
- const spaceIx = shortened.indexOf(' ');
43
+ let shortened =
44
+ str?.replace(/^(a|an|the|da|de|that|there|this|than|then)\b/i, "")
45
+ ?.trim() || "";
46
+ const spaceIx = shortened.indexOf(" ");
45
47
 
46
- if (spaceIx >= 0) {
47
- shortened = shortened.substring(0, spaceIx + 1);
48
- }
48
+ if (spaceIx >= 0) {
49
+ shortened = shortened.substring(0, spaceIx + 1);
50
+ }
49
51
 
50
- if (len < shortened.length) {
51
- shortened = shortened.substring(0, len);
52
- }
52
+ if (len < shortened.length) {
53
+ shortened = shortened.substring(0, len);
54
+ }
53
55
 
54
- const articleReplacedEnd = shortened.replace(
55
- /\b(a|an|the|da|de|that|there|this|than|then)$/i,
56
- '',
57
- );
56
+ const articleReplacedEnd = shortened.replace(
57
+ /\b(a|an|the|da|de|that|there|this|than|then)$/i,
58
+ "",
59
+ );
58
60
 
59
- if (articleReplacedEnd.length < 5) {
60
- return shortened.trim();
61
- }
61
+ if (articleReplacedEnd.length < 5) {
62
+ return shortened.trim();
63
+ }
62
64
 
63
- return articleReplacedEnd.trim();
65
+ return articleReplacedEnd.trim();
64
66
  }
65
67
 
66
68
  /**
67
- * Check if e-mail
69
+ * Get indefinite article ("a" or "an") for a word
70
+ */
71
+
72
+ export function addIndefiniteArticle(word: string) {
73
+ const raw = (word || "").trim().toLowerCase();
74
+
75
+ let article;
76
+ if (!raw) {
77
+ article = "a";
78
+ } else if (/^(honest|honor|hour|heir)\b/.test(raw)) {
79
+ // Common silent-h words use "an"
80
+ article = "an";
81
+ } else if (
82
+ /^(uni([^nmd]|$)|use|user|euro|one|once|ubiquit|ufo|ukulele)\b/.test(raw)
83
+ ) {
84
+ // Common "you"/"w" sound starts use "a"
85
+ article = "a";
86
+ } else {
87
+ article = /^[aeiou]/.test(raw) ? "an" : "a";
88
+ }
89
+
90
+ return `${article} ${word}`;
91
+ }
92
+
93
+ /**
94
+ * Check if email
68
95
  */
69
96
 
70
97
  export function isEmail(str: string) {
71
- // return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
72
- const emailRegex =
73
- /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
74
- return !!str && emailRegex.test(str.trim());
98
+ // return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
99
+ const emailRegex =
100
+ /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
101
+ return !!str && emailRegex.test(str.trim());
75
102
  }
76
103
 
77
104
  /**
@@ -80,25 +107,25 @@ export function isEmail(str: string) {
80
107
  */
81
108
 
82
109
  export function convertToInternationalPhone(str: string) {
83
- // Check if string has a character that isn't one of [(, ), +, -, " ", 0-9]
84
- if (/[^0-9+\-\s().]/.test(str)) {
85
- // Invalid
86
- return null;
87
- }
88
-
89
- const digits = str.replace(/[^0-9]/g, '');
90
- if (!digits || digits.startsWith('0')) {
91
- // Invalid
92
- return null;
93
- } else if (
94
- !digits.startsWith('1') &&
95
- digits.length === 10
96
- ) {
97
- return '+1' + digits;
98
- }
99
-
100
- // If it doesn't start with a country code, assume it's already in international format
101
- return '+' + digits;
110
+ // Check if string has a character that isn't one of [(, ), +, -, " ", 0-9]
111
+ if (/[^0-9+\-\s().]/.test(str)) {
112
+ // Invalid
113
+ return null;
114
+ }
115
+
116
+ const digits = str.replace(/[^0-9]/g, "");
117
+ if (!digits || digits.startsWith("0")) {
118
+ // Invalid
119
+ return null;
120
+ } else if (
121
+ !digits.startsWith("1") &&
122
+ digits.length === 10
123
+ ) {
124
+ return "+1" + digits;
125
+ }
126
+
127
+ // If it doesn't start with a country code, assume it's already in international format
128
+ return "+" + digits;
102
129
  }
103
130
 
104
131
  /**
@@ -107,15 +134,18 @@ export function convertToInternationalPhone(str: string) {
107
134
  * NOTE: This will convert phone-like strings to international format
108
135
  */
109
136
 
110
- export function isPhone(str: string, doNotConvertInternational: boolean = false) {
111
- let phoneNumber: string | null = str.trim();
112
- if (!doNotConvertInternational) {
113
- phoneNumber = convertToInternationalPhone(phoneNumber);
114
- if (!phoneNumber) {
115
- return false;
116
- }
117
- }
118
- return /^\+[0-9]{7,15}$/.test(phoneNumber);
137
+ export function isPhone(
138
+ str: string,
139
+ doNotConvertInternational: boolean = false,
140
+ ) {
141
+ let phoneNumber: string | null = str.trim();
142
+ if (!doNotConvertInternational) {
143
+ phoneNumber = convertToInternationalPhone(phoneNumber);
144
+ if (!phoneNumber) {
145
+ return false;
146
+ }
147
+ }
148
+ return /^\+[0-9]{7,15}$/.test(phoneNumber);
119
149
  }
120
150
 
121
151
  /**
@@ -128,22 +158,22 @@ export function isPhone(str: string, doNotConvertInternational: boolean = false)
128
158
  */
129
159
 
130
160
  export function passwordStrength(str: string, minLength: number = 8) {
131
- const isLongEnough = str.length >= minLength;
132
- const hasLowercase = /[a-z]/.test(str);
133
- const hasUppercase = /[A-Z]/.test(str);
134
- const hasDigit = /\d/.test(str);
135
- const hasSpecial = /\W/.test(str);
136
- const valid = isLongEnough && hasLowercase && hasUppercase && hasDigit &&
137
- hasSpecial;
138
- // return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W)[a-zA-Z\d\W]{8,}$/.test(str);
139
- return {
140
- valid,
141
- isLongEnough,
142
- hasLowercase,
143
- hasUppercase,
144
- hasDigit,
145
- hasSpecial,
146
- };
161
+ const isLongEnough = str.length >= minLength;
162
+ const hasLowercase = /[a-z]/.test(str);
163
+ const hasUppercase = /[A-Z]/.test(str);
164
+ const hasDigit = /\d/.test(str);
165
+ const hasSpecial = /\W/.test(str);
166
+ const valid = isLongEnough && hasLowercase && hasUppercase && hasDigit &&
167
+ hasSpecial;
168
+ // return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W)[a-zA-Z\d\W]{8,}$/.test(str);
169
+ return {
170
+ valid,
171
+ isLongEnough,
172
+ hasLowercase,
173
+ hasUppercase,
174
+ hasDigit,
175
+ hasSpecial,
176
+ };
147
177
  }
148
178
 
149
179
  /**
@@ -151,7 +181,7 @@ export function passwordStrength(str: string, minLength: number = 8) {
151
181
  */
152
182
 
153
183
  export function getTimeBasedUnique() {
154
- return Date.now().toString(36) + Math.random().toString(36).substring(2);
184
+ return Date.now().toString(36) + Math.random().toString(36).substring(2);
155
185
  }
156
186
 
157
187
  /**
@@ -159,7 +189,33 @@ export function getTimeBasedUnique() {
159
189
  */
160
190
 
161
191
  export function getAlphanumeric(str: string, space: boolean = false) {
162
- return str.replace(space ? /[^a-z0-9\s]/gi : /[^a-z0-9]/gi, '');
192
+ return str.replace(space ? /[^a-z0-9\s]/gi : /[^a-z0-9]/gi, "");
193
+ }
194
+
195
+ /**
196
+ * Build normalized unique list of names from raw search inputs
197
+ */
198
+
199
+ export function getSearchNames(
200
+ namesList: (string | null | undefined)[] = [],
201
+ ): string[] {
202
+ const parsedNames = (namesList || [])
203
+ .flatMap((s) => (s || "").split(/\s*(?:,|;|\n|\band\b)\s*/i))
204
+ .map((s) => s.trim())
205
+ .filter(Boolean);
206
+
207
+ const uniqueNames: string[] = [];
208
+ const seen = new Set<string>();
209
+
210
+ for (const name of parsedNames) {
211
+ const key = name.toLowerCase();
212
+ if (!seen.has(key)) {
213
+ seen.add(key);
214
+ uniqueNames.push(name);
215
+ }
216
+ }
217
+
218
+ return uniqueNames;
163
219
  }
164
220
 
165
221
  /**
@@ -167,15 +223,17 @@ export function getAlphanumeric(str: string, space: boolean = false) {
167
223
  */
168
224
 
169
225
  export function regexFromText(text: string) {
170
- const words = getAlphanumeric(text, true).split(/\s+/).filter((s) => s.length >= 2);
171
- if (!words.length) {
172
- return null;
173
- }
174
-
175
- return new RegExp(
176
- '\\b' + (words.length === 1 ? words[0] : '(?:' + words.join('|') + ')'),
177
- 'gi',
178
- );
226
+ const words = getAlphanumeric(text, true).split(/\s+/).filter((s) =>
227
+ s.length >= 2
228
+ );
229
+ if (!words.length) {
230
+ return null;
231
+ }
232
+
233
+ return new RegExp(
234
+ "\\b" + (words.length === 1 ? words[0] : "(?:" + words.join("|") + ")"),
235
+ "gi",
236
+ );
179
237
  }
180
238
 
181
239
  /**
@@ -183,10 +241,10 @@ export function regexFromText(text: string) {
183
241
  */
184
242
 
185
243
  export function ucFirst(str: string) {
186
- if (!str) {
187
- return '';
188
- }
189
- return str.charAt(0).toUpperCase() + str.slice(1);
244
+ if (!str) {
245
+ return "";
246
+ }
247
+ return str.charAt(0).toUpperCase() + str.slice(1);
190
248
  }
191
249
 
192
250
  /**
@@ -194,43 +252,47 @@ export function ucFirst(str: string) {
194
252
  */
195
253
 
196
254
  export function camelCaseToDash(str: string) {
197
- if (/^[A-Z0-9]+$/.test(str)) {
198
- return str.toLowerCase();
199
- }
200
- return str.replace(/[A-Z0-9]/g, (m, i) => {
201
- return `${i ? '-' : ''}${m.toLowerCase()}`;
202
- });
255
+ if (/^[A-Z0-9]+$/.test(str)) {
256
+ return str.toLowerCase();
257
+ }
258
+ return str.replace(/[A-Z0-9]/g, (m, i) => {
259
+ return `${i ? "-" : ""}${m.toLowerCase()}`;
260
+ });
203
261
  }
204
262
 
205
263
  /**
206
264
  * Shorten text to a paragraph length
207
265
  */
208
266
 
209
- export function shortenToParagraph(str: string, len: number, replaceDoubleLineBreaks?: boolean) {
210
- let trimedToParagraph = str || '';
211
- if (replaceDoubleLineBreaks) {
212
- trimedToParagraph = trimedToParagraph.replace(/\n\s*\n/g, '\n');
213
- }
214
-
215
- trimedToParagraph = trimedToParagraph.split('\n').reduce((acc, str) => {
216
- if (acc.done) {
217
- return acc;
218
- }
219
- acc.done = (acc.value.length + str.length) >= len;
220
- acc.value = acc.done ? acc.value : acc.value + '\n' + str;
221
- return acc;
222
- }, {
223
- done: false,
224
- value: '',
225
- }).value.trim();
226
-
227
- if (!trimedToParagraph) {
228
- return shortenToSpace(str || '', len);
229
- } else if (trimedToParagraph.length <= len) {
230
- return trimedToParagraph;
231
- }
232
-
233
- return shortenToSpace(trimedToParagraph, len);
267
+ export function shortenToParagraph(
268
+ str: string,
269
+ len: number,
270
+ replaceDoubleLineBreaks?: boolean,
271
+ ) {
272
+ let trimedToParagraph = str || "";
273
+ if (replaceDoubleLineBreaks) {
274
+ trimedToParagraph = trimedToParagraph.replace(/\n\s*\n/g, "\n");
275
+ }
276
+
277
+ trimedToParagraph = trimedToParagraph.split("\n").reduce((acc, str) => {
278
+ if (acc.done) {
279
+ return acc;
280
+ }
281
+ acc.done = (acc.value.length + str.length) >= len;
282
+ acc.value = acc.done ? acc.value : acc.value + "\n" + str;
283
+ return acc;
284
+ }, {
285
+ done: false,
286
+ value: "",
287
+ }).value.trim();
288
+
289
+ if (!trimedToParagraph) {
290
+ return shortenToSpace(str || "", len);
291
+ } else if (trimedToParagraph.length <= len) {
292
+ return trimedToParagraph;
293
+ }
294
+
295
+ return shortenToSpace(trimedToParagraph, len);
234
296
  }
235
297
 
236
298
  /**
@@ -238,14 +300,14 @@ export function shortenToParagraph(str: string, len: number, replaceDoubleLineBr
238
300
  */
239
301
 
240
302
  export function isInvisibleString(str: string) {
241
- if (!str?.trim()) {
242
- return true;
243
- }
244
-
245
- // eslint-disable-next-line no-misleading-character-class
246
- const invisRegex = /[ㅤ ️⠀ْٔ]/g;
247
- const checkStr = str.replace(invisRegex, ' '); // .replace(/[ㅤ ️⠀]/gi, ' ');
248
- return !checkStr.trim();
303
+ if (!str?.trim()) {
304
+ return true;
305
+ }
306
+
307
+ // eslint-disable-next-line no-misleading-character-class
308
+ const invisRegex = /[ㅤ ️⠀ْٔ]/g;
309
+ const checkStr = str.replace(invisRegex, " "); // .replace(/[ㅤ ️⠀]/gi, ' ');
310
+ return !checkStr.trim();
249
311
  }
250
312
 
251
313
  /**
@@ -254,31 +316,163 @@ export function isInvisibleString(str: string) {
254
316
  */
255
317
 
256
318
  type AnyLineItem = string | undefined | false | null;
319
+ type BuildSingleTextConditionalLine = [
320
+ string[],
321
+ BuildSingleTextLine | BuildSingleTextLine[],
322
+ ];
323
+ type BuildSingleTextConditionalLineGroup = BuildSingleTextConditionalLine[];
324
+ interface BuildSingleTextFeatureMap {
325
+ [key: string]: BuildSingleTextLine | BuildSingleTextLine[];
326
+ }
327
+
328
+ export type BuildSingleTextLine =
329
+ | AnyLineItem
330
+ | BuildSingleTextFeatureMap
331
+ | BuildSingleTextConditionalLine
332
+ | BuildSingleTextConditionalLineGroup;
333
+
334
+ /*
335
+ * Check whether a buildSingleText line uses the all-features conditional tuple syntax.
336
+ */
337
+
338
+ function isBuildSingleTextConditionalLine(
339
+ line: BuildSingleTextLine | BuildSingleTextLine[],
340
+ ): line is BuildSingleTextConditionalLine {
341
+ return Array.isArray(line) &&
342
+ line.length === 2 &&
343
+ Array.isArray(line[0]) &&
344
+ line[0].every((feature) => typeof feature === "string");
345
+ }
346
+
347
+ /*
348
+ * Check whether a buildSingleText line uses the first-match conditional group syntax.
349
+ */
350
+
351
+ function isBuildSingleTextConditionalLineGroup(
352
+ line: BuildSingleTextLine | BuildSingleTextLine[],
353
+ ): line is BuildSingleTextConditionalLineGroup {
354
+ return Array.isArray(line) &&
355
+ line.length > 0 &&
356
+ line.every((lineItem) => isBuildSingleTextConditionalLine(lineItem));
357
+ }
358
+
359
+ /*
360
+ * Check whether a buildSingleText requirement matches the enabled features.
361
+ */
362
+
363
+ function doesBuildSingleTextRequirementMatch(
364
+ requirement: string,
365
+ features: string[],
366
+ ) {
367
+ const isNegatedRequirement = requirement.startsWith("!");
368
+ const feature = isNegatedRequirement ? requirement.slice(1) : requirement;
369
+
370
+ if (!feature) {
371
+ return false;
372
+ }
373
+
374
+ const hasFeature = features.includes(feature);
375
+ return isNegatedRequirement ? !hasFeature : hasFeature;
376
+ }
377
+
378
+ /*
379
+ * Check whether a buildSingleText conditional line matches the enabled features.
380
+ */
381
+
382
+ function doesBuildSingleTextConditionalLineMatch(
383
+ conditionalLine: BuildSingleTextConditionalLine,
384
+ features: string[],
385
+ ) {
386
+ return conditionalLine[0].every((feature) => doesBuildSingleTextRequirementMatch(feature, features));
387
+ }
388
+
389
+ /*
390
+ * Build text for a conditional line payload.
391
+ */
392
+
393
+ function getBuildSingleTextConditionalText(
394
+ conditionalLines: BuildSingleTextLine | BuildSingleTextLine[],
395
+ delemiter: string,
396
+ features: string[],
397
+ ) {
398
+ return buildSingleText(
399
+ Array.isArray(conditionalLines) &&
400
+ !isBuildSingleTextConditionalLine(conditionalLines)
401
+ ? conditionalLines
402
+ : [conditionalLines],
403
+ delemiter,
404
+ features,
405
+ );
406
+ }
257
407
 
258
408
  export function buildSingleText(
259
- lines: (AnyLineItem | Record<string, AnyLineItem[]>)[],
260
- delemiter: string = '\n',
261
- features: string[] = [],
409
+ lines: BuildSingleTextLine[],
410
+ delemiter: string = "\n",
411
+ features: string[] = [],
262
412
  ) {
263
- return lines
264
- .reduce((acc, line_) => {
265
- const line = line_ || '';
266
- if (line && typeof line === 'object') {
267
- for (const key in line) {
268
- const lineItem = line[key];
269
- if (features.includes(key)) {
270
- acc.push(buildSingleText(lineItem, delemiter, features));
271
- }
272
- }
273
- return acc;
274
- }
275
- if (line || acc[acc.length - 1] !== '') {
276
- acc.push(line);
277
- }
278
- return acc;
279
- }, [] as string[])
280
- .join(delemiter)
281
- .trim();
413
+ return lines
414
+ .reduce((acc, line_) => {
415
+ const line = line_ || "";
416
+ if (isBuildSingleTextConditionalLineGroup(line)) {
417
+ const matchedConditionalLine = line.find((conditionalLine) =>
418
+ doesBuildSingleTextConditionalLineMatch(conditionalLine, features)
419
+ );
420
+
421
+ if (!matchedConditionalLine) {
422
+ return acc;
423
+ }
424
+
425
+ const conditionalText = getBuildSingleTextConditionalText(
426
+ matchedConditionalLine[1],
427
+ delemiter,
428
+ features,
429
+ );
430
+
431
+ if (conditionalText || acc[acc.length - 1] !== "") {
432
+ acc.push(conditionalText);
433
+ }
434
+
435
+ return acc;
436
+ }
437
+
438
+ if (isBuildSingleTextConditionalLine(line)) {
439
+ const [, conditionalLines] = line;
440
+
441
+ if (doesBuildSingleTextConditionalLineMatch(line, features)) {
442
+ const conditionalText = getBuildSingleTextConditionalText(
443
+ conditionalLines,
444
+ delemiter,
445
+ features,
446
+ );
447
+
448
+ if (conditionalText || acc[acc.length - 1] !== "") {
449
+ acc.push(conditionalText);
450
+ }
451
+ }
452
+
453
+ return acc;
454
+ }
455
+ if (line && typeof line === "object") {
456
+ for (const key in line) {
457
+ const lineItem = line[key];
458
+ if (features.includes(key)) {
459
+ const nextLines = Array.isArray(lineItem) &&
460
+ !isBuildSingleTextConditionalLine(lineItem)
461
+ ? lineItem
462
+ : [lineItem];
463
+ acc.push(buildSingleText(nextLines, delemiter, features));
464
+ }
465
+ }
466
+ return acc;
467
+ }
468
+ if (line || acc[acc.length - 1] !== "") {
469
+ acc.push(line);
470
+ }
471
+ return acc;
472
+ }, [] as string[])
473
+ .join(delemiter)
474
+ .trim()
475
+ .replace(/^[ \t]+(?=[A-Za-z0-9])/gm, '');
282
476
  }
283
477
 
284
478
  /**
@@ -291,14 +485,14 @@ export function buildSingleText(
291
485
  */
292
486
 
293
487
  export function joinReadable(
294
- texts: string[],
295
- separator: string = ', ',
296
- lastSeparator: string = ' and ',
297
- ) {
298
- const lastIx = texts.length - 1;
299
- return texts.filter(Boolean).reduce((acc, text, i) => {
300
- return acc + (!acc ? '' : i === lastIx ? lastSeparator : separator) + text;
301
- }, '');
488
+ texts: (string | null | undefined)[],
489
+ separator: string = ", ",
490
+ lastSeparator: string = " and ",
491
+ ): string {
492
+ const lastIx = texts.length - 1;
493
+ return texts.filter(Boolean).reduce<string>((acc, text, i) => {
494
+ return acc + (!acc ? "" : i === lastIx ? lastSeparator : separator) + text;
495
+ }, "");
302
496
  }
303
497
 
304
498
  /**
@@ -311,22 +505,22 @@ export function joinReadable(
311
505
  */
312
506
 
313
507
  export function textWithBrackets(
314
- text: string,
315
- bracketsText?: string | string[],
316
- brackets: [string, string] = ['(', ')'],
508
+ text: string,
509
+ bracketsText?: string | string[],
510
+ brackets: [string, string] = ["(", ")"],
317
511
  ) {
318
- let bText;
319
- if (Array.isArray(bracketsText)) {
320
- bText = bracketsText.filter(Boolean).join(' ').trim();
321
- } else {
322
- bText = bracketsText?.trim();
323
- }
324
- if (!bText) {
325
- return text;
326
- } else if (!text) {
327
- return bText;
328
- }
329
- return `${text} ${brackets[0].trimStart()}${bText}${brackets[1].trimEnd()}`;
512
+ let bText;
513
+ if (Array.isArray(bracketsText)) {
514
+ bText = bracketsText.filter(Boolean).join(" ").trim();
515
+ } else {
516
+ bText = bracketsText?.trim();
517
+ }
518
+ if (!bText) {
519
+ return text;
520
+ } else if (!text) {
521
+ return bText;
522
+ }
523
+ return `${text} ${brackets[0].trimStart()}${bText}${brackets[1].trimEnd()}`;
330
524
  }
331
525
 
332
526
  /**
@@ -338,11 +532,11 @@ export function textWithBrackets(
338
532
  */
339
533
 
340
534
  export function removeGeneratedTextGarbage(str: string) {
341
- if (!str || typeof str !== 'string') {
342
- return '';
343
- }
344
- // Remove all line breaks and spaces
345
- return str.replace(/[\n\r\s]+/g, ' ').trim();
535
+ if (!str || typeof str !== "string") {
536
+ return "";
537
+ }
538
+ // Remove all line breaks and spaces
539
+ return str.replace(/[\n\r\s]+/g, " ").trim();
346
540
  }
347
541
 
348
542
  /**
@@ -352,10 +546,25 @@ export function removeGeneratedTextGarbage(str: string) {
352
546
  */
353
547
 
354
548
  export function escapeCSVValue(value: string): string {
355
- if (/[",\n]/.test(value)) {
356
- return `"${value.replace(/"/g, '""')}"`;
357
- }
358
- return value;
549
+ if (/[",\n]/.test(value)) {
550
+ return `"${value.replace(/"/g, '""')}"`;
551
+ }
552
+ return value;
553
+ }
554
+
555
+ /**
556
+ * Truncate a file name while preserving extension when possible.
557
+ */
558
+
559
+ export function truncateFileName(fileName: string, maxLen = 34) {
560
+ if (fileName.length <= maxLen) {
561
+ return fileName;
562
+ }
563
+
564
+ const extIndex = fileName.lastIndexOf(".");
565
+ const ext = extIndex > 0 ? fileName.slice(extIndex) : "";
566
+ const headLen = Math.max(1, maxLen - ext.length - 3);
567
+ return fileName.slice(0, headLen) + "..." + ext;
359
568
  }
360
569
 
361
570
  /**
@@ -364,15 +573,23 @@ export function escapeCSVValue(value: string): string {
364
573
  */
365
574
 
366
575
  export function formatPhoneNumber(phone?: string | null) {
367
- const match = phone?.match(/(\d{3})(\d{3})(\d{4})$/);
368
- if (match) {
369
- const [, area, first, second] = match;
370
- const countryCode = phone!.substring(0, phone.length - area.length - first.length - second.length);
371
- // NOTE: This does not account for non North American (+1) phone numbers
372
- return `${countryCode} (${area}) ${first}-${second}`;
373
- }
374
-
375
- return phone;
576
+ const match = phone?.match(/(\d{3})(\d{3})(\d{4})$/);
577
+ if (match) {
578
+ const [, area, first, second] = match;
579
+ const countryCode = phone!.substring(
580
+ 0,
581
+ phone!.length - area.length - first.length - second.length,
582
+ ).trim();
583
+ const normalizedCountryCode = countryCode
584
+ ? countryCode.startsWith("+") ? countryCode : `+${countryCode}`
585
+ : "";
586
+ // NOTE: This does not account for non North American (+1) phone numbers
587
+ return `${normalizedCountryCode}${
588
+ normalizedCountryCode ? " " : ""
589
+ }(${area}) ${first}-${second}`;
590
+ }
591
+
592
+ return phone;
376
593
  }
377
594
 
378
595
  /**
@@ -383,43 +600,50 @@ export function formatPhoneNumber(phone?: string | null) {
383
600
  * @returns An array of text chunks.
384
601
  */
385
602
 
386
- export function splitTextIntoChunks(text: string, chunkSize: number, linebreakDistance: number = 50): string[] {
387
- if (!text || chunkSize <= 0 || text.length < chunkSize) {
388
- return [text || ''];
389
- }
390
-
391
- const chunks: string[] = [];
392
- let start = 0;
393
-
394
- while (start < text.length) {
395
- let end = Math.min(start + chunkSize, text.length);
396
-
397
- if (end < text.length) {
398
- // Find the nearest line break around the target chunk boundary
399
- const beforeBreak = text.lastIndexOf('\n', end);
400
-
401
- let chosenBreak = -1;
402
- if (beforeBreak !== -1 && end - beforeBreak <= linebreakDistance && beforeBreak > start) {
403
- chosenBreak = beforeBreak + 1;
404
- }
405
-
406
- if (chosenBreak !== -1) {
407
- end = chosenBreak;
408
- } else {
409
- // Fall back to last whitespace near the end
410
- const lastSpace = text.lastIndexOf(' ', end);
411
- if (lastSpace > start && end - lastSpace < 100) {
412
- end = lastSpace;
413
- }
414
- }
415
- }
416
-
417
- const chunk = text.slice(start, end).trim();
418
- if (chunk) chunks.push(chunk);
419
- start = end;
420
- }
421
-
422
- return chunks;
603
+ export function splitTextIntoChunks(
604
+ text: string,
605
+ chunkSize: number,
606
+ linebreakDistance: number = 50,
607
+ ): string[] {
608
+ if (!text || chunkSize <= 0 || text.length < chunkSize) {
609
+ return [text || ""];
610
+ }
611
+
612
+ const chunks: string[] = [];
613
+ let start = 0;
614
+
615
+ while (start < text.length) {
616
+ let end = Math.min(start + chunkSize, text.length);
617
+
618
+ if (end < text.length) {
619
+ // Find the nearest line break around the target chunk boundary
620
+ const beforeBreak = text.lastIndexOf("\n", end);
621
+
622
+ let chosenBreak = -1;
623
+ if (
624
+ beforeBreak !== -1 && end - beforeBreak <= linebreakDistance &&
625
+ beforeBreak > start
626
+ ) {
627
+ chosenBreak = beforeBreak + 1;
628
+ }
629
+
630
+ if (chosenBreak !== -1) {
631
+ end = chosenBreak;
632
+ } else {
633
+ // Fall back to last whitespace near the end
634
+ const lastSpace = text.lastIndexOf(" ", end);
635
+ if (lastSpace > start && end - lastSpace < 100) {
636
+ end = lastSpace;
637
+ }
638
+ }
639
+ }
640
+
641
+ const chunk = text.slice(start, end).trim();
642
+ if (chunk) chunks.push(chunk);
643
+ start = end;
644
+ }
645
+
646
+ return chunks;
423
647
  }
424
648
 
425
649
  /**
@@ -427,10 +651,10 @@ export function splitTextIntoChunks(text: string, chunkSize: number, linebreakDi
427
651
  */
428
652
 
429
653
  export function formatReferenceNumber(idStr: string) {
430
- if (idStr && /^\d+$/.test(idStr)) {
431
- return '#' + idStr;
432
- }
433
- return idStr;
654
+ if (idStr && /^\d+$/.test(idStr)) {
655
+ return "#" + idStr;
656
+ }
657
+ return idStr;
434
658
  }
435
659
 
436
660
  /**
@@ -440,18 +664,18 @@ export function formatReferenceNumber(idStr: string) {
440
664
  */
441
665
 
442
666
  export function getNthString(num: number): string {
443
- const mod10 = num % 10;
444
- const mod100 = num % 100;
445
-
446
- if (mod10 === 1 && mod100 !== 11) {
447
- return `${num}st`;
448
- } else if (mod10 === 2 && mod100 !== 12) {
449
- return `${num}nd`;
450
- } else if (mod10 === 3 && mod100 !== 13) {
451
- return `${num}rd`;
452
- } else {
453
- return `${num}th`;
454
- }
667
+ const mod10 = num % 10;
668
+ const mod100 = num % 100;
669
+
670
+ if (mod10 === 1 && mod100 !== 11) {
671
+ return `${num}st`;
672
+ } else if (mod10 === 2 && mod100 !== 12) {
673
+ return `${num}nd`;
674
+ } else if (mod10 === 3 && mod100 !== 13) {
675
+ return `${num}rd`;
676
+ } else {
677
+ return `${num}th`;
678
+ }
455
679
  }
456
680
 
457
681
  /**
@@ -463,44 +687,60 @@ export function getNthString(num: number): string {
463
687
  */
464
688
 
465
689
  export function makeAddressText(
466
- address: Partial<AddressObj>,
467
- format: 'REGION_ONLY' | 'SINGLE_LINE' | 'NORMAL' = 'NORMAL',
468
- useFullCountryName: boolean = false,
469
- delimiter: string = ', ',
690
+ address: Partial<AddressObj>,
691
+ format: "REGION_ONLY" | "SINGLE_LINE" | "NORMAL" = "NORMAL",
692
+ useFullCountryName: boolean = false,
693
+ delimiter: string = ", ",
470
694
  ) {
471
- if (!address) {
472
- return null;
473
- }
474
-
475
- const countryName = useFullCountryName && i18n.has(`country.from_code.${address.country}`)
476
- ? i18n.t(`country.from_code.${address.country}`)
477
- : address.country;
478
-
479
- if (format === 'REGION_ONLY') {
480
- return [
481
- address.city,
482
- address.state,
483
- countryName,
484
- ].filter(Boolean).join(delimiter);
485
- } else if (format === 'SINGLE_LINE') {
486
- return [
487
- address.line1,
488
- address.line2,
489
- address.city,
490
- address.state,
491
- address.postalCode,
492
- countryName,
493
- ].filter(Boolean).join(delimiter);
494
- }
495
-
496
- // NORMAL format
497
- return [
498
- address.line1,
499
- address.line2,
500
- [
501
- [address.city, address.state].filter(Boolean).join(', '),
502
- address.postalCode,
503
- ].filter(Boolean).join(' '),
504
- countryName,
505
- ].filter(Boolean).join('\n');
695
+ if (!address) {
696
+ return null;
697
+ }
698
+
699
+ const countryName =
700
+ useFullCountryName && i18n.has(`country.from_code.${address.country}`)
701
+ ? i18n.t(`country.from_code.${address.country}`)
702
+ : address.country;
703
+
704
+ if (format === "REGION_ONLY") {
705
+ return [
706
+ address.city,
707
+ address.state,
708
+ countryName,
709
+ ].filter(Boolean).join(delimiter);
710
+ } else if (format === "SINGLE_LINE") {
711
+ return [
712
+ address.line1,
713
+ address.line2,
714
+ address.city,
715
+ address.state,
716
+ address.postalCode,
717
+ countryName,
718
+ ].filter(Boolean).join(delimiter);
719
+ }
720
+
721
+ // NORMAL format
722
+ return [
723
+ address.line1,
724
+ address.line2,
725
+ [
726
+ [address.city, address.state].filter(Boolean).join(", "),
727
+ address.postalCode,
728
+ ].filter(Boolean).join(" "),
729
+ countryName,
730
+ ].filter(Boolean).join("\n");
731
+ }
732
+
733
+ /**
734
+ * Get display name from first and last name
735
+ * @returns Formatted display name
736
+ */
737
+
738
+ export function getDisplayName(firstName?: string | null, lastName?: string | null) {
739
+ const fullName = buildSingleText([firstName, lastName], ' ');
740
+ const displayName = guessFirstName(fullName, 8) || '?';
741
+
742
+ return {
743
+ fullName,
744
+ displayName
745
+ };
506
746
  }