Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.9 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'

import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { Breadcrumb } from '~/types'

import { visualReviewReposList, visualReviewRunsRetrieve } from '../generated/api'
import { ForwardUrl, LegacyRoute, legacyForwardUrl, pickLandingRepo } from '../lib/forwardUrls'
import { isNotFoundError, resolveRepoFullName } from '../lib/repoIds'
import { splitRepoFullName } from '../lib/repoPaths'
import { visualReviewPreferencesLogic } from './visualReviewPreferencesLogic'

export type ForwardRoute = { kind: 'index' } | LegacyRoute
export type ForwardFailure = 'not_found' | 'load_failed'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visualReviewIndexSceneLogicValues {
    currentProjectId: number | string // teamLogic
    currentTeamId: number | null // teamLogic
    lastRepoByTeam: Record<string, string> // visualReviewPreferencesLogic
    breadcrumbs: Breadcrumb[]
    forwardFailure: ForwardFailure | null
    forwardRoute: ForwardRoute | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visualReviewIndexSceneLogicActions {
    forward: (route: ForwardRoute) => {
        route: ForwardRoute
    }
    forwardFailed: (failure: ForwardFailure) => {
        failure: ForwardFailure
    }
}

export type visualReviewIndexSceneLogicType = MakeLogicType<
    visualReviewIndexSceneLogicValues,
    visualReviewIndexSceneLogicActions
>

// Forwarding scene logic. `/visual-review` goes to the repo the team used last, else the first
// connected repo, else Settings. URLs that name a repo or a run by UUID go to the owner/name URL
// of the same page. A failed or unresolvable lookup stays here to show its state, so it cannot loop.
export const visualReviewIndexSceneLogic = kea<visualReviewIndexSceneLogicType>([
    path(['products', 'visual_review', 'frontend', 'scenes', 'visualReviewIndexSceneLogic']),
    connect(() => ({
        values: [teamLogic, ['currentProjectId', 'currentTeamId'], visualReviewPreferencesLogic, ['lastRepoByTeam']],
    })),
    actions({
        forward: (route: ForwardRoute) => ({ route }),
        forwardFailed: (failure: ForwardFailure) => ({ failure }),
    }),
    reducers({
        forwardRoute: [
            null as ForwardRoute | null,
            {
                forward: (_, { route }) => route,
            },
        ],
        forwardFailure: [
            null as ForwardFailure | null,
            {
                forward: () => null,
                forwardFailed: (_, { failure }) => failure,
            },
        ],
    }),
    selectors({
        breadcrumbs: [() => [], (): Breadcrumb[] => [{ key: 'visual_review', name: 'Visual review' }]],
    }),
    listeners(({ actions, values }) => ({
        forward: async ({ route }) => {
            const projectId = String(values.currentProjectId)
            // The lookups below are async, so read the URL now, before the user can move to another page.
            const { pathname } = router.values.location
            const { searchParams, hashParams } = router.values
            let destination: ForwardUrl
            try {
                if (route.kind === 'index') {
                    const response = await visualReviewReposList(projectId)
                    const lastRepoFullName = values.currentTeamId
                        ? (values.lastRepoByTeam[values.currentTeamId] ?? null)
                        : null
                    const repo = pickLandingRepo(response.results, lastRepoFullName)
                    destination = {
                        path: repo
                            ? urls.visualReviewRepoRuns(...splitRepoFullName(repo.repo_full_name))
                            : urls.visualReviewSettings(),
                        searchParams: {},
                        hashParams: {},
                    }
                } else {
                    const repoId =
                        route.kind === 'run'
                            ? (await visualReviewRunsRetrieve(projectId, route.runId)).repo_id
                            : route.repoId
                    const repoFullName = await resolveRepoFullName(projectId, repoId)
                    destination = legacyForwardUrl(route, repoFullName, searchParams, hashParams)
                }
            } catch (error) {
                if (router.values.location.pathname === pathname) {
                    actions.forwardFailed(isNotFoundError(error) ? 'not_found' : 'load_failed')
                }
                return
            }
            if (router.values.location.pathname !== pathname) {
                return
            }
            router.actions.replace(destination.path, destination.searchParams, destination.hashParams)
        },
    })),
    urlToAction(({ actions }) => ({
        '/visual-review': () => actions.forward({ kind: 'index' }),
        '/visual-review/runs/:runId': ({ runId }) => actions.forward({ kind: 'run', runId: runId ?? '' }),
        '/visual-review/repos/:repoId/runs': ({ repoId }) =>
            actions.forward({ kind: 'repoPage', repoId: repoId ?? '', page: 'runs' }),
        '/visual-review/repos/:repoId/snapshots': ({ repoId }) =>
            actions.forward({ kind: 'repoPage', repoId: repoId ?? '', page: 'snapshots' }),
        '/visual-review/repos/:repoId/flakiness': ({ repoId }) =>
            actions.forward({ kind: 'repoPage', repoId: repoId ?? '', page: 'flakiness' }),
        '/visual-review/repos/:repoId/:runType/snapshots/:identifier': ({ repoId, runType, identifier }) =>
            actions.forward({
                kind: 'snapshotHistory',
                repoId: repoId ?? '',
                runType: decodeURIComponent(runType ?? ''),
                identifier: decodeURIComponent(identifier ?? ''),
            }),
    })),
])