Ran prettier on all src files now that printWidth is 120.

This commit is contained in:
Jesse Brault 2024-08-08 10:46:49 -05:00
parent 1ded7331ef
commit 111acea22f
18 changed files with 349 additions and 426 deletions

View File

@ -7,11 +7,7 @@ export interface GetImageDeps {
url: string url: string
} }
const getImage = async ({ const getImage = async ({ accessToken, signal, url }: GetImageDeps): Promise<string> => {
accessToken,
signal,
url
}: GetImageDeps): Promise<string> => {
const headers = new Headers() const headers = new Headers()
if (accessToken !== null) { if (accessToken !== null) {
headers.set('Authorization', `Bearer ${accessToken}`) headers.set('Authorization', `Bearer ${accessToken}`)

View File

@ -2,10 +2,7 @@ import { notFound } from '@tanstack/react-router'
import { AuthContextType } from '../auth' import { AuthContextType } from '../auth'
import { ApiError } from './ApiError' import { ApiError } from './ApiError'
import ExpiredTokenError from './ExpiredTokenError' import ExpiredTokenError from './ExpiredTokenError'
import FullRecipeView, { import FullRecipeView, { RawFullRecipeView, toFullRecipeView } from './types/FullRecipeView'
RawFullRecipeView,
toFullRecipeView
} from './types/FullRecipeView'
export interface GetRecipeDeps { export interface GetRecipeDeps {
authContext: AuthContextType authContext: AuthContextType
@ -14,24 +11,16 @@ export interface GetRecipeDeps {
abortSignal: AbortSignal abortSignal: AbortSignal
} }
const getRecipe = async ({ const getRecipe = async ({ authContext, username, slug, abortSignal }: GetRecipeDeps): Promise<FullRecipeView> => {
authContext,
username,
slug,
abortSignal
}: GetRecipeDeps): Promise<FullRecipeView> => {
const headers = new Headers() const headers = new Headers()
if (authContext.token !== null) { if (authContext.token !== null) {
headers.set('Authorization', `Bearer ${authContext.token}`) headers.set('Authorization', `Bearer ${authContext.token}`)
} }
const response = await fetch( const response = await fetch(import.meta.env.VITE_MME_API_URL + `/recipes/${username}/${slug}`, {
import.meta.env.VITE_MME_API_URL + `/recipes/${username}/${slug}`,
{
signal: abortSignal, signal: abortSignal,
headers, headers,
mode: 'cors' mode: 'cors'
} })
)
if (response.ok) { if (response.ok) {
return toFullRecipeView((await response.json()) as RawFullRecipeView) return toFullRecipeView((await response.json()) as RawFullRecipeView)
} else if (response.status === 401) { } else if (response.status === 401) {

View File

@ -20,18 +20,13 @@ const getRecipeInfos = async ({
if (token !== null) { if (token !== null) {
headers.set('Authorization', `Bearer ${token}`) headers.set('Authorization', `Bearer ${token}`)
} }
const response = await fetch( const response = await fetch(import.meta.env.VITE_MME_API_URL + `/recipes?page=${pageNumber}&size=${pageSize}`, {
import.meta.env.VITE_MME_API_URL +
`/recipes?page=${pageNumber}&size=${pageSize}`,
{
signal: abortSignal, signal: abortSignal,
headers, headers,
mode: 'cors' mode: 'cors'
} })
)
if (response.ok) { if (response.ok) {
const { pageNumber, pageSize, content } = const { pageNumber, pageSize, content } = (await response.json()) as RawRecipeInfosView
(await response.json()) as RawRecipeInfosView
return { return {
pageNumber, pageNumber,
pageSize, pageSize,

View File

@ -1,13 +1,8 @@
import { LoginResult, RawLoginView } from './types/LoginView' import { LoginResult, RawLoginView } from './types/LoginView'
const login = async ( const login = async (username: string, password: string): Promise<LoginResult> => {
username: string,
password: string
): Promise<LoginResult> => {
try { try {
const response = await fetch( const response = await fetch(import.meta.env.VITE_MME_API_URL + '/auth/login', {
import.meta.env.VITE_MME_API_URL + '/auth/login',
{
body: JSON.stringify({ username, password }), body: JSON.stringify({ username, password }),
credentials: 'include', credentials: 'include',
headers: { headers: {
@ -15,14 +10,9 @@ const login = async (
}, },
method: 'POST', method: 'POST',
mode: 'cors' mode: 'cors'
} })
)
if (response.ok) { if (response.ok) {
const { const { username, accessToken, expires: rawExpires } = (await response.json()) as RawLoginView
username,
accessToken,
expires: rawExpires
} = (await response.json()) as RawLoginView
return { return {
_tag: 'success', _tag: 'success',
loginView: { loginView: {
@ -36,13 +26,10 @@ const login = async (
if (response.status === 401) { if (response.status === 401) {
error = 'Invalid username or password.' error = 'Invalid username or password.'
} else if (response.status === 500) { } else if (response.status === 500) {
error = error = 'There was an internal server error. Please try again later.'
'There was an internal server error. Please try again later.'
} else { } else {
error = 'Unknown error.' error = 'Unknown error.'
console.error( console.error(`Unknown error: ${response.status} ${response.statusText}`)
`Unknown error: ${response.status} ${response.statusText}`
)
} }
return { return {
_tag: 'failure', _tag: 'failure',

View File

@ -11,14 +11,11 @@ export class ExpiredRefreshTokenError extends ApiError {
const refresh = async (): Promise<LoginView> => { const refresh = async (): Promise<LoginView> => {
let response: Response let response: Response
try { try {
response = await fetch( response = await fetch(import.meta.env.VITE_MME_API_URL + '/auth/refresh', {
import.meta.env.VITE_MME_API_URL + '/auth/refresh',
{
credentials: 'include', credentials: 'include',
method: 'POST', method: 'POST',
mode: 'cors' mode: 'cors'
} })
)
} catch (fetchError) { } catch (fetchError) {
if (fetchError instanceof TypeError) { if (fetchError instanceof TypeError) {
throw fetchError // rethrow network issues throw fetchError // rethrow network issues
@ -27,11 +24,7 @@ const refresh = async (): Promise<LoginView> => {
} }
} }
if (response.ok) { if (response.ok) {
const { const { username, accessToken, expires: rawExpires } = (await response.json()) as RawLoginView
username,
accessToken,
expires: rawExpires
} = (await response.json()) as RawLoginView
return { return {
username, username,
accessToken, accessToken,

View File

@ -32,12 +32,7 @@ const RecipeCard = ({
slug slug
}} }}
> >
<img <img className={classes.recipeImage} src={mainImageUrl} alt={mainImageAlt} title={mainImageAlt} />
className={classes.recipeImage}
src={mainImageUrl}
alt={mainImageAlt}
title={mainImageAlt}
/>
</Link> </Link>
<div className={classes.infoContainer}> <div className={classes.infoContainer}>
<div className={classes.infoRow}> <div className={classes.infoRow}>

View File

@ -7,17 +7,9 @@ export interface RecipeVisibilityIconProps {
const RecipeVisibilityIcon = ({ isPublic }: RecipeVisibilityIconProps) => const RecipeVisibilityIcon = ({ isPublic }: RecipeVisibilityIconProps) =>
isPublic ? ( isPublic ? (
<FontAwesomeIcon <FontAwesomeIcon icon="globe" className={classes.recipeVisibilityIcon} size="sm" />
icon="globe"
className={classes.recipeVisibilityIcon}
size="sm"
/>
) : ( ) : (
<FontAwesomeIcon <FontAwesomeIcon icon="lock" className={classes.recipeVisibilityIcon} size="sm" />
icon="lock"
className={classes.recipeVisibilityIcon}
size="sm"
/>
) )
export default RecipeVisibilityIcon export default RecipeVisibilityIcon

View File

@ -1,10 +1,4 @@
import { import { createFileRoute, redirect, useNavigate, useRouter, useSearch } from '@tanstack/react-router'
createFileRoute,
redirect,
useNavigate,
useRouter,
useSearch
} from '@tanstack/react-router'
import { FormEvent, useState } from 'react' import { FormEvent, useState } from 'react'
import { z } from 'zod' import { z } from 'zod'
import login from '../api/login' import login from '../api/login'
@ -25,17 +19,13 @@ const Login = () => {
const password = (formData.get('password') as string | null) ?? '' const password = (formData.get('password') as string | null) ?? ''
const loginResult = await login(username, password) const loginResult = await login(username, password)
if (loginResult._tag === 'success') { if (loginResult._tag === 'success') {
auth.putToken( auth.putToken(loginResult.loginView.accessToken, loginResult.loginView.username, async () => {
loginResult.loginView.accessToken,
loginResult.loginView.username,
async () => {
await router.invalidate() await router.invalidate()
await navigate({ await navigate({
to: redirect ?? '/recipes', to: redirect ?? '/recipes',
search: {} search: {}
}) })
} })
)
} else { } else {
setError(loginResult.error) setError(loginResult.error)
} }
@ -44,9 +34,7 @@ const Login = () => {
return ( return (
<div> <div>
<h2>Login Page</h2> <h2>Login Page</h2>
{expired ? ( {expired ? <p>Your session has expired. Please login again.</p> : null}
<p>Your session has expired. Please login again.</p>
) : null}
<form onSubmit={onSubmit}> <form onSubmit={onSubmit}>
<label htmlFor="username">Username</label> <label htmlFor="username">Username</label>
<input id="username" name="username" type="text" /> <input id="username" name="username" type="text" />

View File

@ -38,11 +38,7 @@ export const Route = createFileRoute('/recipes/$username/$slug')({
} = useQuery( } = useQuery(
{ {
enabled: recipe !== undefined, enabled: recipe !== undefined,
queryKey: [ queryKey: ['images', recipe?.mainImage.owner.username, recipe?.mainImage.filename],
'images',
recipe?.mainImage.owner.username,
recipe?.mainImage.filename
],
queryFn: ({ signal }) => queryFn: ({ signal }) =>
getImage({ getImage({
accessToken: authContext.token, accessToken: authContext.token,

View File

@ -1,40 +1,34 @@
import React from 'react'; import React from 'react'
import './button.css'; import './button.css'
interface ButtonProps { interface ButtonProps {
/** /**
* Is this the principal call to action on the page? * Is this the principal call to action on the page?
*/ */
primary?: boolean; primary?: boolean
/** /**
* What background color to use * What background color to use
*/ */
backgroundColor?: string; backgroundColor?: string
/** /**
* How large should the button be? * How large should the button be?
*/ */
size?: 'small' | 'medium' | 'large'; size?: 'small' | 'medium' | 'large'
/** /**
* Button contents * Button contents
*/ */
label: string; label: string
/** /**
* Optional click handler * Optional click handler
*/ */
onClick?: () => void; onClick?: () => void
} }
/** /**
* Primary UI component for user interaction * Primary UI component for user interaction
*/ */
export const Button = ({ export const Button = ({ primary = false, size = 'medium', backgroundColor, label, ...props }: ButtonProps) => {
primary = false, const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary'
size = 'medium',
backgroundColor,
label,
...props
}: ButtonProps) => {
const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
return ( return (
<button <button
type="button" type="button"
@ -44,5 +38,5 @@ export const Button = ({
> >
{label} {label}
</button> </button>
); )
}; }

View File

@ -1,21 +1,22 @@
import { Meta } from "@storybook/blocks"; import { Meta } from '@storybook/blocks'
import Github from "./assets/github.svg"; import Github from './assets/github.svg'
import Discord from "./assets/discord.svg"; import Discord from './assets/discord.svg'
import Youtube from "./assets/youtube.svg"; import Youtube from './assets/youtube.svg'
import Tutorials from "./assets/tutorials.svg"; import Tutorials from './assets/tutorials.svg'
import Styling from "./assets/styling.png"; import Styling from './assets/styling.png'
import Context from "./assets/context.png"; import Context from './assets/context.png'
import Assets from "./assets/assets.png"; import Assets from './assets/assets.png'
import Docs from "./assets/docs.png"; import Docs from './assets/docs.png'
import Share from "./assets/share.png"; import Share from './assets/share.png'
import FigmaPlugin from "./assets/figma-plugin.png"; import FigmaPlugin from './assets/figma-plugin.png'
import Testing from "./assets/testing.png"; import Testing from './assets/testing.png'
import Accessibility from "./assets/accessibility.png"; import Accessibility from './assets/accessibility.png'
import Theming from "./assets/theming.png"; import Theming from './assets/theming.png'
import AddonLibrary from "./assets/addon-library.png"; import AddonLibrary from './assets/addon-library.png'
export const RightArrow = () => <svg export const RightArrow = () => (
<svg
viewBox="0 0 14 14" viewBox="0 0 14 14"
width="8px" width="8px"
height="14px" height="14px"
@ -27,9 +28,10 @@ export const RightArrow = () => <svg
fill: 'currentColor', fill: 'currentColor',
'path fill': 'currentColor' 'path fill': 'currentColor'
}} }}
> >
<path d="m11.1 7.35-5.5 5.5a.5.5 0 0 1-.7-.7L10.04 7 4.9 1.85a.5.5 0 1 1 .7-.7l5.5 5.5c.2.2.2.5 0 .7Z" /> <path d="m11.1 7.35-5.5 5.5a.5.5 0 0 1-.7-.7L10.04 7 4.9 1.85a.5.5 0 1 1 .7-.7l5.5 5.5c.2.2.2.5 0 .7Z" />
</svg> </svg>
)
<Meta title="Configure your project" /> <Meta title="Configure your project" />
@ -38,6 +40,7 @@ export const RightArrow = () => <svg
# Configure your project # Configure your project
Because Storybook works separately from your app, you'll need to configure it for your specific stack and setup. Below, explore guides for configuring Storybook with popular frameworks and tools. If you get stuck, learn how you can ask for help from our community. Because Storybook works separately from your app, you'll need to configure it for your specific stack and setup. Below, explore guides for configuring Storybook with popular frameworks and tools. If you get stuck, learn how you can ask for help from our community.
</div> </div>
<div className="sb-section"> <div className="sb-section">
<div className="sb-section-item"> <div className="sb-section-item">
@ -84,6 +87,7 @@ export const RightArrow = () => <svg
# Do more with Storybook # Do more with Storybook
Now that you know the basics, let's explore other parts of Storybook that will improve your experience. This list is just to get you started. You can customise Storybook in many ways to fit your needs. Now that you know the basics, let's explore other parts of Storybook that will improve your experience. This list is just to get you started. You can customise Storybook in many ways to fit your needs.
</div> </div>
<div className="sb-section"> <div className="sb-section">
@ -203,6 +207,7 @@ export const RightArrow = () => <svg
target="_blank" target="_blank"
>Discover tutorials<RightArrow /></a> >Discover tutorials<RightArrow /></a>
</div> </div>
</div> </div>
<style> <style>

View File

@ -1,7 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react'
import { fn } from '@storybook/test'; import { fn } from '@storybook/test'
import { Header } from './Header'; import { Header } from './Header'
const meta = { const meta = {
title: 'Example/Header', title: 'Example/Header',
@ -10,24 +10,24 @@ const meta = {
tags: ['autodocs'], tags: ['autodocs'],
parameters: { parameters: {
// More on how to position stories at: https://storybook.js.org/docs/configure/story-layout // More on how to position stories at: https://storybook.js.org/docs/configure/story-layout
layout: 'fullscreen', layout: 'fullscreen'
}, },
args: { args: {
onLogin: fn(), onLogin: fn(),
onLogout: fn(), onLogout: fn(),
onCreateAccount: fn(), onCreateAccount: fn()
}, }
} satisfies Meta<typeof Header>; } satisfies Meta<typeof Header>
export default meta; export default meta
type Story = StoryObj<typeof meta>; type Story = StoryObj<typeof meta>
export const LoggedIn: Story = { export const LoggedIn: Story = {
args: { args: {
user: { user: {
name: 'Jane Doe', name: 'Jane Doe'
}, }
}, }
}; }
export const LoggedOut: Story = {}; export const LoggedOut: Story = {}

View File

@ -1,17 +1,17 @@
import React from 'react'; import React from 'react'
import { Button } from './Button'; import { Button } from './Button'
import './header.css'; import './header.css'
type User = { type User = {
name: string; name: string
}; }
interface HeaderProps { interface HeaderProps {
user?: User; user?: User
onLogin?: () => void; onLogin?: () => void
onLogout?: () => void; onLogout?: () => void
onCreateAccount?: () => void; onCreateAccount?: () => void
} }
export const Header = ({ user, onLogin, onLogout, onCreateAccount }: HeaderProps) => ( export const Header = ({ user, onLogin, onLogout, onCreateAccount }: HeaderProps) => (
@ -24,14 +24,8 @@ export const Header = ({ user, onLogin, onLogout, onCreateAccount }: HeaderProps
d="M10 0h12a10 10 0 0110 10v12a10 10 0 01-10 10H10A10 10 0 010 22V10A10 10 0 0110 0z" d="M10 0h12a10 10 0 0110 10v12a10 10 0 01-10 10H10A10 10 0 010 22V10A10 10 0 0110 0z"
fill="#FFF" fill="#FFF"
/> />
<path <path d="M5.3 10.6l10.4 6v11.1l-10.4-6v-11zm11.4-6.2l9.7 5.5-9.7 5.6V4.4z" fill="#555AB9" />
d="M5.3 10.6l10.4 6v11.1l-10.4-6v-11zm11.4-6.2l9.7 5.5-9.7 5.6V4.4z" <path d="M27.2 10.6v11.2l-10.5 6V16.5l10.5-6zM15.7 4.4v11L6 10l9.7-5.5z" fill="#91BAF8" />
fill="#555AB9"
/>
<path
d="M27.2 10.6v11.2l-10.5 6V16.5l10.5-6zM15.7 4.4v11L6 10l9.7-5.5z"
fill="#91BAF8"
/>
</g> </g>
</svg> </svg>
<h1>Acme</h1> <h1>Acme</h1>
@ -53,4 +47,4 @@ export const Header = ({ user, onLogin, onLogout, onCreateAccount }: HeaderProps
</div> </div>
</div> </div>
</header> </header>
); )

View File

@ -1,32 +1,32 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react'
import { within, userEvent, expect } from '@storybook/test'; import { within, userEvent, expect } from '@storybook/test'
import { Page } from './Page'; import { Page } from './Page'
const meta = { const meta = {
title: 'Example/Page', title: 'Example/Page',
component: Page, component: Page,
parameters: { parameters: {
// More on how to position stories at: https://storybook.js.org/docs/configure/story-layout // More on how to position stories at: https://storybook.js.org/docs/configure/story-layout
layout: 'fullscreen', layout: 'fullscreen'
}, }
} satisfies Meta<typeof Page>; } satisfies Meta<typeof Page>
export default meta; export default meta
type Story = StoryObj<typeof meta>; type Story = StoryObj<typeof meta>
export const LoggedOut: Story = {}; export const LoggedOut: Story = {}
// More on interaction testing: https://storybook.js.org/docs/writing-tests/interaction-testing // More on interaction testing: https://storybook.js.org/docs/writing-tests/interaction-testing
export const LoggedIn: Story = { export const LoggedIn: Story = {
play: async ({ canvasElement }) => { play: async ({ canvasElement }) => {
const canvas = within(canvasElement); const canvas = within(canvasElement)
const loginButton = canvas.getByRole('button', { name: /Log in/i }); const loginButton = canvas.getByRole('button', { name: /Log in/i })
await expect(loginButton).toBeInTheDocument(); await expect(loginButton).toBeInTheDocument()
await userEvent.click(loginButton); await userEvent.click(loginButton)
await expect(loginButton).not.toBeInTheDocument(); await expect(loginButton).not.toBeInTheDocument()
const logoutButton = canvas.getByRole('button', { name: /Log out/i }); const logoutButton = canvas.getByRole('button', { name: /Log out/i })
await expect(logoutButton).toBeInTheDocument(); await expect(logoutButton).toBeInTheDocument()
}, }
}; }

View File

@ -1,14 +1,14 @@
import React from 'react'; import React from 'react'
import { Header } from './Header'; import { Header } from './Header'
import './page.css'; import './page.css'
type User = { type User = {
name: string; name: string
}; }
export const Page: React.FC = () => { export const Page: React.FC = () => {
const [user, setUser] = React.useState<User>(); const [user, setUser] = React.useState<User>()
return ( return (
<article> <article>
@ -29,18 +29,17 @@ export const Page: React.FC = () => {
process starting with atomic components and ending with pages. process starting with atomic components and ending with pages.
</p> </p>
<p> <p>
Render pages with mock data. This makes it easy to build and review page states without Render pages with mock data. This makes it easy to build and review page states without needing to
needing to navigate to them in your app. Here are some handy patterns for managing page navigate to them in your app. Here are some handy patterns for managing page data in Storybook:
data in Storybook:
</p> </p>
<ul> <ul>
<li> <li>
Use a higher-level connected component. Storybook helps you compose such data from the Use a higher-level connected component. Storybook helps you compose such data from the "args" of
"args" of child component stories child component stories
</li> </li>
<li> <li>
Assemble data in the page component from your services. You can mock these services out Assemble data in the page component from your services. You can mock these services out using
using Storybook. Storybook.
</li> </li>
</ul> </ul>
<p> <p>
@ -69,5 +68,5 @@ export const Page: React.FC = () => {
</div> </div>
</section> </section>
</article> </article>
); )
}; }