UNPKG

raonkeditor-react

Version:

React component for RAON K Editor

592 lines (584 loc) 25.5 kB
/** * @license Copyright (c) 2003-2022, RAONWIZ DevTeam. All rights reserved. */ import * as React from 'react'; import { getRaonwizComponentNamespace } from 'raonwiz-integrations-common'; import * as PropTypes from 'prop-types'; var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; var events = [ 'loaded', 'creationComplete', 'destroy', 'afterChangeMode', 'onError', 'onLanguageDefinition', 'afterPopupShow', 'agentInstall', 'beforeInsertUrl', 'mouse', 'command', 'key', 'resized', 'documentEditComplete', 'pasteImage', 'wordCount', 'beforePaste', 'customAction', 'fullScreen', 'setComplete', 'setInsertComplete', 'closeInstallPopup', 'setForbiddenWordComplete', 'drag', 'focus', 'dialogLoaded', 'beforeInsertHyperlink' ]; var namespaceEvents = ['beforeLoad', 'namespaceLoaded']; var defaultEvents = __spreadArray(__spreadArray([], events, true), namespaceEvents, true); var EVENT_PREFIX = '__RKE__'; function prefixEventName(evtName) { return "".concat(EVENT_PREFIX).concat(evtName); } function stripPrefix(prefixedEventName) { return prefixedEventName.substr(EVENT_PREFIX.length); } function eventNameToHandlerName(evtName) { var cap = evtName.substr(0, 1).toUpperCase() + evtName.substr(1); return "on".concat(cap); } function handlerNameToEventName(handlerName) { return handlerName.substr(2, 1).toLowerCase() + handlerName.substr(3); } var ComponentEventAction = __spreadArray(__spreadArray([], events, true), namespaceEvents, true).reduce(function (acc, evtName) { var _a; return __assign(__assign({}, acc), (_a = {}, _a[evtName] = prefixEventName(evtName), _a)); }, {}); function uniqueName() { return Math.random() .toString(36) .replace(/[^a-z]+/g, '') .substr(0, 5); } function registerComponentEventHandler(_a) { var debug = _a.debug, component = _a.component, evtName = _a.evtName, handler = _a.handler; var handlerId = debug && uniqueName(); var _handler = handler; if (debug) { _handler = function (args) { console.log({ logType: "RAONWIZ Log - invoke", operation: 'invoke', component: component, componentName: component.object.ID, evtName: evtName, handlerId: handlerId, eventInfo: args.eventInfo }); return handler(args); }; } if (debug) { console.log({ logType: "RAONWIZ Log - register", operation: 'register', component: component, componentName: component.object.ID, evtName: evtName, handlerId: handlerId }); } RAONKEDITOR._ExternalAttachEvents(component.object, evtName, _handler); return function () { if (debug) { console.log({ logType: "RAONWIZ Log - unregister", operation: 'unregister', component: component, componentName: component.object.ID, evtName: evtName, handlerId: handlerId }); } }; } var useEffect$1 = React.useEffect, useReducer = React.useReducer, useRef$1 = React.useRef; var defComponentType = "RAONKEDITOR"; var defComponentUrl = "/raonkeditor/js/raonkeditor.js"; var defConfig = {}; function useRaonkEditor(_a) { var debug = _a.debug, element = _a.element, config = _a.config, componentUrl = _a.componentUrl, _b = _a.runtimes, runtimes = _b === void 0 ? "html5" : _b, dispatchEvent = _a.dispatchEvent, _c = _a.subscribeTo, subscribeTo = _c === void 0 ? defaultEvents : _c; var componentUrlRef = useRef$1(componentUrl || defComponentUrl); var subscribeToRef = useRef$1(subscribeTo !== null && subscribeTo !== void 0 ? subscribeTo : defaultEvents); var debugRef = useRef$1(debug); var dispatchEventRef = useRef$1(dispatchEvent); var configRef = useRef$1(config || defConfig); var runtimesRef = useRef$1(runtimes); var _d = useReducer(reducer, { component: undefined, hookStatus: "init", }), _e = _d[0], component = _e.component, hookStatus = _e.hookStatus, dispatch = _d[1]; useEffect$1(function () { if (element && !component) { dispatch({ type: "loading" }); var onNamespaceLoaded = function (namespace) { var _a; if (subscribeToRef.current.indexOf("namespaceLoaded") !== -1) { (_a = dispatchEventRef.current) === null || _a === void 0 ? void 0 : _a.call(dispatchEventRef, { type: ComponentEventAction.namespaceLoaded, payload: namespace, }); } }; var initComponent = function (namespace) { var _a; var isViewMode = configRef.current.Mode === "view"; var isReadOnly = configRef.current.ReadOnly; if (subscribeToRef.current.indexOf("beforeLoad") !== -1) { (_a = dispatchEventRef.current) === null || _a === void 0 ? void 0 : _a.call(dispatchEventRef, { type: ComponentEventAction.beforeLoad, payload: namespace, }); } if (typeof namespace["_ExternalMakeComponent"] === "undefined") { _ExternalMakeComponent(namespace); } if (typeof namespace["_ExternalSetDestroyEvent"] === "undefined") { _ExternalSetDestroyEvent(namespace); } if (typeof namespace["_ExternalAttachEvents"] === "undefined") { _ExternalAttachEvents(namespace); } typeof runtimesRef.current !== "undefined" && (configRef.current.Runtimes = runtimesRef.current); if (debug) { console.log({ logType: "RAONWIZ Log - initComponent", operation: "makeComponent config", configRef: configRef.current, runtimesRef: runtimesRef.current, componentName: element.id, }); } var component = namespace["_ExternalMakeComponent"](element, configRef.current); var subscribedComponentEvents = subscribeToRef.current.filter(function (evtName) { return namespaceEvents.indexOf(evtName) === -1; }); subscribedComponentEvents.forEach(function (evtName) { registerComponentEventHandler({ debug: debugRef.current, component: component, evtName: evtName, handler: function (payload) { var _a; return (_a = dispatchEventRef.current) === null || _a === void 0 ? void 0 : _a.call(dispatchEventRef, { type: "".concat(EVENT_PREFIX).concat(evtName), payload: payload, }); }, }); }); registerComponentEventHandler({ debug: debugRef.current, component: component, evtName: "loaded", handler: function () { dispatch({ type: "loaded" }); }, }); registerComponentEventHandler({ debug: debugRef.current, component: component, evtName: "creationComplete", handler: function (_a) { _a.component; dispatch({ type: "ready" }); if (!isViewMode) { RAONKEDITOR.SetReadOnly(isReadOnly, element.id); } }, }); registerComponentEventHandler({ debug: debugRef.current, component: component, evtName: "destroy", handler: function () { dispatch({ type: "destroyed" }); }, }); dispatch({ type: "unloaded", payload: component, }); }; getRaonwizComponentNamespace(defComponentType, componentUrlRef.current, onNamespaceLoaded) .then(initComponent) .catch(function (error) { if (process.env.NODE_ENV !== "test") { console.error(error); } dispatch({ type: "error" }); }); } return function () { if (component && component.object && component.object.ID && document.getElementById(component.object.ID) === null && RAONKEDITOR) { if (RAONKEDITOR._ExternalLoadedEventMap.has(component.object.ID)) { RAONKEDITOR._ExternalLoadedEventMap.delete(component.object.ID); } if (RAONKEDITOR._ExternalCreationCompleteEventMap.has(component.object.ID)) { RAONKEDITOR._ExternalCreationCompleteEventMap.delete(component.object.ID); } if (RAONKEDITOR._ExternalDestroyEventMap.has(component.object.ID)) { RAONKEDITOR._ExternalDestroyEventMap.delete(component.object.ID); } RAONKEDITOR.Destroy(component.object.ID, false); } }; }, [component, element]); return { component: component, status: component === null || component === void 0 ? void 0 : component.status, error: hookStatus === "error", loading: hookStatus === "loading", }; } function reducer(state, action) { switch (action.type) { case "init": return __assign(__assign({}, state), { hookStatus: "init" }); case "loading": return __assign(__assign({}, state), { hookStatus: "loading" }); case "unloaded": return { component: action.payload, hookStatus: "unloaded", }; case "loaded": return __assign(__assign({}, state), { hookStatus: "loaded" }); case "ready": return __assign(__assign({}, state), { hookStatus: "ready" }); case "destroyed": return { component: undefined, hookStatus: "destroyed", }; case "error": return { component: undefined, hookStatus: "error", }; default: return state; } } function _ExternalMakeComponent(namespace) { namespace["_ExternalMakeComponent"] = function (element, options) { if (typeof RAONKEDITOR._ExternalLoadedEventMap === "undefined") { RAONKEDITOR._ExternalLoadedEventMap = new Map(); } if (typeof RAONKEDITOR._ExternalCreationCompleteEventMap === "undefined") { RAONKEDITOR._ExternalCreationCompleteEventMap = new Map(); } if (typeof RAONKEDITOR._ExternalDestroyEventMap === "undefined") { RAONKEDITOR._ExternalDestroyEventMap = new Map(); } RAONKEDITOR._ExternalLoadedEventMap.set(element.id, []); RAONKEDITOR._ExternalCreationCompleteEventMap.set(element.id, []); RAONKEDITOR._ExternalDestroyEventMap.set(element.id, []); namespace._ExternalDestroy = true; var _compConfig = { Id: element.id, EditorHolder: element.id, }; _compConfig = namespace.util.objectExtend(true, options, _compConfig); var _componentObject = new RAONKEditor(_compConfig); return { object: _componentObject, status: "ready" }; }; } function _ExternalAttachEvents(namespace) { namespace["_ExternalAttachEvents"] = function (componentObj, eventName, callbackFn) { var _componentConfig = componentObj._config; var _callbackFn = callbackFn; switch (eventName) { case "loaded": var _tempExternalLoadedEventListHT = RAONKEDITOR._ExternalLoadedEventMap.get(componentObj.ID); _tempExternalLoadedEventListHT.push(_callbackFn); RAONKEDITOR._ExternalLoadedEventMap.set(componentObj.ID, _tempExternalLoadedEventListHT); break; case "creationComplete": if (typeof _componentConfig.event[eventName] == "function") { break; } var _tempExternalCreationCompleteEventListHT = RAONKEDITOR._ExternalCreationCompleteEventMap.get(componentObj.ID); _tempExternalCreationCompleteEventListHT.push(_callbackFn); RAONKEDITOR._ExternalCreationCompleteEventMap.set(componentObj.ID, _tempExternalCreationCompleteEventListHT); var _dummyFn1 = function (componentName, paramObj) { var _tempLoaded = RAONKEDITOR._ExternalLoadedEventMap.get(componentObj.ID); for (var _idx = 0, _len = _tempLoaded.length; _idx < _len; _idx++) { try { _tempLoaded[_idx]({ eventInfo: { componentName: componentName, paramObj: paramObj }, }); } catch (e) { } } var _tempCreationComplete = RAONKEDITOR._ExternalCreationCompleteEventMap.get(componentObj.ID); for (var _idx = 0, _len = _tempCreationComplete.length; _idx < _len; _idx++) { try { _tempCreationComplete[_idx]({ eventInfo: { componentName: componentName, paramObj: paramObj }, }); } catch (e) { } } namespace._ExternalSetDestroyEvent(componentObj.ID); }; _componentConfig.event[eventName] = _dummyFn1; break; case "destroy": var _tempExternalDestroyEventListHT = RAONKEDITOR._ExternalDestroyEventMap.get(componentObj.ID); _tempExternalDestroyEventListHT.push(_callbackFn); RAONKEDITOR._ExternalDestroyEventMap.set(componentObj.ID, _tempExternalDestroyEventListHT); break; default: var _dummyFn2 = function (componentName, paramObj) { if (_callbackFn) { try { return _callbackFn({ eventInfo: { componentName: componentName, paramObj: paramObj }, }); } catch (e) { } } }; _componentConfig.event[eventName] = _dummyFn2; } }; } function _ExternalSetDestroyEvent(namespace) { namespace["_ExternalSetDestroyEvent"] = function (componentName) { var _domNodeRemovedTargetNode; var _targetElem; if (typeof MutationObserver === "function") { _targetElem = document.getElementById("raonk_frame_holder" + componentName); if (_targetElem) { _domNodeRemovedTargetNode = _targetElem; } else { _domNodeRemovedTargetNode = document.getElementById("raonk_frame_" + componentName); } if (_domNodeRemovedTargetNode) { new MutationObserver(function () { var _tempDestroy = RAONKEDITOR._ExternalDestroyEventMap.get(componentName); var editor = RAONKEDITOR.GetEditorByName(componentName); if (typeof _tempDestroy !== "undefined" && _tempDestroy.length > 0) { for (var _idx = 0, _len = _tempDestroy.length; _idx < _len; _idx++) { try { _tempDestroy[_idx]({ eventInfo: { componentName: componentName, paramObj: undefined, }, }); } catch (e) { } } } else if ( !!editor && typeof editor._config !== "undefined" && typeof editor._config.event.destroy === "function") { try { editor._config.event.destroy({ eventInfo: { componentName: componentName, paramObj: undefined, }, }); } catch (e) { } } else if (typeof KEDITORTOP.KEDITORWIN.RAONKEDITOR_Destroy === "function") { try { KEDITORTOP.KEDITORWIN.RAONKEDITOR_Destroy({ eventInfo: { componentName: componentName, paramObj: undefined, }, }); } catch (e) { } } }).observe(_domNodeRemovedTargetNode, { childList: true }); } } else { _targetElem = document.getElementById("raonk_frame_" + componentName); if (_targetElem) { _domNodeRemovedTargetNode = _targetElem; } if (_domNodeRemovedTargetNode) { _domNodeRemovedTargetNode.addEventListener("DOMNodeRemoved", function (e) { var _tempDestroy = RAONKEDITOR._ExternalDestroyEventMap.get(componentName); if (typeof _tempDestroy !== "undefined" && _tempDestroy.length > 0) { for (var _idx = 0, _len = _tempDestroy.length; _idx < _len; _idx++) { try { _tempDestroy[_idx]({ eventInfo: { componentName: componentName, paramObj: undefined, }, }); } catch (e) { } } } else if ( !!KEDITORTOP.G_CURRKEDITOR && typeof KEDITORTOP.G_CURRKEDITOR._config !== "undefined" && typeof KEDITORTOP.G_CURRKEDITOR._config.event.destroy === "function") { try { KEDITORTOP.G_CURRKEDITOR._config.event.destroy({ eventInfo: { componentName: componentName, paramObj: undefined, }, }); } catch (e) { } } else if (typeof KEDITORTOP.KEDITORWIN.RAONKEDITOR_Destroy === "function") { try { KEDITORTOP.KEDITORWIN.RAONKEDITOR_Destroy({ eventInfo: { componentName: componentName, paramObj: undefined, }, }); } catch (e) { } } }, false); } } }; } var useEffect = React.useEffect, useRef = React.useRef, useState = React.useState; function getComponentUniqueName() { return 'raonkeditor_' + Math.random() .toString(36) .replace(/[^a-z]+/g, '') .substr(0, 5); } function RaonkEditor(_a) { var debug = _a.debug, _b = _a.id, id = _b === void 0 ? getComponentUniqueName() : _b, _c = _a.config, config = _c === void 0 ? {} : _c, componentUrl = _a.componentUrl, runtimes = _a.runtimes, mode = _a.mode, readOnly = _a.readOnly, handlers = __rest(_a, ["debug", "id", "config", "componentUrl", "runtimes", "mode", "readOnly"]); var _d = useState(null), element = _d[0], setElement = _d[1]; var refs = useRef(handlers); var dispatchEvent = function (_a) { var type = _a.type, payload = _a.payload; var handlerName = eventNameToHandlerName(stripPrefix(type)); var handler = refs.current[handlerName]; if (handler) { return handler(payload); } }; if (config && typeof readOnly === 'boolean') { config.ReadOnly = readOnly; } if (config && typeof mode === 'string') { config.Mode = mode; } var _e = useRaonkEditor({ debug: debug, element: element, config: config, componentUrl: componentUrl, runtimes: runtimes, dispatchEvent: dispatchEvent, subscribeTo: Object.keys(handlers) .filter(function (key) { return key.indexOf('on') === 0; }) .map(handlerNameToEventName) }), component = _e.component, status = _e.status; useEffect(function () { if (component && status === 'ready' && typeof mode === 'string') { var _isLoadedComponent = RAONKEDITOR.IsLoadedEditorEx(component.object.ID); if (debug) { console.log({ logType: 'RAONWIZ Log - useEffect', operation: 'useEffect', component: component, componentName: component.object.ID, mode: mode, status: status, IsLoadedComponentEx: _isLoadedComponent }); } (_isLoadedComponent) && (RAONKEDITOR.SetEditorMode(mode, component.object.ID)); } }, [component, status, mode]); useEffect(function () { if (component && status === 'ready' && typeof readOnly === 'boolean') { var _isLoadedComponent = RAONKEDITOR.IsLoadedEditorEx(component.object.ID); if (debug) { console.log({ logType: 'RAONWIZ Log - useEffect', operation: 'useEffect', component: component, componentName: component.object.ID, readOnly: readOnly, status: status, IsLoadedComponentEx: _isLoadedComponent }); } (_isLoadedComponent) && (RAONKEDITOR.SetReadOnly(readOnly, component.object.ID)); } }, [component, status, readOnly]); return (React.createElement("div", { id: id !== null && id !== void 0 ? id : undefined, ref: setElement })); } var propTypes = __assign({ config: PropTypes.object, debug: PropTypes.bool, componentUrl: PropTypes.string, id: PropTypes.string, mode: PropTypes.oneOf(['edit', 'view']), readOnly: PropTypes.bool, runtimes: PropTypes.oneOf(['html5', 'agent']) }, defaultEvents.reduce(function (acc, key) { var _a; return __assign(__assign({}, acc), (_a = {}, _a[eventNameToHandlerName(key)] = PropTypes.func, _a)); }, {})); RaonkEditor.propTypes = propTypes; export { ComponentEventAction, RaonkEditor, prefixEventName, registerComponentEventHandler, stripPrefix, useRaonkEditor };