@mohasinac/utils 0.1.0 → 1.1.0

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/dist/index.cjs CHANGED
@@ -2,7 +2,21 @@
2
2
  var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
6
20
  var __export = (target, all) => {
7
21
  for (var name in all)
8
22
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -20,17 +34,31 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
34
  // src/index.ts
21
35
  var index_exports = {};
22
36
  __export(index_exports, {
37
+ GlobalEventManager: () => GlobalEventManager,
38
+ addGlobalClickHandler: () => addGlobalClickHandler,
39
+ addGlobalKeyHandler: () => addGlobalKeyHandler,
40
+ addGlobalResizeHandler: () => addGlobalResizeHandler,
41
+ addGlobalScrollHandler: () => addGlobalScrollHandler,
23
42
  arrayToObject: () => arrayToObject,
24
43
  booleanToString: () => booleanToString,
44
+ buildSieveFilters: () => buildSieveFilters,
45
+ calculatePagination: () => calculatePagination,
25
46
  capitalize: () => capitalize,
26
47
  capitalizeWords: () => capitalizeWords,
48
+ chunk: () => chunk,
49
+ cleanObject: () => cleanObject,
27
50
  currentYear: () => currentYear,
28
51
  dateToISOString: () => dateToISOString,
52
+ debounce: () => debounce,
53
+ deepClone: () => deepClone,
54
+ deepMerge: () => deepMerge,
29
55
  deleteCookie: () => deleteCookie,
56
+ easings: () => easings,
30
57
  escapeHtml: () => escapeHtml,
31
58
  firestoreTimestampToDate: () => firestoreTimestampToDate,
32
59
  formatCompactNumber: () => formatCompactNumber,
33
60
  formatCurrency: () => formatCurrency,
61
+ formatCustomDate: () => formatCustomDate,
34
62
  formatDate: () => formatDate,
35
63
  formatDateRange: () => formatDateRange,
36
64
  formatDateTime: () => formatDateTime,
@@ -56,10 +84,20 @@ __export(index_exports, {
56
84
  generateProductId: () => generateProductId,
57
85
  generateReviewId: () => generateReviewId,
58
86
  generateUserId: () => generateUserId,
87
+ getContrastColor: () => getContrastColor,
59
88
  getCookie: () => getCookie,
89
+ getViewportDimensions: () => getViewportDimensions,
90
+ globalEventManager: () => globalEventManager,
91
+ groupBy: () => groupBy,
60
92
  hasCookie: () => hasCookie,
93
+ hasTouchSupport: () => hasTouchSupport,
94
+ hexToRgb: () => hexToRgb,
95
+ isEmptyObject: () => isEmptyObject,
61
96
  isEmptyString: () => isEmptyString,
97
+ isEqual: () => isEqual,
62
98
  isFuture: () => isFuture,
99
+ isInViewport: () => isInViewport,
100
+ isMobileDevice: () => isMobileDevice,
63
101
  isPast: () => isPast,
64
102
  isSameMonth: () => isSameMonth,
65
103
  isToday: () => isToday,
@@ -68,17 +106,29 @@ __export(index_exports, {
68
106
  nowMs: () => nowMs,
69
107
  objectToArray: () => objectToArray,
70
108
  objectToQueryString: () => objectToQueryString,
109
+ omit: () => omit,
110
+ paginate: () => paginate,
71
111
  parseCookies: () => parseCookies,
72
112
  parseFormattedNumber: () => parseFormattedNumber,
113
+ pick: () => pick,
114
+ preventBodyScroll: () => preventBodyScroll,
73
115
  proseMirrorToHtml: () => proseMirrorToHtml,
74
116
  queryStringToObject: () => queryStringToObject,
75
117
  randomString: () => randomString,
118
+ removeGlobalHandler: () => removeGlobalHandler,
76
119
  resolveDate: () => resolveDate,
120
+ rgbToHex: () => rgbToHex,
77
121
  slugify: () => slugify,
122
+ smoothScrollTo: () => smoothScrollTo,
123
+ sort: () => sort,
124
+ sortBy: () => sortBy,
78
125
  stringToBoolean: () => stringToBoolean,
79
126
  stripHtml: () => stripHtml,
127
+ throttle: () => throttle,
80
128
  truncate: () => truncate,
81
- truncateWords: () => truncateWords
129
+ truncateWords: () => truncateWords,
130
+ unique: () => unique,
131
+ uniqueBy: () => uniqueBy
82
132
  });
83
133
  module.exports = __toCommonJS(index_exports);
84
134
 
@@ -234,6 +284,17 @@ function currentYear() {
234
284
  function nowISO() {
235
285
  return new Date(nowMs()).toISOString();
236
286
  }
287
+ function formatCustomDate(date, format = "medium") {
288
+ const dateObj = typeof date === "string" ? new Date(date) : date;
289
+ const formatOptions = {
290
+ short: { month: "numeric", day: "numeric", year: "2-digit" },
291
+ medium: { month: "short", day: "numeric", year: "numeric" },
292
+ long: { month: "long", day: "numeric", year: "numeric" },
293
+ full: { weekday: "long", month: "long", day: "numeric", year: "numeric" }
294
+ };
295
+ const options = formatOptions[format] || formatOptions.medium;
296
+ return dateObj.toLocaleDateString("en-US", options);
297
+ }
237
298
 
238
299
  // src/number.formatter.ts
239
300
  function formatCurrency(amount, currency = "USD", locale = "en-US") {
@@ -609,19 +670,371 @@ function generatePayoutId(input) {
609
670
  const d = String(date.getDate()).padStart(2, "0");
610
671
  return `payout-${sellerSlug}-${y}${m}${d}-${generateRandomString(6)}`;
611
672
  }
673
+
674
+ // src/array.helper.ts
675
+ function groupBy(array, key) {
676
+ return array.reduce(
677
+ (result, item) => {
678
+ const groupKey = String(item[key]);
679
+ if (!result[groupKey]) {
680
+ result[groupKey] = [];
681
+ }
682
+ result[groupKey].push(item);
683
+ return result;
684
+ },
685
+ {}
686
+ );
687
+ }
688
+ function unique(array) {
689
+ return Array.from(new Set(array));
690
+ }
691
+ function uniqueBy(array, key) {
692
+ const seen = /* @__PURE__ */ new Set();
693
+ return array.filter((item) => {
694
+ const value = item[key];
695
+ if (seen.has(value)) return false;
696
+ seen.add(value);
697
+ return true;
698
+ });
699
+ }
700
+ function sortBy(array, key, order = "asc") {
701
+ return [...array].sort((a, b) => {
702
+ const aVal = a[key];
703
+ const bVal = b[key];
704
+ if (aVal < bVal) return order === "asc" ? -1 : 1;
705
+ if (aVal > bVal) return order === "asc" ? 1 : -1;
706
+ return 0;
707
+ });
708
+ }
709
+ function chunk(array, size) {
710
+ const chunks = [];
711
+ for (let i = 0; i < array.length; i += size) {
712
+ chunks.push(array.slice(i, i + size));
713
+ }
714
+ return chunks;
715
+ }
716
+ function paginate(array, page, perPage) {
717
+ const total = array.length;
718
+ const totalPages = Math.ceil(total / perPage);
719
+ const start = (page - 1) * perPage;
720
+ const end = start + perPage;
721
+ return { data: array.slice(start, end), total, page, perPage, totalPages };
722
+ }
723
+
724
+ // src/object.helper.ts
725
+ function deepMerge(target, source) {
726
+ const output = __spreadValues({}, target);
727
+ Object.keys(source).forEach((key) => {
728
+ const sourceValue = source[key];
729
+ const targetValue = target[key];
730
+ if (sourceValue && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue && typeof targetValue === "object" && !Array.isArray(targetValue)) {
731
+ output[key] = deepMerge(targetValue, sourceValue);
732
+ } else {
733
+ output[key] = sourceValue;
734
+ }
735
+ });
736
+ return output;
737
+ }
738
+ function pick(obj, keys) {
739
+ const result = {};
740
+ keys.forEach((key) => {
741
+ if (key in obj) result[key] = obj[key];
742
+ });
743
+ return result;
744
+ }
745
+ function omit(obj, keys) {
746
+ const result = __spreadValues({}, obj);
747
+ keys.forEach((key) => {
748
+ delete result[key];
749
+ });
750
+ return result;
751
+ }
752
+ function isEmptyObject(obj) {
753
+ return Object.keys(obj).length === 0;
754
+ }
755
+ function deepClone(obj) {
756
+ if (obj === null || typeof obj !== "object") return obj;
757
+ if (Array.isArray(obj))
758
+ return obj.map((item) => deepClone(item));
759
+ const cloned = {};
760
+ Object.keys(obj).forEach((key) => {
761
+ cloned[key] = deepClone(obj[key]);
762
+ });
763
+ return cloned;
764
+ }
765
+ function isEqual(obj1, obj2) {
766
+ if (obj1 === obj2) return true;
767
+ if (typeof obj1 !== "object" || typeof obj2 !== "object" || obj1 === null || obj2 === null) {
768
+ return false;
769
+ }
770
+ const keys1 = Object.keys(obj1);
771
+ const keys2 = Object.keys(obj2);
772
+ if (keys1.length !== keys2.length) return false;
773
+ return keys1.every((key) => isEqual(obj1[key], obj2[key]));
774
+ }
775
+ function cleanObject(obj, options = {}) {
776
+ const {
777
+ removeEmpty = true,
778
+ removeNull = true,
779
+ removeUndefined = true
780
+ } = options;
781
+ return Object.entries(obj).reduce((acc, [key, value]) => {
782
+ const shouldRemove = removeUndefined && value === void 0 || removeNull && value === null || removeEmpty && value === "";
783
+ if (!shouldRemove) acc[key] = value;
784
+ return acc;
785
+ }, {});
786
+ }
787
+
788
+ // src/pagination.helper.ts
789
+ function calculatePagination(options) {
790
+ const { page, perPage, total } = options;
791
+ const totalPages = Math.ceil(total / perPage);
792
+ const currentPage = Math.max(1, Math.min(page, totalPages));
793
+ const startIndex = (currentPage - 1) * perPage;
794
+ const endIndex = Math.min(startIndex + perPage, total);
795
+ return {
796
+ currentPage,
797
+ perPage,
798
+ total,
799
+ totalPages,
800
+ hasNextPage: currentPage < totalPages,
801
+ hasPrevPage: currentPage > 1,
802
+ nextPage: currentPage < totalPages ? currentPage + 1 : null,
803
+ prevPage: currentPage > 1 ? currentPage - 1 : null,
804
+ startIndex,
805
+ endIndex
806
+ };
807
+ }
808
+
809
+ // src/sorting.helper.ts
810
+ function sort(array, key, order = "asc") {
811
+ return [...array].sort((a, b) => {
812
+ const aVal = a[key];
813
+ const bVal = b[key];
814
+ if (aVal < bVal) return order === "asc" ? -1 : 1;
815
+ if (aVal > bVal) return order === "asc" ? 1 : -1;
816
+ return 0;
817
+ });
818
+ }
819
+
820
+ // src/filter.helper.ts
821
+ function buildSieveFilters(...entries) {
822
+ return entries.filter((entry) => !!entry[1]).map(([expr, value]) => `${expr}${value}`).join(",");
823
+ }
824
+
825
+ // src/animation.helper.ts
826
+ var easings = {
827
+ linear: (t) => t,
828
+ easeInQuad: (t) => t * t,
829
+ easeOutQuad: (t) => t * (2 - t),
830
+ easeInOutQuad: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
831
+ easeInCubic: (t) => t * t * t,
832
+ easeOutCubic: (t) => --t * t * t + 1,
833
+ easeInOutCubic: (t) => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,
834
+ easeInQuart: (t) => t * t * t * t,
835
+ easeOutQuart: (t) => 1 - --t * t * t * t,
836
+ easeInOutQuart: (t) => t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t
837
+ };
838
+
839
+ // src/color.helper.ts
840
+ function hexToRgb(hex) {
841
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
842
+ return result ? {
843
+ r: parseInt(result[1], 16),
844
+ g: parseInt(result[2], 16),
845
+ b: parseInt(result[3], 16)
846
+ } : null;
847
+ }
848
+ function rgbToHex(r, g, b) {
849
+ return "#" + [r, g, b].map((x) => {
850
+ const hex = x.toString(16);
851
+ return hex.length === 1 ? "0" + hex : hex;
852
+ }).join("");
853
+ }
854
+ function getContrastColor(hex) {
855
+ const rgb = hexToRgb(hex);
856
+ if (!rgb) return "#000000";
857
+ const luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
858
+ return luminance > 0.5 ? "#000000" : "#ffffff";
859
+ }
860
+
861
+ // src/event-manager.ts
862
+ var GlobalEventManager = class {
863
+ constructor() {
864
+ this.handlers = /* @__PURE__ */ new Map();
865
+ this.handlerIds = /* @__PURE__ */ new Map();
866
+ }
867
+ generateId(type, target) {
868
+ var _a;
869
+ const targetId = this.getTargetId(target);
870
+ const key = `${type}-${targetId}`;
871
+ const count = ((_a = this.handlerIds.get(key)) != null ? _a : 0) + 1;
872
+ this.handlerIds.set(key, count);
873
+ return `${key}-${count}`;
874
+ }
875
+ getTargetId(target) {
876
+ if (target === window) return "window";
877
+ if (target === document) return "document";
878
+ if (target instanceof HTMLElement && target.id) return target.id;
879
+ return `element-${crypto.randomUUID()}`;
880
+ }
881
+ add(target, type, callback, options) {
882
+ const id = this.generateId(type, target);
883
+ if (!this.handlers.has(id)) this.handlers.set(id, []);
884
+ this.handlers.get(id).push({ type, target, callback, options });
885
+ target.addEventListener(type, callback, options);
886
+ return id;
887
+ }
888
+ remove(id) {
889
+ const handlers = this.handlers.get(id);
890
+ if (!handlers) return;
891
+ handlers.forEach(({ type, target, callback, options }) => target.removeEventListener(type, callback, options));
892
+ this.handlers.delete(id);
893
+ }
894
+ removeAllForTarget(target, type) {
895
+ const toRemove = [];
896
+ this.handlers.forEach((handlers, id) => {
897
+ const matchesTarget = handlers.some((h) => h.target === target);
898
+ const matchesType = !type || handlers.some((h) => h.type === type);
899
+ if (matchesTarget && matchesType) toRemove.push(id);
900
+ });
901
+ toRemove.forEach((id) => this.remove(id));
902
+ }
903
+ clear() {
904
+ this.handlers.forEach(
905
+ (handlers) => handlers.forEach(({ type, target, callback, options }) => target.removeEventListener(type, callback, options))
906
+ );
907
+ this.handlers.clear();
908
+ this.handlerIds.clear();
909
+ }
910
+ getHandlerCount() {
911
+ return this.handlers.size;
912
+ }
913
+ has(id) {
914
+ return this.handlers.has(id);
915
+ }
916
+ };
917
+ var globalEventManager = new GlobalEventManager();
918
+ function throttle(func, delay) {
919
+ let timeoutId = null;
920
+ let lastRun = 0;
921
+ return (...args) => {
922
+ const now = Date.now();
923
+ if (now - lastRun >= delay) {
924
+ func(...args);
925
+ lastRun = now;
926
+ } else {
927
+ if (timeoutId) clearTimeout(timeoutId);
928
+ timeoutId = setTimeout(() => {
929
+ func(...args);
930
+ lastRun = Date.now();
931
+ }, delay - (now - lastRun));
932
+ }
933
+ };
934
+ }
935
+ function debounce(func, delay) {
936
+ let timeoutId = null;
937
+ return (...args) => {
938
+ if (timeoutId) clearTimeout(timeoutId);
939
+ timeoutId = setTimeout(() => func(...args), delay);
940
+ };
941
+ }
942
+ function addGlobalScrollHandler(callback, options) {
943
+ const { throttle: throttleDelay = 100, target = window } = options != null ? options : {};
944
+ const handler = throttleDelay > 0 ? throttle(callback, throttleDelay) : callback;
945
+ return globalEventManager.add(target, "scroll", handler, { passive: true });
946
+ }
947
+ function addGlobalResizeHandler(callback, options) {
948
+ const { throttle: throttleDelay = 200 } = options != null ? options : {};
949
+ const handler = throttleDelay > 0 ? throttle(callback, throttleDelay) : callback;
950
+ return globalEventManager.add(window, "resize", handler);
951
+ }
952
+ function addGlobalClickHandler(selector, callback, options) {
953
+ const handler = (event) => {
954
+ const element = event.target.closest(selector);
955
+ if (element) {
956
+ if (options == null ? void 0 : options.preventDefault) event.preventDefault();
957
+ callback(event, element);
958
+ }
959
+ };
960
+ return globalEventManager.add(document, "click", handler);
961
+ }
962
+ function addGlobalKeyHandler(key, callback, options) {
963
+ const keys = Array.isArray(key) ? key : [key];
964
+ const { preventDefault = false, ctrl = false, shift = false, alt = false, meta = false } = options != null ? options : {};
965
+ const handler = (event) => {
966
+ const e = event;
967
+ if (!keys.some((k) => e.key === k || e.code === k)) return;
968
+ if (e.ctrlKey !== ctrl || e.shiftKey !== shift || e.altKey !== alt || e.metaKey !== meta) return;
969
+ if (preventDefault) event.preventDefault();
970
+ callback(e);
971
+ };
972
+ return globalEventManager.add(document, "keydown", handler);
973
+ }
974
+ function removeGlobalHandler(id) {
975
+ globalEventManager.remove(id);
976
+ }
977
+ function isMobileDevice() {
978
+ if (typeof window === "undefined") return false;
979
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
980
+ }
981
+ function hasTouchSupport() {
982
+ if (typeof window === "undefined") return false;
983
+ return "ontouchstart" in window || navigator.maxTouchPoints > 0;
984
+ }
985
+ function getViewportDimensions() {
986
+ if (typeof window === "undefined") return { width: 0, height: 0 };
987
+ return { width: window.innerWidth || document.documentElement.clientWidth, height: window.innerHeight || document.documentElement.clientHeight };
988
+ }
989
+ function isInViewport(element, offset = 0) {
990
+ if (typeof window === "undefined") return false;
991
+ const rect = element.getBoundingClientRect();
992
+ const { width, height } = getViewportDimensions();
993
+ return rect.top >= -offset && rect.left >= -offset && rect.bottom <= height + offset && rect.right <= width + offset;
994
+ }
995
+ function smoothScrollTo(element, options) {
996
+ const target = typeof element === "string" ? document.querySelector(element) : element;
997
+ if (!target) return;
998
+ const { offset = 0 } = options != null ? options : {};
999
+ window.scrollTo({ top: target.getBoundingClientRect().top + window.pageYOffset - offset, behavior: "smooth" });
1000
+ }
1001
+ function preventBodyScroll(prevent) {
1002
+ if (typeof document === "undefined") return;
1003
+ if (prevent) {
1004
+ document.body.style.overflow = "hidden";
1005
+ document.body.style.paddingRight = `${window.innerWidth - document.documentElement.clientWidth}px`;
1006
+ } else {
1007
+ document.body.style.overflow = "";
1008
+ document.body.style.paddingRight = "";
1009
+ }
1010
+ }
612
1011
  // Annotate the CommonJS export names for ESM import in node:
613
1012
  0 && (module.exports = {
1013
+ GlobalEventManager,
1014
+ addGlobalClickHandler,
1015
+ addGlobalKeyHandler,
1016
+ addGlobalResizeHandler,
1017
+ addGlobalScrollHandler,
614
1018
  arrayToObject,
615
1019
  booleanToString,
1020
+ buildSieveFilters,
1021
+ calculatePagination,
616
1022
  capitalize,
617
1023
  capitalizeWords,
1024
+ chunk,
1025
+ cleanObject,
618
1026
  currentYear,
619
1027
  dateToISOString,
1028
+ debounce,
1029
+ deepClone,
1030
+ deepMerge,
620
1031
  deleteCookie,
1032
+ easings,
621
1033
  escapeHtml,
622
1034
  firestoreTimestampToDate,
623
1035
  formatCompactNumber,
624
1036
  formatCurrency,
1037
+ formatCustomDate,
625
1038
  formatDate,
626
1039
  formatDateRange,
627
1040
  formatDateTime,
@@ -647,10 +1060,20 @@ function generatePayoutId(input) {
647
1060
  generateProductId,
648
1061
  generateReviewId,
649
1062
  generateUserId,
1063
+ getContrastColor,
650
1064
  getCookie,
1065
+ getViewportDimensions,
1066
+ globalEventManager,
1067
+ groupBy,
651
1068
  hasCookie,
1069
+ hasTouchSupport,
1070
+ hexToRgb,
1071
+ isEmptyObject,
652
1072
  isEmptyString,
1073
+ isEqual,
653
1074
  isFuture,
1075
+ isInViewport,
1076
+ isMobileDevice,
654
1077
  isPast,
655
1078
  isSameMonth,
656
1079
  isToday,
@@ -659,15 +1082,27 @@ function generatePayoutId(input) {
659
1082
  nowMs,
660
1083
  objectToArray,
661
1084
  objectToQueryString,
1085
+ omit,
1086
+ paginate,
662
1087
  parseCookies,
663
1088
  parseFormattedNumber,
1089
+ pick,
1090
+ preventBodyScroll,
664
1091
  proseMirrorToHtml,
665
1092
  queryStringToObject,
666
1093
  randomString,
1094
+ removeGlobalHandler,
667
1095
  resolveDate,
1096
+ rgbToHex,
668
1097
  slugify,
1098
+ smoothScrollTo,
1099
+ sort,
1100
+ sortBy,
669
1101
  stringToBoolean,
670
1102
  stripHtml,
1103
+ throttle,
671
1104
  truncate,
672
- truncateWords
1105
+ truncateWords,
1106
+ unique,
1107
+ uniqueBy
673
1108
  });