-
Notifications
You must be signed in to change notification settings - Fork 78
/
NativeElementNode.ts
254 lines (208 loc) · 8.08 KB
/
NativeElementNode.ts
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
import { logger as log, ViewNode, registerElement } from '../basicdom'
import { isAndroid, isIOS, ObservableArray } from '@nativescript/core';
import ElementNode from '../basicdom/ElementNode';
export enum NativeElementPropType {
Value,
Array,
ObservableArray
}
export interface NativeElementPropConfig {
[key: string]: NativeElementPropType
}
function setOnArrayProp(parent: any, value: any, propName: string, index: number, build: (value: any) => any = null) {
let current = parent[propName];
if (!current || !current.push) {
parent[propName] = build ? build(value) : [value];
} else {
if (current instanceof ObservableArray) {
if (index > -1) {
current.splice(index, 0, value)
} else {
current.push(value);
}
} else {
if (index > -1) {
const newArr = current.slice();
newArr.splice(index, 0, value);
parent[propName] = newArr
} else {
parent[propName] = [...current, value];
}
}
}
}
function removeFromArrayProp(parent: any, value: any, propName: string) {
let current = parent[propName];
if (!current || !current.splice) {
return;
}
let idx = current.indexOf(value);
if (idx < 0) return;
if (current instanceof ObservableArray) {
current.splice(idx, 1);
} else {
const newArr = current.slice()
newArr.splice(idx, 1);
parent[propName] = newArr
}
}
const _normalizedKeys: Map<any, Map<string, string>> = new Map();
function getNormalizedKeysForObject(obj: any, knownPropNames: string[]): Map<string, string> {
let proto = Object.getPrototypeOf(obj);
let m = _normalizedKeys.get(proto);
if (m) return m;
//calculate our prop names
let props = new Map<string, string>();
_normalizedKeys.set(proto, props);
//include known props
knownPropNames.forEach(p => props.set(p.toLowerCase(), p));
//infer the rest from the passed object (including updating any incorrect known prop names if found)
let item = obj;
while (item) {
Object.getOwnPropertyNames(item)
.filter(p => !p.startsWith('_') && !p.startsWith('css:') && p.indexOf('-') === -1)
.map(p => props.set(p.toLowerCase(), p));
item = Object.getPrototypeOf(item);
}
return props;
}
function normalizeKeyFromObject(obj: any, key: string) {
let lowerkey = key.toLowerCase();
for (let p in obj) {
if (p.toLowerCase() == lowerkey) {
return p;
}
}
return key;
}
// Implements an ElementNode that wraps a NativeScript object. It uses the object as the source of truth for its attributes
export default class NativeElementNode<T> extends ElementNode {
_nativeElement: T;
propAttribute: string = null;
propConfig: NativeElementPropConfig;
_normalizedKeys: Map<string, string>;
constructor(tagName: string, elementClass: new () => T, setsParentProp: string = null, propConfig: NativeElementPropConfig = {}) {
super(tagName);
this.propConfig = propConfig
this.propAttribute = setsParentProp
try {
this._nativeElement = new elementClass();
} catch(err) {
throw new Error(`[NativeElementNode] failed to created native element for tag ${tagName}: ${err}`);
}
this._normalizedKeys = getNormalizedKeysForObject(this._nativeElement, Object.keys(this.propConfig));
(this._nativeElement as any).__SvelteNativeElement__ = this;
log.debug(() => `created ${this} ${this._nativeElement}`)
}
get nativeElement() {
return this._nativeElement
}
set nativeElement(el) {
if (this._nativeElement) {
throw new Error(`Can't overwrite native element.`)
}
this._nativeElement = el
}
getAttribute(fullkey: string) {
let getTarget = this.nativeElement as any;
let keypath = fullkey.split(".");
let resolvedKeys: string[] = [];
while (keypath.length > 0) {
if (!getTarget) return null;
let key = keypath.shift();
if (resolvedKeys.length == 0) {
key = this._normalizedKeys.get(key) || key
} else {
key = normalizeKeyFromObject(getTarget, key)
}
resolvedKeys.push(key)
if (keypath.length > 0) {
getTarget = getTarget[key];
} else {
return getTarget[key];
}
}
return null;
}
onInsertedChild(childNode: ViewNode, index: number) {
super.onInsertedChild(childNode, index);
// support for the prop: shorthand for setting parent property to native element
if (!(childNode instanceof NativeElementNode)) return;
let propName = childNode.propAttribute;
if (!propName) return;
//Special case Array and Observable Array keys
propName = this._normalizedKeys.get(propName) || propName
switch (this.propConfig[propName]) {
case NativeElementPropType.Array:
setOnArrayProp(this.nativeElement, childNode.nativeElement, propName, index)
return;
case NativeElementPropType.ObservableArray:
setOnArrayProp(this.nativeElement, childNode.nativeElement, propName, index, (v) => new ObservableArray(v))
return;
default:
this.setAttribute(propName, childNode);
}
}
onRemovedChild(childNode: ViewNode) {
if (!(childNode instanceof NativeElementNode)) return;
let propName = childNode.propAttribute;
if (!propName) return;
//Special case Array and Observable Array keys
propName = this._normalizedKeys.get(propName) || propName
switch (this.propConfig[propName]) {
case NativeElementPropType.Array:
case NativeElementPropType.ObservableArray:
removeFromArrayProp(this.nativeElement, childNode.nativeElement, propName)
return;
default:
this.setAttribute(propName, null);
}
super.onRemovedChild(childNode)
}
setAttribute(fullkey: string, value: any) {
const nv = this.nativeElement as any
let setTarget = nv;
// normalize key
if (isAndroid && fullkey.startsWith('android:')) {
fullkey = fullkey.substr(8);
}
if (isIOS && fullkey.startsWith('ios:')) {
fullkey = fullkey.substr(4);
}
if (fullkey.startsWith("prop:")) {
this.propAttribute = fullkey.substr(5);
return;
}
//we might be getting an element from a propertyNode eg page.actionBar, unwrap
if (value instanceof NativeElementNode) {
value = value.nativeElement
}
let keypath = fullkey.split(".");
let resolvedKeys: string[] = [];
while (keypath.length > 0) {
if (!setTarget) return;
let key = keypath.shift();
// normalize to correct case
if (resolvedKeys.length == 0) {
key = this._normalizedKeys.get(key) || key
} else {
key = normalizeKeyFromObject(setTarget, key)
}
resolvedKeys.push(key)
if (keypath.length > 0) {
setTarget = setTarget[key];
} else {
try {
log.debug(() => `setAttr value ${this} ${resolvedKeys.join(".")} ${value}`)
setTarget[key] = value
} catch (e) {
// ignore but log
log.error(() => `set attribute threw an error, attr:${key} on ${this._tagName}: ${e.message}`)
}
}
}
}
}
export function registerNativeConfigElement<T>(elementName: string, resolver: () => new () => T, parentProp: string = null, propConfig: NativeElementPropConfig = {}) {
registerElement(elementName, () => new NativeElementNode(elementName, resolver(), parentProp, propConfig));
}