Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use RTK Query for nodes state #449

Merged
merged 12 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion papermerge/core/routers/tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,24 @@

logger = logging.getLogger(__name__)

@router.get("/all", response_model=list[schemas.Tag])
@utils.docstring_parameter(scope=scopes.TAG_VIEW)
def retrieve_tags_without_pagination(
user: Annotated[
schemas.User,
Security(get_current_user, scopes=[scopes.TAG_VIEW])
]
):
"""Retrieves (without pagination) tags of the current user

Required scope: `{scope}`
"""
order_by = ['name', ]

return Tag.objects.filter(
user_id=user.id
).order_by(*order_by)


@router.get("/", response_model=PaginatorGeneric[schemas.Tag])
@paginate
Expand All @@ -30,7 +48,7 @@ def retrieve_tags(
],
params: CommonQueryParams = Depends(),
):
"""Retrieves current user tags
"""Retrieves (paginated) tags of the current user

Required scope: `{scope}`
"""
Expand Down
6 changes: 6 additions & 0 deletions ui2/src/app/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {useDispatch, useSelector} from "react-redux"
import type {AppDispatch, RootState} from "./types"

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
export const useAppSelector = useSelector.withTypes<RootState>()
2 changes: 2 additions & 0 deletions ui2/src/app/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import navBarReducer from "@/slices/navBar"
import tagsReducer from "@/features/tags/tagsSlice"
import groupsReducer from "@/features/groups/groupsSlice"
import usersReducer from "@/features/users/usersSlice"
import nodesReducer from "@/features/nodes/nodesSlice"
import {uploaderReducer} from "@/slices/uploader"
import sizesSliceReducer from "@/slices/sizes"
import dragndropReducer from "@/slices/dragndrop"
Expand All @@ -23,6 +24,7 @@ export const store = configureStore({
uploader: uploaderReducer,
sizes: sizesSliceReducer,
dragndrop: dragndropReducer,
nodes: nodesReducer,
[apiSlice.reducerPath]: apiSlice.reducer
},
middleware: getDefaultMiddleware =>
Expand Down
26 changes: 12 additions & 14 deletions ui2/src/components/Breadcrumbs/Breadcrumbs.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {useContext, useEffect, useRef} from "react"
import {useSelector, useDispatch} from "react-redux"
import {useAppSelector, useAppDispatch} from "@/app/hooks"
import {
Breadcrumbs,
Skeleton,
Expand All @@ -15,35 +15,32 @@ import {IconHome, IconInbox, IconChevronDown} from "@tabler/icons-react"
import classes from "./Breadcrumbs.module.css"

import {
selectPanelBreadcrumbs,
selectPanelNodesStatus
selectPanelNodesStatus,
selectCurrentFolderID
} from "@/slices/dualPanel/dualPanel"
import {updateBreadcrumb} from "@/slices/sizes"

import type {PanelMode, NType, UserDetails} from "@/types"
import type {RootState} from "@/app/types"

import PanelContext from "@/contexts/PanelContext"
import {selectCurrentUser} from "@/slices/currentUser"
import {equalUUIDs} from "@/utils"
import {useGetFolderQuery} from "@/features/nodes/apiSlice"

type Args = {
onClick: (node: NType) => void
className?: string
}

export default function BreadcrumbsComponent({onClick, className}: Args) {
const dispatch = useDispatch()
const dispatch = useAppDispatch()
const {height, width} = useViewportSize()
const ref = useRef<HTMLDivElement>(null)
const mode: PanelMode = useContext(PanelContext)
const nodesStatus = useSelector((state: RootState) =>
selectPanelNodesStatus(state, mode)
)
const nodesStatus = useAppSelector(s => selectPanelNodesStatus(s, mode))
const currentNodeID = useAppSelector(s => selectCurrentFolderID(s, mode))

const items = useSelector<RootState>(state =>
selectPanelBreadcrumbs(state, mode)
) as Array<[string, string]> | null | undefined
const {data, isLoading} = useGetFolderQuery(currentNodeID!)

const onRootElementClick = (n: NType) => {
onClick(n)
Expand All @@ -62,14 +59,15 @@ export default function BreadcrumbsComponent({onClick, className}: Args) {
}
}, [width, height])

if (!items) {
if (isLoading || !data) {
return (
<Skeleton width={"25%"} my="md">
<Skeleton ref={ref} width={"25%"} my="md">
<Breadcrumbs>{["one", "two"]}</Breadcrumbs>
</Skeleton>
)
}

const items = data.breadcrumb
const links = items.slice(1, -1).map(i => (
<Anchor key={i[0]} onClick={() => onClick({id: i[0], ctype: "folder"})}>
{i[1]}
Expand Down Expand Up @@ -106,7 +104,7 @@ type RootItemArgs = {
}

function RootItem({itemId, onClick}: RootItemArgs) {
const user = useSelector(selectCurrentUser) as UserDetails | undefined
const user = useAppSelector(selectCurrentUser) as UserDetails | undefined

const onLocalClick = (id: string) => {
onClick({id: id, ctype: "folder"})
Expand Down
103 changes: 32 additions & 71 deletions ui2/src/components/Commander/Commander.tsx
Original file line number Diff line number Diff line change
@@ -1,90 +1,63 @@
import {useContext, useState} from "react"
import {Group, Stack, Box} from "@mantine/core"

import {useSelector, useDispatch} from "react-redux"
import {useAppSelector, useAppDispatch} from "@/app/hooks"
import {useNavigate} from "react-router-dom"

import FolderNodeActions from "@/components/Commander/FolderNodeActions"
import Node from "@/components/Node"
import {
selectPanelNodes,
setCurrentNode,
fetchPaginatedNodes,
selectPagination,
selectLastPageSize,
selectCurrentFolderID,
selectCurrentFolder,
selectCommanderPageSize,
selectCommanderPageNumber,
fetchPaginatedDocument
fetchPaginatedDocument,
selectFilterText
} from "@/slices/dualPanel/dualPanel"

import type {RootState} from "@/app/types"
import type {NType, NodeType, PanelMode} from "@/types"
import Breadcrumbs from "@/components/Breadcrumbs"
import Pagination from "@/components/Pagination"
import PanelContext from "@/contexts/PanelContext"
import drop_files from "@/components/modals/DropFiles"
import {selectContentHeight} from "@/slices/sizes"
import classes from "./Commander.module.scss"
import {useGetPaginatedNodesQuery} from "@/features/nodes/apiSlice"

export default function Commander() {
const [dragOver, setDragOver] = useState<boolean>(false)
const mode: PanelMode = useContext(PanelContext)
const height = useSelector((state: RootState) =>
selectContentHeight(state, mode)
)
const dispatch = useDispatch()
const height = useAppSelector(s => selectContentHeight(s, mode))
const dispatch = useAppDispatch()
const navigate = useNavigate()

const {data, status, error} = useSelector((state: RootState) =>
selectPanelNodes(state, mode)
)
const currentNodeID = useSelector((state: RootState) =>
selectCurrentFolderID(state, mode)
)
const currentFolder = useSelector((state: RootState) =>
selectCurrentFolder(state, mode)
)
const pagination = useSelector((state: RootState) =>
selectPagination(state, mode)
)
const lastPageSize = useSelector((state: RootState) =>
selectLastPageSize(state, mode)
)
const pageSize = useSelector((state: RootState) =>
selectCommanderPageSize(state, mode)
)
const pageNumber = useSelector((state: RootState) =>
selectCommanderPageNumber(state, mode)
)

if (status === "loading" && !data) {
const lastPageSize = useAppSelector(s => selectLastPageSize(s, mode))
const currentNodeID = useAppSelector(s => selectCurrentFolderID(s, mode))
const [pageSize, setPageSize] = useState<number>(lastPageSize)
const [page, setPage] = useState<number>(1)
const filter = useAppSelector(s => selectFilterText(s, mode))
const {data, isLoading, isError} = useGetPaginatedNodesQuery({
nodeID: currentNodeID!,
page_number: page,
page_size: pageSize,
filter: filter
})

const currentFolder = useAppSelector(s => selectCurrentFolder(s, mode))

if (isLoading && !data) {
return <div>Loading...</div>
}

if (status === "failed") {
return <div>{error}</div>
if (isError) {
return <div>{`some error`}</div>
}

if (!data) {
return (
<div>
Data is null Error: {error}
Status: {status}
</div>
)
return <div>Data is null</div>
}

const onClick = (node: NType) => {
if (mode == "secondary" && node.ctype == "folder") {
dispatch(
fetchPaginatedNodes({
nodeId: node.id,
panel: "secondary",
urlParams: new URLSearchParams(`page_size=${lastPageSize}`)
})
)
dispatch(
setCurrentNode({
node: {id: node.id, ctype: "folder", breadcrumb: null},
Expand All @@ -109,28 +82,12 @@ export default function Commander() {
}

const onPageNumberChange = (page: number) => {
dispatch(
fetchPaginatedNodes({
nodeId: currentNodeID!,
panel: mode,
urlParams: new URLSearchParams(
`page_number=${page}&page_size=${pageSize}`
)
})
)
setPage(page)
}

const onPageSizeChange = (value: string | null) => {
if (value) {
dispatch(
fetchPaginatedNodes({
nodeId: currentNodeID!,
panel: mode,
urlParams: new URLSearchParams(
`page_number=${pageNumber}&page_size=${value}`
)
})
)
setPageSize(parseInt(value))
}
}
const onDragOver = (event: React.DragEvent<HTMLDivElement>) => {
Expand All @@ -155,7 +112,7 @@ export default function Commander() {
}).then(() => {})
}

const nodes = data.map((n: NodeType) => (
const nodes = data.items.map((n: NodeType) => (
<Node onClick={onClick} key={n.id} node={n} />
))

Expand All @@ -166,7 +123,11 @@ export default function Commander() {
<>
<Group>{nodes}</Group>
<Pagination
pagination={pagination}
pagination={{
pageNumber: page,
pageSize: pageSize!,
numPages: data.num_pages
}}
onPageNumberChange={onPageNumberChange}
onPageSizeChange={onPageSizeChange}
lastPageSize={lastPageSize}
Expand Down
52 changes: 32 additions & 20 deletions ui2/src/components/Commander/DeleteButton.tsx
Original file line number Diff line number Diff line change
@@ -1,41 +1,53 @@
import {useContext} from "react"
import {useDisclosure} from "@mantine/hooks"

import {Tooltip, ActionIcon} from "@mantine/core"
import {IconTrash} from "@tabler/icons-react"
import {openModal} from "@/components/modals/Generic"
import {NodeType, PanelMode} from "@/types"
import {PanelMode} from "@/types"
import DeleteNodesModal from "./DeleteModal"
import {useSelector, useDispatch} from "react-redux"
import {
selectSelectedNodes,
selectSelectedNodeIds,
clearNodesSelection
} from "@/slices/dualPanel/dualPanel"
import {RootState} from "@/app/types"

import {selectNodesByIds} from "@/features/nodes/nodesSlice"
import PanelContext from "@/contexts/PanelContext"

export default function DeleteButton() {
const [opened, {open, close}] = useDisclosure(false)
const mode: PanelMode = useContext(PanelContext)
const dispatch = useDispatch()
const nodes = useSelector((state: RootState) =>
selectSelectedNodes(state, mode)
) as NodeType[]
const selectedIds = useSelector((state: RootState) =>
selectSelectedNodeIds(state, mode)
)
const selectedNodes = useSelector((state: RootState) =>
selectNodesByIds(state, selectedIds || [])
)

const onSubmit = () => {
dispatch(clearNodesSelection(mode))
close()
}

const onClick = () => {
openModal<string[], {nodes: NodeType[]}>(DeleteNodesModal, {
nodes: nodes
})
.then(() => {
dispatch(clearNodesSelection(mode))
})
.catch(() => {})
const onCancel = () => {
dispatch(clearNodesSelection(mode))
close()
}

return (
<Tooltip withArrow label="Delete">
<ActionIcon size="lg" onClick={onClick} color={"red"}>
<IconTrash />
</ActionIcon>
</Tooltip>
<>
<Tooltip withArrow label="Delete">
<ActionIcon size="lg" onClick={open} color={"red"}>
<IconTrash />
</ActionIcon>
</Tooltip>
<DeleteNodesModal
opened={opened}
nodes={selectedNodes}
onSubmit={onSubmit}
onCancel={onCancel}
/>
</>
)
}
Loading