-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathset-prototype.js
More file actions
249 lines (223 loc) · 7.75 KB
/
Copy pathset-prototype.js
File metadata and controls
249 lines (223 loc) · 7.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import { isFunction, isNumber, isObject } from "../utils.js";
import { PropError } from "./errors.js";
export const CUSTOM_TYPE_NAME = "Custom";
/**
* The Any type avoids the validation of prop types
* @type {null}
**/
export const Any = null;
/**
* Attributes considered as valid boleanos
**/
const TRUE_VALUES = { true: 1, "": 1, 1: 1 };
/**
* Constructs the setter and getter of the associated property
* only if it is not defined in the prototype
* @param {Object} prototype - CustomElement prototype
* @param {string} prop - Name of the reactive property to associate with the customElement
* @param {any} schema - Structure to be evaluated for the definition of the property
* @param {Attrs} attrs - Dictionary of attributes to properties
* @param {Values} values - Values to initialize the customElements
*/
export function setPrototype(prototype, prop, schema, attrs, values) {
/**@type {Schema} */
const {
type,
reflect,
event,
value: defaultValue,
attr = getAttr(prop),
} = schema?.name != CUSTOM_TYPE_NAME && isObject(schema) && schema != Any
? schema
: { type: schema };
const isCustomType = type?.name === CUSTOM_TYPE_NAME && type.map;
const isCallable = !(type == Function || isCustomType || type == Any);
const withDefaultValue = defaultValue != null;
const withDefaultValueAlways = withDefaultValue && type != Boolean;
Object.defineProperty(prototype, prop, {
configurable: true,
/**
* @this {import("dom").AtomicoThisInternal}
* @param {any} newValue
*/
set(newValue) {
const oldValue = this[prop];
if (withDefaultValueAlways && newValue == null)
newValue = defaultValue;
const { error, value } = (isCustomType ? mapValue : filterValue)(
type,
isCallable && isFunction(newValue)
? newValue(oldValue)
: newValue
);
if (error && value != null) {
throw new PropError(
this,
`The value defined for prop '${prop}' must be of type '${type.name}'`,
value
);
}
if (oldValue == value) return;
this._props[prop] = value == null ? undefined : value;
this.update();
/**
* 1.7.0 >, this position reduces the amount of updates to the DOM and render
*/
event && dispatchEvent(this, event);
/**
* attribute mirroring must occur if component is mounted
*/
this.updated.then(() => {
if (reflect) {
this._ignoreAttr = attr;
reflectValue(this, type, attr, this[prop]);
this._ignoreAttr = null;
}
});
},
/**
* @this {import("dom").AtomicoThisInternal}
*/
get() {
return this._props[prop];
},
});
if (withDefaultValue) values[prop] = defaultValue;
attrs[attr] = { prop, type };
}
/**
* Dispatch an event
* @param {Element} node - DOM node to dispatch the event
* @param {InternalEvent & InternalEventInit} event - Event to dispatch on node
*/
export const dispatchEvent = (
node,
{ type, base = CustomEvent, ...eventInit }
) => node.dispatchEvent(new base(type, eventInit));
/**
* Transform a Camel Case string to a Kebab case
* @param {string} prop - string to apply the format
* @returns {string}
*/
export const getAttr = (prop) => prop.replace(/([A-Z])/g, "-$1").toLowerCase();
/**
* reflects an attribute value of the given element as context
* @param {Element} host
* @param {any} type
* @param {string} attr
* @param {any} value
*/
export const reflectValue = (host, type, attr, value) =>
value == null || (type == Boolean && !value)
? host.removeAttribute(attr)
: host.setAttribute(
attr,
type?.name === CUSTOM_TYPE_NAME && type?.serialize
? type?.serialize(value)
: isObject(value)
? JSON.stringify(value)
: type == Boolean
? ""
: value
);
/**
* transform a string to a value according to its type
* @param {any} type
* @param {string} value
* @returns {any}
*/
export const transformValue = (type, value) =>
type == Boolean
? !!TRUE_VALUES[value]
: type == Number
? Number(value)
: type == String
? value
: type == Array || type == Object
? JSON.parse(value)
: type.name == CUSTOM_TYPE_NAME
? value
: // TODO: If when defining reflect the prop can also be of type string?
new type(value);
/**
*
* @param {import("schema").TypeCustom<(...args:any)=>any>} TypeCustom
* @param {*} value
* @returns
*/
export const mapValue = ({ map }, value) => {
try {
return { value: map(value), error: false };
} catch {
return { value, error: true };
}
};
/**
* Filter the values based on their type
* @param {any} type
* @param {any} value
* @returns {{error?:boolean,value:any}}
*/
export const filterValue = (type, value) =>
type == null || value == null
? { value, error: false }
: type != String && value === ""
? { value: undefined, error: false }
: type == Object || type == Array || type == Symbol
? { value, error: {}.toString.call(value) !== `[object ${type.name}]` }
: value instanceof type
? { value, error: type == Number && Number.isNaN(value.valueOf()) }
: type == String || type == Number || type == Boolean
? {
value,
error:
type == Number
? !isNumber(value)
? true
: Number.isNaN(value)
: type == String
? typeof value != "string"
: typeof value != "boolean",
}
: { value, error: true };
/**
* @param {(...args:any[])=>any} map
* @param {(...args:any[])=>any} [serialize]
* @returns {import("schema").TypeCustom<(...args:any)=>any>}
*/
export const createType = (map, serialize) => ({
name: CUSTOM_TYPE_NAME,
map,
serialize,
});
/**
* Type any, used to avoid type validation.
* @typedef {null} Any
*/
/**
* @typedef {Object} InternalEventInit
* @property {typeof CustomEvent|typeof Event} [base] - Optional constructor to initialize the event
* @property {boolean} [bubbles] - indicating whether the event bubbles. The default is false.
* @property {boolean} [cancelable] - indicating whether the event will trigger listeners outside of a shadow root.
* @property {boolean} [composed] - indicating whether the event will trigger listeners outside of a shadow root.
* @property {any} [detail] - indicating whether the event will trigger listeners outside of a shadow root.
*/
/**
* Interface used by dispatchEvent to automate event firing
* @typedef {Object} InternalEvent
* @property {string} type - type of event to dispatch.
*/
/**
* @typedef {Object<string, {prop:string,type:Function}>} Attrs
*/
/**
* @typedef {Object<string, any>} Values
*/
/**
* @typedef {Object} Schema
* @property {any} [type] - data type to be worked as property and attribute
* @property {string} [attr] - allows customizing the name as an attribute by skipping the camelCase format
* @property {boolean} [reflect] - reflects property as attribute of node
* @property {InternalEvent & InternalEventInit} [event] - Allows to emit an event every time the property changes
* @property {any} [value] - defines a default value when instantiating the component
*/