File size: 5,901 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import propisValid from '@emotion/is-prop-valid';
import { lazyLoad } from '@react-page/editor';
import isObject from 'lodash.isobject';
import type { DependencyList } from 'react';
import React, { useCallback } from 'react';
import type { RenderElementProps, RenderLeafProps } from 'slate-react';
import type { SlatePlugin } from '../types/SlatePlugin';
import type { SlatePluginDefinition } from '../types/slatePluginDefinitions';
import { getTextContents } from '../utils/getTextContent';
import {
  useComponentMarkPlugins,
  useComponentNodePlugins,
} from './pluginHooks';

// lazy load as it uses slate library. We don't want to bundle that in readonly mode
const VoidEditableElement = lazyLoad(() => import('./VoidEditableElement'));

type Data = {
  [key: string]: unknown;
};
const pickNativeProps = (data?: Data): Data => {
  if (!data || !isObject(data)) {
    return {};
  }
  return Object.keys(data).reduce((acc, key) => {
    if (propisValid(key)) {
      return {
        ...acc,
        [key]: data[key],
      };
    }
    return acc;
  }, {});
};
type Injections = {
  useSelected: () => boolean;
  useFocused: () => boolean;
  readOnly: boolean;
};
const STATIC_INJECTIONS = {
  useFocused: () => false,
  useSelected: () => false,
  readOnly: true,
};

export const useRenderElement = (
  {
    plugins,
    defaultPluginType,
    injections = STATIC_INJECTIONS,
  }: {
    plugins: SlatePlugin[];
    defaultPluginType: string;
    injections?: Injections;
  },
  deps: DependencyList
) => {
  const componentPlugins = useComponentNodePlugins({ plugins }, deps);

  return useCallback(
    ({ element, children, attributes }: RenderElementProps) => {
      const { type, data = {}, children: childNodes } = element;
      const matchingPlugin =
        componentPlugins.find((plugin) => plugin.type === type) ??
        componentPlugins.find((plugin) => plugin.type === defaultPluginType);

      if (matchingPlugin) {
        const { Component, getStyle } = matchingPlugin;

        const style = getStyle ? getStyle(data || {}) : undefined;
        const baseProps = {
          children,
          style,
        };

        if (typeof Component === 'string' || Component instanceof String) {
          const nativePropsInData = pickNativeProps(data as Data);
          // simple component like "p"
          return (
            <Component {...attributes} {...baseProps} {...nativePropsInData} />
          );
        }

        Component.displayName = 'SlatePlugin(' + matchingPlugin.type + ')';
        // usefull in certain cases
        const additionalProps = {
          childNodes,
          getTextContents: () =>
            getTextContents(childNodes, {
              slatePlugins: plugins,
            }),
          ...injections,
        };
        const component = (
          <Component
            {...baseProps}
            {...data}
            // attributes have to be spread in manually because of ref problem
            attributes={attributes}
            {...additionalProps}
          />
        );
        const isVoid =
          (matchingPlugin.object === 'inline' ||
            matchingPlugin.object === 'block') &&
          matchingPlugin.isVoid;

        // if block is void, we still need to render children due to some quirks of slate

        if (isVoid && !injections.readOnly) {
          const Element = matchingPlugin.object === 'inline' ? 'span' : 'div';
          return (
            <Element {...attributes} contentEditable={false}>
              {children}
              <VoidEditableElement
                component={component}
                element={element}
                plugin={matchingPlugin as SlatePluginDefinition}
              />
            </Element>
          );
        }

        return component;
      }
      return <p>unknown component {type}</p>;
    },
    deps
  );
};

export const useRenderLeave = (
  {
    plugins,
    injections = STATIC_INJECTIONS,
    readOnly = false,
  }: { plugins: SlatePlugin[]; injections?: Injections; readOnly?: boolean },

  deps: DependencyList
) => {
  const markPlugins = useComponentMarkPlugins({ plugins }, deps);

  return useCallback(
    ({
      leaf: { text, ...leaveTypes },
      attributes,
      children,
    }: RenderLeafProps) => {
      // we reduce number of dom elements by avoiding having another span. Its required in edit mode though for slate to work
      const Wrapper = readOnly ? React.Fragment : 'span';
      return (
        <Wrapper {...attributes}>
          {Object.keys(leaveTypes).reduce((el, type) => {
            const matchingPlugin = markPlugins.find(
              (plugin) => plugin.type === type
            );
            if (matchingPlugin) {
              const { Component, getStyle } = matchingPlugin;
              const dataRaw = leaveTypes[type as keyof typeof leaveTypes]; // usually boolean
              const data = isObject(dataRaw) ? dataRaw : {};

              const style = getStyle ? getStyle(data) : undefined;
              if (
                typeof Component === 'string' ||
                Component instanceof String
              ) {
                const nativePropsInData = pickNativeProps(data as Data);
                return (
                  <Component {...nativePropsInData} style={style}>
                    {el}
                  </Component>
                );
              }
              return (
                <Component
                  childNodes={[{ text }]}
                  getTextContents={() => [text]}
                  useSelected={injections.useSelected}
                  useFocused={injections.useFocused}
                  style={style}
                  {...data}
                >
                  {el}
                </Component>
              );
            }
            return el;
          }, children)}
        </Wrapper>
      );
    },
    deps
  );
};