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

Action lifecycle in custom elements #5989

Closed
arackaf opened this issue Feb 14, 2021 · 8 comments · Fixed by #8457
Closed

Action lifecycle in custom elements #5989

arackaf opened this issue Feb 14, 2021 · 8 comments · Fixed by #8457

Comments

@arackaf
Copy link
Contributor

arackaf commented Feb 14, 2021

Is this about svelte@next? This project is currently in a pre-release stage and breaking changes may occur at any time. Please do not post any kind of bug reports or questions on GitHub about it.

No.

Describe the bug

Right now, when you put an action on a component that's compiled into a custom element, the action runs immediately, upon creation, with the destroy callback never running.

It would seem that the more correct behavior would be for the action to run when the web component is connected, with the destroy callback running when disconnected.

The fix would likely be related to the code in this PR, which hasn't quite merged yet

#4522

Logs

n/a

To Reproduce

No repro - I've never been able to get custom elements to run in the REPL.

Expected behavior
A clear and concise description of what you expected to happen.

See above.

Stacktraces
If you have a stack trace to include, we recommend putting inside a <details> block for the sake of the thread's readability:

Stack trace

Stack trace goes here...

  • Your browser and the version: (e.x. Chrome 52.1, Firefox 48.0, IE 10)

Chrome

  • Your operating system: (e.x. OS X 10, Ubuntu Linux 19.10, Windows XP, etc)

Mac

  • Svelte version (Please check you can reproduce the issue with the latest release!)

3.32.3

  • Whether your project uses Webpack or Rollup

webpack

Severity
How severe an issue is this bug to you? Is this annoying, blocking some users, blocking an upgrade or blocking your usage of Svelte entirely?

Minor

Note: the more honest and specific you are here the more we will take you seriously.

Additional context
Add any other context about the problem here.

@hontas
Copy link
Contributor

hontas commented Feb 16, 2021

Could you provide a small code example to illustrate the problem?

@arackaf
Copy link
Contributor Author

arackaf commented Feb 16, 2021

@hontas sure. This is the one example I happen to have, but this applies to any action. So if you have this function / action

export function slotChildAdded(slotEl, { onChild, onAttributesChanged } = {}) {
  let mutationObserver;
  slotEl.addEventListener("slotchange", slotChangeHandler);

  function slotChangeHandler(evt) {
    const el = slotEl.assignedElements()[0];

    if (el != null) {
      // mutating children not supported
      slotEl.removeEventListener("slotchange", slotChangeHandler);
      onChild && onChild(el);

      if (onAttributesChanged) {
        handleElementsAttributes(el, onAttributesChanged);
        mutationObserver = new MutationObserver(handleElementsAttributes.bind(null, el, onAttributesChanged));
        mutationObserver.observe(el, { attributes: true, childList: false, subtree: false });
      }
    }
  }
  return {
    destroy() {
      mutationObserver && mutationObserver.disconnect();
      slotEl.removeEventListener("slotchange", slotChangeHandler);
    }
  };
}

which is used like this

<slot name="slot1" use:slotChildAdded={{ onChild: slotChildExists, onAttributesChanged: inputAttributesChanged }}></slot>

then, ideally, the action should run when the web component is connected, with the destroy function running on disconnect. Instead, it currently runs when created with the destroy callback never running (sound familiar?)

add_actions.ts in src/compiler/compile/render_dom/wrappers/shared seems like the relevant module, with more subtle integration with the Block class, but I don't have the expertise in the Svelte codebase to know exactly what the solution should look at.

@hontas
Copy link
Contributor

hontas commented Mar 11, 2021

It seems like a tricky beast since the the action-destroy call is ultimately triggered by componentInstance.$destroy that does not run on disconnect which was the initial problem I was trying to solve in #4522

So from how it looks now I wouldn't use (pun intended) the use-directive with custom elements.

But I think you can make it work by doing something like this instead:

<script>
import { onMount } from 'svelte';

let slotEl;

function mutatingSlot(slot, { onChild, onAttributeChange }) {
  const el = slot.assignedElements()[0];
  let mutationObserver;
  
  if (el) {
    onChild(el);

    mutationObserver = new MutationObserver(onAttributeChange);
    mutationObserver.observe(el, { attributes: true, childList: false, subtree: false });
  }

  return () => {
    mutationObserver && mutationObserver.disconnect();
  };
}

const onChild = (el) => {};
const onAttributeChange = ([MutationRecord]) => {};

onMount(() => {
  const onDestroy = mutatingSlot(slotEl, { onChild, onAttributeChange });

  return () => {
    onDestroy()
  };
});
</script>

<slot bind:this={slotEl} />

Good luck!

@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.

@stale stale bot added the stale-bot label Jun 26, 2021
@arackaf
Copy link
Contributor Author

arackaf commented Jun 26, 2021

bread goes stale, not issues

@stale stale bot removed the stale-bot label Jun 26, 2021
@nolanlawson
Copy link
Contributor

I noticed this same issue (nolanlawson/emoji-picker-element#152 (comment)) while I was trying to migrate to the new lifecycle behavior from #4522. I was using ResizeObserver instead of MutationObserver, but the effect is the same.

It's worth noting that browsers can be smart about automatically GC'ing event listeners and *Observers (Resize/Intersection/Mutation) when the elements they're observing are no longer referenced, but they don't necessarily do that. The thread in this Chrome bug is very informative about that. (TLDR: not all of the browsers GC ResizeObserver/IntersectionObserver when they could.)

Just spitballing, but I can see three potential solutions:

  1. Don't use actions in custom elements (:cry:)
  2. Have actions return an object with an unmount function as well as destroy (would create a disparity between Svelte components used as custom elements and those that aren't, but would solve the problem)
  3. Use FinalizationRegistry or some other fancy mechanism to automatically call element.$destroy() when the element is no longer referenced anywhere (feels a bit over-complex, and has middling browser support, but maybe it's the most straightforward solution)

@stale
Copy link

stale bot commented Dec 24, 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.

@stale stale bot added the stale-bot label Dec 24, 2021
@baseballyama baseballyama added this to the 4.x milestone Feb 26, 2023
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

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.

5 participants