diff --git a/.changeset/green-cats-matter.md b/.changeset/green-cats-matter.md new file mode 100644 index 000000000000..2597640ff8e6 --- /dev/null +++ b/.changeset/green-cats-matter.md @@ -0,0 +1,5 @@ +--- +'svelte': minor +--- + +feat: add ability to extend custom element class diff --git a/documentation/docs/04-compiler-and-api/04-custom-elements-api.md b/documentation/docs/04-compiler-and-api/04-custom-elements-api.md index 12f51b644018..b120687ef72e 100644 --- a/documentation/docs/04-compiler-and-api/04-custom-elements-api.md +++ b/documentation/docs/04-compiler-and-api/04-custom-elements-api.md @@ -55,13 +55,28 @@ console.log(el.name); el.name = 'everybody'; ``` +## Component lifecycle + +Custom elements are created from Svelte components using a wrapper approach. This means the inner Svelte component has no knowledge that it is a custom element. The custom element wrapper takes care of handling its lifecycle appropriately. + +When a custom element is created, the Svelte component it wraps is _not_ created right away. It is only created in the next tick after the `connectedCallback` is invoked. Properties assigned to the custom element before it is inserted into the DOM are temporarily saved and then set on component creation, so their values are not lost. The same does not work for invoking exported functions on the custom element though, they are only available after the element has mounted. If you need to invoke functions before component creation, you can work around it by using the [`extend` option](#component-options). + +When a custom element written with Svelte is created or updated, the shadow dom will reflect the value in the next tick, not immediately. This way updates can be batched, and DOM moves which temporarily (but synchronously) detach the element from the DOM don't lead to unmounting the inner component. + +The inner Svelte component is destroyed in the next tick after the `disconnectedCallback` is invoked. + ## Component options -When constructing a custom element, you can tailor several aspects by defining `customElement` as an object within `` since Svelte 4. This object comprises a mandatory `tag` property for the custom element's name, an optional `shadow` property that can be set to `"none"` to forgo shadow root creation (note that styles are then no longer encapsulated, and you can't use slots), and a `props` option, which offers the following settings: +When constructing a custom element, you can tailor several aspects by defining `customElement` as an object within `` since Svelte 4. This object may contain the following properties: -- `attribute: string`: To update a custom element's prop, you have two alternatives: either set the property on the custom element's reference as illustrated above or use an HTML attribute. For the latter, the default attribute name is the lowercase property name. Modify this by assigning `attribute: ""`. -- `reflect: boolean`: By default, updated prop values do not reflect back to the DOM. To enable this behavior, set `reflect: true`. -- `type: 'String' | 'Boolean' | 'Number' | 'Array' | 'Object'`: While converting an attribute value to a prop value and reflecting it back, the prop value is assumed to be a `String` by default. This may not always be accurate. For instance, for a number type, define it using `type: "Number"` +- `tag`: the mandatory `tag` property for the custom element's name +- `shadow`: an optional property that can be set to `"none"` to forgo shadow root creation. Note that styles are then no longer encapsulated, and you can't use slots +- `props`: an optional property to modify certain details and behaviors of your component's properties. It offers the following settings: + - `attribute: string`: To update a custom element's prop, you have two alternatives: either set the property on the custom element's reference as illustrated above or use an HTML attribute. For the latter, the default attribute name is the lowercase property name. Modify this by assigning `attribute: ""`. + - `reflect: boolean`: By default, updated prop values do not reflect back to the DOM. To enable this behavior, set `reflect: true`. + - `type: 'String' | 'Boolean' | 'Number' | 'Array' | 'Object'`: While converting an attribute value to a prop value and reflecting it back, the prop value is assumed to be a `String` by default. This may not always be accurate. For instance, for a number type, define it using `type: "Number"` + You don't need to list all properties, those not listed will use the default settings. +- `extend`: an optional property which expects a function as its argument. It is passed the custom element class generated by Svelte and expects you to return a custom element class. This comes in handy if you have very specific requirements to the life cycle of the custom element or want to enhance the class to for example use [ElementInternals](https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals#examples) for better HTML form integration. ```svelte { + return class extends customElementConstructor { + static formAssociated = true; + + constructor() { + super(); + this.attachedInternals = this.attachInternals(); + } + }; } }} /> ... @@ -91,5 +117,4 @@ Custom elements can be a useful way to package components for consumption in a n - In Svelte, slotted content renders _lazily_. In the DOM, it renders _eagerly_. In other words, it will always be created even if the component's `` element is inside an `{#if ...}` block. Similarly, including a `` in an `{#each ...}` block will not cause the slotted content to be rendered multiple times - The `let:` directive has no effect, because custom elements do not have a way to pass data to the parent component that fills the slot - Polyfills are required to support older browsers - -When a custom element written with Svelte is created or updated, the shadow dom will reflect the value in the next tick, not immediately. This way updates can be batched, and DOM moves which temporarily (but synchronously) detach the element from the DOM don't lead to unmounting the inner component. +- You can use Svelte's context feature between regular Svelte components within a custom element, but you can't use them across custom elements. In other words, you can't use `setContext` on a parent custom element and read that with `getContext` in a child custom element. diff --git a/packages/svelte/elements.d.ts b/packages/svelte/elements.d.ts index 046ba9478601..ec450284c5b5 100644 --- a/packages/svelte/elements.d.ts +++ b/packages/svelte/elements.d.ts @@ -1676,6 +1676,9 @@ export interface SvelteHTMLElements { } > | undefined; + extend?: ( + svelteCustomElementClass: new () => HTMLElement + ) => new () => HTMLElement | undefined; }; immutable?: boolean | undefined; accessors?: boolean | undefined; diff --git a/packages/svelte/src/compiler/compile/Component.js b/packages/svelte/src/compiler/compile/Component.js index 06e849fe13b8..b7beb5336277 100644 --- a/packages/svelte/src/compiler/compile/Component.js +++ b/packages/svelte/src/compiler/compile/Component.js @@ -1710,6 +1710,7 @@ function process_component_options(component, nodes) { case 'customElement': { component_options.customElement = component_options.customElement || /** @type {any} */ ({}); + const { value } = attribute; if (value[0].type === 'MustacheTag' && value[0].expression?.value === null) { component_options.customElement.tag = null; @@ -1720,12 +1721,14 @@ function process_component_options(component, nodes) { } else if (value[0].expression.type !== 'ObjectExpression') { return component.error(attribute, compiler_errors.invalid_customElement_attribute); } + const tag = value[0].expression.properties.find((prop) => prop.key.name === 'tag'); if (tag) { parse_tag(tag, tag.value?.value); } else { return component.error(attribute, compiler_errors.invalid_customElement_attribute); } + const props = value[0].expression.properties.find((prop) => prop.key.name === 'props'); if (props) { const error = () => @@ -1770,6 +1773,7 @@ function process_component_options(component, nodes) { } } } + const shadow = value[0].expression.properties.find( (prop) => prop.key.name === 'shadow' ); @@ -1780,6 +1784,14 @@ function process_component_options(component, nodes) { } component_options.customElement.shadow = shadowdom; } + + const extend = value[0].expression.properties.find( + (prop) => prop.key.name === 'extend' + ); + if (extend?.value) { + component_options.customElement.extend = extend.value; + } + break; } case 'namespace': { @@ -1853,7 +1865,8 @@ function get_sourcemap_source_filename(compile_options) { : get_basename(compile_options.filename); } -/** @typedef {Object} ComponentOptions +/** + * @typedef {Object} ComponentOptions * @property {string} [namespace] * @property {boolean} [immutable] * @property {boolean} [accessors] @@ -1862,4 +1875,5 @@ function get_sourcemap_source_filename(compile_options) { * @property {string|null} customElement.tag * @property {'open'|'none'} [customElement.shadow] * @property {Record} [customElement.props] + * @property {(ceClass: new () => HTMLElement) => new () => HTMLElement} [customElement.extend] */ diff --git a/packages/svelte/src/compiler/compile/render_dom/index.js b/packages/svelte/src/compiler/compile/render_dom/index.js index 9a11013fc90a..b2d02bb78c1e 100644 --- a/packages/svelte/src/compiler/compile/render_dom/index.js +++ b/packages/svelte/src/compiler/compile/render_dom/index.js @@ -588,20 +588,19 @@ export default function dom(component, options) { .join(','); const use_shadow_dom = component.component_options.customElement?.shadow !== 'none' ? 'true' : 'false'; + + const create_ce = x`@create_custom_element(${name}, ${JSON.stringify( + props_str + )}, [${slots_str}], [${accessors_str}], ${use_shadow_dom}, ${ + component.component_options.customElement?.extend + })`; + if (component.component_options.customElement?.tag) { body.push( - b`@_customElements.define("${ - component.component_options.customElement.tag - }", @create_custom_element(${name}, ${JSON.stringify( - props_str - )}, [${slots_str}], [${accessors_str}], ${use_shadow_dom}));` + b`@_customElements.define("${component.component_options.customElement.tag}", ${create_ce});` ); } else { - body.push( - b`@create_custom_element(${name}, ${JSON.stringify( - props_str - )}, [${slots_str}], [${accessors_str}], ${use_shadow_dom});` - ); + body.push(b`${create_ce}`); } } diff --git a/packages/svelte/src/runtime/internal/Component.js b/packages/svelte/src/runtime/internal/Component.js index 4733b1d74594..bc5b117c2ff0 100644 --- a/packages/svelte/src/runtime/internal/Component.js +++ b/packages/svelte/src/runtime/internal/Component.js @@ -383,15 +383,17 @@ function get_custom_element_value(prop, value, props_definition, transform) { * @param {string[]} slots The slots to create * @param {string[]} accessors Other accessors besides the ones for props the component has * @param {boolean} use_shadow_dom Whether to use shadow DOM + * @param {(ce: new () => HTMLElement) => new () => HTMLElement} [extend] */ export function create_custom_element( Component, props_definition, slots, accessors, - use_shadow_dom + use_shadow_dom, + extend ) { - const Class = class extends SvelteElement { + let Class = class extends SvelteElement { constructor() { super(Component, slots, use_shadow_dom); this.$$p_d = props_definition; @@ -421,6 +423,10 @@ export function create_custom_element( } }); }); + if (extend) { + // @ts-expect-error - assigning here is fine + Class = extend(Class); + } Component.element = /** @type {any} */ (Class); return Class; } diff --git a/packages/svelte/test/runtime-browser/custom-elements-samples/custom-class/main.svelte b/packages/svelte/test/runtime-browser/custom-elements-samples/custom-class/main.svelte new file mode 100644 index 000000000000..f110b118f46e --- /dev/null +++ b/packages/svelte/test/runtime-browser/custom-elements-samples/custom-class/main.svelte @@ -0,0 +1,22 @@ + { + return class extends CeClass { + updateFoo(value) { + this.foo = value; + } + }; + } + }} +/> + + + +

{foo}

diff --git a/packages/svelte/test/runtime-browser/custom-elements-samples/custom-class/test.js b/packages/svelte/test/runtime-browser/custom-elements-samples/custom-class/test.js new file mode 100644 index 000000000000..b794f02e252f --- /dev/null +++ b/packages/svelte/test/runtime-browser/custom-elements-samples/custom-class/test.js @@ -0,0 +1,14 @@ +import * as assert from 'assert.js'; +import { tick } from 'svelte'; +import './main.svelte'; + +export default async function (target) { + const element = document.createElement('custom-element'); + element.updateFoo('42'); + target.appendChild(element); + await tick(); + + const el = target.querySelector('custom-element'); + const p = el.shadowRoot.querySelector('p'); + assert.equal(p.textContent, '42'); +}