Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
262 changes: 144 additions & 118 deletions design-tokens/input/tokens.json

Large diffs are not rendered by default.

52 changes: 51 additions & 1 deletion scripts/token-generator/__tests__/compiler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,56 @@ describe('token compiler', () => {
expect(compiled.components.dark).toStrictEqual(compiled.components.light)
})

test('достраивает различающиеся component colorScheme из базовых токенов', () => {
const source: TokenTree = {
primitive: { fonts: {} },
semantic: {
dimension: {},
effects: {},
colorScheme: {
light: { color: { base: '#ffffff', override: '#eeeeee' } },
dark: { color: { base: '#111111', override: '#222222' } },
},
},
components: {
missingScheme: {
root: { background: '{color.base}' },
colorScheme: { dark: { root: { background: '{color.override}' } } },
},
partialScheme: {
root: { background: '{color.base}' },
overlay: { background: '{color.base}' },
colorScheme: {
light: { root: { background: '{color.override}' } },
dark: {
root: { background: '{color.override}' },
overlay: { background: '{color.override}' },
},
},
},
},
}

const compiled = compileTokens(source)

expect(compiled.components.light.missingScheme).toHaveProperty(
'colorScheme.root.background',
'#ffffff'
)
expect(compiled.components.dark.missingScheme).toHaveProperty(
'colorScheme.root.background',
'#222222'
)
expect(compiled.components.light.partialScheme).toHaveProperty(
'colorScheme.overlay.background',
'#ffffff'
)
expect(compiled.components.dark.partialScheme).toHaveProperty(
'colorScheme.overlay.background',
'#222222'
)
})

test('отклоняет источник без одной из цветовых схем semantic', () => {
const source: TokenTree = {
primitive: { fonts: {} },
Expand Down Expand Up @@ -532,7 +582,7 @@ describe('production input tokens', () => {
{
width: 4,
style: 'none',
color: '#d4fedc',
color: 'rgba(68, 232, 88, 0.2)',
offset: 0,
shadow: 'inset 0 0 0 4px #d4fedc',
}
Expand Down
75 changes: 70 additions & 5 deletions scripts/token-generator/core/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,51 @@ const selectColorScheme = (
)
}

const completeComponentColorScheme = (
selectedScheme: TokenTree,
alternateScheme: TokenTree,
componentBase: TokenTree,
componentPath: string
): TokenTree => {
const result = mergeTrees({}, selectedScheme)

for (const [key, alternateValue] of Object.entries(alternateScheme)) {
const selectedValue = result[key]
const baseValue = componentBase[key]
const tokenPath = `${componentPath}.${key}`

if (selectedValue === undefined) {
if (baseValue === undefined) {
throw new Error(`Missing base token at "${tokenPath}"`)
}

if (isTokenTree(alternateValue)) {
if (!isTokenTree(baseValue)) {
throw new Error(`Expected an object at "${tokenPath}"`)
}

result[key] = completeComponentColorScheme(
{},
alternateValue,
baseValue,
tokenPath
)
} else {
result[key] = baseValue
}
} else if (isTokenTree(selectedValue) && isTokenTree(alternateValue)) {
result[key] = completeComponentColorScheme(
selectedValue,
alternateValue,
isTokenTree(baseValue) ? baseValue : {},
tokenPath
)
}
}

return result
}

const selectComponentColorSchemes = (
components: TokenTree,
scheme: ColorScheme
Expand All @@ -105,22 +150,42 @@ const selectComponentColorSchemes = (
return [componentName, mergeTrees({}, base)]
}

const selectedScheme = isTokenTree(colorScheme)
? colorScheme[scheme]
: undefined
if (!isTokenTree(colorScheme)) {
throw new Error(
`Expected an object at "components.${componentName}.colorScheme"`
)
}

const alternateSchemeName: ColorScheme =
scheme === 'light' ? 'dark' : 'light'
const selectedScheme = colorScheme[scheme]
const alternateScheme = colorScheme[alternateSchemeName]

if (!isTokenTree(selectedScheme)) {
if (selectedScheme !== undefined && !isTokenTree(selectedScheme)) {
throw new Error(
`Expected an object at "components.${componentName}.colorScheme.${scheme}"`
)
}

if (alternateScheme !== undefined && !isTokenTree(alternateScheme)) {
throw new Error(
`Expected an object at "components.${componentName}.colorScheme.${alternateSchemeName}"`
)
}

const completedScheme = completeComponentColorScheme(
selectedScheme ?? {},
alternateScheme ?? {},
base,
`components.${componentName}`
)

return [
componentName,
Object.fromEntries(
Object.entries(component).map(([key, value]) => [
key,
key === 'colorScheme' ? mergeTrees({}, selectedScheme) : value,
key === 'colorScheme' ? completedScheme : value,
])
),
]
Expand Down
13 changes: 13 additions & 0 deletions src/components/Input/InputOtp/InputOtp.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import type { Meta, StoryObj } from '@storybook/react'
import { useCallback, useEffect, useState } from 'react'

import { InputOtp } from './InputOtp'
import { InputOtpErrorRecoveryScenario } from './InputOtpErrorRecoveryScenario'

const VALIDATION_DELAY = 1000

const validateOtp = () =>
new Promise<boolean>((resolve) => {
setTimeout(() => resolve(false), VALIDATION_DELAY)
})

const meta: Meta<typeof InputOtp> = {
title: 'Form/InputOtp',
Expand Down Expand Up @@ -36,3 +44,8 @@ type Story = StoryObj<typeof InputOtp>
const InputOtpStory: Story = {}

export { InputOtpStory as InputOtp }

export const ErrorRecovery: Story = {
name: 'Scenario: Error Recovery',
render: () => <InputOtpErrorRecoveryScenario validateOtp={validateOtp} />,
}
138 changes: 90 additions & 48 deletions src/components/Input/InputOtp/InputOtp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
type Ref,
Expand All @@ -22,12 +21,20 @@ import {
import { StyleSheet } from 'react-native-unistyles'

import { InputOtpItem } from './InputOtpItem'
import { createInputOtpTestIds, InputOtpTestId } from './testIds'

export { InputOtpTestId } from './testIds'

export interface InputOtpProps
extends
Omit<
TextInputProps,
'onChangeText' | 'onChange' | 'ref' | 'keyboardType' | 'style'
| 'onChangeText'
| 'onChange'
| 'ref'
| 'style'
| 'inputMode'
| 'keyboardType'
>,
Pick<PressableProps, 'testOnly_pressed'> {
length: number
Expand All @@ -37,6 +44,21 @@ export interface InputOtpProps
inputRef?: Ref<TextInput | null>
}

const normalizeOtpValue = (value: string, length: number) =>
value.replace(/[^0-9]/g, '').slice(0, length)

const getDefaultSelection = (value: string) => ({
start: value.length,
end: value.length,
})

const getActiveIndex = (selectionStart: number, length: number) =>
Math.min(Math.max(selectionStart, 0), length - 1)

/**
* Поле для ввода одноразового пароля.
* @link https://www.figma.com/design/Q1BWgZ7zoV5UzlBOnjW0cM/UI-Kit--DS--v2.1?node-id=318-1373
*/
export const InputOtp = memo<InputOtpProps>(
({
length,
Expand All @@ -49,13 +71,22 @@ export const InputOtp = memo<InputOtpProps>(
value = '',
onFocus,
onBlur,
accessibilityState,
autoComplete = 'one-time-code',
selection,
textContentType = 'oneTimeCode',
editable,
...rest
}) => {
const [isFocused, setIsFocused] = useState(false)

const inputRef = useRef<TextInput>(null)
const isInputEditable = !disabled && editable !== false
const inputValue = normalizeOtpValue(value, length)
const inputSelection = selection ?? getDefaultSelection(inputValue)
const hasSelectedText =
(inputSelection.end ?? inputSelection.start) > inputSelection.start
const hasVisibleCursor = inputSelection.start < length

useImperativeHandle<TextInput | null, TextInput | null>(
propsInputRef,
Expand All @@ -80,10 +111,14 @@ export const InputOtp = memo<InputOtpProps>(

const handleChange = useCallback(
(text: string) => {
const sanitizedText = text.replace(/[^0-9]/g, '')
onChange(sanitizedText)
const nextValue = normalizeOtpValue(text, length)
const isSameValueReplacement = hasSelectedText && text === inputValue

if (nextValue !== inputValue || isSameValueReplacement) {
onChange(nextValue)
}
},
[onChange]
[hasSelectedText, inputValue, length, onChange]
)

const handleFocus = useCallback(
Expand All @@ -102,63 +137,70 @@ export const InputOtp = memo<InputOtpProps>(
[onBlur]
)

const activeIndex = useMemo(
() => Math.min(value.length, length - 1),
[value.length, length]
)

const renderArray = useMemo(
() => Array.from({ length }, (_, i) => `Otp-Item-${i}`),
[length]
)
const activeIndex = getActiveIndex(inputSelection.start, length)
const testIds = createInputOtpTestIds(testID ?? InputOtpTestId.root)

return (
<Pressable
disabled={disabled}
accessible={false}
disabled={!isInputEditable}
style={styles.container}
testID={testID}
testOnly_pressed={testOnly_pressed}
testID={testIds.root}
onPress={handlePress}
>
{({ pressed }) => (
<>
<View style={styles.content}>
{renderArray.map((key, index) => (
<InputOtpItem
disabled={disabled}
error={error}
focused={isFocused ? index === activeIndex : false}
key={key}
pressed={pressed}
testID={`${testID}Item`}
value={value[index]}
/>
))}
</View>
<TextInput
editable={isInputEditable}
keyboardType='number-pad'
maxLength={length}
ref={inputRef}
style={styles.input}
testID={`${testID}HiddenInput`}
value={value}
onBlur={handleBlur}
onChangeText={handleChange}
onFocus={handleFocus}
{...rest}
<View
accessibilityElementsHidden
importantForAccessibility='no-hide-descendants'
style={styles.content}
testID={testIds.content}
>
{Array.from({ length }, (_, index) => (
<InputOtpItem
disabled={!isInputEditable}
error={error}
focused={Boolean(
isFocused &&
isInputEditable &&
hasVisibleCursor &&
index === activeIndex
)}
key={`Otp-Item-${index}`}
testIdPrefix={testIds.root}
testOnly_pressed={testOnly_pressed}
value={inputValue[index]}
onPress={handlePress}
/>
</>
)}
))}
</View>
<TextInput
{...rest}
accessibilityState={{
...accessibilityState,
disabled: !isInputEditable,
}}
autoComplete={autoComplete}
editable={isInputEditable}
inputMode='numeric'
keyboardType='number-pad'
ref={inputRef}
selection={inputSelection}
style={styles.input}
testID={testIds.hiddenInput}
textContentType={textContentType}
value={inputValue}
onBlur={handleBlur}
onChangeText={handleChange}
onFocus={handleFocus}
/>
</Pressable>
)
}
)

const styles = StyleSheet.create(({ semantic }) => ({
const styles = StyleSheet.create(({ components }) => ({
container: {},

content: { flexDirection: 'row', gap: semantic.dimension.space[200] },
content: { flexDirection: 'row', gap: components.inputotp.root.gap },

input: { position: 'absolute', width: 1, height: 1, opacity: 0 },
}))
Loading
Loading