Skip to content

Commit

Permalink
Allow generic HTMLElement sub type
Browse files Browse the repository at this point in the history
  • Loading branch information
arnoson committed Jul 27, 2022
1 parent 95fe85f commit 9aaea49
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 6 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ type Component = (payload: {
}) => any
```
You can also use a sub type of `HTMLElement`, for example if you are using
a component only for `HTMLImageElement`:
```ts
registerComponent<HTMLImageElement>('my-image', ({ el }) => (el.src = '...'))
```
### Mount a single Component
Note: this will also mount any child components.
Expand Down
2 changes: 1 addition & 1 deletion src/mountComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { getComponent } from './registerComponent'
import { ComponentPayload } from './types'
import { walkComponent } from './walkComponent'

type Refs = ComponentPayload['refs']
type Refs = ComponentPayload<any>['refs']
const getRefs = (el: HTMLElement): Refs => {
const refs: Refs = {}
walkComponent(el, el => {
Expand Down
7 changes: 5 additions & 2 deletions src/registerComponent.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { Component } from './types'

export const components: Record<string, Component> = {}
export const components: Record<string, Component<any>> = {}
export const getComponent = (el: HTMLElement) => {
const name = el.dataset.simpleComponent
return name ? components[name] : undefined
}

export const registerComponent = (name: string, component: Component) => {
export const registerComponent = <T extends HTMLElement>(
name: string,
component: Component<T>
) => {
if (typeof component !== 'function') {
throw new Error(`Component ${name} is not a function.`)
}
Expand Down
6 changes: 3 additions & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ declare global {
}
}

export interface ComponentPayload {
el: HTMLElement
export interface ComponentPayload<T> {
el: T
ref: Record<string, HTMLElement>
refs: Record<string, HTMLElement[]>
}

export type Component = (payload: ComponentPayload) => any
export type Component<T> = (payload: ComponentPayload<T>) => any

0 comments on commit 9aaea49

Please sign in to comment.