Update telepath JS code for new transport format

pull/6931/head
Matt Westcott 2021-01-12 16:14:45 +00:00
rodzic d4dc02ad0f
commit d18d23190d
2 zmienionych plików z 52 dodań i 15 usunięć

Wyświetl plik

@ -63,7 +63,7 @@ class FieldBlock {
class FieldBlockDefinition {
constructor(name, widget, meta) {
this.name = name;
this.widget = window.telepath.unpack(widget);
this.widget = widget;
this.meta = meta;
}
@ -135,7 +135,7 @@ class StructBlock {
class StructBlockDefinition {
constructor(name, childBlockDefs, meta) {
this.name = name;
this.childBlockDefs = childBlockDefs.map((child) => window.telepath.unpack(child));
this.childBlockDefs = childBlockDefs;
this.meta = meta;
}
@ -247,7 +247,7 @@ class ListBlock {
class ListBlockDefinition {
constructor(name, childBlockDef, meta) {
this.name = name;
this.childBlockDef = window.telepath.unpack(childBlockDef);
this.childBlockDef = childBlockDef;
this.meta = meta;
}
@ -365,7 +365,7 @@ class StreamBlock {
class StreamBlockDefinition {
constructor(name, childBlockDefs, meta) {
this.name = name;
this.childBlockDefs = childBlockDefs.map((child) => window.telepath.unpack(child));
this.childBlockDefs = childBlockDefs;
this.childBlockDefsByName = {};
for (let i = 0; i < this.childBlockDefs.length; i++) {
const blockDef = this.childBlockDefs[i];

Wyświetl plik

@ -1,13 +1,50 @@
/* eslint-disable indent */
/* eslint-disable dot-notation */
window.telepath = {
constructors: {},
register(name, constructor) {
this.constructors[name] = constructor;
},
unpack(objData) {
var [constructorName, ...args] = objData;
var constructor = this.constructors[constructorName];
return new constructor(...args);
class Telepath {
constructor() {
this.constructors = {};
}
register(name, constructor) {
this.constructors[name] = constructor;
}
unpackAsDict(objData) {
const result = [];
for (const [key, val] of Object.entries(objData)) {
result[key] = this.unpack(val);
}
};
return result;
}
unpack(objData) {
if (objData === null || typeof(objData) !== 'object') {
/* primitive value - return unchanged */
return objData;
}
if (Array.isArray(objData)) {
/* unpack recursively */
return objData.map(item => this.unpack(item));
}
/* objData is an object / dict - look for special key names _type and _dict */
if ('_type' in objData) {
/* handle as a custom type */
const constructorId = objData['_type'];
const constructor = this.constructors[constructorId];
/* unpack arguments recursively */
const args = objData['_args'].map(arg => this.unpack(arg));
return new constructor(...args);
}
if ('_dict' in objData) {
return this.unpackAsDict(objData['_dict']);
}
/* no special key names found, so unpack objData as a plain dict */
return this.unpackAsDict(objData);
}
}
window.telepath = new Telepath();