barvian / number-flow

A component to transition, format, and localize numbers.
https://number-flow.barvian.me
MIT License
4.71k stars 75 forks source link

Preact support #32

Closed rcoopr closed 1 month ago

rcoopr commented 1 month ago

Would love to integrate this in some of my current projects, but many use preact. There are a few outstanding issues though

Component mount:

@number-flow_react.js?v=76d9a20d:208 Uncaught NotSupportedError: Failed to execute 'attachShadow' on 'Element': Shadow root cannot be created on a host which already hosts a shadow tree.
    at set parts (@number-flow_react.js?v=76d9a20d:208:37)
    at NumberFlowElement.attributeChangedCallback (@number-flow_react.js?v=76d9a20d:511:16)

There is a call to this.attachShadow({ mode: "open" }) here https://github.com/barvian/number-flow/blob/366217dfd7262172d40efd5ff232f5a773a49821/packages/number-flow/src/index.ts#L93

If we make this conditional on !this.shadowRoot, the component mounts.


Trend (auto)

We run into an issue with trend. Leaving trend on default, the transition from 9 -> 10 loops the last digit through 8, 7, ..., 1, 0 - instead of the correct behaviour of simply going from 9 to 0.

Steps to reproduce:

pnpm create vite@latest number-flow-test
# select preact. typescript
pnpm i @number--flow/react

Add this code to the homepage:

<NumberFlow
  value={count}
  format={{ notation: 'compact' }}
  locales="en-US"
/>

HMR

There is another issue with HMR. customElements.define may be called after already having defined the custom element. The steps to reproduc this are:

This error is produced:

NotSupportedError: Failed to execute 'define' on 'CustomElementRegistry': the name "number-flow" has already been used with this registry
    at NumberFlowElement.define (number-flow.js?v=76d9a20d:150:31)
    at number-flow.tsx:29:19

So it looks like we need to check if the custom element has already been defined before calling define


I have not worked with custom elements before, but I could potentially look into these issues in the coming couple of weeks.

Thanks again for the library.

barvian commented 1 month ago

Hey, thanks for the investigation! I don't have any experience with Preact and I wasn't planning on doing an official wrapper for it, but I may change my mind once I get a few more out. In the future I want to make it easier for other people to create framework wrappers for NumberFlow. Converting this to a discussion for now 👋