@pie-lib/editable-html 12.1.0-next.2 → 12.1.0-next.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lib/block-tags.js +25 -0
  3. package/lib/block-tags.js.map +1 -0
  4. package/lib/constants.js +12 -0
  5. package/lib/constants.js.map +1 -0
  6. package/lib/editor.js +1254 -0
  7. package/lib/editor.js.map +1 -0
  8. package/lib/index.js +224 -0
  9. package/lib/index.js.map +1 -0
  10. package/lib/parse-html.js +19 -0
  11. package/lib/parse-html.js.map +1 -0
  12. package/lib/plugins/characters/custom-popper.js +58 -0
  13. package/lib/plugins/characters/custom-popper.js.map +1 -0
  14. package/lib/plugins/characters/index.js +280 -0
  15. package/lib/plugins/characters/index.js.map +1 -0
  16. package/lib/plugins/characters/utils.js +380 -0
  17. package/lib/plugins/characters/utils.js.map +1 -0
  18. package/lib/plugins/css/icons/index.js +26 -0
  19. package/lib/plugins/css/icons/index.js.map +1 -0
  20. package/lib/plugins/css/index.js +350 -0
  21. package/lib/plugins/css/index.js.map +1 -0
  22. package/lib/plugins/customPlugin/index.js +109 -0
  23. package/lib/plugins/customPlugin/index.js.map +1 -0
  24. package/lib/plugins/html/icons/index.js +31 -0
  25. package/lib/plugins/html/icons/index.js.map +1 -0
  26. package/lib/plugins/html/index.js +72 -0
  27. package/lib/plugins/html/index.js.map +1 -0
  28. package/lib/plugins/image/alt-dialog.js +105 -0
  29. package/lib/plugins/image/alt-dialog.js.map +1 -0
  30. package/lib/plugins/image/component.js +357 -0
  31. package/lib/plugins/image/component.js.map +1 -0
  32. package/lib/plugins/image/image-toolbar.js +140 -0
  33. package/lib/plugins/image/image-toolbar.js.map +1 -0
  34. package/lib/plugins/image/index.js +237 -0
  35. package/lib/plugins/image/index.js.map +1 -0
  36. package/lib/plugins/image/insert-image-handler.js +141 -0
  37. package/lib/plugins/image/insert-image-handler.js.map +1 -0
  38. package/lib/plugins/index.js +359 -0
  39. package/lib/plugins/index.js.map +1 -0
  40. package/lib/plugins/list/index.js +300 -0
  41. package/lib/plugins/list/index.js.map +1 -0
  42. package/lib/plugins/math/index.js +417 -0
  43. package/lib/plugins/math/index.js.map +1 -0
  44. package/lib/plugins/media/index.js +343 -0
  45. package/lib/plugins/media/index.js.map +1 -0
  46. package/lib/plugins/media/media-dialog.js +612 -0
  47. package/lib/plugins/media/media-dialog.js.map +1 -0
  48. package/lib/plugins/media/media-toolbar.js +78 -0
  49. package/lib/plugins/media/media-toolbar.js.map +1 -0
  50. package/lib/plugins/media/media-wrapper.js +66 -0
  51. package/lib/plugins/media/media-wrapper.js.map +1 -0
  52. package/lib/plugins/rendering/index.js +46 -0
  53. package/lib/plugins/rendering/index.js.map +1 -0
  54. package/lib/plugins/respArea/drag-in-the-blank/choice.js +288 -0
  55. package/lib/plugins/respArea/drag-in-the-blank/choice.js.map +1 -0
  56. package/lib/plugins/respArea/drag-in-the-blank/index.js +56 -0
  57. package/lib/plugins/respArea/drag-in-the-blank/index.js.map +1 -0
  58. package/lib/plugins/respArea/drag-in-the-blank/utils.js +48 -0
  59. package/lib/plugins/respArea/drag-in-the-blank/utils.js.map +1 -0
  60. package/lib/plugins/respArea/explicit-constructed-response/index.js +51 -0
  61. package/lib/plugins/respArea/explicit-constructed-response/index.js.map +1 -0
  62. package/lib/plugins/respArea/icons/index.js +82 -0
  63. package/lib/plugins/respArea/icons/index.js.map +1 -0
  64. package/lib/plugins/respArea/index.js +298 -0
  65. package/lib/plugins/respArea/index.js.map +1 -0
  66. package/lib/plugins/respArea/inline-dropdown/index.js +68 -0
  67. package/lib/plugins/respArea/inline-dropdown/index.js.map +1 -0
  68. package/lib/plugins/respArea/math-templated/index.js +113 -0
  69. package/lib/plugins/respArea/math-templated/index.js.map +1 -0
  70. package/lib/plugins/respArea/utils.js +101 -0
  71. package/lib/plugins/respArea/utils.js.map +1 -0
  72. package/lib/plugins/table/CustomTablePlugin.js +123 -0
  73. package/lib/plugins/table/CustomTablePlugin.js.map +1 -0
  74. package/lib/plugins/table/icons/index.js +57 -0
  75. package/lib/plugins/table/icons/index.js.map +1 -0
  76. package/lib/plugins/table/index.js +431 -0
  77. package/lib/plugins/table/index.js.map +1 -0
  78. package/lib/plugins/table/table-toolbar.js +153 -0
  79. package/lib/plugins/table/table-toolbar.js.map +1 -0
  80. package/lib/plugins/textAlign/icons/index.js +202 -0
  81. package/lib/plugins/textAlign/icons/index.js.map +1 -0
  82. package/lib/plugins/textAlign/index.js +27 -0
  83. package/lib/plugins/textAlign/index.js.map +1 -0
  84. package/lib/plugins/toolbar/default-toolbar.js +194 -0
  85. package/lib/plugins/toolbar/default-toolbar.js.map +1 -0
  86. package/lib/plugins/toolbar/done-button.js +36 -0
  87. package/lib/plugins/toolbar/done-button.js.map +1 -0
  88. package/lib/plugins/toolbar/editor-and-toolbar.js +270 -0
  89. package/lib/plugins/toolbar/editor-and-toolbar.js.map +1 -0
  90. package/lib/plugins/toolbar/index.js +30 -0
  91. package/lib/plugins/toolbar/index.js.map +1 -0
  92. package/lib/plugins/toolbar/toolbar-buttons.js +157 -0
  93. package/lib/plugins/toolbar/toolbar-buttons.js.map +1 -0
  94. package/lib/plugins/toolbar/toolbar.js +321 -0
  95. package/lib/plugins/toolbar/toolbar.js.map +1 -0
  96. package/lib/plugins/utils.js +45 -0
  97. package/lib/plugins/utils.js.map +1 -0
  98. package/lib/serialization.js +595 -0
  99. package/lib/serialization.js.map +1 -0
  100. package/lib/shared/alert-dialog.js +69 -0
  101. package/lib/theme.js +9 -0
  102. package/lib/theme.js.map +1 -0
  103. package/package.json +9 -11
package/lib/editor.js ADDED
@@ -0,0 +1,1254 @@
1
+ "use strict";
2
+
3
+ require("core-js/modules/es.symbol.js");
4
+ require("core-js/modules/es.array.iterator.js");
5
+ require("core-js/modules/es.object.define-properties.js");
6
+ require("core-js/modules/es.object.define-property.js");
7
+ require("core-js/modules/es.object.get-own-property-descriptor.js");
8
+ require("core-js/modules/es.object.get-own-property-descriptors.js");
9
+ require("core-js/modules/es.object.keys.js");
10
+ require("core-js/modules/es.reflect.construct.js");
11
+ require("core-js/modules/es.weak-map.js");
12
+ require("core-js/modules/web.dom-collections.iterator.js");
13
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
14
+ var _typeof = require("@babel/runtime/helpers/typeof");
15
+ Object.defineProperty(exports, "__esModule", {
16
+ value: true
17
+ });
18
+ Object.defineProperty(exports, "ALL_PLUGINS", {
19
+ enumerable: true,
20
+ get: function get() {
21
+ return _plugins.ALL_PLUGINS;
22
+ }
23
+ });
24
+ Object.defineProperty(exports, "DEFAULT_PLUGINS", {
25
+ enumerable: true,
26
+ get: function get() {
27
+ return _plugins.DEFAULT_PLUGINS;
28
+ }
29
+ });
30
+ exports.valueToSize = exports.serialization = exports["default"] = exports.buildSizeStyle = exports.Editor = void 0;
31
+ var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
32
+ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
33
+ require("core-js/modules/es.array.concat.js");
34
+ require("core-js/modules/es.array.every.js");
35
+ require("core-js/modules/es.array.filter.js");
36
+ require("core-js/modules/es.array.for-each.js");
37
+ require("core-js/modules/es.array.from.js");
38
+ require("core-js/modules/es.array.includes.js");
39
+ require("core-js/modules/es.array.join.js");
40
+ require("core-js/modules/es.array.reduce.js");
41
+ require("core-js/modules/es.date.to-json.js");
42
+ require("core-js/modules/es.function.bind.js");
43
+ require("core-js/modules/es.object.to-string.js");
44
+ require("core-js/modules/es.parse-int.js");
45
+ require("core-js/modules/es.promise.js");
46
+ require("core-js/modules/es.regexp.exec.js");
47
+ require("core-js/modules/es.string.ends-with.js");
48
+ require("core-js/modules/es.string.includes.js");
49
+ require("core-js/modules/es.string.iterator.js");
50
+ require("core-js/modules/es.string.match.js");
51
+ require("core-js/modules/web.dom-collections.for-each.js");
52
+ require("core-js/modules/web.timers.js");
53
+ var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
54
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
55
+ var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
56
+ var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
57
+ var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
58
+ var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
59
+ var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
60
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
61
+ var _react = _interopRequireDefault(require("react"));
62
+ var _slateReact = require("slate-react");
63
+ var _slatePropTypes = _interopRequireDefault(require("slate-prop-types"));
64
+ var _slate = require("slate");
65
+ var _slatePlainSerializer = _interopRequireDefault(require("slate-plain-serializer"));
66
+ var _propTypes = _interopRequireDefault(require("prop-types"));
67
+ var _debounce = _interopRequireDefault(require("lodash/debounce"));
68
+ var _isEqual = _interopRequireDefault(require("lodash/isEqual"));
69
+ var _classnames = _interopRequireDefault(require("classnames"));
70
+ var _debug = _interopRequireDefault(require("debug"));
71
+ var _styles = require("@mui/material/styles");
72
+ var _renderUi = require("@pie-lib/render-ui");
73
+ var _alertDialog = _interopRequireDefault(require("./shared/alert-dialog"));
74
+ var _serialization = _interopRequireWildcard(require("./serialization"));
75
+ var serialization = _serialization;
76
+ exports.serialization = _serialization;
77
+ var _insertImageHandler = _interopRequireDefault(require("./plugins/image/insert-image-handler"));
78
+ var _plugins = require("./plugins");
79
+ var _excluded = ["customPlugins", "showParagraphs", "separateParagraphs"];
80
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t2 in e) "default" !== _t2 && {}.hasOwnProperty.call(e, _t2) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t2)) && (i.get || i.set) ? o(f, _t2, i) : f[_t2] = e[_t2]); return f; })(e, t); }
81
+ function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2["default"])(o), (0, _possibleConstructorReturn2["default"])(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2["default"])(t).constructor) : o.apply(t, e)); }
82
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
83
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
84
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
85
+ var log = (0, _debug["default"])('editable-html:editor');
86
+ var defaultToolbarOpts = {
87
+ position: 'bottom',
88
+ alignment: 'left',
89
+ alwaysVisible: false,
90
+ showDone: true,
91
+ doneOn: 'blur'
92
+ };
93
+ var defaultResponseAreaProps = {
94
+ options: {},
95
+ respAreaToolbar: function respAreaToolbar() {},
96
+ onHandleAreaChange: function onHandleAreaChange() {}
97
+ };
98
+ var defaultLanguageCharactersProps = [];
99
+ var createToolbarOpts = function createToolbarOpts(toolbarOpts, error, isHtmlMode) {
100
+ return _objectSpread(_objectSpread(_objectSpread({}, defaultToolbarOpts), toolbarOpts), {}, {
101
+ error: error,
102
+ isHtmlMode: isHtmlMode
103
+ });
104
+ };
105
+
106
+ /**
107
+ * Converts a value to a CSS size string
108
+ * @param {string|number} v - The value to convert
109
+ * @returns {string|undefined} CSS size string or undefined
110
+ */
111
+ var valueToSize = exports.valueToSize = function valueToSize(v) {
112
+ if (!v) {
113
+ return;
114
+ }
115
+ var calcRegex = /^calc\((.*)\)$/;
116
+ if (typeof v === 'string') {
117
+ if (v.endsWith('%')) {
118
+ return undefined;
119
+ } else if (v.endsWith('px') || v.endsWith('vh') || v.endsWith('vw') || v.endsWith('ch') || v.endsWith('em') || v.match(calcRegex)) {
120
+ return v;
121
+ } else {
122
+ var value = parseInt(v, 10);
123
+ return isNaN(value) ? value : "".concat(value, "px");
124
+ }
125
+ }
126
+ if (typeof v === 'number') {
127
+ return "".concat(v, "px");
128
+ }
129
+ };
130
+
131
+ /**
132
+ * Builds a style object for editor size constraints
133
+ * @param {Object} props - Editor props containing size values
134
+ * @returns {Object} Style object with width/height constraints
135
+ */
136
+ var _buildSizeStyle = exports.buildSizeStyle = function buildSizeStyle(props) {
137
+ var minWidth = props.minWidth,
138
+ width = props.width,
139
+ maxWidth = props.maxWidth,
140
+ minHeight = props.minHeight,
141
+ height = props.height,
142
+ maxHeight = props.maxHeight;
143
+ return {
144
+ width: valueToSize(width),
145
+ minWidth: valueToSize(minWidth),
146
+ maxWidth: valueToSize(maxWidth),
147
+ height: valueToSize(height),
148
+ minHeight: valueToSize(minHeight),
149
+ maxHeight: valueToSize(maxHeight)
150
+ };
151
+ };
152
+
153
+ /**
154
+ * The maximum number of characters the editor can support
155
+ * @type {number}
156
+ */
157
+ var MAX_CHARACTERS_LIMIT = 1000000;
158
+ var Editor = exports.Editor = /*#__PURE__*/function (_React$Component) {
159
+ function Editor(_props) {
160
+ var _this;
161
+ (0, _classCallCheck2["default"])(this, Editor);
162
+ _this = _callSuper(this, Editor, [_props]);
163
+ (0, _defineProperty2["default"])(_this, "setKeypadInteraction", function (interacted) {
164
+ _this.keypadInteractionDetected = interacted;
165
+ });
166
+ (0, _defineProperty2["default"])(_this, "handleDialog", function (open) {
167
+ var extraDialogProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
168
+ var callback = arguments.length > 2 ? arguments[2] : undefined;
169
+ _this.setState({
170
+ dialog: _objectSpread({
171
+ open: open
172
+ }, extraDialogProps)
173
+ }, callback);
174
+ });
175
+ (0, _defineProperty2["default"])(_this, "toggleHtmlMode", function () {
176
+ _this.setState(function (prevState) {
177
+ return {
178
+ isHtmlMode: !prevState.isHtmlMode,
179
+ isEditedInHtmlMode: false
180
+ };
181
+ }, function () {
182
+ var error = _this.props.error;
183
+ var toolbarOpts = _this.state.toolbarOpts;
184
+ var newToolbarOpts = createToolbarOpts(toolbarOpts, error, _this.state.isHtmlMode);
185
+ _this.setState({
186
+ toolbarOpts: newToolbarOpts
187
+ });
188
+ });
189
+ });
190
+ (0, _defineProperty2["default"])(_this, "handlePlugins", function (props) {
191
+ var normalizedResponseAreaProps = _objectSpread(_objectSpread({}, defaultResponseAreaProps), props.responseAreaProps);
192
+ var htmlPluginOpts = {
193
+ currentValue: _this.props.value,
194
+ isHtmlMode: _this.state.isHtmlMode,
195
+ isEditedInHtmlMode: _this.state.isEditedInHtmlMode,
196
+ toggleHtmlMode: _this.toggleHtmlMode,
197
+ handleAlertDialog: _this.handleDialog
198
+ };
199
+ var _ref = props.pluginProps || {},
200
+ customPlugins = _ref.customPlugins;
201
+ customPlugins = customPlugins || [];
202
+ _this.plugins = (0, _plugins.buildPlugins)(props.activePlugins, customPlugins, {
203
+ math: _objectSpread({
204
+ onClick: _this.onMathClick,
205
+ onFocus: _this.onPluginFocus,
206
+ onBlur: _this.onPluginBlur
207
+ }, props.mathMlOptions),
208
+ textAlign: {
209
+ getValue: function getValue() {
210
+ return _this.state.value;
211
+ },
212
+ onChange: _this.onChange
213
+ },
214
+ html: htmlPluginOpts,
215
+ extraCSSRules: props.extraCSSRules || {},
216
+ image: {
217
+ disableImageAlignmentButtons: props.disableImageAlignmentButtons,
218
+ onDelete: props.imageSupport && props.imageSupport["delete"] && function (node, done) {
219
+ var src = node.data.get('src');
220
+ props.imageSupport["delete"](src, function (e) {
221
+ var newPendingImages = _this.state.pendingImages.filter(function (img) {
222
+ return img.key !== node.key;
223
+ });
224
+ var oldScheduled = _this.state.scheduled;
225
+ var newState = {
226
+ pendingImages: newPendingImages,
227
+ scheduled: oldScheduled && newPendingImages.length === 0 ? false : oldScheduled
228
+ };
229
+ _this.setState(newState, function () {
230
+ return done(e, _this.state.value);
231
+ });
232
+ });
233
+ },
234
+ insertImageRequested: props.imageSupport && function (addedImage, getHandler) {
235
+ var pendingImages = _this.state.pendingImages;
236
+ var onFinish = function onFinish(result) {
237
+ var cb;
238
+ if (_this.state.scheduled && result) {
239
+ // finish editing only on success
240
+ cb = _this.onEditingDone.bind(_this);
241
+ }
242
+ var newPendingImages = _this.state.pendingImages.filter(function (img) {
243
+ return img.key !== addedImage.key;
244
+ });
245
+ var newState = {
246
+ pendingImages: newPendingImages
247
+ };
248
+ if (newPendingImages.length === 0) {
249
+ newState.scheduled = false;
250
+ }
251
+ _this.setState(newState, cb);
252
+ };
253
+ var callback = function callback() {
254
+ /**
255
+ * The handler is the object through which the outer context
256
+ * communicates file upload events like: fileChosen, cancel, progress
257
+ */
258
+ var handler = getHandler(onFinish, function () {
259
+ return _this.state.value;
260
+ });
261
+ props.imageSupport.add(handler);
262
+ };
263
+ _this.setState({
264
+ pendingImages: [].concat((0, _toConsumableArray2["default"])(pendingImages), [addedImage])
265
+ }, callback);
266
+ },
267
+ onFocus: _this.onPluginFocus,
268
+ onBlur: _this.onPluginBlur,
269
+ maxImageWidth: props.maxImageWidth,
270
+ maxImageHeight: props.maxImageHeight
271
+ },
272
+ toolbar: {
273
+ /**
274
+ * To minimize converting html -> state -> html
275
+ * We only emit markup once 'done' is clicked.
276
+ */
277
+ disableScrollbar: !!props.disableScrollbar,
278
+ disableUnderline: props.disableUnderline,
279
+ autoWidth: props.autoWidthToolbar,
280
+ onDone: function onDone() {
281
+ var _this$state$value$sta;
282
+ var nonEmpty = props.nonEmpty;
283
+ log('[onDone]');
284
+ _this.setState({
285
+ toolbarInFocus: false,
286
+ focusedNode: null,
287
+ focusToolbar: false
288
+ });
289
+ _this.editor.blur();
290
+ if (nonEmpty && ((_this$state$value$sta = _this.state.value.startText) === null || _this$state$value$sta === void 0 || (_this$state$value$sta = _this$state$value$sta.text) === null || _this$state$value$sta === void 0 ? void 0 : _this$state$value$sta.length) === 0) {
291
+ _this.resetValue(true).then(function () {
292
+ _this.onEditingDone();
293
+ });
294
+ } else {
295
+ _this.onEditingDone();
296
+ }
297
+ }
298
+ },
299
+ table: {
300
+ onFocus: function onFocus() {
301
+ log('[table:onFocus]...');
302
+ _this.onPluginFocus();
303
+ },
304
+ onBlur: function onBlur() {
305
+ log('[table:onBlur]...');
306
+ _this.onPluginBlur();
307
+ }
308
+ },
309
+ responseArea: {
310
+ type: normalizedResponseAreaProps.type,
311
+ options: normalizedResponseAreaProps.options,
312
+ maxResponseAreas: normalizedResponseAreaProps.maxResponseAreas,
313
+ respAreaToolbar: normalizedResponseAreaProps.respAreaToolbar,
314
+ onHandleAreaChange: normalizedResponseAreaProps.onHandleAreaChange,
315
+ error: normalizedResponseAreaProps.error,
316
+ onFocus: function onFocus() {
317
+ log('[table:onFocus]...');
318
+ _this.onPluginFocus();
319
+ },
320
+ onBlur: function onBlur() {
321
+ log('[table:onBlur]...');
322
+ _this.onPluginBlur();
323
+ }
324
+ },
325
+ languageCharacters: props.languageCharactersProps,
326
+ keyPadCharacterRef: _this.keyPadCharacterRef,
327
+ setKeypadInteraction: _this.setKeypadInteraction,
328
+ media: {
329
+ focus: _this.focus,
330
+ createChange: function createChange() {
331
+ return _this.state.value.change();
332
+ },
333
+ onChange: _this.onChange,
334
+ uploadSoundSupport: props.uploadSoundSupport
335
+ }
336
+ });
337
+ if (props.mathMlOptions.mmlOutput || props.mathMlOptions.mmlEditing) {
338
+ _this.props.runSerializationOnMarkup();
339
+ }
340
+ });
341
+ (0, _defineProperty2["default"])(_this, "onPluginBlur", function (e) {
342
+ log('[onPluginBlur]', e && e.relatedTarget);
343
+ var target = e && e.relatedTarget;
344
+ var node = target ? (0, _slateReact.findNode)(target, _this.state.value) : null;
345
+ log('[onPluginBlur] node: ', node);
346
+ _this.setState({
347
+ focusedNode: node
348
+ }, function () {
349
+ _this.resetValue();
350
+ });
351
+ });
352
+ (0, _defineProperty2["default"])(_this, "onPluginFocus", function (e) {
353
+ log('[onPluginFocus]', e && e.target);
354
+ var target = e && e.target;
355
+ if (target) {
356
+ var node = (0, _slateReact.findNode)(target, _this.state.value);
357
+ log('[onPluginFocus] node: ', node);
358
+ var stashedValue = _this.state.stashedValue || _this.state.value;
359
+ _this.setState({
360
+ focusedNode: node,
361
+ stashedValue: stashedValue
362
+ });
363
+ } else {
364
+ _this.setState({
365
+ focusedNode: null
366
+ });
367
+ }
368
+ _this.stashValue();
369
+ });
370
+ (0, _defineProperty2["default"])(_this, "onMathClick", function (node) {
371
+ _this.editor.change(function (c) {
372
+ return c.collapseToStartOf(node);
373
+ });
374
+ _this.setState({
375
+ selectedNode: node
376
+ });
377
+ });
378
+ (0, _defineProperty2["default"])(_this, "onEditingDone", function () {
379
+ var _this$state = _this.state,
380
+ isHtmlMode = _this$state.isHtmlMode,
381
+ dialog = _this$state.dialog,
382
+ value = _this$state.value,
383
+ pendingImages = _this$state.pendingImages;
384
+
385
+ // Handling HTML mode and dialog state
386
+ if (isHtmlMode) {
387
+ // Early return if HTML mode is enabled
388
+ if (dialog !== null && dialog !== void 0 && dialog.open) return;
389
+ var currentValue = (0, _serialization.htmlToValue)(value.document.text);
390
+ var previewText = _this.renderHtmlPreviewContent();
391
+ _this.openHtmlModeConfirmationDialog(currentValue, previewText);
392
+ return;
393
+ }
394
+ if (pendingImages.length) {
395
+ // schedule image processing
396
+ _this.setState({
397
+ scheduled: true
398
+ });
399
+ return;
400
+ }
401
+
402
+ // Finalizing editing
403
+ log('[onEditingDone]');
404
+ _this.setState({
405
+ pendingImages: [],
406
+ stashedValue: null,
407
+ focusedNode: null
408
+ });
409
+ log('[onEditingDone] value: ', _this.state.value);
410
+ _this.props.onChange(_this.state.value, true);
411
+ });
412
+ /**
413
+ * Renders the HTML preview content to be displayed inside the dialog.
414
+ * This content includes the edited HTML and a prompt for the user.
415
+ */
416
+ (0, _defineProperty2["default"])(_this, "renderHtmlPreviewContent", function () {
417
+ return /*#__PURE__*/_react["default"].createElement("div", {
418
+ ref: function ref(_ref2) {
419
+ return _this.elementRef = _ref2;
420
+ }
421
+ }, /*#__PURE__*/_react["default"].createElement("div", null, "Preview of Edited Html:"), /*#__PURE__*/_react["default"].createElement(StyledPreviewText, null, /*#__PURE__*/_react["default"].createElement(_renderUi.PreviewPrompt, {
422
+ prompt: _this.state.value.document.text
423
+ })), /*#__PURE__*/_react["default"].createElement("div", null, "Would you like to save these changes ?"));
424
+ });
425
+ /**
426
+ * Opens a confirmation dialog in HTML mode, displaying the preview of the current HTML content
427
+ * and offering options to save or continue editing.
428
+ */
429
+ (0, _defineProperty2["default"])(_this, "openHtmlModeConfirmationDialog", function (currentValue, previewText) {
430
+ _this.setState({
431
+ dialog: {
432
+ open: true,
433
+ title: 'Content Preview & Save',
434
+ text: previewText,
435
+ onConfirmText: 'Save changes',
436
+ onCloseText: 'Continue editing',
437
+ onConfirm: function onConfirm() {
438
+ _this.handleHtmlModeSaveConfirmation(currentValue);
439
+ },
440
+ onClose: _this.htmlModeContinueEditing
441
+ }
442
+ });
443
+ });
444
+ /**
445
+ * Handles the save confirmation action in HTML mode. This updates the value to the confirmed
446
+ * content, updates value on props, and exits the HTML mode.
447
+ * @param {string} currentValue - The confirmed value of the HTML content to save.
448
+ */
449
+ (0, _defineProperty2["default"])(_this, "handleHtmlModeSaveConfirmation", function (currentValue) {
450
+ _this.setState({
451
+ value: currentValue
452
+ });
453
+ _this.props.onChange(currentValue, true);
454
+ _this.handleDialog(false);
455
+ _this.toggleHtmlMode();
456
+ });
457
+ /**
458
+ * Closes the dialog in HTML mode and allows the user to continue editing the html content.
459
+ * This function is invoked when the user opts to not save the current changes.
460
+ */
461
+ (0, _defineProperty2["default"])(_this, "htmlModeContinueEditing", function () {
462
+ _this.handleDialog(false);
463
+ });
464
+ // Allowing time for onChange to take effect if it is called
465
+ (0, _defineProperty2["default"])(_this, "handleBlur", function (resolve) {
466
+ var nonEmpty = _this.props.nonEmpty;
467
+ var doneOn = _this.state.toolbarOpts.doneOn;
468
+ _this.setState({
469
+ toolbarInFocus: false,
470
+ focusedNode: null
471
+ });
472
+ if (_this.editor) {
473
+ _this.editor.blur();
474
+ }
475
+ if (doneOn === 'blur') {
476
+ var _this$state$value$sta2;
477
+ if (nonEmpty && ((_this$state$value$sta2 = _this.state.value.startText) === null || _this$state$value$sta2 === void 0 || (_this$state$value$sta2 = _this$state$value$sta2.text) === null || _this$state$value$sta2 === void 0 ? void 0 : _this$state$value$sta2.length) === 0) {
478
+ _this.resetValue(true).then(function () {
479
+ _this.onEditingDone();
480
+ resolve();
481
+ });
482
+ } else {
483
+ _this.onEditingDone();
484
+ resolve();
485
+ }
486
+ }
487
+ });
488
+ (0, _defineProperty2["default"])(_this, "onBlur", function (event) {
489
+ var _this$doneButtonRef$c;
490
+ log('[onBlur]');
491
+ var relatedTarget = event.relatedTarget;
492
+ var toolbarElement = _this.toolbarRef && (relatedTarget === null || relatedTarget === void 0 ? void 0 : relatedTarget.closest("[class*=\"".concat(_this.toolbarRef.className, "\"]")));
493
+
494
+ // Check if relatedTarget is a done button
495
+ var isRawDoneButton = _this.doneButtonRef && (relatedTarget === null || relatedTarget === void 0 ? void 0 : relatedTarget.closest("[class*=\"".concat((_this$doneButtonRef$c = _this.doneButtonRef.current) === null || _this$doneButtonRef$c === void 0 ? void 0 : _this$doneButtonRef$c.className, "\"]")));
496
+
497
+ // Skip onBlur handling if relatedTarget is a button from the KeyPad characters
498
+ _this.skipBlurHandling = _this.keypadInteractionDetected && relatedTarget !== null;
499
+ if (toolbarElement && !isRawDoneButton && !_this.state.focusToolbar) {
500
+ _this.setState({
501
+ focusToolbar: true
502
+ });
503
+ }
504
+ var node = relatedTarget ? (0, _slateReact.findNode)(relatedTarget, _this.state.value) : null;
505
+ log('[onBlur] node: ', node);
506
+ return new Promise(function (resolve) {
507
+ if (!_this.skipBlurHandling) {
508
+ _this.setKeypadInteraction(false);
509
+ _this.setState({
510
+ preBlurValue: _this.state.value,
511
+ focusedNode: !node ? null : node
512
+ }, _this.handleBlur.bind(_this, resolve));
513
+ }
514
+ _this.props.onBlur(event);
515
+ });
516
+ });
517
+ (0, _defineProperty2["default"])(_this, "handleDomBlur", function (e) {
518
+ var editorDOM = document.querySelector("[data-key=\"".concat(_this.state.value.document.key, "\"]"));
519
+ setTimeout(function () {
520
+ var stateValue = _this.state.value;
521
+ if (!_this.wrapperRef) {
522
+ return;
523
+ }
524
+ var editorElement = !editorDOM || document.activeElement.closest("[class*=\"".concat(editorDOM.className, "\"]"));
525
+ var toolbarElement = !_this.toolbarRef || document.activeElement.closest("[class*=\"".concat(_this.toolbarRef.className, "\"]"));
526
+ var isInCurrentComponent = _this.wrapperRef.contains(editorElement) || _this.wrapperRef.contains(toolbarElement);
527
+ if (!isInCurrentComponent) {
528
+ editorDOM.removeEventListener('blur', _this.handleDomBlur);
529
+ if (stateValue.isFocused) {
530
+ _this.onBlur(e);
531
+ }
532
+ }
533
+ }, 50);
534
+ });
535
+ /*
536
+ * Needs to be wrapped otherwise it causes issues because of race conditions
537
+ * Known issue for slatejs. See: https://github.com/ianstormtaylor/slate/issues/2097
538
+ * Using timeout I wasn't able to test this
539
+ *
540
+ * Note: The use of promises has been causing issues with MathQuill
541
+ * */
542
+ (0, _defineProperty2["default"])(_this, "onFocus", function (event, change) {
543
+ return new Promise(function (resolve) {
544
+ var _navigator;
545
+ var editorDOM = document.querySelector("[data-key=\"".concat(_this.state.value.document.key, "\"]"));
546
+ var isTouchDevice = typeof window !== 'undefined' && ('ontouchstart' in window || ((_navigator = navigator) === null || _navigator === void 0 ? void 0 : _navigator.maxTouchPoints) > 0);
547
+ log('[onFocus]', document.activeElement);
548
+ if (_this.keypadInteractionDetected && _this.__TEMPORARY_CHANGE_DATA) {
549
+ _this.__TEMPORARY_CHANGE_DATA = null;
550
+ }
551
+
552
+ /**
553
+ * This is a temporary hack - @see changeData below for some more information.
554
+ */
555
+ if (_this.__TEMPORARY_CHANGE_DATA) {
556
+ var _this$__TEMPORARY_CHA = _this.__TEMPORARY_CHANGE_DATA,
557
+ key = _this$__TEMPORARY_CHA.key,
558
+ data = _this$__TEMPORARY_CHA.data;
559
+ var domEl = document.querySelector("[data-key=\"".concat(key, "\"]"));
560
+ if (domEl) {
561
+ var _change = _this.state.value.change().setNodeByKey(key, {
562
+ data: data
563
+ });
564
+ _this.setState({
565
+ value: _change.value
566
+ }, function () {
567
+ _this.__TEMPORARY_CHANGE_DATA = null;
568
+ });
569
+ }
570
+ }
571
+
572
+ /**
573
+ * This is needed just in case the browser decides to make the editor
574
+ * lose focus without triggering the onBlur event (can happen in a few cases).
575
+ * This will also trigger onBlur if the user clicks outside of the page when the editor
576
+ * is focused.
577
+ */
578
+ if (editorDOM === document.activeElement) {
579
+ editorDOM.removeEventListener('blur', _this.handleDomBlur);
580
+ editorDOM.addEventListener('blur', _this.handleDomBlur);
581
+ }
582
+ _this.stashValue();
583
+ _this.props.onFocus();
584
+
585
+ // Added for accessibility: Ensures the editor gains focus when tabbed to for improved keyboard navigation
586
+ var shouldFocusEditor = !_this.keypadInteractionDetected && !isTouchDevice;
587
+ if (shouldFocusEditor) {
588
+ change === null || change === void 0 || change.focus();
589
+ }
590
+ resolve();
591
+ });
592
+ });
593
+ (0, _defineProperty2["default"])(_this, "stashValue", function () {
594
+ log('[stashValue]');
595
+ if (!_this.state.stashedValue) {
596
+ _this.setState({
597
+ stashedValue: _this.state.value
598
+ });
599
+ }
600
+ });
601
+ /**
602
+ * Reset the value if the user didn't click done.
603
+ */
604
+ (0, _defineProperty2["default"])(_this, "resetValue", function (force) {
605
+ var _this$state2 = _this.state,
606
+ value = _this$state2.value,
607
+ focusedNode = _this$state2.focusedNode;
608
+ var stopReset = _this.plugins.reduce(function (s, p) {
609
+ return s || p.stopReset && p.stopReset(_this.state.value);
610
+ }, false);
611
+ log('[resetValue]', value.isFocused, focusedNode, 'stopReset: ', stopReset);
612
+ if (_this.state.stashedValue && !value.isFocused && !focusedNode && !stopReset || force) {
613
+ log('[resetValue] resetting...');
614
+ log('stashed', _this.state.stashedValue.document.toObject());
615
+ log('current', _this.state.value.document.toObject());
616
+ var newValue = _slate.Value.fromJSON(_this.state.stashedValue.toJSON());
617
+ log('newValue: ', newValue.document);
618
+ return new Promise(function (resolve) {
619
+ setTimeout(function () {
620
+ _this.setState({
621
+ value: newValue,
622
+ stashedValue: null
623
+ }, function () {
624
+ log('value now: ', _this.state.value.document.toJSON());
625
+ resolve();
626
+ });
627
+ }, 50);
628
+ });
629
+ } else {
630
+ return Promise.resolve({});
631
+ }
632
+ });
633
+ (0, _defineProperty2["default"])(_this, "onChange", function (change, done) {
634
+ log('[onChange]');
635
+ window.me = _this;
636
+ var value = change.value;
637
+ var charactersLimit = _this.props.charactersLimit;
638
+ var limit = charactersLimit;
639
+ if (!limit || limit > MAX_CHARACTERS_LIMIT) {
640
+ limit = MAX_CHARACTERS_LIMIT;
641
+ }
642
+ if (value && value.document && value.document.text && value.document.text.length > limit) {
643
+ return;
644
+ }
645
+
646
+ // Mark the editor as edited when in HTML mode and its content has changed.
647
+ // This status will later be used to decide whether to prompt a warning to the user when exiting HTML mode.
648
+ var isEditedInHtmlMode = !_this.state.isHtmlMode ? false : _this.state.value.document.text !== value.document.text ? true : _this.state.isEditedInHtmlMode;
649
+ if (isEditedInHtmlMode != _this.state.isEditedInHtmlMode) {
650
+ _this.handlePlugins(_this.props);
651
+ }
652
+ _this.setState({
653
+ value: value,
654
+ isEditedInHtmlMode: isEditedInHtmlMode
655
+ }, function () {
656
+ log('[onChange], call done()');
657
+ if (done) {
658
+ done();
659
+ }
660
+ });
661
+ });
662
+ (0, _defineProperty2["default"])(_this, "getFocusedValue", function () {
663
+ if (_this.state.value.isFocused) {
664
+ return _this.state.value;
665
+ }
666
+ return _this.state.preBlurValue;
667
+ });
668
+ (0, _defineProperty2["default"])(_this, "validateNode", function (node) {
669
+ if (node.object !== 'block') return;
670
+ var last = node.nodes.last();
671
+ if (!last) return;
672
+ if (last.type !== 'image') return;
673
+ log('[validateNode] last is image..');
674
+ var parent = last.getParent(last.key);
675
+ var p = _slate.Block.getParent(last.key);
676
+ log('[validateNode] parent:', parent, p);
677
+ return undefined;
678
+ });
679
+ (0, _defineProperty2["default"])(_this, "changeData", function (key, data) {
680
+ log('[changeData]. .. ', key, data);
681
+
682
+ /**
683
+ * HACK ALERT: We should be calling setState here and storing the change data:
684
+ *
685
+ * <code>this.setState({changeData: { key, data}})</code>
686
+ * However this is causing issues with the Mathquill instance. The 'input' event stops firing on the element and no
687
+ * more changes get through. The issues seem to be related to the promises in onBlur/onFocus. But removing these
688
+ * brings it's own problems. A major clean up is planned for this component so I've decided to temporarily settle
689
+ * on this hack rather than spend more time on this.
690
+ */
691
+
692
+ // Uncomment this line to see the bug described above.
693
+ // this.setState({changeData: {key, data}})
694
+
695
+ _this.__TEMPORARY_CHANGE_DATA = {
696
+ key: key,
697
+ data: data
698
+ };
699
+ });
700
+ (0, _defineProperty2["default"])(_this, "focus", function (pos, node) {
701
+ var position = pos || 'end';
702
+ _this.props.focus(position, node);
703
+ });
704
+ (0, _defineProperty2["default"])(_this, "onDropPaste", /*#__PURE__*/function () {
705
+ var _ref3 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee(event, change, dropContext) {
706
+ var editor, transfer, file, type, fragment, text, src, inline, range, ch, handler, _change$value, _document, selection, startBlock, defaultBlock, defaultMarks, frag, _t;
707
+ return _regenerator["default"].wrap(function (_context) {
708
+ while (1) switch (_context.prev = _context.next) {
709
+ case 0:
710
+ editor = change.editor;
711
+ transfer = (0, _slateReact.getEventTransfer)(event);
712
+ file = transfer.files && transfer.files[0];
713
+ type = transfer.type;
714
+ fragment = transfer.fragment;
715
+ text = transfer.text;
716
+ if (!(file && (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'))) {
717
+ _context.next = 5;
718
+ break;
719
+ }
720
+ if (_this.props.imageSupport) {
721
+ _context.next = 1;
722
+ break;
723
+ }
724
+ return _context.abrupt("return");
725
+ case 1:
726
+ _context.prev = 1;
727
+ log('[onDropPaste]');
728
+ _context.next = 2;
729
+ return (0, _serialization.getBase64)(file);
730
+ case 2:
731
+ src = _context.sent;
732
+ inline = _slate.Inline.create({
733
+ type: 'image',
734
+ isVoid: true,
735
+ data: {
736
+ loading: false,
737
+ src: src
738
+ }
739
+ });
740
+ if (dropContext) {
741
+ _this.focus();
742
+ } else {
743
+ range = (0, _slateReact.getEventRange)(event, editor);
744
+ if (range) {
745
+ change.select(range);
746
+ }
747
+ }
748
+ ch = change.insertInline(inline);
749
+ _this.onChange(ch);
750
+ handler = new _insertImageHandler["default"](inline, function () {}, function () {
751
+ return _this.state.value;
752
+ }, _this.onChange, true);
753
+ handler.fileChosen(file);
754
+ _this.props.imageSupport.add(handler);
755
+ _context.next = 4;
756
+ break;
757
+ case 3:
758
+ _context.prev = 3;
759
+ _t = _context["catch"](1);
760
+ log('[onDropPaste] error: ', _t);
761
+ case 4:
762
+ _context.next = 9;
763
+ break;
764
+ case 5:
765
+ if (!(type === 'fragment')) {
766
+ _context.next = 6;
767
+ break;
768
+ }
769
+ change.insertFragment(fragment);
770
+ _context.next = 9;
771
+ break;
772
+ case 6:
773
+ if (!(type === 'text' || type === 'html')) {
774
+ _context.next = 9;
775
+ break;
776
+ }
777
+ if (text) {
778
+ _context.next = 7;
779
+ break;
780
+ }
781
+ return _context.abrupt("return");
782
+ case 7:
783
+ _change$value = change.value, _document = _change$value.document, selection = _change$value.selection, startBlock = _change$value.startBlock;
784
+ if (!startBlock.isVoid) {
785
+ _context.next = 8;
786
+ break;
787
+ }
788
+ return _context.abrupt("return");
789
+ case 8:
790
+ defaultBlock = startBlock;
791
+ defaultMarks = _document.getInsertMarksAtRange(selection);
792
+ frag = _slatePlainSerializer["default"].deserialize(text, {
793
+ defaultBlock: defaultBlock,
794
+ defaultMarks: defaultMarks
795
+ }).document;
796
+ change.insertFragment(frag);
797
+ case 9:
798
+ case "end":
799
+ return _context.stop();
800
+ }
801
+ }, _callee, null, [[1, 3]]);
802
+ }));
803
+ return function (_x, _x2, _x3) {
804
+ return _ref3.apply(this, arguments);
805
+ };
806
+ }());
807
+ (0, _defineProperty2["default"])(_this, "renderPlaceholder", function (props) {
808
+ var editor = props.editor;
809
+ var document = editor.value.document;
810
+ if (!editor.props.placeholder || document.text !== '' || document.nodes.size !== 1 || !document.isEmpty) {
811
+ return false;
812
+ }
813
+ return /*#__PURE__*/_react["default"].createElement("span", {
814
+ contentEditable: false,
815
+ style: {
816
+ display: 'inline-block',
817
+ width: 'fit-content',
818
+ // for centering the placeholder if text-align is set to center
819
+ maxWidth: '100%',
820
+ whiteSpace: 'nowrap',
821
+ opacity: '0.33',
822
+ pointerEvents: 'none',
823
+ userSelect: 'none'
824
+ }
825
+ }, editor.props.placeholder);
826
+ });
827
+ _this.state = {
828
+ value: _props.value,
829
+ toolbarOpts: createToolbarOpts(_props.toolbarOpts, _props.error),
830
+ pendingImages: [],
831
+ isHtmlMode: false,
832
+ isEditedInHtmlMode: false,
833
+ focusToolbar: false,
834
+ dialog: {
835
+ open: false
836
+ }
837
+ };
838
+ _this.keyPadCharacterRef = /*#__PURE__*/_react["default"].createRef();
839
+ _this.doneButtonRef = /*#__PURE__*/_react["default"].createRef();
840
+ _this.keypadInteractionDetected = false;
841
+ _this.toggleHtmlMode = _this.toggleHtmlMode.bind(_this);
842
+ _this.handleToolbarFocus = _this.handleToolbarFocus.bind(_this);
843
+ _this.handleToolbarBlur = _this.handleToolbarBlur.bind(_this);
844
+ _this.onResize = (0, _debounce["default"])(function () {
845
+ if (!_this.state.isHtmlMode && _props.onChange) {
846
+ _props.onChange(_this.state.value, true);
847
+ }
848
+ }, 50);
849
+ _this.handlePlugins(_this.props);
850
+ return _this;
851
+ }
852
+ (0, _inherits2["default"])(Editor, _React$Component);
853
+ return (0, _createClass2["default"])(Editor, [{
854
+ key: "handleToolbarFocus",
855
+ value: function handleToolbarFocus() {
856
+ if (this.state.focusToolbar) {
857
+ return;
858
+ }
859
+ this.setState({
860
+ focusToolbar: true
861
+ });
862
+ }
863
+ }, {
864
+ key: "handleToolbarBlur",
865
+ value: function handleToolbarBlur() {
866
+ var _this2 = this;
867
+ setTimeout(function () {
868
+ if (!_this2.toolbarContainsFocus()) {
869
+ _this2.setState({
870
+ focusToolbar: false
871
+ });
872
+ }
873
+ }, 0);
874
+ }
875
+ }, {
876
+ key: "toolbarContainsFocus",
877
+ value: function toolbarContainsFocus() {
878
+ if (!this.toolbarRef) return false;
879
+ var toolbarElement = this.toolbarRef;
880
+ var activeElement = document.activeElement;
881
+ return toolbarElement && toolbarElement.contains(activeElement);
882
+ }
883
+ }, {
884
+ key: "componentDidMount",
885
+ value: function componentDidMount() {
886
+ var _this$props$className,
887
+ _this3 = this;
888
+ // onRef is needed to get the ref of the component
889
+ this.props.onRef(this);
890
+ window.addEventListener('resize', this.onResize);
891
+ var isResponseAreaEditor = (_this$props$className = this.props.className) === null || _this$props$className === void 0 ? void 0 : _this$props$className.includes('response-area-editor');
892
+ if (isResponseAreaEditor && this.editor) {
893
+ var responseAreaEditor = document.querySelector("[data-key=\"".concat(this.editor.value.document.key, "\"]"));
894
+ if (responseAreaEditor) {
895
+ responseAreaEditor.setAttribute('aria-label', 'Answer');
896
+ }
897
+ }
898
+ if (this.editor && this.props.autoFocus) {
899
+ Promise.resolve().then(function () {
900
+ if (_this3.editor) {
901
+ var editorDOM = document.querySelector("[data-key=\"".concat(_this3.editor.value.document.key, "\"]"));
902
+ _this3.editor.focus();
903
+ if (editorDOM) {
904
+ editorDOM.focus();
905
+ }
906
+ }
907
+ });
908
+ }
909
+ }
910
+ }, {
911
+ key: "UNSAFE_componentWillReceiveProps",
912
+ value: function UNSAFE_componentWillReceiveProps(nextProps) {
913
+ var _nextProps$value, _this$props$value;
914
+ var _this$state3 = this.state,
915
+ isHtmlMode = _this$state3.isHtmlMode,
916
+ toolbarOpts = _this$state3.toolbarOpts;
917
+ var newToolbarOpts = createToolbarOpts(nextProps.toolbarOpts, nextProps.error, isHtmlMode);
918
+ if (!(0, _isEqual["default"])(newToolbarOpts, toolbarOpts)) {
919
+ this.setState({
920
+ toolbarOpts: newToolbarOpts
921
+ });
922
+ }
923
+ var differentCharacterProps = !(0, _isEqual["default"])(nextProps.languageCharactersProps, this.props.languageCharactersProps);
924
+ var differentMathMlProps = !(0, _isEqual["default"])(nextProps.mathMlOptions, this.props.mathMlOptions);
925
+ var differentImageMaxDimensionsProps = !(0, _isEqual["default"])(nextProps.maxImageWidth, this.props.maxImageWidth) || !(0, _isEqual["default"])(nextProps.maxImageHeight, this.props.maxImageHeight);
926
+ if (differentCharacterProps || differentMathMlProps || differentImageMaxDimensionsProps) {
927
+ this.handlePlugins(nextProps);
928
+ }
929
+ if (!((_nextProps$value = nextProps.value) !== null && _nextProps$value !== void 0 && (_nextProps$value = _nextProps$value.document) !== null && _nextProps$value !== void 0 && _nextProps$value.equals((_this$props$value = this.props.value) === null || _this$props$value === void 0 ? void 0 : _this$props$value.document))) {
930
+ this.setState({
931
+ focus: false,
932
+ value: nextProps.value
933
+ });
934
+ }
935
+ }
936
+ }, {
937
+ key: "componentDidUpdate",
938
+ value: function componentDidUpdate(prevProps, prevState) {
939
+ // The cursor is on a zero width element and when that is placed near void elements, it is not visible
940
+ // so we increase the width to at least 2px in order for the user to see it
941
+
942
+ // Trigger plugins and finish editing if:
943
+ // 1. The 'isHtmlMode' state has been toggled.
944
+ // 2. We're currently in 'isHtmlMode' and the editor value has been modified.
945
+ if (this.state.isHtmlMode !== prevState.isHtmlMode || this.state.isHtmlMode && !prevState.isEditedInHtmlMode && this.state.isEditedInHtmlMode) {
946
+ this.handlePlugins(this.props);
947
+ }
948
+ var zeroWidthEls = document.querySelectorAll('[data-slate-zero-width="z"]');
949
+ Array.from(zeroWidthEls).forEach(function (el) {
950
+ el.style.minWidth = '2px';
951
+ el.style.display = 'inline-block';
952
+ });
953
+ }
954
+ }, {
955
+ key: "componentWillUnmount",
956
+ value:
957
+ /**
958
+ * Remove onResize event listener
959
+ */
960
+ function componentWillUnmount() {
961
+ window.removeEventListener('resize', this.onResize);
962
+ }
963
+ }, {
964
+ key: "buildSizeStyle",
965
+ value:
966
+ // Use the exported utility functions
967
+ function buildSizeStyle() {
968
+ return _buildSizeStyle(this.props);
969
+ }
970
+ }, {
971
+ key: "render",
972
+ value: function render() {
973
+ var _this4 = this,
974
+ _value$document;
975
+ var _this$props = this.props,
976
+ disabled = _this$props.disabled,
977
+ spellCheck = _this$props.spellCheck,
978
+ highlightShape = _this$props.highlightShape,
979
+ className = _this$props.className,
980
+ placeholder = _this$props.placeholder,
981
+ pluginProps = _this$props.pluginProps,
982
+ onKeyDown = _this$props.onKeyDown,
983
+ slateEditorExtraStyles = _this$props.slateEditorExtraStyles;
984
+ // We don't want to send customPlugins to slate.
985
+ // Not sure if they would do any harm, but I think it's better to not send them.
986
+ // We use custom plugins to be able to add custom buttons
987
+ // eslint-disable-next-line no-unused-vars
988
+ var _ref4 = pluginProps || {},
989
+ customPlugins = _ref4.customPlugins,
990
+ showParagraphs = _ref4.showParagraphs,
991
+ separateParagraphs = _ref4.separateParagraphs,
992
+ otherPluginProps = (0, _objectWithoutProperties2["default"])(_ref4, _excluded);
993
+ var _this$state4 = this.state,
994
+ value = _this$state4.value,
995
+ focusedNode = _this$state4.focusedNode,
996
+ toolbarOpts = _this$state4.toolbarOpts,
997
+ dialog = _this$state4.dialog,
998
+ scheduled = _this$state4.scheduled;
999
+ log('[render] value: ', value);
1000
+ var sizeStyle = this.buildSizeStyle();
1001
+ var wrapperClassNames = (0, _classnames["default"])({
1002
+ withBg: highlightShape,
1003
+ toolbarOnTop: toolbarOpts.alwaysVisible && toolbarOpts.position === 'top',
1004
+ scheduled: scheduled
1005
+ }, className);
1006
+ return /*#__PURE__*/_react["default"].createElement(StyledEditorWrapper, {
1007
+ ref: function ref(_ref5) {
1008
+ return _this4.wrapperRef = _ref5;
1009
+ },
1010
+ style: {
1011
+ width: sizeStyle.width,
1012
+ minWidth: sizeStyle.minWidth,
1013
+ maxWidth: sizeStyle.maxWidth
1014
+ },
1015
+ className: wrapperClassNames,
1016
+ id: "editor-".concat(value === null || value === void 0 || (_value$document = value.document) === null || _value$document === void 0 ? void 0 : _value$document.key)
1017
+ }, scheduled && /*#__PURE__*/_react["default"].createElement(StyledUploadingMessage, null, "Uploading image and then saving..."), /*#__PURE__*/_react["default"].createElement(StyledSlateEditor, {
1018
+ className: (0, _classnames["default"])({
1019
+ noPadding: toolbarOpts === null || toolbarOpts === void 0 ? void 0 : toolbarOpts.noPadding,
1020
+ showParagraph: showParagraphs && !showParagraphs.disabled,
1021
+ separateParagraph: separateParagraphs && !separateParagraphs.disabled
1022
+ })
1023
+ }, /*#__PURE__*/_react["default"].createElement(_slateReact.Editor, {
1024
+ plugins: this.plugins,
1025
+ innerRef: function innerRef(r) {
1026
+ if (r) {
1027
+ _this4.slateEditor = r;
1028
+ }
1029
+ },
1030
+ ref: function ref(r) {
1031
+ return _this4.editor = r && _this4.props.editorRef(r);
1032
+ },
1033
+ toolbarRef: function toolbarRef(r) {
1034
+ if (r) {
1035
+ _this4.toolbarRef = r;
1036
+ }
1037
+ },
1038
+ doneButtonRef: this.doneButtonRef,
1039
+ value: value,
1040
+ focusToolbar: this.state.focusToolbar,
1041
+ onToolbarFocus: this.handleToolbarFocus,
1042
+ onToolbarBlur: this.handleToolbarBlur,
1043
+ focus: this.focus,
1044
+ onKeyDown: onKeyDown,
1045
+ onChange: this.onChange,
1046
+ getFocusedValue: this.getFocusedValue,
1047
+ onBlur: this.onBlur,
1048
+ onDrop: function onDrop(event, editor) {
1049
+ return _this4.onDropPaste(event, editor, true);
1050
+ },
1051
+ onPaste: function onPaste(event, editor) {
1052
+ return _this4.onDropPaste(event, editor);
1053
+ },
1054
+ onFocus: this.onFocus,
1055
+ onEditingDone: this.onEditingDone,
1056
+ focusedNode: focusedNode,
1057
+ normalize: this.normalize,
1058
+ readOnly: disabled,
1059
+ spellCheck: spellCheck,
1060
+ autoCorrect: spellCheck,
1061
+ style: _objectSpread({
1062
+ minHeight: sizeStyle.minHeight,
1063
+ height: sizeStyle.height,
1064
+ maxHeight: sizeStyle.maxHeight
1065
+ }, slateEditorExtraStyles),
1066
+ pluginProps: otherPluginProps,
1067
+ toolbarOpts: toolbarOpts,
1068
+ placeholder: placeholder,
1069
+ renderPlaceholder: this.renderPlaceholder,
1070
+ onDataChange: this.changeData
1071
+ })), /*#__PURE__*/_react["default"].createElement(_alertDialog["default"], {
1072
+ open: dialog.open,
1073
+ title: dialog.title,
1074
+ text: dialog.text,
1075
+ onClose: dialog.onClose,
1076
+ onConfirm: dialog.onConfirm,
1077
+ onConfirmText: dialog.onConfirmText,
1078
+ onCloseText: dialog.onCloseText
1079
+ }));
1080
+ }
1081
+ }]);
1082
+ }(_react["default"].Component); // TODO color - hardcoded gray background and keypad colors will need to change too
1083
+ (0, _defineProperty2["default"])(Editor, "propTypes", {
1084
+ autoFocus: _propTypes["default"].bool,
1085
+ editorRef: _propTypes["default"].func.isRequired,
1086
+ error: _propTypes["default"].any,
1087
+ onRef: _propTypes["default"].func.isRequired,
1088
+ onChange: _propTypes["default"].func.isRequired,
1089
+ onFocus: _propTypes["default"].func,
1090
+ onBlur: _propTypes["default"].func,
1091
+ onKeyDown: _propTypes["default"].func,
1092
+ focus: _propTypes["default"].func.isRequired,
1093
+ value: _slatePropTypes["default"].value.isRequired,
1094
+ imageSupport: _propTypes["default"].object,
1095
+ mathMlOptions: _propTypes["default"].shape({
1096
+ mmlOutput: _propTypes["default"].bool,
1097
+ mmlEditing: _propTypes["default"].bool
1098
+ }),
1099
+ disableImageAlignmentButtons: _propTypes["default"].bool,
1100
+ uploadSoundSupport: _propTypes["default"].shape({
1101
+ add: _propTypes["default"].func,
1102
+ "delete": _propTypes["default"].func
1103
+ }),
1104
+ charactersLimit: _propTypes["default"].number,
1105
+ width: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
1106
+ minWidth: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
1107
+ maxWidth: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
1108
+ height: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
1109
+ minHeight: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
1110
+ maxHeight: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
1111
+ slateEditorExtraStyles: _propTypes["default"].object,
1112
+ highlightShape: _propTypes["default"].bool,
1113
+ disabled: _propTypes["default"].bool,
1114
+ spellCheck: _propTypes["default"].bool,
1115
+ nonEmpty: _propTypes["default"].bool,
1116
+ disableScrollbar: _propTypes["default"].bool,
1117
+ disableUnderline: _propTypes["default"].bool,
1118
+ autoWidthToolbar: _propTypes["default"].bool,
1119
+ pluginProps: _propTypes["default"].any,
1120
+ // customPlugins should be inside pluginProps (a property inside pluginProps)
1121
+ // customPlugins: PropTypes.arrayOf(
1122
+ // PropTypes.shape({
1123
+ // event: PropTypes.string,
1124
+ // icon: PropTypes.string,
1125
+ // iconType: PropTypes.string,
1126
+ // iconAlt: PropTypes.string
1127
+ // }),
1128
+ // ),
1129
+ placeholder: _propTypes["default"].string,
1130
+ isEditor: _propTypes["default"].bool,
1131
+ responseAreaProps: _propTypes["default"].shape({
1132
+ type: _propTypes["default"].oneOf(['explicit-constructed-response', 'inline-dropdown', 'drag-in-the-blank', 'math-templated']),
1133
+ options: _propTypes["default"].object,
1134
+ respAreaToolbar: _propTypes["default"].func,
1135
+ onHandleAreaChange: _propTypes["default"].func,
1136
+ maxResponseAreas: _propTypes["default"].number,
1137
+ error: _propTypes["default"].any
1138
+ }),
1139
+ extraCSSRules: _propTypes["default"].shape({
1140
+ names: _propTypes["default"].arrayOf(_propTypes["default"].string),
1141
+ rules: _propTypes["default"].string
1142
+ }),
1143
+ languageCharactersProps: _propTypes["default"].arrayOf(_propTypes["default"].shape({
1144
+ language: _propTypes["default"].string,
1145
+ characterIcon: _propTypes["default"].string,
1146
+ characters: _propTypes["default"].arrayOf(_propTypes["default"].arrayOf(_propTypes["default"].string))
1147
+ })),
1148
+ runSerializationOnMarkup: _propTypes["default"].func,
1149
+ toolbarOpts: _propTypes["default"].shape({
1150
+ position: _propTypes["default"].oneOf(['bottom', 'top']),
1151
+ alignment: _propTypes["default"].oneOf(['left', 'right']),
1152
+ alwaysVisible: _propTypes["default"].bool,
1153
+ showDone: _propTypes["default"].bool,
1154
+ doneOn: _propTypes["default"].string,
1155
+ minWidth: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number])
1156
+ }),
1157
+ activePlugins: _propTypes["default"].arrayOf(function (values) {
1158
+ var allValid = values.every(function (v) {
1159
+ return _plugins.ALL_PLUGINS.includes(v);
1160
+ });
1161
+ return !allValid && new Error("Invalid values: ".concat(values, ", values must be one of [").concat(_plugins.ALL_PLUGINS.join(','), "]"));
1162
+ }),
1163
+ className: _propTypes["default"].string,
1164
+ maxImageWidth: _propTypes["default"].number,
1165
+ maxImageHeight: _propTypes["default"].number
1166
+ });
1167
+ (0, _defineProperty2["default"])(Editor, "defaultProps", {
1168
+ disableUnderline: true,
1169
+ onFocus: function onFocus() {},
1170
+ onBlur: function onBlur() {},
1171
+ onKeyDown: function onKeyDown() {},
1172
+ runSerializationOnMarkup: function runSerializationOnMarkup() {},
1173
+ mathMlOptions: {
1174
+ mmlOutput: false,
1175
+ mmlEditing: false
1176
+ },
1177
+ toolbarOpts: defaultToolbarOpts,
1178
+ responseAreaProps: defaultResponseAreaProps,
1179
+ languageCharactersProps: defaultLanguageCharactersProps,
1180
+ extraCSSRules: null,
1181
+ isEditor: false
1182
+ });
1183
+ var StyledEditorWrapper = (0, _styles.styled)('div')(function () {
1184
+ return {
1185
+ '&.withBg': {
1186
+ backgroundColor: 'rgba(0,0,0,0.06)'
1187
+ },
1188
+ '&.scheduled': {
1189
+ opacity: 0.5,
1190
+ pointerEvents: 'none',
1191
+ position: 'relative'
1192
+ },
1193
+ '&.toolbarOnTop': {
1194
+ marginTop: '45px'
1195
+ }
1196
+ };
1197
+ });
1198
+ var StyledUploadingMessage = (0, _styles.styled)('div')({
1199
+ position: 'absolute',
1200
+ top: '50%',
1201
+ left: '50%',
1202
+ transform: 'translate(-50%, -50%)'
1203
+ });
1204
+ var StyledSlateEditor = (0, _styles.styled)('div')(function () {
1205
+ return {
1206
+ '& table': {
1207
+ tableLayout: 'fixed',
1208
+ width: '100%',
1209
+ borderCollapse: 'collapse',
1210
+ color: _renderUi.color.text(),
1211
+ backgroundColor: _renderUi.color.background()
1212
+ },
1213
+ '& table:not([border="1"]) tr': {
1214
+ borderTop: '1px solid #dfe2e5'
1215
+ // TODO perhaps secondary color for background, for now disable
1216
+ // '&:nth-child(2n)': {
1217
+ // backgroundColor: '#f6f8fa'
1218
+ // }
1219
+ },
1220
+ '& td, th': {
1221
+ padding: '.6em 1em',
1222
+ textAlign: 'center'
1223
+ },
1224
+ '& table:not([border="1"]) td, th': {
1225
+ border: '1px solid #dfe2e5'
1226
+ },
1227
+ '&.showParagraph': {
1228
+ // a div that has a div after it
1229
+ '& > div:has(+ div)::after': {
1230
+ display: 'block',
1231
+ content: '"¶"',
1232
+ fontSize: '1em',
1233
+ color: '#146EB3'
1234
+ }
1235
+ },
1236
+ '&.separateParagraph': {
1237
+ // a div that has a div after it
1238
+ '& > div:has(+ div)': {
1239
+ marginBottom: '1em'
1240
+ }
1241
+ },
1242
+ '&.noPadding': {
1243
+ padding: '0 !important'
1244
+ }
1245
+ };
1246
+ });
1247
+ var StyledPreviewText = (0, _styles.styled)('div')({
1248
+ marginBottom: '36px',
1249
+ marginTop: '6px',
1250
+ padding: '20px',
1251
+ backgroundColor: 'rgba(0,0,0,0.06)'
1252
+ });
1253
+ var _default = exports["default"] = Editor;
1254
+ //# sourceMappingURL=editor.js.map