-
-
Notifications
You must be signed in to change notification settings - Fork 833
Expand file tree
/
Copy pathset-accessor.ts
More file actions
270 lines (258 loc) · 9.91 KB
/
set-accessor.ts
File metadata and controls
270 lines (258 loc) · 9.91 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/**
* Production setAccessor() function based on Preact by
* Jason Miller (@developit)
* Licensed under the MIT License
* https://github.com/developit/preact/blob/master/LICENSE
*
* Modified for Stencil's compiler and vdom
*/
import { BUILD } from '@app-data';
import { getHostRef, isMemberInElement, plt, win } from '@platform';
import { isComplexType } from '../../utils/helpers';
import type * as d from '../../declarations';
import { NODE_TYPE, VNODE_FLAGS, XLINK_NS } from '../runtime-constants';
import { queueRefAttachment } from './vdom-render';
/**
* When running a VDom render set properties present on a VDom node onto the
* corresponding HTML element.
*
* Note that this function has special functionality for the `class`,
* `style`, `key`, and `ref` attributes, as well as event handlers (like
* `onClick`, etc). All others are just passed through as-is.
*
* @param elm the HTMLElement onto which attributes should be set
* @param memberName the name of the attribute to set
* @param oldValue the old value for the attribute
* @param newValue the new value for the attribute
* @param isSvg whether we're in an svg context or not
* @param flags bitflags for Vdom variables
* @param initialRender whether this is the first render of the VDom
*/
export const setAccessor = (
elm: d.RenderNode,
memberName: string,
oldValue: any,
newValue: any,
isSvg: boolean,
flags: number,
initialRender?: boolean,
) => {
if (oldValue === newValue) {
return;
}
let isProp = isMemberInElement(elm, memberName);
let ln = memberName.toLowerCase();
if (BUILD.vdomClass && memberName === 'class') {
const classList = elm.classList;
const oldClasses = parseClassList(oldValue);
let newClasses = parseClassList(newValue);
if (BUILD.hydrateClientSide && (elm['s-si'] || elm['s-sc']) && initialRender) {
// for `scoped: true` components, new nodes after initial hydration
// from SSR don't have the slotted class added. Let's add that now
const scopeId = elm['s-sc'] || elm['s-si'];
newClasses.push(scopeId);
oldClasses.forEach((c) => {
if (c.startsWith(scopeId)) newClasses.push(c);
});
newClasses = [...new Set(newClasses)].filter((c) => c);
classList.add(...newClasses);
} else {
classList.remove(...oldClasses.filter((c) => c && !newClasses.includes(c)));
classList.add(...newClasses.filter((c) => c && !oldClasses.includes(c)));
}
} else if (BUILD.vdomStyle && memberName === 'style') {
// update style attribute, css properties and values
if (BUILD.updatable) {
for (const prop in oldValue) {
if (!newValue || newValue[prop] == null) {
if (!BUILD.hydrateServerSide && prop.includes('-')) {
elm.style.removeProperty(prop);
} else {
(elm as any).style[prop] = '';
}
}
}
}
for (const prop in newValue) {
if (!oldValue || newValue[prop] !== oldValue[prop]) {
if (!BUILD.hydrateServerSide && prop.includes('-')) {
elm.style.setProperty(prop, newValue[prop]);
} else {
(elm as any).style[prop] = newValue[prop];
}
}
}
} else if (BUILD.vdomKey && memberName === 'key') {
// minifier will clean this up
} else if (BUILD.vdomRef && memberName === 'ref') {
// minifier will clean this up
if (newValue) {
queueRefAttachment(newValue, elm);
}
} else if (
BUILD.vdomListener &&
(BUILD.lazyLoad ? !isProp : !(elm as any).__lookupSetter__(memberName)) &&
memberName[0] === 'o' &&
memberName[1] === 'n'
) {
// Event Handlers
// so if the member name starts with "on" and the 3rd characters is
// a capital letter, and it's not already a member on the element,
// then we're assuming it's an event listener
if (memberName[2] === '-') {
// on- prefixed events
// allows to be explicit about the dom event to listen without any magic
// under the hood:
// <my-cmp on-click> // listens for "click"
// <my-cmp on-Click> // listens for "Click"
// <my-cmp on-ionChange> // listens for "ionChange"
// <my-cmp on-EVENTS> // listens for "EVENTS"
memberName = memberName.slice(3);
} else if (isMemberInElement(win, ln)) {
// standard event
// the JSX attribute could have been "onMouseOver" and the
// member name "onmouseover" is on the window's prototype
// so let's add the listener "mouseover", which is all lowercased
memberName = ln.slice(2);
} else {
// custom event
// the JSX attribute could have been "onMyCustomEvent"
// so let's trim off the "on" prefix and lowercase the first character
// and add the listener "myCustomEvent"
// except for the first character, we keep the event name case
memberName = ln[2] + memberName.slice(3);
}
if (oldValue || newValue) {
// Need to account for "capture" events.
// If the event name ends with "Capture", we'll update the name to remove
// the "Capture" suffix and make sure the event listener is setup to handle the capture event.
const capture = memberName.endsWith(CAPTURE_EVENT_SUFFIX);
// Make sure we only replace the last instance of "Capture"
memberName = memberName.replace(CAPTURE_EVENT_REGEX, '');
if (oldValue) {
plt.rel(elm, memberName, oldValue, capture);
}
if (newValue) {
plt.ael(elm, memberName, newValue, capture);
}
}
} else if (BUILD.vdomPropOrAttr && memberName[0] === 'a' && memberName.startsWith('attr:')) {
// Explicit attr: prefix — always set as attribute, bypass heuristic
const propName = memberName.slice(5);
// Look up the actual attribute name from component metadata
// Component metadata stores [flags, attributeName] for each member
let attrName: string | undefined;
if (BUILD.member) {
const hostRef = getHostRef(elm);
if (hostRef && hostRef.$cmpMeta$ && hostRef.$cmpMeta$.$members$) {
const memberMeta = hostRef.$cmpMeta$.$members$[propName];
if (memberMeta && memberMeta[1]) {
attrName = memberMeta[1];
}
}
}
// Fallback: convert camelCase to kebab-case if no metadata found
if (!attrName) {
attrName = propName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
}
if (newValue == null || newValue === false) {
// null or undefined or false (and no value) - remove attribute
if (newValue !== false || elm.getAttribute(attrName) === '') {
elm.removeAttribute(attrName);
}
} else {
elm.setAttribute(attrName, newValue === true ? '' : newValue);
}
return;
} else if (BUILD.vdomPropOrAttr && memberName[0] === 'p' && memberName.startsWith('prop:')) {
// Explicit prop: prefix — always set as property, bypass heuristic
const propName = memberName.slice(5);
try {
(elm as any)[propName] = newValue;
} catch (e) {
/**
* in case someone tries to set a read-only property, we just ignore it
*/
}
return;
} else if (BUILD.vdomPropOrAttr) {
// Set property if it exists and it's not a SVG
const isComplex = isComplexType(newValue);
if ((isProp || (isComplex && newValue !== null)) && !isSvg) {
try {
if (!elm.tagName.includes('-')) {
const n = newValue == null ? '' : newValue;
// Workaround for Safari, moving the <input> caret when re-assigning the same valued
if (memberName === 'list') {
isProp = false;
} else if (oldValue == null || (elm as any)[memberName] !== n) {
if (typeof (elm as any).__lookupSetter__(memberName) === 'function') {
(elm as any)[memberName] = n;
} else {
elm.setAttribute(memberName, n);
}
}
} else if ((elm as any)[memberName] !== newValue) {
(elm as any)[memberName] = newValue;
}
} catch (e) {
/**
* in case someone tries to set a read-only property, e.g. "namespaceURI", we just ignore it
*/
}
}
/**
* Need to manually update attribute if:
* - memberName is not an attribute
* - if we are rendering the host element in order to reflect attribute
* - if it's a SVG, since properties might not work in <svg>
* - if the newValue is null/undefined or 'false'.
*/
let xlink = false;
if (BUILD.vdomXlink) {
if (ln !== (ln = ln.replace(/^xlink\:?/, ''))) {
memberName = ln;
xlink = true;
}
}
if (newValue == null || newValue === false) {
if (newValue !== false || elm.getAttribute(memberName) === '') {
if (BUILD.vdomXlink && xlink) {
elm.removeAttributeNS(XLINK_NS, memberName);
} else {
elm.removeAttribute(memberName);
}
}
} else if (
(!isProp || flags & VNODE_FLAGS.isHost || isSvg) &&
!isComplex &&
elm.nodeType === NODE_TYPE.ElementNode
) {
newValue = newValue === true ? '' : newValue;
if (BUILD.vdomXlink && xlink) {
elm.setAttributeNS(XLINK_NS, memberName, newValue);
} else {
elm.setAttribute(memberName, newValue);
}
}
}
};
const parseClassListRegex = /\s/;
/**
* Parsed a string of classnames into an array
* @param value className string, e.g. "foo bar baz"
* @returns list of classes, e.g. ["foo", "bar", "baz"]
*/
export const parseClassList = /*@__PURE__*/ (value: string | SVGAnimatedString | undefined | null): string[] => {
// Can't use `value instanceof SVGAnimatedString` because it'll break in non-browser environments
// see https://developer.mozilla.org/docs/Web/API/SVGAnimatedString for more information
if (typeof value === 'object' && value && 'baseVal' in value) {
value = value.baseVal;
}
if (!value || typeof value !== 'string') {
return [];
}
return value.split(parseClassListRegex);
};
const CAPTURE_EVENT_SUFFIX = 'Capture';
const CAPTURE_EVENT_REGEX = new RegExp(CAPTURE_EVENT_SUFFIX + '$');