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 12 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
48 changes: 48 additions & 0 deletions demo/src/screens/incubatorScreens/IncubatorChipsInputScreen.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import _ from 'lodash';
import React, {Component} from 'react';
import {StyleSheet} from 'react-native';
import {View, Text, Card, TextField, Button, Colors, Incubator} from 'react-native-ui-lib'; //eslint-disable-line
Copy link
Contributor

Choose a reason for hiding this comment

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

There're few redundant imports here..


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>
);
}
}

const styles = StyleSheet.create({
container: {}
});
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 :)

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
26 changes: 26 additions & 0 deletions generatedTypes/src/incubator/ChipsInput/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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'> & {
chips?: ChipProps[];
defaultChipProps?: ChipProps;
onChange?: (chips: ChipProps[], changeReason: ChipsInputChangeReason, updatedChip: ChipProps) => void;
/**
* Maximum chips
*/
maxChips?: number;
};
declare const _default: React.ForwardRefExoticComponent<Omit<TextFieldProps, "ref"> & {
chips?: ChipProps[] | undefined;
defaultChipProps?: ChipProps | undefined;
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"}
]
}
224 changes: 224 additions & 0 deletions src/incubator/ChipsInput/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
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'> & {
chips?: ChipProps[];
defaultChipProps?: ChipProps;
onChange?: (chips: ChipProps[], changeReason: ChipsInputChangeReason, updatedChip: ChipProps) => void;
Copy link
Contributor

Choose a reason for hiding this comment

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

Please add descriptions for these props as well

/**
* 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}

// text80
// {...others}
// maxLength={undefined}
// title={this.props.chips ? undefined : title}
// value={value}
// onKeyPress={this.onKeyPress}
// enableErrors={false}
// onFocus={this.onFocus}
// onBlur={this.onBlur}
// hideUnderline
// selectionColor={isLastTagMarked ? 'transparent' : selectionColor}
// style={[inputStyle, styles.alignTextCenter]}
// containerStyle={{flexGrow: 0}}
// collapsable={false}
/>
);
};

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

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

export default forwardRef(ChipsInput);

/* Old ChipsInput props to make sure we have parity */
// /**
// * list of tags. can be string boolean or custom object when implementing getLabel
// */
// chips?: ChipsInputChipProps[];
// /**
// * Style your chips
// */
// defaultChipProps?: ChipsInputChipProps;
// /**
// * callback for extracting the label out of the tag item
// */
// getLabel?: (tag: ChipType) => any;
// /**
// /**
// * callback for onChangeTags event
// */
// onChangeTags?: () => void;
// /**
// * DEPRECATED: use chips instead. callback for creating new tag out of input value (good for composing tag object)
// */
// onCreateTag?: (value: any) => void;
// /**
// * DEPRECATED: use chips instead. callback for when pressing a tag in the following format (tagIndex, markedTagIndex) => {...}
// */
// onTagPress?: (index: number, toRemove?: number) => void;
// /**
// * validation message error appears when tag isn't validate
// */
// validationErrorMessage?: string;
// /**
// * if true, tags *removal* Ux won't be available
// */
// disableTagRemoval?: boolean;
// /**
// * if true, tags *adding* Ux (i.e. by 'submitting' the input text) won't be available
// */
// disableTagAdding?: boolean;
// /**
// * custom styling for the component container
// */
// containerStyle?: ViewStyle;
// /**
// * custom styling for the tag item
// */
// tagStyle?: ViewStyle;
// /**
// * custom styling for the text input
// */
// inputStyle?: RNTextInputProps['style'];
// /**
// * should hide input underline
// */
// hideUnderline?: boolean;
// /**
// * Maximum numbers of chips
// */
// maxLength?: number;
// /**
// * Chips with maxHeigh is inside a scrollView
// */
// scrollViewProps?: ScrollViewProps;
// /**
// * Chips inside a ScrollView
// */
// maxHeight?: number;
// /**
// * Custom element before the chips, for example 'search' icon, 'To:' label etc'
// */
// leftElement?: JSX.Element | JSX.Element[];
Loading