@mysten/dapp-kit-core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +201 -0
  3. package/README.md +3 -0
  4. package/dist/index.d.mts +9 -0
  5. package/dist/index.d.mts.map +1 -0
  6. package/dist/index.mjs +793 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/dist/types-x68aipir.d.mts +240 -0
  9. package/dist/types-x68aipir.d.mts.map +1 -0
  10. package/dist/web/index.d.mts +270 -0
  11. package/dist/web/index.d.mts.map +1 -0
  12. package/dist/web/index.mjs +1446 -0
  13. package/dist/web/index.mjs.map +1 -0
  14. package/package.json +83 -0
  15. package/src/core/actions/connect-wallet.ts +117 -0
  16. package/src/core/actions/disconnect-wallet.ts +43 -0
  17. package/src/core/actions/sign-and-execute-transaction.ts +119 -0
  18. package/src/core/actions/sign-personal-message.ts +42 -0
  19. package/src/core/actions/sign-transaction.ts +83 -0
  20. package/src/core/actions/switch-account.ts +32 -0
  21. package/src/core/actions/switch-network.ts +16 -0
  22. package/src/core/index.ts +119 -0
  23. package/src/core/initializers/autoconnect-wallet.ts +116 -0
  24. package/src/core/initializers/manage-connection.ts +50 -0
  25. package/src/core/initializers/registered-wallets.ts +68 -0
  26. package/src/core/initializers/sync-state-to-storage.ts +44 -0
  27. package/src/core/store.ts +130 -0
  28. package/src/core/types.ts +87 -0
  29. package/src/index.ts +19 -0
  30. package/src/types.ts +15 -0
  31. package/src/utils/errors.ts +29 -0
  32. package/src/utils/lit.ts +61 -0
  33. package/src/utils/name.ts +26 -0
  34. package/src/utils/networks.ts +35 -0
  35. package/src/utils/signer.ts +75 -0
  36. package/src/utils/storage.ts +40 -0
  37. package/src/utils/transaction-result.ts +50 -0
  38. package/src/utils/wallets.ts +82 -0
  39. package/src/wallets/index.ts +56 -0
  40. package/src/wallets/slush-web.ts +27 -0
  41. package/src/wallets/unsafe-burner.ts +165 -0
  42. package/src/web/dapp-kit-connect-button.stories.ts +88 -0
  43. package/src/web/dapp-kit-connect-button.ts +114 -0
  44. package/src/web/dapp-kit-connect-modal.stories.ts +62 -0
  45. package/src/web/dapp-kit-connect-modal.styles.ts +48 -0
  46. package/src/web/dapp-kit-connect-modal.ts +244 -0
  47. package/src/web/index.ts +12 -0
  48. package/src/web/internal/base-modal.ts +149 -0
  49. package/src/web/internal/button.styles.ts +54 -0
  50. package/src/web/internal/button.ts +49 -0
  51. package/src/web/internal/connected-account-menu-item.ts +116 -0
  52. package/src/web/internal/connected-account-menu.styles.ts +217 -0
  53. package/src/web/internal/connected-account-menu.ts +193 -0
  54. package/src/web/internal/connection-status.styles.ts +47 -0
  55. package/src/web/internal/connection-status.ts +31 -0
  56. package/src/web/internal/icons/arrow-right-up-icon.ts +19 -0
  57. package/src/web/internal/icons/back-icon.ts +19 -0
  58. package/src/web/internal/icons/chevron-down-icon.ts +18 -0
  59. package/src/web/internal/icons/circle-check-icon.ts +19 -0
  60. package/src/web/internal/icons/close-icon.ts +18 -0
  61. package/src/web/internal/icons/copy-icon.ts +18 -0
  62. package/src/web/internal/icons/download-icon.ts +24 -0
  63. package/src/web/internal/icons/plus-icon.ts +18 -0
  64. package/src/web/internal/icons/unlink-icon.ts +18 -0
  65. package/src/web/internal/wallet-list-item.styles.ts +41 -0
  66. package/src/web/internal/wallet-list-item.ts +45 -0
  67. package/src/web/internal/wallet-list.styles.ts +49 -0
  68. package/src/web/internal/wallet-list.ts +46 -0
  69. package/src/web/styles/icon-button.ts +28 -0
  70. package/src/web/styles/index.ts +7 -0
  71. package/src/web/styles/reset.ts +45 -0
  72. package/src/web/styles/theme.ts +56 -0
@@ -0,0 +1,244 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { ScopedRegistryHost } from '@lit-labs/scoped-registry-mixin';
5
+ import { html, nothing } from 'lit';
6
+ import { customElement, property, state } from 'lit/decorators.js';
7
+ import { storeProperty } from '../utils/lit.js';
8
+ import { WalletList } from './internal/wallet-list.js';
9
+ import { BaseModal } from './internal/base-modal.js';
10
+ import type { UiWallet } from '@wallet-standard/ui';
11
+ import { closeIcon } from './internal/icons/close-icon.js';
12
+ import { backIcon } from './internal/icons/back-icon.js';
13
+ import type { WalletSelectedEvent } from './internal/wallet-list-item.js';
14
+ import { ConnectionStatus } from './internal/connection-status.js';
15
+ import {
16
+ isWalletStandardError,
17
+ WALLET_STANDARD_ERROR__USER__REQUEST_REJECTED,
18
+ } from '@mysten/wallet-standard';
19
+ import { styles } from './dapp-kit-connect-modal.styles.js';
20
+ import { Button } from './internal/button.js';
21
+ import { iconButtonStyles } from './styles/icon-button.js';
22
+ import type { DefaultExpectedDppKit } from '../types.js';
23
+
24
+ type ModalViewState =
25
+ | { view: 'wallet-selection' }
26
+ | { view: 'connecting'; wallet: UiWallet }
27
+ | { view: 'error'; wallet: UiWallet; error: unknown };
28
+
29
+ export type DAppKitConnectModalOptions = {
30
+ filterFn?: (value: UiWallet, index: number, array: UiWallet[]) => boolean;
31
+ sortFn?: (a: UiWallet, b: UiWallet) => number;
32
+ };
33
+
34
+ /**
35
+ * A modal component for connecting to a Sui wallet, meant to be opened via a trigger button.
36
+ *
37
+ * Opens a modal to let the user select and connect to a wallet.
38
+ *
39
+ * @element mysten-dapp-kit-connect-modal
40
+ *
41
+ * @fires open - Fired *before* the dialog opens (cancelable).
42
+ * @fires opened - Fired *after* the dialog has fully opened.
43
+ * @fires close - Fired *before* the dialog closes (cancelable).
44
+ * @fires closed - Fired *after* the dialog has fully closed.
45
+ * @fires cancel - Fired when clicking the backdrop or pressing Escape (cancelable).
46
+ *
47
+ * @prop {Boolean} open - Programmatic access to the open state of the dialog.
48
+ * @prop {DAppKitConnectModalOptions['filterFn']} filterFn - Function to filter the list of shown wallets (optional).
49
+ * @prop {DAppKitConnectModalOptions['sortFn']} sortFn - Function to sort the list of available wallets (optional).
50
+ * @prop {RegisteredDAppKit} instance - The dApp Kit instance used for state management.
51
+ *
52
+ * @cssprop --background - Background color of the component. Used as the default background for UI elements.
53
+ * @cssprop --foreground - Foreground color of the component. Used as the default text color.
54
+ * @cssprop --primary - Primary color used for interactive elements such as buttons and links.
55
+ * @cssprop --primary-foreground - Text or icon color placed on top of primary elements.
56
+ * @cssprop --secondary - Secondary color used for less prominent interactive elements.
57
+ * @cssprop --secondary-foreground - Text or icon color placed on top of secondary elements.
58
+ * @cssprop --border - Border color for UI elements.
59
+ * @cssprop --accent - Accent color used for highlights and decorative elements.
60
+ * @cssprop --accent-foreground - Text or icon color placed on top of accent elements.
61
+ * @cssprop --muted - Background color for subtle or muted UI elements (e.g., placeholders, disabled states).
62
+ * @cssprop --muted-foreground - Text or icon color for muted UI elements.
63
+ * @cssprop --popover - Background color for floating elements such as popovers, dropdowns, or tooltips.
64
+ * @cssprop --popover-foreground - Text or icon color inside popover elements.
65
+ * @cssprop --ring - Color used for focus rings (visible focus indicators on interactive elements).
66
+ * @cssprop --radius - Border radius used for UI elements.
67
+ * @cssprop --font-sans - Font family used for text content.
68
+ * @cssprop --font-weight-medium - Medium font weight for text (typically used for buttons and interactive elements).
69
+ * @cssprop --font-weight-semibold - Semibold font weight for text (typically used for headings or emphasized text).
70
+ */
71
+ @customElement('mysten-dapp-kit-connect-modal')
72
+ export class DAppKitConnectModal
73
+ extends ScopedRegistryHost(BaseModal)
74
+ implements DAppKitConnectModalOptions
75
+ {
76
+ static override styles = [styles, iconButtonStyles];
77
+
78
+ static elementDefinitions = {
79
+ 'wallet-list': WalletList,
80
+ 'internal-button': Button,
81
+ 'connection-status': ConnectionStatus,
82
+ };
83
+
84
+ /**
85
+ * The dApp Kit instance used for state management.
86
+ */
87
+ @storeProperty()
88
+ instance!: DefaultExpectedDppKit;
89
+
90
+ @state()
91
+ private _state: ModalViewState = { view: 'wallet-selection' };
92
+
93
+ /**
94
+ * Function to filter the list of shown wallets.
95
+ */
96
+ @property({ attribute: false })
97
+ filterFn: DAppKitConnectModalOptions['filterFn'];
98
+
99
+ /**
100
+ * Function to sort the list of shown wallets.
101
+ */
102
+ @property({ attribute: false })
103
+ sortFn: DAppKitConnectModalOptions['sortFn'];
104
+
105
+ #abortController?: AbortController;
106
+
107
+ override render() {
108
+ const showBackButton = this._state.view === 'connecting' || this._state.view === 'error';
109
+ const wallets = this.#getWallets();
110
+
111
+ return html`<dialog @click=${this.handleDialogClick} @close=${this.#resetSelection}>
112
+ <div class="content" @click=${this.handleContentClick}>
113
+ <div class="connect-header">
114
+ ${showBackButton
115
+ ? html`<button
116
+ class="icon-button back-button"
117
+ aria-label="Go back"
118
+ @click=${this.#resetSelection}
119
+ >
120
+ ${backIcon}
121
+ </button>`
122
+ : nothing}
123
+ <h2 class="title">${wallets.length > 0 ? 'Connect a wallet' : 'No wallets installed'}</h2>
124
+ <button
125
+ class="icon-button close-button"
126
+ aria-label="Close"
127
+ @click=${() => {
128
+ // oxlint-disable @typescript-eslint/no-floating-promises
129
+ this.close('cancel');
130
+ }}
131
+ >
132
+ ${closeIcon}
133
+ </button>
134
+ </div>
135
+ ${this.#renderModalView(wallets)}
136
+ </div>
137
+ </dialog>`;
138
+ }
139
+
140
+ #renderModalView(wallets: UiWallet[]) {
141
+ switch (this._state.view) {
142
+ case 'wallet-selection':
143
+ return html`<wallet-list
144
+ .wallets=${wallets}
145
+ @wallet-selected=${async (event: WalletSelectedEvent) => {
146
+ this.#attemptConnect(event.detail.wallet);
147
+ }}
148
+ ></wallet-list>`;
149
+ case 'connecting':
150
+ return html`<connection-status
151
+ .title=${'Awaiting connection...'}
152
+ .copy=${`Accept the request from ${this._state.wallet.name} in order to proceed`}
153
+ .wallet=${this._state.wallet}
154
+ >
155
+ <internal-button
156
+ slot="call-to-action"
157
+ .variant=${'secondary'}
158
+ @click=${this.#resetSelection}
159
+ >
160
+ Cancel
161
+ </internal-button>
162
+ </connection-status>`;
163
+ case 'error':
164
+ const { wallet, error } = this._state;
165
+ const wasRequestCancelled = isWalletStandardError(
166
+ error,
167
+ WALLET_STANDARD_ERROR__USER__REQUEST_REJECTED,
168
+ );
169
+
170
+ return html`<connection-status
171
+ .title=${wasRequestCancelled ? 'Request canceled' : 'Connection failed'}
172
+ .copy=${wasRequestCancelled
173
+ ? `You canceled the request`
174
+ : 'Something went wrong. Please try again'}
175
+ .wallet=${wallet}
176
+ >
177
+ <internal-button
178
+ slot="call-to-action"
179
+ @click=${() => {
180
+ this.#attemptConnect(wallet);
181
+ }}
182
+ >
183
+ Retry
184
+ </internal-button>
185
+ </connection-status>`;
186
+ default:
187
+ throw new Error(`Encountered unknown view state: ${this._state}`);
188
+ }
189
+ }
190
+
191
+ async #attemptConnect(wallet: UiWallet) {
192
+ let delayTimeout: ReturnType<typeof setTimeout> | undefined;
193
+
194
+ try {
195
+ const abortPromise = new Promise((_, reject) => {
196
+ this.#abortController = new AbortController();
197
+ this.#abortController.signal.addEventListener(
198
+ 'abort',
199
+ () => reject(new DOMException('Aborted', 'AbortError')),
200
+ { once: true },
201
+ );
202
+ });
203
+
204
+ // Connection attempts can sometimes be instantaneous when accounts are
205
+ // already authorized or the wallet isn't setup yet, so we'll introduce
206
+ // a tiny delay to prevent the UI flickering on the loading state.
207
+ delayTimeout = setTimeout(() => {
208
+ this._state = { view: 'connecting', wallet };
209
+ }, 100);
210
+
211
+ await Promise.race([abortPromise, this.instance.connectWallet({ wallet })]);
212
+ this.close('successful-connection');
213
+ } catch (error) {
214
+ if (error instanceof Error && error.name === 'AbortError') {
215
+ this._state = { view: 'wallet-selection' };
216
+ } else {
217
+ this._state = { view: 'error', wallet, error };
218
+ }
219
+ } finally {
220
+ clearTimeout(delayTimeout);
221
+ }
222
+ }
223
+
224
+ #resetSelection() {
225
+ if (this._state.view === 'connecting') {
226
+ this.#abortController?.abort('cancelled');
227
+ } else {
228
+ this._state = { view: 'wallet-selection' };
229
+ }
230
+ }
231
+
232
+ #getWallets() {
233
+ const wallets = this.instance.stores.$wallets.get();
234
+ const filtered = this.filterFn ? wallets.filter(this.filterFn) : wallets;
235
+ const sorted = this.sortFn ? filtered.toSorted(this.sortFn) : filtered;
236
+ return sorted;
237
+ }
238
+ }
239
+
240
+ declare global {
241
+ interface HTMLElementTagNameMap {
242
+ 'mysten-dapp-kit-connect-modal': DAppKitConnectModal;
243
+ }
244
+ }
@@ -0,0 +1,12 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import '@webcomponents/scoped-custom-element-registry';
5
+
6
+ import './dapp-kit-connect-button.js';
7
+ import './dapp-kit-connect-modal.js';
8
+
9
+ export { DAppKitConnectButton } from './dapp-kit-connect-button.js';
10
+ export { DAppKitConnectModal } from './dapp-kit-connect-modal.js';
11
+
12
+ export type { DAppKitConnectModalOptions } from './dapp-kit-connect-modal.js';
@@ -0,0 +1,149 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { LitElement } from 'lit';
5
+ import { property, query } from 'lit/decorators.js';
6
+ import { promiseWithResolvers } from '@mysten/utils';
7
+
8
+ export class BaseModal extends LitElement {
9
+ #isOpen = false;
10
+ #isOpening = false;
11
+ #isConnected = promiseWithResolvers<void>();
12
+
13
+ #returnValue: string | undefined;
14
+ #nextClickIsFromContent = false;
15
+
16
+ static override shadowRootOptions = {
17
+ ...LitElement.shadowRootOptions,
18
+ delegatesFocus: true,
19
+ };
20
+
21
+ /**
22
+ * Opens the dialog when set to `true` and closes it when set to `false`.
23
+ */
24
+ @property({ type: Boolean })
25
+ get open() {
26
+ return this.#isOpen;
27
+ }
28
+
29
+ set open(open: boolean) {
30
+ if (open === this.#isOpen) {
31
+ return;
32
+ }
33
+
34
+ this.#isOpen = open;
35
+ if (this.#isOpen) {
36
+ this.setAttribute('open', '');
37
+ this.show();
38
+ } else {
39
+ this.removeAttribute('open');
40
+ this.close();
41
+ }
42
+ }
43
+
44
+ @query('dialog')
45
+ private readonly _dialog!: HTMLDialogElement;
46
+
47
+ /**
48
+ * Opens the dialog and fires a cancelable `open` event. An `opened` event
49
+ * is fired after the dialog opens.
50
+ *
51
+ * @returns A `Promise` that resolves after the `opened` event was fired.
52
+ */
53
+ async show() {
54
+ this.#isOpening = true;
55
+
56
+ // Dialogs can be opened before being attached to the DOM, so we need to
57
+ // wait until we're connected before calling `showModal()`.
58
+ await this.#isConnected.promise;
59
+ await this.updateComplete;
60
+
61
+ // Check if already opened or if `dialog.close()` was called while awaiting.
62
+ if (this._dialog.open || !this.#isOpening) {
63
+ this.#isOpening = false;
64
+ return;
65
+ }
66
+
67
+ const wasDispatched = this.dispatchEvent(new Event('open', { cancelable: true }));
68
+ if (!wasDispatched) {
69
+ this.open = false;
70
+ this.#isOpening = false;
71
+ return;
72
+ }
73
+
74
+ this._dialog.showModal();
75
+ this.open = true;
76
+
77
+ this.dispatchEvent(new Event('opened'));
78
+ this.#isOpening = false;
79
+ }
80
+
81
+ /**
82
+ * Closes the dialog and fires a cancelable `close` event. After a dialog's
83
+ * animation, a `closed` event is fired.
84
+ *
85
+ * @param returnValue A return value usually indicating which button was used
86
+ * to close a dialog. If a dialog is canceled by clicking the backdrop or
87
+ * pressing Escape, it will not change the return value after closing.
88
+ * @returns A Promise that resolves after the `closed` event was fired.
89
+ */
90
+ async close(returnValue = this.#returnValue) {
91
+ this.#isOpening = false;
92
+
93
+ if (!this.isConnected) {
94
+ // Disconnected dialogs do not fire close events or animate.
95
+ this.open = false;
96
+ return;
97
+ }
98
+
99
+ await this.updateComplete;
100
+
101
+ // Check if already closed or if `dialog.show()` was called while awaiting.
102
+ if (!this._dialog.open || this.#isOpening) {
103
+ this.open = false;
104
+ return;
105
+ }
106
+
107
+ const prevReturnValue = this.#returnValue;
108
+ this.#returnValue = returnValue;
109
+
110
+ const wasDispatched = this.dispatchEvent(new Event('close', { cancelable: true }));
111
+ if (!wasDispatched) {
112
+ this.#returnValue = prevReturnValue;
113
+ return;
114
+ }
115
+
116
+ this._dialog.close(this.#returnValue);
117
+ this.open = false;
118
+ this.dispatchEvent(new Event('closed'));
119
+ }
120
+
121
+ override connectedCallback() {
122
+ super.connectedCallback();
123
+ this.#isConnected.resolve();
124
+ }
125
+
126
+ override disconnectedCallback() {
127
+ super.disconnectedCallback();
128
+ this.#isConnected = Promise.withResolvers<void>();
129
+ }
130
+
131
+ protected handleContentClick() {
132
+ this.#nextClickIsFromContent = true;
133
+ }
134
+
135
+ protected handleDialogClick() {
136
+ if (this.#nextClickIsFromContent) {
137
+ // This trick uses event bubbling to determine whether or not the click originated
138
+ // from the dialog content or dialog backdrop psuedo-element. If you click the dialog
139
+ // content, then `nextClickIsFromContent` will be set to true and we'll early exit.
140
+ this.#nextClickIsFromContent = false;
141
+ return;
142
+ }
143
+
144
+ const wasDispatched = this.dispatchEvent(new Event('cancel', { cancelable: true }));
145
+ if (!wasDispatched) return;
146
+
147
+ this.close();
148
+ }
149
+ }
@@ -0,0 +1,54 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { css } from 'lit';
5
+ import { sharedStyles } from '../styles/index.js';
6
+
7
+ export const styles = [
8
+ sharedStyles,
9
+ css`
10
+ .button {
11
+ transition-property: background-color;
12
+ transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
13
+ transition-duration: 0.15s;
14
+ border-radius: var(--dapp-kit-radius-md);
15
+ font-weight: var(--dapp-kit-font-weight-semibold);
16
+ text-decoration: none;
17
+ outline-style: none;
18
+ display: inline-flex;
19
+ justify-content: center;
20
+ align-items: center;
21
+ gap: 12px;
22
+ padding-left: 16px;
23
+ padding-right: 16px;
24
+ padding-top: 8px;
25
+ padding-bottom: 8px;
26
+ height: 40px;
27
+ }
28
+
29
+ .button:focus-visible {
30
+ border-color: var(--dapp-kit-ring);
31
+ box-shadow:
32
+ 0 0 0 3px color-mix(in oklab, var(--dapp-kit-ring) 50%, transparent),
33
+ rgba(0, 0, 0, 0.05) 0px 1px 2px 0px;
34
+ }
35
+
36
+ .button.primary {
37
+ background-color: var(--dapp-kit-primary);
38
+ color: var(--dapp-kit-primary-foreground);
39
+ }
40
+
41
+ .button.primary:hover:not(:disabled) {
42
+ background-color: color-mix(in oklab, var(--dapp-kit-primary) 90%, transparent);
43
+ }
44
+
45
+ .button.secondary {
46
+ background-color: var(--dapp-kit-secondary);
47
+ color: var(--dapp-kit-secondary-foreground);
48
+ }
49
+
50
+ .button.secondary:hover:not(:disabled) {
51
+ background-color: color-mix(in oklab, var(--dapp-kit-secondary) 80%, transparent);
52
+ }
53
+ `,
54
+ ];
@@ -0,0 +1,49 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { html, LitElement } from 'lit';
5
+ import { property } from 'lit/decorators.js';
6
+ import { classMap } from 'lit/directives/class-map.js';
7
+ import { styles } from './button.styles.js';
8
+
9
+ export class Button extends LitElement {
10
+ static override shadowRootOptions = {
11
+ ...LitElement.shadowRootOptions,
12
+ delegatesFocus: true,
13
+ };
14
+
15
+ static override styles = styles;
16
+
17
+ @property({ type: String })
18
+ variant: 'primary' | 'secondary' = 'primary';
19
+
20
+ @property({ type: String })
21
+ href = '';
22
+
23
+ @property({ type: Boolean, reflect: true })
24
+ disabled = false;
25
+
26
+ override render() {
27
+ return this.href
28
+ ? html`
29
+ <a
30
+ href=${this.href}
31
+ ?disabled=${this.disabled}
32
+ target="_blank"
33
+ rel="noreferrer"
34
+ class=${classMap({ button: true, [this.variant]: true })}
35
+ >
36
+ <slot part="button-content"></slot>
37
+ </a>
38
+ `
39
+ : html`
40
+ <button
41
+ type="button"
42
+ ?disabled=${this.disabled}
43
+ class=${classMap({ button: true, [this.variant]: true })}
44
+ >
45
+ <slot part="button-content"></slot>
46
+ </button>
47
+ `;
48
+ }
49
+ }
@@ -0,0 +1,116 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { when } from 'lit/directives/when.js';
5
+ import { html, LitElement } from 'lit';
6
+ import { formatAddress } from '@mysten/sui/utils';
7
+ import { property, state } from 'lit/decorators.js';
8
+ import type { UiWalletAccount } from '@wallet-standard/ui';
9
+ import { copyIcon } from './icons/copy-icon.js';
10
+ import { Task } from '@lit/task';
11
+ import type { DAppKitCompatibleClient } from '../../core/types.js';
12
+ import { resolveNameServiceName } from '../../utils/name.js';
13
+ import { circleCheckIcon } from './icons/circle-check-icon.js';
14
+
15
+ export type AccountSelectedEvent = CustomEvent<{ account: UiWalletAccount }>;
16
+
17
+ export class AccountMenuItem extends LitElement {
18
+ override createRenderRoot() {
19
+ return this;
20
+ }
21
+
22
+ @property({ type: Object })
23
+ account!: UiWalletAccount;
24
+
25
+ @property({ type: Object })
26
+ client!: DAppKitCompatibleClient;
27
+
28
+ @property({ type: Boolean })
29
+ selected = false;
30
+
31
+ @state()
32
+ private _wasCopySuccessful = false;
33
+
34
+ #resolveNameTask = new Task(this, {
35
+ args: () => [this.client, this.account.address],
36
+ task: async ([client, address]) => resolveNameServiceName(client, address),
37
+ });
38
+
39
+ override connectedCallback() {
40
+ super.connectedCallback();
41
+ this.addEventListener('click', this.#accountSelected);
42
+ }
43
+
44
+ override disconnectedCallback() {
45
+ super.disconnectedCallback();
46
+ this.removeEventListener('click', this.#accountSelected);
47
+ }
48
+
49
+ override render() {
50
+ return html`
51
+ <div class="container" data-checked=${this.selected}>
52
+ <input
53
+ type="radio"
54
+ name="wallet-address"
55
+ tabindex="${this.selected ? '0' : '-1'}"
56
+ value=${this.account.address}
57
+ ?checked=${this.selected}
58
+ @change=${this.#accountSelected}
59
+ class="radio-input"
60
+ id=${this.account.address}
61
+ />
62
+ <label class="content" for=${this.account.address}>
63
+ ${when(this.account.icon, (icon) => html`<img src=${icon} alt="" />`)}
64
+ ${this.#resolveNameTask.render({
65
+ pending: this.#renderAccountInfo,
66
+ complete: this.#renderAccountInfo,
67
+ error: () => this.#renderAccountInfo(),
68
+ })}
69
+ </label>
70
+ <button
71
+ class="copy-address-button"
72
+ @click=${this.#copyAddressToClipboard}
73
+ aria-label="Copy address"
74
+ >
75
+ ${this._wasCopySuccessful ? circleCheckIcon : copyIcon}
76
+ </button>
77
+ </div>
78
+ `;
79
+ }
80
+
81
+ async #copyAddressToClipboard(event: Event) {
82
+ event.stopPropagation();
83
+
84
+ try {
85
+ await navigator.clipboard.writeText(this.account.address);
86
+ this._wasCopySuccessful = true;
87
+
88
+ setTimeout(() => {
89
+ this._wasCopySuccessful = false;
90
+ }, 2000);
91
+ } catch {
92
+ // Do nothing here
93
+ }
94
+ }
95
+
96
+ #renderAccountInfo = (name?: string | null) => {
97
+ const { address, label } = this.account;
98
+ const formattedAddress = formatAddress(address);
99
+ const title = name || label;
100
+
101
+ return html`<div class="account-info">
102
+ <div class="account-title">${title || formattedAddress}</div>
103
+ ${when(title, () => html`<div class="account-subtitle">${formattedAddress}</div>`)}
104
+ </div>`;
105
+ };
106
+
107
+ #accountSelected() {
108
+ this.dispatchEvent(
109
+ new CustomEvent<AccountSelectedEvent['detail']>('account-selected', {
110
+ detail: { account: this.account },
111
+ bubbles: true,
112
+ composed: true,
113
+ }),
114
+ );
115
+ }
116
+ }