Image.jsx 17 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
    // Получаем текущую ширину редактора и доступное пространство
    const getEditorDimensions = () => {
Яков's avatar
update    
Яков committed
18
        const editorElement = editor?.options?.element?.closest('.atma-editor-content');
Яков's avatar
fix    
Яков committed
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
        if (!editorElement) return { width: Infinity, availableSpace: Infinity };

        const editorWidth = editorElement.clientWidth;
        const imgElement = imgRef.current;
        let availableSpace = editorWidth;

        if (imgElement) {
            const imgRect = imgElement.getBoundingClientRect();
            const editorRect = editorElement.getBoundingClientRect();

            if (node.attrs.align === 'center') {
                const leftSpace = imgRect.left - editorRect.left;
                const rightSpace = editorRect.right - imgRect.right;
                availableSpace = Math.min(editorWidth, (leftSpace + rightSpace + imgRect.width));
                console.log(leftSpace, rightSpace, availableSpace);
            } else if (node.attrs.align === 'right') {
                availableSpace = imgRect.left - editorRect.left + node.attrs.width;
            } else if (node.attrs.align === 'left' || node.attrs.align === 'text') {
                availableSpace = editorRect.right - imgRect.left;
            }
        }

        return { width: editorWidth, availableSpace };
    };

    // Безопасное обновление атрибутов с учетом выравнивания и границ
    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
76
    };
77

Яков's avatar
fix    
Яков committed
78
    // Инициализация изображения
79
    useEffect(() => {
Яков's avatar
fix    
Яков committed
80
        if (!node.attrs['data-node-id']) {
Яков's avatar
fix    
Яков committed
81
            safeUpdateAttributes({
Яков's avatar
fix    
Яков committed
82
83
84
                'data-node-id': `img-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
            });
        }
Яков's avatar
fix    
Яков committed
85
    }, [node.attrs['data-node-id']]);
Яков's avatar
fix    
Яков committed
86

Яков's avatar
fix    
Яков committed
87
    // Обработка кликов вне изображения
Яков's avatar
fix    
Яков committed
88
89
90
91
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (wrapperRef.current && !wrapperRef.current.contains(event.target) && selected) {
                editor.commands.setNodeSelection(getPos());
Яков's avatar
fix    
Яков committed
92
93
            }
        };
Яков's avatar
fix    
Яков committed
94
95
96
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [selected, editor, getPos]);
yakoff94's avatar
yakoff94 committed
97

Яков's avatar
fix    
Яков committed
98
    // Загрузка и инициализация изображения
yakoff94's avatar
yakoff94 committed
99
    useEffect(() => {
Яков's avatar
fix    
Яков committed
100
101
102
103
        if (!imgRef.current || isInitialized.current) return;

        const initImageSize = () => {
            try {
Яков's avatar
fix    
Яков committed
104
                const { width: editorWidth } = getEditorDimensions();
Яков's avatar
update    
Яков committed
105
106
107
                const naturalWidth = imgRef.current.naturalWidth;
                const naturalHeight = imgRef.current.naturalHeight;

Яков's avatar
fix    
Яков committed
108
109
110
111
112
113
                safeUpdateAttributes({
                    width: naturalWidth,
                    height: naturalHeight,
                    'data-node-id': node.attrs['data-node-id'] || Math.random().toString(36).substr(2, 9)
                });
                isInitialized.current = true;
Яков's avatar
fix    
Яков committed
114
115
116
117
118
119
120
121
122
            } catch (error) {
                console.warn('Error initializing image size:', error);
            }
        };

        if (imgRef.current.complete) {
            initImageSize();
        } else {
            imgRef.current.onload = initImageSize;
123
        }
Яков's avatar
fix    
Яков committed
124
125

        return () => {
Яков's avatar
fix    
Яков committed
126
            if (imgRef.current) imgRef.current.onload = null;
Яков's avatar
fix    
Яков committed
127
        };
Яков's avatar
fix    
Яков committed
128
    }, [node.attrs.width, node.attrs.height, node.attrs['data-node-id']]);
129

Яков's avatar
fix    
Яков committed
130
    // Обработка ресайза изображения
131
132
133
134
    const handleResizeStart = (direction) => (e) => {
        e.preventDefault();
        e.stopPropagation();

Яков's avatar
update    
Яков committed
135
        setIsResizing(true);
Яков's avatar
update    
Яков committed
136
137
        editor.commands.setNodeSelection(getPos());

Яков's avatar
fix    
Яков committed
138
139
140
141
142
        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
fix    
Яков committed
143
        const { width: editorWidth, availableSpace } = getEditorDimensions();
144
145
146
147
148
149

        const onMouseMove = (e) => {
            const deltaX = e.clientX - startX;
            const deltaY = e.clientY - startY;

            let newWidth, newHeight;
Яков's avatar
fix    
Яков committed
150
            const maxWidth = node.attrs.align === 'center' ? editorWidth : availableSpace;
151
152
153
154
155

            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);
Яков's avatar
fix    
Яков committed
156
157
                    newWidth = Math.min(Math.round(newHeight * aspectRatio), maxWidth);
                    newHeight = Math.round(newWidth / aspectRatio);
158
159
                } else {
                    const scale = direction.includes('e') ? 1 : -1;
Яков's avatar
fix    
Яков committed
160
161
162
163
                    newWidth = Math.min(
                        Math.max(startWidth + deltaX * scale, MIN_WIDTH),
                        maxWidth
                    );
164
165
166
167
168
                    newHeight = Math.round(newWidth / aspectRatio);
                }
            } else {
                if (direction.includes('e') || direction.includes('w')) {
                    const scale = direction.includes('e') ? 1 : -1;
Яков's avatar
fix    
Яков committed
169
170
171
172
                    newWidth = Math.min(
                        Math.max(startWidth + deltaX * scale, MIN_WIDTH),
                        maxWidth
                    );
173
174
175
176
                    newHeight = Math.round(newWidth / aspectRatio);
                } else {
                    const scale = direction.includes('s') ? 1 : -1;
                    newHeight = Math.max(startHeight + deltaY * scale, MIN_WIDTH);
Яков's avatar
fix    
Яков committed
177
178
179
180
181
                    newWidth = Math.min(
                        Math.round(newHeight * aspectRatio),
                        maxWidth
                    );
                    newHeight = Math.round(newWidth / aspectRatio);
182
183
184
                }
            }

Яков's avatar
fix    
Яков committed
185
            safeUpdateAttributes({ width: newWidth, height: newHeight });
yakoff94's avatar
yakoff94 committed
186
187
        };

188
189
190
        const onMouseUp = () => {
            window.removeEventListener('mousemove', onMouseMove);
            window.removeEventListener('mouseup', onMouseUp);
Яков's avatar
update    
Яков committed
191
            setIsResizing(false);
Яков's avatar
update    
Яков committed
192
            editor.commands.setNodeSelection(getPos());
Яков's avatar
fix    
Яков committed
193
            editor.commands.focus();
yakoff94's avatar
yakoff94 committed
194
195
        };

196
197
198
        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mouseup', onMouseUp);
    };
yakoff94's avatar
yakoff94 committed
199

Яков's avatar
fix    
Яков committed
200
    // Изменение выравнивания с автоматическим масштабированием
201
    const handleAlign = (align) => {
Яков's avatar
fix    
Яков committed
202
203
        safeUpdateAttributes({ align });
        safeUpdateAttributes({ align });
204
        setShowAlignMenu(false);
Яков's avatar
fix    
Яков committed
205
        editor.commands.focus();
206
207
    };

Яков's avatar
fix    
Яков committed
208
    // Стили для обертки изображения
Яков's avatar
update    
Яков committed
209
210
    const getWrapperStyle = () => {
        const baseStyle = {
211
            display: 'inline-block',
Яков's avatar
update    
Яков committed
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
            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
252

Яков's avatar
fix    
Яков committed
253
    // Стили для самого изображения
254
255
    const getImageStyle = () => ({
        width: node.attrs.width ? `${node.attrs.width}px` : 'auto',
Яков's avatar
fix    
Яков committed
256
        height: 'auto',
257
258
259
260
        maxWidth: '100%',
        display: 'block',
        cursor: 'default',
        userSelect: 'none',
Яков's avatar
Яков committed
261
        margin: node.attrs.align === 'center' ? '0 auto' : '0',
Яков's avatar
update    
Яков committed
262
        verticalAlign: node.attrs.align === 'text' ? 'middle' : 'top',
Яков's avatar
fix    
Яков committed
263
        objectFit: 'contain'
264
265
    });

yakoff94's avatar
yakoff94 committed
266
267
    return (
        <NodeViewWrapper
268
            as="div"
269
270
271
272
            style={getWrapperStyle()}
            ref={wrapperRef}
            onClick={(e) => {
                e.stopPropagation();
Яков's avatar
fix    
Яков committed
273
                editor.commands.setNodeSelection(getPos());
yakoff94's avatar
yakoff94 committed
274
            }}
275
276
            contentEditable={false}
            data-image-wrapper
yakoff94's avatar
yakoff94 committed
277
278
        >
            <img
279
280
                {...node.attrs}
                ref={imgRef}
Яков's avatar
update    
Яков committed
281
                draggable={true}
282
                style={getImageStyle()}
283
                onLoad={() => {
284
                    if (imgRef.current && !isInitialized.current) {
Яков's avatar
fix    
Яков committed
285
                        const { width: editorWidth } = getEditorDimensions();
Яков's avatar
update    
Яков committed
286
287
288
                        const naturalWidth = imgRef.current.naturalWidth;
                        const naturalHeight = imgRef.current.naturalHeight;

Яков's avatar
fix    
Яков committed
289
290
291
                        safeUpdateAttributes({
                            width: naturalWidth,
                            height: naturalHeight,
Яков's avatar
fix    
Яков committed
292
                            'data-node-id': node.attrs['data-node-id'] || Math.random().toString(36).substr(2, 9)
293
294
295
                        });
                        isInitialized.current = true;
                    }
yakoff94's avatar
yakoff94 committed
296
297
                }}
            />
298

Яков's avatar
update    
Яков committed
299
            {(selected || isResizing) && (
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
                <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
319
                    ))}
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339

                    {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',
340
                                        padding: '10px 8px',
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
                                        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,
366
                            padding: '8px 8px',
367
368
369
370
371
372
373
374
                            cursor: 'pointer',
                            fontSize: 12,
                            zIndex: 10
                        }}
                    >
                        Align
                    </button>
                </Fragment>
yakoff94's avatar
yakoff94 committed
375
376
377
378
379
380
381
382
383
            )}
        </NodeViewWrapper>
    );
};

const ResizableImageExtension = TipTapImage.extend({
    addAttributes() {
        return {
            ...this.parent?.(),
Яков's avatar
fix    
Яков committed
384
385
386
            src: { default: null },
            alt: { default: null },
            title: { default: null },
387
388
            width: {
                default: null,
Яков's avatar
fix    
Яков committed
389
                parseHTML: element => parseInt(element.getAttribute('width'), 10) || null,
390
391
392
393
                renderHTML: attributes => attributes.width ? { width: attributes.width } : {}
            },
            height: {
                default: null,
Яков's avatar
fix    
Яков committed
394
                parseHTML: element => parseInt(element.getAttribute('height'), 10) || null,
395
396
397
398
399
400
                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
401
402
403
404
405
            },
            'data-node-id': {
                default: null,
                parseHTML: element => element.getAttribute('data-node-id'),
                renderHTML: attributes => ({ 'data-node-id': attributes['data-node-id'] })
406
            }
yakoff94's avatar
yakoff94 committed
407
408
        };
    },
409

yakoff94's avatar
yakoff94 committed
410
411
    addNodeView() {
        return ReactNodeViewRenderer(ResizableImageTemplate);
Яков's avatar
fix    
Яков committed
412
413
414
415
416
417
418
419
    },

    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' }),
        };
420
421
422
423
424
    }
}).configure({
    inline: true,
    group: 'inline',
    draggable: true,
Яков's avatar
fix    
Яков committed
425
    selectable: true
426
});
yakoff94's avatar
yakoff94 committed
427
428

export default ResizableImageExtension;