package hw.view; import flash.display.DisplayObject; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.errors.Error; import flash.events.Event; import flash.geom.Rectangle; import flash.Lib; import hw.provider.Provider; import hw.signal.Signal; import hw.view.group.IGroupView; class Root { public static function bind(view:IView, autoSize:Bool = true) { new Root(view, autoSize); } public static var instance(default, null):Root; public var view(default, null):IView; public var autoSize(default, default):Bool; public var onResize(default, null):Signal = new Signal(); public function new(view:IView, autoSize:Bool = true) { if (instance != null) throw new Error("Only one instance"); instance = this; this.view = view; this.autoSize = autoSize; Lib.current.addChild(view.content); if (Std.is(view, IGroupView)) { Provider.instance.set(IGroupView, cast view); } var content:DisplayObject = view.content; if (content.stage == null) { content.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage); } else { onAddedToStage(); } View.updater.update(); } private function onAddedToStage(?_):Void { var content:DisplayObject = view.content; content.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); content.stage.scaleMode = StageScaleMode.NO_SCALE; content.stage.align = StageAlign.TOP_LEFT; View.updater.stage = content.stage; content.stage.addEventListener(Event.RESIZE, onResizeEvent); content.stage.stageFocusRect = false; onResizeEvent(); } private function onResizeEvent(?_):Void { var content:DisplayObject = view.content; if (autoSize) { view.setSize(content.stage.stageWidth, content.stage.stageHeight, "stage"); view.toUpdate(); } else { view.x = (content.stage.stageWidth - view.width) / 2; view.y = (content.stage.stageHeight - view.height) / 2; } onResize.emit(new Rectangle(0, 0, content.stage.stageWidth, content.stage.stageHeight)); } public function dispose():Void { if (view != null) { view.content.stage.removeEventListener(Event.RESIZE, onResizeEvent); view = null; } onResize.dispose(); } private static function getViews(view:IView):Array> { var result = []; result.push(view); if (Std.is(view, IGroupView)) { for (v in cast(view, IGroupView).views) { result = result.concat(getViews(v)); } } return result; } public function views():Array> { return getViews(view); } }