kbrgl / svelte-french-toast

🍞🥂 Buttery smooth toast notifications for Svelte
https://svelte-french-toast.vercel.app/
MIT License
844 stars 30 forks source link

Handle dynamic change to toast height #75

Open BlueGreenMagick opened 1 month ago

BlueGreenMagick commented 1 month ago

Fixes #51

Change toast's height property when toast wrapper div's height changes.

Note that we cannot use below one liner:

$: clientHeight !== undefined && setHeight(clientHeight);

because setHeight is re-created whenever toasts is modified.

In Action

https://github.com/user-attachments/assets/47280513-2d6a-43f7-80da-77cc93a24ccf

You can test it with following example code:

toast.promise(promise, {
  loading: 'Saving...',
  success: `Settings saved! And some additional text that is very long and takes up multiple lines`,
  error: `Could not save. An enormous wall of error message is to be placed here, making the toast taller`
});
vercel[bot] commented 1 month ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
svelte-french-toast ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 13, 2024 0:59am
BlueGreenMagick commented 1 month ago

TLDR: There shouldn't be any observable difference for toasts whose height don't change.

  1. It is very likely that <div bind:clientHeight /> sets clientHeight in the same JS task as mount, right after onMount() is run. So there shouldn't be any observable difference for toasts whose height don't change.

    If we run the below code, we can observe that "heightChange" is printed between "mount" and "next microtask". So either onHeightChange() is run after onMount() synchronously, or its microtask is already queued at the time onMount() is run.

    Therefore, there is no browser paint after component mount, but before height is set.

function onHeightChange(clientHeight: number) {
  console.log("heightChange", clientHeight)
  if (clientHeight === undefined) return;
  setHeight(clientHeight);
}

onMount(async () => {
  console.log("mount");
  await Promise.resolve();
  console.log("next microtask") 
})
  1. Even if the browser actually paints a frame when the toast's height is not set, toasts are set to transparent if their height is falsy. So it doesn't cause jitters or flashes. https://github.com/kbrgl/svelte-french-toast/blob/18e26ec591c04decce740c759051dd6b55fe7873/src/lib/components/ToastBar.svelte#L26

    The other place that uses .height property is in calculateOffset(), which skips over toasts whose height is falsy. So having toasts with undefined height does not cause any issues.

The only difference from this PR that I can think of for fixed-height toast, is when a toast is queued while executing a long-running task. Before this PR, toast's duration is measured from mount. With this PR, toast's duration is measured from add, so toasts may be destroyed before it has a chance to render. Would that be an issue?