-
Notifications
You must be signed in to change notification settings - Fork 1
/
directive-css-var-width.ts
80 lines (65 loc) · 1.82 KB
/
directive-css-var-width.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
import {DomWatcher} from '../dom/dom-watcher';
import {INgDisposable} from './i-ng-disposable';
import * as dom from '../dom/dom';
import * as func from '../func/func';
export class CssVarWidth implements INgDisposable {
static get $inject() {
return ['$scope', '$element', '$attrs'];
}
private el: HTMLElement;
private watcher: DomWatcher;
private scalar: number;
private margin: number;
private max: number | null;
constructor(
$scope: ng.IScope,
$element: ng.IAugmentedJQuery,
$attrs: ng.IAttributes
) {
this.el = $element[0];
this.watcher = new DomWatcher();
this.scalar = $attrs.cssVarWidthScalar || 1;
this.margin = $attrs.cssVarWidthMargin || 0;
this.max = func.setDefault($attrs.cssVarWidthMax, null);
this.watcher.add({
element: window,
on: 'smartResize',
callback: this.paint.bind(this),
});
this.paint();
$scope.$on('$destroy', () => {
this.dispose();
});
}
paint() {
let width = this.el.offsetWidth;
width *= this.scalar;
width -= this.margin * 2;
if (this.max) {
width = Math.min(width, this.max);
}
dom.setCssVariable(this.el, '--width', String(width));
}
dispose() {
this.watcher.dispose();
}
}
/*
Usage:
ngApp.directive('cssVarwidth', cssVarWidthDirective);
<div css-var-width></div>
Results in:
<div style="--width: 1302;"></div>
// Optionally, add a scalar (percentage).
<div css-var-width css-var-width-scalar="0.93"></div>
// Optionally, add a margin in px. Px margin is doubled to account for left and right side.
<div css-var-width css-var-width-margin="20"></div>
// Optionally add a max value
<div css-var-width css-var-width-max="1000"></div>
*/
export const cssVarWidthDirective = function () {
return {
restrict: 'A',
controller: CssVarWidth,
};
};