|
1 | 1 | // TODO: merge with getFirstNonEmptyLineOfRichText (and one duplicate I saw and also added a note on) |
2 | 2 |
|
3 | | -export const getActivityPreview = (activityBody: string | null) => { |
4 | | - const noteBody = activityBody ? JSON.parse(activityBody) : []; |
| 3 | +import { isArray, isNonEmptyString } from '@sniptt/guards'; |
| 4 | + |
| 5 | +interface BaseNode { |
| 6 | + type: string; |
| 7 | + content?: RichTextNode[]; |
| 8 | + [key: string]: unknown; |
| 9 | +} |
| 10 | + |
| 11 | +interface TextNode extends BaseNode { |
| 12 | + type: 'text'; |
| 13 | + text: string; |
| 14 | +} |
| 15 | + |
| 16 | +interface LinkNode extends BaseNode { |
| 17 | + type: 'link'; |
| 18 | + href?: string; |
| 19 | + content?: RichTextNode[]; |
| 20 | +} |
| 21 | + |
| 22 | +type RichTextNode = TextNode | LinkNode | BaseNode; |
| 23 | + |
| 24 | +const isTextNode = (node: RichTextNode): node is TextNode => |
| 25 | + node.type === 'text'; |
| 26 | + |
| 27 | +const isLinkNode = (node: RichTextNode): node is LinkNode => |
| 28 | + node.type === 'link'; |
| 29 | + |
| 30 | +export const getActivityPreview = (activityBody: string | null): string => { |
| 31 | + const noteBody: RichTextNode[] = activityBody ? JSON.parse(activityBody) : []; |
| 32 | + |
| 33 | + const extractText = (node: RichTextNode | undefined | null): string => { |
| 34 | + if (!node) return ''; |
| 35 | + |
| 36 | + if (isTextNode(node)) { |
| 37 | + return node.text ?? ''; |
| 38 | + } |
| 39 | + |
| 40 | + if (isLinkNode(node)) { |
| 41 | + return node.content?.map(extractText).join(' ') ?? ''; |
| 42 | + } |
| 43 | + |
| 44 | + if (isArray(node.content)) { |
| 45 | + return node.content.map(extractText).join(' '); |
| 46 | + } |
| 47 | + |
| 48 | + return ''; |
| 49 | + }; |
5 | 50 |
|
6 | 51 | return noteBody.length |
7 | 52 | ? noteBody |
8 | | - .map((x: any) => |
9 | | - Array.isArray(x.content) |
10 | | - ? x.content?.map((content: any) => content?.text).join(' ') |
11 | | - : x.content?.text, |
12 | | - ) |
13 | | - .filter((x: string) => x) |
| 53 | + .map((node) => extractText(node)) |
| 54 | + .filter(isNonEmptyString) |
14 | 55 | .join('\n') |
15 | 56 | : ''; |
16 | 57 | }; |
0 commit comments