Loading...
 

morphit_api

MorphIT API

(Available from MorphIT version 4.0.13)

The MorphIT client is downloaded from the browser and operated via the interface.

Furthermore, JavaScript functions are provided to interact technically with MorphIT. These functions are combined in the MorphIT API.

4.15.0, the MorphIT API additionally provides access to some central MorphIT services and thus enables the development of WebWidgets entirely without Angular(JS).

Structure

The functions of the API are stored in an object in the member morphitApi of the global object window. Functions can thus be called via:

morphitApi.apiCall(...)

Available API functions

Available API objects

4.15.0

webServiceRequest

With the help of this function, it is possible to call up web services such as the login process directly. The response is then interpreted by MorphIT. The caller receives feedback as to whether the process of calling the web service was successful, together with more detailed information on the outcome of the call.

Syntax

morphitApi.webServiceRequest(requestUrl, [parameters], [success], [error]) → Promise
Parameters Optional Type Brief description
requestUrl String Identifier of the WebService to be called
parameters x Object Parameters to be passed to the WebService (named)
success x Function Callback in case of success
error x Function Callback in case of failure
Return value Promise Can be evaluated with regard to the success status of the request

Error handling

There are various possibilities to react to the result of the WebService call. These can theoretically also be combined.

Two callbacks

In both cases, a callback is registered for each case, which deals with that case:

morphitApi.webServiceRequest("url", {}, function(result) { console.log("success: " + JSON.stringify(result)); }, function(result) { console.log("fail: " + JSON.stringify(result)); });
A callback

Only one callback is registered, which is called in both cases:

morphitApi.webServiceRequest("url", {}, function(result) { if (result.type === "error") { console.log("fail: " + JSON.stringify(result)); } else { console.log("success: " + JSON.stringify(result)); } });
Promise

The result is reacted to by Promise:

morphitApi.webServiceRequest("url", {}) .then(function(result) { console.log("success: " + JSON.stringify(result)); }).catch(function(result) { console.log("fail: " + JSON.stringify(result)); });

In browsers that do not support Promise, such as Internet Explorer 11, this type of error handling is not available: In this case nothing is returned.

webServiceLogin

This is a useful short form of morphitApi.webServiceRequest("login_static", ...), which can be used to log a user in via JavaScript.

Syntax

morphitApi.webServiceLogin(username, password, success, error) → Promise
Parameters Optional Type Brief description
username String Username
password String Password of the user
success x Function Callback in case of success
error x Function Callback in case of failure
Return value Promise Can be evaluated with regard to the success status of the request

Error handling

As this is only a short form of the webServiceRequest function, error handling is also carried out in the same way.

Example

morphitApi.webServiceLogin("benutzer", "password") .then(function(result) { console.log("Login was successful"); }).catch(function(result) { console.log("Login failed because " + result.error); });

services

4.15.0

This object contains some MorphIT services that are useful for the development of WebWidgets .

services.contextMenu

This service provides methods for the WebWidget to control its grid menu (a menu button is displayed in the top right corner of the widget).

services.contextMenu.setGridMenuItem(widgetId, item, noAdd)

Adds a new menu item to the grid menu of the widget, or updates an existing item with the same item id.

The widgetId gets a WebWidget from the widget returned by webwidgetLoader.loadWidget().

The item is an object with the following structure:

Item
NameTypeDescription
idstringA unique identifier of this item
titlestringThe text to be displayed
iconstringHere you can optionally specify the class name of a FontAwesome (v4.7) icon to be displayed to the left of the text in this menu item.
action() => voidCallback function that is called as soon as the item is clicked.
keepOpenboolCan optionally be set to true to prevent the grid menu from closing as soon as the item is clicked. Default = false
hideOnCustomMenuboolCan optionally be set to true to hide this menu item once a grid menu has been assigned to the widget via CX_WIDGET::SetGridMenu.
childrenArray&lmt;Item>This field can optionally be used to define the submenu items of this item.
The submenu items are displayed in the order in which they are listed in the array.
isSeparatorboolCan optionally be set to true to insert a separator entry instead of a regular menu entry.
disabledboolCan optionally be set to true to indicate a disabled menu item.
ordernumberHere you can optionally assign an arbitrary order number to determine the order of the menu items on the top level. Menu items with a smaller value are displayed further up in the menu.

If an existing menu item is updated, only the properties specified in the item parameter are updated. For example, one can simply deactivate an already existing menu item with the following call.

morphitApi.services.contextMenu.setGridMenuItem(this.widget.id, {id:itemId, disabled:true});

If noAdd = true is set, then only existing menu items are updated, but no new ones are created if no menu item with the corresponding ID exists.

services.contextMenu.removeGridMenuItem(widgetId, item)

Removes a previously inserted menu item. The only property that must be defined in item is the id.

services.location

This service provides a few methods to work with the URL of the MorphIT application and resolve relative paths for resources.

services.location.clientSearch() -> {name:value}

This method parses the query string (everything after the "?") of the URL (from the current address bar in the browser) and returns the passed query parameters as an object.

services.location.proxySearch() -> {name:value}

If the MorphIT application is running behind a reverse proxy that translates a URL like "https://site.com/morphit/customer/acme" into "https://site2.com/?customer=acme", then this method returns only the query parameters that are added by the reverse proxy and are not visible in the browser's address bar (the MorphIT server plays this information back to the client).

The query parameters are returned as an object just like from location.clientSearch().

services.location.search() -> {name:value}

This method returns all query parameters (location.clientSearch() + location.proxySearch()) as an object that the MorphIT server saw during the query and returned to the client.

services.location.getPort() -> number

This method returns the port number from the address line of the browser. If no port is explicitly specified, the port number is determined from the protocol used (http/https).

services.location.resolvePathStrict(relativePath, startPath?) -> string

Resolves a path relative to a start path (default = path to index.html of MorphIT) and throws an error if during path navigation an attempt is made to navigate out of the root path ("/") via "..".

If an absolute path is passed (starting with "/"), then the path is resolved relative to the root path and the startPath parameter is ignored.

services.location.getRelativePath(resource, startPath?) -> string

Resolves the relative path passed in resource relative to the directory of startPath (default = path to index.html of MorphIT). There is no path resolution in the classical sense, the two strings are connected at the correct position and if the URL is requested via the browser, then the browser resolves the path navigation ("." and "..").

services.location.getAbsolutePath(resource, startPath?) -> string

Like location.getRelativePath(), except that an absolute URL is generated that also contains the server address itself.

services.localization

This service implements methods and objects to allow WebWidgets to respond to language/location changes.

services.localization.onLanguageChanged(callback) -> deregisterFn

This method registers a callback function that is called each time the language changes with the new language. The passed callback function is called with a string parameter and the language corresponds to the DIN EN ISO 639-1 Alpha 2 standard. (Ex. "en", "de", "fr")

The callback function is called directly with the currently active language for the first time during registration.

The returned deregisterFn should be called to deregister the callback as soon as it is no longer needed. For WebWidgets, this should be done at the latest when they are closed (see Widget.onDestroy()).

services.localization.onLocaleChanged(callback) -> deregisterFn

This method registers a callback function that is called with the new locale information whenever the locale information changes. The locale information is an object and currently consists of the following data:

LocaleInfo
NameTypeMeaning
languagestringThe currently active language according to DIN EN ISO 639-1 Alpha 2 standard. (e.g. "de")
languageListArray&lmt;string>The list of languages provided by the system for selection.
dateFormatstringThe date format currently set in the system as used by many formatting libraries. (e.g. "DD.MM.YYYY")
datePlaceholderstringA placeholder for date widgets derived from the date format and adapted to the current language: (e.g. "DD.MM.YYYY").

The callback function is called for the first time during registration directly with the currently active locale information.

The returned deregisterFn should be called to deregister the callback as soon as it is no longer needed. For WebWidgets, this should be done at the latest when they are closed (see Widget.onDestroy()).

services.localization.registerTranslation(widgetUrl, path?) -> Translator

This method allows a WebWidget to register its translation file(s) and returns an object that loads the translation files on demand and reads texts by id from the translation files.

Usually, the path to the WebWidget should be specified as widgetUrl (see Widget.url) and the relative path from the folder of the WebWidget to the translation file, or to the folder with the translation files, as path.

Alternatively, a path to the translation file/folder can be specified directly as widgetUrl and path can be omitted as a parameter in this case. In this case, widgetUrl is resolved relative to MorphIT's index.html.

<script> morphitApi.services.webwidgetLoader.loadWidget('widget.js').then((widget) => { let translator = morphitApi.service.localization.registerTranslation(widget.url, 'translations/'); translator.translate(['hello', 'world']).then((t) => { console.log(t['hello'] + ' ' + t['world']); }); }) </script>

If a .json translation file is specified, then MorphIT expects that for each language abbreviation (e.g. "de") in the JSON file there is an object with the order from Id to text.

If a folder is specified as the translation path, MorphIT expects that for each language abbreviation (e.g. "de") there is a corresponding .json file in the folder (e.g. "de.json") in which the object with the assignment of Id to text is defined.

Only one Translator object is created per translation path, so that several widgets can share the same Translator object. In this case, the translation files are only loaded once into the memory.

Translator

This object is responsible for the delayed loading of the translation files and the translation of the ids into the texts based on the loaded translation files.

Translator.translate(ids, variables?) -> Promise&lmt;string|{id:text}>

This method loads the translation file for the current language (if not already done) and then translates the passed ids (string or array of strings) using this translation file. An id can also be a path if the translation file is structured accordingly (e.g. "dialog.title.warning").

If a single id is passed, then the promise is fulfilled with a single string (the translated text). If an array of ids is passed, then the promise is fulfilled with an object, where the keys represent the individual ids and the values represent the translated texts.

Optionally, an arbitrarily structured object can be passed in variables. In the translation files, the fields of this passed object can be referenced in the translation texts via "{{path}}".

widget.js
// Request and await translation for text literals this.translator.translate(['dialog.info', 'language.changed'], {lang:{from:'en', to:'de'}}).then((t) => { // Display translated texts in a dialog morphitApi.services.overlay.showDialog(t['dialog.info'] + ': ' + t['language.change'], 'info'); });

The associated translation file could look like this:

en.json
{ "dialog": { "info": "Information" }, "language": { "changed": "Sprache wurde von {{lang.from}} auf {{lang.to}} geändert" } }

services.morphitLocalStorage

This service provides access to the localStorage object used internally by MorphIT. The service stores keys with a URL prefix so that two MorphIT instances running on different paths on the same server do not overwrite each other's localStorage.

  • put(key, value) - set value
  • get(key) - read out value
  • remove(key) - remove value
  • clearAll() - remove all stored values
  • getAll() - Returns all entries of the localStorage as an object.

services.overlay

This service provides access to the MorphIT loading & dialogue overlay. Dialogues can be opened in the look & feel of MorphIT.

In addition, this can be used to control the loading overlay (loading curl) for the MorphIT application. However, WebWidgets should preferably use services.widgetOverlay for the display of a loading overlay and status texts in order not to impair the use of the rest of the application.

services.overlay.showDialog(message, level?, options?)

Displays a regular dialogue (as in DialogBox). The displayed message can contain any special characters and line breaks "\n" are displayed as such.

level can take one of the following values: "info", "warning" (=default), "error", "exception", "question" and determines the text and the styling of the title line of the dialogue.

The options object has the following fields that can be set:

NameTypeDescription
buttonsArray&lmt;string>An array of ids containing the buttons to be displayed.
The currently supported buttons are: "abort", "abort_capture", "back", "cancel", "capture", "continue", "help", "ignore", "no", "ok", "reload", "retry", "upload", "select_file", "select_files", "yes", "replace", "change", "save", "dont_save".
The default is a single "ok" button.
The order of the specified buttons does not matter for the display, as MorphIT automatically arranges the buttons according to the semantics.
timeoutnumberA timeout in seconds(!) after which the dialogue should be closed automatically.
onComplete(id)(id) => ?A function that is called with the id of the button with which the dialogue was closed. If the dialogue was closed by a timeout, undefined is passed instead of the button id.
buttonActions{id: (id) => bool }

This field is an object in which a function can be stored for each button id, which is called when this button is clicked with the button id and can then return true to signal that the dialogue is closed with it(onComplete is called with this button id).
If false is returned, the dialogue remains open.

disabledArray&lmt;string>A list of button ids (from buttons) that are displayed disabled.
noEscapeboolCan be set to true to prevent the invalidation of HTML characters in the text. This can be useful if the text has already been invalidated or if the text is to be formatted using HTML.

services.overlay.showInputDialog(options)

Displays a text input dialogue in which 1-n texts can be queried. The options parameter is an object with the following structure:

NameTypeDescription
titlestringThe dialogue title to be displayed
textstring |
array&lmt;string>
1-n texts (prompts). For each text entered here, an input field is displayed in the dialogue.
defaultstring |
array&lmt;string>
1-n Presets for the input fields. If this field is not set, the input fields are not preset and are displayed empty when the dialogue is opened.
placeholderstring |
array&lmt;string>
1-n Placeholder texts. These texts are displayed in grey in the input fields if the input field does not contain any text.
buttonsArray&lmt;string>The same button ids are allowed here as in the options for showDialog().
The default is: "ok", "abort".
abortButtonsArray&lmt;string>Buttons that are considered "abort" buttons. If these buttons are clicked, then the onComplete callback is only called with the button ID, the entered texts are not passed.
The default is: "back", "cancel", "abort", "abort_capture".
extraButtonsArray&lmt;Button>

Additional buttons can be defined here, which are inserted between the left-sorted buttons from button and the right-sorted buttons from buttons in the order in which they are listed in the array.

A button object has the following properties:

NameDescription
idA textual id that uniquely identifies the button.
This id is passed to onComplete if the button was clicked.
Default = the array index of this button.
textThe text to be displayed in the button
posShould the button be aligned left ("left") or right ("right").
Default = "right
defaultCan be set to true if this is to be the default button.
The default button is triggered when ENTER is pressed in the last input line.
Default = false

If no default button is defined, the button furthest to the right becomes the default button.

onComplete(id, result) => A callback function that is called as soon as the dialogue has been closed by pressing a button. If a button from abortButtons was pressed, then only the id parameter is set.
Otherwise result contains the entered text (string), or the entered texts (array&lmt;string>).

services.overlay.showFileDialog(text, multiSelect, webcam, fileTypePattern, onComplete)

Shows a file upload dialogue with text as description text, in which 1-n files can be dropped in. Alternatively, clicking on the upload button opens the native file explorer for file selection. The dialogue also shows a camera button with which the webcam can be opened in order to take a photo and select it.

If multiSelect = true, several files can be selected, otherwise only one file is allowed.

If webcam = true, the webcam is opened directly for taking a photo without the corresponding button having to be pressed first.

fileTypePattern can contain a string like "*.png" to restrict the file selection in the native file explorer to the corresponding file type. If this is not desired, simply pass false or undefined here.

onComplete(files) is the callback function that is called as soon as the dialogue is closed. If the dialogue was cancelled, then the function is called with undefined as a parameter, otherwise an array of files is called (even if multiSelect=false ). Files selected from the file system are passed as file objects, pictures taken with the webcam are objects with the following structure:

nameDescription
dataData URL containing the captured image (Base64 encoded).
fromStreamAlways true
nameA randomly generated filename for the image.

services.overlay.showThumbnailDialog(options, onComplete?)

Displays the overlay with a specified image. The image is displayed in its original size. The user can click anywhere on the overlay to close it again. This overlay is intended for the enlarged display of thumbnails.

options is an object that currently only defines the field imagePath. If a relative path is specified here, then the path is interpreted relative to MorphIT's index.html.

The optionally specified onComplete callbackis called as soon as the user has closed the overlay by clicking.

services.overlay.closeDialog()

Closes any open dialogues. The onConfirm/onComplete function indicated when opening the dialogue is not triggered.

services.overlay.showWaitingElement(message?)

This displays the overlay and the "waiting curl" with an optional status message.
WebWidgets should use WidgetOverlay.show() instead.

services.overlay.closeWaitingElement()

Closes a previously opened loading/status overlay.
WebWidgets should use WidgetOverlay.hide() instead.

services.webwidgetCommunication

This services encapsulates the communication of WebWidgets with ClassiX.

services.webwidgetCommunication.registerWidget(id)-> Channel

With this method, a WebWidget registers that it wants to communicate with the ClassiX counterpart of this WebWidget via a bidirectional communication channel. The id should correspond to the widget id of the WebWidget, which can be obtained, for example, via webwidgetLoader.loadWidget().

registerWidget() does not check the passed widget id for correctness. If an incorrect id is passed, then no messages can be sent and received via the returned channel object.

Note: Since the JavaScript of the WebWidgets can only be executed after the open WebWidget has arrived in the browser, any WebWidget communication between InstantView & JavaScript should always be initiated from the JavaScript side. Messages sent from InstantView to a JavaScript WebWidget before it has activated the channel(Channel.on()) will be lost.

Channel

A channel represents a bidirectional communication channel between ClassiX and the concrete WebWidget. If the channel is no longer needed, the channel should be closed and logged off using close().

Channel.on(type, handler)

Registers a web widget handler that is called each time ClassiX and the widget send a web widget message via PushSocket with the type passed. Only one handler can be registered per type. If on() is called a second time with the same type, only the handler passed last applies.

Parameter
NameTypeDescription
typestringThe message type (see PushSocket) for which this handler is to be registered.
If "*" is passed, then a handler is registered that handles all messages,
that have not already been handled by any other handler.
handlerfunction(data,type)A function called with the two parameters data, type whenever a message has been sent via PushSocket to this widget.

Channel.send(type,data)

Sends a web widget message to the ClassiX web widget (InstantView page) and implements the reverse function to PushSocket.

Parameters
NameTypeDescription
typestringThe type of the WebWidget message. On the InstantView side, the WebWidget receives the message as a
TYPE_SOCKET message(the type passed in uppercase +"_SOCKET"), which is sent directly to the WebWidget.
data*Any JavaScript type that can be serialised as JSON.
This value is then on the stack for the TYPE_SOCKET message.
ClassiX converts the value into an InstantView type like CX_JSON_PARSER::LoadFromString.

Channel.close()

Closes the communication channel. Message handlers logged on to the channel are no longer called following close(). This method should always be called when the channel is no longer needed or the WebWidget has been closed.

services.webwidgetLoader

This service is used to develop pure JS/HTML WebWidgets without Angular and provides only one relevant method for this purpose:

services.webwidgetLoader.loadWidget(path?)-> Promise&lmt;Widget>

This method loads the .js file of an .html WebWidget. This .js file usually contains all the logic of the web widget and, unlike the .html part , is only loaded once.

Attention: This method may only be called within a script block in the .html part of the WebWidget, otherwise the method cannot assign the call to a widget and potentially resolves the path incorrectly.

If no path argument was passed, then no script file is loaded, but only the widget structure is returned (including Promise, which is immediately resolved). The call without path makes sense for small script WebWidgets that are inserted directly into a WebWidget via PutValue and do not need to reload any script files, but still need access to the information from the widget object.

The Promise returned by loadWidget contains a Widget object with the following properties:

Widget
NameValue
idThe widget id of the WebWidget.
Required, among other things, for communication with ClassiX.
url

The URL of the .html file. This path can be used to
request resources located in a directory relative to the WebWidget itself.

elementThe element into which the .html file was loaded.

This element can be used to locate the elements of the .html file.

onDestroy

A function that can be called to register clean-up tasks.
The registered functions (1-n) are executed as soon as the WebWidget is closed.
is closed, or as soon as it

Note: loadWidget also writes the above properties directly into the returned Promise object, so these properties can be read before the Promise is fulfilled.

Code example:

myWidget/widget.html
<script> (function() { morphitApi.services.webwidgetLoader.loadWidget('widget.js').then((widget) => { // now the script is loaded.... }); })(); </script>

services.widgetOverlay(element) -> WidgetOverlay

This service is a factory function that can be used to create a loading/status overlay for an HTML element (e.g. a WebWidget). The overlay only covers the specified element and thus does not affect the use of the rest of the MorphIT application.

WidgetOverlay

The WidgetOverlay can be used to block the user's interactive use of the widget while the widget is unresponsive because it is waiting for data or performing calculations. The user receives a visual cue and can tell when the widget is ready again.

WidgetOverlay.show(statusText?, delay?, timeout?)

This method shows the widget overlay with the given statusText after a delay of delay milliseconds (default = 100). If a timeout (in milliseconds) was passed, then the overlay is hidden again after the specified timeout.

WidgetOverlay.hide()

Closes the last opened overlay again. If hide() is called after show() but before the specified delay, the display of the dialogue is cancelled.

WidgetOverlay.loadPromise(promise, statusText?, delay?) -> Promise

Calls show() with the passed statusText and delay, then hide() once the passed promise is fulfilled (fails or succeeds). The returned promise is fulfilled with the same value as the passed promise with the difference that the returned promise is only fulfilled after the call to hide().

The default delay of 100ms is to prevent the use of loadPromise() with very short running promises from leading to a disturbing flickering effect.

services.widgetModel

This service is used to provide information about a widget's attributes, e.g. "readonly" or slots.

services.widgetModel.getView(widgetId)-> WidgetView

This method returns the view information for the widget with the passed ID. This consists of an object with all the parameters that the widget contains in the view message.

    services.widgetModel.getValue(widgetId)-> WidgetValue

    This method returns the "Value" of the widget with the passed ID.