@ktjs/shared 0.23.17 → 0.23.19

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.d.ts CHANGED
@@ -1,199 +1,161 @@
1
- export declare const $append: typeof originAppend;
2
-
3
- /**
4
- * & Remove `bind` because it is shockingly slower than wrapper
5
- * & `window.document` is safe because it is not configurable and its setter is undefined
6
- */
7
- export declare const $appendChild: <T extends Node>(node: T) => T;
8
-
9
- /**
10
- * Used for `k-model`
11
- */
12
- export declare const $applyModel: (element: HTMLElementTagNameMap[InputElementTag], valueRef: {
13
- value: unknown;
14
- addOnChange: (fn: (newValue: unknown) => void) => void;
15
- }, propName: "value" | "checked", eventName: "change" | "input") => void;
16
-
17
- export declare const $ArrayFrom: {
18
- <T>(arrayLike: ArrayLike<T>): T[];
19
- <T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[];
20
- <T>(iterable: Iterable<T> | ArrayLike<T>): T[];
21
- <T, U>(iterable: Iterable<T> | ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[];
22
- };
23
-
24
- export declare const $assign: {
25
- <T extends {}, U>(target: T, source: U): T & U;
26
- <T extends {}, U, V>(target: T, source1: U, source2: V): T & U & V;
27
- <T extends {}, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
28
- (target: object, ...sources: any[]): any;
29
- };
30
-
31
- export declare const $buttonDisabledGetter: () => any;
32
-
33
- export declare const $buttonDisabledSetter: (v: any) => void;
34
-
35
- export declare const $define: <T>(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType<any>) => T;
36
-
37
- export declare const $defines: <T>(o: T, properties: PropertyDescriptorMap & ThisType<any>) => T;
38
-
39
- export declare const $emptyArray: any[];
40
-
41
- /**
42
- * Default empty function
43
- */
44
- export declare const $emptyFn: (...args: any[]) => any;
45
-
46
- export declare const $emptyObject: any;
47
-
48
- export declare const $entries: <T>(o: T) => Array<[keyof T, T[keyof T]]>;
49
-
50
- /**
51
- * Safe and quick forEach implementation that works with array-like objects and handles sparse arrays.
52
- */
53
- export declare const $forEach: (array: unknown[], callback: (item: unknown, index: number, array: unknown[]) => void) => void;
54
-
55
- /**
56
- * Async version of $forEach that allows for asynchronous callbacks. It processes items sequentially, awaiting each callback before moving to the next.
57
- */
58
- export declare const $forEachAsync: (array: unknown[], callback: (item: unknown, index: number, array: unknown[]) => void) => Promise<void>;
59
-
60
- export declare const $hasOwn: (v: PropertyKey) => boolean;
61
-
62
- export declare const $is: (value1: any, value2: any) => boolean;
63
-
64
- export declare const $isArray: (arg: any) => arg is any[];
65
-
66
- export declare const $isNode: (x: any) => x is ChildNode;
67
-
68
- export declare const $isSame: (a: unknown, b: unknown) => boolean;
69
-
70
- export declare const $isThenable: (o: any) => o is Promise<any>;
71
-
72
- export declare const $keys: <T>(o: T) => Array<keyof T>;
73
-
74
- export declare const $parseStyle: (style: unknown) => string;
75
-
76
- export declare const $random: () => number;
77
-
78
- /**
79
- * Safe replace `oldNode` With `newNode`
80
- */
81
- export declare const $replaceNode: (oldNode: unknown, newNode: unknown) => void;
82
-
83
- export declare const $toString: () => string;
84
-
85
- /**
86
- * Build query string from object
87
- */
88
- export declare const buildQuery: (query: Record<string, string>) => string;
89
-
90
- export declare type ChangeHandler<T = string> = (value: T, ...args: any[]) => void;
91
-
92
- /**
93
- * These fields of HTMLElement can trigger `change`.
94
- */
95
- export declare type ChangeTriggerField = 'value' | 'checked' | 'selected' | 'valueAsDate' | 'valueAsNumber';
96
-
97
- /**
98
- * Substitute params into path pattern
99
- * @example '/user/:id' + {id: '123'} => '/user/123'
100
- */
101
- export declare const emplaceParams: (path: string, params: Record<string, string>) => string;
102
-
103
- /**
104
- * Extract dynamic params from path using pattern
105
- * @example pattern: '/user/:id', path: '/user/123' => {id: '123'}
106
- */
107
- export declare const extractParams: (pattern: string, path: string) => Record<string, string> | null;
108
-
109
- export declare type HTMLJSXTag = HTMLTag | ((props?: any) => HTMLElement) | ((props?: any) => Promise<HTMLElement>);
110
-
111
- /**
112
- * Normal HTML tags like `div`, `span`, `a`, etc.
113
- */
114
- export declare type HTMLTag = keyof HTMLElementTagNameMap;
115
-
116
- export declare type InputElementTag = 'input' | 'select' | 'textarea';
117
-
118
- export declare type JSXTag = HTMLJSXTag | SVGJSXTag | MathMLJSXTag;
119
-
120
- export declare interface KTReactiveLike<T = unknown> {
121
- isKT: true;
122
- value: T;
123
- addOnChange(fn: (newValue: T, oldValue: T) => void): void;
124
- removeOnChange?(fn: (newValue: T, oldValue: T) => void): boolean;
125
- }
126
-
127
- export declare type MathMLJSXTag = HTMLTag | ((props?: any) => MathMLElement) | ((props?: any) => Promise<MathMLElement>);
128
-
129
- export declare type MathMLTag = keyof MathMLElementTagNameMap;
130
-
131
- /**
132
- * Get the tags that makes HTMLElementTagNameMap[tag] = HTMLElement
133
- */
134
- export declare type NonSpecialTags = {
135
- [K in keyof HTMLElementTagNameMap]: HTMLElement extends HTMLElementTagNameMap[K] ? K : never;
136
- }[keyof HTMLElementTagNameMap];
137
-
138
- /**
139
- * Normalize path by joining parts and ensuring leading slash
140
- */
141
- export declare const normalizePath: (...paths: string[]) => string;
142
-
143
- /**
144
- * This is tested on 15 browsers (most popular ones)
145
- * - appending a text node to these tags takes no effect.
146
- * - No effect means `innerText` does not include the text in the text node.
147
- * @see {@link src/core/h/no-text-node.ts}
148
- */
149
- export declare type NoTextNodeTag =
150
- | 'area'
151
- | 'audio'
152
- | 'base'
153
- | 'basefont'
154
- | 'br'
155
- | 'canvas'
156
- | 'datalist'
157
- | 'details'
158
- | 'dialog'
159
- | 'frameset'
160
- | 'head'
161
- | 'iframe'
162
- | 'img'
163
- | 'input'
164
- | 'link'
165
- | 'meta'
166
- | 'meter'
167
- | 'noembed'
168
- | 'noframes'
169
- | 'noscript'
170
- | 'optgroup'
171
- | 'param'
172
- | 'progress'
173
- | 'rp'
174
- | 'select'
175
- | 'style'
176
- | 'template'
177
- | 'textarea'
178
- | 'title'
179
- | 'video'
180
- | 'wbr'
181
- | 'embed'
182
- | 'frame'
183
- | 'keygen'
184
- | 'option';
185
-
186
- declare const originAppend: (...nodes: (Node | string)[]) => void;
187
-
188
- export declare type otherstring = string & {};
189
-
190
- /**
191
- * Parse query string into object
192
- */
193
- export declare const parseQuery: (queryString: string) => Record<string, string>;
194
-
195
- export declare type SVGJSXTag = HTMLTag | ((props?: any) => SVGElement) | ((props?: any) => Promise<SVGElement>);
196
-
197
- export declare type SVGTag = keyof SVGElementTagNameMap;
198
-
199
- export { }
1
+ declare const $isArray: (arg: any) => arg is any[];
2
+ declare const $ArrayFrom: {
3
+ <T>(arrayLike: ArrayLike<T>): T[];
4
+ <T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[];
5
+ <T>(iterable: Iterable<T> | ArrayLike<T>): T[];
6
+ <T, U>(iterable: Iterable<T> | ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[];
7
+ };
8
+ declare const $is: (value1: any, value2: any) => boolean;
9
+ declare const $assign: {
10
+ <T extends {}, U>(target: T, source: U): T & U;
11
+ <T extends {}, U, V>(target: T, source1: U, source2: V): T & U & V;
12
+ <T extends {}, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
13
+ (target: object, ...sources: any[]): any;
14
+ };
15
+ declare const $hasOwn: (v: PropertyKey) => boolean;
16
+ declare const $toString: () => string;
17
+ declare const $keys: <T>(o: T) => Array<keyof T>;
18
+ declare const $defines: <T>(o: T, properties: PropertyDescriptorMap & ThisType<any>) => T;
19
+ declare const $define: <T>(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType<any>) => T;
20
+ declare const $entries: <T>(o: T) => Array<[keyof T, T[keyof T]]>;
21
+ declare const $random: () => number;
22
+ declare const $isThenable: (o: any) => o is Promise<any>;
23
+
24
+ type otherstring = string & {};
25
+
26
+ /**
27
+ * Normal HTML tags like `div`, `span`, `a`, etc.
28
+ */
29
+ type HTMLTag = keyof HTMLElementTagNameMap;
30
+ type SVGTag = keyof SVGElementTagNameMap;
31
+ type MathMLTag = keyof MathMLElementTagNameMap;
32
+
33
+ type HTMLJSXTag = HTMLTag | ((props?: any) => HTMLElement) | ((props?: any) => Promise<HTMLElement>);
34
+ type SVGJSXTag = HTMLTag | ((props?: any) => SVGElement) | ((props?: any) => Promise<SVGElement>);
35
+ type MathMLJSXTag = HTMLTag | ((props?: any) => MathMLElement) | ((props?: any) => Promise<MathMLElement>);
36
+ type JSXTag = HTMLJSXTag | SVGJSXTag | MathMLJSXTag;
37
+
38
+ /**
39
+ * Get the tags that makes HTMLElementTagNameMap[tag] = HTMLElement
40
+ */
41
+ type NonSpecialTags = {
42
+ [K in keyof HTMLElementTagNameMap]: HTMLElement extends HTMLElementTagNameMap[K] ? K : never;
43
+ }[keyof HTMLElementTagNameMap];
44
+
45
+ /**
46
+ * This is tested on 15 browsers (most popular ones)
47
+ * - appending a text node to these tags takes no effect.
48
+ * - No effect means `innerText` does not include the text in the text node.
49
+ * @see {@link src/core/h/no-text-node.ts}
50
+ */
51
+ type NoTextNodeTag =
52
+ | 'area'
53
+ | 'audio'
54
+ | 'base'
55
+ | 'basefont'
56
+ | 'br'
57
+ | 'canvas'
58
+ | 'datalist'
59
+ | 'details'
60
+ | 'dialog'
61
+ | 'frameset'
62
+ | 'head'
63
+ | 'iframe'
64
+ | 'img'
65
+ | 'input'
66
+ | 'link'
67
+ | 'meta'
68
+ | 'meter'
69
+ | 'noembed'
70
+ | 'noframes'
71
+ | 'noscript'
72
+ | 'optgroup'
73
+ | 'param'
74
+ | 'progress'
75
+ | 'rp'
76
+ | 'select'
77
+ | 'style'
78
+ | 'template'
79
+ | 'textarea'
80
+ | 'title'
81
+ | 'video'
82
+ | 'wbr'
83
+ | 'embed'
84
+ | 'frame'
85
+ | 'keygen'
86
+ | 'option';
87
+
88
+ /**
89
+ * These fields of HTMLElement can trigger `change`.
90
+ */
91
+ type ChangeTriggerField = 'value' | 'checked' | 'selected' | 'valueAsDate' | 'valueAsNumber';
92
+
93
+ type InputElementTag = 'input' | 'select' | 'textarea';
94
+
95
+ declare const $isNode: (x: any) => x is ChildNode;
96
+ /**
97
+ * Safe replace `oldNode` With `newNode`
98
+ * - This function is not used everywhere. Because there is no need to check every time.
99
+ */
100
+ declare const $replaceNode: (oldNode: unknown, newNode: unknown) => void;
101
+ declare const $parseStyle: (style: unknown) => string;
102
+ type ChangeHandler<T = string> = (value: T, ...args: any[]) => void;
103
+ /**
104
+ * Used for `k-model`
105
+ */
106
+ declare const $applyModel: (element: HTMLElementTagNameMap[InputElementTag], valueRef: {
107
+ value: unknown;
108
+ addOnChange: (fn: (newValue: unknown) => void) => void;
109
+ }, propName: "value" | "checked", eventName: "change" | "input") => void;
110
+
111
+ /**
112
+ * Default empty function
113
+ */
114
+ declare const $emptyFn: (...args: any[]) => any;
115
+ declare const $emptyArray: any[];
116
+ declare const $emptyObject: any;
117
+ /**
118
+ * SameValueZero comparison, similar to `Object.is` but treats `+0 === -0`
119
+ */
120
+ declare const $SameValueZero: (x: unknown, y: unknown) => boolean;
121
+ /**
122
+ * Safe and quick forEach implementation that works with array-like objects and handles sparse arrays.
123
+ */
124
+ declare const $forEach: (array: unknown[], callback: (item: unknown, index: number, array: unknown[]) => void) => void;
125
+ /**
126
+ * Async version of $forEach that allows for asynchronous callbacks. It processes items sequentially, awaiting each callback before moving to the next.
127
+ */
128
+ declare const $forEachAsync: (array: unknown[], callback: (item: unknown, index: number, array: unknown[]) => void) => Promise<void>;
129
+
130
+ /**
131
+ * Normalize path by joining parts and ensuring leading slash
132
+ */
133
+ declare const normalizePath: (...paths: string[]) => string;
134
+ /**
135
+ * Parse query string into object
136
+ */
137
+ declare const parseQuery: (queryString: string) => Record<string, string>;
138
+ /**
139
+ * Build query string from object
140
+ */
141
+ declare const buildQuery: (query: Record<string, string>) => string;
142
+ /**
143
+ * Substitute params into path pattern
144
+ * @example '/user/:id' + {id: '123'} => '/user/123'
145
+ */
146
+ declare const emplaceParams: (path: string, params: Record<string, string>) => string;
147
+ /**
148
+ * Extract dynamic params from path using pattern
149
+ * @example pattern: '/user/:id', path: '/user/123' => {id: '123'}
150
+ */
151
+ declare const extractParams: (pattern: string, path: string) => Record<string, string> | null;
152
+
153
+ interface KTReactiveLike<T = unknown> {
154
+ isKT: true;
155
+ value: T;
156
+ addOnChange(fn: (newValue: T, oldValue: T) => void): void;
157
+ removeOnChange?(fn: (newValue: T, oldValue: T) => void): boolean;
158
+ }
159
+
160
+ export { $ArrayFrom, $SameValueZero, $applyModel, $assign, $define, $defines, $emptyArray, $emptyFn, $emptyObject, $entries, $forEach, $forEachAsync, $hasOwn, $is, $isArray, $isNode, $isThenable, $keys, $parseStyle, $random, $replaceNode, $toString, buildQuery, emplaceParams, extractParams, normalizePath, parseQuery };
161
+ export type { ChangeHandler, ChangeTriggerField, HTMLJSXTag, HTMLTag, InputElementTag, JSXTag, KTReactiveLike, MathMLJSXTag, MathMLTag, NoTextNodeTag, NonSpecialTags, SVGJSXTag, SVGTag, otherstring };
package/dist/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ // Cached native methods for performance optimization
1
2
  const $isArray = Array.isArray;
2
3
  const $ArrayFrom = Array.from;
3
4
  const $is = Object.is;
@@ -9,152 +10,166 @@ const $defines = Object.defineProperties;
9
10
  const $define = Object.defineProperty;
10
11
  const $entries = Object.entries;
11
12
  const $random = Math.random;
12
- const $isThenable = (o) => typeof o?.then === "function";
13
+ const $isThenable = (o) => typeof o?.then === 'function';
13
14
 
14
- if (typeof Symbol === "undefined") {
15
- window.Symbol = function Symbol2(description) {
16
- return `@@SYMBOL_${description || ""}_${$random().toString(36).slice(2)}`;
17
- };
15
+ if (typeof Symbol === 'undefined') {
16
+ window.Symbol = function Symbol(description) {
17
+ return `@@SYMBOL_${description || ''}_${$random().toString(36).slice(2)}`;
18
+ };
18
19
  }
19
20
 
21
+ // DOM manipulation utilities
22
+ // # dom natives
20
23
  const $isNode = (x) => x?.nodeType > 0;
24
+ /**
25
+ * Safe replace `oldNode` With `newNode`
26
+ * - This function is not used everywhere. Because there is no need to check every time.
27
+ */
21
28
  const $replaceNode = (oldNode, newNode) => {
22
- if ($isNode(oldNode) && $isNode(newNode)) {
23
- if (newNode.contains(oldNode)) {
24
- newNode.remove();
25
- }
26
- oldNode.replaceWith(newNode);
27
- }
28
- };
29
- const $appendChild = HTMLElement.prototype.appendChild;
30
- const originAppend = HTMLElement.prototype.append;
31
- const $append = (
32
- // for ie 9/10/11
33
- typeof originAppend === "function" ? originAppend : function(...nodes) {
34
- if (nodes.length < 50) {
35
- for (let i = 0; i < nodes.length; i++) {
36
- const node = nodes[i];
37
- if (typeof node === "string") {
38
- $appendChild.call(this, document.createTextNode(node));
39
- } else {
40
- $appendChild.call(this, node);
41
- }
42
- }
43
- } else {
44
- const fragment = document.createDocumentFragment();
45
- for (let i = 0; i < nodes.length; i++) {
46
- const node = nodes[i];
47
- if (typeof node === "string") {
48
- $appendChild.call(fragment, document.createTextNode(node));
49
- } else {
50
- $appendChild.call(fragment, node);
29
+ if ($isNode(oldNode) && $isNode(newNode)) {
30
+ if (newNode.contains(oldNode)) {
31
+ newNode.remove();
51
32
  }
52
- }
53
- $appendChild.call(this, fragment);
33
+ oldNode.replaceWith(newNode);
54
34
  }
55
- }
56
- );
57
- const { get: $buttonDisabledGetter, set: $buttonDisabledSetter } = Object.getOwnPropertyDescriptor(
58
- HTMLButtonElement.prototype,
59
- "disabled"
60
- );
35
+ };
36
+ // # DOM utilities
37
+ // Same as it is in @ktjs/core
61
38
  const $parseStyle = (style) => {
62
- if (!style) {
63
- return "";
64
- }
65
- if (typeof style === "string") {
66
- return style;
67
- }
68
- if (style && typeof style === "object") {
69
- if (style.isKT) {
70
- return $parseStyle(style.value);
39
+ if (!style) {
40
+ return '';
41
+ }
42
+ if (typeof style === 'string') {
43
+ return style;
71
44
  }
72
- return $entries(style).map((entry) => {
73
- const cssKey = entry[0].replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
74
- return `${cssKey}:${entry[1]}`;
75
- }).join(";");
76
- }
77
- return "";
45
+ // already !style === false
46
+ if (typeof style === 'object') {
47
+ if (style.isKT) {
48
+ return $parseStyle(style.value);
49
+ }
50
+ return $entries(style)
51
+ .map((entry) => {
52
+ const cssKey = entry[0].replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
53
+ return `${cssKey}:${entry[1]}`;
54
+ })
55
+ .join(';');
56
+ }
57
+ return '';
78
58
  };
59
+ /**
60
+ * Used for `k-model`
61
+ */
79
62
  const $applyModel = (element, valueRef, propName, eventName) => {
80
- element[propName] = valueRef.value;
81
- valueRef.addOnChange((newValue) => element[propName] = newValue);
82
- element.addEventListener(eventName, () => valueRef.value = element[propName]);
63
+ element[propName] = valueRef.value; // initialize
64
+ valueRef.addOnChange((newValue) => (element[propName] = newValue));
65
+ element.addEventListener(eventName, () => (valueRef.value = element[propName]));
83
66
  };
84
67
 
68
+ // String manipulation utilities
69
+ /**
70
+ * Default empty function
71
+ */
85
72
  const $emptyFn = (() => true);
86
73
  const $emptyArray = [];
87
- const $emptyObject = /* @__PURE__ */ Object.create(null);
88
- const $isSame = (a, b) => {
89
- if ($isArray(a)) {
90
- return true;
91
- }
92
- return $is(a, b);
93
- };
74
+ const $emptyObject = Object.create(null);
75
+ /**
76
+ * SameValueZero comparison, similar to `Object.is` but treats `+0 === -0`
77
+ */
78
+ const $SameValueZero = (x, y) => (x !== x && y !== y) || x === y;
79
+ /**
80
+ * Safe and quick forEach implementation that works with array-like objects and handles sparse arrays.
81
+ */
94
82
  const $forEach = (array, callback) => {
95
- const len = array.length;
96
- for (let i = 0; i < len; i++) {
97
- callback(array[i], i, array);
98
- }
83
+ const len = array.length;
84
+ for (let i = 0; i < len; i++) {
85
+ callback(array[i], i, array);
86
+ }
99
87
  };
88
+ /**
89
+ * Async version of $forEach that allows for asynchronous callbacks. It processes items sequentially, awaiting each callback before moving to the next.
90
+ */
100
91
  const $forEachAsync = async (array, callback) => {
101
- const len = array.length;
102
- for (let i = 0; i < len; i++) {
103
- await callback(array[i], i, array);
104
- }
92
+ const len = array.length;
93
+ for (let i = 0; i < len; i++) {
94
+ await callback(array[i], i, array);
95
+ }
105
96
  };
106
97
 
98
+ /**
99
+ * Normalize path by joining parts and ensuring leading slash
100
+ */
107
101
  const normalizePath = (...paths) => {
108
- const p = paths.map((p2) => p2.split("/")).flat().filter(Boolean);
109
- return "/" + p.join("/");
102
+ const p = paths
103
+ .map((p) => p.split('/'))
104
+ .flat()
105
+ .filter(Boolean);
106
+ return '/' + p.join('/');
110
107
  };
108
+ /**
109
+ * Parse query string into object
110
+ */
111
111
  const parseQuery = (queryString) => {
112
- const query = {};
113
- if (!queryString || queryString === "?") {
114
- return query;
115
- }
116
- const params = queryString.replace(/^\?/, "").split("&");
117
- for (const param of params) {
118
- const [key, value] = param.split("=");
119
- if (key) {
120
- query[decodeURIComponent(key)] = value ? decodeURIComponent(value) : "";
112
+ const query = {};
113
+ if (!queryString || queryString === '?') {
114
+ return query;
121
115
  }
122
- }
123
- return query;
116
+ const params = queryString.replace(/^\?/, '').split('&');
117
+ for (const param of params) {
118
+ const [key, value] = param.split('=');
119
+ if (key) {
120
+ query[decodeURIComponent(key)] = value ? decodeURIComponent(value) : '';
121
+ }
122
+ }
123
+ return query;
124
124
  };
125
+ /**
126
+ * Build query string from object
127
+ */
125
128
  const buildQuery = (query) => {
126
- const keys = Object.keys(query);
127
- if (keys.length === 0) return "";
128
- const params = keys.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`).join("&");
129
- return `?${params}`;
129
+ const keys = Object.keys(query);
130
+ if (keys.length === 0)
131
+ return '';
132
+ const params = keys.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`).join('&');
133
+ return `?${params}`;
130
134
  };
135
+ /**
136
+ * Substitute params into path pattern
137
+ * @example '/user/:id' + {id: '123'} => '/user/123'
138
+ */
131
139
  const emplaceParams = (path, params) => {
132
- let result = path;
133
- for (const key in params) {
134
- result = result.replace(`:${key}`, params[key]);
135
- }
136
- return result;
140
+ let result = path;
141
+ for (const key in params) {
142
+ result = result.replace(`:${key}`, params[key]);
143
+ }
144
+ return result;
137
145
  };
146
+ /**
147
+ * Extract dynamic params from path using pattern
148
+ * @example pattern: '/user/:id', path: '/user/123' => {id: '123'}
149
+ */
138
150
  const extractParams = (pattern, path) => {
139
- const params = {};
140
- const patternParts = pattern.split("/");
141
- const pathParts = path.split("/");
142
- if (patternParts.length !== pathParts.length) {
143
- return null;
144
- }
145
- for (let i = 0; i < patternParts.length; i++) {
146
- const patternPart = patternParts[i];
147
- const pathPart = pathParts[i];
148
- if (patternPart.startsWith(":")) {
149
- const paramName = patternPart.slice(1);
150
- params[paramName] = pathPart;
151
- } else if (patternPart !== pathPart) {
152
- return null;
151
+ const params = {};
152
+ const patternParts = pattern.split('/');
153
+ const pathParts = path.split('/');
154
+ if (patternParts.length !== pathParts.length) {
155
+ return null;
156
+ }
157
+ for (let i = 0; i < patternParts.length; i++) {
158
+ const patternPart = patternParts[i];
159
+ const pathPart = pathParts[i];
160
+ if (patternPart.startsWith(':')) {
161
+ const paramName = patternPart.slice(1);
162
+ params[paramName] = pathPart;
163
+ }
164
+ else if (patternPart !== pathPart) {
165
+ return null;
166
+ }
153
167
  }
154
- }
155
- return params;
168
+ return params;
156
169
  };
157
170
 
158
- Object.defineProperty(window, "__ktjs__", { value: "0.23.17" });
171
+ // incase that symbol is not supported
172
+ Object.defineProperty(window, '__ktjs__', { value: '0.23.19' });
159
173
 
160
- export { $ArrayFrom, $append, $appendChild, $applyModel, $assign, $buttonDisabledGetter, $buttonDisabledSetter, $define, $defines, $emptyArray, $emptyFn, $emptyObject, $entries, $forEach, $forEachAsync, $hasOwn, $is, $isArray, $isNode, $isSame, $isThenable, $keys, $parseStyle, $random, $replaceNode, $toString, buildQuery, emplaceParams, extractParams, normalizePath, parseQuery };
174
+ export { $ArrayFrom, $SameValueZero, $applyModel, $assign, $define, $defines, $emptyArray, $emptyFn, $emptyObject, $entries, $forEach, $forEachAsync, $hasOwn, $is, $isArray, $isNode, $isThenable, $keys, $parseStyle, $random, $replaceNode, $toString, buildQuery, emplaceParams, extractParams, normalizePath, parseQuery };
175
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../src/utils/native.ts","../src/misc/symbol-polyfill.ts","../src/utils/dom.ts","../src/utils/misc.ts","../src/utils/url.ts","../src/index.ts"],"sourcesContent":["// Cached native methods for performance optimization\n\nexport const $isArray = Array.isArray;\nexport const $ArrayFrom = Array.from;\n\nexport const $is = Object.is;\nexport const $assign = Object.assign;\nexport const $hasOwn = Object.prototype.hasOwnProperty;\nexport const $toString = Object.prototype.toString;\n\nexport const $keys = Object.keys as <T>(o: T) => Array<keyof T>;\nexport const $defines = Object.defineProperties;\nexport const $define = Object.defineProperty;\nexport const $entries = Object.entries as <T>(o: T) => Array<[keyof T, T[keyof T]]>;\n\nexport const $random = Math.random;\n\nexport const $isThenable = (o: any): o is Promise<any> => typeof o?.then === 'function';\n","import { $random } from '../utils/native.js';\n\nexport {};\nif (typeof Symbol === 'undefined') {\n (window as any).Symbol = function Symbol(description?: string) {\n return `@@SYMBOL_${description || ''}_${$random().toString(36).slice(2)}`;\n };\n}\n","// DOM manipulation utilities\n\nimport type { KTReactiveLike } from '../types/misc.js';\nimport type { InputElementTag } from '../types/global.js';\nimport { $entries } from './native.js';\n\n// # dom natives\n\nexport const $isNode = (x: any): x is ChildNode => x?.nodeType > 0;\n\n/**\n * Safe replace `oldNode` With `newNode`\n * - This function is not used everywhere. Because there is no need to check every time.\n */\nexport const $replaceNode = (oldNode: unknown, newNode: unknown) => {\n if ($isNode(oldNode) && $isNode(newNode)) {\n if (newNode.contains(oldNode)) {\n newNode.remove();\n }\n oldNode.replaceWith(newNode);\n }\n};\n\n// # DOM utilities\n\n// Same as it is in @ktjs/core\nexport const $parseStyle = (style: unknown): string => {\n if (!style) {\n return '';\n }\n if (typeof style === 'string') {\n return style;\n }\n\n // already !style === false\n if (typeof style === 'object') {\n if ((style as KTReactiveLike).isKT) {\n return $parseStyle((style as KTReactiveLike).value);\n }\n\n return $entries(style)\n .map((entry: [string, string]) => {\n const cssKey = entry[0].replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n return `${cssKey}:${entry[1]}`;\n })\n .join(';');\n }\n return '';\n};\n\nexport type ChangeHandler<T = string> = (value: T, ...args: any[]) => void;\n\n/**\n * Used for `k-model`\n */\nexport const $applyModel = (\n element: HTMLElementTagNameMap[InputElementTag],\n valueRef: { value: unknown; addOnChange: (fn: (newValue: unknown) => void) => void },\n propName: 'value' | 'checked',\n eventName: 'change' | 'input',\n) => {\n (element as any)[propName] = valueRef.value; // initialize\n valueRef.addOnChange((newValue) => ((element as any)[propName] = newValue));\n element.addEventListener(eventName, () => (valueRef.value = (element as any)[propName]));\n};\n","// String manipulation utilities\n\nimport { $is, $isArray } from './native.js';\n\n/**\n * Default empty function\n */\nexport const $emptyFn = (() => true) as (...args: any[]) => any;\nexport const $emptyArray: any[] = [];\nexport const $emptyObject = Object.create(null);\n\n/**\n * SameValueZero comparison, similar to `Object.is` but treats `+0 === -0`\n */\nexport const $SameValueZero = (x: unknown, y: unknown): boolean => (x !== x && y !== y) || x === y;\n\n/**\n * Safe and quick forEach implementation that works with array-like objects and handles sparse arrays.\n */\nexport const $forEach = (\n array: unknown[],\n callback: (item: unknown, index: number, array: unknown[]) => void,\n): void => {\n const len = array.length;\n for (let i = 0; i < len; i++) {\n callback(array[i], i, array);\n }\n};\n\n/**\n * Async version of $forEach that allows for asynchronous callbacks. It processes items sequentially, awaiting each callback before moving to the next.\n */\nexport const $forEachAsync = async (\n array: unknown[],\n callback: (item: unknown, index: number, array: unknown[]) => void,\n): Promise<void> => {\n const len = array.length;\n for (let i = 0; i < len; i++) {\n await callback(array[i], i, array);\n }\n};\n","/**\n * Normalize path by joining parts and ensuring leading slash\n */\nexport const normalizePath = (...paths: string[]) => {\n const p = paths\n .map((p) => p.split('/'))\n .flat()\n .filter(Boolean);\n return '/' + p.join('/');\n};\n\n/**\n * Parse query string into object\n */\nexport const parseQuery = (queryString: string): Record<string, string> => {\n const query: Record<string, string> = {};\n if (!queryString || queryString === '?') {\n return query;\n }\n\n const params = queryString.replace(/^\\?/, '').split('&');\n for (const param of params) {\n const [key, value] = param.split('=');\n if (key) {\n query[decodeURIComponent(key)] = value ? decodeURIComponent(value) : '';\n }\n }\n return query;\n};\n\n/**\n * Build query string from object\n */\nexport const buildQuery = (query: Record<string, string>): string => {\n const keys = Object.keys(query);\n if (keys.length === 0) return '';\n\n const params = keys.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`).join('&');\n return `?${params}`;\n};\n\n/**\n * Substitute params into path pattern\n * @example '/user/:id' + {id: '123'} => '/user/123'\n */\nexport const emplaceParams = (path: string, params: Record<string, string>): string => {\n let result = path;\n for (const key in params) {\n result = result.replace(`:${key}`, params[key]);\n }\n return result;\n};\n\n/**\n * Extract dynamic params from path using pattern\n * @example pattern: '/user/:id', path: '/user/123' => {id: '123'}\n */\nexport const extractParams = (pattern: string, path: string): Record<string, string> | null => {\n const params: Record<string, string> = {};\n const patternParts = pattern.split('/');\n const pathParts = path.split('/');\n\n if (patternParts.length !== pathParts.length) {\n return null;\n }\n\n for (let i = 0; i < patternParts.length; i++) {\n const patternPart = patternParts[i];\n const pathPart = pathParts[i];\n\n if (patternPart.startsWith(':')) {\n const paramName = patternPart.slice(1);\n params[paramName] = pathPart;\n } else if (patternPart !== pathPart) {\n return null;\n }\n }\n\n return params;\n};\n","// incase that symbol is not supported\nimport './misc/symbol-polyfill.js';\n\nexport * from './misc/comment.js';\nexport * from './utils/native.js';\nexport * from './utils/dom.js';\nexport * from './utils/misc.js';\nexport * from './utils/url.js';\n\nexport type * from './types/global.js';\nexport type * from './types/misc.js';\n\nObject.defineProperty(window, '__ktjs__', { value: '__VERSION__' });\n"],"names":[],"mappings":"AAAA;AAEO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AM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;IAEjC,IAAI,YAAY,CAAC,MAAM,KAAK,SAAS,CAAC,MAAM,EAAE;AAC5C,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC5C,QAAA,MAAM,WAAW,GAAG,YAAY,CAAC,CAAC,CAAC;AACnC,QAAA,MAAM,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAC;AAE7B,QAAA,IAAI,WAAW,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;YAC/B,MAAM,SAAS,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC;AACtC,YAAA,MAAM,CAAC,SAAS,CAAC,GAAG,QAAQ;QAC9B;AAAO,aAAA,IAAI,WAAW,KAAK,QAAQ,EAAE;AACnC,YAAA,OAAO,IAAI;QACb;IACF;AAEA,IAAA,OAAO,MAAM;AACf;;AC/EA;AAYA,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,SAAa,EAAE,CAAC;;;;"}
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@ktjs/shared",
3
- "version": "0.23.17",
3
+ "version": "0.23.19",
4
4
  "description": "Shared utilities and cached native methods for kt.js framework",
5
+ "description_zh": "kt.js 框架的共享工具与原生方法缓存。",
5
6
  "type": "module",
6
7
  "module": "./dist/index.mjs",
7
8
  "types": "./dist/index.d.ts",