refactor: Migrate sizes to composition api (no-changelog) (#9748)

This commit is contained in:
Tomi Turtiainen 2024-06-14 14:30:38 +03:00 committed by GitHub
parent e293683234
commit 8b4a9dbced
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,3 +1,56 @@
<script setup lang="ts">
import type { PropType } from 'vue';
import { ref, onMounted, onUnmounted, reactive } from 'vue';
// Define props with their types
const props = defineProps({
variables: {
type: Array as PropType<string[]>,
required: true,
},
attr: {
type: String,
default: '',
},
});
const sizes = reactive<Record<string, { rem: string; px: number }>>({});
const observer = ref<MutationObserver | null>(null);
const setSizes = () => {
for (const variable of props.variables) {
const style = getComputedStyle(document.body);
const rem = style.getPropertyValue(variable);
const px = parseFloat(rem.replace('rem', '')) * 16; // Assuming default font-size is 16px
sizes[variable] = { rem, px };
}
};
onMounted(() => {
setSizes();
// Observing attributes changes in body to recompute sizes
const mutationObserverCallback = (mutationsList: MutationRecord[]) => {
for (const mutation of mutationsList) {
if (mutation.type === 'attributes') {
setSizes();
}
}
};
const body = document.querySelector('body');
if (body) {
observer.value = new MutationObserver(mutationObserverCallback);
observer.value.observe(body, { attributes: true });
}
});
onUnmounted(() => {
observer.value?.disconnect();
});
</script>
<template>
<table :class="$style.table">
<tr>
@ -17,65 +70,6 @@
</table>
</template>
<script lang="ts">
import type { PropType } from 'vue';
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Sizes',
props: {
variables: {
type: Array as PropType<string[]>,
required: true,
},
attr: {
type: String,
default: '',
},
},
data() {
return {
observer: null as null | MutationObserver,
sizes: {} as Record<string, { rem: string; px: number }>,
};
},
created() {
const setSizes = () => {
this.variables.forEach((variable: string) => {
const style = getComputedStyle(document.body);
const rem = style.getPropertyValue(variable);
const px = parseFloat(rem.replace('rem', '')) * 16;
this.sizes = {
...this.sizes,
[variable]: { rem, px },
};
});
};
setSizes();
// when theme class is added or removed, reset color values
this.observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'attributes') {
setSizes();
}
}
});
const body = document.querySelector('body');
if (body) {
this.observer.observe(body, { attributes: true });
}
},
unmounted() {
if (this.observer) {
this.observer.disconnect();
}
},
});
</script>
<style lang="scss" module>
.table {
text-align: center;