Skip to content

Commit

Permalink
refactor(pay): use app router in pay (#3992)
Browse files Browse the repository at this point in the history
* chore(pay): use app directory in pay

* refactor: clean up

* chore: updateCurrencyAndReload funciton

* fix: spell

* refactor: create extractSearchParams func to get search params

* chore: removing snake case variables

* fix: manifest error and rename layout

* chore: remove old wrapper

* chore: use Suspense insted of missingSuspenseWithCSRBailout

* chore: remove implicit any

* chore: use URL func to create url

* chore: remove un-used files

* chore: added comments

* refactor: rename memo

* refactor: setuppwa page
  • Loading branch information
siddhart1o1 authored Feb 15, 2024
1 parent c95fff7 commit 90a19b3
Show file tree
Hide file tree
Showing 38 changed files with 975 additions and 1,533 deletions.
19 changes: 19 additions & 0 deletions apps/pay/app/[username]/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from "react"

import UsernameLayoutContainer from "@/components/Layouts/UsernameLayout"

export default function UsernameLayout({
children,
params,
}: {
children: React.ReactNode
params: {
username: string
}
}) {
return (
<UsernameLayoutContainer username={params.username}>
{children}
</UsernameLayoutContainer>
)
}
172 changes: 172 additions & 0 deletions apps/pay/app/[username]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"use client"
import Link from "next/link"
import React from "react"
import Container from "react-bootstrap/Container"
import Image from "react-bootstrap/Image"

import Head from "next/head"

import { gql } from "@apollo/client"

import { useSearchParams } from "next/navigation"

import ParsePayment from "../../components/ParsePOSPayment"
import PinToHomescreen from "../../components/PinToHomescreen"

import CurrencyDropdown from "../../components/Currency/currency-dropdown"

import { useAccountDefaultWalletsQuery } from "../../lib/graphql/generated"

import reducer, { ACTIONS } from "../reducer"

import styles from "./username.module.css"

import LoadingComponent from "@/components/Loading"
import { extractSearchParams } from "@/utils/utils"

gql`
query accountDefaultWallets($username: Username!) {
accountDefaultWallet(username: $username) {
__typename
id
walletCurrency
}
}
`

type Props = {
params: {
username: string
}
}

function updateCurrencyAndReload(newDisplayCurrency: string): void {
localStorage.setItem("display", newDisplayCurrency)

const currentURL = new URL(window.location.toString())
const searchParams = new URLSearchParams(window.location.search)
searchParams.set("display", newDisplayCurrency)
currentURL.search = searchParams.toString()

window.history.pushState({}, "", currentURL.toString())
setTimeout(() => {
window.location.reload()
}, 100)
}

function ReceivePayment({ params }: Props) {
const searchParams = useSearchParams()
const { memo } = extractSearchParams(searchParams)

const { username } = params

let accountUsername: string
if (!username) {
accountUsername = ""
} else {
accountUsername = username.toString()
}

const manifestParams = new URLSearchParams()
if (memo) {
manifestParams.set("memo", memo.toString())
}

const {
data,
error: usernameError,
loading: usernameLoading,
} = useAccountDefaultWalletsQuery({
variables: { username: accountUsername },
skip: !accountUsername,
})

const [state, dispatch] = React.useReducer(reducer, {
currentAmount: "",
createdInvoice: false,
walletCurrency: data?.accountDefaultWallet.walletCurrency,
username: accountUsername,
pinnedToHomeScreenModalVisible: false,
})

React.useEffect(() => {
if (state.walletCurrency === data?.accountDefaultWallet.walletCurrency) {
return
}
dispatch({
type: ACTIONS.UPDATE_WALLET_CURRENCY,
payload: data?.accountDefaultWallet.walletCurrency,
})
dispatch({ type: ACTIONS.UPDATE_USERNAME, payload: username })
}, [state, username, data])

return username ? (
<Container className={styles.payment_container}>
<Head>
<link
rel="manifest"
href={`/api/${username}/manifest?${manifestParams.toString()}`}
id="manifest"
/>
</Head>
{usernameError ? (
<div className={styles.error}>
<p>{`${usernameError.message}.`}</p>
<p>Please check the username in your browser URL and try again.</p>
<Link href={"/setuppwa"} onClick={() => localStorage.removeItem("username")}>
Back
</Link>
</div>
) : (
<>
<PinToHomescreen
pinnedToHomeScreenModalVisible={state.pinnedToHomeScreenModalVisible}
dispatch={dispatch}
/>
<div className={styles.username_container}>
{state.createdInvoice && (
<button onClick={() => dispatch({ type: ACTIONS.BACK })}>
<Image
src="/icons/chevron-left-icon.svg"
alt="back button"
width="10px"
height="12px"
/>
</button>
)}
<p className={styles.username}>{`Pay ${username}`}</p>
<div style={{ marginLeft: "12px", marginTop: "9px" }}>
<CurrencyDropdown
style={{
border: "none",
outline: "none",
width: "56px",
height: "42px",
fontSize: "18px",
backgroundColor: "white",
textAlign: "center",
verticalAlign: "middle",
}}
showOnlyFlag={true}
onSelectedDisplayCurrencyChange={updateCurrencyAndReload}
/>
</div>
</div>
{data && !usernameLoading && accountUsername && state ? (
<ParsePayment
state={state}
dispatch={dispatch}
defaultWalletCurrency={data?.accountDefaultWallet.walletCurrency}
walletId={data?.accountDefaultWallet.id}
username={accountUsername}
/>
) : (
<LoadingComponent />
)}
</>
)}
</Container>
) : null
}

export default ReceivePayment
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import Row from "react-bootstrap/Row"
"use client"
import Col from "react-bootstrap/Col"
import Row from "react-bootstrap/Row"
import Card from "react-bootstrap/Card"
import Container from "react-bootstrap/Container"
import ReactToPrint from "react-to-print"
import { bech32 } from "bech32"
import { QRCode } from "react-qrcode-logo"
import { useRef } from "react"
import { useRouter } from "next/router"

export default function Print() {
export default function Print({
params,
}: {
params: {
username: string
}
}) {
const { username } = params
const componentRef = useRef<HTMLDivElement | null>(null)

const router = useRouter()
const username = router.query.username as string
const url = new URL(window.location.href)
const unencodedLnurl = `${url.protocol}//${url.host}/.well-known/lnurlp/${username}`
const lnurl = bech32.encode(
Expand Down
File renamed without changes.
10 changes: 3 additions & 7 deletions apps/pay/pages/index.css → apps/pay/app/globals.css
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
@import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300;400;600;700&display=swap");
@tailwind base;
@tailwind components;
@tailwind utilities;

body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu",
"Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace;
}

.error {
color: red;
margin: 20px auto;
Expand Down
51 changes: 24 additions & 27 deletions apps/pay/pages/_app.tsx → apps/pay/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,28 @@
// Disable no-unassigned-import rule because we are importing css files
// eslint-disable-next-line
import "bootstrap/dist/css/bootstrap.min.css"
// eslint-disable-next-line
import "./index.css"
import Script from "next/script"
import { NextPage } from "next"
import dynamic from "next/dynamic"
import type { Metadata } from "next"
import { Inter_Tight } from "next/font/google"

// eslint-disable-next-line import/no-unassigned-import
import "./globals.css"

// eslint-disable-next-line import/no-unassigned-import
import "bootstrap/dist/css/bootstrap.css"

import Head from "next/head"
import { useRouter } from "next/router"
import Script from "next/script"

import { ApolloWrapper } from "@/components/apollo-wrapper"
import { APP_DESCRIPTION } from "@/config/config"

import AppLayout from "../components/Layouts/AppLayout"
import { APP_DESCRIPTION } from "../config/config"
const inter = Inter_Tight({ subsets: ["latin"] })

const GraphQLProvider = dynamic(() => import("../lib/graphql"), { ssr: false })
export const metadata: Metadata = {
title: "Blink Cash Register",
description: "Blink official lightning network node",
}

export default function Layout({
Component,
pageProps,
}: {
Component: NextPage
pageProps: Record<string, unknown>
}) {
const { username } = useRouter().query
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<>
<html lang="en">
<Head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
Expand All @@ -44,11 +43,9 @@ export default function Layout({
gtag('config', 'UA-181044262-1');
`}
</Script>
<GraphQLProvider>
<AppLayout username={username}>
<Component {...pageProps} />
</AppLayout>
</GraphQLProvider>
</>
<body className={inter.className}>
<ApolloWrapper>{children}</ApolloWrapper>
</body>
</html>
)
}
49 changes: 25 additions & 24 deletions apps/pay/pages/index.tsx → apps/pay/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from "react"
"use client"
import React, { Suspense, useEffect } from "react"
import Card from "react-bootstrap/Card"
import Col from "react-bootstrap/Col"
import Container from "react-bootstrap/Container"
Expand All @@ -7,7 +8,7 @@ import ListGroup from "react-bootstrap/ListGroup"
import Row from "react-bootstrap/Row"
import { gql, useQuery } from "@apollo/client"

import { useRouter } from "next/router"
import { useRouter } from "next/navigation"

import CurrencyDropdown from "../components/Currency/currency-dropdown"
import { getClientSideGqlConfig } from "../config/config"
Expand All @@ -25,24 +26,22 @@ function Home() {
? `https://mempool.space/signet/lightning/node/`
: `https://mempool.space/lightning/node/`
const { loading, error, data } = useQuery(GET_NODE_STATS)
const [selectedDisplayCurrency, setSelectedDisplayCurrency] = React.useState(
localStorage.getItem("display") ?? "USD",
)
const [selectedDisplayCurrency, setSelectedDisplayCurrency] =
React.useState<string>("USD")

useEffect(() => {
const displayCurrency = localStorage.getItem("display")
if (displayCurrency) {
setSelectedDisplayCurrency(displayCurrency)
}
}, [])

const router = useRouter()
const [username, setUsername] = React.useState<string>("")

const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()

router.push(
{
pathname: username,
query: { display: selectedDisplayCurrency },
},
undefined,
{ shallow: true },
)
router.push(`${username}?display=${selectedDisplayCurrency}`, { scroll: true })
}

return (
Expand Down Expand Up @@ -109,16 +108,18 @@ function Home() {
<label htmlFor="display" style={{ alignSelf: "flex-start" }}>
Enter your currency
</label>
<CurrencyDropdown
name="display"
style={{ height: "42px", width: "100%" }}
onSelectedDisplayCurrencyChange={(newDisplayCurrency) => {
if (newDisplayCurrency) {
localStorage.setItem("display", newDisplayCurrency)
setSelectedDisplayCurrency(newDisplayCurrency)
}
}}
/>
<Suspense>
<CurrencyDropdown
name="display"
style={{ height: "42px", width: "100%" }}
onSelectedDisplayCurrencyChange={(newDisplayCurrency) => {
if (newDisplayCurrency) {
localStorage.setItem("display", newDisplayCurrency)
setSelectedDisplayCurrency(newDisplayCurrency)
}
}}
/>
</Suspense>
<button data-testid="submit-btn">Submit</button>
</form>
</ListGroup.Item>
Expand Down
File renamed without changes.
Loading

0 comments on commit 90a19b3

Please sign in to comment.