Skip to content

Feat/new chips input #1681

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Nov 28, 2021
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
1 change: 1 addition & 0 deletions demo/src/screens/MenuStructure.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ export const navigationData = {
Incubator: {
title: 'Incubator (Experimental)',
screens: [
{title: '(New) ChipsInput', tags: 'chips input', screen: 'unicorn.components.IncubatorChipsInputScreen'},
{title: 'Native TouchableOpacity', tags: 'touchable native', screen: 'unicorn.incubator.TouchableOpacityScreen'},
{title: '(New) Dialog', tags: 'dialog modal popup alert', screen: 'unicorn.incubator.IncubatorDialogScreen'},
{title: '(New) TextField', tags: 'text field input', screen: 'unicorn.components.IncubatorTextFieldScreen'},
Expand Down
41 changes: 41 additions & 0 deletions demo/src/screens/incubatorScreens/IncubatorChipsInputScreen.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import React, {Component} from 'react';
import {View, Text, Card, TextField, Button, Colors, Incubator} from 'react-native-ui-lib'; //eslint-disable-line

export default class ChipsInputScreen extends Component {
state = {
chips: [{label: 'one'}, {label: 'two'}],
chips2: []
};

render() {
return (
<View flex padding-20>
<Text h1 marginB-s4>
ChipsInput
</Text>
<Incubator.ChipsInput
placeholder="Enter chips"
defaultChipProps={{
backgroundColor: Colors.primary,
labelStyle: {color: Colors.white},
containerStyle: {borderWidth: 0},
dismissColor: Colors.white
}}
chips={this.state.chips}
leadingAccessory={<Text>TO: </Text>}
onChange={newChips => {
this.setState({chips: newChips});
}}
/>

<Incubator.ChipsInput
label="Max 3 chips"
placeholder="Enter chips..."
chips={this.state.chips2}
onChange={newChips => this.setState({chips2: newChips})}
maxChips={3}
/>
</View>
);
}
}
1 change: 1 addition & 0 deletions demo/src/screens/incubatorScreens/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {gestureHandlerRootHOC} from 'react-native-gesture-handler';

export function registerScreens(registrar) {
registrar('unicorn.components.IncubatorChipsInputScreen', () => require('./IncubatorChipsInputScreen').default);
registrar('unicorn.incubator.TouchableOpacityScreen', () =>
gestureHandlerRootHOC(require('./TouchableOpacityScreen').default));
registrar('unicorn.incubator.IncubatorDialogScreen', () => require('./IncubatorDialogScreen').default);
Expand Down
44 changes: 44 additions & 0 deletions generatedTypes/src/incubator/ChipsInput/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import React from 'react';
import { TextFieldProps } from '../TextField';
import { ChipProps } from '../../components/chip';
export declare enum ChipsInputChangeReason {
Added = "added",
Removed = "removed"
}
export declare type ChipsInputProps = Omit<TextFieldProps, 'ref'> & {
/**
* Chip items to render in the input
*/
chips?: ChipProps[];
/**
* A default set of chip props to pass to all chips
*/
defaultChipProps?: ChipProps;
/**
* Change callback for when chips changed (either added or removed)
*/
onChange?: (chips: ChipProps[], changeReason: ChipsInputChangeReason, updatedChip: ChipProps) => void;
/**
* Maximum chips
*/
maxChips?: number;
};
declare const _default: React.ForwardRefExoticComponent<Omit<TextFieldProps, "ref"> & {
/**
* Chip items to render in the input
*/
chips?: ChipProps[] | undefined;
/**
* A default set of chip props to pass to all chips
*/
defaultChipProps?: ChipProps | undefined;
/**
* Change callback for when chips changed (either added or removed)
*/
onChange?: ((chips: ChipProps[], changeReason: ChipsInputChangeReason, updatedChip: ChipProps) => void) | undefined;
/**
* Maximum chips
*/
maxChips?: number | undefined;
} & React.RefAttributes<any>>;
export default _default;
1 change: 1 addition & 0 deletions generatedTypes/src/incubator/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { default as ChipsInput, ChipsInputProps, ChipsInputChangeReason } from './ChipsInput';
export { default as ExpandableOverlay } from './expandableOverlay';
export { default as TextField, TextFieldProps, FieldContextType } from './TextField';
export { default as TouchableOpacity, TouchableOpacityProps } from './TouchableOpacity';
Expand Down
Binary file added src/incubator/ChipsInput/assets/xSmall.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/incubator/ChipsInput/assets/[email protected]
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/incubator/ChipsInput/assets/[email protected]
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/incubator/ChipsInput/assets/[email protected]
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/incubator/ChipsInput/assets/[email protected]
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions src/incubator/ChipsInput/chipsInput.api.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "ChipsInput",
"category": "incubator",
"description": "A chips input",
"extends": ["TextField"],
"modifiers": ["margin", "color", "typography"],
"example": "https://github.com/wix/react-native-ui-lib/blob/master/demo/src/screens/incubatorScreens/IncubatorChipsInputScreen.tsx",
"images": [],
"props": [
{"name": "chips", "type": "ChipProps[]", "description": "List of chips to render"},
{
"name": "defaultChipProps",
"type": "ChipProps",
"description": "Default set of props to pass by default to all chips"
},
{
"name": "onChange",
"type": "(newChips, changeReason, updatedChip) => void",
"description": "Callback for chips change (adding or removing chip)"
},
{"name": "maxChips", "type": "number", "description": "The maximum chips to allow adding"}
]
}
147 changes: 147 additions & 0 deletions src/incubator/ChipsInput/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import React, {useCallback, useMemo, useRef, useState, forwardRef} from 'react';
import {StyleSheet, NativeSyntheticEvent, TextInputKeyPressEventData} from 'react-native';
import {isUndefined, map} from 'lodash';
import {Constants} from '../../helpers';
import {useCombinedRefs} from '../../hooks';
import TextField, {TextFieldProps} from '../TextField';
import Chip, {ChipProps} from '../../components/chip';

const removeIcon = require('./assets/xSmall.png');

export enum ChipsInputChangeReason {
Added = 'added',
Removed = 'removed'
}

export type ChipsInputProps = Omit<TextFieldProps, 'ref'> & {
/**
* Chip items to render in the input
*/
chips?: ChipProps[];
/**
* A default set of chip props to pass to all chips
*/
defaultChipProps?: ChipProps;
/**
* Change callback for when chips changed (either added or removed)
*/
onChange?: (chips: ChipProps[], changeReason: ChipsInputChangeReason, updatedChip: ChipProps) => void;
/**
* Maximum chips
*/
maxChips?: number;
};

const ChipsInput = (props: ChipsInputProps, refToForward: React.Ref<any>) => {
const fieldRef = useCombinedRefs(refToForward);
const {chips = [], defaultChipProps, leadingAccessory, onChange, fieldStyle, maxChips, ...others} = props;
const [markedForRemoval, setMarkedForRemoval] = useState<number | undefined>(undefined);
const fieldValue = useRef(others.value);

const addChip = useCallback(() => {
const reachedMaximum = maxChips && chips?.length >= maxChips;
if (fieldValue.current && !reachedMaximum) {
const newChip = {label: fieldValue.current};
onChange?.([...chips, newChip], ChipsInputChangeReason.Added, newChip);
setMarkedForRemoval(undefined);
// @ts-expect-error
fieldRef.current.clear();
fieldValue.current = '';
}
}, [onChange, chips, maxChips]);

const removeMarkedChip = useCallback(() => {
if (!isUndefined(markedForRemoval)) {
const removedChip = chips?.splice(markedForRemoval, 1);
onChange?.([...chips], ChipsInputChangeReason.Removed, removedChip?.[0]);
setMarkedForRemoval(undefined);
}
}, [chips, markedForRemoval, onChange]);

const onChipPress = useCallback(({customValue: index}) => {
const selectedChip = chips[index];
selectedChip?.onPress?.();

setMarkedForRemoval(index);
},
[chips]);

const onChangeText = useCallback(value => {
fieldValue.current = value;
props.onChangeText?.(value);

if (!isUndefined(markedForRemoval)) {
setMarkedForRemoval(undefined);
}
},
[props.onChangeText, markedForRemoval]);

const onKeyPress = useCallback((event: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
props.onKeyPress?.(event);
const keyCode = event?.nativeEvent?.key;
const pressedBackspace = keyCode === Constants.backspaceKey;

if (pressedBackspace && !fieldValue.current) {
if (isUndefined(markedForRemoval) || markedForRemoval !== chips.length - 1) {
setMarkedForRemoval(chips.length - 1);
} else {
removeMarkedChip();
}
}
},
[chips, props.onKeyPress, markedForRemoval, removeMarkedChip]);

const chipList = useMemo(() => {
return (
<>
{leadingAccessory}
{map(chips, (chip, index) => {
const isMarkedForRemoval = index === markedForRemoval;
return (
<Chip
key={index}
customValue={index}
// resetSpacings
// paddingH-s2
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can be removed?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kept it for now so I'll have a quick reference in case there is something missing while we're migrating.
I added a TODO

marginR-s2
marginB-s2
dismissIcon={removeIcon}
{...defaultChipProps}
{...chip}
onPress={onChipPress}
onDismiss={isMarkedForRemoval ? removeMarkedChip : undefined}
/>
);
})}
</>
);
}, [chips, leadingAccessory, defaultChipProps, removeMarkedChip, markedForRemoval]);

return (
<TextField
// @ts-expect-error
ref={fieldRef}
leadingAccessory={chipList}
blurOnSubmit={false}
{...others}
onChangeText={onChangeText}
onSubmitEditing={addChip}
fieldStyle={[fieldStyle, styles.fieldStyle]}
onKeyPress={onKeyPress}
accessibilityHint={props.editable ? 'press keyboard delete button to remove last tag' : undefined}
/>
);
};

const styles = StyleSheet.create({
fieldStyle: {
flexWrap: 'wrap'
}
});

ChipsInput.changeReasons = {
ADDED: 'added',
REMOVED: 'removed'
};

export default forwardRef(ChipsInput);
54 changes: 27 additions & 27 deletions src/incubator/TextField/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -184,34 +184,34 @@ const TextField = (props: InternalTextFieldProps) => {
testID={`${props.testID}.validationMessage`}
/>
)}
<View style={[paddings, fieldStyle]}>
<View row centerV>
{leadingAccessory}
<View flexG>
{floatingPlaceholder && (
<FloatingPlaceholder
placeholder={placeholder}
floatingPlaceholderStyle={[typographyStyle, floatingPlaceholderStyle]}
floatingPlaceholderColor={floatingPlaceholderColor}
floatOnFocus={floatOnFocus}
validationMessagePosition={validationMessagePosition}
/>
)}
{children || (
<Input
placeholderTextColor={hidePlaceholder ? 'transparent' : Colors.grey30}
{...others}
style={[typographyStyle, colorStyle, others.style]}
onFocus={onFocus}
onBlur={onBlur}
onChangeText={onChangeText}
placeholder={placeholder}
hint={hint}
/>
)}
</View>
{trailingAccessory}
<View style={[paddings, fieldStyle]} row centerV>
{/* <View row centerV> */}
{leadingAccessory}
<View flexG>
{floatingPlaceholder && (
<FloatingPlaceholder
placeholder={placeholder}
floatingPlaceholderStyle={[typographyStyle, floatingPlaceholderStyle]}
floatingPlaceholderColor={floatingPlaceholderColor}
floatOnFocus={floatOnFocus}
validationMessagePosition={validationMessagePosition}
/>
)}
{children || (
<Input
placeholderTextColor={hidePlaceholder ? 'transparent' : Colors.grey30}
{...others}
style={[typographyStyle, colorStyle, others.style]}
onFocus={onFocus}
onBlur={onBlur}
onChangeText={onChangeText}
placeholder={placeholder}
hint={hint}
/>
)}
</View>
{trailingAccessory}
{/* </View> */}
</View>
<View row spread>
{validationMessagePosition === ValidationMessagePosition.BOTTOM && (
Expand Down
1 change: 1 addition & 0 deletions src/incubator/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export {default as ChipsInput, ChipsInputProps, ChipsInputChangeReason} from './ChipsInput';
export {default as ExpandableOverlay} from './expandableOverlay';
// @ts-ignore
export {default as TextField, TextFieldProps, FieldContextType} from './TextField';
Expand Down