Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested child components lose their css when the parent is used as a custom element #4274

Closed
TehShrike opened this issue Jan 16, 2020 · 10 comments · Fixed by #8457
Closed

Nested child components lose their css when the parent is used as a custom element #4274

TehShrike opened this issue Jan 16, 2020 · 10 comments · Fixed by #8457

Comments

@TehShrike
Copy link
Member

The setup: I'm exporting a component as a custom element with css: true. That component makes use of a nested component. That nested component has its own <style> tag.

If you check out this REPL example and flip on the css and customElement compiler toggles, you'll see the relevant output.

The problem

I expect those styles to be applied when I use the <x-app></x-app> parent component, but h1 { color: green; } never shows up in the document.

Why

You can see in the JS output that the App component instantiates the child component using new Nested({}). However, since that Nested (HTMLElement) never gets actually inserted into the document, its shadowRoot never makes it into the document.

Since the custom-element-generated component injects css in the constructor using

this.shadowRoot.innerHTML = `<style>h1{color:green}</style>`;

that means that the nested component's styles never make it into the document, and all their CSS is not applied.

What should be done

I don't know. :-x

Other potentially-relevant issues

#3520 has to do with nested custom elements, #4124 has to do with custom elements compiled with css: false.

@TehShrike
Copy link
Member Author

You can sort of work around it with this Rollup plugin

import pify from 'pify'
import fs from 'fs'
const { readFile, writeFile } = pify(fs)

const transformCeCss = async (file) => {
	const code = await readFile(file, { encoding: 'utf8' })
	const transformed = transform(code)
	await writeFile(file, transformed)
}

const assignment = 'this.shadowRoot.innerHTML = '

const transform = code => {
	const parts = code.split(assignment)
	let aggregated = ''
	const partsWithOnlyOneStyle = parts.map((part, i) => {
		const withoutAnyStyleString = part.replace(/^`<style>(.+?)<\/style>`;/, (_,css) => {
			aggregated += css
			return ''
		})

		if (i === parts.length - 1) {
			return assignment + '`<style>' + aggregated + '<style>`;' + withoutAnyStyleString
		}

		return withoutAnyStyleString
	})

	return partsWithOnlyOneStyle.join('')
}

//...

export default {
	output: {
		file: outputPath,
	},
	plugins: [
		svelte({
			css: true,
			customElement: true,
		}),
		{
			writeBundle() {
				// https://github.com/sveltejs/svelte/issues/4274
				transformCeCss(outputPath).catch(err => {
					console.error(err) // eslint-disable-line no-console
				})
			}
		}
	]
}

it rolls up all the component styles so they all get applied at the top.

You lose component style scoping, though.

@MonkeyAndres
Copy link

I just created a template for using Svelte and web components interchangeably in a codebase. And also comes with Storybook and i18n configured.
More info: https://github.com/redradix/svelte-custom-element-template

@wozzashek
Copy link

wozzashek commented Nov 10, 2020

I've just run into this issue.

EDIT: just understood the REPL from your comments.

@ile
Copy link

ile commented Mar 10, 2021

I was using that @TehShrike's Rollup plugin, which worked for a few days, but now, suddenly, the CSS is lost for one of the nested components.

So it seems like this is something that should be fixed in Svelte?

Seems that some HML+ CSS combo was the reason in that component.

The offending CSS was missing a semicolon in the last rule (should work).

@replace5
Copy link

// hack: custom-elment with sub comonents will lose style, manual set it
let elm = document.quqerySlector("xx-element")
function setShadowStyle(host, styleContent) {
	var style = document.createElement( 'style' )
	style.innerHTML = styleContent;
	host.shadowRoot.appendChild( style );
}
setShadowStyle(elm, '@import "./build/component.css"');

@stale
Copy link

stale bot commented Jun 26, 2021

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@erny100
Copy link

erny100 commented Mar 18, 2023

hi
in 2023 no fix for this bug ? not even with svetkit ?

@adrianrudnik
Copy link

adrianrudnik commented Mar 23, 2023

Just encountered this as well. As this seems to be a default behaviour, it would've been nice to have a disclaimer added to https://svelte.dev/docs#run-time-custom-element-api, at least I do not see this restriction there.

dummdidumm added a commit that referenced this issue May 2, 2023
This is an overhaul of custom elements in Svelte. Instead of compiling to a custom element class, the Svelte component class is mostly preserved as-is. Instead a wrapper is introduced which wraps a Svelte component constructor and returns a HTML element constructor. This has a couple of advantages:

- component can be used both as a custom element as well as a regular component. This allows creating one wrapper custom element and using regular Svelte components inside. Fixes #3594, fixes #3128, fixes #4274, fixes #5486, fixes #3422, fixes #2969, helps with sveltejs/kit#4502
- all components are compiled with injected styles (inlined through Javascript), fixes #4274
- the wrapper instantiates the component in `connectedCallback` and disconnects it in `disconnectedCallback` (but only after one tick, because this could be a element move). Mount/destroy works as expected inside, fixes #5989, fixes #8191
- the wrapper forwards `addEventListener` calls to `component.$on`, which allows to listen to custom events, fixes #3119, closes #4142 
- some things are hard to auto-configure, like attribute hyphen preferences or whether or not setting a property should reflect back to the attribute. This is why `<svelte:options customElement={..}>` can also take an object to modify such aspects. This option allows to specify whether setting a prop should be reflected back to the attribute (default `false`), what to use when converting the property to the attribute value and vice versa (through `type`, default `String`, or when `export let prop = false` then `Boolean`), and what the corresponding attribute for the property is (`attribute`, default lowercased prop name). These options are heavily inspired by lit: https://lit.dev/docs/components/properties. Closes #7638, fixes #5705
- adds a `shadowdom` option to control whether or not encapsulate the custom element. Closes #4330, closes #1748 

Breaking changes:
- Wrapped Svelte component now stays as a regular Svelte component (invokeing it like before with `new Component({ target: ..})` won't create a custom element). Its custom element constructor is now a static property named `element` on the class (`Component.element`) and should be regularly invoked through setting it in the html.
- The timing of mount/destroy/update is different. Mount/destroy/updating a prop all happen after a tick, so `shadowRoot.innerHTML` won't immediately reflect the change (Lit does this too). If you rely on it, you need to await a promise
@dummdidumm
Copy link
Member

Closed via #8457, to be released in Svelte 4

@LtSalt
Copy link

LtSalt commented Sep 19, 2024

I am using Svelte 4 and sveltekit. Regular svelte components within custom elements still seem to be stripped of their styles...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.