HT for Web Beginners Manual

Index<

Index

Summary

What is HT?

HT is a one-stop solution based on the HTML5 standard enterprise application graphical user interface (GUI), which includes a rich graphical user interface (GUI) development class library for generic components, topologies, and 3D rendering engines, providing a fully based on HTML5 vector graphics editors, topology editors and 3D scene editors, and many other visual design tools, as well as a complete class library development manuals, tool manuals, and the HTML5 technology for large-scale team development of customer depth training manuals.

Product Features

Ease to use, lightweight, high-performance and cross-platform four principles are our never-ending pursuits.

Developing Class libraries

<script src="ht.js"></script> 

The HT core development class library has only one ht.js JavaScript(hereinafter referred to briefly as JS) file, calling ht.Default.getVersion() can get the current version number. We will ensure that all versions are downward compatibility, which means that when upgrading a product, you only need to update the ht.js file, which can be upgraded without any code modification.

The core ht.js class library contains the data model, generic components such as tree table, 2D topology components, vector and 3D rendering engines and other core functional components, while HT provides many extensions, such as dialog box, menu, and form, to meet other requirements of the class library or component for users to choose from.

Development Tools

Unrestricted, any text editor available.

Operating Environment

Any browser that supports the HTML5 standard. Years ago, Chrome, Firefox, Safari and Opera versions have all supported HTML5, iOS and Android browsers have also supported HTML5, IE needs IE9 and above versions , if you are using HT for Web 3D is supported by IE11 and above, and it is recommended to use the latest version of the browser as much as possible.

If the project environment must use an old IE browser such as IE6, IE7 and IE8, or by using HT for Web 3D, and the onsite environment cannot be upgraded to IE11, you can consider installing Google Chrome Frame plug-in, embedded in the following Tag code fragment, the page will use Chrome to render.

<meta http-equiv="X-UA-Compatible" content="chrome=1"> 

Pay attention to the following points while using the Google Chrome Frame:

The solution with embedded OBJECT element, bypassing Google Chrome Frame does not support iframe

<OBJECT ID="ChromeFrame" WIDTH=500 HEIGHT=500 CODEBASE="http://www.google.com"
        CLASSID="CLSID:E0A900DF-9611-4446-86BD-4B1D47E7DB2A">
    <PARAM NAME="src" VALUE="http://www.google.com">
    <embed ID="ChromeFrameplug-in" WIDTH=500 HEIGHT=500 NAME="ChromeFrame"
        SRC="http://www.google.com" TYPE="application/chromeframe">
    </embed>
</OBJECT>

Google Chrome Frame has stopped supporting and updating in January 2014, and Google Chrome Frame is now developing to 31, which has met the canvas capabilities of HT 2D and 3D, so HT customers can use Google Chrome Frame solves the problem of compatible IE old versions. Other questions refer to Google Chrome Frame's Developer Guide and Troubleshooting

Part of the old version of the Android terminal system, there are bugs that not erased clean and have a residual shadow for the canvas support, the following is a section workaround code:

ht.Default.viewListener = function (view, kind){
    var canvas = view._canvas;
    if(canvas && kind === 'beginValidate'){
        canvas.width = 0;
        canvas.height = 0;
        canvas.style.width = 0;
        canvas.style.height = 0;                    
    }
};

Shorthand

HT based on the JavaScript language, the development tools are weaker in spelling and error cues because of the flexibility of the JavaScript dynamic language, so HT provides shorthand naming methods for some commonly used functions, memorizing the following common function abbreviations can improve coding efficiency.

Several letters of the HT abbreviation have the following meanings:

The list of HT shorthand functions is as follows:

The following is some common shorthand examples:

graphView.getDataModel().getSelectionModel().setSelection(data) = graphView.dm().sm().ss(data) graphView.getDataModel().getSelectionModel().addSelectionChangeListener(func) = graphView.dm().sm().ms(func) dataModel.getSelectionModel().getLastData().setAttr('age', 35) = dataModel.sm().ld.a('age', 35)

Model

Design Pattern

Refer to DataModel Manual

Class Package Hierarchy

HT follows the conventional object-oriented language design style, with Camel-Case for classes and packages, class names beginning with uppercase, and packet names beginning with lowercase. The entire framework occupies only the global variable HT, which means that the development of the regular front-end page will take up the window.ht, if ht.js runs in the webwork environment will occupy the self.ht variable, if ht.js runs in node.js environment will occupy the module.exports.ht variable.

HT overall frame hierarchy is very "flat", ht.* includes models and system-related classes, ht.widget.* contains generic component-related classes, ht.graph.* contains 2D graphics component-related classes, ht.graph3d.* contains the class of the 3D graphics component-related classes, considering js language and HTML5 application particularity, as far as possible to reduce the hierarchy of class package, short package function naming is the characteristics of the API design in HT framework, which can reduce the user learning index, reduce the coding workload, contribute to minify the overall development kit.

The JavaScript language does not provide rigorous language-level support for object-oriented classes, for which the HT designs a package system for users to choose from, refer to Serialization Manual

Tools Class

List

HT provides ht.List array class that encapsulates an Array array and provides a more easily remember and use function interface:

Notifier

HT provides event notification manager ht.Notifier class, you can add listener functions, remove listener functions, and distribute events to all listener functions:

Default

ht.Default defines the default values for all components and a series of tool class functions, refer to Style Manual

Style

ht.Style object defines the default style attribute value with ht.Data type, refer to Style Manual

Color

ht.Color object defines all the default colors for the HT system, refer to Style Manual

JSONSerializer

ht.JSONSerializer serialization class that provides serialization and deserialization of the JSON format for DataModel data model, refer to Serialization Manual

Data Type

ht.Data (referred to briefly as Data, the following is a description of how to omit package header ht.) is described as the most basic data type, the user can store business information in the Data object properties, the current HT provides Node, Edge, Tab, Column, these types have different display effects in different view components: Data on the TreeView tree component represents a tree node; the Data on the TableView table component represents a row of records, and the column represents the properties of the Data object; Graphview Node on the graphics component represents a graphical element; Defining a page sign TabView uses the Tab type to store the page signing information; When defining a table column, TableView uses column to store column information.

Data

Refer to DataModel Manual

Node

ht.Node type is the base class of the GraphView and Graph3dView rendering data nodes, inheriting from the Data class. The following is Node of the GraphView topological map related function properties, and Graph3dView related function properties refer to 3D Manual. In addition to displaying pictures, Node can display a variety of predefined graphics, refer to Shape Section.

In the above example, the air11 data was created to adsorb the air13 data, air11 changed the size, air13 set the rotation:

ht.Default.setImage('mac', 'res/mac-air.png');            

air11 = new ht.Node();
air11.setName('11-inch MacBook Air');
air11.setImage('mac');
air11.setSize(80, 43);
air11.setPosition(100, 70);                
dataModel.add(air11);

air13 = new ht.Node();
air13.setName('13-inch MacBook Air');                
air13.setImage('res/mac-air.png');
air13.setPosition(260, 70);
air13.setRotation(Math.PI/2);
dataModel.add(air13);

air11.setHost(air13);   

The code sets GraphView to editable, allowing only air11 to edit the size, air13 can only rotate, which is implemented by setting Filter

graphView.setEditable(true);
graphView.setRectEditableFunc(function (data){
    return data === air11;
});
graphView.setRotationEditableFunc(function (data){
    return data === air13;
});

Edge

ht.Edge type is used to connect the source and target two Node nodes, and the two nodes can have multiple Edge, and also allow the source and target to be the same node. The agent of the line refers to the node in the current graph where the true agent connects the edge, and when the node is in the closed Group, the Group connects the internal nodes of the agent. More style attributes of Edge refer to Edge Style.

Can insert into the source and target node objects in the constructor by new ht.Edge(source, target), it can also build the Edge object and then set separately, the example overloads the graphView.getLabel function, customized the text label of the data, and when the multiple edges in the same group are merged, the agent text in the edge can show the edge group information:

var edge = new ht.Edge();
edge.setSource(source);
edge.setTarget(target);
dataModel.add(edge);               

edge = new ht.Edge(source, target);
edge.toggle();
dataModel.add(edge);                               

edge = new ht.Edge(source, source);
dataModel.add(edge);                 

graphView.getLabel = function (data){
    if(data instanceof ht.Edge){
        if(data.isEdgeGroupAgent()){
            return data.getEdgeGroupSize() + ' become 1';
        }
    }
    return data.getName();
};

Group

ht.Group type is used as a parent container to contain child datas, which can be expanded and merged by double-clicking on the GraphView topology, and when merged, the hidden descendant data node is automatically set, and the merged Group connects the agent if there is a child node connected to the outside. The movement of the Group will drive the child's nodes to follow, and the child's position and size changes will also affect the Group's expanded graphics and position. Refer to Group Style Properties.

In the example, the Group object is created, and the Group position is automatically affected by the location of the child nodes that are subsequently added, instead of being assigned a position on the group.setExpanded(true). Adding children through addChild or setParent is optional:

var group = new ht.Group();
group.setName('Double click on me'); 
group.setExpanded(true);
dataModel.add(group);

var node1 = new ht.Node();
node1.setName('Node1');
node1.setPosition(80, 80);
group.addChild(node1);
dataModel.add(node1);

var node2 = new ht.Node();
node2.setName('Node2');              
node2.setPosition(180, 80);
node2.setParent(group);
dataModel.add(node2);

Constructs a style of the ingroup attribute to false, the data will be free from the group, the group move and it will follow, but the node position or size change will not affect the Group object:

var node4 = new ht.Node();
node4.setName('The Special One');   
node4.setStyle('ingroup', false);
node4.setPosition(290, 100);
group.addChild(node4);
dataModel.add(node4);

The following code constructs a label label that does not affect the Group's child data, which overloads the Graphview.getBoundsForGroup function for this function, and only returns its node3. getRect() size for the node3 data, other datas continue to maintain the logic of the original function, which first caches the default function var oldfunc = Graphview.getBoundsForGroup, and then called by oldFunc.call(this, child) in the overloaded function, which use the HT common overload technique, such the method can be overloaded without defining a new class and can invoke the original function logic as needed:

var node3 = new ht.Node();
node3.setPosition(130, 140);
node3.s({
    'label.font': 'bold 21px arial',
    'label.color': 'white',
    'label.offset.y': 8,
    'label.background': '#E74C3C'
});                
node3.setName('HT for Web');
node3.setParent(group);
dataModel.add(node3);

var oldFunc = graphView.getBoundsForGroup;
graphView.getBoundsForGroup = function (child){
    if(child === node3){
        return node3.getRect();
    }
    return oldFunc.call(this, child);
};

Shape

Refer to Shape Manual

Polyline

Refer to Shape Manual

Grid

ht.Grid type is generally used as a container for grid layout of the subordinate nodes (attachNode.setHost(grid)), and the subordinate nodes can be Grid types, to achieve nested layouts.

SubGraph

ht.SubGraph types have similarities with the Group type, they will affect the way the child is rendered, different with the Group type with the child node in the same layer interface display, SubGraph type to present its children including descendant nodes in the next layer of interface, in GraphView component is shown as double-clicking SubGraph data will enter the new interface content, under the new interface content double-click the background can return the SubGraph interface of the data, SubGraph can be unlimited layer nesting.

The GraphView is related to the SubGraph function as follow:

Tab

Refer to TabView component Manual

Column

Refer to TableView Component Manual

Property

Refer to PropertyView Components Manual

Data Model

Refer to DataModel Manual

Selection Model

Refer to DataModel Manual#selectionmodel

Components

Constitutes

The components of the HT framework refer to visually interactive view controls, the HT framework is based on HTML5 technology, so the visual part of the HT component is essentially an HTML element, most of the HT components are bound to the DataModel data model, and the user can drive visual components by manipulating the pure JS language, to shield the complexity of the HTML underlying graphics technology. The aim that HT encapsulate HTML5 technology is to improve development efficiency and maintainability, but does not mean that users are not allowed to manipulate HTML native elements, programmers with HTML5 development experience can use a variety of HTML5 technologies to customize the HT component, in the context of understanding the HT system mechanism.

All HT components are at the root of a div component that can be obtained through the component's getView() function. The default and custom interaction event listeners are generally added to the div (getView().addEventListener(type, func, false)), the render layer is generally provided by canvas. The user can set the CSS background and other styles to the root div and canvas layers, you can also add a new HTML component to the root div layer and present it as a sibling component of canvas. HT components are generally set to position as the absolute absolute positioning mode, box-sizing properties are set to border-box.

Most of the HT components provide the isDisabled() and setDisabled(true/false, iconUrl) functions to make the entire component unusable, typically used to remotely load the data process to temporarily leave the component in an unusable state, iconUrl in which case the gif picture path is generally set to represent the being loaded state. Components in the disabled state generate a div that blocks the entire component through ht.Default.disabledBackground can modify the shaded component background color.

The rendering of HT components is largely implemented by the inner canvas component, which provides the appropriate extension function for customization, for example, listView provides drawRow for function custom line drawing, GraphView by vector mechanism to customize data image on topology rendering, etc., components that are rendered based on canvas such as ListView, PropertyView, TreeView, TableView, Treetableview, GraphView, etc., components, provides a brush interface for drawing canvas at the bottom and topmost levels:

All components of HT do not take the HTML feature of the scroll bar, completely from the HT component, the scroll bar can be automatically hidden, dynamically appearing when the component is translated or the mouse slides over the boundary, and the default transparent scrollbar cover is above the content and does not affect the layout of the component interface:

The HT component's coordinate origin defaults to the upper left corner, most components have the translation function, the translation visualization effect is the scrolling, divides into the horizontal ordinate translation translateX attribute, and the vertical coordinate translation translateY attribute, both default values are 0.

Some components can only be translated horizontally, such as tabView and tableHeader; some components can only be translated vertically, such as ListView and TreeView, while GraphView and TableView are both horizontal and vertical; can be overloaded adjustTranslateX and adjustTranslateY functions to change the translation logic:

The HT components are typically embedded in containers such as BorderPane, SplitView and TabView, and the outermost HT component requires the user to manually add getView() back to the bottom div element to the page's DOM element , it should be noted that when the parent container size changes, if the parent container is BorderPane and SplitView and so on these HT predefined container components, then the HT container automatically recursively invokes the child component invalidate function to notify the update. However, if the parent container is native to the HTML element, then the HT component is not known whether need to be updated, so the outermost HT component generally needs to listen for window size change events and invoke the outermost component invalidate function to update.

In order for the outermost component to fill the window with convenience, HT all components have a addToDOM function, its implementation logic is as follows, where iv is the invalidate's shorthand:

addToDOM = function (){   
    var self = this,
        view = self.getView(),   
        style = view.style;
    document.body.appendChild(view);            
    style.left = '0';
    style.right = '0';
    style.top = '0';
    style.bottom = '0';      
    window.addEventListener('resize', function () { self.iv(); }, false);            
}

Config

Changing the HT system default properties requires that the HT system only read htConfig configuration information at initialization time through a global htConfig variable name, so the attribute must be initialized before introducing the ht.js package, modifying htConfig when running the variable does not work again, the sample code is as follows:

<script>
    htconfig = {
        Color: {       
            label: '#000',
            labelSelect: '#FFF'          
        },
        Default: {
            toolTipDelay: 100,
            toolTipContinual: true
        },                
        Style: {
            'select.color': '#E74C3C',
            'select.width': 3
        }
    };
</script>           
<script src="ht.js"></script>   

Configurable parameters are grouped into three broad categories, and specific attribute descriptions refer to Style Manual

Image

Images are an important resource for graphics components, icons on trees, topological datas, and so on can be drawn with images, HT supports regular picture formats such as PNG and JPG, as shown in the Node chapter example, there are two ways to use a image:

Directly setting path in development is convenient, without registering images in advance, but when data model serialization the image path will occupy more memory, image path is not conducive to management maintenance in the future, both ways are the correct way to use, according to the project situation selected different ways or mixed use. If you use the url path, the HT interior automatically loads the picture, and automatically updates the corresponding view component after onload.

The HT frame of the image was given a broader meaning, HT provides a custom JSON format vector description in the HT standard defined JSON vector format, can also be used as a image for registration and use, HT vector are more space-saving than traditional picture format, zoom without distortion, the most powerful thing is that all the graphics parameters of the vector can be dynamically bound to data on the Data model, as specified in the Vector Manual.

ht.Default.setImage function has several methods of invocation:

Using registration img of the HTML element, the user needs to ensure that the image resource is loaded, and that the HT does not listen to its onload event, so the view component updates are not automatically notified.

ht.Default.getImage(name, color) can obtain the corresponding picture element, in the picture loading process, this function returns empty, only after onload can get the corresponding data element, color is the color parameter, generally is NULL, if has the color value then HT interior will build a new picture of color dyed

The HT also provides several drawing functions for the picture, the image in the following parameters can be plotted img or canvas elements, or vector json format, because the vector can dynamically bind the data model has the function of dyeing, so the vector can be drawn into the data view components and color dyeing parameters:

Animation

Under the design architecture of the HT data model driven graphics component, the animation can be understood as the process of gradually changing some attributes from the starting value to the target value, HT provides for ht.Default.startanim animation function, whose sample code is as follows:

ht.Default.startAnim({
    frames: 12, // Animation frame
    interval: 10, // Interval between frames
    easing: function (t){ return t * t; }, // Animation easing function, use `ht.Default.animEasing`, by default
    finishFunc: function (){ console.log('Done!') }, // The call function after animation finished
    action: function (v, t){ // Necessary, properties changed while on animation
        node.setPosition( // `node` moves from `p1` to `p2` in this example
            p1.x + (p2.x - p1.x) * v,
            p1.y + (p2.y - p1.y) * v
        );
    }
});

ht.Default.startAnim support frame-based and time-based two ways of animation, the above code is frame-based way, in this way the user by specifying the frames animation frame number, and interval animation frame interval parameter controls the animation effect.

The following code is time-based, in which the user only needs to specify the number of milliseconds the animation cycle of duration can be, HT will complete the animation in the specified time period, different from frame-based way has a definite fixed number of frames, that is how many times action function been called, the number of time-based mode frames or action functions are called depending on the system environment, generally the system configuration is better, the more efficient browsers call the number of frames and the animation process is smoother. Because JS language can not accurately control the interval time interval, the use of frame-based can not accurately control the animation time period, even if the same frames and interval parameters in different environments, there may be a big difference in the animation cycle, so HT defaults to time-based mode, if the duration and frames parameters are not be set, the duration parameter will be automatically set to ht.Default.animDuration value.

ht.Default.startAnim({
    duration: 500, // Animation-duration, use `ht.Default.animDuration`, by default
    action: function (v, t){ 
        ... 
    }
});

The startAnim function returns an anim object that can be called anim.stop(true) to terminate the animation, where the parameter shouldBeFinished represents a completely outstanding target change, if true, it will invoke anim.action(anim.easing(1)). At the same time anim also has anim.pause() and anim.resume() interruptible and continue animation functions, as well as the anim.isRunning() function to determine whether the animation is in progress.

The action function's first parameter v represents the value after the operation of the easing (t) function, t represents the progress of the current animation form 0 to 1, and the general properties vary according to the v parameter.

The above example shows the animation effect of clicking on a background graphic element to move to a click position, clicking on the data itself to rotate and zoom, ht.Default.startAnim easing parameter is used to allow user-defined functions to control animations through mathematical formulas, such as constant-speed changes, first-slow, and then fast-after effects, refer to http://easings.net/, the sample code easing.js defines a series of animation functions to choose from:

var Easing = {
    swing: function (t) {
        return ( -Math.cos(t * PI) / 2 ) + 0.5;
    },
    /**
    * Begins slowly and accelerates towards end. (quadratic)
    */
    easeIn: function (t) {
        return t * t;
    },
    /**
    * Begins quickly and decelerates towards end.  (quadratic)
    */
    easeOut: function (t) {
        return ( 2 - t) * t;
    },
    // ... 
}

In the example, the build uses graphView.setinteractors to remove all the default interactivity, adding listeners through view.addEventListener, while building the select element for HTML to select different easing effect, add it to the div component of graphView.getView(), so you need to do a filter on the select element in a custom interaction event, where graphview.getLogicalPoint(e) returns the logical coordinate position based on the interaction event.

In this example, the triggering data rotates around its center by clicking on the data, and the data is then restored to the original size by a large variable, which sets the frames for 30 frame and interval for 16 millisecond intervals. The frame-based way completes the animation; click on the background area trigger data to move to the specified click position, which completes the animation by setting duration for 500 cycle time-based.

var select = document.createElement('select');
select.style.position = 'absolute';
select.style.top = '10px';
select.style.right = '10px';
view.appendChild(select);
for(var name in Easing){
    var option = document.createElement('option');
    option.innerHTML = name;
    if(name === 'easeOut'){
        option.setAttribute('selected', 'true');
    }
    select.appendChild(option);
}                  

graphView.setinteractors(null);
var type = "ontouchend" in document ? 'touchstart' : 'mousedown';                                

isAnimating = false;
view.addEventListener(type, function (e){
    e.preventDefault();
    if(isAnimating || e.target === select || !ht.Default.isLeftButton(e)){
        return;
    }
    isAnimating = true;
    var data = graphView.getDataAt(e);
    var easing = Easing[select.value];
    var finishFunc = function (){
        isAnimating = false;
    };
    if(data === toy){
        var size = toy.getSize();
        ht.Default.startAnim({
            frames: 30, 
            interval: 16,
            easing: easing,
            finishFunc: finishFunc,                            
            action: function (v){
                toy.setRotation(Math.PI * v);
                var r = Math.abs(v - 0.5) * 2;
                toy.setSize(size.width * r, size.height * r);
            }
        });                        
    }else{
        var p2 = graphView.getLogicalPoint(e);
        var p1 = toy.getPosition();
        anim = ht.Default.startAnim({  
            duration: 500,
            easing: easing,
            finishFunc: finishFunc,
            action: function (v){
                toy.setPosition(
                    p1.x + (p2.x - p1.x) * v,
                    p1.y + (p2.y - p1.y) * v
                );
            }
        });                        
    }
}, false);

The example modifies the style background color of the underlying div component, while adding the top and bottom brushes, drawing Click anywhere you want ... text information, by moving the data can be found that topPainter drawn content is rendered above the data, bottomPainter drawn content is rendered under the data.

view.style.background = '#FCFCFC';
graphView.addTopPainter(function (g){
    ht.Default.drawText(g, 'click anywhere you want ..', '24px Arial', 'lightgray', 50, 100, 0, 0, 'left');
});      
graphView.addBottomPainter(function (g){
    ht.Default.drawText(g, 'click anywhere you want ..', '24px Arial', 'lightblue', 200, 180, 0, 0, 'left');
}); 

Functions of many components of HT are also animated, such as setTranslate(x, y, anim), zoomIn(anim), rotate(leftRight, upDown, anim), and so on, with anim parameter options, there are two types of arguments that can be passed in:

Except through ht.Default.startAnim to invoke startup animation, DataModel also has functions to start scheduling tasks, which can be extended to flow, flicker, size changes and other animation effects, as detailed in the Dispatch Manual, for more robust descriptive animation controls refer to Animation plug-in.

Property Component

Refer to Property Component Manual and PropertyPane plug-in

Listview Component

Refer to ListView Component Manual

TreeView Component

Refer to TreeView Component Manual

TableView Component

Refer to TableView Component Manual

TreeTableView Component

Refer to TreeTableView Component Manual

Toolbar Component

Refer to Toolbar Manual

SplitView Component

Refer to SplitView Component Manual

BorderPane Component

Refer to BorderPane Component Manual

AccordionView Component

Refer to AccordionView Component Manual

TabView Component

Refer to TabView Component Manual

GraphView Component

The topological graphics component ht.graph.GraphView(hereinafter referred to as GraphView) is the most abundant component in the HT framework 2D and its related class libraries are under the ht.graph package. GraphView has basic graphics rendering and editing functions, topology node connection and automatic layout function, power and telecommunications industry predefined objects, with animation rendering and other special effects, so its application is very wide, can be used as a monitoring field of drawing tools and Man-machine interface, can be used as a general graphical editing tools, can be extended into business applications such as workflows and organization charts.

Zoom In

Changing the zoom attribute value (default to 1) enables the GraphView zooming function to view the full picture or detail of the topological graphics component in an enlarged or reduced manner. The mouse wheel on the peace plate and the double finger pinch gesture can change the zoom value in default. Press SPACEBAR to reset zoom to default 1 (the operation also resets translateX and translateY to 0):

The following is the GraphView scaling correlation function in which the point parameter in the following function represents the center data for zooming, which is typically input the graphView.getLogicalPoint(event)'s return value, that is the center of the current mouse click, when this parameter is empty, it is zooming in the center of the currently visible rectangular area.

The adjustZoom function defaults to the following, for ht.Default configured maximum and minimum values are limited:

adjustZoom = function (value){
    if(value < ht.Default.zoomMin){
        return ht.Default.zoomMin;
    }
    if(value > ht.Default.zoomMax){
        return ht.Default.zoomMax;
    }
    return value;                
}; 

Interaction

GraphView has some internal interactor for basic selection, single double click, zoom, panning, and editing in default, here are the internal interactors:

These interactions can be combined with GraphView#setinteractors(list), and the user can also extend their own interactivity based on interactor, the following code is the implementation of Graphview#setEditable(false/true), the GraphView constructor called setEditable(false), so by default only the basic operation function does not have the editing function, and the edit function can be achieved by calling setEditable(true).

setEditable: function (editable) {
    var self = this;
    if (editable) {
        self.setinteractors([
            new ScrollBarinteractor(self),
            new Selectinteractor(self),
            new Editinteractor(self),
            new Moveinteractor(self),
              new Defaultinteractor(self),
            new Touchinteractor(self)
        ]);
    } else {
        self.setinteractors([
            new ScrollBarinteractor(self),
            new Selectinteractor(self),
            new Moveinteractor(self),
            new Defaultinteractor(self),
            new Touchinteractor(self, {editable: false})
        ]);
    }
},

Touchinteractor the second parameter of the class can be passed into the JSON object control function to open and close, the default is open

The internal interactor sends events in the interactive process, which can be monitored by GraphView#addinteractorListener, referred to briefly as mi

graphView.addinteractorListener(function (e) {
    if(e.kind === 'clickData'){
        console.log(e.data + 'clicked');
    }
    else if(e.kind === 'doubleClickData'){
        console.log(e.data + 'double clicked');
    }            
    else if(e.kind === 'clickBackground'){
        console.log('clicked background');
    }  
    else if(e.kind === 'doubleClickBackground'){
        console.log('double clicked');
    }     
    else if(e.kind === 'beginRectSelect'){
        console.log('start to select the rect');
    }              
    else if(e.kind === 'betweenRectSelect'){
        console.log('selecting the rect');
    }             
    else if(e.kind === 'endRectSelect'){
        console.log('stop to select the rect');
    }           
    else if(e.kind === 'beginMove'){
        console.log('start to move the data');
    }              
    else if(e.kind === 'betweenMove'){
        console.log('moving the data');
    }             
    else if(e.kind === 'endMove'){
        console.log('stop to move the data');
    } 
    else if(e.kind === 'beginPan'){
        console.log('start to pinch pan');
    }              
    else if(e.kind === 'betweenPan'){
        console.log('pinching pan');
    }             
    else if(e.kind === 'endPan'){
        console.log('stop to pinch pan');
    }     
    else if(e.kind === 'beginEditRect'){
        console.log('start to edit the data size and position');
    }              
    else if(e.kind === 'betweenEditRect'){
        console.log('editing the data size and position');
    }             
    else if(e.kind === 'endEditRect'){
        console.log('stop to edit the data size and position');
    } 
    else if(e.kind === 'beginEditPoint'){
        console.log('start to edit the points of multi-sided Shape or multi-point Edge');
    }              
    else if(e.kind === 'betweenEditPoint'){
        console.log('editing the points of multi-sided Shape or multi-point Edge');
    }             
    else if(e.kind === 'endEditPoint'){
        console.log('stop to edit the points of multi-sided Shape or multi-point Edge');
    } 
    else if(e.kind === 'beginEditRotation'){
        console.log('start to rotate the data');
    }              
    else if(e.kind === 'betweenEditRotation'){
        console.log('rotating the data');
    }             
    else if(e.kind === 'endEditRotation'){
        console.log('stop to rotate the data');
    }               
    else if(e.kind === 'moveLeft'){
        console.log('leftarrow move the data 1 pixel to the left');
    }       
    else if(e.kind === 'moveRight'){
        console.log('rightarrow move the data 1 pixel to the right ');
    } 
    else if(e.kind === 'moveUp'){
        console.log('uparrow move the data up 1 pixel');
    } 
    else if(e.kind === 'moveDown'){
        console.log('down-arrow move the data down 1 pixel');
    } 
    else if(e.kind === 'toggleNote'){
        console.log('toggle note to expand and merge');
    }             
    else if(e.kind === 'toggleNote2'){
        console.log('toggle note2 to expand and merge');
    }             
});

There is also a logical coordinate point (LogicalPoint) concept about interaction, the translated and scaled components have getLogicalPoint function in general, according to the interactive event to return the corresponding coordinate point information, simple understanding of logical coordinates point is same as user set model coordinates, and the actual display at the screen point of coordinates, need to be through zoom and translate conversion, in the GraphView to change the zoom and translate process, the data model of the data has not changed, that is, the logical coordinate value is unchanged, only the rendering effect of the view component changes, the logical coordinate information of all datas in DataModel, such as position, points, width and height, remains unchanged, so when customizing the interaction event processing, it is necessary to call the following interactive screen coordinates and logical coordinate conversion functions:

Graphview has a series of on* type callback functions that can be overloaded for subsequent processing or change the default implementation logic:

In addition to calling the GraphView encapsulated functions, users can also add native HTML component listener events, such as the Node chapter example, through graphView.getView().addEventListener to add listening to the bottom of the div, the following code has a few points to note:

In the aforementioned HT package of onDataClicked and on**Clicked events, are triggered in mousedown and touchstart, if needed to listen in mouseup and touchend after letting go of the event, you can listen to the HTML raw events application is more in the case of click on the data to open the dialog box, if in the HT package of the on*clicked event processing directly invoke pop-up dialog, such operations, will affect the HT subsequent interactive event processing , so interactive events affect the function of the interface, you can choose to listen in mouseup and touchend inside, in some cases even need to call ht.Default.callLater(function (){}) is handled in the following ways:

var eventType = ht.Default.isTouchable ? 'touchend' : 'mouseup';
graphView.getView().addEventListener(eventType, function (e){
    var data = graphView.getDataAt(e);
    if(data && ht.Default.isDoubleClick(e)){
        alert(data.getName() + ' is double clicked.');
    }
});

The following example customized to create Node, Edge and Shape interactors:

Filter

Filtering mechanism through the whole HT framework, and the use of filtering mechanism is particularly concentrated in GraphView, the rational use of these filters can flexibly control whether the data visible, movable, editable, etc.

isMovable: function (data) {
    if(data instanceof ht.Edge){
        return false;                
    }
    return this._movableFunc ? this._movableFunc(data) : true;
},

The above code is a simplified version of the GraphView.isMovable(data) function, which is called by the moveinteractor class to determine whether the data movable, this._movableFunc property is set by GraphView.setMovableFunc(func), by the code is known Edge is not allowed to drag by default, and then determine whether the movableFunc function property is set, if the logic is set then whether the function movable is determined by this, finally returns true.

So there are two ways to customize whether movable logic:

The following list is a common filter function:

Many users who have just started using HT are puzzled by the filter set on the view component rather than the data model. If you control the filter on the model, all components that share the same model can only have the same filtering logic, and the HT design idea enables different components to have different filtering logic.

In addition to setting filters on the view components, the GraphView internal filtering mechanism also refers to the following style attributes, which can change the control effect of the following style on a single data:

Similarly, there are similar control parameters for Graph3dView:

Style

HT Data can be classified into three types of properties:

The following code is the implementation of the style related function in HT, the default data _stylemap is NULL, query the value will refer to ht.Style global default value:

getStyleMap: function (){
    return this._styleMap;
},
getStyle: function (name, checkDefault) {
    if (checkDefault === undefined) {
        checkDefault = true;
    }
    var value = this._styleMap ? this._styleMap[name] : undefined;
    if (value === undefined && checkDefault) {
        return ht.Style[name];
    } else {
        return value;
    }
},
setStyle: function (name, newValue) {        
    if (!this._styleMap) {
        this._styleMap = {};
    }
    var oldValue = this._styleMap[name];
    if(newValue === undefined){
        delete this._styleMap[name];               
    }else{
        this._styleMap[name] = newValue;               
    }        
    if (this.fp('s:' + name, oldValue, newValue)) {
        this.onStyleChanged(name, oldValue, newValue);
    }
},

The following is the description of partial style attribute, and more attributes are described in subsequent chapters:

Select

The GraphView data is selected by default to display a selected border, and the effect of the selected border can be controlled by the select.* related properties on the style.

Border

The boder style draws a border effect at the edge of the data, which is used for alarms or prompts, and can be customized by overloading the GraphView.getBorderColor(data).

Shape

The Node data on GraphView, in addition to being displayed as a picture set by image property, can also be set to vector for various polygonal types built into the HT frame. To be displayed in vector format can be achieved by setting the style property of the Node type data, the related style property name is described as follows:

Position

Refer to Position Manual

Label

GraphView datas can add text descriptions, such as the data setName(' Hello ht '), the Hello HT text appears below the data. The chapter position Example text message is not set by setName, but by setStyle(' label ', ' Hello HT '); GraphView.getLabel function decides the final display of label:

getLabel: function (data) {
    var label = data.getStyle('label');
    return label === undefined ? data.getName() : label;        
},

Through the above code, style on the label property priority is higher than name attribute, can overload GraphView.getLabel function to change the text acquisition logic.

*View.getLabel is designed to run through all of the HT components in a similar way to ListView, TreeView, TabView, etc., what is the different is that the default implementation logic for other components is to return the data.toLabel() value, which is the default implementation of Data#toLabel().

toLabel: function (){
    return this._displayName || this._name;
}  

The above code shows that the displayName attribute has a higher precedence than name and style attributes are generally used only GraphView components, and other components do not consider label attributes on style, when tree and When Graphview share the same DataModel data model, you need to display different text on Tree and GraphView, in which case you can set the label attribute on style, or set the displayName property can achieve a different effect, or directly overload the component's getLabel function custom logic.

In addition to provide the label.* properties, HT also provide the label2.* property to meet the need for an data to display double label, the label2 and label attribute meaning is one-to-one correspondence:

note

note generally as the annotation of the data, there are hints and warnings, in the form of bubbles, can also be reduced to merge into a small callout. The note parameter controlled by the style of the note.* related property, and Label, in order to meet the requirements of an data double annotation, provides a note2.* second callout parameter:

icon

icon and note are similar, show around the data, there are hints and warnings of the role, the different is the notes shows the text, and icon shows the picture or Vector.

Above is ht.Data provides the operation icon function, the two methods actually modify the style of the icons attribute, the user can also set and get icons through setStyle('icons', icons) and getStyle('icons').

addStyleIcon method the second parameter icons is a JSON format object whose properties are as follows:

edge.addStyleIcon("flags", {
    position: 17,
    direction: 'east',
    offsetX: -26,
    gap: 10,
    names: ['China', 'Spain', 'USA']
});

edge.addStyleIcon("arrow1", {
    position: 2,
    width: 50,
    height: 25,
    keepOrien: true,
    names: ['arrow']
});

edge.addStyleIcon("arrow2", {
    position: 4,
    width: 50,
    height: 25,
    positionFixed: true,
    names: ['arrow']
}); 

In the above example, the Edge object is set by the addStyleIcon way, with a row of three flag icons of [' China ', ' Spain ', ' USA '], and two arrow vector icons, which can be replaced by the following code:

edge.setStyle('icons', {
    flags: {
        position: 17,
        direction: 'east',
        offsetX: -26,
        gap: 10,
        names: ['China', 'Spain', 'USA']
    },
    arrow1: {
        position: 2,
        width: 50,
        height: 25,
        keepOrien: true,
        names: ['arrow']
    },
    arrow2: {
        position: 4,
        width: 50,
        height: 25,
        positionFixed: true,
        names: ['arrow']
    }
});

In the example node1 node1.setStyle("icons", ...) registers a three-vector orb, by overloading graphView.onDataClicked and combining graphView.getIconInfoAt functions to get clicked on the specific icon icons to change the line arrow color

graphView.onDataClicked = function (data, e) {
    if(data === node1){
        var info = this.getIconInfoAt(e, data);
        if(info){
            edge.a('arrow.color', info.name.comps[0].background);
            node1.a('select.index', info.index);
        } 
    }                                       
};

group

Group type datas can be set to the following styles:

edge

For the line of the edge.type is points, while edge.center is false, and the edge.offset is 0, the begin of the line and the end of the line will cut by the relative node's rectangle boundary.

Recommand

Books

Object-Oriented JavaScript
The development of HTML5 applications, especially enterprise applications, JavaScript almost occupies the bulk of the code, so the need to master the JS syntax, internal classes and functions, and other object-oriented language different class inheritance patterns, as well as DOM basic operations, this book is a good choice for this knowledge.

Pro JavaScript Design Patterns
Design patterns have been widely used in a variety of software development, but many familiar design patterns, with the implementation of the JS language and Java and C# and other traditional object language implementation of the way there are many differences, resulting in many beginners often don't know how to do, or the design of the model is not the best JS practice, the book on the interface, single class, inheritance, factories and other modes of the JS language can be selected to achieve the way.

CSS3: The Missing Manual
HT products provide a wealth of enterprise application components, to make a routine case only with JS is enough, but the more beautiful interface effect can not be separated from the CSS technology to grasp and use of HT product depth customization expansion is often inseparable from the CSS technology. The book's 12th edition on the rave, the third version of the HTML5 has been revised, deleted previously for the old version of the IE browser chapters, added to the CSS3 new features of the chapter space, is a classic reading that worth front-end programmers to read.

Responsive Web Design with HTML5 and CSS3
Responsive Web Design(RWD) is a new area of front-end technology, the first originator of the concept of "responsive Web designs" is Responsive Web Designer responsive-web-design). A good page not only in the PC browser, but also need to consider the user's use of mobile phones or tablets to browse the rendering effect, so programmers and designers need to consider the different screen size and other complex situations, to maintain the desktop mouse and mobile device gesture operation has a better user experience, this book has played a role, can let you understand the current common RWD design skills, began to focus on this aspect of technology and use.

Describe

We recommend reading books to system learning a technology, but it takes months or even years to write an excellent classic book, and it is highly recommended that three weekly subscriptions for front-end technology be developed for the latest technical information in order to keep abreast of the front-line programmers, and just look at the three weekly emails, and will not miss the interesting events that are taking place on earth's front-end development field:


Welcome to contact us service@hightopo.com