chore: rename pjax

This commit is contained in:
EnixCoda 2022-07-17 01:43:25 +08:00
parent ae3b7cc66e
commit bb51a1fa06
26 changed files with 97 additions and 79 deletions

View file

@ -1,4 +1,4 @@
import { expectToFind, expectToNotFind, sleep, waitForLegacyPJAXRedirect } from '../../utils'
import { expectToFind, expectToNotFind, sleep, waitForRedirect } from '../../utils'
describe(`in Gitako project page`, () => {
beforeAll(() => page.goto('https://github.com/EnixCoda/Gitako/commits/develop'))
@ -10,7 +10,7 @@ describe(`in Gitako project page`, () => {
)
if (commitLinks.length < 2) throw new Error(`No enough commits`)
commitLinks[i].click()
await waitForLegacyPJAXRedirect()
await waitForRedirect()
await expectToFind('div.commit')
await sleep(1000)

View file

@ -1,4 +1,8 @@
import { expectToFind, expectToNotFind, sleep, waitForLegacyPJAXRedirect } from '../../utils'
import {
expectToFind,
expectToNotFind,
sleep, waitForRedirect
} from '../../utils'
describe(`in Gitako project page`, () => {
beforeAll(() => page.goto('https://github.com/EnixCoda/Gitako/tree/develop/src'))
@ -9,7 +13,7 @@ describe(`in Gitako project page`, () => {
`.js-details-container div[role="row"] div[role="rowheader"] a[title*="."]`,
)
if (commitLinks.length < 2) throw new Error(`No enough files`)
await waitForLegacyPJAXRedirect(async () => {
await waitForRedirect(async () => {
await commitLinks[i].click()
})
await expectToFind('table.js-file-line-container')

View file

@ -3,8 +3,7 @@ import {
expandFloatModeSidebar,
patientClick,
selectFileTreeItem,
sleep,
waitForLegacyPJAXRedirect,
sleep, waitForRedirect
} from '../../utils'
describe(`in Gitako project page`, () => {
@ -15,14 +14,14 @@ describe(`in Gitako project page`, () => {
await expandFloatModeSidebar()
await patientClick(selectFileTreeItem('src/analytics.ts'))
await waitForLegacyPJAXRedirect()
await waitForRedirect()
await collapseFloatModeSidebar()
await page.click('a[data-selected-links^="repo_issues "]')
await waitForLegacyPJAXRedirect()
await waitForRedirect()
await page.click('a[data-selected-links^="repo_pulls "]')
await waitForLegacyPJAXRedirect()
await waitForRedirect()
page.goBack()
await sleep(1000)

View file

@ -4,8 +4,7 @@ import {
expectToNotFind,
patientClick,
selectFileTreeItem,
sleep,
waitForLegacyPJAXRedirect,
sleep, waitForRedirect
} from '../../utils'
describe(`in Gitako project page`, () => {
@ -16,12 +15,12 @@ describe(`in Gitako project page`, () => {
await expandFloatModeSidebar()
await patientClick(selectFileTreeItem('.babelrc'))
await waitForLegacyPJAXRedirect()
await waitForRedirect()
// The selector for file content
await expectToFind('table.js-file-line-container')
await waitForLegacyPJAXRedirect(async () => {
await waitForRedirect(async () => {
await sleep(1000) // This prevents failing in some cases due to some mystery scheduling issue of puppeteer or jest
page.goBack()
})

View file

@ -3,7 +3,7 @@ import {
expectToFind,
expectToNotFind,
scroll,
selectFileTreeItem,
selectFileTreeItem
} from '../../utils'
describe(`in Gitako project page`, () => {
@ -28,7 +28,7 @@ describe(`in Gitako project page`, () => {
const box = await filesEle?.boundingBox()
if (box) {
await page.mouse.move(box.x + 40, box.y + 40)
await scroll({ totalDistance: 7000, stepDistance: 100 })
await scroll({ totalDistance: 10000, stepDistance: 100 })
// node of tsconfig.json should be rendered now
await expectToFind(selectFileTreeItem('tsconfig.json'))

View file

@ -1,9 +1,9 @@
import { expectToFind, selectFileTreeItem, sleep, waitForLegacyPJAXRedirect } from '../../utils'
import { expectToFind, selectFileTreeItem, sleep, waitForRedirect } from '../../utils'
describe(`in Gitako project page`, () => {
beforeAll(() => page.goto('https://github.com/EnixCoda/Gitako/tree/develop/src'))
it('expand to target on load and after PJAX', async () => {
it('expand to target on load and after redirect', async () => {
await sleep(3000)
// Expect Gitako sidebar to have expanded src to see contents
@ -12,7 +12,7 @@ describe(`in Gitako project page`, () => {
await page.click(
`.js-details-container div[role="row"] div[role="rowheader"] [title="components"]`,
)
await waitForLegacyPJAXRedirect()
await waitForRedirect()
// Expect Gitako sidebar to have expanded components and see contents
await expectToFind(selectFileTreeItem('src/components/Gitako.tsx'))

View file

@ -71,6 +71,24 @@ export async function waitForLegacyPJAXRedirect(action?: () => void | Promise<vo
return promise
}
export async function waitForTurboRedirect(action?: () => void | Promise<void>) {
const promise = once('turbo:load', 'document')
await action?.()
return promise
}
export async function waitForRedirect(action?: () => void | Promise<void>) {
let fired = false
const $action =
action &&
(() => {
if (fired) return
fired = true
return action()
})
return Promise.race([waitForLegacyPJAXRedirect($action), waitForTurboRedirect($action)])
}
export function selectFileTreeItem(path: string): string {
return `.gitako-side-bar .files a[title="${path}"]`
}

View file

@ -52,7 +52,7 @@ export const Node = React.memo(function Node({
title={node.path}
target={node.type === 'commit' ? '_blank' : undefined}
rel="noopener noreferrer"
{...platform.delegatePJAXProps?.({ node })}
{...platform.delegateFastRedirectAnchorProps?.({ node })}
>
<div className={'node-item-label'}>
<NodeItemIcon node={node} open={expanded} loading={loading} />

View file

@ -1,7 +1,7 @@
import * as React from 'react'
import * as DOMHelper from 'utils/DOMHelper'
import { OperatingSystems, os } from 'utils/general'
import { loadWithPJAX } from 'utils/hooks/usePJAX'
import { loadWithFastRedirect } from 'utils/hooks/useFastRedirect'
import { VisibleNodes } from 'utils/VisibleNodesGenerator'
import { AlignMode } from '../useVirtualScroll'
import { VisibleNodesGeneratorMethods } from './useVisibleNodesGeneratorMethods'
@ -100,7 +100,7 @@ export function useHandleKeyDown(
} else if (focusedNode.type === 'blob') {
const focusedNodeElement = DOMHelper.findNodeElement(focusedNode, event.currentTarget)
if (focusedNodeElement && focusedNode.url)
loadWithPJAX(focusedNode.url, focusedNodeElement)
loadWithFastRedirect(focusedNode.url, focusedNodeElement)
} else if (focusedNode.type === 'commit') {
window.open(focusedNode.url)
}
@ -119,7 +119,7 @@ export function useHandleKeyDown(
event.currentTarget,
)
if (focusedNodeElement && focusedNode.url)
loadWithPJAX(focusedNode.url, focusedNodeElement)
loadWithFastRedirect(focusedNode.url, focusedNodeElement)
} else if (focusedNode.type === 'commit') {
window.open(focusedNode.url)
}

View file

@ -1,7 +1,7 @@
import { useConfigs } from 'containers/ConfigsContext'
import * as React from 'react'
import { isOpenInNewWindowClick } from 'utils/general'
import { loadWithPJAX } from 'utils/hooks/usePJAX'
import { loadWithFastRedirect } from 'utils/hooks/useFastRedirect'
import { AlignMode } from '../useVirtualScroll'
import { VisibleNodesGeneratorMethods } from './useVisibleNodesGeneratorMethods'
@ -35,7 +35,7 @@ export function useHandleNodeClick(
const isHashLink = node.url.includes('#')
if (!isHashLink) {
event.preventDefault()
loadWithPJAX(node.url, event.currentTarget)
loadWithFastRedirect(node.url, event.currentTarget)
}
}
break

View file

@ -9,9 +9,9 @@ import { usePrevious } from 'react-use'
import { cx } from 'utils/cx'
import { run } from 'utils/general'
import { useElementSize } from 'utils/hooks/useElementSize'
import { useAfterRedirect } from 'utils/hooks/useFastRedirect'
import { useLoadedContext } from 'utils/hooks/useLoadedContext'
import { useOnLocationChange } from 'utils/hooks/useOnLocationChange'
import { useOnPJAXDone } from 'utils/hooks/usePJAX'
import { VisibleNodes, VisibleNodesGenerator } from 'utils/VisibleNodesGenerator'
import { SideBarStateContext } from '../../containers/SideBarState'
import { useFocusFileExplorerOnFirstRender } from './hooks/useFocusFileExplorerOnFirstRender'
@ -161,7 +161,7 @@ function LoadedFileExplorer({
}, [metaData.branchName, expandTo])
useOnLocationChange(goToCurrentItem)
useOnPJAXDone(goToCurrentItem)
useAfterRedirect(goToCurrentItem)
return (
<div className={`file-explorer`} tabIndex={-1} onKeyDown={handleKeyDown}>

View file

@ -3,6 +3,8 @@ import { ConfigsContextWrapper } from 'containers/ConfigsContext'
import { ReloadContextWrapper } from 'containers/ReloadContext'
import { InspectorContextWrapper } from 'containers/StateInspector'
import * as React from 'react'
import { StyleSheetManager } from 'styled-components'
import { insertMountPoint } from 'utils/DOMHelper'
import { ErrorBoundary } from '../containers/ErrorBoundary'
import { StateBarErrorContextWrapper } from '../containers/ErrorContext'
import { OAuthWrapper } from '../containers/OAuthWrapper'
@ -12,21 +14,23 @@ import { StateBarStateContextWrapper } from '../containers/SideBarState'
export function Gitako() {
return (
<InspectorContextWrapper>
<ReloadContextWrapper>
<ErrorBoundary>
<ConfigsContextWrapper>
<StateBarStateContextWrapper>
<StateBarErrorContextWrapper>
<OAuthWrapper>
<RepoContextWrapper>
<SideBar />
</RepoContextWrapper>
</OAuthWrapper>
</StateBarErrorContextWrapper>
</StateBarStateContextWrapper>
</ConfigsContextWrapper>
</ErrorBoundary>
</ReloadContextWrapper>
<StyleSheetManager target={insertMountPoint()}>
<ReloadContextWrapper>
<ErrorBoundary>
<ConfigsContextWrapper>
<StateBarStateContextWrapper>
<StateBarErrorContextWrapper>
<OAuthWrapper>
<RepoContextWrapper>
<SideBar />
</RepoContextWrapper>
</OAuthWrapper>
</StateBarErrorContextWrapper>
</StateBarStateContextWrapper>
</ConfigsContextWrapper>
</ErrorBoundary>
</ReloadContextWrapper>
</StyleSheetManager>
</InspectorContextWrapper>
)
}

View file

@ -21,7 +21,7 @@ export function MetaBar() {
className={'repo-name'}
href={repoUrl}
onClick={createAnchorClickHandler(repoUrl)}
{...platform.delegatePJAXProps?.()}
{...platform.delegateFastRedirectAnchorProps?.()}
>
<Text fontWeight="bolder">{repoName}</Text>
</Breadcrumbs.Item>
@ -37,7 +37,7 @@ export function MetaBar() {
sx={{
color: 'fg.muted',
}}
{...platform.delegatePJAXProps?.()}
{...platform.delegateFastRedirectAnchorProps?.()}
>
{branchName || '...'}
</BranchName>

View file

@ -16,8 +16,8 @@ import * as DOMHelper from 'utils/DOMHelper'
import * as features from 'utils/features'
import { detectBrowser } from 'utils/general'
import { useConditionalHook } from 'utils/hooks/useConditionalHook'
import { useAfterRedirect, usePJAXAPI } from 'utils/hooks/useFastRedirect'
import { useLoadedContext } from 'utils/hooks/useLoadedContext'
import { useOnPJAXDone, usePJAX } from 'utils/hooks/usePJAX'
import { ResizeState } from 'utils/hooks/useResizeHandler'
import * as keyHelper from 'utils/keyHelper'
import { SideBarErrorContext } from '../containers/ErrorContext'
@ -29,7 +29,7 @@ import { SettingsBarContent } from './settings/SettingsBar'
import { SideBarResizeHandler } from './SideBarResizeHandler'
export function SideBar() {
usePJAX()
usePJAXAPI()
platform.usePlatformHooks?.()
useMarkGitakoReadyState()
@ -198,9 +198,9 @@ function useGetDerivedExpansion() {
)
}
function useUpdateBodyIndentOnPJAXDone(update: (shouldExpand: boolean) => void) {
function useUpdateBodyIndentAfterRedirect(update: (shouldExpand: boolean) => void) {
const { intelligentToggle, sidebarToggleMode } = useConfigs().value
useOnPJAXDone(
useAfterRedirect(
React.useCallback(() => {
// check and update expand state if pinned and auto-expand checked
if (sidebarToggleMode === 'persistent') {
@ -266,7 +266,7 @@ function useShouldExpand() {
useSaveExpandStateOnToggle(shouldExpand)
useUpdateBodyIndentOnStateUpdate(shouldExpand)
useUpdateBodyIndentOnPJAXDone(setShouldExpand)
useUpdateBodyIndentAfterRedirect(setShouldExpand)
useToggleSideBarWithKeyboard(toggleShowSideBar)
useCollapseOnNoPermissionWhenTokenHasBeenSet(setShouldExpand)

View file

@ -3,7 +3,7 @@ import * as React from 'react'
import { useDebounce, useWindowSize } from 'react-use'
import { getDefaultConfigs } from 'utils/config/helper'
import * as DOMHelper from 'utils/DOMHelper'
import { useOnPJAXDone } from 'utils/hooks/usePJAX'
import { useAfterRedirect } from 'utils/hooks/useFastRedirect'
import { ResizeHandler } from './ResizeHandler'
import { Size, Size2D } from './Size'
@ -37,7 +37,7 @@ function useSidebarWidth() {
React.useLayoutEffect(() => DOMHelper.setGitakoWidthCSSVariable(width), [width])
// Keep variable when directing from PR to repo home via meta bar
useOnPJAXDone(React.useCallback(() => DOMHelper.setGitakoWidthCSSVariable(width), [width]))
useAfterRedirect(React.useCallback(() => DOMHelper.setGitakoWidthCSSVariable(width), [width]))
return [width, setWidth] as const
}

View file

@ -2,8 +2,8 @@ import { useConfigs } from 'containers/ConfigsContext'
import { platform } from 'platforms'
import * as React from 'react'
import { useEffectOnSerializableUpdates } from 'utils/hooks/useEffectOnSerializableUpdates'
import { useAfterRedirect } from 'utils/hooks/useFastRedirect'
import { useLoadedContext } from 'utils/hooks/useLoadedContext'
import { useOnPJAXDone } from 'utils/hooks/usePJAX'
import { useStateIO } from 'utils/hooks/useStateIO'
import { useCatchNetworkError } from '../utils/hooks/useCatchNetworkError'
import { SideBarStateContext } from './SideBarState'
@ -47,7 +47,7 @@ function usePartialMetaData(): PartialMetaData | null {
React.useEffect(() => {
if (!isGettingAccessToken) setPartialMetaData()
}, [isGettingAccessToken, setPartialMetaData])
useOnPJAXDone(setPartialMetaData)
useAfterRedirect(setPartialMetaData)
useEffectOnSerializableUpdates(
$partialMetaData.value,
JSON.stringify,
@ -64,7 +64,7 @@ function usePartialMetaData(): PartialMetaData | null {
function useBranchName(): MetaData['branchName'] | null {
// sync along URL and DOM
const $branchName = useStateIO(() => platform.resolvePartialMetaData()?.branchName || null)
useOnPJAXDone(() => $branchName.onChange(platform.resolvePartialMetaData()?.branchName || null))
useAfterRedirect(() => $branchName.onChange(platform.resolvePartialMetaData()?.branchName || null))
return $branchName.value
}

View file

@ -149,9 +149,7 @@ export async function getPullPageDocuments(
// Response of this API contains view of few files but is not complete.
return continuousLoadPages(
document ||
(await getDOM(
`${window.location.origin}/${userName}/${repoName}/pull/${pullId}/files?_pjax=%23js-repo-pjax-container`,
)),
(await getDOM(`${window.location.origin}/${userName}/${repoName}/pull/${pullId}/files`)),
)
}

View file

@ -1,6 +1,6 @@
import { platform } from 'platforms'
import * as React from 'react'
import { useOnPJAXDone } from 'utils/hooks/usePJAX'
import { useAfterRedirect } from 'utils/hooks/useFastRedirect'
import * as DOMHelper from '../DOMHelper'
import { GitHub } from '../index'
@ -12,5 +12,5 @@ export function useGitHubAttachCopyFileButton(copyFileButton: boolean) {
[copyFileButton],
)
React.useEffect(attachCopyFileButton, [attachCopyFileButton])
useOnPJAXDone(attachCopyFileButton)
useAfterRedirect(attachCopyFileButton)
}

View file

@ -1,6 +1,6 @@
import { platform } from 'platforms'
import * as React from 'react'
import { useOnPJAXDone } from 'utils/hooks/usePJAX'
import { useAfterRedirect } from 'utils/hooks/useFastRedirect'
import * as DOMHelper from '../DOMHelper'
import { GitHub } from '../index'
@ -12,5 +12,5 @@ export function useGitHubAttachCopySnippetButton(copySnippetButton: boolean) {
[copySnippetButton],
)
React.useEffect(attachCopySnippetButton, [attachCopySnippetButton])
useOnPJAXDone(attachCopySnippetButton)
useAfterRedirect(attachCopySnippetButton)
}

View file

@ -1,6 +1,6 @@
import { platform } from 'platforms'
import { useCallback, useEffect } from 'react'
import { useOnPJAXDone } from 'utils/hooks/usePJAX'
import { useAfterRedirect } from 'utils/hooks/useFastRedirect'
import { GitHub } from '..'
const theCSSClassMark = 'gitako-code-fold-attached'
@ -164,5 +164,5 @@ export function useGitHubCodeFold(active: boolean) {
}
}, [active])
useEffect(effect, [effect])
useOnPJAXDone(effect)
useAfterRedirect(effect)
}

View file

@ -209,7 +209,7 @@ export const GitHub: Platform = {
useGitHubCodeFold(codeFolding)
useEnterpriseStatBarStyleFix()
},
delegatePJAXProps: options => {
delegateFastRedirectAnchorProps: options => {
if (configRef.pjaxMode === 'native' && (!options?.node || options.node.type === 'blob')) {
const pjaxContainerSelector = 'main'
const turboContainerId = 'repo-content-turbo-frame'
@ -223,7 +223,7 @@ export const GitHub: Platform = {
}
}
},
loadWithPJAX: (url, element) => {
loadWithFastRedirect: (url, element) => {
if (configRef.pjaxMode === 'native') {
element.click()
return true

View file

@ -3,7 +3,7 @@ import { Base64 } from 'js-base64'
import { platform } from 'platforms'
import * as React from 'react'
import { resolveGitModules } from 'utils/gitSubmodule'
import { useOnPJAXDone } from 'utils/hooks/usePJAX'
import { useAfterRedirect } from 'utils/hooks/useFastRedirect'
import { useProgressBar } from 'utils/hooks/useProgressBar'
import { gitakoServiceHost } from 'utils/networkService'
import { sortFoldersToFront } from 'utils/treeParser'
@ -190,5 +190,5 @@ export function useGiteeAttachCopySnippetButton(copySnippetButton: boolean) {
[copySnippetButton],
)
React.useEffect(attachCopySnippetButton, [attachCopySnippetButton])
useOnPJAXDone(attachCopySnippetButton)
useAfterRedirect(attachCopySnippetButton)
}

View file

@ -24,9 +24,9 @@ type Platform = {
getCurrentPath(branchName: string): string[] | null
setOAuth(code: string): Promise<string | null>
getOAuthLink(): string
delegatePJAXProps?(options?: { node?: TreeNode }):
delegateFastRedirectAnchorProps?(options?: { node?: TreeNode }):
| (React.DOMAttributes<HTMLElement> & Record<string, unknown>) // support data-* attributes
| void
loadWithPJAX?(url: string, element: HTMLElement): boolean | void
loadWithFastRedirect?(url: string, element: HTMLElement): boolean | void
usePlatformHooks?(): void
}

View file

@ -1,11 +1,11 @@
import { isOpenInNewWindowClick } from './general'
import { loadWithPJAX } from './hooks/usePJAX'
import { loadWithFastRedirect } from './hooks/useFastRedirect'
export function createAnchorClickHandler(url: string) {
return (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
if (isOpenInNewWindowClick(e)) return
e.preventDefault()
loadWithPJAX(url, e.currentTarget)
loadWithFastRedirect(url, e.currentTarget)
}
}

View file

@ -1,12 +1,9 @@
import { useConfigs } from 'containers/ConfigsContext'
import { Config } from 'pjax-api'
import { platform } from 'platforms'
import * as React from 'react'
import { useEvent } from 'react-use'
// TODO: rename PJAX
const config: Config = {
const config: import('pjax-api').Config = {
areas: [
// github
'.repository-content',
@ -30,7 +27,7 @@ const config: Config = {
},
}
export function usePJAX() {
export function usePJAXAPI() {
const { pjaxMode } = useConfigs().value
// make history travel work
React.useEffect(() => {
@ -51,12 +48,12 @@ export function usePJAX() {
useRedirectedEvents(document, 'pjax:ready', 'pjax:end')
}
export const loadWithPJAX = (url: string, element: HTMLElement) => {
export const loadWithFastRedirect = (url: string, element: HTMLElement) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
platform.loadWithPJAX?.(url, element) || require('pjax-api').Pjax.assign(url, config)
platform.loadWithFastRedirect?.(url, element) || require('pjax-api').Pjax.assign(url, config)
}
export function useOnPJAXDone(callback: () => void) {
export function useAfterRedirect(callback: () => void) {
useEvent('pjax:end', callback, document) // legacy support
useEvent('turbo:render', callback, document) // prevent page content shift after first redirect to new page via turbo when sidebar is pinned
}

View file

@ -11,7 +11,6 @@ const progressBar = {
},
}
// use native progress bar on GitHub
export function useProgressBar() {
React.useEffect(() => {
NProgress.configure({ showSpinner: false })