feat: added pagination for MediaList component

This commit is contained in:
overflowerror 2021-10-10 16:31:17 +02:00
parent e05e897fa8
commit fbdc8df6e6
4 changed files with 66 additions and 8 deletions

View file

@ -1,20 +1,43 @@
import React, {FunctionComponent} from "react";
import React, {FunctionComponent, useEffect, useState} from "react";
import {MediaFile} from "../../database/file";
import MediaListItem from "../MediaListItem";
import {Query} from "../../database/query";
import PageControl from "../PageControl";
const pageLimit = 10
export type MediaListProps = {
basePath: string,
files: MediaFile[],
query: Query,
onSelect: (file: MediaFile) => void
}
const MediaList: FunctionComponent<MediaListProps> = ({basePath, files, onSelect}) => {
const MediaList: FunctionComponent<MediaListProps> = ({basePath, query, onSelect}) => {
const [size, setSize] = useState<number>(0)
const [page, setPage] = useState<number>(0)
useEffect(() => {
if (size != query.count()) {
setSize(query.count())
setPage(0)
}
}, [query])
const files = query.limit(pageLimit, page * pageLimit).get()
const maxPage = Math.floor((size - 1) / pageLimit)
return (
<div>
{
files.map(f => (
<MediaListItem key={f.getPath()} basePath={basePath} file={f} onClick={onSelect} />
))
{ size > 0 &&
<>
<PageControl current={page} max={maxPage} onChange={setPage} />
{
files.map(f => (
<MediaListItem key={f.getPath()} basePath={basePath} file={f} onClick={onSelect}/>
))
}
<PageControl current={page} max={maxPage} onChange={setPage} />
</>
}
</div>
)

View file

@ -0,0 +1,29 @@
import React, {FunctionComponent} from "react";
export type PageControlProps = {
current: number,
max: number,
onChange: (page: number) => void
}
const PageControl: FunctionComponent<PageControlProps> = ({current, max, onChange}) => {
return (
<div>
<button
onClick={() => onChange(current - 1)}
disabled={current == 0}
>
Prev
</button>
page {current + 1} of {max + 1}
<button
onClick={() => onChange(current + 1)}
disabled={current == max}
>
Next
</button>
</div>
)
}
export default PageControl

View file

@ -46,6 +46,12 @@ export class Query {
)
}
public limit(limit: number, offset: number = 0) {
return new Query(
this.files.slice(offset, limit + offset)
)
}
public is(type: MediaFileType): Query {
return new Query(
this.files.filter(f => f.getType() == type)

View file

@ -131,7 +131,7 @@ const Home: FunctionComponent<HomeProps> = () => {
{untagged.length} untagged files
</a>
}
<MediaList basePath={basePath} files={query.get()} onSelect={setSelected} />
<MediaList basePath={basePath} query={query} onSelect={setSelected} />
</>
}
</>