schlechtenburg/packages/core/lib/use-activation.ts

50 lines
1 KiB
TypeScript
Raw Normal View History

2020-12-30 01:32:46 +00:00
import {
Ref,
ref,
inject,
computed,
onBeforeUnmount,
2020-12-30 01:32:46 +00:00
} from 'vue';
2021-03-08 15:29:35 +00:00
export const SymActiveBlock = Symbol('Schlechtenburg active block');
export function useActivation(currentBlockId: string|null = null) {
const activeBlockId: Ref<string|null> = inject(SymActiveBlock, ref(null));
2020-12-30 01:32:46 +00:00
const isActive = computed(() => activeBlockId.value === currentBlockId);
const deactivate = (id: string|null = currentBlockId) => {
if (activeBlockId.value !== id) {
return;
}
activeBlockId.value = null;
2020-12-30 01:32:46 +00:00
};
const deactivateCb = (_:Event) => deactivate();
onBeforeUnmount(() => {
document.removeEventListener('click', deactivateCb);
})
const activate = (id: string|null = currentBlockId) => {
document.addEventListener('click', deactivateCb, { once: true });
activeBlockId.value = id;
};
2020-12-30 01:32:46 +00:00
const requestActivation = () => {
if (activeBlockId.value) {
return;
}
activate();
};
return {
2021-03-07 17:47:28 +00:00
activeBlockId,
2020-12-30 01:32:46 +00:00
isActive,
activate,
deactivate,
2020-12-30 01:32:46 +00:00
requestActivation,
};
}