codeeffects.editor.js

Package

  • @codeeffects/editor - npm

    Files

    • codeeffects.editor.js
    • codeeffects.editor.common.css
    • codeeffects.editor.light.css
    • codeeffects.editor.dark.css

    Remarks

    The Code Effects Rule Editor provides a powerful, modular client-side interface that integrates seamlessly with any modern web application. It enables users to visually create, edit, and manage business rules directly in the browser, while your server-side code handles rule evaluation through the Code Effects Rule Engine.

    The editor is implemented as a self-contained JavaScript library that exposes a compact set of public functions via two global variables — $rule and $ce — while encapsulating all other logic within its internal scope. This makes it completely safe to add the editor to any environment without risking conflicts with existing scripts, frameworks, or global objects.

    Starting with script's version 6.1.5, the editor has been modularized to support both modern frameworks and traditional web applications:

    • It can be imported as an ES module in client frameworks such as React, Angular, or Vue. The module exports $rule and $ce as named exports and also registers them as global variables.
    • It can also be referenced as a plain script in any HTML markup using the <script type="module"> tag.
    • The editor's package is distributed through npm under the package name @codeeffects/editor, making it easy to integrate into any build pipeline.

    The package includes three CSS files:

    • codeeffects.editor.common.css — the core stylesheet shared across all themes
    • codeeffects.editor.light.css — the Light theme
    • codeeffects.editor.dark.css — the Dark theme

    Reference the common stylesheet and exactly one of the theme stylesheets.

    The Rule Editor is fully self-contained and has no dependencies on third-party client or server libraries. It supports all current versions of all major browsers.

    The Rule Repository client script is a separate package. See the Client-Side API Reference overview for how the two packages relate, and the codeeffects.repository.js page for the Repository client API.

    Refer to our demo project repos for examples of referencing, configuring, and using the editor across different web platforms.

Global Shortcuts

  • $rule

    Type: (Object) - The CodeEffects.Rule.Editor namespace

    This global shortcut is declared to make the footprint of the CodeEffects namespace smaller. All global members described on this page, such as $rule.init(..), $rule.defaults, and $rule.Common, are members of this object. The script also exports it as an ES module member (export { $rule, $ce }).

  • $ce(..)

    Returns: (Object) - Instance of the Rule Editor, or null

    This is a global shortcut to the $rule.Context.getControl(..) function that can be used to get an instance of a Rule Editor by the client id of its hosting div element. Returns null if the current context has no editor with that id.

    Parameters

    • id (String) - Client id of the hosting div element of Rule Editor. Required.

    Example

      var codeeffects = $ce("divRuleEditor");
    

Global Functions

  • $rule.init(..)

    Returns: (Object) - Newly created instance of Rule Editor

    This method initializes and returns an instance of the rule editor on the client. It supports both the server-centric and the client-centric initialization. For details, please refer to the dedicated documentation article available here.

    The method throws an error if the argument is missing, if the client id of the hosting element is not set, or if the current context already has an editor with the same id.

    Parameters

    • settings (String or Object) - For the server-centric initialization, the JSON string received from the GetGlobalData() method of the CodeEffects.Rule.Editor.Control .NET class. For the client-centric initialization, a settings object that contains the globalData property. This parameter is required.

    Properties of the settings object

    The client-centric initialization passes a single settings object. If the object contains the globalData property, the editor uses it as described below. The server-centric initialization passes only the JSON string and has no settings object, so the properties below do not apply to it.

    • id (String) - The ID of the <div> element that hosts the editor. Required for the client-centric initialization. The editor throws an error if the ID is missing or if the current context already has an editor with the same ID.

    • refData (String) - Any custom data that you want to pass between the client and server whenever the editor requests a new menu. This can be useful for passing user-specific or source-specific information. The editor passes it to the menuCallback as args.context.refData. Optional. Call the setRefData() function of the editor to change it later. See the Context class documentation for more information.

    • globalData (String) - A proprietary JSON string containing global data required by the editor. Required.

    • editorData (String) - A proprietary JSON string containing source-related data required by the editor. When using Adaptive Source, this value is still required because it contains UI-related information even though the source metadata is loaded dynamically. Required.

    • showHelpString (Boolean) - Indicates whether the editor shows the Help String. Optional. Default value is true.

    • showToolBar (Boolean) - Indicates whether the editor shows the Toolbar. Optional. Default value is true.

    • showLineDots (Boolean) - Indicates whether the editor shows a dot in front of each new line of the rule. Optional. Default value is false.

    • showDescriptionsOnMouseHover (Boolean) - Indicates whether the editor shows the descriptions of rule elements in the Help String when the mouse pointer hovers over them. Optional. Default value is true.

    • showMenuOnElementClicked (Boolean) - Indicates whether the editor shows the menu when the user clicks or taps a rule element. Optional. Default value is true.

    • showMenuOnRightArrowKey (Boolean) - Indicates whether the editor shows the menu when the user presses the right arrow key. Optional. Default value is true.

    • useHighestZindex (Boolean) - Indicates whether the editor calculates the highest zIndex currently used on the page and applies a higher one to its menus, date pickers, and other pop-up elements. Set it to true if the editor is hosted in a dialog or another element that could cover them. Optional. Default value is false.

    • saveRuleCallback (Function) - Called when the user requests to save the rule currently displayed in the Rule Area. Required when the Toolbar is enabled. Optional if your own application provides rule-saving functionality. The callback must not declare any parameters. Use the editor.extract() method to retrieve the current rule. The callback may be declared as either synchronous or asynchronous. The editor always invokes it synchronously.

      Example

        async function save()
        {
        	const res = await fetch(
        		'/api/save',
        		{
        			method: 'POST',
        			headers: {'Content-Type': 'application/json'},
        			body: JSON.stringify(editor.extract())
        		});
        };
      
    • loadRuleCallback (Function) - Loads a rule by its ID. Required when the Toolbar Rules menu is enabled. Optional otherwise. The callback may be declared as either synchronous or asynchronous. The editor always invokes it synchronously.

      Parameters

      • ruleID (String) - GUID string value of the rule ID.
    • deleteRuleCallback (Function) - Deletes the rule currently displayed in the Rule Area. Required when the Toolbar is enabled. Optional otherwise. The callback may be declared as either synchronous or asynchronous. The editor always invokes it synchronously.

      Parameters

      • ruleID (String) - GUID string value of the rule ID.
    • notifyCallback (Function) - Called whenever the editor needs to display a notification. This callback allows you to integrate the editor with your application's own notification system. If not set, the editor calls the default alert function. You can also set or replace it at any time by calling the setNotifyCallback() function of the editor instance. The callback may be declared as either synchronous or asynchronous. The editor always invokes it synchronously.

      Parameters

      • message (String) - Notification text.

      • notificationType (String) - One of the following values used by the editor internally. The editor currently reports only warning and error:

          var notificationTypes = Object.freeze(
          {
          	confirmation: "confirmation",
          	warning: "warning",
          	error: "error"
          });
        
    • adaptiveSource (Object) - Passing this object to $rule.init() instructs the editor to use the Adaptive Source model. If omitted, the editor automatically selects one of the remaining source models based on the supplied globalData.

      Properties

      • menuCallback (Function) - Called whenever the editor requires the next dynamic menu. The callback may be declared as either synchronous or asynchronous. The editor always invokes it synchronously. The callback must hand the received menu data to the editor by calling loadAdaptiveData(), or report a failure by calling adaptiveDataError(). With the server-centric initialization, set the callback and the other Adaptive Source settings by calling the setAdaptiveSource() function of the editor.

          async function menu(args)
          {
          	const res = await fetch(
          		'/api/menu',
          		{
          			method: 'POST',
          			headers: {'Content-Type': 'application/json'},
          			body: JSON.stringify({type: args.type, context: args.context})
          		});
        
          	const data = await res.json();
          	editor.loadAdaptiveData(data);
          };
        
        • args (Object) - Contains the current rule context and the type of menu requested by the editor.

            // The editor sets the value of refData to the value
            // supplied to $rule.init() or setRefData()
            var context = { refData: null, conditions: [], executions: [] };
          
          • The type property contains one of the members of the following public object, which mirrors the server-side RuleSectionType enum:
            $rule.Common.RuleSectionType = Object.freeze({ Conditions: 0, Executions: 1 });
          
      • behavior (Object) - Specifies how the editor processes newly received menu data. The editor can either replace existing menus with matching CacheID values or merge them. The default value is $rule.defaults.behavior, which is $rule.behavior.replace. The object is declared as:

          $rule.behavior = Object.freeze({ merge: 0, replace: 1 });
        
      • max (Integer) - Specifies the maximum time, in milliseconds, that the Loading... menu remains visible to prevent UI flickering. Default value is $rule.defaults.max.

      • min (Integer) - Specifies the minimum time, in milliseconds, before the editor displays the Loading... menu while waiting for the next menu. Default value is $rule.defaults.min.

        Remarks

        The editor includes a built-in mechanism that automatically waits for slow menu responses and displays the Loading... menu when appropriate. The text of this menu can be customized using the HelpXML feature.

        The $rule interface exposes default Adaptive Source settings:

          $rule.defaults = { min: 400, max: 800, behavior: $rule.behavior.replace, calculationValue: "[calculation]" };
        

        The $rule.defaults object also holds the calculationValue property, which is not an Adaptive Source setting. The object is mutable. You can modify the Adaptive Source defaults globally or override them for individual editor instances by passing custom values to $rule.init(). This is particularly useful when different source objects or source providers have different response characteristics.

    Example

      var editor = $rule.init({
      	id: "divEditor",
      	globalData: settings.globalData,
      	editorData: settings.editorData
      });
    

Global Objects

  • $rule.behavior

    Type: (Object) - Frozen

    Enumerates the ways in which the editor processes newly received Adaptive Source menu data. Used by the behavior property of the adaptiveSource setting.

      $rule.behavior = Object.freeze({ merge: 0, replace: 1 });
    
  • $rule.defaults

    Type: (Object)

    Default Adaptive Source settings and other defaults of the editor. The object is mutable: you can change its values globally, or override the Adaptive Source values for an individual editor by passing them to $rule.init(..) or setAdaptiveSource(..).

      $rule.defaults =
      {
      	min: 400,
      	max: 800,
      	behavior: $rule.behavior.replace,
      	calculationValue: "[calculation]"
      };
    

    Properties

    • min (Integer) - Default time, in milliseconds, before the editor displays the Loading... menu while it waits for the next dynamic menu.
    • max (Integer) - Default maximum time, in milliseconds, that the Loading... menu stays visible.
    • behavior (Integer) - Default value of the Adaptive Source behavior setting. One of the $rule.behavior values.
    • calculationValue (String) - The text that the editor uses as the value of a calculation element. Change it only if your application depends on that value.
  • $rule.Common

    Type: (Object)

    Contains frozen objects that mirror the .NET enumerations the editor uses to describe its data. They are useful when you read the arguments of an Adaptive Source callback or process the elements returned by the instance functions of the editor. The values are the same as the values of the matching server-side enumerations.

      // Passed as args.type to the menuCallback of an Adaptive Source
      $rule.Common.RuleSectionType = Object.freeze({ Conditions: 0, Executions: 1 });
    
      $rule.Common.RuleElementType = Object.freeze({ Field: 1, Method: 2, Action: 4, Setter: 6, Group: 8, Source: 12, Operator: 16 });
    
      $rule.Common.DataType = Object.freeze({ String: 0, Numeric: 1, Date: 2, Time: 3, Bool: 4, Enum: 6, Collection: 8, None: 16 });
    
      $rule.Common.ValueInputType = Object.freeze({ Fields: 0, User: 2, All: 4 });
    
      $rule.Common.FunctionType = Object.freeze({ Name: 0, Param: 1, Comma: 2, End: 3, None: 4 });
    
      $rule.Common.InputType = Object.freeze({ Field: 0, Input: 1, None: 2 });
    
      $rule.Common.SelectionType = Object.freeze({ Exists: 0, DoesNotExist: 1, None: 2, All: 3, First: 4, Last: 5, CountWith: 6, Count: 7 });
    
      $rule.Common.CollectionType = Object.freeze({ Value: 0, Reference: 2, Generic: 4, None: 8 });
    
      $rule.Common.CalculationType = Object.freeze(
      {
      	Field: 0, LeftParenthesis: 1, RightParenthesis: 2, Multiplication: 3,
      	Division: 4, Addition: 6, Subtraction: 7, Number: 8, None: 9, Function: 10,
      	Text: 11, Shift: 12, Unit: 13, Join: 14
      });
    
      $rule.Common.ItemType = Object.freeze(
      {
      	Flow: 0, Field: 1, Function: 2, Operator: 3, Value: 4, Clause: 6, Action: 7,
      	LeftParenthesis: 8, RightParenthesis: 9, LeftBracket: 10, RightBracket: 11,
      	Calculation: 12, Tab: 13, NewLine: 15, HtmlTag: 16, Setter: 17,
      	LeftSource: 18, RightSource: 19, Where: 20, Exists: 22,
      	ValueSeparator: 23, ListEnd: 25, InlineRule: 26
      });
    

    The value 24 of ItemType is retired and is never reused.

  • $rule.Context

    Type: (Object)

    The registry of Rule Editor instances on the current page. The editor adds an instance to it when you call $rule.init(..) and removes the instance when you call its dispose() function. Application code normally needs only the following two functions. The other members of the object (controls, addControl(..), removeControl(..), clear(), and Item) are used by the editor internally.

    Functions

    • getControl(id) (Function) - Returns the editor instance hosted by the element with the specified client id, or null. $ce(..) is a shortcut to this function.
    • controlExists(id) (Function) - Returns true if the context holds an editor with the specified client id. Otherwise, returns false.

    Example

      if ($rule.Context.controlExists("divEditor"))
      	$ce("divEditor").dispose();
    
  • $rule.ValueInput

    Type: (Object)

    Opens the editor's own input for a single value (a text box, a list, a date picker, or a time picker) on any element of your page, outside of a rule. The value is entered and validated exactly as the same value would be in a rule. The Rule Repository uses it to let users set the values of a test. Only one input can be open at a time: opening a new one closes the current one.

    Functions

    • open(options) (Function) - Opens the input and returns undefined. Throws an error if options.el is missing. See the options below.
    • close() (Function) - Closes the open input without choosing anything. Returns undefined.
    • isOpen() (Function) - Returns true if an input is open. Otherwise, returns false.
    • text(options, value) (Function) - Returns the text with which the input would show the value for the member described by options, such as a formatted date, Yes/No for a Boolean, or the name of an enumeration member. Useful for cells in which no input is currently open.

    Options

    • el (Element) - The element that the input opens against. Required. An element without an id is given one.
    • type (String) - One of "String", "Numeric", "Date", "Time", "Bool", "Enum", or "Items" (items of a data source). Required.
    • value (Object) - The current value, or null. A string, a number, a Boolean, the number of an enumeration member or the key of an item, a date as an ISO 8601 string (yyyy-MM-dd or yyyy-MM-ddTHH:mm:ss, with the offset for a DateTimeOffset), or a time as HH:mm:ss.
    • format (String) - Display format of a date or time, as the member declares it.
    • offset (Boolean) - true for a DateTimeOffset value: the date picker then asks for the offset as well.
    • duration (Boolean) - true for a TimeSpan value that is a duration. The value is then given and returned in the [d.]hh:mm:ss form.
    • min, max, decimals, maxLength (Number) - Bounds of a numeric or string value, as the member declares them.
    • items (Array) - Items of an enumeration or a data source, as objects with the v (value) and n (label) properties.
    • nullable (Boolean) - Offers null in a list and allows an empty box to mean null.
    • labels (Object) - Replaces the texts of the input. Supported names are cancel, apply, yes, no, nullText, tooLong, tooBig, tooSmall, notNumber, noDecimals, tooManyDecimals, days, hours, minutes, and seconds. Texts you leave out stay in English.
    • commit (Function) - Called as commit(value, text) with the new value, in the forms listed for value, and the text that shows it. value is null for null.
    • cancel (Function) - Called without parameters when the user gives up.

    Example

      $rule.ValueInput.open(
      {
      	el: document.getElementById("cellAge"),
      	type: "Numeric",
      	value: 42,
      	min: 0,
      	max: 150,
      	commit: function (value, text) { console.log(value, text); },
      	cancel: function () { console.log("Nothing chosen"); }
      });
    

Global Utility Functions

The following functions are general helpers that the editor shares with its own modules. They are safe to use in your code.

  • $rule.defined(..)

    Returns: (Boolean)

    Returns true if the parameter is not null, is not undefined, and is not NaN.

    Parameters

    • val (Object) - The value to check.
  • $rule.isNumeric(..)

    Returns: (Boolean)

    Returns true if the parameter is a finite number or a string that represents one.

    Parameters

    • val (Object) - The value to check.
  • $rule.isInteger(..)

    Returns: (Boolean)

    Returns true if the parameter is numeric and has no fractional part.

    Parameters

    • val (Object) - The value to check.
  • $rule.trim(..)

    Returns: (String)

    Removes white space from both ends of the string. Returns the parameter unchanged if it is not defined or empty.

    Parameters

    • txt (String) - The string to trim.
  • $rule.encode(..)

    Returns: (String)

    Escapes markup: replaces &, space, ", <, >, \, and ' with their HTML character references.

    Parameters

    • val (String) - The string to encode.
  • $rule.decode(..)

    Returns: (String)

    Reverses $rule.encode(..). Strings shorter than four characters are returned unchanged.

    Parameters

    • val (String) - The string to decode.
    • leaveQuotes (Boolean) - If true, the references to the double quote and the backslash are left as they are. Optional. Default value is false.
  • $rule.decodeText(..)

    Returns: (String)

    Turns a label that may contain HTML character references (numeric ones and the named Latin-1 ones) into the plain text it reads as. The editor sets all names and descriptions that it shows with this function and never as markup. Returns an empty string if the parameter is not defined.

    Parameters

    • val (String) - The label to convert.
  • $rule.makeDate(..)

    Returns: (Date)

    Creates a local Date from its parts. Unlike new Date(year, ..), it does not read a year from 0 to 99 as 1900 to 1999, so the .NET DateTime.MinValue (0001-01-01) is created correctly.

    Parameters

    • y (Integer) - Year.
    • mo (Integer) - Zero-based month.
    • d (Integer) - Day of the month.
    • h (Integer) - Hours. Optional. Default value is 0.
    • mi (Integer) - Minutes. Optional. Default value is 0.
    • sec (Integer) - Seconds. Optional. Default value is 0.
  • $rule.formatDate(..)

    Returns: (String)

    Formats a Date using a .NET-style date format string, such as "MMM dd, yyyy H:mm:ss tt". Returns date.toString() if the format is empty or "i".

    Parameters

    • date (Date) - The date to format.
    • format (String) - .NET date format string.
    • offsetMinutes (Integer) - The offset, in minutes east of UTC, that the z, zz, and zzz tokens show. Optional. The tokens show the offset of the browser if omitted.
  • $rule.deserialize(..)

    Returns: (Object)

    Parses a JSON string, escaping the new lines and tabs it may contain. Throws an error if the string cannot be parsed.

    Parameters

    • json (String) - The JSON string.

Remarks

The $rule object has other members that the editor uses internally and shares among its modules, such as DOM and layout helpers (getElementSize, getDocBounds, position, topZindex, and similar), Json, Duration, Offset, Event, Menu, Calendar, Time, Prompt, TextBox, Control, Settings, and the date name arrays. They are not part of the supported API, and they may change without notice.

Public Event Handlers

  • onBlur(..)

    Returns: (undefined)

    Gets invoked when the Rule Area loses focus (i.e., when the user first clicks or taps on any DOM element in the current document that is not a child node of the main div container of the Rule Area while it is focused). Subscribe to the onblur event of the Rule Area by calling this handler and passing a callback function as its only parameter. Unsubscribe by calling this handler without any parameters or by passing null as its only parameter.

    Parameters

    • callback (Function) - A callback function that the editor calls when the Rule Area loses focus. The editor passes no parameters to the callback.

    Example

      var editor = $ce("divEditor");
      editor.onBlur(function() { alert("The onBlur event is handled"); });
    
  • onCurrentChange(..)

    Returns: (undefined)

    Gets invoked each time the current element of the Rule Area changes, i.e., the element that the user clicked or moved to with the arrow keys, or the input into which a value is being typed. The editor calls the callback at most once per animation frame. Subscribe by calling this handler and passing a callback function as its only parameter. Unsubscribe by calling this handler without any parameters or by passing null as its only parameter. Hosts that never call this handler see no change in the editor's behavior. See also browseWhileDisabled(..).

    Parameters

    • callback (Function) - A callback function that the editor calls when the current element changes. The editor passes the current element (HTMLElement) to the callback, or null if there is no current element in the document anymore.

    Example

      var editor = $ce("divEditor");
      editor.onCurrentChange(function (el)
      {
      	console.log(el ? el.textContent : "No current element");
      });
    
  • onFocus(..)

    Returns: (undefined)

    Gets invoked when the Rule Area receives focus (i.e., when the user first clicks or taps on any child node of the main div container of the Rule Area while it is not focused). Subscribe to the onfocus event of the Rule Area by calling this handler and passing a callback function as its only parameter. Unsubscribe by calling this handler without any parameters or by passing null as its only parameter.

    Parameters

    • callback (Function) - A callback function invoked when the Rule Area receives focus. The editor passes a reference to the event.target element that was clicked or tapped within the Rule Area.

    Example

      var editor = $ce("divEditor");
      editor.onFocus( function (el) { alert("The onFocus event is handled. Target element: " + el.id); } );
    

Public Instance Functions

Unless stated otherwise, the functions that return the editor instance can be chained.

  • adaptiveDataError(..)

    Returns: (undefined)

    Call this function from the menuCallback of the Adaptive Source if the request for the next menu failed. The editor closes the Loading... menu and shows the message in the Help String (or, if the Help String is hidden, in a notification).

    Parameters

    • message (String) - The error message to show. Optional. If omitted, the editor shows its default error text.
  • browseWhileDisabled(..)

    Returns: (Object) - Rule Editor instance

    Opt-in behavior for a disabled editor. When turned on, a disabled editor still moves its current element on a click and with the arrow keys (it opens no menus and cannot change the rule), so your code can follow it with onCurrentChange(..). A disabled editor otherwise reacts to nothing.

    Parameters

    • on (Boolean) - true to turn the behavior on, false to turn it off.

    Example

      var editor = $ce("divEditor");
      editor.disable();
      editor.browseWhileDisabled(true);
      editor.onCurrentChange(function (el) { console.log(el); });
    
  • clear()

    Returns: (Object) - Rule Editor instance

    Removes all elements of the current rule from the Rule Area and resets the value returned by isAltered().

    Parameters

    • None.
  • deleted(..)

    Returns: (Object) - Rule Editor instance

    Calling this function after deleting a rule is necessary to clear editor's cache and remove the deleted rule from the Rules menu (if the Toolbar is displayed) and context menus.

    Parameters

    • id (String) - ID of the rule that is being deleted. This parameter is required.
  • disable()

    Returns: (Object) - Rule Editor instance

    Prevents users from adding new rules or modifying the rule currently loaded in the Rule Area.

    Parameters

    • None.

    Example

      var editor = $ce("divEditor");
      editor.disable();
    
  • dispose()

    Returns: (Object) - Rule Editor instance

    Disposes all resources used by Rule Editor, removes the event handlers it registered, empties its hosting div element, and removes the editor from the current context. After the call, $ce(..) no longer returns this instance, and you can call $rule.init(..) again with the same element id.

    Parameters

    • None.
  • enable()

    Returns: (Object) - Rule Editor instance

    Restores ability to add new rules or modify the rule currently loaded in the Rule Area.

    Parameters

    • None.
  • extract()

    Returns: (String) - JSON string

    Returns a JSON string containing the current rule and a value indicating whether it is valid. If the Rule Area contains a value that the user has not finished typing, the editor shows a warning and the function returns the JSON null. If the Rule Area is empty, returns an empty JSON.

    Parameters

    • None.

    Example

      var json = $ce("divEditor").extract();
    
  • getCalls()

    Returns: (Array)

    Returns the calls to methods and actions of the source that the current rule makes, in the order they are written. The function reads the Rule Area and does not change it. Calls to reusable rules are not included; use getRuleCalls() to get them. Returns an empty array if the editor is not initialized.

    Each array item is an object with the following properties:

    • scope (String) - "0" for the rule itself, then "0.1", "0.2", and so on for its collection conditions in the order they appear ("0.1.1" for a nested one).
    • position (Integer) - The one-based position of the call within its scope.
    • kind (String) - "method" or "action".
    • source (String) - The name of the source that declares the member.
    • value (String) - The token of the member.
    • name (String) - The display name of the member.
    • elements (Array) - The DOM elements the call consists of: its name, parameters, commas, and end.

    Parameters

    • None.
  • getElementInfo(..)

    Returns: (Object) - Description of the member, or null

    Returns what a rule element refers to in the source of the editor. The function does not change the editor. It returns null for elements that refer to nothing in the source, such as operators, clauses, parentheses, values that are not enumeration members, and calls to reusable rules. A field that is passed to a method, used in a calculation, or used as a value is reported as that field. A value of an enumeration is reported as the enumeration.

    The returned object has these properties:

    • kind (String) - One of "field", "collection", "method", "action", or "enum".
    • source (String) - The name of the source.
    • value (String) - The value of the member in the settings: the declared path of a field, the token of a method, or the class of an enumeration.
    • name (String) - The display name of the member. null for "enum".
    • enumType (String) - The class of the enumeration, if the member is one. Otherwise, null.

    Parameters

    • el (HTMLElement) - An element of the Rule Area, for example, one of the elements returned by getCalls() or the element passed to the onCurrentChange(..) callback.

    Example

      var editor = $ce("divEditor");
      editor.onCurrentChange(function (el)
      {
      	var info = el ? editor.getElementInfo(el) : null;
      	if (info) console.log(info.kind + ": " + info.name);
      });
    
  • getParts()

    Returns: (Object)

    Returns the conditions, setters, and collection conditions of the current rule, in the order they are written, each with the elements it is made of. The function reads the Rule Area and does not change it. The scopes are the same as in getCalls(), and the positions are counted for each kind within its scope.

    The returned object has three arrays, conditions, setters, and collections. Each item has the following properties:

    • scope (String) - The scope in which the part is written.
    • position (Integer) - The one-based position of the part among parts of its kind in the scope.
    • elements (Array) - The DOM elements the part consists of.

    Parameters

    • None.
  • getRuleCalls()

    Returns: (Array)

    Returns the calls to reusable rules that the current rule makes, in the order they are written. The function reads the Rule Area and does not change it. Returns an empty array if the editor is not initialized.

    Each array item is an object with the following properties:

    • scope (String) - The scope in which the call is written, as described for getCalls().
    • ruleId (String) - The ID of the called rule.
    • name (String) - The name of the rule as the Rule Area shows it.
    • source (String) - The name of the source on which the call is made.
    • elements (Array) - The DOM element of the call.

    Parameters

    • None.
  • getRuleId()

    Returns: (String) - String value of the Rule ID (.NET System.Guid)

    Returns the string ID of the current rule assigned by the Rule Editor. The editor generates new rule IDs by calling .NET’s System.Guid.NewGuid().ToString(). Returns null if no rules have been loaded into the editor, if the current rule has not yet been assigned an ID, or if the Rule Area is empty.

    Parameters

    • None.
  • getRuleText()

    Returns: (String)

    Returns the current rule as plain text, the way the editor shows it: the label of every element in order, one space between two elements, a line break for each new line, and a tab character for each tab at the start of a line. An unfinished rule is returned unfinished. Returns an empty string if the Rule Area is empty. The function works on a disabled editor as well.

    Parameters

    • None.

    Example

      var text = $ce("divEditor").getRuleText();
    
  • getSourceDefinitions()

    Returns: (Array)

    Returns a copy of the sources the editor was given, as the settings describe them. Changing the copy changes nothing in the editor. Returns an empty array if the editor has no sources yet.

    Each array item is an object with the following properties:

    • n (String) - The name of the source.
    • fds (Array) - The fields and methods of the source.
    • acs (Array) - The actions of the source.
    • irs (Array) - The reusable rules of the source, as objects with the v (rule ID) and n (name) properties.

    Each item of fds and acs has the properties v (value), n (display name), t (type), o (data type), cv (the name of the source of a collection of a source type), e (the class of an enumeration), and ir (true for a reusable rule). Properties that do not apply are null.

    Parameters

    • None.
  • isAltered()

    Returns: (Boolean)

    Returns true if the user has modified an existing rule after it was loaded into the Rule Area or a new rule after its creation was initiated. Otherwise, returns false.

    Parameters

    • None.
  • isEmpty(..)

    Returns: (Boolean)

    Returns true if the Rule Area currently contains no rule elements. Otherwise, returns false.

    Parameters

    • includeFormattingElements (Boolean) - Indicates whether formatting elements of the rule, such as tabs and new lines, should be counted. Optional. Default value is true.
  • isEvaluationType()

    Returns: (Boolean)

    Returns true if the loaded rule is of the evaluation type or if the rule author selected the New evaluation-type rule option from the Rules menu of the Toolbar. This function does not check which rule elements the author has added to the Rule Area so far. Returns true if the editor has not been initialized with settings yet.

    Parameters

    • None.
  • loadAdaptiveData(..)

    Returns: (undefined)

    Call this function from the menuCallback of the Adaptive Source to hand the requested menu data to the editor.

    Parameters

    • data (Object) - The menu data received from the server-side source provider. This parameter is required.
  • loadInvalids(..)

    Returns: (Object) – Rule Editor instance

    Call this function to load invalid rule elements into the Rule Editor.

    Parameters

  • loadRule(..)

    Returns: (Object) – Rule Editor instance

    Call this function to load a rule into the Rule Editor. The function returns undefined if the parameter is not defined.

    Parameters

  • loadSettings(..)

    Returns: (Object) – Rule Editor instance

    Call this function to load the Rule Editor client settings. You should also call it whenever the rule author changes any of the editor’s settings, such as the visibility of the Toolbar, Help String, and similar options.

    Parameters

  • redraw()

    Returns: (Object) - Rule Editor instance

    Recalculates the size and layout of the editor. Call it after your code changes the size of the hosting div element or shows a hidden one.

    Parameters

    • None.
  • saved(..)

    Returns: (Object) – Rule Editor instance

    Call this function after saving a new rule or updating an existing one to refresh the Rules menu of the Toolbar and context menus of the editor with the new or updated values. If the rule has no name, nothing is added to the menus, and a rule that is already in them keeps its name.

    Parameters

    • id (String) - ID of the rule that has been saved or updated. This parameter is required for new rules and optional for updates.
    • name (String) - Name of the rule. Optional. If omitted, the editor reads the name from the name box of the Toolbar (if the Toolbar is displayed).

    Example

      var editor = $ce("divEditor");
      editor.saved("3f2b7c1e-9d8a-4f55-b6a1-0c2d4e6f8a10", "Adult patients");
    
  • setAdaptiveSource(..)

    Returns: (Object) – Rule Editor instance

    Turns on the Adaptive Source model and sets its client-side settings. Use it for the server-centric initialization, which has no way to pass the callback to $rule.init(..); call it after loadSettings(..). For the client-centric initialization, pass the adaptiveSource object to $rule.init(..) instead.

    Parameters

    • args (Object) - An object with the same properties as the adaptiveSource object described in the initialization article: menuCallback (required), behavior, min, and max. The last three default to the values of $rule.defaults. This parameter is required.

    Example

      editor.setAdaptiveSource(
      {
      	menuCallback: menu,
      	behavior: $rule.behavior.merge
      });
    
  • setCallbacks(..)

    Returns: (Object) – Rule Editor instance

    Call this function during page initialization to specify which functions the Rule Editor should call when the rule author wants to load, delete, or save a rule, and when the editor needs to show a notification. Do not call it for the rule management callbacks if the Toolbar is disabled. The function replaces all four callbacks, so pass undefined or null for those you do not use.

    Parameters

    • loadRuleCallback (Function) - Callback function that handles loading a rule. This function must declare a single parameter of type string. The Rule Editor calls this function and passes it the rule ID when the rule author selects that rule from the Toolbar’s Rules menu.
    • deleteRuleCallback (Function) - Callback function that handles deleting a rule. This function must declare a single parameter of type string. The Rule Editor calls this function and passes it the rule ID when the rule author clicks the Delete button on the Toolbar.
    • saveRuleCallback (Function) - Callback function that handles saving a rule. The Rule Editor calls this function, without parameters, when the rule author clicks the Save button on the Toolbar. Call extract() inside the callback to get the rule data.
    • notifyCallback (Function) - Callback function that displays notifications. The editor passes it the notification text and the notification type ("warning" or "error"). Optional. The editor calls alert if it is not set.

    Example

      var editor = $ce("divEditor");
    
      editor.setCallbacks(
      	function (id) { /* load the rule with this id */ },
      	function (id) { /* delete the rule with this id */ },
      	function () { var json = editor.extract(); /* save json */ },
      	function (message, type) { console.log(type + ": " + message); });
    
  • setClientActions()

    Returns: (undefined)

    Deprecated. Use setCallbacks(..) instead. The function no longer sets anything: calling it throws an error.

    Parameters

    • None.
  • setNotifyCallback(..)

    Returns: (Object) – Rule Editor instance

    Sets or replaces only the notification callback. Pass null to go back to the default alert call.

    Parameters

    • notifyCallback (Function) - Callback function that displays notifications. The editor passes it the notification text (String) and the notification type (String, "warning" or "error").

    Example

      $ce("divEditor").setNotifyCallback(function (message, type)
      {
      	console.log(type + ": " + message);
      });
    
  • setRefData(..)

    Returns: (undefined)

    Changes the custom data that the editor passes to your Adaptive Source menuCallback as args.context.refData. The function throws an error if the editor has no settings yet, so call it after $rule.init(..) and loadSettings(..) (or after a client-centric $rule.init(..)).

    Parameters

    • refData (Object) - Any value. It replaces the refData value passed to $rule.init(..).

Remarks

The editor instance also has an init() function that $rule.init(..) calls internally for the client-centric initialization. Do not call it from your code.

Ask on Stack Overflow - Yes, it's still active
Ask in GitHub Discussions

p102

l097 --

l102

p101

×