Profectus/src/components/Context.vue

44 lines
1 KiB
Vue
Raw Normal View History

2022-01-13 22:25:47 -06:00
<template>
<slot />
</template>
<script setup lang="ts">
import {
RegisterNodeInjectionKey,
UnregisterNodeInjectionKey,
NodesInjectionKey,
FeatureNode
} from "game/layers";
2022-03-22 22:55:48 -05:00
import { nextTick, provide, ref } from "vue";
2022-01-24 22:23:30 -06:00
const nodes = ref<Record<string, FeatureNode | undefined>>({});
2022-01-24 22:23:30 -06:00
defineExpose({ nodes });
2022-01-13 22:25:47 -06:00
const observerOptions = {
attributes: true,
childList: true,
subtree: false
2022-01-13 22:25:47 -06:00
};
provide(RegisterNodeInjectionKey, (id, element) => {
2022-03-22 22:55:48 -05:00
const observer = new MutationObserver(() => updateNode(id));
2022-01-13 22:25:47 -06:00
observer.observe(element, observerOptions);
nodes.value[id] = { element, observer, rect: element.getBoundingClientRect() };
2022-03-22 22:55:48 -05:00
nextTick(() => updateNode(id));
2022-01-13 22:25:47 -06:00
});
provide(UnregisterNodeInjectionKey, id => {
nodes.value[id]?.observer.disconnect();
2022-01-24 22:23:30 -06:00
nodes.value[id] = undefined;
2022-01-13 22:25:47 -06:00
});
provide(NodesInjectionKey, nodes);
2022-01-13 22:25:47 -06:00
function updateNode(id: string) {
2022-01-24 22:23:30 -06:00
const node = nodes.value[id];
2022-03-22 22:55:48 -05:00
if (node == null) {
2022-01-13 22:25:47 -06:00
return;
}
2022-03-22 22:55:48 -05:00
node.rect = node.element.getBoundingClientRect();
2022-01-13 22:25:47 -06:00
}
</script>