2018-10-23 12:29:49 +03:00
|
|
|
import Component from '@ember/component';
|
2022-02-01 12:34:03 +03:00
|
|
|
import classic from 'ember-classic-decorator';
|
2018-10-23 12:29:49 +03:00
|
|
|
import {assert} from '@ember/debug';
|
|
|
|
import {debounce, run} from '@ember/runloop';
|
|
|
|
|
2022-02-01 12:34:03 +03:00
|
|
|
@classic
|
|
|
|
export default class AspectRatioBox extends Component {
|
|
|
|
ratio = '1/1';
|
|
|
|
base = 'height';
|
|
|
|
isResizing = true;
|
|
|
|
_ratio = 1;
|
2018-10-23 12:29:49 +03:00
|
|
|
|
|
|
|
init() {
|
2022-02-01 12:34:03 +03:00
|
|
|
super.init(...arguments);
|
2018-10-23 12:29:49 +03:00
|
|
|
this._onResizeHandler = () => {
|
|
|
|
debounce(this, this._resize, 200);
|
|
|
|
};
|
2022-02-01 12:34:03 +03:00
|
|
|
}
|
2018-10-23 12:29:49 +03:00
|
|
|
|
|
|
|
didReceiveAttrs() {
|
2022-02-01 12:34:03 +03:00
|
|
|
super.didReceiveAttrs(...arguments);
|
2018-10-23 12:29:49 +03:00
|
|
|
assert(
|
|
|
|
'{{aspect-ratio-box}} requires a `ratio` property in the format `"16/9"`',
|
|
|
|
this.ratio.match(/\d+\/\d+/)
|
|
|
|
);
|
|
|
|
this._ratio = this.ratio.split('/').reduce((prev, curr) => prev / curr);
|
2022-02-01 12:34:03 +03:00
|
|
|
}
|
2018-10-23 12:29:49 +03:00
|
|
|
|
|
|
|
didInsertElement() {
|
2022-02-01 12:34:03 +03:00
|
|
|
super.didInsertElement(...arguments);
|
2018-10-23 12:29:49 +03:00
|
|
|
this._resize();
|
|
|
|
window.addEventListener('resize', this._onResizeHandler);
|
2022-02-01 12:34:03 +03:00
|
|
|
}
|
2018-10-23 12:29:49 +03:00
|
|
|
|
|
|
|
willDestroyElement() {
|
2022-02-01 12:34:03 +03:00
|
|
|
super.willDestroyElement(...arguments);
|
2018-10-23 12:29:49 +03:00
|
|
|
window.removeEventListener('resize', this._onResizeHandler);
|
2022-02-01 12:34:03 +03:00
|
|
|
}
|
2018-10-23 12:29:49 +03:00
|
|
|
|
|
|
|
_resize() {
|
|
|
|
this.set('isResizing', true);
|
|
|
|
|
|
|
|
run.schedule('afterRender', this, function () {
|
|
|
|
if (this.base === 'height') {
|
|
|
|
this.element.style.width = `${this.element.clientHeight * this._ratio}px`;
|
|
|
|
} else {
|
|
|
|
this.element.style.height = `${this.element.clientWidth * this._ratio}px`;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.set('isResizing', false);
|
|
|
|
});
|
|
|
|
}
|
2022-02-01 12:34:03 +03:00
|
|
|
}
|