UIManager.ts 16 KB

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