UNPKG

reblend-ui

Version:

Utilities for creating robust overlay components

121 lines (120 loc) 2.85 kB
"use strict"; exports.__esModule = true; exports.default = void 0; exports.isTrivialHref = isTrivialHref; exports.useButtonProps = useButtonProps; var _reblendjs = require("reblendjs"); function isTrivialHref(href) { return !href || href.trim() === '#'; } function useButtonProps({ tagName, disabled, href, target, rel, role, onClick, tabIndex = 0, type }) { if (!tagName) { if (href != null || target != null || rel != null) { tagName = 'a'; } else { tagName = 'button'; } } const meta = { tagName }; this.state.meta = meta; if (tagName === 'button') { return [{ type: type || 'button', disabled }, this.state.meta]; } const handleClick = event => { if (disabled || tagName === 'a' && isTrivialHref(href)) { event.preventDefault(); } if (disabled) { event.stopPropagation(); return; } onClick?.(event); }; this.state.handleClick = handleClick; const handleKeyDown = event => { if (event.key === ' ') { event.preventDefault(); this.state.handleClick(event); } }; this.state.handleKeyDown = handleKeyDown; if (tagName === 'a') { // Ensure there's a href so Enter can trigger anchor button. href ||= '#'; if (disabled) { href = undefined; } } return [{ role: role ?? 'button', // explicitly undefined so that it overrides the props disabled in a spread // e.g. <Tag {...props} {...hookProps} /> disabled: undefined, tabIndex: disabled ? undefined : tabIndex, href, target: tagName === 'a' ? target : undefined, 'aria-disabled': !disabled ? undefined : disabled, rel: tagName === 'a' ? rel : undefined, onClick: this.state.handleClick, onKeyDown: this.state.handleKeyDown }, this.state.meta]; } /* @Reblend: Transformed from function to class */ const Button = class /* @Reblend: Transformed from function to class */ extends _reblendjs.default { static ELEMENT_NAME = "Button"; constructor() { super(); } async initState() { const [buttonProps, { tagName: Component }] = useButtonProps.bind(this)({ tagName: this.props.asProp, disabled: this.props.disabled, ...this.props }); this.state.buttonProps = buttonProps; this.state.Component = Component; } async initProps({ as: asProp, disabled, ref, ...props }) { this.props = {}; this.props.asProp = asProp; this.props.disabled = disabled; this.props.ref = ref; this.props = { ...this.props, ...props }; } async html() { return _reblendjs.default.construct.bind(this)(this.state.Component, { ...this.props, ...this.state.buttonProps, ref: this.props.ref }); } }; Button.displayName = 'Button'; var _default = exports.default = Button;