Leaf.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 from 'react'
  21. import { RenderLeafProps } from 'slate-react'
  22. import { TextStyles } from '../Element/constants'
  23. import { ElementPropertyList } from './constants'
  24. interface ILeafProps extends RenderLeafProps {
  25. onFormatText?: (text: string) => string
  26. }
  27. const Leaf: React.FC<ILeafProps> = (props) => {
  28. const { attributes, children, leaf, onFormatText } = props
  29. let wrappedChildren = children
  30. if (leaf.text && onFormatText) {
  31. leaf.text = onFormatText(leaf.text)
  32. }
  33. const cssStyle: React.CSSProperties = ElementPropertyList.reduce(
  34. (obj, propertyName) => {
  35. if (leaf[propertyName]) {
  36. obj[propertyName] = leaf[propertyName]
  37. }
  38. return obj
  39. },
  40. {}
  41. )
  42. if (leaf[TextStyles.Bold]) {
  43. wrappedChildren = <strong>{wrappedChildren}</strong>
  44. }
  45. if (leaf[TextStyles.Italic]) {
  46. wrappedChildren = <em>{wrappedChildren}</em>
  47. }
  48. if (leaf[TextStyles.Underline]) {
  49. wrappedChildren = <u>{wrappedChildren}</u>
  50. }
  51. if (leaf[TextStyles.StrikeThrough]) {
  52. wrappedChildren = <s>{wrappedChildren}</s>
  53. }
  54. if (leaf[TextStyles.Code]) {
  55. wrappedChildren = <code>{wrappedChildren}</code>
  56. }
  57. return (
  58. <span {...attributes} style={cssStyle}>
  59. {wrappedChildren}
  60. </span>
  61. )
  62. }
  63. export default Leaf