Beautiful Open-Source Form Builder
Refactor dark mode handling and enhance testing for public page forms (#1162)
Chirag Chhatralab0a69945dc24
diff --git a/client/lib/forms/public-page.js b/client/lib/forms/public-page.jsindex 9e6594c76..bc6dac47e 100644--- a/client/lib/forms/public-page.js+++ b/client/lib/forms/public-page.js@@ -74,47 +74,7 @@ export function useDarkMode (elem = ref(null)) {}export function darkModeEnabled (elem = ref(null)) {- if (import.meta.server)- return ref(false)-- // TODO: replace this with a function that returns a watcher for the given of dark class element- // Simplify this- const isDark = ref(false)-- // Update isDark based on the current class- const updateIsDark = () => {- const finalElement = elem.value ?? document.documentElement- isDark.value = finalElement.classList.contains('dark')- }-- // MutationObserver callback to react to class changes- let observer = new MutationObserver(updateIsDark)-- // Initialize and clean up the observer- const initObserver = (element) => {- if (observer) {- observer.disconnect()- }- if (element) {- observer = new MutationObserver(updateIsDark)- observer.observe(element, { attributes: true, attributeFilter: ['class'] })- }- }-- onMounted(() => {- if (!import.meta.server) {- initObserver(elem)- }- })-- onUnmounted(() => {- if (observer) {- observer.disconnect()- }- })-- // Return a computed ref that depends on isDark- return computed(() => isDark.value)+ return useDarkMode(elem)}function handleDarkModeToggle (enabled) {diff --git a/client/test/unit/public-page-dark-mode.test.ts b/client/test/unit/public-page-dark-mode.test.tsnew file mode 100644index 000000000..1cc547aaf--- /dev/null+++ b/client/test/unit/public-page-dark-mode.test.ts@@ -0,0 +1,43 @@+// @vitest-environment happy-dom+import { describe, expect, it, vi } from 'vitest'+import { mount } from '@vue/test-utils'+import {+ computed,+ defineComponent,+ nextTick,+ onMounted,+ onUnmounted,+ ref,+ watch,+} from 'vue'+import { darkModeEnabled } from '../../lib/forms/public-page.js'++vi.stubGlobal('computed', computed)+vi.stubGlobal('onMounted', onMounted)+vi.stubGlobal('onUnmounted', onUnmounted)+vi.stubGlobal('ref', ref)+vi.stubGlobal('watch', watch)++describe('darkModeEnabled', () => {+ it('observes the element referenced by the ref', async () => {+ const wrapper = mount(defineComponent({+ setup () {+ const target = ref(null)+ const isDark = darkModeEnabled(target)++ return {+ isDark,+ target,+ }+ },+ template: '<div ref="target">{{ isDark }}</div>',+ }))++ expect(wrapper.text()).toBe('false')++ wrapper.element.classList.add('dark')+ await nextTick()++ expect(wrapper.text()).toBe('true')+ })+})