From e792d45fcd9b1f29f649c3b9be1ae742bb210b7e Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Wed, 19 Jul 2017 12:16:52 +0900 Subject: [PATCH 01/97] fix: Removed dependency for Node.EventEmitter --- package.json | 3 +- src/Base/EEObject.ts | 56 ++++++++++++++++++++++++---------- src/Base/ListenerFunction.ts | 3 ++ src/Interface/NodeInterface.ts | 9 +++--- 4 files changed, 49 insertions(+), 22 deletions(-) create mode 100644 src/Base/ListenerFunction.ts diff --git a/package.json b/package.json index 6a2e31e11..ba5fc4fd7 100644 --- a/package.json +++ b/package.json @@ -13,8 +13,7 @@ "grimoire" ], "dependencies": { - "@types/node": "^8.0.14", - "events": "^1.1.1" + "eventemitter3": "^2.0.3" }, "devDependencies": { "ava": "^0.21.0", diff --git a/src/Base/EEObject.ts b/src/Base/EEObject.ts index 4ae602da1..911d36886 100644 --- a/src/Base/EEObject.ts +++ b/src/Base/EEObject.ts @@ -1,26 +1,50 @@ -/// -import {EventEmitter} from "events"; +import { EventEmitter, ListenerFn } from "eventemitter3"; import IDObject from "./IDObject"; /** * EventEmitterをmixinしたIDObject */ -class EEObject extends IDObject implements NodeJS.EventEmitter { - public prependListener: (event: string, listener: Function) => this; - public prependOnceListener: (event: string, listener: Function) => this; - public eventNames: () => string[]; - public addListener: (event: string, listener: Function) => this; - public on: (event: string, listener: Function) => this; - public once: (event: string, listener: Function) => this; - public removeListener: (event: string, listener: Function) => this; - public removeAllListeners: (event?: string) => this; - public setMaxListeners: (n: number) => this; - public getMaxListeners: () => number; - public listeners: (event: string) => Function[]; - public listenerCount: (type: string) => number; - public emit: (event: string, ...args: any[]) => boolean; +class EEObject extends IDObject implements EventEmitter { + /** + * Return an array listing the events for which the emitter has registered + * listeners. + */ + public eventNames: () => Array; + + /** + * Return the listeners registered for a given event. + */ + public listeners: ((event: string | symbol, exists: boolean) => Array | boolean) & ((event: string | symbol) => Array); + + /** + * Calls each of the listeners registered for a given event. + */ + public emit: (event: string | symbol, ...args: Array) => boolean; + + /** + * Add a listener for a given event. + */ + public on: (event: string | symbol, fn: ListenerFn, context?: any) => this; + public addListener: (event: string | symbol, fn: ListenerFn, context?: any) => this; + + /** + * Add a one-time listener for a given event. + */ + public once: (event: string | symbol, fn: ListenerFn, context?: any) => this; + + /** + * Remove the listeners of a given event. + */ + public removeListener: (event: string | symbol, fn?: ListenerFn, context?: any, once?: boolean) => this; + public off: (event: string | symbol, fn?: ListenerFn, context?: any, once?: boolean) => this; + + /** + * Remove all listeners, or those of the specified event. + */ + public removeAllListeners: (event?: string | symbol) => this; constructor() { super(); + EventEmitter.call(this); } } diff --git a/src/Base/ListenerFunction.ts b/src/Base/ListenerFunction.ts new file mode 100644 index 000000000..5f0b4a614 --- /dev/null +++ b/src/Base/ListenerFunction.ts @@ -0,0 +1,3 @@ +import {ListenerFn} from "eventemitter3"; +export interface Fake {} +export default ListenerFn; diff --git a/src/Interface/NodeInterface.ts b/src/Interface/NodeInterface.ts index e95036d32..cdc2e8c56 100644 --- a/src/Interface/NodeInterface.ts +++ b/src/Interface/NodeInterface.ts @@ -4,6 +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"; /** @@ -104,9 +105,9 @@ export default class NodeInterface { /** * 対象ノードにイベントリスナを追加します。 * @param {string} eventName [description] - * @param {Function} listener [description] + * @param {ListenerFunction} listener [description] */ - public on(eventName: string, listener: Function): NodeInterface { + public on(eventName: string, listener: ListenerFunction): NodeInterface { this.forEach(node => { node.on(eventName, listener); }); @@ -116,9 +117,9 @@ export default class NodeInterface { /** * 対象ノードに指定したイベントリスナが登録されていれば削除します * @param {string} eventName [description] - * @param {Function} listener [description] + * @param {ListenerFunction} listener [description] */ - public off(eventName: string, listener: Function): NodeInterface { + public off(eventName: string, listener: ListenerFunction): NodeInterface { this.forEach(node => { node.removeListener(eventName, listener); }); From 6605b2d72a9629904748cd5a548d3f8c6af13484 Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Thu, 3 Aug 2017 17:38:17 +0900 Subject: [PATCH 02/97] fix: Readme --- README.md | 156 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 103 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index 74670b3c9..73c1be8bc 100644 --- a/README.md +++ b/README.md @@ -5,87 +5,137 @@ [![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jThreeJS/jThree/blob/develop/LICENSE) [![Dependency Status](https://david-dm.org/GrimoireGL/GrimoireJS.svg)](https://david-dm.org/GrimoireGL/GrimoireJS) [![devDependency Status](https://david-dm.org/GrimoireGL/GrimoireJS/dev-status.svg)](https://david-dm.org/GrimoireGL/GrimoireJS#info=devDependencies) +[![Greenkeeper badge](https://badges.greenkeeper.io/GrimoireGL/GrimoireJS.svg)](https://greenkeeper.io/) ## Overview -[![Greenkeeper badge](https://badges.greenkeeper.io/GrimoireGL/GrimoireJS.svg)](https://greenkeeper.io/) +**Grimoire.js provide a bridge between Web engineers and CG engineers** -Why virtual DOM needs to be only for actual DOM? -Logics like drawing formulas for canvas even needs DOM for easier way. +There were big gap between the development flows used for each. -* **DOM based** ・・・The way that Web engineers can work most effectively. -* **jQuery like API** ・・・No more complex procedural WebGL logics, just operate attributes with the API. -* **Web development friendly**・・・Use with the other Web front-end frameworks. Very easy to coop with them. -* **No more redundant codes**・・・Include only `tag`s you actually need. +Web engineers have typically used `event driven` javascript programs for daily works. And they mutate DOM APIs to make Web pages dynamic. -## Download +However, CG engineers haves typically used `loop based` programs for daily works. These are mostly build with a programming language with strong type like C++ or C#. And recently CG engineers more like to use strongly structured engines like Unity. -The file you might want to download is not included this repository since even set of WebGL operations are treated as plugins. -Basic set for using Grimoire.js is bundled and published here([unpkg](https://unpkg.com/grimoirejs-preset-basic@1.8.5/register/grimoire-preset-basic.min.js)). -This file includes `grimoirejs`,`grimoirejs-math` and `grimoirejs-fundamental`. +This is why these 2 engineers have so much different flow for workings. This is why it is hard to learn CG stuff by Web engineers. And CG engineers are also hard to make suitable APIs for Web engineers working with. -## First Interact +**Grimoire.js is a javascript(Typescript) framework to solve this problem with strong architecture** -**HTML file** +## Features -```xml - - - - - - ", []); +// 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 34/97] 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 35/97] 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 36/97] 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 37/97] 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 38/97] 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 39/97] 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 40/97] 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 41/97] 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 42/97] 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 43/97] 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 44/97] 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 45/97] 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 46/97] 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 47/97] [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 48/97] [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 49/97] [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 50/97] [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 51/97] [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 52/97] 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 53/97] 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 54/97] 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 55/97] 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 125e618567833a846bc9ffa20a1ab43e8aba357c Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Wed, 18 Oct 2017 13:02:23 +0900 Subject: [PATCH 56/97] fix: Check DOMContentLoaded was fired before calling waiting for DOMContentLoaded --- .gitignore | 2 ++ src/main.ts | 6 ++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 3f50108f3..e5f01369d 100644 --- a/.gitignore +++ b/.gitignore @@ -128,3 +128,5 @@ yarn.lock docs test-lib test-lib-es5 +package-lock.json +.vscode \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index dd8f1cde5..88393ea99 100644 --- a/src/main.ts +++ b/src/main.ts @@ -15,7 +15,9 @@ class GrimoireInitializer { GrimoireInitializer._notifyLibraryLoadingToWindow(); GrimoireInitializer._copyGLConstants(); GrimoireInterface.initialize(); - await GrimoireInitializer._waitForDOMLoading(); + if (document.readyState === "loading") { + await GrimoireInitializer._waitForDOMLoading(); + } GrimoireInitializer._logVersions(); await GrimoireInterface.resolvePlugins(); await GomlLoader.loadForPage(); @@ -82,7 +84,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 6fc0163ce9f238b5d943c1d83b97d81786bc0b42 Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Wed, 18 Oct 2017 23:17:32 +0900 Subject: [PATCH 57/97] feat: Accepting library preference as a object on global that is initialized before loading. GrimoireJS.postponeLoading --- src/Interface/GrimoireInterfaceImpl.ts | 1 + src/main.ts | 34 ++++++++++++++++++++------ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/Interface/GrimoireInterfaceImpl.ts b/src/Interface/GrimoireInterfaceImpl.ts index 8b822f303..fda8efc78 100644 --- a/src/Interface/GrimoireInterfaceImpl.ts +++ b/src/Interface/GrimoireInterfaceImpl.ts @@ -49,6 +49,7 @@ export default class GrimoireInterfaceImpl extends EEObject { public nodeDictionary: { [nodeId: string]: GomlNode } = {}; public componentDictionary: { [componentId: string]: Component } = {}; + public libraryPreference?: { [preference: string]: any }; public debug = true; /** diff --git a/src/main.ts b/src/main.ts index 88393ea99..d40428b91 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,6 +1,11 @@ import GrimoireInterface from "./Interface/GrimoireInterface"; import GomlLoader from "./Node/GomlLoader"; +interface IGrimoireWindow extends Window { + GrimoireJS: typeof GrimoireInterface; + gr?: typeof GrimoireInterface; +} + /** * Provides procedures for initializing. */ @@ -15,9 +20,8 @@ class GrimoireInitializer { GrimoireInitializer._notifyLibraryLoadingToWindow(); GrimoireInitializer._copyGLConstants(); GrimoireInterface.initialize(); - if (document.readyState === "loading") { - await GrimoireInitializer._waitForDOMLoading(); - } + await GrimoireInitializer._waitForDOMLoading(); + await GrimoireInitializer._waitForPluginLoadingSuspendPromise(); GrimoireInitializer._logVersions(); await GrimoireInterface.resolvePlugins(); await GomlLoader.loadForPage(); @@ -51,9 +55,13 @@ class GrimoireInitializer { */ private static _waitForDOMLoading(): Promise { return new Promise((resolve) => { - window.addEventListener("DOMContentLoaded", () => { + if (document.readyState === "loading") { + window.addEventListener("DOMContentLoaded", () => { + resolve(); + }); + } else { resolve(); - }); + } }); } @@ -79,13 +87,25 @@ class GrimoireInitializer { $messageType: "library-loading" }, "*"); } + + private static async _waitForPluginLoadingSuspendPromise(): Promise { + if (!GrimoireInterface.libraryPreference) { + return; + } + await (GrimoireInterface.libraryPreference["suspendForLoading"] as Promise); + } } /** * Just start the process. */ export default function (): typeof GrimoireInterface { + const gwin = window as IGrimoireWindow; + if (gwin.GrimoireJS) { + GrimoireInterface.libraryPreference = gwin.GrimoireJS; + } + gwin.gr = gwin.GrimoireJS = GrimoireInterface; GrimoireInitializer.initialize(); - GrimoireInterface.noConflictPreserve = (window as any)["gr"]; - return (window as any)["gr"] = (window as any)["GrimoireJS"] = GrimoireInterface; + GrimoireInterface.noConflictPreserve = gwin.gr; + return GrimoireInterface; } From 5bd0b8cbac4b439d562902ad96c8459094f43ef4 Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Thu, 19 Oct 2017 20:46:06 +0900 Subject: [PATCH 58/97] feat: Implemented postponeLoading --- src/main.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.ts b/src/main.ts index d40428b91..a3b5800f6 100644 --- a/src/main.ts +++ b/src/main.ts @@ -92,7 +92,7 @@ class GrimoireInitializer { if (!GrimoireInterface.libraryPreference) { return; } - await (GrimoireInterface.libraryPreference["suspendForLoading"] as Promise); + await (GrimoireInterface.libraryPreference["postponeLoading"] as Promise); } } @@ -104,8 +104,8 @@ export default function (): typeof GrimoireInterface { if (gwin.GrimoireJS) { GrimoireInterface.libraryPreference = gwin.GrimoireJS; } + GrimoireInterface.noConflictPreserve = gwin.gr; gwin.gr = gwin.GrimoireJS = GrimoireInterface; GrimoireInitializer.initialize(); - GrimoireInterface.noConflictPreserve = gwin.gr; return GrimoireInterface; } From eb6b0fe5efb3129960d9e26048cd5aa9024aa3b9 Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Fri, 20 Oct 2017 16:33:40 +0900 Subject: [PATCH 59/97] fix: Add staging javascript upload shell command --- circle.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/circle.yml b/circle.yml index 97b32982a..36fca09eb 100644 --- a/circle.yml +++ b/circle.yml @@ -21,6 +21,7 @@ test: - aws s3 cp ./coverage/ s3://coverage.grimoire.gl/core/$CIRCLE_BRANCH --recursive --region ap-northeast-1 --acl public-read override: - npm run lint && npm run build && npm run coverage + - aws s3 cp ./register/ s3://ci.grimoire.gl/js/grimoirejs/${CIRCLE_BRANCH}_${CIRCLE_BUILD_NUM} --recursive --region ap-northeast-1 --acl public-read deployment: deploy: From 7da1cf7a435569f420e4f199b8f9df1e244b4c83 Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Fri, 20 Oct 2017 16:47:29 +0900 Subject: [PATCH 60/97] fix: use npm instead of yarn --- circle.yml | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/circle.yml b/circle.yml index 36fca09eb..6928c5e98 100644 --- a/circle.yml +++ b/circle.yml @@ -2,19 +2,6 @@ machine: node: version: 6.9.5 - post: - - curl -o- -L https://yarnpkg.com/install.sh | bash - -dependencies: - cache_directories: - - "~/.cache/yarn" - - pre: - - yarn --version - - override: - - yarn install - test: post: - sh release.sh From deee9003e43c565fab13116d3e2385519225cb3c Mon Sep 17 00:00:00 2001 From: moajo Date: Sun, 15 Oct 2017 23:03:30 +0900 Subject: [PATCH 61/97] 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 62/97] 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 63/97] 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 64/97] 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 65/97] 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 66/97] 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 67/97] 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 68/97] 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 69/97] 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 70/97] 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 71/97] 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 72/97] 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 73/97] 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 74/97] 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 29b61643f52d6a3447bdf3a9c77f01776b17fe81 Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Sun, 5 Nov 2017 20:14:16 +0900 Subject: [PATCH 75/97] fix: add e2e testing --- circle.yml | 12 +++++++----- shell/e2e.sh | 2 ++ 2 files changed, 9 insertions(+), 5 deletions(-) create mode 100644 shell/e2e.sh diff --git a/circle.yml b/circle.yml index 6928c5e98..d02316394 100644 --- a/circle.yml +++ b/circle.yml @@ -1,18 +1,20 @@ machine: node: version: 6.9.5 - test: post: - sh release.sh - - aws s3 cp ./coverage/ s3://coverage.grimoire.gl/core/$CIRCLE_BRANCH --recursive --region ap-northeast-1 --acl public-read + - >- + aws s3 cp ./coverage/ s3://coverage.grimoire.gl/core/$CIRCLE_BRANCH + --recursive --region ap-northeast-1 --acl public-read override: - npm run lint && npm run build && npm run coverage - - aws s3 cp ./register/ s3://ci.grimoire.gl/js/grimoirejs/${CIRCLE_BRANCH}_${CIRCLE_BUILD_NUM} --recursive --region ap-northeast-1 --acl public-read - + - sh -x shell/e2e.sh deployment: deploy: branch: master commands: - npm run doc - - aws s3 cp ./docs/ s3://api.grimoire.gl/core --recursive --region ap-northeast-1 --acl public-read + - >- + aws s3 cp ./docs/ s3://api.grimoire.gl/core --recursive --region + ap-northeast-1 --acl public-read diff --git a/shell/e2e.sh b/shell/e2e.sh new file mode 100644 index 000000000..15479b1b0 --- /dev/null +++ b/shell/e2e.sh @@ -0,0 +1,2 @@ +aws s3 cp register/ s3://$S3_BUCKET_URL/js/$CIRCLE_SHA1 --recursive --acl public-read +curl -X POST -d "repositoryURL=$CIRCLE_REPOSITORY_URL" -d "currentBranch=$CIRCLE_BRANCH" -d "currentBuildNumber=$CIRCLE_BUILD_NUM" -d "previousBuildNumber=$CIRCLE_PREVIOUS_BUILD_NUM" -d "sha1=$CIRCLE_SHA1" -d "pullRequest=$CI_PULL_REQUEST" $E2E_TRIGGER \ No newline at end of file From 27c2eb0ea36792af11a7c1ca0bfe2a0a34d12e2e Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Sun, 5 Nov 2017 20:20:09 +0900 Subject: [PATCH 76/97] fix: add region code --- shell/e2e.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shell/e2e.sh b/shell/e2e.sh index 15479b1b0..9b392fcf9 100644 --- a/shell/e2e.sh +++ b/shell/e2e.sh @@ -1,2 +1,2 @@ -aws s3 cp register/ s3://$S3_BUCKET_URL/js/$CIRCLE_SHA1 --recursive --acl public-read +aws s3 cp register/ s3://$S3_BUCKET_URL/js/$CIRCLE_SHA1 --recursive --acl public-read --region ap-northeast-1 curl -X POST -d "repositoryURL=$CIRCLE_REPOSITORY_URL" -d "currentBranch=$CIRCLE_BRANCH" -d "currentBuildNumber=$CIRCLE_BUILD_NUM" -d "previousBuildNumber=$CIRCLE_PREVIOUS_BUILD_NUM" -d "sha1=$CIRCLE_SHA1" -d "pullRequest=$CI_PULL_REQUEST" $E2E_TRIGGER \ No newline at end of file From e6eb89be82ec531a5d1206801b51d10645b260b1 Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Sun, 5 Nov 2017 20:40:45 +0900 Subject: [PATCH 77/97] fix: Removed noUnusedLocals temporary. This rise some build error --- package.json | 18 +++++++++--------- tsconfig.json | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index 133c4300a..80e062526 100644 --- a/package.json +++ b/package.json @@ -26,25 +26,25 @@ "babel-register": "^6.26.0", "condition-circle": "^1.5.0", "cpx": "^1.5.0", - "grimoirejs-cauldron": "^3.1.6", - "jsdom": "^11.1.0", + "grimoirejs-cauldron": "^3.1.8", + "jsdom": "^11.3.0", "lodash": "^4.17.2", - "nyc": "^11.1.0", + "nyc": "^11.3.0", "proxyquire": "^1.7.11", "regenerator-runtime": "^0.11.0", "remap-istanbul": "^0.9.5", "semantic-release": "^7.0.2", - "sinon": "^3.2.1", + "sinon": "^3.3.0", "trash-cli": "^1.4.0", - "ts-loader": "^2.3.3", - "tslint": "^5.6.0", + "ts-loader": "^2.3.7", + "tslint": "^5.8.0", "typedoc": "^0.8.0", "typedoc-md-theme": "^1.0.1", - "typescript": "^2.4.2", + "typescript": "^2.6.1", "typescript-awaiter": "^1.0.0", - "webpack": "^3.5.5", + "webpack": "^3.8.1", "webpack-shell-plugin": "^0.5.0", - "xhr-mock": "^1.7.0", + "xhr-mock": "^1.9.1", "xmldom": "^0.1.27", "yargs": "^8.0.2" }, diff --git a/tsconfig.json b/tsconfig.json index 12ffdbfa0..08b07318c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,10 +8,10 @@ "declarationDir": "./ref", "noImplicitReturns": true, "noUnusedParameters": true, - "noUnusedLocals":true, + "noUnusedLocals": false, "strict": true }, "include": [ "src/**/*.ts" ] -} +} \ No newline at end of file From 02e180e8c632e04e642881cfd6733e09a720051a Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Sun, 5 Nov 2017 20:50:40 +0900 Subject: [PATCH 78/97] fix: for lint --- src/Base/NSIdentity.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Base/NSIdentity.ts b/src/Base/NSIdentity.ts index f4569da5e..f051d9ffd 100644 --- a/src/Base/NSIdentity.ts +++ b/src/Base/NSIdentity.ts @@ -9,7 +9,7 @@ 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(); } From d40a32b89b5eaafafab5b150fe7a6b527bc7dd3f Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Sun, 5 Nov 2017 23:11:29 +0900 Subject: [PATCH 79/97] trigger e2e From 2e3fafb92cf455c78e38657c0c709766ff4c9b54 Mon Sep 17 00:00:00 2001 From: Kakeru Ishii Date: Mon, 6 Nov 2017 03:17:43 +0900 Subject: [PATCH 80/97] trigger e2e From e3644eb3e759d40961f9fd6df35d75ef30c34500 Mon Sep 17 00:00:00 2001 From: moajo Date: Tue, 21 Nov 2017 22:27:08 +0900 Subject: [PATCH 81/97] 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 82/97] 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 83/97] 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 84/97] 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 85/97] 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 86/97] 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 87/97] 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 88/97] 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 89/97] 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 90/97] 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 91/97] 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 92/97] 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 93/97] 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 94/97] 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 95/97] 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('