From 5e7c493c0cb4200134b78ee32400910450e6ee7d Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 17 Jun 2017 01:28:06 +0900 Subject: [PATCH 001/146] chore: refactor --- src/Base/Constants.ts | 6 +++ src/Base/EEObject.ts | 4 +- src/Base/Ensure.ts | 20 +++++++- src/Base/IDObject.ts | 68 +++++++++++++------------- src/Interface/GrimoireInterfaceImpl.ts | 38 +++++++++----- src/Interface/NodeInterface.ts | 3 -- src/Node/GomlLoader.ts | 6 +-- src/Node/GomlNode.ts | 12 ++--- src/Node/NodeDeclaration.ts | 5 +- src/Node/NodeUtility.ts | 4 +- src/main.ts | 8 +-- 11 files changed, 101 insertions(+), 73 deletions(-) diff --git a/src/Base/Constants.ts b/src/Base/Constants.ts index 5440f2591..6e4201f6f 100644 --- a/src/Base/Constants.ts +++ b/src/Base/Constants.ts @@ -1,3 +1,5 @@ +// import NSIdentity from "./NSIdentity"; + export default class Constants { public static get defaultNamespace(): string { return "grimoirejs"; @@ -5,4 +7,8 @@ export default class Constants { public static get x_gr_id(): string { return "x-gr-id"; } + + public static get baseNodeName(): string { + return Constants.defaultNamespace + ".grimoire-node-base"; + } } diff --git a/src/Base/EEObject.ts b/src/Base/EEObject.ts index 9014d1895..16a45862f 100644 --- a/src/Base/EEObject.ts +++ b/src/Base/EEObject.ts @@ -4,7 +4,7 @@ import IDObject from "./IDObject"; /** * EventEmitterをmixinしたIDObject */ -class EEObject extends IDObject implements NodeJS.EventEmitter { +export default class EEObject extends IDObject implements NodeJS.EventEmitter { public prependListener: (event: string, listener: Function) => this; public prependOnceListener: (event: string, listener: Function) => this; public eventNames: () => string[]; @@ -32,5 +32,3 @@ function applyMixins(derivedCtor: any, baseCtors: any[]) { } applyMixins(EEObject, [EventEmitter]); - -export default EEObject; diff --git a/src/Base/Ensure.ts b/src/Base/Ensure.ts index 0fb8f60d9..aef73853f 100644 --- a/src/Base/Ensure.ts +++ b/src/Base/Ensure.ts @@ -2,7 +2,7 @@ import GrimoireInterface from "../Interface/GrimoireInterface"; import NSIdentity from "./NSIdentity"; // import Namespace from "./Namespace"; import NSDictionary from "./NSDictionary"; -import {Name, Nullable, Ctor} from "./Types"; +import {Name, Nullable, Ctor, ComponentRegistering} from "./Types"; /** * Provides static methods to ensure arguments are valid type. */ @@ -120,7 +120,25 @@ export default class Ensure { } } + /** + * check string is FQN format + * FQN format is just name start with '_' + * @param {string} name [description] + * @return {boolean} [description] + */ public static checkFQNString(name: string): boolean { return name.startsWith("_"); } + + /** + * internal use! + * @param {[type]} typeofname==="string"||nameinstanceofNSIdentity [description] + * @return {[type]} [description] + */ + public static tobeName(name: Name | ComponentRegistering): Name { + if (typeof name === "string" || name instanceof NSIdentity) { + return name; + } + return name.componentName!; + } } diff --git a/src/Base/IDObject.ts b/src/Base/IDObject.ts index 7dd68d038..ef968b27e 100644 --- a/src/Base/IDObject.ts +++ b/src/Base/IDObject.ts @@ -2,42 +2,40 @@ * Most based object for any Grimoire.js related classes. * @type {[type]} */ -class IDObject { - /** - * ID related to this instance to identify. - */ - public id: string; +export default class IDObject { + /** + * ID related to this instance to identify. + */ + public readonly id: string; - /** - * Generate random string - * @param {number} length length of random string - * @return {string} generated string - */ - public static getUniqueRandom(length: number): string { - return Math.random().toString(36).slice(-length); - } + /** + * Generate random string + * @param {number} length length of random string + * @return {string} generated string + */ + public static getUniqueRandom(length: number): string { + return Math.random().toString(36).slice(-length); + } - constructor() { - this.id = IDObject.getUniqueRandom(10); - } - /** - * Obtain stringfied object. - * If this method was not overridden, this method return class name. - * @return {string} stringfied object - */ - public toString(): string { - return this.getTypeName(); - } + constructor() { + this.id = IDObject.getUniqueRandom(10); + } + /** + * Obtain stringfied object. + * If this method was not overridden, this method return class name. + * @return {string} stringfied object + */ + public toString(): string { + return this.getTypeName(); + } - /** - * Obtain class name - * @return {string} Class name of the instance. - */ - public getTypeName(): string { - const funcNameRegex = /function (.{1,})\(/; - const result = (funcNameRegex).exec((this).constructor.toString()); - return (result && result.length > 1) ? result[1] : ""; - } + /** + * Obtain class name + * @return {string} Class name of the instance. + */ + public getTypeName(): string { + const funcNameRegex = /function (.{1,})\(/; + const result = (funcNameRegex).exec((this).constructor.toString()); + return (result && result.length > 1) ? result[1] : ""; + } } - -export default IDObject; diff --git a/src/Interface/GrimoireInterfaceImpl.ts b/src/Interface/GrimoireInterfaceImpl.ts index 1a038fb25..632107c69 100644 --- a/src/Interface/GrimoireInterfaceImpl.ts +++ b/src/Interface/GrimoireInterfaceImpl.ts @@ -51,6 +51,12 @@ export default class GrimoireInterfaceImpl extends EEObject { public componentDictionary: { [componentId: string]: Component } = {}; public debug = true; + /** + * Loading goml when page onload automaticaly or not. + * @return {[type]} [description] + */ + public autoLoading = true; + /** * The object assigned to gr before loading grimoire.js * @type {any} @@ -77,12 +83,12 @@ export default class GrimoireInterfaceImpl extends EEObject { this.registerConverter("String", StringConverter); this.registerConverter("StringArray", StringArrayConverter); this.registerConverter("Boolean", BooleanConverter); - this.registerConverter(ArrayConverter); this.registerConverter("Object", ObjectConverter); - this.registerConverter(EnumConverter); this.registerConverter("Number", NumberConverter); - this.registerConverter(ComponentConverter); this.registerConverter("NumberArray", NumberArrayConverter); + this.registerConverter(ArrayConverter); + this.registerConverter(EnumConverter); + this.registerConverter(ComponentConverter); this.registerComponent(GrimoireComponent); this.registerNode("grimoire-node-base", ["GrimoireComponent"]); } @@ -133,6 +139,7 @@ export default class GrimoireInterfaceImpl extends EEObject { let obj: ComponentRegistering>; let superComponent: Name | Ctor | undefined; if (typeof arg1 === "string" || arg1 instanceof NSIdentity) { + Utility.w(` registerComponent() overload that call with name is deprecated. use other overload instead of.`); name = arg1; obj = arg2 as ComponentRegistering>; superComponent = arg3; @@ -168,9 +175,13 @@ export default class GrimoireInterfaceImpl extends EEObject { return dec; } - public registerNode(name: Name, requiredComponents: Name[] = [], - defaults?: { [key: string]: any } | NSDictionary, - superNode?: Name, freezeAttributes?: Name[]): NodeDeclaration { + public registerNode( + name: Name, + requiredComponents: Name[] = [], + defaults?: { [key: string]: any }, + superNode?: Name, + freezeAttributes?: Name[]): NodeDeclaration { + const registerId = this._ensureTobeNSIdentityOnRegister(name); if (this.nodeDeclarations.get(registerId)) { throw new Error(`gomlnode ${registerId.fqn} is already registerd.`); @@ -245,7 +256,11 @@ export default class GrimoireInterfaceImpl extends EEObject { public registerConverter(declaration: IAttributeConverterDeclaration): void; public registerConverter(arg1: Name | IAttributeConverterDeclaration, converter?: ((val: any, attr: Attribute) => any)): void { if (converter) { - this.registerConverter({ name: this._ensureTobeNSIdentityOnRegister(arg1 as any), verify: () => true, convert: converter }); + this.registerConverter({ + name: this._ensureTobeNSIdentityOnRegister(arg1 as Name), + verify: () => true, + convert: converter + }); return; } const dec = arg1 as IAttributeConverterDeclaration; @@ -358,15 +373,16 @@ export default class GrimoireInterfaceImpl extends EEObject { private _ensureTobeNSIdentityOnRegister(name: Name): NSIdentity; private _ensureTobeNSIdentityOnRegister(name: null | undefined): null; - private _ensureTobeNSIdentityOnRegister(name: Name |null | undefined): Nullable { + private _ensureTobeNSIdentityOnRegister(name: Name | null | undefined): Nullable { if (!name) { return null; } if (typeof name === "string") { - if (name.indexOf("|") !== -1) { - return NSIdentity.fromFQN(name); + const fqn = Ensure.tobeFQN(name); + if (fqn) { + return NSIdentity.fromFQN(fqn); } - return NSIdentity.fromFQN(Namespace.define(this._registrationContext), name); + return Namespace.define(this._registrationContext).for(name); } else { return name; } diff --git a/src/Interface/NodeInterface.ts b/src/Interface/NodeInterface.ts index e95036d32..6e3dc83f5 100644 --- a/src/Interface/NodeInterface.ts +++ b/src/Interface/NodeInterface.ts @@ -20,9 +20,6 @@ export default class NodeInterface { public nodes: GomlNode[][]; constructor(nodes: GomlNode[][]) { - if (!nodes) { - throw new Error("nodes is null"); - } this.nodes = nodes; } diff --git a/src/Node/GomlLoader.ts b/src/Node/GomlLoader.ts index 17366fd5b..fe94bde10 100644 --- a/src/Node/GomlLoader.ts +++ b/src/Node/GomlLoader.ts @@ -2,10 +2,11 @@ import GrimoireInterface from "../Interface/GrimoireInterface"; import GomlParser from "./GomlParser"; import XMLReader from "../Base/XMLReader"; import XMLHttpRequestAsync from "../Base/XMLHttpRequestAsync"; + /** * Provides the features to fetch Goml source. */ -class GomlLoader { +export default class GomlLoader { public static initializedEventHandlers: ((scriptTags: HTMLScriptElement[]) => void)[] = []; /** @@ -29,6 +30,7 @@ class GomlLoader { const rootNode = GomlParser.parse(doc[0]); GrimoireInterface.addRootNode(scriptTag, rootNode); } + /** * Load from the script tags which will be found with specified query. * @param {string} query [the query to find script tag] @@ -60,5 +62,3 @@ class GomlLoader { await GomlLoader.loadFromQuery('script[type="text/goml"]'); } } - -export default GomlLoader; diff --git a/src/Node/GomlNode.ts b/src/Node/GomlNode.ts index ea5950012..3e4a2c47a 100644 --- a/src/Node/GomlNode.ts +++ b/src/Node/GomlNode.ts @@ -17,14 +17,13 @@ import Ensure from "../Base/Ensure"; import MessageException from "../Base/MessageException"; import { Name, GomlInterface, Nullable, Ctor } from "../Base/Types"; -class GomlNode extends EEObject { +export default class GomlNode extends EEObject { public element: Element; // Dom Element public nodeDeclaration: NodeDeclaration; public children: GomlNode[] = []; public componentsElement: Element; // <.components> - private _parent: Nullable = null; private _root: Nullable = null; private _components: Component[]; @@ -32,9 +31,7 @@ class GomlNode extends EEObject { private _companion: NSDictionary = new NSDictionary(); private _attributeManager: AttributeManager; private _isActive = false; - private _messageCache: { [message: string]: Component[] } = {}; - private _deleted = false; private _mounted = false; private _enabled = true; @@ -145,7 +142,7 @@ class GomlNode extends EEObject { * @param {Element} element 対応するDomElement * @return {[type]} [description] */ - constructor(recipe: NodeDeclaration, element?: Nullable) { + constructor(recipe: NodeDeclaration, element?: Element) { super(); if (!recipe) { throw new Error("recipe must not be null"); @@ -689,7 +686,7 @@ class GomlNode extends EEObject { */ public toStructualString(message = ""): string { if (this.parent) { - return "\n" + this.parent._openTreeString() + this._currentSiblingsString(this._layer * 2, `<${this.toString()}/>`, true, message) + this.parent._closeTreeString(); + return "\n" + this.parent._openTreeString() + this._currentSiblingsString(this._layer * 2, `<${this.toString()}/>`, true, message) + this.parent._closeTreeString(); } else { return "\n" + this._currentSiblingsString(0, `<${this.toString()}/>`, true, message); } @@ -903,6 +900,3 @@ class GomlNode extends EEObject { return list; } } - - -export default GomlNode; diff --git a/src/Node/NodeDeclaration.ts b/src/Node/NodeDeclaration.ts index 848cee0f5..33f660d00 100644 --- a/src/Node/NodeDeclaration.ts +++ b/src/Node/NodeDeclaration.ts @@ -4,6 +4,7 @@ import NSSet from "../Base/NSSet"; import NSIdentity from "../Base/NSIdentity"; import IdResolver from "../Base/IdResolver"; import GrimoireInterface from "../Interface/GrimoireInterface"; +import Constants from "../Base/Constants"; import {Name} from "../Base/Types"; export default class NodeDeclaration { @@ -42,8 +43,8 @@ export default class NodeDeclaration { private _defaultAttributes: { [key: string]: any }, private _superNode?: Name, private _freezeAttributes: Name[] = []) { - if (!this._superNode && this.name.name !== "grimoire-node-base") { - this._superNode = new NSIdentity("grimoirejs.grimoire-node-base"); + if (!this._superNode && this.name.fqn !== Constants.baseNodeName) { + this._superNode = NSIdentity.fromFQN(Constants.baseNodeName); } this._freezeAttributes = this._freezeAttributes || []; } diff --git a/src/Node/NodeUtility.ts b/src/Node/NodeUtility.ts index 7b15b5e7d..64bc1c915 100644 --- a/src/Node/NodeUtility.ts +++ b/src/Node/NodeUtility.ts @@ -1,4 +1,4 @@ -class NodeUtility { // TODO merge with Base/XMLReader +export default class NodeUtility { // TODO merge with Base/XMLReader /** * Get index of NodeList converted from index in Element * @param {HTMLElement} targetElement Parent element of search target elements @@ -28,5 +28,3 @@ class NodeUtility { // TODO merge with Base/XMLReader return attributes; } } - -export default NodeUtility; diff --git a/src/main.ts b/src/main.ts index 7eb9e825e..5aa1e541b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -17,7 +17,9 @@ class GrimoireInitializer { await GrimoireInitializer._waitForDOMLoading(); GrimoireInitializer._logVersions(); await GrimoireInterface.resolvePlugins(); - await GomlLoader.loadForPage(); + if (GrimoireInterface.autoLoading) { + await GomlLoader.loadForPage(); + } } catch (e) { console.error(e); } @@ -36,8 +38,8 @@ class GrimoireInitializer { // Otherwise like ""Safari"" for (let propName in WebGLRenderingContext.prototype) { if (/^[A-Z]/.test(propName)) { - const property = (WebGLRenderingContext.prototype)[propName]; - (WebGLRenderingContext)[propName] = property; + const property = (WebGLRenderingContext.prototype as any)[propName]; + (WebGLRenderingContext as any)[propName] = property; } } } From eecf44b508143f56005533e0b8838e0e9483d6fd Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 19 Jun 2017 13:59:37 +0900 Subject: [PATCH 002/146] fix: change registerComponent argument --- src/Base/NSIdentity.ts | 11 +++++++++ src/Interface/GrimoireInterfaceImpl.ts | 4 ++-- test/@/GrimoireInterfaceTest.ts | 31 ++++++++++++++++--------- test/Base/NSIdentityTest.ts | 12 ++++++++++ test/Node/GomlNodeTest.ts | 21 +++++++++++------ test/Node/GomlParserTest_Registering.ts | 21 +++++++++++------ 6 files changed, 73 insertions(+), 27 deletions(-) diff --git a/src/Base/NSIdentity.ts b/src/Base/NSIdentity.ts index 5642fcc30..57ff57ac6 100644 --- a/src/Base/NSIdentity.ts +++ b/src/Base/NSIdentity.ts @@ -1,5 +1,6 @@ import Namespace from "./Namespace"; import IdResolver from "./IdResolver"; +import Ensure from "./Ensure"; /** * The class to identity with XML namespace feature. @@ -116,6 +117,16 @@ export default class NSIdentity { return this._fqn; } + public isMatch(name: string): boolean { + if (Ensure.checkFQNString(name)) { + return this._fqn === Ensure.tobeFQN(name); + } else { + let resolver = new IdResolver(); + resolver.add(this); + let get = resolver.get(name); + return get.length === 1; + } + } public toString(): string { return this.fqn; diff --git a/src/Interface/GrimoireInterfaceImpl.ts b/src/Interface/GrimoireInterfaceImpl.ts index 632107c69..3dc616ff8 100644 --- a/src/Interface/GrimoireInterfaceImpl.ts +++ b/src/Interface/GrimoireInterfaceImpl.ts @@ -321,10 +321,10 @@ export default class GrimoireInterfaceImpl extends EEObject { } public extendGrimoireInterface(name: string, func: Function): void { - if ((this)[name]) { + if ((this as any)[name]) { throw new Error(`gr.${name} can not extend.it is already exist.`); } - (this)[name] = func.bind(this); + (this as any)[name] = func.bind(this); } public extendGomlInterface(name: string, func: Function): void { if ((GomlInterfaceImpl as any)[name]) { diff --git a/test/@/GrimoireInterfaceTest.ts b/test/@/GrimoireInterfaceTest.ts index 4c149d86c..22e76db1d 100644 --- a/test/@/GrimoireInterfaceTest.ts +++ b/test/@/GrimoireInterfaceTest.ts @@ -35,7 +35,8 @@ test("ns method should generate namespace generating function correctly", (t) => test("registerComponent works correctly", (t) => { const l = GrimoireInterface.componentDeclarations.toArray().length; - const dec = GrimoireInterface.registerComponent("Name", { + const dec = GrimoireInterface.registerComponent({ + componentName: "Name", attributes: { attr: { converter: "String", default: "aaa" } } @@ -43,7 +44,8 @@ test("registerComponent works correctly", (t) => { t.truthy(dec.attributes["attr"].default === "aaa"); t.truthy(GrimoireInterface.componentDeclarations.toArray().length === l + 1); t.throws(() => { - GrimoireInterface.registerComponent("Name", { + GrimoireInterface.registerComponent({ + componentName: "Name", attributes: { attr: { converter: "String", default: undefined } } @@ -51,18 +53,20 @@ test("registerComponent works correctly", (t) => { }); class Hoo { + public static componentName = "Name"; public static attributes = { }; } t.throws(() => { - GrimoireInterface.registerComponent("Name", Hoo); // because not extends Component. + GrimoireInterface.registerComponent(Hoo); // because not extends Component. }); }); test("registerComponent by object works correctly", async (t) => { const defaultComponentCount = GrimoireInterface.componentDeclarations.toArray().length; - GrimoireInterface.registerComponent("Aaa", { + GrimoireInterface.registerComponent({ + componentName: "Aaa", attributes: { testValue: { converter: "String", @@ -95,7 +99,8 @@ test("registerComponent by object works correctly", async (t) => { (aaa2 as any).$test(); t.truthy((aaa2 as any).hoge === 1); t.truthy((aaa22 as any).hoge === 0); - GrimoireInterface.registerComponent("Bbb", { + GrimoireInterface.registerComponent({ + componentName: "Bbb", attributes: { testValue2: { converter: "String", @@ -131,6 +136,7 @@ test("registerComponent by class works correctly", async (t) => { const defaultComponentCount = GrimoireInterface.componentDeclarations.toArray().length; class Aaa extends Component { + public static componentName = "Aaa"; public static attributes = { testValue: { converter: "String", @@ -150,6 +156,7 @@ test("registerComponent by class works correctly", async (t) => { } } class Bbb extends Component { + public static componentName = "Bbb"; public static attributes = { testValue2: { converter: "String", @@ -169,7 +176,7 @@ test("registerComponent by class works correctly", async (t) => { } } - GrimoireInterface.registerComponent("Aaa", Aaa); + GrimoireInterface.registerComponent(Aaa); const aaa = GrimoireInterface.componentDeclarations.get("Aaa"); t.truthy(GrimoireInterface.componentDeclarations.toArray().length === defaultComponentCount + 1); t.truthy(aaa.attributes.testValue); @@ -187,7 +194,7 @@ test("registerComponent by class works correctly", async (t) => { t.truthy((aaa2 as any).hoge === 1); t.truthy((aaa22 as any).hoge === 0); - GrimoireInterface.registerComponent("Bbb", Bbb, "Aaa"); + GrimoireInterface.registerComponent(Bbb, "Aaa"); t.truthy(GrimoireInterface.componentDeclarations.toArray().length === defaultComponentCount + 2); const bbb = GrimoireInterface.componentDeclarations.get("Bbb"); @@ -214,6 +221,7 @@ test("registerComponent by class works correctly", async (t) => { test("registerComponent works correctly4", async (t) => { const defaultComponentCount = GrimoireInterface.componentDeclarations.toArray().length; class Aaa extends Component { + public static componentName = "Aaa"; public static attributes: { [key: string]: any } = { testValue: { converter: "String", @@ -230,6 +238,7 @@ test("registerComponent works correctly4", async (t) => { } } class Bbb2 extends Aaa { + public static componentName = "Bbb"; public static attributes = { testValue2: { converter: "String", @@ -245,7 +254,7 @@ test("registerComponent works correctly4", async (t) => { // do nothing. } } - GrimoireInterface.registerComponent("Aaa", Aaa); + GrimoireInterface.registerComponent(Aaa); const aaa = GrimoireInterface.componentDeclarations.get("Aaa"); t.truthy(GrimoireInterface.componentDeclarations.toArray().length === defaultComponentCount + 1); @@ -264,7 +273,7 @@ test("registerComponent works correctly4", async (t) => { t.truthy((aaa2 as any).hoge === 1); t.truthy((aaa22 as any).hoge === 0); - GrimoireInterface.registerComponent("Bbb", Bbb2); + GrimoireInterface.registerComponent(Bbb2); t.truthy(GrimoireInterface.componentDeclarations.toArray().length === defaultComponentCount + 2); const bbb = GrimoireInterface.componentDeclarations.get("Bbb"); await GrimoireInterface.resolvePlugins(); @@ -307,10 +316,10 @@ test("registerNode/Component works correctly.", async t => { t.truthy(a3.idResolver.resolve(Namespace.define("hoge")) === "grimoirejs.Hoge.hoge"); }); test("throw error on attempt registerComponent/Node by duplicate name.", t => { - GrimoireInterface.registerComponent("Aaa", { attributes: {} }); + GrimoireInterface.registerComponent({ componentName: "Aaa", attributes: {} }); GrimoireInterface.registerNode("node"); t.throws(() => { - GrimoireInterface.registerComponent("Aaa", {} as any); + GrimoireInterface.registerComponent({} as any); }); t.throws(() => { GrimoireInterface.registerNode("node"); diff --git a/test/Base/NSIdentityTest.ts b/test/Base/NSIdentityTest.ts index 31738b8f5..0acee00e0 100644 --- a/test/Base/NSIdentityTest.ts +++ b/test/Base/NSIdentityTest.ts @@ -44,3 +44,15 @@ test("Transform name and ns correctly", (t) => { t.truthy(i.name === "Sample"); t.truthy(i.ns.qualifiedName === "ns"); }); + +test("isMatch works correctly", t => { + let hoge = NSIdentity.fromFQN("a.b.c"); + t.truthy(hoge.isMatch("c")); + t.truthy(hoge.isMatch("b.c")); + t.truthy(hoge.isMatch("a.c")); + t.truthy(hoge.isMatch("a.b.c")); + t.truthy(!hoge.isMatch("c.c")); + t.truthy(!hoge.isMatch("b.a.c")); + t.truthy(!hoge.isMatch("d")); + t.truthy(!hoge.isMatch("a.d")); +}); diff --git a/test/Node/GomlNodeTest.ts b/test/Node/GomlNodeTest.ts index d2633270f..a863792dc 100644 --- a/test/Node/GomlNodeTest.ts +++ b/test/Node/GomlNodeTest.ts @@ -99,7 +99,8 @@ test("detach method works correctly", t => { }); test("getComponents method works correctly", t => { - GrimoireInterface.registerComponent("TestComponent", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent", attributes: { attr1: { converter: "String", @@ -135,7 +136,8 @@ test("addComponent method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2, null, null); - GrimoireInterface.registerComponent("TestComponent1", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent1", attributes: { testAttr1: { converter: "String", @@ -154,7 +156,8 @@ test("addComponent method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2, null, null); - GrimoireInterface.registerComponent("TestComponent1", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent1", attributes: { testAttr1: { converter: "String", @@ -173,7 +176,8 @@ test("getComponent method overload works correctly", async t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2, null, null); - GrimoireInterface.registerComponent("TestComponent1", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent1", attributes: { testAttr1: { converter: "String", @@ -181,7 +185,8 @@ test("getComponent method overload works correctly", async t => { } } }); - GrimoireInterface.registerComponent("TestComponent2", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent2", attributes: { testAttr1: { converter: "String", @@ -199,7 +204,8 @@ test("getComponents method overload works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2, null, null); - GrimoireInterface.registerComponent("TestComponent1", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent1", attributes: { testAttr1: { converter: "String", @@ -207,7 +213,8 @@ test("getComponents method overload works correctly", t => { } } }); - GrimoireInterface.registerComponent("TestComponent2", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent2", attributes: { testAttr1: { converter: "String", diff --git a/test/Node/GomlParserTest_Registering.ts b/test/Node/GomlParserTest_Registering.ts index 05d70fe7c..f7f1addc8 100644 --- a/test/Node/GomlParserTest_Registering.ts +++ b/test/Node/GomlParserTest_Registering.ts @@ -3,7 +3,8 @@ import sinon from "sinon"; export function testComponent1() { const spy = sinon.spy(); - GrimoireInterface.registerComponent("TestComponent1", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent1", attributes: { testAttr1: { converter: "Str", @@ -32,7 +33,8 @@ export function testComponent1() { export function testComponent2() { const spy = sinon.spy(); - GrimoireInterface.registerComponent("TestComponent2", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent2", attributes: { testAttr2: { converter: "Str", @@ -57,7 +59,8 @@ export function testComponent2() { export function testComponent3() { const spy = sinon.spy(); - GrimoireInterface.registerComponent("TestComponent3", { + GrimoireInterface.registerComponent({ + componentName: "TestComponent3", attributes: { testAttr3: { converter: "Str", @@ -90,7 +93,8 @@ export function testComponent3() { export function testComponentBase() { const spy = sinon.spy(); - GrimoireInterface.registerComponent("TestComponentBase", { + GrimoireInterface.registerComponent({ + componentName: "TestComponentBase", attributes: { inheritAttr: { converter: "Str", @@ -115,7 +119,8 @@ export function testComponentBase() { export function testComponentOptional() { const spy = sinon.spy(); - GrimoireInterface.registerComponent("TestComponentOptional", { + GrimoireInterface.registerComponent({ + componentName: "TestComponentOptional", attributes: { value: { converter: "Str", @@ -141,7 +146,8 @@ export function testComponentOptional() { export function conflictComponent1() { const spy = sinon.spy(); const ns = GrimoireInterface.ns("test1"); - GrimoireInterface.registerComponent(ns("ConflictComponent"), { + GrimoireInterface.registerComponent({ + componentName: ns("ConflictComponent"), attributes: { value: { converter: "Str", @@ -158,7 +164,8 @@ export function conflictComponent1() { export function conflictComponent2() { const spy = sinon.spy(); const ns = GrimoireInterface.ns("test2"); - GrimoireInterface.registerComponent(ns("ConflictComponent"), { + GrimoireInterface.registerComponent({ + componentName: ns("ConflictComponent"), attributes: { value: { converter: "Str", From d3e790ad5bc0774b6c941affeae97922e7f581ca Mon Sep 17 00:00:00 2001 From: moajo Date: Thu, 14 Sep 2017 16:03:53 +0900 Subject: [PATCH 003/146] fix bug --- src/Base/EEObject.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Base/EEObject.ts b/src/Base/EEObject.ts index 11d0747d0..911d36886 100644 --- a/src/Base/EEObject.ts +++ b/src/Base/EEObject.ts @@ -57,3 +57,5 @@ function applyMixins(derivedCtor: any, baseCtors: any[]) { } applyMixins(EEObject, [EventEmitter]); + +export default EEObject; From 15c11e0201818a93f35299b0f47da1b4e1105b7f Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 15 Sep 2017 14:56:15 +0900 Subject: [PATCH 004/146] [fix] remove unnecessary exports --- src/Base/ListenerFunction.ts | 3 --- src/Interface/NodeInterface.ts | 11 +++++------ 2 files changed, 5 insertions(+), 9 deletions(-) delete mode 100644 src/Base/ListenerFunction.ts diff --git a/src/Base/ListenerFunction.ts b/src/Base/ListenerFunction.ts deleted file mode 100644 index 5f0b4a614..000000000 --- a/src/Base/ListenerFunction.ts +++ /dev/null @@ -1,3 +0,0 @@ -import {ListenerFn} from "eventemitter3"; -export interface Fake {} -export default ListenerFn; diff --git a/src/Interface/NodeInterface.ts b/src/Interface/NodeInterface.ts index 6eba140d0..b4553742e 100644 --- a/src/Interface/NodeInterface.ts +++ b/src/Interface/NodeInterface.ts @@ -4,8 +4,7 @@ import GomlParser from "../Node/GomlParser"; import Attribute from "../Node/Attribute"; import GomlNode from "../Node/GomlNode"; import {Name, Nullable} from "../Base/Types"; -import ListenerFunction from "../Base/ListenerFunction"; - +import { ListenerFn } from "eventemitter3"; /** * interface for operate multicast nodes. @@ -102,9 +101,9 @@ export default class NodeInterface { /** * 対象ノードにイベントリスナを追加します。 * @param {string} eventName [description] - * @param {ListenerFunction} listener [description] + * @param {ListenerFn} listener [description] */ - public on(eventName: string, listener: ListenerFunction): NodeInterface { + public on(eventName: string, listener: ListenerFn): NodeInterface { this.forEach(node => { node.on(eventName, listener); }); @@ -114,9 +113,9 @@ export default class NodeInterface { /** * 対象ノードに指定したイベントリスナが登録されていれば削除します * @param {string} eventName [description] - * @param {ListenerFunction} listener [description] + * @param {ListenerFn} listener [description] */ - public off(eventName: string, listener: ListenerFunction): NodeInterface { + public off(eventName: string, listener: ListenerFn): NodeInterface { this.forEach(node => { node.removeListener(eventName, listener); }); From d3749678935c341090eaae49f7af8f90e3727f9c Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 15 Sep 2017 15:30:37 +0900 Subject: [PATCH 005/146] [refactor] change directory structure --- README.md | 2 +- src/Components/GrimoireComponent.ts | 4 +-- src/Converters/ArrayConverter.ts | 4 +-- src/Converters/ComponentConverter.ts | 8 ++--- src/Converters/EnumConverter.ts | 2 +- src/Converters/NumberConverter.ts | 2 +- src/{Node => Core}/Attribute.ts | 18 +++++----- src/{Base => Core}/AttributeManager.ts | 10 +++--- src/{Node => Core}/Component.ts | 16 ++++----- src/{Node => Core}/ComponentDeclaration.ts | 16 ++++----- src/{Interface => Core}/GomlInterfaceImpl.ts | 6 ++-- src/{Node => Core}/GomlLoader.ts | 6 ++-- src/{Node => Core}/GomlNode.ts | 28 +++++++-------- src/{Node => Core}/GomlParser.ts | 2 +- src/{Interface => Core}/GrimoireInterface.ts | 4 +-- .../GrimoireInterfaceImpl.ts | 34 +++++++++---------- src/{Base => Core}/NSIdentity.ts | 4 +-- src/{Base => Core}/Namespace.ts | 2 +- src/{Node => Core}/NodeDeclaration.ts | 16 ++++----- src/{Interface => Core}/NodeInterface.ts | 12 +++---- src/{Node => Core}/NodeUtility.ts | 0 .../IAttributeConverterDeclaration.ts | 7 ++-- src/Interface/IAttributeDeclaration.ts | 8 +++++ src/Interface/ITreeInitializedInfo.ts | 4 +++ src/Node/IAttributeDeclaration.ts | 9 ----- src/Node/ITreeInitializedInfo.ts | 6 ---- src/{Base => Tools}/Constants.ts | 2 -- src/{Base => Tools}/Ensure.ts | 8 ++--- src/{Base => Tools}/IdResolver.ts | 4 +-- src/{Base => Tools}/MessageException.ts | 5 +-- src/{Base => Tools}/NSDictionary.ts | 4 +-- src/{Base => Tools}/NSSet.ts | 2 +- src/{Base => Tools}/Types.ts | 12 +++---- src/{Base => Tools}/Utility.ts | 2 +- src/{Base => Tools}/XMLHttpRequestAsync.ts | 0 src/{Base => Tools}/XMLReader.ts | 0 src/main.ts | 4 +-- test/@/GrimoireInterfaceTest.ts | 8 ++--- test/Base/AttributeManagerTest.ts | 2 +- test/Base/IdResolverTest.ts | 8 ++--- test/Base/NSIdentityTest.ts | 8 ++--- test/Base/NamespaceTest.ts | 8 ++--- test/Base/NamespacedDictionaryTest.ts | 2 +- test/Interfaces/NodeInterfaceTest.ts | 4 +-- test/Node/GomlLoaderTest.ts | 4 +-- test/Node/GomlNode2Test.ts | 8 ++--- test/Node/GomlNodeTest.ts | 10 +++--- test/Node/GomlParserTest.ts | 2 +- test/Node/NamespacedSetTest.ts | 2 +- test/PageLoadingHelper.ts | 4 +-- 50 files changed, 169 insertions(+), 174 deletions(-) rename src/{Node => Core}/Attribute.ts (94%) rename src/{Base => Core}/AttributeManager.ts (97%) rename src/{Node => Core}/Component.ts (93%) rename src/{Node => Core}/ComponentDeclaration.ts (93%) rename src/{Interface => Core}/GomlInterfaceImpl.ts (87%) rename src/{Node => Core}/GomlLoader.ts (92%) rename src/{Node => Core}/GomlNode.ts (97%) rename src/{Node => Core}/GomlParser.ts (98%) rename src/{Interface => Core}/GrimoireInterface.ts (91%) rename src/{Interface => Core}/GrimoireInterfaceImpl.ts (94%) rename src/{Base => Core}/NSIdentity.ts (97%) rename src/{Base => Core}/Namespace.ts (96%) rename src/{Node => Core}/NodeDeclaration.ts (90%) rename src/{Interface => Core}/NodeInterface.ts (97%) rename src/{Node => Core}/NodeUtility.ts (100%) rename src/{Declaration => Interface}/IAttributeConverterDeclaration.ts (52%) create mode 100644 src/Interface/IAttributeDeclaration.ts create mode 100644 src/Interface/ITreeInitializedInfo.ts delete mode 100644 src/Node/IAttributeDeclaration.ts delete mode 100644 src/Node/ITreeInitializedInfo.ts rename src/{Base => Tools}/Constants.ts (87%) rename src/{Base => Tools}/Ensure.ts (95%) rename src/{Base => Tools}/IdResolver.ts (97%) rename src/{Base => Tools}/MessageException.ts (96%) rename src/{Base => Tools}/NSDictionary.ts (97%) rename src/{Base => Tools}/NSSet.ts (96%) rename src/{Base => Tools}/Types.ts (68%) rename src/{Base => Tools}/Utility.ts (96%) rename src/{Base => Tools}/XMLHttpRequestAsync.ts (100%) rename src/{Base => Tools}/XMLReader.ts (100%) diff --git a/README.md b/README.md index d30db117a..106d228c4 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ And these are able to be written by Typescript. Safe and effective environment f This is a sample to make objects waving movement. (You can see full comprehensive this sample at our top page) ```ts -import Component from "grimoirejs/ref/Node/Component"; +import Component from "grimoirejs/ref/Core/Component"; import ISceneUpdateArgument from "grimoirejs-fundamental/ref/SceneRenderer/ISceneUpdateArgument"; import TransformComponent from "grimoirejs-fundamental/ref/Components/TransformComponent"; import Vector3 from "grimoirejs-math/ref/Vector3"; diff --git a/src/Components/GrimoireComponent.ts b/src/Components/GrimoireComponent.ts index 0d5dfa6fa..4dba3b324 100644 --- a/src/Components/GrimoireComponent.ts +++ b/src/Components/GrimoireComponent.ts @@ -1,5 +1,5 @@ -import IAttributeDeclaration from "../Node/IAttributeDeclaration"; -import Component from "../Node/Component"; +import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +import Component from "../Core/Component"; export default class GrimoireComponent extends Component { public static componentName = "GrimoireComponent"; diff --git a/src/Converters/ArrayConverter.ts b/src/Converters/ArrayConverter.ts index 402a14dbf..89256e428 100644 --- a/src/Converters/ArrayConverter.ts +++ b/src/Converters/ArrayConverter.ts @@ -1,5 +1,5 @@ -import GrimoireInterface from "../Interface/GrimoireInterface"; -import Attribute from "../Node/Attribute"; +import GrimoireInterface from "../Core/GrimoireInterface"; +import Attribute from "../Core/Attribute"; const splitter = " "; const escape = "\\"; diff --git a/src/Converters/ComponentConverter.ts b/src/Converters/ComponentConverter.ts index 71f91484d..55416aa86 100644 --- a/src/Converters/ComponentConverter.ts +++ b/src/Converters/ComponentConverter.ts @@ -1,7 +1,7 @@ -import Ensure from "../Base/Ensure"; -import Component from "../Node/Component"; -import GomlNode from "../Node/GomlNode"; -import Attribute from "../Node/Attribute"; +import Ensure from "../Tools/Ensure"; +import Component from "../Core/Component"; +import GomlNode from "../Core/GomlNode"; +import Attribute from "../Core/Attribute"; /** diff --git a/src/Converters/EnumConverter.ts b/src/Converters/EnumConverter.ts index 93a3ff0b3..3a71cdb20 100644 --- a/src/Converters/EnumConverter.ts +++ b/src/Converters/EnumConverter.ts @@ -1,4 +1,4 @@ -import Attribute from "../Node/Attribute"; +import Attribute from "../Core/Attribute"; /** * 列挙のためのコンバータ。 * 属性宣言に`table`パラメータが必要です。 diff --git a/src/Converters/NumberConverter.ts b/src/Converters/NumberConverter.ts index 88cf0bc7a..028221bc5 100644 --- a/src/Converters/NumberConverter.ts +++ b/src/Converters/NumberConverter.ts @@ -1,4 +1,4 @@ -import {Nullable, Undef} from "../Base/Types"; +import {Nullable, Undef} from "../Tools/Types"; /** * converter for number value. diff --git a/src/Node/Attribute.ts b/src/Core/Attribute.ts similarity index 94% rename from src/Node/Attribute.ts rename to src/Core/Attribute.ts index c860dd8f6..a386b3d79 100644 --- a/src/Node/Attribute.ts +++ b/src/Core/Attribute.ts @@ -1,12 +1,12 @@ -import IAttributeConverterDeclaration from "../Declaration/IAttributeConverterDeclaration"; -import NSDictionary from "../Base/NSDictionary"; -import Ensure from "../Base/Ensure"; -import IAttributeDeclaration from "./IAttributeDeclaration"; -import NSIdentity from "../Base/NSIdentity"; -import IdResolver from "../Base/IdResolver"; -import GrimoireInterface from "../Interface/GrimoireInterface"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; +import NSDictionary from "../Tools/NSDictionary"; +import Ensure from "../Tools/Ensure"; +import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +import NSIdentity from "../Core/NSIdentity"; +import IdResolver from "../Tools/IdResolver"; +import GrimoireInterface from "../Core/GrimoireInterface"; import Component from "./Component"; -import {GomlInterface, Name, Nullable} from "../Base/Types"; +import {GomlInterface, Name, Nullable} from "../Tools/Types"; /** * Manage a attribute attached to components. @@ -175,7 +175,7 @@ export default class Attribute { get: () => this.Value, set: (val) => { this.Value = val; }, enumerable: true, - configurable: true + configurable: true }); } else { let backing: any; diff --git a/src/Base/AttributeManager.ts b/src/Core/AttributeManager.ts similarity index 97% rename from src/Base/AttributeManager.ts rename to src/Core/AttributeManager.ts index f134b3643..2984eda51 100644 --- a/src/Base/AttributeManager.ts +++ b/src/Core/AttributeManager.ts @@ -1,10 +1,10 @@ -import Utility from "./Utility"; -import Attribute from "../Node/Attribute"; -import IdResolver from "./IdResolver"; +import Utility from "../Tools/Utility"; +import Attribute from "../Core/Attribute"; +import IdResolver from "../Tools/IdResolver"; import Namespace from "./Namespace"; import NSIdentity from "./NSIdentity"; -import Ensure from "./Ensure"; -import {Name, Undef} from "./Types"; +import Ensure from "../Tools/Ensure"; +import {Name, Undef} from "../Tools/Types"; type NameValPair = { fqn: string, val: T }; diff --git a/src/Node/Component.ts b/src/Core/Component.ts similarity index 93% rename from src/Node/Component.ts rename to src/Core/Component.ts index df36f9efc..66113d908 100644 --- a/src/Node/Component.ts +++ b/src/Core/Component.ts @@ -1,15 +1,15 @@ -import ITreeInitializedInfo from "./ITreeInitializedInfo"; -import Utility from "../Base/Utility"; -import Constants from "../Base/Constants"; +import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; +import Utility from "../Tools/Utility"; +import Constants from "../Tools/Constants"; import NodeUtility from "./NodeUtility"; -import IAttributeDeclaration from "./IAttributeDeclaration"; +import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import Attribute from "./Attribute"; import GomlNode from "./GomlNode"; -import NSDictionary from "../Base/NSDictionary"; -import NSIdentity from "../Base/NSIdentity"; +import NSDictionary from "../Tools/NSDictionary"; +import NSIdentity from "../Core/NSIdentity"; import IDObject from "../Base/IDObject"; -import Ensure from "../Base/Ensure"; -import {GomlInterface, Nullable, Name} from "../Base/Types"; +import Ensure from "../Tools/Ensure"; +import {GomlInterface, Nullable, Name} from "../Tools/Types"; /** * Base class for any components diff --git a/src/Node/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts similarity index 93% rename from src/Node/ComponentDeclaration.ts rename to src/Core/ComponentDeclaration.ts index 0d2c42171..6efc0698a 100644 --- a/src/Node/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -1,13 +1,13 @@ -import Constants from "../Base/Constants"; -import GrimoireInterface from "../Interface/GrimoireInterface"; +import Constants from "../Tools/Constants"; +import GrimoireInterface from "../Core/GrimoireInterface"; import Attribute from "./Attribute"; -import NSDictionary from "../Base/NSDictionary"; -import IAttributeDeclaration from "./IAttributeDeclaration"; -import NSIdentity from "../Base/NSIdentity"; -import IdResolver from "../Base/IdResolver"; +import NSDictionary from "../Tools/NSDictionary"; +import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +import NSIdentity from "../Core/NSIdentity"; +import IdResolver from "../Tools/IdResolver"; import Component from "./Component"; -import Ensure from "../Base/Ensure"; -import {Ctor, Name, ComponentRegistering} from "../Base/Types"; +import Ensure from "../Tools/Ensure"; +import {Ctor, Name, ComponentRegistering} from "../Tools/Types"; export default class ComponentDeclaration { public static ctorMap: { ctor: ComponentRegistering>, name: NSIdentity }[] = []; diff --git a/src/Interface/GomlInterfaceImpl.ts b/src/Core/GomlInterfaceImpl.ts similarity index 87% rename from src/Interface/GomlInterfaceImpl.ts rename to src/Core/GomlInterfaceImpl.ts index 7c24821f0..4eb9b5a80 100644 --- a/src/Interface/GomlInterfaceImpl.ts +++ b/src/Core/GomlInterfaceImpl.ts @@ -1,7 +1,7 @@ -import Constants from "../Base/Constants"; -import GrimoireInterface from "../Interface/GrimoireInterface"; +import Constants from "../Tools/Constants"; +import GrimoireInterface from "../Core/GrimoireInterface"; import NodeInterface from "./NodeInterface"; -import GomlNode from "../Node/GomlNode"; +import GomlNode from "../Core/GomlNode"; /** * Provides interfaces to treat whole goml tree for each. */ diff --git a/src/Node/GomlLoader.ts b/src/Core/GomlLoader.ts similarity index 92% rename from src/Node/GomlLoader.ts rename to src/Core/GomlLoader.ts index 41567f392..8f57a4dee 100644 --- a/src/Node/GomlLoader.ts +++ b/src/Core/GomlLoader.ts @@ -1,7 +1,7 @@ -import GrimoireInterface from "../Interface/GrimoireInterface"; +import GrimoireInterface from "../Core/GrimoireInterface"; import GomlParser from "./GomlParser"; -import XMLReader from "../Base/XMLReader"; -import XMLHttpRequestAsync from "../Base/XMLHttpRequestAsync"; +import XMLReader from "../Tools/XMLReader"; +import XMLHttpRequestAsync from "../Tools/XMLHttpRequestAsync"; /** * Provides the features to fetch Goml source. diff --git a/src/Node/GomlNode.ts b/src/Core/GomlNode.ts similarity index 97% rename from src/Node/GomlNode.ts rename to src/Core/GomlNode.ts index 051834671..e75d5da6a 100644 --- a/src/Node/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -1,20 +1,20 @@ -import ITreeInitializedInfo from "./ITreeInitializedInfo"; -import AttributeManager from "../Base/AttributeManager"; -import Utility from "../Base/Utility"; -import Constants from "../Base/Constants"; +import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; +import AttributeManager from "../Core/AttributeManager"; +import Utility from "../Tools/Utility"; +import Constants from "../Tools/Constants"; import GomlParser from "./GomlParser"; -import XMLReader from "../Base/XMLReader"; -import GrimoireInterface from "../Interface/GrimoireInterface"; +import XMLReader from "../Tools/XMLReader"; +import GrimoireInterface from "../Core/GrimoireInterface"; import EEObject from "../Base/EEObject"; import Component from "./Component"; import NodeDeclaration from "./NodeDeclaration"; import NodeUtility from "./NodeUtility"; import Attribute from "./Attribute"; -import NSDictionary from "../Base/NSDictionary"; -import NSIdentity from "../Base/NSIdentity"; -import Ensure from "../Base/Ensure"; -import MessageException from "../Base/MessageException"; -import { Name, GomlInterface, Nullable, Ctor } from "../Base/Types"; +import NSDictionary from "../Tools/NSDictionary"; +import NSIdentity from "../Core/NSIdentity"; +import Ensure from "../Tools/Ensure"; +import MessageException from "../Tools/MessageException"; +import { Name, GomlInterface, Nullable, Ctor } from "../Tools/Types"; export default class GomlNode extends EEObject { @@ -208,7 +208,7 @@ export default class GomlNode extends EEObject { for (let i = 0; i < nodes.length; i++) { array[i] = GomlNode.fromElement(nodes.item(i)); } - return array; + return array; } public remove(): void { @@ -583,8 +583,8 @@ export default class GomlNode extends EEObject { */ public getComponent(name: Name | Ctor): T { // 事情によりとはできない。 - // これはref/Node/Componentによって参照されるのが外部ライブラリにおけるコンポーネントであるが、 - // src/Node/Componentがこのプロジェクトにおけるコンポーネントのため、別のコンポーネントとみなされ、型の制約をみたさなくなるからである。 + // これはref/Core/Componentによって参照されるのが外部ライブラリにおけるコンポーネントであるが、 + // src/Core/Componentがこのプロジェクトにおけるコンポーネントのため、別のコンポーネントとみなされ、型の制約をみたさなくなるからである。 if (!name) { throw new Error("name must not be null or undefined"); } else if (typeof name === "function") { diff --git a/src/Node/GomlParser.ts b/src/Core/GomlParser.ts similarity index 98% rename from src/Node/GomlParser.ts rename to src/Core/GomlParser.ts index 4a1ea987c..f7f4df7ee 100644 --- a/src/Node/GomlParser.ts +++ b/src/Core/GomlParser.ts @@ -1,5 +1,5 @@ import GomlNode from "./GomlNode"; -import GrimoireInterface from "../Interface/GrimoireInterface"; +import GrimoireInterface from "../Core/GrimoireInterface"; /** * Parser of Goml to Node utilities. diff --git a/src/Interface/GrimoireInterface.ts b/src/Core/GrimoireInterface.ts similarity index 91% rename from src/Interface/GrimoireInterface.ts rename to src/Core/GrimoireInterface.ts index 0f9bcb695..e4b8328d6 100644 --- a/src/Interface/GrimoireInterface.ts +++ b/src/Core/GrimoireInterface.ts @@ -1,7 +1,7 @@ import GrimoireInterfaceImpl from "./GrimoireInterfaceImpl"; import GomlInterfaceImpl from "./GomlInterfaceImpl"; -import GomlNode from "../Node/GomlNode"; -import { GomlInterface, GrimoireInterface } from "../Base/Types"; +import GomlNode from "../Core/GomlNode"; +import { GomlInterface, GrimoireInterface } from "../Tools/Types"; const context = new GrimoireInterfaceImpl(); diff --git a/src/Interface/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts similarity index 94% rename from src/Interface/GrimoireInterfaceImpl.ts rename to src/Core/GrimoireInterfaceImpl.ts index ce9caaff9..85fe75352 100644 --- a/src/Interface/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -1,31 +1,31 @@ import EEObject from "../Base/EEObject"; -import IAttributeConverterDeclaration from "../Declaration/IAttributeConverterDeclaration"; -import GomlLoader from "../Node/GomlLoader"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; +import GomlLoader from "../Core/GomlLoader"; import EnumConverter from "../Converters/EnumConverter"; import NumberArrayConverter from "../Converters/NumberArrayConverter"; import ComponentConverter from "../Converters/ComponentConverter"; import NumberConverter from "../Converters/NumberConverter"; import ObjectConverter from "../Converters/ObjectConverter"; import ArrayConverter from "../Converters/ArrayConverter"; -import NodeInterface from "../Interface/NodeInterface"; -import Utility from "../Base/Utility"; -import GomlInterfaceImpl from "../Interface/GomlInterfaceImpl"; +import NodeInterface from "../Core/NodeInterface"; +import Utility from "../Tools/Utility"; +import GomlInterfaceImpl from "../Core/GomlInterfaceImpl"; import BooleanConverter from "../Converters/BooleanConverter"; import GrimoireComponent from "../Components/GrimoireComponent"; import StringArrayConverter from "../Converters/StringArrayConverter"; import StringConverter from "../Converters/StringConverter"; -import Attribute from "../Node/Attribute"; -import Constants from "../Base/Constants"; -import ITreeInitializedInfo from "../Node/ITreeInitializedInfo"; -import GomlNode from "../Node/GomlNode"; -import ComponentDeclaration from "../Node/ComponentDeclaration"; -import Component from "../Node/Component"; -import NodeDeclaration from "../Node/NodeDeclaration"; -import NSIdentity from "../Base/NSIdentity"; -import Namespace from "../Base/Namespace"; -import NSDictionary from "../Base/NSDictionary"; -import Ensure from "../Base/Ensure"; -import { Name, Nullable, Ctor, ComponentRegistering } from "../Base/Types"; +import Attribute from "../Core/Attribute"; +import Constants from "../Tools/Constants"; +import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; +import GomlNode from "../Core/GomlNode"; +import ComponentDeclaration from "../Core/ComponentDeclaration"; +import Component from "../Core/Component"; +import NodeDeclaration from "../Core/NodeDeclaration"; +import NSIdentity from "../Core/NSIdentity"; +import Namespace from "../Core/Namespace"; +import NSDictionary from "../Tools/NSDictionary"; +import Ensure from "../Tools/Ensure"; +import { Name, Nullable, Ctor, ComponentRegistering } from "../Tools/Types"; export default class GrimoireInterfaceImpl extends EEObject { diff --git a/src/Base/NSIdentity.ts b/src/Core/NSIdentity.ts similarity index 97% rename from src/Base/NSIdentity.ts rename to src/Core/NSIdentity.ts index 9cd2df4da..1abc3f77a 100644 --- a/src/Base/NSIdentity.ts +++ b/src/Core/NSIdentity.ts @@ -1,6 +1,6 @@ import Namespace from "./Namespace"; -import IdResolver from "./IdResolver"; -import Ensure from "./Ensure"; +import IdResolver from "../Tools/IdResolver"; +import Ensure from "../Tools/Ensure"; /** * The class to identity with XML namespace feature. diff --git a/src/Base/Namespace.ts b/src/Core/Namespace.ts similarity index 96% rename from src/Base/Namespace.ts rename to src/Core/Namespace.ts index d9da988e8..02da046ee 100644 --- a/src/Base/Namespace.ts +++ b/src/Core/Namespace.ts @@ -1,5 +1,5 @@ import NSIdentity from "./NSIdentity"; -import Utility from "./Utility"; +import Utility from "../Tools/Utility"; export default class Namespace { diff --git a/src/Node/NodeDeclaration.ts b/src/Core/NodeDeclaration.ts similarity index 90% rename from src/Node/NodeDeclaration.ts rename to src/Core/NodeDeclaration.ts index 33f660d00..45d266c6d 100644 --- a/src/Node/NodeDeclaration.ts +++ b/src/Core/NodeDeclaration.ts @@ -1,11 +1,11 @@ -import Ensure from "../Base/Ensure"; -import NSDictionary from "../Base/NSDictionary"; -import NSSet from "../Base/NSSet"; -import NSIdentity from "../Base/NSIdentity"; -import IdResolver from "../Base/IdResolver"; -import GrimoireInterface from "../Interface/GrimoireInterface"; -import Constants from "../Base/Constants"; -import {Name} from "../Base/Types"; +import Ensure from "../Tools/Ensure"; +import NSDictionary from "../Tools/NSDictionary"; +import NSSet from "../Tools/NSSet"; +import NSIdentity from "../Core/NSIdentity"; +import IdResolver from "../Tools/IdResolver"; +import GrimoireInterface from "../Core/GrimoireInterface"; +import Constants from "../Tools/Constants"; +import { Name } from "../Tools/Types"; export default class NodeDeclaration { public defaultComponents: NSSet; diff --git a/src/Interface/NodeInterface.ts b/src/Core/NodeInterface.ts similarity index 97% rename from src/Interface/NodeInterface.ts rename to src/Core/NodeInterface.ts index b4553742e..35dc8eaa0 100644 --- a/src/Interface/NodeInterface.ts +++ b/src/Core/NodeInterface.ts @@ -1,9 +1,9 @@ -import Utility from "../Base/Utility"; -import XMLReader from "../Base/XMLReader"; -import GomlParser from "../Node/GomlParser"; -import Attribute from "../Node/Attribute"; -import GomlNode from "../Node/GomlNode"; -import {Name, Nullable} from "../Base/Types"; +import Utility from "../Tools/Utility"; +import XMLReader from "../Tools/XMLReader"; +import GomlParser from "../Core/GomlParser"; +import Attribute from "../Core/Attribute"; +import GomlNode from "../Core/GomlNode"; +import {Name, Nullable} from "../Tools/Types"; import { ListenerFn } from "eventemitter3"; /** diff --git a/src/Node/NodeUtility.ts b/src/Core/NodeUtility.ts similarity index 100% rename from src/Node/NodeUtility.ts rename to src/Core/NodeUtility.ts diff --git a/src/Declaration/IAttributeConverterDeclaration.ts b/src/Interface/IAttributeConverterDeclaration.ts similarity index 52% rename from src/Declaration/IAttributeConverterDeclaration.ts rename to src/Interface/IAttributeConverterDeclaration.ts index 2ee3611e7..35156b63c 100644 --- a/src/Declaration/IAttributeConverterDeclaration.ts +++ b/src/Interface/IAttributeConverterDeclaration.ts @@ -1,10 +1,9 @@ -import Attribute from "../Node/Attribute"; -import {Name} from "../Base/Types"; +import Attribute from "../Core/Attribute"; +import {Name} from "../Tools/Types"; -interface IAttributeConverterDeclaration { +export default interface IAttributeConverterDeclaration { name: Name; [params: string]: any; verify(attr: Attribute): void; // throw error if attribute is not satisfy condition converter needed. convert(val: any, attr: Attribute): any; } -export default IAttributeConverterDeclaration; diff --git a/src/Interface/IAttributeDeclaration.ts b/src/Interface/IAttributeDeclaration.ts new file mode 100644 index 000000000..397a6517c --- /dev/null +++ b/src/Interface/IAttributeDeclaration.ts @@ -0,0 +1,8 @@ +import {Name} from "../Tools/Types"; + +export default interface IAttributeDeclaration { + converter: Name; + default: any; + [parameters: string]: any; +} + diff --git a/src/Interface/ITreeInitializedInfo.ts b/src/Interface/ITreeInitializedInfo.ts new file mode 100644 index 000000000..a16bdfc59 --- /dev/null +++ b/src/Interface/ITreeInitializedInfo.ts @@ -0,0 +1,4 @@ +export default interface ITreeInitializedInfo { + ownerScriptTag: HTMLScriptElement; + id: string; +} \ No newline at end of file diff --git a/src/Node/IAttributeDeclaration.ts b/src/Node/IAttributeDeclaration.ts deleted file mode 100644 index 58977ce6a..000000000 --- a/src/Node/IAttributeDeclaration.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {Name} from "../Base/Types"; - -interface IAttributeDeclaration { - converter: Name; - default: any; - [parameters: string]: any; -} - -export default IAttributeDeclaration; diff --git a/src/Node/ITreeInitializedInfo.ts b/src/Node/ITreeInitializedInfo.ts deleted file mode 100644 index 2f204e94c..000000000 --- a/src/Node/ITreeInitializedInfo.ts +++ /dev/null @@ -1,6 +0,0 @@ -interface ITreeInitializedInfo { - ownerScriptTag: HTMLScriptElement; - id: string; -} - -export default ITreeInitializedInfo; diff --git a/src/Base/Constants.ts b/src/Tools/Constants.ts similarity index 87% rename from src/Base/Constants.ts rename to src/Tools/Constants.ts index 6e4201f6f..d61335202 100644 --- a/src/Base/Constants.ts +++ b/src/Tools/Constants.ts @@ -1,5 +1,3 @@ -// import NSIdentity from "./NSIdentity"; - export default class Constants { public static get defaultNamespace(): string { return "grimoirejs"; diff --git a/src/Base/Ensure.ts b/src/Tools/Ensure.ts similarity index 95% rename from src/Base/Ensure.ts rename to src/Tools/Ensure.ts index b35eda6d2..e7b1a1767 100644 --- a/src/Base/Ensure.ts +++ b/src/Tools/Ensure.ts @@ -1,10 +1,10 @@ -import GrimoireInterface from "../Interface/GrimoireInterface"; -import NSIdentity from "./NSIdentity"; +import GrimoireInterface from "../Core/GrimoireInterface"; +import NSIdentity from "../Core/NSIdentity"; // import Namespace from "./Namespace"; import NSDictionary from "./NSDictionary"; import {Name, Nullable, Ctor, ComponentRegistering} from "./Types"; -import ComponentDeclaration from "../Node/ComponentDeclaration"; -import Component from "../Node/Component"; +import ComponentDeclaration from "../Core/ComponentDeclaration"; +import Component from "../Core/Component"; /** * Provides static methods to ensure arguments are valid type. */ diff --git a/src/Base/IdResolver.ts b/src/Tools/IdResolver.ts similarity index 97% rename from src/Base/IdResolver.ts rename to src/Tools/IdResolver.ts index 5c8419d83..1ef06216e 100644 --- a/src/Base/IdResolver.ts +++ b/src/Tools/IdResolver.ts @@ -1,5 +1,5 @@ -import Namespace from "./Namespace"; -import NSIdentity from "./NSIdentity"; +import Namespace from "../Core/Namespace"; +import NSIdentity from "../Core/NSIdentity"; /** diff --git a/src/Base/MessageException.ts b/src/Tools/MessageException.ts similarity index 96% rename from src/Base/MessageException.ts rename to src/Tools/MessageException.ts index 545839aa7..a47a7c0a2 100644 --- a/src/Base/MessageException.ts +++ b/src/Tools/MessageException.ts @@ -1,5 +1,6 @@ -import GomlNode from "../Node/GomlNode"; -import Component from "../Node/Component"; +import GomlNode from "../Core/GomlNode"; +import Component from "../Core/Component"; + /** * Exception representing uncought error caused in message function. * Do not thorow this error manually. diff --git a/src/Base/NSDictionary.ts b/src/Tools/NSDictionary.ts similarity index 97% rename from src/Base/NSDictionary.ts rename to src/Tools/NSDictionary.ts index 6b663e309..dd586e644 100644 --- a/src/Base/NSDictionary.ts +++ b/src/Tools/NSDictionary.ts @@ -1,6 +1,6 @@ -import NSIdentity from "./NSIdentity"; +import NSIdentity from "../Core/NSIdentity"; import IdResolver from "./IdResolver"; -import Namespace from "./Namespace"; +import Namespace from "../Core/Namespace"; import Ensure from "./Ensure"; import {Name, Nullable, Undef} from "./Types"; diff --git a/src/Base/NSSet.ts b/src/Tools/NSSet.ts similarity index 96% rename from src/Base/NSSet.ts rename to src/Tools/NSSet.ts index 9f4960808..bdd8505fd 100644 --- a/src/Base/NSSet.ts +++ b/src/Tools/NSSet.ts @@ -1,4 +1,4 @@ -import NSIdentity from "./NSIdentity"; +import NSIdentity from "../Core/NSIdentity"; /** * set of NSIdentity diff --git a/src/Base/Types.ts b/src/Tools/Types.ts similarity index 68% rename from src/Base/Types.ts rename to src/Tools/Types.ts index cb58622ea..2677c0a75 100644 --- a/src/Base/Types.ts +++ b/src/Tools/Types.ts @@ -1,9 +1,9 @@ -import NSIdentity from "./NSIdentity"; -import GomlInterfaceImpl from "../Interface/GomlInterfaceImpl"; -import GomlNode from "../Node/GomlNode"; -import GrimoireInterfaceImpl from "../Interface/GrimoireInterfaceImpl"; -import NodeInterface from "../Interface/NodeInterface"; -import IAttributeDeclaration from "../Node/IAttributeDeclaration"; +import NSIdentity from "../Core/NSIdentity"; +import GomlInterfaceImpl from "../Core/GomlInterfaceImpl"; +import GomlNode from "../Core/GomlNode"; +import GrimoireInterfaceImpl from "../Core/GrimoireInterfaceImpl"; +import NodeInterface from "../Core/NodeInterface"; +import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; export type Name = string | NSIdentity; export type GomlInterface = GomlInterfaceImpl & IGomlInterface; diff --git a/src/Base/Utility.ts b/src/Tools/Utility.ts similarity index 96% rename from src/Base/Utility.ts rename to src/Tools/Utility.ts index 2fadb536f..5602c69ce 100644 --- a/src/Base/Utility.ts +++ b/src/Tools/Utility.ts @@ -1,4 +1,4 @@ -import GrimoireInterface from "../Interface/GrimoireInterface"; +import GrimoireInterface from "../Core/GrimoireInterface"; export default class Utility { diff --git a/src/Base/XMLHttpRequestAsync.ts b/src/Tools/XMLHttpRequestAsync.ts similarity index 100% rename from src/Base/XMLHttpRequestAsync.ts rename to src/Tools/XMLHttpRequestAsync.ts diff --git a/src/Base/XMLReader.ts b/src/Tools/XMLReader.ts similarity index 100% rename from src/Base/XMLReader.ts rename to src/Tools/XMLReader.ts diff --git a/src/main.ts b/src/main.ts index 6ab98488e..0af03cea2 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,5 @@ -import GrimoireInterface from "./Interface/GrimoireInterface"; -import GomlLoader from "./Node/GomlLoader"; +import GrimoireInterface from "./Core/GrimoireInterface"; +import GomlLoader from "./Core/GomlLoader"; /** * Provides procedures for initializing. diff --git a/test/@/GrimoireInterfaceTest.ts b/test/@/GrimoireInterfaceTest.ts index 22e76db1d..4a1f79c9e 100644 --- a/test/@/GrimoireInterfaceTest.ts +++ b/test/@/GrimoireInterfaceTest.ts @@ -5,12 +5,12 @@ import test from "ava"; import sinon from "sinon"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import Constants from "../../src/Base/Constants"; -import Component from "../../src/Node/Component"; -import GomlParser from "../../src/Node/GomlParser"; -import GomlLoader from "../../src/Node/GomlLoader"; +import Component from "../../src/Core/Component"; +import GomlParser from "../../src/Core/GomlParser"; +import GomlLoader from "../../src/Core/GomlLoader"; import NSIdentity from "../../src/Base/NSIdentity"; import Namespace from "../../src/Base/Namespace"; -import GomlNode from "../../src/Node/GomlNode"; +import GomlNode from "../../src/Core/GomlNode"; declare namespace global { let Node: any; diff --git a/test/Base/AttributeManagerTest.ts b/test/Base/AttributeManagerTest.ts index 76cfd83f7..86d6a877b 100644 --- a/test/Base/AttributeManagerTest.ts +++ b/test/Base/AttributeManagerTest.ts @@ -6,7 +6,7 @@ import NSDictionary from "../../src/Base/NSDictionary"; import AttributeManager from "../../src/Base/AttributeManager"; import NSIdentity from "../../src/Base/NSIdentity"; import Constants from "../../src/Base/Constants"; -import Attribute from "../../src/Node/Attribute"; +import Attribute from "../../src/Core/Attribute"; import sinon from "sinon"; const genAttr: (name: NSIdentity, watch?: Function | undefined) => Attribute = (name, watch) => { diff --git a/test/Base/IdResolverTest.ts b/test/Base/IdResolverTest.ts index 8873c3a44..2869830bc 100644 --- a/test/Base/IdResolverTest.ts +++ b/test/Base/IdResolverTest.ts @@ -5,10 +5,10 @@ import xmldom from "xmldom"; import sinon from "sinon"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import Constants from "../../src/Base/Constants"; -import Component from "../../src/Node/Component"; -import GomlParser from "../../src/Node/GomlParser"; -import GomlLoader from "../../src/Node/GomlLoader"; -import GomlNode from "../../src/Node/GomlNode"; +import Component from "../../src/Core/Component"; +import GomlParser from "../../src/Core/GomlParser"; +import GomlLoader from "../../src/Core/GomlLoader"; +import GomlNode from "../../src/Core/GomlNode"; import NSIdentity from "../../src/Base/NSIdentity"; import Namespace from "../../src/Base/Namespace"; import IdResolver from "../../src/Base/IdResolver"; diff --git a/test/Base/NSIdentityTest.ts b/test/Base/NSIdentityTest.ts index 0acee00e0..b16a902fb 100644 --- a/test/Base/NSIdentityTest.ts +++ b/test/Base/NSIdentityTest.ts @@ -5,10 +5,10 @@ import xmldom from "xmldom"; import sinon from "sinon"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import Constants from "../../src/Base/Constants"; -import Component from "../../src/Node/Component"; -import GomlParser from "../../src/Node/GomlParser"; -import GomlLoader from "../../src/Node/GomlLoader"; -import GomlNode from "../../src/Node/GomlNode"; +import Component from "../../src/Core/Component"; +import GomlParser from "../../src/Core/GomlParser"; +import GomlLoader from "../../src/Core/GomlLoader"; +import GomlNode from "../../src/Core/GomlNode"; import NSIdentity from "../../src/Base/NSIdentity"; diff --git a/test/Base/NamespaceTest.ts b/test/Base/NamespaceTest.ts index d232e0561..1ac3ae68b 100644 --- a/test/Base/NamespaceTest.ts +++ b/test/Base/NamespaceTest.ts @@ -5,10 +5,10 @@ import xmldom from "xmldom"; import sinon from "sinon"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import Constants from "../../src/Base/Constants"; -import Component from "../../src/Node/Component"; -import GomlParser from "../../src/Node/GomlParser"; -import GomlLoader from "../../src/Node/GomlLoader"; -import GomlNode from "../../src/Node/GomlNode"; +import Component from "../../src/Core/Component"; +import GomlParser from "../../src/Core/GomlParser"; +import GomlLoader from "../../src/Core/GomlLoader"; +import GomlNode from "../../src/Core/GomlNode"; import Namespace from "../../src/Base/Namespace"; test("constructor is works correctly.", (t) => { diff --git a/test/Base/NamespacedDictionaryTest.ts b/test/Base/NamespacedDictionaryTest.ts index 9eb989c1a..cf61873fd 100644 --- a/test/Base/NamespacedDictionaryTest.ts +++ b/test/Base/NamespacedDictionaryTest.ts @@ -3,7 +3,7 @@ import "../XMLDomInit"; import test from "ava"; import sinon from "sinon"; import xhrmock from "xhr-mock"; -import GomlLoader from "../../src/Node/GomlLoader"; +import GomlLoader from "../../src/Core/GomlLoader"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import NodeInterface from "../../src/Interface/NodeInterface"; import NSIdentity from "../../src/Base/NSIdentity"; diff --git a/test/Interfaces/NodeInterfaceTest.ts b/test/Interfaces/NodeInterfaceTest.ts index 09e3ea872..6daa147c6 100644 --- a/test/Interfaces/NodeInterfaceTest.ts +++ b/test/Interfaces/NodeInterfaceTest.ts @@ -21,8 +21,8 @@ import { conflictNode2, conflictComponent1, conflictComponent2 -} from "../Node/GomlParserTest_Registering"; -import GomlLoader from "../../src/Node/GomlLoader"; +} from "../Core/GomlParserTest_Registering"; +import GomlLoader from "../../src/Core/GomlLoader"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import fs from "../fileHelper"; diff --git a/test/Node/GomlLoaderTest.ts b/test/Node/GomlLoaderTest.ts index e13d503d9..6ff0afc87 100644 --- a/test/Node/GomlLoaderTest.ts +++ b/test/Node/GomlLoaderTest.ts @@ -7,7 +7,7 @@ import sinon from "sinon"; import xhrmock from "xhr-mock"; import XMLReader from "../../src/Base/XMLReader"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import GomlParser from "../../src/Node/GomlParser"; +import GomlParser from "../../src/Core/GomlParser"; import fs from "../fileHelper"; import { goml, @@ -51,7 +51,7 @@ xhrmock.get("http://grimoire.gl/index3.goml", (req, res) => { }); function mockXMLParse(func) { - return prequire("../../src/Node/GomlLoader", { + return prequire("../../src/Core/GomlLoader", { "../Base/XMLReader": { default: { parseXML: (srcHtml) => { diff --git a/test/Node/GomlNode2Test.ts b/test/Node/GomlNode2Test.ts index f8a1059be..7e7eb17a7 100644 --- a/test/Node/GomlNode2Test.ts +++ b/test/Node/GomlNode2Test.ts @@ -21,10 +21,10 @@ import { conflictComponent1, conflictComponent2 } from "./GomlParserTest_Registering"; -import GomlLoader from "../../src/Node/GomlLoader"; -import GomlNode from "../../src/Node/GomlNode"; -import Component from "../../src/Node/Component"; -import Attribute from "../../src/Node/Attribute"; +import GomlLoader from "../../src/Core/GomlLoader"; +import GomlNode from "../../src/Core/GomlNode"; +import Component from "../../src/Core/Component"; +import Attribute from "../../src/Core/Attribute"; import NSIdentity from "../../src/Base/NSIdentity"; import GrimoireComponent from "../../src/Components/GrimoireComponent"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; diff --git a/test/Node/GomlNodeTest.ts b/test/Node/GomlNodeTest.ts index 23b26c670..b30d88c3f 100644 --- a/test/Node/GomlNodeTest.ts +++ b/test/Node/GomlNodeTest.ts @@ -5,12 +5,12 @@ import test from "ava"; import sinon from "sinon"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import Constants from "../../src/Base/Constants"; -import Component from "../../src/Node/Component"; -import GomlParser from "../../src/Node/GomlParser"; -import GomlLoader from "../../src/Node/GomlLoader"; +import Component from "../../src/Core/Component"; +import GomlParser from "../../src/Core/GomlParser"; +import GomlLoader from "../../src/Core/GomlLoader"; import NSIdentity from "../../src/Base/NSIdentity"; -import GomlNode from "../../src/Node/GomlNode"; -import Attribute from "../../src/Node/Attribute"; +import GomlNode from "../../src/Core/GomlNode"; +import Attribute from "../../src/Core/Attribute"; declare namespace global { let Node: any; diff --git a/test/Node/GomlParserTest.ts b/test/Node/GomlParserTest.ts index 55041b1f2..916cec5ea 100644 --- a/test/Node/GomlParserTest.ts +++ b/test/Node/GomlParserTest.ts @@ -2,7 +2,7 @@ require("babel-polyfill"); import "../XMLDomInit"; import test from "ava"; import sinon from "sinon"; -import GomlParser from "../../src/Node/GomlParser"; +import GomlParser from "../../src/Core/GomlParser"; import xmldom from "xmldom"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import NSIdentity from "../../src/Base/NSIdentity"; diff --git a/test/Node/NamespacedSetTest.ts b/test/Node/NamespacedSetTest.ts index 0ac860350..f25d429f3 100644 --- a/test/Node/NamespacedSetTest.ts +++ b/test/Node/NamespacedSetTest.ts @@ -1,6 +1,6 @@ import "../XMLDomInit"; import test from "ava"; -import GomlParser from "../../src/Node/GomlParser"; +import GomlParser from "../../src/Core/GomlParser"; import xmldom from "xmldom"; import NSSet from "../../src/Base/NSSet"; import NSIdentity from "../../src/Base/NSIdentity"; diff --git a/test/PageLoadingHelper.ts b/test/PageLoadingHelper.ts index 3ab362c7d..0601334d8 100644 --- a/test/PageLoadingHelper.ts +++ b/test/PageLoadingHelper.ts @@ -1,5 +1,5 @@ -import GrimoireInterface from "../src/Interface/GrimoireInterface"; -import GomlLoader from "../src/Node/GomlLoader"; +import GrimoireInterface from "../src/Core/GrimoireInterface"; +import GomlLoader from "../src/Core/GomlLoader"; import xhrmock from "xhr-mock"; import { From 8bc11307948c2727e52458c2e9522690ba1122a5 Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 15 Sep 2017 17:15:06 +0900 Subject: [PATCH 006/146] [refactor] change test directory structure --- src/Core/GrimoireInterfaceImpl.ts | 3 +++ src/Tools/XMLReader.ts | 8 +++----- ...ParserTest_Registering.ts => DummyObjectRegisterer.ts} | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) rename test/{Node/GomlParserTest_Registering.ts => DummyObjectRegisterer.ts} (98%) diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 85fe75352..fd0e6b5ae 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -155,6 +155,8 @@ export default class GrimoireInterfaceImpl extends EEObject { } name = obj.componentName; } + + // argument validation name = this._ensureTobeNSIdentityOnRegister(name); if (this.componentDeclarations.get(name)) { throw new Error(`component ${name.fqn} is already registerd.`); @@ -174,6 +176,7 @@ export default class GrimoireInterfaceImpl extends EEObject { throw new Error(`default value of attribute ${key} in ${name.fqn} must be not 'undefined'.`); } } + const dec = new ComponentDeclaration(name, obj, superComponent); this.componentDeclarations.set(name, dec); return dec; diff --git a/src/Tools/XMLReader.ts b/src/Tools/XMLReader.ts index 9c7d0e4d6..d1ce36a77 100644 --- a/src/Tools/XMLReader.ts +++ b/src/Tools/XMLReader.ts @@ -3,7 +3,7 @@ import {Nullable} from "./Types"; /** * Provides safe xml read feature. */ -class XMLReader { +export default class XMLReader { private static _parser: DOMParser = new DOMParser(); @@ -88,7 +88,5 @@ class XMLReader { } } return result; - } -} - -export default XMLReader; + } +} \ No newline at end of file diff --git a/test/Node/GomlParserTest_Registering.ts b/test/DummyObjectRegisterer.ts similarity index 98% rename from test/Node/GomlParserTest_Registering.ts rename to test/DummyObjectRegisterer.ts index f7f1addc8..4d814b767 100644 --- a/test/Node/GomlParserTest_Registering.ts +++ b/test/DummyObjectRegisterer.ts @@ -1,4 +1,4 @@ -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; +import GrimoireInterface from "../src/Core/GrimoireInterface"; import sinon from "sinon"; export function testComponent1() { From 626de1a7d64f1584429bbb866adfaba1352e7da2 Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 15 Sep 2017 17:17:24 +0900 Subject: [PATCH 007/146] [add] string converter test --- test/Converters/StringConverterTest.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/Converters/StringConverterTest.ts b/test/Converters/StringConverterTest.ts index ea35ad9a5..1b1df7029 100644 --- a/test/Converters/StringConverterTest.ts +++ b/test/Converters/StringConverterTest.ts @@ -3,4 +3,6 @@ import StringConverter from "../../src/Converters/StringConverter"; test("StringConverter should convert collectly", t => { t.truthy(StringConverter("HELLO") === "HELLO"); + t.truthy(StringConverter(null) === null); + t.truthy(StringConverter(123) === "123"); }); From a4c7319d5bfb6635b27b2bec196bbf1ee4477198 Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 15 Sep 2017 18:23:11 +0900 Subject: [PATCH 008/146] fix: expose XMLReader dependency on DOMParser --- src/Tools/XMLReader.ts | 8 ++++---- src/main.ts | 8 +++++++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/Tools/XMLReader.ts b/src/Tools/XMLReader.ts index d1ce36a77..6b592a1ca 100644 --- a/src/Tools/XMLReader.ts +++ b/src/Tools/XMLReader.ts @@ -1,14 +1,14 @@ -import {Nullable} from "./Types"; +import { Nullable } from "./Types"; /** * Provides safe xml read feature. */ export default class XMLReader { - private static _parser: DOMParser = new DOMParser(); + public static parser: DOMParser; public static parseXML(doc: string, rootElementName?: string): Element[] { - const parsed = XMLReader._parser.parseFromString(doc as string, "text/xml"); + const parsed = XMLReader.parser.parseFromString(doc as string, "text/xml"); if (!parsed || parsed.getElementsByTagName("parsererror").length > 0) { const err = new XMLSerializer().serializeToString(parsed); throw new Error(`Error parsing XML: ${err}`); @@ -89,4 +89,4 @@ export default class XMLReader { } return result; } -} \ No newline at end of file +} diff --git a/src/main.ts b/src/main.ts index 0af03cea2..ce62dddfa 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,6 @@ import GrimoireInterface from "./Core/GrimoireInterface"; import GomlLoader from "./Core/GomlLoader"; +import XMLReader from "./Tools/XMLReader"; /** * Provides procedures for initializing. @@ -14,6 +15,7 @@ class GrimoireInitializer { try { GrimoireInitializer._notifyLibraryLoadingToWindow(); GrimoireInitializer._copyGLConstants(); + GrimoireInitializer._injectDependency(); GrimoireInterface.initialize(); await GrimoireInitializer._waitForDOMLoading(); GrimoireInitializer._logVersions(); @@ -26,6 +28,10 @@ class GrimoireInitializer { } } + private static _injectDependency(): void { + XMLReader.parser = new DOMParser(); + } + /** * Ensure WebGLRenderingContext.[CONSTANTS] is exisiting. * Some of the browsers contains them in prototype. @@ -84,7 +90,7 @@ class GrimoireInitializer { /** * Just start the process. */ -export default function(): typeof GrimoireInterface { +export default function (): typeof GrimoireInterface { GrimoireInitializer.initialize(); GrimoireInterface.noConflictPreserve = (window as any)["gr"]; return (window as any)["gr"] = (window as any)["GrimoireJS"] = GrimoireInterface; From 0fe87b12d3bc3b532be498e62b3bf499aaa8b2ea Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Sep 2017 16:58:06 +0900 Subject: [PATCH 009/146] fix: refactor AttributeManagerTest --- test/Base/AttributeManagerTest.ts | 81 ------------------- test/Core/AttributeManagerTest.ts | 124 ++++++++++++++++++++++++++++++ test/PageLoadingHelper.ts | 2 +- test/TestEnvManager.ts | 24 ++++++ test/TestUtil.ts | 34 ++++++++ 5 files changed, 183 insertions(+), 82 deletions(-) delete mode 100644 test/Base/AttributeManagerTest.ts create mode 100644 test/Core/AttributeManagerTest.ts create mode 100644 test/TestEnvManager.ts create mode 100644 test/TestUtil.ts diff --git a/test/Base/AttributeManagerTest.ts b/test/Base/AttributeManagerTest.ts deleted file mode 100644 index 86d6a877b..000000000 --- a/test/Base/AttributeManagerTest.ts +++ /dev/null @@ -1,81 +0,0 @@ -import "../XMLDomInit"; -import test from "ava"; -import Ensure from "../../src/Base/Ensure"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import NSDictionary from "../../src/Base/NSDictionary"; -import AttributeManager from "../../src/Base/AttributeManager"; -import NSIdentity from "../../src/Base/NSIdentity"; -import Constants from "../../src/Base/Constants"; -import Attribute from "../../src/Core/Attribute"; -import sinon from "sinon"; - -const genAttr: (name: NSIdentity, watch?: Function | undefined) => Attribute = (name, watch) => { - return { name: name, watch: watch, Value: "value of " + name } as Attribute; -}; - -const ns1 = NSIdentity.fromFQN("aaa"); -const ns2 = NSIdentity.fromFQN("ns.bbb"); -const ns3 = NSIdentity.fromFQN("ns.hoge.ccc"); - -const genAM = () => { - const am = new AttributeManager("tag"); - am.addAttribute(genAttr(ns1, new Function())); - am.addAttribute(genAttr(ns2, new Function())); - am.addAttribute(genAttr(ns3, new Function())); - return am; -}; - -test("test", (t) => { - const am = genAM(); - let count = 0; - for (let key in am["_attributesFQNMap"]) { - count += am["_attributesFQNMap"][key].length; - } - t.truthy(count === 3); - t.truthy(!!am.getAttribute(ns1.name)); -}); - -test("test addAttribute", (t) => { - const am = genAM(); - let l = 0; - for (let key in am["_attributesFQNMap"]) { - l += am["_attributesFQNMap"][key].length; - } - am.addAttribute(genAttr(ns1)); - let count = 0; - for (let key in am["_attributesFQNMap"]) { - count += am["_attributesFQNMap"][key].length; - } - t.truthy(count === l + 1); - am.addAttribute(genAttr(ns1)); - count = 0; - for (let key in am["_attributesFQNMap"]) { - count += am["_attributesFQNMap"][key].length; - } - t.truthy(count === l + 2); -}); - -test("test watch", () => { - const am = genAM(); - const spy1 = sinon.spy(); - const spy2 = sinon.spy(); - am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"), () => { - spy1("watch"); - })); - am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"), () => { - spy2("watch"); - })); - am.watch(NSIdentity.guess("hoge.aaa"), (a, b, c) => { /*do nothing*/ }); - sinon.assert.called(spy1); - sinon.assert.called(spy2); -}); - -test("test set/getAttribute", (t) => { - const am = genAM(); - am.setAttribute("aaa", "hoge"); - t.truthy(am.getAttribute("aaa") === "hoge"); - am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"))); - t.throws(() => { - am.getAttribute("aaa"); - }); -}); diff --git a/test/Core/AttributeManagerTest.ts b/test/Core/AttributeManagerTest.ts new file mode 100644 index 000000000..75be1e758 --- /dev/null +++ b/test/Core/AttributeManagerTest.ts @@ -0,0 +1,124 @@ +import test from "ava"; +import Ensure from "../../src/Tools/Ensure"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import NSDictionary from "../../src/Tools/NSDictionary"; +import AttributeManager from "../../src/Core/AttributeManager"; +import NSIdentity from "../../src/Core/NSIdentity"; +import Constants from "../../src/Tools/Constants"; +import Attribute from "../../src/Core/Attribute"; +import sinon from "sinon"; +import ComponentDeclaration from "../../src/Core/ComponentDeclaration"; +import TestUtil from "../TestUtil"; + +const genAttr: (name: NSIdentity, watch?: Function | undefined) => Attribute = (name, watch) => { + return { name: name, watch: watch, Value: "value of " + name } as Attribute; +}; + +const ns1 = NSIdentity.fromFQN("aaa"); +const ns2 = NSIdentity.fromFQN("ns.bbb"); +const ns3 = NSIdentity.fromFQN("ns.hoge.ccc"); + +const genAM = () => { + const am = new AttributeManager("tag"); + am.addAttribute(genAttr(ns1, new Function())); + am.addAttribute(genAttr(ns2, new Function())); + am.addAttribute(genAttr(ns3, new Function())); + return am; +}; + +test("check init for attribute manager", (t) => { + const am = genAM(); + let count = 0; + for (let key in am["_attributesFQNMap"]) { + count += am["_attributesFQNMap"][key].length; + } + t.truthy(count === 3); + t.truthy(!!am.getAttribute(ns1.name)); +}); + +test("simple addAttribute should works correctly", (t) => { + const am = genAM(); + let l = 0; + for (let key in am["_attributesFQNMap"]) { + l += am["_attributesFQNMap"][key].length; + } + am.addAttribute(genAttr(ns1)); + let count = 0; + for (let key in am["_attributesFQNMap"]) { + count += am["_attributesFQNMap"][key].length; + } + t.truthy(count === l + 1); + am.addAttribute(genAttr(ns1)); + count = 0; + for (let key in am["_attributesFQNMap"]) { + count += am["_attributesFQNMap"][key].length; + } + t.truthy(count === l + 2); +}); + +test("addAttribute with value/watch buffers should works correctly", (t) => { + const fqn = "notregisterd.fqn.hoge"; + const am = genAM(); + am.setAttribute(fqn, "hogehoge"); + t.truthy(am.getAttribute(fqn) === "hogehoge"); + let attr = genAttr(NSIdentity.fromFQN(fqn)); + am.addAttribute(attr); + t.truthy(am.getAttribute(fqn) === "hogehoge"); + t.truthy(attr.Value === "hogehoge"); + + const fqn2 = "notregisterd.fqn.hoge2"; + const spy = sinon.spy(); + const attrRaw = new Attribute(); + attrRaw.name = NSIdentity.fromFQN(fqn2); + attrRaw.component = { isActive: true } as any; + attrRaw.converter = { convert: x => x } as any; + am.watch(fqn2, (n, o, a) => { + spy(n, o, a); + }); + + am.setAttribute(attrRaw.name.fqn, "not called"); + t.truthy(!sinon.called); + am.addAttribute(attrRaw); + am.setAttribute(attrRaw.name.fqn, "called"); + + t.truthy("not called" === spy.args[0][0]); + t.truthy(void 0 === spy.args[0][1]); + t.truthy(attrRaw === spy.args[0][2]); + + t.truthy("called" === spy.args[1][0]); + t.truthy("not called" === spy.args[1][1]); + t.truthy(attrRaw === spy.args[1][2]); +}); + +test("watch should works correctly", () => { + const am = genAM(); + const spy1 = sinon.spy(); + const spy2 = sinon.spy(); + const notCalledSpy = sinon.spy(); + am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"), () => { + spy1("watch"); + })); + am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"), () => { + spy2("watch"); + })); + am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.bbbbbb"), () => { + notCalledSpy("watch"); + })); + am.watch(NSIdentity.guess("hoge.aaa"), (a, b, c) => { /*do nothing*/ }); + sinon.assert.called(spy1); + sinon.assert.called(spy2); + sinon.assert.notCalled(notCalledSpy); +}); + +test("set/getAttribute should works correctly", (t) => { + const am = genAM(); + am.setAttribute("aaa", "hoge"); + t.truthy(am.getAttribute("aaa") === "hoge"); + am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"))); + t.throws(() => { + am.getAttribute("aaa"); // ambiguous + }); + t.throws(() => { + am.getAttribute("notexists"); // not found + }); +}); diff --git a/test/PageLoadingHelper.ts b/test/PageLoadingHelper.ts index 0601334d8..29badc697 100644 --- a/test/PageLoadingHelper.ts +++ b/test/PageLoadingHelper.ts @@ -18,7 +18,7 @@ import { conflictNode2, conflictComponent1, conflictComponent2 -} from "./Node/GomlParserTest_Registering"; +} from "./DummyObjectRegisterer"; declare namespace global { let Node: any; diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts new file mode 100644 index 000000000..646aec6b7 --- /dev/null +++ b/test/TestEnvManager.ts @@ -0,0 +1,24 @@ +import XMLReader from "../src/Tools/XMLReader"; +import xmldom from "xmldom"; +import Attribute from "../src/Core/Attribute"; +import IAttributeConverterDeclaration from "../src/Interface/IAttributeConverterDeclaration"; +import IConverterRepository from "../src/Interface/Repository/IConverterRepository"; +import NSDictionary from "../src/Tools/NSDictionary"; +import NSIdentity from "../src/Core/NSIdentity"; + +class TestEnvContext implements IConverterRepository { + public converters: NSDictionary; + +} + +export default class TestEnvManager { + public static context = new TestEnvContext(); + public static addConverter(name: NSIdentity, converter: IAttributeConverterDeclaration) { + this.context.converters.set(name, converter); + } + + public static init() { + XMLReader.parser = new xmldom.DOMParser(); + // Attribute.converterRepository = TestEnvManager.context; + } +} diff --git a/test/TestUtil.ts b/test/TestUtil.ts new file mode 100644 index 000000000..bebc1d4a4 --- /dev/null +++ b/test/TestUtil.ts @@ -0,0 +1,34 @@ +import Component from "../src/Core/Component"; +import ComponentDeclaration from "../src/Core/ComponentDeclaration"; +import NSIdentity from "../src/Core/NSIdentity"; +import Attribute from "../src/Core/Attribute"; +import IAttributeDeclaration from "../src/Interface/IAttributeDeclaration"; +import Ensure from "../src/Tools/Ensure"; +import GrimoireInterface from "../src/Core/GrimoireInterface"; + +export default class TestUtil { + + public static DummyComponentDeclaration(): ComponentDeclaration { + return new ComponentDeclaration(NSIdentity.fromFQN("aaa"), { + attributes: { + + } + }); + } + public static DummyComponent(): Component { + const dec = TestUtil.DummyComponentDeclaration(); + return dec.generateInstance(null); + } + + public static DummyAttribute(name: NSIdentity, component: Component, declaration: IAttributeDeclaration): Attribute { + const attr = new Attribute(); + attr.name = name; + attr.component = component; + attr.declaration = declaration; + const converterName = Ensure.tobeNSIdentity(declaration.converter); + attr.converter = GrimoireInterface.converters.get(converterName); + attr.component.attributes.set(attr.name, attr); + attr.converter.verify(attr); + return attr; + } +} From 8b52a10a0c534bd792460c0097befbcb58f49e0d Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Sep 2017 17:53:39 +0900 Subject: [PATCH 010/146] fix: refactor test structure --- test/Core/AttributeTest.ts | 5 +++++ test/Core/ComponentDeclarationTest.ts | 5 +++++ test/Core/ComponentTest.ts | 5 +++++ test/{Node => Core}/GomlLoaderTest.ts | 14 +++++++----- test/{Node => Core}/GomlNode2Test.ts | 12 +++++----- test/{Node => Core}/GomlNodeTest.ts | 11 +++++----- test/{Node => Core}/GomlParserTest.ts | 14 +++++------- test/{@ => Core}/GrimoireInterfaceTest.ts | 13 +++++------ test/{Base => Core}/NSIdentityTest.ts | 7 +++--- test/{Base => Core}/NamespaceTest.ts | 9 ++++---- .../{Interfaces => Core}/NodeInterfaceTest.ts | 12 +++++----- test/PageLoadingHelper.ts | 3 ++- test/{Base => Tools}/EnsureTest.ts | 21 +++++++++--------- test/{Base => Tools}/IdResolverTest.ts | 11 +++++----- .../NameDictionaryTest.ts} | 22 +++++++++---------- test/{Node => Tools}/NamespacedSetTest.ts | 5 ++--- test/{Base => Tools}/UtilityTest.ts | 3 +-- test/{Base => Tools}/XMLReaderTest.ts | 6 +++-- test/XMLDomInit.ts | 2 -- 19 files changed, 96 insertions(+), 84 deletions(-) create mode 100644 test/Core/AttributeTest.ts create mode 100644 test/Core/ComponentDeclarationTest.ts create mode 100644 test/Core/ComponentTest.ts rename test/{Node => Core}/GomlLoaderTest.ts (93%) rename test/{Node => Core}/GomlNode2Test.ts (98%) rename test/{Node => Core}/GomlNodeTest.ts (97%) rename test/{Node => Core}/GomlParserTest.ts (93%) rename test/{@ => Core}/GrimoireInterfaceTest.ts (96%) rename test/{Base => Core}/NSIdentityTest.ts (87%) rename test/{Base => Core}/NamespaceTest.ts (74%) rename test/{Interfaces => Core}/NodeInterfaceTest.ts (91%) rename test/{Base => Tools}/EnsureTest.ts (79%) rename test/{Base => Tools}/IdResolverTest.ts (87%) rename test/{Base/NamespacedDictionaryTest.ts => Tools/NameDictionaryTest.ts} (89%) rename test/{Node => Tools}/NamespacedSetTest.ts (75%) rename test/{Base => Tools}/UtilityTest.ts (89%) rename test/{Base => Tools}/XMLReaderTest.ts (75%) delete mode 100644 test/XMLDomInit.ts diff --git a/test/Core/AttributeTest.ts b/test/Core/AttributeTest.ts new file mode 100644 index 000000000..91deb5a73 --- /dev/null +++ b/test/Core/AttributeTest.ts @@ -0,0 +1,5 @@ +import test from "ava"; + +test("check init for attribute manager", (t) => { + t.truthy(true, "TODO: write test"); +}); diff --git a/test/Core/ComponentDeclarationTest.ts b/test/Core/ComponentDeclarationTest.ts new file mode 100644 index 000000000..91deb5a73 --- /dev/null +++ b/test/Core/ComponentDeclarationTest.ts @@ -0,0 +1,5 @@ +import test from "ava"; + +test("check init for attribute manager", (t) => { + t.truthy(true, "TODO: write test"); +}); diff --git a/test/Core/ComponentTest.ts b/test/Core/ComponentTest.ts new file mode 100644 index 000000000..91deb5a73 --- /dev/null +++ b/test/Core/ComponentTest.ts @@ -0,0 +1,5 @@ +import test from "ava"; + +test("check init for attribute manager", (t) => { + t.truthy(true, "TODO: write test"); +}); diff --git a/test/Node/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts similarity index 93% rename from test/Node/GomlLoaderTest.ts rename to test/Core/GomlLoaderTest.ts index 6ff0afc87..a7d92974e 100644 --- a/test/Node/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -1,14 +1,14 @@ -import "../AsyncSupport"; -import "../XMLDomInit"; +require("babel-polyfill"); import prequire from "proxyquire"; import jsdomAsync from "../JsDOMAsync"; import test from "ava"; import sinon from "sinon"; import xhrmock from "xhr-mock"; -import XMLReader from "../../src/Base/XMLReader"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; +import XMLReader from "../../src/Tools/XMLReader"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; import GomlParser from "../../src/Core/GomlParser"; import fs from "../fileHelper"; +import TestEnvManager from "../TestEnvManager"; import { goml, stringConverter, @@ -25,7 +25,9 @@ import { conflictNode2, conflictComponent1, conflictComponent2 -} from "./GomlParserTest_Registering"; +} from "../DummyObjectRegisterer"; + +TestEnvManager.init(); declare namespace global { let Node: any; @@ -52,7 +54,7 @@ xhrmock.get("http://grimoire.gl/index3.goml", (req, res) => { function mockXMLParse(func) { return prequire("../../src/Core/GomlLoader", { - "../Base/XMLReader": { + "../Tools/XMLReader": { default: { parseXML: (srcHtml) => { func(srcHtml); diff --git a/test/Node/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts similarity index 98% rename from test/Node/GomlNode2Test.ts rename to test/Core/GomlNode2Test.ts index 7e7eb17a7..9c2af56ee 100644 --- a/test/Node/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -1,9 +1,9 @@ -import "../AsyncSupport"; -import "../XMLDomInit"; +require("babel-polyfill"); import test from "ava"; import sinon from "sinon"; import xmldom from "xmldom"; import * as _ from "lodash"; +import TestEnvManager from "../TestEnvManager"; import { goml, stringConverter, @@ -20,17 +20,19 @@ import { conflictNode2, conflictComponent1, conflictComponent2 -} from "./GomlParserTest_Registering"; +} from "../DummyObjectRegisterer"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import Component from "../../src/Core/Component"; import Attribute from "../../src/Core/Attribute"; -import NSIdentity from "../../src/Base/NSIdentity"; +import NSIdentity from "../../src/Core/NSIdentity"; import GrimoireComponent from "../../src/Components/GrimoireComponent"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; import fs from "../fileHelper"; import PLH from "../PageLoadingHelper"; +TestEnvManager.init(); + const tc1_goml = fs.readFile("../_TestResource/GomlNodeTest_Case1.goml"); const tc1_html = fs.readFile("../_TestResource/GomlNodeTest_Case1.html"); diff --git a/test/Node/GomlNodeTest.ts b/test/Core/GomlNodeTest.ts similarity index 97% rename from test/Node/GomlNodeTest.ts rename to test/Core/GomlNodeTest.ts index b30d88c3f..f8c6f05ed 100644 --- a/test/Node/GomlNodeTest.ts +++ b/test/Core/GomlNodeTest.ts @@ -1,14 +1,13 @@ -import "../AsyncSupport"; -import "../XMLDomInit"; +require("babel-polyfill"); import xmldom from "xmldom"; import test from "ava"; import sinon from "sinon"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import Constants from "../../src/Base/Constants"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; import GomlParser from "../../src/Core/GomlParser"; import GomlLoader from "../../src/Core/GomlLoader"; -import NSIdentity from "../../src/Base/NSIdentity"; +import NSIdentity from "../../src/Core/NSIdentity"; import GomlNode from "../../src/Core/GomlNode"; import Attribute from "../../src/Core/Attribute"; @@ -24,7 +23,7 @@ global.Node = { test.beforeEach(async () => { GrimoireInterface.clear(); - const parser = new DOMParser(); + const parser = new xmldom.DOMParser(); const htmlDoc = parser.parseFromString("", "text/html"); global.document = htmlDoc; GrimoireInterface.registerNode("goml"); diff --git a/test/Node/GomlParserTest.ts b/test/Core/GomlParserTest.ts similarity index 93% rename from test/Node/GomlParserTest.ts rename to test/Core/GomlParserTest.ts index 916cec5ea..bb4f10cbd 100644 --- a/test/Node/GomlParserTest.ts +++ b/test/Core/GomlParserTest.ts @@ -1,12 +1,11 @@ require("babel-polyfill"); -import "../XMLDomInit"; import test from "ava"; import sinon from "sinon"; import GomlParser from "../../src/Core/GomlParser"; import xmldom from "xmldom"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import NSIdentity from "../../src/Base/NSIdentity"; -import Namespace from "../../src/Base/Namespace"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import NSIdentity from "../../src/Core/NSIdentity"; +import Namespace from "../../src/Core/Namespace"; import fs from "../fileHelper"; import { goml, @@ -22,7 +21,7 @@ import { conflictNode2, conflictComponent1, conflictComponent2 -} from "./GomlParserTest_Registering"; +} from "../DummyObjectRegisterer"; declare namespace global { let Node: any; @@ -33,11 +32,10 @@ declare namespace global { // Get element from test case source which is located with relative path. function obtainElementTag(path) { - const DOMParser = xmldom.DOMParser; global.Node = { ELEMENT_NODE: 1 }; - const parser = new DOMParser(); + const parser = new xmldom.DOMParser(); return parser.parseFromString(fs.readFile(path), "text/xml").documentElement; } @@ -51,7 +49,7 @@ let stringConverterSpy, test.beforeEach(async () => { GrimoireInterface.clear(); - const parser = new DOMParser(); + const parser = new xmldom.DOMParser(); const htmlDoc = parser.parseFromString("", "text/html"); global.document = htmlDoc; goml(); diff --git a/test/@/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts similarity index 96% rename from test/@/GrimoireInterfaceTest.ts rename to test/Core/GrimoireInterfaceTest.ts index 4a1f79c9e..96da3df43 100644 --- a/test/@/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -1,15 +1,14 @@ -import "../AsyncSupport"; -import "../XMLDomInit"; +require("babel-polyfill"); import xmldom from "xmldom"; import test from "ava"; import sinon from "sinon"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import Constants from "../../src/Base/Constants"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; import GomlParser from "../../src/Core/GomlParser"; import GomlLoader from "../../src/Core/GomlLoader"; -import NSIdentity from "../../src/Base/NSIdentity"; -import Namespace from "../../src/Base/Namespace"; +import NSIdentity from "../../src/Core/NSIdentity"; +import Namespace from "../../src/Core/Namespace"; import GomlNode from "../../src/Core/GomlNode"; declare namespace global { @@ -20,7 +19,7 @@ declare namespace global { global.Node = { ELEMENT_NODE: 1 }; -global.document = new DOMParser().parseFromString("", "text/html"); +global.document = new xmldom.DOMParser().parseFromString("", "text/html"); test.beforeEach(() => { diff --git a/test/Base/NSIdentityTest.ts b/test/Core/NSIdentityTest.ts similarity index 87% rename from test/Base/NSIdentityTest.ts rename to test/Core/NSIdentityTest.ts index b16a902fb..78eec0e06 100644 --- a/test/Base/NSIdentityTest.ts +++ b/test/Core/NSIdentityTest.ts @@ -1,16 +1,15 @@ import test from "ava"; import "../AsyncSupport"; -import "../XMLDomInit"; import xmldom from "xmldom"; import sinon from "sinon"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import Constants from "../../src/Base/Constants"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; import GomlParser from "../../src/Core/GomlParser"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; -import NSIdentity from "../../src/Base/NSIdentity"; +import NSIdentity from "../../src/Core/NSIdentity"; test.beforeEach(() => { NSIdentity.clear(); diff --git a/test/Base/NamespaceTest.ts b/test/Core/NamespaceTest.ts similarity index 74% rename from test/Base/NamespaceTest.ts rename to test/Core/NamespaceTest.ts index 1ac3ae68b..e6e419c1d 100644 --- a/test/Base/NamespaceTest.ts +++ b/test/Core/NamespaceTest.ts @@ -1,15 +1,14 @@ import test from "ava"; -import "../AsyncSupport"; -import "../XMLDomInit"; +require("babel-polyfill"); import xmldom from "xmldom"; import sinon from "sinon"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import Constants from "../../src/Base/Constants"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; import GomlParser from "../../src/Core/GomlParser"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; -import Namespace from "../../src/Base/Namespace"; +import Namespace from "../../src/Core/Namespace"; test("constructor is works correctly.", (t) => { let ns = Namespace.define("a").extend("b"); diff --git a/test/Interfaces/NodeInterfaceTest.ts b/test/Core/NodeInterfaceTest.ts similarity index 91% rename from test/Interfaces/NodeInterfaceTest.ts rename to test/Core/NodeInterfaceTest.ts index 6daa147c6..c2efe24fa 100644 --- a/test/Interfaces/NodeInterfaceTest.ts +++ b/test/Core/NodeInterfaceTest.ts @@ -1,10 +1,10 @@ -import "../AsyncSupport"; -import "../XMLDomInit"; +require("babel-polyfill"); import test from "ava"; import sinon from "sinon"; import xmldom from "xmldom"; import xhrmock from "xhr-mock"; import * as _ from "lodash"; +import TestEnvManager from "../TestEnvManager"; import { goml, stringConverter, @@ -21,11 +21,13 @@ import { conflictNode2, conflictComponent1, conflictComponent2 -} from "../Core/GomlParserTest_Registering"; +} from "../DummyObjectRegisterer"; import GomlLoader from "../../src/Core/GomlLoader"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; import fs from "../fileHelper"; +TestEnvManager.init(); + const testcase1_goml = fs.readFile("../_TestResource/GomlNodeTest_Case1.goml"); const testcase1_html = fs.readFile("../_TestResource/GomlNodeTest_Case1.html"); @@ -60,7 +62,7 @@ declare namespace global { test.beforeEach(async () => { GrimoireInterface.clear(); - const parser = new DOMParser(); + const parser = new xmldom.DOMParser(); const htmlDoc = parser.parseFromString(testcase1_html, "text/html"); global.document = htmlDoc; global.document.querySelectorAll = function(selector) { diff --git a/test/PageLoadingHelper.ts b/test/PageLoadingHelper.ts index 29badc697..000571080 100644 --- a/test/PageLoadingHelper.ts +++ b/test/PageLoadingHelper.ts @@ -1,6 +1,7 @@ import GrimoireInterface from "../src/Core/GrimoireInterface"; import GomlLoader from "../src/Core/GomlLoader"; import xhrmock from "xhr-mock"; +import xmldom from "xmldom"; import { goml, @@ -28,7 +29,7 @@ declare namespace global { export default class PageLoadingHelper { public static async reset(gr: typeof GrimoireInterface, html: string): Promise { gr.clear(); - const parser = new DOMParser(); + const parser = new xmldom.DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); global.document = htmlDoc; diff --git a/test/Base/EnsureTest.ts b/test/Tools/EnsureTest.ts similarity index 79% rename from test/Base/EnsureTest.ts rename to test/Tools/EnsureTest.ts index bfad59b3a..b6dfb1194 100644 --- a/test/Base/EnsureTest.ts +++ b/test/Tools/EnsureTest.ts @@ -1,10 +1,9 @@ -import "../XMLDomInit"; import test from "ava"; -import Ensure from "../../src/Base/Ensure"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import NSDictionary from "../../src/Base/NSDictionary"; -import NSIdentity from "../../src/Base/NSIdentity"; -import Namespace from "../../src/Base/Namespace"; +import Ensure from "../../src/Tools/Ensure"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import NSDictionary from "../../src/Tools/NSDictionary"; +import NSIdentity from "../../src/Core/NSIdentity"; +import Namespace from "../../src/Core/Namespace"; test.beforeEach(() => { NSIdentity.clear(); @@ -58,9 +57,9 @@ test("Ensure passed object are transformed into NSDictionary", (t) => { test("Ensure name tobe fqn if name start with _", t => { t.truthy(Ensure.tobeFQN("aaa") == null); - t.truthy(Ensure.tobeFQN("_aaa") == "aaa"); + t.truthy(Ensure.tobeFQN("_aaa") === "aaa"); t.truthy(Ensure.tobeFQN("aaa.fff") == null); - t.truthy(Ensure.tobeFQN("_aaa.fff") == "aaa.fff"); - t.truthy(Ensure.tobeFQN(NSIdentity.fromFQN("aaa.bbb")) == "aaa.bbb"); - t.truthy(Ensure.tobeFQN(NSIdentity.fromFQN("aaa")) == "aaa"); -}) + t.truthy(Ensure.tobeFQN("_aaa.fff") === "aaa.fff"); + t.truthy(Ensure.tobeFQN(NSIdentity.fromFQN("aaa.bbb")) === "aaa.bbb"); + t.truthy(Ensure.tobeFQN(NSIdentity.fromFQN("aaa")) === "aaa"); +}); diff --git a/test/Base/IdResolverTest.ts b/test/Tools/IdResolverTest.ts similarity index 87% rename from test/Base/IdResolverTest.ts rename to test/Tools/IdResolverTest.ts index 2869830bc..b661b151e 100644 --- a/test/Base/IdResolverTest.ts +++ b/test/Tools/IdResolverTest.ts @@ -1,17 +1,16 @@ import test from "ava"; import "../AsyncSupport"; -import "../XMLDomInit"; import xmldom from "xmldom"; import sinon from "sinon"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import Constants from "../../src/Base/Constants"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; import GomlParser from "../../src/Core/GomlParser"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; -import NSIdentity from "../../src/Base/NSIdentity"; -import Namespace from "../../src/Base/Namespace"; -import IdResolver from "../../src/Base/IdResolver"; +import NSIdentity from "../../src/Core/NSIdentity"; +import Namespace from "../../src/Core/Namespace"; +import IdResolver from "../../src/Tools/IdResolver"; test("get() works correctly.", t => { diff --git a/test/Base/NamespacedDictionaryTest.ts b/test/Tools/NameDictionaryTest.ts similarity index 89% rename from test/Base/NamespacedDictionaryTest.ts rename to test/Tools/NameDictionaryTest.ts index cf61873fd..9162f53fd 100644 --- a/test/Base/NamespacedDictionaryTest.ts +++ b/test/Tools/NameDictionaryTest.ts @@ -1,13 +1,13 @@ -import "../AsyncSupport"; -import "../XMLDomInit"; +require("babel-polyfill"); +import xmldom from "xmldom"; import test from "ava"; import sinon from "sinon"; import xhrmock from "xhr-mock"; import GomlLoader from "../../src/Core/GomlLoader"; -import GrimoireInterface from "../../src/Interface/GrimoireInterface"; -import NodeInterface from "../../src/Interface/NodeInterface"; -import NSIdentity from "../../src/Base/NSIdentity"; -import NSDictionary from "../../src/Base/NSDictionary"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import NodeInterface from "../../src/Core/NodeInterface"; +import NSIdentity from "../../src/Core/NSIdentity"; +import NSDictionary from "../../src/Tools/NSDictionary"; import fs from "../fileHelper"; const xml = fs.readFile("../_TestResource/NSDictionary_QueryDOM.xml"); @@ -55,7 +55,7 @@ test("get element with strict name", async (t) => { const theDict = new NSDictionary(); theDict.set(newKey, "test1"); theDict.set(secoundKey, "test2"); - const domParser = new DOMParser(); + const domParser = new xmldom.DOMParser(); const parsed = domParser.parseFromString(xml, "text/xml"); const idElement = parsed.getElementById("test"); @@ -74,7 +74,7 @@ test("get element with shortened namespace prefix", async (t) => { const theDict = new NSDictionary(); theDict.set(newKey, "test1"); theDict.set(secoundKey, "test2"); - const domParser = new DOMParser(); + const domParser = new xmldom.DOMParser(); const parsed = domParser.parseFromString(xml, "text/xml"); const idElement = parsed.getElementById("test2"); const attr = idElement.attributes.item(1); @@ -89,7 +89,7 @@ test("get element with shortened namespace prefix", async (t) => { const newKey = NSIdentity.fromFQN("test"); const theDict = new NSDictionary(); theDict.set(newKey, "test"); - const domParser = new DOMParser(); + const domParser = new xmldom.DOMParser(); const parsed = domParser.parseFromString(xml, "text/xml"); const idElement = parsed.getElementById("test2"); const attr = idElement.attributes.item(1); @@ -101,7 +101,7 @@ test("get element with fuzzy name", async (t) => { const secoundKey = NSIdentity.fromFQN("grimoirejs.test"); const theDict = new NSDictionary(); theDict.set(secoundKey, "test2"); - const domParser = new DOMParser(); + const domParser = new xmldom.DOMParser(); const parsed = domParser.parseFromString(xml, "text/xml"); const idElement = parsed.getElementById("test2"); const attr = idElement.attributes.item(1); @@ -117,7 +117,7 @@ test("get element with ambiguous name should throw error", async (t) => { const theDict = new NSDictionary(); theDict.set(newKey, "test1"); theDict.set(secoundKey, "test2"); - const domParser = new DOMParser(); + const domParser = new xmldom.DOMParser(); const parsed = domParser.parseFromString(xml, "text/xml"); const idElement = parsed.getElementById("test2"); const attr = idElement.attributes.item(1); diff --git a/test/Node/NamespacedSetTest.ts b/test/Tools/NamespacedSetTest.ts similarity index 75% rename from test/Node/NamespacedSetTest.ts rename to test/Tools/NamespacedSetTest.ts index f25d429f3..80d1b2efd 100644 --- a/test/Node/NamespacedSetTest.ts +++ b/test/Tools/NamespacedSetTest.ts @@ -1,9 +1,8 @@ -import "../XMLDomInit"; import test from "ava"; import GomlParser from "../../src/Core/GomlParser"; import xmldom from "xmldom"; -import NSSet from "../../src/Base/NSSet"; -import NSIdentity from "../../src/Base/NSIdentity"; +import NSSet from "../../src/Tools/NSSet"; +import NSIdentity from "../../src/Core/NSIdentity"; test("test parse for goml parser", (t) => { diff --git a/test/Base/UtilityTest.ts b/test/Tools/UtilityTest.ts similarity index 89% rename from test/Base/UtilityTest.ts rename to test/Tools/UtilityTest.ts index ca04d2bed..c5c833fee 100644 --- a/test/Base/UtilityTest.ts +++ b/test/Tools/UtilityTest.ts @@ -1,6 +1,5 @@ -import "../XMLDomInit"; import test from "ava"; -import Utility from "../../src/Base/Utility"; +import Utility from "../../src/Tools/Utility"; test("isCamelCase works correctly.", t => { t.truthy(Utility.isCamelCase("NameName123")); diff --git a/test/Base/XMLReaderTest.ts b/test/Tools/XMLReaderTest.ts similarity index 75% rename from test/Base/XMLReaderTest.ts rename to test/Tools/XMLReaderTest.ts index 23849be6c..535727251 100644 --- a/test/Base/XMLReaderTest.ts +++ b/test/Tools/XMLReaderTest.ts @@ -1,8 +1,10 @@ -import "../XMLDomInit"; import test from "ava"; import xmldom from "xmldom"; -import XMLReader from "../../src/Base/XMLReader"; +import XMLReader from "../../src/Tools/XMLReader"; import fs from "../fileHelper"; +import TestEnvManager from "../TestEnvManager"; + +TestEnvManager.init(); const xml = fs.readFile("../_TestResource/XMLReader_Case1.xml"); diff --git a/test/XMLDomInit.ts b/test/XMLDomInit.ts deleted file mode 100644 index b8958c35b..000000000 --- a/test/XMLDomInit.ts +++ /dev/null @@ -1,2 +0,0 @@ -import xmldom from "xmldom"; -global["DOMParser"] = xmldom.DOMParser; From 7642703d6b801889b176b5277a8b5294a7787b8c Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Sep 2017 17:59:58 +0900 Subject: [PATCH 011/146] fix: remove unuse files. --- test/AsyncSupport.ts | 4 ---- test/Core/GomlInterfaceTest.ts | 5 +++++ test/Core/GomlNodeTest.ts | 12 ++++++++++-- test/Core/NSIdentityTest.ts | 2 +- test/Core/NodeDeclarationTest.ts | 5 +++++ test/Tools/IdResolverTest.ts | 2 +- .../{NameDictionaryTest.ts => NSDictionaryTest.ts} | 0 test/Tools/{NamespacedSetTest.ts => NSSetTest.ts} | 0 8 files changed, 22 insertions(+), 8 deletions(-) delete mode 100644 test/AsyncSupport.ts create mode 100644 test/Core/GomlInterfaceTest.ts create mode 100644 test/Core/NodeDeclarationTest.ts rename test/Tools/{NameDictionaryTest.ts => NSDictionaryTest.ts} (100%) rename test/Tools/{NamespacedSetTest.ts => NSSetTest.ts} (100%) diff --git a/test/AsyncSupport.ts b/test/AsyncSupport.ts deleted file mode 100644 index 8e1b00ec1..000000000 --- a/test/AsyncSupport.ts +++ /dev/null @@ -1,4 +0,0 @@ -const rr = require("regenerator-runtime"); -const __awaiter = require("typescript-awaiter"); -global["__awaiter"] = __awaiter; -global["regeneratorRuntime"] = rr; diff --git a/test/Core/GomlInterfaceTest.ts b/test/Core/GomlInterfaceTest.ts new file mode 100644 index 000000000..91deb5a73 --- /dev/null +++ b/test/Core/GomlInterfaceTest.ts @@ -0,0 +1,5 @@ +import test from "ava"; + +test("check init for attribute manager", (t) => { + t.truthy(true, "TODO: write test"); +}); diff --git a/test/Core/GomlNodeTest.ts b/test/Core/GomlNodeTest.ts index f8c6f05ed..fb33aa807 100644 --- a/test/Core/GomlNodeTest.ts +++ b/test/Core/GomlNodeTest.ts @@ -29,8 +29,16 @@ test.beforeEach(async () => { GrimoireInterface.registerNode("goml"); GrimoireInterface.registerNode("scenes"); GrimoireInterface.registerNode("scene"); - GrimoireInterface.registerComponent("Test", { attributes: {}, valueTest: "Test"}); - GrimoireInterface.registerComponent("Test2", { attributes: {}, valueTest: "Test2"}); + GrimoireInterface.registerComponent({ + componentName: "Test", + attributes: {}, + valueTest: "Test" + }); + GrimoireInterface.registerComponent({ + componentName: "Test2", + attributes: {}, + valueTest: "Test2" + }); await GrimoireInterface.resolvePlugins(); }); diff --git a/test/Core/NSIdentityTest.ts b/test/Core/NSIdentityTest.ts index 78eec0e06..a66d864d6 100644 --- a/test/Core/NSIdentityTest.ts +++ b/test/Core/NSIdentityTest.ts @@ -1,5 +1,5 @@ import test from "ava"; -import "../AsyncSupport"; +require("babel-polyfill"); import xmldom from "xmldom"; import sinon from "sinon"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; diff --git a/test/Core/NodeDeclarationTest.ts b/test/Core/NodeDeclarationTest.ts new file mode 100644 index 000000000..91deb5a73 --- /dev/null +++ b/test/Core/NodeDeclarationTest.ts @@ -0,0 +1,5 @@ +import test from "ava"; + +test("check init for attribute manager", (t) => { + t.truthy(true, "TODO: write test"); +}); diff --git a/test/Tools/IdResolverTest.ts b/test/Tools/IdResolverTest.ts index b661b151e..f5954c530 100644 --- a/test/Tools/IdResolverTest.ts +++ b/test/Tools/IdResolverTest.ts @@ -1,5 +1,5 @@ import test from "ava"; -import "../AsyncSupport"; +require("babel-polyfill"); import xmldom from "xmldom"; import sinon from "sinon"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; diff --git a/test/Tools/NameDictionaryTest.ts b/test/Tools/NSDictionaryTest.ts similarity index 100% rename from test/Tools/NameDictionaryTest.ts rename to test/Tools/NSDictionaryTest.ts diff --git a/test/Tools/NamespacedSetTest.ts b/test/Tools/NSSetTest.ts similarity index 100% rename from test/Tools/NamespacedSetTest.ts rename to test/Tools/NSSetTest.ts From 314a9e4e994a27e26e1b1e497c956a69f6935028 Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Sep 2017 20:22:47 +0900 Subject: [PATCH 012/146] fix: refacor Namespace --- src/Core/NSIdentity.ts | 22 ++---------------- src/Core/Namespace.ts | 37 +++++++++++++++++++++++++++--- test/Core/NamespaceTest.ts | 42 +++++++++++++++++++++++++++++++--- test/Tools/NSDictionaryTest.ts | 2 +- 4 files changed, 76 insertions(+), 27 deletions(-) diff --git a/src/Core/NSIdentity.ts b/src/Core/NSIdentity.ts index 1abc3f77a..426a0d8ed 100644 --- a/src/Core/NSIdentity.ts +++ b/src/Core/NSIdentity.ts @@ -7,10 +7,9 @@ import Ensure from "../Tools/Ensure"; */ export default class NSIdentity { - private static _instances: { [fqn: string]: NSIdentity } = {}; private static _mapBackingField: IdResolver; - private static get _map(): IdResolver{ + private static get _map(): IdResolver { if (this._mapBackingField === void 0) { this._mapBackingField = new IdResolver(); } @@ -26,11 +25,7 @@ export default class NSIdentity { * @param {string} fqn [description] * @return {NSIdentity} [description] */ - public static fromFQN(fqn: string): NSIdentity; - public static fromFQN(qn: Namespace, name: string): NSIdentity; - public static fromFQN(fqn: string | Namespace, name?: string): NSIdentity { - const hierarchy = NSIdentity._ensureQNTobeArray(fqn, name); - fqn = hierarchy.join("."); + public static fromFQN(fqn: string): NSIdentity { const inst = NSIdentity._instances[fqn]; if (inst) { return inst; @@ -64,19 +59,6 @@ export default class NSIdentity { return NSIdentity.fromFQN(NSIdentity._map.resolve(Namespace.defineByArray(hierarchy))); } - private static _ensureQNTobeArray(arg1: string | string[] | Namespace, name?: string): string[] { - if (name) { - return NSIdentity._ensureQNTobeArray((arg1 as Namespace).extend(name)); - } - if (typeof arg1 === "string") { - return arg1.split("."); - } - if (Array.isArray(arg1)) { - return arg1; - } - return arg1.hierarchy; - } - public constructor(fqn: string | string[]); public constructor(qn: string[], n: string); public constructor(qn: string | string[], n?: string) { diff --git a/src/Core/Namespace.ts b/src/Core/Namespace.ts index 02da046ee..cd9f8cba3 100644 --- a/src/Core/Namespace.ts +++ b/src/Core/Namespace.ts @@ -14,22 +14,53 @@ export default class Namespace { public static define(...name: string[]): Namespace { return Namespace.defineByArray(name); } + public static defineByArray(name: string[]): Namespace { - return new Namespace(Utility.flat(name.map(n => n.split(".")))); + return new Namespace(Utility.flat(name.map(n => n.split(".").filter(s => s !== "")))); } + /** + * Represents a namespace hierarchy as string array. + */ public get hierarchy(): string[] { return this._ns; } + + /** + * Represents a namespace hierarchy as string joined by '.'. + */ public get qualifiedName(): string { return this._ns.join("."); } + + /** + * generate new Namespace instance extended hierarchy. + * @param extension extend name + */ public extend(extension: string): Namespace { - return new Namespace(this._ns.concat([extension])); + if (extension == null) { + throw new Error("Namespace can not extend with null"); + } + + let split = extension.split(".").filter(s => s !== ""); + if (split.length === 1 && extension === "") { + return new Namespace(this._ns); + } + return new Namespace(this._ns.concat(split)); } + + /** + * to NSIdentity with name + * @param name name + */ public for(name: string): NSIdentity { - return NSIdentity.fromFQN(this, name); + if (!name) { + throw new Error("name must not be null"); + } + const fqn = `${this.hierarchy.join(".")}.${name}`; + return NSIdentity.fromFQN(fqn); } + public toString(): string { return this.qualifiedName; } diff --git a/test/Core/NamespaceTest.ts b/test/Core/NamespaceTest.ts index e6e419c1d..af5230bfe 100644 --- a/test/Core/NamespaceTest.ts +++ b/test/Core/NamespaceTest.ts @@ -1,6 +1,5 @@ -import test from "ava"; require("babel-polyfill"); -import xmldom from "xmldom"; +import test from "ava"; import sinon from "sinon"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Constants from "../../src/Tools/Constants"; @@ -10,7 +9,7 @@ import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import Namespace from "../../src/Core/Namespace"; -test("constructor is works correctly.", (t) => { +test("constructor is works correctly.", t => { let ns = Namespace.define("a").extend("b"); t.truthy(ns.qualifiedName === "a.b"); t.truthy(ns.hierarchy.length === 2); @@ -22,3 +21,40 @@ test("constructor is works correctly.", (t) => { let ns2 = ns.for("name"); t.truthy(ns2.fqn === "a.b.c.name"); }); + +test("check some edge cases.", t => { + const edgeTestCase = [ + [Namespace.define("a").extend("b"), "a.b"], + [Namespace.define("a.b"), "a.b"], + [Namespace.define(""), ""], + [Namespace.define("a"), "a"], + [Namespace.define("").extend(""), ""], + [Namespace.define("a").extend(""), "a"], + [Namespace.define("").extend("a"), "a"], + [Namespace.define("a.b").extend("c.d"), "a.b.c.d"], + ]; + + edgeTestCase.forEach(element => { + let ns = element[0] as Namespace; + let expected = element[1]; + t.truthy(ns.qualifiedName === expected); + }); + for (let i = 0; i < edgeTestCase.length; i++) { + let element = edgeTestCase[i]; + let ns = element[0] as Namespace; + let expected = element[1]; + t.truthy(ns.qualifiedName === expected, `$testcase: {i}`); + } + + const raiseExceptionTestCase = [ + () => Namespace.define(null), + () => Namespace.define("a").extend(null), + () => Namespace.define("a").for(null), + ]; + + for (let i = 0; i < raiseExceptionTestCase.length; i++) { + t.throws(() => { + raiseExceptionTestCase[i](); + }); + } +}); diff --git a/test/Tools/NSDictionaryTest.ts b/test/Tools/NSDictionaryTest.ts index 9162f53fd..e1493b675 100644 --- a/test/Tools/NSDictionaryTest.ts +++ b/test/Tools/NSDictionaryTest.ts @@ -15,7 +15,7 @@ test.beforeEach(() => { NSIdentity.clear(); }); -test("set element correctly", (t) => { +test("set element correctly", t => { const newKey = NSIdentity.fromFQN("hoge.test"); const value = "Grimoire"; const theDict = new NSDictionary(); From 3f76cdde21d69e7efcb4f15ab1954194c9f66889 Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Sep 2017 21:08:48 +0900 Subject: [PATCH 013/146] fix: refactor NSIdentity test --- src/Core/NSIdentity.ts | 4 +-- src/Interface/ITreeInitializedInfo.ts | 2 +- test/Core/NSIdentityTest.ts | 47 +++++++++++++++------------ 3 files changed, 29 insertions(+), 24 deletions(-) diff --git a/src/Core/NSIdentity.ts b/src/Core/NSIdentity.ts index 426a0d8ed..d22af2011 100644 --- a/src/Core/NSIdentity.ts +++ b/src/Core/NSIdentity.ts @@ -35,7 +35,7 @@ export default class NSIdentity { } public static guess(...hierarchy: string[]): NSIdentity { - return NSIdentity._from(hierarchy); + return NSIdentity._guess(hierarchy); } public static clear(): void { @@ -49,7 +49,7 @@ export default class NSIdentity { * @param {string[]} hierarchy [description] * @return {NSIdentity} [description] */ - private static _from(hierarchy: string[]): NSIdentity { + private static _guess(hierarchy: string[]): NSIdentity { const fqn = hierarchy.join("."); const inst = NSIdentity._instances[fqn]; if (inst) { diff --git a/src/Interface/ITreeInitializedInfo.ts b/src/Interface/ITreeInitializedInfo.ts index a16bdfc59..957d11616 100644 --- a/src/Interface/ITreeInitializedInfo.ts +++ b/src/Interface/ITreeInitializedInfo.ts @@ -1,4 +1,4 @@ export default interface ITreeInitializedInfo { ownerScriptTag: HTMLScriptElement; id: string; -} \ No newline at end of file +} diff --git a/test/Core/NSIdentityTest.ts b/test/Core/NSIdentityTest.ts index a66d864d6..dc8e5e4fd 100644 --- a/test/Core/NSIdentityTest.ts +++ b/test/Core/NSIdentityTest.ts @@ -1,47 +1,51 @@ -import test from "ava"; require("babel-polyfill"); -import xmldom from "xmldom"; +import test from "ava"; import sinon from "sinon"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import Constants from "../../src/Tools/Constants"; -import Component from "../../src/Core/Component"; -import GomlParser from "../../src/Core/GomlParser"; -import GomlLoader from "../../src/Core/GomlLoader"; -import GomlNode from "../../src/Core/GomlNode"; - import NSIdentity from "../../src/Core/NSIdentity"; test.beforeEach(() => { NSIdentity.clear(); }); +test("generate instance works correctly", t => { + let inst = NSIdentity.fromFQN("hoge"); + t.truthy(inst.fqn === "hoge"); + t.truthy(NSIdentity.fromFQN("hoge") === inst); // instance is singleton for same fqn. +}); + test("Not accept to get invalid name or namespace", (t) => { NSIdentity.fromFQN("hoge"); + NSIdentity.fromFQN("other.a.hoge"); + NSIdentity.fromFQN("other.b.hoge"); NSIdentity.fromFQN("a.b"); t.throws(() => { - NSIdentity.guess("aaa"); + NSIdentity.guess("aaa"); // not found }); t.throws(() => { - NSIdentity.guess("b", "a"); + NSIdentity.guess("b", "a"); // not found }); t.throws(() => { - NSIdentity.guess("Wrongamespace", "WrongName"); + NSIdentity.guess("Wrongamespace", "WrongName"); // not found }); - t.notThrows(() => { - NSIdentity.guess("hoge"); - }); - t.notThrows(() => { - NSIdentity.guess("a", "b"); + + t.truthy(NSIdentity.guess("hoge").fqn === "hoge"); // ok because strict fqn match. + t.truthy(NSIdentity.guess("a", "b").fqn === "a.b"); + t.truthy(NSIdentity.guess("b").fqn === "a.b"); + + t.throws(() => { + NSIdentity.guess("a"); // not name }); - t.notThrows(() => { - NSIdentity.guess("b"); + t.throws(() => { + let a = NSIdentity.guess("other.hoge"); // ambiguous + console.log(a); }); + t.truthy(NSIdentity.guess("a.hoge").fqn === "other.a.hoge"); }); test("Transform name and ns correctly", (t) => { - const i = NSIdentity.fromFQN("ns.Sample"); + const i = NSIdentity.fromFQN("ns.ns1.Sample"); t.truthy(i.name === "Sample"); - t.truthy(i.ns.qualifiedName === "ns"); + t.truthy(i.ns.qualifiedName === "ns.ns1"); }); test("isMatch works correctly", t => { @@ -52,6 +56,7 @@ test("isMatch works correctly", t => { t.truthy(hoge.isMatch("a.b.c")); t.truthy(!hoge.isMatch("c.c")); t.truthy(!hoge.isMatch("b.a.c")); + t.truthy(!hoge.isMatch("b")); t.truthy(!hoge.isMatch("d")); t.truthy(!hoge.isMatch("a.d")); }); From c1240ee5916bad88d701b5beb3f424b44697ae15 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 17 Sep 2017 10:15:13 +0900 Subject: [PATCH 014/146] fix: add AttributeTest --- src/Core/Attribute.ts | 2 +- src/Tools/IdResolver.ts | 2 +- test/Core/AttributeTest.ts | 162 ++++++++++++++++++++++++++++++++++++- test/TestEnvManager.ts | 13 ++- test/TestUtil.ts | 20 +++++ 5 files changed, 194 insertions(+), 5 deletions(-) diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index a386b3d79..34b5d5636 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -93,7 +93,7 @@ export default class Attribute { } - public static convert(converter: Name, self: Attribute, val: any): any { + public static convert(converter: Name, self: Attribute, val: any): any { // TODO unuse? const cname = Ensure.tobeNSIdentity(converter); const conv = GrimoireInterface.converters.get(cname); if (!conv) { diff --git a/src/Tools/IdResolver.ts b/src/Tools/IdResolver.ts index 1ef06216e..2185fd67d 100644 --- a/src/Tools/IdResolver.ts +++ b/src/Tools/IdResolver.ts @@ -39,7 +39,7 @@ export default class IdResolver { * @param {string | string[]} name [description] * @return {string[]} list of FQN */ - public get(ns: Namespace | string): string[] { + public get(ns: Namespace | string): string[] { // TODO FQNstringに対応? if (typeof ns === "string") { return this.get(Namespace.defineByArray(ns.split("."))); } diff --git a/test/Core/AttributeTest.ts b/test/Core/AttributeTest.ts index 91deb5a73..c99babcab 100644 --- a/test/Core/AttributeTest.ts +++ b/test/Core/AttributeTest.ts @@ -1,5 +1,163 @@ +import TestEnvManager from "../TestEnvManager"; import test from "ava"; +import Attribute from "../../src/Core/Attribute"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import TestUtil from "../TestUtil"; +import GrimoireComponent from "../../src/Components/GrimoireComponent"; +import sinon from "sinon"; +import NSIdentity from "../../src/Core/NSIdentity"; -test("check init for attribute manager", (t) => { - t.truthy(true, "TODO: write test"); +TestEnvManager.init(); + + +const GOML = ``; + +test.beforeEach(async () => { + GrimoireInterface.clear(); + GrimoireInterface.registerNode("goml"); +}); + +test("attibute poperties should be initialized correctly", (t) => { + let rootNode = TestUtil.DummyTreeInit(GOML); + const idAttr = rootNode.getAttributeRaw("id"); + const baseComponent = rootNode.getComponent(GrimoireComponent); + + t.truthy(idAttr.name.fqn === "grimoirejs.GrimoireComponent.id"); + t.truthy(idAttr.declaration.default === null); + t.truthy((idAttr.converter.name as NSIdentity).fqn === "grimoirejs.String"); + t.truthy(idAttr.component === baseComponent); +}); + +test("get/set value should works correctly.", t => { + let rootNode = TestUtil.DummyTreeInit(GOML); + const idAttr = rootNode.getAttributeRaw("id"); + const baseComponent = rootNode.getComponent(GrimoireComponent); + t.truthy(idAttr.Value === null); + idAttr.Value = "string"; + t.truthy(idAttr.Value === "string"); + idAttr.Value = 123; + t.truthy(idAttr.Value === "123"); + t.throws(() => { + idAttr.Value = void 0; + }); +}); + +test("watch/unwatch should works correctly", t => { + let rootNode = TestUtil.DummyTreeInit(GOML); + const idAttr = rootNode.getAttributeRaw("id"); + const baseComponent = rootNode.getComponent(GrimoireComponent); + const spy = sinon.spy(); + + const watcher = (n, o, a) => { + spy(n, o, a); + }; + idAttr.watch(watcher); + + idAttr.Value = "newValue"; + t.truthy(spy.args[0][0] === "newValue"); + t.truthy(spy.args[0][1] === null); + t.truthy(spy.args[0][2] === idAttr); + + spy.reset(); + idAttr.unwatch(watcher); + idAttr.Value = "newValue2"; + sinon.assert.notCalled(spy); +}); + + +test("generateAttributeForComponent should works correctly", t => { + let rootNode = TestUtil.DummyTreeInit(GOML); + const idAttr = rootNode.getAttributeRaw("id"); + const baseComponent = rootNode.getComponent(GrimoireComponent); + const hogeAttr = Attribute.generateAttributeForComponent("hoge", { + converter: "Number", + default: 42 + }, baseComponent); + t.throws(() => { // not resolve default value yet + baseComponent.getAttribute("hoge"); + }); + hogeAttr.resolveDefaultValue({}); + t.truthy(baseComponent.getAttribute("hoge") === 42); + hogeAttr.Value = 43; + t.truthy(baseComponent.getAttribute("hoge") === 43); + + t.throws(() => { // converter can not resolve. + Attribute.generateAttributeForComponent("fuga", { + converter: "False", + default: 42 + }, baseComponent); + }); + t.notThrows(() => { // default value undefined is OK. + Attribute.generateAttributeForComponent("fuga", { + converter: "Number", + default: void 0 + }, baseComponent); + }); +}); +test("boundTo should works correctly", t => { + let rootNode = TestUtil.DummyTreeInit(GOML); + const idAttr = rootNode.getAttributeRaw("id"); + const baseComponent = rootNode.getComponent(GrimoireComponent); + const obj = { id: "hoge" }; + idAttr.boundTo("id", obj); + t.truthy(obj.id === idAttr.Value); + idAttr.Value = "value"; + t.truthy(obj.id === idAttr.Value); +}); + +test("generateAttributeForComponent should works correctly (use dom value)", t => { + GrimoireInterface.registerNode("node1", [], { "ns1.hoge": 52 }); + let rootNode = TestUtil.DummyTreeInit(``); + let node = rootNode.children[0]; + const baseComponent = node.getComponent(GrimoireComponent); + + const attr1 = Attribute.generateAttributeForComponent("ns1.hoge", { + converter: "Number", + default: 42 + }, baseComponent); + + t.throws(() => { + attr1.resolveDefaultValue({ "hoge": "43", "ns1.hoge": "44" }); // ambiguous + }); + + attr1.resolveDefaultValue({ "ns1.hoge": "43" }); + t.truthy(attr1.Value === 43); +}); + +test("generateAttributeForComponent should works correctly (use node value)", t => { + GrimoireInterface.registerNode("node1", [], { "ns1.hoge": 52 }); + let rootNode = TestUtil.DummyTreeInit(``); + let node = rootNode.children[0]; + const baseComponent = node.getComponent(GrimoireComponent); + + const attr1 = Attribute.generateAttributeForComponent("ns1.hoge", { + converter: "Number", + default: 42 + }, baseComponent); + const attr2 = Attribute.generateAttributeForComponent("ns2.hoge", { + converter: "Number", + default: 42 + }, baseComponent); + + attr1.resolveDefaultValue({}); + t.truthy(attr1.Value === 52); +}); + +test("generateAttributeForComponent should works correctly (use declaration default value)", t => { + GrimoireInterface.registerNode("node1"); + let rootNode = TestUtil.DummyTreeInit(``); + let node = rootNode.children[0]; + const baseComponent = node.getComponent(GrimoireComponent); + + const attr1 = Attribute.generateAttributeForComponent("ns1.hoge", { + converter: "Number", + default: 42 + }, baseComponent); + const attr2 = Attribute.generateAttributeForComponent("ns2.hoge", { + converter: "Number", + default: 42 + }, baseComponent); + + attr1.resolveDefaultValue({}); + t.truthy(attr1.Value === 42); }); diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index 646aec6b7..e4c238923 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -1,10 +1,18 @@ +require("babel-polyfill"); import XMLReader from "../src/Tools/XMLReader"; import xmldom from "xmldom"; +import jsdomAsync from "./JsDOMAsync"; import Attribute from "../src/Core/Attribute"; import IAttributeConverterDeclaration from "../src/Interface/IAttributeConverterDeclaration"; import IConverterRepository from "../src/Interface/Repository/IConverterRepository"; import NSDictionary from "../src/Tools/NSDictionary"; import NSIdentity from "../src/Core/NSIdentity"; +import fs from "./fileHelper"; + +declare namespace global { + let Node: any; + let document: any; +} class TestEnvContext implements IConverterRepository { public converters: NSDictionary; @@ -17,8 +25,11 @@ export default class TestEnvManager { this.context.converters.set(name, converter); } - public static init() { + public static async init() { XMLReader.parser = new xmldom.DOMParser(); // Attribute.converterRepository = TestEnvManager.context; + const testcase1_html = fs.readFile("../_TestResource/GomlLoaderTest_Case1.html"); + const window = await jsdomAsync(testcase1_html, []); + global.document = window.document; } } diff --git a/test/TestUtil.ts b/test/TestUtil.ts index bebc1d4a4..04ab6eccd 100644 --- a/test/TestUtil.ts +++ b/test/TestUtil.ts @@ -5,6 +5,10 @@ import Attribute from "../src/Core/Attribute"; import IAttributeDeclaration from "../src/Interface/IAttributeDeclaration"; import Ensure from "../src/Tools/Ensure"; import GrimoireInterface from "../src/Core/GrimoireInterface"; +import XMLReader from "../src/Tools/XMLReader"; +import GomlParser from "../src/Core/GomlParser"; +import ITreeInitializedInfo from "../src/Interface/ITreeInitializedInfo"; +import GomlNode from "../src/Core/GomlNode"; export default class TestUtil { @@ -31,4 +35,20 @@ export default class TestUtil { attr.converter.verify(attr); return attr; } + + public static DummyTreeInit(goml: string): GomlNode { + const doc = XMLReader.parseXML(goml, "GOML"); + const rootNode = GomlParser.parse(doc[0]); + + rootNode.setMounted(true); + rootNode.broadcastMessage("treeInitialized", { + ownerScriptTag: null, + id: rootNode.id + }); + rootNode.sendInitializedMessage({ + ownerScriptTag: null, + id: rootNode.id + }); + return rootNode; + } } From 38e66ddd368960279b0bcfcc16e973ba9099eb2c Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 17 Sep 2017 10:15:37 +0900 Subject: [PATCH 015/146] fix: refactor test --- test/Core/GomlLoaderTest.ts | 1 - test/Core/GomlNode2Test.ts | 1 - test/Core/GrimoireInterfaceTest.ts | 9 +++++---- test/Core/NodeInterfaceTest.ts | 1 - test/TestEnvManager.ts | 3 +++ 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/test/Core/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts index a7d92974e..94fae3086 100644 --- a/test/Core/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -1,4 +1,3 @@ -require("babel-polyfill"); import prequire from "proxyquire"; import jsdomAsync from "../JsDOMAsync"; import test from "ava"; diff --git a/test/Core/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts index 9c2af56ee..9a10ccca0 100644 --- a/test/Core/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -1,4 +1,3 @@ -require("babel-polyfill"); import test from "ava"; import sinon from "sinon"; import xmldom from "xmldom"; diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index 96da3df43..08be5f758 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -77,7 +77,7 @@ test("registerComponent by object works correctly", async (t) => { } }, hoge: 0, - $test: function() { + $test: function () { this.hoge += 1; } }); @@ -110,7 +110,7 @@ test("registerComponent by object works correctly", async (t) => { default: "ccc" } }, - $test2: function() { + $test2: function () { // do nothing. } }, "Aaa"); @@ -294,7 +294,8 @@ test("registerNode/Component works correctly.", async t => { GrimoireInterface.registerNode("a1"); GrimoireInterface.registerNode("a2", ["Hoge"]); GrimoireInterface.registerNode("a3", [], { hoge: 7 }, "a2"); - GrimoireInterface.registerComponent("Hoge", { + GrimoireInterface.registerComponent({ + componentName: "Hoge", attributes: { hoge: { converter: "Number", @@ -328,7 +329,7 @@ test("throw error on attempt registerComponent/Node by duplicate name.", t => { test("register and resolvePlugins works preperly", async () => { const spy1 = sinon.spy(); const spy2 = sinon.spy(); - const wrapPromise: any = function(spy) { + const wrapPromise: any = function (spy) { return () => { return new Promise(resolve => { spy(); diff --git a/test/Core/NodeInterfaceTest.ts b/test/Core/NodeInterfaceTest.ts index c2efe24fa..4b4f8c10c 100644 --- a/test/Core/NodeInterfaceTest.ts +++ b/test/Core/NodeInterfaceTest.ts @@ -1,4 +1,3 @@ -require("babel-polyfill"); import test from "ava"; import sinon from "sinon"; import xmldom from "xmldom"; diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index e4c238923..e246c1582 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -31,5 +31,8 @@ export default class TestEnvManager { const testcase1_html = fs.readFile("../_TestResource/GomlLoaderTest_Case1.html"); const window = await jsdomAsync(testcase1_html, []); global.document = window.document; + global.Node = { + ELEMENT_NODE: 1 + }; } } From 3d1bfdd89700be8d11e1f1603942bc97ef9e7486 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 17 Sep 2017 10:54:26 +0900 Subject: [PATCH 016/146] fix: add ComponentDeclarationTest --- test/Core/ComponentDeclarationTest.ts | 124 +++++++++++++++++++++++++- 1 file changed, 122 insertions(+), 2 deletions(-) diff --git a/test/Core/ComponentDeclarationTest.ts b/test/Core/ComponentDeclarationTest.ts index 91deb5a73..743e19167 100644 --- a/test/Core/ComponentDeclarationTest.ts +++ b/test/Core/ComponentDeclarationTest.ts @@ -1,5 +1,125 @@ import test from "ava"; +import TestEnvManager from "../TestEnvManager"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; -test("check init for attribute manager", (t) => { - t.truthy(true, "TODO: write test"); +TestEnvManager.init(); + +test.beforeEach(async () => { + GrimoireInterface.clear(); +}); + +test("componentDeclaration poperties should be initialized correctly", (t) => { + GrimoireInterface.registerComponent({ + componentName: "Super", + attributes: { + superAttr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "super" + } + } + }); + GrimoireInterface.registerComponent({ + componentName: "Hoge", + attributes: { + attr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "hoge" + } + } + }, "Super"); + const superComponent = GrimoireInterface.componentDeclarations.get("Super"); + const hogeComponent = GrimoireInterface.componentDeclarations.get("Hoge"); + t.truthy(superComponent.name.fqn === "grimoirejs.Super"); + t.truthy(hogeComponent.name.fqn === "grimoirejs.Hoge"); + t.truthy(superComponent.superComponent == null); + t.truthy(hogeComponent.superComponent == null); // because not esolved dependency yet. +}); + +test("resolveDependency should works correctly", (t) => { + GrimoireInterface.registerComponent({ + componentName: "Super", + attributes: { + superAttr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "super" + } + } + }); + GrimoireInterface.registerComponent({ + componentName: "Hoge", + attributes: { + attr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "hoge" + } + } + }, "Super"); + const superComponent = GrimoireInterface.componentDeclarations.get("Super"); + const hogeComponent = GrimoireInterface.componentDeclarations.get("Hoge"); + t.truthy(hogeComponent.resolveDependency()); + t.truthy(!hogeComponent.resolveDependency()); // already resolved + t.truthy(!superComponent.resolveDependency()); // already resolved by inheits + + t.truthy(hogeComponent.superComponent); + t.truthy(hogeComponent.attributes["superAttr1"].default === "hoge"); + t.truthy(hogeComponent.attributes["attr1"].default === "hoge"); + t.truthy(hogeComponent.attributes["overrideAttr1"].default === "hoge"); + t.truthy(superComponent.attributes["superAttr1"].default === "hoge"); + t.truthy(superComponent.attributes["overrideAttr1"].default === "super"); + t.truthy(superComponent.attributes["attr1"] == null); +}); + +test("generateInstance should works correctly", (t) => { + GrimoireInterface.registerComponent({ + componentName: "Super", + attributes: { + superAttr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "super" + } + } + }); + GrimoireInterface.registerComponent({ + componentName: "Hoge", + attributes: { + attr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "hoge" + } + } + }, "Super"); + const superComponentDec = GrimoireInterface.componentDeclarations.get("Super"); + const hogeComponentDec = GrimoireInterface.componentDeclarations.get("Hoge"); + + const superComponent = superComponentDec.generateInstance(); + const hogeComponent = hogeComponentDec.generateInstance(); + t.truthy(hogeComponent.getAttributeRaw("attr1")); + t.truthy(hogeComponent.getAttributeRaw("overrideAttr1")); + t.truthy(hogeComponent.getAttributeRaw("superAttr1")); + t.truthy(superComponent.getAttributeRaw("superAttr1")); + t.truthy(superComponent.getAttributeRaw("overrideAttr1")); }); From 55d334b7aefb1021fdedaba45a47208e785b76ce Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 17 Sep 2017 21:06:01 +0900 Subject: [PATCH 017/146] fix: add ComponentTest --- test/Core/ComponentTest.ts | 89 +++++++++++++++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/test/Core/ComponentTest.ts b/test/Core/ComponentTest.ts index 91deb5a73..7fb4283e8 100644 --- a/test/Core/ComponentTest.ts +++ b/test/Core/ComponentTest.ts @@ -1,5 +1,90 @@ import test from "ava"; +import TestEnvManager from "../TestEnvManager"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; -test("check init for attribute manager", (t) => { - t.truthy(true, "TODO: write test"); +TestEnvManager.init(); + +test.beforeEach(async () => { + GrimoireInterface.clear(); +}); + +test("component poperties should be initialized correctly", (t) => { + GrimoireInterface.registerComponent({ + componentName: "Super", + attributes: { + superAttr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "super" + } + } + }); + GrimoireInterface.registerComponent({ + componentName: "Hoge", + attributes: { + attr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "hoge" + } + } + }, "Super"); + const superComponentDec = GrimoireInterface.componentDeclarations.get("Super"); + const hogeComponentDec = GrimoireInterface.componentDeclarations.get("Hoge"); + + const superComponent = superComponentDec.generateInstance(); + const hogeComponent = hogeComponentDec.generateInstance(); + + t.truthy(hogeComponent.name.fqn === "grimoirejs.Hoge"); + t.truthy(superComponent.name.fqn === "grimoirejs.Super"); + t.truthy(hogeComponent.node === superComponent.node); + t.truthy(hogeComponent.name.fqn === "grimoirejs.Hoge"); + t.truthy(!hogeComponent.disposed); + t.truthy(!superComponent.disposed); +}); + +test("get/set attribute should works correctly", (t) => { + GrimoireInterface.registerComponent({ + componentName: "Super", + attributes: { + superAttr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "super" + } + } + }); + GrimoireInterface.registerComponent({ + componentName: "Hoge", + attributes: { + attr1: { + converter: "String", + default: "hoge" + }, + overrideAttr1: { + converter: "String", + default: "hoge" + } + } + }, "Super"); + const superComponentDec = GrimoireInterface.componentDeclarations.get("Super"); + const hogeComponentDec = GrimoireInterface.componentDeclarations.get("Hoge"); + + const superComponent = superComponentDec.generateInstance(); + const hogeComponent = hogeComponentDec.generateInstance(); + + t.truthy(!hogeComponent.getAttributeRaw("notfound")); + t.truthy(hogeComponent.getAttributeRaw("attr1")); + t.truthy(hogeComponent.getAttributeRaw("grimoirejs.attr1")); + t.truthy(hogeComponent.getAttributeRaw("grimoirejs.Hoge.attr1")); + t.truthy(hogeComponent.getAttributeRaw("Hoge.attr1")); }); From b908d8821ce4b407dc2d61079ae8232fcc74c4d7 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 18 Sep 2017 21:44:05 +0900 Subject: [PATCH 018/146] fix: replace GrimoireInterface.ns() --- src/Core/GrimoireInterfaceImpl.ts | 3 +- test/Core/GrimoireInterfaceTest.ts | 16 ++++---- test/Core/NamespaceTest.ts | 5 +++ test/DummyObjectRegisterer.ts | 61 +++++++++++++++--------------- 4 files changed, 46 insertions(+), 39 deletions(-) diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index fd0e6b5ae..a107cbc3e 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -80,6 +80,7 @@ export default class GrimoireInterfaceImpl extends EEObject { * @return {[type]} the namespaced identity */ public ns(ns: string): (name: string) => NSIdentity { + Utility.w("GrimoireInterface.ns is obsolete. please use `Namespace.define()` instead of."); return (name: string) => Namespace.define(ns).for(name); } @@ -221,7 +222,7 @@ export default class GrimoireInterfaceImpl extends EEObject { } tag.setAttribute("x-rootNodeId", rootNode.id); this.rootNodes[rootNode.id] = rootNode; - rootNode.companion.set(this.ns(Constants.defaultNamespace)("scriptElement"), tag); + rootNode.companion.set(Namespace.define(Constants.defaultNamespace).for("scriptElement"), tag); // awake and mount tree. rootNode.setMounted(true); diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index 08be5f758..2994bcb3f 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -10,26 +10,26 @@ import GomlLoader from "../../src/Core/GomlLoader"; import NSIdentity from "../../src/Core/NSIdentity"; import Namespace from "../../src/Core/Namespace"; import GomlNode from "../../src/Core/GomlNode"; +import TestEnvManager from "../TestEnvManager"; + +TestEnvManager.init(); declare namespace global { let Node: any; let document: any; } -global.Node = { - ELEMENT_NODE: 1 -}; -global.document = new xmldom.DOMParser().parseFromString("", "text/html"); - +// global.document = new xmldom.DOMParser().parseFromString("", "text/html"); test.beforeEach(() => { GrimoireInterface.clear(); GrimoireInterface.resolvePlugins(); }); -test("ns method should generate namespace generating function correctly", (t) => { - const g = Namespace.define("grimoire"); - t.truthy(g.for("test").fqn === "grimoire.test"); +test("properties are initialized correctly", t => { + t.truthy(GrimoireInterface.nodeDeclarations.toArray().length === 1); // only grimoire-node-base + t.truthy(GrimoireInterface.converters.toArray().length > 0); + t.truthy(GrimoireInterface.componentDeclarations.toArray().length === 1); // only GrimoireComponent }); test("registerComponent works correctly", (t) => { diff --git a/test/Core/NamespaceTest.ts b/test/Core/NamespaceTest.ts index af5230bfe..77b5aab0a 100644 --- a/test/Core/NamespaceTest.ts +++ b/test/Core/NamespaceTest.ts @@ -9,6 +9,11 @@ import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import Namespace from "../../src/Core/Namespace"; +test("define/for function works correctly.", (t) => { // TODO test + const g = Namespace.define("grimoire"); + t.truthy(g.for("test").fqn === "grimoire.test"); +}); + test("constructor is works correctly.", t => { let ns = Namespace.define("a").extend("b"); t.truthy(ns.qualifiedName === "a.b"); diff --git a/test/DummyObjectRegisterer.ts b/test/DummyObjectRegisterer.ts index 4d814b767..5898decb5 100644 --- a/test/DummyObjectRegisterer.ts +++ b/test/DummyObjectRegisterer.ts @@ -1,5 +1,6 @@ import GrimoireInterface from "../src/Core/GrimoireInterface"; import sinon from "sinon"; +import Namespace from "../src/Core/Namespace"; export function testComponent1() { const spy = sinon.spy(); @@ -15,16 +16,16 @@ export function testComponent1() { default: "DEFAULT" } }, - $onTest: function(arg) { + $onTest: function (arg) { spy("onTest", arg); }, - $mount: function(arg) { + $mount: function (arg) { spy("mount", arg); }, - $unmount: function(arg) { + $unmount: function (arg) { spy("unmount", arg); }, - $awake: function(arg) { + $awake: function (arg) { spy("awake", arg); } }); @@ -41,16 +42,16 @@ export function testComponent2() { default: "tc2default" } }, - $onTest: function(arg) { + $onTest: function (arg) { spy("onTest", arg); }, - $mount: function(arg) { + $mount: function (arg) { spy("mount", arg); }, - $unmount: function(arg) { + $unmount: function (arg) { spy("unmount", arg); }, - $awake: function(arg) { + $awake: function (arg) { spy("awake", arg); } }); @@ -75,16 +76,16 @@ export function testComponent3() { default: "hoge" } }, - $onTest: function(arg) { + $onTest: function (arg) { spy("onTest", arg); }, - $mount: function(arg) { + $mount: function (arg) { spy("mount", arg); }, - $unmount: function(arg) { + $unmount: function (arg) { spy("unmount", arg); }, - $awake: function(arg) { + $awake: function (arg) { spy("awake", arg); } }); @@ -101,16 +102,16 @@ export function testComponentBase() { default: "base" } }, - $onTest: function(arg) { + $onTest: function (arg) { spy("onTest", arg); }, - $mount: function(arg) { + $mount: function (arg) { spy("mount", arg); }, - $unmount: function(arg) { + $unmount: function (arg) { spy("unmount", arg); }, - $awake: function(arg) { + $awake: function (arg) { spy("awake", arg); } }); @@ -127,16 +128,16 @@ export function testComponentOptional() { default: "optional" } }, - $onTest: function(arg) { + $onTest: function (arg) { spy("onTest", arg); }, - $mount: function(arg) { + $mount: function (arg) { spy("mount", arg); }, - $unmount: function(arg) { + $unmount: function (arg) { spy("unmount", arg); }, - $awake: function(arg) { + $awake: function (arg) { spy("awake", arg); } }); @@ -145,16 +146,16 @@ export function testComponentOptional() { export function conflictComponent1() { const spy = sinon.spy(); - const ns = GrimoireInterface.ns("test1"); + const ns = Namespace.define("test1"); GrimoireInterface.registerComponent({ - componentName: ns("ConflictComponent"), + componentName: ns.for("ConflictComponent"), attributes: { value: { converter: "Str", default: "aaa" } }, - $onTest: function() { + $onTest: function () { spy(this.attributes.get("value").Value); } }); @@ -163,16 +164,16 @@ export function conflictComponent1() { export function conflictComponent2() { const spy = sinon.spy(); - const ns = GrimoireInterface.ns("test2"); + const ns = Namespace.define("test2"); GrimoireInterface.registerComponent({ - componentName: ns("ConflictComponent"), + componentName: ns.for("ConflictComponent"), attributes: { value: { converter: "Str", default: "bbb" } }, - $onTest: function() { + $onTest: function () { spy(this.attributes.get("value").Value); } }); @@ -203,15 +204,15 @@ export function testNodeBase() { } export function conflictNode1() { - const ns = GrimoireInterface.ns("test1"); - GrimoireInterface.registerNode(ns("conflict-node"), ["TestComponent2"], { + const ns = Namespace.define("test1"); + GrimoireInterface.registerNode(ns.for("conflict-node"), ["TestComponent2"], { attr1: "nodeA" }, null, null); } export function conflictNode2() { - const ns = GrimoireInterface.ns("test2"); - GrimoireInterface.registerNode(ns("conflict-node"), ["TestComponent2"], { + const ns = Namespace.define("test2"); + GrimoireInterface.registerNode(ns.for("conflict-node"), ["TestComponent2"], { attr1: "nodeB" }, null, null); } From 592327be39cad75e95c11b73e4f6e1fd3467d987 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 18 Sep 2017 23:46:33 +0900 Subject: [PATCH 019/146] fix: add Environment manager --- src/Core/ComponentDeclaration.ts | 3 ++- src/Core/Environment.ts | 7 +++++++ src/Core/GomlLoader.ts | 3 ++- src/Core/GomlNode.ts | 5 +++-- src/Core/GomlParser.ts | 3 ++- src/Core/GrimoireInterfaceImpl.ts | 3 ++- src/Tools/XMLReader.ts | 5 ++--- src/main.ts | 9 +++++++-- test/Core/GomlLoaderTest.ts | 14 ++++++-------- test/Core/GomlNodeTest.ts | 14 ++++---------- test/Core/GomlParserTest.ts | 11 ++++++----- test/PageLoadingHelper.ts | 10 ++++------ test/TestEnvManager.ts | 16 ++++++++++++---- 13 files changed, 59 insertions(+), 44 deletions(-) create mode 100644 src/Core/Environment.ts diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index 6efc0698a..5ffac79c4 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -8,6 +8,7 @@ import IdResolver from "../Tools/IdResolver"; import Component from "./Component"; import Ensure from "../Tools/Ensure"; import {Ctor, Name, ComponentRegistering} from "../Tools/Types"; +import Environment from "./Environment"; export default class ComponentDeclaration { public static ctorMap: { ctor: ComponentRegistering>, name: NSIdentity }[] = []; @@ -43,7 +44,7 @@ export default class ComponentDeclaration { if (!this.isDependenyResolved) { this.resolveDependency(); } - componentElement = componentElement ? componentElement : document.createElementNS(this.name.ns.qualifiedName, this.name.name); + componentElement = componentElement ? componentElement : Environment.document.createElementNS(this.name.ns.qualifiedName, this.name.name); const component = new this.ctor(); componentElement.setAttribute(Constants.x_gr_id, component.id); GrimoireInterface.componentDictionary[component.id] = component; diff --git a/src/Core/Environment.ts b/src/Core/Environment.ts new file mode 100644 index 000000000..1b613dc51 --- /dev/null +++ b/src/Core/Environment.ts @@ -0,0 +1,7 @@ +export class Environment { + public document: Document; + public Node: any; + public DomParser: DOMParser; +} + +export default new Environment(); diff --git a/src/Core/GomlLoader.ts b/src/Core/GomlLoader.ts index 8f57a4dee..9d62778cd 100644 --- a/src/Core/GomlLoader.ts +++ b/src/Core/GomlLoader.ts @@ -2,6 +2,7 @@ import GrimoireInterface from "../Core/GrimoireInterface"; import GomlParser from "./GomlParser"; import XMLReader from "../Tools/XMLReader"; import XMLHttpRequestAsync from "../Tools/XMLHttpRequestAsync"; +import Environment from "./Environment"; /** * Provides the features to fetch Goml source. @@ -39,7 +40,7 @@ export default class GomlLoader { * @return {Promise} [the promise to wait for all goml loading] */ public static async loadFromQuery(query: string): Promise { - const tags = document.querySelectorAll(query); + const tags = Environment.document.querySelectorAll(query); const pArray: Promise[] = []; const elements: HTMLScriptElement[] = []; for (let i = 0; i < tags.length; i++) { diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index e75d5da6a..cec2a7774 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -15,6 +15,7 @@ import NSIdentity from "../Core/NSIdentity"; import Ensure from "../Tools/Ensure"; import MessageException from "../Tools/MessageException"; import { Name, GomlInterface, Nullable, Ctor } from "../Tools/Types"; +import Environment from "./Environment"; export default class GomlNode extends EEObject { @@ -150,8 +151,8 @@ export default class GomlNode extends EEObject { recipe.resolveDependency(); } this.nodeDeclaration = recipe; - this.element = element ? element : document.createElementNS(recipe.name.ns.qualifiedName, recipe.name.name); - this.componentsElement = document.createElement("COMPONENTS"); + this.element = element ? element : Environment.document.createElementNS(recipe.name.ns.qualifiedName, recipe.name.name); + this.componentsElement = Environment.document.createElement("COMPONENTS"); this._root = this; this._components = []; this._attributeManager = new AttributeManager(recipe.name.name); diff --git a/src/Core/GomlParser.ts b/src/Core/GomlParser.ts index f7f4df7ee..d04fd80a2 100644 --- a/src/Core/GomlParser.ts +++ b/src/Core/GomlParser.ts @@ -1,5 +1,6 @@ import GomlNode from "./GomlNode"; import GrimoireInterface from "../Core/GrimoireInterface"; +import Environment from "./Environment"; /** * Parser of Goml to Node utilities. @@ -93,7 +94,7 @@ class GomlParser { } private static _isElement(node: Node): node is Element { - return node.nodeType === Node.ELEMENT_NODE; + return node.nodeType === Environment.Node.ELEMENT_NODE; } private static _isComponentsTag(element: Element): boolean { diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index a107cbc3e..e2b861f29 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -26,6 +26,7 @@ import Namespace from "../Core/Namespace"; import NSDictionary from "../Tools/NSDictionary"; import Ensure from "../Tools/Ensure"; import { Name, Nullable, Ctor, ComponentRegistering } from "../Tools/Types"; +import Environment from "./Environment"; export default class GrimoireInterfaceImpl extends EEObject { @@ -260,7 +261,7 @@ export default class GrimoireInterfaceImpl extends EEObject { } public queryRootNodes(query: string): GomlNode[] { - const scriptTags = document.querySelectorAll(query); + const scriptTags = Environment.document.querySelectorAll(query); const nodes: GomlNode[] = []; for (let i = 0; i < scriptTags.length; i++) { const node = this.getRootNode(scriptTags.item(i)); diff --git a/src/Tools/XMLReader.ts b/src/Tools/XMLReader.ts index 6b592a1ca..b23146dba 100644 --- a/src/Tools/XMLReader.ts +++ b/src/Tools/XMLReader.ts @@ -1,14 +1,13 @@ import { Nullable } from "./Types"; +import Environment from "../Core/Environment"; /** * Provides safe xml read feature. */ export default class XMLReader { - public static parser: DOMParser; - public static parseXML(doc: string, rootElementName?: string): Element[] { - const parsed = XMLReader.parser.parseFromString(doc as string, "text/xml"); + const parsed = Environment.DomParser.parseFromString(doc, "text/xml"); if (!parsed || parsed.getElementsByTagName("parsererror").length > 0) { const err = new XMLSerializer().serializeToString(parsed); throw new Error(`Error parsing XML: ${err}`); diff --git a/src/main.ts b/src/main.ts index ce62dddfa..be2700b75 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,6 +1,6 @@ import GrimoireInterface from "./Core/GrimoireInterface"; import GomlLoader from "./Core/GomlLoader"; -import XMLReader from "./Tools/XMLReader"; +import Environment from "./Core/Environment"; /** * Provides procedures for initializing. @@ -28,8 +28,13 @@ class GrimoireInitializer { } } + /** + * inject browser environment + */ private static _injectDependency(): void { - XMLReader.parser = new DOMParser(); + Environment.DomParser = new DOMParser(); + Environment.document = document; + Environment.Node = Node; } /** diff --git a/test/Core/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts index 94fae3086..b82a4df75 100644 --- a/test/Core/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -25,6 +25,7 @@ import { conflictComponent1, conflictComponent2 } from "../DummyObjectRegisterer"; +import Environment from "../../src/Core/Environment"; TestEnvManager.init(); @@ -66,9 +67,6 @@ function mockXMLParse(func) { test.beforeEach(async () => { GrimoireInterface.clear(); - global.Node = { - ELEMENT_NODE: 1 - }; goml(); testNode1(); testNode2(); @@ -82,7 +80,7 @@ test.beforeEach(async () => { test("Processing script[type=\"text/goml\"] tag correctly when the text content was existing", async (t) => { const window = await jsdomAsync(testcase1_html, []); - global.document = window.document; + Environment.document = window.document; const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); const spy = sinon.spy(); const mockedParseXML = mockXMLParse(xml => { @@ -95,7 +93,7 @@ test("Processing script[type=\"text/goml\"] tag correctly when the text content test("Processing script[type=\"text/goml\"] and call parse related methods in correct order", async (t) => { const src = testcase1_html; const window = await jsdomAsync(src, []); - global.document = window.document; + Environment.document = window.document; const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); const spy = sinon.spy(); const mockedParseXML = mockXMLParse(xml => { @@ -108,7 +106,7 @@ test("Processing script[type=\"text/goml\"] and call parse related methods in co test("Processing script[type=\"text/goml\"] tag correctly when the src attribute was existing", async (t) => { const src = testcase2_html; const window = await jsdomAsync(src, []); - global.document = window.document; + Environment.document = window.document; const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); const spy = sinon.spy(); const mockedParseXML = mockXMLParse(xml => { @@ -122,7 +120,7 @@ test("Processing script[type=\"text/goml\"] tag correctly when the src attribute test("Processing goml scripts from query", async (t) => { const src = testcase3_html; const window = await jsdomAsync(src, []); - global.document = window.document; + Environment.document = window.document; const spy = sinon.spy(); const mockedParseXML = mockXMLParse(xml => { spy(xml.trim()); @@ -134,7 +132,7 @@ test("Processing goml scripts from query", async (t) => { test("Processing goml scripts for page", async (t) => { const src = testcase4_html; const window = await jsdomAsync(src, []); - global.document = window.document; + Environment.document = window.document; const spy = sinon.spy(); const mockedParseXML = mockXMLParse(xml => { spy(xml.trim()); diff --git a/test/Core/GomlNodeTest.ts b/test/Core/GomlNodeTest.ts index fb33aa807..78da8a8ff 100644 --- a/test/Core/GomlNodeTest.ts +++ b/test/Core/GomlNodeTest.ts @@ -2,6 +2,7 @@ require("babel-polyfill"); import xmldom from "xmldom"; import test from "ava"; import sinon from "sinon"; +import TestEnvManager from "../TestEnvManager"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; @@ -10,22 +11,15 @@ import GomlLoader from "../../src/Core/GomlLoader"; import NSIdentity from "../../src/Core/NSIdentity"; import GomlNode from "../../src/Core/GomlNode"; import Attribute from "../../src/Core/Attribute"; +import Environment from "../../src/Core/Environment"; -declare namespace global { - let Node: any; - let document: any; - let rootNode: any; -} - -global.Node = { - ELEMENT_NODE: 1 -}; +TestEnvManager.init(); test.beforeEach(async () => { GrimoireInterface.clear(); const parser = new xmldom.DOMParser(); const htmlDoc = parser.parseFromString("", "text/html"); - global.document = htmlDoc; + Environment.document = htmlDoc; GrimoireInterface.registerNode("goml"); GrimoireInterface.registerNode("scenes"); GrimoireInterface.registerNode("scene"); diff --git a/test/Core/GomlParserTest.ts b/test/Core/GomlParserTest.ts index bb4f10cbd..9eccb6e9d 100644 --- a/test/Core/GomlParserTest.ts +++ b/test/Core/GomlParserTest.ts @@ -1,8 +1,9 @@ require("babel-polyfill"); import test from "ava"; import sinon from "sinon"; -import GomlParser from "../../src/Core/GomlParser"; import xmldom from "xmldom"; +import TestEnvManager from "../TestEnvManager"; +import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import NSIdentity from "../../src/Core/NSIdentity"; import Namespace from "../../src/Core/Namespace"; @@ -22,6 +23,9 @@ import { conflictComponent1, conflictComponent2 } from "../DummyObjectRegisterer"; +import Environment from "../../src/Core/Environment"; + +TestEnvManager.init(); declare namespace global { let Node: any; @@ -32,9 +36,6 @@ declare namespace global { // Get element from test case source which is located with relative path. function obtainElementTag(path) { - global.Node = { - ELEMENT_NODE: 1 - }; const parser = new xmldom.DOMParser(); return parser.parseFromString(fs.readFile(path), "text/xml").documentElement; } @@ -51,7 +52,7 @@ test.beforeEach(async () => { GrimoireInterface.clear(); const parser = new xmldom.DOMParser(); const htmlDoc = parser.parseFromString("", "text/html"); - global.document = htmlDoc; + Environment.document = htmlDoc; goml(); testNode1(); testNode2(); diff --git a/test/PageLoadingHelper.ts b/test/PageLoadingHelper.ts index 000571080..b1c2fad74 100644 --- a/test/PageLoadingHelper.ts +++ b/test/PageLoadingHelper.ts @@ -20,6 +20,7 @@ import { conflictComponent1, conflictComponent2 } from "./DummyObjectRegisterer"; +import Environment from "../src/Core/Environment"; declare namespace global { let Node: any; @@ -32,12 +33,9 @@ export default class PageLoadingHelper { const parser = new xmldom.DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); - global.document = htmlDoc; - global.document.querySelectorAll = function() { - return global.document.getElementsByTagName("script"); - }; - global.Node = { - ELEMENT_NODE: 1 + Environment.document = htmlDoc; + Environment.document.querySelectorAll = function() { + return Environment.document.getElementsByTagName("script"); }; goml(); testNode1(); diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index e246c1582..63e76e7c5 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -8,6 +8,9 @@ import IConverterRepository from "../src/Interface/Repository/IConverterReposito import NSDictionary from "../src/Tools/NSDictionary"; import NSIdentity from "../src/Core/NSIdentity"; import fs from "./fileHelper"; +import GomlLoader from "../src/Core/GomlLoader"; +import GrimoireInterface from "../src/Core/GrimoireInterface"; +import Environment from "../src/Core/Environment"; declare namespace global { let Node: any; @@ -26,13 +29,18 @@ export default class TestEnvManager { } public static async init() { - XMLReader.parser = new xmldom.DOMParser(); - // Attribute.converterRepository = TestEnvManager.context; + Environment.DomParser = new xmldom.DOMParser(); const testcase1_html = fs.readFile("../_TestResource/GomlLoaderTest_Case1.html"); const window = await jsdomAsync(testcase1_html, []); - global.document = window.document; - global.Node = { + Environment.document = window.document; + Environment.Node = { ELEMENT_NODE: 1 }; } + + public static async loadPage(html: string) { + const window = await jsdomAsync(html, []); + Environment.document = window.document; + await GomlLoader.loadForPage(); + } } From 19d8f4d3b2708b4bf2818488a6ca7fa0759ed05a Mon Sep 17 00:00:00 2001 From: moajo Date: Wed, 20 Sep 2017 01:20:11 +0900 Subject: [PATCH 020/146] fix: refactor test --- test/Core/GomlLoaderTest.ts | 5 --- test/Core/GomlNode2Test.ts | 26 +++++++++-- test/Core/GrimoireInterfaceTest.ts | 7 --- test/Core/NodeInterfaceTest.ts | 22 ++++------ test/PageLoadingHelper.ts | 70 ------------------------------ test/TestEnvManager.ts | 29 +++++++++---- 6 files changed, 51 insertions(+), 108 deletions(-) delete mode 100644 test/PageLoadingHelper.ts diff --git a/test/Core/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts index b82a4df75..f63cbb966 100644 --- a/test/Core/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -29,11 +29,6 @@ import Environment from "../../src/Core/Environment"; TestEnvManager.init(); -declare namespace global { - let Node: any; - let document: any; -} - const testcase1_html = fs.readFile("../_TestResource/GomlLoaderTest_Case1.html"); const testcase2_html = fs.readFile("../_TestResource/GomlLoaderTest_Case2.html"); const testcase3_html = fs.readFile("../_TestResource/GomlLoaderTest_Case3.html"); diff --git a/test/Core/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts index 9a10ccca0..d8435c6f2 100644 --- a/test/Core/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -28,15 +28,14 @@ import NSIdentity from "../../src/Core/NSIdentity"; import GrimoireComponent from "../../src/Components/GrimoireComponent"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import fs from "../fileHelper"; -import PLH from "../PageLoadingHelper"; TestEnvManager.init(); const tc1_goml = fs.readFile("../_TestResource/GomlNodeTest_Case1.goml"); const tc1_html = fs.readFile("../_TestResource/GomlNodeTest_Case1.html"); -PLH.mockSetup(); -PLH.mock("./GomlNodeTest_Case1.goml", tc1_goml); +TestEnvManager.mockSetup(); +TestEnvManager.mock("./GomlNodeTest_Case1.goml", tc1_goml); let stringConverterSpy, testComponent1Spy, @@ -60,7 +59,26 @@ function resetSpies() { let rootNode: GomlNode; test.beforeEach(async () => { - let spys = await PLH.reset(GrimoireInterface, tc1_html); + GrimoireInterface.clear(); + goml(); + testNode1(); + testNode2(); + testNode3(); + testNodeBase(); + conflictNode1(); + conflictNode2(); + const spys: any = {}; + spys.stringConverterSpy = stringConverter(); + spys.testComponent1Spy = testComponent1(); + spys.testComponent2Spy = testComponent2(); + spys.testComponent3Spy = testComponent3(); + spys.testComponentBaseSpy = testComponentBase(); + spys.testComponentOptionalSpy = testComponentOptional(); + spys.conflictComponent1Spy = conflictComponent1(); + spys.conflictComponent2Spy = conflictComponent2(); + await GrimoireInterface.resolvePlugins(); + await TestEnvManager.loadPage(tc1_html); + stringConverterSpy = spys.stringConverterSpy; testComponent1Spy = spys.testComponent1Spy; testComponent2Spy = spys.testComponent2Spy; diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index 2994bcb3f..25f7f4be7 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -14,13 +14,6 @@ import TestEnvManager from "../TestEnvManager"; TestEnvManager.init(); -declare namespace global { - let Node: any; - let document: any; -} - -// global.document = new xmldom.DOMParser().parseFromString("", "text/html"); - test.beforeEach(() => { GrimoireInterface.clear(); GrimoireInterface.resolvePlugins(); diff --git a/test/Core/NodeInterfaceTest.ts b/test/Core/NodeInterfaceTest.ts index 4b4f8c10c..a09638083 100644 --- a/test/Core/NodeInterfaceTest.ts +++ b/test/Core/NodeInterfaceTest.ts @@ -24,6 +24,7 @@ import { import GomlLoader from "../../src/Core/GomlLoader"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import fs from "../fileHelper"; +import Environment from "../../src/Core/Environment"; TestEnvManager.init(); @@ -54,22 +55,17 @@ function resetSpies() { conflictComponent1Spy.reset(); conflictComponent2Spy.reset(); } -declare namespace global { - let document: any; - let Node: any; -} - test.beforeEach(async () => { GrimoireInterface.clear(); + // const window = await jsdomAsync(html, []); + // Environment.document = window.document; const parser = new xmldom.DOMParser(); const htmlDoc = parser.parseFromString(testcase1_html, "text/html"); - global.document = htmlDoc; - global.document.querySelectorAll = function(selector) { - return global.document.getElementsByTagName("script"); - }; - global.Node = { - ELEMENT_NODE: 1 + Environment.document = htmlDoc; + Environment.document.querySelectorAll = function(selector) { + return Environment.document.getElementsByTagName("script"); }; + goml(); testNode1(); testNode2(); @@ -87,8 +83,8 @@ test.beforeEach(async () => { conflictComponent2Spy = conflictComponent2(); await GrimoireInterface.resolvePlugins(); await GomlLoader.loadForPage(); - global["rootNode"] = _.values(GrimoireInterface.rootNodes)[0]; - global["rootNode"].element.ownerDocument = global["document"]; + Environment["rootNode"] = _.values(GrimoireInterface.rootNodes)[0]; + Environment["rootNode"].element.ownerDocument = Environment["document"]; }); test("count first single.", (t) => { diff --git a/test/PageLoadingHelper.ts b/test/PageLoadingHelper.ts deleted file mode 100644 index b1c2fad74..000000000 --- a/test/PageLoadingHelper.ts +++ /dev/null @@ -1,70 +0,0 @@ -import GrimoireInterface from "../src/Core/GrimoireInterface"; -import GomlLoader from "../src/Core/GomlLoader"; -import xhrmock from "xhr-mock"; -import xmldom from "xmldom"; - -import { - goml, - stringConverter, - testComponent1, - testComponent2, - testComponent3, - testComponentBase, - testComponentOptional, - testNode1, - testNode2, - testNode3, - testNodeBase, - conflictNode1, - conflictNode2, - conflictComponent1, - conflictComponent2 -} from "./DummyObjectRegisterer"; -import Environment from "../src/Core/Environment"; - -declare namespace global { - let Node: any; - let document: any; -} - -export default class PageLoadingHelper { - public static async reset(gr: typeof GrimoireInterface, html: string): Promise { - gr.clear(); - const parser = new xmldom.DOMParser(); - const htmlDoc = parser.parseFromString(html, "text/html"); - - Environment.document = htmlDoc; - Environment.document.querySelectorAll = function() { - return Environment.document.getElementsByTagName("script"); - }; - goml(); - testNode1(); - testNode2(); - testNode3(); - testNodeBase(); - conflictNode1(); - conflictNode2(); - const spys: any = {}; - spys.stringConverterSpy = stringConverter(); - spys.testComponent1Spy = testComponent1(); - spys.testComponent2Spy = testComponent2(); - spys.testComponent3Spy = testComponent3(); - spys.testComponentBaseSpy = testComponentBase(); - spys.testComponentOptionalSpy = testComponentOptional(); - spys.conflictComponent1Spy = conflictComponent1(); - spys.conflictComponent2Spy = conflictComponent2(); - await gr.resolvePlugins(); - await GomlLoader.loadForPage(); - return spys; - } - - public static mockSetup(): void { - xhrmock.setup(); - } - public static mock(path: string, content: string): void { - xhrmock.get(path, (req, res) => { - let aa = res.status(200).body(content); - return aa; - }); - } -} diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index 63e76e7c5..ff0085ede 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -11,11 +11,7 @@ import fs from "./fileHelper"; import GomlLoader from "../src/Core/GomlLoader"; import GrimoireInterface from "../src/Core/GrimoireInterface"; import Environment from "../src/Core/Environment"; - -declare namespace global { - let Node: any; - let document: any; -} +import xhrmock from "xhr-mock"; class TestEnvContext implements IConverterRepository { public converters: NSDictionary; @@ -30,17 +26,32 @@ export default class TestEnvManager { public static async init() { Environment.DomParser = new xmldom.DOMParser(); - const testcase1_html = fs.readFile("../_TestResource/GomlLoaderTest_Case1.html"); - const window = await jsdomAsync(testcase1_html, []); + // global.document = new xmldom.DOMParser().parseFromString("", "text/html"); + const window = await jsdomAsync("", []); Environment.document = window.document; Environment.Node = { ELEMENT_NODE: 1 }; } + public static mockSetup(): void { + xhrmock.setup(); + } + public static mock(path: string, content: string): void { + xhrmock.get(path, (req, res) => { + return res.status(200).body(content); + }); + } + + public static async loadPage(html: string) { - const window = await jsdomAsync(html, []); - Environment.document = window.document; + const parser = new xmldom.DOMParser(); + const htmlDoc = parser.parseFromString(html, "text/html"); + + Environment.document = htmlDoc; + Environment.document.querySelectorAll = function () { + return Environment.document.getElementsByTagName("script"); + }; await GomlLoader.loadForPage(); } } From 018999c064e46e928ae1e049118a168b007c0437 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 24 Sep 2017 20:30:26 +0900 Subject: [PATCH 021/146] fix: add test --- src/Converters/BooleanConverter.ts | 8 ++-- src/Converters/ComponentConverter.ts | 4 +- src/Converters/EnumConverter.ts | 7 ++- src/Converters/NumberConverter.ts | 17 ++++--- src/Converters/ObjectConverter.ts | 4 +- test/Converters/ArrayConverterTest.ts | 6 +++ test/Converters/BooleanConverterTest.ts | 16 +++++++ test/Converters/ComponentConverterTest.ts | 17 +++++++ test/Converters/EnumConverterTest.ts | 51 +++++++++++++++++++++ test/Converters/NumberArrayConverterTest.ts | 6 +++ test/Converters/NumberConverterTest.ts | 11 +++++ test/Converters/ObjectConverterTest.ts | 8 ++++ test/Converters/StringConverterTest.ts | 1 + 13 files changed, 139 insertions(+), 17 deletions(-) create mode 100644 test/Converters/ArrayConverterTest.ts create mode 100644 test/Converters/BooleanConverterTest.ts create mode 100644 test/Converters/ComponentConverterTest.ts create mode 100644 test/Converters/EnumConverterTest.ts create mode 100644 test/Converters/NumberArrayConverterTest.ts create mode 100644 test/Converters/NumberConverterTest.ts create mode 100644 test/Converters/ObjectConverterTest.ts diff --git a/src/Converters/BooleanConverter.ts b/src/Converters/BooleanConverter.ts index 8d03802bd..ef52265f3 100644 --- a/src/Converters/BooleanConverter.ts +++ b/src/Converters/BooleanConverter.ts @@ -1,13 +1,13 @@ /** - * booleanのためのコンバータです。 - * booleanはそのまま通します。 - * 文字列は、`true`,`false`のみ通します。 + * converter for booleam value. + * Pass through boolean value as it is. + * Pass through string value only 'true' or 'false'. * @param {any} val [description] * @param {Attribute} attr [description] * @return {any} [description] */ -export default function BooleanConverter(val: any): any { +export default function BooleanConverter(val: any): boolean { if (typeof val === "boolean") { return val; } else if (typeof val === "string") { diff --git a/src/Converters/ComponentConverter.ts b/src/Converters/ComponentConverter.ts index 55416aa86..199ee1b25 100644 --- a/src/Converters/ComponentConverter.ts +++ b/src/Converters/ComponentConverter.ts @@ -14,12 +14,12 @@ import Attribute from "../Core/Attribute"; */ export default { name: "Component", - verify: function(attr: Attribute) { + verify: function (attr: Attribute) { if (!attr.declaration["target"]) { throw new Error("Component converter require to be specified target"); } }, - convert: function(val: any, attr: Attribute) { + convert: function (val: any, attr: Attribute) { if (val === null) { return null; } diff --git a/src/Converters/EnumConverter.ts b/src/Converters/EnumConverter.ts index 3a71cdb20..cfb0c17ba 100644 --- a/src/Converters/EnumConverter.ts +++ b/src/Converters/EnumConverter.ts @@ -8,12 +8,15 @@ import Attribute from "../Core/Attribute"; */ export default { name: "Enum", - verify: function(attr: Attribute) { + verify: function (attr: Attribute) { if (!attr.declaration["table"]) { throw new Error("Enum converter needs to be specified table in attribute dictionary"); } }, - convert: function(val: any, attr: Attribute) { + convert: function (val: any, attr: Attribute) { + if (val === null) { + return null; + } if (typeof val === "number") { return val; } diff --git a/src/Converters/NumberConverter.ts b/src/Converters/NumberConverter.ts index 028221bc5..f06976c5d 100644 --- a/src/Converters/NumberConverter.ts +++ b/src/Converters/NumberConverter.ts @@ -1,4 +1,4 @@ -import {Nullable, Undef} from "../Tools/Types"; +import { Nullable, Undef } from "../Tools/Types"; /** * converter for number value. @@ -7,15 +7,18 @@ import {Nullable, Undef} from "../Tools/Types"; * @param {any} val [description] * @return {number} [description] */ -export default function NumberConverter(val: Nullable | string | Array): Undef { +export default function NumberConverter(val: any): number { if (typeof val === "number") { return val; - } else if (typeof val === "string") { - return Number.parseFloat(val); - } else if (val === null) { + } + if (typeof val === "string") { + let parsed = Number.parseFloat(val); + return Number.isNaN(parsed) ? void 0 : parsed; + } + if (val === null) { return null; - } else if (Array.isArray(val) && val.length === 1) { + } + if (Array.isArray(val) && val.length === 1) { return val[0]; } - return undefined; } diff --git a/src/Converters/ObjectConverter.ts b/src/Converters/ObjectConverter.ts index a7f1733e1..5f275dd60 100644 --- a/src/Converters/ObjectConverter.ts +++ b/src/Converters/ObjectConverter.ts @@ -1,6 +1,6 @@ /** - * オブジェクトのコンバータ。 - * 値をそのまま返します。 + * converter for object + * Pass through any value as it is. * @param {any} val [description] * @return {any} [description] */ diff --git a/test/Converters/ArrayConverterTest.ts b/test/Converters/ArrayConverterTest.ts new file mode 100644 index 000000000..1efab8760 --- /dev/null +++ b/test/Converters/ArrayConverterTest.ts @@ -0,0 +1,6 @@ +import test from "ava"; + +test("ArrayConverter should convert collectly", t => { + // TODO add test + t.truthy(true); +}); diff --git a/test/Converters/BooleanConverterTest.ts b/test/Converters/BooleanConverterTest.ts new file mode 100644 index 000000000..313f2fb71 --- /dev/null +++ b/test/Converters/BooleanConverterTest.ts @@ -0,0 +1,16 @@ +import test from "ava"; +import BooleanConverter from "../../src/Converters/BooleanConverter"; + +test("BooleanConverter should convert collectly", t => { + t.truthy(BooleanConverter(true) === true); + t.truthy(BooleanConverter(false) === false); + t.truthy(BooleanConverter("true") === true); + t.truthy(BooleanConverter("false") === false); + + t.truthy(BooleanConverter("aaaa") === void 0); + t.truthy(BooleanConverter("False") === void 0); + t.truthy(BooleanConverter("True") === void 0); + t.truthy(BooleanConverter("") === void 0); + t.truthy(BooleanConverter(null) === void 0); + t.truthy(BooleanConverter(123) === void 0); +}); diff --git a/test/Converters/ComponentConverterTest.ts b/test/Converters/ComponentConverterTest.ts new file mode 100644 index 000000000..a05f51c5c --- /dev/null +++ b/test/Converters/ComponentConverterTest.ts @@ -0,0 +1,17 @@ +import test from "ava"; + +import ComponentConverter from "../../src/Converters/ComponentConverter"; + +test("verify works correctly", t => { + t.notThrows(() => { + ComponentConverter.verify({ target: "hoge" } as any); + }); + t.throws(() => { + ComponentConverter.verify({} as any); + }); +}); + +test("ComponentConverter should convert collectly", t => { + // TODO add test + t.truthy(true); +}); diff --git a/test/Converters/EnumConverterTest.ts b/test/Converters/EnumConverterTest.ts new file mode 100644 index 000000000..5b0693aa0 --- /dev/null +++ b/test/Converters/EnumConverterTest.ts @@ -0,0 +1,51 @@ +import test from "ava"; + +import EnumConverter from "../../src/Converters/EnumConverter"; + +const mockAttrDec = { + declaration: { + coverter: "Enum", + default: "Hoge", + table: { + "first": 1, + "second": 2, + "third": 3 + } + } +} as any; + +const invalidMockAttrDec = { + declaration: { + coverter: "Enum", + default: "Hoge" + } +} as any; + +test("verify works correctly", t => { + t.notThrows(() => { + EnumConverter.verify(mockAttrDec); + }); + t.throws(() => { + EnumConverter.verify(invalidMockAttrDec); + }); +}); + +test("EnumConverter should convert collectly", t => { + t.truthy(EnumConverter.convert("first", mockAttrDec) === 1); + t.truthy(EnumConverter.convert("second", mockAttrDec) === 2); + t.truthy(EnumConverter.convert("third", mockAttrDec) === 3); + t.truthy(EnumConverter.convert(1, mockAttrDec) === 1); + t.truthy(EnumConverter.convert(2, mockAttrDec) === 2); + t.truthy(EnumConverter.convert(3, mockAttrDec) === 3); + t.truthy(EnumConverter.convert(4, mockAttrDec) === 4); + t.truthy(EnumConverter.convert(null, mockAttrDec) === null); + t.truthy(EnumConverter.convert({}, mockAttrDec) === void 0); + t.truthy(EnumConverter.convert(false, mockAttrDec) === void 0); + + t.throws(() => { + EnumConverter.convert("false", mockAttrDec); + }); + t.throws(() => { + EnumConverter.convert("", mockAttrDec); + }); +}); diff --git a/test/Converters/NumberArrayConverterTest.ts b/test/Converters/NumberArrayConverterTest.ts new file mode 100644 index 000000000..5e11aeb51 --- /dev/null +++ b/test/Converters/NumberArrayConverterTest.ts @@ -0,0 +1,6 @@ +import test from "ava"; + +test("NumberArrayConverter should convert collectly", t => { + // TODO add test + t.truthy(true); +}); diff --git a/test/Converters/NumberConverterTest.ts b/test/Converters/NumberConverterTest.ts new file mode 100644 index 000000000..928e9c626 --- /dev/null +++ b/test/Converters/NumberConverterTest.ts @@ -0,0 +1,11 @@ +import test from "ava"; +import NumberConverter from "../../src/Converters/NumberConverter"; + +test("NumberConverter should convert collectly", t => { + t.truthy(NumberConverter(123) === 123); + t.truthy(NumberConverter("123") === 123); + t.truthy(NumberConverter(null) === null); + t.truthy(NumberConverter([123]) === 123); + t.truthy(NumberConverter("this string can not convert to number") === void 0); + t.truthy(NumberConverter([123, 456]) === 123); +}); diff --git a/test/Converters/ObjectConverterTest.ts b/test/Converters/ObjectConverterTest.ts new file mode 100644 index 000000000..a15f9eec9 --- /dev/null +++ b/test/Converters/ObjectConverterTest.ts @@ -0,0 +1,8 @@ +import test from "ava"; +import ObjectConverter from "../../src/Converters/ObjectConverter"; + +test("ObjectConverter should convert collectly", t => { + t.truthy(ObjectConverter("HELLO") === "HELLO"); + t.truthy(ObjectConverter(null) === null); + t.truthy(ObjectConverter(123) === 123); +}); diff --git a/test/Converters/StringConverterTest.ts b/test/Converters/StringConverterTest.ts index 1b1df7029..1b1bd4a76 100644 --- a/test/Converters/StringConverterTest.ts +++ b/test/Converters/StringConverterTest.ts @@ -5,4 +5,5 @@ test("StringConverter should convert collectly", t => { t.truthy(StringConverter("HELLO") === "HELLO"); t.truthy(StringConverter(null) === null); t.truthy(StringConverter(123) === "123"); + t.truthy(StringConverter({ toString: () => "value" }) === "value"); }); From 7244573ce578c40dba1ada4cc64771b2d2a35966 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 25 Sep 2017 01:03:08 +0900 Subject: [PATCH 022/146] fix: refactor test --- src/Converters/BooleanConverter.ts | 5 +++- src/Converters/NumberConverter.ts | 5 ++-- src/Core/AttributeManager.ts | 7 ++--- src/Core/GomlInterfaceImpl.ts | 12 ++++++--- src/Core/GomlLoader.ts | 6 ++--- test/Converters/ComponentConverterTest.ts | 6 ++++- test/Converters/NumberConverterTest.ts | 3 ++- test/Core/AttributeTest.ts | 10 +++---- test/Core/ComponentDeclarationTest.ts | 4 ++- test/Core/GomlNode2Test.ts | 33 +++++++++++------------ test/Tools/IdResolverTest.ts | 17 ++++++------ 11 files changed, 61 insertions(+), 47 deletions(-) diff --git a/src/Converters/BooleanConverter.ts b/src/Converters/BooleanConverter.ts index ef52265f3..1ae51d718 100644 --- a/src/Converters/BooleanConverter.ts +++ b/src/Converters/BooleanConverter.ts @@ -1,3 +1,5 @@ +import { Undef } from "../Tools/Types"; + /** * converter for booleam value. @@ -7,7 +9,7 @@ * @param {Attribute} attr [description] * @return {any} [description] */ -export default function BooleanConverter(val: any): boolean { +export default function BooleanConverter(val: any): Undef { if (typeof val === "boolean") { return val; } else if (typeof val === "string") { @@ -18,4 +20,5 @@ export default function BooleanConverter(val: any): boolean { return false; } } + return void 0; } diff --git a/src/Converters/NumberConverter.ts b/src/Converters/NumberConverter.ts index f06976c5d..c58a176f8 100644 --- a/src/Converters/NumberConverter.ts +++ b/src/Converters/NumberConverter.ts @@ -1,4 +1,4 @@ -import { Nullable, Undef } from "../Tools/Types"; +import { Undef } from "../Tools/Types"; /** * converter for number value. @@ -7,7 +7,7 @@ import { Nullable, Undef } from "../Tools/Types"; * @param {any} val [description] * @return {number} [description] */ -export default function NumberConverter(val: any): number { +export default function NumberConverter(val: any): Undef { if (typeof val === "number") { return val; } @@ -21,4 +21,5 @@ export default function NumberConverter(val: any): number { if (Array.isArray(val) && val.length === 1) { return val[0]; } + return void 0; } diff --git a/src/Core/AttributeManager.ts b/src/Core/AttributeManager.ts index 2984eda51..f54489449 100644 --- a/src/Core/AttributeManager.ts +++ b/src/Core/AttributeManager.ts @@ -1,13 +1,14 @@ -import Utility from "../Tools/Utility"; import Attribute from "../Core/Attribute"; +import Ensure from "../Tools/Ensure"; import IdResolver from "../Tools/IdResolver"; +import { Name, Undef } from "../Tools/Types"; +import Utility from "../Tools/Utility"; import Namespace from "./Namespace"; import NSIdentity from "./NSIdentity"; -import Ensure from "../Tools/Ensure"; -import {Name, Undef} from "../Tools/Types"; type NameValPair = { fqn: string, val: T }; + class AttributeBuffer { private _fqnList: NameValPair[] = []; diff --git a/src/Core/GomlInterfaceImpl.ts b/src/Core/GomlInterfaceImpl.ts index 4eb9b5a80..c9213f88e 100644 --- a/src/Core/GomlInterfaceImpl.ts +++ b/src/Core/GomlInterfaceImpl.ts @@ -1,11 +1,12 @@ import Constants from "../Tools/Constants"; +import GomlNode from "../Core/GomlNode"; import GrimoireInterface from "../Core/GrimoireInterface"; import NodeInterface from "./NodeInterface"; -import GomlNode from "../Core/GomlNode"; + /** * Provides interfaces to treat whole goml tree for each. */ -class GomlInterface { +export default class GomlInterface { constructor(public rootNodes: GomlNode[]) { } @@ -14,6 +15,11 @@ class GomlInterface { return this.rootNodes.map(root => GomlNode.fromElement(root.element.ownerDocument.getElementById(id)!)); } + /** + * This function is executed when GOMLInterface is called as a function. + * Return all nodes matching the query as NodeInterface from rootNodes. + * @param query query string + */ public queryFunc(query: string): NodeInterface { return new NodeInterface(this._queryNodes(query)); } @@ -35,5 +41,3 @@ class GomlInterface { }); } } - -export default GomlInterface; diff --git a/src/Core/GomlLoader.ts b/src/Core/GomlLoader.ts index 9d62778cd..a0a4db5b1 100644 --- a/src/Core/GomlLoader.ts +++ b/src/Core/GomlLoader.ts @@ -1,8 +1,8 @@ -import GrimoireInterface from "../Core/GrimoireInterface"; +import Environment from "./Environment"; import GomlParser from "./GomlParser"; -import XMLReader from "../Tools/XMLReader"; +import GrimoireInterface from "../Core/GrimoireInterface"; import XMLHttpRequestAsync from "../Tools/XMLHttpRequestAsync"; -import Environment from "./Environment"; +import XMLReader from "../Tools/XMLReader"; /** * Provides the features to fetch Goml source. diff --git a/test/Converters/ComponentConverterTest.ts b/test/Converters/ComponentConverterTest.ts index a05f51c5c..45435587f 100644 --- a/test/Converters/ComponentConverterTest.ts +++ b/test/Converters/ComponentConverterTest.ts @@ -4,7 +4,11 @@ import ComponentConverter from "../../src/Converters/ComponentConverter"; test("verify works correctly", t => { t.notThrows(() => { - ComponentConverter.verify({ target: "hoge" } as any); + ComponentConverter.verify({ + declaration: { + target: "hoge" + } + } as any); }); t.throws(() => { ComponentConverter.verify({} as any); diff --git a/test/Converters/NumberConverterTest.ts b/test/Converters/NumberConverterTest.ts index 928e9c626..a11715743 100644 --- a/test/Converters/NumberConverterTest.ts +++ b/test/Converters/NumberConverterTest.ts @@ -1,4 +1,5 @@ import test from "ava"; + import NumberConverter from "../../src/Converters/NumberConverter"; test("NumberConverter should convert collectly", t => { @@ -7,5 +8,5 @@ test("NumberConverter should convert collectly", t => { t.truthy(NumberConverter(null) === null); t.truthy(NumberConverter([123]) === 123); t.truthy(NumberConverter("this string can not convert to number") === void 0); - t.truthy(NumberConverter([123, 456]) === 123); + t.truthy(NumberConverter([123, 456]) === void 0); }); diff --git a/test/Core/AttributeTest.ts b/test/Core/AttributeTest.ts index c99babcab..f1663bc29 100644 --- a/test/Core/AttributeTest.ts +++ b/test/Core/AttributeTest.ts @@ -1,15 +1,15 @@ -import TestEnvManager from "../TestEnvManager"; import test from "ava"; +import sinon from "sinon"; + +import GrimoireComponent from "../../src/Components/GrimoireComponent"; import Attribute from "../../src/Core/Attribute"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import TestUtil from "../TestUtil"; -import GrimoireComponent from "../../src/Components/GrimoireComponent"; -import sinon from "sinon"; import NSIdentity from "../../src/Core/NSIdentity"; +import TestEnvManager from "../TestEnvManager"; +import TestUtil from "../TestUtil"; TestEnvManager.init(); - const GOML = ``; test.beforeEach(async () => { diff --git a/test/Core/ComponentDeclarationTest.ts b/test/Core/ComponentDeclarationTest.ts index 743e19167..4bea9e954 100644 --- a/test/Core/ComponentDeclarationTest.ts +++ b/test/Core/ComponentDeclarationTest.ts @@ -1,9 +1,11 @@ import test from "ava"; -import TestEnvManager from "../TestEnvManager"; + import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import TestEnvManager from "../TestEnvManager"; TestEnvManager.init(); + test.beforeEach(async () => { GrimoireInterface.clear(); }); diff --git a/test/Core/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts index d8435c6f2..911737200 100644 --- a/test/Core/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -1,9 +1,20 @@ -import test from "ava"; -import sinon from "sinon"; -import xmldom from "xmldom"; import * as _ from "lodash"; +import Attribute from "../../src/Core/Attribute"; +import Component from "../../src/Core/Component"; +import fs from "../fileHelper"; +import GomlLoader from "../../src/Core/GomlLoader"; +import GomlNode from "../../src/Core/GomlNode"; +import GrimoireComponent from "../../src/Components/GrimoireComponent"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import NSIdentity from "../../src/Core/NSIdentity"; +import sinon from "sinon"; +import test from "ava"; import TestEnvManager from "../TestEnvManager"; import { + conflictComponent1, + conflictComponent2, + conflictNode1, + conflictNode2, goml, stringConverter, testComponent1, @@ -14,20 +25,8 @@ import { testNode1, testNode2, testNode3, - testNodeBase, - conflictNode1, - conflictNode2, - conflictComponent1, - conflictComponent2 -} from "../DummyObjectRegisterer"; -import GomlLoader from "../../src/Core/GomlLoader"; -import GomlNode from "../../src/Core/GomlNode"; -import Component from "../../src/Core/Component"; -import Attribute from "../../src/Core/Attribute"; -import NSIdentity from "../../src/Core/NSIdentity"; -import GrimoireComponent from "../../src/Components/GrimoireComponent"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import fs from "../fileHelper"; + testNodeBase + } from "../DummyObjectRegisterer"; TestEnvManager.init(); diff --git a/test/Tools/IdResolverTest.ts b/test/Tools/IdResolverTest.ts index f5954c530..f2e0cb5ce 100644 --- a/test/Tools/IdResolverTest.ts +++ b/test/Tools/IdResolverTest.ts @@ -1,16 +1,15 @@ -import test from "ava"; -require("babel-polyfill"); -import xmldom from "xmldom"; -import sinon from "sinon"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; -import GomlParser from "../../src/Core/GomlParser"; +import Constants from "../../src/Tools/Constants"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; -import NSIdentity from "../../src/Core/NSIdentity"; -import Namespace from "../../src/Core/Namespace"; +import GomlParser from "../../src/Core/GomlParser"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; import IdResolver from "../../src/Tools/IdResolver"; +import Namespace from "../../src/Core/Namespace"; +import NSIdentity from "../../src/Core/NSIdentity"; +import sinon from "sinon"; +import test from "ava"; +require("babel-polyfill"); test("get() works correctly.", t => { From 8a814398be1d1a3bd09205fb44dda4d28c23de32 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 25 Sep 2017 01:07:34 +0900 Subject: [PATCH 023/146] fix: add dependency on xmlserializer for test env --- package.json | 1 + src/Core/Environment.ts | 1 + src/Core/GomlNode.ts | 34 +++++++++++++-------------- src/Tools/XMLReader.ts | 4 ++-- src/main.ts | 5 ++-- test/Core/AttributeManagerTest.ts | 12 ++++------ test/TestEnvManager.ts | 38 +++++++++++++++++++------------ 7 files changed, 51 insertions(+), 44 deletions(-) diff --git a/package.json b/package.json index 133c4300a..ce9324180 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,7 @@ "webpack-shell-plugin": "^0.5.0", "xhr-mock": "^1.7.0", "xmldom": "^0.1.27", + "xmlserializer": "^0.6.0", "yargs": "^8.0.2" }, "repository": "http://github.com/GrimoireGL/GrimoireJS", diff --git a/src/Core/Environment.ts b/src/Core/Environment.ts index 1b613dc51..d82d37ce8 100644 --- a/src/Core/Environment.ts +++ b/src/Core/Environment.ts @@ -2,6 +2,7 @@ export class Environment { public document: Document; public Node: any; public DomParser: DOMParser; + public XMLSerializer: XMLSerializer; } export default new Environment(); diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index cec2a7774..fedeed4cd 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -1,28 +1,32 @@ -import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; +import Attribute from "./Attribute"; import AttributeManager from "../Core/AttributeManager"; -import Utility from "../Tools/Utility"; +import Component from "./Component"; import Constants from "../Tools/Constants"; +import EEObject from "../Base/EEObject"; +import Ensure from "../Tools/Ensure"; +import Environment from "./Environment"; import GomlParser from "./GomlParser"; -import XMLReader from "../Tools/XMLReader"; import GrimoireInterface from "../Core/GrimoireInterface"; -import EEObject from "../Base/EEObject"; -import Component from "./Component"; +import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; +import MessageException from "../Tools/MessageException"; import NodeDeclaration from "./NodeDeclaration"; import NodeUtility from "./NodeUtility"; -import Attribute from "./Attribute"; import NSDictionary from "../Tools/NSDictionary"; import NSIdentity from "../Core/NSIdentity"; -import Ensure from "../Tools/Ensure"; -import MessageException from "../Tools/MessageException"; -import { Name, GomlInterface, Nullable, Ctor } from "../Tools/Types"; -import Environment from "./Environment"; +import Utility from "../Tools/Utility"; +import XMLReader from "../Tools/XMLReader"; +import { + Ctor, + GomlInterface, + Name, + Nullable + } from "../Tools/Types"; export default class GomlNode extends EEObject { public element: Element; // Dom Element public nodeDeclaration: NodeDeclaration; public children: GomlNode[] = []; - public componentsElement: Element; // <.components> private _parent: Nullable = null; private _root: Nullable = null; @@ -152,7 +156,6 @@ export default class GomlNode extends EEObject { } this.nodeDeclaration = recipe; this.element = element ? element : Environment.document.createElementNS(recipe.name.ns.qualifiedName, recipe.name.name); - this.componentsElement = Environment.document.createElement("COMPONENTS"); this._root = this; this._components = []; this._attributeManager = new AttributeManager(recipe.name.name); @@ -498,8 +501,6 @@ export default class GomlNode extends EEObject { component.isDefaultComponent = !!isDefaultComponent; component.node = this; - let referenceElement = (this.componentsElement as any)[NodeUtility.getNodeListIndexByElementIndex(this.componentsElement, this._components.length)]; - this.componentsElement.insertBefore(component.element, referenceElement); // bind this for message reciever. let propNames: string[] = []; @@ -542,8 +543,8 @@ export default class GomlNode extends EEObject { removeTargets.push(c); } } - removeTargets.forEach(c => { - let b = this.removeComponent(c); + removeTargets.forEach(c => { + let b = this.removeComponent(c); result = result || b; }); return result; @@ -554,7 +555,6 @@ export default class GomlNode extends EEObject { if (index !== -1) { this._sendMessageForcedTo(component, "unmount"); this._sendMessageForcedTo(component, "dispose"); - this.componentsElement.removeChild(component.element); this._components.splice(index, 1); this._messageCache = {}; // TODO:optimize. delete component.node; diff --git a/src/Tools/XMLReader.ts b/src/Tools/XMLReader.ts index b23146dba..b21cdb26e 100644 --- a/src/Tools/XMLReader.ts +++ b/src/Tools/XMLReader.ts @@ -1,5 +1,5 @@ -import { Nullable } from "./Types"; import Environment from "../Core/Environment"; +import { Nullable } from "./Types"; /** * Provides safe xml read feature. @@ -9,7 +9,7 @@ export default class XMLReader { public static parseXML(doc: string, rootElementName?: string): Element[] { const parsed = Environment.DomParser.parseFromString(doc, "text/xml"); if (!parsed || parsed.getElementsByTagName("parsererror").length > 0) { - const err = new XMLSerializer().serializeToString(parsed); + const err = Environment.XMLSerializer.serializeToString(parsed); throw new Error(`Error parsing XML: ${err}`); } if (rootElementName) { diff --git a/src/main.ts b/src/main.ts index be2700b75..9e6f43a82 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,6 +1,6 @@ -import GrimoireInterface from "./Core/GrimoireInterface"; -import GomlLoader from "./Core/GomlLoader"; import Environment from "./Core/Environment"; +import GomlLoader from "./Core/GomlLoader"; +import GrimoireInterface from "./Core/GrimoireInterface"; /** * Provides procedures for initializing. @@ -35,6 +35,7 @@ class GrimoireInitializer { Environment.DomParser = new DOMParser(); Environment.document = document; Environment.Node = Node; + Environment.XMLSerializer = new XMLSerializer(); } /** diff --git a/test/Core/AttributeManagerTest.ts b/test/Core/AttributeManagerTest.ts index 75be1e758..c06e430ee 100644 --- a/test/Core/AttributeManagerTest.ts +++ b/test/Core/AttributeManagerTest.ts @@ -1,14 +1,10 @@ import test from "ava"; -import Ensure from "../../src/Tools/Ensure"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import NSDictionary from "../../src/Tools/NSDictionary"; +import sinon from "sinon"; + +import Attribute from "../../src/Core/Attribute"; import AttributeManager from "../../src/Core/AttributeManager"; import NSIdentity from "../../src/Core/NSIdentity"; -import Constants from "../../src/Tools/Constants"; -import Attribute from "../../src/Core/Attribute"; -import sinon from "sinon"; -import ComponentDeclaration from "../../src/Core/ComponentDeclaration"; -import TestUtil from "../TestUtil"; + const genAttr: (name: NSIdentity, watch?: Function | undefined) => Attribute = (name, watch) => { return { name: name, watch: watch, Value: "value of " + name } as Attribute; diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index ff0085ede..fa82c194f 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -1,17 +1,20 @@ -require("babel-polyfill"); -import XMLReader from "../src/Tools/XMLReader"; -import xmldom from "xmldom"; -import jsdomAsync from "./JsDOMAsync"; -import Attribute from "../src/Core/Attribute"; +import Environment from "../src/Core/Environment"; +import GomlLoader from "../src/Core/GomlLoader"; +import GomlParser from "../src/Core/GomlParser"; +import GrimoireInterface from "../src/Core/GrimoireInterface"; import IAttributeConverterDeclaration from "../src/Interface/IAttributeConverterDeclaration"; import IConverterRepository from "../src/Interface/Repository/IConverterRepository"; +import jsdomAsync from "./JsDOMAsync"; import NSDictionary from "../src/Tools/NSDictionary"; import NSIdentity from "../src/Core/NSIdentity"; -import fs from "./fileHelper"; -import GomlLoader from "../src/Core/GomlLoader"; -import GrimoireInterface from "../src/Core/GrimoireInterface"; -import Environment from "../src/Core/Environment"; import xhrmock from "xhr-mock"; +import xmldom from "xmldom"; +import XMLReader from "../src/Tools/XMLReader"; +import xmlserializer from "xmlserializer"; +import "babel-polyfill"; + + + class TestEnvContext implements IConverterRepository { public converters: NSDictionary; @@ -25,13 +28,14 @@ export default class TestEnvManager { } public static async init() { - Environment.DomParser = new xmldom.DOMParser(); - // global.document = new xmldom.DOMParser().parseFromString("", "text/html"); const window = await jsdomAsync("", []); + Environment.DomParser = new window.DOMParser(); + Environment.document = window.document; Environment.Node = { ELEMENT_NODE: 1 }; + Environment.XMLSerializer = xmlserializer; } public static mockSetup(): void { @@ -45,13 +49,17 @@ export default class TestEnvManager { public static async loadPage(html: string) { - const parser = new xmldom.DOMParser(); - const htmlDoc = parser.parseFromString(html, "text/html"); - - Environment.document = htmlDoc; + const window = await jsdomAsync(html, []); + Environment.document = window.document; Environment.document.querySelectorAll = function () { return Environment.document.getElementsByTagName("script"); }; await GomlLoader.loadForPage(); } + + public static loadGoml(goml: string) { + const doc = XMLReader.parseXML(goml, "GOML"); + const rootNode = GomlParser.parse(doc[0]); + GrimoireInterface.addRootNode(null, rootNode); + } } From 4a9d1b4447af52bf6bfa2472d27ede915282ecb9 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 25 Sep 2017 01:09:53 +0900 Subject: [PATCH 024/146] fix: Allow to call addRootNode without specifying scriptTag element --- src/Core/GrimoireInterfaceImpl.ts | 54 ++++++++++++++++++------------- 1 file changed, 31 insertions(+), 23 deletions(-) diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index e2b861f29..1a14237cb 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -1,32 +1,38 @@ +import ArrayConverter from "../Converters/ArrayConverter"; +import Attribute from "./Attribute"; +import BooleanConverter from "../Converters/BooleanConverter"; +import Component from "../Core/Component"; +import ComponentConverter from "../Converters/ComponentConverter"; +import ComponentDeclaration from "../Core/ComponentDeclaration"; +import Constants from "../Tools/Constants"; import EEObject from "../Base/EEObject"; -import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; -import GomlLoader from "../Core/GomlLoader"; +import Ensure from "../Tools/Ensure"; import EnumConverter from "../Converters/EnumConverter"; -import NumberArrayConverter from "../Converters/NumberArrayConverter"; -import ComponentConverter from "../Converters/ComponentConverter"; -import NumberConverter from "../Converters/NumberConverter"; -import ObjectConverter from "../Converters/ObjectConverter"; -import ArrayConverter from "../Converters/ArrayConverter"; -import NodeInterface from "../Core/NodeInterface"; -import Utility from "../Tools/Utility"; +import Environment from "./Environment"; import GomlInterfaceImpl from "../Core/GomlInterfaceImpl"; -import BooleanConverter from "../Converters/BooleanConverter"; +import GomlLoader from "../Core/GomlLoader"; +import GomlNode from "../Core/GomlNode"; import GrimoireComponent from "../Components/GrimoireComponent"; -import StringArrayConverter from "../Converters/StringArrayConverter"; -import StringConverter from "../Converters/StringConverter"; -import Attribute from "../Core/Attribute"; -import Constants from "../Tools/Constants"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; -import GomlNode from "../Core/GomlNode"; -import ComponentDeclaration from "../Core/ComponentDeclaration"; -import Component from "../Core/Component"; -import NodeDeclaration from "../Core/NodeDeclaration"; -import NSIdentity from "../Core/NSIdentity"; import Namespace from "../Core/Namespace"; +import NodeDeclaration from "../Core/NodeDeclaration"; +import NodeInterface from "./NodeInterface"; import NSDictionary from "../Tools/NSDictionary"; -import Ensure from "../Tools/Ensure"; -import { Name, Nullable, Ctor, ComponentRegistering } from "../Tools/Types"; -import Environment from "./Environment"; +import NSIdentity from "../Core/NSIdentity"; +import NumberArrayConverter from "../Converters/NumberArrayConverter"; +import NumberConverter from "../Converters/NumberConverter"; +import ObjectConverter from "../Converters/ObjectConverter"; +import StringArrayConverter from "../Converters/StringArrayConverter"; +import StringConverter from "../Converters/StringConverter"; +import Utility from "../Tools/Utility"; +import { + ComponentRegistering, + Ctor, + Name, + Nullable + } from "../Tools/Types"; + export default class GrimoireInterfaceImpl extends EEObject { @@ -221,7 +227,9 @@ export default class GrimoireInterfaceImpl extends EEObject { if (!rootNode) { throw new Error("can not register null to rootNodes."); } - tag.setAttribute("x-rootNodeId", rootNode.id); + if (tag) { + tag.setAttribute("x-rootNodeId", rootNode.id); + } this.rootNodes[rootNode.id] = rootNode; rootNode.companion.set(Namespace.define(Constants.defaultNamespace).for("scriptElement"), tag); From 2076bb335fec1750128b2a7a9da8591ca43e6a25 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 25 Sep 2017 01:39:19 +0900 Subject: [PATCH 025/146] fix: add test --- test/Core/GomlInterfaceTest.ts | 26 ++++++++++++++++-- test/Core/GomlLoaderTest.ts | 43 +++++++++++++++++++++--------- test/Core/NodeInterfaceTest.ts | 31 +++++++++++---------- test/Tools/IdResolverTest.ts | 17 ++++++------ test/_TestResource/Example_01.html | 21 +++++++++++++++ test/_TestResource/Goml_01.goml | 3 +++ test/_TestResource/Goml_02.goml | 5 ++++ 7 files changed, 107 insertions(+), 39 deletions(-) create mode 100644 test/_TestResource/Example_01.html create mode 100644 test/_TestResource/Goml_01.goml create mode 100644 test/_TestResource/Goml_02.goml diff --git a/test/Core/GomlInterfaceTest.ts b/test/Core/GomlInterfaceTest.ts index 91deb5a73..f82e83fa6 100644 --- a/test/Core/GomlInterfaceTest.ts +++ b/test/Core/GomlInterfaceTest.ts @@ -1,5 +1,27 @@ +import fs from "../fileHelper"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; import test from "ava"; +import TestEnvManager from "../TestEnvManager"; -test("check init for attribute manager", (t) => { - t.truthy(true, "TODO: write test"); + + +TestEnvManager.init(); +const example_html = fs.readFile("../_TestResource/Example_01.html"); + +test.beforeEach(async () => { + GrimoireInterface.clear(); + GrimoireInterface.registerNode("goml"); + await TestEnvManager.loadPage(example_html); +}); + +test("rootNodes works correctly", (t) => { + // t.truthy(true); + let gomlInterface = GrimoireInterface("*"); + t.truthy(gomlInterface.rootNodes.length === 3, "all nodes should be retrieved"); + + gomlInterface = GrimoireInterface("#first"); + t.truthy(gomlInterface.rootNodes.length === 1, "parent node should be retrieved"); + + gomlInterface = GrimoireInterface(".child"); + t.truthy(gomlInterface.rootNodes.length === 0, "all child nodes should be retrieved"); }); diff --git a/test/Core/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts index f63cbb966..e96400021 100644 --- a/test/Core/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -1,14 +1,19 @@ -import prequire from "proxyquire"; +import Environment from "../../src/Core/Environment"; +import fs from "../fileHelper"; +import GomlParser from "../../src/Core/GomlParser"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; import jsdomAsync from "../JsDOMAsync"; -import test from "ava"; +import prequire from "proxyquire"; import sinon from "sinon"; +import test from "ava"; +import TestEnvManager from "../TestEnvManager"; import xhrmock from "xhr-mock"; import XMLReader from "../../src/Tools/XMLReader"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import GomlParser from "../../src/Core/GomlParser"; -import fs from "../fileHelper"; -import TestEnvManager from "../TestEnvManager"; import { + conflictComponent1, + conflictComponent2, + conflictNode1, + conflictNode2, goml, stringConverter, testComponent1, @@ -19,13 +24,8 @@ import { testNode1, testNode2, testNode3, - testNodeBase, - conflictNode1, - conflictNode2, - conflictComponent1, - conflictComponent2 -} from "../DummyObjectRegisterer"; -import Environment from "../../src/Core/Environment"; + testNodeBase + } from "../DummyObjectRegisterer"; TestEnvManager.init(); @@ -73,6 +73,23 @@ test.beforeEach(async () => { await GrimoireInterface.resolvePlugins(); }); +// test("loadForPage throw Error if goml is invalid.", async (t) => { +// const window = await jsdomAsync("", []); +// Environment.document = window.document; +// const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); +// const spy = sinon.spy(); +// const mockedParseXML = mockXMLParse(xml => { +// spy(xml.replace(/[\n\s]/g, "")); +// }); +// t.throws(async () => { +// try { +// await mockedParseXML.loadFromScriptTag(scriptTags.item(0)); +// } catch (e) { +// t.truthy(false); +// } +// }); +// }); + test("Processing script[type=\"text/goml\"] tag correctly when the text content was existing", async (t) => { const window = await jsdomAsync(testcase1_html, []); Environment.document = window.document; diff --git a/test/Core/NodeInterfaceTest.ts b/test/Core/NodeInterfaceTest.ts index a09638083..239cbb5b5 100644 --- a/test/Core/NodeInterfaceTest.ts +++ b/test/Core/NodeInterfaceTest.ts @@ -1,10 +1,18 @@ -import test from "ava"; -import sinon from "sinon"; -import xmldom from "xmldom"; -import xhrmock from "xhr-mock"; import * as _ from "lodash"; +import Environment from "../../src/Core/Environment"; +import fs from "../fileHelper"; +import GomlLoader from "../../src/Core/GomlLoader"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import sinon from "sinon"; +import test from "ava"; import TestEnvManager from "../TestEnvManager"; +import xhrmock from "xhr-mock"; +import xmldom from "xmldom"; import { + conflictComponent1, + conflictComponent2, + conflictNode1, + conflictNode2, goml, stringConverter, testComponent1, @@ -15,16 +23,8 @@ import { testNode1, testNode2, testNode3, - testNodeBase, - conflictNode1, - conflictNode2, - conflictComponent1, - conflictComponent2 -} from "../DummyObjectRegisterer"; -import GomlLoader from "../../src/Core/GomlLoader"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import fs from "../fileHelper"; -import Environment from "../../src/Core/Environment"; + testNodeBase + } from "../DummyObjectRegisterer"; TestEnvManager.init(); @@ -62,7 +62,7 @@ test.beforeEach(async () => { const parser = new xmldom.DOMParser(); const htmlDoc = parser.parseFromString(testcase1_html, "text/html"); Environment.document = htmlDoc; - Environment.document.querySelectorAll = function(selector) { + Environment.document.querySelectorAll = function (selector) { return Environment.document.getElementsByTagName("script"); }; @@ -84,7 +84,6 @@ test.beforeEach(async () => { await GrimoireInterface.resolvePlugins(); await GomlLoader.loadForPage(); Environment["rootNode"] = _.values(GrimoireInterface.rootNodes)[0]; - Environment["rootNode"].element.ownerDocument = Environment["document"]; }); test("count first single.", (t) => { diff --git a/test/Tools/IdResolverTest.ts b/test/Tools/IdResolverTest.ts index f2e0cb5ce..f5954c530 100644 --- a/test/Tools/IdResolverTest.ts +++ b/test/Tools/IdResolverTest.ts @@ -1,15 +1,16 @@ -import Component from "../../src/Core/Component"; +import test from "ava"; +require("babel-polyfill"); +import xmldom from "xmldom"; +import sinon from "sinon"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Constants from "../../src/Tools/Constants"; +import Component from "../../src/Core/Component"; +import GomlParser from "../../src/Core/GomlParser"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; -import GomlParser from "../../src/Core/GomlParser"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import IdResolver from "../../src/Tools/IdResolver"; -import Namespace from "../../src/Core/Namespace"; import NSIdentity from "../../src/Core/NSIdentity"; -import sinon from "sinon"; -import test from "ava"; -require("babel-polyfill"); +import Namespace from "../../src/Core/Namespace"; +import IdResolver from "../../src/Tools/IdResolver"; test("get() works correctly.", t => { diff --git a/test/_TestResource/Example_01.html b/test/_TestResource/Example_01.html new file mode 100644 index 000000000..c306b9f81 --- /dev/null +++ b/test/_TestResource/Example_01.html @@ -0,0 +1,21 @@ + + + + + + + + + + diff --git a/test/_TestResource/Goml_01.goml b/test/_TestResource/Goml_01.goml new file mode 100644 index 000000000..7b0b4e673 --- /dev/null +++ b/test/_TestResource/Goml_01.goml @@ -0,0 +1,3 @@ + + + diff --git a/test/_TestResource/Goml_02.goml b/test/_TestResource/Goml_02.goml new file mode 100644 index 000000000..3ca9afd25 --- /dev/null +++ b/test/_TestResource/Goml_02.goml @@ -0,0 +1,5 @@ + + + + + From 802e154d28574864c8804fad3956405abf1d39a2 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 25 Sep 2017 17:59:03 +0900 Subject: [PATCH 026/146] fix: remove GomlInterface.getNodeById() --- src/Core/GomlInterfaceImpl.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Core/GomlInterfaceImpl.ts b/src/Core/GomlInterfaceImpl.ts index c9213f88e..a4acdb3ba 100644 --- a/src/Core/GomlInterfaceImpl.ts +++ b/src/Core/GomlInterfaceImpl.ts @@ -11,10 +11,6 @@ export default class GomlInterface { } - public getNodeById(id: string): GomlNode[] { - return this.rootNodes.map(root => GomlNode.fromElement(root.element.ownerDocument.getElementById(id)!)); - } - /** * This function is executed when GOMLInterface is called as a function. * Return all nodes matching the query as NodeInterface from rootNodes. From 60839284c57816d3c7cf123391502481bd5d7366 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 25 Sep 2017 18:01:59 +0900 Subject: [PATCH 027/146] fix: fix test --- test/Core/GomlInterfaceTest.ts | 13 ++++--------- test/TestEnvManager.ts | 3 --- test/_TestResource/Example_01.html | 2 +- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/test/Core/GomlInterfaceTest.ts b/test/Core/GomlInterfaceTest.ts index f82e83fa6..698c437a0 100644 --- a/test/Core/GomlInterfaceTest.ts +++ b/test/Core/GomlInterfaceTest.ts @@ -1,3 +1,4 @@ +import Environment from "../../src/Core/Environment"; import fs from "../fileHelper"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import test from "ava"; @@ -15,13 +16,7 @@ test.beforeEach(async () => { }); test("rootNodes works correctly", (t) => { - // t.truthy(true); - let gomlInterface = GrimoireInterface("*"); - t.truthy(gomlInterface.rootNodes.length === 3, "all nodes should be retrieved"); - - gomlInterface = GrimoireInterface("#first"); - t.truthy(gomlInterface.rootNodes.length === 1, "parent node should be retrieved"); - - gomlInterface = GrimoireInterface(".child"); - t.truthy(gomlInterface.rootNodes.length === 0, "all child nodes should be retrieved"); + t.truthy(GrimoireInterface("*").rootNodes.length === 3, "all nodes should be retrieved"); + t.truthy(GrimoireInterface("#first").rootNodes.length === 1, "parent node should be retrieved"); + t.truthy(GrimoireInterface(".child").rootNodes.length === 0, "all child nodes should be retrieved"); }); diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index fa82c194f..949d4bb5e 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -51,9 +51,6 @@ export default class TestEnvManager { public static async loadPage(html: string) { const window = await jsdomAsync(html, []); Environment.document = window.document; - Environment.document.querySelectorAll = function () { - return Environment.document.getElementsByTagName("script"); - }; await GomlLoader.loadForPage(); } diff --git a/test/_TestResource/Example_01.html b/test/_TestResource/Example_01.html index c306b9f81..b2e35f028 100644 --- a/test/_TestResource/Example_01.html +++ b/test/_TestResource/Example_01.html @@ -1,7 +1,7 @@ - From 2a1947e5819e56e21de00eafd041334e5c7252e0 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 25 Sep 2017 18:09:03 +0900 Subject: [PATCH 028/146] fix: merge NodeUtility into Utility --- src/Core/Component.ts | 23 +++++++++++------------ src/Core/GomlNode.ts | 7 +++---- src/Core/NodeUtility.ts | 30 ------------------------------ src/Tools/Utility.ts | 23 +++++++++++++++++++++++ 4 files changed, 37 insertions(+), 46 deletions(-) delete mode 100644 src/Core/NodeUtility.ts diff --git a/src/Core/Component.ts b/src/Core/Component.ts index 66113d908..ee2734e3a 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -1,15 +1,14 @@ -import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; -import Utility from "../Tools/Utility"; -import Constants from "../Tools/Constants"; -import NodeUtility from "./NodeUtility"; -import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import Attribute from "./Attribute"; +import Constants from "../Tools/Constants"; +import Ensure from "../Tools/Ensure"; import GomlNode from "./GomlNode"; +import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +import IDObject from "../Base/IDObject"; +import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; import NSDictionary from "../Tools/NSDictionary"; import NSIdentity from "../Core/NSIdentity"; -import IDObject from "../Base/IDObject"; -import Ensure from "../Tools/Ensure"; -import {GomlInterface, Nullable, Name} from "../Tools/Types"; +import Utility from "../Tools/Utility"; +import { GomlInterface, Name, Nullable } from "../Tools/Types"; /** * Base class for any components @@ -126,12 +125,12 @@ export default class Component extends IDObject { return Utility.remove(this._handlers, observer); } - public resolveDefaultAttributes(nodeAttributes?: { [key: string]: string; } |null): any { + public resolveDefaultAttributes(nodeAttributes?: { [key: string]: string; } | null): any { const nodeAttr = nodeAttributes || {}; if (this.isDefaultComponent) { // If this is default component, the default attribute values should be retrived from node DOM. this.attributes.forEach(attr => attr.resolveDefaultValue(nodeAttr)); } else { // If not,the default value of attributes should be retrived from this element. - const attrs = NodeUtility.getAttributes(this.element); + const attrs = Utility.getAttributes(this.element); for (let key in attrs) { if (key === Constants.x_gr_id) { continue; @@ -185,9 +184,9 @@ export default class Component extends IDObject { const attr = Attribute.generateAttributeForComponent(name, attribute, this); this.node.addAttribute(attr); if (this.isDefaultComponent) { // If this is default component, the default attribute values should be retrived from node DOM. - attr.resolveDefaultValue(NodeUtility.getAttributes(this.node.element)); + attr.resolveDefaultValue(Utility.getAttributes(this.node.element)); } else { // If not,the default value of attributes should be retrived from this element. - const attrs = NodeUtility.getAttributes(this.element); + const attrs = Utility.getAttributes(this.element); attr.resolveDefaultValue(attrs); } this._additionalAttributesNames.push(attr.name); diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index fedeed4cd..545832556 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -10,7 +10,6 @@ import GrimoireInterface from "../Core/GrimoireInterface"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; import MessageException from "../Tools/MessageException"; import NodeDeclaration from "./NodeDeclaration"; -import NodeUtility from "./NodeUtility"; import NSDictionary from "../Tools/NSDictionary"; import NSIdentity from "../Core/NSIdentity"; import Utility from "../Tools/Utility"; @@ -324,7 +323,7 @@ export default class GomlNode extends EEObject { // sync html if (elementSync) { - let referenceElement = (this.element as any)[NodeUtility.getNodeListIndexByElementIndex(this.element, insertIndex)]; + let referenceElement = (this.element as any)[Utility.getNodeListIndexByElementIndex(this.element, insertIndex)]; this.element.insertBefore(child.element, referenceElement); } @@ -518,7 +517,7 @@ export default class GomlNode extends EEObject { // attributes should be exposed on node component.attributes.forEach(p => this.addAttribute(p)); if (this._defaultValueResolved) { - component.attributes.forEach(p => p.resolveDefaultValue(NodeUtility.getAttributes(this.element))); + component.attributes.forEach(p => p.resolveDefaultValue(Utility.getAttributes(this.element))); } if (this._mounted) { @@ -645,7 +644,7 @@ export default class GomlNode extends EEObject { */ public resolveAttributesValue(): void { this._defaultValueResolved = true; - const attrs = NodeUtility.getAttributes(this.element); + const attrs = Utility.getAttributes(this.element); for (let key in attrs) { if (key === Constants.x_gr_id) { continue; diff --git a/src/Core/NodeUtility.ts b/src/Core/NodeUtility.ts deleted file mode 100644 index 64bc1c915..000000000 --- a/src/Core/NodeUtility.ts +++ /dev/null @@ -1,30 +0,0 @@ -export default class NodeUtility { // TODO merge with Base/XMLReader - /** - * Get index of NodeList converted from index in Element - * @param {HTMLElement} targetElement Parent element of search target elements - * @param {number} elementIndex Index in element - * @return {number} Index in NodeList - */ - public static getNodeListIndexByElementIndex(targetElement: Element, elementIndex: number): number { - const nodeArray: Node[] = Array.prototype.slice.call(targetElement.childNodes); - const elementArray = nodeArray.filter((v) => { - return v.nodeType === 1; - }); - elementIndex = elementIndex < 0 ? elementArray.length + elementIndex : elementIndex; - return nodeArray.indexOf(elementArray[elementIndex]); - } - - public static getAttributes(element: Element): { [key: string]: string } { - const attributes: { [key: string]: string } = {}; - const domAttr = element.attributes; - for (let i = 0; i < domAttr.length; i++) { - const attrNode = domAttr.item(i); - if (attrNode.name.startsWith("xmlns")) { - continue; - } - const name = attrNode.namespaceURI ? attrNode.namespaceURI + "." + attrNode.localName! : attrNode.localName!; - attributes[name] = attrNode.value; - } - return attributes; - } -} diff --git a/src/Tools/Utility.ts b/src/Tools/Utility.ts index 5602c69ce..a5b389f28 100644 --- a/src/Tools/Utility.ts +++ b/src/Tools/Utility.ts @@ -72,4 +72,27 @@ export default class Utility { } return true; } + + public static getNodeListIndexByElementIndex(targetElement: Element, elementIndex: number): number { + const nodeArray: Node[] = Array.prototype.slice.call(targetElement.childNodes); + const elementArray = nodeArray.filter((v) => { + return v.nodeType === 1; + }); + elementIndex = elementIndex < 0 ? elementArray.length + elementIndex : elementIndex; + return nodeArray.indexOf(elementArray[elementIndex]); + } + + public static getAttributes(element: Element): { [key: string]: string } { + const attributes: { [key: string]: string } = {}; + const domAttr = element.attributes; + for (let i = 0; i < domAttr.length; i++) { + const attrNode = domAttr.item(i); + if (attrNode.name.startsWith("xmlns")) { + continue; + } + const name = attrNode.namespaceURI ? attrNode.namespaceURI + "." + attrNode.localName! : attrNode.localName!; + attributes[name] = attrNode.value; + } + return attributes; + } } From b44f3151db28e75697387d790a5eeb73fec6ad03 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 25 Sep 2017 19:03:25 +0900 Subject: [PATCH 029/146] fix: convert from Array on NumberConverter tobe deprecated --- src/Converters/NumberConverter.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Converters/NumberConverter.ts b/src/Converters/NumberConverter.ts index c58a176f8..41adde99a 100644 --- a/src/Converters/NumberConverter.ts +++ b/src/Converters/NumberConverter.ts @@ -1,3 +1,4 @@ +import Utility from "../Tools/Utility"; import { Undef } from "../Tools/Types"; /** @@ -19,7 +20,11 @@ export default function NumberConverter(val: any): Undef { return null; } if (Array.isArray(val) && val.length === 1) { - return val[0]; + Utility.w(`[Deprecated] converting from Array is deprecated in NumberConverter.`); + let ret = val[0]; + if (typeof ret === "number") { + return ret; + } } return void 0; } From 68c681a33eeba251002becc204942ff10d114452 Mon Sep 17 00:00:00 2001 From: moajo Date: Mon, 25 Sep 2017 19:28:14 +0900 Subject: [PATCH 030/146] fix: add GomlLoader test --- test/Core/GomlLoaderTest.ts | 60 ++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 34 deletions(-) diff --git a/test/Core/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts index e96400021..bf7ca34cf 100644 --- a/test/Core/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -1,5 +1,7 @@ import Environment from "../../src/Core/Environment"; import fs from "../fileHelper"; +import GomlLoader from "../../src/Core/GomlLoader"; +import GomlNode from "../../src/Core/GomlNode"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import jsdomAsync from "../JsDOMAsync"; @@ -73,38 +75,16 @@ test.beforeEach(async () => { await GrimoireInterface.resolvePlugins(); }); -// test("loadForPage throw Error if goml is invalid.", async (t) => { -// const window = await jsdomAsync("", []); -// Environment.document = window.document; -// const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); -// const spy = sinon.spy(); -// const mockedParseXML = mockXMLParse(xml => { -// spy(xml.replace(/[\n\s]/g, "")); -// }); -// t.throws(async () => { -// try { -// await mockedParseXML.loadFromScriptTag(scriptTags.item(0)); -// } catch (e) { -// t.truthy(false); -// } -// }); -// }); - -test("Processing script[type=\"text/goml\"] tag correctly when the text content was existing", async (t) => { - const window = await jsdomAsync(testcase1_html, []); +test("loadForPage throw Error if goml syntax is invalid.", async (t) => { + const window = await jsdomAsync("", []); Environment.document = window.document; const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); - const spy = sinon.spy(); - const mockedParseXML = mockXMLParse(xml => { - spy(xml.replace(/[\n\s]/g, "")); - }); - await mockedParseXML.loadFromScriptTag(scriptTags.item(0)); - t.truthy(spy.calledWith(``)); + + await t.throws(GomlLoader.loadFromScriptTag(scriptTags.item(0))); }); -test("Processing script[type=\"text/goml\"] and call parse related methods in correct order", async (t) => { - const src = testcase1_html; - const window = await jsdomAsync(src, []); +test("Processing script[type=\"text/goml\"] tag correctly when the text content was existing", async (t) => { + const window = await jsdomAsync(testcase1_html, []); Environment.document = window.document; const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); const spy = sinon.spy(); @@ -116,8 +96,7 @@ test("Processing script[type=\"text/goml\"] and call parse related methods in co }); test("Processing script[type=\"text/goml\"] tag correctly when the src attribute was existing", async (t) => { - const src = testcase2_html; - const window = await jsdomAsync(src, []); + const window = await jsdomAsync(testcase2_html, []); Environment.document = window.document; const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); const spy = sinon.spy(); @@ -130,8 +109,7 @@ test("Processing script[type=\"text/goml\"] tag correctly when the src attribute }); test("Processing goml scripts from query", async (t) => { - const src = testcase3_html; - const window = await jsdomAsync(src, []); + const window = await jsdomAsync(testcase3_html, []); Environment.document = window.document; const spy = sinon.spy(); const mockedParseXML = mockXMLParse(xml => { @@ -142,8 +120,7 @@ test("Processing goml scripts from query", async (t) => { }); test("Processing goml scripts for page", async (t) => { - const src = testcase4_html; - const window = await jsdomAsync(src, []); + const window = await jsdomAsync(testcase4_html, []); Environment.document = window.document; const spy = sinon.spy(); const mockedParseXML = mockXMLParse(xml => { @@ -152,3 +129,18 @@ test("Processing goml scripts for page", async (t) => { await mockedParseXML.loadForPage(); t.truthy(spy.calledWith("\n")); }); + +test("all text/goml scripts tags should be loaded on loadForPage", async (t) => { + const spy = sinon.spy(); + const original = GrimoireInterface.addRootNode.bind(GrimoireInterface); + GrimoireInterface.addRootNode = (tag: HTMLScriptElement, rootNode: GomlNode) => { + spy(tag); + return original(tag, rootNode); + }; + + await TestEnvManager.loadPage(testcase4_html); + t.truthy(spy.callCount === 4); +}); + + + From 6174270ca3eba1cb5e9a61d6874b29be398aec70 Mon Sep 17 00:00:00 2001 From: moajo Date: Tue, 26 Sep 2017 09:22:44 +0900 Subject: [PATCH 031/146] fix: add devDependencies @types/sinon --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index ce9324180..be693fd45 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "eventemitter3": "^2.0.3" }, "devDependencies": { + "@types/sinon": "^2.3.5", "ava": "^0.22.0", "babel-cli": "^6.26.0", "babel-loader": "^7.1.2", From 1b98ad73564e06406dabd47128028024f1d8ffa7 Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 29 Sep 2017 21:53:44 +0900 Subject: [PATCH 032/146] fix: recursive import problem --- src/Converters/ArrayConverter.ts | 6 +- src/Core/Attribute.ts | 16 ++-- src/Core/ComponentDeclaration.ts | 24 +++--- src/Core/Environment.ts | 3 + src/Core/GrimoireInterface.ts | 4 +- src/Tools/Ensure.ts | 19 +++-- src/Tools/Utility.ts | 5 +- test/Converters/NumberConverterTest.ts | 6 +- test/Core/AttributeManagerTest.ts | 25 +++--- test/Core/AttributeTest.ts | 22 ++--- test/Core/ComponentDeclarationTest.ts | 5 +- test/Core/GomlLoaderTest.ts | 49 +++++------- test/Core/GomlNode2Test.ts | 80 +++++++++---------- test/Core/GomlNodeTest.ts | 21 +++-- test/Core/GomlParserTest.ts | 40 +++++----- test/Core/GrimoireInterfaceTest.ts | 28 +++---- test/Core/NSIdentityTest.ts | 5 +- test/Core/NamespaceTest.ts | 11 ++- test/Core/NodeInterfaceTest.ts | 1 - test/DummyObjectRegisterer.ts | 80 +++++++++---------- test/Tools/IdResolverTest.ts | 17 ++-- test/Tools/NSDictionaryTest.ts | 14 ++-- .../GrimoireInterfaceTest_Case1.html | 68 ++++++++-------- 23 files changed, 276 insertions(+), 273 deletions(-) diff --git a/src/Converters/ArrayConverter.ts b/src/Converters/ArrayConverter.ts index 89256e428..a4f42f2ce 100644 --- a/src/Converters/ArrayConverter.ts +++ b/src/Converters/ArrayConverter.ts @@ -1,5 +1,5 @@ -import GrimoireInterface from "../Core/GrimoireInterface"; import Attribute from "../Core/Attribute"; +import GrimoireInterface from "../Core/GrimoireInterface"; const splitter = " "; const escape = "\\"; @@ -14,12 +14,12 @@ const escape = "\\"; */ export default { name: "Array", - verify: function(attr: Attribute) { + verify: function (attr: Attribute) { if (!attr.declaration["type"]) { throw new Error("Array converter needs to be specified type in attribute declaration."); } }, - convert: function(val: any, attr: Attribute) { + convert: function (val: any, attr: Attribute) { let converter = GrimoireInterface.converters.get(attr.declaration["type"]); if (!converter) { throw new Error(`converter ${attr.declaration["type"]} is not registerd.`); diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index 34b5d5636..36f9046fe 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -1,12 +1,12 @@ -import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; -import NSDictionary from "../Tools/NSDictionary"; +import Component from "./Component"; import Ensure from "../Tools/Ensure"; +import Environment from "../Core/Environment"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; -import NSIdentity from "../Core/NSIdentity"; import IdResolver from "../Tools/IdResolver"; -import GrimoireInterface from "../Core/GrimoireInterface"; -import Component from "./Component"; -import {GomlInterface, Name, Nullable} from "../Tools/Types"; +import NSDictionary from "../Tools/NSDictionary"; +import NSIdentity from "../Core/NSIdentity"; +import { GomlInterface, Name, Nullable } from "../Tools/Types"; /** * Manage a attribute attached to components. @@ -95,7 +95,7 @@ export default class Attribute { public static convert(converter: Name, self: Attribute, val: any): any { // TODO unuse? const cname = Ensure.tobeNSIdentity(converter); - const conv = GrimoireInterface.converters.get(cname); + const conv = Environment.GrimoireInterface.converters.get(cname); if (!conv) { throw new Error(`converter ${cname.name} is not defined.`); } @@ -116,7 +116,7 @@ export default class Attribute { attr.component = component; attr.declaration = declaration; const converterName = Ensure.tobeNSIdentity(declaration.converter); - attr.converter = GrimoireInterface.converters.get(converterName); + attr.converter = Environment.GrimoireInterface.converters.get(converterName); if (attr.converter === void 0) { // When the specified converter was not found throw new Error(`Specified converter ${converterName.name} was not found from registered converters.\n Component: ${attr.component.name.fqn}\n Attribute: ${attr.name.name}`); diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index 5ffac79c4..01b503975 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -1,14 +1,14 @@ -import Constants from "../Tools/Constants"; -import GrimoireInterface from "../Core/GrimoireInterface"; import Attribute from "./Attribute"; -import NSDictionary from "../Tools/NSDictionary"; -import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; -import NSIdentity from "../Core/NSIdentity"; -import IdResolver from "../Tools/IdResolver"; import Component from "./Component"; +import Constants from "../Tools/Constants"; import Ensure from "../Tools/Ensure"; -import {Ctor, Name, ComponentRegistering} from "../Tools/Types"; -import Environment from "./Environment"; +import Environment from "../Core/Environment"; +import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +import IdResolver from "../Tools/IdResolver"; +import NSDictionary from "../Tools/NSDictionary"; +import NSIdentity from "../Core/NSIdentity"; +import { ComponentRegistering, Ctor, Name } from "../Tools/Types"; + export default class ComponentDeclaration { public static ctorMap: { ctor: ComponentRegistering>, name: NSIdentity }[] = []; @@ -47,7 +47,7 @@ export default class ComponentDeclaration { componentElement = componentElement ? componentElement : Environment.document.createElementNS(this.name.ns.qualifiedName, this.name.name); const component = new this.ctor(); componentElement.setAttribute(Constants.x_gr_id, component.id); - GrimoireInterface.componentDictionary[component.id] = component; + Environment.GrimoireInterface.componentDictionary[component.id] = component; component.name = this.name; component.element = componentElement; component.attributes = new NSDictionary(); @@ -65,7 +65,7 @@ export default class ComponentDeclaration { let dec; if (this._super || this.superComponent) { // inherits const id = this._super ? Ensure.tobeNSIdentity(this._super) : this.superComponent["name"]; - dec = GrimoireInterface.componentDeclarations.get(id); + dec = Environment.GrimoireInterface.componentDeclarations.get(id); dec.resolveDependency(); for (let key in dec.attributes) { attr[key] = dec.attributes[key]; @@ -94,7 +94,7 @@ export default class ComponentDeclaration { if (typeof obj === "function") { // obj is constructor const inheritsAttr = this._extractInheritsAttributes(obj); if (baseConstructor) { // inherits - const newCtor = function(this: any) { + const newCtor = function (this: any) { baseConstructor.call(this); obj.call(this); }; @@ -113,7 +113,7 @@ export default class ComponentDeclaration { throw new Error("Base component comstructor must extends Compoent class."); } const ctor = baseConstructor || Component; - const newCtor = function(this: any) { + const newCtor = function (this: any) { ctor.call(this); }; (obj as any).__proto__ = ctor.prototype; diff --git a/src/Core/Environment.ts b/src/Core/Environment.ts index d82d37ce8..661d56e4a 100644 --- a/src/Core/Environment.ts +++ b/src/Core/Environment.ts @@ -1,8 +1,11 @@ +import { GrimoireInterface } from "../Tools/Types"; + export class Environment { public document: Document; public Node: any; public DomParser: DOMParser; public XMLSerializer: XMLSerializer; + public GrimoireInterface: GrimoireInterface; } export default new Environment(); diff --git a/src/Core/GrimoireInterface.ts b/src/Core/GrimoireInterface.ts index e4b8328d6..248260eff 100644 --- a/src/Core/GrimoireInterface.ts +++ b/src/Core/GrimoireInterface.ts @@ -1,6 +1,7 @@ -import GrimoireInterfaceImpl from "./GrimoireInterfaceImpl"; +import Environment from "./Environment"; import GomlInterfaceImpl from "./GomlInterfaceImpl"; import GomlNode from "../Core/GomlNode"; +import GrimoireInterfaceImpl from "./GrimoireInterfaceImpl"; import { GomlInterface, GrimoireInterface } from "../Tools/Types"; @@ -29,4 +30,5 @@ function obtainGomlInterface(query: string | GomlNode[] | (() => void)): void | } } Object.setPrototypeOf(obtainGomlInterface, context); +Environment.GrimoireInterface = obtainGomlInterface as GrimoireInterface; export default obtainGomlInterface as GrimoireInterface; diff --git a/src/Tools/Ensure.ts b/src/Tools/Ensure.ts index e7b1a1767..0824868e7 100644 --- a/src/Tools/Ensure.ts +++ b/src/Tools/Ensure.ts @@ -1,10 +1,15 @@ -import GrimoireInterface from "../Core/GrimoireInterface"; -import NSIdentity from "../Core/NSIdentity"; -// import Namespace from "./Namespace"; -import NSDictionary from "./NSDictionary"; -import {Name, Nullable, Ctor, ComponentRegistering} from "./Types"; -import ComponentDeclaration from "../Core/ComponentDeclaration"; import Component from "../Core/Component"; +import ComponentDeclaration from "../Core/ComponentDeclaration"; +import Environment from "../Core/Environment"; +import NSDictionary from "./NSDictionary"; +import NSIdentity from "../Core/NSIdentity"; +import { + ComponentRegistering, + Ctor, + Name, + Nullable + } from "./Types"; + /** * Provides static methods to ensure arguments are valid type. */ @@ -117,7 +122,7 @@ export default class Ensure { if (typeof c === "function") { return c; } else { - const dec = GrimoireInterface.componentDeclarations.get(c); + const dec = Environment.GrimoireInterface.componentDeclarations.get(c); if (dec) { return dec.ctor as any as Ctor; } diff --git a/src/Tools/Utility.ts b/src/Tools/Utility.ts index a5b389f28..634fa1018 100644 --- a/src/Tools/Utility.ts +++ b/src/Tools/Utility.ts @@ -1,9 +1,8 @@ -import GrimoireInterface from "../Core/GrimoireInterface"; - +import Environment from "../Core/Environment"; export default class Utility { public static w(message: string): void { - if (GrimoireInterface.debug) { + if (Environment.GrimoireInterface.debug) { console.warn(message); } } diff --git a/test/Converters/NumberConverterTest.ts b/test/Converters/NumberConverterTest.ts index a11715743..a3376f415 100644 --- a/test/Converters/NumberConverterTest.ts +++ b/test/Converters/NumberConverterTest.ts @@ -1,6 +1,10 @@ +import NumberConverter from "../../src/Converters/NumberConverter"; import test from "ava"; +import TestEnvManager from "../TestEnvManager"; -import NumberConverter from "../../src/Converters/NumberConverter"; + + +TestEnvManager.init(); test("NumberConverter should convert collectly", t => { t.truthy(NumberConverter(123) === 123); diff --git a/test/Core/AttributeManagerTest.ts b/test/Core/AttributeManagerTest.ts index c06e430ee..fa9213e77 100644 --- a/test/Core/AttributeManagerTest.ts +++ b/test/Core/AttributeManagerTest.ts @@ -1,9 +1,12 @@ -import test from "ava"; -import sinon from "sinon"; - import Attribute from "../../src/Core/Attribute"; import AttributeManager from "../../src/Core/AttributeManager"; import NSIdentity from "../../src/Core/NSIdentity"; +import test from "ava"; +import TestEnvManager from "../TestEnvManager"; +import { assert, spy as sinonSpy } from "sinon"; + +TestEnvManager.init(); + const genAttr: (name: NSIdentity, watch?: Function | undefined) => Attribute = (name, watch) => { @@ -63,7 +66,7 @@ test("addAttribute with value/watch buffers should works correctly", (t) => { t.truthy(attr.Value === "hogehoge"); const fqn2 = "notregisterd.fqn.hoge2"; - const spy = sinon.spy(); + const spy = sinonSpy(); const attrRaw = new Attribute(); attrRaw.name = NSIdentity.fromFQN(fqn2); attrRaw.component = { isActive: true } as any; @@ -73,7 +76,7 @@ test("addAttribute with value/watch buffers should works correctly", (t) => { }); am.setAttribute(attrRaw.name.fqn, "not called"); - t.truthy(!sinon.called); + t.truthy(!spy.called); am.addAttribute(attrRaw); am.setAttribute(attrRaw.name.fqn, "called"); @@ -88,9 +91,9 @@ test("addAttribute with value/watch buffers should works correctly", (t) => { test("watch should works correctly", () => { const am = genAM(); - const spy1 = sinon.spy(); - const spy2 = sinon.spy(); - const notCalledSpy = sinon.spy(); + const spy1 = sinonSpy(); + const spy2 = sinonSpy(); + const notCalledSpy = sinonSpy(); am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"), () => { spy1("watch"); })); @@ -101,9 +104,9 @@ test("watch should works correctly", () => { notCalledSpy("watch"); })); am.watch(NSIdentity.guess("hoge.aaa"), (a, b, c) => { /*do nothing*/ }); - sinon.assert.called(spy1); - sinon.assert.called(spy2); - sinon.assert.notCalled(notCalledSpy); + assert.called(spy1); + assert.called(spy2); + assert.notCalled(notCalledSpy); }); test("set/getAttribute should works correctly", (t) => { diff --git a/test/Core/AttributeTest.ts b/test/Core/AttributeTest.ts index f1663bc29..541cc11af 100644 --- a/test/Core/AttributeTest.ts +++ b/test/Core/AttributeTest.ts @@ -1,12 +1,12 @@ -import test from "ava"; -import sinon from "sinon"; - -import GrimoireComponent from "../../src/Components/GrimoireComponent"; import Attribute from "../../src/Core/Attribute"; +import GrimoireComponent from "../../src/Components/GrimoireComponent"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import NSIdentity from "../../src/Core/NSIdentity"; +import test from "ava"; import TestEnvManager from "../TestEnvManager"; import TestUtil from "../TestUtil"; +import { assert, spy } from "sinon"; + TestEnvManager.init(); @@ -46,22 +46,22 @@ test("watch/unwatch should works correctly", t => { let rootNode = TestUtil.DummyTreeInit(GOML); const idAttr = rootNode.getAttributeRaw("id"); const baseComponent = rootNode.getComponent(GrimoireComponent); - const spy = sinon.spy(); + const s = spy(); const watcher = (n, o, a) => { - spy(n, o, a); + s(n, o, a); }; idAttr.watch(watcher); idAttr.Value = "newValue"; - t.truthy(spy.args[0][0] === "newValue"); - t.truthy(spy.args[0][1] === null); - t.truthy(spy.args[0][2] === idAttr); + t.truthy(s.args[0][0] === "newValue"); + t.truthy(s.args[0][1] === null); + t.truthy(s.args[0][2] === idAttr); - spy.reset(); + s.reset(); idAttr.unwatch(watcher); idAttr.Value = "newValue2"; - sinon.assert.notCalled(spy); + assert.notCalled(s); }); diff --git a/test/Core/ComponentDeclarationTest.ts b/test/Core/ComponentDeclarationTest.ts index 4bea9e954..aac731b4b 100644 --- a/test/Core/ComponentDeclarationTest.ts +++ b/test/Core/ComponentDeclarationTest.ts @@ -1,8 +1,9 @@ -import test from "ava"; - import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import test from "ava"; import TestEnvManager from "../TestEnvManager"; + + TestEnvManager.init(); diff --git a/test/Core/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts index bf7ca34cf..7fca8c886 100644 --- a/test/Core/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -6,10 +6,8 @@ import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import jsdomAsync from "../JsDOMAsync"; import prequire from "proxyquire"; -import sinon from "sinon"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; -import xhrmock from "xhr-mock"; import XMLReader from "../../src/Tools/XMLReader"; import { conflictComponent1, @@ -28,6 +26,7 @@ import { testNode3, testNodeBase } from "../DummyObjectRegisterer"; +import { spy } from "sinon"; TestEnvManager.init(); @@ -36,18 +35,10 @@ const testcase2_html = fs.readFile("../_TestResource/GomlLoaderTest_Case2.html") const testcase3_html = fs.readFile("../_TestResource/GomlLoaderTest_Case3.html"); const testcase4_html = fs.readFile("../_TestResource/GomlLoaderTest_Case4.html"); - - -xhrmock.setup(); -xhrmock.get("http://grimoire.gl/index.goml", (req, res) => { - return res.status(200).body("\n"); -}); -xhrmock.get("http://grimoire.gl/index2.goml", (req, res) => { - return res.status(200).body("\n"); -}); -xhrmock.get("http://grimoire.gl/index3.goml", (req, res) => { - return res.status(200).body("\n"); -}); +TestEnvManager.mockSetup(); +TestEnvManager.mock("http://grimoire.gl/index.goml", "\n") +TestEnvManager.mock("http://grimoire.gl/index2.goml", "\n") +TestEnvManager.mock("http://grimoire.gl/index3.goml", "\n") function mockXMLParse(func) { return prequire("../../src/Core/GomlLoader", { @@ -87,59 +78,59 @@ test("Processing script[type=\"text/goml\"] tag correctly when the text content const window = await jsdomAsync(testcase1_html, []); Environment.document = window.document; const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); - const spy = sinon.spy(); + const s = spy(); const mockedParseXML = mockXMLParse(xml => { - spy(xml.replace(/[\n\s]/g, "")); + s(xml.replace(/[\n\s]/g, "")); }); await mockedParseXML.loadFromScriptTag(scriptTags.item(0)); - t.truthy(spy.calledWith(``)); + t.truthy(s.calledWith(``)); }); test("Processing script[type=\"text/goml\"] tag correctly when the src attribute was existing", async (t) => { const window = await jsdomAsync(testcase2_html, []); Environment.document = window.document; const scriptTags = window.document.querySelectorAll("script[type=\"text/goml\"]"); - const spy = sinon.spy(); + const s = spy(); const mockedParseXML = mockXMLParse(xml => { - spy(xml.replace(/[\n\s]/g, "")); + s(xml.replace(/[\n\s]/g, "")); }); await mockedParseXML.loadFromScriptTag(scriptTags.item(0)); - t.truthy(spy.calledWith(``)); + t.truthy(s.calledWith(``)); }); test("Processing goml scripts from query", async (t) => { const window = await jsdomAsync(testcase3_html, []); Environment.document = window.document; - const spy = sinon.spy(); + const s = spy(); const mockedParseXML = mockXMLParse(xml => { - spy(xml.trim()); + s(xml.trim()); }); await mockedParseXML.loadFromQuery("script.call"); - t.truthy(spy.calledWith("\n")); + t.truthy(s.calledWith("\n")); }); test("Processing goml scripts for page", async (t) => { const window = await jsdomAsync(testcase4_html, []); Environment.document = window.document; - const spy = sinon.spy(); + const s = spy(); const mockedParseXML = mockXMLParse(xml => { - spy(xml.trim()); + s(xml.trim()); }); await mockedParseXML.loadForPage(); - t.truthy(spy.calledWith("\n")); + t.truthy(s.calledWith("\n")); }); test("all text/goml scripts tags should be loaded on loadForPage", async (t) => { - const spy = sinon.spy(); + const s = spy(); const original = GrimoireInterface.addRootNode.bind(GrimoireInterface); GrimoireInterface.addRootNode = (tag: HTMLScriptElement, rootNode: GomlNode) => { - spy(tag); + s(tag); return original(tag, rootNode); }; await TestEnvManager.loadPage(testcase4_html); - t.truthy(spy.callCount === 4); + t.truthy(s.callCount === 4); }); diff --git a/test/Core/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts index 911737200..0ed408d8b 100644 --- a/test/Core/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -7,9 +7,9 @@ import GomlNode from "../../src/Core/GomlNode"; import GrimoireComponent from "../../src/Components/GrimoireComponent"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import NSIdentity from "../../src/Core/NSIdentity"; -import sinon from "sinon"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; +import { assert, spy } from "sinon"; import { conflictComponent1, conflictComponent2, @@ -124,7 +124,7 @@ test("mount should be called in ideal timing", (t) => { const testNode3 = rootNode.children[0]; testNode3.enabled = true; const order = [testComponent3Spy, testComponent2Spy, testComponentOptionalSpy, testComponent1Spy]; - sinon.assert.callOrder(testComponent3Spy, testComponent2Spy, testComponentOptionalSpy, testComponent1Spy); + assert.callOrder(testComponent3Spy, testComponent2Spy, testComponentOptionalSpy, testComponent1Spy); order.forEach(v => { t.truthy(v.getCall(1).args[0] === "mount"); }); @@ -151,37 +151,37 @@ test("attribute default value work correctly1", (t) => { test("attribute watch should work correctly", (t) => { const idAttr = rootNode.getAttributeRaw("id"); - const spy = sinon.spy(); + const s = spy(); const watcher = (newValue, oldValue, attr) => { // spy("watch", { newValue: newValue, oldValue: oldValue, attr: attr }); - spy(newValue); + s(newValue); }; idAttr.watch(watcher); idAttr.Value = "id"; - t.truthy(spy.getCall(0).args[0] === "id"); + t.truthy(s.getCall(0).args[0] === "id"); - spy.reset(); + s.reset(); rootNode.enabled = false; idAttr.Value = "id"; - sinon.assert.notCalled(spy); + assert.notCalled(s); }); test("attribute watch should work correctly2", (t) => { const idAttr = rootNode.getAttributeRaw("id"); - const spy = sinon.spy(); + const s = spy(); const watcher = (newValue, oldValue, attr) => { // spy("watch", { newValue: newValue, oldValue: oldValue, attr: attr }); - spy(newValue); + s(newValue); }; idAttr.watch(watcher); idAttr.unwatch(watcher); idAttr.Value = "id"; - sinon.assert.notCalled(spy); + assert.notCalled(s); idAttr.watch(watcher, false, true); rootNode.enabled = false; idAttr.Value = "idid"; - t.truthy(spy.getCall(0).args[0] === "idid"); + t.truthy(s.getCall(0).args[0] === "idid"); }); test("enabled should work correctly", (t) => { @@ -211,7 +211,7 @@ test("enabled should work correctly", (t) => { }); test("Broadcast message should call correct order", (t) => { - sinon.assert.callOrder(testComponent3Spy, testComponent2Spy, testComponentOptionalSpy, testComponent1Spy); + assert.callOrder(testComponent3Spy, testComponent2Spy, testComponentOptionalSpy, testComponent1Spy); }); test("Broadcast message with range should work correctly", (t) => { @@ -219,10 +219,10 @@ test("Broadcast message with range should work correctly", (t) => { resetSpies(); testNode3.enabled = true; rootNode.broadcastMessage(1, "onTest"); - sinon.assert.called(testComponent3Spy); - sinon.assert.notCalled(testComponent2Spy); - sinon.assert.notCalled(testComponentOptionalSpy); - sinon.assert.notCalled(testComponent1Spy); + assert.called(testComponent3Spy); + assert.notCalled(testComponent2Spy); + assert.notCalled(testComponentOptionalSpy); + assert.notCalled(testComponent1Spy); }); test("Broadcast message with enabled should work correctly", (t) => { @@ -230,40 +230,40 @@ test("Broadcast message with enabled should work correctly", (t) => { const testNode2 = testNode3.children[0]; resetSpies(); - sinon.assert.notCalled(testComponent3Spy); - sinon.assert.notCalled(testComponent2Spy); - sinon.assert.notCalled(testComponentOptionalSpy); - sinon.assert.notCalled(testComponent1Spy); + assert.notCalled(testComponent3Spy); + assert.notCalled(testComponent2Spy); + assert.notCalled(testComponentOptionalSpy); + assert.notCalled(testComponent1Spy); resetSpies(); rootNode.broadcastMessage("onTest"); - sinon.assert.notCalled(testComponent3Spy); - sinon.assert.notCalled(testComponent2Spy); - sinon.assert.notCalled(testComponentOptionalSpy); - sinon.assert.notCalled(testComponent1Spy); + assert.notCalled(testComponent3Spy); + assert.notCalled(testComponent2Spy); + assert.notCalled(testComponentOptionalSpy); + assert.notCalled(testComponent1Spy); resetSpies(); testNode3.enabled = true; testNode2.enabled = false; rootNode.broadcastMessage("onTest"); - sinon.assert.called(testComponent3Spy); - sinon.assert.notCalled(testComponent2Spy); - sinon.assert.notCalled(testComponentOptionalSpy); - sinon.assert.called(testComponent1Spy); + assert.called(testComponent3Spy); + assert.notCalled(testComponent2Spy); + assert.notCalled(testComponentOptionalSpy); + assert.called(testComponent1Spy); resetSpies(); testNode2.enabled = true; rootNode.broadcastMessage("onTest"); - sinon.assert.called(testComponent3Spy); - sinon.assert.called(testComponent2Spy); - sinon.assert.called(testComponentOptionalSpy); - sinon.assert.called(testComponent1Spy); + assert.called(testComponent3Spy); + assert.called(testComponent2Spy); + assert.called(testComponentOptionalSpy); + assert.called(testComponent1Spy); }); test("SendMessage should call correct order", (t) => { const testNode2 = rootNode.children[0].children[0]; testNode2.sendMessage("onTest"); - sinon.assert.callOrder(testComponent2Spy, testComponentOptionalSpy); + assert.callOrder(testComponent2Spy, testComponentOptionalSpy); }); test("Detach node should invoke unmount before detaching", (t) => { @@ -272,7 +272,7 @@ test("Detach node should invoke unmount before detaching", (t) => { resetSpies(); testNode3.detach(); const called = [testComponent2Spy, testComponentOptionalSpy, testComponent1Spy, testComponent3Spy]; - sinon.assert.callOrder.apply(sinon.assert, called); + assert.callOrder.apply(assert, called); called.forEach((v) => { t.truthy(v.getCall(0).args[0] === "unmount"); }); @@ -284,7 +284,7 @@ test("Remove() should invoke unmount before deleting", (t) => { resetSpies(); testNode3.remove(); const called = [testComponent2Spy, testComponentOptionalSpy, testComponent1Spy, testComponent3Spy]; - sinon.assert.callOrder.apply(sinon.assert, called); + assert.callOrder.apply(assert, called); called.forEach((v) => { t.truthy(v.getCall(0).args[0] === "unmount"); }); @@ -304,8 +304,8 @@ test("broadcastMessage should not invoke message if the component is not enabled optionalComponent.enabled = false; rootNode.broadcastMessage("onTest"); const called = [testComponent3Spy, testComponent2Spy, testComponent1Spy]; - sinon.assert.callOrder.apply(sinon.assert, called); - sinon.assert.notCalled(testComponentOptionalSpy); + assert.callOrder.apply(assert, called); + assert.notCalled(testComponentOptionalSpy); }); test("broadcastMessage should not invoke message if the node is not enabled", (t) => { @@ -316,9 +316,9 @@ test("broadcastMessage should not invoke message if the node is not enabled", (t testNode2.enabled = false; rootNode.broadcastMessage("onTest"); const called = [testComponent3Spy, testComponent1Spy]; - sinon.assert.callOrder.apply(sinon.assert, called); - sinon.assert.notCalled(testComponentOptionalSpy); - sinon.assert.notCalled(testComponent2Spy); + assert.callOrder.apply(assert, called); + assert.notCalled(testComponentOptionalSpy); + assert.notCalled(testComponent2Spy); }); test("class attribute can be obatined as default", (t) => { diff --git a/test/Core/GomlNodeTest.ts b/test/Core/GomlNodeTest.ts index 78da8a8ff..9f0449361 100644 --- a/test/Core/GomlNodeTest.ts +++ b/test/Core/GomlNodeTest.ts @@ -1,17 +1,16 @@ -require("babel-polyfill"); -import xmldom from "xmldom"; -import test from "ava"; -import sinon from "sinon"; -import TestEnvManager from "../TestEnvManager"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import Constants from "../../src/Tools/Constants"; +import Attribute from "../../src/Core/Attribute"; import Component from "../../src/Core/Component"; -import GomlParser from "../../src/Core/GomlParser"; +import Constants from "../../src/Tools/Constants"; +import Environment from "../../src/Core/Environment"; import GomlLoader from "../../src/Core/GomlLoader"; -import NSIdentity from "../../src/Core/NSIdentity"; import GomlNode from "../../src/Core/GomlNode"; -import Attribute from "../../src/Core/Attribute"; -import Environment from "../../src/Core/Environment"; +import GomlParser from "../../src/Core/GomlParser"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import NSIdentity from "../../src/Core/NSIdentity"; +import test from "ava"; +import TestEnvManager from "../TestEnvManager"; +import xmldom from "xmldom"; +require("babel-polyfill"); TestEnvManager.init(); diff --git a/test/Core/GomlParserTest.ts b/test/Core/GomlParserTest.ts index 9eccb6e9d..539993c3d 100644 --- a/test/Core/GomlParserTest.ts +++ b/test/Core/GomlParserTest.ts @@ -1,14 +1,18 @@ -require("babel-polyfill"); -import test from "ava"; -import sinon from "sinon"; -import xmldom from "xmldom"; -import TestEnvManager from "../TestEnvManager"; +import Environment from "../../src/Core/Environment"; +import fs from "../fileHelper"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import NSIdentity from "../../src/Core/NSIdentity"; import Namespace from "../../src/Core/Namespace"; -import fs from "../fileHelper"; +import NSIdentity from "../../src/Core/NSIdentity"; +import test from "ava"; +import TestEnvManager from "../TestEnvManager"; +import xmldom from "xmldom"; +import { assert, spy } from "sinon"; import { + conflictComponent1, + conflictComponent2, + conflictNode1, + conflictNode2, goml, stringConverter, testComponent1, @@ -17,13 +21,9 @@ import { testComponentOptional, testNode1, testNode2, - testNodeBase, - conflictNode1, - conflictNode2, - conflictComponent1, - conflictComponent2 -} from "../DummyObjectRegisterer"; -import Environment from "../../src/Core/Environment"; + testNodeBase + } from "../DummyObjectRegisterer"; +require("babel-polyfill"); TestEnvManager.init(); @@ -111,7 +111,7 @@ test("test for send/broadcastMessage and component Attribute parsing.", (t) => { const element = obtainElementTag(gomlParserTestCasePath2); const node = GomlParser.parse(element); t.truthy(node.parent === null); - sinon.assert.notCalled(stringConverterSpy); + assert.notCalled(stringConverterSpy); }); test("test for parse user-define component.", (t) => { @@ -125,9 +125,9 @@ test("test for parse user-define component.", (t) => { t.truthy(node.children[0].children.length === 1); t.truthy(node.children[0].children[0].getAttribute("testAttr2") === "123"); node.broadcastMessage("onTest", "testArg"); - sinon.assert.neverCalledWith(testComponent1Spy, "testArg"); - sinon.assert.neverCalledWith(testComponent2Spy, "testArg"); - sinon.assert.neverCalledWith(testComponentOptionalSpy, "testArg"); + assert.neverCalledWith(testComponent1Spy, "testArg"); + assert.neverCalledWith(testComponent2Spy, "testArg"); + assert.neverCalledWith(testComponentOptionalSpy, "testArg"); t.truthy("testArg" === testComponentBaseSpy.args[2][1]); }); @@ -136,8 +136,8 @@ test("test for namespace parsing.", (t) => { const node = GomlParser.parse(element); node.setMounted(true); node.broadcastMessage("onTest", "testArg"); - sinon.assert.calledWith(conflictComponent1Spy, "aaa"); - sinon.assert.calledWith(conflictComponent2Spy, "bbb"); + assert.calledWith(conflictComponent1Spy, "aaa"); + assert.calledWith(conflictComponent2Spy, "bbb"); }); test("test for companion", (t) => { diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index 25f7f4be7..15a159b5c 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -1,16 +1,16 @@ -require("babel-polyfill"); -import xmldom from "xmldom"; -import test from "ava"; -import sinon from "sinon"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; -import GomlParser from "../../src/Core/GomlParser"; +import Constants from "../../src/Tools/Constants"; import GomlLoader from "../../src/Core/GomlLoader"; -import NSIdentity from "../../src/Core/NSIdentity"; -import Namespace from "../../src/Core/Namespace"; import GomlNode from "../../src/Core/GomlNode"; +import GomlParser from "../../src/Core/GomlParser"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import Namespace from "../../src/Core/Namespace"; +import NSIdentity from "../../src/Core/NSIdentity"; +import test from "ava"; import TestEnvManager from "../TestEnvManager"; +import xmldom from "xmldom"; +import { assert, spy } from "sinon"; +require("babel-polyfill"); TestEnvManager.init(); @@ -320,12 +320,12 @@ test("throw error on attempt registerComponent/Node by duplicate name.", t => { }); test("register and resolvePlugins works preperly", async () => { - const spy1 = sinon.spy(); - const spy2 = sinon.spy(); - const wrapPromise: any = function (spy) { + const spy1 = spy(); + const spy2 = spy(); + const wrapPromise: any = function (s) { return () => { return new Promise(resolve => { - spy(); + s(); resolve(null); }); }; @@ -335,5 +335,5 @@ test("register and resolvePlugins works preperly", async () => { GrimoireInterface.register(spyp); GrimoireInterface.register(spyp2); await GrimoireInterface.resolvePlugins(); - sinon.assert.callOrder(spy1, spy2); + assert.callOrder(spy1, spy2); }); diff --git a/test/Core/NSIdentityTest.ts b/test/Core/NSIdentityTest.ts index dc8e5e4fd..dc6fb4fae 100644 --- a/test/Core/NSIdentityTest.ts +++ b/test/Core/NSIdentityTest.ts @@ -1,7 +1,6 @@ -require("babel-polyfill"); -import test from "ava"; -import sinon from "sinon"; import NSIdentity from "../../src/Core/NSIdentity"; +import test from "ava"; +require("babel-polyfill"); test.beforeEach(() => { NSIdentity.clear(); diff --git a/test/Core/NamespaceTest.ts b/test/Core/NamespaceTest.ts index 77b5aab0a..955319539 100644 --- a/test/Core/NamespaceTest.ts +++ b/test/Core/NamespaceTest.ts @@ -1,13 +1,12 @@ -require("babel-polyfill"); -import test from "ava"; -import sinon from "sinon"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; -import GomlParser from "../../src/Core/GomlParser"; +import Constants from "../../src/Tools/Constants"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; +import GomlParser from "../../src/Core/GomlParser"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Namespace from "../../src/Core/Namespace"; +import test from "ava"; +require("babel-polyfill"); test("define/for function works correctly.", (t) => { // TODO test const g = Namespace.define("grimoire"); diff --git a/test/Core/NodeInterfaceTest.ts b/test/Core/NodeInterfaceTest.ts index 239cbb5b5..5bfae5bcf 100644 --- a/test/Core/NodeInterfaceTest.ts +++ b/test/Core/NodeInterfaceTest.ts @@ -3,7 +3,6 @@ import Environment from "../../src/Core/Environment"; import fs from "../fileHelper"; import GomlLoader from "../../src/Core/GomlLoader"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import sinon from "sinon"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import xhrmock from "xhr-mock"; diff --git a/test/DummyObjectRegisterer.ts b/test/DummyObjectRegisterer.ts index 5898decb5..635e64472 100644 --- a/test/DummyObjectRegisterer.ts +++ b/test/DummyObjectRegisterer.ts @@ -1,9 +1,9 @@ import GrimoireInterface from "../src/Core/GrimoireInterface"; -import sinon from "sinon"; import Namespace from "../src/Core/Namespace"; +import { spy } from "sinon"; export function testComponent1() { - const spy = sinon.spy(); + const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponent1", attributes: { @@ -17,23 +17,23 @@ export function testComponent1() { } }, $onTest: function (arg) { - spy("onTest", arg); + s("onTest", arg); }, $mount: function (arg) { - spy("mount", arg); + s("mount", arg); }, $unmount: function (arg) { - spy("unmount", arg); + s("unmount", arg); }, $awake: function (arg) { - spy("awake", arg); + s("awake", arg); } }); - return spy; + return s; } export function testComponent2() { - const spy = sinon.spy(); + const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponent2", attributes: { @@ -43,23 +43,23 @@ export function testComponent2() { } }, $onTest: function (arg) { - spy("onTest", arg); + s("onTest", arg); }, $mount: function (arg) { - spy("mount", arg); + s("mount", arg); }, $unmount: function (arg) { - spy("unmount", arg); + s("unmount", arg); }, $awake: function (arg) { - spy("awake", arg); + s("awake", arg); } }); - return spy; + return s; } export function testComponent3() { - const spy = sinon.spy(); + const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponent3", attributes: { @@ -77,23 +77,23 @@ export function testComponent3() { } }, $onTest: function (arg) { - spy("onTest", arg); + s("onTest", arg); }, $mount: function (arg) { - spy("mount", arg); + s("mount", arg); }, $unmount: function (arg) { - spy("unmount", arg); + s("unmount", arg); }, $awake: function (arg) { - spy("awake", arg); + s("awake", arg); } }); - return spy; + return s; } export function testComponentBase() { - const spy = sinon.spy(); + const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponentBase", attributes: { @@ -103,23 +103,23 @@ export function testComponentBase() { } }, $onTest: function (arg) { - spy("onTest", arg); + s("onTest", arg); }, $mount: function (arg) { - spy("mount", arg); + s("mount", arg); }, $unmount: function (arg) { - spy("unmount", arg); + s("unmount", arg); }, $awake: function (arg) { - spy("awake", arg); + s("awake", arg); } }); - return spy; + return s; } export function testComponentOptional() { - const spy = sinon.spy(); + const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponentOptional", attributes: { @@ -129,23 +129,23 @@ export function testComponentOptional() { } }, $onTest: function (arg) { - spy("onTest", arg); + s("onTest", arg); }, $mount: function (arg) { - spy("mount", arg); + s("mount", arg); }, $unmount: function (arg) { - spy("unmount", arg); + s("unmount", arg); }, $awake: function (arg) { - spy("awake", arg); + s("awake", arg); } }); - return spy; + return s; } export function conflictComponent1() { - const spy = sinon.spy(); + const s = spy(); const ns = Namespace.define("test1"); GrimoireInterface.registerComponent({ componentName: ns.for("ConflictComponent"), @@ -156,14 +156,14 @@ export function conflictComponent1() { } }, $onTest: function () { - spy(this.attributes.get("value").Value); + s(this.attributes.get("value").Value); } }); - return spy; + return s; } export function conflictComponent2() { - const spy = sinon.spy(); + const s = spy(); const ns = Namespace.define("test2"); GrimoireInterface.registerComponent({ componentName: ns.for("ConflictComponent"), @@ -174,10 +174,10 @@ export function conflictComponent2() { } }, $onTest: function () { - spy(this.attributes.get("value").Value); + s(this.attributes.get("value").Value); } }); - return spy; + return s; } @@ -220,13 +220,13 @@ export function conflictNode2() { // Converters export function stringConverter() { - const spy = sinon.spy(); + const s = spy(); GrimoireInterface.registerConverter("Str", (arg) => { - spy(arg); + s(arg); if (typeof arg === "string" || !arg) { return arg; } throw new Error("Not Implemented:" + arg); }); - return spy; + return s; } diff --git a/test/Tools/IdResolverTest.ts b/test/Tools/IdResolverTest.ts index f5954c530..9ee91764a 100644 --- a/test/Tools/IdResolverTest.ts +++ b/test/Tools/IdResolverTest.ts @@ -1,16 +1,15 @@ -import test from "ava"; -require("babel-polyfill"); -import xmldom from "xmldom"; -import sinon from "sinon"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import Constants from "../../src/Tools/Constants"; import Component from "../../src/Core/Component"; -import GomlParser from "../../src/Core/GomlParser"; +import Constants from "../../src/Tools/Constants"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; -import NSIdentity from "../../src/Core/NSIdentity"; -import Namespace from "../../src/Core/Namespace"; +import GomlParser from "../../src/Core/GomlParser"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; import IdResolver from "../../src/Tools/IdResolver"; +import Namespace from "../../src/Core/Namespace"; +import NSIdentity from "../../src/Core/NSIdentity"; +import test from "ava"; +import xmldom from "xmldom"; +require("babel-polyfill"); test("get() works correctly.", t => { diff --git a/test/Tools/NSDictionaryTest.ts b/test/Tools/NSDictionaryTest.ts index e1493b675..f0e8b17db 100644 --- a/test/Tools/NSDictionaryTest.ts +++ b/test/Tools/NSDictionaryTest.ts @@ -1,14 +1,12 @@ -require("babel-polyfill"); -import xmldom from "xmldom"; -import test from "ava"; -import sinon from "sinon"; -import xhrmock from "xhr-mock"; +import fs from "../fileHelper"; import GomlLoader from "../../src/Core/GomlLoader"; -import GrimoireInterface from "../../src/Core/GrimoireInterface"; import NodeInterface from "../../src/Core/NodeInterface"; -import NSIdentity from "../../src/Core/NSIdentity"; import NSDictionary from "../../src/Tools/NSDictionary"; -import fs from "../fileHelper"; +import NSIdentity from "../../src/Core/NSIdentity"; +import test from "ava"; +import xhrmock from "xhr-mock"; +import xmldom from "xmldom"; +require("babel-polyfill"); const xml = fs.readFile("../_TestResource/NSDictionary_QueryDOM.xml"); test.beforeEach(() => { diff --git a/test/_TestResource/GrimoireInterfaceTest_Case1.html b/test/_TestResource/GrimoireInterfaceTest_Case1.html index 81281f41c..a323f54e4 100644 --- a/test/_TestResource/GrimoireInterfaceTest_Case1.html +++ b/test/_TestResource/GrimoireInterfaceTest_Case1.html @@ -1,43 +1,45 @@ - - - - - - + + + + + + - - + + - - - - - - - - -

Hello world! This is HTML5 Boilerplate.

+ +

Hello world! This is HTML5 Boilerplate.

- - - - + + + + - - - - + + + + From 103e22d8889df95c22662f7034a405f966b40bb9 Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 29 Sep 2017 22:35:23 +0900 Subject: [PATCH 033/146] fix: change arguments of XMLReader.parseXML() --- src/Core/GomlLoader.ts | 4 ++-- src/Core/GomlNode.ts | 10 ++++------ src/Core/GomlParser.ts | 4 ++-- src/Core/NodeInterface.ts | 16 +++++++--------- src/Tools/XMLReader.ts | 9 ++------- test/Core/ComponentDeclarationTest.ts | 3 --- test/Core/GomlLoaderTest.ts | 6 +++--- test/Core/GomlParserTest.ts | 16 ++-------------- test/TestEnvManager.ts | 2 +- test/TestUtil.ts | 16 ++++++++-------- test/Tools/XMLReaderTest.ts | 10 +++++----- 11 files changed, 36 insertions(+), 60 deletions(-) diff --git a/src/Core/GomlLoader.ts b/src/Core/GomlLoader.ts index a0a4db5b1..f14a15679 100644 --- a/src/Core/GomlLoader.ts +++ b/src/Core/GomlLoader.ts @@ -29,8 +29,8 @@ export default class GomlLoader { } else { source = scriptTag.text; } - const doc = XMLReader.parseXML(source, "GOML"); - const rootNode = GomlParser.parse(doc[0]); + const doc = XMLReader.parseXML(source); + const rootNode = GomlParser.parse(doc); GrimoireInterface.addRootNode(scriptTag, rootNode); } diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index 545832556..4e63d40fd 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -273,13 +273,11 @@ export default class GomlNode extends EEObject { } public append(tag: string): GomlNode[] { - const elems = XMLReader.parseXML(tag); + const elem = XMLReader.parseXML(tag); let ret: GomlNode[] = []; - elems.forEach(elem => { - let child = GomlParser.parse(elem); - this.addChild(child); - ret.push(child); - }); + let child = GomlParser.parse(elem); + this.addChild(child); + ret.push(child); return ret; } diff --git a/src/Core/GomlParser.ts b/src/Core/GomlParser.ts index d04fd80a2..6fb1d58a7 100644 --- a/src/Core/GomlParser.ts +++ b/src/Core/GomlParser.ts @@ -1,6 +1,6 @@ +import Environment from "./Environment"; import GomlNode from "./GomlNode"; import GrimoireInterface from "../Core/GrimoireInterface"; -import Environment from "./Environment"; /** * Parser of Goml to Node utilities. @@ -13,7 +13,7 @@ class GomlParser { * @param {GomlNode} parent あればこのノードにaddChildされる * @return {GomlNode} ルートノード */ - public static parse(source: Element, parent?: GomlNode |null): GomlNode { + public static parse(source: Element, parent?: GomlNode | null): GomlNode { const newNode = GomlParser._createNode(source); // Parse children recursively diff --git a/src/Core/NodeInterface.ts b/src/Core/NodeInterface.ts index 35dc8eaa0..c0f462dd7 100644 --- a/src/Core/NodeInterface.ts +++ b/src/Core/NodeInterface.ts @@ -1,10 +1,10 @@ -import Utility from "../Tools/Utility"; -import XMLReader from "../Tools/XMLReader"; -import GomlParser from "../Core/GomlParser"; import Attribute from "../Core/Attribute"; import GomlNode from "../Core/GomlNode"; -import {Name, Nullable} from "../Tools/Types"; +import GomlParser from "../Core/GomlParser"; +import Utility from "../Tools/Utility"; +import XMLReader from "../Tools/XMLReader"; import { ListenerFn } from "eventemitter3"; +import { Name, Nullable } from "../Tools/Types"; /** * interface for operate multicast nodes. @@ -129,11 +129,9 @@ export default class NodeInterface { */ public append(tag: string): NodeInterface { this.forEach(node => { - const elems = XMLReader.parseXML(tag); - elems.forEach(elem => { - let child = GomlParser.parse(elem); - node.addChild(child); - }); + const elem = XMLReader.parseXML(tag); + let child = GomlParser.parse(elem); + node.addChild(child); }); return this; } diff --git a/src/Tools/XMLReader.ts b/src/Tools/XMLReader.ts index b21cdb26e..56297004f 100644 --- a/src/Tools/XMLReader.ts +++ b/src/Tools/XMLReader.ts @@ -6,19 +6,14 @@ import { Nullable } from "./Types"; */ export default class XMLReader { - public static parseXML(doc: string, rootElementName?: string): Element[] { + public static parseXML(doc: string): Element { const parsed = Environment.DomParser.parseFromString(doc, "text/xml"); if (!parsed || parsed.getElementsByTagName("parsererror").length > 0) { const err = Environment.XMLSerializer.serializeToString(parsed); throw new Error(`Error parsing XML: ${err}`); } - if (rootElementName) { - if (parsed.documentElement.tagName.toUpperCase() !== rootElementName.toUpperCase()) { - throw new Error("Specified document is invalid."); - }// TODO should throw more detail error - } - return [parsed.documentElement]; // TODO: implenent! + return parsed.documentElement; // TODO: implenent! } public static getElements(elem: Element, name: string): Element[] { diff --git a/test/Core/ComponentDeclarationTest.ts b/test/Core/ComponentDeclarationTest.ts index aac731b4b..fc3ec60e9 100644 --- a/test/Core/ComponentDeclarationTest.ts +++ b/test/Core/ComponentDeclarationTest.ts @@ -2,11 +2,8 @@ import GrimoireInterface from "../../src/Core/GrimoireInterface"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; - - TestEnvManager.init(); - test.beforeEach(async () => { GrimoireInterface.clear(); }); diff --git a/test/Core/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts index 7fca8c886..6520c7779 100644 --- a/test/Core/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -36,9 +36,9 @@ const testcase3_html = fs.readFile("../_TestResource/GomlLoaderTest_Case3.html") const testcase4_html = fs.readFile("../_TestResource/GomlLoaderTest_Case4.html"); TestEnvManager.mockSetup(); -TestEnvManager.mock("http://grimoire.gl/index.goml", "\n") -TestEnvManager.mock("http://grimoire.gl/index2.goml", "\n") -TestEnvManager.mock("http://grimoire.gl/index3.goml", "\n") +TestEnvManager.mock("http://grimoire.gl/index.goml", "\n"); +TestEnvManager.mock("http://grimoire.gl/index2.goml", "\n"); +TestEnvManager.mock("http://grimoire.gl/index3.goml", "\n"); function mockXMLParse(func) { return prequire("../../src/Core/GomlLoader", { diff --git a/test/Core/GomlParserTest.ts b/test/Core/GomlParserTest.ts index 539993c3d..42e7b9090 100644 --- a/test/Core/GomlParserTest.ts +++ b/test/Core/GomlParserTest.ts @@ -7,6 +7,7 @@ import NSIdentity from "../../src/Core/NSIdentity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import xmldom from "xmldom"; +import XMLReader from "../../src/Tools/XMLReader"; import { assert, spy } from "sinon"; import { conflictComponent1, @@ -36,8 +37,7 @@ declare namespace global { // Get element from test case source which is located with relative path. function obtainElementTag(path) { - const parser = new xmldom.DOMParser(); - return parser.parseFromString(fs.readFile(path), "text/xml").documentElement; + return XMLReader.parseXML(fs.readFile(path)); } let stringConverterSpy, @@ -81,18 +81,6 @@ function registerUserPlugin() { GrimoireInterface.registerNode("scene"); } -test("aaa", t => { - GrimoireInterface.nodeDeclarations.forEach(nm => { - t.truthy(nm.resolvedDependency); - }); -}); -test("bbb", async t => { - await GrimoireInterface.resolvePlugins(); - GrimoireInterface.nodeDeclarations.forEach(nm => { - t.truthy(nm.resolvedDependency); - }); -}); - test("test for parsing node hierarchy.", (t) => { const element = obtainElementTag(gomlParserTestCasePath1); const node = GomlParser.parse(element); diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index 949d4bb5e..204e08856 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -55,7 +55,7 @@ export default class TestEnvManager { } public static loadGoml(goml: string) { - const doc = XMLReader.parseXML(goml, "GOML"); + const doc = XMLReader.parseXML(goml); const rootNode = GomlParser.parse(doc[0]); GrimoireInterface.addRootNode(null, rootNode); } diff --git a/test/TestUtil.ts b/test/TestUtil.ts index 04ab6eccd..a4d643c3a 100644 --- a/test/TestUtil.ts +++ b/test/TestUtil.ts @@ -1,14 +1,14 @@ +import Attribute from "../src/Core/Attribute"; import Component from "../src/Core/Component"; import ComponentDeclaration from "../src/Core/ComponentDeclaration"; -import NSIdentity from "../src/Core/NSIdentity"; -import Attribute from "../src/Core/Attribute"; -import IAttributeDeclaration from "../src/Interface/IAttributeDeclaration"; import Ensure from "../src/Tools/Ensure"; -import GrimoireInterface from "../src/Core/GrimoireInterface"; -import XMLReader from "../src/Tools/XMLReader"; +import GomlNode from "../src/Core/GomlNode"; import GomlParser from "../src/Core/GomlParser"; +import GrimoireInterface from "../src/Core/GrimoireInterface"; +import IAttributeDeclaration from "../src/Interface/IAttributeDeclaration"; import ITreeInitializedInfo from "../src/Interface/ITreeInitializedInfo"; -import GomlNode from "../src/Core/GomlNode"; +import NSIdentity from "../src/Core/NSIdentity"; +import XMLReader from "../src/Tools/XMLReader"; export default class TestUtil { @@ -37,8 +37,8 @@ export default class TestUtil { } public static DummyTreeInit(goml: string): GomlNode { - const doc = XMLReader.parseXML(goml, "GOML"); - const rootNode = GomlParser.parse(doc[0]); + const doc = XMLReader.parseXML(goml); + const rootNode = GomlParser.parse(doc); rootNode.setMounted(true); rootNode.broadcastMessage("treeInitialized", { diff --git a/test/Tools/XMLReaderTest.ts b/test/Tools/XMLReaderTest.ts index 535727251..3a47d391f 100644 --- a/test/Tools/XMLReaderTest.ts +++ b/test/Tools/XMLReaderTest.ts @@ -1,17 +1,17 @@ +import fs from "../fileHelper"; import test from "ava"; +import TestEnvManager from "../TestEnvManager"; import xmldom from "xmldom"; import XMLReader from "../../src/Tools/XMLReader"; -import fs from "../fileHelper"; -import TestEnvManager from "../TestEnvManager"; TestEnvManager.init(); const xml = fs.readFile("../_TestResource/XMLReader_Case1.xml"); test("parseXML behaves correctly", t => { - const parsedDocument = XMLReader.parseXML(xml, "Goml"); - t.truthy(parsedDocument[0].localName === "goml"); + const parsedDocument = XMLReader.parseXML(xml); + t.truthy(parsedDocument.localName === "goml"); t.throws(() => { - XMLReader.parseXML(">", "Goml"); + XMLReader.parseXML(">"); }); }); From dd3aff233c55ad3d9c6a6d08fe49e0019d5976d1 Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 29 Sep 2017 23:17:30 +0900 Subject: [PATCH 034/146] fix: refactor test --- test/Converters/NumberConverterTest.ts | 2 - test/Core/GomlLoaderTest.ts | 47 +++++++-------- test/Core/GomlNode2Test.ts | 60 +++++++++---------- test/Core/GomlNodeTest.ts | 63 ++++++++++--------- test/Core/GomlParserTest.ts | 83 +++++++++++--------------- test/Core/GrimoireInterfaceTest.ts | 2 - test/Core/NSIdentityTest.ts | 5 +- test/Core/NamespaceTest.ts | 4 +- test/Core/NodeInterfaceTest.ts | 81 +++++++++++-------------- test/DummyObjectRegisterer.ts | 30 +++++----- test/TestEnvManager.ts | 17 +----- test/Tools/IdResolverTest.ts | 4 +- test/Tools/NSDictionaryTest.ts | 7 ++- test/Tools/NSSetTest.ts | 5 +- test/Tools/XMLReaderTest.ts | 1 - 15 files changed, 187 insertions(+), 224 deletions(-) diff --git a/test/Converters/NumberConverterTest.ts b/test/Converters/NumberConverterTest.ts index a3376f415..80ffa8a62 100644 --- a/test/Converters/NumberConverterTest.ts +++ b/test/Converters/NumberConverterTest.ts @@ -2,8 +2,6 @@ import NumberConverter from "../../src/Converters/NumberConverter"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; - - TestEnvManager.init(); test("NumberConverter should convert collectly", t => { diff --git a/test/Core/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts index 6520c7779..a99078d45 100644 --- a/test/Core/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -10,21 +10,21 @@ import test from "ava"; import TestEnvManager from "../TestEnvManager"; import XMLReader from "../../src/Tools/XMLReader"; import { - conflictComponent1, - conflictComponent2, - conflictNode1, - conflictNode2, - goml, - stringConverter, - testComponent1, - testComponent2, - testComponent3, - testComponentBase, - testComponentOptional, - testNode1, - testNode2, - testNode3, - testNodeBase + registerConflictComponent1, + registerConflictComponent2, + registerConflictNode1, + registerConflictNode2, + registerGoml, + registerStringConverter, + registerTestComponent1, + registerTestComponent2, + registerTestComponent3, + registerTestComponentBase, + registerTestComponentOptional, + registerTestNode1, + registerTestNode2, + registerTestNode3, + registerTestNodeBase } from "../DummyObjectRegisterer"; import { spy } from "sinon"; @@ -55,13 +55,13 @@ function mockXMLParse(func) { test.beforeEach(async () => { GrimoireInterface.clear(); - goml(); - testNode1(); - testNode2(); - testComponent1(); - testComponent2(); - testNodeBase(); - testComponentBase(); + registerGoml(); + registerTestNode1(); + registerTestNode2(); + registerTestComponent1(); + registerTestComponent2(); + registerTestNodeBase(); + registerTestComponentBase(); await GrimoireInterface.resolvePlugins(); }); @@ -132,6 +132,3 @@ test("all text/goml scripts tags should be loaded on loadForPage", async (t) => await TestEnvManager.loadPage(testcase4_html); t.truthy(s.callCount === 4); }); - - - diff --git a/test/Core/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts index 0ed408d8b..37b3adc4d 100644 --- a/test/Core/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -11,21 +11,21 @@ import test from "ava"; import TestEnvManager from "../TestEnvManager"; import { assert, spy } from "sinon"; import { - conflictComponent1, - conflictComponent2, - conflictNode1, - conflictNode2, - goml, - stringConverter, - testComponent1, - testComponent2, - testComponent3, - testComponentBase, - testComponentOptional, - testNode1, - testNode2, - testNode3, - testNodeBase + registerConflictComponent1, + registerConflictComponent2, + registerConflictNode1, + registerConflictNode2, + registerGoml, + registerStringConverter, + registerTestComponent1, + registerTestComponent2, + registerTestComponent3, + registerTestComponentBase, + registerTestComponentOptional, + registerTestNode1, + registerTestNode2, + registerTestNode3, + registerTestNodeBase } from "../DummyObjectRegisterer"; TestEnvManager.init(); @@ -59,22 +59,22 @@ let rootNode: GomlNode; test.beforeEach(async () => { GrimoireInterface.clear(); - goml(); - testNode1(); - testNode2(); - testNode3(); - testNodeBase(); - conflictNode1(); - conflictNode2(); + registerGoml(); + registerTestNode1(); + registerTestNode2(); + registerTestNode3(); + registerTestNodeBase(); + registerConflictNode1(); + registerConflictNode2(); const spys: any = {}; - spys.stringConverterSpy = stringConverter(); - spys.testComponent1Spy = testComponent1(); - spys.testComponent2Spy = testComponent2(); - spys.testComponent3Spy = testComponent3(); - spys.testComponentBaseSpy = testComponentBase(); - spys.testComponentOptionalSpy = testComponentOptional(); - spys.conflictComponent1Spy = conflictComponent1(); - spys.conflictComponent2Spy = conflictComponent2(); + spys.stringConverterSpy = registerStringConverter(); + spys.testComponent1Spy = registerTestComponent1(); + spys.testComponent2Spy = registerTestComponent2(); + spys.testComponent3Spy = registerTestComponent3(); + spys.testComponentBaseSpy = registerTestComponentBase(); + spys.testComponentOptionalSpy = registerTestComponentOptional(); + spys.conflictComponent1Spy = registerConflictComponent1(); + spys.conflictComponent2Spy = registerConflictComponent2(); await GrimoireInterface.resolvePlugins(); await TestEnvManager.loadPage(tc1_html); diff --git a/test/Core/GomlNodeTest.ts b/test/Core/GomlNodeTest.ts index 9f0449361..5c0e02c90 100644 --- a/test/Core/GomlNodeTest.ts +++ b/test/Core/GomlNodeTest.ts @@ -10,7 +10,6 @@ import NSIdentity from "../../src/Core/NSIdentity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import xmldom from "xmldom"; -require("babel-polyfill"); TestEnvManager.init(); @@ -36,7 +35,7 @@ test.beforeEach(async () => { }); test("Add component works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); node.addComponent("Test"); node.addComponent("Test2"); node.addComponent("Test"); @@ -49,7 +48,7 @@ test("Add component works correctly", t => { }); test("Remove component actually delete specified insatnce", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); node.addComponent("Test"); node.addComponent("Test2"); node.addComponent("Test"); @@ -60,7 +59,7 @@ test("Remove component actually delete specified insatnce", t => { }); test("Remove components should delete specified all components in node", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); node.addComponent("Test"); node.addComponent("Test"); node.addComponent("Test"); @@ -70,8 +69,8 @@ test("Remove components should delete specified all components in node", t => { }); test("addChild method works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); node.addChild(node2, null, null); node.addChild(node2, null, null); t.truthy(node.children[0].id === node2.id); @@ -79,9 +78,9 @@ test("addChild method works correctly", t => { }); test("delete method works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); - const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); + const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); node.addChild(node2, null, null); node2.addChild(node3, null, null); node2.remove(); @@ -93,9 +92,9 @@ test("delete method works correctly", t => { }); test("removeChild method works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); - const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); + const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); node.addChild(node2, null, null); node2.addChild(node3, null, null); node.removeChild(node2); @@ -104,9 +103,9 @@ test("removeChild method works correctly", t => { }); test("detachChild method works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); - const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); + const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); node.addChild(node2, null, null); node2.addChild(node3, null, null); node.detachChild(node2); @@ -117,9 +116,9 @@ test("detachChild method works correctly", t => { }); test("detach method works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); - const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); + const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); node.addChild(node2, null, null); node2.addChild(node3, null, null); node2.detach(); @@ -146,15 +145,15 @@ test("getComponents method works correctly", t => { }); GrimoireInterface.registerNode("test-node", ["TestComponent"]); - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("test-node"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("test-node")); const components = node.getComponents(); t.truthy(components.length === 2); }); test("setMounted method works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); - const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); + const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); node.addChild(node2, null, null); node2.addChild(node3, null, null); node.setMounted(true); @@ -163,14 +162,14 @@ test("setMounted method works correctly", t => { t.truthy(node3.mounted === true); }); test("index method works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); node.addChild(node2); t.truthy(node2.index === 0); }); test("addComponent method works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); node.addChild(node2, null, null); GrimoireInterface.registerComponent({ componentName: "TestComponent1", @@ -189,8 +188,8 @@ test("addComponent method works correctly", t => { t.truthy(component.isDefaultComponent); }); test("addComponent method works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); node.addChild(node2, null, null); GrimoireInterface.registerComponent({ componentName: "TestComponent1", @@ -209,8 +208,8 @@ test("addComponent method works correctly", t => { t.truthy(component.isDefaultComponent === false); }); test("getComponent method overload works correctly", async t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); node.addChild(node2, null, null); GrimoireInterface.registerComponent({ componentName: "TestComponent1", @@ -237,8 +236,8 @@ test("getComponent method overload works correctly", async t => { t.truthy(node.getComponent("TestComponent1").name.name === "TestComponent2"); }); test("getComponents method overload works correctly", t => { - const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); - const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); + const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); + const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); node.addChild(node2, null, null); GrimoireInterface.registerComponent({ componentName: "TestComponent1", diff --git a/test/Core/GomlParserTest.ts b/test/Core/GomlParserTest.ts index 42e7b9090..b010d8f14 100644 --- a/test/Core/GomlParserTest.ts +++ b/test/Core/GomlParserTest.ts @@ -6,40 +6,36 @@ import Namespace from "../../src/Core/Namespace"; import NSIdentity from "../../src/Core/NSIdentity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; -import xmldom from "xmldom"; import XMLReader from "../../src/Tools/XMLReader"; import { assert, spy } from "sinon"; import { - conflictComponent1, - conflictComponent2, - conflictNode1, - conflictNode2, - goml, - stringConverter, - testComponent1, - testComponent2, - testComponentBase, - testComponentOptional, - testNode1, - testNode2, - testNodeBase + registerConflictComponent1, + registerConflictComponent2, + registerConflictNode1, + registerConflictNode2, + registerGoml, + registerStringConverter, + registerTestComponent1, + registerTestComponent2, + registerTestComponentBase, + registerTestComponentOptional, + registerTestNode1, + registerTestNode2, + registerTestNodeBase } from "../DummyObjectRegisterer"; -require("babel-polyfill"); TestEnvManager.init(); -declare namespace global { - let Node: any; - let document: any; - let rootNode: any; -} - - // Get element from test case source which is located with relative path. function obtainElementTag(path) { return XMLReader.parseXML(fs.readFile(path)); } +function registerUserPlugin() { + GrimoireInterface.registerNode("scenes"); + GrimoireInterface.registerNode("scene"); +} + let stringConverterSpy, testComponent1Spy, testComponent2Spy, @@ -47,39 +43,30 @@ let stringConverterSpy, testComponentOptionalSpy, conflictComponent1Spy, conflictComponent2Spy; +const gomlParserTestCasePath1 = "../_TestResource/GomlParserTest_Case1.goml"; +const gomlParserTestCasePath2 = "../_TestResource/GomlParserTest_Case2.goml"; +const gomlParserTestCasePath3 = "../_TestResource/GomlParserTest_Case3.goml"; +const gomlParserTestCasePath4 = "../_TestResource/GomlParserTest_Case4.goml"; test.beforeEach(async () => { GrimoireInterface.clear(); - const parser = new xmldom.DOMParser(); - const htmlDoc = parser.parseFromString("", "text/html"); - Environment.document = htmlDoc; - goml(); - testNode1(); - testNode2(); - testNodeBase(); - conflictNode1(); - conflictNode2(); - stringConverterSpy = stringConverter(); - testComponent1Spy = testComponent1(); - testComponent2Spy = testComponent2(); - testComponentBaseSpy = testComponentBase(); - testComponentOptionalSpy = testComponentOptional(); - conflictComponent1Spy = conflictComponent1(); - conflictComponent2Spy = conflictComponent2(); + registerGoml(); + registerTestNode1(); + registerTestNode2(); + registerTestNodeBase(); + registerConflictNode1(); + registerConflictNode2(); + stringConverterSpy = registerStringConverter(); + testComponent1Spy = registerTestComponent1(); + testComponent2Spy = registerTestComponent2(); + testComponentBaseSpy = registerTestComponentBase(); + testComponentOptionalSpy = registerTestComponentOptional(); + conflictComponent1Spy = registerConflictComponent1(); + conflictComponent2Spy = registerConflictComponent2(); registerUserPlugin(); await GrimoireInterface.resolvePlugins(); }); -const gomlParserTestCasePath1 = "../_TestResource/GomlParserTest_Case1.goml"; -const gomlParserTestCasePath2 = "../_TestResource/GomlParserTest_Case2.goml"; -const gomlParserTestCasePath3 = "../_TestResource/GomlParserTest_Case3.goml"; -const gomlParserTestCasePath4 = "../_TestResource/GomlParserTest_Case4.goml"; - - -function registerUserPlugin() { - GrimoireInterface.registerNode("scenes"); - GrimoireInterface.registerNode("scene"); -} test("test for parsing node hierarchy.", (t) => { const element = obtainElementTag(gomlParserTestCasePath1); diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index 15a159b5c..1cc51ca8d 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -8,9 +8,7 @@ import Namespace from "../../src/Core/Namespace"; import NSIdentity from "../../src/Core/NSIdentity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; -import xmldom from "xmldom"; import { assert, spy } from "sinon"; -require("babel-polyfill"); TestEnvManager.init(); diff --git a/test/Core/NSIdentityTest.ts b/test/Core/NSIdentityTest.ts index dc6fb4fae..350a7f742 100644 --- a/test/Core/NSIdentityTest.ts +++ b/test/Core/NSIdentityTest.ts @@ -1,6 +1,9 @@ import NSIdentity from "../../src/Core/NSIdentity"; import test from "ava"; -require("babel-polyfill"); +import TestEnvManager from "../TestEnvManager"; + + +TestEnvManager.init(); test.beforeEach(() => { NSIdentity.clear(); diff --git a/test/Core/NamespaceTest.ts b/test/Core/NamespaceTest.ts index 955319539..2f6a83980 100644 --- a/test/Core/NamespaceTest.ts +++ b/test/Core/NamespaceTest.ts @@ -6,7 +6,9 @@ import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Namespace from "../../src/Core/Namespace"; import test from "ava"; -require("babel-polyfill"); +import TestEnvManager from "../TestEnvManager"; + +TestEnvManager.init(); test("define/for function works correctly.", (t) => { // TODO test const g = Namespace.define("grimoire"); diff --git a/test/Core/NodeInterfaceTest.ts b/test/Core/NodeInterfaceTest.ts index 5bfae5bcf..d78be62a2 100644 --- a/test/Core/NodeInterfaceTest.ts +++ b/test/Core/NodeInterfaceTest.ts @@ -6,34 +6,32 @@ import GrimoireInterface from "../../src/Core/GrimoireInterface"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import xhrmock from "xhr-mock"; -import xmldom from "xmldom"; import { - conflictComponent1, - conflictComponent2, - conflictNode1, - conflictNode2, - goml, - stringConverter, - testComponent1, - testComponent2, - testComponent3, - testComponentBase, - testComponentOptional, - testNode1, - testNode2, - testNode3, - testNodeBase + registerConflictComponent1, + registerConflictComponent2, + registerConflictNode1, + registerConflictNode2, + registerGoml, + registerStringConverter, + registerTestComponent1, + registerTestComponent2, + registerTestComponent3, + registerTestComponentBase, + registerTestComponentOptional, + registerTestNode1, + registerTestNode2, + registerTestNode3, + registerTestNodeBase } from "../DummyObjectRegisterer"; -TestEnvManager.init(); const testcase1_goml = fs.readFile("../_TestResource/GomlNodeTest_Case1.goml"); const testcase1_html = fs.readFile("../_TestResource/GomlNodeTest_Case1.html"); -xhrmock.setup(); -xhrmock.get("./GomlNodeTest_Case1.goml", (req, res) => { - return res.status(200).body(testcase1_goml); -}); +TestEnvManager.init(testcase1_html); +TestEnvManager.mockSetup(); +TestEnvManager.mock("./GomlNodeTest_Case1.goml", testcase1_goml); + let stringConverterSpy, testComponent1Spy, @@ -56,33 +54,24 @@ function resetSpies() { } test.beforeEach(async () => { GrimoireInterface.clear(); - // const window = await jsdomAsync(html, []); - // Environment.document = window.document; - const parser = new xmldom.DOMParser(); - const htmlDoc = parser.parseFromString(testcase1_html, "text/html"); - Environment.document = htmlDoc; - Environment.document.querySelectorAll = function (selector) { - return Environment.document.getElementsByTagName("script"); - }; - goml(); - testNode1(); - testNode2(); - testNode3(); - testNodeBase(); - conflictNode1(); - conflictNode2(); - stringConverterSpy = stringConverter(); - testComponent1Spy = testComponent1(); - testComponent2Spy = testComponent2(); - testComponent3Spy = testComponent3(); - testComponentBaseSpy = testComponentBase(); - testComponentOptionalSpy = testComponentOptional(); - conflictComponent1Spy = conflictComponent1(); - conflictComponent2Spy = conflictComponent2(); + registerGoml(); + registerTestNode1(); + registerTestNode2(); + registerTestNode3(); + registerTestNodeBase(); + registerConflictNode1(); + registerConflictNode2(); + stringConverterSpy = registerStringConverter(); + testComponent1Spy = registerTestComponent1(); + testComponent2Spy = registerTestComponent2(); + testComponent3Spy = registerTestComponent3(); + testComponentBaseSpy = registerTestComponentBase(); + testComponentOptionalSpy = registerTestComponentOptional(); + conflictComponent1Spy = registerConflictComponent1(); + conflictComponent2Spy = registerConflictComponent2(); await GrimoireInterface.resolvePlugins(); await GomlLoader.loadForPage(); - Environment["rootNode"] = _.values(GrimoireInterface.rootNodes)[0]; }); test("count first single.", (t) => { @@ -91,5 +80,5 @@ test("count first single.", (t) => { // t.truthy(ni.count() === 1); // t.truthy(ni.first()); t.truthy(true); - + // TODO add test }); diff --git a/test/DummyObjectRegisterer.ts b/test/DummyObjectRegisterer.ts index 635e64472..746ced208 100644 --- a/test/DummyObjectRegisterer.ts +++ b/test/DummyObjectRegisterer.ts @@ -2,7 +2,7 @@ import GrimoireInterface from "../src/Core/GrimoireInterface"; import Namespace from "../src/Core/Namespace"; import { spy } from "sinon"; -export function testComponent1() { +export function registerTestComponent1() { const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponent1", @@ -32,7 +32,7 @@ export function testComponent1() { return s; } -export function testComponent2() { +export function registerTestComponent2() { const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponent2", @@ -58,7 +58,7 @@ export function testComponent2() { return s; } -export function testComponent3() { +export function registerTestComponent3() { const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponent3", @@ -92,7 +92,7 @@ export function testComponent3() { return s; } -export function testComponentBase() { +export function registerTestComponentBase() { const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponentBase", @@ -118,7 +118,7 @@ export function testComponentBase() { return s; } -export function testComponentOptional() { +export function registerTestComponentOptional() { const s = spy(); GrimoireInterface.registerComponent({ componentName: "TestComponentOptional", @@ -144,7 +144,7 @@ export function testComponentOptional() { return s; } -export function conflictComponent1() { +export function registerConflictComponent1() { const s = spy(); const ns = Namespace.define("test1"); GrimoireInterface.registerComponent({ @@ -162,7 +162,7 @@ export function conflictComponent1() { return s; } -export function conflictComponent2() { +export function registerConflictComponent2() { const s = spy(); const ns = Namespace.define("test2"); GrimoireInterface.registerComponent({ @@ -183,34 +183,34 @@ export function conflictComponent2() { // Nodes -export function goml() { +export function registerGoml() { GrimoireInterface.registerNode("goml"); } -export function testNode1() { +export function registerTestNode1() { GrimoireInterface.registerNode("test-node1", ["TestComponent1"]); } -export function testNode2() { +export function registerTestNode2() { GrimoireInterface.registerNode("test-node2", ["TestComponent2"], null, "test-node-base"); } -export function testNode3() { +export function registerTestNode3() { GrimoireInterface.registerNode("test-node3", ["TestComponent3"], { hoge: "AAA" }); } -export function testNodeBase() { +export function registerTestNodeBase() { GrimoireInterface.registerNode("test-node-base", ["TestComponentBase"]); } -export function conflictNode1() { +export function registerConflictNode1() { const ns = Namespace.define("test1"); GrimoireInterface.registerNode(ns.for("conflict-node"), ["TestComponent2"], { attr1: "nodeA" }, null, null); } -export function conflictNode2() { +export function registerConflictNode2() { const ns = Namespace.define("test2"); GrimoireInterface.registerNode(ns.for("conflict-node"), ["TestComponent2"], { attr1: "nodeB" @@ -219,7 +219,7 @@ export function conflictNode2() { // Converters -export function stringConverter() { +export function registerStringConverter() { const s = spy(); GrimoireInterface.registerConverter("Str", (arg) => { s(arg); diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index 204e08856..38710b35a 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -3,32 +3,19 @@ import GomlLoader from "../src/Core/GomlLoader"; import GomlParser from "../src/Core/GomlParser"; import GrimoireInterface from "../src/Core/GrimoireInterface"; import IAttributeConverterDeclaration from "../src/Interface/IAttributeConverterDeclaration"; -import IConverterRepository from "../src/Interface/Repository/IConverterRepository"; import jsdomAsync from "./JsDOMAsync"; import NSDictionary from "../src/Tools/NSDictionary"; import NSIdentity from "../src/Core/NSIdentity"; import xhrmock from "xhr-mock"; -import xmldom from "xmldom"; import XMLReader from "../src/Tools/XMLReader"; import xmlserializer from "xmlserializer"; import "babel-polyfill"; - - -class TestEnvContext implements IConverterRepository { - public converters: NSDictionary; - -} - export default class TestEnvManager { - public static context = new TestEnvContext(); - public static addConverter(name: NSIdentity, converter: IAttributeConverterDeclaration) { - this.context.converters.set(name, converter); - } - public static async init() { - const window = await jsdomAsync("", []); + public static async init(html = "") { + const window = await jsdomAsync(html, []); Environment.DomParser = new window.DOMParser(); Environment.document = window.document; diff --git a/test/Tools/IdResolverTest.ts b/test/Tools/IdResolverTest.ts index 9ee91764a..e40010d72 100644 --- a/test/Tools/IdResolverTest.ts +++ b/test/Tools/IdResolverTest.ts @@ -8,9 +8,9 @@ import IdResolver from "../../src/Tools/IdResolver"; import Namespace from "../../src/Core/Namespace"; import NSIdentity from "../../src/Core/NSIdentity"; import test from "ava"; -import xmldom from "xmldom"; -require("babel-polyfill"); +import TestEnvManager from "../TestEnvManager"; +TestEnvManager.init(); test("get() works correctly.", t => { let r = new IdResolver(); diff --git a/test/Tools/NSDictionaryTest.ts b/test/Tools/NSDictionaryTest.ts index f0e8b17db..7232f7602 100644 --- a/test/Tools/NSDictionaryTest.ts +++ b/test/Tools/NSDictionaryTest.ts @@ -4,11 +4,16 @@ import NodeInterface from "../../src/Core/NodeInterface"; import NSDictionary from "../../src/Tools/NSDictionary"; import NSIdentity from "../../src/Core/NSIdentity"; import test from "ava"; +import TestEnvManager from "../TestEnvManager"; import xhrmock from "xhr-mock"; import xmldom from "xmldom"; -require("babel-polyfill"); + + const xml = fs.readFile("../_TestResource/NSDictionary_QueryDOM.xml"); + +TestEnvManager.init(); + test.beforeEach(() => { NSIdentity.clear(); }); diff --git a/test/Tools/NSSetTest.ts b/test/Tools/NSSetTest.ts index 80d1b2efd..239e613ff 100644 --- a/test/Tools/NSSetTest.ts +++ b/test/Tools/NSSetTest.ts @@ -1,8 +1,7 @@ -import test from "ava"; import GomlParser from "../../src/Core/GomlParser"; -import xmldom from "xmldom"; -import NSSet from "../../src/Tools/NSSet"; import NSIdentity from "../../src/Core/NSIdentity"; +import NSSet from "../../src/Tools/NSSet"; +import test from "ava"; test("test parse for goml parser", (t) => { diff --git a/test/Tools/XMLReaderTest.ts b/test/Tools/XMLReaderTest.ts index 3a47d391f..0da9c77f9 100644 --- a/test/Tools/XMLReaderTest.ts +++ b/test/Tools/XMLReaderTest.ts @@ -1,7 +1,6 @@ import fs from "../fileHelper"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; -import xmldom from "xmldom"; import XMLReader from "../../src/Tools/XMLReader"; TestEnvManager.init(); From 579543eff4b4ff3a941101b2bad999aedc39f955 Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 7 Oct 2017 22:36:17 +0900 Subject: [PATCH 035/146] fix: change directory structure/rename identity --- src/Core/Attribute.ts | 14 +- src/Core/AttributeManager.ts | 10 +- src/Core/Component.ts | 20 +-- src/Core/ComponentDeclaration.ts | 20 +-- src/{Tools => Core}/Constants.ts | 0 src/Core/GomlInterfaceImpl.ts | 2 +- src/Core/GomlNode.ts | 20 +-- src/Core/GrimoireInterfaceImpl.ts | 29 ++-- src/Core/{NSIdentity.ts => Identity.ts} | 32 ++-- .../NSDictionary.ts => Core/IdentityMap.ts} | 36 ++--- src/{Tools/NSSet.ts => Core/IdentitySet.ts} | 32 ++-- src/Core/Namespace.ts | 6 +- src/Core/NodeDeclaration.ts | 36 ++--- src/Tools/Ensure.ts | 30 ++-- src/Tools/IdResolver.ts | 10 +- src/Tools/Types.ts | 4 +- src/static/color.json | 149 ------------------ test/Core/AttributeManagerTest.ts | 24 +-- test/Core/AttributeTest.ts | 4 +- test/Core/GomlNode2Test.ts | 12 +- test/Core/GomlNodeTest.ts | 4 +- test/Core/GomlParserTest.ts | 8 +- test/Core/GrimoireInterfaceTest.ts | 4 +- .../IdentityMapTest.ts} | 32 ++-- .../NSSetTest.ts => Core/IdentitySetTest.ts} | 8 +- test/Core/IdentityTest.ts | 64 ++++++++ test/Core/NSIdentityTest.ts | 64 -------- test/Core/NamespaceTest.ts | 2 +- test/TestEnvManager.ts | 4 +- test/TestUtil.ts | 6 +- test/Tools/EnsureTest.ts | 24 +-- test/Tools/IdResolverTest.ts | 34 ++-- 32 files changed, 298 insertions(+), 446 deletions(-) rename src/{Tools => Core}/Constants.ts (100%) rename src/Core/{NSIdentity.ts => Identity.ts} (73%) rename src/{Tools/NSDictionary.ts => Core/IdentityMap.ts} (77%) rename src/{Tools/NSSet.ts => Core/IdentitySet.ts} (50%) delete mode 100644 src/static/color.json rename test/{Tools/NSDictionaryTest.ts => Core/IdentityMapTest.ts} (82%) rename test/{Tools/NSSetTest.ts => Core/IdentitySetTest.ts} (56%) create mode 100644 test/Core/IdentityTest.ts delete mode 100644 test/Core/NSIdentityTest.ts diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index 36f9046fe..51c942e04 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -4,8 +4,8 @@ import Environment from "../Core/Environment"; import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import IdResolver from "../Tools/IdResolver"; -import NSDictionary from "../Tools/NSDictionary"; -import NSIdentity from "../Core/NSIdentity"; +import IdentityMap from "../Core/IdentityMap"; +import Identity from "../Core/Identity"; import { GomlInterface, Name, Nullable } from "../Tools/Types"; /** @@ -15,9 +15,9 @@ export default class Attribute { /** * The name of attribute. - * @type {NSIdentity} + * @type {Identity} */ - public name: NSIdentity; + public name: Identity; /** * The declaration of attribute used for defining this attribute. @@ -62,9 +62,9 @@ export default class Attribute { /** * Companion map which is bounding to the component this attribute bound to. - * @return {NSDictionary} [description] + * @return {IdentityMap} [description] */ - public get companion(): Nullable> { + public get companion(): Nullable> { return this.component.companion; } @@ -112,7 +112,7 @@ export default class Attribute { */ public static generateAttributeForComponent(name: string, declaration: IAttributeDeclaration, component: Component): Attribute { const attr = new Attribute(); - attr.name = NSIdentity.fromFQN(component.name.fqn + "." + name); + attr.name = Identity.fromFQN(component.name.fqn + "." + name); attr.component = component; attr.declaration = declaration; const converterName = Ensure.tobeNSIdentity(declaration.converter); diff --git a/src/Core/AttributeManager.ts b/src/Core/AttributeManager.ts index f54489449..601d7e79c 100644 --- a/src/Core/AttributeManager.ts +++ b/src/Core/AttributeManager.ts @@ -4,7 +4,7 @@ import IdResolver from "../Tools/IdResolver"; import { Name, Undef } from "../Tools/Types"; import Utility from "../Tools/Utility"; import Namespace from "./Namespace"; -import NSIdentity from "./NSIdentity"; +import Identity from "./Identity"; type NameValPair = { fqn: string, val: T }; @@ -211,13 +211,13 @@ export default class AttributeManager { return false; } - public guess(name: Name): NSIdentity[] { - if (name instanceof NSIdentity) { + public guess(name: Name): Identity[] { + if (name instanceof Identity) { return [name]; } if (Ensure.checkFQNString(name)) { - return [NSIdentity.fromFQN(name)]; + return [Identity.fromFQN(name)]; } - return this._idResolver.get(name).map(fqn => NSIdentity.fromFQN(fqn)); + return this._idResolver.get(name).map(fqn => Identity.fromFQN(fqn)); } } diff --git a/src/Core/Component.ts b/src/Core/Component.ts index ee2734e3a..f4a59d140 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -1,12 +1,12 @@ import Attribute from "./Attribute"; -import Constants from "../Tools/Constants"; +import Constants from "./Constants"; import Ensure from "../Tools/Ensure"; import GomlNode from "./GomlNode"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import IDObject from "../Base/IDObject"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; -import NSDictionary from "../Tools/NSDictionary"; -import NSIdentity from "../Core/NSIdentity"; +import IdentityMap from "./IdentityMap"; +import Identity from "./Identity"; import Utility from "../Tools/Utility"; import { GomlInterface, Name, Nullable } from "../Tools/Types"; @@ -17,14 +17,14 @@ import { GomlInterface, Name, Nullable } from "../Tools/Types"; export default class Component extends IDObject { /** * Name of this component - * @type {NSIdentity} + * @type {Identity} */ - public name: NSIdentity; + public name: Identity; /** * Attributes managed by this component - * @type {NSDictionary} + * @type {IdentityMap} */ - public attributes: NSDictionary; + public attributes: IdentityMap; /** * Node this component is attached * @type {GomlNode} @@ -51,7 +51,7 @@ export default class Component extends IDObject { private _enabled = true; private _awaked = false; private _handlers: ((component: Component) => void)[] = []; - private _additionalAttributesNames: NSIdentity[] = []; + private _additionalAttributesNames: Identity[] = []; private _initializedInfo: Nullable = null; public get enabled(): boolean { @@ -68,9 +68,9 @@ export default class Component extends IDObject { } /** * The dictionary which is shared in entire tree. - * @return {NSDictionary} [description] + * @return {IdentityMap} [description] */ - public get companion(): NSDictionary { + public get companion(): IdentityMap { return this.node.companion; } /** diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index 01b503975..530c2537a 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -1,17 +1,17 @@ import Attribute from "./Attribute"; import Component from "./Component"; -import Constants from "../Tools/Constants"; +import Constants from "./Constants"; import Ensure from "../Tools/Ensure"; import Environment from "../Core/Environment"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import IdResolver from "../Tools/IdResolver"; -import NSDictionary from "../Tools/NSDictionary"; -import NSIdentity from "../Core/NSIdentity"; +import IdentityMap from "./IdentityMap"; +import Identity from "./Identity"; import { ComponentRegistering, Ctor, Name } from "../Tools/Types"; export default class ComponentDeclaration { - public static ctorMap: { ctor: ComponentRegistering>, name: NSIdentity }[] = []; + public static ctorMap: { ctor: ComponentRegistering>, name: Identity }[] = []; public superComponent: Ctor; public ctor: Ctor; @@ -26,14 +26,14 @@ export default class ComponentDeclaration { } public constructor( - public name: NSIdentity, + public name: Identity, private _ctorOrObj: ComponentRegistering>, _super?: Name | Ctor) { if (!_super) {// no inherits. this.resolveDependency(); return; } - if (_super instanceof NSIdentity || typeof _super === "string") { + if (_super instanceof Identity || typeof _super === "string") { this._super = _super; } else { this.superComponent = _super; @@ -50,7 +50,7 @@ export default class ComponentDeclaration { Environment.GrimoireInterface.componentDictionary[component.id] = component; component.name = this.name; component.element = componentElement; - component.attributes = new NSDictionary(); + component.attributes = new IdentityMap(); for (let key in this.attributes) { Attribute.generateAttributeForComponent(key, this.attributes[key], component); } @@ -69,14 +69,14 @@ export default class ComponentDeclaration { dec.resolveDependency(); for (let key in dec.attributes) { attr[key] = dec.attributes[key]; - this.idResolver.add(NSIdentity.fromFQN(this.name.fqn + "." + key)); + this.idResolver.add(Identity.fromFQN(this.name.fqn + "." + key)); } this.superComponent = dec.ctor; } this.ctor = this._ensureTobeComponentConstructor(this.name, this._ctorOrObj, dec ? dec.ctor : void 0); for (let key in (this.ctor as any).attributes) { attr[key] = (this.ctor as any).attributes[key]; - this.idResolver.add(NSIdentity.fromFQN(this.name.fqn + "." + key)); + this.idResolver.add(Identity.fromFQN(this.name.fqn + "." + key)); } this.attributes = attr; @@ -90,7 +90,7 @@ export default class ComponentDeclaration { * @param {Object | (new ()=> Component} obj [The variable need to be ensured.] * @return {[type]} [The constructor inherits Component] */ - private _ensureTobeComponentConstructor(id: NSIdentity, obj: ComponentRegistering | ComponentRegistering>, baseConstructor?: Ctor): Ctor { + private _ensureTobeComponentConstructor(id: Identity, obj: ComponentRegistering | ComponentRegistering>, baseConstructor?: Ctor): Ctor { if (typeof obj === "function") { // obj is constructor const inheritsAttr = this._extractInheritsAttributes(obj); if (baseConstructor) { // inherits diff --git a/src/Tools/Constants.ts b/src/Core/Constants.ts similarity index 100% rename from src/Tools/Constants.ts rename to src/Core/Constants.ts diff --git a/src/Core/GomlInterfaceImpl.ts b/src/Core/GomlInterfaceImpl.ts index a4acdb3ba..20e11ee4f 100644 --- a/src/Core/GomlInterfaceImpl.ts +++ b/src/Core/GomlInterfaceImpl.ts @@ -1,4 +1,4 @@ -import Constants from "../Tools/Constants"; +import Constants from "./Constants"; import GomlNode from "../Core/GomlNode"; import GrimoireInterface from "../Core/GrimoireInterface"; import NodeInterface from "./NodeInterface"; diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index 4e63d40fd..960d04f25 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -1,7 +1,7 @@ import Attribute from "./Attribute"; import AttributeManager from "../Core/AttributeManager"; import Component from "./Component"; -import Constants from "../Tools/Constants"; +import Constants from "./Constants"; import EEObject from "../Base/EEObject"; import Ensure from "../Tools/Ensure"; import Environment from "./Environment"; @@ -10,8 +10,8 @@ import GrimoireInterface from "../Core/GrimoireInterface"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; import MessageException from "../Tools/MessageException"; import NodeDeclaration from "./NodeDeclaration"; -import NSDictionary from "../Tools/NSDictionary"; -import NSIdentity from "../Core/NSIdentity"; +import IdentityMap from "./IdentityMap"; +import Identity from "./Identity"; import Utility from "../Tools/Utility"; import XMLReader from "../Tools/XMLReader"; import { @@ -19,7 +19,7 @@ import { GomlInterface, Name, Nullable - } from "../Tools/Types"; +} from "../Tools/Types"; export default class GomlNode extends EEObject { @@ -31,7 +31,7 @@ export default class GomlNode extends EEObject { private _root: Nullable = null; private _components: Component[]; private _tree: GomlInterface = GrimoireInterface([this]); - private _companion: NSDictionary = new NSDictionary(); + private _companion: IdentityMap = new IdentityMap(); private _attributeManager: AttributeManager; private _isActive = false; private _messageCache: { [message: string]: Component[] } = {}; @@ -58,7 +58,7 @@ export default class GomlNode extends EEObject { /** * Tag name. */ - public get name(): NSIdentity { + public get name(): Identity { return this.nodeDeclaration.name; } @@ -106,9 +106,9 @@ export default class GomlNode extends EEObject { /** * the shared object by all nodes in tree. - * @return {NSDictionary} [description] + * @return {IdentityMap} [description] */ - public get companion(): NSDictionary { + public get companion(): IdentityMap { return this._companion; } @@ -283,7 +283,7 @@ export default class GomlNode extends EEObject { /** * add new instance created by given name and attributes for this node as child. - * @param {string | NSIdentity} nodeName [description] + * @param {string | Identity} nodeName [description] * @param {any }} attributes [description] */ public addChildByName(nodeName: Name, attributes: { [attrName: string]: any }): GomlNode { @@ -437,7 +437,7 @@ export default class GomlNode extends EEObject { this._sendMessageForced("unmount"); this._isActive = false; this._tree = GrimoireInterface([this]); - this._companion = new NSDictionary(); + this._companion = new IdentityMap(); this._mounted = mounted; } } diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 1a14237cb..66bd1f47d 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -4,7 +4,7 @@ import BooleanConverter from "../Converters/BooleanConverter"; import Component from "../Core/Component"; import ComponentConverter from "../Converters/ComponentConverter"; import ComponentDeclaration from "../Core/ComponentDeclaration"; -import Constants from "../Tools/Constants"; +import Constants from "./Constants"; import EEObject from "../Base/EEObject"; import Ensure from "../Tools/Ensure"; import EnumConverter from "../Converters/EnumConverter"; @@ -18,8 +18,8 @@ import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; import Namespace from "../Core/Namespace"; import NodeDeclaration from "../Core/NodeDeclaration"; import NodeInterface from "./NodeInterface"; -import NSDictionary from "../Tools/NSDictionary"; -import NSIdentity from "../Core/NSIdentity"; +import IdentityMap from "./IdentityMap"; +import Identity from "./Identity"; import NumberArrayConverter from "../Converters/NumberArrayConverter"; import NumberConverter from "../Converters/NumberConverter"; import ObjectConverter from "../Converters/ObjectConverter"; @@ -31,16 +31,16 @@ import { Ctor, Name, Nullable - } from "../Tools/Types"; +} from "../Tools/Types"; export default class GrimoireInterfaceImpl extends EEObject { - public nodeDeclarations: NSDictionary = new NSDictionary(); + public nodeDeclarations: IdentityMap = new IdentityMap(); - public converters: NSDictionary = new NSDictionary(); + public converters: IdentityMap = new IdentityMap(); - public componentDeclarations: NSDictionary = new NSDictionary(); + public componentDeclarations: IdentityMap = new IdentityMap(); public rootNodes: { [rootNodeId: string]: GomlNode } = {}; @@ -85,8 +85,9 @@ export default class GrimoireInterfaceImpl extends EEObject { * [obsolete] use `Namespace.define` instead of. * @param {string} ns namespace URI to be used * @return {[type]} the namespaced identity + * @deprecated */ - public ns(ns: string): (name: string) => NSIdentity { + public ns(ns: string): (name: string) => Identity { Utility.w("GrimoireInterface.ns is obsolete. please use `Namespace.define()` instead of."); return (name: string) => Namespace.define(ns).for(name); } @@ -139,7 +140,7 @@ export default class GrimoireInterfaceImpl extends EEObject { /** * register custom component - * @param {string | NSIdentity} name [description] + * @param {string | Identity} name [description] * @param {IAttributeDeclaration }} attributes [description] * @param {Object | (new (} obj [description] * @return {[type]} [description] @@ -150,7 +151,7 @@ export default class GrimoireInterfaceImpl extends EEObject { let name: Name; let obj: ComponentRegistering>; let superComponent: Name | Ctor | undefined; - if (typeof arg1 === "string" || arg1 instanceof NSIdentity) { + if (typeof arg1 === "string" || arg1 instanceof Identity) { Utility.w(` registerComponent() overload that call with name is deprecated. use other overload instead of.`); name = arg1; obj = arg2 as ComponentRegistering>; @@ -209,7 +210,7 @@ export default class GrimoireInterfaceImpl extends EEObject { this.nodeDeclarations.set(registerId, declaration); return declaration; } - public getCompanion(scriptTag: Element): NSDictionary { + public getCompanion(scriptTag: Element): IdentityMap { const root = this.getRootNode(scriptTag); if (root) { return root.companion; @@ -399,16 +400,16 @@ export default class GrimoireInterfaceImpl extends EEObject { } } - private _ensureTobeNSIdentityOnRegister(name: Name): NSIdentity; + private _ensureTobeNSIdentityOnRegister(name: Name): Identity; private _ensureTobeNSIdentityOnRegister(name: null | undefined): null; - private _ensureTobeNSIdentityOnRegister(name: Name | null | undefined): Nullable { + private _ensureTobeNSIdentityOnRegister(name: Name | null | undefined): Nullable { if (!name) { return null; } if (typeof name === "string") { const fqn = Ensure.tobeFQN(name); if (fqn) { - return NSIdentity.fromFQN(fqn); + return Identity.fromFQN(fqn); } return Namespace.define(this._registrationContext).for(name); } else { diff --git a/src/Core/NSIdentity.ts b/src/Core/Identity.ts similarity index 73% rename from src/Core/NSIdentity.ts rename to src/Core/Identity.ts index d22af2011..81a2701bd 100644 --- a/src/Core/NSIdentity.ts +++ b/src/Core/Identity.ts @@ -5,9 +5,9 @@ import Ensure from "../Tools/Ensure"; /** * The class to identity with XML namespace feature. */ -export default class NSIdentity { +export default class Identity { - private static _instances: { [fqn: string]: NSIdentity } = {}; + private static _instances: { [fqn: string]: Identity } = {}; private static _mapBackingField: IdResolver; private static get _map(): IdResolver { if (this._mapBackingField === void 0) { @@ -23,40 +23,40 @@ export default class NSIdentity { /** * Generate an instance from Full qualified name. * @param {string} fqn [description] - * @return {NSIdentity} [description] + * @return {Identity} [description] */ - public static fromFQN(fqn: string): NSIdentity { - const inst = NSIdentity._instances[fqn]; + public static fromFQN(fqn: string): Identity { + const inst = Identity._instances[fqn]; if (inst) { return inst; } const splitted = fqn.split("."); - return new NSIdentity(splitted); + return new Identity(splitted); } - public static guess(...hierarchy: string[]): NSIdentity { - return NSIdentity._guess(hierarchy); + public static guess(...hierarchy: string[]): Identity { + return Identity._guess(hierarchy); } public static clear(): void { - NSIdentity._instances = {}; - NSIdentity._mapBackingField = new IdResolver(); + Identity._instances = {}; + Identity._mapBackingField = new IdResolver(); } /** * return instance if exists. * generate and return new instanse if not exist id has same fqn. * @param {string[]} hierarchy [description] - * @return {NSIdentity} [description] + * @return {Identity} [description] */ - private static _guess(hierarchy: string[]): NSIdentity { + private static _guess(hierarchy: string[]): Identity { const fqn = hierarchy.join("."); - const inst = NSIdentity._instances[fqn]; + const inst = Identity._instances[fqn]; if (inst) { return inst; } - return NSIdentity.fromFQN(NSIdentity._map.resolve(Namespace.defineByArray(hierarchy))); + return Identity.fromFQN(Identity._map.resolve(Namespace.defineByArray(hierarchy))); } public constructor(fqn: string | string[]); @@ -77,8 +77,8 @@ export default class NSIdentity { this._fqn = this.ns.hierarchy.concat([this.name]).join("."); - NSIdentity._instances[this._fqn] = this; - NSIdentity._map.add(qn.concat([this._name])); + Identity._instances[this._fqn] = this; + Identity._map.add(qn.concat([this._name])); } /** diff --git a/src/Tools/NSDictionary.ts b/src/Core/IdentityMap.ts similarity index 77% rename from src/Tools/NSDictionary.ts rename to src/Core/IdentityMap.ts index dd586e644..8ca38ed1d 100644 --- a/src/Tools/NSDictionary.ts +++ b/src/Core/IdentityMap.ts @@ -1,22 +1,22 @@ -import NSIdentity from "../Core/NSIdentity"; -import IdResolver from "./IdResolver"; +import Identity from "./Identity"; +import IdResolver from "../Tools/IdResolver"; import Namespace from "../Core/Namespace"; -import Ensure from "./Ensure"; -import {Name, Nullable, Undef} from "./Types"; +import Ensure from "../Tools/Ensure"; +import { Name, Nullable, Undef } from "../Tools/Types"; type Dict = { [key: string]: V }; -export default class NSDictionary { +export default class IdentityMap { private _fqnObjectMap: Dict = {}; private _idResolver: IdResolver = new IdResolver(); - public set(key: NSIdentity, value: V): void { + public set(key: Identity, value: V): void { this._fqnObjectMap[key.fqn] = value; this._idResolver.add(key); } - public delete(key: NSIdentity): boolean { + public delete(key: Identity): boolean { if (this._fqnObjectMap[key.fqn] !== void 0) { delete this._fqnObjectMap[key.fqn]; this._idResolver.remove(key); @@ -28,7 +28,7 @@ export default class NSDictionary { public get(name: Name): V; public get(element: Element): V; public get(attribute: Attr): V; - public get(arg1: string | Element | NSIdentity | Attr): Nullable { + public get(arg1: string | Element | Identity | Attr): Nullable { if (!arg1) { throw new Error("NSDictionary.get() can not recieve args null or undefined."); } @@ -50,7 +50,7 @@ export default class NSDictionary { } } else { - if (arg1 instanceof NSIdentity) { + if (arg1 instanceof Identity) { return this._fqnObjectMap[arg1.fqn]; } else { if (arg1.namespaceURI) { @@ -74,15 +74,15 @@ export default class NSDictionary { return this._idResolver.get(Namespace.defineByArray(name.split("."))).length !== 0; } - public pushDictionary(dict: NSDictionary): NSDictionary { + public pushDictionary(dict: IdentityMap): IdentityMap { dict.forEach((value, keyFQN) => { - const id = NSIdentity.fromFQN(keyFQN); + const id = Identity.fromFQN(keyFQN); this.set(id, value); }); return this; } - public hasMatchingValue(name: NSIdentity): Undef { + public hasMatchingValue(name: Identity): Undef { const resolver = new IdResolver(); resolver.add(name); let match: string | undefined = void 0; @@ -109,20 +109,20 @@ export default class NSDictionary { }); return ret; } - public clone(): NSDictionary { - const dict = new NSDictionary(); + public clone(): IdentityMap { + const dict = new IdentityMap(); return dict.pushDictionary(this); } - public forEach(callback: (value: V, fqn: string) => void): NSDictionary { + public forEach(callback: (value: V, fqn: string) => void): IdentityMap { Object.keys(this._fqnObjectMap).forEach(key => { callback(this._fqnObjectMap[key], key); }); return this; } - public map(callback: ((value: V, fqn: string) => T)): NSDictionary { - const ret = new NSDictionary(); + public map(callback: ((value: V, fqn: string) => T)): IdentityMap { + const ret = new IdentityMap(); this.forEach((val, fqn) => { - const id = NSIdentity.fromFQN(fqn); + const id = Identity.fromFQN(fqn); ret.set(id, callback(val, fqn)); }); return ret; diff --git a/src/Tools/NSSet.ts b/src/Core/IdentitySet.ts similarity index 50% rename from src/Tools/NSSet.ts rename to src/Core/IdentitySet.ts index bdd8505fd..e26f0e045 100644 --- a/src/Tools/NSSet.ts +++ b/src/Core/IdentitySet.ts @@ -1,27 +1,27 @@ -import NSIdentity from "../Core/NSIdentity"; +import Identity from "./Identity"; /** * set of NSIdentity - * @param {NSIdentity[]} array [description] - * @return {NSSet} [description] + * @param {Identity[]} array [description] + * @return {IdentitySet} [description] */ -export default class NSSet { - private _content: { [fqn: string]: NSIdentity } = {}; +export default class IdentitySet { + private _content: { [fqn: string]: Identity } = {}; - public static fromArray(array: NSIdentity[]): NSSet { - const nSet = new NSSet(); + public static fromArray(array: Identity[]): IdentitySet { + const nSet = new IdentitySet(); nSet.pushArray(array); return nSet; } - constructor(content?: NSIdentity[]) { + constructor(content?: Identity[]) { if (content) { this.pushArray(content); } } - public push(item: NSIdentity): boolean { + public push(item: Identity): boolean { if (!this._content[item.fqn]) { this._content[item.fqn] = item; return true; @@ -29,35 +29,35 @@ export default class NSSet { return false; } - public pushArray(item: NSIdentity[]): NSSet { + public pushArray(item: Identity[]): IdentitySet { item.forEach(v => { this.push(v); }); return this; } - public toArray(): NSIdentity[] { - const ret: NSIdentity[] = []; + public toArray(): Identity[] { + const ret: Identity[] = []; for (let key in this._content) { ret.push(this._content[key]); } return ret; } - public clone(): NSSet { - const newSet = new NSSet(); + public clone(): IdentitySet { + const newSet = new IdentitySet(); for (let key in this._content) { newSet.push(this._content[key]); } return newSet; } - public merge(other: NSSet): NSSet { + public merge(other: IdentitySet): IdentitySet { this.pushArray(other.toArray()); return this; } - public forEach(func: (name: NSIdentity) => void): NSSet { + public forEach(func: (name: Identity) => void): IdentitySet { for (let key in this._content) { func(this._content[key]); } diff --git a/src/Core/Namespace.ts b/src/Core/Namespace.ts index cd9f8cba3..e04189eb1 100644 --- a/src/Core/Namespace.ts +++ b/src/Core/Namespace.ts @@ -1,4 +1,4 @@ -import NSIdentity from "./NSIdentity"; +import Identity from "./Identity"; import Utility from "../Tools/Utility"; export default class Namespace { @@ -53,12 +53,12 @@ export default class Namespace { * to NSIdentity with name * @param name name */ - public for(name: string): NSIdentity { + public for(name: string): Identity { if (!name) { throw new Error("name must not be null"); } const fqn = `${this.hierarchy.join(".")}.${name}`; - return NSIdentity.fromFQN(fqn); + return Identity.fromFQN(fqn); } public toString(): string { diff --git a/src/Core/NodeDeclaration.ts b/src/Core/NodeDeclaration.ts index 45d266c6d..4db7dc3f4 100644 --- a/src/Core/NodeDeclaration.ts +++ b/src/Core/NodeDeclaration.ts @@ -1,21 +1,21 @@ import Ensure from "../Tools/Ensure"; -import NSDictionary from "../Tools/NSDictionary"; -import NSSet from "../Tools/NSSet"; -import NSIdentity from "../Core/NSIdentity"; +import IdentityMap from "./IdentityMap"; +import IdentitySet from "./IdentitySet"; +import Identity from "./Identity"; import IdResolver from "../Tools/IdResolver"; import GrimoireInterface from "../Core/GrimoireInterface"; -import Constants from "../Tools/Constants"; +import Constants from "./Constants"; import { Name } from "../Tools/Types"; export default class NodeDeclaration { - public defaultComponents: NSSet; - public defaultAttributes: NSDictionary = new NSDictionary(); - public superNode?: NSIdentity; - public freezeAttributes: NSSet; + public defaultComponents: IdentitySet; + public defaultAttributes: IdentityMap = new IdentityMap(); + public superNode?: Identity; + public freezeAttributes: IdentitySet; public idResolver = new IdResolver(); - private _defaultComponentsActual: NSSet; - private _defaultAttributesActual: NSDictionary; + private _defaultComponentsActual: IdentitySet; + private _defaultAttributesActual: IdentityMap; private _resolvedDependency = false; @@ -23,14 +23,14 @@ export default class NodeDeclaration { return this._resolvedDependency; } - public get defaultComponentsActual(): NSSet { + public get defaultComponentsActual(): IdentitySet { if (!this._resolvedDependency) { throw new Error(`${this.name.fqn} is not resolved dependency!`); } return this._defaultComponentsActual; } - public get defaultAttributesActual(): NSDictionary { + public get defaultAttributesActual(): IdentityMap { if (!this._resolvedDependency) { throw new Error(`${this.name.fqn} is not resolved dependency!`); } @@ -38,13 +38,13 @@ export default class NodeDeclaration { } constructor( - public name: NSIdentity, + public name: Identity, private _defaultComponents: Name[], private _defaultAttributes: { [key: string]: any }, private _superNode?: Name, private _freezeAttributes: Name[] = []) { if (!this._superNode && this.name.fqn !== Constants.baseNodeName) { - this._superNode = NSIdentity.fromFQN(Constants.baseNodeName); + this._superNode = Identity.fromFQN(Constants.baseNodeName); } this._freezeAttributes = this._freezeAttributes || []; } @@ -66,21 +66,21 @@ export default class NodeDeclaration { if (this._resolvedDependency) { return false; } - this.defaultComponents = new NSSet(this._defaultComponents.map(name => Ensure.tobeNSIdentity(name))); + this.defaultComponents = new IdentitySet(this._defaultComponents.map(name => Ensure.tobeNSIdentity(name))); for (let key in this._defaultAttributes) { let value = this._defaultAttributes[key]; - this.defaultAttributes.set(NSIdentity.fromFQN(key), value); + this.defaultAttributes.set(Identity.fromFQN(key), value); } this.superNode = this._superNode ? Ensure.tobeNSIdentity(this._superNode) : void 0; this._resolveInherites(); this._defaultComponentsActual.forEach(id => { const dec = GrimoireInterface.componentDeclarations.get(id); dec.idResolver.foreach(fqn => { - this.idResolver.add(NSIdentity.fromFQN(fqn)); + this.idResolver.add(Identity.fromFQN(fqn)); }); }); - this.freezeAttributes = new NSSet(this._freezeAttributes.map(name => Ensure.tobeNSIdentity(name))); + this.freezeAttributes = new IdentitySet(this._freezeAttributes.map(name => Ensure.tobeNSIdentity(name))); this._resolvedDependency = true; return true; } diff --git a/src/Tools/Ensure.ts b/src/Tools/Ensure.ts index 0824868e7..951487f51 100644 --- a/src/Tools/Ensure.ts +++ b/src/Tools/Ensure.ts @@ -1,21 +1,21 @@ import Component from "../Core/Component"; import ComponentDeclaration from "../Core/ComponentDeclaration"; import Environment from "../Core/Environment"; -import NSDictionary from "./NSDictionary"; -import NSIdentity from "../Core/NSIdentity"; +import IdentityMap from "../Core/IdentityMap"; +import Identity from "../Core/Identity"; import { ComponentRegistering, Ctor, Name, Nullable - } from "./Types"; +} from "./Types"; /** * Provides static methods to ensure arguments are valid type. */ export default class Ensure { - public static tobeComponentIdentity(component: Name | (new () => Component)): NSIdentity { + public static tobeComponentIdentity(component: Name | (new () => Component)): Identity { if (typeof component === "function") { const obj = ComponentDeclaration.ctorMap.find(o => o.ctor === component); if (obj) { @@ -61,40 +61,40 @@ export default class Ensure { /** * string or NSIdentity ensure to be NSIdentity. * @param {Name} name [description] - * @return {NSIdentity} [description] + * @return {Identity} [description] */ - public static tobeNSIdentity(name: Name): NSIdentity { + public static tobeNSIdentity(name: Name): Identity { if (!name) { throw Error(`argument can not be null or undefined.`); } if (typeof name === "string") { - return NSIdentity.guess(name); + return Identity.guess(name); } else { return name; } } - public static tobeNSIdentityArray(names: Name[]): NSIdentity[] { + public static tobeNSIdentityArray(names: Name[]): Identity[] { if (!names) { return []; } - const newArr: NSIdentity[] = []; + const newArr: Identity[] = []; for (let i = 0; i < names.length; i++) { newArr.push(this.tobeNSIdentity(names[i])); } return newArr; } - public static tobeNSDictionary(dict: NSDictionary | { [key: string]: T }): NSDictionary { + public static tobeNSDictionary(dict: IdentityMap | { [key: string]: T }): IdentityMap { if (!dict) { - return new NSDictionary(); + return new IdentityMap(); } - if (dict instanceof NSDictionary) { + if (dict instanceof IdentityMap) { return dict; } else { - const newDict = new NSDictionary(); + const newDict = new IdentityMap(); for (let key in dict) { - newDict.set(NSIdentity.guess(key), dict[key]); + newDict.set(Identity.guess(key), dict[key]); } return newDict; } @@ -157,7 +157,7 @@ export default class Ensure { * @return {[type]} [description] */ public static tobeName(name: Name | ComponentRegistering): Name { - if (typeof name === "string" || name instanceof NSIdentity) { + if (typeof name === "string" || name instanceof Identity) { return name; } return name.componentName!; diff --git a/src/Tools/IdResolver.ts b/src/Tools/IdResolver.ts index 2185fd67d..359facde5 100644 --- a/src/Tools/IdResolver.ts +++ b/src/Tools/IdResolver.ts @@ -1,5 +1,5 @@ import Namespace from "../Core/Namespace"; -import NSIdentity from "../Core/NSIdentity"; +import Identity from "../Core/Identity"; /** @@ -18,14 +18,14 @@ export default class IdResolver { /** * add id to resolver context. - * @param {NSIdentity} id [description] + * @param {Identity} id [description] * @return {boolean} true if succcess adding. */ - public add(id: string[] | NSIdentity): boolean { + public add(id: string[] | Identity): boolean { if (!id) { throw new Error(`Argument ns is null or undefined.`); } - if (id instanceof NSIdentity) { + if (id instanceof Identity) { id = id.ns.hierarchy.concat([id.name]); } if (id.length === 0) { @@ -75,7 +75,7 @@ export default class IdResolver { public has(name: string): boolean { return !!this._nameMap[name]; } - public remove(name: NSIdentity): void { + public remove(name: Identity): void { const fqn = name.fqn.split("."); this._remove(fqn); } diff --git a/src/Tools/Types.ts b/src/Tools/Types.ts index 2677c0a75..03310728f 100644 --- a/src/Tools/Types.ts +++ b/src/Tools/Types.ts @@ -1,11 +1,11 @@ -import NSIdentity from "../Core/NSIdentity"; +import Identity from "../Core/Identity"; import GomlInterfaceImpl from "../Core/GomlInterfaceImpl"; import GomlNode from "../Core/GomlNode"; import GrimoireInterfaceImpl from "../Core/GrimoireInterfaceImpl"; import NodeInterface from "../Core/NodeInterface"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; -export type Name = string | NSIdentity; +export type Name = string | Identity; export type GomlInterface = GomlInterfaceImpl & IGomlInterface; export type IGrimoireInterface = { (query: string): GomlInterface; diff --git a/src/static/color.json b/src/static/color.json deleted file mode 100644 index 3531be59a..000000000 --- a/src/static/color.json +++ /dev/null @@ -1,149 +0,0 @@ -{ - "aliceblue": "#F0F8FF", - "antiquewhite": "#FAEBD7", - "aqua": "#00FFFF", - "aquamarine": "#7FFFD4", - "azure": "#F0FFFF", - "beige": "#F5F5DC", - "bisque": "#FFE4C4", - "black": "#000000", - "blanchedalmond": "#FFEBCD", - "blue": "#0000FF", - "blueviolet": "#8A2BE2", - "brown": "#A52A2A", - "burlywood": "#DEB887", - "cadetblue": "#5F9EA0", - "chartreuse": "#7FFF00", - "chocolate": "#D2691E", - "coral": "#FF7F50", - "cornflowerblue": "#6495ED", - "cornsilk": "#FFF8DC", - "crimson": "#DC143C", - "cyan": "#00FFFF", - "darkblue": "#00008B", - "darkcyan": "#008B8B", - "darkgoldenrod": "#B8860B", - "darkgray": "#A9A9A9", - "darkgreen": "#006400", - "darkgrey": "#A9A9A9", - "darkkhaki": "#BDB76B", - "darkmagenta": "#8B008B", - "darkolivegreen": "#556B2F", - "darkorange": "#FF8C00", - "darkorchid": "#9932CC", - "darkred": "#8B0000", - "darksalmon": "#E9967A", - "darkseagreen": "#8FBC8F", - "darkslateblue": "#483D8B", - "darkslategray": "#2F4F4F", - "darkslategrey": "#2F4F4F", - "darkturquoise": "#00CED1", - "darkviolet": "#9400D3", - "deeppink": "#FF1493", - "deepskyblue": "#00BFFF", - "dimgray": "#696969", - "dimgrey": "#696969", - "dodgerblue": "#1E90FF", - "firebrick": "#B22222", - "floralwhite": "#FFFAF0", - "forestgreen": "#228B22", - "fuchsia": "#FF00FF", - "gainsboro": "#DCDCDC", - "ghostwhite": "#F8F8FF", - "gold": "#FFD700", - "goldenrod": "#DAA520", - "gray": "#808080", - "green": "#008000", - "greenyellow": "#ADFF2F", - "grey": "#808080", - "honeydew": "#F0FFF0", - "hotpink": "#FF69B4", - "indianred": "#CD5C5C", - "indigo": "#4B0082", - "ivory": "#FFFFF0", - "khaki": "#F0E68C", - "lavender": "#E6E6FA", - "lavenderblush": "#FFF0F5", - "lawngreen": "#7CFC00", - "lemonchiffon": "#FFFACD", - "lightblue": "#ADD8E6", - "lightcoral": "#F08080", - "lightcyan": "#E0FFFF", - "lightgoldenrodyellow": "#FAFAD2", - "lightgray": "#D3D3D3", - "lightgreen": "#90EE90", - "lightgrey": "#D3D3D3", - "lightpink": "#FFB6C1", - "lightsalmon": "#FFA07A", - "lightseagreen": "#20B2AA", - "lightskyblue": "#87CEFA", - "lightslategray": "#778899", - "lightslategrey": "#778899", - "lightsteelblue": "#B0C4DE", - "lightyellow": "#FFFFE0", - "lime": "#00FF00", - "limegreen": "#32CD32", - "linen": "#FAF0E6", - "magenta": "#FF00FF", - "maroon": "#800000", - "mediumaquamarine": "#66CDAA", - "mediumblue": "#0000CD", - "mediumorchid": "#BA55D3", - "mediumpurple": "#9370DB", - "mediumseagreen": "#3CB371", - "mediumslateblue": "#7B68EE", - "mediumspringgreen": "#00FA9A", - "mediumturquoise": "#48D1CC", - "mediumvioletred": "#C71585", - "midnightblue": "#191970", - "mintcream": "#F5FFFA", - "mistyrose": "#FFE4E1", - "moccasin": "#FFE4B5", - "navajowhite": "#FFDEAD", - "navy": "#000080", - "oldlace": "#FDF5E6", - "olive": "#808000", - "olivedrab": "#6B8E23", - "orange": "#FFA500", - "orangered": "#FF4500", - "orchid": "#DA70D6", - "palegoldenrod": "#EEE8AA", - "palegreen": "#98FB98", - "paleturquoise": "#AFEEEE", - "palevioletred": "#DB7093", - "papayawhip": "#FFEFD5", - "peachpuff": "#FFDAB9", - "peru": "#CD853F", - "pink": "#FFC0CB", - "plum": "#DDA0DD", - "powderblue": "#B0E0E6", - "purple": "#800080", - "red": "#FF0000", - "rosybrown": "#BC8F8F", - "royalblue": "#4169E1", - "saddlebrown": "#8B4513", - "salmon": "#FA8072", - "sandybrown": "#F4A460", - "seagreen": "#2E8B57", - "seashell": "#FFF5EE", - "sienna": "#A0522D", - "silver": "#C0C0C0", - "skyblue": "#87CEEB", - "slateblue": "#6A5ACD", - "slategray": "#708090", - "slategrey": "#708090", - "snow": "#FFFAFA", - "springgreen": "#00FF7F", - "steelblue": "#4682B4", - "tan": "#D2B48C", - "teal": "#008080", - "thistle": "#D8BFD8", - "tomato": "#FF6347", - "turquoise": "#40E0D0", - "violet": "#EE82EE", - "wheat": "#F5DEB3", - "white": "#FFFFFF", - "whitesmoke": "#F5F5F5", - "yellow": "#FFFF00", - "yellowgreen": "#9ACD32" -} diff --git a/test/Core/AttributeManagerTest.ts b/test/Core/AttributeManagerTest.ts index fa9213e77..1ba94ca90 100644 --- a/test/Core/AttributeManagerTest.ts +++ b/test/Core/AttributeManagerTest.ts @@ -1,6 +1,6 @@ import Attribute from "../../src/Core/Attribute"; import AttributeManager from "../../src/Core/AttributeManager"; -import NSIdentity from "../../src/Core/NSIdentity"; +import Identity from "../../src/Core/Identity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import { assert, spy as sinonSpy } from "sinon"; @@ -9,13 +9,13 @@ TestEnvManager.init(); -const genAttr: (name: NSIdentity, watch?: Function | undefined) => Attribute = (name, watch) => { +const genAttr: (name: Identity, watch?: Function | undefined) => Attribute = (name, watch) => { return { name: name, watch: watch, Value: "value of " + name } as Attribute; }; -const ns1 = NSIdentity.fromFQN("aaa"); -const ns2 = NSIdentity.fromFQN("ns.bbb"); -const ns3 = NSIdentity.fromFQN("ns.hoge.ccc"); +const ns1 = Identity.fromFQN("aaa"); +const ns2 = Identity.fromFQN("ns.bbb"); +const ns3 = Identity.fromFQN("ns.hoge.ccc"); const genAM = () => { const am = new AttributeManager("tag"); @@ -60,7 +60,7 @@ test("addAttribute with value/watch buffers should works correctly", (t) => { const am = genAM(); am.setAttribute(fqn, "hogehoge"); t.truthy(am.getAttribute(fqn) === "hogehoge"); - let attr = genAttr(NSIdentity.fromFQN(fqn)); + let attr = genAttr(Identity.fromFQN(fqn)); am.addAttribute(attr); t.truthy(am.getAttribute(fqn) === "hogehoge"); t.truthy(attr.Value === "hogehoge"); @@ -68,7 +68,7 @@ test("addAttribute with value/watch buffers should works correctly", (t) => { const fqn2 = "notregisterd.fqn.hoge2"; const spy = sinonSpy(); const attrRaw = new Attribute(); - attrRaw.name = NSIdentity.fromFQN(fqn2); + attrRaw.name = Identity.fromFQN(fqn2); attrRaw.component = { isActive: true } as any; attrRaw.converter = { convert: x => x } as any; am.watch(fqn2, (n, o, a) => { @@ -94,16 +94,16 @@ test("watch should works correctly", () => { const spy1 = sinonSpy(); const spy2 = sinonSpy(); const notCalledSpy = sinonSpy(); - am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"), () => { + am.addAttribute(genAttr(Identity.fromFQN("hoge.aaa"), () => { spy1("watch"); })); - am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"), () => { + am.addAttribute(genAttr(Identity.fromFQN("hoge.aaa"), () => { spy2("watch"); })); - am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.bbbbbb"), () => { + am.addAttribute(genAttr(Identity.fromFQN("hoge.bbbbbb"), () => { notCalledSpy("watch"); })); - am.watch(NSIdentity.guess("hoge.aaa"), (a, b, c) => { /*do nothing*/ }); + am.watch(Identity.guess("hoge.aaa"), (a, b, c) => { /*do nothing*/ }); assert.called(spy1); assert.called(spy2); assert.notCalled(notCalledSpy); @@ -113,7 +113,7 @@ test("set/getAttribute should works correctly", (t) => { const am = genAM(); am.setAttribute("aaa", "hoge"); t.truthy(am.getAttribute("aaa") === "hoge"); - am.addAttribute(genAttr(NSIdentity.fromFQN("hoge.aaa"))); + am.addAttribute(genAttr(Identity.fromFQN("hoge.aaa"))); t.throws(() => { am.getAttribute("aaa"); // ambiguous }); diff --git a/test/Core/AttributeTest.ts b/test/Core/AttributeTest.ts index 541cc11af..869c168c8 100644 --- a/test/Core/AttributeTest.ts +++ b/test/Core/AttributeTest.ts @@ -1,7 +1,7 @@ import Attribute from "../../src/Core/Attribute"; import GrimoireComponent from "../../src/Components/GrimoireComponent"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import NSIdentity from "../../src/Core/NSIdentity"; +import Identity from "../../src/Core/Identity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import TestUtil from "../TestUtil"; @@ -24,7 +24,7 @@ test("attibute poperties should be initialized correctly", (t) => { t.truthy(idAttr.name.fqn === "grimoirejs.GrimoireComponent.id"); t.truthy(idAttr.declaration.default === null); - t.truthy((idAttr.converter.name as NSIdentity).fqn === "grimoirejs.String"); + t.truthy((idAttr.converter.name as Identity).fqn === "grimoirejs.String"); t.truthy(idAttr.component === baseComponent); }); diff --git a/test/Core/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts index 37b3adc4d..1a0feef78 100644 --- a/test/Core/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -6,7 +6,7 @@ import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import GrimoireComponent from "../../src/Components/GrimoireComponent"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import NSIdentity from "../../src/Core/NSIdentity"; +import Identity from "../../src/Core/Identity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import { assert, spy } from "sinon"; @@ -26,7 +26,7 @@ import { registerTestNode2, registerTestNode3, registerTestNodeBase - } from "../DummyObjectRegisterer"; +} from "../DummyObjectRegisterer"; TestEnvManager.init(); @@ -415,7 +415,7 @@ test("attribute buffer is valid only last set value.", t => { converter: "String", default: "aaa" }); - att = rootNode.getAttribute(NSIdentity.fromFQN(c.name.fqn + ".hoge")); + att = rootNode.getAttribute(Identity.fromFQN(c.name.fqn + ".hoge")); t.truthy(att === "aaa"); rootNode.setAttribute("ns2.aaa", "1"); @@ -425,7 +425,7 @@ test("attribute buffer is valid only last set value.", t => { converter: "String", default: "aaa" }); - att = rootNode.getAttribute(NSIdentity.fromFQN(c.name.fqn + ".ns2.aaa")); + att = rootNode.getAttribute(Identity.fromFQN(c.name.fqn + ".ns2.aaa")); t.truthy(att === "3"); }); @@ -462,7 +462,7 @@ test("get/setAttribute should work correctly 7", t => { }); att = rootNode.getAttribute("ns2.hoge"); t.truthy(att === "2"); - att = rootNode.getAttribute(NSIdentity.fromFQN(c.name.fqn + ".hoge")); + att = rootNode.getAttribute(Identity.fromFQN(c.name.fqn + ".hoge")); t.truthy(att === "3"); }); test("get/setAttribute should work correctly 8", t => { @@ -490,7 +490,7 @@ test("get/setAttribute should work correctly 8", t => { converter: "String", default: "3" }); - att = rootNode.getAttribute(NSIdentity.fromFQN(c.name.fqn + ".hoge")); + att = rootNode.getAttribute(Identity.fromFQN(c.name.fqn + ".hoge")); t.truthy(att === "3"); }); diff --git a/test/Core/GomlNodeTest.ts b/test/Core/GomlNodeTest.ts index 5c0e02c90..b5e73b8c9 100644 --- a/test/Core/GomlNodeTest.ts +++ b/test/Core/GomlNodeTest.ts @@ -1,12 +1,12 @@ import Attribute from "../../src/Core/Attribute"; import Component from "../../src/Core/Component"; -import Constants from "../../src/Tools/Constants"; +import Constants from "../../src/Core/Constants"; import Environment from "../../src/Core/Environment"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import NSIdentity from "../../src/Core/NSIdentity"; +import Identity from "../../src/Core/Identity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import xmldom from "xmldom"; diff --git a/test/Core/GomlParserTest.ts b/test/Core/GomlParserTest.ts index b010d8f14..58f9f173c 100644 --- a/test/Core/GomlParserTest.ts +++ b/test/Core/GomlParserTest.ts @@ -3,7 +3,7 @@ import fs from "../fileHelper"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Namespace from "../../src/Core/Namespace"; -import NSIdentity from "../../src/Core/NSIdentity"; +import Identity from "../../src/Core/Identity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import XMLReader from "../../src/Tools/XMLReader"; @@ -22,7 +22,7 @@ import { registerTestNode1, registerTestNode2, registerTestNodeBase - } from "../DummyObjectRegisterer"; +} from "../DummyObjectRegisterer"; TestEnvManager.init(); @@ -119,8 +119,8 @@ test("test for companion", (t) => { const element = obtainElementTag(gomlParserTestCasePath4); const node = GomlParser.parse(element); const components = node.children[0].getComponents(); - const ns1 = NSIdentity.fromFQN("test1.ConflictComponent"); - const ns2 = NSIdentity.fromFQN("test2.ConflictComponent"); + const ns1 = Identity.fromFQN("test1.ConflictComponent"); + const ns2 = Identity.fromFQN("test2.ConflictComponent"); const compo1 = components.find((comp) => ns1.fqn === comp.name.fqn); const compo2 = components.find((comp) => ns2.fqn === comp.name.fqn); t.truthy(compo1.companion === compo2.companion); diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index 1cc51ca8d..a345475f6 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -1,11 +1,11 @@ import Component from "../../src/Core/Component"; -import Constants from "../../src/Tools/Constants"; +import Constants from "../../src/Core/Constants"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Namespace from "../../src/Core/Namespace"; -import NSIdentity from "../../src/Core/NSIdentity"; +import Identity from "../../src/Core/Identity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import { assert, spy } from "sinon"; diff --git a/test/Tools/NSDictionaryTest.ts b/test/Core/IdentityMapTest.ts similarity index 82% rename from test/Tools/NSDictionaryTest.ts rename to test/Core/IdentityMapTest.ts index 7232f7602..2f7722a76 100644 --- a/test/Tools/NSDictionaryTest.ts +++ b/test/Core/IdentityMapTest.ts @@ -1,8 +1,8 @@ import fs from "../fileHelper"; import GomlLoader from "../../src/Core/GomlLoader"; import NodeInterface from "../../src/Core/NodeInterface"; -import NSDictionary from "../../src/Tools/NSDictionary"; -import NSIdentity from "../../src/Core/NSIdentity"; +import NSDictionary from "../../src/Core/IdentityMap"; +import Identity from "../../src/Core/Identity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; import xhrmock from "xhr-mock"; @@ -15,11 +15,11 @@ const xml = fs.readFile("../_TestResource/NSDictionary_QueryDOM.xml"); TestEnvManager.init(); test.beforeEach(() => { - NSIdentity.clear(); + Identity.clear(); }); test("set element correctly", t => { - const newKey = NSIdentity.fromFQN("hoge.test"); + const newKey = Identity.fromFQN("hoge.test"); const value = "Grimoire"; const theDict = new NSDictionary(); theDict.set(newKey, value); @@ -29,8 +29,8 @@ test("set element correctly", t => { }); test("set element correctly when dupelicated name was given", (t) => { - const newKey = NSIdentity.fromFQN("test"); - const secoundKey = NSIdentity.fromFQN("ns.test"); + const newKey = Identity.fromFQN("test"); + const secoundKey = Identity.fromFQN("ns.test"); const v1 = "gr1"; const v2 = "gr2"; const theDict = new NSDictionary(); @@ -43,8 +43,8 @@ test("set element correctly when dupelicated name was given", (t) => { }); test("element should be repalaced when dupelicated fqn was given", (t) => { - const newKey = NSIdentity.fromFQN("test"); - const secoundKey = NSIdentity.fromFQN("Test"); + const newKey = Identity.fromFQN("test"); + const secoundKey = Identity.fromFQN("Test"); const theDict = new NSDictionary(); theDict.set(newKey, "test1"); theDict.set(secoundKey, "test2"); @@ -53,8 +53,8 @@ test("element should be repalaced when dupelicated fqn was given", (t) => { }); test("get element with strict name", async (t) => { - const newKey = NSIdentity.fromFQN("test"); - const secoundKey = NSIdentity.fromFQN("test.test"); + const newKey = Identity.fromFQN("test"); + const secoundKey = Identity.fromFQN("test.test"); const theDict = new NSDictionary(); theDict.set(newKey, "test1"); theDict.set(secoundKey, "test2"); @@ -72,8 +72,8 @@ test("get element with strict name", async (t) => { }); test("get element with shortened namespace prefix", async (t) => { - const newKey = NSIdentity.fromFQN("test"); - const secoundKey = NSIdentity.fromFQN("grimoirejs.test"); + const newKey = Identity.fromFQN("test"); + const secoundKey = Identity.fromFQN("grimoirejs.test"); const theDict = new NSDictionary(); theDict.set(newKey, "test1"); theDict.set(secoundKey, "test2"); @@ -89,7 +89,7 @@ test("get element with shortened namespace prefix", async (t) => { }); }); test("get element with shortened namespace prefix", async (t) => { - const newKey = NSIdentity.fromFQN("test"); + const newKey = Identity.fromFQN("test"); const theDict = new NSDictionary(); theDict.set(newKey, "test"); const domParser = new xmldom.DOMParser(); @@ -101,7 +101,7 @@ test("get element with shortened namespace prefix", async (t) => { }); test("get element with fuzzy name", async (t) => { - const secoundKey = NSIdentity.fromFQN("grimoirejs.test"); + const secoundKey = Identity.fromFQN("grimoirejs.test"); const theDict = new NSDictionary(); theDict.set(secoundKey, "test2"); const domParser = new xmldom.DOMParser(); @@ -115,8 +115,8 @@ test("get element with fuzzy name", async (t) => { }); test("get element with ambiguous name should throw error", async (t) => { - const newKey = NSIdentity.fromFQN("AATEST.test"); - const secoundKey = NSIdentity.fromFQN("AATEST2.test"); + const newKey = Identity.fromFQN("AATEST.test"); + const secoundKey = Identity.fromFQN("AATEST2.test"); const theDict = new NSDictionary(); theDict.set(newKey, "test1"); theDict.set(secoundKey, "test2"); diff --git a/test/Tools/NSSetTest.ts b/test/Core/IdentitySetTest.ts similarity index 56% rename from test/Tools/NSSetTest.ts rename to test/Core/IdentitySetTest.ts index 239e613ff..98a247698 100644 --- a/test/Tools/NSSetTest.ts +++ b/test/Core/IdentitySetTest.ts @@ -1,12 +1,12 @@ import GomlParser from "../../src/Core/GomlParser"; -import NSIdentity from "../../src/Core/NSIdentity"; -import NSSet from "../../src/Tools/NSSet"; +import Identity from "../../src/Core/Identity"; +import IdentitySet from "../../src/Core/IdentitySet"; import test from "ava"; test("test parse for goml parser", (t) => { - const name = NSIdentity.fromFQN("namespace1.name1"); - const set = new NSSet(); + const name = Identity.fromFQN("namespace1.name1"); + const set = new IdentitySet(); set.push(name); const array = set.toArray(); t.truthy(array.length === 1); diff --git a/test/Core/IdentityTest.ts b/test/Core/IdentityTest.ts new file mode 100644 index 000000000..4ec7d0053 --- /dev/null +++ b/test/Core/IdentityTest.ts @@ -0,0 +1,64 @@ +import Identity from "../../src/Core/Identity"; +import test from "ava"; +import TestEnvManager from "../TestEnvManager"; + + +TestEnvManager.init(); + +test.beforeEach(() => { + Identity.clear(); +}); + +test("generate instance works correctly", t => { + let inst = Identity.fromFQN("hoge"); + t.truthy(inst.fqn === "hoge"); + t.truthy(Identity.fromFQN("hoge") === inst); // instance is singleton for same fqn. +}); + +test("Not accept to get invalid name or namespace", (t) => { + Identity.fromFQN("hoge"); + Identity.fromFQN("other.a.hoge"); + Identity.fromFQN("other.b.hoge"); + Identity.fromFQN("a.b"); + t.throws(() => { + Identity.guess("aaa"); // not found + }); + t.throws(() => { + Identity.guess("b", "a"); // not found + }); + t.throws(() => { + Identity.guess("Wrongamespace", "WrongName"); // not found + }); + + t.truthy(Identity.guess("hoge").fqn === "hoge"); // ok because strict fqn match. + t.truthy(Identity.guess("a", "b").fqn === "a.b"); + t.truthy(Identity.guess("b").fqn === "a.b"); + + t.throws(() => { + Identity.guess("a"); // not name + }); + t.throws(() => { + let a = Identity.guess("other.hoge"); // ambiguous + console.log(a); + }); + t.truthy(Identity.guess("a.hoge").fqn === "other.a.hoge"); +}); + +test("Transform name and ns correctly", (t) => { + const i = Identity.fromFQN("ns.ns1.Sample"); + t.truthy(i.name === "Sample"); + t.truthy(i.ns.qualifiedName === "ns.ns1"); +}); + +test("isMatch works correctly", t => { + let hoge = Identity.fromFQN("a.b.c"); + t.truthy(hoge.isMatch("c")); + t.truthy(hoge.isMatch("b.c")); + t.truthy(hoge.isMatch("a.c")); + t.truthy(hoge.isMatch("a.b.c")); + t.truthy(!hoge.isMatch("c.c")); + t.truthy(!hoge.isMatch("b.a.c")); + t.truthy(!hoge.isMatch("b")); + t.truthy(!hoge.isMatch("d")); + t.truthy(!hoge.isMatch("a.d")); +}); diff --git a/test/Core/NSIdentityTest.ts b/test/Core/NSIdentityTest.ts deleted file mode 100644 index 350a7f742..000000000 --- a/test/Core/NSIdentityTest.ts +++ /dev/null @@ -1,64 +0,0 @@ -import NSIdentity from "../../src/Core/NSIdentity"; -import test from "ava"; -import TestEnvManager from "../TestEnvManager"; - - -TestEnvManager.init(); - -test.beforeEach(() => { - NSIdentity.clear(); -}); - -test("generate instance works correctly", t => { - let inst = NSIdentity.fromFQN("hoge"); - t.truthy(inst.fqn === "hoge"); - t.truthy(NSIdentity.fromFQN("hoge") === inst); // instance is singleton for same fqn. -}); - -test("Not accept to get invalid name or namespace", (t) => { - NSIdentity.fromFQN("hoge"); - NSIdentity.fromFQN("other.a.hoge"); - NSIdentity.fromFQN("other.b.hoge"); - NSIdentity.fromFQN("a.b"); - t.throws(() => { - NSIdentity.guess("aaa"); // not found - }); - t.throws(() => { - NSIdentity.guess("b", "a"); // not found - }); - t.throws(() => { - NSIdentity.guess("Wrongamespace", "WrongName"); // not found - }); - - t.truthy(NSIdentity.guess("hoge").fqn === "hoge"); // ok because strict fqn match. - t.truthy(NSIdentity.guess("a", "b").fqn === "a.b"); - t.truthy(NSIdentity.guess("b").fqn === "a.b"); - - t.throws(() => { - NSIdentity.guess("a"); // not name - }); - t.throws(() => { - let a = NSIdentity.guess("other.hoge"); // ambiguous - console.log(a); - }); - t.truthy(NSIdentity.guess("a.hoge").fqn === "other.a.hoge"); -}); - -test("Transform name and ns correctly", (t) => { - const i = NSIdentity.fromFQN("ns.ns1.Sample"); - t.truthy(i.name === "Sample"); - t.truthy(i.ns.qualifiedName === "ns.ns1"); -}); - -test("isMatch works correctly", t => { - let hoge = NSIdentity.fromFQN("a.b.c"); - t.truthy(hoge.isMatch("c")); - t.truthy(hoge.isMatch("b.c")); - t.truthy(hoge.isMatch("a.c")); - t.truthy(hoge.isMatch("a.b.c")); - t.truthy(!hoge.isMatch("c.c")); - t.truthy(!hoge.isMatch("b.a.c")); - t.truthy(!hoge.isMatch("b")); - t.truthy(!hoge.isMatch("d")); - t.truthy(!hoge.isMatch("a.d")); -}); diff --git a/test/Core/NamespaceTest.ts b/test/Core/NamespaceTest.ts index 2f6a83980..b64f01089 100644 --- a/test/Core/NamespaceTest.ts +++ b/test/Core/NamespaceTest.ts @@ -1,5 +1,5 @@ import Component from "../../src/Core/Component"; -import Constants from "../../src/Tools/Constants"; +import Constants from "../../src/Core/Constants"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import GomlParser from "../../src/Core/GomlParser"; diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index 38710b35a..9c93a9508 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -4,8 +4,8 @@ import GomlParser from "../src/Core/GomlParser"; import GrimoireInterface from "../src/Core/GrimoireInterface"; import IAttributeConverterDeclaration from "../src/Interface/IAttributeConverterDeclaration"; import jsdomAsync from "./JsDOMAsync"; -import NSDictionary from "../src/Tools/NSDictionary"; -import NSIdentity from "../src/Core/NSIdentity"; +import IdentityMap from "../src/Core/IdentityMap"; +import Identity from "../src/Core/Identity"; import xhrmock from "xhr-mock"; import XMLReader from "../src/Tools/XMLReader"; import xmlserializer from "xmlserializer"; diff --git a/test/TestUtil.ts b/test/TestUtil.ts index a4d643c3a..5b33d517d 100644 --- a/test/TestUtil.ts +++ b/test/TestUtil.ts @@ -7,13 +7,13 @@ import GomlParser from "../src/Core/GomlParser"; import GrimoireInterface from "../src/Core/GrimoireInterface"; import IAttributeDeclaration from "../src/Interface/IAttributeDeclaration"; import ITreeInitializedInfo from "../src/Interface/ITreeInitializedInfo"; -import NSIdentity from "../src/Core/NSIdentity"; +import Identity from "../src/Core/Identity"; import XMLReader from "../src/Tools/XMLReader"; export default class TestUtil { public static DummyComponentDeclaration(): ComponentDeclaration { - return new ComponentDeclaration(NSIdentity.fromFQN("aaa"), { + return new ComponentDeclaration(Identity.fromFQN("aaa"), { attributes: { } @@ -24,7 +24,7 @@ export default class TestUtil { return dec.generateInstance(null); } - public static DummyAttribute(name: NSIdentity, component: Component, declaration: IAttributeDeclaration): Attribute { + public static DummyAttribute(name: Identity, component: Component, declaration: IAttributeDeclaration): Attribute { const attr = new Attribute(); attr.name = name; attr.component = component; diff --git a/test/Tools/EnsureTest.ts b/test/Tools/EnsureTest.ts index b6dfb1194..6302b830d 100644 --- a/test/Tools/EnsureTest.ts +++ b/test/Tools/EnsureTest.ts @@ -1,16 +1,16 @@ import test from "ava"; import Ensure from "../../src/Tools/Ensure"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import NSDictionary from "../../src/Tools/NSDictionary"; -import NSIdentity from "../../src/Core/NSIdentity"; +import IdentityMap from "../../src/Core/IdentityMap"; +import Identity from "../../src/Core/Identity"; import Namespace from "../../src/Core/Namespace"; test.beforeEach(() => { - NSIdentity.clear(); + Identity.clear(); }); test("Ensure passed argument should be transformed as NSIdentity", (t) => { - NSIdentity.fromFQN("grimoirejs.HELLO"); + Identity.fromFQN("grimoirejs.HELLO"); t.truthy(Ensure.tobeNSIdentity("HELLO").fqn === "grimoirejs.HELLO"); t.truthy(Ensure.tobeNSIdentity(Namespace.define("test").for("WORLD")).fqn === "test.WORLD"); }); @@ -33,8 +33,8 @@ test("Ensure passed array are transformed into NSIdentity[]", (t) => { let transformed = Ensure.tobeNSIdentityArray(undefined); const g = Namespace.define("test"); t.truthy(transformed.length === 0); - NSIdentity.fromFQN("HELLO"); - NSIdentity.fromFQN("grimoire.WORLD"); + Identity.fromFQN("HELLO"); + Identity.fromFQN("grimoire.WORLD"); transformed = Ensure.tobeNSIdentityArray(["HELLO", "WORLD"]); t.truthy(transformed[0].fqn === "HELLO"); t.truthy(transformed[1].fqn === "grimoire.WORLD"); @@ -45,12 +45,12 @@ test("Ensure passed array are transformed into NSIdentity[]", (t) => { test("Ensure passed object are transformed into NSDictionary", (t) => { let transformed = Ensure.tobeNSDictionary(void 0); - t.truthy(transformed instanceof NSDictionary); + t.truthy(transformed instanceof IdentityMap); let obj = {}; - obj[NSIdentity.fromFQN("Hello").fqn] = "test1"; - obj[NSIdentity.fromFQN("World").fqn] = "test2"; + obj[Identity.fromFQN("Hello").fqn] = "test1"; + obj[Identity.fromFQN("World").fqn] = "test2"; transformed = Ensure.tobeNSDictionary(obj); - t.truthy(transformed instanceof NSDictionary); + t.truthy(transformed instanceof IdentityMap); t.truthy(transformed.get("Hello") === "test1"); t.truthy(transformed.get("World") === "test2"); }); @@ -60,6 +60,6 @@ test("Ensure name tobe fqn if name start with _", t => { t.truthy(Ensure.tobeFQN("_aaa") === "aaa"); t.truthy(Ensure.tobeFQN("aaa.fff") == null); t.truthy(Ensure.tobeFQN("_aaa.fff") === "aaa.fff"); - t.truthy(Ensure.tobeFQN(NSIdentity.fromFQN("aaa.bbb")) === "aaa.bbb"); - t.truthy(Ensure.tobeFQN(NSIdentity.fromFQN("aaa")) === "aaa"); + t.truthy(Ensure.tobeFQN(Identity.fromFQN("aaa.bbb")) === "aaa.bbb"); + t.truthy(Ensure.tobeFQN(Identity.fromFQN("aaa")) === "aaa"); }); diff --git a/test/Tools/IdResolverTest.ts b/test/Tools/IdResolverTest.ts index e40010d72..278321e78 100644 --- a/test/Tools/IdResolverTest.ts +++ b/test/Tools/IdResolverTest.ts @@ -1,12 +1,12 @@ import Component from "../../src/Core/Component"; -import Constants from "../../src/Tools/Constants"; +import Constants from "../../src/Core/Constants"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import IdResolver from "../../src/Tools/IdResolver"; import Namespace from "../../src/Core/Namespace"; -import NSIdentity from "../../src/Core/NSIdentity"; +import Identity from "../../src/Core/Identity"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; @@ -14,7 +14,7 @@ TestEnvManager.init(); test("get() works correctly.", t => { let r = new IdResolver(); - r.add(NSIdentity.fromFQN("c.b.a")); + r.add(Identity.fromFQN("c.b.a")); t.truthy(r.get(Namespace.define("a")).length === 1); t.truthy(r.get(Namespace.define("b.a")).length === 1); t.truthy(r.get(Namespace.define("c.a")).length === 1); @@ -24,26 +24,26 @@ test("get() works correctly.", t => { test("Not accept to get invalid name or namespace", (t) => { let r = new IdResolver(); - r.add(NSIdentity.fromFQN("a")); + r.add(Identity.fromFQN("a")); r = new IdResolver(); // console.log("a"); - t.truthy(r.add(NSIdentity.fromFQN("a"))); + t.truthy(r.add(Identity.fromFQN("a"))); t.truthy(r.count === 1); - t.truthy(!r.add(NSIdentity.fromFQN("a"))); + t.truthy(!r.add(Identity.fromFQN("a"))); t.truthy(r.count === 1); // console.log("f"); r.add(Namespace.define("z").for("b")); r.add(Namespace.define("y.b").hierarchy); - r.add(NSIdentity.fromFQN("c")); + r.add(Identity.fromFQN("c")); t.truthy(r.count === 4); t.truthy(r.get(Namespace.define("a")).length === 1); t.truthy(r.get(Namespace.define("b")).length === 2); - let id = NSIdentity.fromFQN("a.b.c"); + let id = Identity.fromFQN("a.b.c"); t.truthy(id.name === "c"); t.truthy(id.ns.qualifiedName === "a.b"); - id = NSIdentity.guess("b.c"); + id = Identity.guess("b.c"); t.truthy(id.fqn === "a.b.c"); @@ -52,20 +52,20 @@ test("Not accept to get invalid name or namespace", (t) => { test("Not accept to get invalid name or namespace", (t) => { let r = new IdResolver(); // console.log(r); - r.add(NSIdentity.fromFQN("a")); - r.add(NSIdentity.fromFQN("hoge.b")); - r.add(NSIdentity.fromFQN("hage.huga.c")); - r.add(NSIdentity.fromFQN("hage.a")); + r.add(Identity.fromFQN("a")); + r.add(Identity.fromFQN("hoge.b")); + r.add(Identity.fromFQN("hage.huga.c")); + r.add(Identity.fromFQN("hage.a")); t.truthy(r.get(Namespace.define("a")).length === 2); }); test("resolve works correctly", (t) => { let r = new IdResolver(); - r.add(NSIdentity.fromFQN("hoge.a")); - r.add(NSIdentity.fromFQN("hoge.b")); - r.add(NSIdentity.fromFQN("hage.huga.c")); - r.add(NSIdentity.fromFQN("hage.huga.a")); + r.add(Identity.fromFQN("hoge.a")); + r.add(Identity.fromFQN("hoge.b")); + r.add(Identity.fromFQN("hage.huga.c")); + r.add(Identity.fromFQN("hage.huga.a")); t.truthy(r.get(Namespace.define("a")).length === 2); t.truthy(r.get(Namespace.define("b")).length === 1); t.truthy(r.resolve(Namespace.define("c")) === "hage.huga.c"); From ad04250c0ba2aaeadd2b11e99209266c9ef57e83 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 8 Oct 2017 01:31:50 +0900 Subject: [PATCH 036/146] fix: update tslint.json --- package.json | 5 +- tslint.json | 242 ++++++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 215 insertions(+), 32 deletions(-) diff --git a/package.json b/package.json index be693fd45..7fbb245b4 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,8 @@ "scripts": { "coverage": "trash coverage && nyc --reporter=lcov --reporter=text --reporter=json --reporter=html npm run test", "test": "trash test-lib && tsc -p tsconfig.test.json && cpx test/_TestResource/**/* test-lib/_TestResource && ava ./test-lib/**/*Test.js --verbose --serial", - "lint": "tslint -c tslint.json ./src/**/*.ts", + "lint": "tslint -c tslint.json ./src/**/*.ts --project ./ --type-check --exclude ./src/index.ts", + "lint:fix": "tslint -c tslint.json ./src/**/*.ts --project ./ --type-check --exclude ./src/index.ts --fix", "prepublish": "webpack --progress --env.prod && npm test", "start": "webpack --progress --watch", "build": "webpack --progress", @@ -87,4 +88,4 @@ "**/src/**/*" ] } -} +} \ No newline at end of file diff --git a/tslint.json b/tslint.json index bd638a51e..b4f2bac5d 100644 --- a/tslint.json +++ b/tslint.json @@ -1,56 +1,238 @@ { - "rulesDirectory":[], + "rulesDirectory": [], "rules": { - "class-name": true, - "comment-format": [true, "check-space"], - "curly": true, - "eofline": true, - "indent": [true, "spaces"], - "label-position": true, + "adjacent-overload-signatures": true, + "ban-types": false, "member-access": true, - "member-ordering": [true, - "public-before-private", - "static-before-instance", - "variables-before-functions" + "member-ordering": [ + true, + { + "order": [ + "public-static-field", + "protected-static-field", + "private-static-field", + "public-static-method", + "protected-static-method", + "private-static-method", + "public-instance-field", + "protected-instance-field", + "private-instance-field", + "public-constructor", + "protected-constructor", + "private-constructor", + "public-instance-method", + "protected-instance-method", + "private-instance-method" + ] + } ], + "no-any": false, + "no-empty-interface": false, + "no-import-side-effect": false, + "no-inferrable-types": true, + "no-internal-module": true, + "no-magic-numbers": false, + "no-namespace": true, + "no-non-null-assertion": false, + "no-parameter-reassignment": true, + "no-reference": true, + "no-unnecessary-type-assertion": true, + "no-var-requires": true, + "only-arrow-functions": false, + "prefer-for-of": false, + "promise-function-async": true, + "typedef": false, + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "unified-signatures": false, + "await-promise": true, + "ban": false, + "curly": true, + "forin": false, + "import-blacklist": false, + "label-position": true, "no-arg": true, - "no-console": [true, - "debug", + "no-bitwise": false, + "no-conditional-assignment": false, + "no-console": [ + true, + "log", "time", "timeEnd", "trace" ], - "no-construct": true, + "no-construct": false, "no-debugger": true, + "no-duplicate-super": true, "no-duplicate-variable": true, "no-empty": true, "no-eval": true, - "no-inferrable-types": true, + "no-floating-promises": true, + "no-for-in-array": false, + "no-inferred-empty-object-type": true, + "no-invalid-template-strings": true, + "no-invalid-this": false, + "no-misused-new": false, + "no-null-keyword": false, + "no-object-literal-type-assertion": false, "no-shadowed-variable": true, + "no-sparse-arrays": true, + "no-string-literal": false, + "no-string-throw": true, + "no-submodule-imports": false, "no-switch-case-fall-through": true, - "no-trailing-whitespace": true, + "no-this-assignment": false, + "no-unbound-method": false, + "no-unsafe-any": false, + "no-unsafe-finally": true, "no-unused-expression": true, + "no-unused-variable": true, "no-use-before-declare": true, "no-var-keyword": true, - "one-line": [true, + "no-void-expression": true, + "prefer-conditional-expression": false, + "prefer-object-spread": true, + "radix": true, + "restrict-plus-operands": true, + "strict-boolean-expressions": false, + "strict-type-predicates": false, + "switch-default": false, + "triple-equals": [ + true, + "allow-null-check" + ], + "typeof-compare": true, + "use-default-type-parameter": true, + "use-isnan": true, + "cyclomatic-complexity": false, + "deprecation": true, + "eofline": true, + "indent": [ + true, + "spaces", + 2 + ], + "linebreak-style": [ + true, + "LF" + ], + "max-classes-per-file": false, + "max-file-line-count": false, + "max-line-length": false, + "no-default-export": false, + "no-duplicate-imports": true, + "no-mergeable-namespace": true, + "no-require-imports": true, + "object-literal-sort-keys": false, + "prefer-const": true, + "trailing-comma": [ + true, + { + "singleline": "never", + "multiline": "always" + } + ], + "align": true, + "array-type": [ + true, + "array" + ], + "arrow-parens": false, + "arrow-return-shorthand": true, + "binary-expression-operand-order": false, + "callable-types": false, + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "completed-docs": [ + true, + { + "classes": true, + "interfaces": true, + "methods": { + "privacies": [ + "public" + ] + }, + "properties": { + "privacies": [ + "public" + ] + } + } + ], + "encoding": true, + "file-header": false, + "import-spacing": true, + "interface-name": true, + "interface-over-type-literal": false, + "jsdoc-format": true, + "match-default-export-name": true, + "newline-before-return": false, + "new-parens": true, + "no-angle-bracket-type-assertion": true, + "no-boolean-literal-compare": true, + "no-consecutive-blank-lines": true, + "no-irregular-whitespace": true, + "no-parameter-properties": false, + "no-reference-import": true, + "no-trailing-whitespace": true, + "no-unnecessary-callback-wrapper": true, + "no-unnecessary-initializer": true, + "no-unnecessary-qualifier": true, + "number-literal-format": true, + "object-literal-key-quotes": [ + true, + "as-needed" + ], + "object-literal-shorthand": true, + "one-line": [ + true, "check-open-brace", "check-catch", "check-else", "check-whitespace" ], - "quotemark": [true, "double", "avoid-escape"], - "radix": true, - "semicolon": true, - "triple-equals": [true, "allow-null-check"], - "typedef-whitespace": [true, { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - }], + "one-variable-per-declaration": false, + "ordered-imports": true, + "prefer-function-over-method": false, + "prefer-method-signature": true, + "prefer-switch": false, + "prefer-template": [ + true, + "allow-single-concat" + ], + "quotemark": [ + true, + "double", + "avoid-escape", + "avoid-template" + ], + "return-undefined": true, + "semicolon": [ + true, + "always" + ], + "space-before-function-paren": [ + true, + "never" + ], + "space-within-parens": true, + "switch-final-break": true, + "type-literal-delimiter": false, "variable-name": false, - "whitespace": [true, + "whitespace": [ + true, "check-branch", "check-decl", "check-operator", @@ -58,4 +240,4 @@ "check-type" ] } -} +} \ No newline at end of file From f9740ce82fbc2121565a98f81742c2cda24ea85e Mon Sep 17 00:00:00 2001 From: moajo Date: Tue, 10 Oct 2017 14:16:25 +0900 Subject: [PATCH 037/146] fix: lint --- src/Base/EEObject.ts | 14 +- src/Base/IDObject.ts | 9 +- src/Components/GrimoireComponent.ts | 26 ++- src/Converters/ArrayConverter.ts | 21 +- src/Converters/BooleanConverter.ts | 1 - src/Converters/ComponentConverter.ts | 25 ++- src/Converters/EnumConverter.ts | 15 +- src/Converters/NumberConverter.ts | 8 +- src/Core/Attribute.ts | 95 +++++---- src/Core/AttributeManager.ts | 53 ++++- src/Core/Component.ts | 78 +++++-- src/Core/ComponentDeclaration.ts | 77 +++++-- src/Core/Constants.ts | 13 ++ src/Core/Environment.ts | 22 ++ src/Core/GomlInterfaceImpl.ts | 4 +- src/Core/GomlLoader.ts | 11 +- src/Core/GomlNode.ts | 193 ++++++++++++------ src/Core/GomlParser.ts | 4 +- src/Core/GrimoireInterface.ts | 5 +- src/Core/GrimoireInterfaceImpl.ts | 193 ++++++++++++++---- src/Core/Identity.ts | 44 ++-- src/Core/IdentityMap.ts | 68 +++++- src/Core/IdentitySet.ts | 36 +++- src/Core/Namespace.ts | 25 ++- src/Core/NodeDeclaration.ts | 55 ++++- src/Core/NodeInterface.ts | 85 ++++++-- .../IAttributeConverterDeclaration.ts | 5 +- src/Interface/IAttributeDeclaration.ts | 6 +- src/Interface/ITreeInitializedInfo.ts | 7 +- src/Tools/Ensure.ts | 35 +++- src/Tools/IdResolver.ts | 51 +++-- src/Tools/MessageException.ts | 5 +- src/Tools/Types.ts | 2 +- src/Tools/Utility.ts | 63 +++++- src/Tools/XMLHttpRequestAsync.ts | 12 +- src/Tools/XMLReader.ts | 75 +------ tslint.json | 4 +- 37 files changed, 1047 insertions(+), 398 deletions(-) diff --git a/src/Base/EEObject.ts b/src/Base/EEObject.ts index 911d36886..c9050f884 100644 --- a/src/Base/EEObject.ts +++ b/src/Base/EEObject.ts @@ -9,22 +9,26 @@ class EEObject extends IDObject implements EventEmitter { * Return an array listing the events for which the emitter has registered * listeners. */ - public eventNames: () => Array; + public eventNames: () => (string | symbol)[]; /** * Return the listeners registered for a given event. */ - public listeners: ((event: string | symbol, exists: boolean) => Array | boolean) & ((event: string | symbol) => Array); + public listeners: ((event: string | symbol, exists: boolean) => ListenerFn[] | boolean) & ((event: string | symbol) => ListenerFn[]); /** * Calls each of the listeners registered for a given event. */ - public emit: (event: string | symbol, ...args: Array) => boolean; + public emit: (event: string | symbol, ...args: any[]) => boolean; /** * Add a listener for a given event. */ public on: (event: string | symbol, fn: ListenerFn, context?: any) => this; + + /** + * add listener + */ public addListener: (event: string | symbol, fn: ListenerFn, context?: any) => this; /** @@ -36,6 +40,10 @@ class EEObject extends IDObject implements EventEmitter { * Remove the listeners of a given event. */ public removeListener: (event: string | symbol, fn?: ListenerFn, context?: any, once?: boolean) => this; + + /** + * remove listener. + */ public off: (event: string | symbol, fn?: ListenerFn, context?: any, once?: boolean) => this; /** diff --git a/src/Base/IDObject.ts b/src/Base/IDObject.ts index ef968b27e..eee9dcfbb 100644 --- a/src/Base/IDObject.ts +++ b/src/Base/IDObject.ts @@ -3,10 +3,6 @@ * @type {[type]} */ export default class IDObject { - /** - * ID related to this instance to identify. - */ - public readonly id: string; /** * Generate random string @@ -17,6 +13,11 @@ export default class IDObject { return Math.random().toString(36).slice(-length); } + /** + * ID related to this instance to identify. + */ + public readonly id: string; + constructor() { this.id = IDObject.getUniqueRandom(10); } diff --git a/src/Components/GrimoireComponent.ts b/src/Components/GrimoireComponent.ts index 4dba3b324..2b40688c1 100644 --- a/src/Components/GrimoireComponent.ts +++ b/src/Components/GrimoireComponent.ts @@ -1,25 +1,39 @@ -import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import Component from "../Core/Component"; +import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +/** + * Basic Component for all node. + */ export default class GrimoireComponent extends Component { + + /** + * component name. + */ public static componentName = "GrimoireComponent"; + + /** + * attributes + */ public static attributes: { [key: string]: IAttributeDeclaration } = { id: { converter: "String", - default: null + default: null, }, class: { converter: "StringArray", - default: null + default: null, }, enabled: { converter: "Boolean", - default: true - } + default: true, + }, }; + /** + * awake + */ public $awake(): void { - const node = this.node!; + const node = this.node; node.resolveAttributesValue(); this.getAttributeRaw("id").watch((attr) => { node.element.id = attr ? attr : ""; diff --git a/src/Converters/ArrayConverter.ts b/src/Converters/ArrayConverter.ts index a4f42f2ce..ae5eee2bb 100644 --- a/src/Converters/ArrayConverter.ts +++ b/src/Converters/ArrayConverter.ts @@ -14,13 +14,22 @@ const escape = "\\"; */ export default { name: "Array", - verify: function (attr: Attribute) { + /** + * verify + * @param attr + */ + verify(attr: Attribute) { if (!attr.declaration["type"]) { throw new Error("Array converter needs to be specified type in attribute declaration."); } }, - convert: function (val: any, attr: Attribute) { - let converter = GrimoireInterface.converters.get(attr.declaration["type"]); + /** + * convert + * @param val + * @param attr + */ + convert(val: any, attr: Attribute) { + const converter = GrimoireInterface.converters.get(attr.declaration["type"]); if (!converter) { throw new Error(`converter ${attr.declaration["type"]} is not registerd.`); } @@ -28,9 +37,9 @@ export default { return val.map(v => converter.convert(v, attr)); } if (typeof val === "string") { - let ar = val.split(splitter); + const ar = val.split(splitter); for (let i = 0; i < ar.length; i++) { - let s = ar[i]; + const s = ar[i]; if (s[s.length - 1] === escape) { if (i === ar.length - 1) { ar[i] = s.substring(0, s.length - escape.length) + splitter; @@ -44,5 +53,5 @@ export default { return ar.map(v => converter.convert(v, attr)); } return null; - } + }, }; diff --git a/src/Converters/BooleanConverter.ts b/src/Converters/BooleanConverter.ts index 1ae51d718..989d98692 100644 --- a/src/Converters/BooleanConverter.ts +++ b/src/Converters/BooleanConverter.ts @@ -1,6 +1,5 @@ import { Undef } from "../Tools/Types"; - /** * converter for booleam value. * Pass through boolean value as it is. diff --git a/src/Converters/ComponentConverter.ts b/src/Converters/ComponentConverter.ts index 199ee1b25..ae81c9e27 100644 --- a/src/Converters/ComponentConverter.ts +++ b/src/Converters/ComponentConverter.ts @@ -1,8 +1,7 @@ -import Ensure from "../Tools/Ensure"; +import Attribute from "../Core/Attribute"; import Component from "../Core/Component"; import GomlNode from "../Core/GomlNode"; -import Attribute from "../Core/Attribute"; - +import Ensure from "../Tools/Ensure"; /** * コンポーネントのためのコンバータです。 @@ -14,17 +13,27 @@ import Attribute from "../Core/Attribute"; */ export default { name: "Component", - verify: function (attr: Attribute) { + + /** + * verify + * @param attr + */ + verify(attr: Attribute) { if (!attr.declaration["target"]) { throw new Error("Component converter require to be specified target"); } }, - convert: function (val: any, attr: Attribute) { + /** + * convert + * @param val + * @param attr + */ + convert(val: any, attr: Attribute) { if (val === null) { return null; } if (val instanceof GomlNode) { - return val.getComponent(attr.declaration["target"]); + return val.getComponent(attr.declaration["target"]); } else if (val instanceof Component) { if (val.name.fqn === Ensure.tobeNSIdentity(attr.declaration["target"]).fqn) { return val; @@ -34,9 +43,9 @@ export default { } else { const n = attr.tree!(val).first(); if (n) { - return n.getComponent(attr.declaration["target"]); + return n.getComponent(attr.declaration["target"]); } return null; } - } + }, }; diff --git a/src/Converters/EnumConverter.ts b/src/Converters/EnumConverter.ts index cfb0c17ba..1c9326f1d 100644 --- a/src/Converters/EnumConverter.ts +++ b/src/Converters/EnumConverter.ts @@ -8,12 +8,21 @@ import Attribute from "../Core/Attribute"; */ export default { name: "Enum", - verify: function (attr: Attribute) { + /** + * verify + * @param attr + */ + verify(attr: Attribute) { if (!attr.declaration["table"]) { throw new Error("Enum converter needs to be specified table in attribute dictionary"); } }, - convert: function (val: any, attr: Attribute) { + /** + * convert + * @param val + * @param attr + */ + convert(val: any, attr: Attribute) { if (val === null) { return null; } @@ -27,5 +36,5 @@ export default { } return result; } - } + }, }; diff --git a/src/Converters/NumberConverter.ts b/src/Converters/NumberConverter.ts index 41adde99a..579858b34 100644 --- a/src/Converters/NumberConverter.ts +++ b/src/Converters/NumberConverter.ts @@ -1,5 +1,5 @@ -import Utility from "../Tools/Utility"; import { Undef } from "../Tools/Types"; +import Utility from "../Tools/Utility"; /** * converter for number value. @@ -13,15 +13,15 @@ export default function NumberConverter(val: any): Undef { return val; } if (typeof val === "string") { - let parsed = Number.parseFloat(val); + const parsed = Number.parseFloat(val); return Number.isNaN(parsed) ? void 0 : parsed; } if (val === null) { return null; } if (Array.isArray(val) && val.length === 1) { - Utility.w(`[Deprecated] converting from Array is deprecated in NumberConverter.`); - let ret = val[0]; + Utility.w("[Deprecated] converting from Array is deprecated in NumberConverter."); + const ret = val[0]; if (typeof ret === "number") { return ret; } diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index 51c942e04..881949ae2 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -1,18 +1,58 @@ -import Component from "./Component"; -import Ensure from "../Tools/Ensure"; import Environment from "../Core/Environment"; +import Identity from "../Core/Identity"; +import IdentityMap from "../Core/IdentityMap"; import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +import Ensure from "../Tools/Ensure"; import IdResolver from "../Tools/IdResolver"; -import IdentityMap from "../Core/IdentityMap"; -import Identity from "../Core/Identity"; import { GomlInterface, Name, Nullable } from "../Tools/Types"; +import Component from "./Component"; /** * Manage a attribute attached to components. */ export default class Attribute { + /** + * convert value by provided converter. + * @param converter + * @param self + * @param val + * @deprecated + */ + public static convert(converter: Name, self: Attribute, val: any): any { // TODO unuse? + const cname = Ensure.tobeNSIdentity(converter); + const conv = Environment.GrimoireInterface.converters.get(cname); + if (!conv) { + throw new Error(`converter ${cname.name} is not defined.`); + } + return conv.convert(val, self); + } + + /** + * Construct a new attribute with name of key and any value with specified type. If constant flag is true, This attribute will be immutable. + * If converter is not served, string converter will be set as default. + * @param {string} key Key of this attribute. + * @param {any} value Value of this attribute. + * @param {ConverterBase} converter Converter of this attribute. + * @param {boolean} constant Whether this attribute is immutable or not. False as default. + */ + public static generateAttributeForComponent(name: string, declaration: IAttributeDeclaration, component: Component): Attribute { + const attr = new Attribute(); + attr.name = Identity.fromFQN(`${component.name.fqn}.${name}`); + attr.component = component; + attr.declaration = declaration; + const converterName = Ensure.tobeNSIdentity(declaration.converter); + attr.converter = Environment.GrimoireInterface.converters.get(converterName); + if (attr.converter === void 0) { + // When the specified converter was not found + throw new Error(`Specified converter ${converterName.name} was not found from registered converters.\n Component: ${attr.component.name.fqn}\n Attribute: ${attr.name.name}`); + } + attr.component.attributes.set(attr.name, attr); + attr.converter.verify(attr); + return attr; + } + /** * The name of attribute. * @type {Identity} @@ -37,6 +77,9 @@ export default class Attribute { */ public component: Component; + /** + * Internal use! + */ public convertContext: any = {}; /** * Cache of attribute value. @@ -92,40 +135,6 @@ export default class Attribute { this._notifyChange(val); } - - public static convert(converter: Name, self: Attribute, val: any): any { // TODO unuse? - const cname = Ensure.tobeNSIdentity(converter); - const conv = Environment.GrimoireInterface.converters.get(cname); - if (!conv) { - throw new Error(`converter ${cname.name} is not defined.`); - } - return conv.convert(val, self); - } - - /** - * Construct a new attribute with name of key and any value with specified type. If constant flag is true, This attribute will be immutable. - * If converter is not served, string converter will be set as default. - * @param {string} key Key of this attribute. - * @param {any} value Value of this attribute. - * @param {ConverterBase} converter Converter of this attribute. - * @param {boolean} constant Whether this attribute is immutable or not. False as default. - */ - public static generateAttributeForComponent(name: string, declaration: IAttributeDeclaration, component: Component): Attribute { - const attr = new Attribute(); - attr.name = Identity.fromFQN(component.name.fqn + "." + name); - attr.component = component; - attr.declaration = declaration; - const converterName = Ensure.tobeNSIdentity(declaration.converter); - attr.converter = Environment.GrimoireInterface.converters.get(converterName); - if (attr.converter === void 0) { - // When the specified converter was not found - throw new Error(`Specified converter ${converterName.name} was not found from registered converters.\n Component: ${attr.component.name.fqn}\n Attribute: ${attr.name.name}`); - } - attr.component.attributes.set(attr.name, attr); - attr.converter.verify(attr); - return attr; - } - /** * Add event handler to observe changing this attribute. * @param {(attr: Attribute) => void} handler handler the handler you want to add. @@ -175,7 +184,7 @@ export default class Attribute { get: () => this.Value, set: (val) => { this.Value = val; }, enumerable: true, - configurable: true + configurable: true, }); } else { let backing: any; @@ -186,7 +195,7 @@ export default class Attribute { get: () => backing, set: (val) => { this.Value = val; }, enumerable: true, - configurable: true + configurable: true, }); } } @@ -204,7 +213,7 @@ export default class Attribute { const resolver = new IdResolver(); resolver.add(this.name); let tagAttrKey; - for (let key in domValues) { + for (const key in domValues) { if (Ensure.checkFQNString(key)) { if (this.name.fqn === key.substring(1)) { this.Value = domValues[key]; @@ -212,7 +221,7 @@ export default class Attribute { } continue; } - let get = resolver.get(key); + const get = resolver.get(key); if (get.length > 0) { if (tagAttrKey === void 0) { tagAttrKey = key; @@ -227,7 +236,7 @@ export default class Attribute { } // resolve by node defaults. - const nodeDefaultValue = this.component.node!.nodeDeclaration.defaultAttributesActual.hasMatchingValue(this.name); + const nodeDefaultValue = this.component.node.nodeDeclaration.defaultAttributesActual.hasMatchingValue(this.name); if (nodeDefaultValue !== void 0) { this.Value = nodeDefaultValue; // Node指定値で解決 return; diff --git a/src/Core/AttributeManager.ts b/src/Core/AttributeManager.ts index 601d7e79c..df1bd8ad8 100644 --- a/src/Core/AttributeManager.ts +++ b/src/Core/AttributeManager.ts @@ -3,16 +3,23 @@ import Ensure from "../Tools/Ensure"; import IdResolver from "../Tools/IdResolver"; import { Name, Undef } from "../Tools/Types"; import Utility from "../Tools/Utility"; -import Namespace from "./Namespace"; import Identity from "./Identity"; +import Namespace from "./Namespace"; type NameValPair = { fqn: string, val: T }; - +/** + * Internal use! + */ class AttributeBuffer { private _fqnList: NameValPair[] = []; + /** + * Internal use! + * @param fqn + * @param val + */ public add(fqn: string, val: T) { for (let i = 0; i < this._fqnList.length; i++) { const c = this._fqnList[i]; @@ -27,6 +34,11 @@ class AttributeBuffer { this._fqnList.push(obj); } + /** + * Internal use! + * @param fqn + * @param remove + */ public resolve(fqn: string, remove: boolean): Undef { const guess = this.guess(fqn, remove); return guess.length === 0 ? void 0 : guess[guess.length - 1]; @@ -59,7 +71,6 @@ class AttributeBuffer { type observer = (newValue: any, oldValue: any, attr: Attribute) => void; - /** * internal use! * @return {[type]} [description] @@ -72,6 +83,10 @@ export default class AttributeManager { public constructor(public tag: string) { } + /** + * Internal Use! + * @param attr + */ public addAttribute(attr: Attribute): Attribute { const fqn = attr.name.fqn; if (this._idResolver.has(fqn)) { // already exists @@ -96,6 +111,12 @@ export default class AttributeManager { return attr; } + /** + * Internal Use! + * @param attrName + * @param watcher + * @param immediate + */ public watch(attrName: Name, watcher: ((newValue: any, oldValue: any, attr: Attribute) => void), immediate = false) { const fqn = Ensure.tobeFQN(attrName); if (fqn) { @@ -109,7 +130,7 @@ export default class AttributeManager { } } else { attrName = attrName as string; - let res = this._idResolver.get(Namespace.defineByArray(attrName.split("."))); + const res = this._idResolver.get(Namespace.defineByArray(attrName.split("."))); if (res.length === 0) { this._watchBuffer.add(attrName, watcher); return; @@ -123,6 +144,11 @@ export default class AttributeManager { } } + /** + * Internal Use! + * @param attrFQN + * @param value + */ public setAttribute(attrFQN: string, value: any): void { const attrs = this._attributesFQNMap[attrFQN]; if (attrs === void 0 || attrs.length === 0) { @@ -154,7 +180,7 @@ export default class AttributeManager { return attrs[0]; } else { attrName = attrName as string; - let res = this._idResolver.get(attrName); + const res = this._idResolver.get(attrName); if (res.length === 0) { throw new Error(`attribute ${attrName} is not found.`); } @@ -168,6 +194,10 @@ export default class AttributeManager { } } + /** + * Internal Use! + * @param attrName + */ public getAttribute(attrName: Name): any { const fqn = Ensure.tobeFQN(attrName); if (fqn) { @@ -184,7 +214,7 @@ export default class AttributeManager { return attrs[0].Value; } else { attrName = attrName as string; - let res = this._idResolver.get(attrName); + const res = this._idResolver.get(attrName); if (res.length === 0) { const attrBuf = this._attrBuffer.resolve(attrName, false); if (attrBuf !== void 0) { @@ -198,9 +228,14 @@ export default class AttributeManager { return this._attributesFQNMap[res[0]][0].Value; } } + + /** + * Internal Use! + * @param attr + */ public removeAttribute(attr: Attribute): boolean { if (this._attributesFQNMap[attr.name.fqn]) { - let attributes = this._attributesFQNMap[attr.name.fqn]; + const attributes = this._attributesFQNMap[attr.name.fqn]; if (attributes.length === 1) { this._idResolver.remove(attr.name); } @@ -211,6 +246,10 @@ export default class AttributeManager { return false; } + /** + * Internal Use! + * @param name + */ public guess(name: Name): Identity[] { if (name instanceof Identity) { return [name]; diff --git a/src/Core/Component.ts b/src/Core/Component.ts index f4a59d140..ca16ab6bf 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -1,14 +1,14 @@ +import IDObject from "../Base/IDObject"; +import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; +import Ensure from "../Tools/Ensure"; +import { GomlInterface, Name, Nullable } from "../Tools/Types"; +import Utility from "../Tools/Utility"; import Attribute from "./Attribute"; import Constants from "./Constants"; -import Ensure from "../Tools/Ensure"; import GomlNode from "./GomlNode"; -import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; -import IDObject from "../Base/IDObject"; -import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; -import IdentityMap from "./IdentityMap"; import Identity from "./Identity"; -import Utility from "../Tools/Utility"; -import { GomlInterface, Name, Nullable } from "../Tools/Types"; +import IdentityMap from "./IdentityMap"; /** * Base class for any components @@ -42,6 +42,9 @@ export default class Component extends IDObject { */ public isDefaultComponent = false; + /** + * this component has already disposed. + */ public disposed = false; /** @@ -54,6 +57,10 @@ export default class Component extends IDObject { private _additionalAttributesNames: Identity[] = []; private _initializedInfo: Nullable = null; + /** + * whether component enabled. + * if this component disable, all message is not sended to this component. + */ public get enabled(): boolean { return this._enabled; } @@ -66,6 +73,7 @@ export default class Component extends IDObject { handler(this); }); } + /** * The dictionary which is shared in entire tree. * @return {IdentityMap} [description] @@ -80,6 +88,11 @@ export default class Component extends IDObject { public get tree(): GomlInterface { return this.node.tree; } + + /** + * whether component is active. + * component is active only when it is enabled and the node is active. + */ public get isActive(): boolean { return this.enabled && !!this.node && this.node.isActive; } @@ -91,7 +104,7 @@ export default class Component extends IDObject { */ public setAttribute(name: Name, value: any): void { if (typeof name === "string" && Ensure.checkFQNString(name)) { - name = this.name.fqn + "." + name; // TODO: test + name = `${this.name.fqn}.${name}`; // TODO: test } const attr = this.attributes.get(name); if (attr) { @@ -99,9 +112,13 @@ export default class Component extends IDObject { } } + /** + * get attribute value. + * @param name + */ public getAttribute(name: Name): any { if (typeof name === "string" && Ensure.checkFQNString(name)) { - name = this.name.fqn + "." + name; // TODO: test + name = `${this.name.fqn}.${name}`; // TODO: test } const attr = this.getAttributeRaw(name); if (attr) { @@ -110,58 +127,89 @@ export default class Component extends IDObject { throw new Error(`attribute ${name} is not defined in ${this.name.fqn}`); } } + + /** + * get attribute object instance. + * @param name + */ public getAttributeRaw(name: Name): Attribute { if (typeof name === "string" && Ensure.checkFQNString(name)) { - name = this.name.fqn + "." + name; // TODO: test + name = `${this.name.fqn}.${name}`; // TODO: test } return this.attributes.get(name); } + /** + * add enabled observer. + * @param observer + */ public addEnabledObserver(observer: (component: Component) => void): void { this._handlers.push(observer); } + /** + * remove enabled observer. + * @param observer + */ public removeEnabledObserver(observer: (component: Component) => void): boolean { return Utility.remove(this._handlers, observer); } + /** + * Interal use! + * @param nodeAttributes + */ public resolveDefaultAttributes(nodeAttributes?: { [key: string]: string; } | null): any { const nodeAttr = nodeAttributes || {}; if (this.isDefaultComponent) { // If this is default component, the default attribute values should be retrived from node DOM. - this.attributes.forEach(attr => attr.resolveDefaultValue(nodeAttr)); + this.attributes.forEach(attr => { + attr.resolveDefaultValue(nodeAttr); + }); } else { // If not,the default value of attributes should be retrived from this element. const attrs = Utility.getAttributes(this.element); - for (let key in attrs) { + for (const key in attrs) { if (key === Constants.x_gr_id) { continue; } } - this.attributes.forEach(attr => attr.resolveDefaultValue(attrs)); + this.attributes.forEach(attr => { + attr.resolveDefaultValue(attrs); + }); } } + /** + * Interal use! + */ public dispose(): void { this.node.removeComponent(this); } + /** + * Interal use! + */ public awake(): boolean { if (this._awaked) { return false; } this._awaked = true; - let method = (this as any)["$$awake"]; + const method = (this as any)["$$awake"]; if (typeof method === "function") { method(); } return true; } + /** + * Internal use! + * @param info + */ public initialized(info: ITreeInitializedInfo): void { if (this._initializedInfo === info) { return; } this._initializedInfo = info; - let method = (this as any)["$$initialized"]; + const method = (this as any)["$$initialized"]; if (typeof method === "function") { method(info); } diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index 530c2537a..23f95f760 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -1,26 +1,51 @@ -import Attribute from "./Attribute"; -import Component from "./Component"; -import Constants from "./Constants"; -import Ensure from "../Tools/Ensure"; import Environment from "../Core/Environment"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +import Ensure from "../Tools/Ensure"; import IdResolver from "../Tools/IdResolver"; -import IdentityMap from "./IdentityMap"; -import Identity from "./Identity"; import { ComponentRegistering, Ctor, Name } from "../Tools/Types"; +import Attribute from "./Attribute"; +import Component from "./Component"; +import Constants from "./Constants"; +import Identity from "./Identity"; +import IdentityMap from "./IdentityMap"; - +/** + * Declaration of component. + * manage inherits, dependency resolving. + */ export default class ComponentDeclaration { + + /** + * Internal use! + */ public static ctorMap: { ctor: ComponentRegistering>, name: Identity }[] = []; + /** + * super component constructor. + */ public superComponent: Ctor; + + /** + * generated constructor considering inheritance. + */ public ctor: Ctor; + + /** + * Internal use! + */ public idResolver: IdResolver = new IdResolver(); + + /** + * default attributes. + */ public attributes: { [name: string]: IAttributeDeclaration }; // undefined until resolve dependency. private _resolvedDependency = false; private _super?: Name; + /** + * whether dependencies has already resolved. + */ public get isDependenyResolved() { return this._resolvedDependency; } @@ -40,6 +65,11 @@ export default class ComponentDeclaration { } } + /** + * Internal use! + * generate component instance. + * @param componentElement + */ public generateInstance(componentElement?: Element): Component { // TODO: obsolete.make all operation on gomlnode if (!this.isDependenyResolved) { this.resolveDependency(); @@ -51,12 +81,15 @@ export default class ComponentDeclaration { component.name = this.name; component.element = componentElement; component.attributes = new IdentityMap(); - for (let key in this.attributes) { + for (const key in this.attributes) { Attribute.generateAttributeForComponent(key, this.attributes[key], component); } return component; } + /** + * resolve dependency: inherits and default attributes. + */ public resolveDependency(): boolean { if (this._resolvedDependency) { return false; @@ -67,16 +100,16 @@ export default class ComponentDeclaration { const id = this._super ? Ensure.tobeNSIdentity(this._super) : this.superComponent["name"]; dec = Environment.GrimoireInterface.componentDeclarations.get(id); dec.resolveDependency(); - for (let key in dec.attributes) { + for (const key in dec.attributes) { attr[key] = dec.attributes[key]; - this.idResolver.add(Identity.fromFQN(this.name.fqn + "." + key)); + this.idResolver.add(Identity.fromFQN(`${this.name.fqn}.${key}`)); } this.superComponent = dec.ctor; } - this.ctor = this._ensureTobeComponentConstructor(this.name, this._ctorOrObj, dec ? dec.ctor : void 0); - for (let key in (this.ctor as any).attributes) { + this.ctor = this._ensureTobeComponentConstructor(this.name, this._ctorOrObj, dec ? dec.ctor : undefined); + for (const key in (this.ctor as any).attributes) { attr[key] = (this.ctor as any).attributes[key]; - this.idResolver.add(Identity.fromFQN(this.name.fqn + "." + key)); + this.idResolver.add(Identity.fromFQN(`${this.name.fqn}.${key}`)); } this.attributes = attr; @@ -84,17 +117,21 @@ export default class ComponentDeclaration { return this._resolvedDependency = true; } - /** * Ensure the given object or constructor to be an constructor inherits Component; - * @param {Object | (new ()=> Component} obj [The variable need to be ensured.] - * @return {[type]} [The constructor inherits Component] + * @param id + * @param obj + * @param baseConstructor */ - private _ensureTobeComponentConstructor(id: Identity, obj: ComponentRegistering | ComponentRegistering>, baseConstructor?: Ctor): Ctor { + private _ensureTobeComponentConstructor( + id: Identity, + obj: ComponentRegistering>, + baseConstructor?: Ctor, + ): Ctor { if (typeof obj === "function") { // obj is constructor const inheritsAttr = this._extractInheritsAttributes(obj); if (baseConstructor) { // inherits - const newCtor = function (this: any) { + const newCtor = function(this: any) { baseConstructor.call(this); obj.call(this); }; @@ -113,7 +150,7 @@ export default class ComponentDeclaration { throw new Error("Base component comstructor must extends Compoent class."); } const ctor = baseConstructor || Component; - const newCtor = function (this: any) { + const newCtor = function(this: any) { ctor.call(this); }; (obj as any).__proto__ = ctor.prototype; @@ -138,7 +175,7 @@ export default class ComponentDeclaration { } const atr: D = {}; for (let i = attrs.length - 1; i >= 0; i--) { - for (let key in attrs[i]) { + for (const key in attrs[i]) { atr[key] = attrs[i][key]; } } diff --git a/src/Core/Constants.ts b/src/Core/Constants.ts index d61335202..b7e80d827 100644 --- a/src/Core/Constants.ts +++ b/src/Core/Constants.ts @@ -1,11 +1,24 @@ +/** + * define Constants + */ export default class Constants { + /** + * default namespace + */ public static get defaultNamespace(): string { return "grimoirejs"; } + + /** + * id key for node. + */ public static get x_gr_id(): string { return "x-gr-id"; } + /** + * base node name + */ public static get baseNodeName(): string { return Constants.defaultNamespace + ".grimoire-node-base"; } diff --git a/src/Core/Environment.ts b/src/Core/Environment.ts index 661d56e4a..e635673cb 100644 --- a/src/Core/Environment.ts +++ b/src/Core/Environment.ts @@ -1,10 +1,32 @@ import { GrimoireInterface } from "../Tools/Types"; +/** + * Environment manager + */ export class Environment { + + /** + * global document object + */ public document: Document; + + /** + * Node object. + */ public Node: any; + /** + * DomParser + */ public DomParser: DOMParser; + + /** + * XMLSerializer. + */ public XMLSerializer: XMLSerializer; + + /** + * GrimoireInterface + */ public GrimoireInterface: GrimoireInterface; } diff --git a/src/Core/GomlInterfaceImpl.ts b/src/Core/GomlInterfaceImpl.ts index 20e11ee4f..6209ec0f2 100644 --- a/src/Core/GomlInterfaceImpl.ts +++ b/src/Core/GomlInterfaceImpl.ts @@ -1,12 +1,12 @@ -import Constants from "./Constants"; import GomlNode from "../Core/GomlNode"; import GrimoireInterface from "../Core/GrimoireInterface"; +import Constants from "./Constants"; import NodeInterface from "./NodeInterface"; /** * Provides interfaces to treat whole goml tree for each. */ -export default class GomlInterface { +export default class GomlInterfaceImpl { constructor(public rootNodes: GomlNode[]) { } diff --git a/src/Core/GomlLoader.ts b/src/Core/GomlLoader.ts index f14a15679..9405ff2f2 100644 --- a/src/Core/GomlLoader.ts +++ b/src/Core/GomlLoader.ts @@ -1,15 +1,22 @@ -import Environment from "./Environment"; -import GomlParser from "./GomlParser"; import GrimoireInterface from "../Core/GrimoireInterface"; import XMLHttpRequestAsync from "../Tools/XMLHttpRequestAsync"; import XMLReader from "../Tools/XMLReader"; +import Environment from "./Environment"; +import GomlParser from "./GomlParser"; /** * Provides the features to fetch Goml source. */ export default class GomlLoader { + + /** + * Internal use! + */ public static callInitializedAlready = false; + /** + * Internal use! + */ public static initializedEventHandlers: (() => void)[] = []; /** diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index 960d04f25..98fcafa72 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -1,30 +1,59 @@ -import Attribute from "./Attribute"; -import AttributeManager from "../Core/AttributeManager"; -import Component from "./Component"; -import Constants from "./Constants"; import EEObject from "../Base/EEObject"; -import Ensure from "../Tools/Ensure"; -import Environment from "./Environment"; -import GomlParser from "./GomlParser"; +import AttributeManager from "../Core/AttributeManager"; import GrimoireInterface from "../Core/GrimoireInterface"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; +import Ensure from "../Tools/Ensure"; import MessageException from "../Tools/MessageException"; -import NodeDeclaration from "./NodeDeclaration"; -import IdentityMap from "./IdentityMap"; -import Identity from "./Identity"; -import Utility from "../Tools/Utility"; -import XMLReader from "../Tools/XMLReader"; import { Ctor, GomlInterface, Name, - Nullable + Nullable, } from "../Tools/Types"; +import Utility from "../Tools/Utility"; +import XMLReader from "../Tools/XMLReader"; +import Attribute from "./Attribute"; +import Component from "./Component"; +import Constants from "./Constants"; +import Environment from "./Environment"; +import GomlParser from "./GomlParser"; +import Identity from "./Identity"; +import IdentityMap from "./IdentityMap"; +import NodeDeclaration from "./NodeDeclaration"; +/** + * This class is the most primitive element constitute Tree. + * contain some Component, and send/recieve message to them. + */ export default class GomlNode extends EEObject { + /** + * Get actual goml node from element of xml tree. + * @param {Element} elem [description] + * @return {GomlNode} [description] + */ + public static fromElement(elem: Element): GomlNode { + const id = elem.getAttribute(Constants.x_gr_id); + if (id) { + return GrimoireInterface.nodeDictionary[id]; + } else { + throw new Error("element has not 'x-gr-id'"); + } + } + + /** + * Dom Element + */ public element: Element; // Dom Element + + /** + * declaration infomation. + */ public nodeDeclaration: NodeDeclaration; + + /** + * children nodes. + */ public children: GomlNode[] = []; private _parent: Nullable = null; @@ -41,20 +70,6 @@ export default class GomlNode extends EEObject { private _defaultValueResolved = false; private _initializedInfo: Nullable = null; - /** - * Get actual goml node from element of xml tree. - * @param {Element} elem [description] - * @return {GomlNode} [description] - */ - public static fromElement(elem: Element): GomlNode { - const id = elem.getAttribute(Constants.x_gr_id); - if (id) { - return GrimoireInterface.nodeDictionary[id]; - } else { - throw new Error("element has not 'x-gr-id'"); - } - } - /** * Tag name. */ @@ -214,6 +229,9 @@ export default class GomlNode extends EEObject { return array; } + /** + * remove this node from tree. + */ public remove(): void { this.children.forEach((c) => { c.remove(); @@ -262,7 +280,7 @@ export default class GomlNode extends EEObject { } if (typeof arg1 === "number") { const range = arg1; - const message = Ensure.tobeMessage(arg2); + const message = Ensure.tobeMessage(arg2 as string); const args = arg3; this._broadcastMessage(message, args, range); } else { @@ -272,10 +290,14 @@ export default class GomlNode extends EEObject { } } + /** + * add child node. + * @param tag + */ public append(tag: string): GomlNode[] { const elem = XMLReader.parseXML(tag); - let ret: GomlNode[] = []; - let child = GomlParser.parse(elem); + const ret: GomlNode[] = []; + const child = GomlParser.parse(elem); this.addChild(child); ret.push(child); return ret; @@ -290,7 +312,7 @@ export default class GomlNode extends EEObject { const nodeDec = GrimoireInterface.nodeDeclarations.get(nodeName); const node = new GomlNode(nodeDec); if (attributes) { - for (let key in attributes) { + for (const key in attributes) { node.setAttribute(key, attributes[key]); } } @@ -321,7 +343,7 @@ export default class GomlNode extends EEObject { // sync html if (elementSync) { - let referenceElement = (this.element as any)[Utility.getNodeListIndexByElementIndex(this.element, insertIndex)]; + const referenceElement = (this.element as any)[Utility.getNodeListIndexByElementIndex(this.element, insertIndex)]; this.element.insertBefore(child.element, referenceElement); } @@ -336,7 +358,10 @@ export default class GomlNode extends EEObject { } } - + /** + * Internal use! + * @param func + */ public callRecursively(func: (g: GomlNode) => T): T[] { return this._callRecursively(func, (n) => n.children); } @@ -385,21 +410,35 @@ export default class GomlNode extends EEObject { } } + /** + * get attribute value. + * @param attrName + */ public getAttribute(attrName: Name): any { return this._attributeManager.getAttribute(attrName); } + /** + * get attribute object instance. + * @param attrName + */ public getAttributeRaw(attrName: Name): Attribute { return this._attributeManager.getAttributeRaw(attrName); } + /** + * set attribute value + * @param attrName + * @param value + * @param ignoireFreeze set value ignorering attribute freeze. + */ public setAttribute(attrName: Name, value: any, ignoireFreeze = false): void { - let attrIds = this._attributeManager.guess(attrName); + const attrIds = this._attributeManager.guess(attrName); if (attrIds.length === 0) { // such attribute is not exists. set to Attribute buffer. this._attributeManager.setAttribute(typeof attrName === "string" ? attrName : attrName.fqn, value); } for (let i = 0; i < attrIds.length; i++) { - let id = attrIds[i]; + const id = attrIds[i]; if (!ignoireFreeze && this.isFreezeAttribute(id.fqn)) { throw new Error(`attribute ${id.fqn} can not set. Attribute is frozen. `); } @@ -442,7 +481,6 @@ export default class GomlNode extends EEObject { } } - /** * Get index of this node from parent. * @return {number} number of index. @@ -475,7 +513,7 @@ export default class GomlNode extends EEObject { const instance = declaration.generateInstance(); attributes = attributes || {}; - for (let key in attributes) { + for (const key in attributes) { instance.setAttribute(key, attributes[key]); } this._addComponentDirectly(instance, isDefaultComponent); @@ -506,8 +544,8 @@ export default class GomlNode extends EEObject { propNames = propNames.concat(Object.getOwnPropertyNames(o)); o = Object.getPrototypeOf(o); } - propNames.filter(name => name.startsWith("$") && typeof (component)[name] === "function").forEach(method => { - (component)["$" + method] = (component)[method].bind(component); + propNames.filter(name => name.startsWith("$") && typeof (component as any)[name] === "function").forEach(method => { + (component as any)["$" + method] = (component as any)[method].bind(component); }); this._components.push(component); @@ -515,7 +553,9 @@ export default class GomlNode extends EEObject { // attributes should be exposed on node component.attributes.forEach(p => this.addAttribute(p)); if (this._defaultValueResolved) { - component.attributes.forEach(p => p.resolveDefaultValue(Utility.getAttributes(this.element))); + component.attributes.forEach(p => { + p.resolveDefaultValue(Utility.getAttributes(this.element)); + }); } if (this._mounted) { @@ -530,6 +570,11 @@ export default class GomlNode extends EEObject { } } + /** + * remove all component if exists. + * @param component + * @return remove one or more components. + */ public removeComponents(component: Name | (new () => Component)): boolean { let result = false; const removeTargets = []; @@ -541,12 +586,17 @@ export default class GomlNode extends EEObject { } } removeTargets.forEach(c => { - let b = this.removeComponent(c); + const b = this.removeComponent(c); result = result || b; }); return result; } + /** + * remove component if exists. + * @param component + * @return success or not. + */ public removeComponent(component: Component): boolean { const index = this._components.indexOf(component); if (index !== -1) { @@ -562,6 +612,10 @@ export default class GomlNode extends EEObject { return false; } + /** + * get components + * @param filter + */ public getComponents(filter?: Name | Ctor): T[] { if (!filter) { return this._components as any as T[]; @@ -596,6 +650,10 @@ export default class GomlNode extends EEObject { } } + /** + * get all components for chilcren recursively. + * @param name + */ public getComponentsInChildren(name: Name | Ctor): T[] { if (name == null) { throw new Error("getComponentsInChildren recieve null or undefined"); @@ -620,22 +678,25 @@ export default class GomlNode extends EEObject { return null; } + /** + * Internal use! + * @param info + */ public sendInitializedMessage(info: ITreeInitializedInfo) { if (this._initializedInfo === info) { return; } - let components = this._components.concat(); // copy + const components = this._components.concat(); // copy for (let i = 0; i < components.length; i++) { components[i].initialized(info); } this._initializedInfo = info; - let children = this.children.concat(); + const children = this.children.concat(); children.forEach(child => { child.sendInitializedMessage(info); }); } - /** * resolve default attribute value for all component. * すべてのコンポーネントの属性をエレメントかデフォルト値で初期化 @@ -643,7 +704,7 @@ export default class GomlNode extends EEObject { public resolveAttributesValue(): void { this._defaultValueResolved = true; const attrs = Utility.getAttributes(this.element); - for (let key in attrs) { + for (const key in attrs) { if (key === Constants.x_gr_id) { continue; } @@ -656,10 +717,18 @@ export default class GomlNode extends EEObject { }); } + /** + * whether provided name is freeze attribute. + * @param attributeName + */ public isFreezeAttribute(attributeName: string): boolean { return !!this.nodeDeclaration.freezeAttributes.toArray().find(name => attributeName === name.fqn); } + /** + * Internal use! + * @param activeness + */ public notifyActivenessUpdate(activeness: boolean): void { if (this.isActive !== activeness) { this._isActive = activeness; @@ -669,17 +738,26 @@ export default class GomlNode extends EEObject { } } + /** + * watch attribute. + * @param attrName + * @param watcher + * @param immediate + */ public watch(attrName: Name, watcher: ((newValue: any, oldValue: any, attr: Attribute) => void), immediate = false) { this._attributeManager.watch(attrName, watcher, immediate); } + /** + * to string + */ public toString(): string { let name = this.name.fqn; - let id = this.getAttribute("id"); + const id = this.getAttribute("id"); if (id !== null) { name += ` id: ${id}`; } - let classValue = this.getAttribute("class"); + const classValue = this.getAttribute("class"); if (classValue !== null) { name += ` class: ${classValue}`; } @@ -692,7 +770,10 @@ export default class GomlNode extends EEObject { */ public toStructualString(message = ""): string { if (this.parent) { - return "\n" + this.parent._openTreeString() + this._currentSiblingsString(this._layer * 2, `<${this.toString()}/>`, true, message) + this.parent._closeTreeString(); + const open = this.parent._openTreeString(); + const content = this._currentSiblingsString(this._layer * 2, `<${this.toString()}/>`, true, message); + const close = this.parent._closeTreeString(); + return `\n${open}${content} ${close}}`; } else { return "\n" + this._currentSiblingsString(0, `<${this.toString()}/>`, true, message); } @@ -757,7 +838,7 @@ export default class GomlNode extends EEObject { emphasisStr += "^"; } } - let targets: string[] = []; + const targets: string[] = []; if (!this.parent) { targets.push(`${spaces}${current}`); if (emphasis) { @@ -812,8 +893,6 @@ export default class GomlNode extends EEObject { } } - - private _getComponentInAncestor(name: Name | (new () => T)): Nullable { const ret = this.getComponent(name); if (ret) { @@ -838,7 +917,7 @@ export default class GomlNode extends EEObject { if (!targetComponent.enabled) { return false; } - let method = (targetComponent as any)[message]; + const method = (targetComponent as any)[message]; if (typeof method === "function") { try { method(args); @@ -858,9 +937,9 @@ export default class GomlNode extends EEObject { } private _sendMessageForced(message: string): void { - let componentsBuffer = this._components.concat(); + const componentsBuffer = this._components.concat(); for (let i = 0; i < componentsBuffer.length; i++) { - let target = componentsBuffer[i]; + const target = componentsBuffer[i]; if (target.disposed) { continue; } @@ -875,7 +954,7 @@ export default class GomlNode extends EEObject { */ private _sendMessageForcedTo(target: Component, message: string): void { message = Ensure.tobeMessage(message); - let method = (target as any)[message]; + const method = (target as any)[message]; if (typeof method === "function") { method(); } @@ -886,9 +965,9 @@ export default class GomlNode extends EEObject { */ private _mount(): void { this._mounted = true; - let componentsBuffer = this._components.concat(); + const componentsBuffer = this._components.concat(); for (let i = 0; i < componentsBuffer.length; i++) { - let target = componentsBuffer[i]; + const target = componentsBuffer[i]; if (target.disposed) { continue; } diff --git a/src/Core/GomlParser.ts b/src/Core/GomlParser.ts index 6fb1d58a7..c33947b50 100644 --- a/src/Core/GomlParser.ts +++ b/src/Core/GomlParser.ts @@ -1,6 +1,6 @@ +import GrimoireInterface from "../Core/GrimoireInterface"; import Environment from "./Environment"; import GomlNode from "./GomlNode"; -import GrimoireInterface from "../Core/GrimoireInterface"; /** * Parser of Goml to Node utilities. @@ -74,7 +74,7 @@ class GomlParser { * @param {Element} componentsTag .COMPONENTSタグ */ private static _parseComponents(node: GomlNode, componentsTag: Element): void { - let componentNodes = componentsTag.childNodes; + const componentNodes = componentsTag.childNodes; if (!componentNodes) { return; } diff --git a/src/Core/GrimoireInterface.ts b/src/Core/GrimoireInterface.ts index 248260eff..bbef2d31d 100644 --- a/src/Core/GrimoireInterface.ts +++ b/src/Core/GrimoireInterface.ts @@ -1,9 +1,8 @@ +import GomlNode from "../Core/GomlNode"; +import { GomlInterface, GrimoireInterface } from "../Tools/Types"; import Environment from "./Environment"; import GomlInterfaceImpl from "./GomlInterfaceImpl"; -import GomlNode from "../Core/GomlNode"; import GrimoireInterfaceImpl from "./GrimoireInterfaceImpl"; -import { GomlInterface, GrimoireInterface } from "../Tools/Types"; - const context = new GrimoireInterfaceImpl(); diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 66bd1f47d..0c0c888cc 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -1,61 +1,94 @@ +import EEObject from "../Base/EEObject"; +import GrimoireComponent from "../Components/GrimoireComponent"; import ArrayConverter from "../Converters/ArrayConverter"; -import Attribute from "./Attribute"; import BooleanConverter from "../Converters/BooleanConverter"; -import Component from "../Core/Component"; import ComponentConverter from "../Converters/ComponentConverter"; -import ComponentDeclaration from "../Core/ComponentDeclaration"; -import Constants from "./Constants"; -import EEObject from "../Base/EEObject"; -import Ensure from "../Tools/Ensure"; import EnumConverter from "../Converters/EnumConverter"; -import Environment from "./Environment"; -import GomlInterfaceImpl from "../Core/GomlInterfaceImpl"; -import GomlLoader from "../Core/GomlLoader"; -import GomlNode from "../Core/GomlNode"; -import GrimoireComponent from "../Components/GrimoireComponent"; -import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; -import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; -import Namespace from "../Core/Namespace"; -import NodeDeclaration from "../Core/NodeDeclaration"; -import NodeInterface from "./NodeInterface"; -import IdentityMap from "./IdentityMap"; -import Identity from "./Identity"; import NumberArrayConverter from "../Converters/NumberArrayConverter"; import NumberConverter from "../Converters/NumberConverter"; import ObjectConverter from "../Converters/ObjectConverter"; import StringArrayConverter from "../Converters/StringArrayConverter"; import StringConverter from "../Converters/StringConverter"; -import Utility from "../Tools/Utility"; +import Component from "../Core/Component"; +import ComponentDeclaration from "../Core/ComponentDeclaration"; +import GomlInterfaceImpl from "../Core/GomlInterfaceImpl"; +import GomlLoader from "../Core/GomlLoader"; +import GomlNode from "../Core/GomlNode"; +import Namespace from "../Core/Namespace"; +import NodeDeclaration from "../Core/NodeDeclaration"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; +import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; +import Ensure from "../Tools/Ensure"; import { ComponentRegistering, Ctor, Name, - Nullable + Nullable, } from "../Tools/Types"; +import Utility from "../Tools/Utility"; +import Attribute from "./Attribute"; +import Constants from "./Constants"; +import Environment from "./Environment"; +import Identity from "./Identity"; +import IdentityMap from "./IdentityMap"; +import NodeInterface from "./NodeInterface"; - +/** + * implementation of GrimoireInterface + */ export default class GrimoireInterfaceImpl extends EEObject { + /** + * manage all node declarations. + */ public nodeDeclarations: IdentityMap = new IdentityMap(); + /** + * manage all converters + */ public converters: IdentityMap = new IdentityMap(); + /** + * manage all component declaration. + */ public componentDeclarations: IdentityMap = new IdentityMap(); + /** + * map rootNodeId to node. + */ public rootNodes: { [rootNodeId: string]: GomlNode } = {}; - public loadTasks: ({ ns: string, task: () => Promise })[] = []; + /** + * manage all loadtasks. + */ + public loadTasks: ({ ns: string, task(): Promise })[] = []; + /** + * this property is version infomation for logging + */ public lib: { [key: string]: { __VERSION__: string; __NAME__: string; [key: string]: any; - } + }, } = {}; + /** + * manage all node in this context + */ public nodeDictionary: { [nodeId: string]: GomlNode } = {}; + + /** + * manage all components in this context + */ public componentDictionary: { [componentId: string]: Component } = {}; + + /** + * debug-mode. + * if this property is true, some error/worning message will output to console. + * please disable this flag when you publish product application. + */ public debug = true; /** @@ -73,10 +106,16 @@ export default class GrimoireInterfaceImpl extends EEObject { private _registeringPluginNamespace: string; private _registrationContext: string = Constants.defaultNamespace; + /** + * initialized event handlers + */ public get initializedEventHandler(): ((scriptTags: HTMLScriptElement[]) => void)[] { return GomlLoader.initializedEventHandlers; } + /** + * whether already initialized. + */ public get callInitializedAlready(): boolean { return GomlLoader.callInitializedAlready; } @@ -92,6 +131,11 @@ export default class GrimoireInterfaceImpl extends EEObject { return (name: string) => Namespace.define(ns).for(name); } + /** + * initialize GrimoireInterface. + * register primitive coverters/nodes. + * if you want reset state. use GrimoireInterface.clear() instead of. + */ public initialize(): void { this.registerConverter("String", StringConverter); this.registerConverter("StringArray", StringArrayConverter); @@ -116,6 +160,9 @@ export default class GrimoireInterfaceImpl extends EEObject { this._registeringPluginNamespace = Constants.defaultNamespace; } + /** + * call all plugin register functions. + */ public async resolvePlugins(): Promise { for (let i = 0; i < this.loadTasks.length; i++) { const obj = this.loadTasks[i]; @@ -152,12 +199,12 @@ export default class GrimoireInterfaceImpl extends EEObject { let obj: ComponentRegistering>; let superComponent: Name | Ctor | undefined; if (typeof arg1 === "string" || arg1 instanceof Identity) { - Utility.w(` registerComponent() overload that call with name is deprecated. use other overload instead of.`); + Utility.w(" registerComponent() overload that call with name is deprecated. use other overload instead of."); name = arg1; obj = arg2 as ComponentRegistering>; superComponent = arg3; } else { - obj = arg1 as ComponentRegistering>; + obj = arg1; superComponent = arg2 as Name | Ctor; if (obj.componentName == null) { throw new Error(`registering component has not 'componentName': ${obj}`); @@ -180,7 +227,7 @@ export default class GrimoireInterfaceImpl extends EEObject { if (!attrs) { throw new Error("component must has 'attributes'"); } - for (let key in attrs) { + for (const key in attrs) { if (attrs[key].default === void 0) { throw new Error(`default value of attribute ${key} in ${name.fqn} must be not 'undefined'.`); } @@ -191,6 +238,15 @@ export default class GrimoireInterfaceImpl extends EEObject { return dec; } + /** + * register new node to context. + * throw error if already registerd. + * @param name + * @param requiredComponents + * @param defaults + * @param superNode + * @param freezeAttributes + */ public registerNode( name: Name, requiredComponents: Name[] = [], @@ -210,6 +266,11 @@ export default class GrimoireInterfaceImpl extends EEObject { this.nodeDeclarations.set(registerId, declaration); return declaration; } + + /** + * get companion object from Element. + * @param scriptTag + */ public getCompanion(scriptTag: Element): IdentityMap { const root = this.getRootNode(scriptTag); if (root) { @@ -236,28 +297,33 @@ export default class GrimoireInterfaceImpl extends EEObject { // awake and mount tree. rootNode.setMounted(true); - rootNode.broadcastMessage("treeInitialized", { + rootNode.broadcastMessage("treeInitialized", { ownerScriptTag: tag, - id: rootNode.id - }); - rootNode.sendInitializedMessage({ + id: rootNode.id, + } as ITreeInitializedInfo); + rootNode.sendInitializedMessage({ ownerScriptTag: tag, - id: rootNode.id - }); + id: rootNode.id, + } as ITreeInitializedInfo); // send events to catch root node appended this.emit("root-node-added", { ownerScriptTag: tag, - rootNode: rootNode + rootNode, }); return rootNode.id; } + /** + * get root node with script-tag element. + * return null if not exist. + * @param scriptTag + */ public getRootNode(scriptTag: Element): Nullable { const id = scriptTag.getAttribute("x-rootNodeId"); if (id) { - let ret = this.rootNodes[id]; + const ret = this.rootNodes[id]; if (!ret) { - throw new Error(`threr is no rootNode has id ${id}`); + throw new Error(`threr is no rootNode has id ${id}`); // TODO } return ret; } else { @@ -265,10 +331,17 @@ export default class GrimoireInterfaceImpl extends EEObject { } } + /** + * restore global 'gr' variable by original value. + */ public noConflict(): void { (window as any)["gr"] = this.noConflictPreserve; } + /** + * Internal use! + * @param query + */ public queryRootNodes(query: string): GomlNode[] { const scriptTags = Environment.document.querySelectorAll(query); const nodes: GomlNode[] = []; @@ -281,6 +354,12 @@ export default class GrimoireInterfaceImpl extends EEObject { return nodes; } + /** + * register converter to GrimoireInterface. + * converter must be function or IAttributeConverterDeclaration. + * @param name + * @param converter + */ public registerConverter(name: Name, converter: ((val: any, attr: Attribute) => any)): void; public registerConverter(declaration: IAttributeConverterDeclaration): void; public registerConverter(arg1: Name | IAttributeConverterDeclaration, converter?: ((val: any, attr: Attribute) => any)): void { @@ -288,7 +367,7 @@ export default class GrimoireInterfaceImpl extends EEObject { this.registerConverter({ name: this._ensureTobeNSIdentityOnRegister(arg1 as Name), verify: () => true, - convert: converter + convert: converter, }); return; } @@ -296,6 +375,12 @@ export default class GrimoireInterfaceImpl extends EEObject { this.converters.set(this._ensureTobeNSIdentityOnRegister(dec.name), dec); } + /** + * override node declaration. + * you can add default component or change default attributes. + * @param targetDeclaration + * @param additionalComponents + */ public overrideDeclaration(targetDeclaration: Name, additionalComponents: Name[]): NodeDeclaration; public overrideDeclaration(targetDeclaration: Name, defaults: { [attrName: string]: any }): NodeDeclaration; public overrideDeclaration(targetDeclaration: Name, additionalComponents: Name[], defaults: { [attrName: string]: any }): NodeDeclaration; @@ -312,19 +397,17 @@ export default class GrimoireInterfaceImpl extends EEObject { for (let i = 0; i < additionalC.length; i++) { dec.addDefaultComponent(additionalC[i]); } - dec.defaultAttributes.pushDictionary(Ensure.tobeNSDictionary(defaults)); + dec.defaultAttributes.pushDictionary(Ensure.tobeIdentityMap(defaults)); } else if (Array.isArray(arg2)) { // only additiona components. for (let i = 0; i < arg2.length; i++) { dec.addDefaultComponent(arg2[i]); } } else { - dec.defaultAttributes.pushDictionary(Ensure.tobeNSDictionary(arg2)); + dec.defaultAttributes.pushDictionary(Ensure.tobeIdentityMap(arg2)); } return dec; } - - /** * This method is not for users. * Just for unit testing. @@ -335,13 +418,13 @@ export default class GrimoireInterfaceImpl extends EEObject { this.nodeDeclarations.clear(); this.componentDeclarations.clear(); this.converters.clear(); - for (let key in this.rootNodes) { + for (const key in this.rootNodes) { delete this.rootNodes[key]; } - for (let key in this.nodeDictionary) { + for (const key in this.nodeDictionary) { delete this.nodeDictionary[key]; } - for (let key in this.componentDictionary) { + for (const key in this.componentDictionary) { delete this.componentDictionary[key]; } this.loadTasks.splice(0, this.loadTasks.length); @@ -349,18 +432,38 @@ export default class GrimoireInterfaceImpl extends EEObject { this.initialize(); } + /** + * add method to GrimoireInterface. + * throw error if name has already exists. + * @param name + * @param func + */ public extendGrimoireInterface(name: string, func: Function): void { if ((this as any)[name]) { throw new Error(`gr.${name} can not extend.it is already exist.`); } (this as any)[name] = func.bind(this); } + + /** + * add method to GomlInterface. + * throw error if name has already exists. + * @param name + * @param func + */ public extendGomlInterface(name: string, func: Function): void { if ((GomlInterfaceImpl as any)[name]) { throw new Error(`gr.${name} can not extend.it is already exist.`); } (GomlInterfaceImpl as any)[name] = func.bind(this); } + + /** + * add method to NodeInterface. + * throw error if name has already exists. + * @param name + * @param func + */ public extendNodeInterface(name: string, func: Function): void { if ((NodeInterface as any)[name]) { throw new Error(`gr.${name} can not extend.it is already exist.`); @@ -374,7 +477,7 @@ export default class GrimoireInterfaceImpl extends EEObject { * @param {string} namespace namespace of plugin to be ragister. */ public notifyRegisteringPlugin(namespace: string): void { - let res = /^[Gg]rimoire(?:js|JS)?-(.*)$/.exec(namespace); + const res = /^[Gg]rimoire(?:js|JS)?-(.*)$/.exec(namespace); if (res) { namespace = res[1]; } @@ -392,7 +495,7 @@ export default class GrimoireInterfaceImpl extends EEObject { return this._ensureNameTobeConstructor(Ensure.tobeNSIdentity(component)); } else { // here NSIdentity. - let c = this.componentDeclarations.get(component); + const c = this.componentDeclarations.get(component); if (!c) { return null; } diff --git a/src/Core/Identity.ts b/src/Core/Identity.ts index 81a2701bd..4cd9495a0 100644 --- a/src/Core/Identity.ts +++ b/src/Core/Identity.ts @@ -1,6 +1,6 @@ -import Namespace from "./Namespace"; -import IdResolver from "../Tools/IdResolver"; import Ensure from "../Tools/Ensure"; +import IdResolver from "../Tools/IdResolver"; +import Namespace from "./Namespace"; /** * The class to identity with XML namespace feature. @@ -9,16 +9,6 @@ export default class Identity { private static _instances: { [fqn: string]: Identity } = {}; private static _mapBackingField: IdResolver; - private static get _map(): IdResolver { - if (this._mapBackingField === void 0) { - this._mapBackingField = new IdResolver(); - } - return this._mapBackingField; - } - - private _ns: Namespace; - private _name: string; - private _fqn: string; /** * Generate an instance from Full qualified name. @@ -34,15 +24,29 @@ export default class Identity { return new Identity(splitted); } + /** + * guess FQN from name + * @param hierarchy + */ public static guess(...hierarchy: string[]): Identity { return Identity._guess(hierarchy); } + /** + * clear context. + */ public static clear(): void { Identity._instances = {}; Identity._mapBackingField = new IdResolver(); } + private static get _map(): IdResolver { + if (this._mapBackingField === void 0) { + this._mapBackingField = new IdResolver(); + } + return this._mapBackingField; + } + /** * return instance if exists. * generate and return new instanse if not exist id has same fqn. @@ -59,6 +63,10 @@ export default class Identity { return Identity.fromFQN(Identity._map.resolve(Namespace.defineByArray(hierarchy))); } + private _ns: Namespace; + private _name: string; + private _fqn: string; + public constructor(fqn: string | string[]); public constructor(qn: string[], n: string); public constructor(qn: string | string[], n?: string) { @@ -105,17 +113,25 @@ export default class Identity { return this._fqn; } + /** + * whether this identity fqn is match provided name. + * TODO: put url to document here + * @param name this + */ public isMatch(name: string): boolean { if (Ensure.checkFQNString(name)) { return this._fqn === Ensure.tobeFQN(name); } else { - let resolver = new IdResolver(); + const resolver = new IdResolver(); resolver.add(this); - let get = resolver.get(name); + const get = resolver.get(name); return get.length === 1; } } + /** + * return fqn + */ public toString(): string { return this.fqn; } diff --git a/src/Core/IdentityMap.ts b/src/Core/IdentityMap.ts index 8ca38ed1d..2075d39aa 100644 --- a/src/Core/IdentityMap.ts +++ b/src/Core/IdentityMap.ts @@ -1,21 +1,34 @@ -import Identity from "./Identity"; -import IdResolver from "../Tools/IdResolver"; import Namespace from "../Core/Namespace"; import Ensure from "../Tools/Ensure"; +import IdResolver from "../Tools/IdResolver"; import { Name, Nullable, Undef } from "../Tools/Types"; +import Identity from "./Identity"; type Dict = { [key: string]: V }; +/** + * map identity to value. + */ export default class IdentityMap { private _fqnObjectMap: Dict = {}; private _idResolver: IdResolver = new IdResolver(); + /** + * set value for provided key. + * @param key + * @param value + */ public set(key: Identity, value: V): void { this._fqnObjectMap[key.fqn] = value; this._idResolver.add(key); } + /** + * delete provided key value if exists. + * @param key + * @return success or not + */ public delete(key: Identity): boolean { if (this._fqnObjectMap[key.fqn] !== void 0) { delete this._fqnObjectMap[key.fqn]; @@ -25,6 +38,12 @@ export default class IdentityMap { return false; } + /** + * get value by key. + * throw error if provided key is null or udefined. + * return null if key is not exists. + * @param name + */ public get(name: Name): V; public get(element: Element): V; public get(attribute: Attr): V; @@ -54,7 +73,7 @@ export default class IdentityMap { return this._fqnObjectMap[arg1.fqn]; } else { if (arg1.namespaceURI) { - return this.get(arg1.namespaceURI + "." + arg1.localName!); + return this.get(`${arg1.namespaceURI}.${arg1.localName!}`); } return this.get(arg1.localName!); } @@ -70,24 +89,38 @@ export default class IdentityMap { return this._idResolver.get(Namespace.defineByArray(name.split("."))).length > 1; } + /** + * check key is exists in this map. + * @param name + */ public has(name: string): boolean { return this._idResolver.get(Namespace.defineByArray(name.split("."))).length !== 0; } - public pushDictionary(dict: IdentityMap): IdentityMap { - dict.forEach((value, keyFQN) => { + /** + * add all value to this map. + * @param map + */ + public pushDictionary(map: IdentityMap): IdentityMap { + map.forEach((value, keyFQN) => { const id = Identity.fromFQN(keyFQN); this.set(id, value); }); return this; } + /** + * return value if exists key that match provided name. + * throw error if multiple key match provided name. + * return undefined if no key matched. + * @param name + */ public hasMatchingValue(name: Identity): Undef { const resolver = new IdResolver(); resolver.add(name); let match: string | undefined = void 0; - for (let key in this._fqnObjectMap) { - let v = resolver.get(Namespace.defineByArray(key.split("."))); + for (const key in this._fqnObjectMap) { + const v = resolver.get(Namespace.defineByArray(key.split("."))); if (v.length === 1) { if (match === void 0) { match = key; @@ -102,6 +135,9 @@ export default class IdentityMap { return void 0; } + /** + * convert to array. + */ public toArray(): V[] { const ret: V[] = []; Object.keys(this._fqnObjectMap).forEach(key => { @@ -109,16 +145,30 @@ export default class IdentityMap { }); return ret; } + + /** + * create clone IdentityMap. + */ public clone(): IdentityMap { const dict = new IdentityMap(); return dict.pushDictionary(this); } + + /** + * call function for each key value pair. + * @param callback + */ public forEach(callback: (value: V, fqn: string) => void): IdentityMap { Object.keys(this._fqnObjectMap).forEach(key => { callback(this._fqnObjectMap[key], key); }); return this; } + + /** + * create new IdentityMap with mapped values. + * @param callback + */ public map(callback: ((value: V, fqn: string) => T)): IdentityMap { const ret = new IdentityMap(); this.forEach((val, fqn) => { @@ -127,6 +177,10 @@ export default class IdentityMap { }); return ret; } + + /** + * clear all value. + */ public clear(): void { this._fqnObjectMap = {}; this._idResolver = new IdResolver(); diff --git a/src/Core/IdentitySet.ts b/src/Core/IdentitySet.ts index e26f0e045..fe6ea5045 100644 --- a/src/Core/IdentitySet.ts +++ b/src/Core/IdentitySet.ts @@ -6,14 +6,17 @@ import Identity from "./Identity"; * @return {IdentitySet} [description] */ export default class IdentitySet { - private _content: { [fqn: string]: Identity } = {}; + /** + * create new set from array + * @param array + */ public static fromArray(array: Identity[]): IdentitySet { const nSet = new IdentitySet(); nSet.pushArray(array); return nSet; } - + private _content: { [fqn: string]: Identity } = {}; constructor(content?: Identity[]) { if (content) { @@ -21,6 +24,11 @@ export default class IdentitySet { } } + /** + * add new identity to this set. + * @param item + * @return success or not + */ public push(item: Identity): boolean { if (!this._content[item.fqn]) { this._content[item.fqn] = item; @@ -29,6 +37,10 @@ export default class IdentitySet { return false; } + /** + * add new identities to this set + * @param item + */ public pushArray(item: Identity[]): IdentitySet { item.forEach(v => { this.push(v); @@ -36,29 +48,43 @@ export default class IdentitySet { return this; } + /** + * convert to array + */ public toArray(): Identity[] { const ret: Identity[] = []; - for (let key in this._content) { + for (const key in this._content) { ret.push(this._content[key]); } return ret; } + /** + * create clone set. + */ public clone(): IdentitySet { const newSet = new IdentitySet(); - for (let key in this._content) { + for (const key in this._content) { newSet.push(this._content[key]); } return newSet; } + /** + * add all contents of other set to this set. + * @param other + */ public merge(other: IdentitySet): IdentitySet { this.pushArray(other.toArray()); return this; } + /** + * call function foreach identity contained this set. + * @param func + */ public forEach(func: (name: Identity) => void): IdentitySet { - for (let key in this._content) { + for (const key in this._content) { func(this._content[key]); } return this; diff --git a/src/Core/Namespace.ts b/src/Core/Namespace.ts index e04189eb1..636537cc1 100644 --- a/src/Core/Namespace.ts +++ b/src/Core/Namespace.ts @@ -1,10 +1,11 @@ -import Identity from "./Identity"; import Utility from "../Tools/Utility"; +import Identity from "./Identity"; +/** + * Namespace is tail of FQN. + */ export default class Namespace { - private _ns: string[]; - /** * create new Namespace instance. * You can include dots in the name @@ -15,9 +16,18 @@ export default class Namespace { return Namespace.defineByArray(name); } + /** + * create new Namespace instance. + * @param name + */ public static defineByArray(name: string[]): Namespace { return new Namespace(Utility.flat(name.map(n => n.split(".").filter(s => s !== "")))); } + private _ns: string[]; + + private constructor(names: string[]) { + this._ns = names; + } /** * Represents a namespace hierarchy as string array. @@ -42,7 +52,7 @@ export default class Namespace { throw new Error("Namespace can not extend with null"); } - let split = extension.split(".").filter(s => s !== ""); + const split = extension.split(".").filter(s => s !== ""); if (split.length === 1 && extension === "") { return new Namespace(this._ns); } @@ -61,11 +71,10 @@ export default class Namespace { return Identity.fromFQN(fqn); } + /** + * to string + */ public toString(): string { return this.qualifiedName; } - - private constructor(names: string[]) { - this._ns = names; - } } diff --git a/src/Core/NodeDeclaration.ts b/src/Core/NodeDeclaration.ts index 4db7dc3f4..08de0dc7f 100644 --- a/src/Core/NodeDeclaration.ts +++ b/src/Core/NodeDeclaration.ts @@ -1,28 +1,59 @@ +import GrimoireInterface from "../Core/GrimoireInterface"; import Ensure from "../Tools/Ensure"; -import IdentityMap from "./IdentityMap"; -import IdentitySet from "./IdentitySet"; -import Identity from "./Identity"; import IdResolver from "../Tools/IdResolver"; -import GrimoireInterface from "../Core/GrimoireInterface"; -import Constants from "./Constants"; import { Name } from "../Tools/Types"; +import Constants from "./Constants"; +import Identity from "./Identity"; +import IdentityMap from "./IdentityMap"; +import IdentitySet from "./IdentitySet"; +/** + * node declaration for create GomlNode Instance. + */ export default class NodeDeclaration { + + /** + * Components attached to this node by default. + * this property is not consider inheritance. + */ public defaultComponents: IdentitySet; + + /** + * attributes set to this node by default. + * this property is not consider inheritance. + */ public defaultAttributes: IdentityMap = new IdentityMap(); + + /** + * super node id if exists. + * undefined if this node is not inherits any node. + */ public superNode?: Identity; + + /** + * identity set of freeze attributes. + */ public freezeAttributes: IdentitySet; + + /** + * Internal use! + */ public idResolver = new IdResolver(); private _defaultComponentsActual: IdentitySet; private _defaultAttributesActual: IdentityMap; private _resolvedDependency = false; - + /** + * Whether the dependency has already been resolved. + */ public get resolvedDependency() { return this._resolvedDependency; } + /** + * get default components with inheritance in mind. + */ public get defaultComponentsActual(): IdentitySet { if (!this._resolvedDependency) { throw new Error(`${this.name.fqn} is not resolved dependency!`); @@ -30,6 +61,9 @@ export default class NodeDeclaration { return this._defaultComponentsActual; } + /** + * get default attributes with inheritance in mind. + */ public get defaultAttributesActual(): IdentityMap { if (!this._resolvedDependency) { throw new Error(`${this.name.fqn} is not resolved dependency!`); @@ -49,6 +83,10 @@ export default class NodeDeclaration { this._freezeAttributes = this._freezeAttributes || []; } + /** + * add optional default component. + * @param componentName + */ public addDefaultComponent(componentName: Name): void { const componentId = Ensure.tobeNSIdentity(componentName); this.defaultComponents.push(componentId); @@ -68,8 +106,8 @@ export default class NodeDeclaration { } this.defaultComponents = new IdentitySet(this._defaultComponents.map(name => Ensure.tobeNSIdentity(name))); - for (let key in this._defaultAttributes) { - let value = this._defaultAttributes[key]; + for (const key in this._defaultAttributes) { + const value = this._defaultAttributes[key]; this.defaultAttributes.set(Identity.fromFQN(key), value); } this.superNode = this._superNode ? Ensure.tobeNSIdentity(this._superNode) : void 0; @@ -85,7 +123,6 @@ export default class NodeDeclaration { return true; } - private _resolveInherites(): void { if (!this.superNode) { // not inherit. this._defaultComponentsActual = this.defaultComponents; diff --git a/src/Core/NodeInterface.ts b/src/Core/NodeInterface.ts index c0f462dd7..a3cacc69a 100644 --- a/src/Core/NodeInterface.ts +++ b/src/Core/NodeInterface.ts @@ -1,10 +1,10 @@ +import { ListenerFn } from "eventemitter3"; import Attribute from "../Core/Attribute"; import GomlNode from "../Core/GomlNode"; import GomlParser from "../Core/GomlParser"; +import { Name, Nullable } from "../Tools/Types"; import Utility from "../Tools/Utility"; import XMLReader from "../Tools/XMLReader"; -import { ListenerFn } from "eventemitter3"; -import { Name, Nullable } from "../Tools/Types"; /** * interface for operate multicast nodes. @@ -35,6 +35,9 @@ export default class NodeInterface { return Utility.sum(counts); } + /** + * check count is 0. + */ public get isEmpty(): boolean { return this.count === 0; } @@ -85,6 +88,11 @@ export default class NodeInterface { } } + /** + * get attribute of first node. + * throw error if this NodeInterface is empty. + * @param attrName + */ public getAttribute(attrName: Name): any { const first = this.first(); if (!first) { @@ -92,6 +100,12 @@ export default class NodeInterface { } return first.getAttribute(attrName); } + + /** + * set attribute to all target node. + * @param attrName + * @param value + */ public setAttribute(attrName: Name, value: any): void { this.forEach(node => { node.setAttribute(attrName, value, false); @@ -99,7 +113,7 @@ export default class NodeInterface { } /** - * 対象ノードにイベントリスナを追加します。 + * add event listener to all target node. * @param {string} eventName [description] * @param {ListenerFn} listener [description] */ @@ -111,7 +125,7 @@ export default class NodeInterface { } /** - * 対象ノードに指定したイベントリスナが登録されていれば削除します + * remove event listener from all node if exists. * @param {string} eventName [description] * @param {ListenerFn} listener [description] */ @@ -123,21 +137,20 @@ export default class NodeInterface { } /** - * このノードインタフェースが対象とするノードそれぞれに、 - * タグで指定したノードを子要素として追加します。 + * add node as child to all nodes. * @param {string} tag [description] */ public append(tag: string): NodeInterface { this.forEach(node => { const elem = XMLReader.parseXML(tag); - let child = GomlParser.parse(elem); + const child = GomlParser.parse(elem); node.addChild(child); }); return this; } /** - * このノードインタフェースが対象とするノードをツリーから削除します。s + * remove all nodes from tree. * @param {GomlNode} child [description] */ public remove(): NodeInterface { @@ -170,6 +183,10 @@ export default class NodeInterface { return this; } + /** + * map all nodes to the results of provided function. + * @param func + */ public map(func: (node: GomlNode, gomlIndex: number, nodeIndex: number) => T): T[][] { return this.nodes.map((array, gomlIndex) => { return array.map((node, nodeIndex) => { @@ -177,6 +194,12 @@ export default class NodeInterface { }); }); } + + /** + * find first node that satisfies the provided testing function. + * otherwise null is returned. + * @param predicate + */ public find(predicate: (node: GomlNode, gomlIndex: number, nodeIndex: number) => boolean): Nullable { const nodes = this.nodes; for (let i = 0; i < nodes.length; i++) { @@ -190,6 +213,13 @@ export default class NodeInterface { } return null; } + + /** + * watch all nodes attribute. + * @param attrName + * @param watcher + * @param immediate + */ public watch(attrName: Name, watcher: ((newValue: any, oldValue: any, attr: Attribute) => void), immediate = false) { this.forEach(node => { node.watch(attrName, watcher, immediate); @@ -197,7 +227,7 @@ export default class NodeInterface { } /** - * このノードインタフェースが対象とするノードを有効、または無効にします。 + * set enabled all nodes. * @param {boolean} enable [description] */ public setEnable(enable: boolean): NodeInterface { @@ -208,8 +238,7 @@ export default class NodeInterface { } /** - * このノードインタフェースが対象とするノードのそれぞれの子ノードを対象とする、 - * 新しいノードインタフェースを取得します。 + * create new NodeInterface with children of all nodes. * @return {NodeInterface} [description] */ public children(): NodeInterface { @@ -222,7 +251,7 @@ export default class NodeInterface { } /** - * 対象ノードにコンポーネントをアタッチします。 + * add component to all nodes. * @param {Component} component [description] */ public addComponent(componentId: Name, attributes: { [key: string]: any } = {}): NodeInterface { @@ -233,8 +262,8 @@ export default class NodeInterface { } /** - * 最初の対象ノードを取得する - * ひとつもなければnull + * return the first node. + * return null if this NodeInterface is empty. * @return {GomlNode} [description] */ public first(): Nullable { @@ -242,8 +271,8 @@ export default class NodeInterface { } /** - * 対象となる唯一のノードを取得する。 - * 対象が存在しない、あるいは複数存在するときは例外を投げる。 + * return the first node. + * throw error if this NodeInterface count is not exactly 1. * @return {GomlNode} [description] */ public single(): GomlNode { @@ -257,6 +286,10 @@ export default class NodeInterface { return first; } + /** + * create new NodeInterface with filterd nodes. + * @param predicate + */ public filter(predicate: (node: GomlNode, gomlIndex: number, nodeIndex: number) => boolean): NodeInterface { const newNodes: GomlNode[][] = []; for (let i = 0; i < this.nodes.length; i++) { @@ -271,20 +304,40 @@ export default class NodeInterface { } return new NodeInterface(newNodes); } + + /** + * convert to array. + */ public toArray(): GomlNode[] { return Utility.flat(this.nodes); } + /** + * add child node by name to all nodes. + * @param nodeName + * @param attributes + */ public addChildByName(nodeName: Name, attributes: { [attrName: string]: any }): NodeInterface { return new NodeInterface(this.map(node => { return node.addChildByName(nodeName, attributes); })); } + + /** + * send message to all nodes. + */ public sendMessage(message: string, args?: any): void { this.forEach(node => { node.sendMessage(message, args); }); } + + /** + * broadcast message to all nodes. + * @param range + * @param name + * @param args + */ public broadcastMessage(range: number, name: string, args?: any): void; public broadcastMessage(name: string, args?: any): void; public broadcastMessage(arg1: number | string, arg2?: any, arg3?: any): void { diff --git a/src/Interface/IAttributeConverterDeclaration.ts b/src/Interface/IAttributeConverterDeclaration.ts index 35156b63c..b297f4ca1 100644 --- a/src/Interface/IAttributeConverterDeclaration.ts +++ b/src/Interface/IAttributeConverterDeclaration.ts @@ -1,6 +1,9 @@ import Attribute from "../Core/Attribute"; -import {Name} from "../Tools/Types"; +import { Name } from "../Tools/Types"; +/** + * interface for converter declaration + */ export default interface IAttributeConverterDeclaration { name: Name; [params: string]: any; diff --git a/src/Interface/IAttributeDeclaration.ts b/src/Interface/IAttributeDeclaration.ts index 397a6517c..ade9b349b 100644 --- a/src/Interface/IAttributeDeclaration.ts +++ b/src/Interface/IAttributeDeclaration.ts @@ -1,8 +1,10 @@ -import {Name} from "../Tools/Types"; +import { Name } from "../Tools/Types"; +/** + * interface for attribute declaration + */ export default interface IAttributeDeclaration { converter: Name; default: any; [parameters: string]: any; } - diff --git a/src/Interface/ITreeInitializedInfo.ts b/src/Interface/ITreeInitializedInfo.ts index 957d11616..8a015824c 100644 --- a/src/Interface/ITreeInitializedInfo.ts +++ b/src/Interface/ITreeInitializedInfo.ts @@ -1,4 +1,7 @@ +/** + * message argument for TreeInitialized. + */ export default interface ITreeInitializedInfo { - ownerScriptTag: HTMLScriptElement; - id: string; + ownerScriptTag: HTMLScriptElement; + id: string; } diff --git a/src/Tools/Ensure.ts b/src/Tools/Ensure.ts index 951487f51..58f421f18 100644 --- a/src/Tools/Ensure.ts +++ b/src/Tools/Ensure.ts @@ -1,13 +1,13 @@ import Component from "../Core/Component"; import ComponentDeclaration from "../Core/ComponentDeclaration"; import Environment from "../Core/Environment"; -import IdentityMap from "../Core/IdentityMap"; import Identity from "../Core/Identity"; +import IdentityMap from "../Core/IdentityMap"; import { ComponentRegistering, Ctor, Name, - Nullable + Nullable, } from "./Types"; /** @@ -15,13 +15,17 @@ import { */ export default class Ensure { + /** + * name or constructor to be identity + * @param component + */ public static tobeComponentIdentity(component: Name | (new () => Component)): Identity { if (typeof component === "function") { const obj = ComponentDeclaration.ctorMap.find(o => o.ctor === component); if (obj) { component = obj.name; } else { - throw new Error(`Specified constructor have not registered to current context.`); + throw new Error("Specified constructor have not registered to current context."); } } else { component = Ensure.tobeNSIdentity(component); @@ -65,7 +69,7 @@ export default class Ensure { */ public static tobeNSIdentity(name: Name): Identity { if (!name) { - throw Error(`argument can not be null or undefined.`); + throw Error("argument can not be null or undefined."); } if (typeof name === "string") { return Identity.guess(name); @@ -74,6 +78,11 @@ export default class Ensure { } } + /** + * Internal use! + * @param names + * @deprecated + */ public static tobeNSIdentityArray(names: Name[]): Identity[] { if (!names) { return []; @@ -85,7 +94,11 @@ export default class Ensure { return newArr; } - public static tobeNSDictionary(dict: IdentityMap | { [key: string]: T }): IdentityMap { + /** + * object or IdentityMap to be IdentityMap + * @param dict + */ + public static tobeIdentityMap(dict: IdentityMap | { [key: string]: T }): IdentityMap { if (!dict) { return new IdentityMap(); } @@ -93,13 +106,18 @@ export default class Ensure { return dict; } else { const newDict = new IdentityMap(); - for (let key in dict) { + for (const key in dict) { newDict.set(Identity.guess(key), dict[key]); } return newDict; } } + /** + * Internal use! + * Add '$$' to the beginning of the string if it does not start with '$$' + * @param message + */ public static tobeMessage(message: string): string { if (message.startsWith("$")) { if (message.startsWith("$$")) { @@ -130,6 +148,11 @@ export default class Ensure { } } + /** + * return fqn string if name is identity or fqn string. + * return null if name is string but is not start with '_'. + * @param name + */ public static tobeFQN(name: Name): Nullable { if (typeof name === "string") { if (Ensure.checkFQNString(name)) { diff --git a/src/Tools/IdResolver.ts b/src/Tools/IdResolver.ts index 359facde5..bd7285bd1 100644 --- a/src/Tools/IdResolver.ts +++ b/src/Tools/IdResolver.ts @@ -1,6 +1,5 @@ -import Namespace from "../Core/Namespace"; import Identity from "../Core/Identity"; - +import Namespace from "../Core/Namespace"; /** * Internal use! @@ -12,6 +11,9 @@ export default class IdResolver { private _FQNSet: Set = new Set(); private _isTerminal = false; + /** + * number of stored fqn + */ public get count(): number { return this._FQNSet.size; } @@ -23,7 +25,7 @@ export default class IdResolver { */ public add(id: string[] | Identity): boolean { if (!id) { - throw new Error(`Argument ns is null or undefined.`); + throw new Error("Argument ns is null or undefined."); } if (id instanceof Identity) { id = id.ns.hierarchy.concat([id.name]); @@ -44,26 +46,32 @@ export default class IdResolver { return this.get(Namespace.defineByArray(ns.split("."))); } const name = ns.hierarchy; - let current_name = name[name.length - 1]; + const current_name = name[name.length - 1]; if (!this._nameMap[current_name]) { return []; } - let pathes = this._nameMap[current_name]._get(name.slice(0, name.length - 1)); + const pathes = this._nameMap[current_name]._get(name.slice(0, name.length - 1)); const res = []; for (let i = 0; i < pathes.length; i++) { - let a = pathes[i]; + const a = pathes[i]; a.push(current_name); res.push(a.join(".")); } return res; } + + /** + * Internal use! + * return fqn if name is identified clealy + * @param name namespace or name + */ public resolve(name: Namespace | string): string { if (typeof name === "string") { return this.resolve(Namespace.defineByArray(name.split("."))); } - let pathes = this.get(name); + const pathes = this.get(name); if (pathes.length === 0) { throw new Error(`${name} is not found in this context.`); } @@ -72,13 +80,28 @@ export default class IdResolver { } return pathes[0]; } + + /** + * Internal use! + * @param name name + */ public has(name: string): boolean { return !!this._nameMap[name]; } + + /** + * Internal use! + * @param name + */ public remove(name: Identity): void { const fqn = name.fqn.split("."); this._remove(fqn); } + + /** + * Internal use! + * @param callback + */ public foreach(callback: (fqn: string) => void): void { this._FQNSet.forEach(callback); } @@ -98,10 +121,10 @@ export default class IdResolver { if (this.count === 0) { return [[]]; } - for (let key in this._nameMap) { - let match = this._nameMap[key]._get([])!; + for (const key in this._nameMap) { + const match = this._nameMap[key]._get([]); for (let i = 0; i < match.length; i++) { - let m = match[i]; + const m = match[i]; m.push(key); res.push(m); } @@ -111,12 +134,12 @@ export default class IdResolver { } return res; } - let current_name = name[name.length - 1]; - for (let key in this._nameMap) { - let match = key === current_name ? this._nameMap[key]._get(name.slice(0, name.length - 1)) : this._nameMap[key]._get(name); + const current_name = name[name.length - 1]; + for (const key in this._nameMap) { + const match = key === current_name ? this._nameMap[key]._get(name.slice(0, name.length - 1)) : this._nameMap[key]._get(name); if (match.length !== 0) { for (let i = 0; i < match.length; i++) { - let m = match[i]; + const m = match[i]; m.push(key); res.push(m); } diff --git a/src/Tools/MessageException.ts b/src/Tools/MessageException.ts index a47a7c0a2..6c1b58f9d 100644 --- a/src/Tools/MessageException.ts +++ b/src/Tools/MessageException.ts @@ -1,5 +1,5 @@ -import GomlNode from "../Core/GomlNode"; import Component from "../Core/Component"; +import GomlNode from "../Core/GomlNode"; /** * Exception representing uncought error caused in message function. @@ -44,6 +44,9 @@ export default class MessageException extends Error { proto.message = this.message; } + /** + * to string + */ public toString(): string { return this.message; } diff --git a/src/Tools/Types.ts b/src/Tools/Types.ts index 03310728f..c4e26e562 100644 --- a/src/Tools/Types.ts +++ b/src/Tools/Types.ts @@ -1,7 +1,7 @@ -import Identity from "../Core/Identity"; import GomlInterfaceImpl from "../Core/GomlInterfaceImpl"; import GomlNode from "../Core/GomlNode"; import GrimoireInterfaceImpl from "../Core/GrimoireInterfaceImpl"; +import Identity from "../Core/Identity"; import NodeInterface from "../Core/NodeInterface"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; diff --git a/src/Tools/Utility.ts b/src/Tools/Utility.ts index 634fa1018..65d819abf 100644 --- a/src/Tools/Utility.ts +++ b/src/Tools/Utility.ts @@ -1,17 +1,40 @@ import Environment from "../Core/Environment"; +/** + * implement utility functions + */ export default class Utility { + + /** + * write warning if in debug-mode + * @param message warning message + */ public static w(message: string): void { if (Environment.GrimoireInterface.debug) { console.warn(message); } } + + /** + * check string is CamelCase + * @param str string to check + */ public static isCamelCase(str: string): boolean { return /^[A-Z][a-zA-Z0-9]*$/.test(str); } + + /** + * check string is snake-case + * @param str string to check + */ public static isSnakeCase(str: string): boolean { return /^[a-z0-9\-]+$/.test(str); } + + /** + * array to be flat + * @param array array + */ public static flat(array: T[][]): T[] { let count = 0; for (let i = 0; i < array.length; i++) { @@ -28,6 +51,12 @@ export default class Utility { } return ret; } + + /** + * flatting result of map + * @param source array + * @param map map function + */ public static flatMap(source: T[], map: (a: T) => T[]): T[] { const c = new Array(source.length); for (let i = 0; i < source.length; i++) { @@ -35,6 +64,11 @@ export default class Utility { } return Utility.flat(c); } + + /** + * calculate sum of array + * @param array array + */ public static sum(array: number[]): number { let total = 0; for (let i = 0; i < array.length; i++) { @@ -42,6 +76,13 @@ export default class Utility { } return total; } + + /** + * remove element from array if exists + * @param array array + * @param target remove target + * @return success or not + */ public static remove(array: T[], target: T): boolean { let index = -1; for (let i = 0; i < array.length; i++) { @@ -58,7 +99,8 @@ export default class Utility { } /** - * 重複がなければtrue + * return true if array contain multiple same object + * @param array array */ public static checkOverlap(array: T[]): boolean { const list = []; @@ -72,15 +114,22 @@ export default class Utility { return true; } + /** + * get node index by element index + * @param targetElement element + * @param elementIndex index of target element + */ public static getNodeListIndexByElementIndex(targetElement: Element, elementIndex: number): number { const nodeArray: Node[] = Array.prototype.slice.call(targetElement.childNodes); - const elementArray = nodeArray.filter((v) => { - return v.nodeType === 1; - }); - elementIndex = elementIndex < 0 ? elementArray.length + elementIndex : elementIndex; - return nodeArray.indexOf(elementArray[elementIndex]); + const elementArray = nodeArray.filter((v) => v.nodeType === 1); + const updatedElementIndex = elementIndex < 0 ? elementArray.length + elementIndex : elementIndex; + return nodeArray.indexOf(elementArray[updatedElementIndex]); } + /** + * get all attributes of element + * @param element element + */ public static getAttributes(element: Element): { [key: string]: string } { const attributes: { [key: string]: string } = {}; const domAttr = element.attributes; @@ -89,7 +138,7 @@ export default class Utility { if (attrNode.name.startsWith("xmlns")) { continue; } - const name = attrNode.namespaceURI ? attrNode.namespaceURI + "." + attrNode.localName! : attrNode.localName!; + const name = attrNode.namespaceURI ? `${attrNode.namespaceURI}.${attrNode.localName!}` : attrNode.localName!; attributes[name] = attrNode.value; } return attributes; diff --git a/src/Tools/XMLHttpRequestAsync.ts b/src/Tools/XMLHttpRequestAsync.ts index 335d95a49..92daced1d 100644 --- a/src/Tools/XMLHttpRequestAsync.ts +++ b/src/Tools/XMLHttpRequestAsync.ts @@ -1,6 +1,14 @@ +/** + * async wrapper for XMLHttpRequest + */ export default class XMLHttpRequestAsync { - public static send(xhr: XMLHttpRequest, data?: Document | string): Promise { - return new Promise((resolve, reject) => { + /** + * send request async + * @param xhr request + * @param data data to send + */ + public static async send(xhr: XMLHttpRequest, data?: Document | string): Promise { + return new Promise((resolve, reject) => { xhr.onload = (e) => { resolve(e); }; diff --git a/src/Tools/XMLReader.ts b/src/Tools/XMLReader.ts index 56297004f..7accd003c 100644 --- a/src/Tools/XMLReader.ts +++ b/src/Tools/XMLReader.ts @@ -1,11 +1,14 @@ import Environment from "../Core/Environment"; -import { Nullable } from "./Types"; /** * Provides safe xml read feature. */ export default class XMLReader { + /** + * parse XML to Element Tree + * @param doc xml document string + */ public static parseXML(doc: string): Element { const parsed = Environment.DomParser.parseFromString(doc, "text/xml"); if (!parsed || parsed.getElementsByTagName("parsererror").length > 0) { @@ -13,74 +16,6 @@ export default class XMLReader { throw new Error(`Error parsing XML: ${err}`); } - return parsed.documentElement; // TODO: implenent! - } - - public static getElements(elem: Element, name: string): Element[] { - const result: Element[] = []; - const elems = elem.getElementsByTagName(name); - for (let i = 0; i < elems.length; i++) { - result.push(elems.item(i)); - } - return result; - } - - public static getSingleElement(elem: Element, name: string, mandatory?: boolean): Nullable { - const result = XMLReader.getElements(elem, name); - if (result.length === 1) { - return result[0]; - } else if (result.length === 0) { // When the element was not found - if (mandatory) { - throw new Error(`The mandatory element ${name} was required, but not found`); - } else { - return null; - } - } else { - throw new Error(`The element ${name} requires to exist in single. But there is ${result.length} count of elements`); - } - } - - public static getAttribute(elem: Element, name: string, mandatory?: boolean): Nullable { - const result = elem.attributes.getNamedItem(name); - if (result) { - return result.value; - } else if (mandatory) { - throw new Error(`The mandatory attribute ${name} was required, but it was not found`); - } else { - return null; - } - } - - public static getAttributeFloat(elem: Element, name: string, mandatory?: boolean): Nullable { - const resultStr = XMLReader.getAttribute(elem, name, mandatory); - return resultStr ? parseFloat(resultStr) : null; - } - - public static getAttributeInt(elem: Element, name: string, mandatory?: boolean): Nullable { - const resultStr = XMLReader.getAttribute(elem, name, mandatory); - return resultStr ? parseInt(resultStr, 10) : null; - } - - public static getChildElements(elem: Element): Element[] { - const children = elem.childNodes; - const result: Element[] = []; - for (let i = 0; i < children.length; i++) { - if (children.item(i) instanceof Element) { - result.push(children.item(i) as Element); - } - } - return result; - } - - public static getAttributes(elem: Element, ns?: string): { [key: string]: string } { - const result: { [key: string]: string } = {}; - const attrs = elem.attributes; - for (let i = 0; i < attrs.length; i++) { - const attr = attrs.item(i); - if (!ns || attr.namespaceURI === ns) { - result[attr.localName!] = attr.value; - } - } - return result; + return parsed.documentElement; } } diff --git a/tslint.json b/tslint.json index b4f2bac5d..7b11952e0 100644 --- a/tslint.json +++ b/tslint.json @@ -34,7 +34,7 @@ "no-magic-numbers": false, "no-namespace": true, "no-non-null-assertion": false, - "no-parameter-reassignment": true, + "no-parameter-reassignment": false, "no-reference": true, "no-unnecessary-type-assertion": true, "no-var-requires": true, @@ -77,7 +77,7 @@ "no-eval": true, "no-floating-promises": true, "no-for-in-array": false, - "no-inferred-empty-object-type": true, + "no-inferred-empty-object-type": false, "no-invalid-template-strings": true, "no-invalid-this": false, "no-misused-new": false, From 74dc1b3623e18ae81cffb2d4f183e7e36d8d101d Mon Sep 17 00:00:00 2001 From: moajo Date: Tue, 10 Oct 2017 14:32:24 +0900 Subject: [PATCH 038/146] fix: use common submodule --- .gitmodules | 3 + common | 1 + tslint.json | 240 +--------------------------------------------------- 3 files changed, 6 insertions(+), 238 deletions(-) create mode 100644 .gitmodules create mode 160000 common diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..5afd88770 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "common"] + path = common + url = git@github.com:GrimoireGL/common-configurations.git diff --git a/common b/common new file mode 160000 index 000000000..27e461ceb --- /dev/null +++ b/common @@ -0,0 +1 @@ +Subproject commit 27e461cebf2bef9779777f79a0ba732457b24c67 diff --git a/tslint.json b/tslint.json index 7b11952e0..8b4267c5b 100644 --- a/tslint.json +++ b/tslint.json @@ -1,243 +1,7 @@ { + "extends": "./common/tslint.json", "rulesDirectory": [], "rules": { - "adjacent-overload-signatures": true, - "ban-types": false, - "member-access": true, - "member-ordering": [ - true, - { - "order": [ - "public-static-field", - "protected-static-field", - "private-static-field", - "public-static-method", - "protected-static-method", - "private-static-method", - "public-instance-field", - "protected-instance-field", - "private-instance-field", - "public-constructor", - "protected-constructor", - "private-constructor", - "public-instance-method", - "protected-instance-method", - "private-instance-method" - ] - } - ], - "no-any": false, - "no-empty-interface": false, - "no-import-side-effect": false, - "no-inferrable-types": true, - "no-internal-module": true, - "no-magic-numbers": false, - "no-namespace": true, - "no-non-null-assertion": false, - "no-parameter-reassignment": false, - "no-reference": true, - "no-unnecessary-type-assertion": true, - "no-var-requires": true, - "only-arrow-functions": false, - "prefer-for-of": false, - "promise-function-async": true, - "typedef": false, - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "unified-signatures": false, - "await-promise": true, - "ban": false, - "curly": true, - "forin": false, - "import-blacklist": false, - "label-position": true, - "no-arg": true, - "no-bitwise": false, - "no-conditional-assignment": false, - "no-console": [ - true, - "log", - "time", - "timeEnd", - "trace" - ], - "no-construct": false, - "no-debugger": true, - "no-duplicate-super": true, - "no-duplicate-variable": true, - "no-empty": true, - "no-eval": true, - "no-floating-promises": true, - "no-for-in-array": false, - "no-inferred-empty-object-type": false, - "no-invalid-template-strings": true, - "no-invalid-this": false, - "no-misused-new": false, - "no-null-keyword": false, - "no-object-literal-type-assertion": false, - "no-shadowed-variable": true, - "no-sparse-arrays": true, - "no-string-literal": false, - "no-string-throw": true, - "no-submodule-imports": false, - "no-switch-case-fall-through": true, - "no-this-assignment": false, - "no-unbound-method": false, - "no-unsafe-any": false, - "no-unsafe-finally": true, - "no-unused-expression": true, - "no-unused-variable": true, - "no-use-before-declare": true, - "no-var-keyword": true, - "no-void-expression": true, - "prefer-conditional-expression": false, - "prefer-object-spread": true, - "radix": true, - "restrict-plus-operands": true, - "strict-boolean-expressions": false, - "strict-type-predicates": false, - "switch-default": false, - "triple-equals": [ - true, - "allow-null-check" - ], - "typeof-compare": true, - "use-default-type-parameter": true, - "use-isnan": true, - "cyclomatic-complexity": false, - "deprecation": true, - "eofline": true, - "indent": [ - true, - "spaces", - 2 - ], - "linebreak-style": [ - true, - "LF" - ], - "max-classes-per-file": false, - "max-file-line-count": false, - "max-line-length": false, - "no-default-export": false, - "no-duplicate-imports": true, - "no-mergeable-namespace": true, - "no-require-imports": true, - "object-literal-sort-keys": false, - "prefer-const": true, - "trailing-comma": [ - true, - { - "singleline": "never", - "multiline": "always" - } - ], - "align": true, - "array-type": [ - true, - "array" - ], - "arrow-parens": false, - "arrow-return-shorthand": true, - "binary-expression-operand-order": false, - "callable-types": false, - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "completed-docs": [ - true, - { - "classes": true, - "interfaces": true, - "methods": { - "privacies": [ - "public" - ] - }, - "properties": { - "privacies": [ - "public" - ] - } - } - ], - "encoding": true, - "file-header": false, - "import-spacing": true, - "interface-name": true, - "interface-over-type-literal": false, - "jsdoc-format": true, - "match-default-export-name": true, - "newline-before-return": false, - "new-parens": true, - "no-angle-bracket-type-assertion": true, - "no-boolean-literal-compare": true, - "no-consecutive-blank-lines": true, - "no-irregular-whitespace": true, - "no-parameter-properties": false, - "no-reference-import": true, - "no-trailing-whitespace": true, - "no-unnecessary-callback-wrapper": true, - "no-unnecessary-initializer": true, - "no-unnecessary-qualifier": true, - "number-literal-format": true, - "object-literal-key-quotes": [ - true, - "as-needed" - ], - "object-literal-shorthand": true, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], - "one-variable-per-declaration": false, - "ordered-imports": true, - "prefer-function-over-method": false, - "prefer-method-signature": true, - "prefer-switch": false, - "prefer-template": [ - true, - "allow-single-concat" - ], - "quotemark": [ - true, - "double", - "avoid-escape", - "avoid-template" - ], - "return-undefined": true, - "semicolon": [ - true, - "always" - ], - "space-before-function-paren": [ - true, - "never" - ], - "space-within-parens": true, - "switch-final-break": true, - "type-literal-delimiter": false, - "variable-name": false, - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "no-unused-variable": false } } \ No newline at end of file From d08580ff66bc26de1ff0825a55e5fa254e195a9a Mon Sep 17 00:00:00 2001 From: moajo Date: Thu, 12 Oct 2017 12:30:23 +0900 Subject: [PATCH 039/146] [fix] test --- test/Tools/EnsureTest.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/Tools/EnsureTest.ts b/test/Tools/EnsureTest.ts index 6302b830d..6d8691578 100644 --- a/test/Tools/EnsureTest.ts +++ b/test/Tools/EnsureTest.ts @@ -18,14 +18,14 @@ test("Ensure passed argument should be transformed as NSIdentity", (t) => { test("Ensure passed argument are transformed into number", (t) => { t.truthy(Ensure.tobeNumber("9") === 9); t.truthy(Ensure.tobeNumber(9) === 9); - let a: any = () => {/*do nothing*/ }; + const a: any = () => {/*do nothing*/ }; t.throws(() => Ensure.tobeNumber(a)); }); test("Ensure passed argument are transformed into string", (t) => { t.truthy(Ensure.tobeString("9") === "9"); t.truthy(Ensure.tobeString(9) === "9"); - let a: any = () => {/*do nothing*/ }; + const a: any = () => {/*do nothing*/ }; t.throws(() => Ensure.tobeString(a)); }); @@ -44,12 +44,12 @@ test("Ensure passed array are transformed into NSIdentity[]", (t) => { }); test("Ensure passed object are transformed into NSDictionary", (t) => { - let transformed = Ensure.tobeNSDictionary(void 0); + let transformed = Ensure.tobeIdentityMap(void 0); t.truthy(transformed instanceof IdentityMap); - let obj = {}; + const obj = {}; obj[Identity.fromFQN("Hello").fqn] = "test1"; obj[Identity.fromFQN("World").fqn] = "test2"; - transformed = Ensure.tobeNSDictionary(obj); + transformed = Ensure.tobeIdentityMap(obj); t.truthy(transformed instanceof IdentityMap); t.truthy(transformed.get("Hello") === "test1"); t.truthy(transformed.get("World") === "test2"); From 724653f76910985526f0563e7017e5059a0c7d0f Mon Sep 17 00:00:00 2001 From: moajo Date: Thu, 12 Oct 2017 12:47:20 +0900 Subject: [PATCH 040/146] [fix] replace 'snake-case' to 'kebab-case' --- src/Core/GrimoireInterfaceImpl.ts | 2 +- src/Tools/Utility.ts | 4 ++-- test/Tools/UtilityTest.ts | 12 ++++++------ 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 0c0c888cc..9a1790258 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -258,7 +258,7 @@ export default class GrimoireInterfaceImpl extends EEObject { if (this.nodeDeclarations.get(registerId)) { throw new Error(`gomlnode ${registerId.fqn} is already registerd.`); } - if (this.debug && !Utility.isSnakeCase(registerId.name)) { + if (this.debug && !Utility.isKebabCase(registerId.name)) { console.warn(`node ${registerId.name} is registerd. but,it should be 'snake-case'.`); } diff --git a/src/Tools/Utility.ts b/src/Tools/Utility.ts index 65d819abf..3785d861a 100644 --- a/src/Tools/Utility.ts +++ b/src/Tools/Utility.ts @@ -24,10 +24,10 @@ export default class Utility { } /** - * check string is snake-case + * check string is kebab-case * @param str string to check */ - public static isSnakeCase(str: string): boolean { + public static isKebabCase(str: string): boolean { return /^[a-z0-9\-]+$/.test(str); } diff --git a/test/Tools/UtilityTest.ts b/test/Tools/UtilityTest.ts index c5c833fee..0d3736aca 100644 --- a/test/Tools/UtilityTest.ts +++ b/test/Tools/UtilityTest.ts @@ -10,10 +10,10 @@ test("isCamelCase works correctly.", t => { }); test("isSnakeCase works correctly.", t => { - t.truthy(Utility.isSnakeCase("name-name-123")); - t.truthy(Utility.isSnakeCase("nm")); - t.truthy(Utility.isSnakeCase("--")); - t.truthy(!Utility.isSnakeCase("nameName")); - t.truthy(!Utility.isSnakeCase("Name_Name")); - t.truthy(!Utility.isSnakeCase("1nameName")); + t.truthy(Utility.isKebabCase("name-name-123")); + t.truthy(Utility.isKebabCase("nm")); + t.truthy(Utility.isKebabCase("--")); + t.truthy(!Utility.isKebabCase("nameName")); + t.truthy(!Utility.isKebabCase("Name_Name")); + t.truthy(!Utility.isKebabCase("1nameName")); }); From 1415acc0bb822c4a87c773471bd7a45668eefaf5 Mon Sep 17 00:00:00 2001 From: moajo Date: Thu, 12 Oct 2017 12:52:12 +0900 Subject: [PATCH 041/146] [fix] message reciever to be protected --- src/Components/GrimoireComponent.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Components/GrimoireComponent.ts b/src/Components/GrimoireComponent.ts index 2b40688c1..8e5e19f20 100644 --- a/src/Components/GrimoireComponent.ts +++ b/src/Components/GrimoireComponent.ts @@ -32,7 +32,7 @@ export default class GrimoireComponent extends Component { /** * awake */ - public $awake(): void { + protected $awake(): void { const node = this.node; node.resolveAttributesValue(); this.getAttributeRaw("id").watch((attr) => { From a64731e09c42f1b52d0d830dc23065ffa5eaa3bd Mon Sep 17 00:00:00 2001 From: moajo Date: Thu, 12 Oct 2017 13:09:07 +0900 Subject: [PATCH 042/146] [fix] refactor code --- src/Converters/BooleanConverter.ts | 2 +- src/Converters/NumberConverter.ts | 4 ++-- src/Core/Attribute.ts | 20 ++++++++--------- src/Core/AttributeManager.ts | 14 ++++++------ src/Core/Component.ts | 2 +- src/Core/GomlNode.ts | 28 +++++++++++------------ src/Core/GrimoireInterfaceImpl.ts | 10 ++++----- src/Core/Identity.ts | 2 +- src/Core/IdentityMap.ts | 8 +++---- src/Core/NodeDeclaration.ts | 30 ++++++++++++------------- src/Core/NodeInterface.ts | 4 ++-- test/Converters/BooleanConverterTest.ts | 12 +++++----- test/Converters/EnumConverterTest.ts | 8 +++---- test/Converters/NumberConverterTest.ts | 6 ++--- test/Core/AttributeManagerTest.ts | 12 +++++----- test/Core/AttributeTest.ts | 24 ++++++++++---------- test/Core/GomlNode2Test.ts | 16 ++++++------- test/Core/GrimoireInterfaceTest.ts | 16 ++++++------- test/Tools/EnsureTest.ts | 6 ++--- 19 files changed, 111 insertions(+), 113 deletions(-) diff --git a/src/Converters/BooleanConverter.ts b/src/Converters/BooleanConverter.ts index 989d98692..fd36cc6e1 100644 --- a/src/Converters/BooleanConverter.ts +++ b/src/Converters/BooleanConverter.ts @@ -19,5 +19,5 @@ export default function BooleanConverter(val: any): Undef { return false; } } - return void 0; + return undefined; } diff --git a/src/Converters/NumberConverter.ts b/src/Converters/NumberConverter.ts index 579858b34..c4b30e282 100644 --- a/src/Converters/NumberConverter.ts +++ b/src/Converters/NumberConverter.ts @@ -14,7 +14,7 @@ export default function NumberConverter(val: any): Undef { } if (typeof val === "string") { const parsed = Number.parseFloat(val); - return Number.isNaN(parsed) ? void 0 : parsed; + return Number.isNaN(parsed) ? undefined : parsed; } if (val === null) { return null; @@ -26,5 +26,5 @@ export default function NumberConverter(val: any): Undef { return ret; } } - return void 0; + return undefined; } diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index 881949ae2..0165db5b7 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -44,7 +44,7 @@ export default class Attribute { attr.declaration = declaration; const converterName = Ensure.tobeNSIdentity(declaration.converter); attr.converter = Environment.GrimoireInterface.converters.get(converterName); - if (attr.converter === void 0) { + if (attr.converter === undefined) { // When the specified converter was not found throw new Error(`Specified converter ${converterName.name} was not found from registered converters.\n Component: ${attr.component.name.fqn}\n Attribute: ${attr.name.name}`); } @@ -116,7 +116,7 @@ export default class Attribute { * @return {any} value with specified type. */ public get Value(): any { - if (this._value === void 0) { + if (this._value === undefined) { const node = this.component.node; throw new Error(`attribute ${this.name.name} value is undefined in ${node ? node.name.name : "undefined"}`); } @@ -147,7 +147,7 @@ export default class Attribute { this._observers.push(watcher); } if (immedateCalls) { - watcher(this.Value, void 0, this); + watcher(this.Value, undefined, this); } } @@ -175,7 +175,7 @@ export default class Attribute { * @param {string} variableName [description] * @param {any} targetObject [description] */ - public boundTo(variableName: string, targetObject: any = this.component): void { + public bindTo(variableName: string, targetObject: any = this.component): void { if (targetObject[variableName]) { console.warn(`component field ${variableName} is already defined.`); } @@ -205,7 +205,7 @@ export default class Attribute { * @param {string }} domValues [description] */ public resolveDefaultValue(domValues: { [key: string]: string }): void { - if (this._value !== void 0) {// value is already exist. + if (this._value !== undefined) {// value is already exist. return; } @@ -223,21 +223,21 @@ export default class Attribute { } const get = resolver.get(key); if (get.length > 0) { - if (tagAttrKey === void 0) { + if (tagAttrKey === undefined) { tagAttrKey = key; } else { throw new Error(`tag attribute is ambiguous for ${this.name.fqn}. It has the following possibilities ${tagAttrKey} ${get[0]}`); } } } - if (tagAttrKey !== void 0) { + if (tagAttrKey !== undefined) { this.Value = domValues[tagAttrKey]; return; } // resolve by node defaults. - const nodeDefaultValue = this.component.node.nodeDeclaration.defaultAttributesActual.hasMatchingValue(this.name); - if (nodeDefaultValue !== void 0) { + const nodeDefaultValue = this.component.node.declaration.defaultAttributesActual.hasMatchingValue(this.name); + if (nodeDefaultValue !== undefined) { this.Value = nodeDefaultValue; // Node指定値で解決 return; } @@ -248,7 +248,7 @@ export default class Attribute { private _valuate(raw: any): any { const v = this.converter.convert(raw, this); - if (v === void 0) { + if (v === undefined) { const errorMessage = `Converting attribute value failed.\n\n* input : ${raw}\n* Attribute(Attribute FQN) : ${this.name.name}(${this.name.fqn})\n* Component : ${this.component.name.name}(${this.component.name.fqn})\n* Node(Node FQN) : ${this.component.node.name.name}(${this.component.node.name.fqn})\n* Converter : ${this.declaration.converter}\n\n* Structure map:\n${this.component.node.toStructualString(`--------------Error was thrown from '${this.name.name}' of this node.`)}`; throw new Error(errorMessage); } diff --git a/src/Core/AttributeManager.ts b/src/Core/AttributeManager.ts index df1bd8ad8..c31043adc 100644 --- a/src/Core/AttributeManager.ts +++ b/src/Core/AttributeManager.ts @@ -41,7 +41,7 @@ class AttributeBuffer { */ public resolve(fqn: string, remove: boolean): Undef { const guess = this.guess(fqn, remove); - return guess.length === 0 ? void 0 : guess[guess.length - 1]; + return guess.length === 0 ? undefined : guess[guess.length - 1]; } /** @@ -92,7 +92,7 @@ export default class AttributeManager { if (this._idResolver.has(fqn)) { // already exists Utility.w(`attribute ${attr.name} is already exist in ${this.tag}`); } - if (this._attributesFQNMap[fqn] === void 0) { + if (this._attributesFQNMap[fqn] === undefined) { this._attributesFQNMap[fqn] = []; } this._attributesFQNMap[fqn].push(attr); @@ -100,7 +100,7 @@ export default class AttributeManager { // check buffer value. const attrBuf = this._attrBuffer.resolve(attr.name.fqn, true); - if (attrBuf !== void 0) { + if (attrBuf !== undefined) { attr.Value = attrBuf; } @@ -121,7 +121,7 @@ export default class AttributeManager { const fqn = Ensure.tobeFQN(attrName); if (fqn) { const attrs = this._attributesFQNMap[fqn]; - if (attrs === void 0 || attrs.length === 0) { + if (attrs === undefined || attrs.length === 0) { this._watchBuffer.add(fqn, watcher); return; } @@ -151,7 +151,7 @@ export default class AttributeManager { */ public setAttribute(attrFQN: string, value: any): void { const attrs = this._attributesFQNMap[attrFQN]; - if (attrs === void 0 || attrs.length === 0) { + if (attrs === undefined || attrs.length === 0) { this._attrBuffer.add(attrFQN, value); return; } @@ -204,7 +204,7 @@ export default class AttributeManager { const attrs = this._attributesFQNMap[fqn] || []; if (attrs.length === 0) { const attrBuf = this._attrBuffer.resolve(fqn, false); - if (attrBuf !== void 0) { + if (attrBuf !== undefined) { return attrBuf; } throw new Error(`attribute ${attrName} is not found.`); @@ -217,7 +217,7 @@ export default class AttributeManager { const res = this._idResolver.get(attrName); if (res.length === 0) { const attrBuf = this._attrBuffer.resolve(attrName, false); - if (attrBuf !== void 0) { + if (attrBuf !== undefined) { return attrBuf; } throw new Error(`attribute ${attrName} is not found.`); diff --git a/src/Core/Component.ts b/src/Core/Component.ts index ca16ab6bf..2af6516c8 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -260,7 +260,7 @@ export default class Component extends IDObject { protected __bindAttributes(): void { this.attributes.forEach(attr => { const name = attr.name.name; - attr.boundTo(name); + attr.bindTo(name); }); } } diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index 98fcafa72..cee2a75b4 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -49,7 +49,7 @@ export default class GomlNode extends EEObject { /** * declaration infomation. */ - public nodeDeclaration: NodeDeclaration; + public declaration: NodeDeclaration; /** * children nodes. @@ -74,7 +74,7 @@ export default class GomlNode extends EEObject { * Tag name. */ public get name(): Identity { - return this.nodeDeclaration.name; + return this.declaration.name; } /** @@ -156,26 +156,26 @@ export default class GomlNode extends EEObject { /** * create new instance. - * @param {NodeDeclaration} recipe 作成するノードのDeclaration + * @param {NodeDeclaration} declaration 作成するノードのDeclaration * @param {Element} element 対応するDomElement * @return {[type]} [description] */ - constructor(recipe: NodeDeclaration, element?: Element) { + constructor(declaration: NodeDeclaration, element?: Element) { super(); - if (!recipe) { - throw new Error("recipe must not be null"); + if (!declaration) { + throw new Error("declaration must not be null"); } - if (!recipe.resolvedDependency) { - recipe.resolveDependency(); + if (!declaration.resolvedDependency) { + declaration.resolveDependency(); } - this.nodeDeclaration = recipe; - this.element = element ? element : Environment.document.createElementNS(recipe.name.ns.qualifiedName, recipe.name.name); + this.declaration = declaration; + this.element = element ? element : Environment.document.createElementNS(declaration.name.ns.qualifiedName, declaration.name.name); this._root = this; this._components = []; - this._attributeManager = new AttributeManager(recipe.name.name); + this._attributeManager = new AttributeManager(declaration.name.name); this.element.setAttribute(Constants.x_gr_id, this.id); - const defaultComponentNames = recipe.defaultComponentsActual; + const defaultComponentNames = declaration.requiredComponentsActual; // instanciate default components defaultComponentNames.forEach(id => { @@ -722,7 +722,7 @@ export default class GomlNode extends EEObject { * @param attributeName */ public isFreezeAttribute(attributeName: string): boolean { - return !!this.nodeDeclaration.freezeAttributes.toArray().find(name => attributeName === name.fqn); + return !!this.declaration.freezeAttributes.toArray().find(name => attributeName === name.fqn); } /** @@ -867,7 +867,7 @@ export default class GomlNode extends EEObject { } private _sendMessage(message: string, args?: any): void { - if (this._messageCache[message] === void 0) { + if (this._messageCache[message] === undefined) { this._messageCache[message] = this._components.filter(c => typeof (c as any)[message] === "function"); } const targetList = this._messageCache[message]; diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 9a1790258..5c44737fd 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -228,7 +228,7 @@ export default class GrimoireInterfaceImpl extends EEObject { throw new Error("component must has 'attributes'"); } for (const key in attrs) { - if (attrs[key].default === void 0) { + if (attrs[key].default === undefined) { throw new Error(`default value of attribute ${key} in ${name.fqn} must be not 'undefined'.`); } } @@ -322,13 +322,11 @@ export default class GrimoireInterfaceImpl extends EEObject { const id = scriptTag.getAttribute("x-rootNodeId"); if (id) { const ret = this.rootNodes[id]; - if (!ret) { - throw new Error(`threr is no rootNode has id ${id}`); // TODO + if (ret) { + return ret; } - return ret; - } else { - return null; } + return null; } /** diff --git a/src/Core/Identity.ts b/src/Core/Identity.ts index 4cd9495a0..4f6f9fcd1 100644 --- a/src/Core/Identity.ts +++ b/src/Core/Identity.ts @@ -41,7 +41,7 @@ export default class Identity { } private static get _map(): IdResolver { - if (this._mapBackingField === void 0) { + if (this._mapBackingField === undefined) { this._mapBackingField = new IdResolver(); } return this._mapBackingField; diff --git a/src/Core/IdentityMap.ts b/src/Core/IdentityMap.ts index 2075d39aa..9ef7b5353 100644 --- a/src/Core/IdentityMap.ts +++ b/src/Core/IdentityMap.ts @@ -30,7 +30,7 @@ export default class IdentityMap { * @return success or not */ public delete(key: Identity): boolean { - if (this._fqnObjectMap[key.fqn] !== void 0) { + if (this._fqnObjectMap[key.fqn] !== undefined) { delete this._fqnObjectMap[key.fqn]; this._idResolver.remove(key); return true; @@ -118,11 +118,11 @@ export default class IdentityMap { public hasMatchingValue(name: Identity): Undef { const resolver = new IdResolver(); resolver.add(name); - let match: string | undefined = void 0; + let match: string | undefined; for (const key in this._fqnObjectMap) { const v = resolver.get(Namespace.defineByArray(key.split("."))); if (v.length === 1) { - if (match === void 0) { + if (match === undefined) { match = key; } else { throw new Error(`matching attribute is ambiguous. It has following possibilities ${match} ${key}`); @@ -132,7 +132,7 @@ export default class IdentityMap { if (match) { return this._fqnObjectMap[match]; } - return void 0; + return undefined; } /** diff --git a/src/Core/NodeDeclaration.ts b/src/Core/NodeDeclaration.ts index 08de0dc7f..0a020c520 100644 --- a/src/Core/NodeDeclaration.ts +++ b/src/Core/NodeDeclaration.ts @@ -16,7 +16,7 @@ export default class NodeDeclaration { * Components attached to this node by default. * this property is not consider inheritance. */ - public defaultComponents: IdentitySet; + public requiredComponents: IdentitySet; /** * attributes set to this node by default. @@ -40,7 +40,7 @@ export default class NodeDeclaration { */ public idResolver = new IdResolver(); - private _defaultComponentsActual: IdentitySet; + private _requiredComponentsActual: IdentitySet; private _defaultAttributesActual: IdentityMap; private _resolvedDependency = false; @@ -52,13 +52,13 @@ export default class NodeDeclaration { } /** - * get default components with inheritance in mind. + * get required components with inheritance in mind. */ - public get defaultComponentsActual(): IdentitySet { + public get requiredComponentsActual(): IdentitySet { if (!this._resolvedDependency) { throw new Error(`${this.name.fqn} is not resolved dependency!`); } - return this._defaultComponentsActual; + return this._requiredComponentsActual; } /** @@ -73,7 +73,7 @@ export default class NodeDeclaration { constructor( public name: Identity, - private _defaultComponents: Name[], + private _requiredComponents: Name[], private _defaultAttributes: { [key: string]: any }, private _superNode?: Name, private _freezeAttributes: Name[] = []) { @@ -89,9 +89,9 @@ export default class NodeDeclaration { */ public addDefaultComponent(componentName: Name): void { const componentId = Ensure.tobeNSIdentity(componentName); - this.defaultComponents.push(componentId); - if (this._defaultComponentsActual) { - this._defaultComponentsActual.push(componentId); + this.requiredComponents.push(componentId); + if (this._requiredComponentsActual) { + this._requiredComponentsActual.push(componentId); } } @@ -104,15 +104,15 @@ export default class NodeDeclaration { if (this._resolvedDependency) { return false; } - this.defaultComponents = new IdentitySet(this._defaultComponents.map(name => Ensure.tobeNSIdentity(name))); + this.requiredComponents = new IdentitySet(this._requiredComponents.map(name => Ensure.tobeNSIdentity(name))); for (const key in this._defaultAttributes) { const value = this._defaultAttributes[key]; this.defaultAttributes.set(Identity.fromFQN(key), value); } - this.superNode = this._superNode ? Ensure.tobeNSIdentity(this._superNode) : void 0; + this.superNode = this._superNode ? Ensure.tobeNSIdentity(this._superNode) : undefined; this._resolveInherites(); - this._defaultComponentsActual.forEach(id => { + this._requiredComponentsActual.forEach(id => { const dec = GrimoireInterface.componentDeclarations.get(id); dec.idResolver.foreach(fqn => { this.idResolver.add(Identity.fromFQN(fqn)); @@ -125,15 +125,15 @@ export default class NodeDeclaration { private _resolveInherites(): void { if (!this.superNode) { // not inherit. - this._defaultComponentsActual = this.defaultComponents; + this._requiredComponentsActual = this.requiredComponents; this._defaultAttributesActual = this.defaultAttributes; return; } const superNode = GrimoireInterface.nodeDeclarations.get(this.superNode); superNode.resolveDependency(); - const inheritedDefaultComponents = superNode.defaultComponentsActual; + const inheritedDefaultComponents = superNode.requiredComponentsActual; const inheritedDefaultAttribute = superNode.defaultAttributesActual; - this._defaultComponentsActual = inheritedDefaultComponents.clone().merge(this.defaultComponents); + this._requiredComponentsActual = inheritedDefaultComponents.clone().merge(this.requiredComponents); this._defaultAttributesActual = inheritedDefaultAttribute.clone().pushDictionary(this.defaultAttributes); } } diff --git a/src/Core/NodeInterface.ts b/src/Core/NodeInterface.ts index a3cacc69a..a9659ffe1 100644 --- a/src/Core/NodeInterface.ts +++ b/src/Core/NodeInterface.ts @@ -60,14 +60,14 @@ export default class NodeInterface { public get(nodeIndex: number): GomlNode; public get(treeIndex: number, nodeIndex: number): GomlNode; public get(i1?: number, i2?: number): GomlNode { - if (i1 === void 0) { + if (i1 === undefined) { const first = this.first(); if (!first) { throw new Error("this NodeInterface is empty."); } else { return first; } - } else if (i2 === void 0) { + } else if (i2 === undefined) { if (this.count <= i1) { throw new Error("index out of range."); } diff --git a/test/Converters/BooleanConverterTest.ts b/test/Converters/BooleanConverterTest.ts index 313f2fb71..cb4d94f5b 100644 --- a/test/Converters/BooleanConverterTest.ts +++ b/test/Converters/BooleanConverterTest.ts @@ -7,10 +7,10 @@ test("BooleanConverter should convert collectly", t => { t.truthy(BooleanConverter("true") === true); t.truthy(BooleanConverter("false") === false); - t.truthy(BooleanConverter("aaaa") === void 0); - t.truthy(BooleanConverter("False") === void 0); - t.truthy(BooleanConverter("True") === void 0); - t.truthy(BooleanConverter("") === void 0); - t.truthy(BooleanConverter(null) === void 0); - t.truthy(BooleanConverter(123) === void 0); + t.truthy(BooleanConverter("aaaa") === undefined); + t.truthy(BooleanConverter("False") === undefined); + t.truthy(BooleanConverter("True") === undefined); + t.truthy(BooleanConverter("") === undefined); + t.truthy(BooleanConverter(null) === undefined); + t.truthy(BooleanConverter(123) === undefined); }); diff --git a/test/Converters/EnumConverterTest.ts b/test/Converters/EnumConverterTest.ts index 5b0693aa0..f4a84dd21 100644 --- a/test/Converters/EnumConverterTest.ts +++ b/test/Converters/EnumConverterTest.ts @@ -11,14 +11,14 @@ const mockAttrDec = { "second": 2, "third": 3 } - } + }, } as any; const invalidMockAttrDec = { declaration: { coverter: "Enum", default: "Hoge" - } + }, } as any; test("verify works correctly", t => { @@ -39,8 +39,8 @@ test("EnumConverter should convert collectly", t => { t.truthy(EnumConverter.convert(3, mockAttrDec) === 3); t.truthy(EnumConverter.convert(4, mockAttrDec) === 4); t.truthy(EnumConverter.convert(null, mockAttrDec) === null); - t.truthy(EnumConverter.convert({}, mockAttrDec) === void 0); - t.truthy(EnumConverter.convert(false, mockAttrDec) === void 0); + t.truthy(EnumConverter.convert({}, mockAttrDec) === undefined); + t.truthy(EnumConverter.convert(false, mockAttrDec) === undefined); t.throws(() => { EnumConverter.convert("false", mockAttrDec); diff --git a/test/Converters/NumberConverterTest.ts b/test/Converters/NumberConverterTest.ts index 80ffa8a62..7c6ba883b 100644 --- a/test/Converters/NumberConverterTest.ts +++ b/test/Converters/NumberConverterTest.ts @@ -1,5 +1,5 @@ -import NumberConverter from "../../src/Converters/NumberConverter"; import test from "ava"; +import NumberConverter from "../../src/Converters/NumberConverter"; import TestEnvManager from "../TestEnvManager"; TestEnvManager.init(); @@ -9,6 +9,6 @@ test("NumberConverter should convert collectly", t => { t.truthy(NumberConverter("123") === 123); t.truthy(NumberConverter(null) === null); t.truthy(NumberConverter([123]) === 123); - t.truthy(NumberConverter("this string can not convert to number") === void 0); - t.truthy(NumberConverter([123, 456]) === void 0); + t.truthy(NumberConverter("this string can not convert to number") === undefined); + t.truthy(NumberConverter([123, 456]) === undefined); }); diff --git a/test/Core/AttributeManagerTest.ts b/test/Core/AttributeManagerTest.ts index 1ba94ca90..4d739059f 100644 --- a/test/Core/AttributeManagerTest.ts +++ b/test/Core/AttributeManagerTest.ts @@ -28,7 +28,7 @@ const genAM = () => { test("check init for attribute manager", (t) => { const am = genAM(); let count = 0; - for (let key in am["_attributesFQNMap"]) { + for (const key in am["_attributesFQNMap"]) { count += am["_attributesFQNMap"][key].length; } t.truthy(count === 3); @@ -38,18 +38,18 @@ test("check init for attribute manager", (t) => { test("simple addAttribute should works correctly", (t) => { const am = genAM(); let l = 0; - for (let key in am["_attributesFQNMap"]) { + for (const key in am["_attributesFQNMap"]) { l += am["_attributesFQNMap"][key].length; } am.addAttribute(genAttr(ns1)); let count = 0; - for (let key in am["_attributesFQNMap"]) { + for (const key in am["_attributesFQNMap"]) { count += am["_attributesFQNMap"][key].length; } t.truthy(count === l + 1); am.addAttribute(genAttr(ns1)); count = 0; - for (let key in am["_attributesFQNMap"]) { + for (const key in am["_attributesFQNMap"]) { count += am["_attributesFQNMap"][key].length; } t.truthy(count === l + 2); @@ -60,7 +60,7 @@ test("addAttribute with value/watch buffers should works correctly", (t) => { const am = genAM(); am.setAttribute(fqn, "hogehoge"); t.truthy(am.getAttribute(fqn) === "hogehoge"); - let attr = genAttr(Identity.fromFQN(fqn)); + const attr = genAttr(Identity.fromFQN(fqn)); am.addAttribute(attr); t.truthy(am.getAttribute(fqn) === "hogehoge"); t.truthy(attr.Value === "hogehoge"); @@ -81,7 +81,7 @@ test("addAttribute with value/watch buffers should works correctly", (t) => { am.setAttribute(attrRaw.name.fqn, "called"); t.truthy("not called" === spy.args[0][0]); - t.truthy(void 0 === spy.args[0][1]); + t.truthy(undefined === spy.args[0][1]); t.truthy(attrRaw === spy.args[0][2]); t.truthy("called" === spy.args[1][0]); diff --git a/test/Core/AttributeTest.ts b/test/Core/AttributeTest.ts index 869c168c8..7fcec691b 100644 --- a/test/Core/AttributeTest.ts +++ b/test/Core/AttributeTest.ts @@ -38,7 +38,7 @@ test("get/set value should works correctly.", t => { idAttr.Value = 123; t.truthy(idAttr.Value === "123"); t.throws(() => { - idAttr.Value = void 0; + idAttr.Value = undefined; }); }); @@ -90,7 +90,7 @@ test("generateAttributeForComponent should works correctly", t => { t.notThrows(() => { // default value undefined is OK. Attribute.generateAttributeForComponent("fuga", { converter: "Number", - default: void 0 + default: undefined }, baseComponent); }); }); @@ -99,7 +99,7 @@ test("boundTo should works correctly", t => { const idAttr = rootNode.getAttributeRaw("id"); const baseComponent = rootNode.getComponent(GrimoireComponent); const obj = { id: "hoge" }; - idAttr.boundTo("id", obj); + idAttr.bindTo("id", obj); t.truthy(obj.id === idAttr.Value); idAttr.Value = "value"; t.truthy(obj.id === idAttr.Value); @@ -113,7 +113,7 @@ test("generateAttributeForComponent should works correctly (use dom value)", t = const attr1 = Attribute.generateAttributeForComponent("ns1.hoge", { converter: "Number", - default: 42 + default: 42, }, baseComponent); t.throws(() => { @@ -126,17 +126,17 @@ test("generateAttributeForComponent should works correctly (use dom value)", t = test("generateAttributeForComponent should works correctly (use node value)", t => { GrimoireInterface.registerNode("node1", [], { "ns1.hoge": 52 }); - let rootNode = TestUtil.DummyTreeInit(``); - let node = rootNode.children[0]; + const rootNode = TestUtil.DummyTreeInit(``); + const node = rootNode.children[0]; const baseComponent = node.getComponent(GrimoireComponent); const attr1 = Attribute.generateAttributeForComponent("ns1.hoge", { converter: "Number", - default: 42 + default: 42, }, baseComponent); const attr2 = Attribute.generateAttributeForComponent("ns2.hoge", { converter: "Number", - default: 42 + default: 42, }, baseComponent); attr1.resolveDefaultValue({}); @@ -145,17 +145,17 @@ test("generateAttributeForComponent should works correctly (use node value)", t test("generateAttributeForComponent should works correctly (use declaration default value)", t => { GrimoireInterface.registerNode("node1"); - let rootNode = TestUtil.DummyTreeInit(``); - let node = rootNode.children[0]; + const rootNode = TestUtil.DummyTreeInit(""); + const node = rootNode.children[0]; const baseComponent = node.getComponent(GrimoireComponent); const attr1 = Attribute.generateAttributeForComponent("ns1.hoge", { converter: "Number", - default: 42 + default: 42, }, baseComponent); const attr2 = Attribute.generateAttributeForComponent("ns2.hoge", { converter: "Number", - default: 42 + default: 42, }, baseComponent); attr1.resolveDefaultValue({}); diff --git a/test/Core/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts index 1a0feef78..f1de7a7c0 100644 --- a/test/Core/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -145,7 +145,7 @@ test("Nodes should be mounted after loading", (t) => { }); }); test("attribute default value work correctly1", (t) => { - t.truthy(rootNode.getAttribute("id") !== void 0); + t.truthy(rootNode.getAttribute("id") !== undefined); t.truthy(rootNode.getAttribute("id") === null); }); @@ -453,7 +453,7 @@ test("get/setAttribute should work correctly 7", t => { }); (c as any).__addAttribute("hoge", { converter: "String", - default: "3" + default: "3", }); let att = rootNode.getAttribute("ns1.hoge"); t.truthy(att === "1"); @@ -471,14 +471,14 @@ test("get/setAttribute should work correctly 8", t => { rootNode.setAttribute("ns2.hoge", "ccc"); (c as any).__addAttribute("ns1.hoge", { // matchs hoge but not matchs ns2.hoge. converter: "String", - default: "1" + default: "1", }); let att = rootNode.getAttribute("ns1.hoge"); t.truthy(att === "bbb"); (c as any).__addAttribute("ns2.hoge", { converter: "String", - default: "2" + default: "2", }); t.throws(() => { rootNode.getAttribute("hoge"); @@ -488,7 +488,7 @@ test("get/setAttribute should work correctly 8", t => { (c as any).__addAttribute("hoge", { converter: "String", - default: "3" + default: "3", }); att = rootNode.getAttribute(Identity.fromFQN(c.name.fqn + ".hoge")); t.truthy(att === "3"); @@ -498,7 +498,7 @@ test("addNode works correctly", (t) => { const testNode2 = rootNode.children[0].children[0]; testNode2.addChildByName("test-node2", { testAttr2: "ADDEDNODE", - id: "idtest" + id: "idtest", }); const child = testNode2.children[0]; t.truthy(child.name.name === "test-node2"); @@ -513,7 +513,7 @@ test("null should be \"\" as id and classname", async (t) => { testNode2.addChildByName("test-node2", { testAttr2: "ADDEDNODE", id: null, - class: null + class: null, }); const child = testNode2.children[0]; t.truthy(child.name.name === "test-node2"); @@ -531,7 +531,7 @@ test("null should be \"\" as id and classname", async (t) => { testNode2.addChildByName("test-node2", { testAttr2: "ADDEDNODE", id: null, - class: null + class: null, }); const child = testNode2.children[0]; t.truthy(child.name.name === "test-node2"); diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index a345475f6..940112f09 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -154,7 +154,7 @@ test("registerComponent by class works correctly", async (t) => { }, testOverride: { converter: "String", - default: "ccc" + default: "ccc", } }; public fuga = 7; @@ -295,12 +295,12 @@ test("registerNode/Component works correctly.", async t => { } }); await GrimoireInterface.resolvePlugins(); - let a1 = GrimoireInterface.nodeDeclarations.get("a1"); + const a1 = GrimoireInterface.nodeDeclarations.get("a1"); let a2 = GrimoireInterface.nodeDeclarations.get("a2"); - let a3 = GrimoireInterface.nodeDeclarations.get("a3"); - t.truthy(a1.defaultComponentsActual.toArray().length === 1); // grimoireCompone - t.truthy(a2.defaultComponentsActual.toArray().length === 2); // grimoireCompone - t.truthy(a3.defaultComponentsActual.toArray().length === 2); // grimoireCompone + const a3 = GrimoireInterface.nodeDeclarations.get("a3"); + t.truthy(a1.requiredComponentsActual.toArray().length === 1); // grimoireCompone + t.truthy(a2.requiredComponentsActual.toArray().length === 2); // grimoireCompone + t.truthy(a3.requiredComponentsActual.toArray().length === 2); // grimoireCompone // console.log(a2.idResolver) t.truthy(a2.idResolver.resolve(Namespace.define("hoge")) === "grimoirejs.Hoge.hoge"); @@ -317,10 +317,10 @@ test("throw error on attempt registerComponent/Node by duplicate name.", t => { }); }); -test("register and resolvePlugins works preperly", async () => { +test("register and resolvePlugins works preperly", async() => { const spy1 = spy(); const spy2 = spy(); - const wrapPromise: any = function (s) { + const wrapPromise: any = function(s) { return () => { return new Promise(resolve => { s(); diff --git a/test/Tools/EnsureTest.ts b/test/Tools/EnsureTest.ts index 6d8691578..aa33abc1b 100644 --- a/test/Tools/EnsureTest.ts +++ b/test/Tools/EnsureTest.ts @@ -1,9 +1,9 @@ import test from "ava"; -import Ensure from "../../src/Tools/Ensure"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import IdentityMap from "../../src/Core/IdentityMap"; import Identity from "../../src/Core/Identity"; +import IdentityMap from "../../src/Core/IdentityMap"; import Namespace from "../../src/Core/Namespace"; +import Ensure from "../../src/Tools/Ensure"; test.beforeEach(() => { Identity.clear(); @@ -44,7 +44,7 @@ test("Ensure passed array are transformed into NSIdentity[]", (t) => { }); test("Ensure passed object are transformed into NSDictionary", (t) => { - let transformed = Ensure.tobeIdentityMap(void 0); + let transformed = Ensure.tobeIdentityMap(undefined); t.truthy(transformed instanceof IdentityMap); const obj = {}; obj[Identity.fromFQN("Hello").fqn] = "test1"; From 61162ccb2a7a0735e394dcd38f92160a4498807f Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 13 Oct 2017 08:13:40 +0900 Subject: [PATCH 043/146] [fix] rename function --- src/main.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main.ts b/src/main.ts index 9e6f43a82..3c63b3052 100644 --- a/src/main.ts +++ b/src/main.ts @@ -15,7 +15,7 @@ class GrimoireInitializer { try { GrimoireInitializer._notifyLibraryLoadingToWindow(); GrimoireInitializer._copyGLConstants(); - GrimoireInitializer._injectDependency(); + GrimoireInitializer._injectEnvironment(); GrimoireInterface.initialize(); await GrimoireInitializer._waitForDOMLoading(); GrimoireInitializer._logVersions(); @@ -31,7 +31,7 @@ class GrimoireInitializer { /** * inject browser environment */ - private static _injectDependency(): void { + private static _injectEnvironment(): void { Environment.DomParser = new DOMParser(); Environment.document = document; Environment.Node = Node; @@ -49,7 +49,7 @@ class GrimoireInitializer { return; } // Otherwise like ""Safari"" - for (let propName in WebGLRenderingContext.prototype) { + for (const propName in WebGLRenderingContext.prototype) { if (/^[A-Z]/.test(propName)) { const property = (WebGLRenderingContext.prototype as any)[propName]; (WebGLRenderingContext as any)[propName] = property; @@ -76,7 +76,7 @@ class GrimoireInitializer { } let log = `%cGrimoire.js v${(gr as any)["__VERSION__"]}\nplugins:\n\n`; let i = 1; - for (let key in gr.lib) { + for (const key in gr.lib) { const plugin = gr.lib[key]; log += ` ${i} : ${plugin.__NAME__ || key}@${plugin.__VERSION__}\n`; i++; @@ -88,7 +88,7 @@ class GrimoireInitializer { private static _notifyLibraryLoadingToWindow(): void { window.postMessage({ $source: "grimoirejs", - $messageType: "library-loading" + $messageType: "library-loading", }, "*"); } } @@ -96,7 +96,7 @@ class GrimoireInitializer { /** * Just start the process. */ -export default function (): typeof GrimoireInterface { +export default function(): typeof GrimoireInterface { GrimoireInitializer.initialize(); GrimoireInterface.noConflictPreserve = (window as any)["gr"]; return (window as any)["gr"] = (window as any)["GrimoireJS"] = GrimoireInterface; From 97cf84ea40e62631225bc4f3b35874fa6afa1d19 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 15 Oct 2017 21:54:14 +0900 Subject: [PATCH 044/146] fix: remove unuse files --- .jsbeautifyrc | 17 ----------------- .jshintrc | 3 --- 2 files changed, 20 deletions(-) delete mode 100644 .jsbeautifyrc delete mode 100644 .jshintrc diff --git a/.jsbeautifyrc b/.jsbeautifyrc deleted file mode 100644 index bc2949c26..000000000 --- a/.jsbeautifyrc +++ /dev/null @@ -1,17 +0,0 @@ -{ -"indent_size": 2, -"indent_char": " ", -"indent_level": 0, -"indent_with_tabs": false, -"preserve_newlines": true, -"max_preserve_newlines": 10, -"space_after_anon_function": false, -"brace_style": "collapse-preserve-inline", -"keep_array_indentation": false, -"keep_function_indentation": false, -"space_before_conditional": true, -"break_chained_methods": false, -"eval_code": false, -"unescape_strings": false, -"wrap_line_length": 0 -} diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index d97c7c49e..000000000 --- a/.jshintrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "esnext":true -} From d68fffb2c05a7b003a67d65c88f0f0f14bb21674 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 15 Oct 2017 22:12:34 +0900 Subject: [PATCH 045/146] fix: getAtribute() to take type parameter --- src/Core/Component.ts | 2 +- src/Core/GomlNode.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Core/Component.ts b/src/Core/Component.ts index 2af6516c8..fca5a81e5 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -116,7 +116,7 @@ export default class Component extends IDObject { * get attribute value. * @param name */ - public getAttribute(name: Name): any { + public getAttribute(name: Name): T { if (typeof name === "string" && Ensure.checkFQNString(name)) { name = `${this.name.fqn}.${name}`; // TODO: test } diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index cee2a75b4..eb216cf9a 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -414,7 +414,7 @@ export default class GomlNode extends EEObject { * get attribute value. * @param attrName */ - public getAttribute(attrName: Name): any { + public getAttribute(attrName: Name): T { return this._attributeManager.getAttribute(attrName); } From 39c14796f6f2a00597ba3ea11859f18e73ebd3ff Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 15 Oct 2017 22:23:18 +0900 Subject: [PATCH 046/146] fix: remove Component.__addAtribute() --- src/Core/Component.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/Core/Component.ts b/src/Core/Component.ts index fca5a81e5..41e6d6161 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -215,11 +215,6 @@ export default class Component extends IDObject { } } - protected __addAtribute(name: string, attribute: IAttributeDeclaration): void { - console.warn(`${this.name.fqn} is using '__addAtribute()'.\nthis method is deprecated because typo.\nplease use '__addAttribute() instead of.'`); - this.__addAttribute(name, attribute); - } - /** * Add additional attribute to this component. * @param {string} name [description] From fb41a3864fcb8837008d44cb1fcddd6e29cb717f Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 15 Oct 2017 22:24:12 +0900 Subject: [PATCH 047/146] fix: implement Component.__setCompanionWithSelfNS() --- src/Core/Component.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/Core/Component.ts b/src/Core/Component.ts index 41e6d6161..1ed5f3814 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -258,4 +258,13 @@ export default class Component extends IDObject { attr.bindTo(name); }); } + + /** + * set object to companion with identity that has same namespace as this component, and provided name. + * @param name + * @param value + */ + protected __setCompanionWithSelfNS(name: string, value: any) { + this.companion.set(this.name.ns.for(name), value); + } } From deee9003e43c565fab13116d3e2385519225cb3c Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 15 Oct 2017 23:03:30 +0900 Subject: [PATCH 048/146] fix: change signature IdentityMap.get() --- src/Core/Attribute.ts | 5 +++-- src/Core/Component.ts | 6 +++--- src/Core/GomlNode.ts | 3 +++ src/Core/IdentityMap.ts | 14 +++++++------- src/Core/NodeDeclaration.ts | 6 ++++++ test/Core/ComponentTest.ts | 20 ++++++++++---------- 6 files changed, 32 insertions(+), 22 deletions(-) diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index 0165db5b7..15ee17634 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -43,11 +43,12 @@ export default class Attribute { attr.component = component; attr.declaration = declaration; const converterName = Ensure.tobeNSIdentity(declaration.converter); - attr.converter = Environment.GrimoireInterface.converters.get(converterName); - if (attr.converter === undefined) { + const converter = Environment.GrimoireInterface.converters.get(converterName); + if (!converter) { // When the specified converter was not found throw new Error(`Specified converter ${converterName.name} was not found from registered converters.\n Component: ${attr.component.name.fqn}\n Attribute: ${attr.name.name}`); } + attr.converter = converter; attr.component.attributes.set(attr.name, attr); attr.converter.verify(attr); return attr; diff --git a/src/Core/Component.ts b/src/Core/Component.ts index 1ed5f3814..302303f15 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -132,8 +132,8 @@ export default class Component extends IDObject { * get attribute object instance. * @param name */ - public getAttributeRaw(name: Name): Attribute { - if (typeof name === "string" && Ensure.checkFQNString(name)) { + public getAttributeRaw(name: Name): Nullable { + if (typeof name === "string" && !Ensure.checkFQNString(name)) { name = `${this.name.fqn}.${name}`; // TODO: test } return this.attributes.get(name); @@ -242,7 +242,7 @@ export default class Component extends IDObject { throw new Error("can not remove attributes :" + name); } const attrId = this._additionalAttributesNames[index]; - this.node.removeAttribute(this.attributes.get(attrId)); + this.node.removeAttribute(this.attributes.get(attrId)!); this.attributes.delete(attrId); this._additionalAttributesNames.splice(index, 1); } else { diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index eb216cf9a..712992177 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -310,6 +310,9 @@ export default class GomlNode extends EEObject { */ public addChildByName(nodeName: Name, attributes: { [attrName: string]: any }): GomlNode { const nodeDec = GrimoireInterface.nodeDeclarations.get(nodeName); + if (!nodeDec) { + throw new Error(`In node ${this.name}: the node that attempted to add to child is not found.`); + } const node = new GomlNode(nodeDec); if (attributes) { for (const key in attributes) { diff --git a/src/Core/IdentityMap.ts b/src/Core/IdentityMap.ts index 9ef7b5353..fac10e66a 100644 --- a/src/Core/IdentityMap.ts +++ b/src/Core/IdentityMap.ts @@ -44,17 +44,17 @@ export default class IdentityMap { * return null if key is not exists. * @param name */ - public get(name: Name): V; - public get(element: Element): V; - public get(attribute: Attr): V; - public get(arg1: string | Element | Identity | Attr): Nullable { + public get(name: Name): Nullable; + public get(element: Element): Nullable; + public get(attribute: Attr): Nullable; + public get(arg1: string | Element | Identity | Attr): Nullable { if (!arg1) { throw new Error("NSDictionary.get() can not recieve args null or undefined."); } if (typeof arg1 === "string") { const fqn = Ensure.tobeFQN(arg1); if (fqn) { - return this._fqnObjectMap[fqn]; + return this._fqnObjectMap[fqn] as T; } const name = arg1.split("."); const res = this._idResolver.get(Namespace.defineByArray(name)); @@ -63,14 +63,14 @@ export default class IdentityMap { return null; // not exist. } if (res.length === 1) { - return this._fqnObjectMap[res[0]]; + return this._fqnObjectMap[res[0]] as T; } else { throw new Error(`Specified tag name ${arg1} is ambiguous to identify.`); } } else { if (arg1 instanceof Identity) { - return this._fqnObjectMap[arg1.fqn]; + return this._fqnObjectMap[arg1.fqn] as T; } else { if (arg1.namespaceURI) { return this.get(`${arg1.namespaceURI}.${arg1.localName!}`); diff --git a/src/Core/NodeDeclaration.ts b/src/Core/NodeDeclaration.ts index 0a020c520..dc820cad7 100644 --- a/src/Core/NodeDeclaration.ts +++ b/src/Core/NodeDeclaration.ts @@ -114,6 +114,9 @@ export default class NodeDeclaration { this._resolveInherites(); this._requiredComponentsActual.forEach(id => { const dec = GrimoireInterface.componentDeclarations.get(id); + if (!dec) { + throw new Error(`require component ${id} has not registerd. this node is ${this.name}.`); + } dec.idResolver.foreach(fqn => { this.idResolver.add(Identity.fromFQN(fqn)); }); @@ -130,6 +133,9 @@ export default class NodeDeclaration { return; } const superNode = GrimoireInterface.nodeDeclarations.get(this.superNode); + if (!superNode) { + throw new Error(`In node '${this.name.fqn}': super node ${this.superNode.fqn} is not found when resolving inherits, it has registerd correctry?`); + } superNode.resolveDependency(); const inheritedDefaultComponents = superNode.requiredComponentsActual; const inheritedDefaultAttribute = superNode.defaultAttributesActual; diff --git a/test/Core/ComponentTest.ts b/test/Core/ComponentTest.ts index 7fb4283e8..933b1139f 100644 --- a/test/Core/ComponentTest.ts +++ b/test/Core/ComponentTest.ts @@ -20,7 +20,7 @@ test("component poperties should be initialized correctly", (t) => { converter: "String", default: "super" } - } + }, }); GrimoireInterface.registerComponent({ componentName: "Hoge", @@ -33,7 +33,7 @@ test("component poperties should be initialized correctly", (t) => { converter: "String", default: "hoge" } - } + }, }, "Super"); const superComponentDec = GrimoireInterface.componentDeclarations.get("Super"); const hogeComponentDec = GrimoireInterface.componentDeclarations.get("Hoge"); @@ -55,26 +55,26 @@ test("get/set attribute should works correctly", (t) => { attributes: { superAttr1: { converter: "String", - default: "hoge" + default: "hoge", }, overrideAttr1: { converter: "String", - default: "super" - } - } + default: "super", + }, + }, }); GrimoireInterface.registerComponent({ componentName: "Hoge", attributes: { attr1: { converter: "String", - default: "hoge" + default: "hoge", }, overrideAttr1: { converter: "String", - default: "hoge" - } - } + default: "hoge", + }, + }, }, "Super"); const superComponentDec = GrimoireInterface.componentDeclarations.get("Super"); const hogeComponentDec = GrimoireInterface.componentDeclarations.get("Hoge"); From 9d3669dd74acb08993710278e1c472dc89bdd6f2 Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 20 Oct 2017 22:45:33 +0900 Subject: [PATCH 049/146] fix: component constructor can be used as requiredComponents for registerNode() --- src/Core/GrimoireInterfaceImpl.ts | 3 +-- src/Core/NodeDeclaration.ts | 7 ++++--- src/Tools/Ensure.ts | 5 ++--- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 5c44737fd..b409b5776 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -249,7 +249,7 @@ export default class GrimoireInterfaceImpl extends EEObject { */ public registerNode( name: Name, - requiredComponents: Name[] = [], + requiredComponents: (Name | Ctor)[] = [], defaults?: { [key: string]: any }, superNode?: Name, freezeAttributes?: Name[]): NodeDeclaration { @@ -261,7 +261,6 @@ export default class GrimoireInterfaceImpl extends EEObject { if (this.debug && !Utility.isKebabCase(registerId.name)) { console.warn(`node ${registerId.name} is registerd. but,it should be 'snake-case'.`); } - const declaration = new NodeDeclaration(registerId, requiredComponents || [], defaults || {}, superNode, freezeAttributes); this.nodeDeclarations.set(registerId, declaration); return declaration; diff --git a/src/Core/NodeDeclaration.ts b/src/Core/NodeDeclaration.ts index dc820cad7..4864a6fdb 100644 --- a/src/Core/NodeDeclaration.ts +++ b/src/Core/NodeDeclaration.ts @@ -1,7 +1,8 @@ import GrimoireInterface from "../Core/GrimoireInterface"; import Ensure from "../Tools/Ensure"; import IdResolver from "../Tools/IdResolver"; -import { Name } from "../Tools/Types"; +import { Ctor, Name } from "../Tools/Types"; +import Component from "./Component"; import Constants from "./Constants"; import Identity from "./Identity"; import IdentityMap from "./IdentityMap"; @@ -73,7 +74,7 @@ export default class NodeDeclaration { constructor( public name: Identity, - private _requiredComponents: Name[], + private _requiredComponents: (Name | Ctor)[], private _defaultAttributes: { [key: string]: any }, private _superNode?: Name, private _freezeAttributes: Name[] = []) { @@ -104,7 +105,7 @@ export default class NodeDeclaration { if (this._resolvedDependency) { return false; } - this.requiredComponents = new IdentitySet(this._requiredComponents.map(name => Ensure.tobeNSIdentity(name))); + this.requiredComponents = new IdentitySet(this._requiredComponents.map(name => Ensure.tobeComponentIdentity(name))); for (const key in this._defaultAttributes) { const value = this._defaultAttributes[key]; diff --git a/src/Tools/Ensure.ts b/src/Tools/Ensure.ts index 58f421f18..7e5d96847 100644 --- a/src/Tools/Ensure.ts +++ b/src/Tools/Ensure.ts @@ -23,14 +23,13 @@ export default class Ensure { if (typeof component === "function") { const obj = ComponentDeclaration.ctorMap.find(o => o.ctor === component); if (obj) { - component = obj.name; + return obj.name; } else { throw new Error("Specified constructor have not registered to current context."); } } else { - component = Ensure.tobeNSIdentity(component); + return Ensure.tobeNSIdentity(component); } - return component; } /** * Ensure specified str being string From 4da9baa3f7d7848c36c78a6b377977ebffe4dd0a Mon Sep 17 00:00:00 2001 From: moajo Date: Fri, 20 Oct 2017 23:06:25 +0900 Subject: [PATCH 050/146] fix: component test --- src/Components/GrimoireComponent.ts | 6 +++--- src/Core/Component.ts | 12 ++---------- test/Core/ComponentTest.ts | 24 ++++++++++++++++-------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Components/GrimoireComponent.ts b/src/Components/GrimoireComponent.ts index 8e5e19f20..a0b653d2d 100644 --- a/src/Components/GrimoireComponent.ts +++ b/src/Components/GrimoireComponent.ts @@ -35,13 +35,13 @@ export default class GrimoireComponent extends Component { protected $awake(): void { const node = this.node; node.resolveAttributesValue(); - this.getAttributeRaw("id").watch((attr) => { + this.getAttributeRaw("id")!.watch((attr) => { node.element.id = attr ? attr : ""; }, true, true); - this.getAttributeRaw("class").watch((attr) => { + this.getAttributeRaw("class")!.watch((attr) => { node.element.className = Array.isArray(attr) ? attr.join(" ") : ""; }, true, true); - this.getAttributeRaw("enabled").watch(attr => { + this.getAttributeRaw("enabled")!.watch(attr => { node["_enabled"] = attr; const p = node.parent; node.notifyActivenessUpdate(p ? p.isActive && node.enabled : node.enabled); diff --git a/src/Core/Component.ts b/src/Core/Component.ts index 302303f15..c0b703588 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -1,7 +1,6 @@ import IDObject from "../Base/IDObject"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; -import Ensure from "../Tools/Ensure"; import { GomlInterface, Name, Nullable } from "../Tools/Types"; import Utility from "../Tools/Utility"; import Attribute from "./Attribute"; @@ -103,12 +102,11 @@ export default class Component extends IDObject { * @param {any} value [description] */ public setAttribute(name: Name, value: any): void { - if (typeof name === "string" && Ensure.checkFQNString(name)) { - name = `${this.name.fqn}.${name}`; // TODO: test - } const attr = this.attributes.get(name); if (attr) { attr.Value = value; + } else { + throw new Error(`attribute ${name} is not defined in ${this.name.fqn}`); } } @@ -117,9 +115,6 @@ export default class Component extends IDObject { * @param name */ public getAttribute(name: Name): T { - if (typeof name === "string" && Ensure.checkFQNString(name)) { - name = `${this.name.fqn}.${name}`; // TODO: test - } const attr = this.getAttributeRaw(name); if (attr) { return attr.Value; @@ -133,9 +128,6 @@ export default class Component extends IDObject { * @param name */ public getAttributeRaw(name: Name): Nullable { - if (typeof name === "string" && !Ensure.checkFQNString(name)) { - name = `${this.name.fqn}.${name}`; // TODO: test - } return this.attributes.get(name); } diff --git a/test/Core/ComponentTest.ts b/test/Core/ComponentTest.ts index 933b1139f..55c051bff 100644 --- a/test/Core/ComponentTest.ts +++ b/test/Core/ComponentTest.ts @@ -1,6 +1,6 @@ import test from "ava"; -import TestEnvManager from "../TestEnvManager"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import TestEnvManager from "../TestEnvManager"; TestEnvManager.init(); @@ -14,12 +14,12 @@ test("component poperties should be initialized correctly", (t) => { attributes: { superAttr1: { converter: "String", - default: "hoge" + default: "hoge", }, overrideAttr1: { converter: "String", - default: "super" - } + default: "super", + }, }, }); GrimoireInterface.registerComponent({ @@ -27,12 +27,12 @@ test("component poperties should be initialized correctly", (t) => { attributes: { attr1: { converter: "String", - default: "hoge" + default: "hoge", }, overrideAttr1: { converter: "String", - default: "hoge" - } + default: "hoge", + }, }, }, "Super"); const superComponentDec = GrimoireInterface.componentDeclarations.get("Super"); @@ -84,7 +84,15 @@ test("get/set attribute should works correctly", (t) => { t.truthy(!hogeComponent.getAttributeRaw("notfound")); t.truthy(hogeComponent.getAttributeRaw("attr1")); - t.truthy(hogeComponent.getAttributeRaw("grimoirejs.attr1")); t.truthy(hogeComponent.getAttributeRaw("grimoirejs.Hoge.attr1")); + t.truthy(hogeComponent.getAttributeRaw("grimoirejs.attr1")); + t.truthy(hogeComponent.getAttributeRaw("_grimoirejs.Hoge.attr1")); + t.truthy(!hogeComponent.getAttributeRaw("_grimoirejs.attr1")); t.truthy(hogeComponent.getAttributeRaw("Hoge.attr1")); + + hogeComponent.setAttribute("attr1", "some value"); + t.truthy(hogeComponent.getAttribute("attr1") === "some value") + t.throws(() => { + hogeComponent.setAttribute("notfound", "some value"); + }); }); From f3af541ac414886ad2c74d2559ab4091eea15432 Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 21 Oct 2017 01:50:39 +0900 Subject: [PATCH 051/146] fix: add default argument value to GomlNode#addChildByName --- src/Core/GomlNode.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index 712992177..8aa30de74 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -308,7 +308,7 @@ export default class GomlNode extends EEObject { * @param {string | Identity} nodeName [description] * @param {any }} attributes [description] */ - public addChildByName(nodeName: Name, attributes: { [attrName: string]: any }): GomlNode { + public addChildByName(nodeName: Name, attributes: { [attrName: string]: any } = {}): GomlNode { const nodeDec = GrimoireInterface.nodeDeclarations.get(nodeName); if (!nodeDec) { throw new Error(`In node ${this.name}: the node that attempted to add to child is not found.`); From 288a7257b10ee206afd767fa73dcbb590f0ffe24 Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 21 Oct 2017 09:48:08 +0900 Subject: [PATCH 052/146] fix: add assertion to Attribute#bindTo --- src/Core/Attribute.ts | 3 +++ src/Tools/Utility.ts | 12 ++++++++++++ test/Core/AttributeTest.ts | 34 ++++++++++++++++------------------ 3 files changed, 31 insertions(+), 18 deletions(-) diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index 15ee17634..8718655c1 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -6,6 +6,7 @@ import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import Ensure from "../Tools/Ensure"; import IdResolver from "../Tools/IdResolver"; import { GomlInterface, Name, Nullable } from "../Tools/Types"; +import Utility from "../Tools/Utility"; import Component from "./Component"; /** @@ -177,6 +178,8 @@ export default class Attribute { * @param {any} targetObject [description] */ public bindTo(variableName: string, targetObject: any = this.component): void { + Utility.assert(!!variableName, `${this.name}: variableName cannot be null when call Attribute.bindTo.`); + Utility.assert(!!targetObject, `${this.name}: targetObject cannot be null when call Attribute.bindTo.`); if (targetObject[variableName]) { console.warn(`component field ${variableName} is already defined.`); } diff --git a/src/Tools/Utility.ts b/src/Tools/Utility.ts index 3785d861a..a034b6652 100644 --- a/src/Tools/Utility.ts +++ b/src/Tools/Utility.ts @@ -143,4 +143,16 @@ export default class Utility { } return attributes; } + + /** + * Internal use! + * throw error message if first argument is not TRUE. + * @param shouldTrue + * @param errorMessage + */ + public static assert(shouldTrue: boolean, errorMessage: string) { + if (!shouldTrue) { + throw new Error(errorMessage); + } + } } diff --git a/test/Core/AttributeTest.ts b/test/Core/AttributeTest.ts index 7fcec691b..35dabe2dd 100644 --- a/test/Core/AttributeTest.ts +++ b/test/Core/AttributeTest.ts @@ -1,16 +1,15 @@ -import Attribute from "../../src/Core/Attribute"; +import test from "ava"; +import { assert, spy } from "sinon"; import GrimoireComponent from "../../src/Components/GrimoireComponent"; +import Attribute from "../../src/Core/Attribute"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Identity from "../../src/Core/Identity"; -import test from "ava"; import TestEnvManager from "../TestEnvManager"; import TestUtil from "../TestUtil"; -import { assert, spy } from "sinon"; - TestEnvManager.init(); -const GOML = ``; +const GOML = ""; test.beforeEach(async () => { GrimoireInterface.clear(); @@ -18,7 +17,7 @@ test.beforeEach(async () => { }); test("attibute poperties should be initialized correctly", (t) => { - let rootNode = TestUtil.DummyTreeInit(GOML); + const rootNode = TestUtil.DummyTreeInit(GOML); const idAttr = rootNode.getAttributeRaw("id"); const baseComponent = rootNode.getComponent(GrimoireComponent); @@ -29,7 +28,7 @@ test("attibute poperties should be initialized correctly", (t) => { }); test("get/set value should works correctly.", t => { - let rootNode = TestUtil.DummyTreeInit(GOML); + const rootNode = TestUtil.DummyTreeInit(GOML); const idAttr = rootNode.getAttributeRaw("id"); const baseComponent = rootNode.getComponent(GrimoireComponent); t.truthy(idAttr.Value === null); @@ -43,7 +42,7 @@ test("get/set value should works correctly.", t => { }); test("watch/unwatch should works correctly", t => { - let rootNode = TestUtil.DummyTreeInit(GOML); + const rootNode = TestUtil.DummyTreeInit(GOML); const idAttr = rootNode.getAttributeRaw("id"); const baseComponent = rootNode.getComponent(GrimoireComponent); const s = spy(); @@ -64,14 +63,13 @@ test("watch/unwatch should works correctly", t => { assert.notCalled(s); }); - test("generateAttributeForComponent should works correctly", t => { - let rootNode = TestUtil.DummyTreeInit(GOML); + const rootNode = TestUtil.DummyTreeInit(GOML); const idAttr = rootNode.getAttributeRaw("id"); const baseComponent = rootNode.getComponent(GrimoireComponent); const hogeAttr = Attribute.generateAttributeForComponent("hoge", { converter: "Number", - default: 42 + default: 42, }, baseComponent); t.throws(() => { // not resolve default value yet baseComponent.getAttribute("hoge"); @@ -84,18 +82,18 @@ test("generateAttributeForComponent should works correctly", t => { t.throws(() => { // converter can not resolve. Attribute.generateAttributeForComponent("fuga", { converter: "False", - default: 42 + default: 42, }, baseComponent); }); t.notThrows(() => { // default value undefined is OK. Attribute.generateAttributeForComponent("fuga", { converter: "Number", - default: undefined + default: undefined, }, baseComponent); }); }); test("boundTo should works correctly", t => { - let rootNode = TestUtil.DummyTreeInit(GOML); + const rootNode = TestUtil.DummyTreeInit(GOML); const idAttr = rootNode.getAttributeRaw("id"); const baseComponent = rootNode.getComponent(GrimoireComponent); const obj = { id: "hoge" }; @@ -107,8 +105,8 @@ test("boundTo should works correctly", t => { test("generateAttributeForComponent should works correctly (use dom value)", t => { GrimoireInterface.registerNode("node1", [], { "ns1.hoge": 52 }); - let rootNode = TestUtil.DummyTreeInit(``); - let node = rootNode.children[0]; + const rootNode = TestUtil.DummyTreeInit(""); + const node = rootNode.children[0]; const baseComponent = node.getComponent(GrimoireComponent); const attr1 = Attribute.generateAttributeForComponent("ns1.hoge", { @@ -117,7 +115,7 @@ test("generateAttributeForComponent should works correctly (use dom value)", t = }, baseComponent); t.throws(() => { - attr1.resolveDefaultValue({ "hoge": "43", "ns1.hoge": "44" }); // ambiguous + attr1.resolveDefaultValue({ hoge: "43", "ns1.hoge": "44" }); // ambiguous }); attr1.resolveDefaultValue({ "ns1.hoge": "43" }); @@ -126,7 +124,7 @@ test("generateAttributeForComponent should works correctly (use dom value)", t = test("generateAttributeForComponent should works correctly (use node value)", t => { GrimoireInterface.registerNode("node1", [], { "ns1.hoge": 52 }); - const rootNode = TestUtil.DummyTreeInit(``); + const rootNode = TestUtil.DummyTreeInit(""); const node = rootNode.children[0]; const baseComponent = node.getComponent(GrimoireComponent); From beb70f9c18fefc3ca6d497973a94bccde4e3c1a9 Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 21 Oct 2017 12:38:39 +0900 Subject: [PATCH 053/146] feat: Attribute generics --- src/Core/Attribute.ts | 28 +++++++------ src/Core/Component.ts | 21 ++++++++-- src/Core/ComponentDeclaration.ts | 1 + .../IAttributeConverterDeclaration.ts | 6 +-- src/Interface/IAttributeDeclaration.ts | 5 ++- src/Tools/Ensure.ts | 21 ++++++++++ src/Tools/Utility.ts | 2 +- test/Core/ComponentTest.ts | 42 ++++++++++++++++++- test/TestEnvManager.ts | 4 +- test/TestUtil.ts | 20 ++++----- 10 files changed, 114 insertions(+), 36 deletions(-) diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index 8718655c1..c1e7510a3 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -5,14 +5,14 @@ import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDecl import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import Ensure from "../Tools/Ensure"; import IdResolver from "../Tools/IdResolver"; -import { GomlInterface, Name, Nullable } from "../Tools/Types"; +import { GomlInterface, Name, Nullable, Undef } from "../Tools/Types"; import Utility from "../Tools/Utility"; import Component from "./Component"; /** * Manage a attribute attached to components. */ -export default class Attribute { +export default class Attribute { /** * convert value by provided converter. @@ -38,20 +38,22 @@ export default class Attribute { * @param {ConverterBase} converter Converter of this attribute. * @param {boolean} constant Whether this attribute is immutable or not. False as default. */ - public static generateAttributeForComponent(name: string, declaration: IAttributeDeclaration, component: Component): Attribute { - const attr = new Attribute(); + public static generateAttributeForComponent(name: string, declaration: IAttributeDeclaration, component: Component): Attribute { + const attr = new Attribute(); attr.name = Identity.fromFQN(`${component.name.fqn}.${name}`); attr.component = component; attr.declaration = declaration; - const converterName = Ensure.tobeNSIdentity(declaration.converter); + const converterName = Ensure.tobeCnverterIdentity(declaration.converter); const converter = Environment.GrimoireInterface.converters.get(converterName); if (!converter) { // When the specified converter was not found throw new Error(`Specified converter ${converterName.name} was not found from registered converters.\n Component: ${attr.component.name.fqn}\n Attribute: ${attr.name.name}`); } - attr.converter = converter; + attr.converter = converter as IAttributeConverterDeclaration; attr.component.attributes.set(attr.name, attr); - attr.converter.verify(attr); + if (attr.converter.verify) { + attr.converter.verify(attr); + } return attr; } @@ -71,7 +73,7 @@ export default class Attribute { * A function to convert any values into ideal type. * @type {AttributeConverter} */ - public converter: IAttributeConverterDeclaration; + public converter: IAttributeConverterDeclaration; /** * A component reference that this attribute is bound to. @@ -89,13 +91,13 @@ export default class Attribute { */ private _value: any; - private _lastValuete: any; + private _lastValuete: T; /** * List of functions that is listening changing values. */ - private _observers: ((newValue: any, oldValue: any, attr: Attribute) => void)[] = []; - private _ignoireActivenessObservers: ((newValue: any, oldValue: any, attr: Attribute) => void)[] = []; + private _observers: ((newValue: T, oldValue: Undef, attr: Attribute) => void)[] = []; + private _ignoireActivenessObservers: ((newValue: T, oldValue: Undef, attr: Attribute) => void)[] = []; /** * Goml tree interface which contains the component this attribute bound to. @@ -142,7 +144,7 @@ export default class Attribute { * @param {(attr: Attribute) => void} handler handler the handler you want to add. * @param {boolean = false} callFirst whether that handler should be called first time. */ - public watch(watcher: (newValue: any, oldValue: any, attr: Attribute) => void, immedateCalls = false, ignoireActiveness = false): void { + public watch(watcher: (newValue: T, oldValue: Undef, attr: Attribute) => void, immedateCalls = false, ignoireActiveness = false): void { if (ignoireActiveness) { this._ignoireActivenessObservers.push(watcher); } else { @@ -250,7 +252,7 @@ export default class Attribute { this.Value = this.declaration.default; } - private _valuate(raw: any): any { + private _valuate(raw: any): T { const v = this.converter.convert(raw, this); if (v === undefined) { const errorMessage = `Converting attribute value failed.\n\n* input : ${raw}\n* Attribute(Attribute FQN) : ${this.name.name}(${this.name.fqn})\n* Component : ${this.component.name.name}(${this.component.name.fqn})\n* Node(Node FQN) : ${this.component.node.name.name}(${this.component.node.name.fqn})\n* Converter : ${this.declaration.converter}\n\n* Structure map:\n${this.component.node.toStructualString(`--------------Error was thrown from '${this.name.name}' of this node.`)}`; diff --git a/src/Core/Component.ts b/src/Core/Component.ts index c0b703588..8a7f85cba 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -1,9 +1,11 @@ import IDObject from "../Base/IDObject"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; +import Ensure from "../Tools/Ensure"; import { GomlInterface, Name, Nullable } from "../Tools/Types"; import Utility from "../Tools/Utility"; import Attribute from "./Attribute"; +import ComponentDeclaration from "./ComponentDeclaration"; import Constants from "./Constants"; import GomlNode from "./GomlNode"; import Identity from "./Identity"; @@ -46,6 +48,11 @@ export default class Component extends IDObject { */ public disposed = false; + /** + * component declaration object. + */ + public declaration: ComponentDeclaration; + /** * Flag that this component is activated or not. * @type {boolean} @@ -114,7 +121,7 @@ export default class Component extends IDObject { * get attribute value. * @param name */ - public getAttribute(name: Name): T { + public getAttribute(name: Name | IAttributeDeclaration): T { const attr = this.getAttributeRaw(name); if (attr) { return attr.Value; @@ -127,8 +134,16 @@ export default class Component extends IDObject { * get attribute object instance. * @param name */ - public getAttributeRaw(name: Name): Nullable { - return this.attributes.get(name); + public getAttributeRaw(name: Name | IAttributeDeclaration): Nullable> { + if (Ensure.isName(name)) { + return this.attributes.get(name); + } + for (const key in this.declaration.attributes) { + if (this.declaration.attributes[key] === name) { + return this.getAttributeRaw(key); + } + } + return null; } /** diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index 23f95f760..b3a6cfdb8 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -81,6 +81,7 @@ export default class ComponentDeclaration { component.name = this.name; component.element = componentElement; component.attributes = new IdentityMap(); + component.declaration = this; for (const key in this.attributes) { Attribute.generateAttributeForComponent(key, this.attributes[key], component); } diff --git a/src/Interface/IAttributeConverterDeclaration.ts b/src/Interface/IAttributeConverterDeclaration.ts index b297f4ca1..3bb9fa67f 100644 --- a/src/Interface/IAttributeConverterDeclaration.ts +++ b/src/Interface/IAttributeConverterDeclaration.ts @@ -4,9 +4,9 @@ import { Name } from "../Tools/Types"; /** * interface for converter declaration */ -export default interface IAttributeConverterDeclaration { +export default interface IAttributeConverterDeclaration { name: Name; [params: string]: any; - verify(attr: Attribute): void; // throw error if attribute is not satisfy condition converter needed. - convert(val: any, attr: Attribute): any; + verify?(attr: Attribute): void; // throw error if attribute is not satisfy condition converter needed. + convert(val: any, attr: Attribute): T | undefined; } diff --git a/src/Interface/IAttributeDeclaration.ts b/src/Interface/IAttributeDeclaration.ts index ade9b349b..2fbfdf1b5 100644 --- a/src/Interface/IAttributeDeclaration.ts +++ b/src/Interface/IAttributeDeclaration.ts @@ -1,10 +1,11 @@ import { Name } from "../Tools/Types"; +import IAttributeConverterDeclaration from "./IAttributeConverterDeclaration"; /** * interface for attribute declaration */ -export default interface IAttributeDeclaration { - converter: Name; +export default interface IAttributeDeclaration { + converter: Name | IAttributeConverterDeclaration; default: any; [parameters: string]: any; } diff --git a/src/Tools/Ensure.ts b/src/Tools/Ensure.ts index 7e5d96847..2b9685106 100644 --- a/src/Tools/Ensure.ts +++ b/src/Tools/Ensure.ts @@ -3,6 +3,7 @@ import ComponentDeclaration from "../Core/ComponentDeclaration"; import Environment from "../Core/Environment"; import Identity from "../Core/Identity"; import IdentityMap from "../Core/IdentityMap"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import { ComponentRegistering, Ctor, @@ -77,6 +78,26 @@ export default class Ensure { } } + /** + * check argument is Name. + * that is argument is string or instance of Identity. + * @param obj + */ + public static isName(obj: any): obj is Name { + return typeof obj === "string" || obj instanceof Identity; + } + + /** + * Internal use! + * @param identity + */ + public static tobeCnverterIdentity(identity: Name | IAttributeConverterDeclaration): Identity { + if (Ensure.isName(identity)) { + return Ensure.tobeNSIdentity(identity); + } + return Ensure.tobeNSIdentity(identity.name); + } + /** * Internal use! * @param names diff --git a/src/Tools/Utility.ts b/src/Tools/Utility.ts index a034b6652..9f782c65a 100644 --- a/src/Tools/Utility.ts +++ b/src/Tools/Utility.ts @@ -147,7 +147,7 @@ export default class Utility { /** * Internal use! * throw error message if first argument is not TRUE. - * @param shouldTrue + * @param shouldTrue * @param errorMessage */ public static assert(shouldTrue: boolean, errorMessage: string) { diff --git a/test/Core/ComponentTest.ts b/test/Core/ComponentTest.ts index 55c051bff..96efa35f0 100644 --- a/test/Core/ComponentTest.ts +++ b/test/Core/ComponentTest.ts @@ -91,8 +91,48 @@ test("get/set attribute should works correctly", (t) => { t.truthy(hogeComponent.getAttributeRaw("Hoge.attr1")); hogeComponent.setAttribute("attr1", "some value"); - t.truthy(hogeComponent.getAttribute("attr1") === "some value") + t.truthy(hogeComponent.getAttribute("attr1") === "some value"); t.throws(() => { hogeComponent.setAttribute("notfound", "some value"); }); }); + +test("get/set attribute should works correctly", (t) => { + const fugaConverterDec = { + name: "FugaConverter", + convert(val): number { + return 123; + }, + }; + const hogeComponentDec = { + componentName: "Hoge", + attributes: { + attr1: { + converter: fugaConverterDec, + default: "hoge", + }, + }, + }; + GrimoireInterface.registerConverter(fugaConverterDec); + GrimoireInterface.registerComponent(hogeComponentDec); + + const hogeComponent = GrimoireInterface.componentDeclarations.get("Hoge").generateInstance(); + + t.truthy(hogeComponent.getAttributeRaw(hogeComponentDec.attributes.attr1)); + hogeComponent.setAttribute("attr1", "some value"); + t.truthy(hogeComponent.getAttribute(hogeComponentDec.attributes.attr1) === 123); + + const otherConverterDec = { + name: "FugaConverter", + convert(val): number { + return 123; + }, + }; + + t.throws(() => { + hogeComponent.getAttribute({ + converter: otherConverterDec, + default: "hoge", + }); + }, null, "get attribute throw if differet object reference."); +}); diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index 9c93a9508..e1f5184cb 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -11,7 +11,6 @@ import XMLReader from "../src/Tools/XMLReader"; import xmlserializer from "xmlserializer"; import "babel-polyfill"; - export default class TestEnvManager { public static async init(html = "") { @@ -20,7 +19,7 @@ export default class TestEnvManager { Environment.document = window.document; Environment.Node = { - ELEMENT_NODE: 1 + ELEMENT_NODE: 1, }; Environment.XMLSerializer = xmlserializer; } @@ -34,7 +33,6 @@ export default class TestEnvManager { }); } - public static async loadPage(html: string) { const window = await jsdomAsync(html, []); Environment.document = window.document; diff --git a/test/TestUtil.ts b/test/TestUtil.ts index 5b33d517d..c5ab2053c 100644 --- a/test/TestUtil.ts +++ b/test/TestUtil.ts @@ -1,13 +1,13 @@ import Attribute from "../src/Core/Attribute"; import Component from "../src/Core/Component"; import ComponentDeclaration from "../src/Core/ComponentDeclaration"; -import Ensure from "../src/Tools/Ensure"; import GomlNode from "../src/Core/GomlNode"; import GomlParser from "../src/Core/GomlParser"; import GrimoireInterface from "../src/Core/GrimoireInterface"; +import Identity from "../src/Core/Identity"; import IAttributeDeclaration from "../src/Interface/IAttributeDeclaration"; import ITreeInitializedInfo from "../src/Interface/ITreeInitializedInfo"; -import Identity from "../src/Core/Identity"; +import Ensure from "../src/Tools/Ensure"; import XMLReader from "../src/Tools/XMLReader"; export default class TestUtil { @@ -16,7 +16,7 @@ export default class TestUtil { return new ComponentDeclaration(Identity.fromFQN("aaa"), { attributes: { - } + }, }); } public static DummyComponent(): Component { @@ -29,7 +29,7 @@ export default class TestUtil { attr.name = name; attr.component = component; attr.declaration = declaration; - const converterName = Ensure.tobeNSIdentity(declaration.converter); + const converterName = Ensure.tobeCnverterIdentity(declaration.converter); attr.converter = GrimoireInterface.converters.get(converterName); attr.component.attributes.set(attr.name, attr); attr.converter.verify(attr); @@ -41,14 +41,14 @@ export default class TestUtil { const rootNode = GomlParser.parse(doc); rootNode.setMounted(true); - rootNode.broadcastMessage("treeInitialized", { + rootNode.broadcastMessage("treeInitialized", { ownerScriptTag: null, - id: rootNode.id - }); - rootNode.sendInitializedMessage({ + id: rootNode.id, + } as ITreeInitializedInfo); + rootNode.sendInitializedMessage({ ownerScriptTag: null, - id: rootNode.id - }); + id: rootNode.id, + } as ITreeInitializedInfo); return rootNode; } } From 710e9e94506db8d5f949c1a7c392d93c6ff2a24c Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 21 Oct 2017 13:29:54 +0900 Subject: [PATCH 054/146] feat: use converter generics --- src/Components/GrimoireComponent.ts | 11 +++-- src/Converters/BooleanConverter.ts | 47 ++++++++++++--------- src/Converters/ComponentConverter.ts | 3 +- src/Converters/NumberConverter.ts | 55 +++++++++++++------------ src/Converters/ObjectConverter.ts | 21 ++++++---- src/Converters/StringConverter.ts | 31 ++++++++++---- src/Core/GrimoireInterfaceImpl.ts | 8 ++-- test/Converters/BooleanConverterTest.ts | 20 ++++----- test/Converters/NumberConverterTest.ts | 12 +++--- test/Converters/ObjectConverterTest.ts | 6 +-- test/Converters/StringConverterTest.ts | 8 ++-- 11 files changed, 126 insertions(+), 96 deletions(-) diff --git a/src/Components/GrimoireComponent.ts b/src/Components/GrimoireComponent.ts index a0b653d2d..050b18c88 100644 --- a/src/Components/GrimoireComponent.ts +++ b/src/Components/GrimoireComponent.ts @@ -1,5 +1,8 @@ +import BooleanConverter from "../Converters/BooleanConverter"; import Component from "../Core/Component"; -import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; +import Identity from "../Core/Identity"; +import Namespace from "../Core/Namespace"; +import { __NAMESPACE__ } from "../metaInfo"; /** * Basic Component for all node. @@ -9,12 +12,12 @@ export default class GrimoireComponent extends Component { /** * component name. */ - public static componentName = "GrimoireComponent"; + public static componentName = Namespace.define(__NAMESPACE__).for("GrimoireComponent") as Identity; /** * attributes */ - public static attributes: { [key: string]: IAttributeDeclaration } = { + public static attributes = { id: { converter: "String", default: null, @@ -24,7 +27,7 @@ export default class GrimoireComponent extends Component { default: null, }, enabled: { - converter: "Boolean", + converter: BooleanConverter, default: true, }, }; diff --git a/src/Converters/BooleanConverter.ts b/src/Converters/BooleanConverter.ts index fd36cc6e1..6f82ab2f9 100644 --- a/src/Converters/BooleanConverter.ts +++ b/src/Converters/BooleanConverter.ts @@ -1,23 +1,30 @@ +import Identity from "../Core/Identity"; +import Namespace from "../Core/Namespace"; +import { __NAMESPACE__ } from "../metaInfo"; import { Undef } from "../Tools/Types"; -/** - * converter for booleam value. - * Pass through boolean value as it is. - * Pass through string value only 'true' or 'false'. - * @param {any} val [description] - * @param {Attribute} attr [description] - * @return {any} [description] - */ -export default function BooleanConverter(val: any): Undef { - if (typeof val === "boolean") { - return val; - } else if (typeof val === "string") { - switch (val) { - case "true": - return true; - case "false": - return false; +export default { + name: Namespace.define(__NAMESPACE__).for("Boolean") as Identity, + + /** + * converter for booleam value. + * Pass through boolean value as it is. + * Pass through string value only 'true' or 'false'. + * @param {any} val [description] + * @param {Attribute} attr [description] + * @return {any} [description] + */ + convert(val: any): Undef { + if (typeof val === "boolean") { + return val; + } else if (typeof val === "string") { + switch (val) { + case "true": + return true; + case "false": + return false; + } } - } - return undefined; -} + return undefined; + }, +}; diff --git a/src/Converters/ComponentConverter.ts b/src/Converters/ComponentConverter.ts index ae81c9e27..90d454dba 100644 --- a/src/Converters/ComponentConverter.ts +++ b/src/Converters/ComponentConverter.ts @@ -2,6 +2,7 @@ import Attribute from "../Core/Attribute"; import Component from "../Core/Component"; import GomlNode from "../Core/GomlNode"; import Ensure from "../Tools/Ensure"; +import { Undef } from "../Tools/Types"; /** * コンポーネントのためのコンバータです。 @@ -28,7 +29,7 @@ export default { * @param val * @param attr */ - convert(val: any, attr: Attribute) { + convert(val: any, attr: Attribute): Undef { if (val === null) { return null; } diff --git a/src/Converters/NumberConverter.ts b/src/Converters/NumberConverter.ts index c4b30e282..82e48df91 100644 --- a/src/Converters/NumberConverter.ts +++ b/src/Converters/NumberConverter.ts @@ -1,30 +1,33 @@ import { Undef } from "../Tools/Types"; import Utility from "../Tools/Utility"; -/** - * converter for number value. - * number,string,null will be converted. - * Array also convertable only if length equivalent to 1. - * @param {any} val [description] - * @return {number} [description] - */ -export default function NumberConverter(val: any): Undef { - if (typeof val === "number") { - return val; - } - if (typeof val === "string") { - const parsed = Number.parseFloat(val); - return Number.isNaN(parsed) ? undefined : parsed; - } - if (val === null) { - return null; - } - if (Array.isArray(val) && val.length === 1) { - Utility.w("[Deprecated] converting from Array is deprecated in NumberConverter."); - const ret = val[0]; - if (typeof ret === "number") { - return ret; +export default { + name: "Number", + /** + * converter for number value. + * number,string,null will be converted. + * Array also convertable only if length equivalent to 1. + * @param {any} val [description] + * @return {number} [description] + */ + convert(val: any): Undef { + if (typeof val === "number") { + return val; } - } - return undefined; -} + if (typeof val === "string") { + const parsed = Number.parseFloat(val); + return Number.isNaN(parsed) ? undefined : parsed; + } + if (val === null) { + return null; + } + if (Array.isArray(val) && val.length === 1) { + Utility.w("[Deprecated] converting from Array is deprecated in NumberConverter."); + const ret = val[0]; + if (typeof ret === "number") { + return ret; + } + } + return undefined; + }, +}; diff --git a/src/Converters/ObjectConverter.ts b/src/Converters/ObjectConverter.ts index 5f275dd60..14e7ca5ea 100644 --- a/src/Converters/ObjectConverter.ts +++ b/src/Converters/ObjectConverter.ts @@ -1,9 +1,12 @@ -/** - * converter for object - * Pass through any value as it is. - * @param {any} val [description] - * @return {any} [description] - */ -export default function ObjectConverter(val: any): any { - return val; -} +export default { + name: "Object", + /** + * converter for object + * Pass through any value as it is. + * @param {any} val [description] + * @return {any} [description] + */ + convert(val: any): any { + return val; + }, +}; diff --git a/src/Converters/StringConverter.ts b/src/Converters/StringConverter.ts index 4e7e37232..fe01f2117 100644 --- a/src/Converters/StringConverter.ts +++ b/src/Converters/StringConverter.ts @@ -1,9 +1,22 @@ -export default function StringConverter(val: any): any { - if (typeof val === "string") { - return val; - } else if (!val) { - return val; - } else if (typeof val.toString === "function") { - return val.toString(); - } -} +import Identity from "../Core/Identity"; +import Namespace from "../Core/Namespace"; +import { __NAMESPACE__ } from "../metaInfo"; +import { Undef } from "../Tools/Types"; + +export default { + name: Namespace.define(__NAMESPACE__).for("String") as Identity, + /** + * convert to string + * @param val + */ + convert(val: any): Undef { + if (typeof val === "string") { + return val; + } else if (!val) { + return val; + } else if (typeof val.toString === "function") { + return val.toString(); + } + return undefined; + }, +}; diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index b409b5776..5f4b42fc2 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -137,11 +137,11 @@ export default class GrimoireInterfaceImpl extends EEObject { * if you want reset state. use GrimoireInterface.clear() instead of. */ public initialize(): void { - this.registerConverter("String", StringConverter); + this.registerConverter(StringConverter); this.registerConverter("StringArray", StringArrayConverter); - this.registerConverter("Boolean", BooleanConverter); - this.registerConverter("Object", ObjectConverter); - this.registerConverter("Number", NumberConverter); + this.registerConverter(BooleanConverter); + this.registerConverter(ObjectConverter); + this.registerConverter(NumberConverter); this.registerConverter("NumberArray", NumberArrayConverter); this.registerConverter(ArrayConverter); this.registerConverter(EnumConverter); diff --git a/test/Converters/BooleanConverterTest.ts b/test/Converters/BooleanConverterTest.ts index cb4d94f5b..fe9109ce5 100644 --- a/test/Converters/BooleanConverterTest.ts +++ b/test/Converters/BooleanConverterTest.ts @@ -2,15 +2,15 @@ import test from "ava"; import BooleanConverter from "../../src/Converters/BooleanConverter"; test("BooleanConverter should convert collectly", t => { - t.truthy(BooleanConverter(true) === true); - t.truthy(BooleanConverter(false) === false); - t.truthy(BooleanConverter("true") === true); - t.truthy(BooleanConverter("false") === false); + t.truthy(BooleanConverter.convert(true) === true); + t.truthy(BooleanConverter.convert(false) === false); + t.truthy(BooleanConverter.convert("true") === true); + t.truthy(BooleanConverter.convert("false") === false); - t.truthy(BooleanConverter("aaaa") === undefined); - t.truthy(BooleanConverter("False") === undefined); - t.truthy(BooleanConverter("True") === undefined); - t.truthy(BooleanConverter("") === undefined); - t.truthy(BooleanConverter(null) === undefined); - t.truthy(BooleanConverter(123) === undefined); + t.truthy(BooleanConverter.convert("aaaa") === undefined); + t.truthy(BooleanConverter.convert("False") === undefined); + t.truthy(BooleanConverter.convert("True") === undefined); + t.truthy(BooleanConverter.convert("") === undefined); + t.truthy(BooleanConverter.convert(null) === undefined); + t.truthy(BooleanConverter.convert(123) === undefined); }); diff --git a/test/Converters/NumberConverterTest.ts b/test/Converters/NumberConverterTest.ts index 7c6ba883b..65c5ca96e 100644 --- a/test/Converters/NumberConverterTest.ts +++ b/test/Converters/NumberConverterTest.ts @@ -5,10 +5,10 @@ import TestEnvManager from "../TestEnvManager"; TestEnvManager.init(); test("NumberConverter should convert collectly", t => { - t.truthy(NumberConverter(123) === 123); - t.truthy(NumberConverter("123") === 123); - t.truthy(NumberConverter(null) === null); - t.truthy(NumberConverter([123]) === 123); - t.truthy(NumberConverter("this string can not convert to number") === undefined); - t.truthy(NumberConverter([123, 456]) === undefined); + t.truthy(NumberConverter.convert(123) === 123); + t.truthy(NumberConverter.convert("123") === 123); + t.truthy(NumberConverter.convert(null) === null); + t.truthy(NumberConverter.convert([123]) === 123); + t.truthy(NumberConverter.convert("this string can not convert to number") === undefined); + t.truthy(NumberConverter.convert([123, 456]) === undefined); }); diff --git a/test/Converters/ObjectConverterTest.ts b/test/Converters/ObjectConverterTest.ts index a15f9eec9..cd2225832 100644 --- a/test/Converters/ObjectConverterTest.ts +++ b/test/Converters/ObjectConverterTest.ts @@ -2,7 +2,7 @@ import test from "ava"; import ObjectConverter from "../../src/Converters/ObjectConverter"; test("ObjectConverter should convert collectly", t => { - t.truthy(ObjectConverter("HELLO") === "HELLO"); - t.truthy(ObjectConverter(null) === null); - t.truthy(ObjectConverter(123) === 123); + t.truthy(ObjectConverter.convert("HELLO") === "HELLO"); + t.truthy(ObjectConverter.convert(null) === null); + t.truthy(ObjectConverter.convert(123) === 123); }); diff --git a/test/Converters/StringConverterTest.ts b/test/Converters/StringConverterTest.ts index 1b1bd4a76..8666a053a 100644 --- a/test/Converters/StringConverterTest.ts +++ b/test/Converters/StringConverterTest.ts @@ -2,8 +2,8 @@ import test from "ava"; import StringConverter from "../../src/Converters/StringConverter"; test("StringConverter should convert collectly", t => { - t.truthy(StringConverter("HELLO") === "HELLO"); - t.truthy(StringConverter(null) === null); - t.truthy(StringConverter(123) === "123"); - t.truthy(StringConverter({ toString: () => "value" }) === "value"); + t.truthy(StringConverter.convert("HELLO") === "HELLO"); + t.truthy(StringConverter.convert(null) === null); + t.truthy(StringConverter.convert(123) === "123"); + t.truthy(StringConverter.convert({ toString: () => "value" }) === "value"); }); From 9eea312a96ced32dfbad81314ab8f57f20ebdfec Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 21 Oct 2017 13:30:27 +0900 Subject: [PATCH 055/146] fix: update gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 3f50108f3..a016d7aba 100644 --- a/.gitignore +++ b/.gitignore @@ -128,3 +128,4 @@ yarn.lock docs test-lib test-lib-es5 +src/metaInfo.ts From 2a5b2143d6b8261b907370661792710b7bec60c4 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 22 Oct 2017 04:48:11 +0900 Subject: [PATCH 056/146] fix: refactor GomlParser --- src/Components/GrimoireComponent.ts | 5 +- src/Converters/BooleanConverter.ts | 2 +- src/Converters/StringConverter.ts | 2 +- src/Core/Component.ts | 32 ++--- src/Core/ComponentDeclaration.ts | 4 +- src/Core/GomlNode.ts | 37 +++--- src/Core/GomlParser.ts | 157 +++++++++++++---------- src/Interface/IGrimoireComponentModel.ts | 7 + src/Interface/IGrimoireNodeModel.ts | 11 ++ test/Core/GomlNode2Test.ts | 10 +- test/Core/GomlNodeTest.ts | 66 +++++----- test/Core/GomlParserTest.ts | 100 +++++++++++++-- test/Core/GrimoireInterfaceTest.ts | 100 ++++++++++----- test/TestEnvManager.ts | 14 +- test/TestUtil.ts | 2 +- 15 files changed, 350 insertions(+), 199 deletions(-) create mode 100644 src/Interface/IGrimoireComponentModel.ts create mode 100644 src/Interface/IGrimoireNodeModel.ts diff --git a/src/Components/GrimoireComponent.ts b/src/Components/GrimoireComponent.ts index 050b18c88..a0b44e391 100644 --- a/src/Components/GrimoireComponent.ts +++ b/src/Components/GrimoireComponent.ts @@ -1,4 +1,5 @@ import BooleanConverter from "../Converters/BooleanConverter"; +import StringConverter from "../Converters/StringConverter"; import Component from "../Core/Component"; import Identity from "../Core/Identity"; import Namespace from "../Core/Namespace"; @@ -12,14 +13,14 @@ export default class GrimoireComponent extends Component { /** * component name. */ - public static componentName = Namespace.define(__NAMESPACE__).for("GrimoireComponent") as Identity; + public static componentName: Identity = Namespace.define(__NAMESPACE__).for("GrimoireComponent"); /** * attributes */ public static attributes = { id: { - converter: "String", + converter: StringConverter, default: null, }, class: { diff --git a/src/Converters/BooleanConverter.ts b/src/Converters/BooleanConverter.ts index 6f82ab2f9..5f5f6b5df 100644 --- a/src/Converters/BooleanConverter.ts +++ b/src/Converters/BooleanConverter.ts @@ -4,7 +4,7 @@ import { __NAMESPACE__ } from "../metaInfo"; import { Undef } from "../Tools/Types"; export default { - name: Namespace.define(__NAMESPACE__).for("Boolean") as Identity, + name: Namespace.define(__NAMESPACE__).for("Boolean"), /** * converter for booleam value. diff --git a/src/Converters/StringConverter.ts b/src/Converters/StringConverter.ts index fe01f2117..c71b917ca 100644 --- a/src/Converters/StringConverter.ts +++ b/src/Converters/StringConverter.ts @@ -4,7 +4,7 @@ import { __NAMESPACE__ } from "../metaInfo"; import { Undef } from "../Tools/Types"; export default { - name: Namespace.define(__NAMESPACE__).for("String") as Identity, + name: Namespace.define(__NAMESPACE__).for("String"), /** * convert to string * @param val diff --git a/src/Core/Component.ts b/src/Core/Component.ts index 8a7f85cba..dc2824e97 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -6,7 +6,6 @@ import { GomlInterface, Name, Nullable } from "../Tools/Types"; import Utility from "../Tools/Utility"; import Attribute from "./Attribute"; import ComponentDeclaration from "./ComponentDeclaration"; -import Constants from "./Constants"; import GomlNode from "./GomlNode"; import Identity from "./Identity"; import IdentityMap from "./IdentityMap"; @@ -37,6 +36,11 @@ export default class Component extends IDObject { */ public element: Element; + /** + * default attribute defined in GOML + */ + public gomAttribute: { [key: string]: string }; + /** * Whether this component was created by nodeDeclaration * @type {boolean} @@ -166,23 +170,11 @@ export default class Component extends IDObject { * Interal use! * @param nodeAttributes */ - public resolveDefaultAttributes(nodeAttributes?: { [key: string]: string; } | null): any { - const nodeAttr = nodeAttributes || {}; - if (this.isDefaultComponent) { // If this is default component, the default attribute values should be retrived from node DOM. - this.attributes.forEach(attr => { - attr.resolveDefaultValue(nodeAttr); - }); - } else { // If not,the default value of attributes should be retrived from this element. - const attrs = Utility.getAttributes(this.element); - for (const key in attrs) { - if (key === Constants.x_gr_id) { - continue; - } - } - this.attributes.forEach(attr => { - attr.resolveDefaultValue(attrs); - }); - } + public resolveDefaultAttributes(specifiedValue?: { [key: string]: string; }): void { + specifiedValue = specifiedValue || {}; + this.attributes.forEach(attr => { + attr.resolveDefaultValue(specifiedValue || {}); + }); } /** @@ -234,9 +226,9 @@ export default class Component extends IDObject { const attr = Attribute.generateAttributeForComponent(name, attribute, this); this.node.addAttribute(attr); if (this.isDefaultComponent) { // If this is default component, the default attribute values should be retrived from node DOM. - attr.resolveDefaultValue(Utility.getAttributes(this.node.element)); + attr.resolveDefaultValue(this.node.gomAttribute); } else { // If not,the default value of attributes should be retrived from this element. - const attrs = Utility.getAttributes(this.element); + const attrs = this.gomAttribute; attr.resolveDefaultValue(attrs); } this._additionalAttributesNames.push(attr.name); diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index b3a6cfdb8..ec3a160b5 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -70,11 +70,11 @@ export default class ComponentDeclaration { * generate component instance. * @param componentElement */ - public generateInstance(componentElement?: Element): Component { // TODO: obsolete.make all operation on gomlnode + public generateInstance(): Component { if (!this.isDependenyResolved) { this.resolveDependency(); } - componentElement = componentElement ? componentElement : Environment.document.createElementNS(this.name.ns.qualifiedName, this.name.name); + const componentElement = Environment.document.createElementNS(this.name.ns.qualifiedName, this.name.name); const component = new this.ctor(); componentElement.setAttribute(Constants.x_gr_id, component.id); Environment.GrimoireInterface.componentDictionary[component.id] = component; diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index 8aa30de74..293711d9a 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -46,6 +46,11 @@ export default class GomlNode extends EEObject { */ public element: Element; // Dom Element + /** + * default attribute defined in GOML + */ + public gomAttribute: { [key: string]: string }; + /** * declaration infomation. */ @@ -169,7 +174,7 @@ export default class GomlNode extends EEObject { declaration.resolveDependency(); } this.declaration = declaration; - this.element = element ? element : Environment.document.createElementNS(declaration.name.ns.qualifiedName, declaration.name.name); + this.element = element || Environment.document.createElementNS(declaration.name.ns.qualifiedName, declaration.name.name); this._root = this; this._components = []; this._attributeManager = new AttributeManager(declaration.name.name); @@ -327,9 +332,8 @@ export default class GomlNode extends EEObject { * Add child for this node. * @param {GomlNode} child child node to add. * @param {number} index index for insert.なければ末尾に追加 - * @param {[type]} elementSync=true trueのときはElementのツリーを同期させる。(Elementからパースするときはfalseにする) */ - public addChild(child: GomlNode, index?: number | null, elementSync = true): void { + public addChild(child: GomlNode, index?: number | null): void { if (child._deleted) { throw new Error("deleted node never use."); } @@ -341,14 +345,12 @@ export default class GomlNode extends EEObject { const insertIndex = index == null ? this.children.length : index; this.children.splice(insertIndex, 0, child); child._parent = this; - child._tree = this._tree; - child._companion = this._companion; + child._tree = this._tree; // TODO これは問題がある。再帰的に設定しなければ。 + child._companion = this._companion; // TODO これは問題がある。再帰的に設定しなければ。 // sync html - if (elementSync) { - const referenceElement = (this.element as any)[Utility.getNodeListIndexByElementIndex(this.element, insertIndex)]; - this.element.insertBefore(child.element, referenceElement); - } + const referenceElement = (this.element as any)[Utility.getNodeListIndexByElementIndex(this.element, insertIndex)]; + this.element.insertBefore(child.element, referenceElement); // mounting if (this.mounted) { @@ -541,7 +543,7 @@ export default class GomlNode extends EEObject { component.node = this; // bind this for message reciever. - let propNames: string[] = []; + let propNames: string[] = []; // TODOこの6行はgenerateComponentInstanceでやっていいのでは? let o = component; while (o) { propNames = propNames.concat(Object.getOwnPropertyNames(o)); @@ -557,12 +559,12 @@ export default class GomlNode extends EEObject { component.attributes.forEach(p => this.addAttribute(p)); if (this._defaultValueResolved) { component.attributes.forEach(p => { - p.resolveDefaultValue(Utility.getAttributes(this.element)); + p.resolveDefaultValue(this.gomAttribute); }); } if (this._mounted) { - component.resolveDefaultAttributes(null); // here must be optional component.should not use node element attributes. + component.resolveDefaultAttributes(); // here must be optional component.should not use node element attributes. this._sendMessageForcedTo(component, "awake"); this._sendMessageForcedTo(component, "mount"); } @@ -704,13 +706,12 @@ export default class GomlNode extends EEObject { * resolve default attribute value for all component. * すべてのコンポーネントの属性をエレメントかデフォルト値で初期化 */ - public resolveAttributesValue(): void { + public resolveAttributesValue(attrs?: { [key: string]: string }): void { + if (this._defaultValueResolved) { + return; + } this._defaultValueResolved = true; - const attrs = Utility.getAttributes(this.element); - for (const key in attrs) { - if (key === Constants.x_gr_id) { - continue; - } + for (const key in (attrs || {})) { if (this.isFreezeAttribute(key)) { throw new Error(`attribute ${key} can not change from GOML. Attribute is frozen. `); } diff --git a/src/Core/GomlParser.ts b/src/Core/GomlParser.ts index c33947b50..2d1b3b479 100644 --- a/src/Core/GomlParser.ts +++ b/src/Core/GomlParser.ts @@ -1,4 +1,9 @@ import GrimoireInterface from "../Core/GrimoireInterface"; +import IGrimoireComponentModel from "../Interface/IGrimoireComponentModel"; +import IGrimoireNodeModel from "../Interface/IGrimoireNodeModel"; +import Utility from "../Tools/Utility"; +import XMLReader from "../Tools/XMLReader"; +import Component from "./Component"; import Environment from "./Environment"; import GomlNode from "./GomlNode"; @@ -6,93 +11,115 @@ import GomlNode from "./GomlNode"; * Parser of Goml to Node utilities. * This class do not store any nodes and goml properties. */ -class GomlParser { +export default class GomlParser { + /** - * Domをパースする - * @param {Element} source [description] - * @param {GomlNode} parent あればこのノードにaddChildされる - * @return {GomlNode} ルートノード + * parsing XML-DOM to Grimoire object model. + * @param source XML-DOM */ - public static parse(source: Element, parent?: GomlNode | null): GomlNode { - const newNode = GomlParser._createNode(source); + public static parseToGOM(source: Element): IGrimoireNodeModel { + Utility.assert(!!source, "source cannot be null"); + return parseNode(source); - // Parse children recursively - const children = source.childNodes; - const childNodeElements: Element[] = []; // for parse after .Components has resolved. - if (children && children.length !== 0) { // When there is children - const removeTarget: Node[] = []; - for (let i = 0; i < children.length; i++) { - const child = children.item(i); + function parseNode(elem: Element): IGrimoireNodeModel { + const name = elem.namespaceURI ? `${elem.namespaceURI}.${elem.localName!}` : elem.localName!; + const attributes = Utility.getAttributes(elem); + const childrenElement = Array.from(elem.childNodes); + const optionalComponents: IGrimoireComponentModel[] = []; + const childNodeElements: Element[] = []; + childrenElement.forEach(child => { if (!GomlParser._isElement(child)) { - removeTarget.push(child); - continue; + return; } - if (this._isComponentsTag(child)) { - // parse as components - GomlParser._parseComponents(newNode, child); - removeTarget.push(child); + if (GomlParser._isComponentsTag(child)) { + const parsed = parseComponents(child); + optionalComponents.push(...parsed); } else { - // parse as child node. childNodeElements.push(child); } + }); + const children = childNodeElements.map(parseNode); + const ret = { name } as IGrimoireNodeModel; + if (Object.keys(attributes).length !== 0) { + ret.attributes = attributes; + } + if (optionalComponents.length !== 0) { + ret.optionalComponents = optionalComponents; } - // remove unused elements - for (let i = 0; i < removeTarget.length; i++) { - source.removeChild(removeTarget[i]); + if (children.length !== 0) { + ret.children = children; } + return ret; } - - // generate tree - if (parent) { - parent.addChild(newNode, null, false); + function parseComponents(elem: Element): IGrimoireComponentModel[] { + const componentNodes = Array.from(elem.childNodes); + return componentNodes.filter(GomlParser._isElement).map(it => { + const name = it.namespaceURI ? `${it.namespaceURI}.${it.localName!}` : it.localName!; + const attributes = Utility.getAttributes(it); + const ret = { + name, + } as IGrimoireComponentModel; + if (Object.keys(attributes).length !== 0) { + ret.attributes = attributes; + } + return ret; + }); } - - childNodeElements.forEach((child) => { - GomlParser.parse(child, newNode); - }); - return newNode; } /** - * GomlNodeのインスタンス化。GrimoireInterfaceへの登録 - * @param {HTMLElement} elem [description] - * @param {GomlConfigurator} configurator [description] - * @return {GomlTreeNodeBase} [description] + * parsing GOM to GomlNode tree strucure. + * @param gom */ - private static _createNode(elem: Element): GomlNode { - const tagName = elem.localName; - const recipe = GrimoireInterface.nodeDeclarations.get(elem); - if (!recipe) { - throw new Error(`Tag "${tagName}" is not found.`); - } - return new GomlNode(recipe, elem); - } + public static parseGOMToGomlNode(gom: IGrimoireNodeModel): GomlNode { + const namespace = gom.name.substr(0, gom.name.lastIndexOf(".")); + const name = gom.name.substr(gom.name.lastIndexOf(".") + 1); + const rootElement = XMLReader.parseXML(namespace === "" ? `<${name}/>` : ``); + return createNode(gom, undefined, rootElement); - /** - * .COMPONENTSのパース。 - * @param {GomlNode} node アタッチされるコンポーネント - * @param {Element} componentsTag .COMPONENTSタグ - */ - private static _parseComponents(node: GomlNode, componentsTag: Element): void { - const componentNodes = componentsTag.childNodes; - if (!componentNodes) { - return; - } - for (let i = 0; i < componentNodes.length; i++) { - const componentNode = componentNodes.item(i) as Element; - if (!GomlParser._isElement(componentNode)) { - continue; // Skip if the node was not element + function createNode(source: IGrimoireNodeModel, parent?: GomlNode, element?: Element): GomlNode { + const declaration = GrimoireInterface.nodeDeclarations.get(source.name); + if (!declaration) { + throw new Error(`Tag "${source.name}" is not found.`); } - const componentDecl = GrimoireInterface.componentDeclarations.get(componentNode); - if (!componentDecl) { // Verify specified component is actual existing. - throw new Error(`Component ${componentNode.tagName} is not found.`); + const node = new GomlNode(declaration, element); + if (parent) { + parent.addChild(node); // 先に親を設定するのはパフォーマンス上の理由 } - const component = componentDecl.generateInstance(componentNode); - node._addComponentDirectly(component, false); + const components = source.optionalComponents ? createComponents(source.optionalComponents) : []; + (source.children || []).forEach(it => createNode(it, node)); + components.forEach(c => { + node._addComponentDirectly(c, false); + }); + node.gomAttribute = source.attributes || {}; + node.resolveAttributesValue(source.attributes || {}); + return node; + } + function createComponents(components: IGrimoireComponentModel[]): Component[] { + return components.map(it => { + const componentDecl = GrimoireInterface.componentDeclarations.get(it.name); + if (!componentDecl) { + throw new Error(`Component ${it.name} is not found.`); + } + const instance = componentDecl.generateInstance(); + instance.gomAttribute = it.attributes || {}; + return instance; + }); } } + /** + * Domをパースする + * @param {Element} source [description] + * @param {GomlNode} parent あればこのノードにaddChildされる + * @return {GomlNode} ルートノード + */ + public static parse(source: Element): GomlNode { + const gom = GomlParser.parseToGOM(source); + return GomlParser.parseGOMToGomlNode(gom); + } + private static _isElement(node: Node): node is Element { return node.nodeType === Environment.Node.ELEMENT_NODE; } @@ -103,5 +130,3 @@ class GomlParser { } } - -export default GomlParser; diff --git a/src/Interface/IGrimoireComponentModel.ts b/src/Interface/IGrimoireComponentModel.ts new file mode 100644 index 000000000..dbc36dca2 --- /dev/null +++ b/src/Interface/IGrimoireComponentModel.ts @@ -0,0 +1,7 @@ +/** + * Grimoire Object Model structure slement + */ +export default interface IGrimoireComponentModel { + name: string; + attributes?: { [key: string]: string; }; +} diff --git a/src/Interface/IGrimoireNodeModel.ts b/src/Interface/IGrimoireNodeModel.ts new file mode 100644 index 000000000..4d69fc519 --- /dev/null +++ b/src/Interface/IGrimoireNodeModel.ts @@ -0,0 +1,11 @@ +import IGrimoireComponentModel from "./IGrimoireComponentModel"; + +/** + * Grimoire Object Model structure slement + */ +export default interface IGrimoireNodeModel { + name: string; + attributes?: { [key: string]: string; }; + optionalComponents?: IGrimoireComponentModel[]; + children?: IGrimoireNodeModel[]; +} diff --git a/test/Core/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts index f1de7a7c0..8f1435a54 100644 --- a/test/Core/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -413,7 +413,7 @@ test("attribute buffer is valid only last set value.", t => { // both buffer are resolved in above __addAttribute. (c as any).__addAttribute("hoge", { converter: "String", - default: "aaa" + default: "aaa", }); att = rootNode.getAttribute(Identity.fromFQN(c.name.fqn + ".hoge")); t.truthy(att === "aaa"); @@ -423,7 +423,7 @@ test("attribute buffer is valid only last set value.", t => { rootNode.setAttribute("ns2.aaa", "3"); (c as any).__addAttribute("ns2.aaa", { converter: "String", - default: "aaa" + default: "aaa", }); att = rootNode.getAttribute(Identity.fromFQN(c.name.fqn + ".ns2.aaa")); t.truthy(att === "3"); @@ -435,7 +435,7 @@ test("get/setAttribute should work correctly 6", t => { rootNode.setAttribute("hoge", "ccc"); (c as any).__addAttribute("hoge", { converter: "String", - default: "aaa" + default: "aaa", }); const att = rootNode.getAttribute("hoge"); t.truthy(att === "ccc"); @@ -445,11 +445,11 @@ test("get/setAttribute should work correctly 7", t => { const c = rootNode.getComponent("GrimoireComponent"); (c as any).__addAttribute("ns1.hoge", { converter: "String", - default: "1" + default: "1", }); (c as any).__addAttribute("ns2.hoge", { converter: "String", - default: "2" + default: "2", }); (c as any).__addAttribute("hoge", { converter: "String", diff --git a/test/Core/GomlNodeTest.ts b/test/Core/GomlNodeTest.ts index b5e73b8c9..b23c2bbd3 100644 --- a/test/Core/GomlNodeTest.ts +++ b/test/Core/GomlNodeTest.ts @@ -71,8 +71,8 @@ test("Remove components should delete specified all components in node", t => { test("addChild method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); - node.addChild(node2, null, null); - node.addChild(node2, null, null); + node.addChild(node2, null); + node.addChild(node2, null); t.truthy(node.children[0].id === node2.id); t.truthy(node.children.length === 2); }); @@ -81,8 +81,8 @@ test("delete method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); - node.addChild(node2, null, null); - node2.addChild(node3, null, null); + node.addChild(node2, null); + node2.addChild(node3, null); node2.remove(); t.truthy(node.children.length === 0); t.truthy(node2.parent === null); @@ -95,8 +95,8 @@ test("removeChild method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); - node.addChild(node2, null, null); - node2.addChild(node3, null, null); + node.addChild(node2, null); + node2.addChild(node3, null); node.removeChild(node2); t.truthy(node2.deleted === true); t.truthy(node3.deleted === true); @@ -106,8 +106,8 @@ test("detachChild method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); - node.addChild(node2, null, null); - node2.addChild(node3, null, null); + node.addChild(node2, null); + node2.addChild(node3, null); node.detachChild(node2); t.truthy(node.children.length === 0); t.truthy(node2.deleted === false); @@ -119,8 +119,8 @@ test("detach method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); - node.addChild(node2, null, null); - node2.addChild(node3, null, null); + node.addChild(node2, null); + node2.addChild(node3, null); node2.detach(); try { node.detach(); @@ -154,8 +154,8 @@ test("setMounted method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); - node.addChild(node2, null, null); - node2.addChild(node3, null, null); + node.addChild(node2, null); + node2.addChild(node3, null); node.setMounted(true); t.truthy(node.mounted === true); t.truthy(node2.mounted === true); @@ -170,15 +170,15 @@ test("index method works correctly", t => { test("addComponent method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); - node.addChild(node2, null, null); + node.addChild(node2, null); GrimoireInterface.registerComponent({ componentName: "TestComponent1", attributes: { testAttr1: { converter: "String", - default: "thisistest" + default: "thisistest", } - } + }, }); const component = GrimoireInterface.componentDeclarations.get("TestComponent1").generateInstance(); node._addComponentDirectly(component, true); @@ -190,15 +190,15 @@ test("addComponent method works correctly", t => { test("addComponent method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); - node.addChild(node2, null, null); + node.addChild(node2, null); GrimoireInterface.registerComponent({ componentName: "TestComponent1", attributes: { testAttr1: { converter: "String", - default: "thisistest" - } - } + default: "thisistest", + }, + }, }); const component = node.addComponent("TestComponent1", { testAttr1: "testValue" }); const components = node.getComponents(); @@ -210,24 +210,24 @@ test("addComponent method works correctly", t => { test("getComponent method overload works correctly", async t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); - node.addChild(node2, null, null); + node.addChild(node2, null); GrimoireInterface.registerComponent({ componentName: "TestComponent1", attributes: { testAttr1: { converter: "String", - default: "thisistest" - } - } + default: "thisistest", + }, + }, }); GrimoireInterface.registerComponent({ componentName: "TestComponent2", attributes: { testAttr1: { converter: "String", - default: "thisistest" - } - } + default: "thisistest", + }, + }, }, "TestComponent1"); await GrimoireInterface.resolvePlugins(); @@ -238,24 +238,24 @@ test("getComponent method overload works correctly", async t => { test("getComponents method overload works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); - node.addChild(node2, null, null); + node.addChild(node2, null); GrimoireInterface.registerComponent({ componentName: "TestComponent1", attributes: { testAttr1: { converter: "String", - default: "thisistest" - } - } + default: "thisistest", + }, + }, }); GrimoireInterface.registerComponent({ componentName: "TestComponent2", attributes: { testAttr1: { converter: "String", - default: "thisistest" - } - } + default: "thisistest", + }, + }, }); node.addComponent("TestComponent1"); node.addComponent("TestComponent2"); diff --git a/test/Core/GomlParserTest.ts b/test/Core/GomlParserTest.ts index 58f9f173c..d87ee399d 100644 --- a/test/Core/GomlParserTest.ts +++ b/test/Core/GomlParserTest.ts @@ -1,13 +1,11 @@ +import test from "ava"; +import { assert, spy } from "sinon"; import Environment from "../../src/Core/Environment"; -import fs from "../fileHelper"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import Namespace from "../../src/Core/Namespace"; import Identity from "../../src/Core/Identity"; -import test from "ava"; -import TestEnvManager from "../TestEnvManager"; +import Namespace from "../../src/Core/Namespace"; import XMLReader from "../../src/Tools/XMLReader"; -import { assert, spy } from "sinon"; import { registerConflictComponent1, registerConflictComponent2, @@ -21,8 +19,10 @@ import { registerTestComponentOptional, registerTestNode1, registerTestNode2, - registerTestNodeBase + registerTestNodeBase, } from "../DummyObjectRegisterer"; +import fs from "../fileHelper"; +import TestEnvManager from "../TestEnvManager"; TestEnvManager.init(); @@ -48,7 +48,7 @@ const gomlParserTestCasePath2 = "../_TestResource/GomlParserTest_Case2.goml"; const gomlParserTestCasePath3 = "../_TestResource/GomlParserTest_Case3.goml"; const gomlParserTestCasePath4 = "../_TestResource/GomlParserTest_Case4.goml"; -test.beforeEach(async () => { +test.beforeEach(async() => { GrimoireInterface.clear(); registerGoml(); registerTestNode1(); @@ -67,7 +67,6 @@ test.beforeEach(async () => { await GrimoireInterface.resolvePlugins(); }); - test("test for parsing node hierarchy.", (t) => { const element = obtainElementTag(gomlParserTestCasePath1); const node = GomlParser.parse(element); @@ -134,3 +133,88 @@ test("treeInterface must be same if the node is included in same tree", (t) => { t.truthy(original === v["_treeInterface"]); }); }); + +const testcases = [ + { + source: gomlParserTestCasePath1, + expected: { + name: "goml", + children: [{ + name: "goml", + children: [ + { name: "goml" }, + { name: "goml" }, + ], + }], + }, + }, + { + source: gomlParserTestCasePath2, + expected: { + name: "goml", + attributes: { testAttr: "node default Value" }, + children: [ + { + name: "goml", + attributes: { testAttr: "hogehoge" }, + }, + { + name: "goml", + }, + ], + }, + }, + { + source: gomlParserTestCasePath3, + expected: { + name: "goml", + children: [ + { + name: "test-node1", + attributes: { testAttr1: "hugahuga" }, + children: [ + { + name: "test-node2", + attributes: { testAttr2: "123", inheritAttr: "hogehoge" }, + optionalComponents: [ + { + name: "TestComponentOptional", + attributes: { value: "999" }, + }, + ], + }, + ], + }, + ], + }, + }, + { + source: gomlParserTestCasePath4, + expected: { + name: "goml", + children: [ + { + name: "test1.conflict-node", + optionalComponents: [ + { + name: "test1.ConflictComponent", + }, + { + name: "test2.ConflictComponent", + }, + ], + }, + { + name: "test2.conflict-node", + }, + ], + }, + }, +]; + +testcases.forEach((testcase, i) => { + test(`parseToGOM works correctly (${i})`, (t) => { + const result = GomlParser.parseToGOM(obtainElementTag(testcase.source)); + t.deepEqual(result, testcase.expected); + }); +}); diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index 940112f09..72efec8a1 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -1,18 +1,22 @@ +import test from "ava"; +import { assert, spy } from "sinon"; import Component from "../../src/Core/Component"; import Constants from "../../src/Core/Constants"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import Namespace from "../../src/Core/Namespace"; import Identity from "../../src/Core/Identity"; -import test from "ava"; +import Namespace from "../../src/Core/Namespace"; +import fs from "../fileHelper"; +import jsdomAsync from "../JsDOMAsync"; import TestEnvManager from "../TestEnvManager"; -import { assert, spy } from "sinon"; TestEnvManager.init(); -test.beforeEach(() => { +const tc1_html = fs.readFile("../_TestResource/GrimoireInterfaceTest_Case1.html"); + +test.beforeEach(async () => { GrimoireInterface.clear(); GrimoireInterface.resolvePlugins(); }); @@ -23,13 +27,39 @@ test("properties are initialized correctly", t => { t.truthy(GrimoireInterface.componentDeclarations.toArray().length === 1); // only GrimoireComponent }); +test("call as function works correctly", async t => { + GrimoireInterface.registerNode("goml"); + GrimoireInterface.resolvePlugins(); + await TestEnvManager.loadPage(tc1_html); + t.truthy(GrimoireInterface("*")("*").count === 3); + t.truthy(GrimoireInterface("*")("#testId1").count === 1); + t.truthy(GrimoireInterface("*")(".class").count === 0); +}); + +test("call as function works correctly", async t => { + GrimoireInterface.registerNode("goml"); + GrimoireInterface.resolvePlugins(); + await TestEnvManager.loadPage(''); + t.truthy(GrimoireInterface("*")("*").count === 1); + t.truthy(GrimoireInterface("*")("goml").count === 1); +}); + +test("call as function works correctly", async t => { + GrimoireInterface.clear(); + GrimoireInterface.registerNode("_grimoirejs.goml"); + GrimoireInterface.resolvePlugins(); + await TestEnvManager.loadPage(''); + t.truthy(GrimoireInterface("*")("*").count === 1); + // t.truthy(GrimoireInterface("*")("goml").count === 1);// TODO fix? +}); + test("registerComponent works correctly", (t) => { const l = GrimoireInterface.componentDeclarations.toArray().length; const dec = GrimoireInterface.registerComponent({ componentName: "Name", attributes: { - attr: { converter: "String", default: "aaa" } - } + attr: { converter: "String", default: "aaa" }, + }, }); t.truthy(dec.attributes["attr"].default === "aaa"); t.truthy(GrimoireInterface.componentDeclarations.toArray().length === l + 1); @@ -37,8 +67,8 @@ test("registerComponent works correctly", (t) => { GrimoireInterface.registerComponent({ componentName: "Name", attributes: { - attr: { converter: "String", default: undefined } - } + attr: { converter: "String", default: undefined }, + }, }); }); @@ -60,17 +90,17 @@ test("registerComponent by object works correctly", async (t) => { attributes: { testValue: { converter: "String", - default: "bbb" + default: "bbb", }, testOverride: { converter: "String", - default: "bbb" - } + default: "bbb", + }, }, hoge: 0, - $test: function () { + $test() { this.hoge += 1; - } + }, }); const aaa = GrimoireInterface.componentDeclarations.get("Aaa"); @@ -94,16 +124,16 @@ test("registerComponent by object works correctly", async (t) => { attributes: { testValue2: { converter: "String", - default: "ccc" + default: "ccc", }, testOverride: { converter: "String", - default: "ccc" - } + default: "ccc", + }, }, - $test2: function () { + $test2() { // do nothing. - } + }, }, "Aaa"); t.truthy(GrimoireInterface.componentDeclarations.toArray().length === defaultComponentCount + 2); const bbb = GrimoireInterface.componentDeclarations.get("Bbb"); @@ -130,12 +160,12 @@ test("registerComponent by class works correctly", async (t) => { public static attributes = { testValue: { converter: "String", - default: "bbb" + default: "bbb", }, testOverride: { converter: "String", - default: "bbb" - } + default: "bbb", + }, }; public hoge = 0; public $test() { @@ -150,12 +180,12 @@ test("registerComponent by class works correctly", async (t) => { public static attributes = { testValue2: { converter: "String", - default: "ccc" + default: "ccc", }, testOverride: { converter: "String", default: "ccc", - } + }, }; public fuga = 7; public $test2() { @@ -215,12 +245,12 @@ test("registerComponent works correctly4", async (t) => { public static attributes: { [key: string]: any } = { testValue: { converter: "String", - default: "bbb" + default: "bbb", }, testOverride: { converter: "String", - default: "bbb" - } + default: "bbb", + }, }; public hoge = 0; public $test() { @@ -232,12 +262,12 @@ test("registerComponent works correctly4", async (t) => { public static attributes = { testValue2: { converter: "String", - default: "bbb" + default: "bbb", }, testOverride: { converter: "String", - default: "ccc" - } + default: "ccc", + }, }; public fuga = 7; public $test2() { @@ -290,13 +320,13 @@ test("registerNode/Component works correctly.", async t => { attributes: { hoge: { converter: "Number", - default: 9 - } - } + default: 9, + }, + }, }); await GrimoireInterface.resolvePlugins(); const a1 = GrimoireInterface.nodeDeclarations.get("a1"); - let a2 = GrimoireInterface.nodeDeclarations.get("a2"); + const a2 = GrimoireInterface.nodeDeclarations.get("a2"); const a3 = GrimoireInterface.nodeDeclarations.get("a3"); t.truthy(a1.requiredComponentsActual.toArray().length === 1); // grimoireCompone t.truthy(a2.requiredComponentsActual.toArray().length === 2); // grimoireCompone @@ -317,10 +347,10 @@ test("throw error on attempt registerComponent/Node by duplicate name.", t => { }); }); -test("register and resolvePlugins works preperly", async() => { +test("register and resolvePlugins works preperly", async () => { const spy1 = spy(); const spy2 = spy(); - const wrapPromise: any = function(s) { + const wrapPromise: any = function (s) { return () => { return new Promise(resolve => { s(); diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index e1f5184cb..59e07f990 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -1,15 +1,15 @@ +import "babel-polyfill"; +import xhrmock from "xhr-mock"; +import xmlserializer from "xmlserializer"; import Environment from "../src/Core/Environment"; import GomlLoader from "../src/Core/GomlLoader"; import GomlParser from "../src/Core/GomlParser"; import GrimoireInterface from "../src/Core/GrimoireInterface"; -import IAttributeConverterDeclaration from "../src/Interface/IAttributeConverterDeclaration"; -import jsdomAsync from "./JsDOMAsync"; -import IdentityMap from "../src/Core/IdentityMap"; import Identity from "../src/Core/Identity"; -import xhrmock from "xhr-mock"; +import IdentityMap from "../src/Core/IdentityMap"; +import IAttributeConverterDeclaration from "../src/Interface/IAttributeConverterDeclaration"; import XMLReader from "../src/Tools/XMLReader"; -import xmlserializer from "xmlserializer"; -import "babel-polyfill"; +import jsdomAsync from "./JsDOMAsync"; export default class TestEnvManager { @@ -41,7 +41,7 @@ export default class TestEnvManager { public static loadGoml(goml: string) { const doc = XMLReader.parseXML(goml); - const rootNode = GomlParser.parse(doc[0]); + const rootNode = GomlParser.parse(doc); GrimoireInterface.addRootNode(null, rootNode); } } diff --git a/test/TestUtil.ts b/test/TestUtil.ts index c5ab2053c..a182c5ece 100644 --- a/test/TestUtil.ts +++ b/test/TestUtil.ts @@ -21,7 +21,7 @@ export default class TestUtil { } public static DummyComponent(): Component { const dec = TestUtil.DummyComponentDeclaration(); - return dec.generateInstance(null); + return dec.generateInstance(); } public static DummyAttribute(name: Identity, component: Component, declaration: IAttributeDeclaration): Attribute { From 2145f75420c8bffa020fe6203b1cea9887214280 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 22 Oct 2017 05:51:46 +0900 Subject: [PATCH 057/146] feat: implement template node --- src/Components/GrimoireComponent.ts | 3 ++ src/Components/TemplateComponent.ts | 58 +++++++++++++++++++++++++ src/Converters/BooleanConverter.ts | 7 ++- src/Converters/StringConverter.ts | 4 +- src/Core/GrimoireInterfaceImpl.ts | 3 ++ test/Converters/BooleanConverterTest.ts | 20 ++++----- test/Converters/StringConverterTest.ts | 8 ++-- test/Core/GrimoireInterfaceTest.ts | 16 +++---- 8 files changed, 91 insertions(+), 28 deletions(-) create mode 100644 src/Components/TemplateComponent.ts diff --git a/src/Components/GrimoireComponent.ts b/src/Components/GrimoireComponent.ts index a0b44e391..fa1c826e0 100644 --- a/src/Components/GrimoireComponent.ts +++ b/src/Components/GrimoireComponent.ts @@ -3,8 +3,11 @@ import StringConverter from "../Converters/StringConverter"; import Component from "../Core/Component"; import Identity from "../Core/Identity"; import Namespace from "../Core/Namespace"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import { __NAMESPACE__ } from "../metaInfo"; +export { IAttributeConverterDeclaration }; + /** * Basic Component for all node. */ diff --git a/src/Components/TemplateComponent.ts b/src/Components/TemplateComponent.ts new file mode 100644 index 000000000..2d3468a7c --- /dev/null +++ b/src/Components/TemplateComponent.ts @@ -0,0 +1,58 @@ +import BooleanConverter from "../Converters/BooleanConverter"; +import StringConverter from "../Converters/StringConverter"; +import Component from "../Core/Component"; +import GomlNode from "../Core/GomlNode"; +import GomlParser from "../Core/GomlParser"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; +import XMLReader from "../Tools/XMLReader"; + +export { IAttributeConverterDeclaration }; + +/** + * template component + * TODO add document + */ +export default class TemplateComponent extends Component { // TODO test + /** + * name + */ + public static componentName = "Template"; + /** + * attributes + */ + public static attributes = { + goml: { + converter: StringConverter, + default: null, + }, + auto: { + converter: BooleanConverter, + default: true, + }, + }; + + /** + * clone node structure. + */ + public clone(node: GomlNode) { + throw new Error("not implement" + node.toString()); + } + + /** + * replace self with goml + */ + public inflate() { + const goml = this.getAttribute(TemplateComponent.attributes.goml); + if (goml) { + const doc = XMLReader.parseXML(goml); + const node = GomlParser.parse(doc); + this.node.addChild(node); + } + } + + protected $awake() { + if (this.getAttribute(TemplateComponent.attributes.auto)) { + this.inflate(); + } + } +} diff --git a/src/Converters/BooleanConverter.ts b/src/Converters/BooleanConverter.ts index 5f5f6b5df..0c0c740f3 100644 --- a/src/Converters/BooleanConverter.ts +++ b/src/Converters/BooleanConverter.ts @@ -1,7 +1,6 @@ -import Identity from "../Core/Identity"; import Namespace from "../Core/Namespace"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import { __NAMESPACE__ } from "../metaInfo"; -import { Undef } from "../Tools/Types"; export default { name: Namespace.define(__NAMESPACE__).for("Boolean"), @@ -14,7 +13,7 @@ export default { * @param {Attribute} attr [description] * @return {any} [description] */ - convert(val: any): Undef { + convert(val: any): boolean | undefined { if (typeof val === "boolean") { return val; } else if (typeof val === "string") { @@ -27,4 +26,4 @@ export default { } return undefined; }, -}; +} as IAttributeConverterDeclaration; diff --git a/src/Converters/StringConverter.ts b/src/Converters/StringConverter.ts index c71b917ca..c66f7f6f0 100644 --- a/src/Converters/StringConverter.ts +++ b/src/Converters/StringConverter.ts @@ -1,5 +1,5 @@ -import Identity from "../Core/Identity"; import Namespace from "../Core/Namespace"; +import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import { __NAMESPACE__ } from "../metaInfo"; import { Undef } from "../Tools/Types"; @@ -19,4 +19,4 @@ export default { } return undefined; }, -}; +} as IAttributeConverterDeclaration; diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 5f4b42fc2..7f7ef226f 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -1,5 +1,6 @@ import EEObject from "../Base/EEObject"; import GrimoireComponent from "../Components/GrimoireComponent"; +import TemplateComponent from "../Components/TemplateComponent"; import ArrayConverter from "../Converters/ArrayConverter"; import BooleanConverter from "../Converters/BooleanConverter"; import ComponentConverter from "../Converters/ComponentConverter"; @@ -147,7 +148,9 @@ export default class GrimoireInterfaceImpl extends EEObject { this.registerConverter(EnumConverter); this.registerConverter(ComponentConverter); this.registerComponent(GrimoireComponent); + this.registerComponent(TemplateComponent); this.registerNode("grimoire-node-base", ["GrimoireComponent"]); + this.registerNode("template", [TemplateComponent]); } /** diff --git a/test/Converters/BooleanConverterTest.ts b/test/Converters/BooleanConverterTest.ts index fe9109ce5..a9e8a9975 100644 --- a/test/Converters/BooleanConverterTest.ts +++ b/test/Converters/BooleanConverterTest.ts @@ -2,15 +2,15 @@ import test from "ava"; import BooleanConverter from "../../src/Converters/BooleanConverter"; test("BooleanConverter should convert collectly", t => { - t.truthy(BooleanConverter.convert(true) === true); - t.truthy(BooleanConverter.convert(false) === false); - t.truthy(BooleanConverter.convert("true") === true); - t.truthy(BooleanConverter.convert("false") === false); + t.truthy(BooleanConverter.convert(true, null as any) === true); + t.truthy(BooleanConverter.convert(false, null as any) === false); + t.truthy(BooleanConverter.convert("true", null as any) === true); + t.truthy(BooleanConverter.convert("false", null as any) === false); - t.truthy(BooleanConverter.convert("aaaa") === undefined); - t.truthy(BooleanConverter.convert("False") === undefined); - t.truthy(BooleanConverter.convert("True") === undefined); - t.truthy(BooleanConverter.convert("") === undefined); - t.truthy(BooleanConverter.convert(null) === undefined); - t.truthy(BooleanConverter.convert(123) === undefined); + t.truthy(BooleanConverter.convert("aaaa", null as any) === undefined); + t.truthy(BooleanConverter.convert("False", null as any) === undefined); + t.truthy(BooleanConverter.convert("True", null as any) === undefined); + t.truthy(BooleanConverter.convert("", null as any) === undefined); + t.truthy(BooleanConverter.convert(null, null as any) === undefined); + t.truthy(BooleanConverter.convert(123, null as any) === undefined); }); diff --git a/test/Converters/StringConverterTest.ts b/test/Converters/StringConverterTest.ts index 8666a053a..ab11368d6 100644 --- a/test/Converters/StringConverterTest.ts +++ b/test/Converters/StringConverterTest.ts @@ -2,8 +2,8 @@ import test from "ava"; import StringConverter from "../../src/Converters/StringConverter"; test("StringConverter should convert collectly", t => { - t.truthy(StringConverter.convert("HELLO") === "HELLO"); - t.truthy(StringConverter.convert(null) === null); - t.truthy(StringConverter.convert(123) === "123"); - t.truthy(StringConverter.convert({ toString: () => "value" }) === "value"); + t.truthy(StringConverter.convert("HELLO", null as any) === "HELLO"); + t.truthy(StringConverter.convert(null, null as any) === null); + t.truthy(StringConverter.convert(123, null as any) === "123"); + t.truthy(StringConverter.convert({ toString: () => "value" }, null as any) === "value"); }); diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index 72efec8a1..792c86b71 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -16,15 +16,15 @@ TestEnvManager.init(); const tc1_html = fs.readFile("../_TestResource/GrimoireInterfaceTest_Case1.html"); -test.beforeEach(async () => { +test.beforeEach(async() => { GrimoireInterface.clear(); GrimoireInterface.resolvePlugins(); }); test("properties are initialized correctly", t => { - t.truthy(GrimoireInterface.nodeDeclarations.toArray().length === 1); // only grimoire-node-base + t.truthy(GrimoireInterface.nodeDeclarations.toArray().length > 0); // grimoire-node-base, template,,, t.truthy(GrimoireInterface.converters.toArray().length > 0); - t.truthy(GrimoireInterface.componentDeclarations.toArray().length === 1); // only GrimoireComponent + t.truthy(GrimoireInterface.componentDeclarations.toArray().length > 0); // GrimoireComponent and more }); test("call as function works correctly", async t => { @@ -83,7 +83,7 @@ test("registerComponent works correctly", (t) => { }); }); -test("registerComponent by object works correctly", async (t) => { +test("registerComponent by object works correctly", async(t) => { const defaultComponentCount = GrimoireInterface.componentDeclarations.toArray().length; GrimoireInterface.registerComponent({ componentName: "Aaa", @@ -152,7 +152,7 @@ test("registerComponent by object works correctly", async (t) => { t.truthy((bbb2 as any).$test); t.truthy((bbb2 as any).$test2); }); -test("registerComponent by class works correctly", async (t) => { +test("registerComponent by class works correctly", async(t) => { const defaultComponentCount = GrimoireInterface.componentDeclarations.toArray().length; class Aaa extends Component { @@ -238,7 +238,7 @@ test("registerComponent by class works correctly", async (t) => { t.truthy((bbb2 as any).overridedFunc() === 7); }); -test("registerComponent works correctly4", async (t) => { +test("registerComponent works correctly4", async(t) => { const defaultComponentCount = GrimoireInterface.componentDeclarations.toArray().length; class Aaa extends Component { public static componentName = "Aaa"; @@ -347,10 +347,10 @@ test("throw error on attempt registerComponent/Node by duplicate name.", t => { }); }); -test("register and resolvePlugins works preperly", async () => { +test("register and resolvePlugins works preperly", async() => { const spy1 = spy(); const spy2 = spy(); - const wrapPromise: any = function (s) { + const wrapPromise: any = function(s) { return () => { return new Promise(resolve => { s(); From c91c8a9007e09541836e92b2a7a22dc22762107c Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 22 Oct 2017 12:25:59 +0900 Subject: [PATCH 058/146] fix: change directory name --- .../GrimoireComponent.ts | 4 +-- .../TemplateComponent.ts | 6 ++-- .../ArrayConverter.ts | 0 .../BooleanConverter.ts | 0 .../ComponentConverter.ts | 4 +-- .../EnumConverter.ts | 0 .../NumberArrayConverter.ts | 0 .../NumberConverter.ts | 4 +-- .../ObjectConverter.ts | 0 .../StringArrayConverter.ts | 0 .../StringConverter.ts | 2 +- src/Core/Attribute.ts | 8 +++--- src/Core/AttributeManager.ts | 8 +++--- src/Core/Component.ts | 6 ++-- src/Core/ComponentDeclaration.ts | 10 +++---- src/Core/Environment.ts | 2 +- src/Core/GomlLoader.ts | 4 +-- src/Core/GomlNode.ts | 10 +++---- src/Core/GomlParser.ts | 4 +-- src/Core/GrimoireInterface.ts | 2 +- src/Core/GrimoireInterfaceImpl.ts | 28 +++++++++---------- src/Core/Identity.ts | 4 +-- src/Core/IdentityMap.ts | 6 ++-- src/Core/Namespace.ts | 2 +- src/Core/NodeDeclaration.ts | 6 ++-- src/Core/NodeInterface.ts | 6 ++-- .../IAttributeConverterDeclaration.ts | 2 +- src/Interface/IAttributeDeclaration.ts | 2 +- src/{Tools => Tool}/Ensure.ts | 0 src/{Tools => Tool}/IdResolver.ts | 0 src/{Tools => Tool}/MessageException.ts | 0 src/{Tools => Tool}/Types.ts | 0 src/{Tools => Tool}/Utility.ts | 0 src/{Tools => Tool}/XMLHttpRequestAsync.ts | 0 src/{Tools => Tool}/XMLReader.ts | 0 test/Converters/BooleanConverterTest.ts | 2 +- test/Converters/ComponentConverterTest.ts | 6 ++-- test/Converters/EnumConverterTest.ts | 8 +++--- test/Converters/NumberConverterTest.ts | 2 +- test/Converters/ObjectConverterTest.ts | 2 +- test/Converters/StringConverterTest.ts | 2 +- test/Core/AttributeTest.ts | 4 +-- test/Core/GomlLoaderTest.ts | 16 +++++------ test/Core/GomlNode2Test.ts | 16 +++++------ test/Core/GomlParserTest.ts | 2 +- test/TestEnvManager.ts | 2 +- test/TestUtil.ts | 4 +-- test/Tools/EnsureTest.ts | 2 +- test/Tools/IdResolverTest.ts | 8 +++--- test/Tools/UtilityTest.ts | 2 +- test/Tools/XMLReaderTest.ts | 4 +-- 51 files changed, 106 insertions(+), 106 deletions(-) rename src/{Components => Component}/GrimoireComponent.ts (92%) rename src/{Components => Component}/TemplateComponent.ts (87%) rename src/{Converters => Converter}/ArrayConverter.ts (100%) rename src/{Converters => Converter}/BooleanConverter.ts (100%) rename src/{Converters => Converter}/ComponentConverter.ts (95%) rename src/{Converters => Converter}/EnumConverter.ts (100%) rename src/{Converters => Converter}/NumberArrayConverter.ts (100%) rename src/{Converters => Converter}/NumberConverter.ts (91%) rename src/{Converters => Converter}/ObjectConverter.ts (100%) rename src/{Converters => Converter}/StringArrayConverter.ts (100%) rename src/{Converters => Converter}/StringConverter.ts (93%) rename src/{Tools => Tool}/Ensure.ts (100%) rename src/{Tools => Tool}/IdResolver.ts (100%) rename src/{Tools => Tool}/MessageException.ts (100%) rename src/{Tools => Tool}/Types.ts (100%) rename src/{Tools => Tool}/Utility.ts (100%) rename src/{Tools => Tool}/XMLHttpRequestAsync.ts (100%) rename src/{Tools => Tool}/XMLReader.ts (100%) diff --git a/src/Components/GrimoireComponent.ts b/src/Component/GrimoireComponent.ts similarity index 92% rename from src/Components/GrimoireComponent.ts rename to src/Component/GrimoireComponent.ts index fa1c826e0..4319ceb11 100644 --- a/src/Components/GrimoireComponent.ts +++ b/src/Component/GrimoireComponent.ts @@ -1,5 +1,5 @@ -import BooleanConverter from "../Converters/BooleanConverter"; -import StringConverter from "../Converters/StringConverter"; +import BooleanConverter from "../Converter/BooleanConverter"; +import StringConverter from "../Converter/StringConverter"; import Component from "../Core/Component"; import Identity from "../Core/Identity"; import Namespace from "../Core/Namespace"; diff --git a/src/Components/TemplateComponent.ts b/src/Component/TemplateComponent.ts similarity index 87% rename from src/Components/TemplateComponent.ts rename to src/Component/TemplateComponent.ts index 2d3468a7c..6138b44e2 100644 --- a/src/Components/TemplateComponent.ts +++ b/src/Component/TemplateComponent.ts @@ -1,10 +1,10 @@ -import BooleanConverter from "../Converters/BooleanConverter"; -import StringConverter from "../Converters/StringConverter"; +import BooleanConverter from "../Converter/BooleanConverter"; +import StringConverter from "../Converter/StringConverter"; import Component from "../Core/Component"; import GomlNode from "../Core/GomlNode"; import GomlParser from "../Core/GomlParser"; import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; -import XMLReader from "../Tools/XMLReader"; +import XMLReader from "../Tool/XMLReader"; export { IAttributeConverterDeclaration }; diff --git a/src/Converters/ArrayConverter.ts b/src/Converter/ArrayConverter.ts similarity index 100% rename from src/Converters/ArrayConverter.ts rename to src/Converter/ArrayConverter.ts diff --git a/src/Converters/BooleanConverter.ts b/src/Converter/BooleanConverter.ts similarity index 100% rename from src/Converters/BooleanConverter.ts rename to src/Converter/BooleanConverter.ts diff --git a/src/Converters/ComponentConverter.ts b/src/Converter/ComponentConverter.ts similarity index 95% rename from src/Converters/ComponentConverter.ts rename to src/Converter/ComponentConverter.ts index 90d454dba..00bbddb46 100644 --- a/src/Converters/ComponentConverter.ts +++ b/src/Converter/ComponentConverter.ts @@ -1,8 +1,8 @@ import Attribute from "../Core/Attribute"; import Component from "../Core/Component"; import GomlNode from "../Core/GomlNode"; -import Ensure from "../Tools/Ensure"; -import { Undef } from "../Tools/Types"; +import Ensure from "../Tool/Ensure"; +import { Undef } from "../Tool/Types"; /** * コンポーネントのためのコンバータです。 diff --git a/src/Converters/EnumConverter.ts b/src/Converter/EnumConverter.ts similarity index 100% rename from src/Converters/EnumConverter.ts rename to src/Converter/EnumConverter.ts diff --git a/src/Converters/NumberArrayConverter.ts b/src/Converter/NumberArrayConverter.ts similarity index 100% rename from src/Converters/NumberArrayConverter.ts rename to src/Converter/NumberArrayConverter.ts diff --git a/src/Converters/NumberConverter.ts b/src/Converter/NumberConverter.ts similarity index 91% rename from src/Converters/NumberConverter.ts rename to src/Converter/NumberConverter.ts index 82e48df91..922d20ff0 100644 --- a/src/Converters/NumberConverter.ts +++ b/src/Converter/NumberConverter.ts @@ -1,5 +1,5 @@ -import { Undef } from "../Tools/Types"; -import Utility from "../Tools/Utility"; +import { Undef } from "../Tool/Types"; +import Utility from "../Tool/Utility"; export default { name: "Number", diff --git a/src/Converters/ObjectConverter.ts b/src/Converter/ObjectConverter.ts similarity index 100% rename from src/Converters/ObjectConverter.ts rename to src/Converter/ObjectConverter.ts diff --git a/src/Converters/StringArrayConverter.ts b/src/Converter/StringArrayConverter.ts similarity index 100% rename from src/Converters/StringArrayConverter.ts rename to src/Converter/StringArrayConverter.ts diff --git a/src/Converters/StringConverter.ts b/src/Converter/StringConverter.ts similarity index 93% rename from src/Converters/StringConverter.ts rename to src/Converter/StringConverter.ts index c66f7f6f0..8a0730bf3 100644 --- a/src/Converters/StringConverter.ts +++ b/src/Converter/StringConverter.ts @@ -1,7 +1,7 @@ import Namespace from "../Core/Namespace"; import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import { __NAMESPACE__ } from "../metaInfo"; -import { Undef } from "../Tools/Types"; +import { Undef } from "../Tool/Types"; export default { name: Namespace.define(__NAMESPACE__).for("String"), diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index c1e7510a3..bf78b6f94 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -3,10 +3,10 @@ import Identity from "../Core/Identity"; import IdentityMap from "../Core/IdentityMap"; import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; -import Ensure from "../Tools/Ensure"; -import IdResolver from "../Tools/IdResolver"; -import { GomlInterface, Name, Nullable, Undef } from "../Tools/Types"; -import Utility from "../Tools/Utility"; +import Ensure from "../Tool/Ensure"; +import IdResolver from "../Tool/IdResolver"; +import { GomlInterface, Name, Nullable, Undef } from "../Tool/Types"; +import Utility from "../Tool/Utility"; import Component from "./Component"; /** diff --git a/src/Core/AttributeManager.ts b/src/Core/AttributeManager.ts index c31043adc..0ca75fc94 100644 --- a/src/Core/AttributeManager.ts +++ b/src/Core/AttributeManager.ts @@ -1,8 +1,8 @@ import Attribute from "../Core/Attribute"; -import Ensure from "../Tools/Ensure"; -import IdResolver from "../Tools/IdResolver"; -import { Name, Undef } from "../Tools/Types"; -import Utility from "../Tools/Utility"; +import Ensure from "../Tool/Ensure"; +import IdResolver from "../Tool/IdResolver"; +import { Name, Undef } from "../Tool/Types"; +import Utility from "../Tool/Utility"; import Identity from "./Identity"; import Namespace from "./Namespace"; diff --git a/src/Core/Component.ts b/src/Core/Component.ts index dc2824e97..8380d9092 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -1,9 +1,9 @@ import IDObject from "../Base/IDObject"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; -import Ensure from "../Tools/Ensure"; -import { GomlInterface, Name, Nullable } from "../Tools/Types"; -import Utility from "../Tools/Utility"; +import Ensure from "../Tool/Ensure"; +import { GomlInterface, Name, Nullable } from "../Tool/Types"; +import Utility from "../Tool/Utility"; import Attribute from "./Attribute"; import ComponentDeclaration from "./ComponentDeclaration"; import GomlNode from "./GomlNode"; diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index ec3a160b5..253fa1bcf 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -1,8 +1,8 @@ import Environment from "../Core/Environment"; import IAttributeDeclaration from "../Interface/IAttributeDeclaration"; -import Ensure from "../Tools/Ensure"; -import IdResolver from "../Tools/IdResolver"; -import { ComponentRegistering, Ctor, Name } from "../Tools/Types"; +import Ensure from "../Tool/Ensure"; +import IdResolver from "../Tool/IdResolver"; +import { ComponentRegistering, Ctor, Name } from "../Tool/Types"; import Attribute from "./Attribute"; import Component from "./Component"; import Constants from "./Constants"; @@ -132,7 +132,7 @@ export default class ComponentDeclaration { if (typeof obj === "function") { // obj is constructor const inheritsAttr = this._extractInheritsAttributes(obj); if (baseConstructor) { // inherits - const newCtor = function(this: any) { + const newCtor = function (this: any) { baseConstructor.call(this); obj.call(this); }; @@ -151,7 +151,7 @@ export default class ComponentDeclaration { throw new Error("Base component comstructor must extends Compoent class."); } const ctor = baseConstructor || Component; - const newCtor = function(this: any) { + const newCtor = function (this: any) { ctor.call(this); }; (obj as any).__proto__ = ctor.prototype; diff --git a/src/Core/Environment.ts b/src/Core/Environment.ts index e635673cb..e863d65a6 100644 --- a/src/Core/Environment.ts +++ b/src/Core/Environment.ts @@ -1,4 +1,4 @@ -import { GrimoireInterface } from "../Tools/Types"; +import { GrimoireInterface } from "../Tool/Types"; /** * Environment manager diff --git a/src/Core/GomlLoader.ts b/src/Core/GomlLoader.ts index 9405ff2f2..97e8a765f 100644 --- a/src/Core/GomlLoader.ts +++ b/src/Core/GomlLoader.ts @@ -1,6 +1,6 @@ import GrimoireInterface from "../Core/GrimoireInterface"; -import XMLHttpRequestAsync from "../Tools/XMLHttpRequestAsync"; -import XMLReader from "../Tools/XMLReader"; +import XMLHttpRequestAsync from "../Tool/XMLHttpRequestAsync"; +import XMLReader from "../Tool/XMLReader"; import Environment from "./Environment"; import GomlParser from "./GomlParser"; diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index 293711d9a..e29ceada3 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -2,16 +2,16 @@ import EEObject from "../Base/EEObject"; import AttributeManager from "../Core/AttributeManager"; import GrimoireInterface from "../Core/GrimoireInterface"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; -import Ensure from "../Tools/Ensure"; -import MessageException from "../Tools/MessageException"; +import Ensure from "../Tool/Ensure"; +import MessageException from "../Tool/MessageException"; import { Ctor, GomlInterface, Name, Nullable, -} from "../Tools/Types"; -import Utility from "../Tools/Utility"; -import XMLReader from "../Tools/XMLReader"; +} from "../Tool/Types"; +import Utility from "../Tool/Utility"; +import XMLReader from "../Tool/XMLReader"; import Attribute from "./Attribute"; import Component from "./Component"; import Constants from "./Constants"; diff --git a/src/Core/GomlParser.ts b/src/Core/GomlParser.ts index 2d1b3b479..3a97f5f4a 100644 --- a/src/Core/GomlParser.ts +++ b/src/Core/GomlParser.ts @@ -1,8 +1,8 @@ import GrimoireInterface from "../Core/GrimoireInterface"; import IGrimoireComponentModel from "../Interface/IGrimoireComponentModel"; import IGrimoireNodeModel from "../Interface/IGrimoireNodeModel"; -import Utility from "../Tools/Utility"; -import XMLReader from "../Tools/XMLReader"; +import Utility from "../Tool/Utility"; +import XMLReader from "../Tool/XMLReader"; import Component from "./Component"; import Environment from "./Environment"; import GomlNode from "./GomlNode"; diff --git a/src/Core/GrimoireInterface.ts b/src/Core/GrimoireInterface.ts index bbef2d31d..d16b6ade5 100644 --- a/src/Core/GrimoireInterface.ts +++ b/src/Core/GrimoireInterface.ts @@ -1,5 +1,5 @@ import GomlNode from "../Core/GomlNode"; -import { GomlInterface, GrimoireInterface } from "../Tools/Types"; +import { GomlInterface, GrimoireInterface } from "../Tool/Types"; import Environment from "./Environment"; import GomlInterfaceImpl from "./GomlInterfaceImpl"; import GrimoireInterfaceImpl from "./GrimoireInterfaceImpl"; diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 372d9494e..73da809b3 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -1,15 +1,15 @@ import EEObject from "../Base/EEObject"; -import GrimoireComponent from "../Components/GrimoireComponent"; -import TemplateComponent from "../Components/TemplateComponent"; -import ArrayConverter from "../Converters/ArrayConverter"; -import BooleanConverter from "../Converters/BooleanConverter"; -import ComponentConverter from "../Converters/ComponentConverter"; -import EnumConverter from "../Converters/EnumConverter"; -import NumberArrayConverter from "../Converters/NumberArrayConverter"; -import NumberConverter from "../Converters/NumberConverter"; -import ObjectConverter from "../Converters/ObjectConverter"; -import StringArrayConverter from "../Converters/StringArrayConverter"; -import StringConverter from "../Converters/StringConverter"; +import GrimoireComponent from "../Component/GrimoireComponent"; +import TemplateComponent from "../Component/TemplateComponent"; +import ArrayConverter from "../Converter/ArrayConverter"; +import BooleanConverter from "../Converter/BooleanConverter"; +import ComponentConverter from "../Converter/ComponentConverter"; +import EnumConverter from "../Converter/EnumConverter"; +import NumberArrayConverter from "../Converter/NumberArrayConverter"; +import NumberConverter from "../Converter/NumberConverter"; +import ObjectConverter from "../Converter/ObjectConverter"; +import StringArrayConverter from "../Converter/StringArrayConverter"; +import StringConverter from "../Converter/StringConverter"; import Component from "../Core/Component"; import ComponentDeclaration from "../Core/ComponentDeclaration"; import GomlInterfaceImpl from "../Core/GomlInterfaceImpl"; @@ -19,14 +19,14 @@ import Namespace from "../Core/Namespace"; import NodeDeclaration from "../Core/NodeDeclaration"; import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; import ITreeInitializedInfo from "../Interface/ITreeInitializedInfo"; -import Ensure from "../Tools/Ensure"; +import Ensure from "../Tool/Ensure"; import { ComponentRegistering, Ctor, Name, Nullable, -} from "../Tools/Types"; -import Utility from "../Tools/Utility"; +} from "../Tool/Types"; +import Utility from "../Tool/Utility"; import Attribute from "./Attribute"; import Constants from "./Constants"; import Environment from "./Environment"; diff --git a/src/Core/Identity.ts b/src/Core/Identity.ts index 4f6f9fcd1..4da962cbb 100644 --- a/src/Core/Identity.ts +++ b/src/Core/Identity.ts @@ -1,5 +1,5 @@ -import Ensure from "../Tools/Ensure"; -import IdResolver from "../Tools/IdResolver"; +import Ensure from "../Tool/Ensure"; +import IdResolver from "../Tool/IdResolver"; import Namespace from "./Namespace"; /** diff --git a/src/Core/IdentityMap.ts b/src/Core/IdentityMap.ts index fac10e66a..bb2877345 100644 --- a/src/Core/IdentityMap.ts +++ b/src/Core/IdentityMap.ts @@ -1,7 +1,7 @@ import Namespace from "../Core/Namespace"; -import Ensure from "../Tools/Ensure"; -import IdResolver from "../Tools/IdResolver"; -import { Name, Nullable, Undef } from "../Tools/Types"; +import Ensure from "../Tool/Ensure"; +import IdResolver from "../Tool/IdResolver"; +import { Name, Nullable, Undef } from "../Tool/Types"; import Identity from "./Identity"; type Dict = { [key: string]: V }; diff --git a/src/Core/Namespace.ts b/src/Core/Namespace.ts index 636537cc1..ba9ab5d9f 100644 --- a/src/Core/Namespace.ts +++ b/src/Core/Namespace.ts @@ -1,4 +1,4 @@ -import Utility from "../Tools/Utility"; +import Utility from "../Tool/Utility"; import Identity from "./Identity"; /** diff --git a/src/Core/NodeDeclaration.ts b/src/Core/NodeDeclaration.ts index 4864a6fdb..deeed3965 100644 --- a/src/Core/NodeDeclaration.ts +++ b/src/Core/NodeDeclaration.ts @@ -1,7 +1,7 @@ import GrimoireInterface from "../Core/GrimoireInterface"; -import Ensure from "../Tools/Ensure"; -import IdResolver from "../Tools/IdResolver"; -import { Ctor, Name } from "../Tools/Types"; +import Ensure from "../Tool/Ensure"; +import IdResolver from "../Tool/IdResolver"; +import { Ctor, Name } from "../Tool/Types"; import Component from "./Component"; import Constants from "./Constants"; import Identity from "./Identity"; diff --git a/src/Core/NodeInterface.ts b/src/Core/NodeInterface.ts index a9659ffe1..777091a46 100644 --- a/src/Core/NodeInterface.ts +++ b/src/Core/NodeInterface.ts @@ -2,9 +2,9 @@ import { ListenerFn } from "eventemitter3"; import Attribute from "../Core/Attribute"; import GomlNode from "../Core/GomlNode"; import GomlParser from "../Core/GomlParser"; -import { Name, Nullable } from "../Tools/Types"; -import Utility from "../Tools/Utility"; -import XMLReader from "../Tools/XMLReader"; +import { Name, Nullable } from "../Tool/Types"; +import Utility from "../Tool/Utility"; +import XMLReader from "../Tool/XMLReader"; /** * interface for operate multicast nodes. diff --git a/src/Interface/IAttributeConverterDeclaration.ts b/src/Interface/IAttributeConverterDeclaration.ts index 3bb9fa67f..6993e0f5e 100644 --- a/src/Interface/IAttributeConverterDeclaration.ts +++ b/src/Interface/IAttributeConverterDeclaration.ts @@ -1,5 +1,5 @@ import Attribute from "../Core/Attribute"; -import { Name } from "../Tools/Types"; +import { Name } from "../Tool/Types"; /** * interface for converter declaration diff --git a/src/Interface/IAttributeDeclaration.ts b/src/Interface/IAttributeDeclaration.ts index 2fbfdf1b5..2b3a50041 100644 --- a/src/Interface/IAttributeDeclaration.ts +++ b/src/Interface/IAttributeDeclaration.ts @@ -1,4 +1,4 @@ -import { Name } from "../Tools/Types"; +import { Name } from "../Tool/Types"; import IAttributeConverterDeclaration from "./IAttributeConverterDeclaration"; /** diff --git a/src/Tools/Ensure.ts b/src/Tool/Ensure.ts similarity index 100% rename from src/Tools/Ensure.ts rename to src/Tool/Ensure.ts diff --git a/src/Tools/IdResolver.ts b/src/Tool/IdResolver.ts similarity index 100% rename from src/Tools/IdResolver.ts rename to src/Tool/IdResolver.ts diff --git a/src/Tools/MessageException.ts b/src/Tool/MessageException.ts similarity index 100% rename from src/Tools/MessageException.ts rename to src/Tool/MessageException.ts diff --git a/src/Tools/Types.ts b/src/Tool/Types.ts similarity index 100% rename from src/Tools/Types.ts rename to src/Tool/Types.ts diff --git a/src/Tools/Utility.ts b/src/Tool/Utility.ts similarity index 100% rename from src/Tools/Utility.ts rename to src/Tool/Utility.ts diff --git a/src/Tools/XMLHttpRequestAsync.ts b/src/Tool/XMLHttpRequestAsync.ts similarity index 100% rename from src/Tools/XMLHttpRequestAsync.ts rename to src/Tool/XMLHttpRequestAsync.ts diff --git a/src/Tools/XMLReader.ts b/src/Tool/XMLReader.ts similarity index 100% rename from src/Tools/XMLReader.ts rename to src/Tool/XMLReader.ts diff --git a/test/Converters/BooleanConverterTest.ts b/test/Converters/BooleanConverterTest.ts index a9e8a9975..8229fbd88 100644 --- a/test/Converters/BooleanConverterTest.ts +++ b/test/Converters/BooleanConverterTest.ts @@ -1,5 +1,5 @@ import test from "ava"; -import BooleanConverter from "../../src/Converters/BooleanConverter"; +import BooleanConverter from "../../src/Converter/BooleanConverter"; test("BooleanConverter should convert collectly", t => { t.truthy(BooleanConverter.convert(true, null as any) === true); diff --git a/test/Converters/ComponentConverterTest.ts b/test/Converters/ComponentConverterTest.ts index 45435587f..e911204c6 100644 --- a/test/Converters/ComponentConverterTest.ts +++ b/test/Converters/ComponentConverterTest.ts @@ -1,13 +1,13 @@ import test from "ava"; -import ComponentConverter from "../../src/Converters/ComponentConverter"; +import ComponentConverter from "../../src/Converter/ComponentConverter"; test("verify works correctly", t => { t.notThrows(() => { ComponentConverter.verify({ declaration: { - target: "hoge" - } + target: "hoge", + }, } as any); }); t.throws(() => { diff --git a/test/Converters/EnumConverterTest.ts b/test/Converters/EnumConverterTest.ts index f4a84dd21..ca1c95297 100644 --- a/test/Converters/EnumConverterTest.ts +++ b/test/Converters/EnumConverterTest.ts @@ -1,6 +1,6 @@ import test from "ava"; -import EnumConverter from "../../src/Converters/EnumConverter"; +import EnumConverter from "../../src/Converter/EnumConverter"; const mockAttrDec = { declaration: { @@ -9,15 +9,15 @@ const mockAttrDec = { table: { "first": 1, "second": 2, - "third": 3 - } + "third": 3, + }, }, } as any; const invalidMockAttrDec = { declaration: { coverter: "Enum", - default: "Hoge" + default: "Hoge", }, } as any; diff --git a/test/Converters/NumberConverterTest.ts b/test/Converters/NumberConverterTest.ts index 65c5ca96e..f220ceb68 100644 --- a/test/Converters/NumberConverterTest.ts +++ b/test/Converters/NumberConverterTest.ts @@ -1,5 +1,5 @@ import test from "ava"; -import NumberConverter from "../../src/Converters/NumberConverter"; +import NumberConverter from "../../src/Converter/NumberConverter"; import TestEnvManager from "../TestEnvManager"; TestEnvManager.init(); diff --git a/test/Converters/ObjectConverterTest.ts b/test/Converters/ObjectConverterTest.ts index cd2225832..479f82d66 100644 --- a/test/Converters/ObjectConverterTest.ts +++ b/test/Converters/ObjectConverterTest.ts @@ -1,5 +1,5 @@ import test from "ava"; -import ObjectConverter from "../../src/Converters/ObjectConverter"; +import ObjectConverter from "../../src/Converter/ObjectConverter"; test("ObjectConverter should convert collectly", t => { t.truthy(ObjectConverter.convert("HELLO") === "HELLO"); diff --git a/test/Converters/StringConverterTest.ts b/test/Converters/StringConverterTest.ts index ab11368d6..37f1d9505 100644 --- a/test/Converters/StringConverterTest.ts +++ b/test/Converters/StringConverterTest.ts @@ -1,5 +1,5 @@ import test from "ava"; -import StringConverter from "../../src/Converters/StringConverter"; +import StringConverter from "../../src/Converter/StringConverter"; test("StringConverter should convert collectly", t => { t.truthy(StringConverter.convert("HELLO", null as any) === "HELLO"); diff --git a/test/Core/AttributeTest.ts b/test/Core/AttributeTest.ts index 35dabe2dd..1c65a5064 100644 --- a/test/Core/AttributeTest.ts +++ b/test/Core/AttributeTest.ts @@ -1,6 +1,6 @@ import test from "ava"; import { assert, spy } from "sinon"; -import GrimoireComponent from "../../src/Components/GrimoireComponent"; +import GrimoireComponent from "../../src/Component/GrimoireComponent"; import Attribute from "../../src/Core/Attribute"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Identity from "../../src/Core/Identity"; @@ -11,7 +11,7 @@ TestEnvManager.init(); const GOML = ""; -test.beforeEach(async () => { +test.beforeEach(async() => { GrimoireInterface.clear(); GrimoireInterface.registerNode("goml"); }); diff --git a/test/Core/GomlLoaderTest.ts b/test/Core/GomlLoaderTest.ts index a99078d45..cb71e0054 100644 --- a/test/Core/GomlLoaderTest.ts +++ b/test/Core/GomlLoaderTest.ts @@ -8,7 +8,7 @@ import jsdomAsync from "../JsDOMAsync"; import prequire from "proxyquire"; import test from "ava"; import TestEnvManager from "../TestEnvManager"; -import XMLReader from "../../src/Tools/XMLReader"; +import XMLReader from "../../src/Tool/XMLReader"; import { registerConflictComponent1, registerConflictComponent2, @@ -42,7 +42,7 @@ TestEnvManager.mock("http://grimoire.gl/index3.goml", "\n"); function mockXMLParse(func) { return prequire("../../src/Core/GomlLoader", { - "../Tools/XMLReader": { + "../Tool/XMLReader": { default: { parseXML: (srcHtml) => { func(srcHtml); @@ -53,7 +53,7 @@ function mockXMLParse(func) { }).default; } -test.beforeEach(async () => { +test.beforeEach(async() => { GrimoireInterface.clear(); registerGoml(); registerTestNode1(); @@ -83,7 +83,7 @@ test("Processing script[type=\"text/goml\"] tag correctly when the text content s(xml.replace(/[\n\s]/g, "")); }); await mockedParseXML.loadFromScriptTag(scriptTags.item(0)); - t.truthy(s.calledWith(``)); + t.truthy(s.calledWith("")); }); test("Processing script[type=\"text/goml\"] tag correctly when the src attribute was existing", async (t) => { @@ -96,10 +96,10 @@ test("Processing script[type=\"text/goml\"] tag correctly when the src attribute }); await mockedParseXML.loadFromScriptTag(scriptTags.item(0)); - t.truthy(s.calledWith(``)); + t.truthy(s.calledWith("")); }); -test("Processing goml scripts from query", async (t) => { +test("Processing goml scripts from query", async(t) => { const window = await jsdomAsync(testcase3_html, []); Environment.document = window.document; const s = spy(); @@ -110,7 +110,7 @@ test("Processing goml scripts from query", async (t) => { t.truthy(s.calledWith("\n")); }); -test("Processing goml scripts for page", async (t) => { +test("Processing goml scripts for page", async(t) => { const window = await jsdomAsync(testcase4_html, []); Environment.document = window.document; const s = spy(); @@ -121,7 +121,7 @@ test("Processing goml scripts for page", async (t) => { t.truthy(s.calledWith("\n")); }); -test("all text/goml scripts tags should be loaded on loadForPage", async (t) => { +test("all text/goml scripts tags should be loaded on loadForPage", async(t) => { const s = spy(); const original = GrimoireInterface.addRootNode.bind(GrimoireInterface); GrimoireInterface.addRootNode = (tag: HTMLScriptElement, rootNode: GomlNode) => { diff --git a/test/Core/GomlNode2Test.ts b/test/Core/GomlNode2Test.ts index 8f1435a54..670dfdd4f 100644 --- a/test/Core/GomlNode2Test.ts +++ b/test/Core/GomlNode2Test.ts @@ -4,7 +4,7 @@ import Component from "../../src/Core/Component"; import fs from "../fileHelper"; import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; -import GrimoireComponent from "../../src/Components/GrimoireComponent"; +import GrimoireComponent from "../../src/Component/GrimoireComponent"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Identity from "../../src/Core/Identity"; import test from "ava"; @@ -323,7 +323,7 @@ test("broadcastMessage should not invoke message if the node is not enabled", (t test("class attribute can be obatined as default", (t) => { const testNode3 = rootNode.children[0]; - let classes = testNode3.getAttribute("class"); + const classes = testNode3.getAttribute("class"); t.truthy(classes.length === 1); t.truthy(classes[0] === "classTest"); }); @@ -371,7 +371,7 @@ test("get/setAttribute should work correctly 2", t => { const c = rootNode.getComponent("GrimoireComponent"); (c as any).__addAttribute("hoge", { converter: "String", - default: "aaa" + default: "aaa", }); const att = rootNode.getAttribute("hoge"); t.truthy(att === "aaa"); @@ -382,7 +382,7 @@ test("get/setAttribute should work correctly 3", t => { rootNode.setAttribute("hoge", "bbb"); (c as any).__addAttribute("hoge", { converter: "String", - default: "aaa" + default: "aaa", }); const att = rootNode.getAttribute("hoge"); t.truthy(att === "bbb"); @@ -393,7 +393,7 @@ test("get/setAttribute should work correctly 4", t => { rootNode.setAttribute("ns1.hoge", "bbb"); (c as any).__addAttribute("hoge", { converter: "String", - default: "aaa" + default: "aaa", }); const att = rootNode.getAttribute("hoge"); t.truthy(att === "aaa"); @@ -405,7 +405,7 @@ test("attribute buffer is valid only last set value.", t => { rootNode.setAttribute("ns1.hoge", "ccc"); (c as any).__addAttribute("ns1.hoge", { converter: "String", - default: "aaa" + default: "aaa", }); let att = rootNode.getAttribute("ns1.hoge"); t.truthy(att === "ccc"); @@ -508,7 +508,7 @@ test("addNode works correctly", (t) => { t.truthy(child.getComponent(GrimoireComponent).getAttribute("id") === "idtest"); }); -test("null should be \"\" as id and classname", async (t) => { +test("null should be \"\" as id and classname", async(t) => { const testNode2 = rootNode.children[0].children[0]; testNode2.addChildByName("test-node2", { testAttr2: "ADDEDNODE", @@ -526,7 +526,7 @@ test("null should be \"\" as id and classname", async (t) => { t.truthy(child.getComponent(GrimoireComponent).getAttribute("class") === null); }); -test("null should be \"\" as id and classname", async (t) => { +test("null should be \"\" as id and classname", async(t) => { const testNode2 = rootNode.children[0].children[0]; testNode2.addChildByName("test-node2", { testAttr2: "ADDEDNODE", diff --git a/test/Core/GomlParserTest.ts b/test/Core/GomlParserTest.ts index d87ee399d..09e8cef20 100644 --- a/test/Core/GomlParserTest.ts +++ b/test/Core/GomlParserTest.ts @@ -5,7 +5,7 @@ import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Identity from "../../src/Core/Identity"; import Namespace from "../../src/Core/Namespace"; -import XMLReader from "../../src/Tools/XMLReader"; +import XMLReader from "../../src/Tool/XMLReader"; import { registerConflictComponent1, registerConflictComponent2, diff --git a/test/TestEnvManager.ts b/test/TestEnvManager.ts index 59e07f990..b47f951ff 100644 --- a/test/TestEnvManager.ts +++ b/test/TestEnvManager.ts @@ -8,7 +8,7 @@ import GrimoireInterface from "../src/Core/GrimoireInterface"; import Identity from "../src/Core/Identity"; import IdentityMap from "../src/Core/IdentityMap"; import IAttributeConverterDeclaration from "../src/Interface/IAttributeConverterDeclaration"; -import XMLReader from "../src/Tools/XMLReader"; +import XMLReader from "../src/Tool/XMLReader"; import jsdomAsync from "./JsDOMAsync"; export default class TestEnvManager { diff --git a/test/TestUtil.ts b/test/TestUtil.ts index a182c5ece..03b26b160 100644 --- a/test/TestUtil.ts +++ b/test/TestUtil.ts @@ -7,8 +7,8 @@ import GrimoireInterface from "../src/Core/GrimoireInterface"; import Identity from "../src/Core/Identity"; import IAttributeDeclaration from "../src/Interface/IAttributeDeclaration"; import ITreeInitializedInfo from "../src/Interface/ITreeInitializedInfo"; -import Ensure from "../src/Tools/Ensure"; -import XMLReader from "../src/Tools/XMLReader"; +import Ensure from "../src/Tool/Ensure"; +import XMLReader from "../src/Tool/XMLReader"; export default class TestUtil { diff --git a/test/Tools/EnsureTest.ts b/test/Tools/EnsureTest.ts index aa33abc1b..cbaea0212 100644 --- a/test/Tools/EnsureTest.ts +++ b/test/Tools/EnsureTest.ts @@ -3,7 +3,7 @@ import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Identity from "../../src/Core/Identity"; import IdentityMap from "../../src/Core/IdentityMap"; import Namespace from "../../src/Core/Namespace"; -import Ensure from "../../src/Tools/Ensure"; +import Ensure from "../../src/Tool/Ensure"; test.beforeEach(() => { Identity.clear(); diff --git a/test/Tools/IdResolverTest.ts b/test/Tools/IdResolverTest.ts index 278321e78..3191ed33b 100644 --- a/test/Tools/IdResolverTest.ts +++ b/test/Tools/IdResolverTest.ts @@ -4,7 +4,7 @@ import GomlLoader from "../../src/Core/GomlLoader"; import GomlNode from "../../src/Core/GomlNode"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; -import IdResolver from "../../src/Tools/IdResolver"; +import IdResolver from "../../src/Tool/IdResolver"; import Namespace from "../../src/Core/Namespace"; import Identity from "../../src/Core/Identity"; import test from "ava"; @@ -13,7 +13,7 @@ import TestEnvManager from "../TestEnvManager"; TestEnvManager.init(); test("get() works correctly.", t => { - let r = new IdResolver(); + const r = new IdResolver(); r.add(Identity.fromFQN("c.b.a")); t.truthy(r.get(Namespace.define("a")).length === 1); t.truthy(r.get(Namespace.define("b.a")).length === 1); @@ -50,7 +50,7 @@ test("Not accept to get invalid name or namespace", (t) => { }); test("Not accept to get invalid name or namespace", (t) => { - let r = new IdResolver(); + const r = new IdResolver(); // console.log(r); r.add(Identity.fromFQN("a")); r.add(Identity.fromFQN("hoge.b")); @@ -61,7 +61,7 @@ test("Not accept to get invalid name or namespace", (t) => { }); test("resolve works correctly", (t) => { - let r = new IdResolver(); + const r = new IdResolver(); r.add(Identity.fromFQN("hoge.a")); r.add(Identity.fromFQN("hoge.b")); r.add(Identity.fromFQN("hage.huga.c")); diff --git a/test/Tools/UtilityTest.ts b/test/Tools/UtilityTest.ts index 0d3736aca..a52293fa5 100644 --- a/test/Tools/UtilityTest.ts +++ b/test/Tools/UtilityTest.ts @@ -1,5 +1,5 @@ import test from "ava"; -import Utility from "../../src/Tools/Utility"; +import Utility from "../../src/Tool/Utility"; test("isCamelCase works correctly.", t => { t.truthy(Utility.isCamelCase("NameName123")); diff --git a/test/Tools/XMLReaderTest.ts b/test/Tools/XMLReaderTest.ts index 0da9c77f9..ec3803e7c 100644 --- a/test/Tools/XMLReaderTest.ts +++ b/test/Tools/XMLReaderTest.ts @@ -1,7 +1,7 @@ -import fs from "../fileHelper"; import test from "ava"; +import XMLReader from "../../src/Tool/XMLReader"; +import fs from "../fileHelper"; import TestEnvManager from "../TestEnvManager"; -import XMLReader from "../../src/Tools/XMLReader"; TestEnvManager.init(); From aba0bac06a72346dbfc5ffe85fe26cc24ba2d371 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 22 Oct 2017 14:00:29 +0900 Subject: [PATCH 059/146] feat:implement goml mutation observeing --- package.json | 5 ++- src/Core/ComponentDeclaration.ts | 4 +-- src/Core/GomlMutationObserver.ts | 60 +++++++++++++++++++++++++++++++ src/Core/GomlParser.ts | 9 ++--- src/Core/GrimoireInterfaceImpl.ts | 44 +++++++++++++++++++++++ src/Tool/Utility.ts | 8 +++++ src/main.ts | 5 +-- test/TestUtil.ts | 4 +++ 8 files changed, 127 insertions(+), 12 deletions(-) create mode 100644 src/Core/GomlMutationObserver.ts diff --git a/package.json b/package.json index 7fbb245b4..470af7e25 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ "repository": "http://github.com/GrimoireGL/GrimoireJS", "scripts": { "coverage": "trash coverage && nyc --reporter=lcov --reporter=text --reporter=json --reporter=html npm run test", - "test": "trash test-lib && tsc -p tsconfig.test.json && cpx test/_TestResource/**/* test-lib/_TestResource && ava ./test-lib/**/*Test.js --verbose --serial", + "test": "trash test-lib && tsc -p tsconfig.test.json && cpx test/_TestResource/**/* test-lib/_TestResource && ava --verbose --serial", "lint": "tslint -c tslint.json ./src/**/*.ts --project ./ --type-check --exclude ./src/index.ts", "lint:fix": "tslint -c tslint.json ./src/**/*.ts --project ./ --type-check --exclude ./src/index.ts --fix", "prepublish": "webpack --progress --env.prod && npm test", @@ -78,6 +78,9 @@ }, "ava": { "failWithoutAssertions": false, + "files": [ + "./test-lib/**/*Test.js" + ], "require": [ "babel-register" ], diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index 253fa1bcf..1ce3ccd9a 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -132,7 +132,7 @@ export default class ComponentDeclaration { if (typeof obj === "function") { // obj is constructor const inheritsAttr = this._extractInheritsAttributes(obj); if (baseConstructor) { // inherits - const newCtor = function (this: any) { + const newCtor = function(this: any) { baseConstructor.call(this); obj.call(this); }; @@ -151,7 +151,7 @@ export default class ComponentDeclaration { throw new Error("Base component comstructor must extends Compoent class."); } const ctor = baseConstructor || Component; - const newCtor = function (this: any) { + const newCtor = function(this: any) { ctor.call(this); }; (obj as any).__proto__ = ctor.prototype; diff --git a/src/Core/GomlMutationObserver.ts b/src/Core/GomlMutationObserver.ts new file mode 100644 index 000000000..2800dac64 --- /dev/null +++ b/src/Core/GomlMutationObserver.ts @@ -0,0 +1,60 @@ +import Utility from "../Tool/Utility"; +import Environment from "./Environment"; + +/** + * this class observe mutation dom for detect late added goml or removed goml. + */ +export default class GomlMutationObserver { + + private _mutationObserver?: MutationObserver; + + /** + * this is observing goml or not. + */ + public get isObserving(): boolean { + return !!this._mutationObserver; + } + + /** + * start observing goml + * @param addedObserver + * @param removedObserver + */ + public startObservation(addedObserver: (scriptTag: Element) => void, removedObserver: (scriptTag: Element) => void) { + if (this._mutationObserver) { + throw new Error("observation is already started"); + } + this._mutationObserver = new MutationObserver(mutations => { + mutations.forEach(mutation => { + Array.from(mutation.addedNodes).forEach(it => { + if (it.localName === "script" && Utility.isElement(it) && it.getAttribute("type") === "text/goml") { + addedObserver(it); + } + }); + + Array.from(mutation.addedNodes).forEach(it => { + if (it.localName === "script" && Utility.isElement(it) && it.getAttribute("type") === "text/goml") { + removedObserver(it); + } + }); + + }); + }); + const option = { + childList: true, + subtree: true, + }; + this._mutationObserver.observe(Environment.document.body, option); + + } + + /** + * stop observation + */ + public stopObservation() { + if (this._mutationObserver) { + this._mutationObserver.disconnect(); + this._mutationObserver = undefined; + } + } +} diff --git a/src/Core/GomlParser.ts b/src/Core/GomlParser.ts index 3a97f5f4a..0ab89376e 100644 --- a/src/Core/GomlParser.ts +++ b/src/Core/GomlParser.ts @@ -4,7 +4,6 @@ import IGrimoireNodeModel from "../Interface/IGrimoireNodeModel"; import Utility from "../Tool/Utility"; import XMLReader from "../Tool/XMLReader"; import Component from "./Component"; -import Environment from "./Environment"; import GomlNode from "./GomlNode"; /** @@ -28,7 +27,7 @@ export default class GomlParser { const optionalComponents: IGrimoireComponentModel[] = []; const childNodeElements: Element[] = []; childrenElement.forEach(child => { - if (!GomlParser._isElement(child)) { + if (!Utility.isElement(child)) { return; } if (GomlParser._isComponentsTag(child)) { @@ -53,7 +52,7 @@ export default class GomlParser { } function parseComponents(elem: Element): IGrimoireComponentModel[] { const componentNodes = Array.from(elem.childNodes); - return componentNodes.filter(GomlParser._isElement).map(it => { + return componentNodes.filter(Utility.isElement).map(it => { const name = it.namespaceURI ? `${it.namespaceURI}.${it.localName!}` : it.localName!; const attributes = Utility.getAttributes(it); const ret = { @@ -120,10 +119,6 @@ export default class GomlParser { return GomlParser.parseGOMToGomlNode(gom); } - private static _isElement(node: Node): node is Element { - return node.nodeType === Environment.Node.ELEMENT_NODE; - } - private static _isComponentsTag(element: Element): boolean { const regexToFindComponent = /\.COMPONENTS$/mi; // TODO might needs to fix return regexToFindComponent.test(element.nodeName); diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 73da809b3..5901457d5 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -30,6 +30,7 @@ import Utility from "../Tool/Utility"; import Attribute from "./Attribute"; import Constants from "./Constants"; import Environment from "./Environment"; +import GomlMutationObserver from "./GomlMutationObserver"; import Identity from "./Identity"; import IdentityMap from "./IdentityMap"; import NodeInterface from "./NodeInterface"; @@ -38,6 +39,7 @@ import NodeInterface from "./NodeInterface"; * implementation of GrimoireInterface */ export default class GrimoireInterfaceImpl extends EEObject { + public EVENT_GOML_WILL_ADD = "gomlWillAdd"; /** * manage all node declarations. @@ -103,6 +105,12 @@ export default class GrimoireInterfaceImpl extends EEObject { */ public autoLoading = true; + /** + * auto loading goml if added. + * and remove GomlNode if goml is removed from DOM. + */ + public shouldObserveGoml = true; + /** * The object assigned to gr before loading grimoire.js * @type {any} @@ -112,6 +120,8 @@ export default class GrimoireInterfaceImpl extends EEObject { private _registeringPluginNamespace: string; private _registrationContext: string = Constants.defaultNamespace; + private _gomlMutationObserber = new GomlMutationObserver(); + /** * initialized event handlers */ @@ -137,6 +147,40 @@ export default class GrimoireInterfaceImpl extends EEObject { return (name: string) => Namespace.define(ns).for(name); } + /** + * start observation goml mutation. + */ + public startObservation() { + if (this._gomlMutationObserber.isObserving) { + return; + } + this._gomlMutationObserber.startObservation(async added => { + if (!this.shouldObserveGoml) { + return; + } + this.emit(this.EVENT_GOML_WILL_ADD, added); + await GomlLoader.loadFromScriptTag(added as HTMLScriptElement); + this.emit("gomlDidAdded", added); + }, removed => { + if (!this.shouldObserveGoml) { + return; + } + const root = this.getRootNode(removed); + if (root) { + this.emit("gomlWillRemove", removed); + root.remove(); + this.emit("gomlDidRemove", removed); + } + }); + } + + /** + * stop observation + */ + public stopObservation() { + this._gomlMutationObserber.stopObservation(); + } + /** * initialize GrimoireInterface. * register primitive coverters/nodes. diff --git a/src/Tool/Utility.ts b/src/Tool/Utility.ts index 9f782c65a..9eb0afe56 100644 --- a/src/Tool/Utility.ts +++ b/src/Tool/Utility.ts @@ -155,4 +155,12 @@ export default class Utility { throw new Error(errorMessage); } } + + /** + * chack node is Element + * @param node + */ + public static isElement(node: Node): node is Element { + return node.nodeType === Environment.Node.ELEMENT_NODE; + } } diff --git a/src/main.ts b/src/main.ts index 79b664b0d..52cce7f72 100644 --- a/src/main.ts +++ b/src/main.ts @@ -27,6 +27,7 @@ class GrimoireInitializer { GrimoireInitializer._logVersions(); await GrimoireInterface.resolvePlugins(); if (GrimoireInterface.autoLoading) { + GrimoireInterface.startObservation(); await GomlLoader.loadForPage(); } } catch (e) { @@ -91,7 +92,7 @@ class GrimoireInitializer { log += ` ${i} : ${plugin.__NAME__ || key}@${plugin.__VERSION__}\n`; i++; } - log += `\nTo suppress this message,please inject a line "gr.debug = false;" on the initializing timing.`; + log += '\nTo suppress this message,please inject a line "gr.debug = false;" on the initializing timing.'; console.log(log, "color:#44F;font-weight:bold;"); } @@ -113,7 +114,7 @@ class GrimoireInitializer { /** * Just start the process. */ -export default function (): typeof GrimoireInterface { +export default function(): typeof GrimoireInterface { const gwin = window as IGrimoireWindow; if (gwin.GrimoireJS) { GrimoireInterface.libraryPreference = gwin.GrimoireJS; diff --git a/test/TestUtil.ts b/test/TestUtil.ts index 03b26b160..5d6091a69 100644 --- a/test/TestUtil.ts +++ b/test/TestUtil.ts @@ -51,4 +51,8 @@ export default class TestUtil { } as ITreeInitializedInfo); return rootNode; } + + public static GenerateGomlEmbeddedHtml(goml: string): string { + return ``; + } } From e19d24ec453fb271d1e4f8b32e59049d6f18fa71 Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 22 Oct 2017 20:22:08 +0900 Subject: [PATCH 060/146] fix: refactor --- src/Core/Attribute.ts | 14 ++- src/Core/Component.ts | 20 +--- src/Core/ComponentDeclaration.ts | 19 +++- src/Core/GomlLoader.ts | 2 +- src/Core/GomlNode.ts | 153 +++++++++++++----------------- src/Core/GomlParser.ts | 4 +- src/Core/GrimoireInterfaceImpl.ts | 1 + src/Core/NodeDeclaration.ts | 6 +- test/Core/AttributeTest.ts | 14 +-- test/Core/GomlNodeTest.ts | 80 +++++++++++----- test/Core/NodeInterfaceTest.ts | 3 +- 11 files changed, 173 insertions(+), 143 deletions(-) diff --git a/src/Core/Attribute.ts b/src/Core/Attribute.ts index bf78b6f94..d172113b1 100644 --- a/src/Core/Attribute.ts +++ b/src/Core/Attribute.ts @@ -39,8 +39,12 @@ export default class Attribute { * @param {boolean} constant Whether this attribute is immutable or not. False as default. */ public static generateAttributeForComponent(name: string, declaration: IAttributeDeclaration, component: Component): Attribute { + const identity = Identity.fromFQN(`${component.name.fqn}.${name}`); + if (component.attributes.get(identity)) { + throw new Error(`attribute ${identity} is already exists in component`); + } const attr = new Attribute(); - attr.name = Identity.fromFQN(`${component.name.fqn}.${name}`); + attr.name = identity; attr.component = component; attr.declaration = declaration; const converterName = Ensure.tobeCnverterIdentity(declaration.converter); @@ -210,10 +214,16 @@ export default class Attribute { * Apply default value to attribute from DOM values. * @param {string }} domValues [description] */ - public resolveDefaultValue(domValues: { [key: string]: string }): void { + public resolveDefaultValue(): void { if (this._value !== undefined) {// value is already exist. return; } + let domValues; + if (!this.component.isDefaultComponent) { + domValues = this.component.gomAttribute; + } else {// node is exists because this is default component. + domValues = this.component.node.gomAttribute; + } // resolve by goml value const resolver = new IdResolver(); diff --git a/src/Core/Component.ts b/src/Core/Component.ts index 8380d9092..ff5dd28df 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -30,16 +30,11 @@ export default class Component extends IDObject { * @type {GomlNode} */ public node: GomlNode; - /** - * XMLElement of this component - * @type {Element} - */ - public element: Element; /** * default attribute defined in GOML */ - public gomAttribute: { [key: string]: string }; + public gomAttribute: { [key: string]: string } = {}; /** * Whether this component was created by nodeDeclaration @@ -74,6 +69,7 @@ export default class Component extends IDObject { public get enabled(): boolean { return this._enabled; } + public set enabled(val) { if (this._enabled === val) { return; @@ -170,10 +166,9 @@ export default class Component extends IDObject { * Interal use! * @param nodeAttributes */ - public resolveDefaultAttributes(specifiedValue?: { [key: string]: string; }): void { - specifiedValue = specifiedValue || {}; + public resolveDefaultAttributes(): void { this.attributes.forEach(attr => { - attr.resolveDefaultValue(specifiedValue || {}); + attr.resolveDefaultValue(); }); } @@ -225,12 +220,7 @@ export default class Component extends IDObject { } const attr = Attribute.generateAttributeForComponent(name, attribute, this); this.node.addAttribute(attr); - if (this.isDefaultComponent) { // If this is default component, the default attribute values should be retrived from node DOM. - attr.resolveDefaultValue(this.node.gomAttribute); - } else { // If not,the default value of attributes should be retrived from this element. - const attrs = this.gomAttribute; - attr.resolveDefaultValue(attrs); - } + attr.resolveDefaultValue(); this._additionalAttributesNames.push(attr.name); return attr; } diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index 1ce3ccd9a..bc2097c18 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -5,7 +5,6 @@ import IdResolver from "../Tool/IdResolver"; import { ComponentRegistering, Ctor, Name } from "../Tool/Types"; import Attribute from "./Attribute"; import Component from "./Component"; -import Constants from "./Constants"; import Identity from "./Identity"; import IdentityMap from "./IdentityMap"; @@ -20,6 +19,10 @@ export default class ComponentDeclaration { */ public static ctorMap: { ctor: ComponentRegistering>, name: Identity }[] = []; + public static clear() { + ComponentDeclaration.ctorMap = []; + } + /** * super component constructor. */ @@ -74,17 +77,25 @@ export default class ComponentDeclaration { if (!this.isDependenyResolved) { this.resolveDependency(); } - const componentElement = Environment.document.createElementNS(this.name.ns.qualifiedName, this.name.name); const component = new this.ctor(); - componentElement.setAttribute(Constants.x_gr_id, component.id); Environment.GrimoireInterface.componentDictionary[component.id] = component; component.name = this.name; - component.element = componentElement; component.attributes = new IdentityMap(); component.declaration = this; for (const key in this.attributes) { Attribute.generateAttributeForComponent(key, this.attributes[key], component); } + + // bind this for message reciever. + let propNames: string[] = []; + let o = component; + while (o) { + propNames = propNames.concat(Object.getOwnPropertyNames(o)); + o = Object.getPrototypeOf(o); + } + propNames.filter(name => name.startsWith("$") && typeof (component as any)[name] === "function").forEach(method => { + (component as any)["$" + method] = (component as any)[method].bind(component); + }); return component; } diff --git a/src/Core/GomlLoader.ts b/src/Core/GomlLoader.ts index 97e8a765f..1e3a05c9a 100644 --- a/src/Core/GomlLoader.ts +++ b/src/Core/GomlLoader.ts @@ -62,7 +62,6 @@ export default class GomlLoader { GomlLoader.initializedEventHandlers.forEach(handler => { handler(); }); - this.callInitializedAlready = true; } /** @@ -71,5 +70,6 @@ export default class GomlLoader { */ public static async loadForPage(): Promise { await GomlLoader.loadFromQuery('script[type="text/goml"]'); + this.callInitializedAlready = true; } } diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index e29ceada3..635f7aa02 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -21,6 +21,8 @@ import Identity from "./Identity"; import IdentityMap from "./IdentityMap"; import NodeDeclaration from "./NodeDeclaration"; +type SystemMessage = "$$awake" | "$$mount" | "$$unmount" | "$$dispose"; + /** * This class is the most primitive element constitute Tree. * contain some Component, and send/recieve message to them. @@ -49,7 +51,7 @@ export default class GomlNode extends EEObject { /** * default attribute defined in GOML */ - public gomAttribute: { [key: string]: string }; + public gomAttribute: { [key: string]: string } = {}; /** * declaration infomation. @@ -159,6 +161,17 @@ export default class GomlNode extends EEObject { return this._mounted; } + /** + * Get index of this node from parent. + * @return {number} number of index. + */ + public get index(): number { + if (!this._parent) { + return -1; + } + return this._parent.children.indexOf(this); + } + /** * create new instance. * @param {NodeDeclaration} declaration 作成するノードのDeclaration @@ -368,7 +381,16 @@ export default class GomlNode extends EEObject { * @param func */ public callRecursively(func: (g: GomlNode) => T): T[] { - return this._callRecursively(func, (n) => n.children); + return _callRecursively(this, func, (n) => n.children); + + function _callRecursively(self: GomlNode, f: (g: GomlNode) => T, nextGenerator: (n: GomlNode) => GomlNode[]): T[] { + const val = f(self); + const nexts = nextGenerator(self); + const nextVals = nexts.map(c => _callRecursively(c, f, nextGenerator)); + const list = Utility.flat(nextVals); + list.unshift(val); + return list; + } } /** @@ -389,7 +411,6 @@ export default class GomlNode extends EEObject { * @return {GomlNode} detached node. */ public detachChild(target: GomlNode): Nullable { - // search child. const index = this.children.indexOf(target); if (index === -1) { return null; @@ -460,6 +481,14 @@ export default class GomlNode extends EEObject { return this._attributeManager.addAttribute(attr); } + /** + * remove attribute from this node. + * @param {Attribute} attr [description] + */ + public removeAttribute(attr: Attribute): boolean { + return this._attributeManager.removeAttribute(attr); + } + /** * Internal use! * Update mounted status and emit events @@ -470,41 +499,32 @@ export default class GomlNode extends EEObject { return; } if (mounted) { - this._mount(); + this._mounted = true; + const temp = this._components.concat(); + for (let i = 0; i < temp.length; i++) { + const target = temp[i]; + if (target.disposed) { + continue; + } + target.awake(); + this._sendMessageForcedTo(target, "$$mount"); + } for (let i = 0; i < this.children.length; i++) { - this.children[i].setMounted(mounted); + this.children[i].setMounted(true); } } else { + // TODOここでpreunmount for (let i = 0; i < this.children.length; i++) { - this.children[i].setMounted(mounted); + this.children[i].setMounted(false); } - this._sendMessageForced("unmount"); + this._sendMessageForced("$$unmount"); this._isActive = false; this._tree = GrimoireInterface([this]); this._companion = new IdentityMap(); - this._mounted = mounted; + this._mounted = false; } } - /** - * Get index of this node from parent. - * @return {number} number of index. - */ - public get index(): number { - if (!this._parent) { - return -1; - } - return this._parent.children.indexOf(this); - } - - /** - * remove attribute from this node. - * @param {Attribute} attr [description] - */ - public removeAttribute(attr: Attribute): boolean { - return this._attributeManager.removeAttribute(attr); - } - /** * attach component to this node. * @param {Component} component [description] @@ -542,31 +562,17 @@ export default class GomlNode extends EEObject { component.isDefaultComponent = !!isDefaultComponent; component.node = this; - // bind this for message reciever. - let propNames: string[] = []; // TODOこの6行はgenerateComponentInstanceでやっていいのでは? - let o = component; - while (o) { - propNames = propNames.concat(Object.getOwnPropertyNames(o)); - o = Object.getPrototypeOf(o); - } - propNames.filter(name => name.startsWith("$") && typeof (component as any)[name] === "function").forEach(method => { - (component as any)["$" + method] = (component as any)[method].bind(component); - }); - this._components.push(component); // attributes should be exposed on node component.attributes.forEach(p => this.addAttribute(p)); if (this._defaultValueResolved) { - component.attributes.forEach(p => { - p.resolveDefaultValue(this.gomAttribute); - }); + component.resolveDefaultAttributes(); } if (this._mounted) { - component.resolveDefaultAttributes(); // here must be optional component.should not use node element attributes. - this._sendMessageForcedTo(component, "awake"); - this._sendMessageForcedTo(component, "mount"); + this._sendMessageForcedTo(component, "$$awake"); + this._sendMessageForcedTo(component, "$$mount"); } // sending `initialized` message if needed. @@ -582,14 +588,14 @@ export default class GomlNode extends EEObject { */ public removeComponents(component: Name | (new () => Component)): boolean { let result = false; - const removeTargets = []; - component = Ensure.tobeComponentIdentity(component); - for (let i = 0; i < this._components.length; i++) { - const c = this._components[i]; - if (c.name.fqn === component.fqn) { - removeTargets.push(c); - } - } + const removeTargets = this.getComponents(component); + // component = Ensure.tobeComponentIdentity(component); + // for (let i = 0; i < this._components.length; i++) { + // const c = this._components[i]; + // if (c.name.fqn === component.fqn) { + // removeTargets.push(c); + // } + // } removeTargets.forEach(c => { const b = this.removeComponent(c); result = result || b; @@ -605,8 +611,11 @@ export default class GomlNode extends EEObject { public removeComponent(component: Component): boolean { const index = this._components.indexOf(component); if (index !== -1) { - this._sendMessageForcedTo(component, "unmount"); - this._sendMessageForcedTo(component, "dispose"); + this._sendMessageForcedTo(component, "$$unmount"); + this._sendMessageForcedTo(component, "$$dispose"); + component.attributes.forEach(attr => { + this.removeAttribute(attr); + }); this._components.splice(index, 1); this._messageCache = {}; // TODO:optimize. delete component.node; @@ -706,18 +715,18 @@ export default class GomlNode extends EEObject { * resolve default attribute value for all component. * すべてのコンポーネントの属性をエレメントかデフォルト値で初期化 */ - public resolveAttributesValue(attrs?: { [key: string]: string }): void { + public resolveAttributesValue(): void { if (this._defaultValueResolved) { return; } this._defaultValueResolved = true; - for (const key in (attrs || {})) { + for (const key in (this.gomAttribute || {})) { if (this.isFreezeAttribute(key)) { throw new Error(`attribute ${key} can not change from GOML. Attribute is frozen. `); } } this._components.forEach((component) => { - component.resolveDefaultAttributes(attrs); + component.resolveDefaultAttributes(); }); } @@ -940,7 +949,7 @@ export default class GomlNode extends EEObject { return false; } - private _sendMessageForced(message: string): void { + private _sendMessageForced(message: SystemMessage): void { const componentsBuffer = this._components.concat(); for (let i = 0; i < componentsBuffer.length; i++) { const target = componentsBuffer[i]; @@ -956,36 +965,10 @@ export default class GomlNode extends EEObject { * @param {Component} target [description] * @param {string} message [description] */ - private _sendMessageForcedTo(target: Component, message: string): void { - message = Ensure.tobeMessage(message); + private _sendMessageForcedTo(target: Component, message: SystemMessage): void { const method = (target as any)[message]; if (typeof method === "function") { method(); } } - - /** - * sending mount and awake message if needed to all components. - */ - private _mount(): void { - this._mounted = true; - const componentsBuffer = this._components.concat(); - for (let i = 0; i < componentsBuffer.length; i++) { - const target = componentsBuffer[i]; - if (target.disposed) { - continue; - } - target.awake(); - this._sendMessageForcedTo(target, "$$mount"); - } - } - - private _callRecursively(func: (g: GomlNode) => T, nextGenerator: (n: GomlNode) => GomlNode[]): T[] { - const val = func(this); - const nexts = nextGenerator(this); - const nextVals = nexts.map(c => c.callRecursively(func)); - const list = Utility.flat(nextVals); - list.unshift(val); - return list; - } } diff --git a/src/Core/GomlParser.ts b/src/Core/GomlParser.ts index 0ab89376e..448082fce 100644 --- a/src/Core/GomlParser.ts +++ b/src/Core/GomlParser.ts @@ -87,12 +87,12 @@ export default class GomlParser { } const components = source.optionalComponents ? createComponents(source.optionalComponents) : []; - (source.children || []).forEach(it => createNode(it, node)); components.forEach(c => { node._addComponentDirectly(c, false); }); node.gomAttribute = source.attributes || {}; - node.resolveAttributesValue(source.attributes || {}); + node.resolveAttributesValue(); + (source.children || []).forEach(it => createNode(it, node)); return node; } function createComponents(components: IGrimoireComponentModel[]): Component[] { diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 5901457d5..343e62846 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -464,6 +464,7 @@ export default class GrimoireInterfaceImpl extends EEObject { * Clear all configuration that GrimoireInterface contain. */ public clear(): void { + ComponentDeclaration.clear(); this.nodeDeclarations.clear(); this.componentDeclarations.clear(); this.converters.clear(); diff --git a/src/Core/NodeDeclaration.ts b/src/Core/NodeDeclaration.ts index deeed3965..d18348de0 100644 --- a/src/Core/NodeDeclaration.ts +++ b/src/Core/NodeDeclaration.ts @@ -45,6 +45,8 @@ export default class NodeDeclaration { private _defaultAttributesActual: IdentityMap; private _resolvedDependency = false; + private _freezeAttributes: Name[]; + /** * Whether the dependency has already been resolved. */ @@ -77,11 +79,11 @@ export default class NodeDeclaration { private _requiredComponents: (Name | Ctor)[], private _defaultAttributes: { [key: string]: any }, private _superNode?: Name, - private _freezeAttributes: Name[] = []) { + freezeAttributes?: Name[]) { if (!this._superNode && this.name.fqn !== Constants.baseNodeName) { this._superNode = Identity.fromFQN(Constants.baseNodeName); } - this._freezeAttributes = this._freezeAttributes || []; + this._freezeAttributes = freezeAttributes || []; } /** diff --git a/test/Core/AttributeTest.ts b/test/Core/AttributeTest.ts index 1c65a5064..603971673 100644 --- a/test/Core/AttributeTest.ts +++ b/test/Core/AttributeTest.ts @@ -11,7 +11,7 @@ TestEnvManager.init(); const GOML = ""; -test.beforeEach(async() => { +test.beforeEach(async () => { GrimoireInterface.clear(); GrimoireInterface.registerNode("goml"); }); @@ -74,7 +74,7 @@ test("generateAttributeForComponent should works correctly", t => { t.throws(() => { // not resolve default value yet baseComponent.getAttribute("hoge"); }); - hogeAttr.resolveDefaultValue({}); + hogeAttr.resolveDefaultValue(); t.truthy(baseComponent.getAttribute("hoge") === 42); hogeAttr.Value = 43; t.truthy(baseComponent.getAttribute("hoge") === 43); @@ -115,10 +115,12 @@ test("generateAttributeForComponent should works correctly (use dom value)", t = }, baseComponent); t.throws(() => { - attr1.resolveDefaultValue({ hoge: "43", "ns1.hoge": "44" }); // ambiguous + node.gomAttribute = { hoge: "43", "ns1.hoge": "44" }; + attr1.resolveDefaultValue(); // ambiguous }); - attr1.resolveDefaultValue({ "ns1.hoge": "43" }); + node.gomAttribute = { "ns1.hoge": "43" }; + attr1.resolveDefaultValue(); t.truthy(attr1.Value === 43); }); @@ -137,7 +139,7 @@ test("generateAttributeForComponent should works correctly (use node value)", t default: 42, }, baseComponent); - attr1.resolveDefaultValue({}); + attr1.resolveDefaultValue(); t.truthy(attr1.Value === 52); }); @@ -156,6 +158,6 @@ test("generateAttributeForComponent should works correctly (use declaration defa default: 42, }, baseComponent); - attr1.resolveDefaultValue({}); + attr1.resolveDefaultValue(); t.truthy(attr1.Value === 42); }); diff --git a/test/Core/GomlNodeTest.ts b/test/Core/GomlNodeTest.ts index b23c2bbd3..e082c2aa6 100644 --- a/test/Core/GomlNodeTest.ts +++ b/test/Core/GomlNodeTest.ts @@ -1,3 +1,5 @@ +import test from "ava"; +import { spy } from "sinon"; import Attribute from "../../src/Core/Attribute"; import Component from "../../src/Core/Component"; import Constants from "../../src/Core/Constants"; @@ -7,29 +9,26 @@ import GomlNode from "../../src/Core/GomlNode"; import GomlParser from "../../src/Core/GomlParser"; import GrimoireInterface from "../../src/Core/GrimoireInterface"; import Identity from "../../src/Core/Identity"; -import test from "ava"; import TestEnvManager from "../TestEnvManager"; -import xmldom from "xmldom"; +import TestUtil from "../TestUtil"; TestEnvManager.init(); test.beforeEach(async () => { GrimoireInterface.clear(); - const parser = new xmldom.DOMParser(); - const htmlDoc = parser.parseFromString("", "text/html"); - Environment.document = htmlDoc; + TestEnvManager.loadPage(""); GrimoireInterface.registerNode("goml"); GrimoireInterface.registerNode("scenes"); GrimoireInterface.registerNode("scene"); GrimoireInterface.registerComponent({ componentName: "Test", attributes: {}, - valueTest: "Test" + valueTest: "Test", }); GrimoireInterface.registerComponent({ componentName: "Test2", attributes: {}, - valueTest: "Test2" + valueTest: "Test2", }); await GrimoireInterface.resolvePlugins(); }); @@ -139,9 +138,9 @@ test("getComponents method works correctly", t => { attributes: { attr1: { converter: "String", - default: "testAttr" - } - } + default: "testAttr", + }, + }, }); GrimoireInterface.registerNode("test-node", ["TestComponent"]); @@ -177,7 +176,7 @@ test("addComponent method works correctly", t => { testAttr1: { converter: "String", default: "thisistest", - } + }, }, }); const component = GrimoireInterface.componentDeclarations.get("TestComponent1").generateInstance(); @@ -262,19 +261,50 @@ test("getComponents method overload works correctly", t => { const components = node.getComponents(); t.truthy(components.length === 3); }); -// test("addAttribute method works correctly", t => { -// const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); -// GrimoireInterface.registerComponent("TestComponent1", { -// attributes: { -// testAttr1: { -// converter: "String", -// default: "thisistest" -// } -// } + +// test("async message reciever called with await", async t => { // this is experimental feature!! +// const gr = Environment.GrimoireInterface; +// let res1; +// const promise1 = new Promise(resolve => { +// res1 = resolve; +// }); +// let res2; +// const promise2 = new Promise(resolve => { +// res2 = resolve; // }); -// const component = GrimoireInterface.componentDeclarations.get("TestComponent1").generateInstance(); -// const attr = new Attribute("testAttr", { -// converter: "String", -// default: "thisistest" -// }, component); +// const spy1 = spy(); +// const spy2 = spy(); + +// gr.registerComponent({ +// componentName: "hoge1", +// attributes: {}, +// async $messsage(arg) { +// spy1(arg); +// return promise1; +// }, +// }); +// gr.registerComponent({ +// componentName: "hoge2", +// attributes: {}, +// async $messsage(arg) { +// spy1(arg); +// return promise2; +// }, +// }); +// gr.registerNode("a", ["hoge1"]); +// gr.registerNode("b", ["hoge2"]); + +// await TestEnvManager.loadPage(TestUtil.GenerateGomlEmbeddedHtml("")); + +// const root = gr("*")("a").first(); +// const arg = 42; + +// t.truthy(spy1.notCalled); +// t.truthy(spy2.notCalled); +// root.broadcastMessage("message", arg); +// t.truthy(spy1.calledWith(arg)); +// t.truthy(spy2.notCalled); +// res1(); +// t.truthy(spy2.calledWith(arg)); + // }); diff --git a/test/Core/NodeInterfaceTest.ts b/test/Core/NodeInterfaceTest.ts index d78be62a2..618a92c5a 100644 --- a/test/Core/NodeInterfaceTest.ts +++ b/test/Core/NodeInterfaceTest.ts @@ -22,7 +22,7 @@ import { registerTestNode2, registerTestNode3, registerTestNodeBase - } from "../DummyObjectRegisterer"; +} from "../DummyObjectRegisterer"; const testcase1_goml = fs.readFile("../_TestResource/GomlNodeTest_Case1.goml"); @@ -74,6 +74,7 @@ test.beforeEach(async () => { await GomlLoader.loadForPage(); }); + test("count first single.", (t) => { const ni = GrimoireInterface("script")("goml"); // console.log(ni.nodes) From 6bd3c98b1c7826edb2a7957b6deae6a4d01dbbce Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 22 Oct 2017 23:54:47 +0900 Subject: [PATCH 061/146] feat: implement clearMessageRecieverCache --- src/Core/ComponentDeclaration.ts | 3 + src/Core/GomlNode.ts | 31 +++--- src/Core/GrimoireInterfaceImpl.ts | 4 + test/Core/GomlNodeTest.ts | 162 ++++++++++++++++++++++-------- 4 files changed, 145 insertions(+), 55 deletions(-) diff --git a/src/Core/ComponentDeclaration.ts b/src/Core/ComponentDeclaration.ts index bc2097c18..aa7cb5e06 100644 --- a/src/Core/ComponentDeclaration.ts +++ b/src/Core/ComponentDeclaration.ts @@ -19,6 +19,9 @@ export default class ComponentDeclaration { */ public static ctorMap: { ctor: ComponentRegistering>, name: Identity }[] = []; + /** + * clear constructor map + */ public static clear() { ComponentDeclaration.ctorMap = []; } diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index 635f7aa02..848ce46f5 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -21,7 +21,7 @@ import Identity from "./Identity"; import IdentityMap from "./IdentityMap"; import NodeDeclaration from "./NodeDeclaration"; -type SystemMessage = "$$awake" | "$$mount" | "$$unmount" | "$$dispose"; +type SystemMessage = "$$awake" | "$$mount" | "$$unmount" | "$$dispose" | "$$mounted" | "$$preunmount"; /** * This class is the most primitive element constitute Tree. @@ -251,12 +251,6 @@ export default class GomlNode extends EEObject { * remove this node from tree. */ public remove(): void { - this.children.forEach((c) => { - c.remove(); - }); - this._sendMessageForced("$$dispose"); - this.removeAllListeners(); - delete GrimoireInterface.nodeDictionary[this.id]; if (this._parent) { this._parent.detachChild(this); } else { @@ -265,6 +259,13 @@ export default class GomlNode extends EEObject { this.element.parentNode.removeChild(this.element); } } + + this.children.forEach((c) => { + c.remove(); + }); + this._sendMessageForced("$$dispose"); + this.removeAllListeners(); + delete GrimoireInterface.nodeDictionary[this.id]; this._deleted = true; } @@ -503,17 +504,15 @@ export default class GomlNode extends EEObject { const temp = this._components.concat(); for (let i = 0; i < temp.length; i++) { const target = temp[i]; - if (target.disposed) { - continue; - } target.awake(); this._sendMessageForcedTo(target, "$$mount"); } for (let i = 0; i < this.children.length; i++) { this.children[i].setMounted(true); } + this._sendMessageForced("$$mounted"); } else { - // TODOここでpreunmount + this._sendMessageForced("$$preunmount"); for (let i = 0; i < this.children.length; i++) { this.children[i].setMounted(false); } @@ -650,7 +649,7 @@ export default class GomlNode extends EEObject { public getComponent(name: Name | Ctor): T { // 事情によりとはできない。 // これはref/Core/Componentによって参照されるのが外部ライブラリにおけるコンポーネントであるが、 - // src/Core/Componentがこのプロジェクトにおけるコンポーネントのため、別のコンポーネントとみなされ、型の制約をみたさなくなるからである。 + // src/Core/Componentがこのプロジェクトにおけるコンポーネントのため、別のコンポーネントとみなされ、型の制約をみたさなくなるらである。 if (!name) { throw new Error("name must not be null or undefined"); } else if (typeof name === "function") { @@ -761,6 +760,14 @@ export default class GomlNode extends EEObject { this._attributeManager.watch(attrName, watcher, immediate); } + /** + * clear message cache. + * call if dynamic change message reciever. + */ + public clearMessageRecieverCache() { + this._messageCache = {}; + } + /** * to string */ diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 343e62846..9d2c33423 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -39,6 +39,10 @@ import NodeInterface from "./NodeInterface"; * implementation of GrimoireInterface */ export default class GrimoireInterfaceImpl extends EEObject { + /** + * constant for emitting event. + * added goml in ducument. + */ public EVENT_GOML_WILL_ADD = "gomlWillAdd"; /** diff --git a/test/Core/GomlNodeTest.ts b/test/Core/GomlNodeTest.ts index e082c2aa6..6e54aa5c3 100644 --- a/test/Core/GomlNodeTest.ts +++ b/test/Core/GomlNodeTest.ts @@ -14,7 +14,7 @@ import TestUtil from "../TestUtil"; TestEnvManager.init(); -test.beforeEach(async () => { +test.beforeEach(async() => { GrimoireInterface.clear(); TestEnvManager.loadPage(""); GrimoireInterface.registerNode("goml"); @@ -76,7 +76,7 @@ test("addChild method works correctly", t => { t.truthy(node.children.length === 2); }); -test("delete method works correctly", t => { +test("remove method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml")); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes")); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene")); @@ -262,49 +262,125 @@ test("getComponents method overload works correctly", t => { t.truthy(components.length === 3); }); -// test("async message reciever called with await", async t => { // this is experimental feature!! -// const gr = Environment.GrimoireInterface; -// let res1; -// const promise1 = new Promise(resolve => { -// res1 = resolve; -// }); -// let res2; -// const promise2 = new Promise(resolve => { -// res2 = resolve; -// }); -// const spy1 = spy(); -// const spy2 = spy(); +test("async message reciever called with await", async t => { + const gr = Environment.GrimoireInterface; + const spy1 = spy(); -// gr.registerComponent({ -// componentName: "hoge1", -// attributes: {}, -// async $messsage(arg) { -// spy1(arg); -// return promise1; -// }, -// }); -// gr.registerComponent({ -// componentName: "hoge2", -// attributes: {}, -// async $messsage(arg) { -// spy1(arg); -// return promise2; -// }, -// }); -// gr.registerNode("a", ["hoge1"]); -// gr.registerNode("b", ["hoge2"]); + gr.registerComponent({ + componentName: "Aaa", + attributes: {}, + $awake() { + spy1("awake:" + this.node.getAttribute("id")); + }, + $mount() { + spy1("mount:" + this.node.getAttribute("id")); + }, + $mounted() { + spy1("mounted:" + this.node.getAttribute("id")); + }, + $preunmount() { + spy1("preunmount:" + this.node.getAttribute("id")); + }, + $unmount() { + spy1("unmount:" + this.node.getAttribute("id")); + }, + $dispose() { + spy1("dispose:" + this.node.getAttribute("id")); + }, + }); + gr.registerNode("a", ["Aaa"]); + + await TestEnvManager.loadPage(TestUtil.GenerateGomlEmbeddedHtml('')); + + const root = gr("*")("#parent").first(); + const middle = gr("*")("#middle").first(); + t.deepEqual(spy1.args, [ + ["awake:parent"], + ["mount:parent"], + ["awake:middle"], + ["mount:middle"], + ["awake:child"], + ["mount:child"], + ["mounted:child"], + ["mounted:middle"], + ["mounted:parent"], + ]); -// await TestEnvManager.loadPage(TestUtil.GenerateGomlEmbeddedHtml("")); + spy1.reset(); -// const root = gr("*")("a").first(); -// const arg = 42; + middle.detach(); + t.deepEqual(spy1.args, [ + ["preunmount:middle"], + ["preunmount:child"], + ["unmount:child"], + ["unmount:middle"], + ]); -// t.truthy(spy1.notCalled); -// t.truthy(spy2.notCalled); -// root.broadcastMessage("message", arg); -// t.truthy(spy1.calledWith(arg)); -// t.truthy(spy2.notCalled); -// res1(); -// t.truthy(spy2.calledWith(arg)); + spy1.reset(); + root.remove(); + t.deepEqual(spy1.args, [ + ["preunmount:parent"], + ["unmount:parent"], + ["dispose:parent"], + ]); +}); + +test("async message reciever called with await", async t => { + const gr = Environment.GrimoireInterface; + const spy1 = spy(); -// }); + gr.registerComponent({ + componentName: "Aaa", + attributes: {}, + $awake() { + spy1("awake:" + this.node.getAttribute("id")); + }, + $mount() { + spy1("mount:" + this.node.getAttribute("id")); + }, + $mounted() { + spy1("mounted:" + this.node.getAttribute("id")); + }, + $preunmount() { + spy1("preunmount:" + this.node.getAttribute("id")); + }, + $unmount() { + spy1("unmount:" + this.node.getAttribute("id")); + }, + $dispose() { + spy1("dispose:" + this.node.getAttribute("id")); + }, + }); + gr.registerNode("a", ["Aaa"]); + + await TestEnvManager.loadPage(TestUtil.GenerateGomlEmbeddedHtml('')); + + const root = gr("*")("#parent").first(); + const middle = gr("*")("#middle").first(); + t.deepEqual(spy1.args, [ + ["awake:parent"], + ["mount:parent"], + ["awake:middle"], + ["mount:middle"], + ["awake:child"], + ["mount:child"], + ["mounted:child"], + ["mounted:middle"], + ["mounted:parent"], + ]); + + spy1.reset(); + + root.remove(); + t.deepEqual(spy1.args, [ + ["preunmount:parent"], + ["preunmount:middle"], + ["preunmount:child"], + ["unmount:child"], + ["unmount:middle"], + ["unmount:parent"], + ["dispose:child"], + ["dispose:middle"], + ["dispose:parent"], + ]); +}); From e3644eb3e759d40961f9fd6df35d75ef30c34500 Mon Sep 17 00:00:00 2001 From: moajo Date: Tue, 21 Nov 2017 22:27:08 +0900 Subject: [PATCH 062/146] fix: remove unuse variables --- src/Core/GomlNode.ts | 2 -- src/Core/GrimoireInterfaceImpl.ts | 19 ------------------- 2 files changed, 21 deletions(-) diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index 848ce46f5..f17ac2aa1 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -64,7 +64,6 @@ export default class GomlNode extends EEObject { public children: GomlNode[] = []; private _parent: Nullable = null; - private _root: Nullable = null; private _components: Component[]; private _tree: GomlInterface = GrimoireInterface([this]); private _companion: IdentityMap = new IdentityMap(); @@ -188,7 +187,6 @@ export default class GomlNode extends EEObject { } this.declaration = declaration; this.element = element || Environment.document.createElementNS(declaration.name.ns.qualifiedName, declaration.name.name); - this._root = this; this._components = []; this._attributeManager = new AttributeManager(declaration.name.name); diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 9d2c33423..029babf8e 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -538,25 +538,6 @@ export default class GrimoireInterfaceImpl extends EEObject { this._registeringPluginNamespace = namespace; } - private _ensureNameTobeConstructor(component: Name | Ctor): Nullable> { - if (!component) { - return null; - } - - if (typeof component === "function") { - return component; - } else if (typeof component === "string") { - return this._ensureNameTobeConstructor(Ensure.tobeNSIdentity(component)); - } else { - // here NSIdentity. - const c = this.componentDeclarations.get(component); - if (!c) { - return null; - } - return c.ctor; - } - } - private _ensureTobeNSIdentityOnRegister(name: Name): Identity; private _ensureTobeNSIdentityOnRegister(name: null | undefined): null; private _ensureTobeNSIdentityOnRegister(name: Name | null | undefined): Nullable { From 7ebd84f237ba5ba8525d8b161425a6d6c3074b25 Mon Sep 17 00:00:00 2001 From: "greenkeeper[bot]" Date: Wed, 29 Nov 2017 17:25:51 +0000 Subject: [PATCH 063/146] fix(package): update eventemitter3 to version 3.0.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 80e062526..28850f37b 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "grimoire" ], "dependencies": { - "eventemitter3": "^2.0.3" + "eventemitter3": "^3.0.0" }, "devDependencies": { "ava": "^0.22.0", From d943767a50d417591b526b0f16def88b8980d78a Mon Sep 17 00:00:00 2001 From: "greenkeeper[bot]" Date: Wed, 29 Nov 2017 21:18:12 +0000 Subject: [PATCH 064/146] chore(package): update ts-loader to version 3.2.0 Closes #535 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 80e062526..000f23a4d 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "semantic-release": "^7.0.2", "sinon": "^3.3.0", "trash-cli": "^1.4.0", - "ts-loader": "^2.3.7", + "ts-loader": "^3.2.0", "tslint": "^5.8.0", "typedoc": "^0.8.0", "typedoc-md-theme": "^1.0.1", From 1ba1665a5fad5cc487954adc1dfda46b4d72635c Mon Sep 17 00:00:00 2001 From: "greenkeeper[bot]" Date: Thu, 7 Dec 2017 13:36:02 +0000 Subject: [PATCH 065/146] chore(package): update sinon to version 4.1.3 Closes #528 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 80e062526..2a9299b8d 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,7 @@ "regenerator-runtime": "^0.11.0", "remap-istanbul": "^0.9.5", "semantic-release": "^7.0.2", - "sinon": "^3.3.0", + "sinon": "^4.1.3", "trash-cli": "^1.4.0", "ts-loader": "^2.3.7", "tslint": "^5.8.0", From 382b8175adfc534691a8c5350d9a0a64e4a1dc95 Mon Sep 17 00:00:00 2001 From: "greenkeeper[bot]" Date: Thu, 14 Dec 2017 03:24:25 +0000 Subject: [PATCH 066/146] chore(package): update condition-circle to version 2.0.1 Closes #544 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 80e062526..7812abec5 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "babel-preset-es2015": "^6.24.0", "babel-preset-stage-2": "^6.22.0", "babel-register": "^6.26.0", - "condition-circle": "^1.5.0", + "condition-circle": "^2.0.1", "cpx": "^1.5.0", "grimoirejs-cauldron": "^3.1.8", "jsdom": "^11.3.0", From 9877e1ef3c79f22e95fdd146a548211de2c25c51 Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Dec 2017 17:47:04 +0900 Subject: [PATCH 067/146] chore: rename properties --- src/Core/GomlNode.ts | 2 +- src/Core/GrimoireInterfaceImpl.ts | 6 +++--- src/Core/NodeDeclaration.ts | 4 ++-- test/Core/GrimoireInterfaceTest.ts | 6 +++--- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Core/GomlNode.ts b/src/Core/GomlNode.ts index f17ac2aa1..186197663 100644 --- a/src/Core/GomlNode.ts +++ b/src/Core/GomlNode.ts @@ -191,7 +191,7 @@ export default class GomlNode extends EEObject { this._attributeManager = new AttributeManager(declaration.name.name); this.element.setAttribute(Constants.x_gr_id, this.id); - const defaultComponentNames = declaration.requiredComponentsActual; + const defaultComponentNames = declaration.defaultComponentsActual; // instanciate default components defaultComponentNames.forEach(id => { diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index 029babf8e..d0b0df47c 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -298,14 +298,14 @@ export default class GrimoireInterfaceImpl extends EEObject { * register new node to context. * throw error if already registerd. * @param name - * @param requiredComponents + * @param defaultComponents * @param defaults * @param superNode * @param freezeAttributes */ public registerNode( name: Name, - requiredComponents: (Name | Ctor)[] = [], + defaultComponents: (Name | Ctor)[] = [], defaults?: { [key: string]: any }, superNode?: Name, freezeAttributes?: Name[]): NodeDeclaration { @@ -317,7 +317,7 @@ export default class GrimoireInterfaceImpl extends EEObject { if (this.debug && !Utility.isKebabCase(registerId.name)) { console.warn(`node ${registerId.name} is registerd. but,it should be 'snake-case'.`); } - const declaration = new NodeDeclaration(registerId, requiredComponents || [], defaults || {}, superNode, freezeAttributes); + const declaration = new NodeDeclaration(registerId, defaultComponents || [], defaults || {}, superNode, freezeAttributes); this.nodeDeclarations.set(registerId, declaration); return declaration; } diff --git a/src/Core/NodeDeclaration.ts b/src/Core/NodeDeclaration.ts index d18348de0..04dd12eea 100644 --- a/src/Core/NodeDeclaration.ts +++ b/src/Core/NodeDeclaration.ts @@ -57,7 +57,7 @@ export default class NodeDeclaration { /** * get required components with inheritance in mind. */ - public get requiredComponentsActual(): IdentitySet { + public get defaultComponentsActual(): IdentitySet { if (!this._resolvedDependency) { throw new Error(`${this.name.fqn} is not resolved dependency!`); } @@ -140,7 +140,7 @@ export default class NodeDeclaration { throw new Error(`In node '${this.name.fqn}': super node ${this.superNode.fqn} is not found when resolving inherits, it has registerd correctry?`); } superNode.resolveDependency(); - const inheritedDefaultComponents = superNode.requiredComponentsActual; + const inheritedDefaultComponents = superNode.defaultComponentsActual; const inheritedDefaultAttribute = superNode.defaultAttributesActual; this._requiredComponentsActual = inheritedDefaultComponents.clone().merge(this.requiredComponents); this._defaultAttributesActual = inheritedDefaultAttribute.clone().pushDictionary(this.defaultAttributes); diff --git a/test/Core/GrimoireInterfaceTest.ts b/test/Core/GrimoireInterfaceTest.ts index 792c86b71..97684bcaf 100644 --- a/test/Core/GrimoireInterfaceTest.ts +++ b/test/Core/GrimoireInterfaceTest.ts @@ -328,9 +328,9 @@ test("registerNode/Component works correctly.", async t => { const a1 = GrimoireInterface.nodeDeclarations.get("a1"); const a2 = GrimoireInterface.nodeDeclarations.get("a2"); const a3 = GrimoireInterface.nodeDeclarations.get("a3"); - t.truthy(a1.requiredComponentsActual.toArray().length === 1); // grimoireCompone - t.truthy(a2.requiredComponentsActual.toArray().length === 2); // grimoireCompone - t.truthy(a3.requiredComponentsActual.toArray().length === 2); // grimoireCompone + t.truthy(a1.defaultComponentsActual.toArray().length === 1); // grimoireCompone + t.truthy(a2.defaultComponentsActual.toArray().length === 2); // grimoireCompone + t.truthy(a3.defaultComponentsActual.toArray().length === 2); // grimoireCompone // console.log(a2.idResolver) t.truthy(a2.idResolver.resolve(Namespace.define("hoge")) === "grimoirejs.Hoge.hoge"); From a0a788a6941b531106c18b59b8622838690f4c10 Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Dec 2017 18:13:13 +0900 Subject: [PATCH 068/146] chore: update common-configuration --- common | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common b/common index 27e461ceb..b4bb4ea7c 160000 --- a/common +++ b/common @@ -1 +1 @@ -Subproject commit 27e461cebf2bef9779777f79a0ba732457b24c67 +Subproject commit b4bb4ea7c69c75900ca984a10c498ab151627f44 From b5e09c995c568b3649469843e69bdd8f3c863cdf Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Dec 2017 18:39:29 +0900 Subject: [PATCH 069/146] update common configurations --- .gitignore | 1 + common | 2 +- package.json | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index a016d7aba..0fd83de01 100644 --- a/.gitignore +++ b/.gitignore @@ -129,3 +129,4 @@ docs test-lib test-lib-es5 src/metaInfo.ts +package-lock.json diff --git a/common b/common index b4bb4ea7c..7cb3fe2bc 160000 --- a/common +++ b/common @@ -1 +1 @@ -Subproject commit b4bb4ea7c69c75900ca984a10c498ab151627f44 +Subproject commit 7cb3fe2bcbbea238e4090024820ff7c2c3213187 diff --git a/package.json b/package.json index 920e34464..8e6eb56a3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "grimoirejs", - "version": "0.0.0-development", + "version": "1.0.0", "description": "A service-oriented WebGL framework.", "main": "./ref/index.js", "typings": "./ref/index.d.ts", @@ -27,7 +27,7 @@ "babel-register": "^6.26.0", "condition-circle": "^1.5.0", "cpx": "^1.5.0", - "grimoirejs-cauldron": "^3.1.8", + "grimoirejs-cauldron": "beta", "jsdom": "^11.3.0", "lodash": "^4.17.2", "nyc": "^11.3.0", @@ -91,4 +91,4 @@ "**/src/**/*" ] } -} \ No newline at end of file +} From 15f7f64bc523550b10c8a757980e1a3963258363 Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Dec 2017 19:09:31 +0900 Subject: [PATCH 070/146] update circle.yaml --- circle.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index d02316394..d6609fd9a 100644 --- a/circle.yml +++ b/circle.yml @@ -1,6 +1,6 @@ machine: node: - version: 6.9.5 + version: 9.3.0 test: post: - sh release.sh @@ -10,6 +10,10 @@ test: override: - npm run lint && npm run build && npm run coverage - sh -x shell/e2e.sh +checkout: + post: + - git submodule init + - git submodule update deployment: deploy: branch: master From e86b3eafdd6e7b0115879006ef30d3681d3008ff Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Dec 2017 21:07:23 +0900 Subject: [PATCH 071/146] update dependencies --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8e6eb56a3..1f0acf035 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "grimoirejs-cauldron": "beta", "jsdom": "^11.3.0", "lodash": "^4.17.2", - "nyc": "^11.3.0", + "nyc": "^11.4.1", "proxyquire": "^1.7.11", "regenerator-runtime": "^0.11.0", "remap-istanbul": "^0.9.5", From 7d2bb3cbf3438e80e76a7b16cffde1fe39437f9d Mon Sep 17 00:00:00 2001 From: moajo Date: Sat, 16 Dec 2017 21:59:03 +0900 Subject: [PATCH 072/146] chore: update event emitter --- package.json | 2 +- src/Base/EEObject.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 2319d6afc..1df052ca5 100644 --- a/package.json +++ b/package.json @@ -56,7 +56,7 @@ "test": "trash test-lib && tsc -p tsconfig.test.json && cpx test/_TestResource/**/* test-lib/_TestResource && ava --verbose --serial", "lint": "tslint -c tslint.json ./src/**/*.ts --project ./ --type-check --exclude ./src/index.ts", "lint:fix": "tslint -c tslint.json ./src/**/*.ts --project ./ --type-check --exclude ./src/index.ts --fix", - "prepublish": "webpack --progress --env.prod && npm test", + "prepare": "webpack --progress --env.prod && npm test", "start": "webpack --progress --watch", "build": "webpack --progress", "generate-expose": "cauldron generate-exposure --src ./src --dest ./src/index.ts --ts --main ./src/main.ts --core", diff --git a/src/Base/EEObject.ts b/src/Base/EEObject.ts index 7fb7c0f97..4b361c759 100644 --- a/src/Base/EEObject.ts +++ b/src/Base/EEObject.ts @@ -16,6 +16,8 @@ class EEObject extends IDObject implements EventEmitter { */ public listeners: ((event: string | symbol, exists: boolean) => ListenerFn[] | boolean) & ((event: string | symbol) => ListenerFn[]); + public listenerCount: (event: string | symbol) => number; + /** * Calls each of the listeners registered for a given event. */ From 43b7dee1781f5ecb132594cb00957c1dc62a2ad9 Mon Sep 17 00:00:00 2001 From: moajo Date: Tue, 19 Dec 2017 00:25:51 +0900 Subject: [PATCH 073/146] chore: replace babel-preset-es2015 with babel-preset-env --- package.json | 6 +++--- webpack.config.js | 16 ++++++++-------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index 1df052ca5..16a7e2202 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "babel-loader": "^7.1.2", "babel-plugin-transform-runtime": "^6.23.0", "babel-polyfill": "^6.26.0", - "babel-preset-es2015": "^6.24.0", + "babel-preset-env": "^1.6.1", "babel-preset-stage-2": "^6.22.0", "babel-register": "^6.26.0", "condition-circle": "^2.0.1", @@ -72,7 +72,7 @@ }, "babel": { "presets": [ - "es2015", + "env", "stage-2" ] }, @@ -91,4 +91,4 @@ "**/src/**/*" ] } -} +} \ No newline at end of file diff --git a/webpack.config.js b/webpack.config.js index 3ae45fffb..27ab7ab83 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -54,7 +54,7 @@ const getBuildTask = (fileName, plugins, needPolyfill) => { loaders: [{ test: /\.ts$/, exclude: /node_modules/, - loader: "babel-loader?presets[]=es2015,presets[]=stage-2!ts-loader" + loader: "babel-loader?presets[]=env,presets[]=stage-2!ts-loader" }] }, resolve: { @@ -74,10 +74,10 @@ module.exports = (env = {}) => { // // // - if(!env.browser && !env.npm && !env.prod){ + if (!env.browser && !env.npm && !env.prod) { env.browser = true; } - const productPlugins = [new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}}),new webpack.optimize.OccurrenceOrderPlugin(),new webpack.optimize.AggressiveMergingPlugin()]; + const productPlugins = [new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.AggressiveMergingPlugin()]; let buildTasks = []; let skipIndex = false; let cauldron = new CauldronPlugin(); @@ -89,18 +89,18 @@ module.exports = (env = {}) => { plugins.push(new CopyPlugin(`./register/${fnPrefix}.js`, './register/index.js')); plugins.push(new CopyPlugin(`./register/${fnPrefix}.js.map`, './register/index.js.map')); skipIndex = true; - console.log(`${index}.js will be generated for NPM environment by copy`); + console.log(`${index}.js will be generated for NPM environment by copy`); } - buildTasks.push(getBuildTask(`${fnPrefix}.js`, [cauldron,...plugins], includeCore)); + buildTasks.push(getBuildTask(`${fnPrefix}.js`, [cauldron, ...plugins], includeCore)); console.log(`${fnPrefix}.js will be generated for browser environment`); } if (!skipIndex && (env.npm || env.prod)) { buildTasks.push(getBuildTask("index.js", [cauldron], false)); - console.log(`index.js will be generated for NPM environment`); + console.log(`index.js will be generated for NPM environment`); } if (env.prod) { - buildTasks.push(getBuildTask(fnPrefix + ".min.js", [cauldron,...productPlugins],includeCore)); - console.log(`${fnPrefix}.min.js will be generated for browser environment`); + buildTasks.push(getBuildTask(fnPrefix + ".min.js", [cauldron, ...productPlugins], includeCore)); + console.log(`${fnPrefix}.min.js will be generated for browser environment`); } return buildTasks; }; From 2aaddb27bd64b4d1f13774d8c584418a75d94e6c Mon Sep 17 00:00:00 2001 From: moajo Date: Tue, 19 Dec 2017 01:43:31 +0900 Subject: [PATCH 074/146] feat: add overload to Component#setAttribute --- src/Core/Component.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Core/Component.ts b/src/Core/Component.ts index ff5dd28df..2cfd6b299 100644 --- a/src/Core/Component.ts +++ b/src/Core/Component.ts @@ -108,8 +108,8 @@ export default class Component extends IDObject { * @param {string} name [description] * @param {any} value [description] */ - public setAttribute(name: Name, value: any): void { - const attr = this.attributes.get(name); + public setAttribute(name: Name | IAttributeDeclaration, value: any): void { + const attr = this.getAttributeRaw(name); if (attr) { attr.Value = value; } else { From 6c3877d6a68e1f2a82e7b482682e28cce41eb9c8 Mon Sep 17 00:00:00 2001 From: moajo Date: Tue, 19 Dec 2017 01:44:02 +0900 Subject: [PATCH 075/146] feat: add loadFromGOML method to GomlLoader --- src/Core/GomlLoader.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Core/GomlLoader.ts b/src/Core/GomlLoader.ts index 1e3a05c9a..61c7dbaf7 100644 --- a/src/Core/GomlLoader.ts +++ b/src/Core/GomlLoader.ts @@ -2,6 +2,7 @@ import GrimoireInterface from "../Core/GrimoireInterface"; import XMLHttpRequestAsync from "../Tool/XMLHttpRequestAsync"; import XMLReader from "../Tool/XMLReader"; import Environment from "./Environment"; +import GomlNode from "./GomlNode"; import GomlParser from "./GomlParser"; /** @@ -19,6 +20,13 @@ export default class GomlLoader { */ public static initializedEventHandlers: (() => void)[] = []; + public static loadFromGOML(goml: string): GomlNode { + const doc = XMLReader.parseXML(goml); + const rootNode = GomlParser.parse(doc); + GrimoireInterface.addRootNode(null, rootNode); + return rootNode; + } + /** * Obtain the Goml source from specified tag. * @param {HTMLScriptElement} scriptTag [the script tag to load] From 63a1f1cfb389d9edaa00f1ec723e38a5071602e7 Mon Sep 17 00:00:00 2001 From: moajo Date: Tue, 19 Dec 2017 01:45:05 +0900 Subject: [PATCH 076/146] feat: implement TemplateNode.src --- src/Component/GrimoireComponent.ts | 6 +-- src/Component/TemplateComponent.ts | 18 +++++++-- src/Core/GrimoireInterfaceImpl.ts | 2 +- test/Component/TemplateComponentTest.ts | 53 +++++++++++++++++++++++++ 4 files changed, 72 insertions(+), 7 deletions(-) create mode 100644 test/Component/TemplateComponentTest.ts diff --git a/src/Component/GrimoireComponent.ts b/src/Component/GrimoireComponent.ts index 4319ceb11..206e4d575 100644 --- a/src/Component/GrimoireComponent.ts +++ b/src/Component/GrimoireComponent.ts @@ -42,13 +42,13 @@ export default class GrimoireComponent extends Component { protected $awake(): void { const node = this.node; node.resolveAttributesValue(); - this.getAttributeRaw("id")!.watch((attr) => { + this.getAttributeRaw(GrimoireComponent.attributes.id)!.watch((attr) => { node.element.id = attr ? attr : ""; }, true, true); - this.getAttributeRaw("class")!.watch((attr) => { + this.getAttributeRaw(GrimoireComponent.attributes.class)!.watch((attr) => { node.element.className = Array.isArray(attr) ? attr.join(" ") : ""; }, true, true); - this.getAttributeRaw("enabled")!.watch(attr => { + this.getAttributeRaw(GrimoireComponent.attributes.enabled)!.watch(attr => { node["_enabled"] = attr; const p = node.parent; node.notifyActivenessUpdate(p ? p.isActive && node.enabled : node.enabled); diff --git a/src/Component/TemplateComponent.ts b/src/Component/TemplateComponent.ts index 6138b44e2..a2a0d37af 100644 --- a/src/Component/TemplateComponent.ts +++ b/src/Component/TemplateComponent.ts @@ -4,6 +4,7 @@ import Component from "../Core/Component"; import GomlNode from "../Core/GomlNode"; import GomlParser from "../Core/GomlParser"; import IAttributeConverterDeclaration from "../Interface/IAttributeConverterDeclaration"; +import XMLHttpRequestAsync from "../Tool/XMLHttpRequestAsync"; import XMLReader from "../Tool/XMLReader"; export { IAttributeConverterDeclaration }; @@ -25,6 +26,10 @@ export default class TemplateComponent extends Component { // TODO test converter: StringConverter, default: null, }, + src: { + converter: StringConverter, + default: null, + }, auto: { converter: BooleanConverter, default: true, @@ -41,7 +46,14 @@ export default class TemplateComponent extends Component { // TODO test /** * replace self with goml */ - public inflate() { + public async inflate() { + const src = this.getAttribute(TemplateComponent.attributes.src); + if (src) { + const req = new XMLHttpRequest(); + req.open("GET", src); + await XMLHttpRequestAsync.send(req); + this.setAttribute(TemplateComponent.attributes.goml, req.responseText); + } const goml = this.getAttribute(TemplateComponent.attributes.goml); if (goml) { const doc = XMLReader.parseXML(goml); @@ -50,9 +62,9 @@ export default class TemplateComponent extends Component { // TODO test } } - protected $awake() { + protected async $awake() { if (this.getAttribute(TemplateComponent.attributes.auto)) { - this.inflate(); + await this.inflate(); } } } diff --git a/src/Core/GrimoireInterfaceImpl.ts b/src/Core/GrimoireInterfaceImpl.ts index d0b0df47c..9488dbaee 100644 --- a/src/Core/GrimoireInterfaceImpl.ts +++ b/src/Core/GrimoireInterfaceImpl.ts @@ -340,7 +340,7 @@ export default class GrimoireInterfaceImpl extends EEObject { * @param tag the script element containing GOML source * @param rootNode root node of Goml */ - public addRootNode(tag: HTMLScriptElement, rootNode: GomlNode): string { + public addRootNode(tag: Nullable, rootNode: GomlNode): string { if (!rootNode) { throw new Error("can not register null to rootNodes."); } diff --git a/test/Component/TemplateComponentTest.ts b/test/Component/TemplateComponentTest.ts new file mode 100644 index 000000000..c5a116ce8 --- /dev/null +++ b/test/Component/TemplateComponentTest.ts @@ -0,0 +1,53 @@ +import test from "ava"; +import { spy } from "sinon"; +import TemplateComponent from "../../src/Component/TemplateComponent"; +import Attribute from "../../src/Core/Attribute"; +import Component from "../../src/Core/Component"; +import Constants from "../../src/Core/Constants"; +import Environment from "../../src/Core/Environment"; +import GomlLoader from "../../src/Core/GomlLoader"; +import GomlNode from "../../src/Core/GomlNode"; +import GomlParser from "../../src/Core/GomlParser"; +import GrimoireInterface from "../../src/Core/GrimoireInterface"; +import Identity from "../../src/Core/Identity"; +import TestEnvManager from "../TestEnvManager"; +import TestUtil from "../TestUtil"; + +TestEnvManager.init(); +TestEnvManager.mockSetup(); +TestEnvManager.mock("template.goml", ""); + +test.beforeEach(async() => { + GrimoireInterface.clear(); + TestEnvManager.loadPage(""); + GrimoireInterface.registerNode("goml"); + GrimoireInterface.registerNode("scenes"); + GrimoireInterface.registerNode("scene"); + GrimoireInterface.registerComponent({ + componentName: "Test", + attributes: {}, + valueTest: "Test", + }); + GrimoireInterface.registerComponent({ + componentName: "Test2", + attributes: {}, + valueTest: "Test2", + }); + await GrimoireInterface.resolvePlugins(); +}); + +test("template component inflate correctly in awake", t => { + const root = GomlLoader.loadFromGOML('