-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStickyNoteNode.tsx
More file actions
438 lines (409 loc) · 14 KB
/
StickyNoteNode.tsx
File metadata and controls
438 lines (409 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import { Global } from '@emotion/react';
import { CanvasIcon } from '@uipath/apollo-react/canvas';
import type { NodeProps } from '@uipath/apollo-react/canvas/xyflow/react';
import { NodeResizeControl, useReactFlow } from '@uipath/apollo-react/canvas/xyflow/react';
import type { ResizeDragEvent, ResizeParams } from '@uipath/apollo-react/canvas/xyflow/system';
import { AnimatePresence } from 'motion/react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ApI18nProvider } from '../../../i18n';
import ReactMarkdown from 'react-markdown';
import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm';
import { GRID_SPACING } from '../../constants';
import type { ToolbarAction } from '../Toolbar';
import { NodeToolbar } from '../Toolbar';
import { FormattingToolbar } from './FormattingToolbar';
import {
type ActiveFormats,
activeFormatsEqual,
continueListOnEnter,
detectActiveFormats,
} from './markdown-formatting';
import {
BottomCornerIndicators,
ColorOption,
ColorPickerPanel,
RESIZE_CONTROL_Z_INDEX,
ResizeHandle,
StickyNoteContainer,
StickyNoteMarkdown,
StickyNoteTextArea,
StickyNoteWrapper,
stickyNoteGlobalStyles,
TopCornerIndicators,
} from './StickyNoteNode.styles';
import type { StickyNoteColor, StickyNoteData, TextSelection } from './StickyNoteNode.types';
import { STICKY_NOTE_COLORS, withAlpha } from './StickyNoteNode.types';
import { preserveNewlines } from './StickyNoteNode.utils';
import { useMarkdownShortcuts } from './useMarkdownShortcuts';
import { useScrollCapture } from './useScrollCapture';
export interface StickyNoteNodeProps extends NodeProps {
data: StickyNoteData;
placeholder?: string;
renderPlaceholderOnSelect?: boolean;
onContentChange?: (content: string) => void;
onColorChange?: (color: StickyNoteColor) => void;
onResize?: (width: number, height: number) => void;
}
const minWidth = GRID_SPACING * 8;
const minHeight = GRID_SPACING * 8;
const StickyNoteNodeComponent = ({
id,
data,
selected,
dragging,
placeholder = 'Add text',
renderPlaceholderOnSelect = false,
onContentChange,
onColorChange,
onResize,
}: StickyNoteNodeProps) => {
const { updateNodeData, deleteElements } = useReactFlow();
const [isEditing, setIsEditing] = useState(data.autoFocus ?? false);
const [isResizing, setIsResizing] = useState(false);
const [isColorPickerOpen, setIsColorPickerOpen] = useState(false);
const [localContent, setLocalContent] = useState(data.content || '');
const textAreaRef = useRef<HTMLTextAreaElement>(null);
const { ref: markdownRef, scrollCaptureProps } = useScrollCapture();
const colorButtonRef = useRef<HTMLDivElement>(null);
const [activeFormats, setActiveFormats] = useState<ActiveFormats>({
bold: false,
italic: false,
strikethrough: false,
bulletList: false,
numberedList: false,
});
const colorKey = (data.color || 'yellow') as StickyNoteColor;
const color = STICKY_NOTE_COLORS[colorKey] ?? STICKY_NOTE_COLORS.yellow;
const colorWithAlpha = withAlpha(color);
useEffect(() => {
setLocalContent(data.content || '');
}, [data.content]);
// Handle autoFocus - focus textarea when entering edit mode
useEffect(() => {
if (isEditing && textAreaRef.current) {
textAreaRef.current.focus();
textAreaRef.current.select();
}
// Clear autoFocus from data after initial focus to prevent re-focusing on re-renders
if (data.autoFocus) {
updateNodeData(id, { autoFocus: false });
}
}, [isEditing, data.autoFocus, id, updateNodeData]);
useEffect(() => {
if (!selected || isResizing) {
setIsColorPickerOpen(false);
}
}, [selected, isResizing]);
const handleDoubleClick = useCallback(() => {
if (isEditing) return;
setIsEditing(true);
setTimeout(() => {
if (textAreaRef.current) {
textAreaRef.current.focus();
textAreaRef.current.select();
}
}, 0);
}, [isEditing]);
const handleBlur = useCallback(() => {
setIsEditing(false);
if (localContent !== data.content) {
onContentChange?.(localContent);
updateNodeData(id, { content: localContent });
}
}, [id, localContent, data.content, updateNodeData, onContentChange]);
const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setLocalContent(e.target.value);
}, []);
const handleFormat = useCallback((result: TextSelection) => {
setLocalContent(result.value);
setActiveFormats(detectActiveFormats(result));
requestAnimationFrame(() => {
if (textAreaRef.current) {
textAreaRef.current.selectionStart = result.selectionStart;
textAreaRef.current.selectionEnd = result.selectionEnd;
}
});
}, []);
const updateActiveFormats = useCallback(() => {
if (!textAreaRef.current) return;
const next = detectActiveFormats({
value: textAreaRef.current.value,
selectionStart: textAreaRef.current.selectionStart,
selectionEnd: textAreaRef.current.selectionEnd,
});
setActiveFormats((prev) => (activeFormatsEqual(prev, next) ? prev : next));
}, []);
const shortcutKeyDown = useMarkdownShortcuts(textAreaRef, handleFormat);
// Handle key down for saving on Enter (optional, depends on UX preference)
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Escape') {
setIsEditing(false);
setLocalContent(data.content || '');
textAreaRef.current?.blur();
return;
}
if (e.key === 'Enter' && !e.shiftKey && !e.metaKey && !e.ctrlKey) {
const textarea = textAreaRef.current;
if (textarea) {
const result = continueListOnEnter({
value: textarea.value,
selectionStart: textarea.selectionStart,
selectionEnd: textarea.selectionEnd,
});
if (result) {
e.preventDefault();
handleFormat(result);
}
}
return;
}
shortcutKeyDown(e);
},
[data.content, shortcutKeyDown, handleFormat]
);
// Resize handlers
const handleResizeStart = useCallback(() => {
setIsResizing(true);
}, []);
const handleResizeEnd = useCallback(
(_event: ResizeDragEvent, params: ResizeParams) => {
setIsResizing(false);
onResize?.(params.width, params.height);
},
[onResize]
);
// Color change handler
const handleColorChange = useCallback(
(newColor: StickyNoteColor) => {
onColorChange?.(newColor);
updateNodeData(id, { color: newColor });
setIsColorPickerOpen(false);
},
[id, updateNodeData, onColorChange]
);
// Toggle color picker
const handleToggleColorPicker = useCallback(() => {
setIsColorPickerOpen((prev) => !prev);
}, []);
// Handle edit button click
const handleEditClick = useCallback(() => {
setIsEditing(true);
setTimeout(() => {
if (textAreaRef.current) {
textAreaRef.current.focus();
textAreaRef.current.select();
}
}, 0);
}, []);
const handleDelete = useCallback(() => {
deleteElements({ nodes: [{ id }] });
}, [id, deleteElements]);
// Custom markdown components to handle link clicks properly in React Flow nodes
const markdownComponents = useMemo(
() => ({
a: ({ href, children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
<a
{...props}
href={href}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => {
e.stopPropagation();
}}
onDoubleClick={(e) => {
e.stopPropagation();
}}
>
{children}
</a>
),
}),
[]
);
// Build toolbar config with only Edit and Color buttons
const toolbarConfig = useMemo(() => {
const actions: ToolbarAction[] = [
{
id: 'delete',
icon: <CanvasIcon icon="trash" size={14} />,
label: 'Delete',
onAction: handleDelete,
},
{
id: 'edit',
icon: <CanvasIcon icon="pencil" size={14} />,
label: 'Edit',
onAction: handleEditClick,
},
{ id: 'separator' },
{
id: 'color',
icon: (
<div
ref={colorButtonRef}
style={{
width: '16px',
height: '16px',
borderRadius: '50%',
backgroundColor: color,
border: '1px solid transparent',
}}
/>
),
label: 'Color',
onAction: handleToggleColorPicker,
},
];
return {
actions,
overflowActions: [],
overflowLabel: '',
position: 'top' as const,
align: 'center' as const,
};
}, [handleEditClick, handleToggleColorPicker, color, handleDelete]);
return (
<>
<Global styles={stickyNoteGlobalStyles} />
<StickyNoteWrapper>
{/* Top-left resize control */}
<NodeResizeControl
style={{ background: 'transparent', border: 'none', zIndex: RESIZE_CONTROL_Z_INDEX }}
position="top-left"
minWidth={minWidth}
minHeight={minHeight}
onResizeStart={handleResizeStart}
onResizeEnd={handleResizeEnd}
>
<ResizeHandle selected={selected} cursor="nwse-resize" />
</NodeResizeControl>
{/* Top-right resize control */}
<NodeResizeControl
style={{ background: 'transparent', border: 'none', zIndex: RESIZE_CONTROL_Z_INDEX }}
position="top-right"
minWidth={minWidth}
minHeight={minHeight}
onResizeStart={handleResizeStart}
onResizeEnd={handleResizeEnd}
>
<ResizeHandle selected={selected} cursor="nesw-resize" />
</NodeResizeControl>
{/* Bottom-left resize control */}
<NodeResizeControl
style={{ background: 'transparent', border: 'none', zIndex: RESIZE_CONTROL_Z_INDEX }}
position="bottom-left"
minWidth={minWidth}
minHeight={minHeight}
onResizeStart={handleResizeStart}
onResizeEnd={handleResizeEnd}
>
<ResizeHandle selected={selected} cursor="nesw-resize" />
</NodeResizeControl>
{/* Bottom-right resize control */}
<NodeResizeControl
style={{ background: 'transparent', border: 'none', zIndex: RESIZE_CONTROL_Z_INDEX }}
position="bottom-right"
minWidth={minWidth}
minHeight={minHeight}
onResizeStart={handleResizeStart}
onResizeEnd={handleResizeEnd}
>
<ResizeHandle selected={selected} cursor="nwse-resize" />
</NodeResizeControl>
<StickyNoteContainer
backgroundColor={colorWithAlpha}
borderColor={color}
isEditing={isEditing}
selected={selected}
onDoubleClick={handleDoubleClick}
>
<TopCornerIndicators selected={selected} />
<BottomCornerIndicators selected={selected} />
{isEditing ? (
<ApI18nProvider component="canvas">
<FormattingToolbar
textAreaRef={textAreaRef}
borderColor={color}
activeFormats={activeFormats}
onFormat={handleFormat}
/>
<StickyNoteTextArea
ref={textAreaRef}
value={localContent}
onChange={handleChange}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
onSelect={updateActiveFormats}
onKeyUp={updateActiveFormats}
placeholder={placeholder}
isEditing={isEditing}
className="nodrag nowheel"
/>
</ApI18nProvider>
) : (
<StickyNoteMarkdown ref={markdownRef} {...scrollCaptureProps}>
{localContent ? (
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkBreaks]}
components={markdownComponents}
>
{preserveNewlines(localContent)}
</ReactMarkdown>
) : (
// Render placeholder if renderPlaceholderOnSelect is enabled, node is selected, and the content is empty
renderPlaceholderOnSelect &&
selected && (
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkBreaks]}
components={markdownComponents}
>
{placeholder}
</ReactMarkdown>
)
)}
</StickyNoteMarkdown>
)}
</StickyNoteContainer>
{selected && !dragging && !isResizing && (
<NodeToolbar nodeId={id} config={toolbarConfig} expanded={true} />
)}
<AnimatePresence>
{selected && !dragging && !isResizing && isColorPickerOpen && (
<div
style={{
position: 'absolute',
top: -40,
left: '50%',
transform: 'translateX(40px)',
zIndex: 1000,
}}
>
<ColorPickerPanel
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 10 }}
transition={{ duration: 0.15, ease: 'easeOut' }}
>
{Object.keys(STICKY_NOTE_COLORS).map((stickyColorKey) => {
const colorName = stickyColorKey as StickyNoteColor;
return (
<ColorOption
key={stickyColorKey}
color={STICKY_NOTE_COLORS[colorName]}
isSelected={colorKey === colorName}
onClick={() => handleColorChange(colorName)}
title={colorName.charAt(0).toUpperCase() + colorName.slice(1)}
/>
);
})}
</ColorPickerPanel>
</div>
)}
</AnimatePresence>
</StickyNoteWrapper>
</>
);
};
export const StickyNoteNode = memo(StickyNoteNodeComponent);