#with ViewTransitions on, it auto switches to light mode

4 messages · Page 1 of 1 (latest)

coarse flower
#

Even with this copied directly from the tutorial it does not work:

    <script is:inline>
  // Function to set the dark mode based on localStorage or system preference
  function setDarkMode() {
    // Check if 'color-theme' is set in localStorage or if the user has a system preference
    if (
      localStorage.getItem("color-theme") === "dark" ||
      (!("color-theme" in localStorage) &&
        window.matchMedia("(prefers-color-scheme: dark)").matches)
    ) {
      // Apply the dark theme
      document.documentElement.classList.add("dark");
    } else {
      // Remove the dark theme
      document.documentElement.classList.remove("dark");
    }
  }
  // Call setDarkMode on initial load
  setDarkMode();
  // Listen for the 'astro:before-swap' event to update the theme on document swaps
  document.addEventListener('astro:before-swap', ev => {
    // Pass the incoming document to set the theme on it
    // Note: This assumes that the incoming document will have the same script logic
    // to handle theme setting. If not, you may need to directly manipulate the
    // incoming document's classList as done in the setDarkMode function.
    setDarkMode();
  });
</script>

at https://docs.astro.build/en/guides/view-transitions/

#

thank you!

icy pastureBOT
#
Learn: View Transitions - Lifecycle events #astrobefore-swap

Added in: [email protected]
An event that fires before the new document (which is populated during the preparation phase) replaces the current document. This event occurs inside of the view transition, where the user is still seeing a snapshot of the old page.
This event can be used to make changes before the swap occurs. The newDocument property on the event represents the incoming document. Here is an example of ensuring the browser’s light or dark mode preference in localStorage is carried over to the new page:
The astro:before-swap event can also be used to change the implementation of the swap. The default swap implementation diffs head content, moves persistent elements from the old document to the newDocument, and then replaces the entire body with the body of the new document.
At this point of the lifecycle, you could choose to define your own swap implementation, for example to diff the entire contents of the existing document (which some other routers do):

read more

amber forge
#

I have the exact same problem, and I tried with both after-swap and before-swap. Does anyone have a solution for this ?
https://github.com/shadcn-ui/ui/discussions/3528

I'm using Astro with react and shadcn/ui mode toggle

GitHub

Hi! Has anyone successfully added Dark Mode to an Astro app when also using ViewTransitions ? Iv'e followed the Shadcn/ui steps for adding Dark Mode in Astro and it works fine, but as soon as I...