2.0 KB74 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8import {Button} from './Button';
9import {Icon} from './Icon';
10
11export function TokensList({
12 tokens,
13 onClickX,
14 onClickToken,
15}: {
16 tokens: Array<string>;
17 onClickX?: (token: string) => unknown;
18 onClickToken?: (token: string) => unknown;
19}) {
20 const hasOnClick = onClickToken != null;
21 return (
22 <>
23 {tokens
24 .filter(token => token != '')
25 .map((token, i) => (
26 <span
27 key={i}
28 className={'token' + (hasOnClick ? ' clickable' : '')}
29 onClick={
30 hasOnClick
31 ? e => {
32 onClickToken(token);
33 e.preventDefault();
34 e.stopPropagation();
35 }
36 : undefined
37 }>
38 {token}
39 {onClickX == null ? null : (
40 <Button
41 icon
42 data-testid="token-x"
43 onClick={e => {
44 onClickX?.(token);
45 e.stopPropagation();
46 }}>
47 <Icon icon="x" />
48 </Button>
49 )}
50 </span>
51 ))}
52 </>
53 );
54}
55
56function deduplicate<T>(values: Array<T>) {
57 return [...new Set(values)];
58}
59
60/** Extract comma-separated tokens into an array, plus any remaining non-tokenized text */
61export function extractTokens(raw: string): [Array<string>, string] {
62 const tokens = raw.split(',');
63 const remaining = tokens.length === 0 ? raw : tokens.pop();
64 return [
65 deduplicate(tokens.map(token => token.trim())).filter(token => token !== ''),
66 remaining?.trimStart() ?? '',
67 ];
68}
69
70/** Combine tokens back into a string to be stored in the commit message */
71export function tokensToString(tokens: Array<string>, remaining: string): string {
72 return tokens.length === 0 ? remaining : tokens.join(',') + ',' + remaining;
73}
74