UIManager.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import { instantiate, Node } from 'cc';
  2. import { BUNDLE_ID } from '@scripts/define/ResDefine';
  3. import { getUIViewConfig, UIViewConfig, UIViewID } from '../../define/UIDefine';
  4. import { ResourceManager } from '../resource/ResourceManager';
  5. import { UICachePolicy, UICloseReason, UILayer, UIViewState } from './UILayer';
  6. import { UIView } from './UIView';
  7. interface UIViewRecord {
  8. config: UIViewConfig;
  9. state: UIViewState;
  10. view: UIView | null;
  11. ownerRoot: Node | null;
  12. generation: number;
  13. opening: Promise<UIView | null> | null;
  14. closing: Promise<boolean> | null;
  15. delayedDestroyTimer: ReturnType<typeof setTimeout> | null;
  16. }
  17. export class UIManager {
  18. private static readonly DELAYED_DESTROY_MS = 5000;
  19. private readonly records = new Map<UIViewID, UIViewRecord>();
  20. private readonly roots = new Map<UILayer, Node>();
  21. constructor(private readonly resources: ResourceManager) { }
  22. bindLayer(layer: UILayer, root: Node): void {
  23. this.roots.set(layer, root);
  24. }
  25. /**
  26. * 接管当前场景各 UI Layer 中预放置的 UIView。
  27. * 注册后的 View 先进入缓存态,之后仍由 open/close 统一驱动生命周期。
  28. */
  29. async registerSceneViews(): Promise<void> {
  30. for (const [layer, root] of this.roots) {
  31. if (!root.isValid) continue;
  32. const views = root.getComponentsInChildren(UIView);
  33. for (const view of views) {
  34. const viewId = view.viewId;
  35. if (!viewId) {
  36. console.warn(`[UIManager] Scene UIView has no viewId: ${view.node.name}`);
  37. continue;
  38. }
  39. const config = getUIViewConfig(viewId);
  40. if (!config) {
  41. console.warn(`[UIManager] Scene UIView is not configured: ${viewId}`);
  42. continue;
  43. }
  44. if (config.layer !== layer) {
  45. console.warn(
  46. `[UIManager] Scene UIView is under the wrong layer: ${viewId}, expected=${config.layer}, actual=${layer}`,
  47. );
  48. continue;
  49. }
  50. const existing = this.records.get(viewId);
  51. if (existing?.view === view) continue;
  52. if (existing?.view?.node?.isValid) {
  53. console.warn(`[UIManager] Duplicate scene UIView ignored: ${viewId}`);
  54. continue;
  55. }
  56. if (existing) this.forgetRecord(existing);
  57. const record: UIViewRecord = {
  58. config,
  59. state: UIViewState.Creating,
  60. view,
  61. ownerRoot: root,
  62. generation: 1,
  63. opening: null,
  64. closing: null,
  65. delayedDestroyTimer: null,
  66. };
  67. this.records.set(viewId, record);
  68. view.node.active = false;
  69. try {
  70. await view.internalCreate();
  71. if (!view.node.isValid || this.records.get(viewId) !== record) {
  72. this.forgetRecord(record);
  73. continue;
  74. }
  75. record.state = UIViewState.Cached;
  76. } catch (error) {
  77. this.forgetRecord(record);
  78. throw error;
  79. }
  80. }
  81. }
  82. }
  83. clearSceneLayers(): void {
  84. const sceneRoots = new Set(this.roots.values());
  85. this.roots.clear();
  86. for (const record of [...this.records.values()]) {
  87. const node = record.view?.node;
  88. const belongsToSceneLayer = node?.isValid
  89. ? [...sceneRoots].some((root) => root.isValid && (node === root || node.isChildOf(root)))
  90. : record.ownerRoot !== null && sceneRoots.has(record.ownerRoot);
  91. if (!node?.isValid || belongsToSceneLayer) {
  92. this.forgetRecord(record);
  93. }
  94. }
  95. }
  96. get<TView extends UIView>(viewId: UIViewID): TView | null {
  97. const record = this.records.get(viewId);
  98. if (
  99. !record
  100. || !record.view?.node?.isValid
  101. || (record.state !== UIViewState.Opening && record.state !== UIViewState.Opened)
  102. ) {
  103. return null;
  104. }
  105. return record.view as TView | null;
  106. }
  107. isOpen(viewId: UIViewID): boolean {
  108. return this.get(viewId) !== null;
  109. }
  110. async open<TView extends UIView, TParams = unknown>(viewId: UIViewID, params?: TParams): Promise<TView | null> {
  111. let record = this.records.get(viewId);
  112. if (record?.view && !record.view.node.isValid) {
  113. this.forgetRecord(record);
  114. record = undefined;
  115. }
  116. if (record?.state === UIViewState.Opened) return record.view as TView;
  117. if (record?.opening) return record.opening as Promise<TView | null>;
  118. if (record?.closing) await record.closing;
  119. if (record) this.cancelDelayedDestroy(record);
  120. if (record?.state === UIViewState.Cached && record.view?.node.isValid) {
  121. await this.closeMutexViews(record.config);
  122. record.state = UIViewState.Opening;
  123. record.view.node.active = true;
  124. await record.view.internalOpen(params);
  125. record.state = UIViewState.Opened;
  126. return record.view as TView;
  127. }
  128. const config = getUIViewConfig(viewId);
  129. const root = this.roots.get(config.layer);
  130. if (!root?.isValid) throw new Error(`[UIManager] UILayer is not bound: ${config.layer}`);
  131. record = record ?? {
  132. config,
  133. state: UIViewState.None,
  134. view: null,
  135. ownerRoot: root,
  136. generation: 0,
  137. opening: null,
  138. closing: null,
  139. delayedDestroyTimer: null,
  140. };
  141. record.ownerRoot = root;
  142. this.records.set(viewId, record);
  143. const generation = ++record.generation;
  144. record.opening = this.performOpen(record, root, params, generation);
  145. try {
  146. return await record.opening as TView | null;
  147. } finally {
  148. if (record.generation === generation) record.opening = null;
  149. }
  150. }
  151. async close(viewIdOrInstance: UIViewID, reason = UICloseReason.User): Promise<boolean> {
  152. const record = typeof viewIdOrInstance === 'string'
  153. ? this.records.get(viewIdOrInstance)
  154. : [...this.records.values()].find((item) => item.view === viewIdOrInstance);
  155. if (!record) return false;
  156. if (record.closing) return record.closing;
  157. if (record.state === UIViewState.Cached) return true;
  158. ++record.generation;
  159. record.closing = this.performClose(record, reason);
  160. try {
  161. return await record.closing;
  162. } finally {
  163. record.closing = null;
  164. }
  165. }
  166. async closeAll(reason = UICloseReason.SceneChanged): Promise<void> {
  167. await Promise.all([...this.records.values()].map((record) => this.close(record.config.id, reason)));
  168. }
  169. private async performOpen(
  170. record: UIViewRecord,
  171. root: Node,
  172. params: unknown,
  173. generation: number,
  174. ): Promise<UIView | null> {
  175. record.state = UIViewState.Loading;
  176. const bundleName = record.config.bundle || BUNDLE_ID.Lobby;
  177. const prefab = await this.resources.loadPrefab(bundleName, record.config.prefabPath);
  178. if (generation !== record.generation) return null;
  179. record.state = UIViewState.Creating;
  180. const node = instantiate(prefab);
  181. root.addChild(node);
  182. const view = node.getComponent(UIView);
  183. if (!view) {
  184. node.destroy();
  185. throw new Error(`[UIManager] Prefab has no UIView component: ${record.config.id}`);
  186. }
  187. record.view = view;
  188. await view.internalCreate();
  189. if (generation !== record.generation || !node.isValid) {
  190. node.destroy();
  191. record.view = null;
  192. return null;
  193. }
  194. await this.closeMutexViews(record.config);
  195. record.state = UIViewState.Opening;
  196. node.active = true;
  197. await view.internalOpen(params);
  198. if (generation !== record.generation || !node.isValid) return null;
  199. record.state = UIViewState.Opened;
  200. return view;
  201. }
  202. private async performClose(record: UIViewRecord, reason: UICloseReason): Promise<boolean> {
  203. if (!record.view?.node?.isValid) {
  204. this.cancelDelayedDestroy(record);
  205. record.state = UIViewState.Disposed;
  206. record.view = null;
  207. this.records.delete(record.config.id);
  208. return false;
  209. }
  210. const allow = reason === UICloseReason.ForceDispose
  211. ? true
  212. : await record.view.internalBeforeClose(reason);
  213. if (!allow) return false;
  214. record.state = UIViewState.Closing;
  215. await record.view.internalClose(reason);
  216. const uiCache = record.config.cache || UICachePolicy.None;
  217. if (reason === UICloseReason.ForceDispose || uiCache === UICachePolicy.None) {
  218. this.disposeRecord(record);
  219. return true;
  220. }
  221. record.view.node.active = false;
  222. record.state = UIViewState.Cached;
  223. if (uiCache === UICachePolicy.Delayed) {
  224. this.scheduleDelayedDestroy(record);
  225. }
  226. return true;
  227. }
  228. private scheduleDelayedDestroy(record: UIViewRecord): void {
  229. this.cancelDelayedDestroy(record);
  230. const generation = record.generation;
  231. record.delayedDestroyTimer = setTimeout(() => {
  232. record.delayedDestroyTimer = null;
  233. if (
  234. record.generation === generation
  235. && record.state === UIViewState.Cached
  236. ) {
  237. this.disposeRecord(record);
  238. }
  239. }, UIManager.DELAYED_DESTROY_MS);
  240. }
  241. private cancelDelayedDestroy(record: UIViewRecord): void {
  242. if (record.delayedDestroyTimer === null) return;
  243. clearTimeout(record.delayedDestroyTimer);
  244. record.delayedDestroyTimer = null;
  245. }
  246. private disposeRecord(record: UIViewRecord): void {
  247. this.cancelDelayedDestroy(record);
  248. if (record.view?.node?.isValid) {
  249. record.view.internalDispose();
  250. record.view.node.destroy();
  251. }
  252. record.view = null;
  253. record.ownerRoot = null;
  254. record.state = UIViewState.Disposed;
  255. this.records.delete(record.config.id);
  256. }
  257. /** 从管理器中同步移除记录,不主动销毁正由场景释放的节点。 */
  258. private forgetRecord(record: UIViewRecord): void {
  259. ++record.generation;
  260. this.cancelDelayedDestroy(record);
  261. if (record.view?.node?.isValid) {
  262. record.view.internalDispose();
  263. }
  264. record.view = null;
  265. record.ownerRoot = null;
  266. record.opening = null;
  267. record.closing = null;
  268. record.state = UIViewState.Disposed;
  269. if (this.records.get(record.config.id) === record) {
  270. this.records.delete(record.config.id);
  271. }
  272. }
  273. private async closeMutexViews(config: UIViewConfig): Promise<void> {
  274. const tasks: Promise<boolean>[] = [];
  275. for (const record of this.records.values()) {
  276. if (!record.config.mutexGroup) continue;
  277. if (record.config.id !== config.id && record.config.mutexGroup === config.mutexGroup) {
  278. tasks.push(this.close(record.config.id, UICloseReason.Navigation));
  279. }
  280. }
  281. await Promise.all(tasks);
  282. }
  283. loading(active: boolean) {
  284. if (active) {
  285. this.open(UIViewID.LoadingView);
  286. } else {
  287. this.close(UIViewID.LoadingView);
  288. }
  289. }
  290. toast() {
  291. }
  292. dialog() {
  293. }
  294. }