This repository has been archived by the owner on Sep 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
interimElement.js
428 lines (383 loc) · 14.7 KB
/
interimElement.js
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
angular.module('material.core')
.provider('$$interimElement', InterimElementProvider);
/*
* @ngdoc service
* @name $$interimElement
* @module material.core
*
* @description
*
* Factory that contructs `$$interimElement.$service` services.
* Used internally in material design for elements that appear on screen temporarily.
* The service provides a promise-like API for interacting with the temporary
* elements.
*
* ```js
* app.service('$mdToast', function($$interimElement) {
* var $mdToast = $$interimElement(toastDefaultOptions);
* return $mdToast;
* });
* ```
* @param {object=} defaultOptions Options used by default for the `show` method on the service.
*
* @returns {$$interimElement.$service}
*
*/
function InterimElementProvider() {
createInterimElementProvider.$get = InterimElementFactory;
return createInterimElementProvider;
/**
* Returns a new provider which allows configuration of a new interimElement
* service. Allows configuration of default options & methods for options,
* as well as configuration of 'preset' methods (eg dialog.basic(): basic is a preset method)
*/
function createInterimElementProvider(interimFactoryName) {
var EXPOSED_METHODS = ['onHide', 'onShow', 'onRemove'];
var customMethods = {};
var providerConfig = {
presets: {}
};
var provider = {
setDefaults: setDefaults,
addPreset: addPreset,
addMethod: addMethod,
$get: factory
};
/**
* all interim elements will come with the 'build' preset
*/
provider.addPreset('build', {
methods: ['controller', 'controllerAs', 'resolve',
'template', 'templateUrl', 'themable', 'transformTemplate', 'parent']
});
return provider;
/**
* Save the configured defaults to be used when the factory is instantiated
*/
function setDefaults(definition) {
providerConfig.optionsFactory = definition.options;
providerConfig.methods = (definition.methods || []).concat(EXPOSED_METHODS);
return provider;
}
/**
* Add a method to the factory that isn't specific to any interim element operations
*/
function addMethod(name, fn) {
customMethods[name] = fn;
return provider;
}
/**
* Save the configured preset to be used when the factory is instantiated
*/
function addPreset(name, definition) {
definition = definition || {};
definition.methods = definition.methods || [];
definition.options = definition.options || function() { return {}; };
if (/^cancel|hide|show$/.test(name)) {
throw new Error("Preset '" + name + "' in " + interimFactoryName + " is reserved!");
}
if (definition.methods.indexOf('_options') > -1) {
throw new Error("Method '_options' in " + interimFactoryName + " is reserved!");
}
providerConfig.presets[name] = {
methods: definition.methods.concat(EXPOSED_METHODS),
optionsFactory: definition.options,
argOption: definition.argOption
};
return provider;
}
/**
* Create a factory that has the given methods & defaults implementing interimElement
*/
/* @ngInject */
function factory($$interimElement, $animate, $injector) {
var defaultMethods;
var defaultOptions;
var interimElementService = $$interimElement();
/*
* publicService is what the developer will be using.
* It has methods hide(), cancel(), show(), build(), and any other
* presets which were set during the config phase.
*/
var publicService = {
hide: interimElementService.hide,
cancel: interimElementService.cancel,
show: showInterimElement
};
defaultMethods = providerConfig.methods || [];
// This must be invoked after the publicService is initialized
defaultOptions = invokeFactory(providerConfig.optionsFactory, {});
// Copy over the simple custom methods
angular.forEach(customMethods, function(fn, name) {
publicService[name] = fn;
});
angular.forEach(providerConfig.presets, function(definition, name) {
var presetDefaults = invokeFactory(definition.optionsFactory, {});
var presetMethods = (definition.methods || []).concat(defaultMethods);
// Every interimElement built with a preset has a field called `$type`,
// which matches the name of the preset.
// Eg in preset 'confirm', options.$type === 'confirm'
angular.extend(presetDefaults, { $type: name });
// This creates a preset class which has setter methods for every
// method given in the `.addPreset()` function, as well as every
// method given in the `.setDefaults()` function.
//
// @example
// .setDefaults({
// methods: ['hasBackdrop', 'clickOutsideToClose', 'escapeToClose', 'targetEvent'],
// options: dialogDefaultOptions
// })
// .addPreset('alert', {
// methods: ['title', 'ok'],
// options: alertDialogOptions
// })
//
// Set values will be passed to the options when interimElemnt.show() is called.
function Preset(opts) {
this._options = angular.extend({}, presetDefaults, opts);
}
angular.forEach(presetMethods, function(name) {
Preset.prototype[name] = function(value) {
this._options[name] = value;
return this;
};
});
// Create shortcut method for one-linear methods
if (definition.argOption) {
var methodName = 'show' + name.charAt(0).toUpperCase() + name.slice(1);
publicService[methodName] = function(arg) {
var config = publicService[name](arg);
return publicService.show(config);
};
}
// eg $mdDialog.alert() will return a new alert preset
publicService[name] = function(arg) {
// If argOption is supplied, eg `argOption: 'content'`, then we assume
// if the argument is not an options object then it is the `argOption` option.
//
// @example `$mdToast.simple('hello')` // sets options.content to hello
// // because argOption === 'content'
if (arguments.length && definition.argOption && !angular.isObject(arg) &&
!angular.isArray(arg)) {
return (new Preset())[definition.argOption](arg);
} else {
return new Preset(arg);
}
};
});
return publicService;
function showInterimElement(opts) {
// opts is either a preset which stores its options on an _options field,
// or just an object made up of options
if (opts && opts._options) opts = opts._options;
return interimElementService.show(
angular.extend({}, defaultOptions, opts)
);
}
/**
* Helper to call $injector.invoke with a local of the factory name for
* this provider.
* If an $mdDialog is providing options for a dialog and tries to inject
* $mdDialog, a circular dependency error will happen.
* We get around that by manually injecting $mdDialog as a local.
*/
function invokeFactory(factory, defaultVal) {
var locals = {};
locals[interimFactoryName] = publicService;
return $injector.invoke(factory || function() { return defaultVal; }, {}, locals);
}
}
}
/* @ngInject */
function InterimElementFactory($document, $q, $rootScope, $timeout, $rootElement, $animate,
$interpolate, $mdCompiler, $mdTheming ) {
var startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
usesStandardSymbols = ((startSymbol === '{{') && (endSymbol === '}}')),
processTemplate = usesStandardSymbols ? angular.identity : replaceInterpolationSymbols;
return function createInterimElementService() {
/*
* @ngdoc service
* @name $$interimElement.$service
*
* @description
* A service used to control inserting and removing an element into the DOM.
*
*/
var stack = [];
var service;
return service = {
show: show,
hide: hide,
cancel: cancel
};
/*
* @ngdoc method
* @name $$interimElement.$service#show
* @kind function
*
* @description
* Adds the `$interimElement` to the DOM and returns a promise that will be resolved or rejected
* with hide or cancel, respectively.
*
* @param {*} options is hashMap of settings
* @returns a Promise
*
*/
function show(options) {
if (stack.length) {
return service.cancel().then(function() {
return show(options);
});
} else {
var interimElement = new InterimElement(options);
stack.push(interimElement);
return interimElement.show().then(function() {
return interimElement.deferred.promise;
});
}
}
/*
* @ngdoc method
* @name $$interimElement.$service#hide
* @kind function
*
* @description
* Removes the `$interimElement` from the DOM and resolves the promise returned from `show`
*
* @param {*} resolveParam Data to resolve the promise with
* @returns a Promise that will be resolved after the element has been removed.
*
*/
function hide(response) {
var interimElement = stack.shift();
return interimElement && interimElement.remove().then(function() {
interimElement.deferred.resolve(response);
});
}
/*
* @ngdoc method
* @name $$interimElement.$service#cancel
* @kind function
*
* @description
* Removes the `$interimElement` from the DOM and rejects the promise returned from `show`
*
* @param {*} reason Data to reject the promise with
* @returns Promise that will be resolved after the element has been removed.
*
*/
function cancel(reason) {
var interimElement = stack.shift();
return $q.when(interimElement && interimElement.remove().then(function() {
interimElement.deferred.reject(reason);
}));
}
/*
* Internal Interim Element Object
* Used internally to manage the DOM element and related data
*/
function InterimElement(options) {
var self;
var hideTimeout, element, showDone, removeDone;
options = options || {};
options = angular.extend({
preserveScope: false,
scope: options.scope || $rootScope.$new(options.isolateScope),
onShow: function(scope, element, options) {
return $animate.enter(element, options.parent);
},
onRemove: function(scope, element, options) {
// Element could be undefined if a new element is shown before
// the old one finishes compiling.
return element && $animate.leave(element) || $q.when();
}
}, options);
if (options.template) {
options.template = processTemplate(options.template);
}
return self = {
options: options,
deferred: $q.defer(),
show: function() {
var compilePromise;
if (options.skipCompile) {
compilePromise = $q(function(resolve) {
resolve({
locals: {},
link: function() { return options.element; }
});
});
} else {
compilePromise = $mdCompiler.compile(options);
}
return showDone = compilePromise.then(function(compileData) {
angular.extend(compileData.locals, self.options);
element = compileData.link(options.scope);
// Search for parent at insertion time, if not specified
if (angular.isFunction(options.parent)) {
options.parent = options.parent(options.scope, element, options);
} else if (angular.isString(options.parent)) {
options.parent = angular.element($document[0].querySelector(options.parent));
}
// If parent querySelector/getter function fails, or it's just null,
// find a default.
if (!(options.parent || {}).length) {
var el;
if ($rootElement[0] && $rootElement[0].querySelector) {
el = $rootElement[0].querySelector(':not(svg) > body');
}
if (!el) el = $rootElement[0];
if (el.nodeName == '#comment') {
el = $document[0].body;
}
options.parent = angular.element(el);
}
if (options.themable) $mdTheming(element);
var ret = options.onShow(options.scope, element, options);
return $q.when(ret)
.then(function(){
// Issue onComplete callback when the `show()` finishes
(options.onComplete || angular.noop)(options.scope, element, options);
startHideTimeout();
});
function startHideTimeout() {
if (options.hideDelay) {
hideTimeout = $timeout(service.cancel, options.hideDelay) ;
}
}
}, function(reason) { showDone = true; self.deferred.reject(reason); });
},
cancelTimeout: function() {
if (hideTimeout) {
$timeout.cancel(hideTimeout);
hideTimeout = undefined;
}
},
remove: function() {
self.cancelTimeout();
return removeDone = $q.when(showDone).then(function() {
var ret = element ? options.onRemove(options.scope, element, options) : true;
return $q.when(ret).then(function() {
if (!options.preserveScope) options.scope.$destroy();
removeDone = true;
});
});
}
};
}
};
/*
* Replace `{{` and `}}` in a string (usually a template) with the actual start-/endSymbols used
* for interpolation. This allows pre-defined templates (for components such as dialog, toast etc)
* to continue to work in apps that use custom interpolation start-/endSymbols.
*
* @param {string} text The text in which to replace `{{` / `}}`
* @returns {string} The modified string using the actual interpolation start-/endSymbols
*/
function replaceInterpolationSymbols(text) {
if (!text || !angular.isString(text)) return text;
return text.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
}
}
}