-
-
Notifications
You must be signed in to change notification settings - Fork 274
feat(UiStateController): init controller #7808
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Kriys94
wants to merge
5
commits into
main
Choose a base branch
from
feature/ApplicationState
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+825
−2
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| # Changelog | ||
|
|
||
| All notable changes to this project will be documented in this file. | ||
|
|
||
| The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), | ||
| and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). | ||
|
|
||
| ## [Unreleased] | ||
|
|
||
| ### Added | ||
|
|
||
| - Initial release of `@metamask/ui-state-controller` ([#7808](https://github.com/MetaMask/core/pull/7808)) | ||
| - `UiStateController` for managing client (UI) open/closed state (formerly `ClientStateController`) | ||
| - `UiStateController:setClientOpen` messenger action for platform code to call | ||
| - `UiStateController:stateChange` event for controllers to subscribe to lifecycle changes | ||
| - `isUiOpen` state property (not persisted - always starts as `false`) | ||
| - `uiStateControllerSelectors.selectIsUiOpen` selector for derived state access | ||
| - Full TypeScript support with exported types | ||
|
|
||
| [Unreleased]: https://github.com/MetaMask/core/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| MIT License | ||
|
|
||
| Copyright (c) 2026 MetaMask | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| # `@metamask/ui-state-controller` | ||
|
|
||
| Provides a centralized way for controllers to respond to application lifecycle changes. | ||
|
|
||
| ## Installation | ||
|
|
||
| `yarn add @metamask/ui-state-controller` | ||
|
|
||
| or | ||
|
|
||
| `npm install @metamask/ui-state-controller` | ||
|
|
||
| ## Usage | ||
|
|
||
| ### Basic Setup | ||
|
|
||
| ```typescript | ||
| import { Messenger } from '@metamask/messenger'; | ||
| import { | ||
| UiStateController, | ||
| UiStateControllerActions, | ||
| UiStateControllerEvents, | ||
| } from '@metamask/ui-state-controller'; | ||
|
|
||
| const rootMessenger = new Messenger< | ||
| 'Root', | ||
| UiStateControllerActions, | ||
| UiStateControllerEvents | ||
| >({ namespace: 'Root' }); | ||
|
|
||
| const controllerMessenger = new Messenger({ | ||
| namespace: 'UiStateController', | ||
| parent: rootMessenger, | ||
| }); | ||
|
|
||
| const uiStateController = new UiStateController({ | ||
| messenger: controllerMessenger, | ||
| }); | ||
| ``` | ||
|
|
||
| ### Platform Integration | ||
|
|
||
| Platform code calls `UiStateController:setUiOpen` when the UI is opened or closed: | ||
|
|
||
| ```text | ||
| onUiOpened() { | ||
| controllerMessenger.call('UiStateController:setUiOpen', true); | ||
| } | ||
|
|
||
| onUiClosed() { | ||
| controllerMessenger.call('UiStateController:setUiOpen', false); | ||
| } | ||
| ``` | ||
|
|
||
| ### Consumer controller and using with other lifecycle state (e.g. Keyring unlock/lock) | ||
|
|
||
| Use `UiStateController:stateChange` only for behavior that **must** run when the UI is open or closed (e.g., pausing/resuming a critical background task). **Use the selector** when subscribing so the handler receives a single derived value (e.g. `isUiOpen`), and **prefer pause/resume** over stop/start for polling. | ||
|
|
||
| UI open/close alone is usually not enough to decide when to start or stop work. Combine `UiStateController:stateChange` with other lifecycle events, such as **KeyringController:unlock** / **KeyringController:lock** (or any controller that expresses "ready for background work"). Only start subscriptions, polling, or network requests when **both** the UI is open and the keyring (or equivalent) is unlocked; stop or pause when the UI closes **or** the keyring locks. | ||
|
|
||
| #### Important: Usage guidelines and warnings | ||
|
|
||
| **Do not subscribe to updates for all kinds of data as soon as the client opens.** When MetaMask opens, the current screen may not need every type of data. Starting subscriptions, polling, or network requests for everything when `isUiOpen` becomes true can lead to unnecessary network traffic and battery use, requests before onboarding is complete (a recurring source of issues), and poor performance as more features are added. | ||
|
|
||
| **Use this controller responsibly:** | ||
|
|
||
| - Start only the subscriptions, polling, or requests that are **needed for the current screen or flow** | ||
| - Do **not** start network-dependent or heavy behavior solely because `UiStateController:stateChange` reported `isUiOpen: true` | ||
| - Consider **deferring** non-critical updates until the user has completed onboarding or reached a screen that needs that data | ||
| - Prefer starting and stopping per feature or per screen (e.g., when a component mounts that needs the data) rather than globally when the client opens | ||
| - **Combine with Keyring unlock/lock:** Only start work when it is appropriate for both UI open state and wallet state (e.g. client open **and** keyring unlocked) | ||
| - **Prefer pause/resume over stop/start for polling** so you can resume without full re-initialization. Use the selector when subscribing (see example below). | ||
|
|
||
| ```typescript | ||
| import { uiStateControllerSelectors } from '@metamask/ui-state-controller'; | ||
|
|
||
| class SomeDataController extends BaseController { | ||
| #uiOpen = false; | ||
| #keyringUnlocked = false; | ||
|
|
||
| constructor({ messenger }) { | ||
| super({ messenger, ... }); | ||
|
|
||
| messenger.subscribe( | ||
| 'UiStateController:stateChange', | ||
| (isUiOpen) => { | ||
| this.#uiOpen = isUiOpen; | ||
| this.updateActive(); | ||
| }, | ||
| uiStateControllerSelectors.selectIsUiOpen, | ||
| ); | ||
|
|
||
| messenger.subscribe('KeyringController:unlock', () => { | ||
| this.#keyringUnlocked = true; | ||
| this.updateActive(); | ||
| }); | ||
|
|
||
| messenger.subscribe('KeyringController:lock', () => { | ||
| this.#keyringUnlocked = false; | ||
| this.updateActive(); | ||
| }); | ||
| } | ||
|
|
||
| updateActive() { | ||
| const shouldRun = this.#uiOpen && this.#keyringUnlocked; | ||
| if (shouldRun) { | ||
| this.resume(); | ||
| } else { | ||
| this.pause(); | ||
| } | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| Note: `stateChange` emits `[state, patches]`; the selector receives the full payload and returns the value passed to the handler (here, `isUiOpen`). | ||
|
|
||
| ## API Reference | ||
|
|
||
| ### State | ||
|
|
||
| | Property | Type | Description | | ||
| | ---------- | --------- | ------------------------------------------ | | ||
| | `isUiOpen` | `boolean` | Whether the client (UI) is currently open. | | ||
|
|
||
| Note: State is not persisted. It always starts as `false`. | ||
|
|
||
| ### Actions | ||
|
|
||
| | Action | Parameters | Description | | ||
| | ----------------------------- | --------------- | ---------------------------- | | ||
| | `UiStateController:getState` | none | Returns current state. | | ||
| | `UiStateController:setUiOpen` | `open: boolean` | Sets whether the UI is open. | | ||
|
|
||
| ### Events | ||
|
|
||
| | Event | Payload | Description | | ||
| | ------------------------------- | ------------------ | ---------------------------- | | ||
| | `UiStateController:stateChange` | `[state, patches]` | Standard state change event. | | ||
|
|
||
| ### Selectors | ||
|
|
||
| ```typescript | ||
| import { uiStateControllerSelectors } from '@metamask/ui-state-controller'; | ||
|
|
||
| const state = messenger.call('UiStateController:getState'); | ||
| const isOpen = uiStateControllerSelectors.selectIsUiOpen(state); | ||
| ``` | ||
|
|
||
| ## Contributing | ||
|
|
||
| This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| /* | ||
| * For a detailed explanation regarding each configuration property and type check, visit: | ||
| * https://jestjs.io/docs/configuration | ||
| */ | ||
|
|
||
| const merge = require('deepmerge'); | ||
| const path = require('path'); | ||
|
|
||
| const baseConfig = require('../../jest.config.packages'); | ||
|
|
||
| const displayName = path.basename(__dirname); | ||
|
|
||
| module.exports = merge(baseConfig, { | ||
| displayName, | ||
| coveragePathIgnorePatterns: [], | ||
| coverageThreshold: { | ||
| global: { | ||
| branches: 100, | ||
| functions: 100, | ||
| lines: 100, | ||
| statements: 100, | ||
| }, | ||
| }, | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| { | ||
| "name": "@metamask/ui-state-controller", | ||
| "version": "0.0.0", | ||
| "description": "Tracks and manages the lifecycle state of MetaMask as an application", | ||
| "keywords": [ | ||
| "MetaMask", | ||
| "Ethereum" | ||
| ], | ||
| "homepage": "https://github.com/MetaMask/core/tree/main/packages/ui-state-controller#readme", | ||
| "bugs": { | ||
| "url": "https://github.com/MetaMask/core/issues" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "https://github.com/MetaMask/core.git" | ||
| }, | ||
| "license": "MIT", | ||
| "sideEffects": false, | ||
| "exports": { | ||
| ".": { | ||
| "import": { | ||
| "types": "./dist/index.d.mts", | ||
| "default": "./dist/index.mjs" | ||
| }, | ||
| "require": { | ||
| "types": "./dist/index.d.cts", | ||
| "default": "./dist/index.cjs" | ||
| } | ||
| }, | ||
| "./package.json": "./package.json" | ||
| }, | ||
| "main": "./dist/index.cjs", | ||
| "types": "./dist/index.d.cts", | ||
| "files": [ | ||
| "dist/" | ||
| ], | ||
| "scripts": { | ||
| "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references", | ||
| "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean", | ||
| "build:docs": "typedoc", | ||
| "changelog:update": "../../scripts/update-changelog.sh @metamask/ui-state-controller", | ||
| "changelog:validate": "../../scripts/validate-changelog.sh @metamask/ui-state-controller", | ||
| "publish:preview": "yarn npm publish --tag preview", | ||
| "since-latest-release": "../../scripts/since-latest-release.sh", | ||
| "test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter", | ||
| "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache", | ||
| "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose", | ||
| "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch" | ||
| }, | ||
| "dependencies": { | ||
| "@metamask/base-controller": "^9.0.0", | ||
| "@metamask/messenger": "^0.3.0" | ||
| }, | ||
| "devDependencies": { | ||
| "@metamask/auto-changelog": "^3.4.4", | ||
| "@ts-bridge/cli": "^0.6.4", | ||
| "@types/jest": "^27.5.2", | ||
| "deepmerge": "^4.2.2", | ||
| "jest": "^27.5.1", | ||
| "ts-jest": "^27.1.5", | ||
| "typedoc": "^0.24.8", | ||
| "typedoc-plugin-missing-exports": "^2.0.0", | ||
| "typescript": "~5.3.3" | ||
| }, | ||
| "engines": { | ||
| "node": "^18.18 || >=20" | ||
| }, | ||
| "publishConfig": { | ||
| "access": "public", | ||
| "registry": "https://registry.npmjs.org/" | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What are your thoughts on putting this controller under the ownership of Extension Platform and Mobile Platform? Our team already own a lot of things we shouldn't, and it doesn't fit with the goals of our team, it seems like something that's more feature-oriented. This controller also feels like something these teams need to be in the loop on, as the logic for tracking the state of the UI is dependent on the platform.