Add installation instructions for iOS
Test / test (push) Successful in 33s Details

This commit is contained in:
Jeff 2024-05-28 20:46:39 -04:00
parent c24cfa0b4c
commit a7c955e908
39 changed files with 4736 additions and 1049 deletions

View File

@ -0,0 +1,10 @@
name: Test
run-name: Test?
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm install && npm run test

8
.gitignore vendored
View File

@ -1,5 +1,9 @@
.env
data/
node_modules/
public/
build/
build/
/public/entry.worker.js
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/

20
.prettierrc Normal file
View File

@ -0,0 +1,20 @@
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": false,
"singleQuote": false,
"maxLineLength": 120,
"overrides": [
{
"files": [
"*.test.ts",
"*.test.js",
"*.spec.ts",
"*.spec.js"
],
"options": {
"maxLineLength": 9999999
}
}
]
}

31
.swcrc Normal file
View File

@ -0,0 +1,31 @@
{
"jsc": {
"target": "es2022",
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": false,
"dynamicImport": false
},
"transform": {
"react": {
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"development": false,
"useBuiltins": false,
"runtime": "automatic"
},
"hidden": {
"jest": true
}
}
},
"module": {
"type": "commonjs",
"strict": false,
"strictMode": true,
"lazy": false,
"noInterop": false
}
}

View File

@ -1,4 +1,4 @@
FROM node
FROM node:22-alpine
WORKDIR /tack-up-now
COPY . .
RUN npm install

5
api/subscribe.ts Normal file
View File

@ -0,0 +1,5 @@
import type { Response, Request } from "express"
export function subscribe(req: Request, res: Response) {
res.status(200).send()
}

19
app/ClientOnly.tsx Normal file
View File

@ -0,0 +1,19 @@
import { ReactNode, useEffect, useState } from "react"
export default function ClientOnly({
fallback,
children,
}: {
fallback: ReactNode
children(): ReactNode
}) {
const isClient = typeof window !== "undefined"
const [rendered, setRendered] = useState(false)
useEffect(() => {
setRendered(true)
}, [])
return isClient && rendered ? children() : fallback
}

View File

@ -4,9 +4,10 @@
* For more information, see https://remix.run/file-conventions/entry.client
*/
import { RemixBrowser } from "@remix-run/react";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { RemixBrowser } from "@remix-run/react"
import React from "react"
import { startTransition, StrictMode } from "react"
import { hydrateRoot } from "react-dom/client"
startTransition(() => {
hydrateRoot(
@ -14,5 +15,5 @@ startTransition(() => {
<StrictMode>
<RemixBrowser />
</StrictMode>
);
});
)
})

View File

@ -4,15 +4,16 @@
* For more information, see https://remix.run/file-conventions/entry.server
*/
import { PassThrough } from "node:stream";
import { PassThrough } from "node:stream"
import type { AppLoadContext, EntryContext } from "@remix-run/node";
import { createReadableStreamFromReadable } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { isbot } from "isbot";
import { renderToPipeableStream } from "react-dom/server";
import type { AppLoadContext, EntryContext } from "@remix-run/node"
import { createReadableStreamFromReadable } from "@remix-run/node"
import { RemixServer } from "@remix-run/react"
import { isbot } from "isbot"
import { renderToPipeableStream } from "react-dom/server"
import React from "react"
const ABORT_DELAY = 5_000;
const ABORT_DELAY = 5_000
export default function handleRequest(
request: Request,
@ -36,7 +37,7 @@ export default function handleRequest(
responseStatusCode,
responseHeaders,
remixContext
);
)
}
function handleBotRequest(
@ -46,7 +47,7 @@ function handleBotRequest(
remixContext: EntryContext
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
let shellRendered = false
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
@ -55,38 +56,38 @@ function handleBotRequest(
/>,
{
onAllReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);
shellRendered = true
const body = new PassThrough()
const stream = createReadableStreamFromReadable(body)
responseHeaders.set("Content-Type", "text/html");
responseHeaders.set("Content-Type", "text/html")
resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);
)
pipe(body);
pipe(body)
},
onShellError(error: unknown) {
reject(error);
reject(error)
},
onError(error: unknown) {
responseStatusCode = 500;
responseStatusCode = 500
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
console.error(error)
}
},
}
);
)
setTimeout(abort, ABORT_DELAY);
});
setTimeout(abort, ABORT_DELAY)
})
}
function handleBrowserRequest(
@ -96,7 +97,7 @@ function handleBrowserRequest(
remixContext: EntryContext
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
let shellRendered = false
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
@ -105,36 +106,36 @@ function handleBrowserRequest(
/>,
{
onShellReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);
shellRendered = true
const body = new PassThrough()
const stream = createReadableStreamFromReadable(body)
responseHeaders.set("Content-Type", "text/html");
responseHeaders.set("Content-Type", "text/html")
resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);
)
pipe(body);
pipe(body)
},
onShellError(error: unknown) {
reject(error);
reject(error)
},
onError(error: unknown) {
responseStatusCode = 500;
responseStatusCode = 500
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
console.error(error)
}
},
}
);
)
setTimeout(abort, ABORT_DELAY);
});
setTimeout(abort, ABORT_DELAY)
})
}

17
app/entry.worker.ts Normal file
View File

@ -0,0 +1,17 @@
/// <reference lib="WebWorker" />
export {}
declare let self: ServiceWorkerGlobalScope
self.addEventListener("install", (event) => {
console.log("Service worker installed")
event.waitUntil(self.skipWaiting())
})
self.addEventListener("activate", (event) => {
console.log("Service worker activated")
event.waitUntil(self.clients.claim())
})

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,61 @@
import React from "react"
import { useEffect } from "react"
import { usePush } from "../usePush"
export default function EnableNotifications({
onSubscribe,
}: {
onSubscribe: () => void
}) {
return (
<div>
<h1>Allow Notifications</h1>
<div>
Tack Up Now requires your permission to send notifications in order to
function properly
</div>
<EnableButton onSubscribe={onSubscribe} />
</div>
)
}
function EnableButton({ onSubscribe }: { onSubscribe: () => void }) {
const { subscribeToPush, requestPermission, canSendPush } = usePush()
function subscribe() {
requestPermission()
}
useEffect(() => {
if (!canSendPush) return
subscribeToPush(
urlB64ToUint8Array(applicationServerPublicKey) as any,
(subscription) => {
fetch("/api/subscribe", {
method: "POST",
body: JSON.stringify(subscription),
})
onSubscribe()
}
)
}, [canSendPush])
return <button onClick={subscribe}>Enable Notifications</button>
}
const applicationServerPublicKey =
"BDTbzdtzJxwV0sscdsXla-GKvlcxqQr7edEfkX8-papwvvV1UVc3IMyRacl1BbgTi31nWPji2wKCZkjf1l5iX7Y"
function urlB64ToUint8Array(base64String: string) {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4)
const base64 = (base64String + padding).replace(/\-/g, "+").replace(/_/g, "/")
const rawData = window.atob(base64)
const outputArray = new Uint8Array(rawData.length)
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i)
}
return outputArray
}

View File

@ -0,0 +1,32 @@
import React from "react"
import shareIcon from "../images/safari-share-icon.png?url"
export default function InstallPWA() {
return (
<div>
<h1>Install Tack Up Now!</h1>
<div>
Install Tack Up Now on your device to get notified when it's time to
tack up
</div>
<div>
<ul>
<span>Tap </span>
<img style={{ width: "2rem" }} src={shareIcon} />
<span> and choose </span>
<span className="bold">Add to Home Screen</span>
</ul>
<ul>
<span>On the next screen, tap </span>
<span className="bold">Add</span>
</ul>
<ul>
<span>Then open </span>
<span className="bold">Tack Up Now</span>
<span> from your home screen</span>
</ul>
</div>
</div>
)
}

View File

@ -0,0 +1,32 @@
import React from "react"
import useInstallState from "../useInstallState"
import EnableNotifications from "./EnableNotifications"
import OpenSafari from "./OpenSafari"
import InstallPWA from "./InstallPWA"
import Unsupported from "./Unsupported"
interface InstallPromptsProps {
isMobileSafari: boolean
isSupported: boolean
notificationsEnabled: boolean
onInstallComplete: () => void
}
export default function InstallPrompts({
isSupported,
isMobileSafari,
onInstallComplete,
}: InstallPromptsProps) {
const { step } = useInstallState({ isSupported, isMobileSafari })
const steps = {
"open safari": <OpenSafari />,
install: <InstallPWA />,
"enable notifications": (
<EnableNotifications onSubscribe={onInstallComplete} />
),
unsupported: <Unsupported />,
}
return steps[step as keyof typeof steps] ?? null
}

View File

@ -0,0 +1,11 @@
import React from "react"
export default function OpenSafari() {
return (
<div>
<div>This device requires Tack Up Now to be installed using Safari</div>
<br />
<div>Open tackupnow.com in Safari to continue!</div>
</div>
)
}

View File

@ -0,0 +1,22 @@
import React, { useState } from "react"
export default function Unsupported() {
const [showWhy, setShowWhy] = useState(false)
return (
<div>
<h1>{"Sorry :("}</h1>
<br />
<div>Your device doesn't support Tack Up Now!</div>
{showWhy ? (
<div>
iOS 16.3 and under does not support notification delivery through web
apps, so Tack Up Now can't send notifications to your device.
</div>
) : (
<button onClick={() => setShowWhy(true)}>Why not?</button>
)}
</div>
)
}

View File

@ -4,7 +4,13 @@ import {
Outlet,
Scripts,
ScrollRestoration,
} from "@remix-run/react";
} from "@remix-run/react"
import React from "react"
import { ManifestLink } from "@remix-pwa/sw"
import { LinksFunction } from "@remix-run/node"
import styles from "./styles/styles.css?url"
export const links: LinksFunction = () => [{ rel: "stylesheet", href: styles }]
export function Layout({ children }: { children: React.ReactNode }) {
return (
@ -13,6 +19,7 @@ export function Layout({ children }: { children: React.ReactNode }) {
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<ManifestLink />
<Links />
</head>
<body>
@ -21,9 +28,9 @@ export function Layout({ children }: { children: React.ReactNode }) {
<Scripts />
</body>
</html>
);
)
}
export default function App() {
return <Outlet />;
return <Outlet />
}

View File

@ -0,0 +1,51 @@
import { act, render, screen, waitFor } from "@testing-library/react"
import MatchMediaMock from "jest-matchmedia-mock"
import { createRemixStub, RemixStubProps } from "@remix-run/testing"
import App from "../root"
import React from "react"
import Index from "./_index"
let RemixStub: (props: RemixStubProps) => React.JSX.Element
describe("root", () => {
beforeEach(() => {
RemixStub = createRemixStub([
{
path: "/",
meta: () => [],
links: () => [],
loader: () => ({ isSupported: true, isMobileSafari: true }),
Component: Index,
},
])
})
let matchMedia: MatchMediaMock
beforeAll(() => {
matchMedia = new MatchMediaMock()
})
afterEach(() => {
matchMedia.clear()
})
describe("when user is on iOS", () => {
describe("version 16.4 or higher", () => {
describe("and tack up now is not already installed on their device", () => {
test("they are instructed to install tack up now", async () => {
render(<RemixStub />)
await waitFor(
() => screen.findByText<HTMLElement>(/Install Tack Up Now!/),
{
timeout: 2000,
}
)
expect(true).toBe(true)
})
})
})
})
})

View File

@ -1,18 +1,84 @@
import type { MetaFunction } from "@remix-run/node";
import {
json,
type LoaderFunctionArgs,
type MetaFunction,
} from "@remix-run/node"
import { useLoaderData } from "@remix-run/react"
import React, { Suspense, useEffect, useState } from "react"
import coerceSemver from "semver/functions/coerce"
import versionAtLeast from "semver/functions/gte"
import UAParser from "ua-parser-js"
import InstallPrompts from "../install/InstallPrompts"
import useInstallState from "../useInstallState"
import ClientOnly from "../ClientOnly"
export const meta: MetaFunction = () => {
return [
{ title: "Tack Up Now!" },
{ name: "description", content: "Get equinelive notifications" },
];
};
]
}
export const loader = async ({ request }: LoaderFunctionArgs) => {
const userAgent = request.headers.get("user-agent")
const parsedUserAgent = new UAParser(userAgent ?? "")
const os = parsedUserAgent.getOS()
const isMobileSafari = parsedUserAgent.getBrowser().name === "Mobile Safari"
const isSupported =
os.name !== "iOS" ||
versionAtLeast(coerceSemver(os.version) ?? "0.0.0", "16.4.0")
return json({
isSupported,
isMobileSafari,
name: os.name,
version: os.version,
})
}
export default function Index() {
const { isSupported, isMobileSafari, name, version } =
useLoaderData<typeof loader>()
console.log(name, version)
return (
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
<h1>WHOAH! A WEBSITE</h1>
<div>Hey check it out!</div>
<Suspense>
<LandingMessage
isSupported={isSupported}
isMobileSafari={isMobileSafari}
/>
</Suspense>
</div>
);
)
}
function LandingMessage({
isSupported,
isMobileSafari,
}: {
isSupported: boolean
isMobileSafari: boolean
}) {
const { installed } = useInstallState({ isSupported, isMobileSafari })
const [isInstalled, setIsInstalled] = useState(installed)
return (
<ClientOnly fallback={<div>Loading</div>}>
{() =>
isInstalled ? (
<div>Your Notifications</div>
) : (
<InstallPrompts
isMobileSafari={isMobileSafari}
isSupported={isSupported}
notificationsEnabled={false}
onInstallComplete={() => setIsInstalled(true)}
/>
)
}
</ClientOnly>
)
}

View File

@ -0,0 +1,35 @@
import type { WebAppManifest } from "@remix-pwa/dev"
import { json } from "@remix-run/node"
export const loader = () => {
return json(
{
name: "Tack Up Now!",
short_name: "Tack Up Now!",
icons: [
{
src: "./images/192.png",
sizes: "192x192",
type: "image/png",
},
{
src: "./images/512.png",
sizes: "512x512",
type: "image/png",
},
],
theme_color: "#ffffff",
background_color: "#ffffff",
display: "standalone",
description: "Notifications for equinelive.com",
start_url: "/",
id: "tackupnow.com",
} as WebAppManifest,
{
headers: {
"Cache-Control": "public, max-age=600",
"Content-Type": "application/manifest+json",
},
}
)
}

10
app/styles/styles.css Normal file
View File

@ -0,0 +1,10 @@
.bold {
font-weight: bold;
}
ul {
display: flex;
flex-direction: row;
align-items: center;
white-space: pre-wrap;
}

48
app/useInstallState.ts Normal file
View File

@ -0,0 +1,48 @@
import { usePush } from "./usePush"
type IOSInstallStep =
| "loading"
| "install"
| "open safari"
| "enable notifications"
| "unsupported"
export default function useInstallState({
isSupported,
isMobileSafari,
}: {
isSupported: boolean
isMobileSafari: boolean
}) {
const isClient = typeof window !== "undefined"
if (!isClient)
return {
step: isSupported ? "loading" : ("unsupported" as IOSInstallStep),
installed: false,
}
const { canSendPush } = usePush()
const notificationsEnabled =
("Notification" in window &&
window.Notification.permission === "granted") ||
canSendPush
const isRunningPWA =
("standalone" in navigator && (navigator.standalone as boolean)) ||
matchMedia("(dislay-mode: standalone)").matches
return {
step: !isSupported
? "unsupported"
: !isMobileSafari
? "open safari"
: !isRunningPWA && isMobileSafari
? "install"
: !notificationsEnabled
? "enable notifications"
: (null as IOSInstallStep | null),
installed: notificationsEnabled,
}
}

183
app/usePush.ts Normal file
View File

@ -0,0 +1,183 @@
import { useEffect, useState } from "react"
export type PushObject = {
/**
* Boolean state indicating whether the user is subscribed to push notifications or not.
*/
isSubscribed: boolean
/**
* The push subscription object
*/
pushSubscription: PushSubscription | null
/**
* Request permission for push notifications
* @returns The permission status of the push notifications
*/
requestPermission: () => NotificationPermission
/**
* Utility to subscribe to push notifications
* @param publicKey the public vapid key
* @param callback a callback function to be called when the subscription is successful
* @param errorCallback a callback function to be called if the subscription fails
*/
subscribeToPush: (
publicKey: string,
callback?: (subscription: PushSubscription) => void,
errorCallback?: (error: any) => void
) => void
/**
* Utility to unsubscribe from push notifications
* @param callback a callback function to be called when the unsubscription is successful
* @param errorCallback a callback function to be called if the unsubscription fails
*/
unsubscribeFromPush: (
callback?: () => void,
errorCallback?: (error: any) => void
) => void
/**
* Boolean state indicating whether the user has allowed sending of push notifications or not.
*/
canSendPush: boolean
}
/**
* Push API hook - contains all your necessities for handling push notifications in the client
*/
export const usePush = (): PushObject => {
const [swRegistration, setSWRegistration] =
useState<ServiceWorkerRegistration | null>(null)
const [isSubscribed, setIsSubscribed] = useState<boolean>(false)
const [pushSubscription, setPushSubscription] =
useState<PushSubscription | null>(null)
const [canSendPush, setCanSendPush] = useState<boolean>(false)
const requestPermission = () => {
if (canSendPush) return "granted"
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
setCanSendPush(true)
return permission
} else {
setCanSendPush(false)
return permission
}
})
return "default"
}
const subscribeToPush = (
publicKey: string,
callback?: (subscription: PushSubscription) => void,
errorCallback?: (error: any) => void
) => {
if (swRegistration === null || swRegistration.pushManager === undefined)
return
swRegistration.pushManager
.subscribe({
userVisibleOnly: true,
applicationServerKey: publicKey,
})
.then(
(subscription) => {
setIsSubscribed(true)
setPushSubscription(subscription)
callback && callback(subscription)
},
(error) => {
errorCallback && errorCallback(error)
}
)
}
const unsubscribeFromPush = (
callback?: () => void,
errorCallback?: (error: any) => void
) => {
if (swRegistration === null || swRegistration.pushManager === undefined)
return
swRegistration.pushManager
.getSubscription()
.then((subscription) => {
if (subscription) {
subscription.unsubscribe().then(
() => {
setIsSubscribed(false)
setPushSubscription(null)
callback && callback()
},
(error) => {
errorCallback && errorCallback(error)
}
)
}
})
.catch((error) => {
errorCallback && errorCallback(error)
})
}
useEffect(() => {
if (typeof window === "undefined") return
const getRegistration = async () => {
if ("serviceWorker" in navigator) {
try {
const _registration = await navigator.serviceWorker.getRegistration()
setSWRegistration(_registration ?? null)
} catch (err) {
console.error("Error getting service worker registration:", err)
}
} else {
console.warn("Service Workers are not supported in this browser.")
}
}
const handleControllerChange = () => {
getRegistration()
}
if ("serviceWorker" in navigator) {
navigator.serviceWorker.addEventListener(
"controllerchange",
handleControllerChange
)
}
getRegistration()
return () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.removeEventListener(
"controllerchange",
handleControllerChange
)
}
}
}, [])
useEffect(() => {
if (swRegistration && swRegistration.pushManager !== undefined) {
swRegistration.pushManager.getSubscription().then((subscription) => {
setIsSubscribed(!!subscription)
setPushSubscription(subscription)
})
Notification.permission === "granted"
? setCanSendPush(true)
: setCanSendPush(false)
}
}, [swRegistration])
return {
isSubscribed,
pushSubscription,
requestPermission,
subscribeToPush,
unsubscribeFromPush,
canSendPush,
}
}

View File

@ -6,7 +6,7 @@ services:
database:
image: postgres
ports:
- "0.0.0.0:5433:5432"
- "5433:5432"
environment:
POSTGRES_PASSWORD: $POSTGRES_PASSWORD
POSTGRES_USER: postgres

202
e2e/install.spec.ts Normal file
View File

@ -0,0 +1,202 @@
import { test, expect, Page } from "@playwright/test"
const { describe, beforeEach, skip, use } = test
function webkitOnly() {
beforeEach(async ({ browserName }) => {
if (browserName !== "webkit") skip()
})
}
describe("when user is on iOS", () => {
webkitOnly()
describe("version 16.4 or higher", () => {
use({
userAgent:
"Mozilla/5.0 (iPhone; CPU iPhone OS 16_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Mobile/15E148 Safari/604.1",
})
describe("and the browser is not safari", () => {
use({
userAgent:
"Mozilla/5.0 (iPhone; U; CPU iPhone OS 16_4 like Mac OS X; en-gb) AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60 Mobile/9B206 Safari/7534.48.3",
})
test("the user is told they need to install through Safari, because reasons, I guess", async ({
page,
}) => {
await page.goto("/")
const safariText = await page.getByText(/Open tackupnow.com in Safari/)
await expect(safariText).toBeAttached()
})
})
test("and tack up now is not running as a PWA, they are instructed to install tack up now", async ({
page,
}) => {
await page.goto("/")
const installText = await page.getByText(/Install Tack Up Now!/)
await expect(installText).toBeAttached()
})
describe("and tack up now is running as a PWA", () => {
beforeEach(async ({ page }) => {
await page.addInitScript(
() => ((window.navigator as any)["standalone"] = true)
)
await stubServiceWorker(page)
})
describe("and notifications aren't enabled", () => {
test("they are asked to enable notifications", async ({ page }) => {
await stubNotifications(page, { permission: "default" })
await page.goto("/")
const enableButton = await page.getByText(/Enable Notifications/)
await expect(enableButton).toBeAttached()
})
describe("and then the user enables notifications", () => {
beforeEach(async ({ page }) => {
await stubNotifications(page, {
permission: "default",
requestPermissionResult: "granted",
})
await page.route("/api/subscribe", async (route) => {
await route.fulfill()
})
})
test("their push token is submitted after notifications are enabled", async ({
page,
}) => {
await page.goto("/")
const requestPromise = page.waitForRequest("/api/subscribe")
await page.getByText(/Enable Notifications/).click()
const request = await requestPromise
await expect(request.postDataJSON()).toEqual({ hi: "subscription" })
})
test("users see tack up now after enabling notifications", async ({
page,
}) => {
await page.goto("/")
const requestPromise = page.waitForRequest("/api/subscribe")
await page.getByText(/Enable Notifications/).click()
await requestPromise
const yourNotificationsHeading =
await page.getByText(/Your Notifications/)
await expect(yourNotificationsHeading).toBeVisible()
})
})
})
describe("and notifications are enabled", () => {
beforeEach(async ({ page }) => {
await stubNotifications(page, { permission: "granted" })
})
test("they aren't asked to enable notifications", async ({ page }) => {
await page.goto("/")
await page.evaluate(async () => await navigator.serviceWorker.ready)
const notificationText = await page.getByText(/Enable Notifications/)
await expect(notificationText).not.toBeAttached()
})
test("users see tack up now", async ({ page }) => {
await page.goto("/")
const yourNotificationsHeading =
await page.getByText(/Your Notifications/)
await expect(yourNotificationsHeading).toBeVisible()
})
})
})
})
describe("version 16.3 and under", () => {
use({
userAgent:
"Mozilla/5.0 (iPhone; CPU iPhone OS 16_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Mobile/15E148 Safari/604.1",
})
test("version 16.3 and under they are informed that their iOS version isn't supported", async ({
page,
}) => {
await page.goto("/")
const sorryText = await page.getByText(/Sorry/)
await expect(sorryText).toBeVisible()
})
})
})
function stubNotifications(
page: Page,
args: {
permission: NotificationPermission
requestPermissionResult?: NotificationPermission
}
) {
return page.addInitScript(
(args: {
permission: NotificationPermission
requestPermissionResult?: NotificationPermission
}) => {
window.Notification = window.Notification ?? {}
Object.defineProperty(window.Notification, "permission", {
value: args.permission,
writable: true,
})
Object.defineProperty(window.Notification, "requestPermission", {
value: () =>
Promise.resolve(args.requestPermissionResult ?? args.permission),
})
},
args
)
}
function stubServiceWorker(page: Page) {
return page.addInitScript(() => {
const registration = {
pushManager: {
getSubscription() {
return Promise.resolve({ hi: "subscription" })
},
subscribe(args: Parameters<PushManager["subscribe"]>[0]) {
return Promise.resolve({ hi: "subscription" })
},
},
}
Object.defineProperty(navigator, "serviceWorker", {
value: {
register() {
return Promise.resolve(registration)
},
getRegistration() {
return Promise.resolve(registration)
},
addEventListener() {},
removeEventListener() {},
},
writable: false,
})
})
}

32
jest.config.ts Normal file
View File

@ -0,0 +1,32 @@
const ignorePatterns = [
"\\/build\\/",
"\\/coverage\\/",
"\\/\\.vscode\\/",
"\\/\\.tmp\\/",
"\\/\\.cache\\/",
"data",
"e2e",
]
module.exports = {
moduleNameMapper: {
"^@web3-storage/multipart-parser$": require.resolve(
"@web3-storage/multipart-parser"
),
"\\?url$": "<rootDir>/url-mock.js",
},
modulePathIgnorePatterns: ignorePatterns,
transform: {
"\\.[jt]sx?$": require.resolve("./transform"),
},
transformIgnorePatterns: [],
watchPathIgnorePatterns: [...ignorePatterns, "\\/node_modules\\/"],
watchPlugins: [
require.resolve("jest-watch-typeahead/filename"),
require.resolve("jest-watch-typeahead/testname"),
],
displayName: "testing",
setupFiles: [],
testEnvironment: "jsdom",
setupFilesAfterEnv: ["./setupTests.ts", "@testing-library/jest-dom"],
}

4553
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -9,9 +9,12 @@
"lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .",
"start": "remix-serve ./build/server/index.js",
"typecheck": "tsc",
"test": "jest --watch"
"watch": "jest --watch --config=jest.config.ts",
"test": "jest --config=jest.config.ts"
},
"dependencies": {
"@remix-pwa/sw": "^3.0.9",
"@remix-pwa/worker-runtime": "^2.1.4",
"@remix-run/express": "^2.9.1",
"@remix-run/node": "^2.9.0",
"@remix-run/react": "^2.9.0",
@ -20,20 +23,37 @@
"express": "^4.19.2",
"isbot": "^4.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"react-dom": "^18.2.0",
"semver": "^7.6.3",
"ua-parser-js": "^1.0.39"
},
"devDependencies": {
"@babel/core": "^7.24.5",
"@babel/plugin-proposal-export-namespace-from": "^7.18.9",
"@babel/plugin-proposal-optional-chaining": "^7.21.0",
"@babel/preset-env": "^7.24.5",
"@babel/preset-react": "^7.24.1",
"@babel/preset-typescript": "^7.24.1",
"@playwright/test": "^1.44.1",
"@remix-pwa/dev": "^3.1.0",
"@remix-run/dev": "^2.9.0",
"@remix-run/testing": "^2.9.1",
"@swc/core": "^1.5.7",
"@swc/jest": "^0.2.36",
"@testing-library/jest-dom": "^6.4.5",
"@testing-library/react": "^15.0.4",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.12",
"@types/node": "^20.14.5",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"@types/semver": "^7.5.8",
"@types/supertest": "^6.0.2",
"@types/ua-parser-js": "^0.7.39",
"@typescript-eslint/eslint-plugin": "^6.7.4",
"@typescript-eslint/parser": "^6.7.4",
"chai": "^4.4.1",
"chai-as-promised": "^7.1.1",
"babel-jest": "^29.7.0",
"babel-plugin-transform-remove-console": "^6.9.4",
"eslint": "^8.38.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.28.1",
@ -41,8 +61,10 @@
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"jest": "^29.7.0",
"sinon": "^17.0.1",
"sinon-chai": "^3.7.0",
"jest-environment-jsdom": "^29.7.0",
"jest-matchmedia-mock": "^1.1.0",
"jest-watch-typeahead": "^2.2.2",
"prettier": "^3.3.3",
"supertest": "^7.0.0",
"ts-node": "^10.9.2",
"typescript": "^5.1.6",
@ -52,4 +74,4 @@
"engines": {
"node": ">=18.0.0"
}
}
}

66
playwright.config.ts Normal file
View File

@ -0,0 +1,66 @@
import { defineConfig, devices } from '@playwright/test';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './e2e',
testMatch: "*.spec.ts",
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://127.0.0.1:5173',
ignoreHTTPSErrors: true,
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
/* Test against mobile viewports. */
{
name: 'Mobile Chrome',
use: { ...devices['Pixel 5'] },
},
{
name: 'Mobile Safari',
use: { ...devices['iPhone 12'] },
},
],
/* Run your local dev server before starting the tests */
webServer: {
command: 'npm run dev',
url: 'http://127.0.0.1:5173',
reuseExistingServer: !process.env.CI,
},
});

BIN
public/images/192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

BIN
public/images/512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

View File

View File

@ -3,15 +3,16 @@ import express from "express"
// notice that the result of `remix vite:build` is "just a module"
import * as build from "./build/server/index.js"
import { subscribe } from "./api/subscribe.js"
const app = express()
app.use(express.static("build/client"))
app.get("/api", (req, res) => res.send("HI"))
app.post("/api/subscribe", subscribe)
// and your app is "just a request handler"
app.all("*", createRequestHandler({ build }))
app.listen(3000, () => {
console.log("App listening on http://localhost:3000")
})

16
setupTests.ts Normal file
View File

@ -0,0 +1,16 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import React from 'react'
import '@testing-library/jest-dom'
const JSDOMFormData = global.FormData;
global.React = React
global.TextDecoder = require("util").TextDecoder;
global.TextEncoder = require("util").TextEncoder;
global.ReadableStream = require("stream/web").ReadableStream;
global.WritableStream = require("stream/web").WritableStream;
require("@remix-run/node").installGlobals({ nativeFetch: true });
global.FormData = JSDOMFormData;

27
thebabel.config.cjs Normal file
View File

@ -0,0 +1,27 @@
module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "18",
},
},
],
"@babel/preset-react",
"@babel/preset-typescript",
],
plugins: [
"@babel/plugin-proposal-export-namespace-from",
"@babel/plugin-proposal-optional-chaining",
// Strip console.debug calls unless REMIX_DEBUG=true
...(process.env.REMIX_DEBUG === "true"
? []
: [
[
"transform-remove-console",
{ exclude: ["error", "warn", "log", "info"] },
],
]),
],
}

24
transform.js Normal file
View File

@ -0,0 +1,24 @@
import babelJest from "babel-jest"
import baseConfig from "./thebabel.config.cjs"
/**
* Replace `import.meta` with `undefined`
*
* Needed to support server-side CJS in Jest
* that access `@remix-run/react`, where `import.meta.hot`
* is used for HMR.
*/
let metaPlugin = ({ types: t }) => ({
visitor: {
MetaProperty: (path) => {
path.replaceWith(t.identifier("undefined"))
},
},
})
export default babelJest.createTransformer({
babelrc: false,
...baseConfig,
plugins: [...baseConfig.plugins, metaPlugin],
})

View File

@ -1,33 +1,19 @@
{
"include": [
"**/*.ts",
"**/*.tsx",
"**/.server/**/*.ts",
"**/.server/**/*.tsx",
"**/.client/**/*.ts",
"**/.client/**/*.tsx"
],
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["dist", "__tests__", "node_modules"],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"types": ["@remix-run/node", "vite/client"],
"isolatedModules": true,
"esModuleInterop": true,
"jsx": "react-jsx",
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"target": "ES2022",
"strict": true,
"allowJs": true,
"module": "ES2022",
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"~/*": ["./app/*"]
},
// Vite takes care of building everything, not tsc.
"noEmit": true
"moduleResolution": "Bundler",
"allowSyntheticDefaultImports": true,
"strict": true,
"jsx": "react",
"declaration": true,
"emitDeclarationOnly": true,
"rootDir": ".",
"outDir": "../../build/node_modules/@remix-run/testing/dist"
}
}
}

1
url-mock.js Normal file
View File

@ -0,0 +1 @@
export default "/path/to/something"

View File

@ -1,10 +1,11 @@
import { vitePlugin as remix } from "@remix-run/dev";
import { installGlobals } from "@remix-run/node";
import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
import { vitePlugin as remix } from "@remix-run/dev"
import { installGlobals } from "@remix-run/node"
import { defineConfig } from "vite"
import tsconfigPaths from "vite-tsconfig-paths"
import { remixPWA } from "@remix-pwa/dev"
installGlobals();
installGlobals()
export default defineConfig({
plugins: [remix(), tsconfigPaths()],
});
plugins: [remix(), tsconfigPaths(), remixPWA()],
})