Profectus/src/components/Context.vue

44 lines
1,017 B
Vue
Raw Normal View History

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