/
action.ts
450 lines (364 loc) · 13.2 KB
/
action.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/**
@module ember
*/
import { get } from '@ember/-internals/metal';
import { assert } from '@ember/debug';
import { flaggedInstrument } from '@ember/instrumentation';
import { join } from '@ember/runloop';
import { DEBUG } from '@glimmer/env';
import { CapturedArguments } from '@glimmer/interfaces';
import {
createUnboundRef,
isInvokableRef,
Reference,
updateRef,
valueForRef,
} from '@glimmer/reference';
import { _WeakSet } from '@glimmer/util';
import { internalHelper } from './internal-helper';
export const ACTIONS = new _WeakSet();
/**
The `{{action}}` helper provides a way to pass triggers for behavior (usually
just a function) between components, and into components from controllers.
### Passing functions with the action helper
There are three contexts an action helper can be used in. The first two
contexts to discuss are attribute context, and Handlebars value context.
```handlebars
{{! An example of attribute context }}
<div onclick={{action "save"}}></div>
{{! Examples of Handlebars value context }}
{{input on-input=(action "save")}}
{{yield (action "refreshData") andAnotherParam}}
```
In these contexts,
the helper is called a "closure action" helper. Its behavior is simple:
If passed a function name, read that function off the `actions` property
of the current context. Once that function is read, or immediately if a function was
passed, create a closure over that function and any arguments.
The resulting value of an action helper used this way is simply a function.
For example, in the attribute context:
```handlebars
{{! An example of attribute context }}
<div onclick={{action "save"}}></div>
```
The resulting template render logic would be:
```js
var div = document.createElement('div');
var actionFunction = (function(context){
return function() {
return context.actions.save.apply(context, arguments);
};
})(context);
div.onclick = actionFunction;
```
Thus when the div is clicked, the action on that context is called.
Because the `actionFunction` is just a function, closure actions can be
passed between components and still execute in the correct context.
Here is an example action handler on a component:
```app/components/my-component.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class extends Component {
@action
save() {
this.model.save();
}
}
```
Actions are always looked up on the `actions` property of the current context.
This avoids collisions in the naming of common actions, such as `destroy`.
Two options can be passed to the `action` helper when it is used in this way.
* `target=someProperty` will look to `someProperty` instead of the current
context for the `actions` hash. This can be useful when targeting a
service for actions.
* `value="target.value"` will read the path `target.value` off the first
argument to the action when it is called and rewrite the first argument
to be that value. This is useful when attaching actions to event listeners.
### Invoking an action
Closure actions curry both their scope and any arguments. When invoked, any
additional arguments are added to the already curried list.
Actions should be invoked using the [sendAction](/ember/release/classes/Component/methods/sendAction?anchor=sendAction)
method. The first argument to `sendAction` is the action to be called, and
additional arguments are passed to the action function. This has interesting
properties combined with currying of arguments. For example:
```app/components/update-name.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class extends Component {
@action
setName(model, name) {
model.set('name', name);
}
}
```
```app/components/update-name.hbs
{{input on-input=(action (action 'setName' @model) value="target.value")}}
```
The first argument (`@model`) was curried over, and the run-time argument (`event`)
becomes a second argument. Action calls can be nested this way because each simply
returns a function. Any function can be passed to the `{{action}}` helper, including
other actions.
Actions invoked with `sendAction` have the same currying behavior as demonstrated
with `on-input` above. For example:
```app/components/my-input.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class extends Component {
@action
setName(model, name) {
model.set('name', name);
}
}
```
```handlebars
<MyInput @submit={{action 'setName' @model}} />
```
or
```handlebars
{{my-input submit=(action 'setName' @model)}}
```
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
click() {
// Note that model is not passed, it was curried in the template
this.sendAction('submit', 'bob');
}
});
```
### Attaching actions to DOM elements
The third context of the `{{action}}` helper can be called "element space".
For example:
```handlebars
{{! An example of element space }}
<div {{action "save"}}></div>
```
Used this way, the `{{action}}` helper provides a useful shortcut for
registering an HTML element in a template for a single DOM event and
forwarding that interaction to the template's context (controller or component).
If the context of a template is a controller, actions used this way will
bubble to routes when the controller does not implement the specified action.
Once an action hits a route, it will bubble through the route hierarchy.
### Event Propagation
`{{action}}` helpers called in element space can control event bubbling. Note
that the closure style actions cannot.
Events triggered through the action helper will automatically have
`.preventDefault()` called on them. You do not need to do so in your event
handlers. If you need to allow event propagation (to handle file inputs for
example) you can supply the `preventDefault=false` option to the `{{action}}` helper:
```handlebars
<div {{action "sayHello" preventDefault=false}}>
<input type="file" />
<input type="checkbox" />
</div>
```
To disable bubbling, pass `bubbles=false` to the helper:
```handlebars
<button {{action 'edit' post bubbles=false}}>Edit</button>
```
To disable bubbling with closure style actions you must create your own
wrapper helper that makes use of `event.stopPropagation()`:
```handlebars
<div onclick={{disable-bubbling (action "sayHello")}}>Hello</div>
```
```app/helpers/disable-bubbling.js
import { helper } from '@ember/component/helper';
export function disableBubbling([action]) {
return function(event) {
event.stopPropagation();
return action(event);
};
}
export default helper(disableBubbling);
```
If you need the default handler to trigger you should either register your
own event handler, or use event methods on your view class. See
["Responding to Browser Events"](/ember/release/classes/Component)
in the documentation for `Component` for more information.
### Specifying DOM event type
`{{action}}` helpers called in element space can specify an event type.
By default the `{{action}}` helper registers for DOM `click` events. You can
supply an `on` option to the helper to specify a different DOM event name:
```handlebars
<div {{action "anActionName" on="doubleClick"}}>
click me
</div>
```
See ["Event Names"](/ember/release/classes/Component) for a list of
acceptable DOM event names.
### Specifying whitelisted modifier keys
`{{action}}` helpers called in element space can specify modifier keys.
By default the `{{action}}` helper will ignore click events with pressed modifier
keys. You can supply an `allowedKeys` option to specify which keys should not be ignored.
```handlebars
<div {{action "anActionName" allowedKeys="alt"}}>
click me
</div>
```
This way the action will fire when clicking with the alt key pressed down.
Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys.
```handlebars
<div {{action "anActionName" allowedKeys="any"}}>
click me with any key pressed
</div>
```
### Specifying a Target
A `target` option can be provided to the helper to change
which object will receive the method call. This option must be a path
to an object, accessible in the current context:
```app/templates/application.hbs
<div {{action "anActionName" target=someService}}>
click me
</div>
```
```app/controllers/application.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
export default class extends Controller {
@service someService;
}
```
@method action
@for Ember.Templates.helpers
@public
*/
export default internalHelper(
(args: CapturedArguments): Reference<Function> => {
let { named, positional } = args;
// The first two argument slots are reserved.
// pos[0] is the context (or `this`)
// pos[1] is the action name or function
// Anything else is an action argument.
let [context, action, ...restArgs] = positional;
let debugKey: string = action.debugLabel!;
let target = 'target' in named ? named.target : context;
let processArgs = makeArgsProcessor('value' in named && named.value, restArgs);
let fn: Function;
if (isInvokableRef(action)) {
fn = makeClosureAction(
action,
action as MaybeActionHandler,
invokeRef,
processArgs,
debugKey
);
} else {
fn = makeDynamicClosureAction(
valueForRef(context) as object,
target,
action,
processArgs,
debugKey
);
}
ACTIONS.add(fn);
return createUnboundRef(fn, '(result of an `action` helper)');
}
);
function NOOP(args: unknown[]) {
return args;
}
function makeArgsProcessor(valuePathRef: Reference | false, actionArgsRef: Reference[]) {
let mergeArgs: ((args: unknown[]) => unknown[]) | undefined;
if (actionArgsRef.length > 0) {
mergeArgs = (args: unknown[]) => {
return actionArgsRef.map(valueForRef).concat(args);
};
}
let readValue: ((args: unknown[]) => unknown[]) | undefined;
if (valuePathRef) {
readValue = (args: unknown[]) => {
let valuePath = valueForRef(valuePathRef);
if (valuePath && args.length > 0) {
args[0] = get(args[0] as object, valuePath as string);
}
return args;
};
}
if (mergeArgs && readValue) {
return (args: unknown[]) => {
return readValue!(mergeArgs!(args));
};
} else {
return mergeArgs || readValue || NOOP;
}
}
function makeDynamicClosureAction(
context: object,
targetRef: Reference<MaybeActionHandler>,
actionRef: Reference<string | Function>,
processArgs: (args: unknown[]) => unknown[],
debugKey: string
) {
// We don't allow undefined/null values, so this creates a throw-away action to trigger the assertions
if (DEBUG) {
makeClosureAction(
context,
valueForRef(targetRef),
valueForRef(actionRef),
processArgs,
debugKey
);
}
return (...args: any[]) => {
return makeClosureAction(
context,
valueForRef(targetRef),
valueForRef(actionRef),
processArgs,
debugKey
)(...args);
};
}
interface MaybeActionHandler {
actions?: Record<string, Function>;
}
function makeClosureAction(
context: object,
target: MaybeActionHandler,
action: string | Function,
processArgs: (args: unknown[]) => unknown[],
debugKey: string
) {
let self: object;
let fn: Function;
assert(
`Action passed is null or undefined in (action) from ${target}.`,
action !== undefined && action !== null
);
let typeofAction = typeof action;
if (typeofAction === 'string') {
self = target;
fn = target.actions! && target.actions![action as string];
assert(`An action named '${action}' was not found in ${target}`, Boolean(fn));
} else if (typeofAction === 'function') {
self = context;
fn = action as Function;
} else {
// tslint:disable-next-line:max-line-length
assert(
`An action could not be made for \`${
debugKey || action
}\` in ${target}. Please confirm that you are using either a quoted action name (i.e. \`(action '${
debugKey || 'myAction'
}')\`) or a function available in ${target}.`,
false
);
}
return (...args: any[]) => {
let payload = { target: self, args, label: '@glimmer/closure-action' };
return flaggedInstrument('interaction.ember-action', payload, () => {
return join(self, fn, ...processArgs(args));
});
};
}
// The code above:
// 1. Finds an action function, usually on the `actions` hash
// 2. Calls it with the target as the correct `this` context
// Previously, `UPDATE_REFERENCED_VALUE` was a method on the reference itself,
// so this made a bit more sense. Now, it isn't, and so we need to create a
// function that can have `this` bound to it when called. This allows us to use
// the same codepath to call `updateRef` on the reference.
function invokeRef(this: Reference, value: unknown) {
updateRef(this, value);
}