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
/
layout.js
489 lines (413 loc) · 15.6 KB
/
layout.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
(function() {
'use strict';
var $mdUtil, $interpolate, $log;
var SUFFIXES = /(-gt)?-(sm|md|lg)/g;
var WHITESPACE = /\s+/g;
var FLEX_OPTIONS = ['grow', 'initial', 'auto', 'none', 'noshrink'];
var LAYOUT_OPTIONS = ['row', 'column'];
var ALIGNMENT_MAIN_AXIS= [ "", "start", "center", "end", "stretch", "space-around", "space-between" ];
var ALIGNMENT_CROSS_AXIS= [ "", "start", "center", "end", "stretch" ];
var config = {
/**
* Enable directive attribute-to-class conversions
* Developers can use `<body md-layout-css />` to quickly
* disable the Layout directives and prohibit the injection of Layout classNames
*/
enabled: true,
/**
* List of mediaQuery breakpoints and associated suffixes
*
* [
* { suffix: "sm", mediaQuery: "screen and (max-width: 599px)" },
* { suffix: "md", mediaQuery: "screen and (min-width: 600px) and (max-width: 959px)" }
* ]
*/
breakpoints: []
};
registerLayoutAPI( angular.module('material.core.layout', ['ng']) );
/**
* registerLayoutAPI()
*
* The original ngMaterial Layout solution used attribute selectors and CSS.
*
* ```html
* <div layout="column"> My Content </div>
* ```
*
* ```css
* [layout] {
* box-sizing: border-box;
* display:flex;
* }
* [layout=column] {
* flex-direction : column
* }
* ```
*
* Use of attribute selectors creates significant performance impacts in some
* browsers... mainly IE.
*
* This module registers directives that allow the same layout attributes to be
* interpreted and converted to class selectors. The directive will add equivalent classes to each element that
* contains a Layout directive.
*
* ```html
* <div layout="column" class="layout layout-column"> My Content </div>
*```
*
* ```css
* .layout {
* box-sizing: border-box;
* display:flex;
* }
* .layout-column {
* flex-direction : column
* }
* ```
*/
function registerLayoutAPI(module){
var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
// NOTE: these are also defined in constants::MEDIA_PRIORITY and constants::MEDIA
var BREAKPOINTS = [ "", "xs", "gt-xs", "sm", "gt-sm", "md", "gt-md", "lg", "gt-lg", "xl" ];
var API_WITH_VALUES = [ "layout", "flex", "flex-order", "flex-offset", "layout-align" ];
var API_NO_VALUES = [ "show", "hide", "layout-padding", "layout-margin" ];
// Build directive registration functions for the standard Layout API... for all breakpoints.
angular.forEach(BREAKPOINTS, function(mqb) {
// Attribute directives with expected, observable value(s)
angular.forEach( API_WITH_VALUES, function(name){
var fullName = mqb ? name + "-" + mqb : name;
module.directive( directiveNormalize(fullName), attributeWithObserve(fullName));
});
// Attribute directives with no expected value(s)
angular.forEach( API_NO_VALUES, function(name){
var fullName = mqb ? name + "-" + mqb : name;
module.directive( directiveNormalize(fullName), attributeWithoutValue(fullName));
});
});
// Register other, special directive functions for the Layout features:
module
.directive('mdLayoutCss' , disableLayoutDirective )
.directive('ngCloak' , buildCloakInterceptor('ng-cloak'))
.directive('layoutWrap' , attributeWithoutValue('layout-wrap'))
.directive('layoutNoWrap' , attributeWithoutValue('layout-no-wrap'))
.directive('layoutFill' , attributeWithoutValue('layout-fill'))
// !! Deprecated attributes: use the `-lt` (aka less-than) notations
.directive('layoutLtMd' , warnAttrNotSupported('layout-lt-md', true))
.directive('layoutLtLg' , warnAttrNotSupported('layout-lt-lg', true))
.directive('flexLtMd' , warnAttrNotSupported('flex-lt-md', true))
.directive('flexLtLg' , warnAttrNotSupported('flex-lt-lg', true))
.directive('layoutAlignLtMd', warnAttrNotSupported('layout-align-lt-md'))
.directive('layoutAlignLtLg', warnAttrNotSupported('layout-align-lt-lg'))
.directive('flexOrderLtMd' , warnAttrNotSupported('flex-order-lt-md'))
.directive('flexOrderLtLg' , warnAttrNotSupported('flex-order-lt-lg'))
.directive('offsetLtMd' , warnAttrNotSupported('flex-offset-lt-md'))
.directive('offsetLtLg' , warnAttrNotSupported('flex-offset-lt-lg'))
.directive('hideLtMd' , warnAttrNotSupported('hide-lt-md'))
.directive('hideLtLg' , warnAttrNotSupported('hide-lt-lg'))
.directive('showLtMd' , warnAttrNotSupported('show-lt-md'))
.directive('showLtLg' , warnAttrNotSupported('show-lt-lg'));
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return name
.replace(PREFIX_REGEXP, '')
.replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
});
}
}
/**
* Special directive that will disable ALL Layout conversions of layout
* attribute(s) to classname(s).
*
* <link rel="stylesheet" href="angular-material.min.css">
* <link rel="stylesheet" href="angular-material.layout.css">
*
* <body md-layout-css>
* ...
* </body>
*
* Note: Using md-layout-css directive requires the developer to load the Material
* Layout Attribute stylesheet (which only uses attribute selectors):
*
* `angular-material.layout.css`
*
* Another option is to use the LayoutProvider to configure and disable the attribute
* conversions; this would obviate the use of the `md-layout-css` directive
*
*/
function disableLayoutDirective() {
return {
restrict : 'A',
priority : '900',
compile : function(element, attr) {
config.enabled = false;
return angular.noop;
}
};
}
/**
* Tail-hook ngCloak to delay the uncloaking while Layout transformers
* finish processing. Eliminates flicker with Material.Layoouts
*/
function buildCloakInterceptor(className) {
return [ '$timeout', function($timeout){
return {
restrict : 'A',
priority : -10, // run after normal ng-cloak
compile : function( element ) {
if (!config.enabled) return angular.noop;
// Re-add the cloak
element.addClass(className);
return function( scope, element ) {
// Wait while layout injectors configure, then uncloak
// NOTE: $rAF does not delay enough... and this is a 1x-only event,
// $timeout is acceptable.
$timeout( function(){
element.removeClass(className);
}, 10, false);
};
}
};
}];
}
// *********************************************************************************
//
// These functions create registration functions for ngMaterial Layout attribute directives
// This provides easy translation to switch ngMaterial attribute selectors to
// CLASS selectors and directives; which has huge performance implications
// for IE Browsers
//
// *********************************************************************************
/**
* Creates a directive registration function where a possible dynamic attribute
* value will be observed/watched.
* @param {string} className attribute name; eg `layout-gt-md` with value ="row"
*/
function attributeWithObserve(className) {
return ['$mdUtil', '$interpolate', "$log", function(_$mdUtil_, _$interpolate_, _$log_) {
$mdUtil = _$mdUtil_;
$interpolate = _$interpolate_;
$log = _$log_;
return {
restrict: 'A',
compile: function(element, attr) {
var linkFn;
if (config.enabled) {
// immediately replace static (non-interpolated) invalid values...
validateAttributeUsage(className, attr, element, $log);
validateAttributeValue( className,
getNormalizedAttrValue(className, attr, ""),
buildUpdateFn(element, className, attr)
);
linkFn = translateWithValueToCssClass;
}
// Use for postLink to account for transforms after ng-transclude.
return linkFn || angular.noop;
}
};
}];
/**
* Add as transformed class selector(s), then
* remove the deprecated attribute selector
*/
function translateWithValueToCssClass(scope, element, attrs) {
var updateFn = updateClassWithValue(element, className, attrs);
var unwatch = attrs.$observe(attrs.$normalize(className), updateFn);
updateFn(getNormalizedAttrValue(className, attrs, ""));
scope.$on("$destroy", function() { unwatch() });
}
}
/**
* Creates a registration function for ngMaterial Layout attribute directive.
* This is a `simple` transpose of attribute usage to class usage; where we ignore
* any attribute value
*/
function attributeWithoutValue(className) {
return ['$mdUtil', '$interpolate', "$log", function(_$mdUtil_, _$interpolate_, _$log_) {
$mdUtil = _$mdUtil_;
$interpolate = _$interpolate_;
$log = _$log_;
return {
restrict: 'A',
compile: function(element, attr) {
var linkFn;
if (config.enabled) {
// immediately replace static (non-interpolated) invalid values...
validateAttributeValue( className,
getNormalizedAttrValue(className, attr, ""),
buildUpdateFn(element, className, attr)
);
translateToCssClass(null, element);
// Use for postLink to account for transforms after ng-transclude.
linkFn = translateToCssClass;
}
return linkFn || angular.noop;
}
};
}];
/**
* Add as transformed class selector, then
* remove the deprecated attribute selector
*/
function translateToCssClass(scope, element) {
element.addClass(className);
}
}
/**
* After link-phase, do NOT remove deprecated layout attribute selector.
* Instead watch the attribute so interpolated data-bindings to layout
* selectors will continue to be supported.
*
* $observe() the className and update with new class (after removing the last one)
*
* e.g. `layout="{{layoutDemo.direction}}"` will update...
*
* NOTE: The value must match one of the specified styles in the CSS.
* For example `flex-gt-md="{{size}}` where `scope.size == 47` will NOT work since
* only breakpoints for 0, 5, 10, 15... 100, 33, 34, 66, 67 are defined.
*
*/
function updateClassWithValue(element, className) {
var lastClass;
return function updateClassFn(newValue) {
var value = validateAttributeValue(className, newValue || "");
if ( angular.isDefined(value) ) {
if (lastClass) element.removeClass(lastClass);
lastClass = !value ? className : className + "-" + value.replace(WHITESPACE, "-");
element.addClass(lastClass);
}
};
}
/**
* Provide console warning that this layout attribute has been deprecated
*
*/
function warnAttrNotSupported(className) {
var parts = className.split("-");
return ["$log", function($log) {
$log.warn(className + "has been deprecated. Please use a `" + parts[0] + "-gt-<xxx>` variant.");
return angular.noop;
}];
}
/**
* Centralize warnings for known flexbox issues (especially IE-related issues)
*/
function validateAttributeUsage(className, attr, element, $log){
var message, usage, url;
var nodeName = element[0].nodeName.toLowerCase();
switch(className.replace(SUFFIXES,"")) {
case "flex":
if ((nodeName == "md-button") || (nodeName == "fieldset")){
// @see https://github.com/philipwalton/flexbugs#9-some-html-elements-cant-be-flex-containers
// Use <div flex> wrapper inside (preferred) or outside
usage = "<" + nodeName + " " + className + "></" + nodeName + ">";
url = "https://github.com/philipwalton/flexbugs#9-some-html-elements-cant-be-flex-containers";
message = "Markup '{0}' may not work as expected in IE Browsers. Consult '{1}' for details.";
$log.warn( $mdUtil.supplant(message, [usage, url]) );
}
}
}
/**
* For the Layout attribute value, validate or replace with default
* fallback value
*/
function validateAttributeValue(className, value, updateFn) {
var origValue = value;
if (!needsInterpolation(value)) {
switch (className.replace(SUFFIXES,"")) {
case 'layout' :
if ( !findIn(value, LAYOUT_OPTIONS) ) {
value = LAYOUT_OPTIONS[0]; // 'row';
}
break;
case 'flex' :
if (!findIn(value, FLEX_OPTIONS)) {
if (isNaN(value)) {
value = '';
}
}
break;
case 'flex-offset' :
case 'flex-order' :
if (!value || isNaN(+value)) {
value = '0';
}
break;
case 'layout-align' :
var axis = extractAlignAxis(value);
value = $mdUtil.supplant("{main}-{cross}",axis);
break;
case 'layout-padding' :
case 'layout-margin' :
case 'layout-fill' :
case 'layout-wrap' :
case 'layout-no-wrap' :
value = '';
break;
}
if (value != origValue) {
(updateFn || angular.noop)(value);
}
}
return value;
}
/**
* Replace current attribute value with fallback value
*/
function buildUpdateFn(element, className, attrs) {
return function updateAttrValue(fallback) {
if (!needsInterpolation(fallback)) {
element.attr(className, fallback);
attrs[attrs.$normalize(className)] = fallback;
}
};
}
/**
* See if the original value has interpolation symbols:
* e.g. flex-gt-md="{{triggerPoint}}"
*/
function needsInterpolation(value) {
return (value || "").indexOf($interpolate.startSymbol()) > -1;
}
function getNormalizedAttrValue(className, attrs, defaultVal) {
var normalizedAttr = attrs.$normalize(className);
return attrs[normalizedAttr] ? attrs[normalizedAttr].replace(WHITESPACE, "-") : defaultVal || null;
}
function findIn(item, list, replaceWith) {
item = replaceWith && item ? item.replace(WHITESPACE, replaceWith) : item;
var found = false;
if (item) {
list.forEach(function(it) {
it = replaceWith ? it.replace(WHITESPACE, replaceWith) : it;
found = found || (it === item);
});
}
return found;
}
function extractAlignAxis(attrValue) {
var axis = {
main : "start",
cross: "stretch"
}, values;
attrValue = (attrValue || "");
if ( attrValue.indexOf("-") == 0 || attrValue.indexOf(" ") == 0) {
// For missing main-axis values
attrValue = "none" + attrValue;
}
values = attrValue.toLowerCase().trim().replace(WHITESPACE, "-").split("-");
if ( values.length && (values[0] === "space") ) {
// for main-axis values of "space-around" or "space-between"
values = [ values[0]+"-"+values[1],values[2] ];
}
if ( values.length > 0 ) axis.main = values[0] || axis.main;
if ( values.length > 1 ) axis.cross = values[1] || axis.cross;
if ( ALIGNMENT_MAIN_AXIS.indexOf(axis.main) < 0 ) axis.main = "start";
if ( ALIGNMENT_CROSS_AXIS.indexOf(axis.cross) < 0 ) axis.cross = "stretch";
return axis;
}
})();