QEditor.jsx 48.3 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')
        },
173
174
175
176
        audio: {
            title: 'Вставить аудио файл',
            onClick: () => modalOpener('audio', 'Вставить аудио файл')
        },
yakoff94's avatar
add pdf    
yakoff94 committed
177
178
        iframe_pdf: {
            title: 'Вставить презентацию pdf',
yakoff94's avatar
add pdf    
yakoff94 committed
179
            onClick: () => modalOpener('iframe_pdf', 'Вставить презентацию pdf')
yakoff94's avatar
add pdf    
yakoff94 committed
180
        },
Рамис's avatar
Рамис committed
181
182
183
184
185
186
        image: {
            title: 'Загрузить изображение',
            onClick: () => modalOpener('image', 'Загрузить изображение')
        },
        h2: {
            title: 'Заголовок 2',
Яков's avatar
Яков committed
187
            onClick: () => editor.chain().focus().toggleHeading({level: 2}).run()
Рамис's avatar
Рамис committed
188
189
190
        },
        h3: {
            title: 'Заголовок 3',
Яков's avatar
Яков committed
191
            onClick: () => editor.chain().focus().toggleHeading({level: 3}).run()
Рамис's avatar
Рамис committed
192
193
194
        },
        h4: {
            title: 'Заголовок 4',
Яков's avatar
Яков committed
195
            onClick: () => editor.chain().focus().toggleHeading({level: 4}).run()
Рамис's avatar
Рамис committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
        },
        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
217
218
219
220
221
222
223
224
        superscript: {
            title: 'Надстрочный символ',
            onClick: () => editor.chain().focus().toggleSuperscript().run()
        },
        subscript: {
            title: 'Подстрочный символ',
            onClick: () => editor.chain().focus().toggleSubscript().run()
        },
Рамис's avatar
Рамис committed
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
255
256
257
258
259
260
261
262
        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
263
264
265
266
            onClick: () => {
                editor.commands.setTextAlign('left');
                editor.chain().focus();
            }
Рамис's avatar
Рамис committed
267
268
269
        },
        alignCenter: {
            title: 'По центру',
Рамис's avatar
Рамис committed
270
271
272
273
            onClick: () => {
                editor.commands.setTextAlign('center')
                editor.chain().focus();
            }
Рамис's avatar
Рамис committed
274
275
276
        },
        alignRight: {
            title: 'По правому краю',
Рамис's avatar
Рамис committed
277
278
279
280
            onClick: () => {
                editor.commands.setTextAlign('right');
                editor.chain().focus();
            }
Рамис's avatar
Рамис committed
281
282
283
        },
        insertTable: {
            title: 'Вставить таблицу',
Яков's avatar
Яков committed
284
            onClick: () => editor.chain().focus().insertTable({rows: 2, cols: 2}).run()
Рамис's avatar
Рамис committed
285
286
287
288
289
290
291
292
293
294
295
        },
        deleteTable: {
            title: 'Удалить таблицу',
            onClick: () => editor.chain().focus().deleteTable().run()
        },
        addRowBefore: {
            title: 'Вставить строку перед',
            onClick: () => editor.chain().focus().addRowBefore().run()
        },
        addRowAfter: {
            title: 'Вставить строку после',
Рамис's avatar
Рамис committed
296
297
298
299
300
            onClick: () => editor.chain().focus().addRowAfter().run()
        },
        deleteRow: {
            title: 'Удалить строку',
            onClick: () => editor.chain().focus().deleteRow().run()
Рамис's avatar
Рамис committed
301
302
303
304
305
306
307
308
        },
        addColumnBefore: {
            title: 'Вставить столбец перед',
            onClick: () => editor.chain().focus().addColumnBefore().run()
        },
        addColumnAfter: {
            title: 'Вставить столбец после',
            onClick: () => editor.chain().focus().addColumnAfter().run()
Рамис's avatar
Рамис committed
309
        },
Рамис's avatar
Рамис committed
310
311
312
313
314
315
316
317
318
319
320
        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
321
322
323
        },
        colorText: {
            title: 'Цвет текста',
Рамис's avatar
Рамис committed
324
325
326
327
            onClick: () => {
                setColorsSelected('color')
                editor.chain().focus();
            }
Рамис's avatar
Рамис committed
328
329
330
331
332
        },
        highlight: {
            title: 'Цвет фона',
            onClick: () => setColorsSelected('highlight')
        },
333
334
335
336
        voicemessage: {
            title: 'Записать голосовое сообщение',
            onClick: () => {
                setRecordType({audio: true})
Sergey's avatar
Sergey committed
337
                clearBlobUrl()
Sergey's avatar
Sergey committed
338
                modalOpener('voicemessage', 'Записать голосовое сообщение')
339
340
341
342
343
344
            }
        },
        webcamera: {
            title: 'Записать с камеры',
            onClick: () => {
                setRecordType({video: true})
Sergey's avatar
Sergey committed
345
                clearBlobUrl()
Sergey's avatar
Sergey committed
346
                modalOpener('webcamera', 'Записать с камеры')
347
348
349
350
351
            }
        },
        screencust: {
            title: 'Записать экран',
            onClick: () => {
Яков's avatar
Яков committed
352
353
354
355
356
                if (isMobile) {
                    setRecordType({video: true})
                } else {
                    setRecordType({screen: true})
                }
Sergey's avatar
Sergey committed
357
                clearBlobUrl()
Sergey's avatar
Sergey committed
358
                modalOpener('screencust', 'Записать экран')
359
360
            }
        },
Рамис's avatar
Рамис committed
361
362
363
364
365
366
367
368
369
        // katex: {
        //     title: 'Вставить формулу',
        //     onClick: () => {
        //
        //         console.log(katex.renderToString(String.raw`c = \pm\sqrt{a^2 + b^2}`));
        //
        //         // editor.chain().focus().insertContent()
        //     }
        // }
Рамис's avatar
Рамис committed
370
371
    }

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

Яков's avatar
Яков committed
426
            wrap.querySelectorAll('.atma-editor-toolbar-s').forEach(function (s) {
Рамис's avatar
Рамис committed
427
428
429
                s.classList.remove('show');
            });

Рамис's avatar
bug fix    
Рамис committed
430
        }
Рамис's avatar
Рамис committed
431
432
433
    })

    const buildActionsModal = (buttons = []) => {
Рамис's avatar
Рамис committed
434
435
436
437
438
439
440
441
        if (buttons.length === 0) {
            return null;
        }

        return (
            <div className={'atma-editor-modal-action'}>
                {
                    buttons.map((btn, i) => (
Яков's avatar
Яков committed
442
443
                        <button disabled={btn.disabled} type={'button'} key={'mAction' + i}
                                className={'atma-editor-btn' + btn.className}
Рамис's avatar
Рамис committed
444
445
446
447
448
449
450
                                onClick={btn.onClick}>{btn.title}</button>
                    ))
                }
            </div>
        )
    }

Яков's avatar
Яков committed
451
    const getUploader = ({accept = '*', ...o}) => {
Яков's avatar
Яков committed
452
453
        let url = uploadOptions.url,
            multiple = true;
Яков's avatar
Яков committed
454
455
        if (o.afterParams && o.afterParams.length > 0) {
            if (uploadOptions.url.indexOf('?') !== -1) {
Рамис's avatar
Рамис committed
456
                url = uploadOptions.url + '&' + o.afterParams.join('&');
Яков's avatar
Яков committed
457
            } else {
Рамис's avatar
Рамис committed
458
459
460
461
                url = uploadOptions.url + '?' + o.afterParams.join('&');
            }
        }

Яков's avatar
Яков committed
462
463
464
465
        if (typeof o.multiple !== 'undefined') {
            multiple = o.multiple;
        }

Рамис's avatar
Рамис committed
466
467
        return <Uploader
            key={uploaderUid}
Яков's avatar
Яков committed
468
469
470
            accept={accept}
            action={url}
            errorMessage={uploadOptions.errorMessage}
Рамис's avatar
Рамис committed
471
472
473
474
475
476
            onSuccess={(file) => {
                let _uploadedPaths = [...uploadedPaths];

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

Яков's avatar
Яков committed
481
482
                _uploadedPaths.map((f, i) => {
                    if (f.uid === deleteFile.uid) {
Рамис's avatar
Рамис committed
483
484
485
486
487
488
                        deleteIdx = i;
                    }
                });
                _uploadedPaths.splice(deleteIdx, 1);
                setUploadedPaths(_uploadedPaths)
            }}
Яков's avatar
Яков committed
489
            multiple={multiple}
Яков's avatar
Яков committed
490
            modalType={innerModalType}
Рамис's avatar
Рамис committed
491
492
493
        />
    }

Sergey's avatar
Sergey committed
494
    const saveScreenCust = async (fileBlob) => {
495
496
497
498
499
500
501
502
503
        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
504
505
506
507
508
509
510
511
512

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

Рамис's avatar
Рамис committed
516
517
518
    const getInnerModal = () => {
        switch (innerModalType) {
            case 'iframe':
Рамис's avatar
Рамис committed
519
520
                return (
                    <Fragment>
Яков's avatar
Яков committed
521
522
523
                        <input type="text" value={embedContent} placeholder={'https://'}
                               onInput={(e) => setEmbedContent(e.target.value)
                               }/>
Рамис's avatar
Рамис committed
524
525
526
                        <ul className={'atma-editor-soc-video'}>
                            <li className={'youtube'}/>
                            <li className={'vimeo'}/>
Рамис's avatar
Рамис committed
527
                            {/* <li className={'vk'}/> */}
Рамис's avatar
Рамис committed
528
                            <li className={'ok'}/>
Рамис's avatar
fix bug    
Рамис committed
529
                            <li className={'rutube'}/>
Рамис's avatar
Рамис committed
530
531
532
                        </ul>
                    </Fragment>
                )
Яков's avatar
Яков committed
533
534
535
            case 'iframe_custom':
                return (
                    <Fragment>
Яков's avatar
Яков committed
536
                        <textarea style={{width: '100%', height: '100%'}} rows={18} value={embedContent} placeholder={'<iframe></iframe>'}
Яков's avatar
Яков committed
537
538
539
540
                               onInput={(e) => setEmbedContent(e.target.value)}
                        />
                    </Fragment>
                )
Яков's avatar
Яков committed
541
542
543
544
            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>
                )
545
546
547
548
            case 'audio':
                return (
                    <Fragment>{getUploader({accept: '.wav, .mp3, .ogg'})}</Fragment>
                )
yakoff94's avatar
add pdf    
yakoff94 committed
549
550
551
552
            case 'iframe_pdf':
                return (
                    <Fragment>{getUploader({accept: 'application/pdf', afterParams: ['no_convert=1']})}</Fragment>
                )
Рамис's avatar
Рамис committed
553
            case 'video':
Рамис's avatar
Рамис committed
554
                return (
Яков's avatar
Яков committed
555
                    <Fragment>{getUploader({accept: 'video/*'})}</Fragment>
Рамис's avatar
Рамис committed
556
557
558
                )
            case 'image':
                return (
Яков's avatar
Яков committed
559
                    <Fragment>{getUploader({accept: 'image/*'})}</Fragment>
Рамис's avatar
Рамис committed
560
                )
Рамис's avatar
Рамис committed
561
            case 'file':
Рамис's avatar
Рамис committed
562
                return (
Яков's avatar
Яков committed
563
                    <Fragment>{getUploader({accept: '*', afterParams: ['no_convert=1']})}</Fragment>
Рамис's avatar
Рамис committed
564
                )
565
566
567
568
            case 'voicemessage':
                return (
                    <>
                        <Fragment>
Яков's avatar
Яков committed
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
                            {
                                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"}/>
591
                                    {
Яков's avatar
Яков committed
592
593
594
595
596
597
598
599
600
601
602
603
                                        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"}/>
604
605
                                    }
                                </div>
Яков's avatar
Яков committed
606
                            }
607
608
609
610
611
612
613
                        </Fragment>
                    </>
                )
            case 'screencust':
                return (
                    <>
                        <Fragment>
Яков's avatar
Яков committed
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
                            {
                                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"}>
645
646
                                                    {formatted}
                                                </span>
Яков's avatar
Яков committed
647
648
649
650
651
652
653
654
655
656
657
658
                                                            )
                                                        }}
                                                    /> : <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>
                                            }
659
660
                                        </div>
                                    </div>
Яков's avatar
Яков committed
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
                                    <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>
                                </>
                            }
681
682
683
                        </Fragment>
                    </>
                )
Sergey's avatar
Sergey committed
684
685
686
            case 'webcamera':
                return (
                    <>
Яков's avatar
Яков committed
687
                        <Fragment>
688
                            {
Яков's avatar
Яков committed
689
690
691
692
693
694
695
696
                                isMobile &&
                                <>
                                    <div className={"webwrap"}>
                                        <div>Видеозапись с мобильного устройства недоступна, <br/> запишите стандартными
                                            функциями устройства и воспользуйтесь кнопкой «Загрузить видео»
                                        </div>
                                    </div>
                                </>
697
698
                            }
                            {
Яков's avatar
Яков committed
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
                                ! 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>
                                </>
756
                            }
Яков's avatar
Яков committed
757
758
759
                        </Fragment>
                    </>
                )
Рамис's avatar
Рамис committed
760
761
762
763
764
            default:
                return <div>Пусто</div>
        }
    }

Рамис's avatar
Рамис committed
765
    const isDisabledAction = () => {
766
767
        let isDisabled = false;

Яков's avatar
Яков committed
768
        switch (innerModalType) {
Рамис's avatar
Рамис committed
769
            case 'video':
770
            case 'image':
Яков's avatar
Яков committed
771
                if (uploadOptions.url === null || uploadedPaths.length === 0) {
772
773
774
                    isDisabled = true;
                }
                break;
Sergey's avatar
Sergey committed
775
            case 'screencust':
Яков's avatar
Яков committed
776
                if (status === 'recording' || isUploading || ! mediaBlobUrl) {
Sergey's avatar
Sergey committed
777
778
779
780
                    isDisabled = true;
                }
                break;
            case 'voicemessage':
Яков's avatar
Яков committed
781
                if (status === 'recording' || isUploading || ! mediaBlobUrl) {
Sergey's avatar
Sergey committed
782
783
784
785
                    isDisabled = true;
                }
                break;
            case 'webcamera':
Яков's avatar
Яков committed
786
                if (status === 'recording' || isUploading || ! mediaBlobUrl) {
Sergey's avatar
Sergey committed
787
788
789
                    isDisabled = true;
                }
                break;
Рамис's avatar
Рамис committed
790
            case 'iframe':
Яков's avatar
Яков committed
791
                try {
792
793
                    let url = new URL(embedContent);

Яков's avatar
Яков committed
794
                    switch (url.hostname) {
795
796
797
798
799
800
801
802
803
804
805
806
807
                        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
808
                } catch (error) {
809
810
811
                    isDisabled = true;
                }
                break;
Яков's avatar
Яков committed
812
813
814
815
            case 'iframe_custom':
                let regex = new RegExp('(?:<iframe[^>]*)(?:(?:\\/>)|(?:>.*?<\\/iframe>))');
                isDisabled = !regex.test(embedContent);
                break;
816
817
818
819
820
        }

        return isDisabled;
    }

Яков's avatar
Яков committed
821
    if ( ! editor) {
Рамис's avatar
Рамис committed
822
823
        return null
    }
Рамис's avatar
Рамис committed
824

Рамис's avatar
Рамис committed
825
    return (
Рамис's avatar
Рамис committed
826
827
828
829
        <div
            className="atma-editor-wrap"
            style={style}
        >
Рамис's avatar
Рамис committed
830
831
832
            <div className="atma-editor">
                <ToolBar
                    editor={editor}
Рамис's avatar
Рамис committed
833
                    {...{toolsOptions}}
Рамис's avatar
Рамис committed
834
                    {...{toolsLib}}
Рамис's avatar
Рамис committed
835

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

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

Яков's avatar
Яков committed
844
                    if (editor.isActive('image') === true) {
Рамис's avatar
Рамис committed
845
                        items = ['alignLeft', 'alignCenter', 'alignRight'];
Рамис's avatar
Рамис committed
846
                    }
Рамис's avatar
Рамис committed
847
848
                    setFocusFromTo([o.from, o.to].join(':'));

Яков's avatar
Яков committed
849
                    if (items.length > 0) {
Рамис's avatar
Рамис committed
850
851
852
                        setBubbleItems(items);
                        return true;
                    }
Яков's avatar
Яков committed
853
                }} tippyOptions={{duration: 100}}>
Рамис's avatar
Рамис committed
854
                    <div className={"atma-editor-bubble"} onClick={e => e.stopPropagation()}>
Рамис's avatar
Рамис committed
855
                        {
Рамис's avatar
Рамис committed
856
                            colorsSelected !== null ?
Рамис's avatar
Рамис committed
857
                                colors[colorsSelected].map((itemColor, i) => {
Яков's avatar
Яков committed
858
859
860
                                    return (<div key={'colors' + colorsSelected + i}
                                                 className={'qcolors' + (itemColor === 'none' ? ' unset' : '')}
                                                 style={{background: itemColor}} onClick={() => {
Рамис's avatar
Рамис committed
861

Яков's avatar
Яков committed
862
                                        if (itemColor === 'none') {
Рамис's avatar
Рамис committed
863
864
865
                                            colorsSelected === 'color' ?
                                                editor.chain().focus().unsetHighlight().unsetColor().run() :
                                                editor.chain().focus().unsetColor().unsetHighlight().run();
Яков's avatar
Яков committed
866
                                        } else {
Рамис's avatar
Рамис committed
867
868
                                            colorsSelected === 'color' ?
                                                editor.chain().focus().unsetHighlight().setColor(itemColor).run() :
Яков's avatar
Яков committed
869
                                                editor.chain().focus().unsetColor().toggleHighlight({color: itemColor}).run();
Рамис's avatar
Рамис committed
870
871
                                        }

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

Sergey's avatar
Sergey committed
922
                                if ((status === 'recording' || isUploading)) {
Яков's avatar
update    
Яков committed
923
                                    return false;
924
925
926
927
928
929
                                } else {
                                    if (document.querySelectorAll('.atma-editor-uploader-progress').length > 0) {
                                        if ( ! confirm('Не полностью загруженные файлы будут утеряны. Вы уверены, что хотите продолжить?')) {
                                            return false;
                                        }
                                    }
Sergey's avatar
Sergey committed
930

931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
                                    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
947
948
949
950
951
952
953
954
                                                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();
                                                            }
                                                        });
                                                    }
955
956
957
                                                }
                                                break
                                            case 'screencust':
Sergey's avatar
Sergey committed
958
959
960
961
962
963
964
965
                                                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();
                                                            }
                                                        });
                                                    }
966
967
968
                                                }
                                                break
                                            case 'webcamera':
Sergey's avatar
Sergey committed
969
970
971
972
973
974
975
976
                                                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();
                                                            }
                                                        });
                                                    }
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
                                                }
                                                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
1006
                                                        }
1007
1008
1009
1010
                                                        _url = `https://www.youtube.com/embed/${urlId}`;
                                                        break
                                                }
                                                editor.chain().focus().setIframe({src: _url}).run();
Рамис's avatar
Рамис committed
1011

Яков's avatar
Яков committed
1012
1013
1014
                                                break
                                            case 'iframe_custom':
                                                editor.chain().focus().insertContent(embedContent).run();
1015
                                                break
Яков's avatar
Яков committed
1016
1017
1018
                                            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();
yakoff94's avatar
add pdf    
yakoff94 committed
1019
1020
1021
1022
                                                })
                                                break
                                            case 'iframe_pdf':
                                                uploadedPaths.map((file, i)=>{
yakoff94's avatar
add pdf    
yakoff94 committed
1023
                                                    editor.chain().focus().insertContent(`<iframe src="https://docs.google.com/viewer?embedded=true&url=${file.path}" width="100%" height="800px" frameBorder="0"></iframe>`).run();
Яков's avatar
Яков committed
1024
1025
                                                })
                                                break
1026
1027
1028
1029
1030
                                            case 'audio':
                                                uploadedPaths.map((file) => {
                                                    editor.chain().focus().insertContent(`<audio class="audio-player" controls="true" src="${file.path}" />`).run()
                                                })
                                                break;
1031
1032
                                            case 'file':
                                                uploadedPaths.map((file, i) => {
Яков's avatar
Яков committed
1033
1034
                                                    let exp = file.path.split('.');
                                                    exp = exp[exp.length - 1]
Яков's avatar
Яков committed
1035
                                                    editor.chain().focus().insertContent(`<a href="${file.path}" target="_blank" download="${file.name}.${exp}" data-size="${file.size}">${file.name}</a>`).run();
1036
1037
1038
                                                });
                                                break
                                        }
Рамис's avatar
Рамис committed
1039

1040
                                        setModalIsOpen(false);
Sergey's avatar
Sergey committed
1041
                                        clearBlobUrl();
1042
1043
1044
1045
1046
                                        setUploaderUid(`uid${new Date()}`);
                                        setEmbedContent('');
                                        setUploadedPaths([]);
                                        setModalTitle('');
                                    } catch (err) {
Яков's avatar
update    
Яков committed
1047
1048
1049
1050
1051
1052
1053
                                        console.log(err);
                                        setModalIsOpen(false);
                                        clearBlobUrl();
                                        setUploaderUid(`uid${new Date()}`);
                                        setEmbedContent('');
                                        setUploadedPaths([]);
                                        setModalTitle('');
1054
                                    }
Рамис's avatar
Рамис committed
1055
1056
1057
1058
1059
                                }
                            },
                            disabled: isDisabledAction()
                        }
                    ])
Рамис's avatar
Рамис committed
1060
1061
1062
1063
                }
            </EditorModal>
        </div>
    )
Рамис's avatar
Рамис committed
1064
}
Рамис's avatar
Рамис committed
1065
1066

export default QEditor;