Image.jsx 20.6 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

Яков's avatar
fix    
Яков committed
9
const ResizableImageTemplate = ({ node, updateAttributes, editor, getPos, selected }) => {
yakoff94's avatar
yakoff94 committed
10
    const imgRef = useRef(null);
11
12
13
    const wrapperRef = useRef(null);
    const [showAlignMenu, setShowAlignMenu] = useState(false);
    const isInitialized = useRef(false);
Яков's avatar
update    
Яков committed
14
15
    const [isResizing, setIsResizing] = useState(false);

Яков's avatar
fix    
Яков committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    // Добавляем прозрачный нулевой пробел после изображения
    useEffect(() => {
        if (!editor || !getPos) return;

        const pos = getPos() + 1;
        const doc = editor.state.doc;

        if (doc.nodeSize > pos && doc.nodeAt(pos)?.textContent !== '\u200B') {
            editor.commands.insertContentAt(pos, {
                type: 'text',
                text: '\u200B' // Невидимый нулевой пробел
            });
        }
    }, [editor, getPos]);

Яков's avatar
fix    
Яков committed
31
32
    // Получаем текущую ширину редактора и доступное пространство
    const getEditorDimensions = () => {
Яков's avatar
Яков committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
        const editorContent = editor?.options?.element?.closest('.atma-editor-content');
        if (!editorContent) return { width: Infinity, availableSpace: Infinity };

        const fullEditorWidth = editorContent.clientWidth;
        const editorStyles = window.getComputedStyle(editorContent);
        const paddingLeft = parseFloat(editorStyles.paddingLeft) || 0;
        const paddingRight = parseFloat(editorStyles.paddingRight) || 0;
        const availableEditorWidth = fullEditorWidth - paddingLeft - paddingRight;

        let container;

        // при center — всегда редактор
        if (node.attrs.align === 'center') {
            container = editorContent;
        } else {
            // при других выравниваниях — ближайший блок
            container = imgRef.current?.closest('li, blockquote, td, p, div') || editorContent;
Яков's avatar
fix    
Яков committed
50
51
        }

Яков's avatar
Яков committed
52
53
54
55
56
57
58
59
60
        const containerStyles = window.getComputedStyle(container);
        const containerPaddingLeft = parseFloat(containerStyles.paddingLeft) || 0;
        const containerPaddingRight = parseFloat(containerStyles.paddingRight) || 0;
        const containerWidth = container.clientWidth - containerPaddingLeft - containerPaddingRight;

        return {
            width: containerWidth,            // текущая ширина контейнера
            availableSpace: availableEditorWidth // фиксированная доступная ширина
        };
Яков's avatar
fix    
Яков committed
61
62
    };

Яков's avatar
Яков committed
63

Яков's avatar
fix    
Яков committed
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
    // Безопасное обновление атрибутов с учетом выравнивания и границ
    const safeUpdateAttributes = (newAttrs) => {
        const { width: editorWidth, availableSpace } = getEditorDimensions();
        let { width, height, align } = { ...node.attrs, ...newAttrs };
        const newAlign = newAttrs.align || align;

        // При изменении выравнивания проверяем доступное пространство
        if (newAlign && newAlign !== align) {
            const maxWidth = availableSpace;
            if (width > maxWidth) {
                const ratio = maxWidth / width;
                width = maxWidth;
                height = Math.round(height * ratio);
            }
        } else {
            // Для обычного обновления размеров
            const maxWidth = availableSpace;
            if (width > maxWidth) {
                const ratio = maxWidth / width;
                width = maxWidth;
                height = Math.round(height * ratio);
            }
        }

        // Проверяем минимальный размер
        if (width < MIN_WIDTH) {
            const ratio = MIN_WIDTH / width;
            width = MIN_WIDTH;
            height = Math.round(height * ratio);
        }

        updateAttributes({ width, height, ...newAttrs });
Яков's avatar
update    
Яков committed
96
    };
97

Яков's avatar
fix    
Яков committed
98
    // Инициализация изображения
99
    useEffect(() => {
Яков's avatar
fix    
Яков committed
100
        if (!node.attrs['data-node-id']) {
Яков's avatar
fix    
Яков committed
101
            safeUpdateAttributes({
Яков's avatar
fix    
Яков committed
102
103
104
                'data-node-id': `img-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
            });
        }
Яков's avatar
fix    
Яков committed
105
    }, [node.attrs['data-node-id']]);
Яков's avatar
fix    
Яков committed
106

Яков's avatar
fix    
Яков committed
107
    // Обработка кликов вне изображения
Яков's avatar
fix    
Яков committed
108
109
110
111
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (wrapperRef.current && !wrapperRef.current.contains(event.target) && selected) {
                editor.commands.setNodeSelection(getPos());
Яков's avatar
fix    
Яков committed
112
113
            }
        };
Яков's avatar
fix    
Яков committed
114
115
116
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [selected, editor, getPos]);
yakoff94's avatar
yakoff94 committed
117

Яков's avatar
fix    
Яков committed
118
    // Загрузка и инициализация изображения
yakoff94's avatar
yakoff94 committed
119
    useEffect(() => {
Яков's avatar
fix    
Яков committed
120
121
122
123
        if (!imgRef.current || isInitialized.current) return;

        const initImageSize = () => {
            try {
Яков's avatar
fix    
Яков committed
124
125
126
127
128
                // Если размеры уже заданы в атрибутах - используем их сразу
                if (node.attrs.width && node.attrs.height) {
                    isInitialized.current = true;
                    return;
                }
Яков's avatar
fix    
Яков committed
129

Яков's avatar
fix    
Яков committed
130
                const { width: editorWidth } = getEditorDimensions();
Яков's avatar
fix    
Яков committed
131
132
                const naturalWidth = imgRef.current.naturalWidth;
                const naturalHeight = imgRef.current.naturalHeight;
Яков's avatar
update    
Яков committed
133

Яков's avatar
fix    
Яков committed
134
135
                if (naturalWidth <= 0 || naturalHeight <= 0) {
                    console.warn('Image has invalid natural dimensions, retrying...');
Яков's avatar
fix    
Яков committed
136
                    setTimeout(initImageSize, 100);
Яков's avatar
fix    
Яков committed
137
138
139
140
141
142
143
144
145
146
147
148
                    return;
                }

                let initialWidth = naturalWidth;
                let initialHeight = naturalHeight;

                if (initialWidth > editorWidth) {
                    const ratio = editorWidth / initialWidth;
                    initialWidth = editorWidth;
                    initialHeight = Math.round(initialHeight * ratio);
                }

Яков's avatar
fix    
Яков committed
149
                safeUpdateAttributes({
Яков's avatar
fix    
Яков committed
150
151
152
                    width: initialWidth,
                    height: initialHeight,
                    'data-node-id': node.attrs['data-node-id'] || `img-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
Яков's avatar
fix    
Яков committed
153
154
                });
                isInitialized.current = true;
Яков's avatar
fix    
Яков committed
155
156
157
158
159
            } catch (error) {
                console.warn('Error initializing image size:', error);
            }
        };

Яков's avatar
fix    
Яков committed
160
        const handleLoad = () => {
Яков's avatar
fix    
Яков committed
161
162
163
164
165
            // Если размеры уже заданы в атрибутах, пропускаем инициализацию
            if (node.attrs.width && node.attrs.height) {
                isInitialized.current = true;
                return;
            }
Яков's avatar
fix    
Яков committed
166
167
168
            setTimeout(initImageSize, 50);
        };

Яков's avatar
fix    
Яков committed
169
        if (imgRef.current.complete) {
Яков's avatar
fix    
Яков committed
170
            handleLoad();
Яков's avatar
fix    
Яков committed
171
        } else {
Яков's avatar
fix    
Яков committed
172
            imgRef.current.addEventListener('load', handleLoad);
173
        }
Яков's avatar
fix    
Яков committed
174
175

        return () => {
Яков's avatar
fix    
Яков committed
176
177
178
            if (imgRef.current) {
                imgRef.current.removeEventListener('load', handleLoad);
            }
Яков's avatar
fix    
Яков committed
179
        };
Яков's avatar
fix    
Яков committed
180
    }, [node.attrs.width, node.attrs.height, node.attrs['data-node-id']]);
181

Яков's avatar
fix    
Яков committed
182
    // Обработка ресайза изображения
183
184
185
186
    const handleResizeStart = (direction) => (e) => {
        e.preventDefault();
        e.stopPropagation();

Яков's avatar
update    
Яков committed
187
        setIsResizing(true);
Яков's avatar
update    
Яков committed
188
189
        editor.commands.setNodeSelection(getPos());

Яков's avatar
fix    
Яков committed
190
191
192
193
194
        const startWidth = node.attrs.width || imgRef.current.naturalWidth;
        const startHeight = node.attrs.height || imgRef.current.naturalHeight;
        const aspectRatio = startWidth / startHeight;
        const startX = e.clientX;
        const startY = e.clientY;
Яков's avatar
Яков committed
195
        const { width: initialEditorWidth, availableSpace: initialAvailableSpace } = getEditorDimensions();
196
197

        const onMouseMove = (e) => {
Яков's avatar
Яков committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
            requestAnimationFrame(() => {
                const maxWidth = node.attrs.align === 'center' ? initialEditorWidth : initialAvailableSpace;

                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.min(Math.round(newHeight * aspectRatio), maxWidth);
                        newHeight = Math.round(newWidth / aspectRatio);
                    } else {
                        const scale = direction.includes('e') ? 1 : -1;
                        newWidth = Math.min(
                            Math.max(startWidth + deltaX * scale, MIN_WIDTH),
                            maxWidth
                        );
                        newHeight = Math.round(newWidth / aspectRatio);
                    }
220
                } else {
Яков's avatar
Яков committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
                    if (direction.includes('e') || direction.includes('w')) {
                        const scale = direction.includes('e') ? 1 : -1;
                        newWidth = Math.min(
                            Math.max(startWidth + deltaX * scale, MIN_WIDTH),
                            maxWidth
                        );
                        newHeight = Math.round(newWidth / aspectRatio);
                    } else {
                        const scale = direction.includes('s') ? 1 : -1;
                        newHeight = Math.max(startHeight + deltaY * scale, MIN_WIDTH);
                        newWidth = Math.min(
                            Math.round(newHeight * aspectRatio),
                            maxWidth
                        );
                        newHeight = Math.round(newWidth / aspectRatio);
                    }
237
238
                }

Яков's avatar
Яков committed
239
240
                safeUpdateAttributes({ width: newWidth, height: newHeight });
            });
yakoff94's avatar
yakoff94 committed
241
242
        };

Яков's avatar
Яков committed
243

244
245
246
        const onMouseUp = () => {
            window.removeEventListener('mousemove', onMouseMove);
            window.removeEventListener('mouseup', onMouseUp);
Яков's avatar
update    
Яков committed
247
            setIsResizing(false);
Яков's avatar
update    
Яков committed
248
            editor.commands.setNodeSelection(getPos());
Яков's avatar
fix    
Яков committed
249
            editor.commands.focus();
yakoff94's avatar
yakoff94 committed
250
251
        };

252
253
254
        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mouseup', onMouseUp);
    };
yakoff94's avatar
yakoff94 committed
255

Яков's avatar
fix    
Яков committed
256
    // Изменение выравнивания с автоматическим масштабированием
257
    const handleAlign = (align) => {
Яков's avatar
Яков committed
258
259
260
261
        safeUpdateAttributes({ align }); // первый вызов
        setTimeout(() => {
            safeUpdateAttributes({ align }); // повторный вызов с обновлёнными размерами
        }, 50);
262
        setShowAlignMenu(false);
Яков's avatar
fix    
Яков committed
263
        editor.commands.focus();
264
265
    };

Яков's avatar
fix    
Яков committed
266
    // Стили для обертки изображения
Яков's avatar
update    
Яков committed
267
268
    const getWrapperStyle = () => {
        const baseStyle = {
269
            display: 'inline-block',
Яков's avatar
update    
Яков committed
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
            lineHeight: 0,
            position: 'relative',
            outline: (selected || isResizing) ? `1px dashed ${BORDER_COLOR}` : 'none',
            verticalAlign: 'top',
            margin: '0.5rem 0',
        };

        if (node.attrs.align === 'center') {
            return {
                ...baseStyle,
                display: 'block',
                marginLeft: 'auto',
                marginRight: 'auto',
                width: node.attrs.width ? `${node.attrs.width}px` : 'fit-content',
                maxWidth: '100%',
                textAlign: 'center'
            };
        }

        return {
            ...baseStyle,
            ...(node.attrs.align === 'left' && {
                float: 'left',
                marginRight: '1rem',
                width: node.attrs.width ? `${node.attrs.width}px` : 'auto',
            }),
            ...(node.attrs.align === 'right' && {
                float: 'right',
                marginLeft: '1rem',
                width: node.attrs.width ? `${node.attrs.width}px` : 'auto',
            }),
            ...(node.attrs.align === 'text' && {
                display: 'inline-block',
                float: 'none',
                margin: '0 0.2rem',
                verticalAlign: 'middle',
                width: node.attrs.width ? `${node.attrs.width}px` : 'auto',
            }),
        };
    };
yakoff94's avatar
yakoff94 committed
310

Яков's avatar
fix    
Яков committed
311
    // Стили для самого изображения
312
313
    const getImageStyle = () => ({
        width: node.attrs.width ? `${node.attrs.width}px` : 'auto',
Яков's avatar
fix    
Яков committed
314
        height: 'auto',
315
316
317
318
        maxWidth: '100%',
        display: 'block',
        cursor: 'default',
        userSelect: 'none',
Яков's avatar
Яков committed
319
        margin: node.attrs.align === 'center' ? '0 auto' : '0',
Яков's avatar
update    
Яков committed
320
        verticalAlign: node.attrs.align === 'text' ? 'middle' : 'top',
Яков's avatar
fix    
Яков committed
321
        objectFit: 'contain'
322
323
    });

yakoff94's avatar
yakoff94 committed
324
325
    return (
        <NodeViewWrapper
326
            as="div"
327
328
329
330
            style={getWrapperStyle()}
            ref={wrapperRef}
            onClick={(e) => {
                e.stopPropagation();
Яков's avatar
fix    
Яков committed
331
                editor.commands.setNodeSelection(getPos());
yakoff94's avatar
yakoff94 committed
332
            }}
333
334
            contentEditable={false}
            data-image-wrapper
yakoff94's avatar
yakoff94 committed
335
336
        >
            <img
337
338
                {...node.attrs}
                ref={imgRef}
Яков's avatar
update    
Яков committed
339
                draggable={true}
340
                style={getImageStyle()}
341
                onLoad={() => {
Яков's avatar
fix    
Яков committed
342
                    if (imgRef.current && !isInitialized.current && !node.attrs.width && !node.attrs.height) {
Яков's avatar
fix    
Яков committed
343
                        const { width: editorWidth } = getEditorDimensions();
Яков's avatar
update    
Яков committed
344
345
346
                        const naturalWidth = imgRef.current.naturalWidth;
                        const naturalHeight = imgRef.current.naturalHeight;

Яков's avatar
fix    
Яков committed
347
348
349
                        safeUpdateAttributes({
                            width: naturalWidth,
                            height: naturalHeight,
Яков's avatar
fix    
Яков committed
350
                            'data-node-id': node.attrs['data-node-id'] || Math.random().toString(36).substr(2, 9)
351
352
353
                        });
                        isInitialized.current = true;
                    }
yakoff94's avatar
yakoff94 committed
354
355
                }}
            />
356

Яков's avatar
update    
Яков committed
357
            {(selected || isResizing) && (
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
                <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
377
                    ))}
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397

                    {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',
398
                                        padding: '10px 8px',
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
                                        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,
424
                            padding: '8px 8px',
425
426
427
428
429
430
431
432
                            cursor: 'pointer',
                            fontSize: 12,
                            zIndex: 10
                        }}
                    >
                        Align
                    </button>
                </Fragment>
yakoff94's avatar
yakoff94 committed
433
434
435
436
437
438
439
440
441
            )}
        </NodeViewWrapper>
    );
};

const ResizableImageExtension = TipTapImage.extend({
    addAttributes() {
        return {
            ...this.parent?.(),
Яков's avatar
fix    
Яков committed
442
443
444
            src: { default: null },
            alt: { default: null },
            title: { default: null },
445
446
            width: {
                default: null,
Яков's avatar
fix    
Яков committed
447
                parseHTML: element => parseInt(element.getAttribute('width'), 10) || null,
448
449
450
451
                renderHTML: attributes => attributes.width ? { width: attributes.width } : {}
            },
            height: {
                default: null,
Яков's avatar
fix    
Яков committed
452
                parseHTML: element => parseInt(element.getAttribute('height'), 10) || null,
453
454
455
456
457
458
                renderHTML: attributes => attributes.height ? { height: attributes.height } : {}
            },
            align: {
                default: 'left',
                parseHTML: element => element.getAttribute('data-align') || 'left',
                renderHTML: attributes => ({ 'data-align': attributes.align })
Яков's avatar
fix    
Яков committed
459
460
461
462
463
            },
            'data-node-id': {
                default: null,
                parseHTML: element => element.getAttribute('data-node-id'),
                renderHTML: attributes => ({ 'data-node-id': attributes['data-node-id'] })
464
            }
yakoff94's avatar
yakoff94 committed
465
466
        };
    },
Яков's avatar
update    
Яков committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
    renderHTML({ node, HTMLAttributes }) {
        const {
            src,
            alt = '',
            title = '',
            width,
            height,
            ...rest
        } = HTMLAttributes;

        const align = node.attrs.align || 'left';

        const style = [];

Яков's avatar
fix    
Яков committed
481

Яков's avatar
update    
Яков committed
482
483
484
        if (align === 'center') {
            style.push('display: block', 'margin-left: auto', 'margin-right: auto');
        } else if (align === 'left') {
Яков's avatar
fix    
Яков committed
485
            style.push('float: left', 'margin-right: 1rem');
Яков's avatar
update    
Яков committed
486
        } else if (align === 'right') {
Яков's avatar
fix    
Яков committed
487
            style.push('float: right', 'margin-left: 1rem');
Яков's avatar
update    
Яков committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
        } else if (align === 'text') {
            style.push('display: inline-block', 'vertical-align: middle', 'margin: 0 0.2rem');
        }

        if (width) style.push(`width: ${width}px`);
        if (height) style.push(`height: ${height}px`);

        return [
            'img',
            {
                src,
                alt,
                title,
                width,
                height,
                'data-align': align,
                style: style.join('; '),
                ...rest,
            }
        ];
    },
509

yakoff94's avatar
yakoff94 committed
510
511
    addNodeView() {
        return ReactNodeViewRenderer(ResizableImageTemplate);
Яков's avatar
fix    
Яков committed
512
513
514
515
516
517
518
519
    },

    addKeyboardShortcuts() {
        return {
            'Mod-ArrowLeft': () => this.editor.commands.updateAttributes(this.type.name, { align: 'left' }),
            'Mod-ArrowRight': () => this.editor.commands.updateAttributes(this.type.name, { align: 'right' }),
            'Mod-ArrowDown': () => this.editor.commands.updateAttributes(this.type.name, { align: 'center' }),
        };
520
521
522
523
524
    }
}).configure({
    inline: true,
    group: 'inline',
    draggable: true,
Яков's avatar
fix    
Яков committed
525
    selectable: true
526
});
yakoff94's avatar
yakoff94 committed
527
528

export default ResizableImageExtension;