withTables.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 { ReactEditor } from 'slate-react'
  21. import { Editor, Range, Point } from 'slate'
  22. import { ElementTypes } from '../constants'
  23. const withTables = (editor: ReactEditor) => {
  24. const { deleteBackward, deleteForward, insertBreak } = editor
  25. editor.deleteBackward = (unit) => {
  26. const { selection } = editor
  27. if (selection && Range.isCollapsed(selection)) {
  28. const [cell] = Editor.nodes(editor, {
  29. match: (n) => n.type === ElementTypes.TableCell
  30. })
  31. if (cell) {
  32. const [, cellPath] = cell
  33. const start = Editor.start(editor, cellPath)
  34. if (Point.equals(selection.anchor, start)) {
  35. return
  36. }
  37. }
  38. }
  39. deleteBackward(unit)
  40. }
  41. editor.deleteForward = (unit) => {
  42. const { selection } = editor
  43. if (selection && Range.isCollapsed(selection)) {
  44. const [cell] = Editor.nodes(editor, {
  45. match: (n) => n.type === ElementTypes.TableCell
  46. })
  47. if (cell) {
  48. const [, cellPath] = cell
  49. const end = Editor.end(editor, cellPath)
  50. if (Point.equals(selection.anchor, end)) {
  51. return
  52. }
  53. }
  54. }
  55. deleteForward(unit)
  56. }
  57. editor.insertBreak = () => {
  58. const { selection } = editor
  59. if (selection) {
  60. const [table] = Editor.nodes(editor, {
  61. match: (n) => n.type === ElementTypes.Table
  62. })
  63. if (table) {
  64. return
  65. }
  66. }
  67. insertBreak()
  68. }
  69. return editor
  70. }
  71. export default withTables