Image.jsx 33.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
import TipTapImage from "@tiptap/extension-image";
Яков's avatar
update    
Яков committed
4
import { Button, Modal, Input, Typography } from 'antd';
Яков's avatar
update    
Яков committed
5
import {FontSizeOutlined} from "@ant-design/icons";
Яков's avatar
update    
Яков committed
6
const { TextArea } = Input;
Яков's avatar
update    
Яков committed
7
const {Text} = Typography;
yakoff94's avatar
yakoff94 committed
8
9
10

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

Яков's avatar
fix    
Яков committed
13
const ResizableImageTemplate = ({ node, updateAttributes, editor, getPos, selected }) => {
yakoff94's avatar
yakoff94 committed
14
    const imgRef = useRef(null);
15
16
    const wrapperRef = useRef(null);
    const isInitialized = useRef(false);
Яков's avatar
update    
Яков committed
17
    const [isResizing, setIsResizing] = useState(false);
Яков's avatar
update    
Яков committed
18
19
    const [altModalVisible, setAltModalVisible] = useState(false);
    const [tempAlt, setTempAlt] = useState(node.attrs.alt || '');
Яков's avatar
update    
Яков committed
20
    const [tempFrontAlt, setTempFrontAlt] = useState(node.attrs.frontAlt || '');
Яков's avatar
Яков committed
21
22
    // wrap=false + left/right: outer wrapper is full-width block, inner div holds image+handles
    const isNoWrap = !node.attrs.wrap && (node.attrs.align === 'left' || node.attrs.align === 'right');
Яков's avatar
update    
Яков committed
23

Яков's avatar
update    
Яков committed
24

Яков's avatar
fix    
Яков committed
25
26
    // Добавляем прозрачный нулевой пробел после изображения
    useEffect(() => {
Яков's avatar
Яков committed
27
        if (!editor || !getPos || editor.isDestroyed) return
Яков's avatar
fix    
Яков committed
28

Яков's avatar
Яков committed
29
        let pos
Яков's avatar
update    
Яков committed
30
        try {
Яков's avatar
Яков committed
31
32
33
            pos = getPos()
        } catch {
            return
Яков's avatar
update    
Яков committed
34
        }
Яков's avatar
Яков committed
35
        if (typeof pos !== 'number') return
Яков's avatar
update    
Яков committed
36

Яков's avatar
Яков committed
37
38
39
        const { doc } = editor.state
        const node = doc.nodeAt(pos)
        if (!node || node.type.name !== 'image') return
Яков's avatar
fix    
Яков committed
40

Яков's avatar
Яков committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
        const next = doc.nodeAt(pos + node.nodeSize)
        if (next?.isText && next.text === '\u200B') return

        requestAnimationFrame(() => {
            if (editor.isDestroyed) return

            try {
                const p = getPos()
                const n = editor.state.doc.nodeAt(p)
                if (!n || n.type.name !== 'image') return

                editor.commands.insertContentAt(p + n.nodeSize, '\u200B')
            } catch {}
        })
    }, [])
Яков's avatar
fix    
Яков committed
56

Яков's avatar
update    
Яков committed
57

Яков's avatar
fix    
Яков committed
58
59
    // Получаем текущую ширину редактора и доступное пространство
    const getEditorDimensions = () => {
Яков's avatar
Яков committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
        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
77
78
        }

Яков's avatar
Яков committed
79
80
81
82
83
84
85
86
87
        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
88
89
    };

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

Яков's avatar
fix    
Яков committed
91
    // Безопасное обновление атрибутов с учетом выравнивания и границ
Яков's avatar
Яков committed
92
93
94
95
96
97
98
99
100
101
    const clamp = (v, min, max) => Math.min(max, Math.max(min, v))

    const safeUpdateAttributes = (patch) => {
        if (!editor || editor.isDestroyed) return

        let pos
        try {
            pos = getPos()
        } catch {
            return
Яков's avatar
fix    
Яков committed
102
        }
Яков's avatar
Яков committed
103
        if (typeof pos !== 'number') return
Яков's avatar
fix    
Яков committed
104

Яков's avatar
Яков committed
105
106
107
108
109
110
111
112
113
114
115
116
        const currentNode = editor.state.doc.nodeAt(pos)
        if (!currentNode || currentNode.type.name !== 'image') return

        const base = currentNode.attrs || {}

        // 1) сохраняем то, что не хотим потерять
        const keep = {
            align: base.align,
            border: base.border,
            borderColor: base.borderColor,
            borderWidth: base.borderWidth,
            borderRadius: base.borderRadius,
Яков's avatar
fix    
Яков committed
117
118
        }

Яков's avatar
Яков committed
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
        // 2) кандидат на апдейт
        let next = { ...keep, ...base, ...patch }

        // 3) нормализуем размеры (границы)
        const minW = 80
        const maxW = 1600
        const minH = 40
        const maxH = 2000

        if (next.width != null) next.width = clamp(Number(next.width) || 0, minW, maxW)
        if (next.height != null) next.height = clamp(Number(next.height) || 0, minH, maxH)

        // 4) нормализуем align (чтобы не улетало в мусор)
        const allowedAlign = new Set(['left', 'center', 'right', 'full'])
        if (next.align && !allowedAlign.has(next.align)) next.align = base.align || 'center'

        updateAttributes(next)
    }
    //
    // 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 });
    // };
170

Яков's avatar
fix    
Яков committed
171
    // Инициализация изображения
172
    useEffect(() => {
Яков's avatar
fix    
Яков committed
173
        if (!node.attrs['data-node-id']) {
Яков's avatar
fix    
Яков committed
174
            safeUpdateAttributes({
Яков's avatar
fix    
Яков committed
175
176
177
                'data-node-id': `img-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
            });
        }
Яков's avatar
fix    
Яков committed
178
    }, [node.attrs['data-node-id']]);
Яков's avatar
fix    
Яков committed
179

Яков's avatar
fix    
Яков committed
180
    // Обработка кликов вне изображения
Яков's avatar
fix    
Яков committed
181
182
183
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (wrapperRef.current && !wrapperRef.current.contains(event.target) && selected) {
Яков's avatar
update    
Яков committed
184
185
186
187
188
189
190
191
192
                try {
                    const pos = getPos?.()
                    if (typeof pos === 'number') {
                        editor.commands.setNodeSelection(pos)
                    }
                } catch (e) {
                    console.warn('getPos() failed:', e)
                }
                // editor.commands.setNodeSelection(getPos());
Яков's avatar
fix    
Яков committed
193
194
            }
        };
Яков's avatar
fix    
Яков committed
195
196
197
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [selected, editor, getPos]);
yakoff94's avatar
yakoff94 committed
198

Яков's avatar
fix    
Яков committed
199
    // Загрузка и инициализация изображения
yakoff94's avatar
yakoff94 committed
200
    useEffect(() => {
Яков's avatar
fix    
Яков committed
201
202
203
204
        if (!imgRef.current || isInitialized.current) return;

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

Яков's avatar
fix    
Яков committed
211
                const { width: editorWidth } = getEditorDimensions();
Яков's avatar
fix    
Яков committed
212
213
                const naturalWidth = imgRef.current.naturalWidth;
                const naturalHeight = imgRef.current.naturalHeight;
Яков's avatar
update    
Яков committed
214

Яков's avatar
fix    
Яков committed
215
216
                if (naturalWidth <= 0 || naturalHeight <= 0) {
                    console.warn('Image has invalid natural dimensions, retrying...');
Яков's avatar
fix    
Яков committed
217
                    setTimeout(initImageSize, 100);
Яков's avatar
fix    
Яков committed
218
219
220
221
222
223
224
225
226
227
228
229
                    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
230
                safeUpdateAttributes({
Яков's avatar
fix    
Яков committed
231
232
233
                    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
234
235
                });
                isInitialized.current = true;
Яков's avatar
fix    
Яков committed
236
237
238
239
240
            } catch (error) {
                console.warn('Error initializing image size:', error);
            }
        };

Яков's avatar
fix    
Яков committed
241
        const handleLoad = () => {
Яков's avatar
fix    
Яков committed
242
243
244
245
246
            // Если размеры уже заданы в атрибутах, пропускаем инициализацию
            if (node.attrs.width && node.attrs.height) {
                isInitialized.current = true;
                return;
            }
Яков's avatar
fix    
Яков committed
247
248
249
            setTimeout(initImageSize, 50);
        };

Яков's avatar
fix    
Яков committed
250
        if (imgRef.current.complete) {
Яков's avatar
fix    
Яков committed
251
            handleLoad();
Яков's avatar
fix    
Яков committed
252
        } else {
Яков's avatar
fix    
Яков committed
253
            imgRef.current.addEventListener('load', handleLoad);
254
        }
Яков's avatar
fix    
Яков committed
255
256

        return () => {
Яков's avatar
fix    
Яков committed
257
258
259
            if (imgRef.current) {
                imgRef.current.removeEventListener('load', handleLoad);
            }
Яков's avatar
fix    
Яков committed
260
        };
Яков's avatar
fix    
Яков committed
261
    }, [node.attrs.width, node.attrs.height, node.attrs['data-node-id']]);
262

Яков's avatar
fix    
Яков committed
263
    // Обработка ресайза изображения
264
265
266
267
    const handleResizeStart = (direction) => (e) => {
        e.preventDefault();
        e.stopPropagation();

Яков's avatar
update    
Яков committed
268
        setIsResizing(true);
Яков's avatar
update    
Яков committed
269
270
271
272
273
274
275
276
277
        try {
            const pos = getPos?.()
            if (typeof pos === 'number') {
                editor.commands.setNodeSelection(pos)
            }
        } catch (e) {
            console.warn('getPos() failed:', e)
        }
        // editor.commands.setNodeSelection(getPos());
Яков's avatar
update    
Яков committed
278

Яков's avatar
fix    
Яков committed
279
280
281
        const startWidth = node.attrs.width || imgRef.current.naturalWidth;
        const startHeight = node.attrs.height || imgRef.current.naturalHeight;
        const aspectRatio = startWidth / startHeight;
Яков's avatar
update    
Яков committed
282
283
284
285
286
287

        const getClientX = (e) => e.touches ? e.touches[0].clientX : e.clientX;
        const getClientY = (e) => e.touches ? e.touches[0].clientY : e.clientY;

        const startX = getClientX(e);
        const startY = getClientY(e);
Яков's avatar
Яков committed
288
        const { width: initialEditorWidth, availableSpace: initialAvailableSpace } = getEditorDimensions();
289

Яков's avatar
update    
Яков committed
290
291
        const onMove = (e) => {
            if (e.cancelable) e.preventDefault();
Яков's avatar
Яков committed
292
293
294
            requestAnimationFrame(() => {
                const maxWidth = node.attrs.align === 'center' ? initialEditorWidth : initialAvailableSpace;

Яков's avatar
update    
Яков committed
295
296
                const deltaX = getClientX(e) - startX;
                const deltaY = getClientY(e) - startY;
Яков's avatar
Яков committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313

                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);
                    }
314
                } else {
Яков's avatar
Яков committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
                    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);
                    }
331
332
                }

Яков's avatar
Яков committed
333
334
                safeUpdateAttributes({ width: newWidth, height: newHeight });
            });
yakoff94's avatar
yakoff94 committed
335
336
        };

Яков's avatar
update    
Яков committed
337
338
339
340
341
        const onEnd = () => {
            window.removeEventListener('mousemove', onMove);
            window.removeEventListener('mouseup', onEnd);
            window.removeEventListener('touchmove', onMove);
            window.removeEventListener('touchend', onEnd);
Яков's avatar
update    
Яков committed
342
            setIsResizing(false);
Яков's avatar
update    
Яков committed
343
344
345
346
347
348
349
350
            try {
                const pos = getPos?.()
                if (typeof pos === 'number') {
                    editor.commands.setNodeSelection(pos)
                }
            } catch (e) {
                console.warn('getPos() failed:', e)
            }
Яков's avatar
fix    
Яков committed
351
            editor.commands.focus();
yakoff94's avatar
yakoff94 committed
352
353
        };

Яков's avatar
update    
Яков committed
354
355
356
357
        window.addEventListener('mousemove', onMove);
        window.addEventListener('mouseup', onEnd);
        window.addEventListener('touchmove', onMove, { passive: false });
        window.addEventListener('touchend', onEnd);
358
    };
yakoff94's avatar
yakoff94 committed
359

Яков's avatar
fix    
Яков committed
360
    // Изменение выравнивания с автоматическим масштабированием
361
    const handleAlign = (align) => {
Яков's avatar
update    
Яков committed
362
        safeUpdateAttributes({ align });
Яков's avatar
Яков committed
363
        setTimeout(() => {
Яков's avatar
update    
Яков committed
364
365
366
367
368
369
370
371
372
            safeUpdateAttributes({ align });
            try {
                const pos = getPos?.()
                if (typeof pos === 'number') {
                    editor.commands.setNodeSelection(pos)
                }
            } catch (e) {
                console.warn('getPos() failed:', e)
            }
Яков's avatar
Яков committed
373
        }, 50);
374
375
    };

Яков's avatar
Яков committed
376
377
378
379
380
    // Внешняя обёртка (NodeViewWrapper): управляет float/block-layout и отступами
    const getOuterStyle = () => {
        const { align, wrap, width } = node.attrs;
        const w = width ? `${width}px` : 'auto';
        const sharedMargin = { marginTop: '0.5rem', marginBottom: '0.5rem' };
Яков's avatar
update    
Яков committed
381

Яков's avatar
Яков committed
382
383
384
385
386
387
388
        if (align === 'center') {
            return { ...sharedMargin, display: 'block', lineHeight: 0 };
        }
        if (!wrap) {
            // no-wrap: float:left + width:100% — занимает всю строку, текст не может встать рядом.
            // Используем float (а не display:block) чтобы layout-алгоритм был одинаковым
            // с wrap=true и не было прыжка при переключении обтекания.
Яков's avatar
update    
Яков committed
389
            return {
Яков's avatar
Яков committed
390
391
392
393
394
395
                ...sharedMargin, lineHeight: 0,
                display: 'inline-block',
                float: 'left',
                clear: 'both',
                width: '100%',
                ...(align === 'right' ? { textAlign: 'right' } : { textAlign: 'left' }),
Яков's avatar
update    
Яков committed
396
397
            };
        }
Яков's avatar
Яков committed
398
        // wrap: true — узкий float с шириной картинки, текст обтекает
Яков's avatar
update    
Яков committed
399
        return {
Яков's avatar
Яков committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
            ...sharedMargin, lineHeight: 0,
            display: 'inline-block',
            float: align === 'left' ? 'left' : 'right',
            ...(align === 'left' ? { marginRight: '1rem' } : { marginLeft: '1rem' }),
            width: w, maxWidth: '100%',
        };
    };

    // Внутренний контейнер: всегда inline-block — надёжно получает высоту от дочернего img
    const getInnerStyle = () => {
        const { align, width } = node.attrs;
        const w = width ? `${width}px` : 'auto';
        const base = {
            position: 'relative',
            display: 'inline-block',
            verticalAlign: 'top',
            lineHeight: 0,
            outline: (selected || isResizing) ? `1px dashed ${BORDER_COLOR}` : 'none',
            width: w,
            maxWidth: '100%',
Яков's avatar
update    
Яков committed
420
        };
Яков's avatar
Яков committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        if (align === 'center') {
            return { ...base, display: 'block', marginLeft: 'auto', marginRight: 'auto',
                width: width ? `${width}px` : 'fit-content' };
        }
        return base;
    };

    const handleNodeClick = (e) => {
        e.stopPropagation();
        try {
            const pos = getPos?.();
            if (typeof pos === 'number') editor.commands.setNodeSelection(pos);
        } catch (err) {
            console.warn('getPos() failed:', err);
        }
Яков's avatar
update    
Яков committed
436
    };
yakoff94's avatar
yakoff94 committed
437

Яков's avatar
fix    
Яков committed
438
    // Стили для самого изображения
439
440
    const getImageStyle = () => ({
        width: node.attrs.width ? `${node.attrs.width}px` : 'auto',
Яков's avatar
fix    
Яков committed
441
        height: 'auto',
442
443
444
445
        maxWidth: '100%',
        display: 'block',
        cursor: 'default',
        userSelect: 'none',
Яков's avatar
Яков committed
446
        margin: node.attrs.align === 'center' ? '0 auto' : '0',
Яков's avatar
update    
Яков committed
447
        verticalAlign: node.attrs.align === 'text' ? 'middle' : 'top',
Яков's avatar
fix    
Яков committed
448
        objectFit: 'contain'
449
450
    });

Яков's avatar
Яков committed
451
452
453
    // Inner content shared between both rendering paths
    const imageContent = (
        <>
yakoff94's avatar
yakoff94 committed
454
            <img
455
456
                {...node.attrs}
                ref={imgRef}
Яков's avatar
update    
Яков committed
457
                draggable={true}
458
                style={getImageStyle()}
yakoff94's avatar
yakoff94 committed
459
            />
Яков's avatar
Яков committed
460
            {node.attrs.frontAlt?.length > 0 && (
Яков's avatar
update    
Яков committed
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
                <div
                    style={{
                        backgroundColor: '#FDE674',
                        borderRadius: '35px',
                        padding: '5px 25px',
                        textAlign: 'center',
                        color: '#000000D9',
                        position: 'absolute',
                        left: '50%',
                        transform: 'translateX(-50%)',
                        fontSize: '12px',
                        lineHeight: '16px',
                        letterSpacing: '2%',
                        fontWeight: '500',
                        bottom: '10px',
                        whiteSpace: 'pre-line'
                    }}
                >{node.attrs.frontAlt}</div>
Яков's avatar
Яков committed
479
            )}
Яков's avatar
update    
Яков committed
480
481
482
            <Button
                size="default"
                shape={'circle'}
Яков's avatar
update    
Яков committed
483
                type={node.attrs.alt?.length > 0 || node.attrs.frontAlt?.length ? 'primary' : 'default'}
Яков's avatar
update    
Яков committed
484
485
486
                onClick={(e) => {
                    e.stopPropagation();
                    setTempAlt(node.attrs.alt || '');
Яков's avatar
update    
Яков committed
487
                    setTempFrontAlt(node.attrs.frontAlt || '');
Яков's avatar
update    
Яков committed
488
489
                    setAltModalVisible(true);
                }}
Яков's avatar
Яков committed
490
                style={{ position: 'absolute', top: 4, right: '30px', zIndex: 15 }}
Яков's avatar
update    
Яков committed
491
492
493
494
495
496
497
498
499
            >
                <FontSizeOutlined />
            </Button>
            {selected && (
                <Button
                    type="text"
                    danger
                    size="small"
                    onClick={(e) => {
Яков's avatar
Яков committed
500
501
                        e.stopPropagation();
                        const pos = getPos?.();
Яков's avatar
update    
Яков committed
502
503
504
                        if (typeof pos === 'number') {
                            editor.view.dispatch(
                                editor.view.state.tr.delete(pos, pos + node.nodeSize)
Яков's avatar
Яков committed
505
                            );
Яков's avatar
update    
Яков committed
506
507
508
                        }
                    }}
                    style={{
Яков's avatar
Яков committed
509
510
511
512
                        position: 'absolute', top: 4, right: 4, zIndex: 30,
                        backgroundColor: 'white', border: '1px solid #d9d9d9',
                        borderRadius: '50%', width: 20, height: 20,
                        fontSize: 12, lineHeight: 1, padding: '0px 0px 2px 0px', cursor: 'pointer'
Яков's avatar
update    
Яков committed
513
                    }}
Яков's avatar
Яков committed
514
                >×</Button>
Яков's avatar
update    
Яков committed
515
            )}
Яков's avatar
update    
Яков committed
516
            {(selected || isResizing) && (
517
518
519
520
521
                <Fragment>
                    {['nw', 'ne', 'sw', 'se'].map(dir => (
                        <div
                            key={dir}
                            onMouseDown={handleResizeStart(dir)}
Яков's avatar
update    
Яков committed
522
                            onTouchStart={handleResizeStart(dir)}
523
524
                            style={{
                                position: 'absolute',
Яков's avatar
Яков committed
525
                                width: 12, height: 12,
526
527
528
529
                                backgroundColor: BORDER_COLOR,
                                border: '1px solid white',
                                [dir[0] === 'n' ? 'top' : 'bottom']: -6,
                                [dir[1] === 'w' ? 'left' : 'right']: node.attrs.align === 'center' ? '50%' : -6,
Яков's avatar
Яков committed
530
531
                                transform: node.attrs.align === 'center'
                                    ? `translateX(${dir[1] === 'w' ? '-100%' : '0%'})` : 'none',
532
533
534
535
                                cursor: `${dir}-resize`,
                                zIndex: 10
                            }}
                        />
yakoff94's avatar
yakoff94 committed
536
                    ))}
Яков's avatar
Яков committed
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
                    <div style={{
                        position: 'absolute', top: -36, 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', alignItems: 'center', gap: 2, whiteSpace: 'nowrap',
                    }}>
                        {ALIGN_OPTIONS.map(a => (
                            <button
                                type="button"
                                key={a}
                                title={a === 'left' ? 'По левому краю' : a === 'center' ? 'По центру' : 'По правому краю'}
                                onClick={() => handleAlign(a)}
                                style={{
                                    padding: '4px 6px',
                                    background: node.attrs.align === a ? '#e6f7ff' : 'transparent',
                                    border: `1px solid ${node.attrs.align === a ? BORDER_COLOR : '#d9d9d9'}`,
                                    borderRadius: 2, cursor: 'pointer', display: 'flex', alignItems: 'center',
                                }}
                            >
                                {a === 'left' && (
                                    <svg width="16" height="14" viewBox="0 0 16 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <rect x="0" y="0"  width="16" height="2" rx="1" fill="currentColor"/>
                                        <rect x="0" y="4"  width="10" height="2" rx="1" fill="currentColor"/>
                                        <rect x="0" y="8"  width="16" height="2" rx="1" fill="currentColor"/>
                                        <rect x="0" y="12" width="10" height="2" rx="1" fill="currentColor"/>
                                    </svg>
                                )}
                                {a === 'center' && (
                                    <svg width="16" height="14" viewBox="0 0 16 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <rect x="0" y="0"  width="16" height="2" rx="1" fill="currentColor"/>
                                        <rect x="3" y="4"  width="10" height="2" rx="1" fill="currentColor"/>
                                        <rect x="0" y="8"  width="16" height="2" rx="1" fill="currentColor"/>
                                        <rect x="3" y="12" width="10" height="2" rx="1" fill="currentColor"/>
                                    </svg>
                                )}
                                {a === 'right' && (
                                    <svg width="16" height="14" viewBox="0 0 16 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <rect x="0" y="0"  width="16" height="2" rx="1" fill="currentColor"/>
                                        <rect x="6" y="4"  width="10" height="2" rx="1" fill="currentColor"/>
                                        <rect x="0" y="8"  width="16" height="2" rx="1" fill="currentColor"/>
                                        <rect x="6" y="12" width="10" height="2" rx="1" fill="currentColor"/>
                                    </svg>
                                )}
                            </button>
                        ))}
                        {node.attrs.align !== 'center' && (
                            <>
                                <div style={{ width: 1, background: '#d9d9d9', alignSelf: 'stretch', margin: '0 2px' }} />
587
                                <button
Яков's avatar
update    
Яков committed
588
                                    type="button"
Яков's avatar
Яков committed
589
590
591
592
593
594
595
596
597
598
599
                                    title={node.attrs.wrap ? 'Обтекание включено' : 'Обтекание выключено'}
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        safeUpdateAttributes({ wrap: !node.attrs.wrap });
                                        requestAnimationFrame(() => {
                                            try {
                                                const pos = getPos?.();
                                                if (typeof pos === 'number') editor.commands.setNodeSelection(pos);
                                            } catch {}
                                        });
                                    }}
600
                                    style={{
Яков's avatar
Яков committed
601
602
603
604
605
                                        padding: '4px 6px',
                                        background: node.attrs.wrap ? '#e6f7ff' : 'transparent',
                                        border: `1px solid ${node.attrs.wrap ? BORDER_COLOR : '#d9d9d9'}`,
                                        borderRadius: 2, cursor: 'pointer', fontSize: 11,
                                        display: 'flex', alignItems: 'center', gap: 3,
606
607
                                    }}
                                >
Яков's avatar
Яков committed
608
609
610
611
612
613
614
615
                                    <svg width="16" height="14" viewBox="0 0 16 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <rect x="0" y="0" width="7" height="7" rx="1" fill="currentColor" opacity="0.5"/>
                                        <rect x="9" y="0"  width="7" height="2" rx="1" fill="currentColor"/>
                                        <rect x="9" y="4"  width="5" height="2" rx="1" fill="currentColor"/>
                                        <rect x="0" y="9"  width="16" height="2" rx="1" fill="currentColor"/>
                                        <rect x="0" y="12" width="12" height="2" rx="1" fill="currentColor"/>
                                    </svg>
                                    Обтекание
616
                                </button>
Яков's avatar
Яков committed
617
618
619
                            </>
                        )}
                    </div>
620
                </Fragment>
yakoff94's avatar
yakoff94 committed
621
            )}
Яков's avatar
update    
Яков committed
622
            <Modal
Яков's avatar
update    
Яков committed
623
                title="Текст на картинке"
Яков's avatar
update    
Яков committed
624
                open={altModalVisible}
Яков's avatar
Яков committed
625
                onOk={() => { updateAttributes({ alt: tempAlt, frontAlt: tempFrontAlt }); setAltModalVisible(false); }}
Яков's avatar
update    
Яков committed
626
627
628
629
                onCancel={() => setAltModalVisible(false)}
                okText="Применить"
                cancelText="Отмена"
            >
Яков's avatar
update    
Яков committed
630
                <div style={{marginBottom: '5px'}}><Text>Лицевая сторона</Text></div>
Яков's avatar
Яков committed
631
                <TextArea value={tempFrontAlt} onChange={(e) => setTempFrontAlt(e.target.value)} rows={4} placeholder="Введите текст" />
Яков's avatar
update    
Яков committed
632
                <div style={{marginTop: '15px', marginBottom: '5px'}}><Text>Обратная сторона</Text></div>
Яков's avatar
Яков committed
633
                <TextArea value={tempAlt} onChange={(e) => setTempAlt(e.target.value)} rows={4} placeholder="Введите текст" />
Яков's avatar
update    
Яков committed
634
            </Modal>
Яков's avatar
Яков committed
635
636
637
638
639
640
641
642
643
644
        </>
    );

    // Единая структура NodeViewWrapper > div > content — img всегда на одной глубине,
    // поэтому при смене выравнивания React не размонтирует img и не перезагружает его.
    return (
        <NodeViewWrapper as="div" style={getOuterStyle()} contentEditable={false} data-image-wrapper>
            <div ref={wrapperRef} style={getInnerStyle()} onClick={handleNodeClick}>
                {imageContent}
            </div>
yakoff94's avatar
yakoff94 committed
645
646
647
648
649
650
651
652
        </NodeViewWrapper>
    );
};

const ResizableImageExtension = TipTapImage.extend({
    addAttributes() {
        return {
            ...this.parent?.(),
Яков's avatar
fix    
Яков committed
653
            src: { default: null },
Яков's avatar
update    
Яков committed
654
655
656
657
658
659
660
661
662
663
664
665
            alt: {
                default: null,
                parseHTML: element => {
                    const raw = element.getAttribute('alt')
                    return raw?.replace(/&#10;/g, '\n') || null
                },
                renderHTML: attributes => {
                    return attributes.alt
                        ? { alt: attributes.alt.replace(/\n/g, '&#10;') }
                        : {}
                }
            },
Яков's avatar
update    
Яков committed
666
667
668
669
670
671
672
673
674
675
676
677
            frontAlt: {
                default: null,
                parseHTML: element => {
                    const raw = element.getAttribute('frontAlt')
                    return raw?.replace(/&#10;/g, '\n') || null
                },
                renderHTML: attributes => {
                    return attributes.frontAlt
                        ? { frontAlt: attributes.frontAlt.replace(/\n/g, '&#10;') }
                        : {}
                }
            },
Яков's avatar
fix    
Яков committed
678
            title: { default: null },
679
680
            width: {
                default: null,
Яков's avatar
fix    
Яков committed
681
                parseHTML: element => parseInt(element.getAttribute('width'), 10) || null,
682
683
684
685
                renderHTML: attributes => attributes.width ? { width: attributes.width } : {}
            },
            height: {
                default: null,
Яков's avatar
fix    
Яков committed
686
                parseHTML: element => parseInt(element.getAttribute('height'), 10) || null,
687
688
689
690
691
692
                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
693
            },
Яков's avatar
Яков committed
694
695
696
697
698
            wrap: {
                default: false,
                parseHTML: element => element.getAttribute('data-wrap') === 'true',
                renderHTML: attributes => attributes.wrap ? { 'data-wrap': 'true' } : {}
            },
Яков's avatar
fix    
Яков committed
699
700
701
702
            'data-node-id': {
                default: null,
                parseHTML: element => element.getAttribute('data-node-id'),
                renderHTML: attributes => ({ 'data-node-id': attributes['data-node-id'] })
703
            }
yakoff94's avatar
yakoff94 committed
704
705
        };
    },
Яков's avatar
update    
Яков committed
706
707
708
709
710
711
712
713
714
715
716
    renderHTML({ node, HTMLAttributes }) {
        const {
            src,
            alt = '',
            title = '',
            width,
            height,
            ...rest
        } = HTMLAttributes;

        const align = node.attrs.align || 'left';
Яков's avatar
Яков committed
717
        const wrap  = node.attrs.wrap  || false;
Яков's avatar
update    
Яков committed
718
719
720
721
722
723

        const style = [];

        if (align === 'center') {
            style.push('display: block', 'margin-left: auto', 'margin-right: auto');
        } else if (align === 'left') {
Яков's avatar
Яков committed
724
725
726
            wrap
                ? style.push('float: left', 'margin-right: 1rem')
                : style.push('display: block', 'margin-right: auto');
Яков's avatar
update    
Яков committed
727
        } else if (align === 'right') {
Яков's avatar
Яков committed
728
729
730
            wrap
                ? style.push('float: right', 'margin-left: 1rem')
                : style.push('display: block', 'margin-left: auto');
Яков's avatar
update    
Яков committed
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
        }

        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,
            }
        ];
    },
750

yakoff94's avatar
yakoff94 committed
751
752
    addNodeView() {
        return ReactNodeViewRenderer(ResizableImageTemplate);
Яков's avatar
fix    
Яков committed
753
754
755
756
757
758
759
760
    },

    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' }),
        };
761
762
763
764
765
    }
}).configure({
    inline: true,
    group: 'inline',
    draggable: true,
Яков's avatar
fix    
Яков committed
766
    selectable: true
767
});
yakoff94's avatar
yakoff94 committed
768
769

export default ResizableImageExtension;