preact#VNode TypeScript Examples

The following examples show how to use preact#VNode. 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: formControl.story.tsx    From passwords-fountain with MIT License 6 votes vote down vote up
hasError = (): VNode => (
    <FormControl
        id="has-error-id"
        renderInput={(id: string) => (
            <TextInput
                id={id}
                hasError
                onInput={() => {
                    /* eslint-disable @typescript-eslint/no-empty-function */
                }}
            />
        )}
        renderLabel={() => 'Type your name:'}
        renderError={() => 'This field is required.'}
        hasError
    />
)
Example #2
Source File: grid.ts    From gridjs with MIT License 6 votes vote down vote up
createElement(): VNode {
    return h(Container, {
      config: this.config,
      pipeline: this.config.pipeline,
      header: this.config.header,
      width: this.config.width,
      height: this.config.height,
    });
  }
Example #3
Source File: button.story.tsx    From passwords-fountain with MIT License 6 votes vote down vote up
disabled = (): VNode => (
    <Button
        disabled
        onClick={() => {
            /* eslint-disable @typescript-eslint/no-empty-function */
        }}
    >
        You cannot click me
    </Button>
)
Example #4
Source File: index.tsx    From big-web-quiz with Apache License 2.0 5 votes vote down vote up
function childIsVNode(child: VDOMChild): child is VNode {
  return typeof child === 'object';
}
Example #5
Source File: optionsPanel.story.tsx    From passwords-fountain with MIT License 5 votes vote down vote up
entityFormCollapsed = (): VNode =>
    withStoreMock(() => <OptionsPanel />, getState('entityFormCollapsed'))
Example #6
Source File: render.tsx    From big-web-quiz with Apache License 2.0 5 votes vote down vote up
export function renderPage(vnode: VNode) {
  return '<!DOCTYPE html>' + render(vnode);
}
Example #7
Source File: search.ts    From gridjs with MIT License 5 votes vote down vote up
export default function (
  keyword: string,
  columns: OneDArray<TColumn>,
  ignoreHiddenColumns: boolean,
  tabular: Tabular,
  selector?: (cell: TCell, rowIndex: number, cellIndex: number) => string,
): Tabular {
  // escape special regex chars
  keyword = keyword.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

  return new Tabular(
    tabular.rows.filter((row, rowIndex) =>
      row.cells.some((cell, cellIndex) => {
        if (!cell) {
          return false;
        }

        if (ignoreHiddenColumns) {
          if (
            columns &&
            columns[cellIndex] &&
            typeof columns[cellIndex] === 'object'
          ) {
            const typedColumn = columns[cellIndex] as TColumn;
            if (typedColumn.hidden) {
              return false;
            }
          }
        }

        let data = '';

        if (typeof selector === 'function') {
          data = selector(cell.data, rowIndex, cellIndex);
        } else if (typeof cell.data === 'object') {
          // HTMLContent element
          const element = cell.data as VNode<HTMLContentProps>;
          if (element && element.props && element.props.content) {
            // TODO: we should only search in the content of the element. props.content is the entire HTML element
            data = element.props.content;
          }
        } else {
          // primitive types
          data = String(cell.data);
        }

        return new RegExp(keyword, 'gi').test(data);
      }),
    ),
  );
}
Example #8
Source File: helpers.tsx    From passwords-fountain with MIT License 5 votes vote down vote up
withStoreMock = (render: () => VNode, mockState: any): VNode => {
    return (
        <StoreProvider value={createStore(mockState)}>{render()}</StoreProvider>
    );
}
Example #9
Source File: Field.tsx    From adyen-web with MIT License 4 votes vote down vote up
Field: FunctionalComponent<FieldProps> = props => {
    //
    const {
        children,
        className,
        classNameModifiers,
        dir,
        disabled,
        errorMessage,
        helper,
        inputWrapperModifiers,
        isCollatingErrors,
        isLoading,
        isValid,
        label,
        name,
        onBlur,
        onFieldBlur,
        onFocus,
        onFocusField,
        showValidIcon,
        useLabelElement,
        // Redeclare prop names to avoid internal clashes
        filled: propsFilled,
        focused: propsFocused
    } = props;

    const uniqueId = useRef(getUniqueId(`adyen-checkout-${name}`));

    const [focused, setFocused] = useState(false);
    const [filled, setFilled] = useState(false);

    // The means by which focussed/filled is set for securedFields
    if (propsFocused != null) setFocused(!!propsFocused);
    if (propsFilled != null) setFilled(!!propsFilled);

    // The means by which focussed/filled is set for other fields - this function is passed down to them and triggered
    const onFocusHandler = useCallback(
        (event: h.JSX.TargetedEvent<HTMLInputElement>) => {
            setFocused(true);
            onFocus?.(event);
        },
        [onFocus]
    );

    const onBlurHandler = useCallback(
        (event: h.JSX.TargetedEvent<HTMLInputElement>) => {
            setFocused(false);
            onBlur?.(event);
            // When we also need to fire a specific function when a field blurs
            onFieldBlur?.(event);
        },
        [onBlur, onFieldBlur]
    );

    const renderContent = useCallback(() => {
        return (
            <Fragment>
                {typeof label === 'string' && (
                    <span
                        className={classNames({
                            'adyen-checkout__label__text': true,
                            'adyen-checkout__label__text--error': errorMessage
                        })}
                    >
                        {label}
                    </span>
                )}

                {/*@ts-ignore - function is callable*/}
                {typeof label === 'function' && label()}

                {helper && <span className={'adyen-checkout__helper-text'}>{helper}</span>}
                <div
                    className={classNames([
                        'adyen-checkout__input-wrapper',
                        ...inputWrapperModifiers.map(m => `adyen-checkout__input-wrapper--${m}`)
                    ])}
                    dir={dir}
                >
                    {toChildArray(children).map(
                        (child: ComponentChild): ComponentChild => {
                            const childProps = {
                                isValid,
                                onFocusHandler,
                                onBlurHandler,
                                isInvalid: !!errorMessage,
                                ...(name && { uniqueId: uniqueId.current })
                            };
                            return cloneElement(child as VNode, childProps);
                        }
                    )}

                    {isLoading && (
                        <span className="adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--loading">
                            <Spinner size="small" />
                        </span>
                    )}

                    {isValid && showValidIcon !== false && (
                        <span className="adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--valid">
                            <Icon type="checkmark" />
                        </span>
                    )}

                    {errorMessage && (
                        <span className="adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--invalid">
                            <Icon type="field_error" />
                        </span>
                    )}
                </div>
                {errorMessage && typeof errorMessage === 'string' && errorMessage.length && (
                    <span
                        className={'adyen-checkout__error-text'}
                        id={`${uniqueId.current}${ARIA_ERROR_SUFFIX}`}
                        aria-hidden={isCollatingErrors ? 'true' : null}
                        aria-live={isCollatingErrors ? null : 'polite'}
                    >
                        {errorMessage}
                    </span>
                )}
            </Fragment>
        );
    }, [children, errorMessage, isLoading, isValid, label, onFocusHandler, onBlurHandler]);

    const LabelOrDiv = useCallback(({ onFocusField, focused, filled, disabled, name, uniqueId, useLabelElement, children }) => {
        const defaultWrapperProps = {
            onClick: onFocusField,
            className: classNames({
                'adyen-checkout__label': true,
                'adyen-checkout__label--focused': focused,
                'adyen-checkout__label--filled': filled,
                'adyen-checkout__label--disabled': disabled
            })
        };

        return useLabelElement ? (
            <label {...defaultWrapperProps} htmlFor={name && uniqueId}>
                {children}
            </label>
        ) : (
            <div {...defaultWrapperProps} role={'form'}>
                {children}
            </div>
        );
    }, []);

    /**
     * RENDER
     */
    return (
        <div
            className={classNames(
                'adyen-checkout__field',
                className,
                classNameModifiers.map(m => `adyen-checkout__field--${m}`),
                {
                    'adyen-checkout__field--error': errorMessage,
                    'adyen-checkout__field--valid': isValid
                }
            )}
        >
            <LabelOrDiv
                onFocusField={onFocusField}
                name={name}
                disabled={disabled}
                filled={filled}
                focused={focused}
                useLabelElement={useLabelElement}
                uniqueId={uniqueId.current}
            >
                {renderContent()}
            </LabelOrDiv>
        </div>
    );
}
Example #10
Source File: settings.tsx    From passwords-fountain with MIT License 4 votes vote down vote up
Settings: TypedComponent<Props> = () => {
    const isFirstTimeOnDevice = useSelector(selectIsFirstTimeOnDevice);
    const fetchPasswords = useAction(passwordListActions.fetchPasswords);
    const formRef = useRef<HTMLFormElement>(undefined as any);
    const [adminKeyInputState, adminKeyInputProps] = useInputFormControl(
        formRef,
        formValidation,
        'adminKey'
    );
    const [masterKeyInputState, masterKeyInputProps] = useInputFormControl(
        formRef,
        formValidation,
        'masterKey'
    );

    const headingText = isFirstTimeOnDevice
        ? 'settings.connectToDB'
        : 'settings.headingText';

    const handleConnectClick = async (e: Event): Promise<void> => {
        e.preventDefault();

        if (!formRef.current?.isValid) {
            return;
        }

        await fetchPasswords(
            masterKeyInputState.value,
            adminKeyInputState.value,
            true
        );
        route('/app');
    };
    const handleBackClick = (): void => {
        history.back();
    };

    const renderNoteLabel = (labelDescription: string, shouldRender: boolean) =>
        renderIfTrue(() => (
            <NoteLabelWrapper>
                <Text>settings.noteLabel</Text>{' '}
                <DescriptiveText>
                    <Text>{labelDescription}</Text>
                </DescriptiveText>
            </NoteLabelWrapper>
        ))(shouldRender);

    const renderLabel = (
        label: string,
        labelDescription: string,
        noteLabelDescription: string,
        shouldRenderNote = false
    ) => (): VNode => {
        return (
            <Fragment>
                <LabelWrapper>
                    <Text>{label}</Text> -{' '}
                    <DescriptiveText>
                        <Text>{labelDescription}</Text>
                    </DescriptiveText>
                </LabelWrapper>
                {renderNoteLabel(noteLabelDescription, shouldRenderNote)}
            </Fragment>
        );
    };
    const renderError = (error: string) => (): VNode => <Text>{error}</Text>;

    return (
        <Wrapper>
            <Header>
                <Heading>
                    <Text>{headingText}</Text>
                </Heading>
            </Header>
            <FormWrapper>
                <form ref={formRef}>
                    <FormControlWrapper>
                        <FormControl
                            id={adminKeyInputProps.name}
                            hasError={Boolean(adminKeyInputProps.hasError)}
                            renderLabel={renderLabel(
                                'settings.adminKeyLabel',
                                'settings.adminKeyLabelDescription',
                                'settings.noteLabelDescriptionAdminKey'
                            )}
                            renderInput={(id: string): VNode => (
                                <TextInput
                                    id={id}
                                    type="password"
                                    placeholder="92xIJf_ge234kalfnqql4o25ou4334201"
                                    {...adminKeyInputProps}
                                />
                            )}
                            renderError={renderError(adminKeyInputState.errors)}
                        />
                    </FormControlWrapper>
                    <FormControlWrapper>
                        <FormControl
                            id={masterKeyInputProps.name}
                            hasError={Boolean(masterKeyInputProps.hasError)}
                            renderLabel={renderLabel(
                                'settings.masterKeyLabel',
                                'settings.masterKeyLabelDescription',
                                'settings.noteLabelDescription',
                                true
                            )}
                            renderInput={(id: string): VNode => (
                                <TextInput
                                    id={id}
                                    type="password"
                                    placeholder="myMasterPassword1234"
                                    {...masterKeyInputProps}
                                />
                            )}
                            renderError={renderError(
                                masterKeyInputState.errors
                            )}
                        />
                    </FormControlWrapper>
                    <ControlsWrapper>
                        <Button onClick={handleBackClick}>
                            <Text>settings.back</Text>
                        </Button>
                        <Button
                            type="submit"
                            onClick={handleConnectClick}
                            disabled={!formRef.current?.isValid}
                        >
                            <Text>settings.connect</Text>
                        </Button>
                    </ControlsWrapper>
                </form>
            </FormWrapper>
        </Wrapper>
    );
}