Commit cbdf4e4b by DenSakh

Merge branch '2694_iframe_remove_button' into tiptap

# Conflicts:
#	src/QEditor.jsx
parents ce97b7dc a5f0c2db
/* eslint-disable no-undef */
/* eslint-disable no-case-declarations */
import React, { Fragment, useEffect, useState, useRef } from 'react' import React, { Fragment, useEffect, useState, useRef } from 'react'
import './index.scss' import './index.scss'
// import EditorModal from "./components/EditorModal" // import EditorModal from "./components/EditorModal"
...@@ -13,1054 +15,1237 @@ import TableHeader from '@tiptap/extension-table-header' ...@@ -13,1054 +15,1237 @@ import TableHeader from '@tiptap/extension-table-header'
import Focus from '@tiptap/extension-focus' import Focus from '@tiptap/extension-focus'
// import Link from '@tiptap/extension-link' // import Link from '@tiptap/extension-link'
import Image from '@tiptap/extension-image' import Image from '@tiptap/extension-image'
import TextAlign from '@tiptap/extension-text-align'; import TextAlign from '@tiptap/extension-text-align'
import { Color } from '@tiptap/extension-color'; import { Color } from '@tiptap/extension-color'
import Highlight from '@tiptap/extension-highlight'; import Highlight from '@tiptap/extension-highlight'
import TextStyle from '@tiptap/extension-text-style'; import TextStyle from '@tiptap/extension-text-style'
import Superscript from "@tiptap/extension-superscript"; import Superscript from '@tiptap/extension-superscript'
import Subscript from "@tiptap/extension-subscript"; import Subscript from '@tiptap/extension-subscript'
import ToolBar from "./components/ToolBar" import ToolBar from './components/ToolBar'
import EditorModal from "./components/EditorModal" import EditorModal from './components/EditorModal'
import Uploader from "./components/Uploader" import Uploader from './components/Uploader'
import Video from './extensions/Video' import Video from './extensions/Video'
import Iframe from './extensions/Iframe' import Iframe from './extensions/Iframe'
import CustomLink from './extensions/CustomLink' import CustomLink from './extensions/CustomLink'
import DragAndDrop from "./extensions/DragAndDrop"; import DragAndDrop from './extensions/DragAndDrop'
import { useReactMediaRecorder } from "react-media-recorder"; import { useReactMediaRecorder } from 'react-media-recorder'
import axios from "axios"; import axios from 'axios'
import ReactStopwatch from 'react-stopwatch'; import ReactStopwatch from 'react-stopwatch'
import Audio from "./extensions/Audio"; import Audio from './extensions/Audio'
import { isMobile } from 'react-device-detect'; import IframeModal from './modals/IframeModal'
import IframeCustomModal from './modals/IframeCustomModal'
import { isMobile } from 'react-device-detect'
const initialBubbleItems = ['bold', 'italic', 'underline', 'strike', 'superscript', 'subscript', '|', 'colorText', 'highlight']; const initialBubbleItems = [
'bold',
'italic',
'underline',
'strike',
'superscript',
'subscript',
'|',
'colorText',
'highlight'
]
const QEditor = ({ const QEditor = ({
value, value,
onChange = () => {}, onChange = () => {},
style, style,
uploadOptions = {url: "", errorMessage: ""}, uploadOptions = { url: '', errorMessage: '' },
toolsOptions = {type: 'all'} toolsOptions = { type: 'all' }
}) => { }) => {
global.uploadUrl = uploadOptions.url; global.uploadUrl = uploadOptions.url
const [innerModalType, setInnerModalType] = useState(null); const [innerModalType, setInnerModalType] = useState(null)
const [embedContent, setEmbedContent] = useState(''); const [embedContent, setEmbedContent] = useState('')
const [uploaderUid, setUploaderUid] = useState('uid' + new Date()); const [uploaderUid, setUploaderUid] = useState('uid' + new Date())
const [uploadedPaths, setUploadedPaths] = useState([]); const [uploadedPaths, setUploadedPaths] = useState([])
const [modalIsOpen, setModalIsOpen] = useState(false); const [modalIsOpen, setModalIsOpen] = useState(false)
const [modalTitle, setModalTitle] = useState(''); const [modalTitle, setModalTitle] = useState('')
const [bubbleItems, setBubbleItems] = useState(initialBubbleItems); const [bubbleItems, setBubbleItems] = useState(initialBubbleItems)
const [colorsSelected, setColorsSelected] = useState(null); const [colorsSelected, setColorsSelected] = useState(null)
const [focusFromTo, setFocusFromTo] = useState(null); const [focusFromTo, setFocusFromTo] = useState(null)
const [oldFocusFromTo, setOldFocusFromTo] = useState(null); const [oldFocusFromTo, setOldFocusFromTo] = useState(null)
const [isUploading, setIsUploading] = useState(false); const [isUploading, setIsUploading] = useState(false)
const [recordType, setRecordType] = useState({video: true}) const [recordType, setRecordType] = useState({ video: true })
const getRgb = (hex) => { // eslint-disable-next-line no-unused-vars
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); const getRgb = (hex) => {
return result ? `rgb(${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)})` : null; var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
} return result
const { ? `rgb(${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(
status, result[3],
startRecording, 16
stopRecording, )})`
mediaBlobUrl, : null
previewStream, }
muteAudio, const {
unMuteAudio, status,
isAudioMuted, startRecording,
clearBlobUrl stopRecording,
} = useReactMediaRecorder(recordType); mediaBlobUrl,
previewStream,
const videoRef = useRef(null); muteAudio,
unMuteAudio,
isAudioMuted,
clearBlobUrl
} = useReactMediaRecorder(recordType)
useEffect(() => { const videoRef = useRef(null)
if (videoRef.current && previewStream) {
videoRef.current.srcObject = previewStream;
}
}, [previewStream]);
useEffect(() => {
if (focusFromTo !== oldFocusFromTo) {
setColorsSelected(null)
setOldFocusFromTo(focusFromTo);
}
}, [focusFromTo])
const modalOpener = (type, title) => { useEffect(() => {
setModalTitle(title); if (videoRef.current && previewStream) {
setInnerModalType(type); videoRef.current.srcObject = previewStream
setModalIsOpen(true);
} }
const colors = { }, [previewStream])
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'
]
};
const toolsLib = {
link: {
title: 'Вставить ссылку',
onClick: () => {
const previousUrl = editor.getAttributes('link').href
const url = window.prompt('Введите URL', previousUrl);
// cancelled useEffect(() => {
if (url === null) { if (focusFromTo !== oldFocusFromTo) {
return setColorsSelected(null)
} setOldFocusFromTo(focusFromTo)
// empty
if (url === '') {
editor.chain().focus().extendMarkRange('link').unsetLink().run();
return
}
// update link
editor.chain().focus().extendMarkRange('link').setLink({href: url, target: '_blank'}).run();
}
},
file: {
title: 'Прикрепить файл',
onClick: () => modalOpener('file', 'Прикрепить файл')
},
video: {
title: 'Загрузить видео',
onClick: () => modalOpener('video', 'Загрузить видео')
},
iframe: {
title: 'Видео по ссылке',
onClick: () => modalOpener('iframe', 'Видео по ссылке')
},
iframe_custom: {
title: 'Вставить iframe',
onClick: () => modalOpener('iframe_custom', 'Вставить iframe')
},
iframe_pptx: {
title: 'Вставить презентацию pptx',
onClick: () => modalOpener('iframe_pptx', 'Вставить презентацию pptx')
},
audio: {
title: 'Вставить аудио файл',
onClick: () => modalOpener('audio', 'Вставить аудио файл')
},
iframe_pdf: {
title: 'Вставить презентацию pdf',
onClick: () => modalOpener('iframe_pdf', 'Вставить презентацию pdf')
},
image: {
title: 'Загрузить изображение',
onClick: () => modalOpener('image', 'Загрузить изображение')
},
h2: {
title: 'Заголовок 2',
onClick: () => editor.chain().focus().toggleHeading({level: 2}).run()
},
h3: {
title: 'Заголовок 3',
onClick: () => editor.chain().focus().toggleHeading({level: 3}).run()
},
h4: {
title: 'Заголовок 4',
onClick: () => editor.chain().focus().toggleHeading({level: 4}).run()
},
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()
},
superscript: {
title: 'Надстрочный символ',
onClick: () => editor.chain().focus().toggleSuperscript().run()
},
subscript: {
title: 'Подстрочный символ',
onClick: () => editor.chain().focus().toggleSubscript().run()
},
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: 'По левому краю',
onClick: () => {
editor.commands.setTextAlign('left');
editor.chain().focus();
}
},
alignCenter: {
title: 'По центру',
onClick: () => {
editor.commands.setTextAlign('center')
editor.chain().focus();
}
},
alignRight: {
title: 'По правому краю',
onClick: () => {
editor.commands.setTextAlign('right');
editor.chain().focus();
}
},
insertTable: {
title: 'Вставить таблицу',
onClick: () => editor.chain().focus().insertTable({rows: 2, cols: 2}).run()
},
deleteTable: {
title: 'Удалить таблицу',
onClick: () => editor.chain().focus().deleteTable().run()
},
addRowBefore: {
title: 'Вставить строку перед',
onClick: () => editor.chain().focus().addRowBefore().run()
},
addRowAfter: {
title: 'Вставить строку после',
onClick: () => editor.chain().focus().addRowAfter().run()
},
deleteRow: {
title: 'Удалить строку',
onClick: () => editor.chain().focus().deleteRow().run()
},
addColumnBefore: {
title: 'Вставить столбец перед',
onClick: () => editor.chain().focus().addColumnBefore().run()
},
addColumnAfter: {
title: 'Вставить столбец после',
onClick: () => editor.chain().focus().addColumnAfter().run()
},
deleteColumn: {
title: 'Удалить столбец',
onClick: () => editor.chain().focus().deleteColumn().run()
},
mergeOrSplit: {
title: 'Объединить/разъединить ячейки',
onClick: () => editor.chain().focus().mergeOrSplit().run()
},
toggleHeaderCell: {
title: 'Добавить/удалить заголовок',
onClick: () => editor.chain().focus().toggleHeaderCell().run()
},
colorText: {
title: 'Цвет текста',
onClick: () => {
setColorsSelected('color')
editor.chain().focus();
}
},
highlight: {
title: 'Цвет фона',
onClick: () => setColorsSelected('highlight')
},
voicemessage: {
title: 'Записать голосовое сообщение',
onClick: () => {
setRecordType({audio: true})
clearBlobUrl()
modalOpener('voicemessage', 'Записать голосовое сообщение')
}
},
webcamera: {
title: 'Записать с камеры',
onClick: () => {
setRecordType({video: true})
clearBlobUrl()
modalOpener('webcamera', 'Записать с камеры')
}
},
screencust: {
title: 'Записать экран',
onClick: () => {
if (isMobile) {
setRecordType({video: true})
} else {
setRecordType({screen: true})
}
clearBlobUrl()
modalOpener('screencust', 'Записать экран')
}
},
// katex: {
// title: 'Вставить формулу',
// onClick: () => {
//
// console.log(katex.renderToString(String.raw`c = \pm\sqrt{a^2 + b^2}`));
//
// // editor.chain().focus().insertContent()
// }
// }
} }
}, [focusFromTo])
const editor = useEditor({ const modalOpener = (type, title) => {
extensions: [ setModalTitle(title)
StarterKit, setInnerModalType(type)
Underline, setModalIsOpen(true)
Image.configure({ }
inline: true const colors = {
}), color: [
// Link.configure({ 'none',
// autolink: true, '#8a8a8a',
// linkOnPaste: true, '#afafaf',
// validate: (href)=> console.log(href), '#44d724',
// }), '#0bd9b2',
Video, '#4fb7ff',
Iframe, '#226aff',
Table.configure({ '#b153e5',
resizable: true, '#f54f8e',
allowTableNodeSelection: true '#f34c37',
}), '#ee7027',
TableRow, '#d27303',
TableHeader, '#ffd102'
TableCell, ],
BubbleMenu, highlight: [
TextAlign.configure({ 'none',
defaultAlignment: 'left', '#9B9B9B',
types: ['heading', 'paragraph'], '#CCCCCC',
alignments: ['left', 'center', 'right', 'justify'], '#9ee191',
}), '#43e7bf',
TextStyle, '#4fb7ff',
Color.configure({ '#6d9ef5',
types: ['textStyle'], '#cd92e8',
}), '#f597bc',
Highlight.configure({ '#fa9084',
multicolor: true '#ef9558',
}), '#dea75b',
CustomLink.configure({ '#ffe672'
linkOnPaste: false, ]
openOnClick: false }
}),
Focus.configure({
className: 'atma-editor-focused',
mode: "all"
}),
DragAndDrop.configure({
linkUpload: uploadOptions.url
}),
Audio,
Superscript,
Subscript
],
content: value,
onUpdate: ({editor}) => onChange(editor.getHTML()),
onFocus: ({editor}) => {
let wrap = editor.options.element.closest('.atma-editor-wrap');
wrap.querySelectorAll('.atma-editor-toolbar-s').forEach(function (s) { const toolsLib = {
s.classList.remove('show'); link: {
}); title: 'Вставить ссылку',
onClick: () => {
const previousUrl = editor.getAttributes('link').href
const url = window.prompt('Введите URL', previousUrl)
// cancelled
if (url === null) {
return
} }
})
const buildActionsModal = (buttons = []) => { // empty
if (buttons.length === 0) { if (url === '') {
return null; editor.chain().focus().extendMarkRange('link').unsetLink().run()
return
} }
return ( // update link
<div className={'atma-editor-modal-action'}> editor
{ .chain()
buttons.map((btn, i) => ( .focus()
<button disabled={btn.disabled} type={'button'} key={'mAction' + i} .extendMarkRange('link')
className={'atma-editor-btn' + btn.className} .setLink({ href: url, target: '_blank' })
onClick={btn.onClick}>{btn.title}</button> .run()
)) }
} },
</div> file: {
) title: 'Прикрепить файл',
onClick: () => modalOpener('file', 'Прикрепить файл')
},
video: {
title: 'Загрузить видео',
onClick: () => modalOpener('video', 'Загрузить видео')
},
iframe: {
title: 'Видео по ссылке',
onClick: () => modalOpener('iframe', 'Видео по ссылке')
},
iframe_custom: {
title: 'Вставить iframe',
onClick: () => modalOpener('iframe_custom', 'Вставить iframe')
},
iframe_pptx: {
title: 'Вставить презентацию pptx',
onClick: () => modalOpener('iframe_pptx', 'Вставить презентацию pptx')
},
iframe_pdf: {
title: 'Вставить презентацию pdf',
onClick: () => modalOpener('iframe_pdf', 'Вставить презентацию pdf')
},
audio: {
title: 'Вставить аудио файл',
onClick: () => modalOpener('audio', 'Вставить аудио файл')
},
image: {
title: 'Загрузить изображение',
onClick: () => modalOpener('image', 'Загрузить изображение')
},
h2: {
title: 'Заголовок 2',
onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run()
},
h3: {
title: 'Заголовок 3',
onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run()
},
h4: {
title: 'Заголовок 4',
onClick: () => editor.chain().focus().toggleHeading({ level: 4 }).run()
},
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()
},
superscript: {
title: 'Надстрочный символ',
onClick: () => editor.chain().focus().toggleSuperscript().run()
},
subscript: {
title: 'Подстрочный символ',
onClick: () => editor.chain().focus().toggleSubscript().run()
},
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: 'По левому краю',
onClick: () => {
editor.commands.setTextAlign('left')
editor.chain().focus()
}
},
alignCenter: {
title: 'По центру',
onClick: () => {
editor.commands.setTextAlign('center')
editor.chain().focus()
}
},
alignRight: {
title: 'По правому краю',
onClick: () => {
editor.commands.setTextAlign('right')
editor.chain().focus()
}
},
insertTable: {
title: 'Вставить таблицу',
onClick: () =>
editor.chain().focus().insertTable({ rows: 2, cols: 2 }).run()
},
deleteTable: {
title: 'Удалить таблицу',
onClick: () => editor.chain().focus().deleteTable().run()
},
addRowBefore: {
title: 'Вставить строку перед',
onClick: () => editor.chain().focus().addRowBefore().run()
},
addRowAfter: {
title: 'Вставить строку после',
onClick: () => editor.chain().focus().addRowAfter().run()
},
deleteRow: {
title: 'Удалить строку',
onClick: () => editor.chain().focus().deleteRow().run()
},
addColumnBefore: {
title: 'Вставить столбец перед',
onClick: () => editor.chain().focus().addColumnBefore().run()
},
addColumnAfter: {
title: 'Вставить столбец после',
onClick: () => editor.chain().focus().addColumnAfter().run()
},
deleteColumn: {
title: 'Удалить столбец',
onClick: () => editor.chain().focus().deleteColumn().run()
},
mergeOrSplit: {
title: 'Объединить/разъединить ячейки',
onClick: () => editor.chain().focus().mergeOrSplit().run()
},
toggleHeaderCell: {
title: 'Добавить/удалить заголовок',
onClick: () => editor.chain().focus().toggleHeaderCell().run()
},
colorText: {
title: 'Цвет текста',
onClick: () => {
setColorsSelected('color')
editor.chain().focus()
}
},
highlight: {
title: 'Цвет фона',
onClick: () => setColorsSelected('highlight')
},
voicemessage: {
title: 'Записать голосовое сообщение',
onClick: () => {
setRecordType({ audio: true })
clearBlobUrl()
modalOpener('voicemessage', 'Записать голосовое сообщение')
}
},
webcamera: {
title: 'Записать с камеры',
onClick: () => {
setRecordType({ video: true })
clearBlobUrl()
modalOpener('webcamera', 'Записать с камеры')
}
},
screencust: {
title: 'Записать экран',
onClick: () => {
if (isMobile) {
setRecordType({ video: true })
} else {
setRecordType({ screen: true })
}
clearBlobUrl()
modalOpener('screencust', 'Записать экран')
}
} }
// katex: {
// title: 'Вставить формулу',
// onClick: () => {
//
// console.log(katex.renderToString(String.raw`c = \pm\sqrt{a^2 + b^2}`));
//
// // editor.chain().focus().insertContent()
// }
// }
}
const getUploader = ({accept = '*', ...o}) => { const editor = useEditor({
let url = uploadOptions.url, extensions: [
multiple = true; StarterKit,
if (o.afterParams && o.afterParams.length > 0) { Underline,
if (uploadOptions.url.indexOf('?') !== -1) { Image.configure({
url = uploadOptions.url + '&' + o.afterParams.join('&'); inline: true
} else { }),
url = uploadOptions.url + '?' + o.afterParams.join('&'); // Link.configure({
} // autolink: true,
} // linkOnPaste: true,
// validate: (href)=> console.log(href),
// }),
Video,
Iframe,
Table.configure({
resizable: true,
allowTableNodeSelection: true
}),
TableRow,
TableHeader,
TableCell,
BubbleMenu,
TextAlign.configure({
defaultAlignment: 'left',
types: ['heading', 'paragraph'],
alignments: ['left', 'center', 'right', 'justify']
}),
TextStyle,
Color.configure({
types: ['textStyle']
}),
Highlight.configure({
multicolor: true
}),
CustomLink.configure({
linkOnPaste: false,
openOnClick: false
}),
Focus.configure({
className: 'atma-editor-focused',
mode: 'all'
}),
DragAndDrop.configure({
linkUpload: uploadOptions.url
}),
Audio,
Superscript,
Subscript
],
content: value,
onUpdate: ({ editor }) => onChange(editor.getHTML()),
onFocus: ({ editor }) => {
const wrap = editor.options.element.closest('.atma-editor-wrap')
if (typeof o.multiple !== 'undefined') { wrap.querySelectorAll('.atma-editor-toolbar-s').forEach(function (s) {
multiple = o.multiple; s.classList.remove('show')
} })
}
})
return <Uploader const buildActionsModal = (buttons = []) => {
key={uploaderUid} if (buttons.length === 0) {
accept={accept} return null
action={url} }
errorMessage={uploadOptions.errorMessage}
onSuccess={(file) => {
let _uploadedPaths = [...uploadedPaths];
_uploadedPaths.push(file); return (
setUploadedPaths(_uploadedPaths) <div className='atma-editor-modal-action'>
}} {buttons.map((btn, i) => (
onDelete={(deleteFile) => { <button
let deleteIdx = null; disabled={btn.disabled}
let _uploadedPaths = [...uploadedPaths]; type='button'
key={'mAction' + i}
className={'atma-editor-btn' + btn.className}
onClick={btn.onClick}
>
{btn.title}
</button>
))}
</div>
)
}
_uploadedPaths.map((f, i) => { const getUploader = ({ accept = '*', ...o }) => {
if (f.uid === deleteFile.uid) { let url = uploadOptions.url
deleteIdx = i; let multiple = true
} if (o.afterParams && o.afterParams.length > 0) {
}); if (uploadOptions.url.indexOf('?') !== -1) {
_uploadedPaths.splice(deleteIdx, 1); url = uploadOptions.url + '&' + o.afterParams.join('&')
setUploadedPaths(_uploadedPaths) } else {
}} url = uploadOptions.url + '?' + o.afterParams.join('&')
multiple={multiple} }
modalType={innerModalType}
/>
} }
const saveScreenCust = async (fileBlob) => { if (typeof o.multiple !== 'undefined') {
if (fileBlob) { multiple = o.multiple
setIsUploading(true) }
let blobData = await fetch(fileBlob).then((res) => res.blob());
const data = new FormData(); return (
let file = new File([blobData], "name." + (recordType?.audio ? "mp3" : "webm")); <Uploader
data.append("file", file); key={uploaderUid}
accept={accept}
action={url}
errorMessage={uploadOptions.errorMessage}
onSuccess={(file) => {
const _uploadedPaths = [...uploadedPaths]
_uploadedPaths.push(file)
setUploadedPaths(_uploadedPaths)
}}
onDelete={(deleteFile) => {
let deleteIdx = null
const _uploadedPaths = [...uploadedPaths]
const headers = {'Content-Type': 'multipart/form-data'}; _uploadedPaths.map((f, i) => {
if (f.uid === deleteFile.uid) {
deleteIdx = i
}
})
_uploadedPaths.splice(deleteIdx, 1)
setUploadedPaths(_uploadedPaths)
}}
multiple={multiple}
modalType={innerModalType}
/>
)
}
return new Promise(function (resolve) { const saveScreenCust = async (fileBlob) => {
axios.post(uploadOptions.url, data, {headers: headers}).then(response => { if (fileBlob) {
if (response.data.state === "success") { setIsUploading(true)
resolve(response.data) const blobData = await fetch(fileBlob).then((res) => res.blob())
}
setIsUploading(false) const data = new FormData()
}); const file = new File(
}) [blobData],
} 'name.' + (recordType?.audio ? 'mp3' : 'webm')
}; )
data.append('file', file)
const headers = { 'Content-Type': 'multipart/form-data' }
const getInnerModal = () => { return new Promise(function (resolve) {
switch (innerModalType) { axios
case 'iframe': .post(uploadOptions.url, data, { headers: headers })
return ( .then((response) => {
<Fragment> if (response.data.state === 'success') {
<input type="text" value={embedContent} placeholder={'https://'} resolve(response.data)
onInput={(e) => setEmbedContent(e.target.value) }
}/> setIsUploading(false)
<ul className={'atma-editor-soc-video'}> })
<li className={'youtube'}/> })
<li className={'vimeo'}/> }
{/* <li className={'vk'}/> */} }
<li className={'ok'}/>
<li className={'rutube'}/> const getInnerModal = () => {
</ul> switch (innerModalType) {
</Fragment> case 'iframe':
) return (
case 'iframe_custom': <IframeModal
return ( embedContent={embedContent}
<Fragment> setEmbedContent={setEmbedContent}
<textarea style={{width: '100%', height: '100%'}} rows={18} value={embedContent} placeholder={'<iframe></iframe>'} />
onInput={(e) => setEmbedContent(e.target.value)} )
case 'iframe_custom':
return (
<IframeCustomModal
embedContent={embedContent}
setEmbedContent={setEmbedContent}
/>
)
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>
)
case 'audio':
return (
<Fragment>{getUploader({ accept: '.wav, .mp3, .ogg' })}</Fragment>
)
case 'iframe_pdf':
return (
<Fragment>
{getUploader({
accept: 'application/pdf',
afterParams: ['no_convert=1']
})}
</Fragment>
)
case 'video':
return <Fragment>{getUploader({ accept: 'video/*' })}</Fragment>
case 'image':
return <Fragment>{getUploader({ accept: 'image/*' })}</Fragment>
case 'file':
return (
<Fragment>
{getUploader({ accept: '*', afterParams: ['no_convert=1'] })}
</Fragment>
)
case 'voicemessage':
return (
<Fragment>
{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' />
{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' />
)}
</div>
)}
</Fragment>
)
case 'screencust':
return (
<>
<Fragment>
{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
/> />
</Fragment> ) : (
) status === 'recording' && (
case 'iframe_pptx': <video
return ( className='webwrap-video'
<Fragment>{getUploader({accept: 'application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.openxmlformats-officedocument.presentationml.presentation', afterParams: ['no_convert=1']})}</Fragment> ref={videoRef}
) src={previewStream}
case 'audio': autoPlay
return ( controls={false}
<Fragment>{getUploader({accept: '.wav, .mp3, .ogg'})}</Fragment> />
) )
case 'iframe_pdf': )}
return ( {status === 'recording' && !mediaBlobUrl ? (
<Fragment>{getUploader({accept: 'application/pdf', afterParams: ['no_convert=1']})}</Fragment> <ReactStopwatch
) seconds={0}
case 'video': minutes={0}
return ( hours={0}
<Fragment>{getUploader({accept: 'video/*'})}</Fragment> render={({ formatted }) => {
) return (
case 'image': <span className='webwrap-timer'>{formatted}</span>
return ( )
<Fragment>{getUploader({accept: 'image/*'})}</Fragment> }}
) />
case 'file': ) : (
return ( <span className='webwrap-timer'>00:00:00</span>
<Fragment>{getUploader({accept: '*', afterParams: ['no_convert=1']})}</Fragment> )}
) {!mediaBlobUrl && (
case 'voicemessage': <div className='webwrap-start-border'>
return ( <button
<> onClick={
<Fragment> status === 'recording'
{ ? stopRecording
isMobile && : startRecording
<>
<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"}/>
{
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"}/>
}
</div>
}
</Fragment>
</>
)
case 'screencust':
return (
<>
<Fragment>
{
isMobile &&
<>
<div className={"webwrap"}>
<div>Запись экрана с мобильного устройства недоступна, <br/> запишите
стандартными функциями устройства и воспользуйтесь кнопкой «Загрузить видео»
</div>
</div>
</>
} }
{ className={
! isMobile && status === 'recording'
<> ? 'webwrap-record-center'
<div className={"webwrap"}> : 'webwrap-start-center'
<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>
</>
} }
</Fragment> />
</> </div>
) )}
case 'webcamera': </div>
return ( </div>
<> <div className='web-bottom-elements'>
<Fragment> {mediaBlobUrl && (
{ <div onClick={clearBlobUrl} className='web-button-wrap'>
isMobile && <div className='web-button-rerecord' />
<> <span className='web-button-rerecord-text'>
<div className={"webwrap"}> Перезаписать
<div>Видеозапись с мобильного устройства недоступна, <br/> запишите стандартными </span>
функциями устройства и воспользуйтесь кнопкой «Загрузить видео» </div>
</div> )}
</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>
</>
)}
</Fragment>
</>
)
case 'webcamera':
return (
<>
<Fragment>
{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'>{formatted}</span>
)
}}
/>
) : (
<span className='webwrap-timer'>00:00:00</span>
)}
{!mediaBlobUrl && (
<div className='webwrap-start-border'>
<button
onClick={
status === 'recording'
? stopRecording
: startRecording
} }
{ className={
! isMobile && status === 'recording'
<> ? 'webwrap-record-center'
<div className={"webwrap"}> : 'webwrap-start-center'
<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>
</>
} }
</Fragment> />
</> </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>
</>
)}
</Fragment>
</>
)
default:
return <div>Пусто</div>
}
}
const isDisabledAction = () => {
let isDisabled = false
switch (innerModalType) {
case 'video':
case 'image':
if (uploadOptions.url === null || uploadedPaths.length === 0) {
isDisabled = true
}
break
case 'screencust':
if (status === 'recording' || isUploading || !mediaBlobUrl) {
isDisabled = true
}
break
case 'voicemessage':
if (status === 'recording' || isUploading || !mediaBlobUrl) {
isDisabled = true
}
break
case 'webcamera':
if (status === 'recording' || isUploading || !mediaBlobUrl) {
isDisabled = true
}
break
case 'iframe':
try {
const url = new URL(embedContent)
switch (url.hostname) {
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: default:
return <div>Пусто</div> isDisabled = true
}
} catch (error) {
isDisabled = true
} }
break
case 'iframe_custom':
const regex = new RegExp(
'(?:<iframe[^>]*)(?:(?:\\/>)|(?:>.*?<\\/iframe>))'
)
isDisabled = !regex.test(embedContent)
break
} }
const isDisabledAction = () => { return isDisabled
let isDisabled = false; }
switch (innerModalType) { if (!editor) {
case 'video': return null
case 'image': }
if (uploadOptions.url === null || uploadedPaths.length === 0) {
isDisabled = true; const buttons =
} innerModalType === 'remove_iframe'
break; ? [
case 'screencust': {
if (status === 'recording' || isUploading || ! mediaBlobUrl) { title: 'Отмена',
isDisabled = true; className: ' atma-editor-cancel',
} onClick: () => {
break; stopRecording()
case 'voicemessage': unMuteAudio()
if (status === 'recording' || isUploading || ! mediaBlobUrl) { clearBlobUrl()
isDisabled = true; setUploaderUid(`uid${new Date()}`)
} setUploadedPaths([])
break; setModalIsOpen(false)
case 'webcamera': }
if (status === 'recording' || isUploading || ! mediaBlobUrl) { },
isDisabled = true; {
title: 'Удалить',
className: ' atma-editor-complete',
onClick: () => {
stopRecording()
unMuteAudio()
clearBlobUrl()
setUploaderUid(`uid${new Date()}`)
setUploadedPaths([])
setModalIsOpen(false)
}
}
]
: [
{
title: 'Отмена',
className: ' atma-editor-cancel',
onClick: () => {
stopRecording()
unMuteAudio()
clearBlobUrl()
setUploaderUid(`uid${new Date()}`)
setUploadedPaths([])
setModalIsOpen(false)
}
},
{
title:
mediaBlobUrl && uploadedPaths.length === 0
? isUploading
? 'Сохранение...'
: 'Вставить'
: 'Вставить',
className: ' atma-editor-complete',
onClick: async () => {
if (status === 'recording' || isUploading) {
return false
} else {
if (
document.querySelectorAll('.atma-editor-uploader-progress')
.length > 0
) {
if (
// eslint-disable-next-line no-undef
!confirm(
'Не полностью загруженные файлы будут утеряны. Вы уверены, что хотите продолжить?'
)
) {
return false
}
} }
break;
case 'iframe':
try { try {
let url = new URL(embedContent); switch (innerModalType) {
case 'image':
uploadedPaths.map((file, i) => {
editor.chain().focus().setImage({ src: file.path })
})
break
case 'video':
uploadedPaths.map((file, i) => {
editor
.chain()
.focus()
.setVideo({
src: file.path,
poster: file.path + '.jpg'
})
.run()
})
break
case 'voicemessage':
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()
}
})
}
}
break
case 'screencust':
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()
}
})
}
}
break
case 'webcamera':
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()
}
})
}
}
break
case 'iframe':
let _url = embedContent
const reg = /(http|https):\/\/([\w.]+\/?)\S*/
const url = new URL(
reg.test(_url) ? _url : 'https:' + _url
)
let urlId = url.pathname
.replace(/\/$/gi, '')
.split('/')
.pop()
switch (url.hostname) { switch (url.hostname) {
case 'rutube.ru': case 'rutube.ru':
case 'www.rutube.ru': case 'www.rutube.ru':
_url = `https://rutube.ru/pl/?pl_id&pl_type&pl_video=${urlId}`
break
case 'vimeo.com': case 'vimeo.com':
_url = `https://player.vimeo.com/video/${urlId}`
break
case 'ok.ru': case 'ok.ru':
case 'www.ok.ru': case 'www.ok.ru':
_url = `//ok.ru/videoembed/${urlId}`
break
case 'youtu.be': case 'youtu.be':
case 'youtube.com': case 'youtube.com':
case 'www.youtube.com': case 'www.youtube.com':
break; if (
default: url.hostname.indexOf('youtu.be') === -1 &&
isDisabled = true; url.search !== ''
} ) {
if (url.searchParams.get('v')) {
} catch (error) { urlId = url.searchParams.get('v')
isDisabled = true; }
}
_url = `https://www.youtube.com/embed/${urlId}`
break
}
editor.chain().focus().setIframe({ src: _url }).run()
break
case 'iframe_custom':
editor.chain().focus().insertContent(embedContent).run()
break
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
case 'audio':
uploadedPaths.map((file) => {
editor
.chain()
.focus()
.insertContent(
`<audio class="audio-player" controls="true" src="${file.path}" />`
)
.run()
})
break
case 'iframe_pdf':
uploadedPaths.map((file, i) => {
editor
.chain()
.focus()
.insertContent(
`<iframe src="https://docs.google.com/viewer?embedded=true&url=${file.path}" width="100%" height="800px" frameBorder="0"></iframe>`
)
.run()
})
break
case 'file':
uploadedPaths.map((file, i) => {
let exp = file.path.split('.')
exp = exp[exp.length - 1]
editor
.chain()
.focus()
.insertContent(
`
<a href="${file.path}" target="_blank" download="${file.name}.${exp}" data-size="${file.size}">${file.name}</a>
`
)
.run()
})
break
}
setModalIsOpen(false)
clearBlobUrl()
setUploaderUid(`uid${new Date()}`)
setEmbedContent('')
setUploadedPaths([])
setModalTitle('')
} catch (err) {
console.log(err)
setModalIsOpen(false)
clearBlobUrl()
setUploaderUid(`uid${new Date()}`)
setEmbedContent('')
setUploadedPaths([])
setModalTitle('')
} }
break; }
case 'iframe_custom': },
let regex = new RegExp('(?:<iframe[^>]*)(?:(?:\\/>)|(?:>.*?<\\/iframe>))'); disabled: isDisabledAction()
isDisabled = !regex.test(embedContent); }
break; ]
}
return isDisabled; return (
} <div className='atma-editor-wrap' style={style}>
<div className='atma-editor'>
<ToolBar editor={editor} {...{ toolsOptions }} {...{ toolsLib }} />
<BubbleMenu
typpyOptions={{ followCursor: true }}
editor={editor}
shouldShow={({ ...o }) => {
let items = []
if (
o.from !== o.to &&
editor.isActive('paragraph') &&
editor.isActive('image') === false &&
document.querySelectorAll('.selectedCell').length === 0
) {
items = initialBubbleItems
}
if ( ! editor) { if (editor.isActive('image') === true) {
return null items = ['alignLeft', 'alignCenter', 'alignRight']
} }
setFocusFromTo([o.from, o.to].join(':'))
return ( if (items.length > 0) {
<div setBubbleItems(items)
className="atma-editor-wrap" return true
style={style} }
}}
tippyOptions={{ duration: 100 }}
> >
<div className="atma-editor"> <div
<ToolBar className='atma-editor-bubble'
editor={editor} onClick={(e) => e.stopPropagation()}
{...{toolsOptions}} >
{...{toolsLib}} {colorsSelected !== null
? colors[colorsSelected].map((itemColor, i) => {
/> return (
<BubbleMenu typpyOptions={{followCursor: true,}} editor={editor} shouldShow={({...o}) => { <div
let items = []; key={'colors' + colorsSelected + i}
className={
if (o.from !== o.to && editor.isActive('paragraph') && editor.isActive('image') === false && document.querySelectorAll('.selectedCell').length === 0) { 'qcolors' + (itemColor === 'none' ? ' unset' : '')
items = initialBubbleItems; }
} style={{ background: itemColor }}
onClick={() => {
if (editor.isActive('image') === true) { if (itemColor === 'none') {
items = ['alignLeft', 'alignCenter', 'alignRight']; colorsSelected === 'color'
} ? editor
setFocusFromTo([o.from, o.to].join(':')); .chain()
.focus()
if (items.length > 0) { .unsetHighlight()
setBubbleItems(items); .unsetColor()
return true; .run()
} : editor
}} tippyOptions={{duration: 100}}> .chain()
<div className={"atma-editor-bubble"} onClick={e => e.stopPropagation()}> .focus()
{ .unsetColor()
colorsSelected !== null ? .unsetHighlight()
colors[colorsSelected].map((itemColor, i) => { .run()
return (<div key={'colors' + colorsSelected + i} } else {
className={'qcolors' + (itemColor === 'none' ? ' unset' : '')} colorsSelected === 'color'
style={{background: itemColor}} onClick={() => { ? editor
.chain()
if (itemColor === 'none') { .focus()
colorsSelected === 'color' ? .unsetHighlight()
editor.chain().focus().unsetHighlight().unsetColor().run() : .setColor(itemColor)
editor.chain().focus().unsetColor().unsetHighlight().run(); .run()
} else { : editor
colorsSelected === 'color' ? .chain()
editor.chain().focus().unsetHighlight().setColor(itemColor).run() : .focus()
editor.chain().focus().unsetColor().toggleHighlight({color: itemColor}).run(); .unsetColor()
} .toggleHighlight({ color: itemColor })
.run()
setColorsSelected(null);
}}/>)
}) : bubbleItems.map((type, i) => {
if (type === '|') {
return (<div key={'bubbleSeparator' + i} className={'qseparator'}/>)
} else {
return (
<div
key={'bubbleItems' + i}
className={'qicon q' + type + (editor.isActive(type) ? ' active' : '')}
title={toolsLib[type] ? toolsLib[type].title : ''}
onClick={toolsLib[type].onClick}
/>
)
}
})
} }
</div> setColorsSelected(null)
</BubbleMenu> }}
<EditorContent />
editor={editor} )
className={'atma-editor-content'} })
/> : bubbleItems.map((type, i) => {
</div> if (type === '|') {
<EditorModal return (
isOpen={modalIsOpen} <div key={'bubbleSeparator' + i} className='qseparator' />
title={modalTitle} )
> } else {
{ return (
getInnerModal() <div
} key={'bubbleItems' + i}
{ className={
buildActionsModal([ 'qicon q' +
{ type +
title: 'Отмена', (editor.isActive(type) ? ' active' : '')
className: ' atma-editor-cancel',
onClick: () => {
stopRecording();
unMuteAudio();
clearBlobUrl();
setUploaderUid(`uid${new Date()}`);
setUploadedPaths([]);
setModalIsOpen(false);
}
},
{
title: (mediaBlobUrl && uploadedPaths.length === 0) ? (isUploading ? 'Сохранение...' : 'Вставить') : 'Вставить',
className: ' atma-editor-complete',
onClick: async () => {
if ((status === 'recording' || isUploading)) {
return false;
} else {
if (document.querySelectorAll('.atma-editor-uploader-progress').length > 0) {
if ( ! confirm('Не полностью загруженные файлы будут утеряны. Вы уверены, что хотите продолжить?')) {
return false;
}
}
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':
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();
}
});
}
}
break
case 'screencust':
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();
}
});
}
}
break
case 'webcamera':
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();
}
});
}
}
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');
}
}
_url = `https://www.youtube.com/embed/${urlId}`;
break
}
editor.chain().focus().setIframe({src: _url}).run();
break
case 'iframe_custom':
editor.chain().focus().insertContent(embedContent).run();
break
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
case 'iframe_pdf':
uploadedPaths.map((file, i)=>{
editor.chain().focus().insertContent(`<iframe src="https://docs.google.com/viewer?embedded=true&url=${file.path}" width="100%" height="800px" frameBorder="0"></iframe>`).run();
})
break
case 'audio':
uploadedPaths.map((file) => {
editor.chain().focus().insertContent(`<audio class="audio-player" controls="true" src="${file.path}" />`).run()
})
break;
case 'file':
uploadedPaths.map((file, i) => {
let exp = file.path.split('.');
exp = exp[exp.length - 1]
editor.chain().focus().insertContent(`<a href="${file.path}" target="_blank" download="${file.name}.${exp}" data-size="${file.size}">${file.name}</a>`).run();
});
break
}
setModalIsOpen(false);
clearBlobUrl();
setUploaderUid(`uid${new Date()}`);
setEmbedContent('');
setUploadedPaths([]);
setModalTitle('');
} catch (err) {
console.log(err);
setModalIsOpen(false);
clearBlobUrl();
setUploaderUid(`uid${new Date()}`);
setEmbedContent('');
setUploadedPaths([]);
setModalTitle('');
}
}
},
disabled: isDisabledAction()
} }
]) title={toolsLib[type] ? toolsLib[type].title : ''}
} onClick={toolsLib[type].onClick}
</EditorModal> />
</div> )
) }
})}
</div>
</BubbleMenu>
<EditorContent editor={editor} className='atma-editor-content' />
</div>
<EditorModal isOpen={modalIsOpen} title={modalTitle}>
{getInnerModal()}
{buildActionsModal(buttons)}
</EditorModal>
</div>
)
} }
export default QEditor; export default QEditor
import { Node, mergeAttributes } from '@tiptap/core' import { Node, mergeAttributes } from '@tiptap/core'
const Iframe = Node.create({ const Iframe = Node.create({
name: 'iframe', name: 'iframe',
group: 'block', group: 'block',
selectable: false, selectable: false,
draggable: true, draggable: true,
atom: true, atom: true,
addAttributes() { addAttributes() {
return { return {
"src": { src: {
default: null default: null
}, },
"frameborder": { frameborder: {
default: 0, default: 0
}, },
"allowfullscreen": { allowfullscreen: {
default: true, default: true,
parseHTML: () => { parseHTML: () => {
console.log(this) console.log(this)
},
},
} }
}, }
}
},
parseHTML() { parseHTML() {
return [ return [
{ {
tag: 'iframe', tag: 'iframe'
}, }
] ]
}, },
renderHTML({ HTMLAttributes }) { renderHTML({ HTMLAttributes }) {
return ['iframe', mergeAttributes(HTMLAttributes)]; return ['iframe', mergeAttributes(HTMLAttributes)]
}, },
addNodeView() { addNodeView() {
return ({ editor, node, ...a }) => { return ({ editor, node, ...a }) => {
const container = document.createElement('div')
const iframe = document.createElement('iframe')
iframe.src = node.attrs.src
iframe.allowfullscreen = node.attrs.allowfullscreen
iframe.classList.add('customIframe')
// div.className = 'aspect-w-16 aspect-h-9' + (editor.isEditable ? ' cursor-pointer' : ''); const closeBtn = document.createElement('button')
const iframe = document.createElement('iframe'); closeBtn.textContent = 'X'
if (editor.isEditable) { closeBtn.classList.add('closeBtn')
iframe.className = 'pointer-events-none'; closeBtn.addEventListener('click', function () {
} container.remove()
})
iframe.src = node.attrs.src; // if (editor.isEditable) {
iframe.frameBorder = node.attrs.frameborder; // container.classList.add('pointer-events-none');
iframe.allowfullscreen = node.attrs.allowfullscreen; // }
iframe.style = 'width:1280px;height:auto;aspect-ratio: 16 / 9;';
// div.append(video); container.append(closeBtn, iframe)
return {
dom: iframe, return {
} dom: container
} }
}, }
},
addCommands() { addCommands() {
return { return {
setIframe: (options) => ({ tr, dispatch }) => { setIframe:
const { selection } = tr (options) =>
const node = this.type.create(options) ({ tr, dispatch }) => {
// const { selection } = tr
if (dispatch) { const node = this.type.create(options)
tr.replaceRangeWith(selection.from, selection.to, node)
}
return true if (dispatch) {
}, tr.replaceRangeWith(selection.from, selection.to, node)
}
return true
} }
}, }
}); }
})
export default Iframe; export default Iframe
...@@ -1045,4 +1045,25 @@ body{ ...@@ -1045,4 +1045,25 @@ body{
.qseparator{ .qseparator{
width: 16px; width: 16px;
} }
.closeBtn {
position: relative;
display: flex;
justify-content: end;
border-radius: 50%;
border: none;
background-color: #2677e3;
color: #fff;
font-size: 0.5rem;
padding: 4px 6px;
top: 10px;
cursor: pointer;
right: 8px;
}
.customIframe {
width:1280px;
height:auto;
aspect-ratio: 16 / 9;
}
} }
import React, { Fragment } from 'react'
export default function IframeCustomModal({ embedContent, setEmbedContent }) {
return (
<Fragment>
<textarea
style={{ width: '100%', height: '100%' }}
rows={18}
value={embedContent}
placeholder='<iframe></iframe>'
onInput={(e) => setEmbedContent(e.target.value)}
/>
</Fragment>
)
}
import React, { Fragment } from 'react'
export default function IframeModal({ embedContent, setEmbedContent }) {
return (
<Fragment>
<input
type='text'
value={embedContent}
placeholder='https://'
onInput={(e) => setEmbedContent(e.target.value)}
/>
<ul className='atma-editor-soc-video'>
<li className='youtube' />
<li className='vimeo' />
{/* <li className={'vk'}/> */}
<li className='ok' />
<li className='rutube' />
</ul>
</Fragment>
)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment