Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

chore: refactor schedule banner#4274

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
presleyp merged 11 commits intomainfrombump/presleyp/3566
Sep 30, 2022
Merged
Show file tree
Hide file tree
Changes fromall 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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -309,6 +309,7 @@ export const WorkspaceScheduleForm: FC<React.PropsWithChildren<WorkspaceSchedule
name="autoStopEnabled"
checked={form.values.autoStopEnabled}
onChange={handleToggleAutoStop}
color="primary"
/>
}
label={Language.stopSwitch}
Expand Down
149 changes: 23 additions & 126 deletionssite/src/pages/WorkspacePage/WorkspacePage.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,21 @@
import { makeStyles } from "@material-ui/core/styles"
import { useActor, useMachine, useSelector } from "@xstate/react"
import { FeatureNames } from "api/types"
import dayjs from "dayjs"
import minMax from "dayjs/plugin/minMax"
import { FC, useContext, useEffect } from "react"
import { Helmet } from "react-helmet-async"
import { useTranslation } from "react-i18next"
import { useMachine } from "@xstate/react"
import { ChooseOne, Cond } from "components/Conditionals/ChooseOne"
import { FC, useEffect } from "react"
import { useParams } from "react-router-dom"
import { selectFeatureVisibility } from "xServices/entitlements/entitlementsSelectors"
import { DeleteDialog } from "../../components/Dialogs/DeleteDialog/DeleteDialog"
import { ErrorSummary } from "../../components/ErrorSummary/ErrorSummary"
import { FullScreenLoader } from "../../components/Loader/FullScreenLoader"
import { Workspace, WorkspaceErrors } from "../../components/Workspace/Workspace"
import { firstOrItem } from "../../util/array"
import { pageTitle } from "../../util/page"
import { canExtendDeadline, canReduceDeadline, maxDeadline, minDeadline } from "../../util/schedule"
import { getFaviconByStatus } from "../../util/workspace"
import { XServiceContext } from "../../xServices/StateContext"
import { workspaceMachine } from "../../xServices/workspace/workspaceXService"
import { workspaceScheduleBannerMachine } from "../../xServices/workspaceSchedule/workspaceScheduleBannerXService"

dayjs.extend(minMax)
import { WorkspaceReadyPage } from "./WorkspaceReadyPage"

export const WorkspacePage: FC = () => {
const { username: usernameQueryParam, workspace: workspaceQueryParam } = useParams()
const username = firstOrItem(usernameQueryParam, null)
const workspaceName = firstOrItem(workspaceQueryParam, null)
const { t } = useTranslation("workspacePage")
const xServices = useContext(XServiceContext)
const featureVisibility = useSelector(xServices.entitlementsXService, selectFeatureVisibility)
const [workspaceState, workspaceSend] = useMachine(workspaceMachine)
const {
workspace,
getWorkspaceError,
template,
getTemplateWarning,
refreshWorkspaceWarning,
builds,
getBuildsError,
permissions,
checkPermissionsError,
buildError,
cancellationError,
applicationsHost,
} = workspaceState.context
const canUpdateWorkspace = Boolean(permissions?.updateWorkspace)
const [bannerState, bannerSend] = useMachine(workspaceScheduleBannerMachine)
const [buildInfoState] = useActor(xServices.buildInfoXService)
const { workspace, getWorkspaceError, getTemplateWarning, checkPermissionsError } =
workspaceState.context
const styles = useStyles()

/**
Expand All@@ -57,95 +26,23 @@ export const WorkspacePage: FC = () => {
username && workspaceName && workspaceSend({ type: "GET_WORKSPACE", username, workspaceName })
}, [username, workspaceName, workspaceSend])

if (workspaceState.matches("error")) {
return (
<div className={styles.error}>
{Boolean(getWorkspaceError) && <ErrorSummary error={getWorkspaceError} />}
{Boolean(getTemplateWarning) && <ErrorSummary error={getTemplateWarning} />}
{Boolean(checkPermissionsError) && <ErrorSummary error={checkPermissionsError} />}
</div>
)
} else if (!workspace || !permissions) {
return <FullScreenLoader />
} else if (!template) {
return <FullScreenLoader />
} else {
const deadline = dayjs(workspace.latest_build.deadline).utc()
const favicon = getFaviconByStatus(workspace.latest_build)
return (
<>
<Helmet>
<title>{pageTitle(`${workspace.owner_name}/${workspace.name}`)}</title>
<link rel="alternate icon" type="image/png" href={`/favicons/${favicon}.png`} />
<link rel="icon" type="image/svg+xml" href={`/favicons/${favicon}.svg`} />
</Helmet>

<Workspace
bannerProps={{
isLoading: bannerState.hasTag("loading"),
onExtend: () => {
bannerSend({
type: "UPDATE_DEADLINE",
workspaceId: workspace.id,
newDeadline: dayjs.min(deadline.add(4, "hours"), maxDeadline(workspace, template)),
})
},
}}
scheduleProps={{
onDeadlineMinus: () => {
bannerSend({
type: "UPDATE_DEADLINE",
workspaceId: workspace.id,
newDeadline: dayjs.max(deadline.add(-1, "hours"), minDeadline()),
})
},
onDeadlinePlus: () => {
bannerSend({
type: "UPDATE_DEADLINE",
workspaceId: workspace.id,
newDeadline: dayjs.min(deadline.add(1, "hours"), maxDeadline(workspace, template)),
})
},
deadlineMinusEnabled: () => {
return canReduceDeadline(deadline)
},
deadlinePlusEnabled: () => {
return canExtendDeadline(deadline, workspace, template)
},
}}
isUpdating={workspaceState.hasTag("updating")}
workspace={workspace}
handleStart={() => workspaceSend("START")}
handleStop={() => workspaceSend("STOP")}
handleDelete={() => workspaceSend("ASK_DELETE")}
handleUpdate={() => workspaceSend("UPDATE")}
handleCancel={() => workspaceSend("CANCEL")}
resources={workspace.latest_build.resources}
builds={builds}
canUpdateWorkspace={canUpdateWorkspace}
hideSSHButton={featureVisibility[FeatureNames.BrowserOnly]}
workspaceErrors={{
[WorkspaceErrors.GET_RESOURCES_ERROR]: refreshWorkspaceWarning,
[WorkspaceErrors.GET_BUILDS_ERROR]: getBuildsError,
[WorkspaceErrors.BUILD_ERROR]: buildError,
[WorkspaceErrors.CANCELLATION_ERROR]: cancellationError,
}}
buildInfo={buildInfoState.context.buildInfo}
applicationsHost={applicationsHost}
/>
<DeleteDialog
entity="workspace"
name={workspace.name}
info={t("deleteDialog.info", { timeAgo: dayjs(workspace.created_at).fromNow() })}
isOpen={workspaceState.matches({ ready: { build: "askingDelete" } })}
onCancel={() => workspaceSend("CANCEL_DELETE")}
onConfirm={() => {
workspaceSend("DELETE")
}}
/>
</>
)
}
return (
<ChooseOne>
<Cond condition={workspaceState.matches("error")}>
<div className={styles.error}>
{Boolean(getWorkspaceError) && <ErrorSummary error={getWorkspaceError} />}
{Boolean(getTemplateWarning) && <ErrorSummary error={getTemplateWarning} />}
{Boolean(checkPermissionsError) && <ErrorSummary error={checkPermissionsError} />}
</div>
</Cond>
<Cond condition={Boolean(workspace) && workspaceState.matches("ready")}>
<WorkspaceReadyPage workspaceState={workspaceState} workspaceSend={workspaceSend} />
</Cond>
<Cond>
<FullScreenLoader />
</Cond>
</ChooseOne>
)
}

const useStyles = makeStyles((theme) => ({
Expand Down
112 changes: 112 additions & 0 deletionssite/src/pages/WorkspacePage/WorkspaceReadyPage.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
import { useActor, useSelector } from "@xstate/react"
import { FeatureNames } from "api/types"
import dayjs from "dayjs"
import { useContext } from "react"
import { Helmet } from "react-helmet-async"
import { useTranslation } from "react-i18next"
import { selectFeatureVisibility } from "xServices/entitlements/entitlementsSelectors"
import { StateFrom } from "xstate"
import { DeleteDialog } from "../../components/Dialogs/DeleteDialog/DeleteDialog"
import { Workspace, WorkspaceErrors } from "../../components/Workspace/Workspace"
import { pageTitle } from "../../util/page"
import { getFaviconByStatus } from "../../util/workspace"
import { XServiceContext } from "../../xServices/StateContext"
import { WorkspaceEvent, workspaceMachine } from "../../xServices/workspace/workspaceXService"

interface WorkspaceReadyPageProps {
workspaceState: StateFrom<typeof workspaceMachine>
workspaceSend: (event: WorkspaceEvent) => void
}

export const WorkspaceReadyPage = ({
workspaceState,
workspaceSend,
}: WorkspaceReadyPageProps): JSX.Element => {
const [bannerState, bannerSend] = useActor(workspaceState.children["scheduleBannerMachine"])
const xServices = useContext(XServiceContext)
const featureVisibility = useSelector(xServices.entitlementsXService, selectFeatureVisibility)
const [buildInfoState] = useActor(xServices.buildInfoXService)
const {
workspace,
refreshWorkspaceWarning,
builds,
getBuildsError,
buildError,
cancellationError,
applicationsHost,
permissions,
} = workspaceState.context
if (workspace === undefined) {
throw Error("Workspace is undefined")
}
const canUpdateWorkspace = Boolean(permissions?.updateWorkspace)
const { t } = useTranslation("workspacePage")
const favicon = getFaviconByStatus(workspace.latest_build)

return (
<>
<Helmet>
<title>{pageTitle(`${workspace.owner_name}/${workspace.name}`)}</title>
<link rel="alternate icon" type="image/png" href={`/favicons/${favicon}.png`} />
<link rel="icon" type="image/svg+xml" href={`/favicons/${favicon}.svg`} />
</Helmet>

<Workspace
bannerProps={{
isLoading: bannerState.hasTag("loading"),
onExtend: () => {
bannerSend({
type: "INCREASE_DEADLINE",
hours: 4,
})
},
}}
scheduleProps={{
onDeadlineMinus: () => {
bannerSend({
type: "DECREASE_DEADLINE",
hours: 1,
})
},
onDeadlinePlus: () => {
bannerSend({
type: "INCREASE_DEADLINE",
hours: 1,
})
},
deadlineMinusEnabled: () => !bannerState.matches("atMinDeadline"),
deadlinePlusEnabled: () => !bannerState.matches("atMaxDeadline"),
}}
isUpdating={workspaceState.hasTag("updating")}
workspace={workspace}
handleStart={() => workspaceSend({ type: "START" })}
handleStop={() => workspaceSend({ type: "STOP" })}
handleDelete={() => workspaceSend({ type: "ASK_DELETE" })}
handleUpdate={() => workspaceSend({ type: "UPDATE" })}
handleCancel={() => workspaceSend({ type: "CANCEL" })}
resources={workspace.latest_build.resources}
builds={builds}
canUpdateWorkspace={canUpdateWorkspace}
hideSSHButton={featureVisibility[FeatureNames.BrowserOnly]}
workspaceErrors={{
[WorkspaceErrors.GET_RESOURCES_ERROR]: refreshWorkspaceWarning,
[WorkspaceErrors.GET_BUILDS_ERROR]: getBuildsError,
[WorkspaceErrors.BUILD_ERROR]: buildError,
[WorkspaceErrors.CANCELLATION_ERROR]: cancellationError,
}}
buildInfo={buildInfoState.context.buildInfo}
applicationsHost={applicationsHost}
/>
<DeleteDialog
entity="workspace"
name={workspace.name}
info={t("deleteDialog.info", { timeAgo: dayjs(workspace.created_at).fromNow() })}
isOpen={workspaceState.matches({ ready: { build: "askingDelete" } })}
onCancel={() => workspaceSend({ type: "CANCEL_DELETE" })}
onConfirm={() => {
workspaceSend({ type: "DELETE" })
}}
/>
</>
)
}
10 changes: 5 additions & 5 deletionssite/src/util/schedule.test.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,8 +8,8 @@ import {
deadlineExtensionMax,
deadlineExtensionMin,
extractTimezone,
maxDeadline,
minDeadline,
getMaxDeadline,
getMinDeadline,
stripTimezone,
} from "./schedule"

Expand DownExpand Up@@ -55,7 +55,7 @@ describe("maxDeadline", () => {
}

// Then: deadlineMinusDisabled should be falsy
const delta =maxDeadline(workspace, template).diff(now)
const delta =getMaxDeadline(workspace, template).diff(now)
expect(delta).toBeLessThanOrEqual(deadlineExtensionMax.asMilliseconds())
})
})
Expand All@@ -68,15 +68,15 @@ describe("maxDeadline", () => {
}

// Then: deadlineMinusDisabled should be falsy
const delta =maxDeadline(workspace, template).diff(now)
const delta =getMaxDeadline(workspace, template).diff(now)
expect(delta).toBeLessThanOrEqual(deadlineExtensionMax.asMilliseconds())
})
})
})

describe("minDeadline", () => {
it("should never be less than 30 minutes", () => {
const delta =minDeadline().diff(now)
const delta =getMinDeadline().diff(now)
expect(delta).toBeGreaterThanOrEqual(deadlineExtensionMin.asMilliseconds())
})
})
Expand Down
25 changes: 21 additions & 4 deletionssite/src/util/schedule.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,16 +113,30 @@ export const autoStopDisplay = (workspace: Workspace): string => {
export const deadlineExtensionMin = dayjs.duration(30, "minutes")
export const deadlineExtensionMax = dayjs.duration(24, "hours")

export function maxDeadline(ws: Workspace, tpl: Template): dayjs.Dayjs {
/**
* Depends on the time the workspace was last updated, the template config,
* and a global constant.
* @param ws workspace
* @param tpl template
* @returns the latest datetime at which the workspace can be automatically shut down.
*/
export function getMaxDeadline(ws: Workspace | undefined, tpl: Template): dayjs.Dayjs {
// note: we count runtime from updated_at as started_at counts from the start of
// the workspace build process, which can take a while.
if (ws === undefined) {
throw Error("Cannot calculate max deadline because workspace is undefined")
}
const startedAt = dayjs(ws.latest_build.updated_at)
const maxTemplateDeadline = startedAt.add(dayjs.duration(tpl.max_ttl_ms, "milliseconds"))
const maxGlobalDeadline = startedAt.add(deadlineExtensionMax)
return dayjs.min(maxTemplateDeadline, maxGlobalDeadline)
}

export function minDeadline(): dayjs.Dayjs {
/**
* Depends on the current time and a global constant.
* @returns the earliest datetime at which the workspace can be automatically shut down.
*/
export function getMinDeadline(): dayjs.Dayjs {
return dayjs().add(deadlineExtensionMin)
}

Expand All@@ -131,9 +145,12 @@ export function canExtendDeadline(
workspace: Workspace,
template: Template,
): boolean {
return deadline <maxDeadline(workspace, template)
return deadline <getMaxDeadline(workspace, template)
}

export function canReduceDeadline(deadline: dayjs.Dayjs): boolean {
return deadline >minDeadline()
return deadline >getMinDeadline()
}

export const getDeadline = (workspace: Workspace): dayjs.Dayjs =>
dayjs(workspace.latest_build.deadline).utc()
Loading

[8]ページ先頭

©2009-2025 Movatter.jp