ferns-ui 2.0.0-beta.4 → 2.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,510 @@
1
+ /**
2
+ * The MIT License (MIT)
3
+ *
4
+ * Copyright © 2019 Arron Hunt <arronjhunt@gmail.com>
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person
7
+ * obtaining a copy of this software and associated documentation
8
+ * files (the “Software”), to deal in the Software without
9
+ * restriction, including without limitation the rights to use,
10
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the Software, and to permit persons to whom the
12
+ * Software is furnished to do so, subject to the following
13
+ * conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be
16
+ * included in all copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
19
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25
+ * OTHER DEALINGS IN THE SOFTWARE.
26
+ */
27
+
28
+ import AsyncStorage from "@react-native-async-storage/async-storage";
29
+ import emoji from "emoji-datasource";
30
+ import React, {useCallback, useEffect, useRef, useState} from "react";
31
+ import type {FlatListProps, LayoutChangeEvent} from "react-native";
32
+ import {
33
+ ActivityIndicator,
34
+ FlatList,
35
+ Platform,
36
+ StyleSheet,
37
+ Text,
38
+ TextInput,
39
+ TouchableOpacity,
40
+ View,
41
+ } from "react-native";
42
+
43
+ export const Categories = {
44
+ all: {
45
+ symbol: null,
46
+ name: "All",
47
+ },
48
+ history: {
49
+ symbol: "🕘",
50
+ name: "Recently used",
51
+ },
52
+ emotion: {
53
+ symbol: "😀",
54
+ name: "Smileys & Emotion",
55
+ },
56
+ people: {
57
+ symbol: "🧑",
58
+ name: "People & Body",
59
+ },
60
+ nature: {
61
+ symbol: "🦄",
62
+ name: "Animals & Nature",
63
+ },
64
+ food: {
65
+ symbol: "🍔",
66
+ name: "Food & Drink",
67
+ },
68
+ activities: {
69
+ symbol: "⚾️",
70
+ name: "Activities",
71
+ },
72
+ places: {
73
+ symbol: "✈️",
74
+ name: "Travel & Places",
75
+ },
76
+ objects: {
77
+ symbol: "💡",
78
+ name: "Objects",
79
+ },
80
+ symbols: {
81
+ symbol: "🔣",
82
+ name: "Symbols",
83
+ },
84
+ flags: {
85
+ symbol: "🏳️‍🌈",
86
+ name: "Flags",
87
+ },
88
+ };
89
+
90
+ interface Emoji {
91
+ unified: string;
92
+ short_names: string[];
93
+ category: string;
94
+ sort_order: number;
95
+ obsoleted_by?: string;
96
+ [key: string]: unknown;
97
+ }
98
+
99
+ type CategoryKey = keyof typeof Categories;
100
+ type Category = (typeof Categories)[CategoryKey];
101
+
102
+ const charFromUtf16 = (utf16: string): string =>
103
+ String.fromCodePoint(...utf16.split("-").map((u) => Number(`0x${u}`)));
104
+
105
+ export const charFromEmojiObject = (obj: Emoji): string => charFromUtf16(obj.unified);
106
+
107
+ const filteredEmojis: Emoji[] = (emoji as Emoji[]).filter((e) => !e.obsoleted_by);
108
+
109
+ const emojiByCategory = (category: string): Emoji[] =>
110
+ filteredEmojis.filter((e) => e.category === category);
111
+
112
+ const sortEmoji = (list: Emoji[]): Emoji[] => list.sort((a, b) => a.sort_order - b.sort_order);
113
+
114
+ const categoryKeys = Object.keys(Categories) as CategoryKey[];
115
+
116
+ interface TabBarProps {
117
+ theme: string;
118
+ activeCategory: Category;
119
+ onPress: (category: Category) => void;
120
+ width: number;
121
+ }
122
+
123
+ const TabBar = ({theme, activeCategory, onPress, width}: TabBarProps) => {
124
+ const tabSize = width / categoryKeys.length;
125
+
126
+ return categoryKeys.map((c) => {
127
+ if (c === "all") {
128
+ return null;
129
+ }
130
+ const category = Categories[c];
131
+ return (
132
+ <TouchableOpacity
133
+ key={category.name}
134
+ onPress={() => onPress(category)}
135
+ style={{
136
+ flex: 1,
137
+ minHeight: 44,
138
+ maxHeight: 60,
139
+ borderColor: category === activeCategory ? theme : "#EEEEEE",
140
+ borderBottomWidth: 2,
141
+ alignItems: "center",
142
+ justifyContent: "center",
143
+ }}
144
+ >
145
+ <Text
146
+ style={{
147
+ textAlign: "center",
148
+ paddingBottom: 8,
149
+ fontSize: Math.max(tabSize - 24, 18),
150
+ }}
151
+ >
152
+ {category.symbol}
153
+ </Text>
154
+ </TouchableOpacity>
155
+ );
156
+ });
157
+ };
158
+
159
+ interface EmojiSelectorProps {
160
+ theme: string;
161
+ category: Category;
162
+ showTabs: boolean;
163
+ showSearchBar: boolean;
164
+ showHistory: boolean;
165
+ showSectionTitles: boolean;
166
+ columns: number;
167
+ placeholder: string;
168
+ onEmojiSelected: (emoji: string) => void;
169
+ shouldInclude?: (emoji: Emoji) => boolean;
170
+ [key: string]: unknown;
171
+ }
172
+
173
+ interface EmojiListByCategory {
174
+ [name: string]: Emoji[];
175
+ }
176
+
177
+ interface EmojiItem {
178
+ key: string;
179
+ emoji: Emoji;
180
+ }
181
+
182
+ interface EmojiCellProps {
183
+ emoji: Emoji;
184
+ colSize: number;
185
+ onPress: () => void;
186
+ }
187
+
188
+ const EmojiCell = ({emoji, colSize, onPress}: EmojiCellProps) => (
189
+ <TouchableOpacity
190
+ activeOpacity={0.5}
191
+ style={{
192
+ width: colSize,
193
+ height: colSize,
194
+ alignItems: "center",
195
+ justifyContent: "center",
196
+ }}
197
+ onPress={onPress}
198
+ >
199
+ <Text style={{color: "#FFFFFF", fontSize: Math.max(colSize - 12, 6)}}>
200
+ {charFromEmojiObject(emoji)}
201
+ </Text>
202
+ </TouchableOpacity>
203
+ );
204
+
205
+ const storage_key = "@react-native-emoji-selector:HISTORY";
206
+
207
+ const EmojiSelector = (props: EmojiSelectorProps) => {
208
+ const {
209
+ theme,
210
+ columns,
211
+ placeholder,
212
+ showHistory,
213
+ showSearchBar,
214
+ showSectionTitles,
215
+ showTabs,
216
+ category: initialCategory,
217
+ shouldInclude,
218
+ onEmojiSelected,
219
+ ...other
220
+ } = props;
221
+
222
+ const [searchQuery, setSearchQuery] = useState<string>("");
223
+ const [category, setCategory] = useState<Category>(initialCategory);
224
+ const [isReady, setIsReady] = useState<boolean>(false);
225
+ const [history, setHistory] = useState<Emoji[]>([]);
226
+ const [emojiList, setEmojiList] = useState<EmojiListByCategory | null>(null);
227
+ const [colSize, setColSize] = useState<number>(0);
228
+ const [width, setWidth] = useState<number>(0);
229
+ const scrollview = useRef<FlatList<EmojiItem> | null>(null);
230
+
231
+ //
232
+ // HANDLER METHODS
233
+ //
234
+ const handleTabSelect = useCallback(
235
+ (nextCategory: Category) => {
236
+ if (isReady) {
237
+ if (scrollview.current) {
238
+ scrollview.current.scrollToOffset({offset: 0, animated: false});
239
+ }
240
+ setSearchQuery("");
241
+ setCategory(nextCategory);
242
+ }
243
+ },
244
+ [isReady]
245
+ );
246
+
247
+ const handleEmojiSelect = useCallback(
248
+ (selectedEmoji: Emoji) => {
249
+ if (showHistory) {
250
+ addToHistoryAsync(selectedEmoji);
251
+ }
252
+ onEmojiSelected(charFromEmojiObject(selectedEmoji));
253
+ },
254
+ [onEmojiSelected, showHistory]
255
+ );
256
+
257
+ const handleSearch = useCallback((query: string) => {
258
+ setSearchQuery(query);
259
+ }, []);
260
+
261
+ const addToHistoryAsync = useCallback(async (selectedEmoji: Emoji) => {
262
+ const stored = await AsyncStorage.getItem(storage_key);
263
+
264
+ let value: Emoji[] = [];
265
+ if (!stored) {
266
+ // no history
267
+ const record = Object.assign({}, selectedEmoji, {count: 1});
268
+ value.push(record);
269
+ } else {
270
+ const json: Emoji[] = JSON.parse(stored);
271
+ if (json.filter((r) => r.unified === selectedEmoji.unified).length > 0) {
272
+ value = json;
273
+ } else {
274
+ const record = Object.assign({}, selectedEmoji, {count: 1});
275
+ value = [record, ...json];
276
+ }
277
+ }
278
+
279
+ AsyncStorage.setItem(storage_key, JSON.stringify(value));
280
+ setHistory(value);
281
+ }, []);
282
+
283
+ const loadHistoryAsync = useCallback(async () => {
284
+ const result = await AsyncStorage.getItem(storage_key);
285
+ if (result) {
286
+ const parsed: Emoji[] = JSON.parse(result);
287
+ setHistory(parsed);
288
+ }
289
+ }, []);
290
+
291
+ //
292
+ // RENDER METHODS
293
+ //
294
+ const renderEmojiCell: FlatListProps<EmojiItem>["renderItem"] = useCallback(
295
+ ({item}: {item: EmojiItem}) => (
296
+ <EmojiCell
297
+ key={item.key}
298
+ emoji={item.emoji}
299
+ onPress={() => handleEmojiSelect(item.emoji)}
300
+ colSize={colSize}
301
+ />
302
+ ),
303
+ [handleEmojiSelect, colSize]
304
+ );
305
+
306
+ const returnSectionData = useCallback((): EmojiItem[] => {
307
+ const currentEmojiList = emojiList;
308
+ if (!currentEmojiList) {
309
+ return [];
310
+ }
311
+
312
+ const currentCategory = category;
313
+ const currentSearchQuery = searchQuery;
314
+ const currentHistory = history;
315
+ let emojiData: EmojiItem[];
316
+
317
+ if (currentCategory === Categories.all && currentSearchQuery === "") {
318
+ //TODO: OPTIMIZE THIS
319
+ const largeList: Emoji[] = [];
320
+ for (const c of categoryKeys) {
321
+ const name = Categories[c].name;
322
+ const list =
323
+ name === Categories.history.name ? currentHistory : currentEmojiList[name] || [];
324
+ if (c !== "all" && c !== "history") {
325
+ largeList.push(...list);
326
+ }
327
+ }
328
+
329
+ emojiData = largeList.map((e) => ({key: e.unified, emoji: e}));
330
+ } else {
331
+ let list: Emoji[];
332
+ const hasSearchQuery = currentSearchQuery !== "";
333
+ const name = currentCategory.name;
334
+ if (hasSearchQuery) {
335
+ const filtered = filteredEmojis.filter((e) => {
336
+ let display = false;
337
+ for (const shortName of e.short_names) {
338
+ if (shortName.includes(currentSearchQuery.toLowerCase())) {
339
+ display = true;
340
+ break;
341
+ }
342
+ }
343
+ return display;
344
+ });
345
+ list = sortEmoji(filtered);
346
+ } else if (name === Categories.history.name) {
347
+ list = currentHistory;
348
+ } else {
349
+ list = currentEmojiList[name] || [];
350
+ }
351
+ emojiData = list.map((e) => ({key: e.unified, emoji: e}));
352
+ }
353
+
354
+ return shouldInclude ? emojiData.filter((e) => shouldInclude(e.emoji)) : emojiData;
355
+ }, [category, emojiList, history, searchQuery, shouldInclude]);
356
+
357
+ const prerenderEmojis = useCallback(
358
+ (callback?: () => void) => {
359
+ const listByCategory: EmojiListByCategory = {};
360
+ for (const c of categoryKeys) {
361
+ const name = Categories[c].name;
362
+ listByCategory[name] = sortEmoji(emojiByCategory(name));
363
+ }
364
+
365
+ setEmojiList(listByCategory);
366
+ setColSize(Math.max(Math.floor(width / columns), 32));
367
+ if (callback) {
368
+ callback();
369
+ }
370
+ },
371
+ [columns, width]
372
+ );
373
+
374
+ const handleLayout = useCallback(
375
+ ({nativeEvent: {layout}}: LayoutChangeEvent) => {
376
+ setWidth(layout.width);
377
+ prerenderEmojis(() => {
378
+ setIsReady(true);
379
+ });
380
+ },
381
+ [prerenderEmojis]
382
+ );
383
+
384
+ //
385
+ // LIFECYCLE METHODS
386
+ //
387
+ useEffect(() => {
388
+ setCategory(initialCategory);
389
+ if (showHistory) {
390
+ loadHistoryAsync();
391
+ }
392
+ }, [initialCategory, loadHistoryAsync, showHistory]);
393
+
394
+ const Searchbar = (
395
+ <View style={styles.searchbar_container}>
396
+ <TextInput
397
+ style={styles.search}
398
+ placeholder={placeholder}
399
+ clearButtonMode="always"
400
+ returnKeyType="done"
401
+ autoCorrect={false}
402
+ underlineColorAndroid={theme}
403
+ value={searchQuery}
404
+ onChangeText={handleSearch}
405
+ />
406
+ </View>
407
+ );
408
+
409
+ const title = searchQuery !== "" ? "Search Results" : category.name;
410
+
411
+ return (
412
+ <View style={styles.frame} {...other} onLayout={handleLayout}>
413
+ <View style={styles.tabBar}>
414
+ {showTabs && (
415
+ <TabBar activeCategory={category} onPress={handleTabSelect} theme={theme} width={width} />
416
+ )}
417
+ </View>
418
+ <View style={{flex: 1}}>
419
+ {showSearchBar && Searchbar}
420
+ {isReady ? (
421
+ <View style={{flex: 1}}>
422
+ <View style={styles.container}>
423
+ {showSectionTitles && <Text style={styles.sectionHeader}>{title}</Text>}
424
+ <FlatList
425
+ style={styles.scrollview}
426
+ contentContainerStyle={{paddingBottom: colSize}}
427
+ data={returnSectionData()}
428
+ renderItem={renderEmojiCell}
429
+ horizontal={false}
430
+ numColumns={columns}
431
+ keyboardShouldPersistTaps={"always"}
432
+ ref={scrollview}
433
+ removeClippedSubviews
434
+ />
435
+ </View>
436
+ </View>
437
+ ) : (
438
+ <View style={styles.loader} {...other}>
439
+ <ActivityIndicator
440
+ size={"large"}
441
+ color={Platform.OS === "android" ? theme : "#000000"}
442
+ />
443
+ </View>
444
+ )}
445
+ </View>
446
+ </View>
447
+ );
448
+ };
449
+
450
+ EmojiSelector.defaultProps = {
451
+ theme: "#007AFF",
452
+ category: Categories.all,
453
+ showTabs: true,
454
+ showSearchBar: true,
455
+ showHistory: false,
456
+ showSectionTitles: true,
457
+ columns: 6,
458
+ placeholder: "Search...",
459
+ };
460
+
461
+ export default EmojiSelector;
462
+
463
+ const styles = StyleSheet.create({
464
+ frame: {
465
+ flex: 1,
466
+ width: "100%",
467
+ },
468
+ loader: {
469
+ flex: 1,
470
+ alignItems: "center",
471
+ justifyContent: "center",
472
+ },
473
+ tabBar: {
474
+ flexDirection: "row",
475
+ minHeight: 44,
476
+ maxHeight: 60,
477
+ },
478
+ scrollview: {
479
+ flex: 1,
480
+ overflow: "hidden",
481
+ },
482
+ searchbar_container: {
483
+ width: "100%",
484
+ zIndex: 1,
485
+ backgroundColor: "rgba(255,255,255,0.75)",
486
+ },
487
+ search: {
488
+ ...Platform.select({
489
+ ios: {
490
+ height: 36,
491
+ paddingLeft: 8,
492
+ borderRadius: 10,
493
+ backgroundColor: "#E5E8E9",
494
+ },
495
+ }),
496
+ margin: 8,
497
+ },
498
+ container: {
499
+ flex: 1,
500
+ flexDirection: "column",
501
+ alignItems: "flex-start",
502
+ overflow: "hidden",
503
+ },
504
+ sectionHeader: {
505
+ margin: 8,
506
+ fontSize: 17,
507
+ width: "100%",
508
+ color: "#8F8F8F",
509
+ },
510
+ });
@@ -1,4 +1,4 @@
1
- import {act, userEvent} from "@testing-library/react-native";
1
+ import {act, fireEvent, userEvent} from "@testing-library/react-native";
2
2
  import React from "react";
3
3
  import {TextField} from "./TextField";
4
4
  import {renderWithTheme} from "./test-utils";
@@ -114,6 +114,66 @@ describe("TextField", () => {
114
114
 
115
115
  expect(mockOnEnter).toHaveBeenCalledTimes(1);
116
116
  });
117
+
118
+ it("should trim value on blur if trimOnBlur is true, even if onBlur prop is not provided", () => {
119
+ const {getByDisplayValue} = renderWithTheme(
120
+ <TextField value="test " trimOnBlur onChange={mockOnChange} />
121
+ );
122
+
123
+ const input = getByDisplayValue("test ");
124
+
125
+ fireEvent(input, "blur");
126
+
127
+ // on change should be called with trimmed value
128
+ expect(mockOnChange).toHaveBeenCalled();
129
+ const lastCall = mockOnChange.mock.calls.at(-1);
130
+ expect(lastCall?.[0]).toBe("test");
131
+ });
132
+
133
+ it("should trim value on blur if trimOnBlur is true, with onBlur prop provided", async () => {
134
+ const {getByDisplayValue} = renderWithTheme(
135
+ <TextField value="test " trimOnBlur={true} onChange={mockOnChange} onBlur={mockOnBlur} />
136
+ );
137
+
138
+ const input = getByDisplayValue("test ");
139
+
140
+ fireEvent(input, "blur");
141
+
142
+ // onChange should be called with trimmed value
143
+ expect(mockOnChange).toHaveBeenCalled();
144
+ const lastCall = mockOnChange.mock.calls[mockOnChange.mock.calls.length - 1];
145
+ expect(lastCall[0]).toBe("test");
146
+
147
+ // onBlur should also be called with trimmed value
148
+ expect(mockOnBlur).toHaveBeenCalledTimes(1);
149
+ expect(mockOnBlur.mock.calls[0][0]).toBe("test");
150
+ });
151
+
152
+ it("should NOT trim value on blur if trimOnBlur is false", async () => {
153
+ const {getByDisplayValue} = renderWithTheme(
154
+ <TextField value="test " trimOnBlur={false} onChange={mockOnChange} />
155
+ );
156
+
157
+ const input = getByDisplayValue("test ");
158
+ fireEvent(input, "blur");
159
+
160
+ // onChange should not be called because the value hasn't changed (no trimming)
161
+ expect(mockOnChange).not.toHaveBeenCalled();
162
+ });
163
+
164
+ it("trims on blur by default when no prop is provided", async () => {
165
+ const {getByDisplayValue} = renderWithTheme(
166
+ <TextField value="test " onChange={mockOnChange} />
167
+ );
168
+
169
+ const input = getByDisplayValue("test ");
170
+ fireEvent(input, "blur");
171
+
172
+ // onChange should be called with trimmed value
173
+ expect(mockOnChange).toHaveBeenCalled();
174
+ const lastCall = mockOnChange.mock.calls.at(-1);
175
+ expect(lastCall?.[0]).toBe("test");
176
+ });
117
177
  });
118
178
 
119
179
  describe("field types", () => {
package/src/TextField.tsx CHANGED
@@ -65,6 +65,7 @@ export const TextField: FC<TextFieldProps> = ({
65
65
  blurOnSubmit = true,
66
66
  iconName,
67
67
  onIconClick,
68
+ trimOnBlur = true,
68
69
  type = "text",
69
70
  autoComplete,
70
71
  inputRef,
@@ -183,8 +184,16 @@ export const TextField: FC<TextFieldProps> = ({
183
184
  value={value}
184
185
  onBlur={() => {
185
186
  if (disabled) return;
187
+ let finalValue = value ?? "";
188
+
189
+ if (trimOnBlur && value) {
190
+ finalValue = finalValue.trim();
191
+ if (finalValue !== value) {
192
+ onChange(finalValue);
193
+ }
194
+ }
186
195
  if (onBlur) {
187
- onBlur(value ?? "");
196
+ onBlur(finalValue);
188
197
  }
189
198
  setFocused(false);
190
199
  }}