Skip to content

Commit

Permalink
fix: only use MutationObserver after mounting
Browse files Browse the repository at this point in the history
  • Loading branch information
flekschas committed Feb 21, 2024
1 parent 0849a0b commit 82bc711
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 26 deletions.
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"type": "module",
"devDependencies": {
"vitepress": "^1.0.0-rc.42"
"vitepress": "^1.0.0-rc.44"
},
"scripts": {
"start": "vitepress dev",
Expand Down
51 changes: 26 additions & 25 deletions docs/utils.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,45 @@
import { onMounted, onUnmounted } from 'vue';

export const videoColorModeSrcSwitcher = () => {
const switchSrc = () => {
const suffix = document.documentElement.classList.contains('dark')
? 'dark'
: 'light';
let classObserver;

const videos = document.body.querySelectorAll('video');
onMounted(() => {
const switchSrc = () => {
const suffix = document.documentElement.classList.contains('dark')
? 'dark'
: 'light';

for (const video of videos) {
const name = video.dataset.name;
const videos = document.body.querySelectorAll('video');

video
.querySelector('source')
?.setAttribute('src', `/videos/${name}-${suffix}.mp4`);
for (const video of videos) {
const name = video.dataset.name;

if (video.getAttribute('poster')) {
video.setAttribute('poster', `/images/${name}-${suffix}.jpg`);
}
video
.querySelector('source')
?.setAttribute('src', `/videos/${name}-${suffix}.mp4`);

video.pause();
video.currentTime = 0;
video.load();
if (video.getAttribute('poster')) {
video.setAttribute('poster', `/images/${name}-${suffix}.jpg`);
}

video.pause();
video.currentTime = 0;
video.load();
}
}
}

const classObserver = new MutationObserver((mutations) => {
mutations.forEach((mu) => {
if (mu.type !== 'attributes' && mu.attributeName !== 'class') return;
switchSrc();
classObserver = new window.MutationObserver((mutations) => {
mutations.forEach((mu) => {
if (mu.type !== 'attributes' && mu.attributeName !== 'class') return;
switchSrc();
});
});
});

onMounted(() => {
classObserver.observe(document.documentElement, {attributes: true});
switchSrc();
});

onUnmounted(() => {
classObserver.disconnect();
if (classObserver) classObserver.disconnect();
});
}

Expand Down

0 comments on commit 82bc711

Please sign in to comment.