UNPKG

catreact

Version:

Catavolt Core React Components

682 lines (680 loc) 28.2 kB
"use strict"; /** * Created by rburson on 1/6/16. */ var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var catavolt_sdk_1 = require("catavolt-sdk"); /** Base Mixin for all catavolt components */ exports.CvBaseMixin = { contextTypes: { cvContext: React.PropTypes.object }, childContextTypes: { cvContext: React.PropTypes.object }, catavolt: function () { return this.props.catavolt || (this.context.cvContext && this.context.cvContext.catavolt); }, eventRegistry: function () { return this.props.eventRegistry || (this.context.cvContext && this.context.cvContext.eventRegistry); }, findFirstDescendant: function (elem, filter) { var result = null; if (elem.props && elem.props.children) { var elems = React.Children.toArray(elem.props.children); for (var i = 0; i < elems.length; i++) { var child = elems[i]; console.log(child); if (filter(child)) { result = child; } else if (child.props.children) { result = this.findFirstDescendant(child, filter); } } } return result ? result : null; }, findAllDescendants: function (elem, filter, results) { if (results === void 0) { results = []; } if (elem.props && elem.props.children) { var elems = React.Children.toArray(elem.props.children); for (var i = 0; i < elems.length; i++) { var child = elems[i]; console.log(child); if (filter(child)) { results.push(child); } if (child.props && child.props.children) { this.findAllDescendants(child, filter, results); } } } return results; }, findFirstScopeCtx: function (matchFn, startingCtx) { var scopeCtx = startingCtx || this.scopeCtx(); var result = null; while (scopeCtx && !result) { if (matchFn(scopeCtx)) { result = scopeCtx; } else { scopeCtx = scopeCtx.parentScopeCtx; } } return result; }, findEntityRec: function (startingContext) { if (this.props.entityRec) { return this.props.entityRec; } else { var e = null; var scopeCtx = this.findFirstScopeCtx(function (scopeCtx) { return scopeCtx.scopeObj instanceof catavolt_sdk_1.EntityBuffer || scopeCtx.scopeObj instanceof catavolt_sdk_1.EntityRecImpl || scopeCtx.scopeObj instanceof catavolt_sdk_1.NullEntityRec; }, startingContext); return scopeCtx ? scopeCtx.scopeObj : null; } }, findPaneContext: function (startingContext) { if (this.props.paneContext) { return this.props.paneContext; } else { var scopeCtx = this.findFirstScopeCtx(function (scopeCtx) { return scopeCtx.scopeObj instanceof catavolt_sdk_1.PaneContext; }, startingContext); return scopeCtx ? scopeCtx.scopeObj : null; } }, findPaneTitle: function (paneContext) { var title = paneContext.paneTitle; if (!title) title = paneContext.actionSource instanceof catavolt_sdk_1.WorkbenchLaunchAction ? paneContext.actionSource.name : null; if (!title) title = paneContext.paneDef.settings['dialogDescription']; if (!title || title === 'null') { return ''; } else { return title; } }, firstInScope: function (type, startingScopeCtx) { var scopeCtx = this.findFirstScopeCtx(function (scopeCtx) { return scopeCtx.scopeObj instanceof type; }, startingScopeCtx); return scopeCtx ? scopeCtx.scopeObj : null; }, getDefaultChildContext: function () { return { cvContext: { catavolt: this.catavolt(), eventRegistry: this.eventRegistry(), scopeCtx: { scopeObj: null, parentScopeCtx: this.scopeCtx() } } }; }, scopeCtx: function () { return this.context.cvContext && this.context.cvContext.scopeCtx; } }; /** * Enumeration of event types to be used with {@link CvEvent} * There is also a corresponding 'payload' object type for each of these * enum values, that is used as the {@link CvEvent.eventObj} type */ var CvEventType; (function (CvEventType) { CvEventType[CvEventType["LOGIN"] = 0] = "LOGIN"; CvEventType[CvEventType["LOGOUT"] = 1] = "LOGOUT"; CvEventType[CvEventType["ACTION_FIRED"] = 2] = "ACTION_FIRED"; CvEventType[CvEventType["NAVIGATION"] = 3] = "NAVIGATION"; CvEventType[CvEventType["STATE_CHANGE"] = 4] = "STATE_CHANGE"; CvEventType[CvEventType["MESSAGE"] = 5] = "MESSAGE"; CvEventType[CvEventType["SESSION_UPDATE"] = 6] = "SESSION_UPDATE"; })(CvEventType = exports.CvEventType || (exports.CvEventType = {})); var CvNavigationResultType; (function (CvNavigationResultType) { CvNavigationResultType[CvNavigationResultType["FORM"] = 0] = "FORM"; CvNavigationResultType[CvNavigationResultType["URL"] = 1] = "URL"; CvNavigationResultType[CvNavigationResultType["NULL"] = 2] = "NULL"; })(CvNavigationResultType = exports.CvNavigationResultType || (exports.CvNavigationResultType = {})); var CvMessageType; (function (CvMessageType) { CvMessageType[CvMessageType["ERROR"] = 0] = "ERROR"; CvMessageType[CvMessageType["WARN"] = 1] = "WARN"; CvMessageType[CvMessageType["INFO"] = 2] = "INFO"; })(CvMessageType = exports.CvMessageType || (exports.CvMessageType = {})); var CvStateChangeType; (function (CvStateChangeType) { CvStateChangeType[CvStateChangeType["PANE_DEF_CHANGE"] = 0] = "PANE_DEF_CHANGE"; CvStateChangeType[CvStateChangeType["DATA_CHANGE"] = 1] = "DATA_CHANGE"; CvStateChangeType[CvStateChangeType["DESTROYED"] = 2] = "DESTROYED"; CvStateChangeType[CvStateChangeType["MODE_CHANGE_READ"] = 3] = "MODE_CHANGE_READ"; CvStateChangeType[CvStateChangeType["MODE_CHANGE_WRITE"] = 4] = "MODE_CHANGE_WRITE"; })(CvStateChangeType = exports.CvStateChangeType || (exports.CvStateChangeType = {})); var CvActionFiredResultType; (function (CvActionFiredResultType) { CvActionFiredResultType[CvActionFiredResultType["ACTION_STARTED"] = 0] = "ACTION_STARTED"; CvActionFiredResultType[CvActionFiredResultType["ACTION_COMPLETED"] = 1] = "ACTION_COMPLETED"; })(CvActionFiredResultType = exports.CvActionFiredResultType || (exports.CvActionFiredResultType = {})); /** * The {@link CvEventRegistry} handles decoupled communication between components. Any component may subscribe to and publish * {@link CvEvent}s. See also {@link CvListener} and {@link CvEventType}. It also provides resource caching (i.e. caching of * some server provided objects to allow retrieval by 'id') */ var CvEventRegistry = (function () { function CvEventRegistry() { this._cache = null; this._listenerMap = []; } CvEventRegistry.prototype.clearAll = function () { this.clearCache(); this.removeAllListeners(); }; CvEventRegistry.prototype.clearCache = function () { this._cache = {}; }; CvEventRegistry.prototype.enableCache = function () { this._cache = this._cache || {}; }; CvEventRegistry.prototype.disableCache = function () { this._cache = null; }; CvEventRegistry.prototype.isCacheEnabled = function () { return this._cache !== null; }; CvEventRegistry.prototype.getEventByKey = function (key) { var result = this.isCacheEnabled() ? this._cache[key] : null; if (!result) { catavolt_sdk_1.Log.debug('No resource entry exists for resourceId ' + key); } return result; }; CvEventRegistry.prototype.publish = function (event, shouldCache) { if (shouldCache === void 0) { shouldCache = false; } var listenerArray = this._listenerMap[event.type]; if (listenerArray) { listenerArray.forEach(function (listener) { catavolt_sdk_1.Log.debug('publishing ' + JSON.stringify(CvEventType[event.type]) + ' to ' + listener); listener(event); }); } if (this.isCacheEnabled() && shouldCache && event.resourceId) { this.cacheObjectAt(event.resourceId, event); } }; CvEventRegistry.prototype.publishError = function (message, messageObj) { var event = { type: CvEventType.MESSAGE, eventObj: { message: message, messageObj: messageObj, type: CvMessageType.ERROR } }; this.publish(event, false); }; CvEventRegistry.prototype.cacheObjectAt = function (id, obj) { this._cache[id] = obj; }; CvEventRegistry.prototype.removeFromCache = function (key) { if (this.isCacheEnabled()) { delete this._cache[key]; } }; CvEventRegistry.prototype.subscribe = function (listener, eventType) { var listenerArray = this._listenerMap[eventType]; if (!listenerArray) { listenerArray = []; this._listenerMap[eventType] = listenerArray; } if (listenerArray.indexOf(listener) < 0) { listenerArray.push(listener); } }; CvEventRegistry.prototype.removeAllListeners = function () { this._listenerMap = []; }; CvEventRegistry.prototype.unsubscribe = function (listener) { for (var eventType in this._listenerMap) { var listenerArray = this._listenerMap[eventType]; if (listenerArray) { var index = listenerArray.indexOf(listener); if (index > -1) { listenerArray.splice(index, 1); } } } }; return CvEventRegistry; }()); exports.CvEventRegistry = CvEventRegistry; var CvValueAdapter = (function () { function CvValueAdapter() { this._subscriberArray = []; } /* Create a listener that can be 'handed off' to components that are the SOURCE of events, and that expect a listener. When this listener is notified, it will notify the rest of the listeners in the chain - i.e. the one's that have 'subscribed' to this provider */ CvValueAdapter.prototype.getDelegateValueListener = function () { var _this = this; return (function (value) { _this._value = value; _this._subscriberArray.forEach(function (updateListener) { updateListener(value); }); }); }; /** * @deprecated since 2.0.32 Use getNotifyFunction() instead */ CvValueAdapter.prototype.createValueListener = function () { return this.getDelegateValueListener(); }; CvValueAdapter.prototype.subscribe = function (updateListener) { if (this._subscriberArray.indexOf(updateListener) < 0) { this._subscriberArray.push(updateListener); if (this._value) { updateListener(this._value); } } }; return CvValueAdapter; }()); exports.CvValueAdapter = CvValueAdapter; /** Utilities */ var CvNavigationResultUtil = (function () { function CvNavigationResultUtil() { } CvNavigationResultUtil.determineType = function (navRequest) { if (navRequest instanceof catavolt_sdk_1.FormContext) { return CvNavigationResultType.FORM; } else if (navRequest instanceof catavolt_sdk_1.WebRedirection) { return CvNavigationResultType.URL; } else { return CvNavigationResultType.NULL; } }; CvNavigationResultUtil.publishNavigation = function (catavolt, eventRegistry, navRequest, actionId, workbenchId, navTarget, navigationListeners, sourceIsDestroyed, noTransition) { var resourceId = CvResourceManager.resourceIdForObject(navRequest, catavolt); var e = { type: CvEventType.NAVIGATION, resourceId: resourceId, eventObj: { navRequest: navRequest, actionId: actionId, workbenchId: workbenchId, navTarget: navTarget, noTransition: noTransition, sourceIsDestroyed: sourceIsDestroyed, type: CvNavigationResultUtil.determineType(navRequest) } }; eventRegistry.publish(e, CvResourceManager.shouldCacheResult(eventRegistry)); if (navigationListeners) { navigationListeners.forEach(function (listener) { listener(e); }); } return e; }; return CvNavigationResultUtil; }()); exports.CvNavigationResultUtil = CvNavigationResultUtil; var CvSessionManager = (function () { function CvSessionManager() { } CvSessionManager.removeSession = function () { if (typeof (sessionStorage) != 'undefined') { sessionStorage.removeItem('catavolt::session'); } }; CvSessionManager.storeSession = function (sessionContext) { if (typeof (sessionStorage) != 'undefined') { sessionStorage.setItem('catavolt::session', JSON.stringify(sessionContext)); } }; CvSessionManager.getSession = function () { if (typeof (sessionStorage) != 'undefined') { var sessionStr = sessionStorage.getItem('catavolt::session'); if (sessionStr) { var sessionObj = JSON.parse(sessionStr); if (sessionObj) { var systemContext = new catavolt_sdk_1.SystemContextImpl(sessionObj.systemContext._urlString, sessionObj.systemContext._appVersion); return new catavolt_sdk_1.SessionContextImpl(sessionObj.sessionHandle, sessionObj.userName, sessionObj.currentDivision, sessionObj.serverVersion, systemContext, sessionObj.tenantId); } else { return null; } } else { return null; } } else { return null; } }; CvSessionManager.updateSession = function (catavolt, eventRegistry) { if (typeof (sessionStorage) != 'undefined') { var sessionContext = this.getSession(); if (sessionContext) { var refreshFuture = catavolt.refreshContext(sessionContext); refreshFuture.onComplete(function (appWinDefTry) { if (appWinDefTry.isFailure) { var event_1 = { type: CvEventType.MESSAGE, eventObj: { message: 'Update session failed', messageObj: appWinDefTry.failure, type: CvMessageType.ERROR } }; eventRegistry.publish(event_1, false); } else { var event_2 = { type: CvEventType.SESSION_UPDATE, resourceId: CvResourceManager.resourceIdForObject(appWinDefTry.success, catavolt), eventObj: { appWinDef: appWinDefTry.success } }; eventRegistry.publish(event_2, CvResourceManager.shouldCacheResult(eventRegistry)); } }); return refreshFuture; } else { return catavolt_sdk_1.Future.createFailedFuture('CvReact::updateSession', 'no persistent session found'); } } else { return catavolt_sdk_1.Future.createFailedFuture('CvReact::updateSession', 'sessionStorage not supported'); } }; return CvSessionManager; }()); exports.CvSessionManager = CvSessionManager; var CvResourceManager = (function () { function CvResourceManager() { } CvResourceManager.deserializeRedirection = function (token) { var _a = token.split(CvResourceManager.PARAM_DELIM), handleValue = _a[0], sessionHandle = _a[1], dialogMode = _a[2], dialogType = _a[3], objectId = _a[4], actionId = _a[5], actionObjId = _a[6], actionType = _a[7]; var actionSource = null; if (actionType && actionType === 'ca') { actionSource = new catavolt_sdk_1.ContextAction(actionId, actionObjId, null); } else if (actionType && actionType === 'wla') { actionSource = new catavolt_sdk_1.WorkbenchLaunchAction(actionId, actionObjId, '', '', ''); } return { redirection: new catavolt_sdk_1.DialogRedirection(new catavolt_sdk_1.DialogHandle(Number(handleValue), sessionHandle), dialogType, dialogMode, null, objectId, false, null, null, {}, {}), actionSource: actionSource }; }; CvResourceManager.shouldCacheResult = function (eventRegistry) { //cache everything for now, can later set this preference component-by-component via a property return eventRegistry.isCacheEnabled(); }; CvResourceManager.resourceIdForObject = function (o, catavolt) { if (o instanceof catavolt_sdk_1.FormContext) { var formContext = o; return CvResourceManager.serializeRedirection(formContext.paneDef.dialogRedirection, formContext.actionSource); } else if (o instanceof catavolt_sdk_1.AppWinDef) { if (catavolt.sessionContextTry.isSuccess) { //right now the 'windowId' is the session handle. may need to change this if want to have multiple windows... return catavolt.sessionContextTry.success.sessionHandle; } else { return null; } } else if (o instanceof catavolt_sdk_1.WebRedirection) { var webRedirection = o; return 'ext_' + catavolt_sdk_1.StringUtil.hashCode(webRedirection.webURL); } else { catavolt_sdk_1.Log.debug('No resourceId found for object'); return null; } }; /** * @private * * This is an attempt to preserve a redirection and all it's state along with the action source, * in a single 'token' that can be used on the URL. This along with the session information, are used to make a * 'stateless' transition to a new URL. * The sdk and server require quite a bit of state to be retained by the client in order to 'rebuild' a navigation. * * @param redirection * @param actionSource * @returns {string} */ CvResourceManager.serializeRedirection = function (redirection, actionSource) { var _a = ['', '', ''], actionId = _a[0], actionObjId = _a[1], actionType = _a[2]; if (actionSource instanceof catavolt_sdk_1.ContextAction) { actionId = actionSource.actionId; actionObjId = actionSource.objectId; actionType = 'ca'; } else if (actionSource instanceof catavolt_sdk_1.WorkbenchLaunchAction) { actionId = actionSource.id; actionObjId = actionSource.workbenchId; actionType = 'wla'; } var dialogHandle = redirection.dialogHandle; var PARAM_DELIM = CvResourceManager.PARAM_DELIM; return (dialogHandle.handleValue ? dialogHandle.handleValue : '') + PARAM_DELIM + (dialogHandle.sessionHandle ? dialogHandle.sessionHandle : '') + PARAM_DELIM + (redirection.dialogMode ? redirection.dialogMode : '') + PARAM_DELIM + (redirection.dialogType ? redirection.dialogType : '') + PARAM_DELIM + (redirection.objectId ? redirection.objectId : '') + PARAM_DELIM + actionId + PARAM_DELIM + actionObjId + PARAM_DELIM + actionType; }; return CvResourceManager; }()); CvResourceManager.PARAM_DELIM = '~'; exports.CvResourceManager = CvResourceManager; var ColorUtil = (function () { function ColorUtil() { } ColorUtil.toColor = function (c) { return "rgba(" + [c.red, c.green, c.blue, c.alpha].join(",") + ")"; }; ColorUtil.toColorFromNum = function (num) { num >>>= 0; var b = num & 0xFF, g = (num & 0xFF00) >>> 8, r = (num & 0xFF0000) >>> 16, a = ((num & 0xFF000000) >>> 24) / 255; return "rgba(" + [r, g, b, a].join(",") + ")"; }; ColorUtil.toColorFromNumWithAlpha = function (num, a) { num >>>= 0; var b = num & 0xFF, g = (num & 0xFF00) >>> 8, r = (num & 0xFF0000) >>> 16; return "rgba(" + [r, g, b, a].join(",") + ")"; }; return ColorUtil; }()); exports.ColorUtil = ColorUtil; var DateUtil = (function () { function DateUtil() { } DateUtil.toISOFormatNoOffset = function (d) { // Build the ISO string because toISOString() will adjust for timezone, which we don't want. // d.toISOString(); - This will adjust the date based on timezone which is undesirable. var a = d.getFullYear() + "-"; var x = d.getMonth() + "-"; if (x.length == 2) { x = "0" + x; } a += x; x = d.getDate() + ""; if (x.length == 1) { x = "0" + x; } a += x; return a; }; return DateUtil; }()); exports.DateUtil = DateUtil; /** * CvImage Action Components * A CvImage has a property for actions. An action (CvImageAction) simply represents a button with a button style * and a parameterless callback action to be executed when the button is pressed. * * A CvImageProducer is a candidate representation of a CvAction. It has flags to determine when a CvAction should be * created or not (i.e. you can't delete an image if there is not already an image). UI will configure a set of * CvImageProducers that are appopriate for the UI. A signature control never supports a delete, while an image * control might support create/delete/undo. * * A CvImagePackage is an abstract class with 5 concrete subclasses. An instance of CvImagePackage is the value to * be set on the CvImageProducer call back listener. */ var CvImageExistenceState; (function (CvImageExistenceState) { CvImageExistenceState[CvImageExistenceState["Missing"] = 0] = "Missing"; CvImageExistenceState[CvImageExistenceState["Present"] = 1] = "Present"; CvImageExistenceState[CvImageExistenceState["Deleted"] = 2] = "Deleted"; })(CvImageExistenceState = exports.CvImageExistenceState || (exports.CvImageExistenceState = {})); ; var CvImagePackage = (function () { function CvImagePackage() { } CvImagePackage.prototype.isUrl = function () { return false; }; CvImagePackage.prototype.isDelete = function () { return false; }; CvImagePackage.prototype.isPick = function () { return false; }; CvImagePackage.prototype.isUndo = function () { return false; }; CvImagePackage.prototype.isRedo = function () { return false; }; return CvImagePackage; }()); exports.CvImagePackage = CvImagePackage; var CvImagePackageUrl = (function (_super) { __extends(CvImagePackageUrl, _super); function CvImagePackageUrl(url) { var _this = _super.call(this) || this; _this._url = url; return _this; } Object.defineProperty(CvImagePackageUrl.prototype, "url", { get: function () { return this._url; }, enumerable: true, configurable: true }); CvImagePackageUrl.prototype.isUrl = function () { return true; }; return CvImagePackageUrl; }(CvImagePackage)); exports.CvImagePackageUrl = CvImagePackageUrl; var CvImagePackagePick = (function (_super) { __extends(CvImagePackagePick, _super); function CvImagePackagePick() { return _super !== null && _super.apply(this, arguments) || this; } CvImagePackagePick.prototype.isPick = function () { return true; }; return CvImagePackagePick; }(CvImagePackage)); exports.CvImagePackagePick = CvImagePackagePick; var CvImagePackageUndo = (function (_super) { __extends(CvImagePackageUndo, _super); function CvImagePackageUndo() { return _super !== null && _super.apply(this, arguments) || this; } CvImagePackageUndo.prototype.isUndo = function () { return true; }; return CvImagePackageUndo; }(CvImagePackage)); exports.CvImagePackageUndo = CvImagePackageUndo; var CvImagePackageRedo = (function (_super) { __extends(CvImagePackageRedo, _super); function CvImagePackageRedo() { return _super !== null && _super.apply(this, arguments) || this; } CvImagePackageRedo.prototype.isRedo = function () { return true; }; return CvImagePackageRedo; }(CvImagePackage)); exports.CvImagePackageRedo = CvImagePackageRedo; var CvImagePackageDelete = (function (_super) { __extends(CvImagePackageDelete, _super); function CvImagePackageDelete() { return _super !== null && _super.apply(this, arguments) || this; } CvImagePackageDelete.prototype.isDelete = function () { return true; }; return CvImagePackageDelete; }(CvImagePackage)); exports.CvImagePackageDelete = CvImagePackageDelete; var ImageUtil = (function () { function ImageUtil() { } /** * Conserve aspect ratio of the orignal region. Useful when shrinking/enlarging * images to fit into a certain area. * * In most cases this is not needed as the object-fit:contain CSS will obtain * the desired result. * * @param {Number} srcWidth Source area width * @param {Number} srcHeight Source area height * @param {Number} maxWidth Fittable area maximum available width * @param {Number} maxHeight Fittable area maximum available height * @return {Object} { width, heigth } */ ImageUtil.calculateAspectRatioFit = function (srcWidth, srcHeight, maxWidth, maxHeight) { var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight); return { width: srcWidth * ratio, height: srcHeight * ratio }; }; return ImageUtil; }()); exports.ImageUtil = ImageUtil; var UIUtil = (function () { function UIUtil() { } /* Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing. Note: to use debounce with a React event handler (w/ SyntheticEvent), see http://blog.revathskumar.com/2016/02/reactjs-using-debounce-in-react-components.html */ UIUtil.debounce = function (func, wait, immediate) { if (immediate === void 0) { immediate = false; } var timeout; return function () { var context = this, args = arguments; var later = function () { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; ; return UIUtil; }()); exports.UIUtil = UIUtil;