QEditor.jsx 14.1 KB
Newer Older
Рамис's avatar
Рамис committed
1
import React, { Fragment } from 'react'
Рамис's avatar
fix bug    
Рамис committed
2
3
import ReactQuill, { Quill } from 'react-quill'
import 'react-quill/dist/quill.snow.css'
Рамис's avatar
Рамис committed
4
import './index.scss'
Рамис's avatar
fix bug    
Рамис committed
5
6
7
8
9
10
11
12
import "katex/dist/katex.min.css"
import ImageBlot from "./blots/ImageBlot"
import VideoBlot from "./blots/VideoBlot"
import VideoLocalBlot from "./blots/VideoLocalBlot"
import EditorModal from "./components/EditorModal"
import Uploader from "./components/Uploader"
import BlotFormatter from 'quill-blot-formatter'
import ResizeImageBlot from "./blots/ResizeImageBlot"
Рамис's avatar
Рамис committed
13
14
15
16
17
18
19
20
21
22
23
24
import katex from "katex";

export default class QEditor extends React.Component {
    constructor (props) {
        super(props)
        this.state = {
            init: false,
            modalIsOpen: false,
            innerModalType: null,
            quillRef: null,
            uploadedPaths: [],
            uploaderUid: 'uid' + new Date(),
25
26
            embedContent: '',
            focusedIndex: 0
Рамис's avatar
Рамис committed
27
28
        }

Рамис's avatar
Рамис committed
29

Рамис's avatar
Рамис committed
30
        Quill.register('formats/videoLocal', VideoLocalBlot)
Рамис's avatar
fix bug    
Рамис committed
31
        Quill.register('modules/blotFormatter', BlotFormatter)
Рамис's avatar
Рамис committed
32
        Quill.register('formats/image', ImageBlot)
Рамис's avatar
Рамис committed
33
        Quill.register('formats/video', VideoBlot)
Рамис's avatar
Рамис committed
34
35
36
37
38
    }

    componentDidMount () {
        this.setState({
            init: true
Рамис's avatar
fix    
Рамис committed
39
        });
Рамис's avatar
Рамис committed
40

Рамис's avatar
Рамис committed
41
42
43
44
45
46
47
48
49
50
51
52
53
        // if(window.checkOptimizeVideo === undefined){
        //     window.checkOptimizeVideo = setInterval(()=>{
        //         const children = [...document.getElementsByTagName('video')];
        //
        //         if(children.length > 0){
        //             children.forEach((video, i) => {
        //                 if(video.duration === 2.48){
        //                     video.setAttribute('src', video.getAttribute('src').split('?')[0] + `?f=${parseInt(Date.now()/1000)}`)
        //                 }
        //             })
        //         }
        //     }, 3000);
        // }
Рамис's avatar
Рамис committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    }

    modules = {
        toolbar: {
            container: [
                [{header: [2, 3, 4, false]}],
                ['bold', 'italic', 'underline', 'strike', 'blockquote'],
                [
                    {list: 'ordered'},
                    {list: 'bullet'},
                    {indent: '-1'},
                    {indent: '+1'}
                ],
                [{align: []}, {color: []}, {background: []}],
Рамис's avatar
Рамис committed
68
                ['link', 'image', 'video', 'videoLocal'],
Рамис's avatar
Рамис committed
69
70
71
72
73
74
                ['formula'],
                ['clean']
            ],

            handlers: {
                video: (a) => {
75
76
77
78
                    const quill = this.quillRef.getEditor();
                    let range = quill.getSelection();
                    let index = range ? range.index : 0;

Рамис's avatar
Рамис committed
79
80
                    this.setState(
                        {
81
82
                            innerModalType: 'video',
                            focusedIndex: index
Рамис's avatar
Рамис committed
83
84
85
86
                        },
                        () => this.editorModal.show({title: 'Видео по ссылке'})
                    )
                },
Рамис's avatar
Рамис committed
87
                videoLocal: (a) => {
88
89
90
91
92
                    const quill = this.quillRef.getEditor();
                    let range = quill.getSelection();
                    let index = range ? range.index : 0;


Рамис's avatar
Рамис committed
93
                    this.setState({
94
95
                        innerModalType: 'videoLocal',
                        focusedIndex: index
Рамис's avatar
Рамис committed
96
                    }, () => this.editorModal.show({title: 'Загрузить видео'}));
Рамис's avatar
Рамис committed
97
                },
Рамис's avatar
Рамис committed
98
                image: (a) => {
99
100
101
102
                    const quill = this.quillRef.getEditor();
                    let range = quill.getSelection();
                    let index = range ? range.index : 0;

Рамис's avatar
Рамис committed
103
                    this.setState({
104
105
                        innerModalType: 'image',
                        focusedIndex: index
Рамис's avatar
Рамис committed
106
107
108
109
                    }, () => this.editorModal.show({title: 'Загрузить изображение'}));
                }
            }
        },
Рамис's avatar
fix bug    
Рамис committed
110
111
112
        blotFormatter: {
            specs: [ ResizeImageBlot ],
        }
Рамис's avatar
Рамис committed
113
114
115
116
117
118
119
    }

    formats = [
        'header',
        'bold', 'italic', 'underline', 'strike', 'blockquote',
        'list', 'bullet', 'indent',
        'align',
Рамис's avatar
Рамис committed
120
        'link', 'image', 'color', 'background', 'video', 'videoLocal',
121
        'formula',
Рамис's avatar
Рамис committed
122
123
124
125
126
127
128
129
130
131
132
    ]

    buildActionsModal (buttons = []) {
        if (buttons.length === 0) {
            return null;
        }

        return (
            <div className={'atma-editor-modal-action'}>
                {
                    buttons.map((btn, i) => (
Рамис's avatar
Рамис committed
133
                        <button disabled={ btn.disabled } type={'button'} key={'mAction' + i} className={'atma-editor-btn' + btn.className}
Рамис's avatar
Рамис committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
                                onClick={btn.onClick}>{btn.title}</button>
                    ))
                }
            </div>
        )
    }

    getInnerModal () {
        switch (this.state.innerModalType) {
            case 'video':
                return (
                    <Fragment>
                        <input type="text" value={this.state.embedContent} placeholder={'https://'} onInput={(e) => {
                            this.setState({
                                embedContent: e.target.value
                            })
                        }}/>
                        <ul className={'atma-editor-soc-video'}>
                            <li className={'youtube'}/>
                            <li className={'vimeo'}/>
Рамис's avatar
Рамис committed
154
                            {/* <li className={'vk'}/> */}
Рамис's avatar
Рамис committed
155
                            <li className={'ok'}/>
Рамис's avatar
fix bug    
Рамис committed
156
                            <li className={'rutube'}/>
Рамис's avatar
Рамис committed
157
158
159
160
161
162
163
164
165
                        </ul>
                    </Fragment>
                )
            case 'videoLocal':
                return (
                    <Fragment>
                        <Uploader
                            key={this.state.uploaderUid}
                            accept={'video/*'}
Рамис's avatar
Рамис committed
166
167
                            action={ this.props.uploadOptions.url }
                            errorMessage={ this.props.uploadOptions.errorMessage }
Рамис's avatar
Рамис committed
168
169
170
171
172
173
                            onSuccess={(file) => {
                                let uploadedPaths = this.state.uploadedPaths;

                                uploadedPaths.push(file);
                                this.setState({uploadedPaths});
                            }}
Рамис's avatar
Рамис committed
174
175
176
177
178
179
180
181
182
183
184
185
186
187
                            onDelete={(deleteFile)=>{
                                let deleteIdx = null;
                                let uploadedPaths = this.state.uploadedPaths;

                                uploadedPaths.map((f, i)=>{
                                    if(f.uid === deleteFile.uid){
                                        deleteIdx = i;
                                    }
                                });
                                uploadedPaths.splice(deleteIdx, 1);
                                this.setState({
                                    uploadedPaths
                                })
                            }}
Рамис's avatar
Рамис committed
188
189
190
191
192
193
194
195
196
197
                            multiple={true}
                        />
                    </Fragment>
                )
            case 'image':
                return (
                    <Fragment>
                        <Uploader
                            key={this.state.uploaderUid}
                            accept={'image/*'}
Рамис's avatar
Рамис committed
198
199
                            action={ this.props.uploadOptions.url }
                            errorMessage={ this.props.uploadOptions.errorMessage }
Рамис's avatar
Рамис committed
200
201
202
203
204
205
                            onSuccess={(file) => {
                                let uploadedPaths = this.state.uploadedPaths;

                                uploadedPaths.push(file);
                                this.setState({uploadedPaths});
                            }}
Рамис's avatar
Рамис committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
                            onDelete={(deleteFile)=>{
                                let deleteIdx = null;
                                let uploadedPaths = this.state.uploadedPaths;

                                uploadedPaths.map((f, i)=>{
                                    if(f.uid === deleteFile.uid){
                                        deleteIdx = i;
                                    }
                                });
                                uploadedPaths.splice(deleteIdx, 1);
                                this.setState({
                                    uploadedPaths
                                })
                            }}
Рамис's avatar
Рамис committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
                            multiple={true}
                        />
                    </Fragment>
                )
            default:
                return <div>Пусто</div>
        }
    }

    quillInsert () {
        const quill = this.quillRef.getEditor();
        let range = quill.getSelection();
        let index = range ? range.index : 0;

234
235
236
237
238
        if(this.state.focusedIndex > 0){
            index = this.state.focusedIndex;
        }

        switch (this.state.innerModalType) {
Рамис's avatar
Рамис committed
239
240
241
242
243
244
            case 'image':
            case 'videoLocal':
                this.state.uploadedPaths.map((file, i) => {
                    quill.insertEmbed(index, this.state.innerModalType, file.path, Quill.sources.USER);
                    quill.setSelection(index + 1);
                });
Рамис's avatar
Рамис committed
245
246
247
248

                this.setState({
                    uploadedPaths: []
                })
Рамис's avatar
Рамис committed
249
250
251
252
253
254
255
256
                break
            default:
                quill.insertEmbed(index, this.state.innerModalType, this.state.embedContent, Quill.sources.USER);
                quill.setSelection(index + 1);
        }

        this.setState({
            uploaderUid: `uid${new Date()}`,
257
            embedContent: '',
Рамис's avatar
Рамис committed
258
            uplodedPaths: [],
259
            focusedIndex: 0
Рамис's avatar
Рамис committed
260
261
262
        }, () => this.editorModal.hide());
    }

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
    isDisabledAction(){
        let { innerModalType, uploadedPaths, embedContent } = this.state;
        let isDisabled = false;

        switch(innerModalType){
            case 'videoLocal':
            case 'image':
                if(this.props.uploadOptions.url === null || uploadedPaths.length === 0){
                    isDisabled = true;
                }
                break;
            case 'video':
                try{
                    let 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:
                            isDisabled = true;
                    }

                }catch (error){
                    isDisabled = true;
                }
                break;
        }

        return isDisabled;
    }

Рамис's avatar
Рамис committed
301
302
    render () {
        let {init, innerModalType, modalIsOpen} = this.state;
303
        let { value, style } = this.props;
Рамис's avatar
Рамис committed
304
305
306

        window.katex = katex;

Рамис's avatar
Рамис committed
307
        if ( !this.state.init) {
Рамис's avatar
Рамис committed
308
309
310
311
            return null;
        }
        return (
            <Fragment>
312
                <div className="atma-editor-wrap" style={style}>
Рамис's avatar
Рамис committed
313
                    <div className={'atma-editor'} data-lang={ this.props.lang ? this.props.lang : 'ru' }>
Рамис's avatar
Рамис committed
314
315
316
317
                        <ReactQuill
                            ref={ref => this.quillRef = ref}
                            defaultValue={value}
                            theme="snow"
Рамис's avatar
Рамис committed
318
319
320
                            onChange={value => {
                                this.props.onChange(value)
                            }}
Рамис's avatar
Рамис committed
321
322
323
324
325
                            modules={this.modules}
                            formats={this.formats}
                            onChangeSelection={(range, source, editor) => {
                                // console.log(range, source, editor.getText());
                            }}
Рамис's avatar
Рамис committed
326
                            scrollingContainer={'html'}
Рамис's avatar
Рамис committed
327
328
329
330
331
332
333
334
335
336
337
338
                        />
                    </div>
                    <EditorModal
                        isOpen={modalIsOpen}
                        ref={ref => this.editorModal = ref}
                    >
                        {this.getInnerModal()}
                        {this.buildActionsModal([
                            {
                                title: 'Отмена',
                                className: ' atma-editor-cancel',
                                onClick: () => {
339
340
341
342
                                    const quill = this.quillRef.getEditor();
                                    let range = quill.getSelection();
                                    let index = range ? range.index : 0;

Рамис's avatar
Рамис committed
343
344
                                    this.setState(
                                        {
345
346
                                            uploaderUid: `uid${new Date()}`,
                                            uploadedPaths: []
Рамис's avatar
Рамис committed
347
348
349
350
351
352
353
354
                                        },
                                        () => this.editorModal.hide()
                                    )
                                }
                            },
                            {
                                title: 'Вставить',
                                className: ' atma-editor-complete',
Рамис's avatar
Рамис committed
355
356
357
358
359
360
361
362
363
                                onClick: () => {
                                    if(document.querySelectorAll('.atma-editor-uploader-progress').length > 0){
                                        if(!confirm('Не полностью загруженные файлы будут утеряны. Вы уверены, что хотите продолжить?')){
                                            return false;
                                        }
                                    }

                                    this.quillInsert()
                                },
364
                                disabled: this.isDisabledAction()
Рамис's avatar
Рамис committed
365
366
367
368
369
370
371
372
373
374
375
                            }
                        ])
                        }
                    </EditorModal>
                </div>
            </Fragment>
        )
    }
}

QEditor.defaultProps = {
Рамис's avatar
Рамис committed
376
    onChange: ()=>{},
Рамис's avatar
Рамис committed
377
378
379
    lang: 'ru',
    uploadOptions: {
        url: null,
Рамис's avatar
Рамис committed
380
        errorMessage: 'Загрузка временно невозможна'
381
382
    },
    style: {}
Рамис's avatar
Рамис committed
383
}