From fc13bd19c09bb903c67953651c15feef0c82308e Mon Sep 17 00:00:00 2001 From: Josh Scanlan <75971516+joshuascan@users.noreply.github.com> Date: Mon, 25 Nov 2024 13:58:48 -0800 Subject: [PATCH] adds prettier formatting --- .prettierrc | 5 + package.json | 5 +- src/index.ts | 4 +- .../connectors/dedicatedWalletConnector.ts | 183 +++++++----------- src/lib/connectors/magicConnector.ts | 85 ++++---- .../connectors/universalWalletConnector.ts | 119 ++++++------ src/lib/modal/logos.ts | 24 +-- src/lib/modal/styles.ts | 2 +- src/lib/modal/view.ts | 137 ++++++------- src/lib/utils.ts | 7 +- 10 files changed, 260 insertions(+), 311 deletions(-) create mode 100644 .prettierrc diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..3268470 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,5 @@ +{ + "arrowParens": "avoid", + "printWidth": 120, + "singleQuote": true +} diff --git a/package.json b/package.json index abb11ad..c44b3e4 100644 --- a/package.json +++ b/package.json @@ -26,15 +26,16 @@ "dependencies": { "@changesets/cli": "^2.24.0", "@magic-ext/oauth": "^12.3.0", - "@magic-sdk/provider": "^28.6.0", + "@magic-sdk/provider": "^18.3.0", "@wagmi/connectors": "^4.1.14", "@wagmi/core": "^2.6.5", - "magic-sdk": "^28.6.0", + "magic-sdk": "^18.3.0", "tsc-esm-fix": "^2.20.10" }, "devDependencies": { "@types/node": "^20.11.24", "changeset": "^0.2.6", + "prettier": "^3.3.3", "rome": "12.0.0", "typescript": "^5.0.4", "viem": "2.x" diff --git a/src/index.ts b/src/index.ts index 58a9dfc..ebb0d5c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,2 +1,2 @@ -export * from './lib/connectors/dedicatedWalletConnector' -export * from './lib/connectors/universalWalletConnector' +export * from './lib/connectors/dedicatedWalletConnector'; +export * from './lib/connectors/universalWalletConnector'; diff --git a/src/lib/connectors/dedicatedWalletConnector.ts b/src/lib/connectors/dedicatedWalletConnector.ts index b96718c..5e78b6a 100644 --- a/src/lib/connectors/dedicatedWalletConnector.ts +++ b/src/lib/connectors/dedicatedWalletConnector.ts @@ -1,22 +1,14 @@ -import type { OAuthExtension, OAuthProvider } from '@magic-ext/oauth' -import type { - InstanceWithExtensions, - MagicSDKAdditionalConfiguration, - SDKBase, -} from '@magic-sdk/provider' -import { createConnector, normalizeChainId } from '@wagmi/core' -import { - type MagicConnectorParams, - type MagicOptions, - magicConnector, -} from './magicConnector' -import { UserRejectedRequestError, getAddress } from 'viem' -import { createModal } from '../modal/view' +import type { OAuthExtension, OAuthProvider } from '@magic-ext/oauth'; +import type { InstanceWithExtensions, MagicSDKAdditionalConfiguration, SDKBase } from '@magic-sdk/provider'; +import { createConnector, normalizeChainId } from '@wagmi/core'; +import { type MagicConnectorParams, type MagicOptions, magicConnector } from './magicConnector'; +import { UserRejectedRequestError, getAddress } from 'viem'; +import { createModal } from '../modal/view'; interface UserDetails { - email: string - phoneNumber: string - oauthProvider: OAuthProvider + email: string; + phoneNumber: string; + oauthProvider: OAuthProvider; } /** @@ -39,44 +31,29 @@ interface UserDetails { */ interface DedicatedWalletOptions extends MagicOptions { - enableEmailLogin?: boolean - enableSMSLogin?: boolean + enableEmailLogin?: boolean; + enableSMSLogin?: boolean; oauthOptions?: { - providers: OAuthProvider[] - callbackUrl?: string - } - magicSdkConfiguration?: MagicSDKAdditionalConfiguration< - string, - OAuthExtension[] - > + providers: OAuthProvider[]; + callbackUrl?: string; + }; + magicSdkConfiguration?: MagicSDKAdditionalConfiguration; } export interface DedicatedWalletConnectorParams extends MagicConnectorParams { - options: DedicatedWalletOptions + options: DedicatedWalletOptions; } -export function dedicatedWalletConnector({ - chains, - options, -}: DedicatedWalletConnectorParams) { - let { - id, - name, - type, - isModalOpen, - getAccount, - getMagicSDK, - getProvider, - onAccountsChanged, - } = magicConnector({ +export function dedicatedWalletConnector({ chains, options }: DedicatedWalletConnectorParams) { + let { id, name, type, isModalOpen, getAccount, getMagicSDK, getProvider, onAccountsChanged } = magicConnector({ chains, options: { ...options, connectorType: 'dedicated' }, - }) + }); - const oauthProviders = options.oauthOptions?.providers ?? [] - const oauthCallbackUrl = options.oauthOptions?.callbackUrl - const enableSMSLogin = options.enableSMSLogin ?? false - const enableEmailLogin = options.enableEmailLogin ?? true + const oauthProviders = options.oauthOptions?.providers ?? []; + const oauthCallbackUrl = options.oauthOptions?.callbackUrl; + const enableSMSLogin = options.enableSMSLogin ?? false; + const enableEmailLogin = options.enableEmailLogin ?? true; /** * This method is used to get user details from the modal UI @@ -86,7 +63,7 @@ export function dedicatedWalletConnector({ const getUserDetailsByForm = async ( enableSMSLogin: boolean, enableEmailLogin: boolean, - oauthProviders: OAuthProvider[], + oauthProviders: OAuthProvider[] ): Promise => { const output: UserDetails = (await createModal({ accentColor: options.accentColor, @@ -96,159 +73,149 @@ export function dedicatedWalletConnector({ enableSMSLogin: enableSMSLogin, enableEmailLogin: enableEmailLogin, oauthProviders, - })) as UserDetails + })) as UserDetails; - isModalOpen = false - return output - } + isModalOpen = false; + return output; + }; - return createConnector((config) => ({ + return createConnector(config => ({ id, type, name, getProvider, connect: async function () { if (!options.apiKey) { - throw new Error('Magic API Key is not provided.') + throw new Error('Magic API Key is not provided.'); } - const provider = await getProvider() + const provider = await getProvider(); if (provider?.on) { - provider.on('accountsChanged', this.onAccountsChanged.bind(this)) - provider.on('chainChanged', this.onChainChanged.bind(this)) - provider.on('disconnect', this.onDisconnect.bind(this)) + provider.on('accountsChanged', this.onAccountsChanged.bind(this)); + provider.on('chainChanged', this.onChainChanged.bind(this)); + provider.on('disconnect', this.onDisconnect.bind(this)); } - let chainId: number + let chainId: number; try { - chainId = await this.getChainId() + chainId = await this.getChainId(); } catch { - chainId = 0 + chainId = 0; } if (await this.isAuthorized()) { return { chainId, accounts: [await getAccount()], - } + }; } if (!isModalOpen) { - const modalOutput = await getUserDetailsByForm( - enableSMSLogin, - enableEmailLogin, - oauthProviders, - ) + const modalOutput = await getUserDetailsByForm(enableSMSLogin, enableEmailLogin, oauthProviders); - const magic = getMagicSDK() as InstanceWithExtensions< - SDKBase, - OAuthExtension[] - > + const magic = getMagicSDK() as InstanceWithExtensions; // LOGIN WITH MAGIC USING OAUTH PROVIDER if (modalOutput.oauthProvider) await magic.oauth.loginWithRedirect({ provider: modalOutput.oauthProvider, redirectURI: oauthCallbackUrl ?? window.location.href, - }) + }); // LOGIN WITH MAGIC USING EMAIL if (modalOutput.email) await magic.auth.loginWithEmailOTP({ email: modalOutput.email, - }) + }); // LOGIN WITH MAGIC USING PHONE NUMBER if (modalOutput.phoneNumber) await magic.auth.loginWithSMS({ phoneNumber: modalOutput.phoneNumber, - }) + }); if (await magic.user.isLoggedIn()) return { accounts: [await getAccount()], chainId, - } + }; } - throw new UserRejectedRequestError(Error('User Rejected Request')) + throw new UserRejectedRequestError(Error('User Rejected Request')); }, disconnect: async () => { try { - const magic = getMagicSDK() - await magic?.wallet.disconnect() - localStorage.removeItem('magicRedirectResult') - config.emitter.emit('disconnect') + const magic = getMagicSDK(); + await magic?.wallet.disconnect(); + localStorage.removeItem('magicRedirectResult'); + config.emitter.emit('disconnect'); } catch (error) { - console.error('Error disconnecting from Magic SDK:', error) + console.error('Error disconnecting from Magic SDK:', error); } }, getAccounts: async () => { - const provider = await getProvider() + const provider = await getProvider(); const accounts = (await provider?.request({ method: 'eth_accounts', - })) as string[] - return accounts.map((x) => getAddress(x)) + })) as string[]; + return accounts.map(x => getAddress(x)); }, getChainId: async (): Promise => { - const provider = await getProvider() + const provider = await getProvider(); if (provider) { const chainId = await provider.request({ method: 'eth_chainId', params: [], - }) - return normalizeChainId(chainId) + }); + return normalizeChainId(chainId); } - const networkOptions = options.magicSdkConfiguration?.network + const networkOptions = options.magicSdkConfiguration?.network; if (typeof networkOptions === 'object') { - const chainID = networkOptions.chainId - if (chainID) return normalizeChainId(chainID) + const chainID = networkOptions.chainId; + if (chainID) return normalizeChainId(chainID); } - throw new Error('Chain ID is not defined') + throw new Error('Chain ID is not defined'); }, isAuthorized: async () => { try { - const magic = getMagicSDK() as InstanceWithExtensions< - SDKBase, - OAuthExtension[] - > + const magic = getMagicSDK() as InstanceWithExtensions; if (!magic) { - return false + return false; } - const isLoggedIn = await magic.user.isLoggedIn() - const result = await magic.oauth.getRedirectResult() + const isLoggedIn = await magic.user.isLoggedIn(); + const result = await magic.oauth.getRedirectResult(); if (result) { - localStorage.setItem('magicRedirectResult', JSON.stringify(result)) + localStorage.setItem('magicRedirectResult', JSON.stringify(result)); } - if (isLoggedIn) return true + if (isLoggedIn) return true; - return result !== null + return result !== null; } catch {} - return false + return false; }, onAccountsChanged, onChainChanged(chain) { - const chainId = normalizeChainId(chain) - config.emitter.emit('change', { chainId }) + const chainId = normalizeChainId(chain); + config.emitter.emit('change', { chainId }); }, async onConnect(connectInfo) { - const chainId = normalizeChainId(connectInfo.chainId) - const accounts = await this.getAccounts() - config.emitter.emit('connect', { accounts, chainId }) + const chainId = normalizeChainId(connectInfo.chainId); + const accounts = await this.getAccounts(); + config.emitter.emit('connect', { accounts, chainId }); }, onDisconnect: () => { - config.emitter.emit('disconnect') + config.emitter.emit('disconnect'); }, - })) + })); } diff --git a/src/lib/connectors/magicConnector.ts b/src/lib/connectors/magicConnector.ts index 6fdbdb6..7af009f 100644 --- a/src/lib/connectors/magicConnector.ts +++ b/src/lib/connectors/magicConnector.ts @@ -1,24 +1,24 @@ -import { OAuthExtension } from '@magic-ext/oauth' +import { OAuthExtension } from '@magic-ext/oauth'; import type { InstanceWithExtensions, MagicSDKAdditionalConfiguration, MagicSDKExtensionsOption, SDKBase, -} from '@magic-sdk/provider' -import { type EthNetworkConfiguration, Magic } from 'magic-sdk' -import { type Chain, createWalletClient, custom, getAddress } from 'viem' +} from '@magic-sdk/provider'; +import { type EthNetworkConfiguration, Magic } from 'magic-sdk'; +import { type Chain, createWalletClient, custom, getAddress } from 'viem'; -const IS_SERVER = typeof window === 'undefined' +const IS_SERVER = typeof window === 'undefined'; export interface MagicOptions { - apiKey: string - accentColor?: string - isDarkMode?: boolean - customLogo?: string - customHeaderText?: string - connectorType?: 'dedicated' | 'universal' - magicSdkConfiguration?: MagicSDKAdditionalConfiguration - networks?: EthNetworkConfiguration[] + apiKey: string; + accentColor?: string; + isDarkMode?: boolean; + customLogo?: string; + customHeaderText?: string; + connectorType?: 'dedicated' | 'universal'; + magicSdkConfiguration?: MagicSDKAdditionalConfiguration; + networks?: EthNetworkConfiguration[]; } /** @@ -30,15 +30,13 @@ export interface MagicOptions { */ export interface MagicConnectorParams { - chains: readonly Chain[] - options: MagicOptions + chains: readonly Chain[]; + options: MagicOptions; } export function magicConnector({ chains = [], options }: MagicConnectorParams) { if (!options.apiKey) { - throw new Error( - 'Magic API Key is required. Get one at https://dashboard.magic.link/', - ) + throw new Error('Magic API Key is required. Get one at https://dashboard.magic.link/'); } const getMagicSDK = (): @@ -49,50 +47,49 @@ export function magicConnector({ chains = [], options }: MagicConnectorParams) { return new Magic(options.apiKey, { ...options.magicSdkConfiguration, extensions: [new OAuthExtension()], - }) + }); } if (options.connectorType === 'universal') { return new Magic(options.apiKey, { ...options.magicSdkConfiguration, - network: - options.magicSdkConfiguration?.network ?? options?.networks?.[0], - }) + network: options.magicSdkConfiguration?.network ?? options?.networks?.[0], + }); } - return null - } + return null; + }; const getProvider = async () => { - const magic = getMagicSDK() - if (!magic) return null - return magic.rpcProvider - } + const magic = getMagicSDK(); + if (!magic) return null; + return magic.rpcProvider; + }; const getAccount = async () => { - const provider = await getProvider() + const provider = await getProvider(); const accounts = await provider?.request({ method: 'eth_accounts', - }) - const account = getAddress(accounts[0] as string) - return account - } + }); + const account = getAddress(accounts[0] as string); + return account; + }; const getWalletClient = async ({ chainId }: { chainId?: number } = {}) => { - const provider = await getProvider() - const account = await getAccount() - const chain = chains.find((x) => x.id === chainId) ?? chains[0] - if (!provider) throw new Error('provider is required.') + const provider = await getProvider(); + const account = await getAccount(); + const chain = chains.find(x => x.id === chainId) ?? chains[0]; + if (!provider) throw new Error('provider is required.'); return createWalletClient({ account, chain, transport: custom(provider), - }) - } + }); + }; const onAccountsChanged = async (accounts: string[]) => { - const provider = await getProvider() - if (accounts.length === 0 || !accounts[0]) provider?.emit('disconnect') - else provider?.emit('change', { account: getAddress(accounts[0]) }) - } + const provider = await getProvider(); + if (accounts.length === 0 || !accounts[0]) provider?.emit('disconnect'); + else provider?.emit('change', { account: getAddress(accounts[0]) }); + }; return { id: 'magic', @@ -105,5 +102,5 @@ export function magicConnector({ chains = [], options }: MagicConnectorParams) { getAccount, getWalletClient, onAccountsChanged, - } + }; } diff --git a/src/lib/connectors/universalWalletConnector.ts b/src/lib/connectors/universalWalletConnector.ts index f1a88d5..1c89982 100644 --- a/src/lib/connectors/universalWalletConnector.ts +++ b/src/lib/connectors/universalWalletConnector.ts @@ -1,15 +1,15 @@ -import type { MagicSDKAdditionalConfiguration } from '@magic-sdk/provider' -import type { RPCProviderModule } from '@magic-sdk/provider/dist/types/modules/rpc-provider' -import type { EthNetworkConfiguration } from '@magic-sdk/types' -import { createConnector } from '@wagmi/core' -import { normalizeChainId } from '../utils' -import { magicConnector } from './magicConnector' -import { type Chain, getAddress } from 'viem' +import type { MagicSDKAdditionalConfiguration } from '@magic-sdk/provider'; +import type { RPCProviderModule } from '@magic-sdk/provider/dist/types/modules/rpc-provider'; +import type { EthNetworkConfiguration } from '@magic-sdk/types'; +import { createConnector } from '@wagmi/core'; +import { normalizeChainId } from '../utils'; +import { magicConnector } from './magicConnector'; +import { type Chain, getAddress } from 'viem'; export interface UniversalWalletOptions { - apiKey: string - magicSdkConfiguration?: MagicSDKAdditionalConfiguration - networks?: EthNetworkConfiguration[] + apiKey: string; + magicSdkConfiguration?: MagicSDKAdditionalConfiguration; + networks?: EthNetworkConfiguration[]; } /** @@ -32,28 +32,17 @@ export interface UniversalWalletOptions { */ interface UniversalWalletConnectorParams { - chains: readonly Chain[] - options: UniversalWalletOptions + chains: readonly Chain[]; + options: UniversalWalletOptions; } -export function universalWalletConnector({ - chains, - options, -}: UniversalWalletConnectorParams) { - const { - id, - name, - type, - getAccount, - getMagicSDK, - getProvider, - onAccountsChanged, - } = magicConnector({ +export function universalWalletConnector({ chains, options }: UniversalWalletConnectorParams) { + const { id, name, type, getAccount, getMagicSDK, getProvider, onAccountsChanged } = magicConnector({ chains, options: { ...options, connectorType: 'universal' }, - }) + }); - const magic = getMagicSDK() + const magic = getMagicSDK(); const registerProviderEventListeners = ( provider: RPCProviderModule, @@ -61,89 +50,89 @@ export function universalWalletConnector({ onDisconnect: () => void, ) => { if (provider.on) { - provider.on('accountsChanged', onAccountsChanged) - provider.on('chainChanged', (chain) => onChainChanged(chain)) - provider.on('disconnect', onDisconnect) + provider.on('accountsChanged', onAccountsChanged); + provider.on('chainChanged', chain => onChainChanged(chain)); + provider.on('disconnect', onDisconnect); } - } + }; - return createConnector((config) => ({ + return createConnector(config => ({ id, name, type, getProvider, connect: async function () { - await magic?.wallet.connectWithUI() - const provider = await getProvider() - const chainId = await this.getChainId() + await magic?.wallet.connectWithUI(); + const provider = await getProvider(); + const chainId = await this.getChainId(); provider && registerProviderEventListeners( provider, - (chain) => { - const chainId = normalizeChainId(chain) - config.emitter.emit('change', { chainId }) + chain => { + const chainId = normalizeChainId(chain); + config.emitter.emit('change', { chainId }); }, this.onDisconnect, - ) - const account = await getAccount() + ); + const account = await getAccount(); return { accounts: [account], chainId, - } + }; }, onAccountsChanged, getAccounts: async () => { - const provider = await getProvider() + const provider = await getProvider(); const accounts = (await provider?.request({ method: 'eth_accounts', - })) as string[] - return accounts.map((x) => getAddress(x)) + })) as string[]; + return accounts.map(x => getAddress(x)); }, - onChainChanged: (chain) => { - const chainId = normalizeChainId(chain) - config.emitter.emit('change', { chainId }) + onChainChanged: chain => { + const chainId = normalizeChainId(chain); + config.emitter.emit('change', { chainId }); }, async onConnect(connectInfo) { - const chainId = normalizeChainId(connectInfo.chainId) - const accounts = await this.getAccounts() - config.emitter.emit('connect', { accounts, chainId }) + const chainId = normalizeChainId(connectInfo.chainId); + const accounts = await this.getAccounts(); + config.emitter.emit('connect', { accounts, chainId }); }, disconnect: async () => { try { - await magic?.wallet.disconnect() - config.emitter.emit('disconnect') + await magic?.wallet.disconnect(); + config.emitter.emit('disconnect'); } catch (error) { - console.error('Error disconnecting from Magic SDK:', error) + console.error('Error disconnecting from Magic SDK:', error); } }, isAuthorized: async () => { try { - const walletInfo = await magic?.wallet.getInfo() - return !!walletInfo + const walletInfo = await magic?.wallet.getInfo(); + return !!walletInfo; } catch { - return false + return false; } }, getChainId: async (): Promise => { - const provider = await getProvider() + const provider = await getProvider(); if (provider) { const chainId = await provider.request({ method: 'eth_chainId', params: [], - }) - return normalizeChainId(chainId) + }); + return normalizeChainId(chainId); } - const networkOptions = options.magicSdkConfiguration?.network + const networkOptions = options.magicSdkConfiguration?.network; if (typeof networkOptions === 'object') { - const chainID = networkOptions.chainId - if (chainID) return normalizeChainId(chainID) + const chainID = networkOptions.chainId; + if (chainID) return normalizeChainId(chainID); } - throw new Error('Chain ID is not defined') + throw new Error('Chain ID is not defined'); }, onDisconnect: () => { - config.emitter.emit('disconnect') + config.emitter.emit('disconnect'); }, - })) + })); } diff --git a/src/lib/modal/logos.ts b/src/lib/modal/logos.ts index 0e614e3..26e70b3 100644 --- a/src/lib/modal/logos.ts +++ b/src/lib/modal/logos.ts @@ -5,7 +5,7 @@ export const MagicLogo = ` -` +`; export const googleLogo = ` @@ -14,49 +14,49 @@ export const googleLogo = ` -` +`; export const twitchLogo = ` -` +`; export const discordLogo = ` -` +`; export const bitbucketLogo = ` -` +`; export const linkedinLogo = ` -` +`; export const appleLogo = ` -` +`; export const twitterLogo = ` -` +`; export const facebookLogo = ` @@ -71,7 +71,7 @@ export const facebookLogo = ` -` +`; export const githubLogo = ` @@ -80,7 +80,7 @@ export const githubLogo = ` -` +`; export const gitlabLogo = ` @@ -93,7 +93,7 @@ export const gitlabLogo = ` -` +`; export const microsoftLogo = ` @@ -103,4 +103,4 @@ export const microsoftLogo = ` -` +`; diff --git a/src/lib/modal/styles.ts b/src/lib/modal/styles.ts index 8da65ff..e888258 100644 --- a/src/lib/modal/styles.ts +++ b/src/lib/modal/styles.ts @@ -184,4 +184,4 @@ export const modalStyles = (accentColor = '#6452f7') => ` font-size: 16px; text-transform: capitalize; } -` +`; diff --git a/src/lib/modal/view.ts b/src/lib/modal/view.ts index b69b78c..457a480 100644 --- a/src/lib/modal/view.ts +++ b/src/lib/modal/view.ts @@ -1,4 +1,4 @@ -import type { OAuthProvider } from '@magic-ext/oauth' +import type { OAuthProvider } from '@magic-ext/oauth'; import { appleLogo, @@ -13,22 +13,22 @@ import { microsoftLogo, twitchLogo, twitterLogo, -} from './logos' -import { modalStyles } from './styles' +} from './logos'; +import { modalStyles } from './styles'; export const createModal = async (props: { - accentColor?: string - isDarkMode?: boolean - customLogo?: string - customHeaderText?: string - enableSMSLogin?: boolean - enableEmailLogin?: boolean - oauthProviders?: OAuthProvider[] + accentColor?: string; + isDarkMode?: boolean; + customLogo?: string; + customHeaderText?: string; + enableSMSLogin?: boolean; + enableEmailLogin?: boolean; + oauthProviders?: OAuthProvider[]; }) => { // INJECT FORM STYLES - const style = document.createElement('style') - style.innerHTML = modalStyles(props.accentColor) - document.head.appendChild(style) + const style = document.createElement('style'); + style.innerHTML = modalStyles(props.accentColor); + document.head.appendChild(style); // PROVIDERS FOR OAUTH BUTTONS const allProviders = [ @@ -43,18 +43,17 @@ export const createModal = async (props: { { name: 'discord', icon: discordLogo }, { name: 'twitch', icon: twitchLogo }, { name: 'microsoft', icon: microsoftLogo }, - ] + ]; // make providers included in oauthProviders const providers = props.oauthProviders - ?.map((provider) => { - return allProviders.find((p) => p.name === provider) + ?.map(provider => { + return allProviders.find(p => p.name === provider); }) - .filter((p) => p !== undefined) + .filter(p => p !== undefined); - const phoneNumberRegex = '(\\+|00)[0-9]{1,3}[0-9]{4,14}(?:x.+)?$' - const emailRegex = - '^([a-zA-Z0-9_.-])+(\\+[a-zA-Z0-9-]+)?@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})' + const phoneNumberRegex = '(\\+|00)[0-9]{1,3}[0-9]{4,14}(?:x.+)?$'; + const emailRegex = '^([a-zA-Z0-9_.-])+(\\+[a-zA-Z0-9-]+)?@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})'; // MODAL HTML const modal = ` @@ -76,16 +75,16 @@ export const createModal = async (props: { ` : props.enableEmailLogin - ? ` + ? ` ` - : props.enableSMSLogin - ? ` + : props.enableSMSLogin + ? ` ` - : '' + : '' } ${ props.enableSMSLogin || props.enableEmailLogin @@ -96,9 +95,7 @@ export const createModal = async (props: { } ${ - providers && - providers.length > 0 && - (props.enableSMSLogin || props.enableEmailLogin) + providers && providers.length > 0 && (props.enableSMSLogin || props.enableEmailLogin) ? `
⎯⎯⎯ OR ⎯⎯⎯
` @@ -110,11 +107,9 @@ export const createModal = async (props: { : 'Magic__oauthButtonsContainer' }"> ${providers - ?.map((provider) => { + ?.map(provider => { return ` - - ` + `; }) .join('')} ${ - !props.enableEmailLogin && - !props.enableEmailLogin && - providers?.length === 0 + !props.enableEmailLogin && !props.enableEmailLogin && providers?.length === 0 ? '
No Login Methods Configured 😥
' : '' } - ` + `; // ADD FORM TO BODY - const overlay = document.createElement('div') - overlay.classList.add('Magic__formOverlay') - if (props.isDarkMode) overlay.classList.add('Magic__dark') - document.body.appendChild(overlay) - overlay.innerHTML = modal - const formBody = document.getElementById('MagicModalBody') + const overlay = document.createElement('div'); + overlay.classList.add('Magic__formOverlay'); + if (props.isDarkMode) overlay.classList.add('Magic__dark'); + document.body.appendChild(overlay); + overlay.innerHTML = modal; + const formBody = document.getElementById('MagicModalBody'); setTimeout(() => { - if (formBody) formBody.style.transform = 'translate(-50%, -50%) scale(1)' - }, 100) + if (formBody) formBody.style.transform = 'translate(-50%, -50%) scale(1)'; + }, 100); // FORM SUBMIT HANDLER const removeForm = () => { - if (formBody) formBody.style.transform = 'translate(-50%, -50%) scale(0)' + if (formBody) formBody.style.transform = 'translate(-50%, -50%) scale(0)'; setTimeout(() => { - overlay.remove() - }, 200) - } + overlay.remove(); + }, 200); + }; - return new Promise((resolve) => { + return new Promise(resolve => { // FORM CLOSE BUTTON document.getElementById('MagicCloseBtn')?.addEventListener('click', () => { - removeForm() + removeForm(); resolve({ email: '', phoneNumber: '', isGoogle: false, isDiscord: false, - }) - }) + }); + }); // EMAIL FORM SUBMIT HANDLER - document.getElementById('MagicForm')?.addEventListener('submit', (e) => { - e.preventDefault() - const formInputField = document.getElementById( - 'MagicFormInput', - ) as HTMLInputElement - const isFormValid = formInputField?.checkValidity() + document.getElementById('MagicForm')?.addEventListener('submit', e => { + e.preventDefault(); + const formInputField = document.getElementById('MagicFormInput') as HTMLInputElement; + const isFormValid = formInputField?.checkValidity(); if (isFormValid) { - let output + let output; if (RegExp(phoneNumberRegex).test(formInputField.value)) { output = { phoneNumber: formInputField?.value, - } + }; } else { output = { email: formInputField?.value, - } + }; } - removeForm() - resolve(output) + removeForm(); + resolve(output); } - }) + }); // OAUTH BUTTONS - providers?.forEach((provider) => { - const oauthButton = document.getElementById(`MagicOauth${provider?.name}`) + providers?.forEach(provider => { + const oauthButton = document.getElementById(`MagicOauth${provider?.name}`); oauthButton?.addEventListener('click', () => { const output = { oauthProvider: provider?.name as OAuthProvider, - } - removeForm() - resolve(output) - }) - }) - }) -} + }; + removeForm(); + resolve(output); + }); + }); + }); +}; diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 9e0fe04..4138790 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -1,6 +1,5 @@ export function normalizeChainId(chainId: string | number | bigint) { - if (typeof chainId === 'string') - return Number.parseInt(chainId, chainId.trim().startsWith('0x') ? 16 : 10) - if (typeof chainId === 'bigint') return Number(chainId) - return chainId + if (typeof chainId === 'string') return Number.parseInt(chainId, chainId.trim().startsWith('0x') ? 16 : 10); + if (typeof chainId === 'bigint') return Number(chainId); + return chainId; }