UIManager.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. private loadingCount = 0;
  22. constructor(private readonly resources: ResourceManager) { }
  23. bindLayer(layer: UILayer, root: Node): void {
  24. this.roots.set(layer, root);
  25. }
  26. /**
  27. * 接管当前场景各 UI Layer 中预放置的 UIView。
  28. * 注册后的 View 先进入缓存态,之后仍由 open/close 统一驱动生命周期。
  29. */
  30. async registerSceneViews(): Promise<void> {
  31. for (const [layer, root] of this.roots) {
  32. if (!root.isValid) continue;
  33. const views = root.getComponentsInChildren(UIView);
  34. for (const view of views) {
  35. const viewId = view.getViewID();
  36. if (!viewId) {
  37. console.warn(`[UIManager] Scene UIView has no viewId: ${view.node.name}`);
  38. continue;
  39. }
  40. const config = getUIViewConfig(viewId);
  41. if (!config) {
  42. console.warn(`[UIManager] Scene UIView is not configured: ${viewId}`);
  43. continue;
  44. }
  45. if (config.layer !== layer) {
  46. console.warn(
  47. `[UIManager] Scene UIView is under the wrong layer: ${viewId}, expected=${config.layer}, actual=${layer}`,
  48. );
  49. continue;
  50. }
  51. const existing = this.records.get(viewId);
  52. if (existing?.view === view) continue;
  53. if (existing?.view?.node?.isValid) {
  54. console.warn(`[UIManager] Duplicate scene UIView ignored: ${viewId}`);
  55. continue;
  56. }
  57. if (existing) this.forgetRecord(existing);
  58. const record: UIViewRecord = {
  59. config,
  60. state: UIViewState.Creating,
  61. view,
  62. ownerRoot: root,
  63. generation: 1,
  64. opening: null,
  65. closing: null,
  66. delayedDestroyTimer: null,
  67. };
  68. this.records.set(viewId, record);
  69. view.node.active = false;
  70. try {
  71. await view.internalCreate();
  72. if (!view.node.isValid || this.records.get(viewId) !== record) {
  73. this.forgetRecord(record);
  74. continue;
  75. }
  76. record.state = UIViewState.Cached;
  77. } catch (error) {
  78. this.forgetRecord(record);
  79. throw error;
  80. }
  81. }
  82. }
  83. }
  84. clearSceneLayers(): void {
  85. const sceneRoots = new Set(this.roots.values());
  86. this.roots.clear();
  87. for (const record of [...this.records.values()]) {
  88. const node = record.view?.node;
  89. const belongsToSceneLayer = node?.isValid
  90. ? [...sceneRoots].some((root) => root.isValid && (node === root || node.isChildOf(root)))
  91. : record.ownerRoot !== null && sceneRoots.has(record.ownerRoot);
  92. if (!node?.isValid || belongsToSceneLayer) {
  93. this.forgetRecord(record);
  94. }
  95. }
  96. }
  97. get<TView extends UIView>(viewId: UIViewID): TView | null {
  98. const record = this.records.get(viewId);
  99. if (
  100. !record
  101. || !record.view?.node?.isValid
  102. || (record.state !== UIViewState.Opening && record.state !== UIViewState.Opened)
  103. ) {
  104. return null;
  105. }
  106. return record.view as TView | null;
  107. }
  108. isOpen(viewId: UIViewID): boolean {
  109. return this.get(viewId) !== null;
  110. }
  111. async open<TView extends UIView, TParams = unknown>(viewId: UIViewID, params?: TParams): Promise<TView | null> {
  112. const config = getUIViewConfig(viewId);
  113. const currentRecord = this.records.get(viewId);
  114. const shouldShowLoading = config.ignoreLoading !== true
  115. && currentRecord?.state !== UIViewState.Opened
  116. && !currentRecord?.opening;
  117. if (!shouldShowLoading) {
  118. return this.openView<TView, TParams>(viewId, params);
  119. }
  120. await this.loading(true, 0.5);
  121. try {
  122. return await this.openView<TView, TParams>(viewId, params);
  123. } finally {
  124. await this.loading(false);
  125. }
  126. }
  127. private async openView<TView extends UIView, TParams = unknown>(
  128. viewId: UIViewID,
  129. params?: TParams,
  130. ): Promise<TView | null> {
  131. let record = this.records.get(viewId);
  132. if (record?.closing) {
  133. await record.closing;
  134. record = this.records.get(viewId);
  135. }
  136. if (record?.view && !record.view.node.isValid) {
  137. this.forgetRecord(record);
  138. record = undefined;
  139. }
  140. if (record?.state === UIViewState.Opened) return record.view as TView;
  141. if (record?.opening) return record.opening as Promise<TView | null>;
  142. if (record) this.cancelDelayedDestroy(record);
  143. if (record?.state === UIViewState.Cached && record.view?.node.isValid) {
  144. const generation = ++record.generation;
  145. const opening = this.performCachedOpen(record, params, generation);
  146. record.opening = opening;
  147. try {
  148. return await opening as TView | null;
  149. } finally {
  150. if (record.opening === opening) record.opening = null;
  151. }
  152. }
  153. const config = getUIViewConfig(viewId);
  154. const root = this.roots.get(config.layer);
  155. if (!root?.isValid) throw new Error(`[UIManager] UILayer is not bound: ${config.layer}`);
  156. record = record ?? {
  157. config,
  158. state: UIViewState.None,
  159. view: null,
  160. ownerRoot: root,
  161. generation: 0,
  162. opening: null,
  163. closing: null,
  164. delayedDestroyTimer: null,
  165. };
  166. record.ownerRoot = root;
  167. this.records.set(viewId, record);
  168. const generation = ++record.generation;
  169. const opening = this.performOpen(record, root, params, generation);
  170. record.opening = opening;
  171. try {
  172. return await opening as TView | null;
  173. } finally {
  174. if (record.opening === opening) record.opening = null;
  175. }
  176. }
  177. async close(viewIdOrInstance: UIViewID, reason = UICloseReason.User): Promise<boolean> {
  178. const record = typeof viewIdOrInstance === 'string'
  179. ? this.records.get(viewIdOrInstance)
  180. : [...this.records.values()].find((item) => item.view === viewIdOrInstance);
  181. if (!record) return false;
  182. if (record.closing) return record.closing;
  183. if (record.state === UIViewState.Cached) {
  184. if (record.opening) {
  185. ++record.generation;
  186. if ((record.config.cache || UICachePolicy.None) === UICachePolicy.Delayed) {
  187. this.scheduleDelayedDestroy(record);
  188. }
  189. }
  190. return true;
  191. }
  192. ++record.generation;
  193. record.closing = this.performClose(record, reason);
  194. try {
  195. return await record.closing;
  196. } finally {
  197. record.closing = null;
  198. }
  199. }
  200. async closeAll(reason = UICloseReason.SceneChanged): Promise<void> {
  201. const handles: Promise<boolean>[] = [];
  202. this.records.forEach(record => {
  203. handles.push(this.close(record.config.id, reason));
  204. })
  205. await Promise.all(handles);
  206. }
  207. private async performOpen(
  208. record: UIViewRecord,
  209. root: Node,
  210. params: unknown,
  211. generation: number,
  212. ): Promise<UIView | null> {
  213. record.state = UIViewState.Loading;
  214. const bundleName = record.config.bundle || BUNDLE_ID.Lobby;
  215. const prefab = await this.resources.loadPrefab(bundleName, record.config.prefabPath);
  216. if (generation !== record.generation) return null;
  217. const prefabView = prefab.data?.getComponent?.(UIView) as UIView | null;
  218. if (!prefabView) {
  219. record.state = UIViewState.None;
  220. throw new Error(`[UIManager] Prefab has no UIView component: ${record.config.id}`);
  221. }
  222. let allowOpen: boolean;
  223. try {
  224. allowOpen = await prefabView.internalOpenBefore(params);
  225. } catch (error) {
  226. if (generation === record.generation) record.state = UIViewState.None;
  227. throw error;
  228. }
  229. if (generation !== record.generation) return null;
  230. if (!allowOpen) {
  231. record.state = UIViewState.None;
  232. return null;
  233. }
  234. record.state = UIViewState.Creating;
  235. const node = instantiate(prefab);
  236. root.addChild(node);
  237. const view = node.getComponent(UIView);
  238. if (!view) {
  239. node.destroy();
  240. throw new Error(`[UIManager] Prefab has no UIView component: ${record.config.id}`);
  241. }
  242. record.view = view;
  243. await view.internalCreate();
  244. if (generation !== record.generation || !node.isValid) {
  245. node.destroy();
  246. record.view = null;
  247. return null;
  248. }
  249. await this.closeMutexViews(record.config);
  250. record.state = UIViewState.Opening;
  251. node.active = true;
  252. await view.internalOpen(params);
  253. if (generation !== record.generation || !node.isValid) return null;
  254. record.state = UIViewState.Opened;
  255. return view;
  256. }
  257. private async performCachedOpen(
  258. record: UIViewRecord,
  259. params: unknown,
  260. generation: number,
  261. ): Promise<UIView | null> {
  262. const view = record.view;
  263. if (!view?.node?.isValid) return null;
  264. let allowOpen: boolean;
  265. try {
  266. allowOpen = await view.internalOpenBefore(params);
  267. } catch (error) {
  268. if (generation === record.generation) this.restoreCachedRecord(record);
  269. throw error;
  270. }
  271. if (generation !== record.generation || !view.node.isValid) return null;
  272. if (!allowOpen) {
  273. this.restoreCachedRecord(record);
  274. return null;
  275. }
  276. await this.closeMutexViews(record.config);
  277. if (generation !== record.generation || !view.node.isValid) return null;
  278. record.state = UIViewState.Opening;
  279. view.node.active = true;
  280. await view.internalOpen(params);
  281. if (generation !== record.generation || !view.node.isValid) return null;
  282. record.state = UIViewState.Opened;
  283. return view;
  284. }
  285. private restoreCachedRecord(record: UIViewRecord): void {
  286. if (!record.view?.node?.isValid || this.records.get(record.config.id) !== record) return;
  287. record.view.node.active = false;
  288. record.state = UIViewState.Cached;
  289. if ((record.config.cache || UICachePolicy.None) === UICachePolicy.Delayed) {
  290. this.scheduleDelayedDestroy(record);
  291. }
  292. }
  293. private async performClose(record: UIViewRecord, reason: UICloseReason): Promise<boolean> {
  294. if (!record.view?.node?.isValid) {
  295. this.cancelDelayedDestroy(record);
  296. record.state = UIViewState.Disposed;
  297. record.view = null;
  298. this.records.delete(record.config.id);
  299. return false;
  300. }
  301. const allow = reason === UICloseReason.ForceDispose
  302. ? true
  303. : await record.view.internalBeforeClose(reason);
  304. if (!allow) return false;
  305. record.state = UIViewState.Closing;
  306. await record.view.internalClose(reason);
  307. const uiCache = record.config.cache || UICachePolicy.None;
  308. if (reason === UICloseReason.ForceDispose || uiCache === UICachePolicy.None) {
  309. this.disposeRecord(record);
  310. return true;
  311. }
  312. record.view.node.active = false;
  313. record.state = UIViewState.Cached;
  314. if (uiCache === UICachePolicy.Delayed) {
  315. this.scheduleDelayedDestroy(record);
  316. }
  317. return true;
  318. }
  319. private scheduleDelayedDestroy(record: UIViewRecord): void {
  320. this.cancelDelayedDestroy(record);
  321. const generation = record.generation;
  322. record.delayedDestroyTimer = setTimeout(() => {
  323. record.delayedDestroyTimer = null;
  324. if (
  325. record.generation === generation
  326. && record.state === UIViewState.Cached
  327. ) {
  328. this.disposeRecord(record);
  329. }
  330. }, UIManager.DELAYED_DESTROY_MS);
  331. }
  332. private cancelDelayedDestroy(record: UIViewRecord): void {
  333. if (record.delayedDestroyTimer === null) return;
  334. clearTimeout(record.delayedDestroyTimer);
  335. record.delayedDestroyTimer = null;
  336. }
  337. private disposeRecord(record: UIViewRecord): void {
  338. this.cancelDelayedDestroy(record);
  339. if (record.view?.node?.isValid) {
  340. record.view.internalDispose();
  341. record.view.node.destroy();
  342. }
  343. record.view = null;
  344. record.ownerRoot = null;
  345. record.state = UIViewState.Disposed;
  346. this.records.delete(record.config.id);
  347. }
  348. /** 从管理器中同步移除记录,不主动销毁正由场景释放的节点。 */
  349. private forgetRecord(record: UIViewRecord): void {
  350. ++record.generation;
  351. this.cancelDelayedDestroy(record);
  352. if (record.view?.node?.isValid) {
  353. record.view.internalDispose();
  354. }
  355. record.view = null;
  356. record.ownerRoot = null;
  357. record.opening = null;
  358. record.closing = null;
  359. record.state = UIViewState.Disposed;
  360. if (this.records.get(record.config.id) === record) {
  361. this.records.delete(record.config.id);
  362. }
  363. }
  364. private async closeMutexViews(config: UIViewConfig): Promise<void> {
  365. const tasks: Promise<boolean>[] = [];
  366. for (const record of this.records.values()) {
  367. if (!record.config.mutexGroup) continue;
  368. if (record.config.id !== config.id && record.config.mutexGroup === config.mutexGroup) {
  369. tasks.push(this.close(record.config.id, UICloseReason.Navigation));
  370. }
  371. }
  372. await Promise.all(tasks);
  373. }
  374. async loading(active: boolean, delay = 0): Promise<void> {
  375. if (active) {
  376. ++this.loadingCount;
  377. try {
  378. await this.open(UIViewID.LoadingView, { delay });
  379. if (this.loadingCount === 0) {
  380. await this.close(UIViewID.LoadingView);
  381. }
  382. } catch (error) {
  383. this.loadingCount = Math.max(0, this.loadingCount - 1);
  384. throw error;
  385. }
  386. return;
  387. }
  388. if (this.loadingCount > 0) --this.loadingCount;
  389. if (this.loadingCount > 0) return;
  390. await this.close(UIViewID.LoadingView);
  391. // close 等待期间可能又有新的加载任务,需重新显示 LoadingView。
  392. if (this.loadingCount > 0) {
  393. await this.open(UIViewID.LoadingView);
  394. }
  395. }
  396. toast(msg: string) {
  397. }
  398. dialog() {
  399. }
  400. }