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
|
|
|
*/
|
|
|
|
|
2021-07-06 15:56:36 +00:00
|
|
|
import Modifier from 'ember-modifier';
|
|
|
|
import { inject as service } from '@ember/service';
|
|
|
|
import { runInDebug } from '@ember/debug';
|
2023-10-17 13:27:42 +00:00
|
|
|
import { registerDestructor } from '@ember/destroyable';
|
2021-07-06 15:56:36 +00:00
|
|
|
|
|
|
|
const typeAssertion = (type, value, withDefault) => {
|
|
|
|
return typeof value === type ? value : withDefault;
|
|
|
|
};
|
2023-10-17 13:27:42 +00:00
|
|
|
|
|
|
|
function cleanup(instance) {
|
|
|
|
if (instance && instance?.source && instance?.hash) {
|
|
|
|
instance.source?.off('success', instance.hash.success)?.off('error', instance.hash.error);
|
|
|
|
|
|
|
|
instance.source?.destroy();
|
|
|
|
instance.hash = null;
|
|
|
|
instance.source = null;
|
|
|
|
}
|
|
|
|
}
|
2021-07-06 15:56:36 +00:00
|
|
|
export default class WithCopyableModifier extends Modifier {
|
|
|
|
@service('clipboard/os') clipboard;
|
|
|
|
|
|
|
|
hash = null;
|
|
|
|
source = null;
|
|
|
|
|
|
|
|
connect([value], _hash) {
|
|
|
|
value = typeAssertion('string', value, this.element.innerText);
|
|
|
|
const hash = {
|
2022-09-15 08:43:17 +00:00
|
|
|
success: (e) => {
|
|
|
|
runInDebug((_) => console.info(`with-copyable: Copied \`${value}\``));
|
2021-07-06 15:56:36 +00:00
|
|
|
return typeAssertion('function', _hash.success, () => {})(e);
|
|
|
|
},
|
2022-09-15 08:43:17 +00:00
|
|
|
error: (e) => {
|
|
|
|
runInDebug((_) => console.info(`with-copyable: Error copying \`${value}\``));
|
2021-07-06 15:56:36 +00:00
|
|
|
return typeAssertion('function', _hash.error, () => {})(e);
|
|
|
|
},
|
|
|
|
};
|
|
|
|
this.source = this.clipboard
|
|
|
|
.execute(this.element, {
|
2022-09-15 08:43:17 +00:00
|
|
|
text: (_) => value,
|
2023-03-20 22:41:47 +00:00
|
|
|
container: this.element,
|
2021-07-06 15:56:36 +00:00
|
|
|
...hash.options,
|
|
|
|
})
|
|
|
|
.on('success', hash.success)
|
|
|
|
.on('error', hash.error);
|
|
|
|
this.hash = hash;
|
|
|
|
}
|
|
|
|
|
2023-10-17 13:27:42 +00:00
|
|
|
constructor() {
|
|
|
|
super(...arguments);
|
|
|
|
registerDestructor(this, cleanup);
|
2021-07-06 15:56:36 +00:00
|
|
|
}
|
|
|
|
|
2023-10-17 13:27:42 +00:00
|
|
|
modify(element, value, namedArgs) {
|
|
|
|
this.element = element;
|
2021-07-06 15:56:36 +00:00
|
|
|
this.disconnect();
|
2023-10-17 13:27:42 +00:00
|
|
|
this.connect(value, namedArgs);
|
2021-07-06 15:56:36 +00:00
|
|
|
}
|
|
|
|
|
2023-10-17 13:27:42 +00:00
|
|
|
disconnect() {
|
|
|
|
cleanup.call(this);
|
2021-07-06 15:56:36 +00:00
|
|
|
}
|
|
|
|
}
|