forked from DA0-DA0/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 1
/
useDaoNavHelpers.ts
88 lines (76 loc) · 2.38 KB
/
useDaoNavHelpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { useRouter } from 'next/router'
import { useCallback } from 'react'
import { DaoPageMode } from '@dao-dao/types'
import {
getDaoPath as _getDaoPath,
getDaoProposalPath as _getDaoProposalPath,
} from '@dao-dao/utils'
import { useAppContextIfAvailable } from '../components/layout/AppContext'
export const useDaoNavHelpers = (overrideMode?: DaoPageMode) => {
const router = useRouter()
// On SDA, some pages, like 404 and discord redirect, render outside the app
// layout context. We still want to be able to use these helpers to redirect
// to DAO pages, so we allow overriding the mode.
const { mode } = useAppContextIfAvailable() ?? {
mode: overrideMode,
}
if (!mode) {
throw new Error('No mode available')
}
const getDaoPath = useCallback(
(coreAddress: string, path?: string, params?: Record<string, unknown>) =>
_getDaoPath(mode, coreAddress, path, params),
[mode]
)
const goToDao = useCallback(
(
coreAddress: string,
path?: string,
params?: Record<string, unknown>,
{ shallow = false }: { shallow?: boolean } = {}
) =>
router.push(getDaoPath(coreAddress, path, params), undefined, {
shallow,
}),
[getDaoPath, router]
)
const getDaoProposalPath = useCallback(
(
coreAddress: string,
proposalId: string,
params?: Record<string, unknown>
) => _getDaoProposalPath(mode, coreAddress, proposalId, params),
[mode]
)
const goToDaoProposal = useCallback(
(...args: Parameters<typeof getDaoProposalPath>) =>
router.push(getDaoProposalPath(...args)),
[getDaoProposalPath, router]
)
// Returns proposal ID if we're on a DAO proposal subpath, or undefined.
const getDaoFromPath = () =>
router.asPath.match(new RegExp('^' + getDaoPath('([a-zA-Z0-9]+)')))?.[1]
// Returns proposal ID if we're on a DAO proposal subpath, or undefined.
const getProposalIdFromPath = () =>
router.asPath.match(
new RegExp('^' + getDaoProposalPath('.+', '([a-zA-Z0-9]+)'))
)?.[1]
// Path components after the DAO's address.
const daoSubpathComponents = new URL(
router.asPath,
'http://localhost'
).pathname
.replace(getDaoPath(''), '')
.split('/')
.slice(1)
return {
getDaoPath,
goToDao,
getDaoProposalPath,
goToDaoProposal,
getDaoFromPath,
getProposalIdFromPath,
router,
daoSubpathComponents,
}
}