Repository navigation
Description
Prerequisites
- I have read the Contributing Guidelines.
- I agree to follow the Code of Conduct.
- I have searched for existing issues that already include this feature request, without success.
Describe the Feature Request
Add a feature to the hydrate package so the renderToString function produces static html using Declarative Shadow DOMs' tag instead of the current custom solution.
Terminology used:
Declarative Shadow DOM = DSD.
Resources:
https://caniuse.com/declarative-shadow-dom
https://github.com/mfreed7/declarative-shadow-dom
Describe the Use Case
The current hydrate pacakge is good, thanks for that as we all know how hard WebComponents and SSR are, but with the implementation of DSD in Webkit and easy Polyfils, the hydrate script should have an option which produces Declarative Shadow DOM.
Please keep in mind that my internal knowledge of Stencil is limited, I take some assumptions with the benefits this feature could have.
What are the benefits:
- The browser automatically creates a shadow-root fragment from
<template shadowroot="open">. For Firefox, a simple polyfill can be used. - This also means that the WebComponents can be 100% compatible with React/SSR, as React only sees the same tree as the one specified in the template. No hydration warnings anymore.
- No extra css-scoping and de-scoping required. Just place the css as is inside a <style> tag inside the
<template>. renderToStringmay not require the full html anymore, as no mutations to<head>are needed. It would only need the code of the component(s).- Hydration does need not a full re-rendering. The contents of the DSD are still present in the #shadow-root fragment.
- Currently this means that Stencil must hydrate components before any other framework does, otherwise it would cause for example React Hydration Errors as the DOM does not match.
Describe Preferred Solution
- "Stencil Hydrate" should allow to render components using Declarative Shadow DOM
- "Stencil Hydrate"s' hydration logic should work with existing ShadowRoot and Nodes upon initialization to avoid unecessary re-rendering.
- Styles should be usable without the current custom scoping solution.
Additional Information
I dont have any information on how Firefox plans to support DSD, but for cross-framework-compatible SSR i see no way around DSD.
Edit: Firefox DSD implementation is finished: https://bugzilla.mozilla.org/show_bug.cgi?id=1712140
Activity
[-]feat: Hydrate should produce Declarative Shadow DOM[/-][+]feat: Produce Declarative Shadow DOM with Hydrate[/+]rwaskiewicz commentedon Jan 30, 2023
Thanks for the detailed request @mayerraphael! Feature requests like these are very much appreciated. This is something we've been keeping an eye on, and don't have an existing issue/feature request for. I'm going to label this to try to gauge interest in something like this, which helps from a prioritization standpoint. Thanks again!
mayerraphael commentedon Mar 29, 2023
@rwaskiewicz Any update on when or if this is planned? With currently 16 upvotes this seems to spark some interest.
I guess this would also simplify the current custom hydration logic massivly (maybe some problems that needed to be fixed with PR 2938)
rwaskiewicz commentedon Mar 29, 2023
@mayerraphael It's moved up on our backlog to do some spike work around this, but I don't have a concrete timeline to share at this time
mayerraphael commentedon Jun 27, 2023
@rwaskiewicz
Just wanted to say that Porsche is also using Stencil, but they wrote their own SSR solution using Declarative ShadowDOM:
https://github.com/porsche-design-system/porsche-design-system/blob/aa8177ff61c916c8c6872844650fd2b0bfaf1d23/packages/components/scripts/generateDSRComponents.ts#L121
benelan commentedon Sep 23, 2023
Not sure if this is possible, but it would be awesome if generating declarative shadow DOMs happened via a build flag rather than as an output of
renderToString.Using
renderToStringwith SSR frameworks requires swapping in a custom server in a lot of cases, which removes some of the frameworks' benefits. For example, Next.js says:Compiling directly to web components with declarative shadow DOMs should theoretically remove the need for middleware like
renderToString.mayerraphael commentedon Sep 23, 2023
@benelan This would be the job of the React (Wrapper) component then.
I've created a repo which shows how DSD works with a handwritten WebComponent and NextJS: https://github.com/mayerraphael/nextjs-webcomponent-hydration
It works WITHOUT a custom
server.js(updated just now with a working StencilJS component).The DSD cannot be part of the WebComponent because if you use the custom element directly in NextJS, like
<my-component />, it does not call a render function on that component, but renders the tag as is.Now a React-based wrapper components will be called by NextJS and can therefor inject the DSD as seen in my example.
Porsche does the same: their custom SSR code generates React components from the Stencil source files.
I will extend my example soon using StencilJS and try to create a generic wrapper around Stencil components so they can be used with SSR/DSD.
benelan commentedon Sep 25, 2023
Thanks for the info and sample @mayerraphael! I haven't worked with DSDs yet, but my understanding is the templates will be rendered on the server, and then the custom elements will hydrate on the client. This Chrome article talks about that a bit.
Do you mean it literally renders the component tag as text or only renders the template?
If it's the latter, that may be a React-specific issue with their VDOM implementation not re-rendering once the custom element hydrates. Stencil provides a React wrapper output target that should be able to help wire up the DSDs and force a rerender after hydration, if that's the issue.
I just used NextJS as an example but there are plenty of other SSR/SSG frameworks like Astro/SveleKit/NuxtJS that won't run into React's web component weirdness.
Note: I was able to prerender Stencil components in NextJS using
getStaticPropsinstead of a custom server at one point, but it was pretty fragile. Here is the sample if anyone is curious.mayerraphael commentedon Sep 26, 2023
Exactly, the goal is to render the
<template shadowrootmode>Tag, which the Browser converts on parsing the HTML to a ShadowRoot Fragment. This means we have a working Shadow Root even before the component hydrates on the client.I mean the first. If you have a basic HtmlElement WebComponent, you specifiy it in your code by tag, like
<my-component>. There is no import or class related for NextJS to instantiate that class and call render() on. So it cannot now the "internals" of the component. It only places the tag as is in the HTML. It is like you write a<div>tag.You can try it yourself. Just normally place your custom element by tag name () inside a NextJS page and disable JavaScript in the Browser or check the generated html. The components content will not be visible (only the children, as they can be rendered by NextJS depending if they are webcomponents too or not) until the component hydrates.
We are not on the client yet, that is another topic with problems regarding Reconciliation React Issue. This can be worked around by providing different VDOM on client and on server, as seen here. This is basically a custom React Wrapper (like the React Stencil Output Target creates, but more incomplete) which handles the DSD on the server and no-dsd on the client so React does not create hydration errors because of VDOM mismatches.
You are right that most likely all the SSR/DSD wiring has to happen in the
React/Vue/... Output Targets.They also do, at least with SSR/DSD. The problem is always the same. With a native WebComponent, you need to integrated it into the Framework so it can render the contents of the WebComponent on the server, as WebComponents are a client side only construct by nature (with the CustomElementRegistry and so on) and may use other libraries (as Stencil does with copying/adjusting Preact) to render. So you need to "tell" the framework on how to run your component and what to do with the "render()" result.
Stencil uses a custom VNode format here, derived from Preact. Because of that we need to convert the result of the
render()call to another VNode format, whatever you use for rendering.This is what i'm doing here. Instantiate the Component class (pass an empty hostref WeakMap), apply props and call the render method. Then i convert the StencilJS VNodes to Preact VNodes, so i can render them on the server. Would also be possible to convert them directly to React VNodes, but i found using preact-render-to-string easier.
I see you use the hydrate renderToString. This is what we want to get away from. The current hydrate renderToString is bad for all the reasons listed in the initial issue comment.
benelan commentedon Sep 28, 2023
That all makes sense, thanks for taking the time to write up the response! I'm looking forward to playing with DSDs more.
I think my initial suggestion of generating web components with DSDs during Stencil's component compilation is still valid though. It sounds like we are in agreement that Stencil's framework wrapper output targets should hold the responsibility of wiring up the SSR/DSDs. So
renderToStringshouldn't be required at all if the web components already have DSDs.This is all theoretical, I have no idea if it is possible with Stencil's component architecture or compilation process. And if it is possible, I'm sure it would be a much larger undertaking than switching
renderToStringto generate DSDs.However, there would be many benefits to removing the need for the component library consumers to use
renderToString. It would reduce server render time, which can be pretty significant for very large applications. It would also reduce/eliminate the extra steps required for users to get the component library set up with SSR. The steps for usingrenderToStringwill differ depending on the SSR framework, and may not even be possible/stable in some frameworks.5 remaining items
igorlino commentedon Nov 24, 2023
FYI support for Declarative Shadow DOM (DSD) has been very recently merged and is already part of the HTML spec under whatwg/html#9538
which was mentioned in this article: https://developer.chrome.com/en/articles/declarative-shadow-dom/
It would be a dream for a clean out-of-the-box way to integrate Next.js with Stencil web components without workarounds or performance penalties.
No qualified nor out-of-the-box anwers under:
christian-bromann commentedon Jun 14, 2024
We have implemented support for this in #5792. Please give it a try by installing our dev build for this:
And provide feedback. Thanks!
mayerraphael commentedon Jun 18, 2024
Thanks for your work Christian.
Unfortunately all elements next to the style tag (which are part of the original render method) in the shadow root are duplicated on hydration.
We render the following html:
The style tag is injected by us in our React component on the server. Same like the new renderToString with serializeShadowRoot should do.
This happens with every component we render on the server.
Its like those slot projection bugs that existed (and still exist to some extend).
christian-bromann commentedon Jun 18, 2024
Thanks @mayerraphael for taking a look at testing it out, I've received this feedback from my peers as well and will investigate.
christian-bromann commentedon Jun 18, 2024
@mayerraphael can you provide a minimal reproducible example by any chance?
mayerraphael commentedon Jun 19, 2024
@christian-bromann I created an isolated simple example here: https://github.com/mayerraphael/stencil-dsd-ssr-playground
I faked the SSR part by sending the html with the declarative shadow dom in a fixed way.
Upon hydration, the
<div>is rendered twice again.The component:
How the component is send out using a declarative shadow dom (see server.js).
I hope that helps.
christian-bromann commentedon Jun 20, 2024
This is not supported as Stencil relies on HTML comments created during the serialization process. Without them it won't be able to reconcile the elements properly. Applying the following patch made the example work:
mayerraphael commentedon Jun 21, 2024
@christian-bromann Thanks for your reply.
I would've not expected that those things would still be required with the new solution. The whole reason for Declarative Shadow DOM is to be able to let the HTML/CSS inside the component as-is so no reconstruction is required, just "real hydration" (attaching handlers).
I think Stencil should be able to hydrate without any weird CSS scoping (which was part of the feature request) and HTML comments (and mutation like c-id) like most frameworks out there.
Edit:
I have a really hard time to imagine how to integrate
renderToString(" ... ")into a real world application without having most of the drawbacks the old solution already had.The current solution would require, again, to first serialize the whole React/NextJS page and then pass everything to renderToString.
This does not allow:
Really curious how #5831 will be solved without those drawbacks. Especially how the increment s-id/c-id stuff will work if individual components are rendered.
But really, thanks! This is a step in the right direction, even though still hard to apply in a real-world use case.
christian-bromann commentedon Jun 21, 2024
@mayerraphael thanks a lot for your feedback!
This makes sense. I would love to track this in a separate issue as I believe it requires a new approach on how we hydrate components in general. We already had conversations within them team of getting rid of the HTML comments but this may be a breaking change that we have to carefully evaluate. Hence I suggest to track this as a next step.
How so? You can serialize/hydrate individual components by setting
fullDocument: falseas an option. In fact, my next step is to enhance the StencIl React Output target to support Next.js application using this approach.Keep an 👁️ on #5831 , I would love to get your feedback on this. I hope to have something to test for you within the next 1/2 weeks.
mayerraphael commentedon Jun 22, 2024
Because the current solution can only work with strings? Or maybe i am missing something crucial here.
Lets take a normal page in NextJS:
How would serialization work in this case? The only way i currently see is a custom server which serializes the NextJS page (with
next/apps'renderToHtml) and then running that result through hydratesrenderToString(). With the new Shadow DOM serialization we at least dont have to run Stencil first on the client because the browser already creates the Shadow Root and React is not complaining about not being isomorphic with what was declared on the server.Your solution, extending the React output target: Does this mean inside the wrapper the contents are serialized to string and some kind of dangerouslySetInnerHTML element is rendered? Or do you plan on returning React compatible VNodes (with the HTML attributes/comments added) so the serialization can be done by native React/NextJS?
The ideal case would be if Stencils React ouput target would provide React compatible JSX/VNodes (or calling a method which serializes not to string, but to VDOM) so nothing has to be done by Stencil on the server (maybe the VNodes have the required HTML attributes/comments included). But as s-id is incremental and unique for each rendering and the c-ids are dependent on s-id ($host$ part) and conditional parts inside the component, this can never be done at compile time but only at runtime? So each rendering would require quite the amount of preprocessing on Stencils part. At least according to my limited understanding.
I understand. One step after the other 👍🏼
christian-bromann commentedon Jun 24, 2024
We are working on an enhancement on the React output target which would provide better support for Next.js. The approach is to wrap the Stencil component to use the
renderToStringmethod on server side and the react output target on client side. We have a POC that verified this approach to be working fairly well. This would indeed mean we will have logic that transforms the Stencil component and its props into a string internally.Correct, it may look something like this:
Yes, these are required at runtime for Stencil to reconcile the VDOM correctly. They are indeed random which is why the
suppressHydrationErrorsflag has to be set. As mentioned before we are looking for better solutions, e.g. not being dependent on any custom attributes or html comments for reconciliation but we will approach this one step at a time.Thanks for all your great feedback so far.
tanner-reits commentedon Jun 26, 2024
The initial work for this was included in today's v4.19.0 release! Please let us know of any bugs or complications in a new issue.
chore(deps): update dependency @stencil/core to v4.19.0 (#29666)