Skip to content

Instantly share code, notes, and snippets.

@Archmonger
Last active February 12, 2023 05:37
Show Gist options
  • Save Archmonger/8d01d2efba1071f4950549004719eb19 to your computer and use it in GitHub Desktop.
Save Archmonger/8d01d2efba1071f4950549004719eb19 to your computer and use it in GitHub Desktop.
from __future__ import annotations
import re
from pprint import pprint
from typing import Any, Callable, Literal, Awaitable, Union
from dataclasses import dataclass
# >>> React props <<<
# https://beta.reactjs.org/reference/react-dom/components/common#common-props
UNSUPPORTED_PROPS = {"children", "ref"}
EITHER_REGEX = re.compile(r"Either '(\w+)' or '(\w+)'.")
def camel_to_snake_case(string: str):
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", string)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
def react_doc_infer_type(key: str, value: str) -> Any:
# Key heuristics
if key.startswith("on_"):
return Union[Callable[..., Awaitable[None]], Callable[..., None]]
if key.endswith("-"):
return None
if key == "dangerously_set_inner_html":
return dict[str, str]
if key == "style":
return dict[str, str | int | float]
# Value heuristics
if value.startswith("A string."):
return str
if value.startswith("A boolean."):
return bool
if value.startswith("A boolean or a string."):
return bool | str
if value.startswith("A boolean or null."):
return bool | None
if value.startswith("A number."):
return int
# Value heuristics (special case)
match = EITHER_REGEX.match(value)
if match:
groups = match.groups()
if groups == ("ltr", "rtl"):
return Literal["ltr", "rtl"]
if groups == ("yes", "no"):
return Literal["yes", "no"]
raise ValueError(f"Unknown type for {key}")
def react_doc_to_typedict(string: str) -> dict[str, Any]:
"""Converts a docstring to a dictionary. Each dictionary entry is split by
lines, and then key value pairs are split by a colon.
If a colon is not found, then nothing is added to the dictionary.
"""
lines = string.strip().split("\n")
d = {}
for line in lines:
parts = line.split(":", maxsplit=1)
if len(parts) == 2 and parts[0] not in UNSUPPORTED_PROPS:
key, value = parts
key = key.strip()
value = value.strip()
# Convert to snake case
key = camel_to_snake_case(key)
# Remove trailing asterisk on `aria-*` and `data-*`
key = key.rstrip("*")
d[key] = react_doc_infer_type(key, value)
return d
SPECIAL_PROPS = r"""
children: A React node (an element, a string, a number, a portal, an empty node like null, undefined and booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify the children prop implicitly by nesting tags like <div><span /></div>.
dangerouslySetInnerHTML: An object of the form { __html: '<p>some html</p>' } with a raw HTML string inside. Overrides the innerHTML property of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isn’t trusted (for example, if it’s based on user data), you risk introducing an XSS vulnerability. Read more about using dangerouslySetInnerHTML.
ref: A ref object from useRef or createRef, or a ref callback function, or a string for legacy refs. Your ref will be filled with the DOM element for this node. Read more about manipulating the DOM with refs.
suppressContentEditableWarning: A boolean. If true, suppresses the warning that React shows for elements that both have children and contentEditable={true} (which normally do not work together). Use this if you’re building a text input library that manages the contentEditable content manually.
suppressHydrationWarning: A boolean. If you use server rendering, normally there is a warning when the server and the client render different content. In some rare cases (like timestamps), it is very hard or impossible to guarantee an exact match. If you set suppressHydrationWarning to true, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don’t overuse it. Read more about suppressing hydration errors.
style: An object with CSS styles, for example { fontWeight: 'bold', margin: 20 }. Similarly to the DOM style property, the CSS property names need to be written as camelCase, for example fontWeight instead of font-weight. You can pass strings or numbers as values. If you pass a number, like width: 100, React will automatically append px (“pixels”) to the value unless it’s a unitless property. We recommend using style only for dynamic styles where you don’t know the style values ahead of time. In other cases, applying plain CSS classes with className is more efficient. Read more about applying CSS with className and styles.
""" # noqa: E501
STANDARD_PROPS = r"""
accessKey: A string. Specifies a keyboard shortcut for the element. Not generally recommended.
aria-*: ARIA attributes let you specify the accessibility tree information for this element. See ARIA attributes for a complete reference. In React, all ARIA attribute names are exactly the same as in HTML.
autoCapitalize: A string. Specifies whether and how the user input should be capitalized.
className: A string. Specifies the element’s CSS class name. Read more about applying CSS styles.
contentEditable: A boolean. If true, the browser lets the user edit the rendered element directly. This is used to implement rich text input libraries like Lexical. React warns if you try to pass React children to an element with contentEditable={true} because React will not be able to update its content after user edits.
data-*: Data attributes let you attach some string data to the element, for example data-fruit="banana". In React, they are not commonly used because you would usually read data from props or state instead.
dir: Either 'ltr' or 'rtl'. Specifies the text direction of the element.
draggable: A boolean. Specifies whether the element is draggable. Part of HTML Drag and Drop API.
enterKeyHint: A string. Specifies which action to present for the enter key on virtual keyboards.
htmlFor: A string. For <label> and <output>, lets you associate the label with some control. Same as for HTML attribute. React uses the standard DOM property names (htmlFor) instead of HTML attribute names.
hidden: A boolean or a string. Specifies whether the element should be hidden.
id: A string. Specifies a unique identifier for this element, which can be used to find it later or connect it with other elements. Generate it with useId to avoid clashes between multiple instances of the same component.
is: A string. If specified, the component will behave like a custom element.
inputMode: A string. Specifies what kind of keyboard to display (for example, text, number or telephone).
itemProp: A string. Specifies which property the element represents for structured data crawlers.
lang: A string. Specifies the language of the element.
onAnimationEnd: An AnimationEvent handler function. Fires when a CSS animation completes.
onAnimationEndCapture: A version of onAnimationEnd that fires in the capture phase.
onAnimationIteration: An AnimationEvent handler function. Fires when an iteration of a CSS animation ends, and another one begins.
onAnimationIterationCapture: A version of onAnimationIteration that fires in the capture phase.
onAnimationStart: An AnimationEvent handler function. Fires when a CSS animation starts.
onAnimationStartCapture: onAnimationStart, but fires in the capture phase.
onAuxClick: A MouseEvent handler function. Fires when a non-primary pointer button was clicked.
onAuxClickCapture: A version of onAuxClick that fires in the capture phase.
onBeforeInput: An InputEvent handler function. Fires before the value of an editable element is modified. React does not yet use the native beforeinput event, and instead attempts to polyfill it using other events.
onBeforeInputCapture: A version of onBeforeInput that fires in the capture phase.
onBlur: A FocusEvent handler function. Fires when an element lost focus. Unlike the built-in browser blur event, in React the onBlur event bubbles.
onBlurCapture: A version of onBlur that fires in the capture phase.
onClick: A MouseEvent handler function. Fires when the primary button was clicked on the pointing device.
onClickCapture: A version of onClick that fires in the capture phase.
onCompositionStart: A CompositionEvent handler function. Fires when an input method editor starts a new composition session.
onCompositionStartCapture: A version of onCompositionStart that fires in the capture phase.
onCompositionEnd: A CompositionEvent handler function. Fires when an input method editor completes or cancels a composition session.
onCompositionEndCapture: A version of onCompositionEnd that fires in the capture phase.
onCompositionUpdate: A CompositionEvent handler function. Fires when an input method editor receives a new character.
onCompositionUpdateCapture: A version of onCompositionUpdate that fires in the capture phase.
onContextMenu: A MouseEvent handler function. Fires when the user tries to open a context menu.
onContextMenuCapture: A version of onContextMenu that fires in the capture phase.
onCopy: A ClipboardEvent handler function. Fires when the user tries to copy something into the clipboard.
onCopyCapture: A version of onCopy that fires in the capture phase.
onCut: A ClipboardEvent handler function. Fires when the user tries to cut something into the clipboard.
onCutCapture: A version of onCut that fires in the capture phase.
onDoubleClick: A MouseEvent handler function. Fires when the user clicks twice. Corresponds to the browser dblclick event.
onDoubleClickCapture: A version of onDoubleClick that fires in the capture phase.
onDrag: A DragEvent handler function. Fires while the user is dragging something.
onDragCapture: A version of onDrag that fires in the capture phase.
onDragEnd: A DragEvent handler function. Fires when the user stops dragging something.
onDragEndCapture: A version of onDragEnd that fires in the capture phase.
onDragEnter: A DragEvent handler function. Fires when the dragged content enters a valid drop target.
onDragEnterCapture: A version of onDragEnter that fires in the capture phase.
onDragOver: A DragEvent handler function. Fires on a valid drop target while the dragged content is dragged over it. You must call e.preventDefault() here to allow dropping.
onDragOverCapture: A version of onDragOver that fires in the capture phase.
onDragStart: A DragEvent handler function. Fires when the user starts dragging an element.
onDragStartCapture: A version of onDragStart that fires in the capture phase.
onDrop: A DragEvent handler function. Fires when something is dropped on a valid drop target.
onDropCapture: A version of onDrop that fires in the capture phase.
onFocus: A FocusEvent handler function. Fires when an element lost focus. Unlike the built-in browser focus event, in React the onFocus event bubbles.
onFocusCapture: A version of onFocus that fires in the capture phase.
onGotPointerCapture: A PointerEvent handler function. Fires when an element programmatically captures a pointer.
onGotPointerCaptureCapture: A version of onGotPointerCapture that fires in the capture phase.
onKeyDown: A KeyboardEvent handler function. Fires when a key is pressed.
onKeyDownCapture: A version of onKeyDown that fires in the capture phase.
onKeyPress: A KeyboardEvent handler function. Deprecated. Use onKeyDown or onBeforeInput instead.
onKeyPressCapture: A version of onKeyPress that fires in the capture phase.
onKeyUp: A KeyboardEvent handler function. Fires when a key is released.
onKeyUpCapture: A version of onKeyUp that fires in the capture phase.
onLostPointerCapture: A PointerEvent handler function. Fires when an element stops capturing a pointer.
onLostPointerCaptureCapture: A version of onLostPointerCapture that fires in the capture phase.
onMouseDown: A MouseEvent handler function. Fires when the pointer is pressed down.
onMouseDownCapture: A version of onMouseDown that fires in the capture phase.
onMouseEnter: A MouseEvent handler function. Fires when the pointer moves inside an element. Does not have a capture phase. Instead, onMouseLeave and onMouseEnter propagate from the element being left to the one being entered.
onMouseLeave: A MouseEvent handler function. Fires when the pointer moves outside an element. Does not have a capture phase. Instead, onMouseLeave and onMouseEnter propagate from the element being left to the one being entered.
onMouseMove: A MouseEvent handler function. Fires when the pointer changes coordinates.
onMouseMoveCapture: A version of onMouseMove that fires in the capture phase.
onMouseOut: A MouseEvent handler function. Fires when the pointer moves outside an element, or if it moves into a child element.
onMouseOutCapture: A version of onMouseOut that fires in the capture phase.
onMouseUp: A MouseEvent handler function. Fires when the pointer is released.
onMouseUpCapture: A version of onMouseUp that fires in the capture phase.
onPointerCancel: A PointerEvent handler function. Fires when the browser cancels a pointer interaction.
onPointerCancelCapture: A version of onPointerCancel that fires in the capture phase.
onPointerDown: A PointerEvent handler function. Fires when a pointer becomes active.
onPointerDownCapture: A version of onPointerDown that fires in the capture phase.
onPointerEnter: A PointerEvent handler function. Fires when a pointer moves inside an element. Does not have a capture phase. Instead, onPointerLeave and onPointerEnter propagate from the element being left to the one being entered.
onPointerLeave: A PointerEvent handler function. Fires when a pointer moves outside an element. Does not have a capture phase. Instead, onPointerLeave and onPointerEnter propagate from the element being left to the one being entered.
onPointerMove: A PointerEvent handler function. Fires when a pointer changes coordinates.
onPointerMoveCapture: A version of onPointerMove that fires in the capture phase.
onPointerOut: A PointerEvent handler function. Fires when a pointer moves outside an element, if the pointer interaction is cancelled, and a few other reasons.
onPointerOutCapture: A version of onPointerOut that fires in the capture phase.
onPointerUp: A PointerEvent handler function. Fires when a pointer is no longer active.
onPointerUpCapture: A version of onPointerUp that fires in the capture phase.
onPaste: A ClipboardEvent handler function. Fires when the user tries to paste something from the clipboard.
onPasteCapture: A version of onPaste that fires in the capture phase.
onScroll: An Event handler function. Fires when an element has been scrolled. This event does not bubble.
onScrollCapture: A version of onScroll that fires in the capture phase.
onSelect: An Event handler function. Fires after the selection inside an editable element like an input changes. React extends the onSelect event to work for contentEditable={true} elements as well. In addition, React extends it to fire for empty selection and on edits (which may affect the selection).
onSelectCapture: A version of onSelect that fires in the capture phase.
onTouchCancel: A TouchEvent handler function. Fires when the browser cancels a touch interaction.
onTouchCancelCapture: A version of onTouchCancel that fires in the capture phase.
onTouchEnd: A TouchEvent handler function. Fires when one or more touch points are removed.
onTouchEndCapture: A version of onTouchEnd that fires in the capture phase.
onTouchMove: A TouchEvent handler function. Fires one or more touch points are moved.
onTouchMoveCapture: A version of onTouchMove that fires in the capture phase.
onTouchStart: A TouchEvent handler function. Fires when one or more touch points are placed.
onTouchStartCapture: A version of onTouchStart that fires in the capture phase.
onTransitionEnd: A TransitionEvent handler function. Fires when a CSS transition completes.
onTransitionEndCapture: A version of onTransitionEnd that fires in the capture phase.
onWheel: A WheelEvent handler function. Fires when the user rotates a wheel button.
onWheelCapture: A version of onWheel that fires in the capture phase.
role: A string. Specifies the element role explicitly for assistive technologies. nt.
slot: A string. Specifies the slot name when using shadow DOM. In React, an equivalent pattern is typically achieved by passing JSX as props, for example <Layout left={<Sidebar />} right={<Content />} />.
spellCheck: A boolean or null. If explicitly set to true or false, enables or disables spellchecking.
tabIndex: A number. Overrides the default Tab button behavior. Avoid using values other than -1 and 0.
title: A string. Specifies the tooltip text for the element.
translate: Either 'yes' or 'no'. Passing 'no' excludes the element content from being translated.
""" # noqa: E501
FORM_PROPS = r"""
onReset: An Event handler function. Fires when a form gets reset.
onResetCapture: A version of onReset that fires in the capture phase.
onSubmit: An Event handler function. Fires when a form gets submitted.
onSubmitCapture: A version of onSubmit that fires in the capture phase.
"""
DIALOG_PROPS = r"""
onCancel: An Event handler function. Fires when the user tries to dismiss the dialog.
onCancelCapture: A version of onCancel that fires in the capture phase. capture-phase-events)
onClose: An Event handler function. Fires when a dialog has been closed.
onCloseCapture: A version of onClose that fires in the capture phase.
""" # noqa: E501
DETAILS_PROPS = r"""
onToggle: An Event handler function. Fires when the user toggles the details.
onToggleCapture: A version of onToggle that fires in the capture phase. capture-phase-events)
""" # noqa: E501
IMG_IFRAME_OBJECT_EMBED_LINK_IMAGE_PROPS = r"""
onLoad: An Event handler function. Fires when the resource has loaded.
onLoadCapture: A version of onLoad that fires in the capture phase.
onError: An Event handler function. Fires when the resource could not be loaded.
onErrorCapture: A version of onError that fires in the capture phase.
""" # noqa: E501
AUDIO_VIDEO_PROPS = r"""
onAbort: An Event handler function. Fires when the resource has not fully loaded, but not due to an error.
onAbortCapture: A version of onAbort that fires in the capture phase.
onCanPlay: An Event handler function. Fires when there’s enough data to start playing, but not enough to play to the end without buffering.
onCanPlayCapture: A version of onCanPlay that fires in the capture phase.
onCanPlayThrough: An Event handler function. Fires when there’s enough data that it’s likely possible to start playing without buffering until the end.
onCanPlayThroughCapture: A version of onCanPlayThrough that fires in the capture phase.
onDurationChange: An Event handler function. Fires when the media duration has updated.
onDurationChangeCapture: A version of onDurationChange that fires in the capture phase.
onEmptied: An Event handler function. Fires when the media has become empty.
onEmptiedCapture: A version of onEmptied that fires in the capture phase.
onEncrypted: An Event handler function. Fires when the browser encounters encrypted media.
onEncryptedCapture: A version of onEncrypted that fires in the capture phase.
onEnded: An Event handler function. Fires when the playback stops because there’s nothing left to play.
onEndedCapture: A version of onEnded that fires in the capture phase.
onError: An Event handler function. Fires when the resource could not be loaded.
onErrorCapture: A version of onError that fires in the capture phase.
onLoadedData: An Event handler function. Fires when the current playback frame has loaded.
onLoadedDataCapture: A version of onLoadedData that fires in the capture phase.
onLoadedMetadata: An Event handler function. Fires when metadata has loaded.
onLoadedMetadataCapture: A version of onLoadedMetadata that fires in the capture phase.
onLoadStart: An Event handler function. Fires when the browser started loading the resource.
onLoadStartCapture: A version of onLoadStart that fires in the capture phase.
onPause: An Event handler function. Fires when the media was paused.
onPauseCapture: A version of onPause that fires in the capture phase.
onPlay: An Event handler function. Fires when the media is no longer paused.
onPlayCapture: A version of onPlay that fires in the capture phase.
onPlaying: An Event handler function. Fires when the media starts or restarts playing.
onPlayingCapture: A version of onPlaying that fires in the capture phase.
onProgress: An Event handler function. Fires periodically while the resource is loading.
onProgressCapture: A version of onProgress that fires in the capture phase.
onRateChange: An Event handler function. Fires when playback rate changes.
onRateChangeCapture: A version of onRateChange that fires in the capture phase.
onResize: An Event handler function. Fires when video changes size.
onResizeCapture: A version of onResize that fires in the capture phase.
onSeeked: An Event handler function. Fires when a seek operation completes.
onSeekedCapture: A version of onSeeked that fires in the capture phase.
onSeeking: An Event handler function. Fires when a seek operation starts.
onSeekingCapture: A version of onSeeking that fires in the capture phase.
onStalled: An Event handler function. Fires when the browser is waiting for data but it keeps not loading.
onStalledCapture: A version of onStalled that fires in the capture phase.
onSuspend: An Event handler function. Fires when loading the resource was suspended.
onSuspendCapture: A version of onSuspend that fires in the capture phase.
onTimeUpdate: An Event handler function. Fires when the current playback time updates.
onTimeUpdateCapture: A version of onTimeUpdate that fires in the capture phase.
onVolumeChange: An Event handler function. Fires when the volume has changed.
onVolumeChangeCapture: A version of onVolumeChange that fires in the capture phase.
onWaiting: An Event handler function. Fires when the playback stopped due to temporary lack of data.
onWaitingCapture: A version of onWaiting that fires in the capture phase.
""" # noqa: E501
# >>> CSS Styles <<<
# https://developer.mozilla.org/en-US/docs/Web/CSS/Reference#index
CSS_REGEX = re.compile(r"^[a-z\-]+$")
def css_to_typedict(string: str) -> dict[str, Any]:
"""Parse CSS styles from a string, which is a list of CSS styles."""
lines = string.strip().split("\n")
return {x: str | int for x in lines if len(x) > 1 and CSS_REGEX.match(x)}
CSS_STYLES = r"""
-
--*
-webkit-line-clamp
A
abs()
accent-color
acos()
:active
additive-symbols (@counter-style)
::after (:after)
align-content
align-items
align-self
align-tracks
all
<an-plus-b>
<angle>
<angle-percentage>
animation
animation-composition
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timeline
animation-timing-function
@annotation
annotation()
:any-link
appearance
ascent-override (@font-face)
asin()
aspect-ratio
atan()
atan2()
attr()
B
::backdrop
backdrop-filter
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-position-x
background-position-y
background-repeat
background-size
<basic-shape>
::before (:before)
:blank
bleed (@page)
<blend-mode>
block-overflow
block-size
blur()
border
border-block
border-block-color
border-block-end
border-block-end-color
border-block-end-style
border-block-end-width
border-block-start
border-block-start-color
border-block-start-style
border-block-start-width
border-block-style
border-block-width
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-end-end-radius
border-end-start-radius
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-inline
border-inline-color
border-inline-end
border-inline-end-color
border-inline-end-style
border-inline-end-width
border-inline-start
border-inline-start-color
border-inline-start-style
border-inline-start-width
border-inline-style
border-inline-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-start-end-radius
border-start-start-radius
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
@bottom-center
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside
brightness()
C
calc()
caption-side
caret
caret-color
caret-shape
@character-variant
character-variant()
@charset
:checked
circle()
clamp()
clear
clip
clip-path
<color>
color
color-scheme
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
conic-gradient()
contain
contain-intrinsic-block-size
contain-intrinsic-height
contain-intrinsic-inline-size
contain-intrinsic-size
contain-intrinsic-width
content
content-visibility
contrast()
cos()
<counter>
counter-increment
counter-reset
counter-set
@counter-style
counters()
cross-fade()
cubic-bezier()
::cue
::cue-region
:current
cursor
<custom-ident>
length#cap
length#ch
length#cm
D
angle#deg
:default
:defined
descent-override (@font-face)
<dimension>
:dir
direction
:disabled
display
<display-box>
<display-inside>
<display-internal>
<display-legacy>
<display-listitem>
<display-outside>
drop-shadow()
resolution#dpcm
resolution#dpi
resolution#dppx
E
element()
ellipse()
:empty
empty-cells
:enabled
env()
exp()
length#em
length#ex
F
fallback (@counter-style)
filter
<filter-function>
:first
:first-child
::first-letter (:first-letter)
::first-line (:first-line)
:first-of-type
fit-content()
<flex>
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
flex_value#fr
float
:focus
:focus-visible
:focus-within
font
font-display (@font-face)
@font-face
font-family
font-family (@font-face)
font-feature-settings
font-feature-settings (@font-face)
@font-feature-values
font-kerning
font-language-override
font-optical-sizing
font-size
font-size-adjust
font-stretch
font-stretch (@font-face)
font-style
font-style (@font-face)
font-synthesis
font-variant
font-variant (@font-face)
font-variant-alternates
font-variant-caps
font-variant-east-asian
font-variant-ligatures
font-variant-numeric
font-variant-position
font-variation-settings
font-variation-settings (@font-face)
font-weight
font-weight (@font-face)
forced-color-adjust
format()
<frequency>
<frequency-percentage>
:fullscreen
:future
G
angle#grad
gap
<gradient>
::grammar-error
grayscale()
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-start
grid-row
grid-row-end
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows
H
frequency#Hz
hanging-punctuation
:has
height
height (@viewport)
@historical-forms
:host()
:host-context()
:hover
hsl()
hsla()
hue-rotate()
hwb()
hyphenate-character
hyphenate-limit-chars
hyphens
hypot()
I
<ident>
<image>
image()
image-orientation
image-rendering
image-resolution
image-set()
@import
:in-range
:indeterminate
inherit
inherits (@property)
initial
initial-letter
initial-letter-align
initial-value (@property)
inline-size
input-security
inset
inset()
inset-block
inset-block-end
inset-block-start
inset-inline
inset-inline-end
inset-inline-start
<integer>
:invalid
invert()
:is
isolation
length#ic
length#in
J
justify-content
justify-items
justify-self
justify-tracks
K
frequency#kHz
@keyframes
L
lab()
:lang
:last-child
:last-of-type
@layer
layer()
layer() (@import)
lch()
leader()
:left
left
@left-bottom
<length>
<length-percentage>
letter-spacing
line-break
line-clamp
line-gap-override (@font-face)
line-height
line-height-step
linear-gradient()
:link
list-style
list-style-image
list-style-position
list-style-type
local()
:local-link
log()
M
length#mm
margin
margin-block
margin-block-end
margin-block-start
margin-bottom
margin-inline
margin-inline-end
margin-inline-start
margin-left
margin-right
margin-top
margin-trim
::marker
marks (@page)
mask
mask-border
mask-border-mode
mask-border-outset
mask-border-repeat
mask-border-slice
mask-border-source
mask-border-width
mask-clip
mask-composite
mask-image
mask-mode
mask-origin
mask-position
mask-repeat
mask-size
mask-type
masonry-auto-flow
math-depth
math-shift
math-style
matrix()
matrix3d()
max()
max-block-size
max-height
max-height (@viewport)
max-inline-size
max-lines
max-width
max-width (@viewport)
max-zoom (@viewport)
@media
min()
min-block-size
min-height
min-height (@viewport)
min-inline-size
min-width
min-width (@viewport)
min-zoom (@viewport)
minmax()
mix-blend-mode
mod()
time#ms
N
@namespace
negative (@counter-style)
:not
:nth-child
:nth-col
:nth-last-child
:nth-last-col
:nth-last-of-type
:nth-of-type
<number>
O
object-fit
object-position
offset
offset-anchor
offset-distance
offset-path
offset-position
offset-rotate
:only-child
:only-of-type
opacity
opacity()
:optional
order
orientation (@viewport)
@ornaments
ornaments()
orphans
:out-of-range
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-anchor
overflow-block
overflow-clip-margin
overflow-inline
overflow-wrap
overflow-x
overflow-y
overscroll-behavior
overscroll-behavior-block
overscroll-behavior-inline
overscroll-behavior-x
overscroll-behavior-y
P
Pseudo-classes
Pseudo-elements
length#pc
length#pt
length#px
pad (@counter-style)
padding
padding-block
padding-block-end
padding-block-start
padding-bottom
padding-inline
padding-inline-end
padding-inline-start
padding-left
padding-right
padding-top
@page
page-break-after
page-break-before
page-break-inside
paint()
paint-order
::part
:past
path()
:paused
<percentage>
perspective
perspective()
perspective-origin
:picture-in-picture
place-content
place-items
place-self
::placeholder
:placeholder-shown
:playing
pointer-events
polygon()
<position>
position
pow()
prefix (@counter-style)
print-color-adjust
@property
Q
length#Q
quotes
R
angle#rad
length#rem
radial-gradient()
range (@counter-style)
<ratio>
:read-only
:read-write
rect()
rem()
repeat()
repeating-conic-gradient()
repeating-linear-gradient()
repeating-radial-gradient()
:required
resize
<resolution>
reversed()
revert
rgb()
rgba()
:right
right
@right-bottom
:root
rotate
rotate()
rotate3d()
rotateX()
rotateY()
rotateZ()
round()
row-gap
ruby-align
ruby-merge
ruby-position
S
saturate()
scale
scale()
scale3d()
scaleX()
scaleY()
scaleZ()
:scope
scroll()
scroll-behavior
scroll-margin
scroll-margin-block
scroll-margin-block-end
scroll-margin-block-start
scroll-margin-bottom
scroll-margin-inline
scroll-margin-inline-end
scroll-margin-inline-start
scroll-margin-left
scroll-margin-right
scroll-margin-top
scroll-padding
scroll-padding-block
scroll-padding-block-end
scroll-padding-block-start
scroll-padding-bottom
scroll-padding-inline
scroll-padding-inline-end
scroll-padding-inline-start
scroll-padding-left
scroll-padding-right
scroll-padding-top
scroll-snap-align
scroll-snap-stop
scroll-snap-type
@scroll-timeline
scroll-timeline
scroll-timeline-axis
scroll-timeline-name
scrollbar-color
scrollbar-gutter
scrollbar-width
::selection
selector()
sepia()
<shape>
shape-image-threshold
shape-margin
shape-outside
sign()
sin()
size (@page)
size-adjust (@font-face)
skew()
skewX()
skewY()
::slotted
speak-as (@counter-style)
::spelling-error
sqrt()
src (@font-face)
steps()
<string>
@styleset
styleset()
@stylistic
stylistic()
suffix (@counter-style)
@supports
supports() (@import)
@swash
swash()
symbols (@counter-style)
symbols()
syntax (@property)
system (@counter-style)
time#s
T
angle#turn
tab-size
table-layout
tan()
:target
target-counter()
target-counters()
::target-text
target-text()
:target-within
text-align
text-align-last
text-combine-upright
text-decoration
text-decoration-color
text-decoration-line
text-decoration-skip
text-decoration-skip-ink
text-decoration-style
text-decoration-thickness
text-emphasis
text-emphasis-color
text-emphasis-position
text-emphasis-style
text-indent
text-justify
text-orientation
text-overflow
text-rendering
text-shadow
text-size-adjust
text-transform
text-underline-offset
text-underline-position
<time>
<time-percentage>
<timing-function>
top
@top-center
touch-action
transform
transform-box
<transform-function>
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
translate
translate()
translate3d()
translateX()
translateY()
translateZ()
type()
U
unicode-bidi
unicode-range (@font-face)
unset
<url>
url()
:user-invalid
user-select
:user-valid
user-zoom (@viewport)
V
length#vh
length#vmax
length#vmin
length#vw
:valid
var()
vertical-align
@viewport
viewport-fit (@viewport)
visibility
:visited
W
:where
white-space
widows
width
width (@viewport)
will-change
word-break
word-spacing
word-wrap
writing-mode
X
resolution#x
Z
z-index
zoom (@viewport)
Others
--*
""" # noqa: E501
# >>> Basic HTML Attributes <<<
# https://html.spec.whatwg.org/multipage/indices.html#attributes-3
@dataclass
class Html5Attr:
attribute: str
elements: str
description: str
value: str
def html5_doc_infer_type(row: Html5Attr):
"""Infer the type of the attribute from the description"""
if row.value.startswith("Boolean attribute"):
return bool
if row.value.startswith(
(
"Text",
"Autofill field name",
"Unordered set of",
"Regular expression",
'"',
)
):
return str
if row.value.startswith("ID"):
return str | int
if row.value.startswith("Valid floating-point number"):
return int | float
if row.value.startswith(("Valid non-negative integer", "Valid integer")):
return int
if row.value.startswith("Valid list of floating-point numbers"):
return list[int | float]
if row.value.startswith("Varies"):
return str | int | float
if "Comma-separated list" in row.value:
return str
if "list" in row.value:
return list[str]
if "string" in row.value or "URL" in row.value or "name or keyword" in row.value:
return str
if row.attribute in {
"color",
"as",
"referrerpolicy",
"srclang",
"hreflang",
"type",
"usemap",
"srcdoc",
"allow",
"accept-charset",
}:
return str
raise ValueError(
f"Unknown type for attribute: [{row.attribute}] element: [{row.elements}]"
)
def html5_to_sorted_typedict(html_attrs: str) -> dict[str, dict[str, Any]]:
d: dict[str, dict[str, Any]] = {}
for row_str in html_attrs.strip().splitlines():
row_split = row_str.split("\t")
# Parse out garbage
if len(row_split) == 4:
row = Html5Attr(*row_split)
else:
continue
# Skip global attributes, they are already covered by React
if row.elements != "HTML elements":
elements = row.elements.split("; ")
else:
continue
# Set a dict for each element
# in the format `{element: {attribute: type}}`
for element in elements:
element_clean = element.split(" ")[0]
# Parse out invalid rows
if not element_clean.isalpha() or not element_clean.islower():
continue
# Add the element to the dict
if element_clean not in d:
d[element_clean] = {}
d[element_clean][row.attribute] = html5_doc_infer_type(row)
return d
HTML5_ATTRS = r"""
Attribute Element(s) Description Value
abbr th Alternative label to use for the header cell when referencing the cell in other contexts Text*
accept input Hint for expected file type in file upload controls Set of comma-separated tokens* consisting of valid MIME type strings with no parameters or audio/*, video/*, or image/*
accept-charset form Character encodings to use for form submission ASCII case-insensitive match for "UTF-8"
accesskey HTML elements Keyboard shortcut to activate or focus element Ordered set of unique space-separated tokens, none of which are identical to another, each consisting of one code point in length
action form URL to use for form submission Valid non-empty URL potentially surrounded by spaces
allow iframe Permissions policy to be applied to the iframe's contents Serialized permissions policy
allowfullscreen iframe Whether to allow the iframe's contents to use requestFullscreen() Boolean attribute
alt area; img; input Replacement text for use when images are not available Text*
as link Potential destination for a preload request (for rel="preload" and rel="modulepreload") Potential destination, for rel="preload"; script-like destination, for rel="modulepreload"
async script Execute script when available, without blocking while fetching Boolean attribute
autocapitalize HTML elements Recommended autocapitalization behavior (for supported input methods) "on"; "off"; "none"; "sentences"; "words"; "characters"
autocomplete form Default setting for autofill feature for controls in the form "on"; "off"
autocomplete input; select; textarea Hint for form autofill feature Autofill field name and related tokens*
autofocus HTML elements Automatically focus the element when the page is loaded Boolean attribute
autoplay audio; video Hint that the media resource can be started automatically when the page is loaded Boolean attribute
blocking link; script; style Whether the element is potentially render-blocking Unordered set of unique space-separated tokens*
charset meta Character encoding declaration "utf-8"
checked input Whether the control is checked Boolean attribute
cite blockquote; del; ins; q Link to the source of the quotation or more information about the edit Valid URL potentially surrounded by spaces
class HTML elements Classes to which the element belongs Set of space-separated tokens
color link Color to use when customizing a site's icon (for rel="mask-icon") CSS <color>
cols textarea Maximum number of characters per line Valid non-negative integer greater than zero
colspan td; th Number of columns that the cell is to span Valid non-negative integer greater than zero
content meta Value of the element Text*
contenteditable HTML elements Whether the element is editable "true"; "false"
controls audio; video Show user agent controls Boolean attribute
coords area Coordinates for the shape to be created in an image map Valid list of floating-point numbers*
crossorigin audio; img; link; script; video How the element handles crossorigin requests "anonymous"; "use-credentials"
data object Address of the resource Valid non-empty URL potentially surrounded by spaces
datetime del; ins Date and (optionally) time of the change Valid date string with optional time
datetime time Machine-readable value Valid month string, valid date string, valid yearless date string, valid time string, valid local date and time string, valid time-zone offset string, valid global date and time string, valid week string, valid non-negative integer, or valid duration string
decoding img Decoding hint to use when processing this image for presentation "sync"; "async"; "auto"
default track Enable the track if no other text track is more suitable Boolean attribute
defer script Defer script execution Boolean attribute
dir HTML elements The text directionality of the element "ltr"; "rtl"; "auto"
dir bdo The text directionality of the element "ltr"; "rtl"
dirname input; textarea Name of form control to use for sending the element's directionality in form submission Text*
disabled button; input; optgroup; option; select; textarea; form-associated custom elements Whether the form control is disabled Boolean attribute
disabled fieldset Whether the descendant form controls, except any inside legend, are disabled Boolean attribute
disabled link Whether the link is disabled Boolean attribute
download a; area Whether to download the resource instead of navigating to it, and its filename if so Text
draggable HTML elements Whether the element is draggable "true"; "false"
enctype form Entry list encoding type to use for form submission "application/x-www-form-urlencoded"; "multipart/form-data"; "text/plain"
enterkeyhint HTML elements Hint for selecting an enter key action "enter"; "done"; "go"; "next"; "previous"; "search"; "send"
for label Associate the label with form control ID*
for output Specifies controls from which the output was calculated Unordered set of unique space-separated tokens consisting of IDs*
form button; fieldset; input; object; output; select; textarea; form-associated custom elements Associates the element with a form element ID*
formaction button; input URL to use for form submission Valid non-empty URL potentially surrounded by spaces
formenctype button; input Entry list encoding type to use for form submission "application/x-www-form-urlencoded"; "multipart/form-data"; "text/plain"
formmethod button; input Variant to use for form submission "GET"; "POST"; "dialog"
formnovalidate button; input Bypass form control validation for form submission Boolean attribute
formtarget button; input Navigable for form submission Valid navigable target name or keyword
headers td; th The header cells for this cell Unordered set of unique space-separated tokens consisting of IDs*
height canvas; embed; iframe; img; input; object; source (in picture); video Vertical dimension Valid non-negative integer
hidden HTML elements Whether the element is relevant "until-found"; "hidden"; the empty string
high meter Low limit of high range Valid floating-point number*
href a; area Address of the hyperlink Valid URL potentially surrounded by spaces
href link Address of the hyperlink Valid non-empty URL potentially surrounded by spaces
href base Document base URL Valid URL potentially surrounded by spaces
hreflang a; link Language of the linked resource Valid BCP 47 language tag
http-equiv meta Pragma directive "content-type"; "default-style"; "refresh"; "x-ua-compatible"; "content-security-policy"
id HTML elements The element's ID Text*
imagesizes link Image sizes for different page layouts (for rel="preload") Valid source size list
imagesrcset link Images to use in different situations, e.g., high-resolution displays, small monitors, etc. (for rel="preload") Comma-separated list of image candidate strings
inert HTML elements Whether the element is inert. Boolean attribute
inputmode HTML elements Hint for selecting an input modality "none"; "text"; "tel"; "email"; "url"; "numeric"; "decimal"; "search"
integrity link; script Integrity metadata used in Subresource Integrity checks [SRI] Text
is HTML elements Creates a customized built-in element Valid custom element name of a defined customized built-in element
ismap img Whether the image is a server-side image map Boolean attribute
itemid HTML elements Global identifier for a microdata item Valid URL potentially surrounded by spaces
itemprop HTML elements Property names of a microdata item Unordered set of unique space-separated tokens consisting of valid absolute URLs, defined property names, or text*
itemref HTML elements Referenced elements Unordered set of unique space-separated tokens consisting of IDs*
itemscope HTML elements Introduces a microdata item Boolean attribute
itemtype HTML elements Item types of a microdata item Unordered set of unique space-separated tokens consisting of valid absolute URLs*
kind track The type of text track "subtitles"; "captions"; "descriptions"; "chapters"; "metadata"
label optgroup; option; track User-visible label Text
lang HTML elements Language of the element Valid BCP 47 language tag or the empty string
list input List of autocomplete options ID*
loading iframe; img Used when determining loading deferral "lazy"; "eager"
loop audio; video Whether to loop the media resource Boolean attribute
low meter High limit of low range Valid floating-point number*
max input Maximum value Varies*
max meter; progress Upper bound of range Valid floating-point number*
maxlength input; textarea Maximum length of value Valid non-negative integer
media link; meta; source (in picture); style Applicable media Valid media query list
method form Variant to use for form submission "GET"; "POST"; "dialog"
min input Minimum value Varies*
min meter Lower bound of range Valid floating-point number*
minlength input; textarea Minimum length of value Valid non-negative integer
multiple input; select Whether to allow multiple values Boolean attribute
muted audio; video Whether to mute the media resource by default Boolean attribute
name button; fieldset; input; output; select; textarea; form-associated custom elements Name of the element to use for form submission and in the form.elements API Text*
name form Name of form to use in the document.forms API Text*
name iframe; object Name of content navigable Valid navigable target name or keyword
name map Name of image map to reference from the usemap attribute Text*
name meta Metadata name Text*
name slot Name of shadow tree slot Text
nomodule script Prevents execution in user agents that support module scripts Boolean attribute
nonce HTML elements Cryptographic nonce used in Content Security Policy checks [CSP] Text
novalidate form Bypass form control validation for form submission Boolean attribute
open details Whether the details are visible Boolean attribute
open dialog Whether the dialog box is showing Boolean attribute
optimum meter Optimum value in gauge Valid floating-point number*
pattern input Pattern to be matched by the form control's value Regular expression matching the JavaScript Pattern production
ping a; area URLs to ping Set of space-separated tokens consisting of valid non-empty URLs
placeholder input; textarea User-visible label to be placed within the form control Text*
playsinline video Encourage the user agent to display video content within the element's playback area Boolean attribute
popover HTML elements Makes the element a popover element "auto"; "manual";
popoverhidetarget input; button Hides the specified popover element when clicked ID of the element to hide
popovershowtarget input; button Shows the specified popover element when clicked ID of the element to show
popovertoggletarget input; button Toggles the specified popover element when clicked ID of the element to toggle
poster video Poster frame to show prior to video playback Valid non-empty URL potentially surrounded by spaces
preload audio; video Hints how much buffering the media resource will likely need "none"; "metadata"; "auto"
readonly input; textarea Whether to allow the value to be edited by the user Boolean attribute
readonly form-associated custom elements Affects willValidate, plus any behavior added by the custom element author Boolean attribute
referrerpolicy a; area; iframe; img; link; script Referrer policy for fetches initiated by the element Referrer policy
rel a; area Relationship between the location in the document containing the hyperlink and the destination resource Unordered set of unique space-separated tokens*
rel link Relationship between the document containing the hyperlink and the destination resource Unordered set of unique space-separated tokens*
required input; select; textarea Whether the control is required for form submission Boolean attribute
reversed ol Number the list backwards Boolean attribute
rows textarea Number of lines to show Valid non-negative integer greater than zero
rowspan td; th Number of rows that the cell is to span Valid non-negative integer
sandbox iframe Security rules for nested content Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of
"allow-downloads"
"allow-forms"
"allow-modals"
"allow-orientation-lock"
"allow-pointer-lock"
"allow-popups"
"allow-popups-to-escape-sandbox"
"allow-presentation"
"allow-same-origin"
"allow-scripts"
"allow-top-navigation"
"allow-top-navigation-by-user-activation"
"allow-top-navigation-to-custom-protocols"
scope th Specifies which cells the header cell applies to "row"; "col"; "rowgroup"; "colgroup"
selected option Whether the option is selected by default Boolean attribute
shape area The kind of shape to be created in an image map "circle"; "default"; "poly"; "rect"
size input; select Size of the control Valid non-negative integer greater than zero
sizes link Sizes of the icons (for rel="icon") Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of sizes*
sizes img; source Image sizes for different page layouts Valid source size list
slot HTML elements The element's desired slot Text
span col; colgroup Number of columns spanned by the element Valid non-negative integer greater than zero
spellcheck HTML elements Whether the element is to have its spelling and grammar checked "true"; "false"
src audio; embed; iframe; img; input; script; source (in video or audio); track; video Address of the resource Valid non-empty URL potentially surrounded by spaces
srcdoc iframe A document to render in the iframe The source of an iframe srcdoc document*
srclang track Language of the text track Valid BCP 47 language tag
srcset img; source Images to use in different situations, e.g., high-resolution displays, small monitors, etc. Comma-separated list of image candidate strings
start ol Starting value of the list Valid integer
step input Granularity to be matched by the form control's value Valid floating-point number greater than zero, or "any"
style HTML elements Presentational and formatting instructions CSS declarations*
tabindex HTML elements Whether the element is focusable and sequentially focusable, and the relative order of the element for the purposes of sequential focus navigation Valid integer
target a; area Navigable for hyperlink navigation Valid navigable target name or keyword
target base Default navigable for hyperlink navigation and form submission Valid navigable target name or keyword
target form Navigable for form submission Valid navigable target name or keyword
title HTML elements Advisory information for the element Text
title abbr; dfn Full term or expansion of abbreviation Text
title input Description of pattern (when used with pattern attribute) Text
title link Title of the link Text
title link; style CSS style sheet set name Text
translate HTML elements Whether the element is to be translated when the page is localized "yes"; "no"
type a; link Hint for the type of the referenced resource Valid MIME type string
type button Type of button "submit"; "reset"; "button"
type embed; object; source Type of embedded resource Valid MIME type string
type input Type of form control input type keyword
type ol Kind of list marker "1"; "a"; "A"; "i"; "I"
type script Type of script "module"; a valid MIME type string that is not a JavaScript MIME type essence match
usemap img Name of image map to use Valid hash-name reference*
value button; option Value to be used for form submission Text
value data Machine-readable value Text*
value input Value of the form control Varies*
value li Ordinal value of the list item Valid integer
value meter; progress Current value of the element Valid floating-point number
width canvas; embed; iframe; img; input; object; source (in picture); video Horizontal dimension Valid non-negative integer
wrap textarea How the value of the form control is to be wrapped for form submission "soft"; "hard"
""" # noqa: E501
react_typedict = react_doc_to_typedict(
SPECIAL_PROPS
+ STANDARD_PROPS
+ FORM_PROPS
+ DETAILS_PROPS
+ IMG_IFRAME_OBJECT_EMBED_LINK_IMAGE_PROPS
+ AUDIO_VIDEO_PROPS
)
style_prop_typedict = css_to_typedict(CSS_STYLES)
html5_attrs_sorted_typedict = html5_to_sorted_typedict(HTML5_ATTRS)
print(">>> react_typedict")
pprint(react_typedict)
print("\n>>> style_prop_typedict")
pprint(style_prop_typedict)
print("\n>>> html5_attrs_sorted_typedict")
pprint(html5_attrs_sorted_typedict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment