2023-03-14 13:18:55 +00:00
|
|
|
/**
|
|
|
|
* Copyright (c) HashiCorp, Inc.
|
2023-08-11 13:12:13 +00:00
|
|
|
* SPDX-License-Identifier: BUSL-1.1
|
2023-03-14 13:18:55 +00:00
|
|
|
*/
|
|
|
|
|
2022-02-01 14:25:24 +00:00
|
|
|
import Modifier from 'ember-modifier';
|
|
|
|
import { action } from '@ember/object';
|
|
|
|
import { inject as service } from '@ember/service';
|
2023-10-17 13:27:42 +00:00
|
|
|
import { registerDestructor } from '@ember/destroyable';
|
|
|
|
|
|
|
|
function cleanup(instance) {
|
|
|
|
if (instance) {
|
|
|
|
instance.doc?.removeEventListener('click', instance.listen);
|
|
|
|
}
|
|
|
|
}
|
2022-02-01 14:25:24 +00:00
|
|
|
|
|
|
|
export default class OnOutsideModifier extends Modifier {
|
|
|
|
@service('dom') dom;
|
|
|
|
|
2023-10-17 13:27:42 +00:00
|
|
|
constructor(owner, args) {
|
|
|
|
super(owner, args);
|
2022-02-01 14:25:24 +00:00
|
|
|
this.doc = this.dom.document();
|
2023-10-17 13:27:42 +00:00
|
|
|
|
|
|
|
registerDestructor(this, cleanup);
|
2022-02-01 14:25:24 +00:00
|
|
|
}
|
2023-10-17 13:27:42 +00:00
|
|
|
|
|
|
|
async modify(element, positional, named) {
|
|
|
|
cleanup.call(this);
|
|
|
|
|
|
|
|
this.params = positional;
|
|
|
|
this.options = named;
|
|
|
|
this.element = element;
|
|
|
|
|
2022-09-15 08:43:17 +00:00
|
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
2022-02-01 14:25:24 +00:00
|
|
|
try {
|
2023-10-17 13:27:42 +00:00
|
|
|
this.doc.addEventListener(positional[0], this.listen);
|
2022-02-01 14:25:24 +00:00
|
|
|
} catch (e) {
|
|
|
|
// continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@action
|
|
|
|
listen(e) {
|
2023-10-17 13:27:42 +00:00
|
|
|
if (this.element && this.dom.isOutside(this.element, e.target)) {
|
2022-09-15 08:43:17 +00:00
|
|
|
const dispatch = typeof this.params[1] === 'function' ? this.params[1] : (_) => {};
|
2022-02-01 14:25:24 +00:00
|
|
|
dispatch.apply(this.element, [e]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|