-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
tracked.ts
207 lines (160 loc) · 6.34 KB
/
tracked.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
import { meta as metaFor } from '@ember/-internals/meta';
import { isEmberArray } from '@ember/array/-internals';
import { assert } from '@ember/debug';
import { DEBUG } from '@glimmer/env';
import { consumeTag, dirtyTagFor, tagFor, trackedData } from '@glimmer/validator';
import type { ElementDescriptor } from '..';
import { CHAIN_PASS_THROUGH } from './chain-tags';
import type { ExtendedMethodDecorator, DecoratorPropertyDescriptor } from './decorator';
import { COMPUTED_SETTERS, isElementDescriptor, setClassicDecorator } from './decorator';
import { SELF_TAG } from './tags';
/**
@decorator
@private
Marks a property as tracked.
By default, a component's properties are expected to be static,
meaning you are not able to update them and have the template update accordingly.
Marking a property as tracked means that when that property changes,
a rerender of the component is scheduled so the template is kept up to date.
There are two usages for the `@tracked` decorator, shown below.
@example No dependencies
If you don't pass an argument to `@tracked`, only changes to that property
will be tracked:
```typescript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
export default class MyComponent extends Component {
@tracked
remainingApples = 10
}
```
When something changes the component's `remainingApples` property, the rerender
will be scheduled.
@example Dependents
In the case that you have a computed property that depends other
properties, you want to track both so that when one of the
dependents change, a rerender is scheduled.
In the following example we have two properties,
`eatenApples`, and `remainingApples`.
```typescript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
const totalApples = 100;
export default class MyComponent extends Component {
@tracked
eatenApples = 0
get remainingApples() {
return totalApples - this.eatenApples;
}
increment() {
this.eatenApples = this.eatenApples + 1;
}
}
```
@param dependencies Optional dependents to be tracked.
*/
export function tracked(propertyDesc: {
value: any;
initializer: () => any;
}): ExtendedMethodDecorator;
export function tracked(target: object, key: string): void;
export function tracked(
target: object,
key: string,
desc: DecoratorPropertyDescriptor
): DecoratorPropertyDescriptor;
export function tracked(...args: any[]): ExtendedMethodDecorator | DecoratorPropertyDescriptor {
assert(
`@tracked can only be used directly as a native decorator. If you're using tracked in classic classes, add parenthesis to call it like a function: tracked()`,
!(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && args[4] === true)
);
if (!isElementDescriptor(args)) {
let propertyDesc = args[0];
assert(
`tracked() may only receive an options object containing 'value' or 'initializer', received ${propertyDesc}`,
args.length === 0 || (typeof propertyDesc === 'object' && propertyDesc !== null)
);
if (DEBUG && propertyDesc) {
let keys = Object.keys(propertyDesc);
assert(
`The options object passed to tracked() may only contain a 'value' or 'initializer' property, not both. Received: [${keys}]`,
keys.length <= 1 &&
(keys[0] === undefined || keys[0] === 'value' || keys[0] === 'initializer')
);
assert(
`The initializer passed to tracked must be a function. Received ${propertyDesc.initializer}`,
!('initializer' in propertyDesc) || typeof propertyDesc.initializer === 'function'
);
}
let initializer = propertyDesc ? propertyDesc.initializer : undefined;
let value = propertyDesc ? propertyDesc.value : undefined;
let decorator = function (
target: object,
key: string,
_desc?: DecoratorPropertyDescriptor,
_meta?: any,
isClassicDecorator?: boolean
): DecoratorPropertyDescriptor {
assert(
`You attempted to set a default value for ${key} with the @tracked({ value: 'default' }) syntax. You can only use this syntax with classic classes. For native classes, you can use class initializers: @tracked field = 'default';`,
isClassicDecorator
);
let fieldDesc = {
initializer: initializer || (() => value),
};
return descriptorForField([target, key, fieldDesc]);
};
setClassicDecorator(decorator);
return decorator;
}
return descriptorForField(args);
}
if (DEBUG) {
// Normally this isn't a classic decorator, but we want to throw a helpful
// error in development so we need it to treat it like one
setClassicDecorator(tracked);
}
function descriptorForField([target, key, desc]: ElementDescriptor): DecoratorPropertyDescriptor {
assert(
`You attempted to use @tracked on ${key}, but that element is not a class field. @tracked is only usable on class fields. Native getters and setters will autotrack add any tracked fields they encounter, so there is no need mark getters and setters with @tracked.`,
!desc || (!desc.value && !desc.get && !desc.set)
);
let { getter, setter } = trackedData<any, any>(key, desc ? desc.initializer : undefined);
function get(this: object): unknown {
let value = getter(this);
// Add the tag of the returned value if it is an array, since arrays
// should always cause updates if they are consumed and then changed
if (Array.isArray(value) || isEmberArray(value)) {
consumeTag(tagFor(value, '[]'));
}
return value;
}
function set(this: object, newValue: unknown): void {
setter(this, newValue);
dirtyTagFor(this, SELF_TAG);
}
let newDesc = {
enumerable: true,
configurable: true,
isTracked: true,
get,
set,
};
COMPUTED_SETTERS.add(set);
metaFor(target).writeDescriptors(key, new TrackedDescriptor(get, set));
return newDesc;
}
export class TrackedDescriptor {
constructor(private _get: () => unknown, private _set: (value: unknown) => void) {
CHAIN_PASS_THROUGH.add(this);
}
get(obj: object): unknown {
return this._get.call(obj);
}
set(obj: object, _key: string, value: unknown): void {
this._set.call(obj, value);
}
}
export function isTrackedProperty(object: object, prop: string): boolean {
return metaFor(object).peekDescriptors(prop) instanceof TrackedDescriptor;
}