本地logicflow依赖包

This commit is contained in:
Jam committed 2022-11-28 14:31:03 +08:00
1 parent 8ff82208ad
commit 30f225df00
290 files changed
+18624 -16276

No files matched your search

@@ -0,0 +1 @@
export declare function getBpmnId(): string;
@@ -0,0 +1,5 @@
import Ids from 'ids';
var ids = new Ids([32, 32, 1]);
export function getBpmnId() {
return ids.next();
}
@@ -0,0 +1,45 @@
declare const BpmnAdapter: {
pluginName: string;
install(lf: any): void;
shapeConfigMap: Map<any, any>;
setCustomShape(key: any, val: any): void;
adapterOut(data: any): {
'bpmn:definitions': {
'-id': string;
'-xmlns:xsi': string;
'-xmlns:bpmn': string;
'-xmlns:bpmndi': string;
'-xmlns:dc': string;
'-xmlns:di': string;
'-targetNamespace': string;
'-exporter': string;
'-exporterVersion': string;
'bpmn:process': {
'-id': string;
'-isExecutable': string;
};
'bpmndi:BPMNDiagram': {
'-id': string;
'bpmndi:BPMNPlane': {
'-id': string;
'-bpmnElement': string;
};
};
};
};
adapterIn(bpmnData: any): {
nodes: any[];
edges: any[];
};
};
declare const BpmnXmlAdapter: {
pluginName: string;
install(lf: any): void;
adapterXmlIn(bpmnData: any): {
nodes: any[];
edges: any[];
};
adapterXmlOut(data: any): string;
};
export { BpmnAdapter, BpmnXmlAdapter, };
export default BpmnAdapter;
@@ -0,0 +1,485 @@
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
import { getBpmnId } from './bpmnIds';
import { lfJson2Xml } from './json2xml';
import { lfXml2Json } from './xml2json';
import { ExclusiveGatewayConfig, StartEventConfig, EndEventConfig, ServiceTaskConfig, UserTaskConfig, } from '../bpmn/constant';
var BpmnElements;
(function (BpmnElements) {
BpmnElements["START"] = "bpmn:startEvent";
BpmnElements["END"] = "bpmn:endEvent";
BpmnElements["GATEWAY"] = "bpmn:exclusiveGateway";
BpmnElements["USER"] = "bpmn:userTask";
BpmnElements["SYSTEM"] = "bpmn:serviceTask";
BpmnElements["FLOW"] = "bpmn:sequenceFlow";
})(BpmnElements || (BpmnElements = {}));
var defaultAttrs = ['-name', '-id', 'bpmn:incoming', 'bpmn:outgoing', '-sourceRef', '-targetRef'];
/**
* 将普通json转换为xmljson
* xmljson中properity会以“-”开头
* 如果没有“-”表示为子节点
*/
function toXmlJson(json) {
var xmlJson = {};
Object.entries(json).forEach(function (_a) {
var _b = __read(_a, 2), key = _b[0], value = _b[1];
if (typeof value !== 'object') {
if (key.indexOf('-') === 0) { // 如果本来就是“-”开头的了,那就不处理了。
xmlJson[key] = value;
}
else {
xmlJson["-" + key] = value;
}
}
else {
xmlJson[key] = toXmlJson(value);
}
});
return xmlJson;
}
/**
* 将xmlJson转换为普通的json,在内部使用。
*/
function toNormalJson(xmlJson) {
var json = {};
Object.entries(xmlJson).forEach(function (_a) {
var _b = __read(_a, 2), key = _b[0], value = _b[1];
if (typeof value === 'string') {
if (key.indexOf('-') === 0) { // 如果本来就是“-”开头的了,那就不处理了。
json[key.substr(1)] = value;
}
else {
json[key] = value;
}
}
else if (typeof value === 'object') {
json[key] = toNormalJson(value);
}
else {
json[key] = value;
}
});
return json;
}
/**
* 设置bpmn process信息
* 目标格式请参考examples/bpmn.json
* bpmn因为是默认基于xml格式的,其特点与json存在差异。
* 1) 如果是xml的属性,json中属性用'-'开头
* 2)如果只有一个子元素,json中表示为正常属性
* 3)如果是多个子元素,json中使用数组存储
*/
function convertLf2ProcessData(bpmnProcessData, data) {
var nodeMap = new Map();
data.nodes.forEach(function (node) {
var _a;
var processNode = {
'-id': node.id,
};
if ((_a = node.text) === null || _a === void 0 ? void 0 : _a.value) {
processNode['-name'] = node.text.value;
}
if (node.properties) {
var properties = toXmlJson(node.properties);
Object.assign(processNode, properties);
}
nodeMap.set(node.id, processNode);
if (!bpmnProcessData[node.type]) {
bpmnProcessData[node.type] = processNode; // 如果只有一个子元素,json中表示为正常属性
}
else if (Array.isArray(bpmnProcessData[node.type])) { // 如果是多个子元素,json中使用数组存储
bpmnProcessData[node.type].push(processNode);
}
else { // 如果是多个子元素,json中使用数组存储
bpmnProcessData[node.type] = [
bpmnProcessData[node.type],
processNode,
];
}
});
var sequenceFlow = data.edges.map(function (edge) {
var _a, _b;
var targetNode = nodeMap.get(edge.targetNodeId);
// @see https://github.com/didi/LogicFlow/issues/325
// 需要保证incomming在outgoing之前
if (!targetNode['bpmn:incoming']) {
targetNode['bpmn:incoming'] = edge.id;
}
else if (Array.isArray(targetNode['bpmn:incoming'])) {
targetNode['bpmn:incoming'].push(edge.id);
}
else {
targetNode['bpmn:incoming'] = [
targetNode['bpmn:incoming'],
edge.id,
];
}
var sourceNode = nodeMap.get(edge.sourceNodeId);
if (!sourceNode['bpmn:outgoing']) {
sourceNode['bpmn:outgoing'] = edge.id;
}
else if (Array.isArray(sourceNode['bpmn:outgoing'])) {
sourceNode['bpmn:outgoing'].push(edge.id);
}
else { // 字符串转数组
sourceNode['bpmn:outgoing'] = [
sourceNode['bpmn:outgoing'],
edge.id,
];
}
var edgeConfig = {
'-id': edge.id,
'-sourceRef': edge.sourceNodeId,
'-targetRef': edge.targetNodeId,
};
if ((_a = edge.text) === null || _a === void 0 ? void 0 : _a.value) {
edgeConfig['-name'] = (_b = edge.text) === null || _b === void 0 ? void 0 : _b.value;
}
if (edge.properties) {
var properties = toXmlJson(edge.properties);
Object.assign(edgeConfig, properties);
}
return edgeConfig;
});
bpmnProcessData[BpmnElements.FLOW] = sequenceFlow;
}
/**
* adapterOut 设置bpmn diagram信息
*/
function convertLf2DiagramData(bpmnDiagramData, data) {
bpmnDiagramData['bpmndi:BPMNEdge'] = data.edges.map(function (edge) {
var _a;
var edgeId = edge.id;
var pointsList = edge.pointsList.map(function (_a) {
var x = _a.x, y = _a.y;
return ({ '-x': x, '-y': y });
});
var diagramData = {
'-id': edgeId + "_di",
'-bpmnElement': edgeId,
'di:waypoint': pointsList,
};
if ((_a = edge.text) === null || _a === void 0 ? void 0 : _a.value) {
diagramData['bpmndi:BPMNLabel'] = {
'dc:Bounds': {
'-x': edge.text.x - (edge.text.value.length * 10) / 2,
'-y': edge.text.y - 7,
'-width': edge.text.value.length * 10,
'-height': 14,
},
};
}
return diagramData;
});
bpmnDiagramData['bpmndi:BPMNShape'] = data.nodes.map(function (node) {
var _a;
var nodeId = node.id;
var width = 100;
var height = 80;
var x = node.x, y = node.y;
// bpmn坐标是基于左上角,LogicFlow基于中心点,此处处理一下。
var shapeConfig = BpmnAdapter.shapeConfigMap.get(node.type);
if (shapeConfig) {
width = shapeConfig.width;
height = shapeConfig.height;
}
x -= width / 2;
y -= height / 2;
var diagramData = {
'-id': nodeId + "_di",
'-bpmnElement': nodeId,
'dc:Bounds': {
'-x': x,
'-y': y,
'-width': width,
'-height': height,
},
};
if ((_a = node.text) === null || _a === void 0 ? void 0 : _a.value) {
diagramData['bpmndi:BPMNLabel'] = {
'dc:Bounds': {
'-x': node.text.x - (node.text.value.length * 10) / 2,
'-y': node.text.y - 7,
'-width': node.text.value.length * 10,
'-height': 14,
},
};
}
return diagramData;
});
}
/**
* 将bpmn数据转换为LogicFlow内部能识别数据
*/
function convertBpmn2LfData(bpmnData) {
var nodes = [];
var edges = [];
var definitions = bpmnData['bpmn:definitions'];
if (definitions) {
var process_1 = definitions['bpmn:process'];
Object.keys(process_1).forEach(function (key) {
if (key.indexOf('bpmn:') === 0) {
var value = process_1[key];
if (key === BpmnElements.FLOW) {
var bpmnEdges = definitions['bpmndi:BPMNDiagram']['bpmndi:BPMNPlane']['bpmndi:BPMNEdge'];
edges = getLfEdges(value, bpmnEdges);
}
else {
var shapes = definitions['bpmndi:BPMNDiagram']['bpmndi:BPMNPlane']['bpmndi:BPMNShape'];
nodes = nodes.concat(getLfNodes(value, shapes, key));
}
}
});
}
return {
nodes: nodes,
edges: edges,
};
}
function getLfNodes(value, shapes, key) {
var nodes = [];
if (Array.isArray(value)) { // 数组
value.forEach(function (val) {
var shapeValue;
if (Array.isArray(shapes)) {
shapeValue = shapes.find(function (shape) { return shape['-bpmnElement'] === val['-id']; });
}
else {
shapeValue = shapes;
}
var node = getNodeConfig(shapeValue, key, val);
nodes.push(node);
});
}
else {
var shapeValue = void 0;
if (Array.isArray(shapes)) {
shapeValue = shapes.find(function (shape) { return shape['-bpmnElement'] === value['-id']; });
}
else {
shapeValue = shapes;
}
var node = getNodeConfig(shapeValue, key, value);
nodes.push(node);
}
return nodes;
}
function getNodeConfig(shapeValue, type, processValue) {
var x = Number(shapeValue['dc:Bounds']['-x']);
var y = Number(shapeValue['dc:Bounds']['-y']);
var name = processValue['-name'];
var shapeConfig = BpmnAdapter.shapeConfigMap.get(type);
if (shapeConfig) {
x += shapeConfig.width / 2;
y += shapeConfig.height / 2;
}
var properties;
// 判断是否存在额外的属性,将额外的属性放到properties中
Object.entries(processValue).forEach(function (_a) {
var _b = __read(_a, 2), key = _b[0], value = _b[1];
if (defaultAttrs.indexOf(key) === -1) {
if (!properties)
properties = {};
properties[key] = value;
}
});
if (properties) {
properties = toNormalJson(properties);
}
var text;
if (name) {
text = {
x: x,
y: y,
value: name,
};
// 自定义文本位置
if (shapeValue['bpmndi:BPMNLabel'] && shapeValue['bpmndi:BPMNLabel']['dc:Bounds']) {
var textBounds = shapeValue['bpmndi:BPMNLabel']['dc:Bounds'];
text.x = Number(textBounds['-x']) + Number(textBounds['-width']) / 2;
text.y = Number(textBounds['-y']) + Number(textBounds['-height']) / 2;
}
}
var nodeConfig = {
id: shapeValue['-bpmnElement'],
type: type,
x: x,
y: y,
properties: properties,
};
if (text) {
nodeConfig.text = text;
}
return nodeConfig;
}
function getLfEdges(value, bpmnEdges) {
var edges = [];
if (Array.isArray(value)) {
value.forEach(function (val) {
var edgeValue;
if (Array.isArray(bpmnEdges)) {
edgeValue = bpmnEdges.find(function (edge) { return edge['-bpmnElement'] === val['-id']; });
}
else {
edgeValue = bpmnEdges;
}
edges.push(getEdgeConfig(edgeValue, val));
});
}
else {
var edgeValue = void 0;
if (Array.isArray(bpmnEdges)) {
edgeValue = bpmnEdges.find(function (edge) { return edge['-bpmnElement'] === value['-id']; });
}
else {
edgeValue = bpmnEdges;
}
edges.push(getEdgeConfig(edgeValue, value));
}
return edges;
}
function getEdgeConfig(edgeValue, processValue) {
var text;
var textVal = processValue['-name'];
if (textVal) {
var textBounds = edgeValue['bpmndi:BPMNLabel']['dc:Bounds'];
// 如果边文本换行,则其偏移量应该是最长一行的位置
var textLength_1 = 0;
textVal.split('\n').forEach(function (textSpan) {
if (textLength_1 < textSpan.length) {
textLength_1 = textSpan.length;
}
});
text = {
value: textVal,
x: Number(textBounds['-x']) + (textLength_1 * 10) / 2,
y: Number(textBounds['-y']) + 7,
};
}
var properties;
// 判断是否存在额外的属性,将额外的属性放到properties中
Object.entries(processValue).forEach(function (_a) {
var _b = __read(_a, 2), key = _b[0], value = _b[1];
if (defaultAttrs.indexOf(key) === -1) {
if (!properties)
properties = {};
properties[key] = value;
}
});
if (properties) {
properties = toNormalJson(properties);
}
var edge = {
id: processValue['-id'],
type: BpmnElements.FLOW,
pointsList: edgeValue['di:waypoint'].map(function (point) { return ({
x: Number(point['-x']),
y: Number(point['-y']),
}); }),
sourceNodeId: processValue['-sourceRef'],
targetNodeId: processValue['-targetRef'],
properties: properties,
};
if (text) {
edge.text = text;
}
return edge;
}
var BpmnAdapter = {
pluginName: 'bpmn-adapter',
install: function (lf) {
lf.adapterIn = this.adapterIn;
lf.adapterOut = this.adapterOut;
},
shapeConfigMap: new Map(),
setCustomShape: function (key, val) {
this.shapeConfigMap.set(key, val);
},
adapterOut: function (data) {
var bpmnProcessData = {
'-id': "Process_" + getBpmnId(),
'-isExecutable': 'false',
};
convertLf2ProcessData(bpmnProcessData, data);
var bpmnDiagramData = {
'-id': 'BPMNPlane_1',
'-bpmnElement': bpmnProcessData['-id'],
};
convertLf2DiagramData(bpmnDiagramData, data);
var bpmnData = {
'bpmn:definitions': {
'-id': "Definitions_" + getBpmnId(),
'-xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'-xmlns:bpmn': 'http://www.omg.org/spec/BPMN/20100524/MODEL',
'-xmlns:bpmndi': 'http://www.omg.org/spec/BPMN/20100524/DI',
'-xmlns:dc': 'http://www.omg.org/spec/DD/20100524/DC',
'-xmlns:di': 'http://www.omg.org/spec/DD/20100524/DI',
'-targetNamespace': 'http://bpmn.io/schema/bpmn',
'-exporter': 'bpmn-js (https://demo.bpmn.io)',
'-exporterVersion': '7.3.0',
'bpmn:process': bpmnProcessData,
'bpmndi:BPMNDiagram': {
'-id': 'BPMNDiagram_1',
'bpmndi:BPMNPlane': bpmnDiagramData,
},
},
};
return bpmnData;
},
adapterIn: function (bpmnData) {
if (bpmnData) {
return convertBpmn2LfData(bpmnData);
}
},
};
BpmnAdapter.shapeConfigMap.set(BpmnElements.START, {
width: StartEventConfig.width,
height: StartEventConfig.height,
});
BpmnAdapter.shapeConfigMap.set(BpmnElements.END, {
width: EndEventConfig.width,
height: EndEventConfig.height,
});
BpmnAdapter.shapeConfigMap.set(BpmnElements.GATEWAY, {
width: ExclusiveGatewayConfig.width,
height: ExclusiveGatewayConfig.height,
});
BpmnAdapter.shapeConfigMap.set(BpmnElements.SYSTEM, {
width: ServiceTaskConfig.width,
height: ServiceTaskConfig.height,
});
BpmnAdapter.shapeConfigMap.set(BpmnElements.USER, {
width: UserTaskConfig.width,
height: UserTaskConfig.height,
});
var BpmnXmlAdapter = {
pluginName: 'bpmnXmlAdapter',
install: function (lf) {
lf.adapterIn = this.adapterXmlIn;
lf.adapterOut = this.adapterXmlOut;
},
adapterXmlIn: function (bpmnData) {
var json = lfXml2Json(bpmnData);
return BpmnAdapter.adapterIn(json);
},
adapterXmlOut: function (data) {
var outData = BpmnAdapter.adapterOut(data);
return lfJson2Xml(outData);
},
};
export { BpmnAdapter, BpmnXmlAdapter, };
export default BpmnAdapter;
@@ -0,0 +1,2 @@
declare function lfJson2Xml(o: any): string;
export { lfJson2Xml };
@@ -0,0 +1,59 @@
/**
* This work is licensed under Creative Commons GNU LGPL License.
* License:
* Version: 0.9
* Author: Stefan Goessner/2006
* Web: http://goessner.net/
*/
function addIndSpace(ind, deep) {
for (var i = 0; i < deep; i++) {
ind += ' ';
}
return ind;
}
function toXml(v, name, ind, deep) {
var xml = "";
if (v instanceof Array) {
for (var i = 0, n = v.length; i < n; i++) {
xml += addIndSpace(ind, deep) + toXml(v[i], name, ind, deep + 1);
}
}
else if (typeof (v) == "object") {
var hasChild = false;
xml += addIndSpace(ind, deep) + "<" + name;
for (var m in v) {
if (m.charAt(0) == "-")
xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
else
hasChild = true;
}
xml += hasChild ? ">" : " />";
if (hasChild) {
for (var m in v) {
if (m == "#text")
xml += v[m];
else if (m == "#cdata")
xml += "<![CDATA[" + v[m] + "]]>";
else if (m.charAt(0) != "-")
xml += toXml(v[m], m, ind, deep + 1);
}
xml += addIndSpace(ind, deep) + "</" + name + ">";
}
else {
// xml += addIndSpace(ind, deep);
}
}
else {
xml += addIndSpace(ind, deep) + "<" + name + ">" + v.toString() + "</" + name + ">";
}
return xml;
}
;
function lfJson2Xml(o) {
var xmlStr = "";
for (var m in o) {
xmlStr += toXml(o[m], m, "\t\n", 0);
}
return xmlStr;
}
export { lfJson2Xml };
@@ -0,0 +1,2 @@
declare const lfXml2Json: (xmlData: any) => any;
export { lfXml2Json, };
@@ -0,0 +1,526 @@
// @ts-nocheck
// ========================================================================
// XML.ObjTree -- XML source code from/to JavaScript object like E4X
// ========================================================================
var XML = function () { };
// constructor
XML.ObjTree = function () {
return this;
};
// class variables
XML.ObjTree.VERSION = "0.23";
// object prototype
XML.ObjTree.prototype.xmlDecl = '<?xml version="1.0" encoding="UTF-8" ?>\n';
XML.ObjTree.prototype.attr_prefix = '-';
// method: parseXML( xmlsource )
XML.ObjTree.prototype.parseXML = function (xml) {
var root;
if (window.DOMParser) {
var xmldom = new DOMParser();
// xmldom.async = false; // DOMParser is always sync-mode
var dom = xmldom.parseFromString(xml, "application/xml");
if (!dom)
return;
root = dom.documentElement;
}
else if (window.ActiveXObject) {
xmldom = new ActiveXObject('Microsoft.XMLDOM');
xmldom.async = false;
xmldom.loadXML(xml);
root = xmldom.documentElement;
}
if (!root)
return;
return this.parseDOM(root);
};
// method: parseHTTP( url, options, callback )
XML.ObjTree.prototype.parseHTTP = function (url, options, callback) {
var myopt = {};
for (var key in options) {
myopt[key] = options[key]; // copy object
}
if (!myopt.method) {
if (typeof (myopt.postBody) == "undefined" &&
typeof (myopt.postbody) == "undefined" &&
typeof (myopt.parameters) == "undefined") {
myopt.method = "get";
}
else {
myopt.method = "post";
}
}
if (callback) {
myopt.asynchronous = true; // async-mode
var __this = this;
var __func = callback;
var __save = myopt.onComplete;
myopt.onComplete = function (trans) {
var tree;
if (trans && trans.responseXML && trans.responseXML.documentElement) {
tree = __this.parseDOM(trans.responseXML.documentElement);
}
__func(tree, trans);
if (__save)
__save(trans);
};
}
else {
myopt.asynchronous = false; // sync-mode
}
var trans;
if (typeof (HTTP) != "undefined" && HTTP.Request) {
myopt.uri = url;
var req = new HTTP.Request(myopt); // JSAN
if (req)
trans = req.transport;
}
else if (typeof (Ajax) != "undefined" && Ajax.Request) {
var req = new Ajax.Request(url, myopt); // ptorotype.js
if (req)
trans = req.transport;
}
if (callback)
return trans;
if (trans && trans.responseXML && trans.responseXML.documentElement) {
return this.parseDOM(trans.responseXML.documentElement);
}
};
// method: parseDOM( documentroot )
XML.ObjTree.prototype.parseDOM = function (root) {
if (!root)
return;
this.__force_array = {};
if (this.force_array) {
for (var i = 0; i < this.force_array.length; i++) {
this.__force_array[this.force_array[i]] = 1;
}
}
var json = this.parseElement(root); // parse root node
if (this.__force_array[root.nodeName]) {
json = [json];
}
if (root.nodeType != 11) { // DOCUMENT_FRAGMENT_NODE
var tmp = {};
tmp[root.nodeName] = json; // root nodeName
json = tmp;
}
return json;
};
// method: parseElement( element )
XML.ObjTree.prototype.parseElement = function (elem) {
// COMMENT_NODE
if (elem.nodeType == 7) {
return;
}
// TEXT_NODE CDATA_SECTION_NODE
if (elem.nodeType == 3 || elem.nodeType == 4) {
var bool = elem.nodeValue.match(/[^\x00-\x20]/);
if (bool == null)
return; // ignore white spaces
return elem.nodeValue;
}
var retval;
var cnt = {};
// parse attributes
if (elem.attributes && elem.attributes.length) {
retval = {};
for (var i = 0; i < elem.attributes.length; i++) {
var key = elem.attributes[i].nodeName;
if (typeof (key) != "string")
continue;
var val = elem.attributes[i].nodeValue;
if (!val)
continue;
key = this.attr_prefix + key;
if (typeof (cnt[key]) == "undefined")
cnt[key] = 0;
cnt[key]++;
this.addNode(retval, key, cnt[key], val);
}
}
// parse child nodes (recursive)
if (elem.childNodes && elem.childNodes.length) {
var textonly = true;
if (retval)
textonly = false; // some attributes exists
for (var i = 0; i < elem.childNodes.length && textonly; i++) {
var ntype = elem.childNodes[i].nodeType;
if (ntype == 3 || ntype == 4)
continue;
textonly = false;
}
if (textonly) {
if (!retval)
retval = "";
for (var i = 0; i < elem.childNodes.length; i++) {
retval += elem.childNodes[i].nodeValue;
}
}
else {
if (!retval)
retval = {};
for (var i = 0; i < elem.childNodes.length; i++) {
var key = elem.childNodes[i].nodeName;
if (typeof (key) != "string")
continue;
var val = this.parseElement(elem.childNodes[i]);
if (!val)
continue;
if (typeof (cnt[key]) == "undefined")
cnt[key] = 0;
cnt[key]++;
this.addNode(retval, key, cnt[key], val);
}
}
}
return retval;
};
// method: addNode( hash, key, count, value )
XML.ObjTree.prototype.addNode = function (hash, key, cnts, val) {
if (this.__force_array[key]) {
if (cnts == 1)
hash[key] = [];
hash[key][hash[key].length] = val; // push
}
else if (cnts == 1) { // 1st sibling
hash[key] = val;
}
else if (cnts == 2) { // 2nd sibling
hash[key] = [hash[key], val];
}
else { // 3rd sibling and more
hash[key][hash[key].length] = val;
}
};
// method: writeXML( tree )
XML.ObjTree.prototype.writeXML = function (tree) {
var xml = this.hash_to_xml(null, tree);
return this.xmlDecl + xml;
};
// method: hash_to_xml( tagName, tree )
XML.ObjTree.prototype.hash_to_xml = function (name, tree) {
var elem = [];
var attr = [];
for (var key in tree) {
if (!tree.hasOwnProperty(key))
continue;
var val = tree[key];
if (key.charAt(0) != this.attr_prefix) {
if (typeof (val) == "undefined" || val == null) {
elem[elem.length] = "<" + key + " />";
}
else if (typeof (val) == "object" && val.constructor == Array) {
elem[elem.length] = this.array_to_xml(key, val);
}
else if (typeof (val) == "object") {
elem[elem.length] = this.hash_to_xml(key, val);
}
else {
elem[elem.length] = this.scalar_to_xml(key, val);
}
}
else {
attr[attr.length] = " " + (key.substring(1)) + '="' + (this.xml_escape(val)) + '"';
}
}
var jattr = attr.join("");
var jelem = elem.join("");
if (typeof (name) == "undefined" || name == null) {
// no tag
}
else if (elem.length > 0) {
if (jelem.match(/\n/)) {
jelem = "<" + name + jattr + ">\n" + jelem + "</" + name + ">\n";
}
else {
jelem = "<" + name + jattr + ">" + jelem + "</" + name + ">\n";
}
}
else {
jelem = "<" + name + jattr + " />\n";
}
return jelem;
};
// method: array_to_xml( tagName, array )
XML.ObjTree.prototype.array_to_xml = function (name, array) {
var out = [];
for (var i = 0; i < array.length; i++) {
var val = array[i];
if (typeof (val) == "undefined" || val == null) {
out[out.length] = "<" + name + " />";
}
else if (typeof (val) == "object" && val.constructor == Array) {
out[out.length] = this.array_to_xml(name, val);
}
else if (typeof (val) == "object") {
out[out.length] = this.hash_to_xml(name, val);
}
else {
out[out.length] = this.scalar_to_xml(name, val);
}
}
return out.join("");
};
// method: scalar_to_xml( tagName, text )
XML.ObjTree.prototype.scalar_to_xml = function (name, text) {
if (name == "#text") {
return this.xml_escape(text);
}
else {
return "<" + name + ">" + this.xml_escape(text) + "</" + name + ">\n";
}
};
// method: xml_escape( text )
XML.ObjTree.prototype.xml_escape = function (text) {
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
/*
// ========================================================================
=head1 NAME
XML.ObjTree -- XML source code from/to JavaScript object like E4X
=head1 SYNOPSIS
var xotree = new XML.ObjTree();
var tree1 = {
root: {
node: "Hello, World!"
}
};
var xml1 = xotree.writeXML( tree1 ); // object tree to XML source
alert( "xml1: "+xml1 );
var xml2 = '<?xml version="1.0"?><response><error>0</error></response>';
var tree2 = xotree.parseXML( xml2 ); // XML source to object tree
alert( "error: "+tree2.response.error );
=head1 DESCRIPTION
XML.ObjTree class is a parser/generater between XML source code
and JavaScript object like E4X, ECMAScript for XML.
This is a JavaScript version of the XML::TreePP module for Perl.
This also works as a wrapper for XMLHTTPRequest and successor to JKL.ParseXML class
when this is used with prototype.js or JSAN's HTTP.Request class.
=head2 JavaScript object tree format
A sample XML source:
<?xml version="1.0" encoding="UTF-8"?>
<family name="Kawasaki">
<father>Yasuhisa</father>
<mother>Chizuko</mother>
<children>
<girl>Shiori</girl>
<boy>Yusuke</boy>
<boy>Kairi</boy>
</children>
</family>
Its JavaScript object tree like JSON/E4X:
{
'family': {
'-name': 'Kawasaki',
'father': 'Yasuhisa',
'mother': 'Chizuko',
'children': {
'girl': 'Shiori'
'boy': [
'Yusuke',
'Kairi'
]
}
}
};
Each elements are parsed into objects:
tree.family.father; # the father's given name.
Prefix '-' is inserted before every attributes' name.
tree.family["-name"]; # this family's family name
A array is used because this family has two boys.
tree.family.children.boy[0]; # first boy's name
tree.family.children.boy[1]; # second boy's name
tree.family.children.girl; # (girl has no other sisiters)
=head1 METHODS
=head2 xotree = new XML.ObjTree()
This constructor method returns a new XML.ObjTree object.
=head2 xotree.force_array = [ "rdf:li", "item", "-xmlns" ];
This property allows you to specify a list of element names
which should always be forced into an array representation.
The default value is null, it means that context of the elements
will determine to make array or to keep it scalar.
=head2 xotree.attr_prefix = '@';
This property allows you to specify a prefix character which is
inserted before each attribute names.
Instead of default prefix '-', E4X-style prefix '@' is also available.
The default character is '-'.
Or set '@' to access attribute values like E4X, ECMAScript for XML.
The length of attr_prefix must be just one character and not be empty.
=head2 tree = xotree.parseXML( xmlsrc );
This method loads an XML document using the supplied string
and returns its JavaScript object converted.
=head2 tree = xotree.parseDOM( domnode );
This method parses a DOM tree (ex. responseXML.documentElement)
and returns its JavaScript object converted.
=head2 tree = xotree.parseHTTP( url, options );
This method loads a XML file from remote web server
and returns its JavaScript object converted.
XMLHTTPRequest's synchronous mode is always used.
This mode blocks the process until the response is completed.
First argument is a XML file's URL
which must exist in the same domain as parent HTML file's.
Cross-domain loading is not available for security reasons.
Second argument is options' object which can contains some parameters:
method, postBody, parameters, onLoading, etc.
This method requires JSAN's L<HTTP.Request> class or prototype.js's Ajax.Request class.
=head2 xotree.parseHTTP( url, options, callback );
If a callback function is set as third argument,
XMLHTTPRequest's asynchronous mode is used.
This mode calls a callback function with XML file's JavaScript object converted
after the response is completed.
=head2 xmlsrc = xotree.writeXML( tree );
This method parses a JavaScript object tree
and returns its XML source generated.
=head1 EXAMPLES
=head2 Text node and attributes
If a element has both of a text node and attributes
or both of a text node and other child nodes,
text node's value is moved to a special node named "#text".
var xotree = new XML.ObjTree();
var xmlsrc = '<span class="author">Kawasaki Yusuke</span>';
var tree = xotree.parseXML( xmlsrc );
var class = tree.span["-class"]; # attribute
var name = tree.span["#text"]; # text node
=head2 parseHTTP() method with HTTP-GET and sync-mode
HTTP/Request.js or prototype.js must be loaded before calling this method.
var xotree = new XML.ObjTree();
var url = "http://example.com/index.html";
var tree = xotree.parseHTTP( url );
xotree.attr_prefix = '@'; // E4X-style
alert( tree.html["@lang"] );
This code shows C<lang=""> attribute from a X-HTML source code.
=head2 parseHTTP() method with HTTP-POST and async-mode
Third argument is a callback function which is called on onComplete.
var xotree = new XML.ObjTree();
var url = "http://example.com/mt-tb.cgi";
var opts = {
postBody: "title=...&excerpt=...&url=...&blog_name=..."
};
var func = function ( tree ) {
alert( tree.response.error );
};
xotree.parseHTTP( url, opts, func );
This code send a trackback ping and shows its response code.
=head2 Simple RSS reader
This is a RSS reader which loads RDF file and displays all items.
var xotree = new XML.ObjTree();
xotree.force_array = [ "rdf:li", "item" ];
var url = "http://example.com/news-rdf.xml";
var func = function( tree ) {
var elem = document.getElementById("rss_here");
for( var i=0; i<tree["rdf:RDF"].item.length; i++ ) {
var divtag = document.createElement( "div" );
var atag = document.createElement( "a" );
atag.href = tree["rdf:RDF"].item[i].link;
var title = tree["rdf:RDF"].item[i].title;
var tnode = document.createTextNode( title );
atag.appendChild( tnode );
divtag.appendChild( atag );
elem.appendChild( divtag );
}
};
xotree.parseHTTP( url, {}, func );
=head2 XML-RPC using writeXML, prototype.js and parseDOM
If you wish to use prototype.js's Ajax.Request class by yourself:
var xotree = new XML.ObjTree();
var reqtree = {
methodCall: {
methodName: "weblogUpdates.ping",
params: {
param: [
{ value: "Kawa.net xp top page" }, // 1st param
{ value: "http://www.kawa.net/" } // 2nd param
]
}
}
};
var reqxml = xotree.writeXML( reqtree ); // JS-Object to XML code
var url = "http://example.com/xmlrpc";
var func = function( req ) {
var resdom = req.responseXML.documentElement;
xotree.force_array = [ "member" ];
var restree = xotree.parseDOM( resdom ); // XML-DOM to JS-Object
alert( restree.methodResponse.params.param.value.struct.member[0].value.string );
};
var opt = {
method: "post",
postBody: reqxml,
asynchronous: true,
onComplete: func
};
new Ajax.Request( url, opt );
=head1 AUTHOR
Yusuke Kawasaki http://www.kawa.net/
=head1 COPYRIGHT AND LICENSE
Copyright (c) 2005-2006 Yusuke Kawasaki. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the Artistic license. Or whatever license I choose,
which I will do instead of keeping this documentation like it is.
=cut
// ========================================================================
*/
var lfXml2Json = function (xmlData) {
return new XML.ObjTree().parseXML(xmlData);
};
export { lfXml2Json, };