QEditor.jsx 46.7 KB
Newer Older
Рамис's avatar
Рамис committed
1
import React, { Fragment, useEffect, useState, useRef } from 'react'
Рамис's avatar
Рамис committed
2
import './index.scss'
Рамис's avatar
Рамис committed
3
4
5
// import EditorModal from "./components/EditorModal"
// import Uploader from "./components/Uploader"

Рамис's avatar
Рамис committed
6
import { useEditor, EditorContent, BubbleMenu } from '@tiptap/react'
Рамис's avatar
Рамис committed
7
8
9
10
11
12
import StarterKit from '@tiptap/starter-kit'
import Underline from '@tiptap/extension-underline'
import Table from '@tiptap/extension-table'
import TableCell from '@tiptap/extension-table-cell'
import TableRow from '@tiptap/extension-table-row'
import TableHeader from '@tiptap/extension-table-header'
Рамис's avatar
bug fix    
Рамис committed
13
import Focus from '@tiptap/extension-focus'
Рамис's avatar
Рамис committed
14
// import Link from '@tiptap/extension-link'
Рамис's avatar
Рамис committed
15
16
import Image from '@tiptap/extension-image'
import TextAlign from '@tiptap/extension-text-align';
Рамис's avatar
Рамис committed
17
18
19
import { Color } from '@tiptap/extension-color';
import Highlight from '@tiptap/extension-highlight';
import TextStyle from '@tiptap/extension-text-style';
Nikita's avatar
Nikita committed
20
21
import Superscript from "@tiptap/extension-superscript";
import Subscript from "@tiptap/extension-subscript";
Рамис's avatar
Рамис committed
22
23

import ToolBar from "./components/ToolBar"
Рамис's avatar
fix bug    
Рамис committed
24
25
import EditorModal from "./components/EditorModal"
import Uploader from "./components/Uploader"
Рамис's avatar
Рамис committed
26
27
import Video from './extensions/Video'
import Iframe from './extensions/Iframe'
Рамис's avatar
Рамис committed
28
import CustomLink from './extensions/CustomLink'
Sergey's avatar
Sergey committed
29
import DragAndDrop from "./extensions/DragAndDrop";
Sergey's avatar
Sergey committed
30
31
import { useReactMediaRecorder } from "react-media-recorder";
import axios from "axios";
32
import ReactStopwatch from 'react-stopwatch';
Sergey's avatar
Sergey committed
33
import Audio from "./extensions/Audio";
Рамис's avatar
Рамис committed
34

Яков's avatar
Яков committed
35
36
import { isMobile } from 'react-device-detect';

Nikita's avatar
Nikita committed
37
const initialBubbleItems = ['bold', 'italic', 'underline', 'strike', 'superscript', 'subscript', '|', 'colorText', 'highlight'];
Рамис's avatar
Рамис committed
38

Яков's avatar
Яков committed
39
40
41
42
43
44
45
const QEditor = ({
    value,
    onChange = () => {},
    style,
    uploadOptions = {url: "", errorMessage: ""},
    toolsOptions = {type: 'all'}
}) => {
Sergey's avatar
Sergey committed
46
47
    global.uploadUrl = uploadOptions.url;

Рамис's avatar
Рамис committed
48
49
50
51
52
53
54
    const [innerModalType, setInnerModalType] = useState(null);
    const [embedContent, setEmbedContent] = useState('');
    const [uploaderUid, setUploaderUid] = useState('uid' + new Date());
    const [uploadedPaths, setUploadedPaths] = useState([]);
    const [modalIsOpen, setModalIsOpen] = useState(false);
    const [modalTitle, setModalTitle] = useState('');
    const [bubbleItems, setBubbleItems] = useState(initialBubbleItems);
Рамис's avatar
Рамис committed
55
    const [colorsSelected, setColorsSelected] = useState(null);
Рамис's avatar
Рамис committed
56
57
    const [focusFromTo, setFocusFromTo] = useState(null);
    const [oldFocusFromTo, setOldFocusFromTo] = useState(null);
Sergey's avatar
Sergey committed
58
    const [isUploading, setIsUploading] = useState(false);
Яков's avatar
Яков committed
59
    const [recordType, setRecordType] = useState({video: true})
Sergey's avatar
Sergey committed
60

Рамис's avatar
Рамис committed
61
62
63
64
    const getRgb = (hex) => {
        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? `rgb(${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)})` : null;
    }
Яков's avatar
Яков committed
65
66
67
68
69
70
71
72
73
74
75
    const {
        status,
        startRecording,
        stopRecording,
        mediaBlobUrl,
        previewStream,
        muteAudio,
        unMuteAudio,
        isAudioMuted,
        clearBlobUrl
    } = useReactMediaRecorder(recordType);
Sergey's avatar
Sergey committed
76
77
78
79
80
81
82
83

    const videoRef = useRef(null);

    useEffect(() => {
        if (videoRef.current && previewStream) {
            videoRef.current.srcObject = previewStream;
        }
    }, [previewStream]);
Рамис's avatar
Рамис committed
84

Рамис's avatar
Рамис committed
85
    useEffect(() => {
Яков's avatar
Яков committed
86
        if (focusFromTo !== oldFocusFromTo) {
Рамис's avatar
Рамис committed
87
88
89
90
91
            setColorsSelected(null)
            setOldFocusFromTo(focusFromTo);
        }
    }, [focusFromTo])

Рамис's avatar
Рамис committed
92
93
94
95
    const modalOpener = (type, title) => {
        setModalTitle(title);
        setInnerModalType(type);
        setModalIsOpen(true);
Рамис's avatar
Рамис committed
96
    }
Рамис's avatar
Рамис committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
    const colors = {
        color: [
            'none',
            '#8a8a8a',
            '#afafaf',
            '#44d724',
            '#0bd9b2',
            '#4fb7ff',
            '#226aff',
            '#b153e5',
            '#f54f8e',
            '#f34c37',
            '#ee7027',
            '#d27303',
            '#ffd102'
        ],
        highlight: [
            'none',
            '#9B9B9B',
            '#CCCCCC',
            '#9ee191',
            '#43e7bf',
            '#4fb7ff',
            '#6d9ef5',
            '#cd92e8',
            '#f597bc',
            '#fa9084',
            '#ef9558',
            '#dea75b',
            '#ffe672'
        ]
    };
Рамис's avatar
Рамис committed
129

Рамис's avatar
Рамис committed
130
    const toolsLib = {
Рамис's avatar
Рамис committed
131
132
133
134
135
136
137
138
139
140
141
142
143
        link: {
            title: 'Вставить ссылку',
            onClick: () => {
                const previousUrl = editor.getAttributes('link').href
                const url = window.prompt('Введите URL', previousUrl);

                // cancelled
                if (url === null) {
                    return
                }

                // empty
                if (url === '') {
Яков's avatar
Яков committed
144
                    editor.chain().focus().extendMarkRange('link').unsetLink().run();
Рамис's avatar
Рамис committed
145
146
147
148
149

                    return
                }

                // update link
Яков's avatar
Яков committed
150
                editor.chain().focus().extendMarkRange('link').setLink({href: url, target: '_blank'}).run();
Рамис's avatar
Рамис committed
151
152
            }
        },
Рамис's avatar
Рамис committed
153
154
155
156
        file: {
            title: 'Прикрепить файл',
            onClick: () => modalOpener('file', 'Прикрепить файл')
        },
Рамис's avatar
Рамис committed
157
158
159
160
161
162
163
164
        video: {
            title: 'Загрузить видео',
            onClick: () => modalOpener('video', 'Загрузить видео')
        },
        iframe: {
            title: 'Видео по ссылке',
            onClick: () => modalOpener('iframe', 'Видео по ссылке')
        },
Яков's avatar
Яков committed
165
166
167
168
        iframe_custom: {
            title: 'Вставить iframe',
            onClick: () => modalOpener('iframe_custom', 'Вставить iframe')
        },
Яков's avatar
Яков committed
169
170
171
172
        iframe_pptx: {
            title: 'Вставить презентацию pptx',
            onClick: () => modalOpener('iframe_pptx', 'Вставить презентацию pptx')
        },
Рамис's avatar
Рамис committed
173
174
175
176
177
178
        image: {
            title: 'Загрузить изображение',
            onClick: () => modalOpener('image', 'Загрузить изображение')
        },
        h2: {
            title: 'Заголовок 2',
Яков's avatar
Яков committed
179
            onClick: () => editor.chain().focus().toggleHeading({level: 2}).run()
Рамис's avatar
Рамис committed
180
181
182
        },
        h3: {
            title: 'Заголовок 3',
Яков's avatar
Яков committed
183
            onClick: () => editor.chain().focus().toggleHeading({level: 3}).run()
Рамис's avatar
Рамис committed
184
185
186
        },
        h4: {
            title: 'Заголовок 4',
Яков's avatar
Яков committed
187
            onClick: () => editor.chain().focus().toggleHeading({level: 4}).run()
Рамис's avatar
Рамис committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
        },
        paragraph: {
            title: 'Обычный',
            onClick: () => editor.chain().focus().setParagraph().run()
        },
        bold: {
            title: 'Жирный',
            onClick: () => editor.chain().focus().toggleBold().run()
        },
        italic: {
            title: 'Курсив',
            onClick: () => editor.chain().focus().toggleItalic().run()
        },
        underline: {
            title: 'Подчеркнутый',
            onClick: () => editor.chain().focus().toggleUnderline().run()
        },
        strike: {
            title: 'Зачеркнутый',
            onClick: () => editor.chain().focus().toggleStrike().run()
        },
Nikita's avatar
Nikita committed
209
210
211
212
213
214
215
216
        superscript: {
            title: 'Надстрочный символ',
            onClick: () => editor.chain().focus().toggleSuperscript().run()
        },
        subscript: {
            title: 'Подстрочный символ',
            onClick: () => editor.chain().focus().toggleSubscript().run()
        },
Рамис's avatar
Рамис committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
        codeBlock: {
            title: 'Код',
            onClick: () => editor.chain().focus().toggleCodeBlock().run()
        },
        clearMarks: {
            title: 'Очистить форматирование',
            onClick: () => editor.chain().focus().unsetAllMarks().run()
        },
        bulletList: {
            title: 'Маркированный список',
            onClick: () => editor.chain().focus().toggleBulletList().run()
        },
        orderedList: {
            title: 'Нумированный список',
            onClick: () => editor.chain().focus().toggleOrderedList().run()
        },
        blockquote: {
            title: 'Цитата',
            onClick: () => editor.chain().focus().toggleBlockquote().run()
        },
        hardBreak: {
            title: 'Перенос строки',
            onClick: () => editor.chain().focus().setHardBreak().run()
        },
        hr: {
            title: 'Горизонтальная линия',
            onClick: () => editor.chain().focus().setHorizontalRule().run()
        },
        undo: {
            title: 'Действие назад',
            onClick: () => editor.chain().focus().undo().run()
        },
        redo: {
            title: 'Действие вперед',
            onClick: () => editor.chain().focus().redo().run()
        },
        alignLeft: {
            title: 'По левому краю',
Рамис's avatar
Рамис committed
255
256
257
258
            onClick: () => {
                editor.commands.setTextAlign('left');
                editor.chain().focus();
            }
Рамис's avatar
Рамис committed
259
260
261
        },
        alignCenter: {
            title: 'По центру',
Рамис's avatar
Рамис committed
262
263
264
265
            onClick: () => {
                editor.commands.setTextAlign('center')
                editor.chain().focus();
            }
Рамис's avatar
Рамис committed
266
267
268
        },
        alignRight: {
            title: 'По правому краю',
Рамис's avatar
Рамис committed
269
270
271
272
            onClick: () => {
                editor.commands.setTextAlign('right');
                editor.chain().focus();
            }
Рамис's avatar
Рамис committed
273
274
275
        },
        insertTable: {
            title: 'Вставить таблицу',
Яков's avatar
Яков committed
276
            onClick: () => editor.chain().focus().insertTable({rows: 2, cols: 2}).run()
Рамис's avatar
Рамис committed
277
278
279
280
281
282
283
284
285
286
287
        },
        deleteTable: {
            title: 'Удалить таблицу',
            onClick: () => editor.chain().focus().deleteTable().run()
        },
        addRowBefore: {
            title: 'Вставить строку перед',
            onClick: () => editor.chain().focus().addRowBefore().run()
        },
        addRowAfter: {
            title: 'Вставить строку после',
Рамис's avatar
Рамис committed
288
289
290
291
292
            onClick: () => editor.chain().focus().addRowAfter().run()
        },
        deleteRow: {
            title: 'Удалить строку',
            onClick: () => editor.chain().focus().deleteRow().run()
Рамис's avatar
Рамис committed
293
294
295
296
297
298
299
300
        },
        addColumnBefore: {
            title: 'Вставить столбец перед',
            onClick: () => editor.chain().focus().addColumnBefore().run()
        },
        addColumnAfter: {
            title: 'Вставить столбец после',
            onClick: () => editor.chain().focus().addColumnAfter().run()
Рамис's avatar
Рамис committed
301
        },
Рамис's avatar
Рамис committed
302
303
304
305
306
307
308
309
310
311
312
        deleteColumn: {
            title: 'Удалить столбец',
            onClick: () => editor.chain().focus().deleteColumn().run()
        },
        mergeOrSplit: {
            title: 'Объединить/разъединить ячейки',
            onClick: () => editor.chain().focus().mergeOrSplit().run()
        },
        toggleHeaderCell: {
            title: 'Добавить/удалить заголовок',
            onClick: () => editor.chain().focus().toggleHeaderCell().run()
Рамис's avatar
Рамис committed
313
314
315
        },
        colorText: {
            title: 'Цвет текста',
Рамис's avatar
Рамис committed
316
317
318
319
            onClick: () => {
                setColorsSelected('color')
                editor.chain().focus();
            }
Рамис's avatar
Рамис committed
320
321
322
323
324
        },
        highlight: {
            title: 'Цвет фона',
            onClick: () => setColorsSelected('highlight')
        },
325
326
327
328
        voicemessage: {
            title: 'Записать голосовое сообщение',
            onClick: () => {
                setRecordType({audio: true})
Sergey's avatar
Sergey committed
329
                clearBlobUrl()
Sergey's avatar
Sergey committed
330
                modalOpener('voicemessage', 'Записать голосовое сообщение')
331
332
333
334
335
336
            }
        },
        webcamera: {
            title: 'Записать с камеры',
            onClick: () => {
                setRecordType({video: true})
Sergey's avatar
Sergey committed
337
                clearBlobUrl()
Sergey's avatar
Sergey committed
338
                modalOpener('webcamera', 'Записать с камеры')
339
340
341
342
343
            }
        },
        screencust: {
            title: 'Записать экран',
            onClick: () => {
Яков's avatar
Яков committed
344
345
346
347
348
                if (isMobile) {
                    setRecordType({video: true})
                } else {
                    setRecordType({screen: true})
                }
Sergey's avatar
Sergey committed
349
                clearBlobUrl()
Sergey's avatar
Sergey committed
350
                modalOpener('screencust', 'Записать экран')
351
352
            }
        },
Рамис's avatar
Рамис committed
353
354
355
356
357
358
359
360
361
        // katex: {
        //     title: 'Вставить формулу',
        //     onClick: () => {
        //
        //         console.log(katex.renderToString(String.raw`c = \pm\sqrt{a^2 + b^2}`));
        //
        //         // editor.chain().focus().insertContent()
        //     }
        // }
Рамис's avatar
Рамис committed
362
363
    }

Рамис's avatar
Рамис committed
364
365
366
367
    const editor = useEditor({
        extensions: [
            StarterKit,
            Underline,
Рамис's avatar
Рамис committed
368
369
370
            Image.configure({
                inline: true
            }),
Рамис's avatar
Рамис committed
371
372
373
374
375
            // Link.configure({
            //     autolink: true,
            //     linkOnPaste: true,
            //     validate: (href)=> console.log(href),
            // }),
Рамис's avatar
Рамис committed
376
377
378
379
            Video,
            Iframe,
            Table.configure({
                resizable: true,
Рамис's avatar
bug fix    
Рамис committed
380
                allowTableNodeSelection: true
Рамис's avatar
Рамис committed
381
382
383
384
385
386
387
388
389
            }),
            TableRow,
            TableHeader,
            TableCell,
            BubbleMenu,
            TextAlign.configure({
                defaultAlignment: 'left',
                types: ['heading', 'paragraph'],
                alignments: ['left', 'center', 'right', 'justify'],
Рамис's avatar
Рамис committed
390
391
392
393
394
395
396
            }),
            TextStyle,
            Color.configure({
                types: ['textStyle'],
            }),
            Highlight.configure({
                multicolor: true
Рамис's avatar
Рамис committed
397
            }),
Рамис's avatar
Рамис committed
398
399
400
            CustomLink.configure({
                linkOnPaste: false,
                openOnClick: false
Рамис's avatar
bug fix    
Рамис committed
401
402
403
404
            }),
            Focus.configure({
                className: 'atma-editor-focused',
                mode: "all"
Sergey's avatar
Sergey committed
405
            }),
Sergey's avatar
Sergey committed
406
407
408
            DragAndDrop.configure({
                linkUpload: uploadOptions.url
            }),
Nikita's avatar
Nikita committed
409
410
411
            Audio,
            Superscript,
            Subscript
Рамис's avatar
Рамис committed
412
413
        ],
        content: value,
Рамис's avatar
bug fix    
Рамис committed
414
        onUpdate: ({editor}) => onChange(editor.getHTML()),
Яков's avatar
Яков committed
415
        onFocus: ({editor}) => {
Рамис's avatar
bug fix    
Рамис committed
416
417
            let wrap = editor.options.element.closest('.atma-editor-wrap');

Яков's avatar
Яков committed
418
            wrap.querySelectorAll('.atma-editor-toolbar-s').forEach(function (s) {
Рамис's avatar
Рамис committed
419
420
421
                s.classList.remove('show');
            });

Рамис's avatar
bug fix    
Рамис committed
422
        }
Рамис's avatar
Рамис committed
423
424
425
    })

    const buildActionsModal = (buttons = []) => {
Рамис's avatar
Рамис committed
426
427
428
429
430
431
432
433
        if (buttons.length === 0) {
            return null;
        }

        return (
            <div className={'atma-editor-modal-action'}>
                {
                    buttons.map((btn, i) => (
Яков's avatar
Яков committed
434
435
                        <button disabled={btn.disabled} type={'button'} key={'mAction' + i}
                                className={'atma-editor-btn' + btn.className}
Рамис's avatar
Рамис committed
436
437
438
439
440
441
442
                                onClick={btn.onClick}>{btn.title}</button>
                    ))
                }
            </div>
        )
    }

Яков's avatar
Яков committed
443
    const getUploader = ({accept = '*', ...o}) => {
Яков's avatar
Яков committed
444
445
        let url = uploadOptions.url,
            multiple = true;
Яков's avatar
Яков committed
446
447
        if (o.afterParams && o.afterParams.length > 0) {
            if (uploadOptions.url.indexOf('?') !== -1) {
Рамис's avatar
Рамис committed
448
                url = uploadOptions.url + '&' + o.afterParams.join('&');
Яков's avatar
Яков committed
449
            } else {
Рамис's avatar
Рамис committed
450
451
452
453
                url = uploadOptions.url + '?' + o.afterParams.join('&');
            }
        }

Яков's avatar
Яков committed
454
455
456
457
        if (typeof o.multiple !== 'undefined') {
            multiple = o.multiple;
        }

Рамис's avatar
Рамис committed
458
459
        return <Uploader
            key={uploaderUid}
Яков's avatar
Яков committed
460
461
462
            accept={accept}
            action={url}
            errorMessage={uploadOptions.errorMessage}
Рамис's avatar
Рамис committed
463
464
465
466
467
468
            onSuccess={(file) => {
                let _uploadedPaths = [...uploadedPaths];

                _uploadedPaths.push(file);
                setUploadedPaths(_uploadedPaths)
            }}
Яков's avatar
Яков committed
469
            onDelete={(deleteFile) => {
Рамис's avatar
Рамис committed
470
471
472
                let deleteIdx = null;
                let _uploadedPaths = [...uploadedPaths];

Яков's avatar
Яков committed
473
474
                _uploadedPaths.map((f, i) => {
                    if (f.uid === deleteFile.uid) {
Рамис's avatar
Рамис committed
475
476
477
478
479
480
                        deleteIdx = i;
                    }
                });
                _uploadedPaths.splice(deleteIdx, 1);
                setUploadedPaths(_uploadedPaths)
            }}
Яков's avatar
Яков committed
481
            multiple={multiple}
Яков's avatar
Яков committed
482
            modalType={innerModalType}
Рамис's avatar
Рамис committed
483
484
485
        />
    }

Sergey's avatar
Sergey committed
486
    const saveScreenCust = async (fileBlob) => {
487
488
489
490
491
492
493
494
495
        if (fileBlob) {
            setIsUploading(true)
            let blobData = await fetch(fileBlob).then((res) => res.blob());

            const data = new FormData();
            let file = new File([blobData], "name." + (recordType?.audio ? "mp3" : "webm"));
            data.append("file", file);

            const headers = {'Content-Type': 'multipart/form-data'};
Sergey's avatar
Sergey committed
496
497
498
499
500
501
502
503
504

            return new Promise(function (resolve) {
                axios.post(uploadOptions.url, data, {headers: headers}).then(response => {
                    if (response.data.state === "success") {
                        resolve(response.data)
                    }
                    setIsUploading(false)
                });
            })
505
        }
Sergey's avatar
Sergey committed
506
507
    };

Рамис's avatar
Рамис committed
508
509
510
    const getInnerModal = () => {
        switch (innerModalType) {
            case 'iframe':
Рамис's avatar
Рамис committed
511
512
                return (
                    <Fragment>
Яков's avatar
Яков committed
513
514
515
                        <input type="text" value={embedContent} placeholder={'https://'}
                               onInput={(e) => setEmbedContent(e.target.value)
                               }/>
Рамис's avatar
Рамис committed
516
517
518
                        <ul className={'atma-editor-soc-video'}>
                            <li className={'youtube'}/>
                            <li className={'vimeo'}/>
Рамис's avatar
Рамис committed
519
                            {/* <li className={'vk'}/> */}
Рамис's avatar
Рамис committed
520
                            <li className={'ok'}/>
Рамис's avatar
fix bug    
Рамис committed
521
                            <li className={'rutube'}/>
Рамис's avatar
Рамис committed
522
523
524
                        </ul>
                    </Fragment>
                )
Яков's avatar
Яков committed
525
526
527
            case 'iframe_custom':
                return (
                    <Fragment>
Яков's avatar
Яков committed
528
                        <textarea style={{width: '100%', height: '100%'}} rows={18} value={embedContent} placeholder={'<iframe></iframe>'}
Яков's avatar
Яков committed
529
530
531
532
                               onInput={(e) => setEmbedContent(e.target.value)}
                        />
                    </Fragment>
                )
Яков's avatar
Яков committed
533
534
535
536
            case 'iframe_pptx':
                return (
                    <Fragment>{getUploader({accept: 'application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.openxmlformats-officedocument.presentationml.presentation', afterParams: ['no_convert=1']})}</Fragment>
                )
Рамис's avatar
Рамис committed
537
            case 'video':
Рамис's avatar
Рамис committed
538
                return (
Яков's avatar
Яков committed
539
                    <Fragment>{getUploader({accept: 'video/*'})}</Fragment>
Рамис's avatar
Рамис committed
540
541
542
                )
            case 'image':
                return (
Яков's avatar
Яков committed
543
                    <Fragment>{getUploader({accept: 'image/*'})}</Fragment>
Рамис's avatar
Рамис committed
544
                )
Рамис's avatar
Рамис committed
545
            case 'file':
Рамис's avatar
Рамис committed
546
                return (
Яков's avatar
Яков committed
547
                    <Fragment>{getUploader({accept: '*', afterParams: ['no_convert=1']})}</Fragment>
Рамис's avatar
Рамис committed
548
                )
549
550
551
552
            case 'voicemessage':
                return (
                    <>
                        <Fragment>
Яков's avatar
Яков committed
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
                            {
                                isMobile &&
                                <>
                                    <div className={"webwrap"}>
                                        <div>Аудиозапись с мобильного устройства недоступна, <br/> запишите стандартными
                                            функциями устройства и воспользуйтесь кнопкой «Прикрепить файл»
                                        </div>
                                    </div>
                                </>
                            }
                            {
                                ! isMobile &&
                                <div className={"audio-player"}>
                                    <div className={"audio-player-start audio-player-margin"}>
                                        {
                                            status === 'recording' && ! mediaBlobUrl ?
                                                <div onClick={stopRecording}
                                                     className={"audio-player-center-recording"}/> :
                                                <div onClick={startRecording} className={"audio-player-center-start"}/>
                                        }
                                    </div>
                                    <div className={"audio-player-voice audio-player-margin"}/>
575
                                    {
Яков's avatar
Яков committed
576
577
578
579
580
581
582
583
584
585
586
587
                                        status === 'recording' && ! mediaBlobUrl ?
                                            <ReactStopwatch
                                                seconds={0}
                                                minutes={0}
                                                hours={0}
                                                render={({formatted}) => {
                                                    return (
                                                        <span
                                                            className={"audio-player-timer audio-player-margin"}>{formatted}</span>
                                                    )
                                                }}
                                            /> : <span className={"audio-player-timer audio-player-margin"}/>
588
589
                                    }
                                </div>
Яков's avatar
Яков committed
590
                            }
591
592
593
594
595
596
597
                        </Fragment>
                    </>
                )
            case 'screencust':
                return (
                    <>
                        <Fragment>
Яков's avatar
Яков committed
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
                            {
                                isMobile &&
                                <>
                                    <div className={"webwrap"}>
                                        <div>Запись экрана с мобильного устройства недоступна, <br/> запишите
                                            стандартными функциями устройства и воспользуйтесь кнопкой «Загрузить видео»
                                        </div>
                                    </div>
                                </>
                            }
                            {
                                ! isMobile &&
                                <>
                                    <div className={"webwrap"}>
                                        <div className={"webwrap-content"}>
                                            {
                                                mediaBlobUrl ?
                                                    <video className={"webwrap-video"} id={"id-video"}
                                                           src={mediaBlobUrl} controls/> : status === "recording" &&
                                                    <video className={"webwrap-video"} ref={videoRef}
                                                           src={previewStream} autoPlay controls={false}/>
                                            }
                                            {
                                                status === 'recording' && ! mediaBlobUrl ?
                                                    <ReactStopwatch
                                                        seconds={0}
                                                        minutes={0}
                                                        hours={0}
                                                        render={({formatted}) => {
                                                            return (
                                                                <span className={"webwrap-timer"}>
629
630
                                                    {formatted}
                                                </span>
Яков's avatar
Яков committed
631
632
633
634
635
636
637
638
639
640
641
642
                                                            )
                                                        }}
                                                    /> : <span className={"webwrap-timer"}>00:00:00</span>
                                            }
                                            {
                                                ! mediaBlobUrl &&
                                                <div className={"webwrap-start-border"}>
                                                    <button
                                                        onClick={status === 'recording' ? stopRecording : startRecording}
                                                        className={status === 'recording' ? "webwrap-record-center" : "webwrap-start-center"}/>
                                                </div>
                                            }
643
644
                                        </div>
                                    </div>
Яков's avatar
Яков committed
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
                                    <div className={"web-bottom-elements"}>
                                        {mediaBlobUrl &&
                                            <div onClick={clearBlobUrl} className={"web-button-wrap"}>
                                                <div className={"web-button-rerecord"}/>
                                                <span className={"web-button-rerecord-text"}>Перезаписать</span>
                                            </div>
                                        }
                                        {
                                            ! mediaBlobUrl &&
                                            <div className={"web-button-spacer"}/>
                                        }
                                        {
                                            ! mediaBlobUrl &&
                                            <div onClick={isAudioMuted ? unMuteAudio : muteAudio}
                                                 className={isAudioMuted ? "web-button-unmute" : "web-button-mute"}/>
                                        }
                                        <div className={"web-button-spacer"}/>
                                    </div>
                                </>
                            }
665
666
667
                        </Fragment>
                    </>
                )
Sergey's avatar
Sergey committed
668
669
670
            case 'webcamera':
                return (
                    <>
Яков's avatar
Яков committed
671
                        <Fragment>
672
                            {
Яков's avatar
Яков committed
673
674
675
676
677
678
679
680
                                isMobile &&
                                <>
                                    <div className={"webwrap"}>
                                        <div>Видеозапись с мобильного устройства недоступна, <br/> запишите стандартными
                                            функциями устройства и воспользуйтесь кнопкой «Загрузить видео»
                                        </div>
                                    </div>
                                </>
681
682
                            }
                            {
Яков's avatar
Яков committed
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
                                ! isMobile &&
                                <>
                                    <div className={"webwrap"}>
                                        <div className={"webwrap-content"}>
                                            {
                                                mediaBlobUrl ?
                                                    <video className={"webwrap-video"} id={"id-video"}
                                                           src={mediaBlobUrl}
                                                           controls/> : status === "recording" &&
                                                    <video className={"webwrap-video"} ref={videoRef}
                                                           src={previewStream}
                                                           autoPlay controls={false}/>
                                            }
                                            {
                                                status === 'recording' && ! mediaBlobUrl ?
                                                    <ReactStopwatch
                                                        seconds={0}
                                                        minutes={0}
                                                        hours={0}
                                                        render={({formatted}) => {
                                                            return (
                                                                <span className={"webwrap-timer"}>
                                                    {formatted}
                                                </span>
                                                            )
                                                        }}
                                                    /> : <span className={"webwrap-timer"}>00:00:00</span>
                                            }
                                            {
                                                ! mediaBlobUrl &&
                                                <div className={"webwrap-start-border"}>
                                                    <button
                                                        onClick={status === 'recording' ? stopRecording : startRecording}
                                                        className={status === 'recording' ? "webwrap-record-center" : "webwrap-start-center"}/>
                                                </div>
                                            }
                                        </div>
                                    </div>
                                    <div className={"web-bottom-elements"}>
                                        {mediaBlobUrl &&
                                            <div onClick={clearBlobUrl} className={"web-button-wrap"}>
                                                <div className={"web-button-rerecord"}/>
                                                <span className={"web-button-rerecord-text"}>Перезаписать</span>
                                            </div>
                                        }
                                        {
                                            ! mediaBlobUrl &&
                                            <div className={"web-button-spacer"}/>
                                        }
                                        {
                                            ! mediaBlobUrl &&
                                            <div onClick={isAudioMuted ? unMuteAudio : muteAudio}
                                                 className={isAudioMuted ? "web-button-unmute" : "web-button-mute"}/>
                                        }
                                        <div className={"web-button-spacer"}/>
                                    </div>
                                </>
740
                            }
Яков's avatar
Яков committed
741
742
743
                        </Fragment>
                    </>
                )
Рамис's avatar
Рамис committed
744
745
746
747
748
            default:
                return <div>Пусто</div>
        }
    }

Рамис's avatar
Рамис committed
749
    const isDisabledAction = () => {
750
751
        let isDisabled = false;

Яков's avatar
Яков committed
752
        switch (innerModalType) {
Рамис's avatar
Рамис committed
753
            case 'video':
754
            case 'image':
Яков's avatar
Яков committed
755
                if (uploadOptions.url === null || uploadedPaths.length === 0) {
756
757
758
                    isDisabled = true;
                }
                break;
Sergey's avatar
Sergey committed
759
            case 'screencust':
Яков's avatar
Яков committed
760
                if (status === 'recording' || isUploading || ! mediaBlobUrl) {
Sergey's avatar
Sergey committed
761
762
763
764
                    isDisabled = true;
                }
                break;
            case 'voicemessage':
Яков's avatar
Яков committed
765
                if (status === 'recording' || isUploading || ! mediaBlobUrl) {
Sergey's avatar
Sergey committed
766
767
768
769
                    isDisabled = true;
                }
                break;
            case 'webcamera':
Яков's avatar
Яков committed
770
                if (status === 'recording' || isUploading || ! mediaBlobUrl) {
Sergey's avatar
Sergey committed
771
772
773
                    isDisabled = true;
                }
                break;
Рамис's avatar
Рамис committed
774
            case 'iframe':
Яков's avatar
Яков committed
775
                try {
776
777
                    let url = new URL(embedContent);

Яков's avatar
Яков committed
778
                    switch (url.hostname) {
779
780
781
782
783
784
785
786
787
788
789
790
791
                        case 'rutube.ru':
                        case 'www.rutube.ru':
                        case 'vimeo.com':
                        case 'ok.ru':
                        case 'www.ok.ru':
                        case 'youtu.be':
                        case 'youtube.com':
                        case 'www.youtube.com':
                            break;
                        default:
                            isDisabled = true;
                    }

Яков's avatar
Яков committed
792
                } catch (error) {
793
794
795
                    isDisabled = true;
                }
                break;
Яков's avatar
Яков committed
796
797
798
799
            case 'iframe_custom':
                let regex = new RegExp('(?:<iframe[^>]*)(?:(?:\\/>)|(?:>.*?<\\/iframe>))');
                isDisabled = !regex.test(embedContent);
                break;
800
801
802
803
804
        }

        return isDisabled;
    }

Яков's avatar
Яков committed
805
    if ( ! editor) {
Рамис's avatar
Рамис committed
806
807
        return null
    }
Рамис's avatar
Рамис committed
808

Рамис's avatar
Рамис committed
809
    return (
Рамис's avatar
Рамис committed
810
811
812
813
        <div
            className="atma-editor-wrap"
            style={style}
        >
Рамис's avatar
Рамис committed
814
815
816
            <div className="atma-editor">
                <ToolBar
                    editor={editor}
Рамис's avatar
Рамис committed
817
                    {...{toolsOptions}}
Рамис's avatar
Рамис committed
818
                    {...{toolsLib}}
Рамис's avatar
Рамис committed
819

Рамис's avatar
Рамис committed
820
                />
Рамис's avatar
bug fix    
Рамис committed
821
                <BubbleMenu typpyOptions={{followCursor: true,}} editor={editor} shouldShow={({...o}) => {
Рамис's avatar
Рамис committed
822
823
                    let items = [];

Яков's avatar
Яков committed
824
                    if (o.from !== o.to && editor.isActive('paragraph') && editor.isActive('image') === false && document.querySelectorAll('.selectedCell').length === 0) {
Рамис's avatar
Рамис committed
825
826
827
                        items = initialBubbleItems;
                    }

Яков's avatar
Яков committed
828
                    if (editor.isActive('image') === true) {
Рамис's avatar
Рамис committed
829
                        items = ['alignLeft', 'alignCenter', 'alignRight'];
Рамис's avatar
Рамис committed
830
                    }
Рамис's avatar
Рамис committed
831
832
                    setFocusFromTo([o.from, o.to].join(':'));

Яков's avatar
Яков committed
833
                    if (items.length > 0) {
Рамис's avatar
Рамис committed
834
835
836
                        setBubbleItems(items);
                        return true;
                    }
Яков's avatar
Яков committed
837
                }} tippyOptions={{duration: 100}}>
Рамис's avatar
Рамис committed
838
                    <div className={"atma-editor-bubble"} onClick={e => e.stopPropagation()}>
Рамис's avatar
Рамис committed
839
                        {
Рамис's avatar
Рамис committed
840
                            colorsSelected !== null ?
Рамис's avatar
Рамис committed
841
                                colors[colorsSelected].map((itemColor, i) => {
Яков's avatar
Яков committed
842
843
844
                                    return (<div key={'colors' + colorsSelected + i}
                                                 className={'qcolors' + (itemColor === 'none' ? ' unset' : '')}
                                                 style={{background: itemColor}} onClick={() => {
Рамис's avatar
Рамис committed
845

Яков's avatar
Яков committed
846
                                        if (itemColor === 'none') {
Рамис's avatar
Рамис committed
847
848
849
                                            colorsSelected === 'color' ?
                                                editor.chain().focus().unsetHighlight().unsetColor().run() :
                                                editor.chain().focus().unsetColor().unsetHighlight().run();
Яков's avatar
Яков committed
850
                                        } else {
Рамис's avatar
Рамис committed
851
852
                                            colorsSelected === 'color' ?
                                                editor.chain().focus().unsetHighlight().setColor(itemColor).run() :
Яков's avatar
Яков committed
853
                                                editor.chain().focus().unsetColor().toggleHighlight({color: itemColor}).run();
Рамис's avatar
Рамис committed
854
855
                                        }

Рамис's avatar
Рамис committed
856
                                        setColorsSelected(null);
Яков's avatar
Яков committed
857
                                    }}/>)
Рамис's avatar
Рамис committed
858
                                }) : bubbleItems.map((type, i) => {
Яков's avatar
Яков committed
859
860
861
                                    if (type === '|') {
                                        return (<div key={'bubbleSeparator' + i} className={'qseparator'}/>)
                                    } else {
Рамис's avatar
Рамис committed
862
863
                                        return (
                                            <div
Яков's avatar
Яков committed
864
                                                key={'bubbleItems' + i}
Рамис's avatar
Рамис committed
865
                                                className={'qicon q' + type + (editor.isActive(type) ? ' active' : '')}
Яков's avatar
Яков committed
866
867
                                                title={toolsLib[type] ? toolsLib[type].title : ''}
                                                onClick={toolsLib[type].onClick}
Рамис's avatar
Рамис committed
868
869
870
871
                                            />
                                        )
                                    }
                                })
Рамис's avatar
Рамис committed
872
                        }
Рамис's avatar
Рамис committed
873
                    </div>
Рамис's avatar
Рамис committed
874
875
876
877
878
879
880
881
882
883
                </BubbleMenu>
                <EditorContent
                    editor={editor}
                    className={'atma-editor-content'}
                />
            </div>
            <EditorModal
                isOpen={modalIsOpen}
                title={modalTitle}
            >
Рамис's avatar
Рамис committed
884
885
886
887
                {
                    getInnerModal()
                }
                {
Рамис's avatar
Рамис committed
888
                    buildActionsModal([
Рамис's avatar
Рамис committed
889
890
891
892
                        {
                            title: 'Отмена',
                            className: ' atma-editor-cancel',
                            onClick: () => {
Sergey's avatar
Sergey committed
893
894
                                stopRecording();
                                unMuteAudio();
Sergey's avatar
Sergey committed
895
                                clearBlobUrl();
Рамис's avatar
Рамис committed
896
897
                                setUploaderUid(`uid${new Date()}`);
                                setUploadedPaths([]);
898
                                setModalIsOpen(false);
Рамис's avatar
Рамис committed
899
                            }
Рамис's avatar
Рамис committed
900
901
                        },
                        {
Sergey's avatar
Sergey committed
902
903
                            title: (mediaBlobUrl && uploadedPaths.length === 0) ? (isUploading ? 'Сохранение...' : 'Вставить') : 'Вставить',
                            className: ' atma-editor-complete',
Яков's avatar
update    
Яков committed
904
                            onClick: async () => {
Яков's avatar
update    
Яков committed
905

Sergey's avatar
Sergey committed
906
                                if ((status === 'recording' || isUploading)) {
Яков's avatar
update    
Яков committed
907
                                    return false;
908
909
910
911
912
913
                                } else {
                                    if (document.querySelectorAll('.atma-editor-uploader-progress').length > 0) {
                                        if ( ! confirm('Не полностью загруженные файлы будут утеряны. Вы уверены, что хотите продолжить?')) {
                                            return false;
                                        }
                                    }
Sergey's avatar
Sergey committed
914

915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
                                    try {
                                        switch (innerModalType) {
                                            case 'image':
                                                uploadedPaths.map((file, i) => {
                                                    editor.chain().focus().setImage({src: file.path}).run();
                                                });
                                                break
                                            case 'video':
                                                uploadedPaths.map((file, i) => {
                                                    editor.chain().focus().setVideo({
                                                        src: file.path,
                                                        poster: file.path + '.jpg'
                                                    }).run();
                                                });
                                                break
                                            case 'voicemessage':
Sergey's avatar
Sergey committed
931
932
933
934
935
936
937
938
                                                if (mediaBlobUrl && uploadedPaths.length === 0) {
                                                    if ( ! isUploading) {
                                                        await saveScreenCust(mediaBlobUrl).then(data => {
                                                            if (data?.file_path) {
                                                                editor.chain().focus().addVoiceMessage({src: data.file_path}).run();
                                                            }
                                                        });
                                                    }
939
940
941
                                                }
                                                break
                                            case 'screencust':
Sergey's avatar
Sergey committed
942
943
944
945
946
947
948
949
                                                if (mediaBlobUrl && uploadedPaths.length === 0) {
                                                    if ( ! isUploading) {
                                                        await saveScreenCust(mediaBlobUrl).then(data => {
                                                            if (data?.file_path) {
                                                                editor.chain().focus().setVideo({src: data.file_path}).run();
                                                            }
                                                        });
                                                    }
950
951
952
                                                }
                                                break
                                            case 'webcamera':
Sergey's avatar
Sergey committed
953
954
955
956
957
958
959
960
                                                if (mediaBlobUrl && uploadedPaths.length === 0) {
                                                    if ( ! isUploading) {
                                                        await saveScreenCust(mediaBlobUrl).then(data => {
                                                            if (data?.file_path) {
                                                                editor.chain().focus().setVideo({src: data.file_path}).run();
                                                            }
                                                        });
                                                    }
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
                                                }
                                                break
                                            case 'iframe':
                                                let _url = embedContent;
                                                let reg = /(http|https):\/\/([\w.]+\/?)\S*/;

                                                const url = new URL(reg.test(_url) ? _url : 'https:' + _url);
                                                let urlId = url.pathname.replace(/\/$/ig, '').split('/').pop();

                                                switch (url.hostname) {
                                                    case 'rutube.ru':
                                                    case 'www.rutube.ru':
                                                        _url = `https://rutube.ru/pl/?pl_id&pl_type&pl_video=${urlId}`;
                                                        break
                                                    case 'vimeo.com':
                                                        _url = `https://player.vimeo.com/video/${urlId}`;

                                                        break
                                                    case 'ok.ru':
                                                    case 'www.ok.ru':
                                                        _url = `//ok.ru/videoembed/${urlId}`;
                                                        break
                                                    case 'youtu.be':
                                                    case 'youtube.com':
                                                    case 'www.youtube.com':
                                                        if (url.hostname.indexOf('youtu.be') === -1 && url.search !== '') {
                                                            if (url.searchParams.get('v')) {
                                                                urlId = url.searchParams.get('v');
                                                            }
Рамис's avatar
Рамис committed
990
                                                        }
991
992
993
994
                                                        _url = `https://www.youtube.com/embed/${urlId}`;
                                                        break
                                                }
                                                editor.chain().focus().setIframe({src: _url}).run();
Рамис's avatar
Рамис committed
995

Яков's avatar
Яков committed
996
997
998
                                                break
                                            case 'iframe_custom':
                                                editor.chain().focus().insertContent(embedContent).run();
999
                                                break
Яков's avatar
Яков committed
1000
1001
1002
1003
1004
                                            case 'iframe_pptx':
                                                uploadedPaths.map((file, i)=>{
                                                    editor.chain().focus().insertContent(`<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=${file.path}" width="100%" height="600px" frameBorder="0"></iframe>`).run();
                                                })
                                                break
1005
1006
                                            case 'file':
                                                uploadedPaths.map((file, i) => {
Яков's avatar
Яков committed
1007
1008
                                                    let exp = file.path.split('.');
                                                    exp = exp[exp.length - 1]
Яков's avatar
Яков committed
1009
                                                    editor.chain().focus().insertContent(`<a href="${file.path}" target="_blank" download="${file.name}.${exp}" data-size="${file.size}">${file.name}</a>`).run();
1010
1011
1012
                                                });
                                                break
                                        }
Рамис's avatar
Рамис committed
1013

1014
                                        setModalIsOpen(false);
Sergey's avatar
Sergey committed
1015
                                        clearBlobUrl();
1016
1017
1018
1019
1020
                                        setUploaderUid(`uid${new Date()}`);
                                        setEmbedContent('');
                                        setUploadedPaths([]);
                                        setModalTitle('');
                                    } catch (err) {
Яков's avatar
update    
Яков committed
1021
1022
1023
1024
1025
1026
1027
                                        console.log(err);
                                        setModalIsOpen(false);
                                        clearBlobUrl();
                                        setUploaderUid(`uid${new Date()}`);
                                        setEmbedContent('');
                                        setUploadedPaths([]);
                                        setModalTitle('');
1028
                                    }
Рамис's avatar
Рамис committed
1029
1030
1031
1032
1033
                                }
                            },
                            disabled: isDisabledAction()
                        }
                    ])
Рамис's avatar
Рамис committed
1034
1035
1036
1037
                }
            </EditorModal>
        </div>
    )
Рамис's avatar
Рамис committed
1038
}
Рамис's avatar
Рамис committed
1039
1040

export default QEditor;