withImages.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * <<
  3. * Davinci
  4. * ==
  5. * Copyright (C) 2016 - 2017 EDP
  6. * ==
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. * >>
  19. */
  20. import { Transforms } from 'slate'
  21. import { ReactEditor } from 'slate-react'
  22. import { isUrl, isImagePath } from 'utils/util'
  23. import { ElementTypes } from '../constants'
  24. const insertImage = (editor: ReactEditor, url: string | ArrayBuffer) => {
  25. const text = { text: '' }
  26. const image = { type: ElementTypes.Image, url, children: [text] }
  27. Transforms.insertNodes(editor, image)
  28. }
  29. const isImageUrl = (url: string) => {
  30. if (!url) {
  31. return false
  32. }
  33. if (!isUrl(url)) {
  34. return false
  35. }
  36. const { pathname } = new URL(url)
  37. return isImagePath(pathname)
  38. }
  39. const withImages = (editor: ReactEditor) => {
  40. const { insertData } = editor
  41. editor.insertData = (data) => {
  42. const text = data.getData('text/plain')
  43. const { files } = data
  44. if (files && files.length) {
  45. for (let idx = 0; idx < files.length; idx++) {
  46. const reader = new FileReader()
  47. const file = files[idx]
  48. const [mine] = file.type.split('/')
  49. if (mine === 'image') {
  50. reader.addEventListener('load', () => {
  51. const url = reader.result
  52. insertImage(editor, url)
  53. })
  54. reader.readAsDataURL(file)
  55. }
  56. }
  57. } else if (isImageUrl(text)) {
  58. insertImage(editor, text)
  59. } else {
  60. insertData(data)
  61. }
  62. }
  63. return editor
  64. }
  65. export default withImages