Field.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, { useMemo, useCallback } from 'react'
  21. import { Dropdown, Menu, Icon } from 'antd'
  22. import { useSlate } from 'slate-react'
  23. const MenuItem = Menu.Item
  24. interface IFieldProps {
  25. mapFields: object
  26. fieldBoundaries: [string, string]
  27. }
  28. const Field: React.FC<IFieldProps> = (props) => {
  29. const editor = useSlate()
  30. const { mapFields, fieldBoundaries } = props
  31. const selectField = useCallback((name: string) => {
  32. const [prefix, suffix] = fieldBoundaries
  33. editor.insertNode({ text: `${prefix}${name}${suffix}` })
  34. }, [])
  35. const menuField = useMemo(
  36. () =>
  37. Object.keys(mapFields).length ? (
  38. <Menu>
  39. {Object.keys(mapFields).map((fieldName) => (
  40. <MenuItem key={fieldName}>
  41. <FieldItem name={fieldName} onSelect={selectField} />
  42. </MenuItem>
  43. ))}
  44. </Menu>
  45. ) : (
  46. <Menu>
  47. <MenuItem>暂无可用字段</MenuItem>
  48. </Menu>
  49. ),
  50. [mapFields]
  51. )
  52. return (
  53. <Dropdown trigger={['click']} overlay={menuField}>
  54. <Icon type="form" />
  55. </Dropdown>
  56. )
  57. }
  58. interface IFieldItemProps {
  59. name: string
  60. onSelect: (name: string) => void
  61. }
  62. const FieldItem: React.FC<IFieldItemProps> = (props) => {
  63. const { name, onSelect } = props
  64. const select = useCallback(() => {
  65. onSelect(name)
  66. }, [name, onSelect])
  67. return (
  68. <a href="javascript:void(0)" onClick={select}>
  69. {name}
  70. </a>
  71. )
  72. }
  73. export default Field