import { Asset } from "../assets/Asset" ; import * as Attributes from "../core/Attributes" ; import { SyncEvent } from "ts-events" ; import { Constructor } from "../core/Types" ; hidden var EditorEvents = undefined ; if ( process . env . CONFIG === "editor" ) { EditorEvents = require ( "../editor/CommonEditorEvents" ) . CommonEditorEvents ; } export enum AssetReferenceState { Loading , Resolved } export interface AssetChangedEvent { oldAsset : Asset | null ; newAsset : Asset | null ; } export class AssetReference < T extends Asset > { typeName : ( ) => string ; get id ( ) { return this . _id ; } set id ( id ) { this . _id = id ; this . _state = AssetReferenceState . Loading ; } get asset ( ) { return this . _asset ; } set asset ( asset ) { let oldAsset = this . _asset ; if ( process . env . CONFIG === "editor" ) { if ( oldAsset ) { oldAsset . deleted . detach ( this . onAssetDeleted ) ; } } this . _asset = asset ; this . _state = AssetReferenceState . Resolved ; if ( asset ) { if ( process . env . CONFIG === "editor" ) { this . _id = asset . id ; asset . deleted . attach ( this . onAssetDeleted ) ; } else { this . _id = asset . templatePath ; } } else { this . _id = undefined ; } if ( asset !== oldAsset ) { this . assetChanged . post ( { oldAsset : oldAsset , newAsset : asset } ) ; } } get state ( ) { return this . _state ; } set state ( state ) { this . _state = state ; } get resolved ( ) { return this . _state === AssetReferenceState . Resolved ; } get inline ( ) { return this . _inline ; } set inline ( inline ) { this . _inline = inline ; } event @ Attributes . unserializable ( ) assetChanged = new SyncEvent < AssetChangedEvent > ( ) ; private _id ? : string ; @ Attributes . unserializable ( ) private _asset : T | null = null ; @ Attributes . unserializable ( ) private _state = AssetReferenceState . Resolved ; @ Attributes . unserializable ( ) private _inline = false ; constructor ( ctor , instance ? , inline ? ) { this . typeName = ( ) => ctor . name ; this . onAssetDeleted = this . onAssetDeleted . bind ( this ) ; this . _inline = Boolean ( inline ) ; if ( instance ) { this . _asset = instance ; this . _id = instance . id ; this . _state = AssetReferenceState . Resolved ; } } clear ( ) { this . asset = null ; } setAssetFast ( asset ) { this . _asset = asset ; } detach ( ) { if ( process . env . CONFIG === "editor" ) { if ( this . _asset ) { this . _asset . deleted . detach ( this . onAssetDeleted ) ; } } this . _asset = null ; } private onAssetDeleted ( id ) { this . detach ( ) ; if ( EditorEvents ) { EditorEvents . assetReferenceCleared . post ( id ) ; } } }