sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
77.43k stars 4.03k forks source link

Custom Elements Hydrated Incorrectly #7379

Open mihar-22 opened 2 years ago

mihar-22 commented 2 years ago

Describe the bug

I was able to get custom elements for our video player library (https://github.com/vidstack/player) to render server-side, but noticed strange behaviour when elements are hydrated. You can observe in the repro link provided.

Essentially the element is parsed and rendered by the browser when the initial HTML is served, however, after the element is claimed by Svelte whilst hydrating, it wipes the entire state out and sets all attributes/properties to null that were not set by the user (traced to this line).

This means all default prop values are set to an unexpected null value, and the style property is also reset which means all CSS variables that are set on the custom element itself are removed.

This behaviour is inconsistent between client-side and server-side rendering with Svelte. I'd expect the custom element to work mostly the same way regardless of how it's rendered.

I'm not entirely sure why the claiming process removes all attributes in the way it does so I can't suggest a solution. Maybe if it's a custom element leaving the attributes as-is?

NOTE: To clarify this only occurs with SSR (not an SPA), and only if the elements are registered before they're claimed by Svelte. As mentioned, it's because (1) the browser parses the HTML delivered from the server, (2) the element is registered, (3) the element is "upgraded" to a custom element, and then (4) Svelte in the claiming process wipes all attrs/props by resetting them to null.

Reproduction

https://github.com/mihar-22/svelte-custom-elements-hydration-bug

Logs

No response

System Info

System:
    OS: macOS 12.0.1
    CPU: (8) arm64 Apple M1
    Memory: 76.64 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.13.1 - ~/.volta/tools/image/node/16.13.1/bin/node
    Yarn: 1.22.17 - ~/.volta/tools/image/yarn/1.22.17/bin/yarn
    npm: 8.1.2 - ~/.volta/tools/image/node/16.13.1/bin/npm
  Browsers:
    Chrome: 98.0.4758.102
    Firefox: 97.0.2
    Safari: 15.1
  npmPackages:
    svelte: ^3.44.0 => 3.46.4

Severity

annoyance

tytusplanck-8451 commented 2 years ago

I'm having this same issue with trying to use web components in a SvelteKit app, that are built with StencilJS.

Leftium commented 6 months ago

Two work-arounds documented here:

Raphael2b3 commented 3 months ago

same issue here https://github.com/sveltejs/kit/issues/12032