Skip to content

[labs/react] export component and prop types #3188

Closed

Description

@taylor-vann

Which package is this a feature request for?

React (@lit-labs/react)

Description

An explicit helper type for devs to use in JSXIntrinicElements would reduce type conflicts for react clients.

declare namespace JSX {
  interface IntrinsicElements {
    foo: HelperType<CustomElement>;
  }
}

Currently we rely on Typescript to infer what is returned from createComponent and although TS is fairly good, an inference is not as durable as an explicit typing.

Related to: #3163

Alternatives and Workarounds

There are a few caveats to keep in mind:

  • our package returns a ForwardedRef as a component
  • web components not created through createComponent still need proper typing, they are not a ForardRef

Two types should be exported:

  1. type returned from createComponent
  2. a type any dev can use for IntrinsicElements

Activity

  1. self-assigned this
    on Jul 29, 2022
  2. michaelwarren1106 commented on Jul 29, 2022

    @michaelwarren1106

    This would be amazing for the Lit team's help on this kind of thing!

    I started off on this typing journey just trying to give my component consumers some intellisense in their Typescript/React apps when they were consuming/using the components I build. I started with the typing suggested in this article:

    https://coryrylan.com/blog/how-to-use-web-components-with-typescript-and-react

    and have since discovered and been troubleshooting some issues.

    The things I've been going after for the "bulletproof" web component type in react are:

    • enable all the common react syntax props correctly on web component tags
      • so all of the following wouldn't give type errors:
        • <x-comp style={{}} >
        • <x-comp ref={} >
        • <x-comp onChange={} >
    • potentially exclude className for styling since class is the proper way to style custom elements even in react
    • type custom events with the on${name} syntax
    • add support for typing the web component's own properties
    • correctly type children using react's typing so that children can be other react nodes, other web components, HTMLCollections, and strings, etc

    The following is our current working "bulletproof" web component type. It does not yet have custom event notation working, but I believe the technique mentioned in Cory's article above could be applied.

    import type { HTMLAttributes, MutableRefObject } from 'react';
    export declare type CustomElement<ComponentClass> = HTMLAttributes<ComponentClass> & Omit<Partial<ComponentClass>, 'children'> & {ref?: MutableRefObject<ComponentClass | undefined>};

    Explanation of the parts:

    • HTMLAttributes<ComponentClass> - enables all the react syntax
    • Omit<Partial<ComponentClass>, 'children'> - enables all the properties from the component, but omit's children so that react's definition of children from HTMLAttributes
    • {ref?: MutableRefObject<ComponentClass | undefined>} - adds the ref={} syntax typing and types the ref as the component if defined, or undefined if not

    I'm sure there's a cleaner way to exercise all the parts, and I'm sure there's a cleaner/more modern mechanism for this "bulletproof" type, and Id love if this package explores those options with the Lit team's expertise and provided this type back out for us component devs to use!

  3. michaelwarren1106 commented on Jul 29, 2022

    @michaelwarren1106

    Additional attempt at adding in custom events (only custom additional ones, not overwriting or omitting from events provided by DOMAttributes)

    type CustomEvents<ComponentClass, CustomEventName extends string> = {
      [key in CustomEventName]: (event: CustomEvent & { target: ComponentClass, currentTarget: ComponentClass }) => void;
    };
    
    export declare type CustomElement<ComponentClass> = HTMLAttributes<ComponentClass> &
      Omit<Partial<ComponentClass>, 'children'> & {
        ref?: MutableRefObject<ComponentClass | undefined>;
      };
    
    export declare type CustomElementWithEvents<
      ComponentClass,
      CustomEventName extends string
    > = HTMLAttributes<ComponentClass> &
      Omit<Partial<ComponentClass>, 'children'> & {
        ref?: MutableRefObject<ComponentClass | undefined>;
      } & Partial<CustomEvents<ComponentClass, `on${Capitalize<CustomEventName>}`>>;
  4. taylor-vann commented on Jul 29, 2022

    @taylor-vann
    ContributorAuthor

    I find this part pretty interesting:

    export declare type CustomElementWithEvents<
      ComponentClass,
      CustomEventName extends string
    > = HTMLAttributes<ComponentClass> &
      Omit<Partial<ComponentClass>, 'children'> & {
        ref?: MutableRefObject<ComponentClass | undefined>;
      } & Partial<CustomEvents<ComponentClass, `on${Capitalize<CustomEventName>}`>>;

    We already do this in a similar manner:

    type Events = Record<string, EventName | string>;
    
    type EventProps<R extends Events> = {
      [K in keyof R]: R[K] extends EventName
        ? (e: R[K]['__event_type']) => void
        : (e: Event) => void;
    };
    
      type ReactProps = Omit<React.HTMLAttributes<I>, keyof E>;
      type ElementWithoutPropsOrEvents = Omit<I, keyof E | keyof ReactProps>;
      type UserProps = Partial<
        ReactProps & ElementWithoutPropsOrEvents & EventProps<E>
      >;

    I've been currently working on a PR to export an explicit typing from our createComponent function that is very close to what @michaelwarren1106 has described.

    #3163

    export type UserProps<I, E extends Events = {}> = Partial<
      ReactProps<I, E> & ElementWithoutPropsOrEvents<I, E> & EventProps<E>
    >;
    // Props used by this component wrapper. This is the UserProps and the
    // special `__forwardedRef` property. Note, this ref is special because
    // it's both needed in this component to get access to the rendered element
    // and must fulfill any ref passed by the user.
    type ComponentProps<I, E extends Events = {}> = UserProps<I, E> & {
      __forwardedRef?: React.Ref<I>;
    };
    
    export type WrappedWebComponent<
      I,
      E extends Events = {}
    > = React.ForwardRefExoticComponent<
      React.PropsWithoutRef<UserProps<I, E>> & React.RefAttributes<I>
    >;

    In the above WrappedWebComponent is the return type of createComponent but there's no reason we couldn't also export UserProps as a kind of IntrinsicElement.

    There would be caveats like event listners might be correctly typed but react might not handle adding and removing them (this is where the lit-labs react package helps)

  5. taylor-vann commented on Jul 29, 2022

    @taylor-vann
    ContributorAuthor

    A type that does not include event listeners would be a good place to start. That is the main difference between React handling web components and LitLabs React Wrapper handling web components.

  6. michaelwarren1106 commented on Aug 1, 2022

    @michaelwarren1106

    another test I did today adds omission of the style prop from the component class so that react's inline style typing can take over:

    export declare type CustomElement<ComponentClass> = HTMLAttributes<ComponentClass> &
      Omit<Partial<ComponentClass>, 'children' | 'style'> & {
        ref?: MutableRefObject<ComponentClass | undefined>;
      };
    
    export declare type CustomElementWithEvents<
      ComponentClass,
      CustomEventName extends string
    > = HTMLAttributes<ComponentClass> &
      Omit<Partial<ComponentClass>, 'children' | 'style'> & {
        ref?: MutableRefObject<ComponentClass | undefined>;
      } & Partial<CustomEvents<ComponentClass, `on${Capitalize<CustomEventName>}`>>;
  7. michaelwarren1106 commented on Aug 1, 2022

    @michaelwarren1106

    this leads me to believe that any type for react we create would need to basically omit a list of props that are common to both react syntax and standard HTML props, so that the react typing can take over and be correct in the context of a react app.

  8. moved this to ⏱ In Progress in Lit Project Boardon Aug 2, 2022
  9. taylor-vann commented on Aug 2, 2022

    @taylor-vann
    ContributorAuthor

    @michaelwarren1106 totally agree and that's actually our goal code-wise! It's nice to see a similar conclusion independent of ours :)

  10. moved this from ⏱ In Progress to 🤔 In Review in Lit Project Boardon Aug 2, 2022
  11. taylor-vann commented on Sep 30, 2022

    @taylor-vann
    ContributorAuthor

    @michaelwarren1106 an explicitly exported type ReactWebComponent is now exported from @lit-labs/react!

    We're halfway to the type you requested!
    I believe one of the following types would be what you needed
    https://github.com/lit/lit/blob/main/packages/labs/react/src/create-component.ts#L29-L49

    Curious to hear more though now that we're making progress!

  12. michaelwarren1106 commented on Sep 30, 2022

    @michaelwarren1106

    amazing! I can definitely test this out some more.

    One question I've had come up that i wanted to ask. Does this new type collection type the event.target correctly on the event listeners? That was another struggle that I'm not good enough at Typescript to solve haha.

  13. taylor-vann commented on Sep 30, 2022

    @taylor-vann
    ContributorAuthor

    I can definitely find out :3

  14. michaelwarren1106 commented on Oct 4, 2022

    @michaelwarren1106

    So i tested the WebComponentProps type here and I found one error, and had one question.

    The error is that class isn't accounted for. When using a web component as a web component in a react app, you can't use className, only class will work, right? So that needs to be reflected in the typing, and I don't see it currently.

    The question is "Why can't the typing be attribute-based instead of property-based?" Right now, when we're seeing typing messages and autocomplete help bubbles in VSCode, they always contain the JS property names from my WC classes, but not the attribute names. But in react/JSX, only the attribute names work. So something like:

    <some-web-component align
    

    would show a typing hint like alignX or alignY instead of align-x and align-y. If the dev uses the autocomplete chooser, they'll get:

    <some-web-component alignY=
    

    and that wont work. A related note is that the type above didnt seem to provide any attribute value hinting when you get the correct attribute. If you type:

    <some-web-component align-y="
    

    you dont get any completion help for the values for alignY ('start', 'center', 'end' etc). Presumably thats because the JS prop and the HTML attribute have different names. IMO tho, the typing should reflect that somehow? Does that have to do with what is in HTMLElementTagMap?

  15. moved this from 🤔 In Review to ✅ Done in Lit Project Boardon Oct 11, 2022
  16. moved this from ✅ Done to 📋 Triaged in Lit Project Boardon Oct 11, 2022
  17. moved this from 📋 Triaged to ⏱ In Progress in Lit Project Boardon Oct 11, 2022
  18. moved this from ⏱ In Progress to ✅ Done in Lit Project Boardon Nov 7, 2022
  19. taylor-vann commented on Nov 9, 2022

    @taylor-vann
    ContributorAuthor

    Hey @michaelwarren1106! There have been some updates. I think some of our tests match your use case.

    We declare the web component in the HTMLElmenetTagNameMap and the IntrinsicElements namespaces.
    https://github.com/lit/lit/blob/main/packages/labs/react/src/test/create-component_test.tsx#L20-L31

    Later those props are applied to an unwrapped custom web component. The types match both the unwrapped and wrapped component.
    https://github.com/lit/lit/blob/main/packages/labs/react/src/test/create-component_test.tsx#L122

    TS understands the properties x-foo requires.

  20. taylor-vann commented on Nov 9, 2022

    @taylor-vann
    ContributorAuthor

    "Why can't the typing be attribute-based instead of property-based?"

    Would be curious to expand on that.

    We set the "attributes" from react props as properties on the element. We also interrogate the element prototype to find which properties are apart of that element. This also lets us allow us to infer some kind of type from properties on the web component with TS.

    I think if we did all our typing by "attributes" everything might be strings :)

    Or maybe I'm misunderstanding?

  21. michaelwarren1106 commented on Nov 9, 2022

    @michaelwarren1106

    that’s pretty true. my main use case i guess is with multi-word attributes like display-name. say in my WC, i have a reactive property displayName with an attribute name defined from the Lit decorator as display-name.

    In JSX when using a WC tag, say I type the tag name and start typing some attribute <x-foo d. The intellisense would show me displayName:string; right? if I choose that from
    the context menu, then i’d have <x-foo displayName=“” which wouldn’t be right? In JSX for WCs youve gotta use the actual attribute name, right?

    So if the typing isn’t smart enough to know that in JSX displayName should be autocompleted as display-name, then won’t devs who choose to use the autocomplete have to go back and change the autocomplete back to display-name=?

    you’re right that the attribute typing would all be strings and booleans, but that’s all JSX can set on a WC tag right now anyway, right? maybe once they land support for setting either/both attrs and props on a WC it’ll get better?

  22. taylor-vann commented on Nov 9, 2022

    @taylor-vann
    ContributorAuthor

    Oh I see, yah the wrapped components property names could potentially be different than the actual property names: ie kabob vs camel case.

    It's possible to correlate the attribute names you want to property names using some kind of map.

    That might be a feature worth chasing

  23. michaelwarren1106 commented on Nov 9, 2022

    @michaelwarren1106

    i wonder if it’s something to do with HTMLElementTagMap? I think Justin said somewhere on discord that JSX falls back to that for web component typing, so if that’s true, I wonder if there’s some like types generation helper function that could connect attrs and props together and spit out typed attributes for usage in HTMLElementTagMap?

  24. taylor-vann commented on Nov 9, 2022

    @taylor-vann
    ContributorAuthor

    That'd be an interesting default! And worth looking into, will do

  25. augustjk commented on Aug 17, 2023

    @augustjk
    Member

    I'll close this issue as the original goal of this issue was completed a while back with @lit-labs/react exporting ReactWebComponent type as the type of the return value of createComponent() and WebComponentProps type as a utility to be used for adding to JSX.IntrinsicElements.

    The latter is not feature-full as it creates a type based on the custom element class's properties. It turns everything optional, and still exposes ReactiveElement lifecycle methods in code suggestion. It'll also only work for properties with string values and isn't smart enough to detect properties with different attribute names. Addressing all of this is not possible without intimate knowledge of the custom element, making assumptions about it, and/or adding additional dependency to the package which I don't think we're ready to tackle at the moment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions