Image.jsx 16.2 KB
Newer Older
yakoff94's avatar
yakoff94 committed
1
import { NodeViewWrapper, ReactNodeViewRenderer } from "@tiptap/react";
2
import React, { useEffect, useRef, useState, Fragment } from "react";
yakoff94's avatar
yakoff94 committed
3
4
5
6
import TipTapImage from "@tiptap/extension-image";

const MIN_WIDTH = 60;
const BORDER_COLOR = '#0096fd';
Яков's avatar
Яков committed
7
const ALIGN_OPTIONS = ['left', 'center', 'right', 'text'];
yakoff94's avatar
yakoff94 committed
8

9
const ResizableImageTemplate = ({ node, updateAttributes, editor, getPos }) => {
yakoff94's avatar
yakoff94 committed
10
    const imgRef = useRef(null);
11
    const wrapperRef = useRef(null);
yakoff94's avatar
yakoff94 committed
12
    const [editing, setEditing] = useState(false);
13
14
15
16
17
18
19
20
21
22
23
    const [showAlignMenu, setShowAlignMenu] = useState(false);
    const isInitialized = useRef(false);
    const resizeData = useRef({
        startWidth: 0,
        startHeight: 0,
        startX: 0,
        startY: 0,
        aspectRatio: 1
    });

    useEffect(() => {
Яков's avatar
fix    
Яков committed
24
        if (!editor?.isEditable || typeof getPos !== 'function') return;
25

Яков's avatar
fix    
Яков committed
26
27
28
29
        const insertZeroWidthSpace = () => {
            try {
                const pos = getPos();
                if (typeof pos !== 'number' || pos < 0) return;
30

Яков's avatar
fix    
Яков committed
31
                const doc = editor.state.doc;
Яков's avatar
Яков committed
32
                const insertPos = pos + 1;
Яков's avatar
fix    
Яков committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

                if (insertPos >= doc.content.size) return;

                const nextNode = doc.nodeAt(insertPos);
                if (nextNode?.textContent === '\u200B') return;

                setTimeout(() => {
                    if (editor.isDestroyed) return;
                    editor.commands.insertContentAt(insertPos, {
                        type: 'text',
                        text: '\u200B'
                    });
                }, 50);
            } catch (error) {
                console.warn('Error inserting zero-width space:', error);
            }
        };

        const timer = setTimeout(insertZeroWidthSpace, 100);
        return () => clearTimeout(timer);
53
    }, [editor, getPos]);
yakoff94's avatar
yakoff94 committed
54
55

    useEffect(() => {
Яков's avatar
fix    
Яков committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
        if (!imgRef.current || isInitialized.current) return;

        const initImageSize = () => {
            try {
                const width = node.attrs.width || imgRef.current.naturalWidth;
                const height = node.attrs.height || imgRef.current.naturalHeight;

                if (width > 0 && height > 0) {
                    updateAttributes({
                        width: Math.round(width),
                        height: Math.round(height)
                    });
                    isInitialized.current = true;
                }
            } catch (error) {
                console.warn('Error initializing image size:', error);
            }
        };

        if (imgRef.current.complete) {
            initImageSize();
        } else {
            imgRef.current.onload = initImageSize;
79
        }
Яков's avatar
fix    
Яков committed
80
81
82
83
84
85

        return () => {
            if (imgRef.current) {
                imgRef.current.onload = null;
            }
        };
86
87
88
89
90
91
    }, [node.attrs.width, node.attrs.height, updateAttributes]);

    const handleResizeStart = (direction) => (e) => {
        e.preventDefault();
        e.stopPropagation();

Яков's avatar
Яков committed
92
        const nodePos = typeof getPos === 'function' ? getPos() : null;
93
94
        const currentWidth = node.attrs.width || imgRef.current.naturalWidth;
        const currentHeight = node.attrs.height || imgRef.current.naturalHeight;
95
96
97
98
99
100
101

        resizeData.current = {
            startWidth: currentWidth,
            startHeight: currentHeight,
            startX: e.clientX,
            startY: e.clientY,
            aspectRatio: currentWidth / currentHeight,
Яков's avatar
Яков committed
102
103
            direction,
            nodePos
yakoff94's avatar
yakoff94 committed
104
        };
105
106

        const onMouseMove = (e) => {
Яков's avatar
Яков committed
107
108
109
110
111
112
113
114
115
116
            const { startWidth, startHeight, startX, startY, aspectRatio, direction, nodePos } = resizeData.current;

            if (typeof nodePos === 'number') {
                try {
                    const resolvedPos = editor.view.state.doc.resolve(nodePos);
                    if (!resolvedPos?.nodeAfter) return;
                } catch {
                    return;
                }
            }
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

            const deltaX = e.clientX - startX;
            const deltaY = e.clientY - startY;

            let newWidth, newHeight;

            if (node.attrs.align === 'center') {
                if (direction.includes('n') || direction.includes('s')) {
                    const scale = direction.includes('s') ? 1 : -1;
                    newHeight = Math.max(startHeight + deltaY * scale, MIN_WIDTH);
                    newWidth = Math.round(newHeight * aspectRatio);
                } else {
                    const scale = direction.includes('e') ? 1 : -1;
                    newWidth = Math.max(startWidth + deltaX * scale, MIN_WIDTH);
                    newHeight = Math.round(newWidth / aspectRatio);
                }
            } else {
                if (direction.includes('e') || direction.includes('w')) {
                    const scale = direction.includes('e') ? 1 : -1;
                    newWidth = Math.max(startWidth + deltaX * scale, MIN_WIDTH);
                    newHeight = Math.round(newWidth / aspectRatio);
                } else {
                    const scale = direction.includes('s') ? 1 : -1;
                    newHeight = Math.max(startHeight + deltaY * scale, MIN_WIDTH);
                    newWidth = Math.round(newHeight * aspectRatio);
                }
            }

Яков's avatar
fix    
Яков committed
145
146
147
148
149
            // Сохраняем новые размеры в resizeData для использования в onMouseUp
            resizeData.current.currentWidth = newWidth;
            resizeData.current.currentHeight = newHeight;

            updateAttributes({
150
151
152
                width: newWidth,
                height: newHeight
            });
yakoff94's avatar
yakoff94 committed
153
154
        };

155
156
157
        const onMouseUp = () => {
            window.removeEventListener('mousemove', onMouseMove);
            window.removeEventListener('mouseup', onMouseUp);
Яков's avatar
Яков committed
158

Яков's avatar
fix    
Яков committed
159
            // Фиксируем окончательные размеры
Яков's avatar
Яков committed
160
161
            if (typeof resizeData.current.nodePos === 'number') {
                updateAttributes({
Яков's avatar
fix    
Яков committed
162
163
                    width: resizeData.current.currentWidth,
                    height: resizeData.current.currentHeight
Яков's avatar
Яков committed
164
165
166
167
168
169
170
171
172
173
174
175
176
                });
            }

            if (!editor.isDestroyed && editor.view) {
                setTimeout(() => {
                    try {
                        editor.commands.focus();
                        editor.view.dispatch(editor.view.state.tr.setMeta('forceUpdate', true));
                    } catch (error) {
                        console.warn('Focus error after resize:', error);
                    }
                }, 50);
            }
yakoff94's avatar
yakoff94 committed
177
178
        };

179
180
181
        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mouseup', onMouseUp);
    };
yakoff94's avatar
yakoff94 committed
182

183
184
185
186
187
188
189
190
191
    const handleAlign = (align) => {
        updateAttributes({ align });
        setShowAlignMenu(false);
        setTimeout(() => editor.commands.focus(), 100);
    };

    const getWrapperStyle = () => {
        const baseStyle = {
            display: 'inline-block',
192
193
            lineHeight: 0,
            margin: '0.5rem 0',
194
195
            position: 'relative',
            outline: editing ? `1px dashed ${BORDER_COLOR}` : 'none',
Яков's avatar
fix    
Яков committed
196
            verticalAlign: 'top'
197
198
199
200
        };

        switch(node.attrs.align) {
            case 'left':
201
                return { ...baseStyle, float: 'left', marginRight: '1rem' };
202
            case 'right':
203
                return { ...baseStyle, float: 'right', marginLeft: '1rem' };
204
205
206
207
            case 'center':
                return {
                    ...baseStyle,
                    display: 'block',
208
209
                    marginLeft: 'auto',
                    marginRight: 'auto',
210
211
                    textAlign: 'center'
                };
Яков's avatar
Яков committed
212
213
214
215
216
217
218
219
            case 'text':
                return {
                    ...baseStyle,
                    display: 'inline-block',
                    float: 'none',
                    margin: '0 0.2rem',
                    verticalAlign: 'middle'
                };
220
221
222
223
            case 'wrap-left':
                return { ...baseStyle, float: 'left', margin: '0 1rem 1rem 0', shapeOutside: 'margin-box' };
            case 'wrap-right':
                return { ...baseStyle, float: 'right', margin: '0 0 1rem 1rem', shapeOutside: 'margin-box' };
224
225
226
227
            default:
                return baseStyle;
        }
    };
yakoff94's avatar
yakoff94 committed
228

229
230
231
232
233
234
235
    const getImageStyle = () => ({
        width: node.attrs.width ? `${node.attrs.width}px` : 'auto',
        height: node.attrs.height ? `${node.attrs.height}px` : 'auto',
        maxWidth: '100%',
        display: 'block',
        cursor: 'default',
        userSelect: 'none',
Яков's avatar
Яков committed
236
237
        margin: node.attrs.align === 'center' ? '0 auto' : '0',
        verticalAlign: node.attrs.align === 'text' ? 'middle' : 'top'
238
239
    });

yakoff94's avatar
yakoff94 committed
240
241
    return (
        <NodeViewWrapper
242
            as="div"
243
244
245
246
247
            style={getWrapperStyle()}
            ref={wrapperRef}
            onClick={(e) => {
                e.stopPropagation();
                setEditing(true);
yakoff94's avatar
yakoff94 committed
248
            }}
249
250
            contentEditable={false}
            data-image-wrapper
yakoff94's avatar
yakoff94 committed
251
252
        >
            <img
253
254
                {...node.attrs}
                ref={imgRef}
255
                style={getImageStyle()}
256
                onLoad={() => {
257
                    if (imgRef.current && !isInitialized.current) {
258
259
260
261
262
263
264
265
                        const width = imgRef.current.naturalWidth;
                        const height = imgRef.current.naturalHeight;
                        updateAttributes({
                            width: Math.round(width),
                            height: Math.round(height)
                        });
                        isInitialized.current = true;
                    }
yakoff94's avatar
yakoff94 committed
266
267
                }}
            />
268

yakoff94's avatar
yakoff94 committed
269
            {editing && (
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
                <Fragment>
                    {['nw', 'ne', 'sw', 'se'].map(dir => (
                        <div
                            key={dir}
                            onMouseDown={handleResizeStart(dir)}
                            style={{
                                position: 'absolute',
                                width: 12,
                                height: 12,
                                backgroundColor: BORDER_COLOR,
                                border: '1px solid white',
                                [dir[0] === 'n' ? 'top' : 'bottom']: -6,
                                [dir[1] === 'w' ? 'left' : 'right']: node.attrs.align === 'center' ? '50%' : -6,
                                transform: node.attrs.align === 'center' ?
                                    `translateX(${dir[1] === 'w' ? '-100%' : '0%'})` : 'none',
                                cursor: `${dir}-resize`,
                                zIndex: 10
                            }}
                        />
yakoff94's avatar
yakoff94 committed
289
                    ))}
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309

                    {showAlignMenu && (
                        <div style={{
                            position: 'absolute',
                            top: -40,
                            left: '50%',
                            transform: 'translateX(-50%)',
                            backgroundColor: 'white',
                            boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                            borderRadius: 4,
                            padding: 4,
                            zIndex: 20,
                            display: 'flex'
                        }}>
                            {ALIGN_OPTIONS.map(align => (
                                <button
                                    key={align}
                                    onClick={() => handleAlign(align)}
                                    style={{
                                        margin: '0 2px',
310
                                        padding: '10px 8px',
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
                                        background: node.attrs.align === align ? '#e6f7ff' : 'transparent',
                                        border: '1px solid #d9d9d9',
                                        borderRadius: 2,
                                        cursor: 'pointer'
                                    }}
                                >
                                    {align}
                                </button>
                            ))}
                        </div>
                    )}

                    <button
                        onClick={(e) => {
                            e.stopPropagation();
                            setShowAlignMenu(!showAlignMenu);
                        }}
                        style={{
                            position: 'absolute',
                            top: -30,
                            left: '50%',
                            transform: 'translateX(-50%)',
                            backgroundColor: 'white',
                            border: `1px solid ${BORDER_COLOR}`,
                            borderRadius: 4,
336
                            padding: '8px 8px',
337
338
339
340
341
342
343
344
                            cursor: 'pointer',
                            fontSize: 12,
                            zIndex: 10
                        }}
                    >
                        Align
                    </button>
                </Fragment>
yakoff94's avatar
yakoff94 committed
345
346
347
348
349
350
351
352
353
            )}
        </NodeViewWrapper>
    );
};

const ResizableImageExtension = TipTapImage.extend({
    addAttributes() {
        return {
            ...this.parent?.(),
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
            src: {
                default: null,
            },
            alt: {
                default: null,
            },
            title: {
                default: null,
            },
            width: {
                default: null,
                parseHTML: element => {
                    const width = element.getAttribute('width');
                    return width ? parseInt(width, 10) : null;
                },
                renderHTML: attributes => attributes.width ? { width: attributes.width } : {}
            },
            height: {
                default: null,
                parseHTML: element => {
                    const height = element.getAttribute('height');
                    return height ? parseInt(height, 10) : null;
                },
                renderHTML: attributes => attributes.height ? { height: attributes.height } : {}
            },
            align: {
                default: 'left',
                parseHTML: element => element.getAttribute('data-align') || 'left',
                renderHTML: attributes => ({ 'data-align': attributes.align })
            }
yakoff94's avatar
yakoff94 committed
384
385
        };
    },
386
387

    renderHTML({ HTMLAttributes }) {
Яков's avatar
fix    
Яков committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
        const align = HTMLAttributes.align ||
            HTMLAttributes['data-align'] ||
            'left';

        const floatValue = align.startsWith('wrap-') ? align.split('-')[1] :
            ['left', 'right'].includes(align) ? align :
                'none';

        let marginValue;
        switch(align) {
            case 'left':
            case 'wrap-left':
                marginValue = '0 1rem 1rem 0';
                break;
            case 'right':
            case 'wrap-right':
                marginValue = '0 0 1rem 1rem';
                break;
            case 'center':
                marginValue = '0.5rem auto';
                break;
Яков's avatar
Яков committed
409
410
411
            case 'text':
                marginValue = '0 0.2rem';
                break;
Яков's avatar
fix    
Яков committed
412
413
414
            default:
                marginValue = '0';
        }
415
416
417
418

        return ['span', {
            'data-type': 'resizable-image',
            'data-image-wrapper': true,
Яков's avatar
Яков committed
419
            'data-align': align,
420
            style: `
Яков's avatar
fix    
Яков committed
421
            display: ${align === 'center' ? 'block' : 'inline-block'};
Яков's avatar
fix    
Яков committed
422
423
424
            float: ${floatValue};
            margin: ${marginValue};
            shape-outside: ${align.startsWith('wrap-') ? 'margin-box' : 'none'};
Яков's avatar
Яков committed
425
            vertical-align: ${align === 'text' ? 'middle' : 'top'};
Яков's avatar
fix    
Яков committed
426
427
            position: relative;
            ${align === 'center' ? 'width: 100%; text-align: center;' : ''}
Яков's avatar
fix    
Яков committed
428
        `
Яков's avatar
fix    
Яков committed
429
430
431
432
433
434
435
436
        }, ['img', {
            ...HTMLAttributes,
            style: `
            ${HTMLAttributes.style || ''};
            display: ${align === 'center' ? 'inline-block' : 'block'};
            margin: ${align === 'center' ? '0 auto' : '0'};
            max-width: 100%;
            height: auto;
Яков's avatar
Яков committed
437
            vertical-align: ${align === 'text' ? 'middle' : 'top'};
Яков's avatar
fix    
Яков committed
438
439
        `,
            'data-align': align
Яков's avatar
fix    
Яков committed
440
        }]];
441
442
    },

yakoff94's avatar
yakoff94 committed
443
444
    addNodeView() {
        return ReactNodeViewRenderer(ResizableImageTemplate);
445
446
447
448
449
    }
}).configure({
    inline: true,
    group: 'inline',
    draggable: true,
Яков's avatar
Яков committed
450
    selectable: false
451
});
yakoff94's avatar
yakoff94 committed
452
453

export default ResizableImageExtension;