summaryrefslogtreecommitdiff
path: root/packages/client/src/components/global/sticky-container.vue
blob: 859b2c1d73c45ae1eff25c47db141d3bf33ed5c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<template>
<div ref="rootEl">
	<slot name="header"></slot>
	<div ref="bodyEl">
		<slot></slot>
	</div>
</div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref } from 'vue';

export default defineComponent({
	props: {
		autoSticky: {
			type: Boolean,
			required: false,
			default: false,
		},
	},

	setup(props, context) {
		const rootEl = ref<HTMLElement>(null);
		const bodyEl = ref<HTMLElement>(null);

		const calc = () => {
			const currentStickyTop = getComputedStyle(rootEl.value).getPropertyValue('--stickyTop') || '0px';

			const header = rootEl.value.children[0];
			if (header === bodyEl.value) {
				bodyEl.value.style.setProperty('--stickyTop', currentStickyTop);
			} else {
				bodyEl.value.style.setProperty('--stickyTop', `calc(${currentStickyTop} + ${header.offsetHeight}px)`);

				if (props.autoSticky) {
					header.style.setProperty('--stickyTop', currentStickyTop);
					header.style.position = 'sticky';
					header.style.top = 'var(--stickyTop)';
					header.style.zIndex = '1';
				}
			}
		};

		onMounted(() => {
			calc();

			const observer = new MutationObserver(() => {
				setTimeout(() => {
					calc();
				}, 100);
			});

			observer.observe(rootEl.value, {
				attributes: false,
				childList: true,
				subtree: false,
			});

			onUnmounted(() => {
				observer.disconnect();
			});
		});

		return {
			rootEl,
			bodyEl,
		};
	},
});
</script>

<style lang="scss" module>

</style>