@braineet/ui
Version:
Braineet design system
375 lines (373 loc) • 23.8 kB
JavaScript
;
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _tinymceReact = require("@tinymce/tinymce-react");
var _formik = require("formik");
var _styledComponents = require("styled-components");
var _utils = require("../../utils");
var _content = _interopRequireDefault(require("./styles/content"));
var _contentUI = _interopRequireDefault(require("./styles/contentUI"));
var _files = require("./utilies/files");
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["name", "editorFuncs", "uploadImage", "uploadVideo", "uploadFile", "value", "language", "autoRefresh", "wording", "onChange", "form", "theme", "disabled", "readOnly", "debouncedVal", "placeholder", "plugins", "autoFocus", "contentStyle", "quickbar", "init", "id"];
/* eslint-disable global-require */
// Import TinyMCE core and plugins
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(typeof e + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
if (typeof window !== 'undefined') {
require('tinymce/tinymce');
require('tinymce/models/dom');
require('tinymce/themes/silver');
require('tinymce/icons/default');
require('tinymce/plugins/advlist');
require('tinymce/plugins/autolink');
require('tinymce/plugins/autoresize');
require('tinymce/plugins/lists');
require('tinymce/plugins/link');
require('tinymce/plugins/image');
require('tinymce/plugins/charmap');
require('tinymce/plugins/preview');
require('tinymce/plugins/anchor');
require('tinymce/plugins/searchreplace');
require('tinymce/plugins/visualblocks');
require('tinymce/plugins/fullscreen');
require('tinymce/plugins/insertdatetime');
require('tinymce/plugins/media');
require('tinymce/plugins/table');
require('tinymce/plugins/code');
require('tinymce/plugins/help');
require('tinymce/plugins/wordcount');
require('tinymce/plugins/emoticons');
require('tinymce/plugins/emoticons/js/emojis');
require('tinymce/plugins/quickbars');
}
var Editor = function Editor(_ref) {
var name = _ref.name,
editorFuncs = _ref.editorFuncs,
uploadImage = _ref.uploadImage,
uploadVideo = _ref.uploadVideo,
uploadFile = _ref.uploadFile,
v = _ref.value,
language = _ref.language,
autoRefresh = _ref.autoRefresh,
wording = _ref.wording,
onChange = _ref.onChange,
_ref$form = _ref.form,
values = _ref$form.values,
setFieldValue = _ref$form.setFieldValue,
setFieldTouched = _ref$form.setFieldTouched,
theme = _ref.theme,
disabled = _ref.disabled,
readOnly = _ref.readOnly,
debouncedVal = _ref.debouncedVal,
placeholder = _ref.placeholder,
pluginsProps = _ref.plugins,
autoFocus = _ref.autoFocus,
contentStyle = _ref.contentStyle,
quickbar = _ref.quickbar,
init = _ref.init,
providedId = _ref.id,
restProps = _objectWithoutPropertiesLoose(_ref, _excluded);
var _useState = (0, _react.useState)(false),
isEditorChanged = _useState[0],
setIsEditorChanged = _useState[1];
var _useState2 = (0, _react.useState)(false),
languageLoaded = _useState2[0],
setLanguageLoaded = _useState2[1];
var editorId = _react.default.useMemo(function () {
return providedId || "tinymce-editor-" + Math.random().toString(36).substr(2, 9);
}, [providedId]);
var quickbarInit = quickbar ? {
toolbar: false,
quickbars_selection_toolbar: 'formatselect bold italic link bullist numlist',
quickbars_insert_toolbar: false
} : {};
var defaultPlugins = {
autoresize: true,
link: true,
media: true,
lists: true,
autolink: true,
image: true,
quickbars: quickbar
};
var plugins = _extends({}, defaultPlugins, pluginsProps);
var pluginList = [];
Object.keys(plugins).forEach(function (pluginName) {
if (plugins[pluginName]) {
pluginList.push(pluginName);
}
});
var initialValue;
if (values) {
initialValue = (0, _formik.getIn)(values, name);
} else {
initialValue = v;
}
var editorRef = (0, _react.useRef)(null);
var _useState3 = (0, _react.useState)(initialValue),
value = _useState3[0],
setValue = _useState3[1];
var debouncedValChange = (0, _utils.useDebounce)(value, debouncedVal);
(0, _react.useEffect)(function () {
var newVal = values ? (0, _formik.getIn)(values, name) : v;
if (newVal !== value && editorRef && editorRef.current && autoRefresh) {
editorRef.current.editor.setContent(newVal);
}
}, [values || v]);
(0, _react.useEffect)(function () {
if (typeof debouncedValChange === 'string' && debouncedValChange !== initialValue) {
if (setFieldValue) {
setFieldValue(name, debouncedValChange);
} else {
onChange(debouncedValChange);
}
if (setFieldTouched) {
setTimeout(function () {
return setFieldTouched(name);
}, 0);
}
}
}, [debouncedValChange]);
(0, _react.useEffect)(function () {
if (typeof window !== 'undefined') {
// Load icons if not already loaded
if (!document.getElementById('tinymce-icons')) {
try {
var script = document.createElement('script');
script.id = 'tinymce-icons';
script.src = 'https://data.braineet.com/braineet/assets/tinymce/icons.js';
script.onerror = function () {
return console.warn('TinyMCE icons not found');
};
document.head.appendChild(script);
} catch (error) {
console.warn('Failed to load TinyMCE icons');
}
}
// Load language if not already loaded
if (language && !document.getElementById("tinymce-lang-" + language)) {
try {
var _script = document.createElement('script');
_script.id = "tinymce-lang-" + language;
_script.src = "https://data.braineet.com/braineet/assets/tinymce/langs/" + language + ".js";
_script.onerror = function () {
return console.warn("Language " + language + " not found for TinyMCE");
};
document.head.appendChild(_script);
} catch (error) {
console.warn("Language " + language + " not found for TinyMCE");
}
}
setTimeout(function () {
setLanguageLoaded(true);
}, 100);
}
}, [language, languageLoaded]);
var onChangeEditor = function onChangeEditor(content) {
setIsEditorChanged(true);
setValue(content);
};
var onFileUpload = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(evt, callback) {
var file, acceptedTypes, uploadId, type;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
file = evt.target.files[0];
if (file) {
acceptedTypes = _files.acceptedFiles.split(',');
uploadId = Math.floor(Math.random() * 10000);
type = '';
if (file.type.match('image/*')) {
type = 'image';
} else if (file.type.match('video/*')) {
type = 'video';
} else if (acceptedTypes.some(function (mime) {
return file.type.match(mime);
})) {
type = 'file';
}
uploadEditorFile(file, uploadId, type).then(function (uploadedFile) {
if (type === 'image') {
imageUploaded(callback, uploadedFile.url);
} else if (type === 'video') {
videoUploaded(callback, uploadedFile.url);
} else if (type === 'file') {
fileUploaded(callback, uploadedFile.url, uploadedFile.name);
}
});
}
case 2:
case "end":
return _context.stop();
}
}, _callee);
}));
return function onFileUpload(_x, _x2) {
return _ref2.apply(this, arguments);
};
}();
var imageUploaded = function imageUploaded(callback, imageUrl) {
callback(imageUrl);
};
var videoUploaded = function videoUploaded(callback, videoUrl) {
callback(videoUrl);
};
var fileUploaded = function fileUploaded(callback, fileUrl, fileName) {
callback(fileUrl, {
text: fileName
});
};
var uploadEditorFile = function uploadEditorFile(file, id, type) {
if (!file) {
return;
}
if (type === 'image') {
if (uploadImage) {
return uploadImage(file, type, id);
}
} else if (type === 'video') {
if (uploadVideo) {
return uploadVideo(file, type, id);
}
} else if (type === 'file') {
if (uploadFile) {
return uploadFile(file, type, id);
}
}
};
var filePickCallback = function filePickCallback(callback, _, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
if (meta.filetype === 'file') {
input.setAttribute('accept', '*/*');
} else if (meta.filetype === 'image') {
input.setAttribute('accept', 'image/*');
} else if (meta.filetype === 'media') {
input.setAttribute('accept', 'video/*');
} else {
input.setAttribute('accept', '*/*');
}
input.onchange = function (e) {
return onFileUpload(e, callback);
};
input.click();
};
var initialValueUnchanged = _react.default.useMemo(function () {
if (!isEditorChanged) {
return value;
}
return initialValueUnchanged;
}, [value, isEditorChanged]);
if (typeof window === 'undefined') {
return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {});
}
if (!languageLoaded) {
return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {});
}
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_tinymceReact.Editor, _extends({
initialValue: initialValueUnchanged,
ref: editorRef,
disabled: disabled || readOnly,
id: editorId,
init: _extends({
skin: false,
placeholder: placeholder,
content_css: false,
content_style: [_content.default, _contentUI.default, contentStyle].join('\n'),
license_key: 'gpl',
relative_urls: true,
remove_script_host: true,
convert_urls: false,
branding: false,
menubar: false,
plugins: pluginList,
language: language,
file_picker_callback: filePickCallback,
file_picker_types: 'file image media',
statusbar: false,
image_description: false,
language_load: false,
default_link_target: '_blank',
toolbar_drawer: false,
paste_retain_style_properties: 'none',
block_formats: 'Paragraph=p; Heading 1=h1; Heading 2=h2; Heading 3=h3',
toolbar: !readOnly && "formatselect bold italic bullist numlist link image media alignleft aligncenter alignright alignjustify",
auto_focus: autoFocus ? editorId : false,
link_default_target: '_blank',
link_title: false,
setup: function setup(editor) {
if (!editor) return;
editor.on('focus', function () {
var _editor$container;
if (!(editor != null && (_editor$container = editor.container) != null && _editor$container.classList)) return;
editor.container.classList.toggle('focused');
editor.container.classList.remove('filled');
});
editor.on('blur', function () {
var _editor$container2;
var content = editor.getContent();
if (!(editor != null && (_editor$container2 = editor.container) != null && _editor$container2.classList)) return;
if (content != null && content.length) {
editor.container.classList.toggle('filled');
}
editor.container.classList.toggle('focused');
});
editor.on('init', function () {
var _editor$container3;
var content = editor.getContent();
if (!(editor != null && (_editor$container3 = editor.container) != null && _editor$container3.classList)) return;
if (content != null && content.length) {
editor.container.classList.toggle('filled');
}
});
}
}, quickbarInit, init),
onEditorChange: onChangeEditor
}, restProps));
};
Editor.defaultProps = {
editorFuncs: {
bold: true,
italic: true,
lists: true,
links: true,
uploads: true
},
wording: {
paragraph: 'Paragraph',
title: 'Title',
subtitle: 'Sub Title',
modalLink: {
title: 'Add a link',
fieldUrlTitle: 'Link',
fieldTextTitle: 'Text to display',
fieldTextPlaceholder: 'If not, then link displayed'
}
},
placeholder: '',
language: 'en',
theme: {},
plugins: {},
value: null,
autoRefresh: false,
onChange: function onChange() {},
readOnly: false,
debouncedVal: 300,
form: {},
uploadImage: null,
uploadVideo: null,
uploadFile: null,
autoFocus: false,
disabled: false,
init: {}
};
var _default = exports.default = (0, _styledComponents.withTheme)(Editor);