Skip to content

Commit

Permalink
feat: add ability to extend custom element class
Browse files Browse the repository at this point in the history
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 - 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
  • Loading branch information
dummdidumm committed Jul 18, 2023
1 parent f10ec83 commit ef390b4
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 19 deletions.
5 changes: 5 additions & 0 deletions .changeset/green-cats-matter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': minor
---

feat: add ability to extend custom element class
37 changes: 31 additions & 6 deletions documentation/docs/04-compiler-and-api/04-custom-elements-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<svelte:options>` 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 `<svelte:options>` 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: "<desired name>"`.
- `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: "<desired name>"`.
- `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
<svelte:options
Expand All @@ -70,12 +85,23 @@ When constructing a custom element, you can tailor several aspects by defining `
shadow: 'none',
props: {
name: { reflect: true, type: 'Number', attribute: 'element-index' }
},
extend: (customElementConstructor) => {
return class extends customElementConstructor {
static formAssociated = true;
constructor() {
super();
this.attachedInternals = this.attachInternals();
}
};
}
}}
/>
<script>
export let elementIndex;
export let attachedInternals;
</script>
...
Expand All @@ -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 `<slot>` element is inside an `{#if ...}` block. Similarly, including a `<slot>` 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.
3 changes: 3 additions & 0 deletions packages/svelte/elements.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1676,6 +1676,9 @@ export interface SvelteHTMLElements {
}
>
| undefined;
extend?: (
svelteCustomElementClass: new () => HTMLElement
) => new () => HTMLElement | undefined;
};
immutable?: boolean | undefined;
accessors?: boolean | undefined;
Expand Down
16 changes: 15 additions & 1 deletion packages/svelte/src/compiler/compile/Component.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 = () =>
Expand Down Expand Up @@ -1770,6 +1773,7 @@ function process_component_options(component, nodes) {
}
}
}

const shadow = value[0].expression.properties.find(
(prop) => prop.key.name === 'shadow'
);
Expand All @@ -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': {
Expand Down Expand Up @@ -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]
Expand All @@ -1862,4 +1875,5 @@ function get_sourcemap_source_filename(compile_options) {
* @property {string|null} customElement.tag
* @property {'open'|'none'} [customElement.shadow]
* @property {Record<string,{attribute?:string;reflect?:boolean;type?:'String'|'Boolean'|'Number'|'Array'|'Object';}>} [customElement.props]
* @property {(ceClass: new () => HTMLElement) => new () => HTMLElement} [customElement.extend]
*/
19 changes: 9 additions & 10 deletions packages/svelte/src/compiler/compile/render_dom/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
}
}

Expand Down
10 changes: 8 additions & 2 deletions packages/svelte/src/runtime/internal/Component.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<svelte:options
customElement={{
tag: 'custom-element',
extend: (CeClass) => {
return class extends CeClass {
updateFoo(value) {
this.foo = value;
}
};
}
}}
/>

<script>
export function updateFoo(value) {
foo = value;
}
export let foo;
</script>

<p>{foo}</p>
Original file line number Diff line number Diff line change
@@ -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');
}

0 comments on commit ef390b4

Please sign in to comment.