react#DOMAttributes TypeScript Examples

The following examples show how to use react#DOMAttributes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: tooltip-element-props.ts    From react-circular-menu with Apache License 2.0 6 votes vote down vote up
getTooltipElementProps = <T>(
  elementProps: ReactElement["props"],
  openTooltip: () => void,
  closeTooltip: () => void
): DOMAttributes<T> => ({
  onMouseEnter: (event) => {
    openTooltip();
    elementProps.onMouseEnter?.(event);
  },
  onMouseLeave: (event) => {
    closeTooltip();
    elementProps.onMouseLeave?.(event);
  },
  onFocus: (event) => {
    openTooltip();
    elementProps.onFocus?.(event);
  },
  onBlur: (event) => {
    closeTooltip();
    elementProps.onBlur?.(event);
  },
  onTouchStart: (event) => {
    openTooltip();
    elementProps.onTouchStart?.(event);
  },
  onTouchEnd: (event) => {
    closeTooltip();
    elementProps.onTouchEnd?.(event);
  },
})
Example #2
Source File: react-utils.ts    From utopia with MIT License 6 votes vote down vote up
static create<P extends DOMAttributes<T>, T extends HTMLElement>(
    type: string,
    props?: { key: Key } & ClassAttributes<T> & P,
    ...children: ReactNode[]
  ): DOMElement<P, T>
Example #3
Source File: useContextMenu.tsx    From yana with MIT License 6 votes vote down vote up
useContextMenu = (menu?: JSX.Element) => {
  const elementProps: DOMAttributes<any> = {
    onContextMenu: e => {
      if (menu) {
        e.stopPropagation();
        e.preventDefault();
        ContextMenu.show(menu, { left: e.clientX, top: e.clientY });
      }
    },
  };
  return elementProps;
}
Example #4
Source File: CheckboxItem.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
CheckboxItem: React.ForwardRefRenderFunction<
  HTMLLIElement,
  BaseItemProps & Omit<DOMAttributes<HTMLInputElement | HTMLLIElement>, 'onClick'>
> & { isItem?: boolean } = (props, ref?) => {
  const { value, children, onClick, disabled, selected, label, ...rest } = props;
  const prefixCls = `${usePrefixCls(PREFIX)}--item`;
  const prefixIcon = rest.prefix ? renderIcon(`${prefixCls}-prefix-icon`, rest.prefix) : undefined;
  const suffixIcon = rest.suffix ? renderIcon(`${prefixCls}-suffix-icon`, rest.suffix) : undefined;
  /** context */
  const context = useContext(ListContext);
  const { value: contextValue, disabled: contextDisabled, onClick: contextOnClick } = context;
  const mergedDisabled = disabled ?? contextDisabled;

  const mergeSelected = useMemo(() => selected ?? selectStatus(value, contextValue), [selected, contextValue, value]);
  const isMax =
    (contextValue as string[])?.length >= (context?.max ?? Infinity) &&
    !(contextValue as [string | number]).includes(value);
  return (
    <BaseItem
      data-testid="list-item"
      ref={ref}
      disabled={mergedDisabled || isMax}
      onClick={onClick}
      value={value}
      label={label}
      {...rest}
    >
      <Checkbox
        checked={mergeSelected}
        className={`${prefixCls}--checkbox`}
        value={value}
        disabled={mergedDisabled || isMax}
        onClick={(e) => {
          if (!mergedDisabled) {
            contextOnClick?.(value, e);
            onClick?.(value, e);
            e.stopPropagation();
          }
        }}
      />
      <Content label={label ?? children} prefix={prefixIcon} suffix={suffixIcon} />
    </BaseItem>
  );
}
Example #5
Source File: Tabs.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
Tabs = WithRef<
  HTMLDivElement,
  WithCommonProps<TabsProps> & Omit<DOMAttributes<HTMLDivElement>, 'onChange'>
>(
  (
    {
      defaultValue = 0,
      value,
      onChange,
      className: classname,
      children,
      size = 'normal',
      tabListStyle,
      ...restProps
    }: WithCommonProps<TabsProps> & Omit<DOMAttributes<HTMLDivElement>, 'onChange'>,
    ref?
  ) => {
    const [activeValue, setActiveValue] = useControlledState<React.Key>(value, defaultValue);
    const prefixCls = usePrefixCls('tabs');
    const tabClasses = classnames(classname, prefixCls);

    const elementList = React.Children.toArray(children).filter(
      (node) => React.isValidElement(node) && node.type === Tab
    );

    const onClick = (v: React.Key) => {
      setActiveValue(v);
      onChange?.(v);
    };

    const tabs = elementList.map((tab: React.ReactElement<WithCommonProps<TabProps>>, index) => (
      <TabButton
        key={tab.props.value}
        value={tab.props.value || index}
        size={size}
        onClick={onClick}
        prefix={tab.props.prefix}
        active={activeValue === tab.props.value}
        disabled={tab.props.disabled}
      >
        {tab.props.label}
      </TabButton>
    ));

    const tabPanels = elementList.map((tab: React.ReactElement<WithCommonProps<TabProps>>, index) => {
      if (isNil(tab.props.value)) {
        // eslint-disable-next-line react/no-array-index-key
        return React.cloneElement(<Tab />, { ...tab.props, value: index, key: index });
      }
      return React.cloneElement(<Tab />, { ...tab.props, key: tab.props.value });
    });

    return (
      <TabsContext.Provider value={{ activeValue }}>
        <div className={tabClasses} data-testid="tabs" ref={ref} {...restProps}>
          <div data-testid="tablist" className={`${prefixCls}-tablist`} style={tabListStyle}>
            {tabs}
          </div>
          <div data-testid="tabpanels" className={`${prefixCls}-tabpanels`}>
            {tabPanels}
          </div>
        </div>
      </TabsContext.Provider>
    );
  }
)
Example #6
Source File: ApiDetailsCard.tsx    From one-platform with MIT License 4 votes vote down vote up
ApiDetailsCard = ({
  title,
  owners = [],
  schemas = [],
  updatedAt,
}: Props): JSX.Element => {
  const formatUpdatedAt = useCallback(
    (apiUpdatedAt: string) => `modified on: ${dayjs(apiUpdatedAt).format('DD MMM YYYY hh:mm a')}`,
    []
  );

  const stopOnClickPropogation: DOMAttributes<HTMLDivElement>['onClick'] = (event) => {
    event.stopPropagation();
  };

  return (
    <Card className="catalog-card-hover-effect cursor-pointer">
      <CardBody className="pf-u-px-md">
        <Stack hasGutter>
          <StackItem>
            <Split hasGutter className="pf-l-flex pf-m-align-items-flex-end">
              <SplitItem isFilled>
                <Title headingLevel="h4" size={TitleSizes['2xl']}>
                  {title}
                </Title>
              </SplitItem>
              <SplitItem>
                <Text component={TextVariants.small} className="pf-u-color-400">
                  {formatUpdatedAt(updatedAt)}
                </Text>
              </SplitItem>
            </Split>
          </StackItem>
          <StackItem>
            <Split hasGutter>
              <SplitItem>
                <Split isWrappable onClick={stopOnClickPropogation}>
                  <SplitItem className="pf-u-mr-xs">
                    <Text>Owned by:</Text>
                  </SplitItem>
                  <ReadMore
                    limit={MAX_LOADED}
                    showMoreText={`+${(owners || []).length - MAX_LOADED} more`}
                  >
                    {owners.map((owner) => (
                      <SplitItem className="pf-u-ml-xs" key={owner}>
                        <Label isCompact color="cyan">
                          {owner}
                        </Label>
                      </SplitItem>
                    ))}
                  </ReadMore>
                </Split>
              </SplitItem>
              <SplitItem isFilled />
              <SplitItem>
                <Split onClick={stopOnClickPropogation} isWrappable>
                  <SplitItem className="pf-u-mr-sm">
                    <Text>Schema(s): </Text>
                  </SplitItem>
                  <ReadMore
                    limit={MAX_LOADED}
                    showMoreText={`+${(schemas || []).length - MAX_LOADED} more`}
                  >
                    {schemas.map(({ name, type }) => (
                      <SplitItem style={{ marginTop: '0.1rem' }} key={name}>
                        <Label
                          color="blue"
                          className="pf-u-mr-xs"
                          isCompact
                          icon={
                            <img
                              src={`${config.baseURL}/images/${
                                type === 'REST' ? 'swagger-black-logo.svg' : 'graphql-logo.svg'
                              }`}
                              alt="api-type"
                              className="pf-u-mt-xs"
                              style={{ height: '0.8rem', width: '0.8rem' }}
                            />
                          }
                        >
                          {name}
                        </Label>
                      </SplitItem>
                    ))}
                  </ReadMore>
                </Split>
              </SplitItem>
            </Split>
          </StackItem>
        </Stack>
      </CardBody>
    </Card>
  );
}
Example #7
Source File: CascaderItem.tsx    From gio-design with Apache License 2.0 4 votes vote down vote up
CascaderItem: React.ForwardRefRenderFunction<
  HTMLLIElement,
  CascaderItemProps & Omit<DOMAttributes<HTMLLIElement>, 'onClick'>
> & { isItem?: boolean } = (
  { label, value, children, items = [], disabled, onClick: propsOnClick, strategy = 'fixed', ...rest },
  ref?
) => {
    const prefixCls = usePrefixCls('cascader');
    const popoverClassName = `${prefixCls}--content`;
    const [hovered, setHovered] = useState(false);
    const childrens = (items || []).filter(i => !!i && i.value && i.label);
    /** context */
    const context = useContext(ListContext);
    const popoverContext = useContext(TriggerContext);
    const { disabled: contextDisabled, selectParent, onClick: contextOnClick, setOptions } = context;
    /** end */
    const childSelectPrent = generateSelectParent(label, value, selectParent);
    const childNodeOptions = convertChildrenToData(children, {});
    const mergedOptions = useMemo(() => [...childNodeOptions, ...childrens], [childNodeOptions, childrens]);
    const mergedDisabled = disabled ?? contextDisabled;
    useEffect(() => {
      setOptions?.(mergedOptions as OptionProps[]);
    }, [mergedOptions, setOptions]);

    // list
    const prefixClsItem = `${prefixCls}--item`;
    const handleOnClick: BaseItemProps['onClick'] = (_, event) => {
      if (!mergedDisabled) {
        contextOnClick?.(generateString(value, selectParent), event);
        propsOnClick?.(generateString(value, selectParent), event);
      }
    };
    const content = () => {
      /** options render */
      if (!isEmpty(childrens)) {
        return (
          <ListContext.Provider
            value={{
              ...context,
              isEmpty: false,
              disabled: mergedDisabled,
              model: 'cascader',
              selectParent: childSelectPrent,
            }}
          >
            <List className={`${prefixCls}--list`}>
              {childrens.map((child) => (
                <CascaderItem
                  {...child}
                  label={child.label}
                  value={child.value}
                  items={child.items as CascaderItemProps[]}
                />
              ))}
            </List>
          </ListContext.Provider>
        );
      }

      /** JSX */
      return (
        <ListContext.Provider
          value={{
            ...context,
            isEmpty: false,
            disabled: mergedDisabled,
            model: 'cascader',
            selectParent: childSelectPrent,
          }}
        >
          {React.isValidElement(children)
            ? React.cloneElement(children, { className: classNames(children?.props?.className, `${prefixCls}--list`) })
            : children}
        </ListContext.Provider>
      );
    };

    const renderItem = (
      <TriggerContext.Provider value={popoverContext}>
        <Popover
          placement="rightTop"
          onVisibleChange={(v) => setHovered(v)}
          overlayClassName={popoverClassName}
          // document click contains node
          getContainer={(node) => node || document.body}
          content={content()}
          strategy={strategy}
          // distoryOnHide
          delay={200}
          offset={[0, 12]}
        >
          <BaseItem
            data-testid="item-base"
            {...rest}
            className={classNames(prefixClsItem, rest?.className)}
            ref={ref}
            label={label}
            value={value}
            disabled={mergedDisabled}
            hovered={hovered}
            suffix={React.isValidElement(children) || !isEmpty(childrens) ? <RightFilled size="14px" /> : undefined}
            onClick={
              React.isValidElement(children) || !isEmpty(childrens)
                ? (itemValue, event) => propsOnClick?.(itemValue, event)
                : handleOnClick
            }
          />
        </Popover>
      </TriggerContext.Provider>
    );
    return renderItem;
  }
Example #8
Source File: baseItem.tsx    From gio-design with Apache License 2.0 4 votes vote down vote up
InnerBaseItem = WithRef<HTMLLIElement, BaseItemProps & Omit<DOMAttributes<HTMLLIElement>, 'onClick'>>(
  (props, ref?) => {
    const {
      label,
      title,
      value,
      className,
      style,
      prefix: propPrefix,
      suffix: propSuffix,
      children,
      disabled,
      disabledTooltip,
      onClick,
      contentRender = defaultContentRender,
      wrapper = defaultContentRender,
      onMouseEnter,
      onMouseLeave,
      selected: propSelected,
      hovered: propsHovered,
      ...rest
    } = props;
    const prefixCls = `${usePrefixCls(PREFIX)}--item`;
    const {
      model,
      value: contextValue,
      disabled: contextDisabled,
      prefix: contextPrefix,
      suffix: contextSuffix,
      onClick: contextOnClick,
      selectParent,
    } = useContext(ListContext);
    const mergedDisabled = disabled ?? contextDisabled;
    const [hovered, setHovered] = useState(false);
    const selected = useMemo(() => {
      if (propSelected) {
        return propSelected;
      }
      if (model === 'cascader') {
        // 最顶级
        if (!selectParent) {
          return contextValue?.toString()?.split('.')?.[0] === value?.toString();
        }
        // 次级
        return (contextValue as string).startsWith(generateString(value, selectParent)?.toString());
      }
      if (model === 'multiple') {
        return false;
      }
      return selectStatus?.(value, contextValue);
    }, [contextValue, model, selectParent, value, propSelected]);

    useEffect(
      () => () => {
        setHovered(false);
      },
      []
    );

    /** ============ prefix suffix  ================  */
    const prefix = useMemo(
      () => propPrefix ?? contextPrefix?.({ label, value, disabled, disabledTooltip }),
      [contextPrefix, disabled, disabledTooltip, label, propPrefix, value]
    );
    const suffix = useMemo(
      () => propSuffix ?? contextSuffix?.({ label, value, disabled, disabledTooltip }),
      [contextSuffix, disabled, disabledTooltip, label, propSuffix, value]
    );
    const prefixIcon = prefix ? renderIcon(`${prefixCls}-prefix-icon`, prefix) : undefined;
    const suffixIcon = suffix ? renderIcon(`${prefixCls}-suffix-icon`, suffix) : undefined;
    /** ======= end =========== */

    /** =================== events =================== */

    const handleOnClick = (event: React.MouseEvent<HTMLLIElement>) => {
      if (mergedDisabled) {
        event.stopPropagation();
        return;
      }
      /** cascader click 从上级来 */
      if (model !== 'cascader') {
        contextOnClick?.(value, event);
      }
      onClick?.(value, event);
    };

    const titleContent = children ?? label;

    const renderContentEle = () => {
      if (typeof children !== 'string') {
        return children || <Content prefix={prefixIcon} suffix={suffixIcon} label={label} />;
      }
      return <Content prefix={prefixIcon} suffix={suffixIcon} label={label ?? children} />;
    };
    const renderElement = (
      <Tooltip
        disabled={!mergedDisabled || isEmpty(disabledTooltip)}
        strategy="fixed"
        title={disabledTooltip}
        getContainer={() => document.body}
      >
        <li
          data-testid="item-base"
          style={style}
          onMouseEnter={(e) => {
            setHovered(true);
            onMouseEnter?.(e);
          }}
          onMouseLeave={(e) => {
            setHovered(false);
            onMouseLeave?.(e);
          }}
          className={classNames(
            className,
            prefixCls,
            {
              [`${prefixCls}--disabled`]: mergedDisabled,
              [`${prefixCls}--actived`]: selected,
              [`${prefixCls}--hovered`]: !mergedDisabled ? propsHovered || hovered : false,
            },
            className
          )}
          key={value}
          aria-hidden="true"
          ref={ref}
          onClick={handleOnClick}
          title={title || (!disabled && isString(titleContent) && titleContent) || undefined}
          {...rest}
        >
          {contentRender?.(renderContentEle())}
        </li>
      </Tooltip>
    );

    return wrapper(renderElement) as ReactElement;
  }
)
Example #9
Source File: Steps.tsx    From gio-design with Apache License 2.0 4 votes vote down vote up
Steps = WithRef<
  HTMLDivElement,
  WithCommonProps<StepsProps> & Omit<DOMAttributes<HTMLDivElement>, 'onChange'>
>(
  (
    {
      current = 1,
      value,
      onChange,
      className: classname,
      children,
      size = 'normal',
      ...restProps
    }: WithCommonProps<StepsProps> & Omit<DOMAttributes<HTMLDivElement>, 'onChange'>,
    ref?
  ) => {
    const [activeValue, setActiveValue] = useControlledState<React.Key>(value, current - 1);
    const prefixCls = usePrefixCls('tabs');
    const tabClasses = classnames(classname, prefixCls);

    const elementList = React.Children.toArray(children).filter(
      (node) => React.isValidElement(node) && node.type === Tab
    );

    useEffect(() => {
      let currentVal: number;
      if (current > elementList.length) {
        currentVal = elementList?.length + 1;
      } else if (current <= 1) {
        currentVal = 1;
      } else {
        currentVal = current;
      }
      setActiveValue(currentVal - 1);
    }, [current, elementList.length, setActiveValue]);

    const onClick = (v: React.Key) => {
      if (v <= current - 1) {
        setActiveValue(v);
        onChange?.(v);
      }
    };

    const tabs = elementList.map((tab: React.ReactElement<WithCommonProps<TabProps>>, index) => {
      let prefix = null;
      let className = '';
      if (index < current - 1) {
        prefix = <CheckOutlined />;
        className = 'complete';
      } else if (index === current - 1) {
        className = 'process';
      } else if (index >= current) {
        className = 'uncomplete';
      }
      return (
        <span className={`${prefixCls}-tablist-stepbar stepbar-${className}`} key={tab.props.value}>
          <TabButton
            value={tab.props.value || index}
            size={size}
            onClick={onClick}
            prefix={prefix}
            active={activeValue === index}
            disabled={tab.props.disabled}
          >
            {tab.props.label}
          </TabButton>
        </span>
      );
    });

    const tabPanels = elementList.map((tab: React.ReactElement<WithCommonProps<TabProps>>, index) => {
      if (isNil(tab.props.value)) {
        return React.cloneElement(<Tab />, { ...tab.props, value: index, key: tab.props.value });
      }
      return React.cloneElement(<Tab />, { ...tab.props, key: tab.props.value });
    });

    return (
      <StepsContext.Provider value={{ activeValue }}>
        <div className={tabClasses} data-testid="steps" ref={ref} {...restProps}>
          <div data-testid="tablist" className={`${prefixCls}-tablist steps-container`}>
            {tabs}
          </div>
          <div data-testid="tabpanels" className={`${prefixCls}-tabpanels`}>
            {tabPanels}
          </div>
        </div>
      </StepsContext.Provider>
    );
  }
)