From 657f11376cf2ef0cc2f855559a02526a2d8412d6 Mon Sep 17 00:00:00 2001 From: Simon H <5968653+dummdidumm@users.noreply.github.com> Date: Tue, 18 Jul 2023 18:21:19 +0200 Subject: [PATCH] feat: add ability to extend custom element class (#8991) This should help everyone who has special needs and use cases around custom elements. Since Svelte components are wrapped and only run on connectedCallback, it makes sense to expose the custom element class for modification before that. - fixes #8954 / closes #8955 - use extend to attach the function manually and save possible values to a prop - closes #8473 / closes #4168 - use extend to set the proper static attribute and then call attachInternals in the constructor - closes #8472 - use extend to attach anything custom you need - closes #3091 - pass `this` to a prop of your choice and use it inside your component - add some doc for #8987 --- .changeset/green-cats-matter.md | 5 ++ .../04-custom-elements-api.md | 49 ++++++++++++++++--- packages/svelte/elements.d.ts | 3 ++ .../svelte/src/compiler/compile/Component.js | 16 +++++- .../src/compiler/compile/render_dom/index.js | 19 ++++--- .../svelte/src/runtime/internal/Component.js | 10 +++- .../custom-class/main.svelte | 22 +++++++++ .../custom-class/test.js | 14 ++++++ 8 files changed, 119 insertions(+), 19 deletions(-) create mode 100644 .changeset/green-cats-matter.md create mode 100644 packages/svelte/test/runtime-browser/custom-elements-samples/custom-class/main.svelte create mode 100644 packages/svelte/test/runtime-browser/custom-elements-samples/custom-class/test.js 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..2227ae83c27d 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 { + // Extend the class so we can let it participate in HTML forms + return class extends customElementConstructor { + static formAssociated = true; + + constructor() { + super(); + this.attachedInternals = this.attachInternals(); + } + + // Add the function here, not below in the component so that + // it's always available, not just when the inner Svelte component + // is mounted + randomIndex() { + this.elementIndex = Math.random(); + } + }; } }} /> ... @@ -91,5 +129,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 bba2dd47edba..7598e6096741 100644 --- a/packages/svelte/src/compiler/compile/Component.js +++ b/packages/svelte/src/compiler/compile/Component.js @@ -1708,6 +1708,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; @@ -1718,12 +1719,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 = () => @@ -1768,6 +1771,7 @@ function process_component_options(component, nodes) { } } } + const shadow = value[0].expression.properties.find( (prop) => prop.key.name === 'shadow' ); @@ -1778,6 +1782,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': { @@ -1851,7 +1863,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] @@ -1860,4 +1873,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'); +}