Merge pull request #15 from acid-info/topic-implement-textfield

Implement textField component
This commit is contained in:
jeangovil 2023-02-23 15:33:35 +03:30 committed by GitHub
commit b26d959fca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 582 additions and 18 deletions

View File

@ -0,0 +1,17 @@
export const autocompleteClasses = {
root: `lsd-autocomplete`,
input: `lsd-autocomplete__input`,
icon: `lsd-autocomplete__icon`,
listBox: `lsd-autocomplete-list-box`,
dropdownItem: `lsd-autocomplete-dropdown-item`,
dropdownItemPlaceholder: `lsd-autocomplete-dropdown-item__placeholder`,
disabled: `lsd-autocomplete--disabled`,
error: 'lsd-autocomplete--error',
large: `lsd-autocomplete--large`,
medium: `lsd-autocomplete--medium`,
withIcon: `lsd-autocomplete--with-icon`,
}

View File

@ -0,0 +1,33 @@
import { Meta, Story } from '@storybook/react'
import { Autocomplete, AutocompleteProps } from './Autocomplete'
const list = JSON.parse(
'["BitTorrent","VANIG","BenjiRolls","Status Network Token","GigTricks","Vechain","Insureum","Instant Sponsor Token","IslaCoin","Kcash","Litecoin","BoutsPro","Valorem","Artcoin","Insureum","Zen Protocol","CryptoPennies","MediBond","WishFinance","BlockNet","Big Data Block","Loom Network","Gamedex","Universal Recognition Token","Soarcoin","IZX","aelf","Bitcoin Private","TerraCoin","Coinnec","Revolution VR","SecureCoin","Swarm Fund","Fan360","LakeBanker","16BitCoin","CyberTrust","Actinium","ZestCoin","Monero 0","DACash","Bitswift","Bethereum","Hedge Token","Megastake","HeelCoin","RealChain","LiteBitcoin","SexCoin","Suretly","Internet of People","Rate3","Invictus","WorldPay","iOlite","Cashaa","NovaCoin","U Network","Gimli","Chynge.net","BMChain","Ethereum Premium","BlackShadowCoin","Javvy","Befund","Bancor Network Token","BOONSCoin","Pantos","IDEX Membership","BitStation","Lynx","Encrybit","HighVibe.Network","Credo","HiCoin","RiptideCoin","BitBoss","NXTTY","Presale Ventures","Urbit Data","Xeonbit","Newbium","Mint","Crypto Wine Exchange","HARA","Pioneer Coin","Ethereum Dark","FazzCoin","Fitrova","The EFFECT Network","CargoX","PolicyPal Network","Vechain","President Clinton","GenesysCoin","Trivver","Bitdeal","ShareMeAll","Primas","RoboAdvisorCoin","Liquid","Napoleon X","NOKU Master token","Liqnet","ZeroState","0chain","DarkCash","Sudan Gold Coin","PokerSports","Bankera","Think And Get Rich Coin","ELTCOIN","USOAMIC","XDNA","Autoria","Cosmo","Bigbom","EagsCoin","Stakinglab","SaffronCoin","BnrtxCoin","FoodCoin","PutinCoin","SID Token","Quartz","IOU1","Spend","NEO Gold","High Voltage Coin","Unobtanium","Sandcoin","FrazCoin","Sudan Gold Coin","VeriCoin","Aurora","NANJCOIN","Muse","DuckDuckCoin","Saifu","CryCash","Rustbits","BitFlip","Cpollo","Monkey Project","Coin Analyst","Scanetchain Token","Aditus","LendConnect","FOREXCOIN","Crypto Improvement Fund","Electra","Psilocybin","GameLeagueCoin","Switcheo","BitQuark","BinaryCoin","CyberVein","KATZcoin","BtcEX","ByteCoin","Shping Coin","Liquid","Stacktical","Tezos","ParkByte","Imbrex","Pinmo","Sigil","LePenCoin","OmiseGO Classic","Digix DAO","ShareRing","CryptoCarbon","CDX Network","SONM","PhoenixCoin","Incent","Tokyo Coin","Premium","Unattanium","Biotron","WETH","Rublebit","KRCoin","Aegis","Legends Cryptocurrency","VARcrypt","Witcoin","GlowShares","HOQU","VARcrypt","Linx","BlackholeCoin","NumbersCoin","ZayedCoin","CarVertical","Securosys","ElliotCoin","Zelcash","AcesCoin","EtherInc"]',
)
export default {
title: 'Autocomplete',
component: Autocomplete,
argTypes: {
size: {
type: {
name: 'enum',
value: ['medium', 'large'],
},
defaultValue: 'large',
},
},
} as Meta
export const Root: Story<AutocompleteProps> = (args) => (
<Autocomplete {...args}>Autocomplete</Autocomplete>
)
Root.args = {
size: 'large',
disabled: false,
withIcon: false,
error: false,
placeholder: 'Placeholder',
onChange: undefined,
options: list,
}

View File

@ -0,0 +1,83 @@
import { css } from '@emotion/react'
import { autocompleteClasses } from './Autocomplete.classes'
export const AutocompleteStyles = css`
.${autocompleteClasses.root} {
width: auto;
border: 1px solid rgb(var(--lsd-border-primary));
box-sizing: border-box;
align-items: center;
}
.${autocompleteClasses.root} > div {
display: flex;
justify-content: space-between;
}
.${autocompleteClasses.disabled} {
opacity: 0.34;
}
.${autocompleteClasses.input} {
border: none;
outline: none;
font-size: 14px;
color: rgb(var(--lsd-text-primary));
background: none;
width: 100%;
}
.${autocompleteClasses.input}:hover {
outline: none;
}
.${autocompleteClasses.input}::placeholder {
color: rgb(var(--lsd-text-primary));
opacity: 0.3;
}
.${autocompleteClasses.error} {
text-decoration: line-through;
}
.${autocompleteClasses.large} {
width: 208px;
height: 40px;
padding: 10px 14px;
}
.${autocompleteClasses.medium} {
width: 188px;
height: 32px;
padding: 6px 12px;
}
.${autocompleteClasses.withIcon} {
}
.${autocompleteClasses.icon} {
cursor: pointer;
display: flex;
align-items: center;
}
.${autocompleteClasses.listBox} {
max-height: 400px;
overflow: auto;
border: 1px solid rgb(var(--lsd-border-primary));
border-top: 0;
}
.${autocompleteClasses.dropdownItem} {
border: 0;
&:not(:last-child) {
border-bottom: 1px solid rgb(var(--lsd-border-primary));
}
}
.${autocompleteClasses.dropdownItemPlaceholder} {
opacity: 0.5;
white-space: pre;
}
`

View File

@ -0,0 +1,150 @@
import clsx from 'clsx'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useInput } from '../../utils/useInput'
import { DropdownItem } from '../DropdownItem'
import { CloseIcon, SearchIcon } from '../Icons'
import { ListBox } from '../ListBox'
import { Portal } from '../PortalProvider/Portal'
import { autocompleteClasses } from './Autocomplete.classes'
export type AutocompleteProps = Omit<
React.HTMLAttributes<HTMLDivElement>,
'onChange' | 'value'
> &
Pick<React.InputHTMLAttributes<HTMLInputElement>, 'onChange'> & {
size?: 'large' | 'medium'
withIcon?: boolean
error?: boolean
disabled?: boolean
placeholder?: string
value?: string
defaultValue?: string
options?: string[]
inputProps?: React.InputHTMLAttributes<HTMLInputElement>
}
export const Autocomplete: React.FC<AutocompleteProps> & {
classes: typeof autocompleteClasses
} = ({
size = 'large',
withIcon = false,
error = false,
disabled = false,
children,
value,
defaultValue,
placeholder,
onChange,
options = [],
inputProps = {},
...props
}) => {
const ref = useRef<HTMLInputElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const input = useInput({ defaultValue, value, onChange, ref })
const inputValue = input.value as string
const [open, setOpen] = useState(false)
const [selected, setSelected] = useState<string>()
const onCancel = () => input.setValue('')
const handleDropdownClick = (value: string) => {
setOpen(false)
setSelected(value)
input.setValue(value)
}
const suggestions = useMemo(
() =>
input.filled
? options
.filter((option) =>
new RegExp(`^${input.value}.+`, 'i').test(option),
)
.map((option) => [
option,
option.slice(0, inputValue.length),
option.slice(inputValue.length),
])
: options,
[input.value, options],
)
useEffect(() => {
!selected && input.filled && !open && setOpen(true)
}, [input.value, selected, open])
const isOpen = !disabled && open && suggestions.length > 0 && input.filled
return (
<div
ref={containerRef}
className={clsx(
props.className,
autocompleteClasses.root,
autocompleteClasses[size],
disabled && autocompleteClasses.disabled,
withIcon && autocompleteClasses.withIcon,
)}
{...props}
>
<div>
<input
{...inputProps}
ref={ref}
value={input.value}
placeholder={placeholder}
onChange={input.onChange}
disabled={disabled}
onFocus={() => setOpen(true)}
className={clsx(
inputProps.className,
autocompleteClasses.input,
error && autocompleteClasses.error,
)}
/>
{withIcon && input.value ? (
<span className={autocompleteClasses.icon} onClick={onCancel}>
<CloseIcon color="primary" />
</span>
) : withIcon && !input.value ? (
<span className={autocompleteClasses.icon}>
<SearchIcon color="primary" />
</span>
) : null}
</div>
<Portal id="autocomplete">
<ListBox
handleRef={containerRef}
open={isOpen}
onClose={() => setOpen(false)}
className={autocompleteClasses.listBox}
>
{suggestions.map((opt, idx: number) => (
<DropdownItem
key={idx}
size={size}
tabIndex={0}
label={
<>
{opt[1]}
<span className={autocompleteClasses.dropdownItemPlaceholder}>
{opt[2]}
</span>
</>
}
className={autocompleteClasses.dropdownItem}
onClick={() => handleDropdownClick(opt[0])}
onKeyDown={(e) =>
e.key === 'Enter' && handleDropdownClick(opt[0])
}
/>
))}
</ListBox>
</Portal>
</div>
)
}
Autocomplete.classes = autocompleteClasses

View File

@ -0,0 +1 @@
export * from './Autocomplete'

View File

@ -1,5 +1,6 @@
import { Global, SerializedStyles } from '@emotion/react'
import React, { useMemo } from 'react'
import { AutocompleteStyles } from '../Autocomplete/Autocomplete.styles'
import { BreadcrumbStyles } from '../Breadcrumb/Breadcrumb.styles'
import { BreadcrumbItemStyles } from '../BreadcrumbItem/BreadcrumbItem.styles'
import { ButtonStyles } from '../Button/Button.styles'
@ -13,6 +14,7 @@ import { ListBoxStyles } from '../ListBox/ListBox.styles'
import { QuoteStyles } from '../Quote/Quote.styles'
import { TabItemStyles } from '../TabItem/TabItem.styles'
import { TabsStyles } from '../Tabs/Tabs.styles'
import { TextFieldStyles } from '../TextField/TextField.styles'
import { defaultThemes, Theme, withTheme } from '../Theme'
import { TypographyStyles } from '../Typography/Typography.styles'
@ -29,6 +31,8 @@ const componentStyles: Array<ReturnType<typeof withTheme> | SerializedStyles> =
IconTagStyles,
BreadcrumbStyles,
BreadcrumbItemStyles,
TextFieldStyles,
AutocompleteStyles,
QuoteStyles,
CollapseStyles,
CollapseHeaderStyles,

View File

@ -4,8 +4,11 @@ import { CheckboxFilledIcon, CheckboxIcon, LsdIconProps } from '../Icons'
import { Typography } from '../Typography'
import { dropdownItemClasses } from './DropdownItem.classes'
export type DropdownItemProps = React.HTMLAttributes<HTMLDivElement> & {
label: string
export type DropdownItemProps = Omit<
React.HTMLAttributes<HTMLDivElement>,
'label'
> & {
label: React.ReactNode
selected?: boolean
withIcon?: boolean
disabled?: boolean
@ -32,7 +35,6 @@ export const DropdownItem: React.FC<DropdownItemProps> & {
<div
role="option"
aria-selected={selected ? 'true' : 'false'}
aria-label={label}
className={clsx(
className,
dropdownItemClasses.root,

View File

@ -1,17 +1,22 @@
import { LsdIcon } from '../LsdIcon'
export const CheckIcon = LsdIcon((props) => (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M11.0833 2.91667V11.0833H2.91667V2.91667H11.0833ZM11.0833 1.75H2.91667C2.275 1.75 1.75 2.275 1.75 2.91667V11.0833C1.75 11.725 2.275 12.25 2.91667 12.25H11.0833C11.725 12.25 12.25 11.725 12.25 11.0833V2.91667C12.25 2.275 11.725 1.75 11.0833 1.75Z"
fill="black"
/>
</svg>
))
export const CheckIcon = LsdIcon(
(props) => (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M5.25009 9.43247L2.81759 6.99997L1.98926 7.82247L5.25009 11.0833L12.2501 4.0833L11.4276 3.2608L5.25009 9.43247Z"
fill="black"
/>
</svg>
),
{
filled: true,
},
)

View File

@ -0,0 +1,15 @@
export const textFieldClasses = {
root: `lsd-textField`,
input: `lsd-textField__input`,
icon: `lsd-textField__icon`,
supportingText: 'lsd-textField__supporting-text',
disabled: `lsd-textField--disabled`,
error: 'lsd-textField--error',
large: `lsd-textField--large`,
medium: `lsd-textField--medium`,
withIcon: `lsd-textField--with-icon`,
}

View File

@ -0,0 +1,30 @@
import { Meta, Story } from '@storybook/react'
import { TextField, TextFieldProps } from './TextField'
export default {
title: 'TextField',
component: TextField,
argTypes: {
size: {
type: {
name: 'enum',
value: ['medium', 'large'],
},
defaultValue: 'large',
},
},
} as Meta
export const Root: Story<TextFieldProps> = (args) => (
<TextField {...args}>TextField</TextField>
)
Root.args = {
size: 'large',
supportingText: 'Supporting text',
disabled: false,
withIcon: false,
error: false,
placeholder: 'Placeholder',
defaultValue: 'default value',
onChange: undefined,
}

View File

@ -0,0 +1,68 @@
import { css } from '@emotion/react'
import { textFieldClasses } from './TextField.classes'
export const TextFieldStyles = css`
.${textFieldClasses.root} {
width: auto;
border-bottom: 1px solid rgb(var(--lsd-border-primary));
box-sizing: border-box;
align-items: center;
}
.${textFieldClasses.root} > div {
display: flex;
justify-content: space-between;
}
.${textFieldClasses.disabled} {
opacity: 0.34;
}
.${textFieldClasses.input} {
border: none;
outline: none;
font-size: 14px;
color: rgb(var(--lsd-text-primary));
background: none;
width: 100%;
}
.${textFieldClasses.input}:hover {
outline: none;
}
.${textFieldClasses.input}::placeholder {
color: rgb(var(--lsd-text-primary));
opacity: 0.3;
}
.${textFieldClasses.error} {
text-decoration: line-through;
}
.${textFieldClasses.supportingText} {
width: fit-content;
margin-top: 20px;
}
.${textFieldClasses.large} {
width: 208px;
height: 40px;
padding: 10px 14px;
}
.${textFieldClasses.medium} {
width: 188px;
height: 32px;
padding: 6px 12px;
}
.${textFieldClasses.withIcon} {
}
.${textFieldClasses.icon} {
cursor: pointer;
display: flex;
align-items: center;
}
`

View File

@ -0,0 +1,96 @@
import clsx from 'clsx'
import React, { useRef } from 'react'
import { useInput } from '../../utils/useInput'
import { CheckIcon, CloseIcon, ErrorIcon } from '../Icons'
import { Typography } from '../Typography'
import { textFieldClasses } from './TextField.classes'
export type TextFieldProps = Omit<
React.HTMLAttributes<HTMLDivElement>,
'onChange' | 'value'
> &
Pick<React.InputHTMLAttributes<HTMLInputElement>, 'onChange'> & {
size?: 'large' | 'medium'
withIcon?: boolean
error?: boolean
disabled?: boolean
supportingText?: string
value?: string
defaultValue?: string
placeholder?: string
inputProps?: React.InputHTMLAttributes<HTMLInputElement>
}
export const TextField: React.FC<TextFieldProps> & {
classes: typeof textFieldClasses
} = ({
size = 'large',
withIcon = false,
supportingText,
error = false,
children,
value,
placeholder,
defaultValue,
onChange,
inputProps = {},
...props
}) => {
const ref = useRef<HTMLInputElement>(null)
const input = useInput({ defaultValue, value, onChange, ref })
const onCancel = () => input.setValue('')
return (
<div
className={clsx(
props.className,
textFieldClasses.root,
textFieldClasses[size],
props.disabled && textFieldClasses.disabled,
withIcon && textFieldClasses.withIcon,
)}
{...props}
>
<div>
<input
placeholder={placeholder}
{...inputProps}
ref={ref}
value={input.value}
onChange={input.onChange}
className={clsx(
inputProps.className,
textFieldClasses.input,
error && textFieldClasses.error,
)}
/>
{withIcon && error ? (
<span className={textFieldClasses.icon} onClick={onCancel}>
<ErrorIcon color="primary" className={textFieldClasses.icon} />
</span>
) : withIcon && !input.filled ? (
<span className={textFieldClasses.icon}>
<CheckIcon color="primary" />
</span>
) : withIcon && input.filled ? (
<span className={textFieldClasses.icon} onClick={onCancel}>
<CloseIcon color="primary" />
</span>
) : null}
</div>
{supportingText && (
<div className={clsx(textFieldClasses.supportingText)}>
<Typography
variant={size === 'large' ? 'label1' : 'label2'}
component="p"
>
{supportingText}
</Typography>
</div>
)}
</div>
)
}
TextField.classes = textFieldClasses

View File

@ -0,0 +1 @@
export * from './TextField'

View File

@ -1,3 +1,4 @@
export * from './components/Autocomplete'
export * from './components/Breadcrumb'
export * from './components/BreadcrumbItem'
export * from './components/Button'

View File

@ -0,0 +1,58 @@
import React, { useEffect, useState } from 'react'
export type InputValueType =
React.InputHTMLAttributes<HTMLInputElement>['value']
export type InputOnChangeType =
React.InputHTMLAttributes<HTMLInputElement>['onChange']
export type InputProps = {
value?: InputValueType
defaultValue?: InputValueType
onChange?: InputOnChangeType
ref?: React.RefObject<HTMLInputElement>
}
export const useInput = (props: InputProps) => {
const [value, setValue] = useState<InputValueType>(
props.value ?? props.defaultValue ?? '',
)
const uncontrolled = typeof props.value === 'undefined'
const filled =
typeof value === 'undefined'
? false
: typeof value === 'string'
? value.length > 0
: value.toString().length > 0
const onChange: InputOnChangeType = (event) => {
if (uncontrolled) return setValue(event.target.value)
props.onChange && props.onChange(event)
}
const setter = (value: InputValueType) => {
if (!props.ref?.current) return
const element = props.ref.current
const event = new Event('input', { bubbles: true })
Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
'value',
)?.set?.call?.(element, value)
element.dispatchEvent(event)
}
useEffect(() => {
!uncontrolled && setValue(props.value)
}, [uncontrolled, props.value])
return {
value,
filled,
onChange,
setValue: setter,
}
}