Skip to content

Commit

Permalink
feat: customize slate_richtext widget to add backward compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
razvanMiu committed May 22, 2023
1 parent 7cf6d5b commit aa0ebd2
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
79 changes: 79 additions & 0 deletions src/RichTextWidget.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* A Slate widget that uses internal JSON representation as its value
*
*/

import React from 'react';
import isUndefined from 'lodash/isUndefined';
import isString from 'lodash/isString';
import config from '@plone/volto/registry';
import { FormFieldWrapper } from '@plone/volto/components';
import SlateEditor from '@plone/volto-slate/editor/SlateEditor';
import { createEmptyParagraph } from '@plone/volto-slate/utils/blocks';

import '@plone/volto-slate/widgets/style.css';

function createParagraph(text) {
return {
type: config.settings.slate.defaultBlockType,
children: [{ text }],
};
}

const getValue = (value) => {
if (isUndefined(value) || !isUndefined(value?.data)) {
return [createEmptyParagraph()];
}
// Previously this was a text field
if (isString(value)) {
return [createParagraph(value)];
}
return value;
};

const SlateRichTextWidget = (props) => {
const {
id,
onChange,
value,
focus,
className,
block,
placeholder,
properties,
readOnly = false,
} = props;
const [selected, setSelected] = React.useState(focus);

return (
<FormFieldWrapper {...props} draggable={false} className="slate_wysiwyg">
<div
className="slate_wysiwyg_box"
role="textbox"
tabIndex="-1"
style={{ boxSizing: 'initial' }}
onClick={() => {
setSelected(true);
}}
onKeyDown={() => {}}
>
<SlateEditor
className={className}
readOnly={readOnly}
id={id}
name={id}
value={getValue(value)}
onChange={(newValue) => {
onChange(id, newValue);
}}
block={block}
selected={selected}
properties={properties}
placeholder={placeholder}
/>
</div>
</FormFieldWrapper>
);
};

export default SlateRichTextWidget;
4 changes: 4 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import installStatisticBlock from './StatisticBlock';
import RichTextWidget from './RichTextWidget';

const applyConfig = (config) => {
config.widgets.widget.slate = RichTextWidget;
config.widgets.widget.slate_richtext = RichTextWidget;

return [installStatisticBlock].reduce((acc, apply) => apply(acc), config);
};

Expand Down

0 comments on commit aa0ebd2

Please sign in to comment.