ImageElement.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 React, { DOMAttributes, useMemo } from 'react'
  21. import classnames from 'classnames'
  22. import { Transforms } from 'slate'
  23. import {
  24. RenderElementProps,
  25. ReactEditor,
  26. useSelected,
  27. useReadOnly,
  28. useSlate
  29. } from 'slate-react'
  30. import { Resizable, ResizeCallbackData } from 'libs/react-resizable'
  31. import './Element.less'
  32. const ImageElement: React.FC<RenderElementProps> = (props) => {
  33. const { attributes, children, element } = props
  34. const editor = useSlate()
  35. const readOnly = useReadOnly()
  36. const selected = useSelected()
  37. const resize = (_, data: ResizeCallbackData) => {
  38. const path = ReactEditor.findPath(editor, element)
  39. Transforms.setNodes(editor, { width: data.size.width }, { at: path })
  40. }
  41. if (readOnly) {
  42. return (
  43. <div {...attributes}>
  44. {children}
  45. <img src={element.url} width={element.width} />
  46. </div>
  47. )
  48. }
  49. const cls = classnames({
  50. 'richtext-image-element': true,
  51. 'richtext-image-element-selected': selected
  52. })
  53. const width = +element.width || 400
  54. return (
  55. <div {...attributes} className={cls}>
  56. {children}
  57. <Resizable
  58. width={width}
  59. axis="x"
  60. resizeHandles={['e']}
  61. onResize={resize}
  62. >
  63. <div style={{ width }}>
  64. <img src={element.url} width={element.width} />
  65. </div>
  66. </Resizable>
  67. </div>
  68. )
  69. }
  70. export default ImageElement