wip add button and feed stuff

This commit is contained in:
john 2025-05-03 23:40:30 +02:00
parent 38d09a582c
commit 1c2d6d60a6
11 changed files with 211 additions and 46 deletions

View file

@ -1,10 +1,12 @@
import { AuthorPage } from './pages/AuthorPage.tsx'
import { BrowserRouter, Route, Routes } from 'react-router'
import HomePage from './pages/HomePage.tsx'
import AuthorPage from './pages/AuthorPage.tsx'
function App() {
return (
<BrowserRouter>
<Routes>
<Route path={'/'} element={<HomePage />} />
<Route path="/u/:username" element={<AuthorPage />} />
</Routes>
</BrowserRouter>

View file

@ -8,17 +8,35 @@ console.debug('API HOST IS', ApiHost)
export async function loadPostsForAuthor(
authorId: string,
count?: number,
cursor?: string,
cursor: string | null,
amount: number | null,
): Promise<components['schemas']['GetAuthorPostsResponse']> {
const url = new URL(`authors/${authorId}/posts`, ApiHost)
if (count != null) url.searchParams.set('count', count.toString())
if (amount != null) url.searchParams.set('amount', amount.toString())
if (cursor != null) url.searchParams.set('cursor', cursor)
const res = await doGetRequest(url)
return res as components['schemas']['GetAuthorPostsResponse']
}
export async function loadPublicFeed(
cursor: string | null,
amount: number | null,
): Promise<components['schemas']['GetAllPublicPostsResponse']> {
const url = new URL(`posts`, ApiHost)
if (amount != null) url.searchParams.set('amount', amount.toString())
if (cursor) url.searchParams.set('cursor', cursor)
const request = new Request(url)
const res = await doGetRequest(url)
const response = await fetch(request)
return res as components['schemas']['GetAllPublicPostsResponse']
}
async function doGetRequest(url: URL): Promise<unknown> {
const response = await fetch(new Request(url))
if (!response.ok) throw new Error(await response.text())

View file

@ -6,7 +6,31 @@ export interface paths {
path?: never
cookie?: never
}
get?: never
get: {
parameters: {
query?: {
Cursor?: string
Amount?: number
}
header?: never
path?: never
cookie?: never
}
requestBody?: never
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown
}
content: {
'text/plain': components['schemas']['GetAllPublicPostsResponse']
'application/json': components['schemas']['GetAllPublicPostsResponse']
'text/json': components['schemas']['GetAllPublicPostsResponse']
}
}
}
}
put?: never
post: {
parameters: {
@ -53,7 +77,7 @@ export interface paths {
parameters: {
query?: {
Cursor?: string
Count?: number
Amount?: number
}
header?: never
path: {
@ -106,9 +130,26 @@ export interface components {
/** Format: uuid */
postId: string
}
GetAllPublicPostsResponse: {
posts: components['schemas']['PublicPostDto'][]
}
GetAuthorPostsResponse: {
posts: components['schemas']['AuthorPostDto'][]
}
PublicPostAuthorDto: {
/** Format: uuid */
authorId: string
username: string
}
PublicPostDto: {
authorDto: components['schemas']['PublicPostAuthorDto']
/** Format: uuid */
postId: string
content: string
media: string[]
/** Format: date-time */
createdAt: string
}
}
responses: never
parameters: never

View file

@ -5,17 +5,7 @@ interface PostsFeedProps {
posts: Post[]
}
export function PostsFeed({ posts }: PostsFeedProps) {
const formatDate = (date: Temporal.PlainDateTime) => {
return date.toLocaleString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}
export default function PostsFeed({ posts }: PostsFeedProps) {
return (
<div className="flex flex-col gap-6 w-full">
{posts.map((post) => (
@ -36,3 +26,13 @@ export function PostsFeed({ posts }: PostsFeedProps) {
</div>
)
}
function formatDate(date: Temporal.PlainDateTime) {
return date.toLocaleString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}

View file

@ -1,7 +1,9 @@
import { useEffect, useState } from 'react'
export function useAsyncState<T>(loader: () => Promise<T>): T | undefined {
const [state, setState] = useState<T>()
export function useAsyncState<T>(loader: () => Promise<T>): T | undefined
export function useAsyncState<T>(loader: () => Promise<T>, defaultValue: T): T
export function useAsyncState<T>(loader: () => Promise<T>, defaultValue?: T): T | undefined {
const [state, setState] = useState<T>(defaultValue as T)
useEffect(() => {
setTimeout(async () => {

View file

@ -7,10 +7,3 @@
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
margin: 0;
width: 100vw;
height: 100vh;
}

View file

@ -1,25 +1,20 @@
import { PostsFeed } from '../components/PostsFeed.tsx'
import { useCallback } from 'react'
import { useParams } from 'react-router'
import { loadPostsForAuthor } from '../api/api.ts'
import { useAsyncState } from '../hooks/useAsyncData.ts'
import { Post } from '../model/posts/posts.ts'
import './FeedView.css'
import FeedView from './FeedView.tsx'
export function AuthorPage() {
export default function AuthorPage() {
const { username } = useParams()
const fetchPosts = useCallback(async () => {
const result = await loadPostsForAuthor(username!)
const fetchPosts = useCallback(
async (cursor: string | null, amount: number | null) => {
const result = await loadPostsForAuthor(username!, cursor, amount)
return result.posts.map((post) => Post.fromDto(post))
}, [username])
const posts = useAsyncState(fetchPosts)
return (
<main className={`w-full max-w-full md:flex md:justify-center`}>
<div className="w-full md:w-lg md:max-w-lg md:ml-8">
<PostsFeed posts={posts ?? []} />
</div>
</main>
},
[username],
)
return <FeedView loadPosts={fetchPosts} />
}

6
src/pages/FeedView.css Normal file
View file

@ -0,0 +1,6 @@
@media (width >= 48rem) {
main {
display: grid;
grid-template-columns: 1.618fr 1fr;
}
}

94
src/pages/FeedView.tsx Normal file
View file

@ -0,0 +1,94 @@
import { Post } from '../model/posts/posts.ts'
import PostsFeed from '../components/PostsFeed.tsx'
import { useCallback, useEffect, useRef, useState } from 'react'
import './FeedView.css'
// Stub for spinner component
const Spinner = () => (
<div className="animate-spin h-5 w-5 border-2 border-gray-500 rounded-full border-t-transparent"></div>
)
const PageSize = 2
interface FeedViewProps {
loadPosts: (cursor: string | null, amount: number) => Promise<Post[]>
}
export default function FeedView({ loadPosts }: FeedViewProps) {
const [pages, setPages] = useState<Post[][]>([])
const posts = pages.flat()
const [hasMore, setHasMore] = useState(true)
const cursor = useRef<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
const loading = useRef(false)
const loadNextPage = useCallback(async () => {
if (loading.current) return
loading.current = true
setIsLoading(true)
try {
const page = await loadPosts(cursor.current, PageSize)
if (page.length < PageSize) {
setHasMore(false)
}
cursor.current = page.at(-1)?.postId ?? null
setPages((prev) => [...prev, page])
} finally {
setIsLoading(false)
loading.current = false
}
}, [loadPosts])
useEffect(() => {
const timeoutId = setTimeout(async () => {
await loadNextPage()
})
return () => {
clearTimeout(timeoutId)
}
}, [loadNextPage])
const loadButtonState = isLoading ? 'loading' : hasMore ? 'ready' : 'done'
return (
<main className={`w-full max-w-full px-12 py-6`}>
<div className={`col-start-1`}>
<PostsFeed posts={posts} />
<LoadMoreButton state={loadButtonState} onClick={loadNextPage} />
</div>
</main>
)
}
interface LoadMoreButtonProps {
state: 'ready' | 'loading' | 'done'
onClick: () => void
}
function LoadMoreButton({ state, onClick }: LoadMoreButtonProps) {
const buttonClasses =
'w-full py-3 px-4 bg-gray-100 hover:bg-gray-200 text-gray-800 rounded-md flex items-center justify-center disabled:opacity-70'
switch (state) {
case 'done':
return <div className="text-center text-gray-400 py-4">that's all...</div>
case 'loading':
return (
<button disabled={true} className={buttonClasses}>
<Spinner />
</button>
)
case 'ready':
return (
<button className={buttonClasses} onClick={onClick}>
Load more
</button>
)
}
}

14
src/pages/HomePage.tsx Normal file
View file

@ -0,0 +1,14 @@
import { useCallback } from 'react'
import { Post } from '../model/posts/posts.ts'
import './FeedView.css'
import { loadPublicFeed } from '../api/api.ts'
import FeedView from './FeedView.tsx'
export default function HomePage() {
const fetchPosts = useCallback(async (cursor: string | null, amount: number | null) => {
const result = await loadPublicFeed(cursor, amount)
return result.posts.map((post) => Post.fromDto(post))
}, [])
return <FeedView loadPosts={fetchPosts} />
}

View file

@ -1,9 +1,9 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"lib": ["ESNext", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,