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.

feat(today): replace the Views pane with Analytics (#112982)

Mike Warren8d214b6db38f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b669906d0084..594d126572bf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9370,6 +9370,46 @@ snapshots:
hash: v1.k794b7964.13ae77563960d8df1279788e5a1b2a17b0f38c4469bb92d3a22f3cc569903681.v3gbz8mdvwkQ2INsmiXInoQZTCBj3KGPrqcynRaxFCU
scenes-app-ai-observability-trace-view-trace-view-switch--on-old-view--light:
hash: v1.k794b7964.de72868c75c31f3ba3d9813b5f86064d7dbf37bc1a896b8f13032dc102758876.Xpri2jtS8YkCfKQmwMkmtGGWN8oTE_vfUOaiXtOwJK0
+ scenes-app-analytics--list--dark:
+ hash: v1.k794b7964.491dc621aeb0310eccd1992b6bcb6e49c878d1af174ddb4f8a6eb5a206d2dc15.62VHh3pelc5zQaSVOAYh5nLSDsstMvfqAABNu1tXtIo
+ scenes-app-analytics--list--light:
+ hash: v1.k794b7964.ec7610bdf50d37e731fdc0a6446671ff50903f1ccce1d5e33571c55a93ecd539.RpYbc1iskXq3RYmsMgbiyYHLxQwvYDar5HT8_zUiF6w
+ scenes-app-analytics--list-empty--dark:
+ hash: v1.k794b7964.61b8cac61e0cb0c46668f8740b9202f976c06512abfb0a96f90673f4f50c03fd.Fs5KYZ0rz3bW9aNkR4AeY8U4A-uVhNEhPzrb0xVkAb0
+ scenes-app-analytics--list-empty--light:
+ hash: v1.k794b7964.f163f33e7397d83e292087c2d26a7852df8a7115dd207238b9e9c56db1f216d4.UTnKo-X_nCBTnArLxV6dX7hYpXfxpKaKPylOIS4TdbE
+ scenes-app-analytics--list-error--dark:
+ hash: v1.k794b7964.4de9ab34ddee89dce8194de9ba6d950bd682a7100baf2c92628f2fcdeef732e1.8EMDrLMjH_v5VkS85v9lQ-E3ix_xlm_5PiAjKo8z2ok
+ scenes-app-analytics--list-error--light:
+ hash: v1.k794b7964.0b3822357c7057f4b4096caa49e409f04c0dcf873d1caec1142905c973b8a388.-6qSzWEy-GkipPBSWw5E7UIxgqM5hd_i7aeuO6vqLz0
+ scenes-app-analytics--list-filtered--dark:
+ hash: v1.k794b7964.61ab68dc34b3f4d139c73fd9f79dafd14e688069057ec8c384d16dc246b89560.WDh5lB-Zoknv2Oi7bd_Yn0xJBE4zqDvpT8V9KOnX2i4
+ scenes-app-analytics--list-filtered--light:
+ hash: v1.k794b7964.adfe28600efc57e2163f9712881ccb60b9e1cc9c4ecd688ceb1968cc8fff9a5e.kFNWycZGCBpto8f3bZNrOCIs9iLecy9WssloS0FEZrQ
+ scenes-app-analytics--list-new-insight-dialog--dark:
+ hash: v1.k794b7964.983417bc244b0139b676dcf72f101702ac2c9066893c9c091efaeaf720f7771f.24WgEVRBrA6BG5sl7FcJ1JUNyWv-RivTP9rr8jiWDJE
+ scenes-app-analytics--list-new-insight-dialog--light:
+ hash: v1.k794b7964.acf4a37b9e529157b76ec0f2a1e34aa796ef1404de92691214949ebbdef89278.lGNrQ2ek0BRv64LWku7m_OATa5UI-ElEY9F4ad0NY_I
+ scenes-app-analytics--list-no-matches--dark:
+ hash: v1.k794b7964.98526bded52fc586d26be8aa477781ac496a680e4458e017dfc310c48b3b61b5.ygBt3gdmzn3evrpZw9XV5vyor-3bKHLfn8jZbkBPOQw
+ scenes-app-analytics--list-no-matches--light:
+ hash: v1.k794b7964.fbe8cd795c32098fc31475759b54b388b64d541bcefc7871e76ccccb6479e2d1.rsL0ngvVt-9wpIgvEDLpDC5a463fGWs0hauE55Yr9Qs
+ scenes-app-analytics--list-share-dialog--dark:
+ hash: v1.k794b7964.b528e70195dd8749bbde5002bf057f223bc98667cbc85dd3acbdfd866e2dbc26.V6FVJXZufy6dzhF-tSqQC5ViYRC_BJ-7UrrJDO3LdQg
+ scenes-app-analytics--list-share-dialog--light:
+ hash: v1.k794b7964.f43cb0139d84b558a384e87b16b12481b3af4ecf809c00846830728b6623d015.mD3NNCHWyyLOisEnE7cUuWK2iKrGf9re7zP8o9IUrz0
+ scenes-app-analytics--list-space--dark:
+ hash: v1.k794b7964.02cc537be9545d63c1519a3c4e8843f49b4693f17ceda6e68dc2a43a03c226ad.OaYVq7xmYBotkOPvzh5CcQZRXv1z7LdFNfSGPXI24jg
+ scenes-app-analytics--list-space--light:
+ hash: v1.k794b7964.df1ef949811073830fa620d905b8abdc14cdf4a4ae3129d962ab678186bd8727.uWlFQERiA-1QpohoPbgqHGPOwHU4d9QSg6KQX6qHBxU
+ scenes-app-analytics--mine--dark:
+ hash: v1.k794b7964.659428eb68d4d634c208995e28dbfe344ddcf0cca992b94675b477c7adbd440f.vH9NIDJc_a7Iwuz5Almo0pe63ikM-JQrv0Un1QM-FS4
+ scenes-app-analytics--mine--light:
+ hash: v1.k794b7964.b5f523dd51f2e6f3cbaafa4363f455e57836cb02761cc6aaec94b56b4ddea44d.ZnN6FG9-YmW4hFdv3dRyr5HRFZb33OmeNZ5jMNicTJA
+ scenes-app-analytics--spaces--dark:
+ hash: v1.k794b7964.978b19e47d5106243cfe2873e2a623a4e22cf89139df7bce365824ab34fde2b1.L4q9XBXDrhvtrZUasYZpzrKf2jCcvE7WORywHS7brOc
+ scenes-app-analytics--spaces--light:
+ hash: v1.k794b7964.be9cd5ceb8e72ad4b9eca2ad9850f502ce2653f116769d8e476fc2e0031417cf.n2krwqEQH0eDBqXdeuzf5-zISd7VZQqW4QrvhE60eJg
scenes-app-annotations--annotations--dark:
hash: v1.k794b7964.651aae7146d31971a314f627499eafdaa3d35933cde8dd0ad47abc6eab722148.H9u02T71vFBWS4vd-5sVVqacwrqXc9xeeOHs7b4qnL4
scenes-app-annotations--annotations--light:
@@ -10511,9 +10551,9 @@ snapshots:
scenes-app-errortracking--group-page-releases-stacked--light:
hash: v1.k794b7964.6229ba0294619c7c881929c7375df4700325ee629f842369641e5fe2355c1cd4._sFGlcefvjCQOkjMzoP9-CWeQ054s-pQHQ0vChbYbhE
scenes-app-errortracking--group-page-today-rail-nav--dark:
- hash: v1.k794b7964.7ab84acc163b7e23d7f655a44a090f6f79fbfddbc6e84de1eeaa39041e851840.d__a2juGztMkVn9HsH--AUfMwv3yK1IUidE81k0iLhw
+ hash: v1.k794b7964.51774301e193ce23aa082825a13a4c8222b1ab7cee5020316650a30a09263ca8.rtaHVo9A6Ks4bR_fBhcE_ti4Y1afBzbXUMGbb7wsQLk
scenes-app-errortracking--group-page-today-rail-nav--light:
- hash: v1.k794b7964.ad2fd7d9905a1a02f1ad7f5f96ed78a7066000beb5375a442b66f135b28f2105.-IAWojMrz9ZMe4OnWdfuoq_x4FF8wxpXZrvGcudaiLk
+ hash: v1.k794b7964.7087fa389913eb61a5e8eca00e0519ec11efd6395e6d4c6e646f080fcbda2333.1SYO_4nSy1Dzp--Kn2CPGcG_GZhFEGF6feO3oHBHcMA
scenes-app-errortracking--group-page-with-many-self-driving-reports--dark:
hash: v1.k794b7964.0aa0858442d3e422f4825c4665d289c006c87b1c5a22265e447a1c0fa5e5a544.Hy3i1o_nWpWVqH4WqCEDvZTI4LQxeI2c9B6GW9rHDYA
scenes-app-errortracking--group-page-with-many-self-driving-reports--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index f41a057b45ae..e0a887b51820 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -6911,6 +6911,10 @@ export type FileSystemListParams = {
* Include meta.content_type for notebooks and insights on this page, without their contents.
*/
include_content_type?: boolean
+ /**
+ * Include meta.tags, the tag names, for dashboards and insights on this page.
+ */
+ include_tags?: boolean
/**
* Number of results to return per page.
*/
diff --git a/frontend/src/layout/today/TodayAnalyticsNewFolderDialog.tsx b/frontend/src/layout/today/TodayAnalyticsNewFolderDialog.tsx
new file mode 100644
index 000000000000..0d8e0056b560
--- /dev/null
+++ b/frontend/src/layout/today/TodayAnalyticsNewFolderDialog.tsx
@@ -0,0 +1,89 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldLabel,
+ Input,
+} from '@posthog/quill'
+
+import { todayAnalyticsLogic } from './todayAnalyticsLogic'
+
+/** Asks for a name and creates a top-level project folder. */
+export function TodayAnalyticsNewFolderDialog(): JSX.Element {
+ const { newFolderDialogOpen, creatingFolder, newFolderParent } = useValues(todayAnalyticsLogic)
+ const { setNewFolderDialogOpen, createFolder } = useActions(todayAnalyticsLogic)
+ const [name, setName] = useState('')
+ const trimmed = name.trim()
+
+ return (
+ <Dialog
+ open={newFolderDialogOpen}
+ onOpenChange={(open: boolean) => {
+ setNewFolderDialogOpen(open)
+ if (!open) {
+ setName('')
+ }
+ }}
+ >
+ <DialogContent data-attr="analytics-new-folder-dialog">
+ <form
+ className="contents"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (trimmed && !creatingFolder) {
+ createFolder(trimmed)
+ }
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>
+ {newFolderParent ? `New folder in ${newFolderParent}` : 'New collection'}
+ </DialogTitle>
+ <DialogDescription>
+ {newFolderParent
+ ? 'A folder inside this collection.'
+ : 'A collection for a team or an area. Add dashboards, insights, notebooks and canvases to it from their own pages.'}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ <Field>
+ <FieldLabel htmlFor="analytics-new-folder-name">Name</FieldLabel>
+ <Input
+ id="analytics-new-folder-name"
+ autoFocus
+ value={name}
+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => setName(event.target.value)}
+ placeholder={newFolderParent ? 'Q4 launch' : 'Growth team'}
+ data-attr="analytics-new-folder-name"
+ />
+ </Field>
+ </DialogBody>
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" data-attr="analytics-new-folder-cancel" />}>
+ Cancel
+ </DialogClose>
+ <Button
+ type="submit"
+ variant="primary"
+ loading={creatingFolder}
+ disabled={!trimmed}
+ data-attr="analytics-new-folder-create"
+ >
+ {newFolderParent ? 'Create folder' : 'Create collection'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/layout/today/TodayAnalyticsSidebar.tsx b/frontend/src/layout/today/TodayAnalyticsSidebar.tsx
new file mode 100644
index 000000000000..b1aab6d1c219
--- /dev/null
+++ b/frontend/src/layout/today/TodayAnalyticsSidebar.tsx
@@ -0,0 +1,148 @@
+import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+
+import { IconBell, IconBox, IconList, IconNotification, IconPerson } from '@posthog/icons'
+
+import { Logomark } from 'lib/brand'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { analyticsListFiltersFromUrl } from 'scenes/analytics/analyticsListLogic'
+import { AnalyticsSpaceGlyph } from 'scenes/analytics/AnalyticsSpaceGlyph'
+import { analyticsSpacesLogic } from 'scenes/analytics/analyticsSpacesLogic'
+import { urls } from 'scenes/urls'
+
+import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
+import { FileSystemIconType } from '~/queries/schema/schema-general'
+
+import { TodayAnalyticsSection, todayAnalyticsLogic } from './todayAnalyticsLogic'
+import { TodayPaneRow } from './TodayPaneRow'
+import { TodayPaneSearchList } from './TodayPaneSearchList'
+import { TodayPaneSection } from './TodayPaneSection'
+
+/** The Analyses sub-nav: the three ways to browse, the collections a person pinned, and what to keep an eye on. */
+export function TodayAnalyticsSidebar(): JSX.Element {
+ const { collapsedSections, fromPostHog } = useValues(todayAnalyticsLogic)
+ const { toggleSection } = useActions(todayAnalyticsLogic)
+ const { pinnedSpaces } = useValues(analyticsSpacesLogic)
+ const { location, searchParams } = useValues(router)
+ const path = removeProjectIdIfPresent(location.pathname)
+ const isOpen = (section: TodayAnalyticsSection): boolean => !collapsedSections.includes(section)
+ const listFilters =
+ path === urls.analyticsList() || path === urls.analyticsMine()
+ ? analyticsListFiltersFromUrl(searchParams)
+ : null
+ const openFolder = path === urls.analyticsList() ? (listFilters?.folder ?? null) : null
+
+ return (
+ <div className="TodayPane group/colorful-product-icons colorful-product-icons-true" data-quill>
+ {/* The rows are list options that need the pane list around them; this pane has no search, so the field stays hidden. */}
+ <TodayPaneSearchList
+ query=""
+ onQueryChange={() => {}}
+ searchLabel="Search analytics"
+ dataAttr="analytics-sidebar-search"
+ className="[&>div:first-child]:hidden"
+ >
+ <TodayPaneSection
+ label="Browse"
+ open={isOpen('browse')}
+ count={3 + pinnedSpaces.length}
+ showCount={false}
+ onToggle={() => toggleSection('browse')}
+ dataAttr="analytics-section-browse"
+ >
+ <TodayPaneRow
+ value="browse:all"
+ label="View all"
+ icon={<IconList />}
+ to={urls.analyticsList()}
+ active={path === urls.analyticsList() && openFolder === null}
+ dataAttr="analytics-sidebar-browse"
+ />
+ <TodayPaneRow
+ value="browse:mine"
+ label="My work"
+ icon={<IconPerson />}
+ to={urls.analyticsMine()}
+ active={path === urls.analyticsMine()}
+ dataAttr="analytics-sidebar-browse"
+ />
+ <TodayPaneRow
+ value="browse:spaces"
+ label="Collections"
+ icon={<IconBox />}
+ to={urls.analyticsSpaces()}
+ active={path === urls.analyticsSpaces()}
+ dataAttr="analytics-sidebar-browse"
+ />
+ {pinnedSpaces.map((space) => (
+ <TodayPaneRow
+ key={space.path}
+ value={`space:${space.path}`}
+ label={space.name}
+ icon={<AnalyticsSpaceGlyph name={space.name} />}
+ to={urls.analyticsList({ folder: space.path })}
+ active={openFolder === space.path}
+ dataAttr="analytics-sidebar-starred-space"
+ />
+ ))}
+ </TodayPaneSection>
+ <TodayPaneSection
+ label="Monitor"
+ open={isOpen('monitor')}
+ count={2}
+ showCount={false}
+ onToggle={() => toggleSection('monitor')}
+ divider
+ dataAttr="analytics-section-monitor"
+ >
+ <TodayPaneRow
+ value="monitor:alerts"
+ label="Alerts"
+ icon={<IconBell />}
+ to={urls.alerts()}
+ active={path === urls.alerts()}
+ dataAttr="analytics-sidebar-monitor"
+ />
+ <TodayPaneRow
+ value="monitor:subscriptions"
+ label="Subscriptions"
+ icon={<IconNotification />}
+ to={`${urls.subscriptions()}?tab=mine`}
+ active={path === urls.subscriptions()}
+ dataAttr="analytics-sidebar-monitor"
+ />
+ </TodayPaneSection>
+ {fromPostHog.length > 0 && (
+ <TodayPaneSection
+ label="By PostHog"
+ icon={<Logomark className="h-auto w-3.5" />}
+ open={isOpen('by-posthog')}
+ count={fromPostHog.length}
+ showCount={false}
+ onToggle={() => toggleSection('by-posthog')}
+ divider
+ dataAttr="analytics-section-by-posthog"
+ >
+ {fromPostHog.map((product) => {
+ const productPath = product.href.split(/[?#]/)[0]
+ return (
+ <TodayPaneRow
+ key={product.key}
+ value={`by-posthog:${product.key}`}
+ label={product.label}
+ icon={iconForType(
+ (product.item.iconType ?? product.item.type) as FileSystemIconType,
+ product.item.iconColor
+ )}
+ to={product.href}
+ active={path === productPath || path.startsWith(`${productPath}/`)}
+ dataAttr="analytics-sidebar-by-posthog"
+ />
+ )
+ })}
+ </TodayPaneSection>
+ )}
+ </TodayPaneSearchList>
+ </div>
+ )
+}
diff --git a/frontend/src/layout/today/TodayNewAnalyticsButton.tsx b/frontend/src/layout/today/TodayNewAnalyticsButton.tsx
new file mode 100644
index 000000000000..5f3915bef5eb
--- /dev/null
+++ b/frontend/src/layout/today/TodayNewAnalyticsButton.tsx
@@ -0,0 +1,22 @@
+import { IconPlus } from '@posthog/icons'
+import { Button } from '@posthog/quill'
+
+import { NewAnalyticsMenu } from 'scenes/analytics/NewAnalyticsMenu'
+
+export function TodayNewAnalyticsButton(): JSX.Element {
+ return (
+ <NewAnalyticsMenu
+ source="sidebar"
+ trigger={
+ <Button
+ size="icon"
+ className="-me-2 text-muted-foreground"
+ aria-label="New analytics"
+ data-attr="today-new-analytics-header"
+ />
+ }
+ >
+ <IconPlus />
+ </NewAnalyticsMenu>
+ )
+}
diff --git a/frontend/src/layout/today/TodayNewViewButton.tsx b/frontend/src/layout/today/TodayNewViewButton.tsx
deleted file mode 100644
index dc85780510f3..000000000000
--- a/frontend/src/layout/today/TodayNewViewButton.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { IconPlus } from '@posthog/icons'
-import { Button } from '@posthog/quill'
-
-import { NewViewMenu } from 'scenes/views/NewViewMenu'
-
-export function TodayNewViewButton(): JSX.Element {
- return (
- <NewViewMenu
- trigger={
- <Button
- size="icon"
- className="-me-2 text-muted-foreground"
- aria-label="New view"
- data-attr="today-new-view-header"
- />
- }
- >
- <IconPlus />
- </NewViewMenu>
- )
-}
diff --git a/frontend/src/layout/today/TodayPaneSection.tsx b/frontend/src/layout/today/TodayPaneSection.tsx
index 68c8287a1a6a..c99dc603f8bf 100644
--- a/frontend/src/layout/today/TodayPaneSection.tsx
+++ b/frontend/src/layout/today/TodayPaneSection.tsx
@@ -8,8 +8,12 @@ import { TodaySectionResizer } from './useTodaySectionLayout'
export interface TodayPaneSectionProps {
label: string
+ /** Shows before the label, for a section whose source matters, such as the PostHog mark. */
+ icon?: JSX.Element | null
open: boolean
count: number
+ /** Whether the row count shows next to a collapsed label. */
+ showCount?: boolean
onToggle: () => void
actions?: JSX.Element | null
/** Replaces the label while set, for example with a search field. */
@@ -26,8 +30,10 @@ export interface TodayPaneSectionProps {
export function TodayPaneSection({
label,
+ icon,
open,
count,
+ showCount = true,
onToggle,
actions,
heading,
@@ -53,9 +59,17 @@ export function TodayPaneSection({
onClick={onToggle}
className="flex min-w-0 flex-1 cursor-pointer items-center gap-1 rounded-sm py-1 text-left text-foreground/70 hover:text-foreground"
>
+ {icon && (
+ <span
+ className="flex size-3.5 shrink-0 items-center justify-center [&_svg]:size-3.5"
+ aria-hidden
+ >
+ {icon}
+ </span>
+ )}
<span>{label}</span>
<Caret className="size-3 shrink-0 opacity-60" />
- {!open && count > 0 && (
+ {!open && showCount && count > 0 && (
<span className="ml-0.5 font-normal text-muted-foreground tabular-nums">{count}</span>
)}
</MenuLabel>
diff --git a/frontend/src/layout/today/TodayProductsViewsHint.tsx b/frontend/src/layout/today/TodayProductsAnalyticsHint.tsx
similarity index 50%
rename from frontend/src/layout/today/TodayProductsViewsHint.tsx
rename to frontend/src/layout/today/TodayProductsAnalyticsHint.tsx
index d6ed8c93f994..5478805a2fc3 100644
--- a/frontend/src/layout/today/TodayProductsViewsHint.tsx
+++ b/frontend/src/layout/today/TodayProductsAnalyticsHint.tsx
@@ -10,36 +10,36 @@ import {
} from '@posthog/quill'
import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { AnalyticsTypeIcon } from 'scenes/analytics/AnalyticsTypeIcon'
+import { ANALYTICS_TYPES, AnalyticsTypeInfo } from 'scenes/analytics/analyticsUtils'
import { urls } from 'scenes/urls'
-import { VIEW_TYPES, ViewTypeInfo } from 'scenes/views/viewsUtils'
-import { ViewTypeIcon } from 'scenes/views/ViewTypeIcon'
-/** Points a Products search for a view type to the Views pane, where those types live. */
-export function TodayProductsViewsHint({ viewTypes }: { viewTypes: ViewTypeInfo[] }): JSX.Element {
- const title = viewTypes
+/** Points a Products search for an analytics type to the Analytics pane, where those types live. */
+export function TodayProductsAnalyticsHint({ analyticsTypes }: { analyticsTypes: AnalyticsTypeInfo[] }): JSX.Element {
+ const title = analyticsTypes
.map((info, index) => (index === 0 ? info.pluralLabel : info.pluralLabel.toLowerCase()))
.join(' and ')
return (
- <Empty className="mt-2 gap-3 p-4" data-attr="today-products-views-hint">
+ <Empty className="mt-2 gap-3 p-4" data-attr="today-products-analytics-hint">
<EmptyHeader>
<IconStack>
- {VIEW_TYPES.map((info) => (
+ {ANALYTICS_TYPES.map((info) => (
<IconStackItem key={info.type} color={info.color}>
- <ViewTypeIcon type={info.type} />
+ <AnalyticsTypeIcon type={info.type} />
</IconStackItem>
))}
</IconStack>
- <EmptyTitle>{`${title} are in Views`}</EmptyTitle>
- <EmptyDescription>Canvases, notebooks and dashboards live in Views.</EmptyDescription>
+ <EmptyTitle>{`${title} are in Analytics`}</EmptyTitle>
+ <EmptyDescription>Canvases, dashboards, notebooks and insights live in Analytics.</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button
size="sm"
variant="outline"
- render={<LinkPrimitive to={urls.views()} />}
- data-attr="today-products-views-hint-open"
+ render={<LinkPrimitive to={urls.analyticsList()} />}
+ data-attr="today-products-analytics-hint-open"
>
- Open Views
+ Open Analytics
</Button>
</EmptyContent>
</Empty>
diff --git a/frontend/src/layout/today/TodayProductsSidebar.tsx b/frontend/src/layout/today/TodayProductsSidebar.tsx
index 5c117abaac3e..cd9c942fa3b6 100644
--- a/frontend/src/layout/today/TodayProductsSidebar.tsx
+++ b/frontend/src/layout/today/TodayProductsSidebar.tsx
@@ -16,9 +16,9 @@ import { FileSystemIconType, FileSystemImport } from '~/queries/schema/schema-ge
import { TodayPaneGroupLabel } from './TodayPaneGroupLabel'
import { TodayPaneRow } from './TodayPaneRow'
-import { matchesPaneQuery, viewTypesForPaneSearch } from './todayPaneSearch'
+import { analyticsTypesForPaneSearch, matchesPaneQuery } from './todayPaneSearch'
import { TodayPaneSearchList } from './TodayPaneSearchList'
-import { TodayProductsViewsHint } from './TodayProductsViewsHint'
+import { TodayProductsAnalyticsHint } from './TodayProductsAnalyticsHint'
import { todayToolsLogic } from './todayToolsLogic'
/** The Products sub-nav: recently viewed tools, every saved object type, then the tools by category. */
@@ -36,7 +36,7 @@ export function TodayProductsSidebar(): JSX.Element {
[type.pluralLabel, ...libraryRowProductLabels(type.value)].some((label) => matchesPaneQuery(label, search))
)
const showLibrary = showAllObjects || libraryTypes.length > 0
- const searchedViewTypes = viewTypesForPaneSearch(search)
+ const searchedAnalyticsTypes = analyticsTypesForPaneSearch(search)
const recentSection = recentTools.length ? { key: 'recent', label: 'Recently viewed', tools: recentTools } : null
const categorySections = toolGroups.map((group) => ({
key: group.category,
@@ -75,7 +75,7 @@ export function TodayProductsSidebar(): JSX.Element {
searchLabel="Search products"
dataAttr="today-products-search"
>
- {!hasProducts && !searchedViewTypes.length && (
+ {!hasProducts && !searchedAnalyticsTypes.length && (
<Text size="xs" variant="muted" className="block px-2 py-1">
No products match that search.
</Text>
@@ -114,7 +114,9 @@ export function TodayProductsSidebar(): JSX.Element {
{categorySections.map((section, index) =>
renderToolSection(section, !recentSection && !showLibrary && index === 0)
)}
- {searchedViewTypes.length > 0 && <TodayProductsViewsHint viewTypes={searchedViewTypes} />}
+ {searchedAnalyticsTypes.length > 0 && (
+ <TodayProductsAnalyticsHint analyticsTypes={searchedAnalyticsTypes} />
+ )}
</TodayPaneSearchList>
</div>
)
diff --git a/frontend/src/layout/today/TodayShell.tsx b/frontend/src/layout/today/TodayShell.tsx
index 4ecb6e18d7cc..d1eddf88ae1b 100644
--- a/frontend/src/layout/today/TodayShell.tsx
+++ b/frontend/src/layout/today/TodayShell.tsx
@@ -26,8 +26,8 @@ import { TodaySidebarPinButton } from './TodaySidebarPinButton'
import { TodayTabBar } from './TodayTabBar'
const TodaySpacesPane = lazyWithRetry(() => import('./TodaySpacesPane').then((m) => ({ default: m.TodaySpacesPane })))
-const TodayViewsSidebar = lazyWithRetry(() =>
- import('./TodayViewsSidebar').then((m) => ({ default: m.TodayViewsSidebar }))
+const TodayAnalyticsSidebar = lazyWithRetry(() =>
+ import('./TodayAnalyticsSidebar').then((m) => ({ default: m.TodayAnalyticsSidebar }))
)
const TodayProductsSidebar = lazyWithRetry(() =>
import('./TodayProductsSidebar').then((m) => ({ default: m.TodayProductsSidebar }))
@@ -43,7 +43,7 @@ const NewSpaceDialog = lazyWithRetry(() =>
export function TodayShell({ className }: { className?: string }): JSX.Element {
const { activePane, mobileLayout, phoneLayout, sidebarVisible, sidebarWidth, phoneHeaderHidden } =
useValues(todayShellLogic)
- // Records the tools and sessions visited while other panes are open, so each pane's Recent group is ready.
+ // Records the tools visited while other panes are open, so the Tools pane's Recent group is ready.
useMountedLogic(todayRecentsLogic)
const { setMobileSidebarOpen, setSidebarOpen, setSidebarWidth, toggleSidebar } = useActions(todayShellLogic)
useShortcut({
@@ -94,8 +94,8 @@ export function TodayShell({ className }: { className?: string }): JSX.Element {
<Suspense fallback={<Skeleton className="m-4 h-24" />}>
{activePane === 'home' ? null : activePane === 'spaces' ? (
<TodaySpacesPane />
- ) : activePane === 'views' ? (
- <TodayViewsSidebar />
+ ) : activePane === 'analytics' ? (
+ <TodayAnalyticsSidebar />
) : activePane === 'settings' ? (
<TodaySettingsSidebar />
) : (
@@ -189,7 +189,7 @@ export function TodayShell({ className }: { className?: string }): JSX.Element {
sidebarVisible && (
<aside
ref={sidebarRef}
- className="group/sidebar TodayShell__sidebar TodayShell__sidebar--framed relative bg-[var(--scene-layout-background)]"
+ className="group/sidebar TodayShell__sidebar TodayShell__sidebar--framed relative bg-surface-primary"
aria-label={paneTitle}
// eslint-disable-next-line react/forbid-dom-props
style={{ width: sidebarWidth }}
diff --git a/frontend/src/layout/today/TodayViewsFilterMenu.tsx b/frontend/src/layout/today/TodayViewsFilterMenu.tsx
deleted file mode 100644
index 647e10d894aa..000000000000
--- a/frontend/src/layout/today/TodayViewsFilterMenu.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from '@posthog/quill'
-
-import { TodayFilterMenuTrigger } from './TodayFilterMenuTrigger'
-import { TodayRecentRadioSubmenu } from './TodayRecentRadioSubmenu'
-import { DEFAULT_VIEWS_FILTERS, VIEWS_CREATED_BY_OPTIONS, VIEWS_TYPE_OPTIONS } from './todayViewsFilters'
-import { todayViewsLogic } from './todayViewsLogic'
-
-/** The Views pane's filters for its recent list, laid out like the Spaces pane's. */
-export function TodayViewsFilterMenu(): JSX.Element {
- const { recentFilters: filters, recentFiltersActive: active } = useValues(todayViewsLogic)
- const { setRecentFilters, clearRecentSearchAndFilters } = useActions(todayViewsLogic)
-
- return (
- <DropdownMenu>
- <TodayFilterMenuTrigger active={active} dataAttr="today-views-filter" />
- <DropdownMenuContent align="end" className="min-w-56">
- <TodayRecentRadioSubmenu
- label="Type"
- options={VIEWS_TYPE_OPTIONS}
- value={filters.type}
- defaultValue={DEFAULT_VIEWS_FILTERS.type}
- onChange={(type) => setRecentFilters({ ...filters, type })}
- dataAttr="today-views-filter-type"
- />
- <TodayRecentRadioSubmenu
- label="Created by"
- options={VIEWS_CREATED_BY_OPTIONS}
- value={filters.createdBy}
- defaultValue={DEFAULT_VIEWS_FILTERS.createdBy}
- onChange={(createdBy) => setRecentFilters({ ...filters, createdBy })}
- dataAttr="today-views-filter-created-by"
- />
- {active && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onClick={clearRecentSearchAndFilters}
- data-attr="today-views-filter-clear"
- >
- Clear filters
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- )
-}
diff --git a/frontend/src/layout/today/TodayViewsSidebar.tsx b/frontend/src/layout/today/TodayViewsSidebar.tsx
deleted file mode 100644
index b3ea06ec22f9..000000000000
--- a/frontend/src/layout/today/TodayViewsSidebar.tsx
+++ /dev/null
@@ -1,220 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { router } from 'kea-router'
-import { useCallback, useEffect, useState } from 'react'
-import { useInView } from 'react-intersection-observer'
-
-import { IconGridMasonry } from '@posthog/icons'
-import { Button, Spinner } from '@posthog/quill'
-
-import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { urls } from 'scenes/urls'
-import { VIEW_TYPE_INFO } from 'scenes/views/viewsUtils'
-import { ViewTypeIcon } from 'scenes/views/ViewTypeIcon'
-
-import { ProductIconWrapper, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
-import { FileSystemIconType } from '~/queries/schema/schema-general'
-
-import { TodayPaneGroupLabel } from './TodayPaneGroupLabel'
-import { TodayPaneRow } from './TodayPaneRow'
-import { matchesPaneQuery } from './todayPaneSearch'
-import { TodayPaneSearchList } from './TodayPaneSearchList'
-import { TodayViewsFilterMenu } from './TodayViewsFilterMenu'
-import { todayViewsLogic } from './todayViewsLogic'
-import { shortTimeAgo } from './todayWorkItems'
-
-const SCROLL_PREFETCH_MARGIN = '600px 0px'
-
-/** The Views sub-nav: recently viewed views, then the full list, newest first. */
-export function TodayViewsSidebar(): JSX.Element {
- const {
- recentViews,
- recentReady,
- recentItems,
- recentHasMore,
- recentViewsLoading,
- recentUnavailable,
- recentQuery,
- recentFiltersActive,
- buildingViewIds,
- recentlyViewed: recents,
- } = useValues(todayViewsLogic)
- const { loadRecentViews, loadMoreRecentViews, setRecentQuery, clearRecentSearchAndFilters } =
- useActions(todayViewsLogic)
- const [scrollRoot, setScrollRoot] = useState<Element | null>(null)
- const { ref: inViewRef, inView: endInView } = useInView({
- root: scrollRoot,
- rootMargin: SCROLL_PREFETCH_MARGIN,
- skip: !scrollRoot,
- })
- const endRef = useCallback(
- (node: HTMLDivElement | null) => {
- setScrollRoot(node?.closest('.TodayPaneSearchList') ?? null)
- inViewRef(node)
- },
- [inViewRef]
- )
- const loadedCount = recentViews.items.length
-
- useEffect(() => {
- if (endInView && recentHasMore) {
- loadMoreRecentViews()
- }
- }, [endInView, recentHasMore, loadedCount, loadMoreRecentViews])
- const narrowed = recentQuery.trim() !== '' || recentFiltersActive
- const { location } = useValues(router)
- const path = removeProjectIdIfPresent(location.pathname)
- const failedTypes = recentViews.failedTypes
- const showAll = matchesPaneQuery('All views', recentQuery)
- const showAllDashboards = matchesPaneQuery('All dashboards', recentQuery)
- const showAllNotebooks = matchesPaneQuery('All notebooks', recentQuery)
-
- const retryButton = (size: 'sm' | 'xs'): JSX.Element => (
- <Button
- size={size}
- variant="outline"
- loading={recentViewsLoading}
- onClick={() => loadRecentViews()}
- data-attr="today-views-retry"
- >
- Try again
- </Button>
- )
-
- return (
- <div className="TodayPane group/colorful-product-icons colorful-product-icons-true" data-quill>
- <TodayPaneSearchList
- query={recentQuery}
- onQueryChange={setRecentQuery}
- searchLabel="Search views"
- dataAttr="today-views-search"
- searchActions={<TodayViewsFilterMenu />}
- >
- {recents.length > 0 && (
- <div>
- <TodayPaneGroupLabel first>Recently viewed</TodayPaneGroupLabel>
- {recents.map((recent) => (
- <TodayPaneRow
- key={recent.entry.id}
- value={`recent:${recent.entry.id}`}
- label={recent.name}
- icon={iconForType(recent.entry.type as FileSystemIconType)}
- to={recent.href}
- active={path === removeProjectIdIfPresent(recent.href)}
- dataAttr="today-views-recently-viewed"
- />
- ))}
- </div>
- )}
- <div>
- <TodayPaneGroupLabel first={!recents.length}>Views</TodayPaneGroupLabel>
- {showAll && (
- <TodayPaneRow
- value="all"
- label="All views"
- icon={<IconGridMasonry />}
- to={urls.views()}
- active={path === urls.views()}
- dataAttr="today-views-all"
- />
- )}
- {showAllDashboards && (
- <TodayPaneRow
- value="all-dashboards"
- label="All dashboards"
- icon={
- <ProductIconWrapper colorOverride={[VIEW_TYPE_INFO.dashboard.color]}>
- <ViewTypeIcon type="dashboard" />
- </ProductIconWrapper>
- }
- to={urls.dashboards()}
- active={path === urls.dashboards()}
- dataAttr="today-views-all-dashboards"
- />
- )}
- {showAllNotebooks && (
- <TodayPaneRow
- value="all-notebooks"
- label="All notebooks"
- icon={
- <ProductIconWrapper colorOverride={[VIEW_TYPE_INFO.notebook.color]}>
- <ViewTypeIcon type="notebook" />
- </ProductIconWrapper>
- }
- to={urls.notebooks()}
- active={path === urls.notebooks()}
- dataAttr="today-views-all-notebooks"
- />
- )}
- {recentUnavailable || !recentReady ? (
- recentUnavailable ? (
- <div className="TodayPane__state">
- <span>Your views didn’t load.</span>
- {retryButton('sm')}
- </div>
- ) : (
- <div className="TodayPane__state" aria-busy>
- <Spinner />
- </div>
- )
- ) : !recentItems.length && narrowed ? (
- <div className="TodayPane__state">
- <span>Nothing here matches.</span>
- <Button
- size="xs"
- variant="outline"
- onClick={() => clearRecentSearchAndFilters()}
- data-attr="today-views-clear-filters"
- >
- Clear filters
- </Button>
- </div>
- ) : !recentItems.length && !failedTypes.length ? (
- <div className="TodayPane__state">
- Canvases, notebooks and dashboards you create show up here.
- </div>
- ) : (
- <>
- {failedTypes.length > 0 && (
- <div className="TodayPane__state">
- <span>
- {`${failedTypes.map((type) => VIEW_TYPE_INFO[type].pluralLabel).join(' and ')} didn’t load.`}
- </span>
- {retryButton('xs')}
- </div>
- )}
- {recentItems.map((item) => {
- const building = buildingViewIds.includes(item.id)
- return (
- <TodayPaneRow
- key={`${item.type}-${item.id}`}
- value={`view:${item.type}-${item.id}`}
- label={item.name}
- icon={
- building ? (
- <Spinner />
- ) : (
- <ProductIconWrapper colorOverride={[VIEW_TYPE_INFO[item.type].color]}>
- <ViewTypeIcon type={item.type} />
- </ProductIconWrapper>
- )
- }
- meta={building ? 'Building' : shortTimeAgo(item.timestamp)}
- to={item.href}
- active={path === removeProjectIdIfPresent(item.href)}
- dataAttr={`today-views-recent-${item.type}`}
- />
- )
- })}
- {recentHasMore && (
- <div className="TodayPane__state" aria-busy>
- <Spinner />
- </div>
- )}
- <div ref={endRef} aria-hidden />
- </>
- )}
- </div>
- </TodayPaneSearchList>
- </div>
- )
-}
diff --git a/frontend/src/layout/today/todayAnalyticsLogic.test.ts b/frontend/src/layout/today/todayAnalyticsLogic.test.ts
new file mode 100644
index 000000000000..28df12627c4a
--- /dev/null
+++ b/frontend/src/layout/today/todayAnalyticsLogic.test.ts
@@ -0,0 +1,34 @@
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { DEFAULT_COLLAPSED_SECTIONS, todayAnalyticsLogic } from './todayAnalyticsLogic'
+
+describe('todayAnalyticsLogic', () => {
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/task_channels/': [],
+ '/api/projects/:team_id/canvases/': { results: [], next: null },
+ '/api/projects/:team_id/notebooks/': { results: [], next: null },
+ '/api/projects/:team_id/dashboards/': { results: [], next: null },
+ '/api/projects/:team_id/insights/': { results: [], next: null },
+ },
+ })
+ initKeaTests()
+ })
+
+ it('starts with every section open, and remembers a toggled section', () => {
+ const logic = todayAnalyticsLogic()
+ logic.mount()
+ expect(logic.values.collapsedSections).toEqual(DEFAULT_COLLAPSED_SECTIONS)
+ expect(logic.values.collapsedSections).toEqual([])
+
+ logic.actions.toggleSection('monitor')
+ expect(logic.values.collapsedSections).toEqual(['monitor'])
+
+ logic.unmount()
+ const remounted = todayAnalyticsLogic()
+ remounted.mount()
+ expect(remounted.values.collapsedSections).toEqual(['monitor'])
+ })
+})
diff --git a/frontend/src/layout/today/todayAnalyticsLogic.ts b/frontend/src/layout/today/todayAnalyticsLogic.ts
new file mode 100644
index 000000000000..4f05f87b25f6
--- /dev/null
+++ b/frontend/src/layout/today/todayAnalyticsLogic.ts
@@ -0,0 +1,150 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { toast } from '@posthog/quill'
+
+import api from 'lib/api'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { FromPostHogItem, fromPostHogItems } from 'scenes/analytics/analyticsUtils'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { escapePath } from '~/layout/panel-layout/ProjectTree/utils'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+// pinned: persisted section ids and the `section` property of `analytics section toggled`.
+export type TodayAnalyticsSection = 'browse' | 'monitor' | 'by-posthog'
+
+export const DEFAULT_COLLAPSED_SECTIONS: TodayAnalyticsSection[] = []
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayAnalyticsLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ collapsedSections: TodayAnalyticsSection[]
+ creatingFolder: boolean
+ fromPostHog: FromPostHogItem[]
+ newFolderDialogOpen: boolean
+ newFolderParent: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayAnalyticsLogicActions {
+ createSavedItem: (savedItem: FileSystemEntry) => {
+ savedItem: FileSystemEntry
+ } // projectTreeDataLogic
+ createFolder: (name: string) => {
+ name: string
+ }
+ folderCreated: () => {
+ value: true
+ }
+ folderCreationFailed: () => {
+ value: true
+ }
+ setNewFolderDialogOpen: (
+ open: boolean,
+ parent?: string | null
+ ) => {
+ open: boolean
+ parent: string | null
+ }
+ toggleSection: (section: TodayAnalyticsSection) => {
+ section: TodayAnalyticsSection
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface todayAnalyticsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ fromPostHog: (featureFlags: FeatureFlagsSet) => FromPostHogItem[]
+ }
+}
+
+export type todayAnalyticsLogicType = MakeLogicType<
+ todayAnalyticsLogicValues,
+ todayAnalyticsLogicActions,
+ Record<string, any>,
+ todayAnalyticsLogicMeta
+>
+
+export const todayAnalyticsLogic = kea<todayAnalyticsLogicType>([
+ path(['layout', 'today', 'todayAnalyticsLogic']),
+ connect(() => ({
+ values: [featureFlagLogic, ['featureFlags']],
+ actions: [projectTreeDataLogic, ['createSavedItem']],
+ })),
+ actions({
+ toggleSection: (section: TodayAnalyticsSection) => ({ section }),
+ setNewFolderDialogOpen: (open: boolean, parent: string | null = null) => ({ open, parent }),
+ createFolder: (name: string) => ({ name }),
+ folderCreated: true,
+ folderCreationFailed: true,
+ }),
+ reducers({
+ // pinned: storage key for the persisted sections. Renaming it reopens everyone's sections.
+ collapsedSections: [
+ DEFAULT_COLLAPSED_SECTIONS,
+ { persist: true },
+ {
+ toggleSection: (state, { section }) =>
+ state.includes(section) ? state.filter((id) => id !== section) : [...state, section],
+ },
+ ],
+ // The collection a folder is created in, or null for a new top-level collection.
+ newFolderParent: [null as string | null, { setNewFolderDialogOpen: (_, { parent }) => parent }],
+ newFolderDialogOpen: [
+ false,
+ {
+ setNewFolderDialogOpen: (_, { open }) => open,
+ folderCreated: () => false,
+ },
+ ],
+ creatingFolder: [
+ false,
+ {
+ createFolder: () => true,
+ folderCreated: () => false,
+ folderCreationFailed: () => false,
+ },
+ ],
+ }),
+ selectors({
+ fromPostHog: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): FromPostHogItem[] => fromPostHogItems(featureFlags),
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ toggleSection: ({ section }) => {
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('analytics section toggled', {
+ section,
+ open: !values.collapsedSections.includes(section),
+ })
+ },
+ createFolder: async ({ name }) => {
+ const parent = values.newFolderParent
+ // One name is one segment: a slash in it must not create a nested folder.
+ const path = parent ? `${parent}/${escapePath(name.trim())}` : escapePath(name.trim())
+ if (!name.trim()) {
+ actions.folderCreationFailed()
+ return
+ }
+ try {
+ // The project tree keeps the rows, so the new folder shows wherever the tree is open.
+ const entry = await api.fileSystem.create({ path, type: 'folder' } as FileSystemEntry)
+ actions.createSavedItem(entry)
+ actions.folderCreated()
+ // pinned: analytics event name. Renaming it breaks dashboards.
+ posthog.capture('analytics folder created', { nested: parent !== null })
+ toast.success({ title: parent ? 'Folder created' : 'Collection created' })
+ } catch {
+ actions.folderCreationFailed()
+ toast.error({
+ title: parent
+ ? 'Couldn’t create the folder. Try again.'
+ : 'Couldn’t create the collection. Try again.',
+ })
+ }
+ },
+ })),
+])
diff --git a/frontend/src/layout/today/todayPaneSearch.test.ts b/frontend/src/layout/today/todayPaneSearch.test.ts
index d2c1548a63ba..f247b16f7eb9 100644
--- a/frontend/src/layout/today/todayPaneSearch.test.ts
+++ b/frontend/src/layout/today/todayPaneSearch.test.ts
@@ -1,4 +1,4 @@
-import { viewTypesForPaneSearch } from './todayPaneSearch'
+import { analyticsTypesForPaneSearch } from './todayPaneSearch'
describe('todayPaneSearch', () => {
test.each([
@@ -6,9 +6,10 @@ describe('todayPaneSearch', () => {
['My Dashboards', ['dashboard']],
['notebook', ['notebook']],
['canvas', ['canvas']],
+ ['insights', ['insight']],
['da', []],
['feature flags', []],
- ])('points a Products search for %s to these view types: %j', (search, types) => {
- expect(viewTypesForPaneSearch(search).map((info) => info.type)).toEqual(types)
+ ])('points a Products search for %s to these analytics types: %j', (search, types) => {
+ expect(analyticsTypesForPaneSearch(search).map((info) => info.type)).toEqual(types)
})
})
diff --git a/frontend/src/layout/today/todayPaneSearch.ts b/frontend/src/layout/today/todayPaneSearch.ts
index 1f2b839bec34..b5862a2c056a 100644
--- a/frontend/src/layout/today/todayPaneSearch.ts
+++ b/frontend/src/layout/today/todayPaneSearch.ts
@@ -1,20 +1,20 @@
-import { VIEW_TYPES, ViewTypeInfo } from 'scenes/views/viewsUtils'
+import { ANALYTICS_TYPES, AnalyticsTypeInfo } from 'scenes/analytics/analyticsUtils'
export function matchesPaneQuery(label: string, query: string): boolean {
const needle = query.trim().toLowerCase()
return needle === '' || label.toLowerCase().includes(needle)
}
-// A shorter search, like "da", matches too many words to mean a view type.
-const VIEW_TYPE_SEARCH_MIN_LENGTH = 3
+// A shorter search, like "da", matches too many words to mean an analytics type.
+const ANALYTICS_TYPE_SEARCH_MIN_LENGTH = 3
-export function viewTypesForPaneSearch(search: string): ViewTypeInfo[] {
+export function analyticsTypesForPaneSearch(search: string): AnalyticsTypeInfo[] {
const query = search.trim().toLowerCase()
- if (query.length < VIEW_TYPE_SEARCH_MIN_LENGTH) {
+ if (query.length < ANALYTICS_TYPE_SEARCH_MIN_LENGTH) {
return []
}
// The second check catches a search that wraps the type name, like "my dashboards".
- return VIEW_TYPES.filter(
+ return ANALYTICS_TYPES.filter(
(info) => matchesPaneQuery(info.pluralLabel, query) || query.includes(info.label.toLowerCase())
)
}
diff --git a/frontend/src/layout/today/todayRailItems.tsx b/frontend/src/layout/today/todayRailItems.tsx
index 869e9b281a89..5162329f30b9 100644
--- a/frontend/src/layout/today/todayRailItems.tsx
+++ b/frontend/src/layout/today/todayRailItems.tsx
@@ -1,18 +1,10 @@
-import {
- IconApps,
- IconChat,
- IconGear,
- IconGridMasonry,
- IconHome,
- IconSidebarClose,
- IconSidebarOpen,
-} from '@posthog/icons'
+import { IconApps, IconChat, IconGear, IconHome, IconSidebarClose, IconSidebarOpen, IconTrends } from '@posthog/icons'
import { isMac } from 'lib/utils/dom'
import { urls } from 'scenes/urls'
+import { TodayNewAnalyticsButton } from './TodayNewAnalyticsButton'
import { TodayNewChatButton } from './TodayNewChatButton'
-import { TodayNewViewButton } from './TodayNewViewButton'
import type { TodayRailPane } from './todayShellLogic'
export interface TodayPane {
@@ -34,12 +26,13 @@ export const TODAY_PANES: Record<TodayRailPane, TodayPane> = {
home: () => urls.taskNewSession(),
action: TodayNewChatButton,
},
- views: { label: 'Views', title: 'Views', icon: <IconGridMasonry />, action: TodayNewViewButton },
+ // No home: like Products, a pick only opens the sidebar and the open page stays.
+ analytics: { label: 'Analytics', title: 'Analytics', icon: <IconTrends />, action: TodayNewAnalyticsButton },
products: { label: 'Products', title: 'Products', icon: <IconApps /> },
settings: { label: 'Settings', title: 'Settings', icon: <IconGear />, home: () => urls.settings('project') },
}
-export const TODAY_RAIL_PANES: TodayRailPane[] = ['home', 'spaces', 'views', 'products']
+export const TODAY_RAIL_PANES: TodayRailPane[] = ['home', 'spaces', 'analytics', 'products']
export const TODAY_RAIL_FOOTER_PANES: TodayRailPane[] = ['settings']
export function todaySidebarShortcutLabel(): string {
diff --git a/frontend/src/layout/today/todayRecentsLogic.ts b/frontend/src/layout/today/todayRecentsLogic.ts
index e34434d7c6db..75a5953284d2 100644
--- a/frontend/src/layout/today/todayRecentsLogic.ts
+++ b/frontend/src/layout/today/todayRecentsLogic.ts
@@ -1,42 +1,25 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'
import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { VIEW_FILE_SYSTEM_TYPES, baseObjectType, libraryObjectHref } from 'scenes/library/libraryUtils'
import { toolHrefForPath } from 'scenes/tools/toolsUtils'
-import { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'
-import { recentItemsModel } from '~/models/recentItemsModel'
-import { FileSystemEntry } from '~/queries/schema/schema-general'
-
export const TODAY_RECENTS_LIMIT = 5
-export interface TodayRecentEntry {
- entry: FileSystemEntry
- name: string
- href: string
-}
-
function pushRecent(list: string[], value: string): string[] {
return [value, ...list.filter((item) => item !== value)].slice(0, TODAY_RECENTS_LIMIT)
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayRecentsLogicValues {
- recents: FileSystemEntry[] // recentItemsModel
recentToolHrefs: string[]
- recentViewEntries: TodayRecentEntry[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayRecentsLogicActions {
- recordLocation: (
- pathname: string,
- searchParams: Record<string, any>
- ) => {
+ recordLocation: (pathname: string) => {
pathname: string
- searchParams: Record<string, any>
}
recordToolVisit: (href: string) => {
href: string
@@ -45,9 +28,6 @@ export interface todayRecentsLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayRecentsLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- recentViewEntries: (recents: FileSystemEntry[]) => TodayRecentEntry[]
- }
__keaTypeGenInternalReducerActions: {
'location changed (kea.router)': ({
method,
@@ -84,15 +64,14 @@ export type todayRecentsLogicType = MakeLogicType<
>
/**
- * What the sidebar panes list as recently viewed. Views reads the project's recently viewed objects.
+ * What the Tools pane lists as recently viewed.
* Tools have no server record of views, so this browser keeps one as the user moves between pages.
*/
export const todayRecentsLogic = kea<todayRecentsLogicType>([
path(['layout', 'today', 'todayRecentsLogic']),
- connect(() => ({ values: [recentItemsModel, ['recents']] })),
actions({
recordToolVisit: (href: string) => ({ href }),
- recordLocation: (pathname: string, searchParams: Record<string, any>) => ({ pathname, searchParams }),
+ recordLocation: (pathname: string) => ({ pathname }),
}),
reducers({
// pinned: storage keys for persisted state. Renaming them clears everyone's recents.
@@ -102,22 +81,6 @@ export const todayRecentsLogic = kea<todayRecentsLogicType>([
{ recordToolVisit: (state, { href }) => pushRecent(state, href) },
],
}),
- selectors({
- recentViewEntries: [
- (s) => [s.recents],
- (recents: FileSystemEntry[]): TodayRecentEntry[] =>
- recents
- .flatMap((entry) => {
- const href = VIEW_FILE_SYSTEM_TYPES.has(baseObjectType(entry.type))
- ? libraryObjectHref(entry)
- : null
- return href
- ? [{ entry, href, name: unescapePath(splitPath(entry.path).pop() ?? entry.path) }]
- : []
- })
- .slice(0, TODAY_RECENTS_LIMIT),
- ],
- }),
listeners(({ actions }) => ({
recordLocation: ({ pathname }) => {
const path = removeProjectIdIfPresent(pathname)
@@ -126,12 +89,11 @@ export const todayRecentsLogic = kea<todayRecentsLogicType>([
actions.recordToolVisit(toolHref)
}
},
- [router.actionTypes.locationChanged]: ({ pathname, searchParams }: LocationChangedPayload) => {
- actions.recordLocation(pathname, searchParams)
+ [router.actionTypes.locationChanged]: ({ pathname }: LocationChangedPayload) => {
+ actions.recordLocation(pathname)
},
})),
afterMount(({ actions }) => {
- const { location, searchParams } = router.values
- actions.recordLocation(location.pathname, searchParams)
+ actions.recordLocation(router.values.location.pathname)
}),
])
diff --git a/frontend/src/layout/today/todayShellLogic.test.ts b/frontend/src/layout/today/todayShellLogic.test.ts
index 7eaf7c5318d5..4af2c9d1697f 100644
--- a/frontend/src/layout/today/todayShellLogic.test.ts
+++ b/frontend/src/layout/today/todayShellLogic.test.ts
@@ -29,17 +29,22 @@ describe('todayShellLogic', () => {
['/project/1/ai/history', 'spaces'],
['/project/1/spaces/abc', 'spaces'],
['/project/1/feature_flags/920847', 'products'],
- ['/project/1/insights/abc', 'products'],
+ ['/project/1/insights/abc', 'analytics'],
+ ['/project/1/insights', 'analytics'],
['/project/1/feature_flags', 'products'],
['/project/1/data-management/destinations', 'products'],
+ ['/project/1/web', 'analytics'],
+ ['/project/1/marketing', 'analytics'],
+ ['/project/1/mcp-analytics', 'analytics'],
['/project/1/sql', 'products'],
- ['/project/1/views', 'views'],
- ['/project/1/canvases/abc', 'views'],
- ['/project/1/canvases/new', 'views'],
- ['/project/1/notebooks/abc', 'views'],
- ['/project/1/dashboard/12', 'views'],
- ['/project/1/notebooks', 'views'],
- ['/project/1/dashboard', 'views'],
+ ['/project/1/analytics', 'analytics'],
+ ['/project/1/analytics/all', 'analytics'],
+ ['/project/1/canvases/abc', 'analytics'],
+ ['/project/1/canvases/new', 'analytics'],
+ ['/project/1/notebooks/abc', 'analytics'],
+ ['/project/1/dashboard/12', 'analytics'],
+ ['/project/1/notebooks', 'analytics'],
+ ['/project/1/dashboard', 'analytics'],
['/project/1/persons', 'products'],
['/project/1/activity/events', 'products'],
['/project/1/settings/project-replay', 'settings'],
@@ -77,14 +82,14 @@ describe('todayShellLogic', () => {
expect(rows.includes(label)).toBe(ownRow)
})
- it('finds the Insights row with a search for the Product analytics name', () => {
- expect(libraryRowProductLabels('insight')).toContain('Product analytics')
+ it('finds the Feature flags row with a search for the product name', () => {
+ expect(libraryRowProductLabels('feature_flag')).toContain('Feature flags')
})
test.each([
['home', '/home'],
['spaces', '/spaces/new'],
- ['views', '/airplane'],
+ ['analytics', '/airplane'],
['products', '/airplane'],
] as const)('opens the %s section when its rail item is picked', (pane, pathname) => {
const logic = todayShellLogic()
@@ -96,7 +101,7 @@ describe('todayShellLogic', () => {
expect(logic.values.activePane).toBe(pane)
})
- test.each(['spaces', 'views', 'products'] as const)(
+ test.each(['spaces', 'analytics', 'products'] as const)(
'a second rail click on %s hides the sidebar it opened',
(pane) => {
const logic = todayShellLogic()
@@ -166,7 +171,7 @@ describe('todayShellLogic', () => {
router.actions.push('/project/1/cohorts')
expect(logic.values.sidebarVisible).toBe(false)
- logic.actions.pickPane('views')
+ logic.actions.pickPane('analytics')
expect(logic.values.sidebarVisible).toBe(true)
})
it('keeps the rail on narrow windows and opens the sidebar as a drawer that closes on navigation', () => {
diff --git a/frontend/src/layout/today/todayShellLogic.ts b/frontend/src/layout/today/todayShellLogic.ts
index 9a9732428ea3..cd8d9bc97c15 100644
--- a/frontend/src/layout/today/todayShellLogic.ts
+++ b/frontend/src/layout/today/todayShellLogic.ts
@@ -8,6 +8,7 @@ import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { isUnderPath, removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { fromPostHogProducts } from 'scenes/analytics/analyticsUtils'
import { libraryTypeForPath } from 'scenes/library/libraryUtils'
import { settingsSectionSceneForPath } from 'scenes/settings/settingsSectionScenes'
import { toolHrefForPath } from 'scenes/tools/toolsUtils'
@@ -17,7 +18,7 @@ import { navigationLogic } from '~/layout/navigation/navigationLogic'
import { TODAY_PANES } from './todayRailItems'
-export type TodayRailPane = 'home' | 'spaces' | 'views' | 'products' | 'settings'
+export type TodayRailPane = 'home' | 'spaces' | 'analytics' | 'products' | 'settings'
/** What showed or hid the sidebar. `navigation` is a page change that hides the unpinned sidebar. */
export type TodaySidebarToggleSource =
@@ -79,14 +80,16 @@ export function railPaneForPath(pathname: string): TodayRailPane | null {
if (isUnderPath(path, '/ai') || isUnderPath(path, '/spaces')) {
return 'spaces'
}
- // Notebooks and dashboards are views, list pages included, so they never open the Products pane.
+ // Notebooks, dashboards and insights are analytics, list pages included, so they never open the Products pane.
if (
- isUnderPath(path, urls.views()) ||
+ isUnderPath(path, urls.analytics()) ||
isUnderPath(path, '/canvases') ||
isUnderPath(path, urls.notebooks()) ||
- isUnderPath(path, urls.dashboards())
+ isUnderPath(path, urls.dashboards()) ||
+ isUnderPath(path, '/insights') ||
+ fromPostHogProducts().some((product) => isUnderPath(path, product.href.split(/[?#]/)[0]))
) {
- return 'views'
+ return 'analytics'
}
if (isUnderPath(path, '/settings') || settingsSectionSceneForPath(path)) {
return 'settings'
diff --git a/frontend/src/layout/today/todayToolsLogic.ts b/frontend/src/layout/today/todayToolsLogic.ts
index bd20c4191b24..11b8eae0dcb5 100644
--- a/frontend/src/layout/today/todayToolsLogic.ts
+++ b/frontend/src/layout/today/todayToolsLogic.ts
@@ -47,11 +47,11 @@ export const todayToolsLogic = kea<todayToolsLogicType>([
actions({ setSearch: (search: string) => ({ search }) }),
reducers({ search: ['', { setSearch: (_, { search }) => search }] }),
selectors({
- // Tools whose pages open another pane, like dashboards and notebooks under Views, stay out of Products.
+ // Tools whose pages open another pane, like dashboards and notebooks under Analytics, stay out of Products.
productTools: [
(s) => [s.tools],
(tools: FileSystemImport[]): FileSystemImport[] =>
- tools.filter((tool) => !tool.href || railPaneForPath(tool.href.split('?')[0]) !== 'views'),
+ tools.filter((tool) => !tool.href || railPaneForPath(tool.href.split('?')[0]) !== 'analytics'),
],
toolGroups: [
(s) => [s.productTools, s.search],
diff --git a/frontend/src/layout/today/todayViewsFilters.ts b/frontend/src/layout/today/todayViewsFilters.ts
deleted file mode 100644
index 28d090f6c509..000000000000
--- a/frontend/src/layout/today/todayViewsFilters.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { VIEW_TYPES, ViewItem, ViewTypeFilter } from 'scenes/views/viewsUtils'
-
-import { RECENT_CREATED_BY_OPTIONS, TodayRecentCreatedByFilter } from './todayRecentFilters'
-
-export interface TodayViewsFilters {
- type: ViewTypeFilter
- createdBy: TodayRecentCreatedByFilter
-}
-
-export const DEFAULT_VIEWS_FILTERS: TodayViewsFilters = { type: 'all', createdBy: 'anyone' }
-
-export const VIEWS_TYPE_OPTIONS: { value: ViewTypeFilter; label: string }[] = [
- { value: 'all', label: 'All' },
- ...VIEW_TYPES.map((info) => ({ value: info.type, label: info.pluralLabel })),
-]
-
-export const VIEWS_CREATED_BY_OPTIONS = RECENT_CREATED_BY_OPTIONS
-
-export function viewsFiltersActive(filters: TodayViewsFilters): boolean {
- return filters.type !== DEFAULT_VIEWS_FILTERS.type || filters.createdBy !== DEFAULT_VIEWS_FILTERS.createdBy
-}
-
-/** The views that match the search and the filters, in their original order. */
-export function filterRecentViews(
- items: ViewItem[],
- query: string,
- filters: TodayViewsFilters,
- currentUserUuid: string | null
-): ViewItem[] {
- const needle = query.trim().toLowerCase()
- return items.filter(
- (item) =>
- (!needle || item.name.toLowerCase().includes(needle)) &&
- (filters.type === 'all' || item.type === filters.type) &&
- (filters.createdBy === 'anyone' ||
- // A view with no known creator is neither yours nor someone else's.
- (!!item.createdByUuid && (filters.createdBy === 'me') === (item.createdByUuid === currentUserUuid)))
- )
-}
diff --git a/frontend/src/layout/today/todayViewsLogic.ts b/frontend/src/layout/today/todayViewsLogic.ts
deleted file mode 100644
index 4f289758b267..000000000000
--- a/frontend/src/layout/today/todayViewsLogic.ts
+++ /dev/null
@@ -1,427 +0,0 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-import { router } from 'kea-router'
-import type { LocationChangedPayload } from 'kea-router/lib/types'
-
-import { teamLogic } from 'scenes/teamLogic'
-import { userLogic } from 'scenes/userLogic'
-import { VIEW_FEED_PAGE_SIZE, ViewFeed, ViewFeedQuery, ViewSourceState } from 'scenes/views/viewFeed'
-import { selectViewFeed, viewFeedLogic } from 'scenes/views/viewFeedLogic'
-import { ViewItem } from 'scenes/views/viewsUtils'
-
-import type { UserType } from '~/types'
-
-import { canvasesRetrieve } from 'products/canvas/frontend/generated/api'
-import { tasksRetrieve } from 'products/tasks/frontend/generated/api'
-
-import { matchesPaneQuery } from './todayPaneSearch'
-import { TodayRecentEntry, todayRecentsLogic } from './todayRecentsLogic'
-import { railPaneForPath } from './todayShellLogic'
-import { DEFAULT_VIEWS_FILTERS, TodayViewsFilters, filterRecentViews, viewsFiltersActive } from './todayViewsFilters'
-
-const ALL_RECENT_QUERY: ViewFeedQuery = { type: 'all', search: '' }
-const FIRST_BUILD_POLL_MS = 5000
-// pinned: task run statuses from the tasks API
-const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed', 'cancelled'])
-
-/** Whether a canvas on its first build has its first version yet, and where its run is. */
-export interface FirstBuildState {
- hasVersion: boolean
- runStatus: string | null
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface todayViewsLogicValues {
- currentTeamId: number | null // teamLogic
- recentViewEntries: TodayRecentEntry[] // todayRecentsLogic
- user: UserType | null // userLogic
- sources: Record<string, ViewSourceState> // viewFeedLogic
- spaceNames: Record<string, string> // viewFeedLogic
- allRecentViews: ViewFeed
- buildingViewIds: string[]
- firstBuilds: Record<string, FirstBuildState>
- firstBuildsLoading: boolean
- openCanvasBuilding: Record<string, boolean>
- recentFeedQuery: ViewFeedQuery
- recentFilters: TodayViewsFilters
- recentFiltersActive: boolean
- recentHasMore: boolean
- recentItems: ViewItem[]
- recentQuery: string
- recentReady: boolean
- recentSearch: string
- recentUnavailable: boolean
- recentViews: ViewFeed
- recentViewsLoading: boolean
- recentlyViewed: TodayRecentEntry[]
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface todayViewsLogicActions {
- ensureFeed: (
- query: ViewFeedQuery,
- count: number
- ) => {
- count: number
- query: ViewFeedQuery
- } // viewFeedLogic
- refreshFeed: (query: ViewFeedQuery) => {
- query: ViewFeedQuery
- } // viewFeedLogic
- sourceRefreshed: (
- key: string,
- generation: number,
- page: null | import('scenes/views/viewFeed').ViewSourcePage
- ) => {
- generation: number
- key: string
- page: null | import('scenes/views/viewFeed').ViewSourcePage
- } // viewFeedLogic
- clearRecentSearchAndFilters: () => {
- value: true
- }
- loadFirstBuilds: (_: void) => void
- loadFirstBuildsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadFirstBuildsSuccess: (
- firstBuilds: {
- [k: string]: FirstBuildState
- },
- payload?: void
- ) => {
- firstBuilds: {
- [k: string]: FirstBuildState
- }
- payload?: void
- }
- loadMoreRecentViews: () => {
- value: true
- }
- loadRecentViews: () => {
- value: true
- }
- setOpenCanvasBuilding: (
- canvasId: string,
- building: boolean | null
- ) => {
- building: boolean | null
- canvasId: string
- }
- setRecentFilters: (filters: TodayViewsFilters) => {
- filters: TodayViewsFilters
- }
- setRecentQuery: (query: string) => {
- query: string
- }
- setRecentSearch: (search: string) => {
- search: string
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface todayViewsLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- recentlyViewed: (recentViewEntries: TodayRecentEntry[], recentQuery: string) => TodayRecentEntry[]
- recentFiltersActive: (recentFilters: TodayViewsFilters) => boolean
- recentFeedQuery: (
- recentFilters: TodayViewsFilters,
- recentSearch: string,
- user: UserType | null
- ) => ViewFeedQuery
- allRecentViews: (
- sources: Record<string, ViewSourceState>,
- spaceNames: Record<string, string>,
- currentTeamId: number | null
- ) => ViewFeed
- recentViews: (
- sources: Record<string, ViewSourceState>,
- spaceNames: Record<string, string>,
- currentTeamId: number | null,
- recentFeedQuery: ViewFeedQuery
- ) => ViewFeed
- recentViewsLoading: (recentViews: ViewFeed) => boolean
- recentUnavailable: (recentViews: ViewFeed) => boolean
- recentReady: (recentViews: ViewFeed, allRecentViews: ViewFeed) => boolean
- recentItems: (
- recentViews: ViewFeed,
- allRecentViews: ViewFeed,
- recentFeedQuery: ViewFeedQuery,
- recentQuery: string,
- recentFilters: TodayViewsFilters,
- user: UserType | null
- ) => ViewItem[]
- recentHasMore: (recentViews: ViewFeed, recentFeedQuery: ViewFeedQuery, recentQuery: string) => boolean
- buildingViewIds: (
- allRecentViews: ViewFeed,
- firstBuilds: Record<string, FirstBuildState>,
- openCanvasBuilding: Record<string, boolean>
- ) => string[]
- }
- __keaTypeGenInternalReducerActions: {
- 'location changed (kea.router)': ({
- method,
- pathname,
- search,
- searchParams,
- hash,
- hashParams,
- initial,
- url,
- routerState,
- }: LocationChangedPayload) => {
- payload: {
- hash: string
- hashParams: Record<string, any>
- initial: boolean
- method: 'POP' | 'PUSH' | 'REPLACE'
- pathname: string
- routerState: Record<string, any>
- search: string
- searchParams: Record<string, any>
- url: string
- }
- type: 'location changed (kea.router)'
- }
- }
-}
-
-export type todayViewsLogicType = MakeLogicType<
- todayViewsLogicValues,
- todayViewsLogicActions,
- Record<string, any>,
- todayViewsLogicMeta
->
-
-export const todayViewsLogic = kea<todayViewsLogicType>([
- path(['layout', 'today', 'todayViewsLogic']),
- connect(() => ({
- values: [
- teamLogic,
- ['currentTeamId'],
- userLogic,
- ['user'],
- todayRecentsLogic,
- ['recentViewEntries'],
- viewFeedLogic,
- ['sources', 'spaceNames'],
- ],
- actions: [viewFeedLogic, ['ensureFeed', 'refreshFeed', 'sourceRefreshed']],
- })),
- actions({
- loadRecentViews: true,
- loadMoreRecentViews: true,
- setRecentQuery: (query: string) => ({ query }),
- setRecentSearch: (search: string) => ({ search }),
- setRecentFilters: (filters: TodayViewsFilters) => ({ filters }),
- clearRecentSearchAndFilters: true,
- /** The open canvas reports whether its agent or a build is at work, which it knows exactly. Null when it closes. */
- setOpenCanvasBuilding: (canvasId: string, building: boolean | null) => ({ canvasId, building }),
- }),
- loaders(({ values }) => ({
- // A canvas on its first build has nothing to show until its first version, so until then its run
- // says whether the agent is building it. Later runs stay open after the agent's turn, so they cannot.
- firstBuilds: [
- {} as Record<string, FirstBuildState>,
- {
- loadFirstBuilds: async (_: void, breakpoint) => {
- const projectId = values.currentTeamId ? String(values.currentTeamId) : null
- const pending = values.allRecentViews.items.filter((item) => item.firstBuildTaskId)
- if (!projectId || !pending.length) {
- return {}
- }
- const results = await Promise.allSettled(
- pending.map(async (item): Promise<[string, FirstBuildState]> => {
- const [canvas, task] = await Promise.all([
- canvasesRetrieve(projectId, item.id),
- tasksRetrieve(projectId, item.firstBuildTaskId as string),
- ])
- return [
- item.id,
- { hasVersion: !!canvas.current_version_id, runStatus: task.latest_run?.status ?? null },
- ]
- })
- )
- breakpoint()
- // A canvas whose lookup failed shows no spinner rather than holding up the rest.
- return Object.fromEntries(
- results.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []))
- )
- },
- },
- ],
- })),
- reducers({
- recentQuery: ['', { setRecentQuery: (_, { query }) => query, clearRecentSearchAndFilters: () => '' }],
- recentSearch: ['', { setRecentSearch: (_, { search }) => search, clearRecentSearchAndFilters: () => '' }],
- recentFilters: [
- DEFAULT_VIEWS_FILTERS,
- { persist: true },
- {
- setRecentFilters: (_, { filters }) => filters,
- clearRecentSearchAndFilters: () => DEFAULT_VIEWS_FILTERS,
- },
- ],
- openCanvasBuilding: [
- {} as Record<string, boolean>,
- {
- setOpenCanvasBuilding: (state, { canvasId, building }) => {
- const { [canvasId]: _, ...rest } = state
- return building === null ? rest : { ...rest, [canvasId]: building }
- },
- },
- ],
- }),
- selectors({
- recentlyViewed: [
- (s) => [s.recentViewEntries, s.recentQuery],
- (recentViewEntries: TodayRecentEntry[], recentQuery: string): TodayRecentEntry[] =>
- recentViewEntries.filter((recent) => matchesPaneQuery(recent.name, recentQuery)),
- ],
- recentFiltersActive: [
- (s) => [s.recentFilters],
- (recentFilters: TodayViewsFilters): boolean => viewsFiltersActive(recentFilters),
- ],
- recentFeedQuery: [
- (s) => [s.recentFilters, s.recentSearch, s.user],
- (recentFilters: TodayViewsFilters, recentSearch: string, user: UserType | null): ViewFeedQuery => ({
- type: recentFilters.type,
- search: recentSearch.trim(),
- createdBy: recentFilters.createdBy === 'me' ? (user?.uuid ?? null) : null,
- }),
- ],
- allRecentViews: [
- (s) => [s.sources, s.spaceNames, s.currentTeamId],
- (
- sources: Record<string, ViewSourceState>,
- spaceNames: Record<string, string>,
- currentTeamId: number | null
- ): ViewFeed => selectViewFeed(sources, spaceNames, currentTeamId, ALL_RECENT_QUERY),
- ],
- recentViews: [
- (s) => [s.sources, s.spaceNames, s.currentTeamId, s.recentFeedQuery],
- (
- sources: Record<string, ViewSourceState>,
- spaceNames: Record<string, string>,
- currentTeamId: number | null,
- recentFeedQuery: ViewFeedQuery
- ): ViewFeed => selectViewFeed(sources, spaceNames, currentTeamId, recentFeedQuery),
- ],
- recentViewsLoading: [(s) => [s.recentViews], (recentViews: ViewFeed): boolean => recentViews.loading],
- recentUnavailable: [(s) => [s.recentViews], (recentViews: ViewFeed): boolean => recentViews.loadFailed],
- recentReady: [
- (s) => [s.recentViews, s.allRecentViews],
- (recentViews: ViewFeed, allRecentViews: ViewFeed): boolean =>
- recentViews.initialized || allRecentViews.initialized,
- ],
- recentItems: [
- (s) => [s.recentViews, s.allRecentViews, s.recentFeedQuery, s.recentQuery, s.recentFilters, s.user],
- (
- recentViews: ViewFeed,
- allRecentViews: ViewFeed,
- recentFeedQuery: ViewFeedQuery,
- recentQuery: string,
- recentFilters: TodayViewsFilters,
- user: UserType | null
- ): ViewItem[] => {
- const userUuid = user?.uuid ?? null
- if (recentViews.initialized && recentQuery.trim() === recentFeedQuery.search) {
- return filterRecentViews(recentViews.items, '', recentFilters, userUuid)
- }
- return filterRecentViews(allRecentViews.items, recentQuery, recentFilters, userUuid)
- },
- ],
- recentHasMore: [
- (s) => [s.recentViews, s.recentFeedQuery, s.recentQuery],
- (recentViews: ViewFeed, recentFeedQuery: ViewFeedQuery, recentQuery: string): boolean =>
- recentViews.initialized && recentViews.hasMore && recentQuery.trim() === recentFeedQuery.search,
- ],
- buildingViewIds: [
- (s) => [s.allRecentViews, s.firstBuilds, s.openCanvasBuilding],
- (
- allRecentViews: ViewFeed,
- firstBuilds: Record<string, FirstBuildState>,
- openCanvasBuilding: Record<string, boolean>
- ): string[] =>
- allRecentViews.items
- .filter((item) => {
- if (item.id in openCanvasBuilding) {
- return openCanvasBuilding[item.id]
- }
- const firstBuild = firstBuilds[item.id]
- return (
- !!item.firstBuildTaskId &&
- !!firstBuild &&
- !firstBuild.hasVersion &&
- !!firstBuild.runStatus &&
- !TERMINAL_RUN_STATUSES.has(firstBuild.runStatus)
- )
- })
- .map((item) => item.id),
- ],
- }),
- listeners(({ actions, values, cache }) => ({
- loadRecentViews: () => {
- actions.refreshFeed(ALL_RECENT_QUERY)
- if (
- values.recentFeedQuery.type !== 'all' ||
- values.recentFeedQuery.search ||
- values.recentFeedQuery.createdBy
- ) {
- actions.refreshFeed(values.recentFeedQuery)
- }
- },
- sourceRefreshed: () => {
- if (values.allRecentViews.initialized && !values.allRecentViews.loading) {
- actions.loadFirstBuilds()
- }
- },
- setRecentQuery: async ({ query }, breakpoint) => {
- if (query.trim() !== values.recentSearch) {
- await breakpoint(query.trim() ? 200 : 0)
- actions.setRecentSearch(query.trim())
- }
- },
- loadMoreRecentViews: () => {
- if (values.recentHasMore) {
- actions.ensureFeed(values.recentFeedQuery, values.recentViews.items.length + VIEW_FEED_PAGE_SIZE)
- }
- },
- setRecentSearch: () => actions.ensureFeed(values.recentFeedQuery, VIEW_FEED_PAGE_SIZE),
- setRecentFilters: () => actions.ensureFeed(values.recentFeedQuery, VIEW_FEED_PAGE_SIZE),
- loadFirstBuildsSuccess: ({ firstBuilds }) => {
- const building = Object.values(firstBuilds).filter(
- (build) => !build.hasVersion && !!build.runStatus && !TERMINAL_RUN_STATUSES.has(build.runStatus)
- )
- // A first version changes the row, so the list reloads once the build is done.
- if (Object.values(firstBuilds).some((build) => build.hasVersion)) {
- actions.loadRecentViews()
- return
- }
- if (building.length && !values.allRecentViews.loading) {
- cache.disposables.add(() => {
- const id = setTimeout(() => actions.loadFirstBuilds(), FIRST_BUILD_POLL_MS)
- return () => clearTimeout(id)
- }, 'firstBuildPoll')
- } else {
- cache.disposables.dispose('firstBuildPoll')
- }
- },
- [router.actionTypes.locationChanged]: ({ pathname }: LocationChangedPayload) => {
- // Creating, restoring or opening a view lands on a new Views path, so the recents stay current.
- // Search and hash changes, such as dashboard filters, keep the path and do not reload.
- if (pathname !== cache.lastPathname && railPaneForPath(pathname) === 'views') {
- actions.loadRecentViews()
- }
- cache.lastPathname = pathname
- },
- })),
- afterMount(({ actions, cache }) => {
- cache.lastPathname = router.values.location.pathname
- actions.loadRecentViews()
- }),
-])
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index a91ab7181d68..91d909686027 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2344,6 +2344,7 @@ const api = {
createdAtGt,
createdAtLt,
searchNameOnly,
+ includeTags,
signal,
}: {
parent?: string
@@ -2360,6 +2361,7 @@ const api = {
createdAtGt?: string
createdAtLt?: string
searchNameOnly?: boolean
+ includeTags?: boolean
signal?: AbortSignal
}): Promise<CountedPaginatedResponseWithUsers<FileSystemEntry>> {
return await new ApiRequest()
@@ -2379,6 +2381,7 @@ const api = {
created_at__gt: createdAtGt,
created_at__lt: createdAtLt,
search_name_only: searchNameOnly,
+ include_tags: includeTags,
})
.get({ signal })
},
diff --git a/frontend/src/models/notebooksModel.ts b/frontend/src/models/notebooksModel.ts
index c614561602b2..05ae14c07479 100644
--- a/frontend/src/models/notebooksModel.ts
+++ b/frontend/src/models/notebooksModel.ts
@@ -7,6 +7,7 @@ import api from 'lib/api'
import { JSONContent } from 'lib/components/RichContentEditor/types'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { addProductIntent } from 'lib/utils/product-intents'
+import { withBackLink } from 'scenes/analytics/analyticsBackLink'
import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'
import type { notebookLogicType } from 'scenes/notebooks/Notebook/notebookLogic'
import { notebookPanelLogic } from 'scenes/notebooks/NotebookPanel/notebookPanelLogic'
@@ -59,9 +60,9 @@ export const openNotebook = async (
thePanelLogic.actions.selectNotebook(notebookId)
} else {
if (router.values.location.pathname === urls.notebook('new')) {
- router.actions.replace(urls.notebook(notebookId))
+ router.actions.replace(withBackLink(urls.notebook(notebookId)))
} else {
- router.actions.push(urls.notebook(notebookId))
+ router.actions.push(withBackLink(urls.notebook(notebookId)))
}
}
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 8f42f368fce4..ae81e2803d96 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1998,7 +1998,7 @@ export const fileSystemTypes = {
iconType: 'canvas',
flag: FEATURE_FLAGS.TODAY_RAIL_NAV,
href: (ref: string) => urls.canvasDetail(ref),
- listHref: () => urls.canvases(),
+ listHref: () => urls.analyticsList({ type: 'canvas' }),
iconColor: ['var(--color-product-tasks-light)', 'var(--color-product-tasks-dark)'],
filterKey: 'canvas',
},
diff --git a/frontend/src/scenes/analytics/Analytics.stories.tsx b/frontend/src/scenes/analytics/Analytics.stories.tsx
new file mode 100644
index 000000000000..3d2ba5c4f851
--- /dev/null
+++ b/frontend/src/scenes/analytics/Analytics.stories.tsx
@@ -0,0 +1,308 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { waitFor, within } from '@testing-library/dom'
+import userEvent from '@testing-library/user-event'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+import { EMPTY_PAGINATED_RESPONSE } from '~/mocks/handlers'
+
+const ADA = {
+ id: 1,
+ uuid: 'user-ada',
+ distinct_id: 'user-ada',
+ first_name: 'Ada',
+ last_name: 'Lovelace',
+ email: '[email protected]',
+}
+const GRACE = {
+ id: 7,
+ uuid: 'user-grace',
+ distinct_id: 'user-grace',
+ first_name: 'Grace',
+ last_name: 'Hopper',
+ email: '[email protected]',
+}
+
+const at = (day: number, hour = 9): string =>
+ `2026-09-${String(day).padStart(2, '0')}T${String(hour).padStart(2, '0')}:00:00Z`
+
+const CANVASES = [
+ {
+ id: 'canvas-1',
+ name: 'Checkout funnel explorer',
+ kind: 'freeform',
+ description: '',
+ channel: 'space-growth',
+ template_id: 'freeform',
+ generation_task_id: null,
+ pinned: false,
+ pinned_at: null,
+ current_version_id: 'v1',
+ published_build_id: 'b1',
+ component_meta: null,
+ created_by: GRACE,
+ created_at: at(20),
+ updated_at: at(27, 16),
+ url: 'https://app.example.com/canvases/canvas-1',
+ },
+]
+
+const DASHBOARDS = [
+ {
+ id: 12,
+ name: 'Revenue overview',
+ description: '',
+ pinned: true,
+ deleted: false,
+ tags: ['finance', 'weekly'],
+ created_by: ADA,
+ created_at: at(2),
+ last_accessed_at: at(28, 8),
+ last_viewed_at: at(28, 8),
+ folder: 'Finance',
+ creation_mode: 'default',
+ is_shared: false,
+ },
+ {
+ id: 13,
+ name: 'Activation',
+ description: '',
+ pinned: false,
+ deleted: false,
+ tags: ['growth'],
+ created_by: GRACE,
+ created_at: at(5),
+ last_accessed_at: at(26),
+ last_viewed_at: null,
+ folder: 'Unfiled/Dashboards',
+ creation_mode: 'default',
+ is_shared: true,
+ },
+]
+
+const NOTEBOOKS = [
+ {
+ short_id: 'nb-plan',
+ title: 'Q4 experiment plan',
+ deleted: false,
+ created_by: ADA,
+ created_at: at(10),
+ last_modified_at: at(27, 11),
+ },
+]
+
+const INSIGHTS = [
+ {
+ short_id: 'ins-signups',
+ name: 'Signups by plan',
+ derived_name: null,
+ deleted: false,
+ saved: true,
+ tags: ['growth', 'onboarding', 'north-star', 'weekly'],
+ created_by: ADA,
+ created_at: at(1),
+ last_modified_at: at(25),
+ last_viewed_at: at(27, 18),
+ },
+ {
+ short_id: 'ins-retention',
+ name: null,
+ derived_name: 'Weekly retention of paying users',
+ deleted: false,
+ saved: true,
+ tags: [],
+ created_by: GRACE,
+ created_at: at(3),
+ last_modified_at: at(22),
+ last_viewed_at: null,
+ },
+]
+
+const FILE_SYSTEM = [
+ { id: 'fs-folder-finance', path: 'Finance', type: 'folder', depth: 1 },
+ { id: 'fs-folder-growth', path: 'Growth', type: 'folder', depth: 1 },
+ { id: 'fs-folder-unfiled', path: 'Unfiled', type: 'folder', depth: 1 },
+ {
+ id: 'fs-dash-12',
+ path: 'Finance/Revenue overview',
+ type: 'dashboard',
+ ref: '12',
+ href: '/dashboard/12',
+ depth: 2,
+ created_at: at(2),
+ last_viewed_at: at(28, 8),
+ meta: { created_by: ADA.id, tags: ['finance', 'weekly', 'board'] },
+ },
+ {
+ id: 'fs-ins-signups',
+ path: 'Growth/Signups by plan',
+ type: 'insight/trends',
+ ref: 'ins-signups',
+ href: '/insights/ins-signups',
+ depth: 2,
+ created_at: at(1),
+ last_viewed_at: at(27, 18),
+ meta: { created_by: ADA.id },
+ },
+ {
+ id: 'fs-nb-plan',
+ path: 'Unfiled/Notebooks/Q4 experiment plan',
+ type: 'notebook',
+ ref: 'nb-plan',
+ href: '/notebooks/nb-plan',
+ depth: 3,
+ created_at: at(10),
+ last_viewed_at: at(27, 11),
+ meta: { created_by: ADA.id },
+ },
+ {
+ id: 'fs-canvas-1',
+ path: 'Growth/Checkout funnel explorer',
+ type: 'canvas',
+ ref: 'canvas-1',
+ href: '/canvases/canvas-1',
+ depth: 2,
+ created_at: at(20),
+ last_viewed_at: at(26),
+ meta: { created_by: GRACE.id, tags: ['growth'] },
+ },
+]
+
+// Answers the file system like the API does for the params the Analyses pages send.
+const fileSystemHandler = ({ request }: { request: Request }): [number, unknown] => {
+ const params = new URL(request.url).searchParams
+ const parent = params.get('parent')
+ const depth = params.get('depth')
+ const type = params.get('type')
+ const typePrefix = params.get('type__startswith')
+ const search = params.get('search')?.toLowerCase()
+ const ref = params.get('ref')
+ const results = FILE_SYSTEM.filter(
+ (entry) =>
+ (parent === null || entry.path.startsWith(`${parent}/`)) &&
+ (depth === null || entry.depth === Number(depth)) &&
+ (type === null || entry.type === type) &&
+ (typePrefix === null || entry.type.startsWith(typePrefix)) &&
+ (ref === null || entry.ref === ref) &&
+ (!search || entry.path.toLowerCase().includes(search)) &&
+ (parent !== null || depth !== null || type !== null || typePrefix !== null || entry.type !== 'folder')
+ )
+ return [200, { results, count: results.length, next: null, users: [ADA, GRACE] }]
+}
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/Analytics',
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/task_channels/': [
+ { id: 'space-growth', name: 'growth', channel_type: 'public' },
+ ],
+ '/api/projects/:team_id/canvases/': { results: CANVASES, next: null, count: CANVASES.length },
+ '/api/environments/:team_id/dashboards/': { results: DASHBOARDS, next: null, count: DASHBOARDS.length },
+ '/api/projects/:team_id/dashboards/': { results: DASHBOARDS, next: null, count: DASHBOARDS.length },
+ '/api/projects/:team_id/notebooks/': { results: NOTEBOOKS, next: null, count: NOTEBOOKS.length },
+ '/api/environments/:team_id/insights/': { results: INSIGHTS, next: null, count: INSIGHTS.length },
+ '/api/projects/:team_id/insights/': { results: INSIGHTS, next: null, count: INSIGHTS.length },
+ '/api/environments/:team_id/file_system/': fileSystemHandler,
+ '/api/projects/:team_id/file_system/': fileSystemHandler,
+ '/api/projects/:team_id/tags/': ['finance', 'growth', 'onboarding', 'weekly'],
+ },
+ }),
+ ],
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2026-09-28 18:30:00',
+ pageUrl: urls.analyticsList(),
+ featureFlags: [FEATURE_FLAGS.TODAY_RAIL_NAV],
+ testOptions: { waitForLoadersToDisappear: true },
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+export const List: Story = {
+ parameters: { pageUrl: urls.analyticsList() },
+}
+
+export const ListFiltered: Story = {
+ parameters: { pageUrl: urls.analyticsList({ type: 'dashboard', createdBy: ['user-ada'] }) },
+}
+
+export const Mine: Story = {
+ parameters: { pageUrl: urls.analyticsMine() },
+}
+
+export const Spaces: Story = {
+ parameters: { pageUrl: urls.analyticsSpaces() },
+}
+
+export const ListNoMatches: Story = {
+ parameters: { pageUrl: urls.analyticsList({ search: 'quarterly' }) },
+}
+
+export const ListEmpty: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/file_system/': EMPTY_PAGINATED_RESPONSE,
+ '/api/projects/:team_id/file_system/': EMPTY_PAGINATED_RESPONSE,
+ },
+ }),
+ ],
+ parameters: { pageUrl: urls.analyticsList() },
+}
+
+export const ListError: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/file_system/': () => [500, { detail: 'Server error' }],
+ '/api/projects/:team_id/file_system/': () => [500, { detail: 'Server error' }],
+ },
+ }),
+ ],
+ parameters: { pageUrl: urls.analyticsList() },
+}
+
+export const ListSpace: Story = {
+ parameters: { pageUrl: urls.analyticsList({ folder: 'Growth' }) },
+}
+
+// Dialogs and menus render in portals outside the story canvas, so the helpers read the whole document.
+async function clickWhenRendered(attr: string): Promise<void> {
+ const element = await waitFor(
+ () => {
+ const found = document.querySelector<HTMLElement>(`[data-attr=${attr}]`)
+ if (!found) {
+ throw new Error(`${attr} is not rendered yet`)
+ }
+ return found
+ },
+ { timeout: 15000 }
+ )
+ await userEvent.click(element)
+}
+
+export const ListShareDialog: Story = {
+ parameters: { pageUrl: urls.analyticsList() },
+ play: async () => {
+ await clickWhenRendered('analytics-list-row-share')
+ await within(document.body).findAllByText('Finance', {}, { timeout: 15000 })
+ },
+}
+
+export const ListNewInsightDialog: Story = {
+ parameters: { pageUrl: urls.analyticsList() },
+ play: async () => {
+ await clickWhenRendered('analytics-list-new')
+ await clickWhenRendered('analytics-new-insight')
+ await within(document.body).findByText('How does it change over time?', {}, { timeout: 15000 })
+ },
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsCreateModals.tsx b/frontend/src/scenes/analytics/AnalyticsCreateModals.tsx
new file mode 100644
index 000000000000..a7f4387ed72c
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsCreateModals.tsx
@@ -0,0 +1,16 @@
+import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'
+
+import { NewInsightDialog } from './NewInsightDialog'
+
+/**
+ * The create dialogs an Analytics page hosts, so "New dashboard" and "New insight" open in place.
+ * `newAnalyticsLogic` falls back to the products' own pages when no host is mounted.
+ */
+export function AnalyticsCreateModals(): JSX.Element {
+ return (
+ <>
+ <NewDashboardModal />
+ <NewInsightDialog />
+ </>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsDraggableRow.tsx b/frontend/src/scenes/analytics/AnalyticsDraggableRow.tsx
new file mode 100644
index 000000000000..5f8e2284222a
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsDraggableRow.tsx
@@ -0,0 +1,57 @@
+import { useDraggable } from '@dnd-kit/core'
+import { useActions } from 'kea'
+import { useEffect, useRef } from 'react'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { ProjectDragData } from '~/layout/panel-layout/ProjectTree/ProjectDragAndDropContext'
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+import { ANALYTICS_DRAG_SCOPE } from './analyticsUtils'
+
+/**
+ * Lets a list row be dragged onto a folder. The app-wide project drag context performs the move,
+ * so the row is handed to the project tree first: that context only resolves rows the tree knows.
+ */
+export function AnalyticsDraggableRow({
+ entry,
+ children,
+}: {
+ entry: FileSystemEntry
+ children: React.ReactNode
+}): JSX.Element {
+ const { createSavedItem } = useActions(projectTreeDataLogic)
+ const data: ProjectDragData = {
+ identifier: { type: entry.type, ref: entry.ref, href: entry.href, path: entry.path },
+ logicKey: ANALYTICS_DRAG_SCOPE,
+ }
+ const { listeners, setNodeRef, isDragging } = useDraggable({ id: `${ANALYTICS_DRAG_SCOPE}::${entry.id}`, data })
+ // A drop ends with a click on whatever sits under the pointer, which must not open the dragged row.
+ const dragged = useRef(false)
+ useEffect(() => {
+ if (isDragging) {
+ dragged.current = true
+ }
+ }, [isDragging])
+
+ return (
+ <span
+ ref={setNodeRef}
+ {...listeners}
+ onPointerDownCapture={() => createSavedItem(entry)}
+ // The browser's own link drag would take over from the row drag.
+ onDragStart={(event) => event.preventDefault()}
+ onClickCapture={(event) => {
+ if (dragged.current) {
+ dragged.current = false
+ event.preventDefault()
+ event.stopPropagation()
+ }
+ }}
+ className={cn('flex min-w-0 flex-1 items-center gap-2 overflow-hidden', isDragging && 'opacity-50')}
+ >
+ {children}
+ </span>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsFilterPicker.tsx b/frontend/src/scenes/analytics/AnalyticsFilterPicker.tsx
new file mode 100644
index 000000000000..0430c7c47032
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsFilterPicker.tsx
@@ -0,0 +1,130 @@
+import { ReactNode, useRef, useState } from 'react'
+
+import {
+ Button,
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ Spinner,
+ Text,
+} from '@posthog/quill'
+
+export interface AnalyticsFilterOption {
+ value: string
+ label: string
+ media?: ReactNode
+ /** A muted note after the label, such as "(you)". */
+ hint?: string
+}
+
+interface AnalyticsFilterPickerProps {
+ label: string
+ value: string[]
+ onChange: (value: string[]) => void
+ options: AnalyticsFilterOption[]
+ loading?: boolean
+ onOpen?: () => void
+ searchPlaceholder: string
+ emptyText: string
+ dataAttr: string
+}
+
+/** A filter that is a dropdown and a search at once: a button opens a searchable list to tick values in. */
+export function AnalyticsFilterPicker({
+ label,
+ value,
+ onChange,
+ options,
+ loading,
+ onOpen,
+ searchPlaceholder,
+ emptyText,
+ dataAttr,
+}: AnalyticsFilterPickerProps): JSX.Element {
+ const [open, setOpen] = useState(false)
+ const triggerRef = useRef<HTMLButtonElement>(null)
+ // The trigger opens the popup itself, so the list loads from here as well as from the combobox's own opens.
+ const toggle = (next: boolean): void => {
+ setOpen(next)
+ if (next) {
+ onOpen?.()
+ }
+ }
+ const selected = options.filter((option) => value.includes(option.value))
+ // Values the options do not know yet (a tag from the URL before the list loads) still count as picked.
+ const unknown = value.filter((item) => !options.some((option) => option.value === item))
+ const picked = [...selected, ...unknown.map((item) => ({ value: item, label: item }))]
+ return (
+ <Combobox
+ multiple
+ items={[...options, ...unknown.map((item) => ({ value: item, label: item }))]}
+ itemToStringValue={(option: AnalyticsFilterOption) => option.label}
+ isItemEqualToValue={(option: AnalyticsFilterOption, other: AnalyticsFilterOption) =>
+ option.value === other.value
+ }
+ value={picked}
+ onValueChange={(next: AnalyticsFilterOption[]) => onChange(next.map((option) => option.value))}
+ open={open}
+ onOpenChange={toggle}
+ >
+ <Button
+ ref={triggerRef}
+ variant="outline"
+ size="sm"
+ className="h-8"
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ onClick={() => toggle(!open)}
+ data-attr={dataAttr}
+ >
+ {label}
+ {value.length > 0 && (
+ <Text size="xs" variant="muted" render={<span />}>
+ {value.length}
+ </Text>
+ )}
+ </Button>
+ <ComboboxContent anchor={triggerRef} className="min-w-64">
+ <ComboboxInput placeholder={searchPlaceholder} showTrigger={false} />
+ {value.length > 0 && (
+ <div className="px-1 pt-1">
+ <Button
+ variant="link-muted"
+ size="xs"
+ onClick={() => onChange([])}
+ data-attr={`${dataAttr}-clear`}
+ >
+ Clear selection
+ </Button>
+ </div>
+ )}
+ <ComboboxEmpty>
+ {loading ? (
+ <span className="flex items-center gap-2">
+ <Spinner />
+ Loading…
+ </span>
+ ) : (
+ emptyText
+ )}
+ </ComboboxEmpty>
+ <ComboboxList>
+ {(option: AnalyticsFilterOption) => (
+ <ComboboxItem key={option.value} value={option} title={option.label}>
+ {option.media}
+ <span className="truncate">{option.label}</span>
+ {option.hint && (
+ <Text size="xs" variant="muted" render={<span />} className="ml-auto">
+ {option.hint}
+ </Text>
+ )}
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsFolderBreadcrumbs.tsx b/frontend/src/scenes/analytics/AnalyticsFolderBreadcrumbs.tsx
new file mode 100644
index 000000000000..d0a4dc3ab8cd
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsFolderBreadcrumbs.tsx
@@ -0,0 +1,48 @@
+import { IconChevronRight, IconFolder } from '@posthog/icons'
+import { Button, Text } from '@posthog/quill'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { AnalyticsFolderDropTarget } from './AnalyticsFolderDropTarget'
+import { FolderRow } from './analyticsListLogic'
+
+export function AnalyticsFolderBreadcrumbs({ crumbs }: { crumbs: FolderRow[] }): JSX.Element {
+ return (
+ <nav aria-label="Collection" className="flex flex-wrap items-center gap-1 text-sm">
+ <Button
+ variant="link-muted"
+ size="sm"
+ nativeButton={false}
+ render={<LinkPrimitive to={urls.analyticsSpaces()} />}
+ data-attr="analytics-list-folder-root"
+ >
+ <IconFolder />
+ Collections
+ </Button>
+ {crumbs.map((crumb, index) => (
+ <span key={crumb.path} className="flex items-center gap-1">
+ <IconChevronRight className="size-3 text-muted-foreground" aria-hidden />
+ {index === crumbs.length - 1 ? (
+ <Text size="sm" className="font-semibold">
+ {crumb.name}
+ </Text>
+ ) : (
+ // A parent crumb takes dropped rows, which is how an item moves back out of a folder.
+ <AnalyticsFolderDropTarget path={crumb.path}>
+ <Button
+ variant="link-muted"
+ size="sm"
+ nativeButton={false}
+ render={<LinkPrimitive to={urls.analyticsList({ folder: crumb.path })} />}
+ data-attr="analytics-list-folder-crumb"
+ >
+ {crumb.name}
+ </Button>
+ </AnalyticsFolderDropTarget>
+ )}
+ </span>
+ ))}
+ </nav>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsFolderDropTarget.tsx b/frontend/src/scenes/analytics/AnalyticsFolderDropTarget.tsx
new file mode 100644
index 000000000000..63014fac06f1
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsFolderDropTarget.tsx
@@ -0,0 +1,41 @@
+import { useDndContext, useDroppable } from '@dnd-kit/core'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { ProjectDragData } from '~/layout/panel-layout/ProjectTree/ProjectDragAndDropContext'
+import { projectDroppableId } from '~/layout/panel-layout/ProjectTree/ProjectDragAndDropContext'
+import { isPathUnder } from '~/layout/panel-layout/ProjectTree/utils'
+
+import { ANALYTICS_DRAG_SCOPE } from './analyticsUtils'
+
+/** A folder that takes dropped rows. A folder never takes itself or one of its own parents. */
+export function AnalyticsFolderDropTarget({
+ path,
+ children,
+ className,
+}: {
+ path: string
+ children: React.ReactNode
+ className?: string
+}): JSX.Element {
+ const { active } = useDndContext()
+ const draggedPath = (active?.data.current as ProjectDragData | undefined)?.identifier.path
+ const draggedFolder = (active?.data.current as ProjectDragData | undefined)?.identifier.type === 'folder'
+ const disabled = !!draggedPath && draggedFolder && (path === draggedPath || isPathUnder(path, draggedPath))
+ const { setNodeRef, isOver } = useDroppable({
+ id: projectDroppableId(path, 'project://', ANALYTICS_DRAG_SCOPE),
+ disabled,
+ })
+ return (
+ <span
+ ref={setNodeRef}
+ className={cn(
+ 'rounded-sm',
+ isOver && !disabled && 'bg-fill-button-tertiary-hover ring-2 ring-ring',
+ className
+ )}
+ >
+ {children}
+ </span>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsList.tsx b/frontend/src/scenes/analytics/AnalyticsList.tsx
new file mode 100644
index 000000000000..c8e82f3562b4
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsList.tsx
@@ -0,0 +1,333 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useMemo } from 'react'
+import { useInView } from 'react-intersection-observer'
+
+import {
+ IconChevronDown,
+ IconFolder,
+ IconFolderPlus,
+ IconPlus,
+ IconSearch,
+ IconTrash,
+ IconTrends,
+} from '@posthog/icons'
+import {
+ Button,
+ DataTable,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Skeleton,
+ Spinner,
+ Text,
+} from '@posthog/quill'
+
+import { NotFound } from 'lib/components/NotFound'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { todayAnalyticsLogic } from '~/layout/today/todayAnalyticsLogic'
+import { TodayAnalyticsNewFolderDialog } from '~/layout/today/TodayAnalyticsNewFolderDialog'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+import { AnalyticsCreateModals } from './AnalyticsCreateModals'
+import { AnalyticsFolderBreadcrumbs } from './AnalyticsFolderBreadcrumbs'
+import { AnalyticsListRow, analyticsListColumns } from './AnalyticsListColumns'
+import { AnalyticsListFilters } from './AnalyticsListFilters'
+import { analyticsListLogic, analyticsListUrlParams } from './analyticsListLogic'
+import { AnalyticsSpaceGlyph } from './AnalyticsSpaceGlyph'
+import { ANALYTICS_DRAG_SCOPE, ANALYTICS_TYPE_INFO, USERS_FOLDER, analyticsSpaceOfPath } from './analyticsUtils'
+import { NewAnalyticsMenu } from './NewAnalyticsMenu'
+import { ShareToSpaceDialog } from './ShareToSpaceDialog'
+
+const SCROLL_PREFETCH_MARGIN = '1200px 0px'
+
+export const scene: SceneExport = {
+ component: AnalyticsList,
+ logic: analyticsListLogic,
+}
+
+export function AnalyticsList(): JSX.Element {
+ const analyticsEnabled = useFeatureFlag('TODAY_RAIL_NAV')
+ // The page ships behind the Today navigation, so without the flag `/analytics/all` stays a missing page.
+ return analyticsEnabled ? <AnalyticsListContent /> : <NotFound object="page" />
+}
+
+function TableSkeleton(): JSX.Element {
+ return (
+ <div className="flex flex-col gap-2" aria-busy aria-label="Loading analytics">
+ {Array.from({ length: 6 }, (_, index) => (
+ <Skeleton key={index} className="h-9" />
+ ))}
+ </div>
+ )
+}
+
+function AnalyticsListContent(): JSX.Element {
+ const {
+ filters,
+ items,
+ subfolders,
+ folderBreadcrumbs,
+ listState,
+ loading,
+ hasMore,
+ failedTypes,
+ feedStale,
+ mode,
+ scope,
+ loadedCount,
+ } = useValues(analyticsListLogic)
+ const { clearFilters, loadList, loadMore } = useActions(analyticsListLogic)
+ const { setNewFolderDialogOpen } = useActions(todayAnalyticsLogic)
+ const { deleteItem } = useActions(projectTreeDataLogic)
+ const { ref: endRef, inView: endInView } = useInView({
+ root: document.getElementById('main-content'),
+ rootMargin: SCROLL_PREFETCH_MARGIN,
+ })
+ // An opened page sends the person back to this exact list, filters included.
+ const backUrl =
+ scope === 'mine'
+ ? urls.analyticsMine(analyticsListUrlParams(filters))
+ : urls.analyticsList(analyticsListUrlParams(filters))
+ const columns = analyticsListColumns({ backUrl, showSpace: mode === 'feed' })
+ const rows = useMemo<AnalyticsListRow[]>(
+ () => [
+ ...subfolders.map((folder) => ({ kind: 'folder' as const, folder })),
+ ...items.map((item) => ({ kind: 'item' as const, item })),
+ ],
+ [subfolders, items]
+ )
+ const spaceName = mode === 'folder' ? folderBreadcrumbs[folderBreadcrumbs.length - 1]?.name || 'Project root' : null
+ // Only the collection itself is deleted from Manage; a folder inside it is deleted from its row.
+ const topLevelSpace = mode === 'folder' && filters.folder ? analyticsSpaceOfPath(filters.folder) : null
+ const isSpaceRoot = !!topLevelSpace && topLevelSpace !== USERS_FOLDER && folderBreadcrumbs.length === 1
+
+ useEffect(() => {
+ if (endInView && hasMore) {
+ loadMore()
+ }
+ }, [endInView, hasMore, loadedCount, loadMore])
+
+ const newButton = (
+ <NewAnalyticsMenu source="list" trigger={<Button variant="primary" size="sm" data-attr="analytics-list-new" />}>
+ <IconPlus />
+ New
+ </NewAnalyticsMenu>
+ )
+
+ const renderBody = (): JSX.Element => {
+ if (listState === 'error') {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>Couldn’t load your analytics</EmptyTitle>
+ <EmptyDescription>Try again, and if it keeps happening contact support.</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button
+ variant="outline"
+ loading={loading}
+ onClick={() => loadList()}
+ data-attr="analytics-list-retry"
+ >
+ Try again
+ </Button>
+ </EmptyContent>
+ </Empty>
+ )
+ }
+ if (listState === 'loading') {
+ return <TableSkeleton />
+ }
+ if (listState === 'no-matches') {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <IconSearch />
+ </EmptyMedia>
+ <EmptyTitle>Nothing matches these filters</EmptyTitle>
+ <EmptyDescription>Try a different name, or clear the filters.</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button
+ variant="outline"
+ onClick={() => clearFilters()}
+ data-attr="analytics-list-clear-filters"
+ >
+ Clear filters
+ </Button>
+ </EmptyContent>
+ </Empty>
+ )
+ }
+ if (listState === 'empty') {
+ return (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <IconFolder />
+ </EmptyMedia>
+ <EmptyTitle>
+ {mode === 'folder'
+ ? 'Nothing shared here yet'
+ : scope === 'mine'
+ ? 'Nothing of yours yet'
+ : 'No analytics yet'}
+ </EmptyTitle>
+ <EmptyDescription>
+ {mode === 'folder'
+ ? 'Add something to this collection from its page and it shows up here.'
+ : scope === 'mine'
+ ? 'Canvases, dashboards, notebooks and insights you create show up here.'
+ : 'Canvases, dashboards, notebooks and insights show up here as people create them.'}
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ {mode === 'feed' ? (
+ newButton
+ ) : (
+ <Button
+ variant="outline"
+ nativeButton={false}
+ render={<LinkPrimitive to={urls.analyticsSpaces()} />}
+ data-attr="analytics-list-browse-all"
+ >
+ Back to collections
+ </Button>
+ )}
+ </EmptyContent>
+ </Empty>
+ )
+ }
+ return (
+ <div
+ className={feedStale ? 'opacity-60 transition-opacity' : 'transition-opacity'}
+ aria-busy={feedStale || hasMore}
+ >
+ {rows.length > 0 && (
+ <DataTable
+ columns={columns}
+ data={rows}
+ fullWidth
+ size="sm"
+ stickyHeader
+ // The title column soaks up the slack, and `max-w-0` stops a long title from widening
+ // the table past its container, so the filters above keep their width across types.
+ // Below the minimum width the table scrolls sideways instead of squeezing the title away.
+ className="w-full min-w-0 **:data-expand:max-w-0 **:data-[slot=table]:min-w-208"
+ empty={<Text size="sm">Nothing in this collection.</Text>}
+ />
+ )}
+ {hasMore && (
+ <div className="flex items-center justify-center gap-2 py-3" aria-busy>
+ <Spinner />
+ <Text size="xs" variant="muted">
+ Loading more…
+ </Text>
+ </div>
+ )}
+ </div>
+ )
+ }
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name={spaceName ?? (scope === 'mine' ? 'My work' : 'Analytics')}
+ description={
+ mode === 'folder'
+ ? null
+ : scope === 'mine'
+ ? 'Everything you created, shared or not.'
+ : 'Canvases, dashboards, notebooks and insights shared in this project.'
+ }
+ resourceType={{
+ type: 'analytics',
+ forceIcon: spaceName ? <AnalyticsSpaceGlyph name={spaceName} /> : <IconTrends />,
+ }}
+ actions={
+ <div data-quill className="flex items-center gap-2">
+ {mode === 'folder' && filters.folder && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setNewFolderDialogOpen(true, filters.folder)}
+ data-attr="analytics-list-new-folder"
+ >
+ <IconFolderPlus />
+ New folder
+ </Button>
+ )}
+ {isSpaceRoot && topLevelSpace && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={<Button variant="outline" size="sm" data-attr="analytics-space-manage" />}
+ >
+ Manage
+ <IconChevronDown />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-48">
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() =>
+ deleteItem(
+ { path: filters.folder!, type: 'folder' } as FileSystemEntry,
+ ANALYTICS_DRAG_SCOPE
+ )
+ }
+ data-attr="analytics-space-delete"
+ >
+ <IconTrash />
+ Delete collection…
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {newButton}
+ </div>
+ }
+ />
+ <div data-quill className="@container/analytics flex flex-col gap-3">
+ {mode === 'folder' && <AnalyticsFolderBreadcrumbs crumbs={folderBreadcrumbs} />}
+ <AnalyticsListFilters />
+ {listState === 'ready' && failedTypes.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2" role="alert">
+ <Text size="sm" variant="destructive">
+ {`${new Intl.ListFormat('en', { type: 'conjunction' }).format(
+ failedTypes.map((type) => ANALYTICS_TYPE_INFO[type].pluralLabel)
+ )} didn’t load, so this list may be incomplete.`}
+ </Text>
+ <Button
+ variant="outline"
+ size="xs"
+ loading={loading}
+ onClick={() => loadList()}
+ data-attr="analytics-list-retry"
+ >
+ Try again
+ </Button>
+ </div>
+ )}
+ {renderBody()}
+ <div ref={endRef} aria-hidden />
+ </div>
+ <AnalyticsCreateModals />
+ <ShareToSpaceDialog />
+ <TodayAnalyticsNewFolderDialog />
+ </SceneContent>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsListColumns.tsx b/frontend/src/scenes/analytics/AnalyticsListColumns.tsx
new file mode 100644
index 000000000000..ad26e028048a
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsListColumns.tsx
@@ -0,0 +1,394 @@
+import { useActions } from 'kea'
+import { router } from 'kea-router'
+
+import { IconEllipsis, IconFolder, IconFolderMove, IconFolderOpen, IconShare, IconTrash, IconX } from '@posthog/icons'
+import {
+ Button,
+ Chip,
+ ChipGroup,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Text,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@posthog/quill'
+import type { DataTableProps } from '@posthog/quill-components'
+
+import { dayjs } from 'lib/dayjs'
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { escapePath } from '~/layout/panel-layout/ProjectTree/utils'
+
+import { AnalyticsDraggableRow } from './AnalyticsDraggableRow'
+import { AnalyticsFolderDropTarget } from './AnalyticsFolderDropTarget'
+import type { FolderRow } from './analyticsListLogic'
+import { AnalyticsOwner } from './AnalyticsOwner'
+import { analyticsShareLogic } from './analyticsShareLogic'
+import { AnalyticsSpaceGlyph } from './AnalyticsSpaceGlyph'
+import { AnalyticsTypeIcon } from './AnalyticsTypeIcon'
+import { ANALYTICS_DRAG_SCOPE, ANALYTICS_TYPE_INFO, AnalyticsItem, analyticsOpenHref } from './analyticsUtils'
+
+export type AnalyticsListRow = { kind: 'folder'; folder: FolderRow } | { kind: 'item'; item: AnalyticsItem }
+
+export type AnalyticsListColumns = DataTableProps<AnalyticsListRow, unknown>['columns']
+
+function EmptyCell(): JSX.Element {
+ return (
+ <Text size="xs" variant="muted">
+ –
+ </Text>
+ )
+}
+
+function TimeCell({ time, label }: { time: string | null; label?: string }): JSX.Element {
+ if (!time) {
+ return (
+ <Text size="xs" variant="muted">
+ –
+ </Text>
+ )
+ }
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={<span className="text-xs whitespace-nowrap text-muted-foreground" translate="no" />}
+ >
+ {label ? `${label} ${dayjs(time).fromNow()}` : dayjs(time).fromNow()}
+ </TooltipTrigger>
+ <TooltipContent>{dayjs(time).format('LLL')}</TooltipContent>
+ </Tooltip>
+ )
+}
+
+// Two chips fit the fixed tags column; the rest fold into a count.
+const VISIBLE_TAGS = 2
+
+function TagsCell({ tags }: { tags: string[] }): JSX.Element {
+ if (!tags.length) {
+ return (
+ <Text size="xs" variant="muted">
+ –
+ </Text>
+ )
+ }
+ const hidden = tags.length - VISIBLE_TAGS
+ return (
+ <ChipGroup className="flex-nowrap overflow-hidden">
+ {tags.slice(0, VISIBLE_TAGS).map((tag) => (
+ <Chip key={tag} size="xs" className="max-w-24 truncate">
+ {tag}
+ </Chip>
+ ))}
+ {hidden > 0 && (
+ <Text size="xs" variant="muted">
+ {`+${hidden}`}
+ </Text>
+ )}
+ </ChipGroup>
+ )
+}
+
+function SpaceCell({ item }: { item: AnalyticsItem }): JSX.Element {
+ const { openShareToSpace, moveItem } = useActions(analyticsShareLogic)
+ const target = { type: item.type, ref: item.id, name: item.name }
+ if (!item.spaceName) {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="link-muted"
+ size="xs"
+ className="h-auto gap-1 px-0 text-xs"
+ onClick={() => openShareToSpace(target)}
+ data-attr="analytics-list-row-share"
+ />
+ }
+ >
+ None
+ <IconShare className="size-3" />
+ </TooltipTrigger>
+ <TooltipContent>Add to a collection</TooltipContent>
+ </Tooltip>
+ )
+ }
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="link"
+ size="xs"
+ className="h-auto max-w-full gap-1.5 px-0 text-xs text-foreground"
+ data-attr="analytics-list-row-space"
+ />
+ }
+ >
+ <AnalyticsSpaceGlyph name={item.spaceName} />
+ <span className="truncate">{item.spaceName}</span>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-60">
+ <DropdownMenuItem
+ onClick={() =>
+ router.actions.push(urls.analyticsList({ folder: escapePath(item.spaceName ?? '') }))
+ }
+ data-attr="analytics-list-row-open-space"
+ >
+ <IconFolderOpen />
+ {`Open "${item.spaceName}"`}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => openShareToSpace(target)} data-attr="analytics-list-row-move">
+ <IconFolderMove />
+ Move to another collection
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => moveItem(target, null)}
+ data-attr="analytics-list-row-remove-from-space"
+ >
+ <IconX />
+ {`Remove from "${item.spaceName}"`}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+function MoveCell({ item }: { item: AnalyticsItem }): JSX.Element {
+ const { openShareToSpace } = useActions(analyticsShareLogic)
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label="Move to another collection"
+ onClick={() => openShareToSpace({ type: item.type, ref: item.id, name: item.name })}
+ data-attr="analytics-list-row-move"
+ />
+ }
+ >
+ <IconFolderMove />
+ </TooltipTrigger>
+ <TooltipContent>Move to another collection</TooltipContent>
+ </Tooltip>
+ )
+}
+
+function FolderMenuCell({ folder }: { folder: FolderRow }): JSX.Element | null {
+ const { deleteItem } = useActions(projectTreeDataLogic)
+ const entry = folder.entry
+ if (!entry) {
+ return null
+ }
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label={`Actions for ${folder.name}`}
+ data-attr="analytics-list-folder-menu"
+ />
+ }
+ >
+ <IconEllipsis />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-48">
+ <DropdownMenuItem
+ onClick={() => router.actions.push(urls.analyticsList({ folder: folder.path }))}
+ data-attr="analytics-list-folder-open"
+ >
+ <IconFolderOpen />
+ Open folder
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => deleteItem(entry, ANALYTICS_DRAG_SCOPE)}
+ data-attr="analytics-list-folder-delete"
+ >
+ <IconTrash />
+ Delete folder
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+function FolderTitle({ folder, draggable }: { folder: FolderRow; draggable: boolean }): JSX.Element {
+ const title = (
+ <>
+ <IconFolder className="size-4 shrink-0 text-muted-foreground" aria-hidden />
+ <LinkPrimitive
+ to={urls.analyticsList({ folder: folder.path })}
+ className="truncate font-semibold text-foreground"
+ data-attr="analytics-list-subfolder"
+ >
+ {folder.name}
+ </LinkPrimitive>
+ </>
+ )
+ return (
+ <AnalyticsFolderDropTarget path={folder.path} className="flex min-w-48 items-center gap-2 overflow-hidden">
+ {draggable && folder.entry ? (
+ <AnalyticsDraggableRow entry={folder.entry}>{title}</AnalyticsDraggableRow>
+ ) : (
+ title
+ )}
+ </AnalyticsFolderDropTarget>
+ )
+}
+
+function ItemTitle({
+ item,
+ backUrl,
+ draggable,
+}: {
+ item: AnalyticsItem
+ backUrl: string
+ draggable: boolean
+}): JSX.Element {
+ const title = (
+ <>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ className="flex size-4 shrink-0 items-center justify-center [&_svg]:size-4"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ color: ANALYTICS_TYPE_INFO[item.type].color }}
+ />
+ }
+ >
+ <AnalyticsTypeIcon type={item.type} />
+ </TooltipTrigger>
+ <TooltipContent>{ANALYTICS_TYPE_INFO[item.type].label}</TooltipContent>
+ </Tooltip>
+ <LinkPrimitive
+ to={analyticsOpenHref(item, backUrl)}
+ className="truncate font-semibold text-foreground"
+ data-attr={`analytics-list-row-${item.type}`}
+ >
+ {item.name}
+ </LinkPrimitive>
+ </>
+ )
+ return (
+ <span className="flex min-w-48 items-center gap-2 overflow-hidden">
+ {draggable && item.entry ? (
+ <AnalyticsDraggableRow entry={item.entry}>{title}</AnalyticsDraggableRow>
+ ) : (
+ title
+ )}
+ </span>
+ )
+}
+
+/**
+ * The list's columns. Every column but the title has a fixed width, so the title always gets the same
+ * remainder and the table does not resize as the rows change. The type shows as the title's icon.
+ */
+export function analyticsListColumns({
+ backUrl,
+ showSpace,
+}: {
+ backUrl: string
+ showSpace: boolean
+}): AnalyticsListColumns {
+ const draggable = !showSpace
+ return [
+ {
+ id: 'name',
+ header: 'Title',
+ meta: { expand: true },
+ enableSorting: false,
+ cell: ({ row }) =>
+ row.original.kind === 'folder' ? (
+ <FolderTitle folder={row.original.folder} draggable={draggable} />
+ ) : (
+ <ItemTitle item={row.original.item} backUrl={backUrl} draggable={draggable} />
+ ),
+ },
+ ...(showSpace
+ ? ([
+ {
+ id: 'space',
+ header: 'Collection',
+ enableSorting: false,
+ cell: ({ row }) => (
+ <div className="w-36">
+ {row.original.kind === 'item' ? <SpaceCell item={row.original.item} /> : <EmptyCell />}
+ </div>
+ ),
+ },
+ ] satisfies AnalyticsListColumns)
+ : []),
+ {
+ id: 'tags',
+ header: 'Tags',
+ enableSorting: false,
+ cell: ({ row }) => (
+ <div className="w-36 overflow-hidden">
+ {row.original.kind === 'item' ? <TagsCell tags={row.original.item.tags} /> : <EmptyCell />}
+ </div>
+ ),
+ },
+ {
+ id: 'owner',
+ header: 'Owner',
+ enableSorting: false,
+ cell: ({ row }) => (
+ <AnalyticsOwner
+ owner={
+ row.original.kind === 'item'
+ ? row.original.item.createdBy
+ : (row.original.folder.createdBy ?? null)
+ }
+ className="w-36"
+ />
+ ),
+ },
+ {
+ id: 'created',
+ header: 'Created',
+ enableSorting: false,
+ cell: ({ row }) => (
+ <div className="w-24">
+ <TimeCell
+ time={
+ row.original.kind === 'item'
+ ? row.original.item.createdAt
+ : (row.original.folder.createdAt ?? null)
+ }
+ />
+ </div>
+ ),
+ },
+ // Inside a collection the Collection column is gone, so the row carries the way out instead.
+ ...(showSpace
+ ? []
+ : ([
+ {
+ id: 'move',
+ header: '',
+ enableSorting: false,
+ cell: ({ row }) => (
+ <div className="flex w-8 justify-end">
+ {row.original.kind === 'item' ? (
+ <MoveCell item={row.original.item} />
+ ) : (
+ <FolderMenuCell folder={row.original.folder} />
+ )}
+ </div>
+ ),
+ },
+ ] satisfies AnalyticsListColumns)),
+ ]
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsListFilters.tsx b/frontend/src/scenes/analytics/AnalyticsListFilters.tsx
new file mode 100644
index 000000000000..790a203610eb
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsListFilters.tsx
@@ -0,0 +1,122 @@
+import { useActions, useValues } from 'kea'
+
+import { IconSearch, IconTrends } from '@posthog/icons'
+import {
+ Button,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ InputGroupText,
+ ToggleGroup,
+ ToggleGroupItem,
+} from '@posthog/quill'
+
+import { fullName } from 'lib/utils/strings'
+import { membersLogic } from 'scenes/organization/membersLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import { tagsModel } from '~/models/tagsModel'
+
+import { AnalyticsFilterOption, AnalyticsFilterPicker } from './AnalyticsFilterPicker'
+import { analyticsListLogic } from './analyticsListLogic'
+import { AnalyticsOwnerAvatar } from './AnalyticsOwner'
+import { AnalyticsTypeIcon } from './AnalyticsTypeIcon'
+import { ANALYTICS_TYPES, AnalyticsTypeFilter } from './analyticsUtils'
+
+/** Search, type, creator and the personal toggle, all one height so the row reads as one bar. */
+export function AnalyticsListFilters(): JSX.Element {
+ const { filters, filtersActive, searchInput, scope } = useValues(analyticsListLogic)
+ const { setSearchInput, setFilters, clearFilters } = useActions(analyticsListLogic)
+ const { tags: allTags, tagsLoading } = useValues(tagsModel)
+ const { loadTagsIfNeeded } = useActions(tagsModel)
+ const { meFirstMembers, membersLoading } = useValues(membersLogic)
+ const { ensureAllMembersLoaded } = useActions(membersLogic)
+ const { user } = useValues(userLogic)
+ const memberOptions: AnalyticsFilterOption[] = meFirstMembers.map((member) => ({
+ value: member.user.uuid,
+ label: fullName(member.user) || member.user.email,
+ media: <AnalyticsOwnerAvatar owner={member.user} />,
+ hint: member.user.uuid === user?.uuid ? '(you)' : undefined,
+ }))
+
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <InputGroup className="h-8 w-56 max-w-full">
+ <InputGroupAddon align="inline-start">
+ <InputGroupText>
+ <IconSearch />
+ </InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ type="search"
+ aria-label="Search analytics"
+ placeholder="Search"
+ value={searchInput}
+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => setSearchInput(event.target.value)}
+ data-attr="analytics-list-search"
+ />
+ </InputGroup>
+ <ToggleGroup
+ size="lg"
+ variant="default"
+ aria-label="Filter by type"
+ className="h-8"
+ value={[filters.type]}
+ onValueChange={(value: string[]) => value[0] && setFilters({ type: value[0] as AnalyticsTypeFilter })}
+ >
+ <ToggleGroupItem value="all" size="lg" data-attr="analytics-list-type-filter">
+ <IconTrends />
+ All
+ </ToggleGroupItem>
+ {ANALYTICS_TYPES.map((info) => (
+ <ToggleGroupItem
+ key={info.type}
+ value={info.type}
+ size="lg"
+ aria-label={info.pluralLabel}
+ title={info.pluralLabel}
+ data-attr="analytics-list-type-filter"
+ >
+ <span
+ className="flex items-center [&_svg]:size-4"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ color: info.color }}
+ >
+ <AnalyticsTypeIcon type={info.type} />
+ </span>
+ <span className="hidden @6xl/analytics:inline">{info.pluralLabel}</span>
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ {scope === 'all' && (
+ <AnalyticsFilterPicker
+ label="Created by"
+ value={filters.createdBy}
+ onChange={(createdBy) => setFilters({ createdBy })}
+ onOpen={ensureAllMembersLoaded}
+ loading={membersLoading}
+ options={memberOptions}
+ searchPlaceholder="Search people"
+ emptyText="No one matches"
+ dataAttr="analytics-list-created-by"
+ />
+ )}
+ <AnalyticsFilterPicker
+ label="Tags"
+ value={filters.tags}
+ onChange={(tags) => setFilters({ tags })}
+ onOpen={loadTagsIfNeeded}
+ loading={tagsLoading}
+ options={allTags.map((tag) => ({ value: tag, label: tag }))}
+ searchPlaceholder="Search tags"
+ emptyText="No tag matches"
+ dataAttr="analytics-list-tags"
+ />
+ {filtersActive && (
+ <Button variant="link-muted" size="sm" onClick={() => clearFilters()} data-attr="analytics-list-clear">
+ Clear filters
+ </Button>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsOwner.tsx b/frontend/src/scenes/analytics/AnalyticsOwner.tsx
new file mode 100644
index 000000000000..7fffb498cdf9
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsOwner.tsx
@@ -0,0 +1,50 @@
+import { Avatar, AvatarFallback, Text, cn } from '@posthog/quill'
+
+import { fullName } from 'lib/utils/strings'
+
+import { AnalyticsItem } from './analyticsUtils'
+
+function initials(owner: NonNullable<AnalyticsItem['createdBy']>): string {
+ const name = fullName(owner)
+ const letters = name === 'Unknown User' || !name ? owner.email : name
+ return letters
+ .split(/[\s@._-]+/)
+ .filter(Boolean)
+ .slice(0, 2)
+ .map((part) => part[0].toUpperCase())
+ .join('')
+}
+
+export function AnalyticsOwnerAvatar({ owner }: { owner: NonNullable<AnalyticsItem['createdBy']> }): JSX.Element {
+ return (
+ <Avatar size="xs">
+ <AvatarFallback>{initials(owner)}</AvatarFallback>
+ </Avatar>
+ )
+}
+
+/** Who created an item, as an avatar and name. Reads as a dash when the API knows no creator. */
+export function AnalyticsOwner({
+ owner,
+ className,
+}: {
+ owner: AnalyticsItem['createdBy']
+ className?: string
+}): JSX.Element {
+ if (!owner) {
+ return (
+ <Text size="xs" variant="muted" className={className}>
+ –
+ </Text>
+ )
+ }
+ const name = fullName(owner) === 'Unknown User' ? owner.email : fullName(owner) || owner.email
+ return (
+ <span className={cn('flex min-w-0 items-center gap-2', className)}>
+ <AnalyticsOwnerAvatar owner={owner} />
+ <Text size="xs" className="truncate">
+ {name}
+ </Text>
+ </span>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsProductHome.tsx b/frontend/src/scenes/analytics/AnalyticsProductHome.tsx
new file mode 100644
index 000000000000..b56b756d9fef
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsProductHome.tsx
@@ -0,0 +1,35 @@
+import { NotFound } from 'lib/components/NotFound'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { HomeTab } from 'products/product_analytics/frontend/insights/home/HomeTab'
+
+import { AnalyticsCreateModals } from './AnalyticsCreateModals'
+import { AnalyticsTypeIcon } from './AnalyticsTypeIcon'
+
+export const scene: SceneExport = {
+ component: AnalyticsProductHome,
+}
+
+/** The product analytics home dashboard on its own, without the Insights tabs around it. */
+export function AnalyticsProductHome(): JSX.Element {
+ const railEnabled = useFeatureFlag('TODAY_RAIL_NAV')
+ const homeEnabled = useFeatureFlag('PRODUCT_ANALYTICS_HOME_TAB')
+ if (!railEnabled || !homeEnabled) {
+ return <NotFound object="page" />
+ }
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="Product analytics"
+ description="How people use your product, ready-made by PostHog."
+ resourceType={{ type: 'analytics', forceIcon: <AnalyticsTypeIcon type="insight" /> }}
+ />
+ <HomeTab />
+ <AnalyticsCreateModals />
+ </SceneContent>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsSpaceGlyph.tsx b/frontend/src/scenes/analytics/AnalyticsSpaceGlyph.tsx
new file mode 100644
index 000000000000..fd6bed1ff327
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsSpaceGlyph.tsx
@@ -0,0 +1,31 @@
+import { cn } from '@posthog/quill'
+
+import { analyticsSpaceColor } from './analyticsUtils'
+
+/** A space's mark: a coloured tile with its initial, so each space reads the same wherever it is listed. */
+export function AnalyticsSpaceGlyph({
+ name,
+ size = 'sm',
+ className,
+}: {
+ name: string
+ size?: 'sm' | 'md' | 'lg'
+ className?: string
+}): JSX.Element {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ 'inline-flex shrink-0 items-center justify-center rounded-md font-semibold text-white uppercase',
+ size === 'sm' && 'size-4 rounded text-[9px]',
+ size === 'md' && 'size-6 text-xs',
+ size === 'lg' && 'size-10 rounded-lg text-base',
+ className
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ backgroundColor: analyticsSpaceColor(name) }}
+ >
+ {name.trim().charAt(0) || '#'}
+ </span>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsSpaces.tsx b/frontend/src/scenes/analytics/AnalyticsSpaces.tsx
new file mode 100644
index 000000000000..bcb5b1e475c6
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsSpaces.tsx
@@ -0,0 +1,245 @@
+import { useActions, useValues } from 'kea'
+
+import { IconBox, IconPin, IconPinFilled, IconPlus, IconSearch } from '@posthog/icons'
+import {
+ Button,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ InputGroupText,
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemTitle,
+ Skeleton,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@posthog/quill'
+
+import { NotFound } from 'lib/components/NotFound'
+import { dayjs } from 'lib/dayjs'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { cn } from 'lib/utils/css-classes'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { todayAnalyticsLogic } from '~/layout/today/todayAnalyticsLogic'
+import { TodayAnalyticsNewFolderDialog } from '~/layout/today/TodayAnalyticsNewFolderDialog'
+
+import { AnalyticsCreateModals } from './AnalyticsCreateModals'
+import { AnalyticsSpaceGlyph } from './AnalyticsSpaceGlyph'
+import { AnalyticsSpace, analyticsSpacesLogic } from './analyticsSpacesLogic'
+import { AnalyticsTypeIcon } from './AnalyticsTypeIcon'
+import { ANALYTICS_TYPES } from './analyticsUtils'
+
+export const scene: SceneExport = {
+ component: AnalyticsSpaces,
+ logic: analyticsSpacesLogic,
+}
+
+export function AnalyticsSpaces(): JSX.Element {
+ const enabled = useFeatureFlag('TODAY_RAIL_NAV')
+ return enabled ? <AnalyticsSpacesContent /> : <NotFound object="page" />
+}
+
+/** Each count sits in a cell of one width, so the columns line up down the list whatever the numbers. */
+function SpaceCounts({ space, className }: { space: AnalyticsSpace; className?: string }): JSX.Element {
+ return (
+ <div className={cn('flex flex-wrap gap-x-4 gap-y-1', className)}>
+ {ANALYTICS_TYPES.map((info) => (
+ <span
+ key={info.type}
+ className="flex items-center gap-1 text-xs whitespace-nowrap text-muted-foreground @3xl/analytics:w-28"
+ >
+ <span
+ className="flex [&_svg]:size-4"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ color: info.color }}
+ >
+ <AnalyticsTypeIcon type={info.type} />
+ </span>
+ <span className="font-semibold text-foreground">{space.counts[info.type]}</span>
+ {space.counts[info.type] === 1 ? info.label.toLowerCase() : info.pluralLabel.toLowerCase()}
+ </span>
+ ))}
+ </div>
+ )
+}
+
+function SpaceRow({ space }: { space: AnalyticsSpace }): JSX.Element {
+ const { pinnedPaths, pinning } = useValues(analyticsSpacesLogic)
+ const { togglePin } = useActions(analyticsSpacesLogic)
+ const pinned = pinnedPaths.has(space.path)
+ return (
+ <Item
+ variant="outline"
+ size="sm"
+ className="relative items-center gap-3 transition-colors hover:bg-fill-button-tertiary-hover"
+ data-attr="analytics-space-row"
+ >
+ <ItemMedia>
+ <AnalyticsSpaceGlyph name={space.name} size="lg" />
+ </ItemMedia>
+ <ItemContent className="min-w-0 gap-0.5">
+ <ItemTitle className="truncate">
+ {/* The link's pseudo-element covers the row, so the whole row opens the space while the pin stays its own control. */}
+ <LinkPrimitive
+ to={urls.analyticsList({ folder: space.path })}
+ className="text-foreground after:absolute after:inset-0 after:content-['']"
+ data-attr="analytics-space-card"
+ >
+ {space.name}
+ </LinkPrimitive>
+ </ItemTitle>
+ <ItemDescription>
+ {space.total === 0
+ ? 'Nothing here yet'
+ : `${space.total} ${space.total === 1 ? 'item' : 'items'}${
+ space.lastAddedAt ? ` · added ${dayjs(space.lastAddedAt).fromNow()}` : ''
+ }`}
+ </ItemDescription>
+ <SpaceCounts space={space} className="mt-1 @3xl/analytics:hidden" />
+ </ItemContent>
+ <SpaceCounts space={space} className="hidden shrink-0 @3xl/analytics:flex" />
+ <ItemActions className="relative z-10 shrink-0 self-center">
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="default"
+ size="icon"
+ aria-pressed={pinned}
+ aria-label={pinned ? 'Unpin from sidebar' : 'Pin to sidebar'}
+ loading={pinning === space.path}
+ onClick={() => togglePin(space)}
+ data-attr="analytics-space-star"
+ />
+ }
+ >
+ {pinned ? <IconPinFilled className="size-5 text-warning" /> : <IconPin className="size-5" />}
+ </TooltipTrigger>
+ <TooltipContent>{pinned ? 'Unpin from the sidebar' : 'Pin to the sidebar'}</TooltipContent>
+ </Tooltip>
+ </ItemActions>
+ </Item>
+ )
+}
+
+function AnalyticsSpacesContent(): JSX.Element {
+ const { spaces, visibleSpaces, spacesLoading, spacesFailed, search } = useValues(analyticsSpacesLogic)
+ const { loadSpaces, setSearch } = useActions(analyticsSpacesLogic)
+ const { setNewFolderDialogOpen } = useActions(todayAnalyticsLogic)
+
+ const newSpaceButton = (
+ <Button
+ variant="primary"
+ size="sm"
+ onClick={() => setNewFolderDialogOpen(true)}
+ data-attr="analytics-spaces-new"
+ >
+ <IconPlus />
+ New collection
+ </Button>
+ )
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="Collections"
+ description="Where teams keep the work they share."
+ resourceType={{ type: 'analytics', forceIcon: <IconBox /> }}
+ actions={<div data-quill>{newSpaceButton}</div>}
+ />
+ <div data-quill className="@container/analytics flex flex-col gap-3">
+ {spacesFailed ? (
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>Couldn’t load your collections</EmptyTitle>
+ <EmptyDescription>Try again, and if it keeps happening contact support.</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button variant="outline" loading={spacesLoading} onClick={() => loadSpaces()}>
+ Try again
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : spacesLoading && !spaces.length ? (
+ <div className="flex flex-col gap-2" aria-busy>
+ {Array.from({ length: 4 }, (_, index) => (
+ <Skeleton key={index} className="h-16" />
+ ))}
+ </div>
+ ) : !spaces.length ? (
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>No collections yet</EmptyTitle>
+ <EmptyDescription>
+ Create one for a team or an area, then add work to it from each item's page.
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>{newSpaceButton}</EmptyContent>
+ </Empty>
+ ) : (
+ <>
+ <InputGroup className="h-8 w-56 max-w-full">
+ <InputGroupAddon align="inline-start">
+ <InputGroupText>
+ <IconSearch />
+ </InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ type="search"
+ aria-label="Search collections"
+ placeholder="Search collections"
+ value={search}
+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => setSearch(event.target.value)}
+ data-attr="analytics-spaces-search"
+ />
+ </InputGroup>
+ {visibleSpaces.length ? (
+ <ItemGroup className="flex flex-col gap-2 pb-8">
+ {visibleSpaces.map((space) => (
+ <SpaceRow key={space.path} space={space} />
+ ))}
+ </ItemGroup>
+ ) : (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <IconSearch />
+ </EmptyMedia>
+ <EmptyTitle>No collection matches</EmptyTitle>
+ <EmptyDescription>Try a different name, or clear the search.</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button
+ variant="outline"
+ onClick={() => setSearch('')}
+ data-attr="analytics-spaces-clear-search"
+ >
+ Clear search
+ </Button>
+ </EmptyContent>
+ </Empty>
+ )}
+ </>
+ )}
+ </div>
+ <AnalyticsCreateModals />
+ <TodayAnalyticsNewFolderDialog />
+ </SceneContent>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsTypeIcon.tsx b/frontend/src/scenes/analytics/AnalyticsTypeIcon.tsx
new file mode 100644
index 000000000000..60d0dc581be0
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsTypeIcon.tsx
@@ -0,0 +1,15 @@
+import { IconDashboard, IconGraph, IconNotebook, IconPalette } from '@posthog/icons'
+
+import { AnalyticsType } from './analyticsUtils'
+
+const ICONS: Record<AnalyticsType, JSX.Element> = {
+ canvas: <IconPalette />,
+ dashboard: <IconDashboard />,
+ notebook: <IconNotebook />,
+ insight: <IconGraph />,
+}
+
+/** The icon that marks an item's type in lists, menus and the sidebar. */
+export function AnalyticsTypeIcon({ type }: { type: AnalyticsType }): JSX.Element {
+ return ICONS[type]
+}
diff --git a/frontend/src/scenes/analytics/NewAnalyticsMenu.tsx b/frontend/src/scenes/analytics/NewAnalyticsMenu.tsx
new file mode 100644
index 000000000000..89fcc2b68227
--- /dev/null
+++ b/frontend/src/scenes/analytics/NewAnalyticsMenu.tsx
@@ -0,0 +1,55 @@
+import { useActions } from 'kea'
+
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ IconStack,
+ IconStackItem,
+ ItemContent,
+ ItemDescription,
+ ItemTitle,
+} from '@posthog/quill'
+
+import { AnalyticsTypeIcon } from './AnalyticsTypeIcon'
+import { ANALYTICS_TYPES } from './analyticsUtils'
+import { NewAnalyticsSource, newAnalyticsLogic } from './newAnalyticsLogic'
+
+interface NewAnalyticsMenuProps {
+ /** The element that opens the menu, such as a quill `Button`. The menu merges its own props onto it. */
+ trigger: JSX.Element
+ source: NewAnalyticsSource
+ children?: React.ReactNode
+}
+
+/** Asks which type of analysis to create, then hands off to that type's own create flow. */
+export function NewAnalyticsMenu({ trigger, source, children }: NewAnalyticsMenuProps): JSX.Element {
+ const { pickNewAnalyticsType } = useActions(newAnalyticsLogic)
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger render={trigger}>{children}</DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-72">
+ {ANALYTICS_TYPES.map((info) => (
+ <DropdownMenuItem
+ key={info.type}
+ className="h-auto cursor-pointer items-start py-1.5 whitespace-normal"
+ onClick={() => pickNewAnalyticsType(info.type, source)}
+ data-attr={`analytics-new-${info.type}`}
+ >
+ <IconStack className="mt-0.5 shrink-0">
+ <IconStackItem color={info.color}>
+ <AnalyticsTypeIcon type={info.type} />
+ </IconStackItem>
+ </IconStack>
+ <ItemContent variant="menuItem">
+ <ItemTitle>{info.label}</ItemTitle>
+ <ItemDescription>{info.description}</ItemDescription>
+ </ItemContent>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
diff --git a/frontend/src/scenes/analytics/NewInsightDialog.tsx b/frontend/src/scenes/analytics/NewInsightDialog.tsx
new file mode 100644
index 000000000000..2f140caa9cb0
--- /dev/null
+++ b/frontend/src/scenes/analytics/NewInsightDialog.tsx
@@ -0,0 +1,44 @@
+import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+
+import { Dialog, DialogBody, DialogContent, DialogHeader, DialogTitle } from '@posthog/quill'
+
+import { NewInsightMenuContent } from 'products/product_analytics/frontend/insights/newInsightMenu/NewInsightMenu'
+
+import { withBackLink } from './analyticsBackLink'
+import { newAnalyticsLogic } from './newAnalyticsLogic'
+
+/** The insight type picker in a dialog, so the Analytics pages stay put until a type is chosen. */
+export function NewInsightDialog(): JSX.Element {
+ const { newInsightDialogOpen } = useValues(newAnalyticsLogic)
+ const { setNewInsightDialogOpen } = useActions(newAnalyticsLogic)
+
+ // The picker's cards are plain links to the editor. Catching the click here adds the way back to
+ // Analytics, which the editor then carries on to the saved insight.
+ const onClickCapture = (event: React.MouseEvent<HTMLDivElement>): void => {
+ const anchor = (event.target as HTMLElement).closest('a[href]')
+ if (!anchor || event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) {
+ return
+ }
+ event.preventDefault()
+ event.stopPropagation()
+ const href = anchor.getAttribute('href') ?? ''
+ setNewInsightDialogOpen(false)
+ router.actions.push(withBackLink(href))
+ }
+
+ return (
+ <Dialog open={newInsightDialogOpen} onOpenChange={(open: boolean) => !open && setNewInsightDialogOpen(false)}>
+ <DialogContent size="wide" data-attr="analytics-new-insight-dialog">
+ <DialogHeader>
+ <DialogTitle>New insight</DialogTitle>
+ </DialogHeader>
+ <DialogBody>
+ <div onClickCapture={onClickCapture}>
+ <NewInsightMenuContent />
+ </div>
+ </DialogBody>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/scenes/analytics/ShareToSpaceDialog.tsx b/frontend/src/scenes/analytics/ShareToSpaceDialog.tsx
new file mode 100644
index 000000000000..5fee022c8817
--- /dev/null
+++ b/frontend/src/scenes/analytics/ShareToSpaceDialog.tsx
@@ -0,0 +1,129 @@
+import { useActions, useValues } from 'kea'
+
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ Item,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemTitle,
+ Skeleton,
+ Text,
+} from '@posthog/quill'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { analyticsShareLogic } from './analyticsShareLogic'
+import { AnalyticsSpaceGlyph } from './AnalyticsSpaceGlyph'
+
+/** Picks the space an item is shared into, or moved to, on the quill Analytics pages. */
+export function ShareToSpaceDialog(): JSX.Element {
+ const { target, spaces, spacesLoading, sharing, currentSpace, entryLoading } = useValues(analyticsShareLogic)
+ const { closeShareToSpace, shareToSpace } = useActions(analyticsShareLogic)
+ const moving = !!currentSpace
+ const loading = (spacesLoading && !spaces.length) || entryLoading
+
+ return (
+ <Dialog open={!!target} onOpenChange={(open: boolean) => !open && closeShareToSpace()}>
+ <DialogContent className="max-h-[32rem]" data-attr="analytics-share-dialog">
+ <DialogHeader>
+ <DialogTitle>{moving ? 'Move to a collection' : 'Add to a collection'}</DialogTitle>
+ <DialogDescription>
+ {target
+ ? moving
+ ? `"${target.name}" is in ${currentSpace}. Pick where it goes next.`
+ : `Pick the collection "${target.name}" goes in.`
+ : ''}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ {loading ? (
+ <div className="flex flex-col gap-2" aria-busy>
+ <Skeleton className="h-10" />
+ <Skeleton className="h-10" />
+ </div>
+ ) : !spaces.length ? (
+ <div className="flex flex-col items-start gap-2">
+ <Text size="sm" variant="muted">
+ No collections yet. Create one first, then add to it.
+ </Text>
+ <Button
+ variant="outline"
+ size="sm"
+ nativeButton={false}
+ render={<LinkPrimitive to={urls.analyticsSpaces()} />}
+ onClick={() => closeShareToSpace()}
+ >
+ Open collections
+ </Button>
+ </div>
+ ) : (
+ <ItemGroup className="flex flex-col gap-1">
+ {spaces.map((space) => {
+ const isCurrent = space.name === currentSpace
+ return (
+ <Item
+ key={space.path}
+ variant="outline"
+ size="sm"
+ render={
+ <button
+ type="button"
+ disabled={isCurrent || sharing}
+ onClick={() => shareToSpace(space)}
+ data-attr="analytics-share-to-space"
+ />
+ }
+ className="cursor-pointer text-start text-foreground hover:bg-fill-button-tertiary-hover disabled:cursor-default disabled:opacity-60"
+ >
+ <ItemMedia aria-hidden>
+ <AnalyticsSpaceGlyph name={space.name} size="md" />
+ </ItemMedia>
+ <ItemContent className="min-w-0">
+ <ItemTitle>{space.name}</ItemTitle>
+ <ItemDescription>
+ {isCurrent
+ ? 'Current collection'
+ : space.total === 0
+ ? 'Empty'
+ : `${space.total} ${space.total === 1 ? 'item' : 'items'}`}
+ </ItemDescription>
+ </ItemContent>
+ </Item>
+ )
+ })}
+ {moving && (
+ <Item
+ variant="outline"
+ size="sm"
+ render={
+ <button
+ type="button"
+ disabled={sharing}
+ onClick={() => shareToSpace(null)}
+ data-attr="analytics-share-make-personal"
+ />
+ }
+ className="cursor-pointer text-start text-foreground hover:bg-fill-button-tertiary-hover"
+ >
+ <ItemContent className="min-w-0">
+ <ItemTitle>No collection</ItemTitle>
+ <ItemDescription>Takes it out of every collection.</ItemDescription>
+ </ItemContent>
+ </Item>
+ )}
+ </ItemGroup>
+ )}
+ </DialogBody>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/scenes/analytics/ShareToSpaceModal.tsx b/frontend/src/scenes/analytics/ShareToSpaceModal.tsx
new file mode 100644
index 000000000000..9f61e85c01a0
--- /dev/null
+++ b/frontend/src/scenes/analytics/ShareToSpaceModal.tsx
@@ -0,0 +1,92 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+import { urls } from 'scenes/urls'
+
+import { analyticsShareLogic } from './analyticsShareLogic'
+import { AnalyticsSpaceGlyph } from './AnalyticsSpaceGlyph'
+
+/** Picks the space an item is shared into, or moved to. Lives in the Lemon scene headers, so it is a Lemon modal. */
+export function ShareToSpaceModal(): JSX.Element {
+ const { target, spaces, spacesLoading, sharing, currentSpace, entryLoading } = useValues(analyticsShareLogic)
+ const { closeShareToSpace, shareToSpace } = useActions(analyticsShareLogic)
+ const moving = !!currentSpace
+ const loading = (spacesLoading && !spaces.length) || entryLoading
+
+ return (
+ <LemonModal
+ isOpen={!!target}
+ onClose={closeShareToSpace}
+ title={moving ? 'Move to a collection' : 'Add to a collection'}
+ description={
+ target
+ ? moving
+ ? `"${target.name}" is in ${currentSpace}. Pick where it goes next.`
+ : `Pick the collection "${target.name}" goes in.`
+ : undefined
+ }
+ width={480}
+ >
+ {loading ? (
+ <div className="flex flex-col gap-2">
+ <LemonSkeleton className="h-10" />
+ <LemonSkeleton className="h-10" />
+ </div>
+ ) : !spaces.length ? (
+ <div className="flex flex-col gap-2">
+ <p className="m-0 text-secondary">No collections yet. Create one first, then add to it.</p>
+ <LemonButton type="secondary" to={urls.analyticsSpaces()} onClick={closeShareToSpace}>
+ Open collections
+ </LemonButton>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-1">
+ {spaces.map((space) => {
+ const isCurrent = space.name === currentSpace
+ return (
+ <LemonButton
+ key={space.path}
+ type="tertiary"
+ fullWidth
+ icon={<AnalyticsSpaceGlyph name={space.name} size="md" />}
+ loading={sharing}
+ disabledReason={isCurrent ? 'Already here' : sharing ? 'Working…' : undefined}
+ onClick={() => shareToSpace(space)}
+ data-attr="analytics-share-to-space"
+ >
+ <span className="flex flex-col items-start">
+ <span>{space.name}</span>
+ <span className="text-xs text-secondary">
+ {isCurrent
+ ? 'Current collection'
+ : space.total === 0
+ ? 'Empty'
+ : `${space.total} ${space.total === 1 ? 'item' : 'items'}`}
+ </span>
+ </span>
+ </LemonButton>
+ )
+ })}
+ {moving && (
+ <LemonButton
+ type="tertiary"
+ fullWidth
+ loading={sharing}
+ onClick={() => shareToSpace(null)}
+ data-attr="analytics-share-make-personal"
+ >
+ <span className="flex flex-col items-start">
+ <span>No collection</span>
+ <span className="text-xs text-secondary">
+ Takes it out of every collection. It stays in View all.
+ </span>
+ </span>
+ </LemonButton>
+ )}
+ </div>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/analytics/analyticsBackLink.test.ts b/frontend/src/scenes/analytics/analyticsBackLink.test.ts
new file mode 100644
index 000000000000..cc9a00cabfb1
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsBackLink.test.ts
@@ -0,0 +1,76 @@
+import { router } from 'kea-router'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { analyticsBackLink, withBackLink } from './analyticsBackLink'
+
+const FLAG_ON = { [FEATURE_FLAGS.TODAY_RAIL_NAV]: true }
+
+describe('analyticsBackLink', () => {
+ test.each([
+ [
+ 'an Analytics list',
+ { backUrl: '/analytics/all?type=notebook', backName: 'Analytics' },
+ FLAG_ON,
+ '/analytics/all?type=notebook',
+ ],
+ ['a project-prefixed Analytics page', { backUrl: '/project/1/analytics' }, FLAG_ON, '/project/1/analytics'],
+ ["a flag's usage dashboard link", { backUrl: '/feature_flags/12', backName: 'my-flag' }, FLAG_ON, null],
+ ['an external address', { backUrl: 'https://example.com/analytics' }, FLAG_ON, null],
+ ['a protocol-relative address', { backUrl: '//example.com/analytics' }, FLAG_ON, null],
+ ['an Analytics link for someone without the flag', { backUrl: '/analytics/all' }, {}, null],
+ ['no link at all', {}, FLAG_ON, null],
+ ])('trusts %s: %s', (_, searchParams, featureFlags, expected) => {
+ expect(analyticsBackLink(searchParams, featureFlags)?.url ?? null).toBe(expected)
+ })
+})
+
+describe('withBackLink', () => {
+ beforeEach(() => {
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TODAY_RAIL_NAV], FLAG_ON)
+ })
+
+ test.each([
+ [
+ 'an Analytics page names itself',
+ '/project/1/analytics/all?type=notebook',
+ '/notebooks/abc',
+ { backUrl: '/analytics/all?type=notebook', backName: 'Analytics' },
+ ],
+ [
+ 'a hop keeps the Analytics link it was given',
+ '/project/1/notebooks/new?backUrl=%2Fanalytics&backName=Analytics',
+ '/notebooks/abc',
+ { backUrl: '/analytics', backName: 'Analytics' },
+ ],
+ [
+ 'a hop drops a link another page left',
+ '/project/1/dashboard/12?backUrl=%2Ffeature_flags%2F12&backName=my-flag',
+ '/notebooks/abc',
+ null,
+ ],
+ ['any other page leaves the URL alone', '/project/1/dashboard/12', '/notebooks/abc', null],
+ ])('%s', (_, from, to, expected) => {
+ router.actions.push(from)
+ const result = withBackLink(to)
+ if (!expected) {
+ expect(result).toBe(to)
+ return
+ }
+ const url = new URL(result, 'http://localhost')
+ expect(url.pathname).toBe(to)
+ expect(url.searchParams.get('backUrl')).toBe(expected.backUrl)
+ expect(url.searchParams.get('backName')).toBe(expected.backName)
+ })
+
+ it('leaves the URL alone for someone without the flag, even on an Analytics page', () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TODAY_RAIL_NAV], {})
+ router.actions.push('/project/1/analytics/all')
+ expect(withBackLink('/notebooks/abc')).toBe('/notebooks/abc')
+ })
+})
diff --git a/frontend/src/scenes/analytics/analyticsBackLink.ts b/frontend/src/scenes/analytics/analyticsBackLink.ts
new file mode 100644
index 000000000000..32f5c3cebd04
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsBackLink.ts
@@ -0,0 +1,71 @@
+import { combineUrl, router } from 'kea-router'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { urls } from 'scenes/urls'
+
+import { ANALYTICS_BACK_NAME } from './analyticsUtils'
+
+export interface AnalyticsBackLink {
+ url: string
+ name: string
+}
+
+function isAnalyticsPath(path: string): boolean {
+ return path === urls.analytics() || path.startsWith(`${urls.analytics()}/`)
+}
+
+/**
+ * The way back an Analytics page left in the URL, or null when the URL holds none to trust.
+ *
+ * Other pages write `backUrl` too (a flag's usage dashboard, the accounts list), and anyone can type one.
+ * Only a relative link under the Analytics pages counts, and only while the pane exists for this person,
+ * so a shared address bar never sends a colleague without the flag to a missing page or off the app.
+ */
+export function analyticsBackLink(
+ searchParams: Record<string, unknown>,
+ featureFlags: Record<string, unknown>
+): AnalyticsBackLink | null {
+ const backUrl = searchParams.backUrl
+ if (typeof backUrl !== 'string' || !backUrl.startsWith('/') || backUrl.startsWith('//')) {
+ return null
+ }
+ if (!featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
+ return null
+ }
+ if (!isAnalyticsPath(removeProjectIdIfPresent(backUrl.split(/[?#]/)[0]))) {
+ return null
+ }
+ const backName = searchParams.backName
+ return { url: backUrl, name: typeof backName === 'string' && backName ? backName : ANALYTICS_BACK_NAME }
+}
+
+/**
+ * The URL with the way back carried along, so a page reached from Analytics sends the person back there.
+ *
+ * A create flow moves through several URLs (the "new" page, then the saved item), so each hop keeps an
+ * Analytics link it was given. A hop that starts on an Analytics page names that page as the way back.
+ * Anywhere else the URL is returned as is, and the destination falls back to its own list.
+ */
+export function withBackLink(url: string): string {
+ const { location, searchParams } = router.values
+ const featureFlags = featureFlagLogic.findMounted()?.values.featureFlags ?? {}
+ const current = removeProjectIdIfPresent(location.pathname)
+ const carried = analyticsBackLink(searchParams, featureFlags)
+ if (carried) {
+ return combineUrl(url, { backUrl: carried.url, backName: carried.name }).url
+ }
+ if (featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] && isAnalyticsPath(current)) {
+ return combineUrl(url, { backUrl: `${current}${location.search}`, backName: ANALYTICS_BACK_NAME }).url
+ }
+ return url
+}
+
+/** The two params that carry an Analytics back link, for a page that rebuilds its own URL and must keep them. */
+export function backLinkParams(
+ searchParams: Record<string, unknown>
+): { backUrl: string; backName: string } | undefined {
+ const link = analyticsBackLink(searchParams, featureFlagLogic.findMounted()?.values.featureFlags ?? {})
+ return link ? { backUrl: link.url, backName: link.name } : undefined
+}
diff --git a/frontend/src/scenes/analytics/analyticsFeed.ts b/frontend/src/scenes/analytics/analyticsFeed.ts
new file mode 100644
index 000000000000..3c1e2dee9635
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsFeed.ts
@@ -0,0 +1,153 @@
+import api from 'lib/api'
+
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+import {
+ ANALYTICS_TYPES,
+ AnalyticsItem,
+ AnalyticsType,
+ AnalyticsTypeFilter,
+ fileSystemEntryToAnalytics,
+} from './analyticsUtils'
+
+export const ANALYTICS_FEED_PAGE_SIZE = 50
+
+export interface AnalyticsFeedQuery {
+ type: AnalyticsTypeFilter
+ search: string
+ /** Creators' uuids; empty means anyone. The file system cannot filter on it, so the rows are narrowed on the client. */
+ createdBy: string[]
+ /** Tag names a row must all carry. Like the creator, narrowed on the client. */
+ tags: string[]
+}
+
+export const EMPTY_ANALYTICS_FEED_QUERY: AnalyticsFeedQuery = { type: 'all', search: '', createdBy: [], tags: [] }
+
+export interface AnalyticsSourcePage {
+ items: AnalyticsItem[]
+ /** Rows the API returned, before any client-side filtering, so the next offset stays right. */
+ fetched: number
+ hasMore: boolean
+}
+
+export interface AnalyticsSourceState {
+ projectId: string
+ query: AnalyticsFeedQuery
+ type: AnalyticsType
+ items: AnalyticsItem[]
+ offset: number
+ hasMore: boolean
+ initialized: boolean
+ refreshing: boolean
+ loading: boolean
+ failed: boolean
+ generation: number
+}
+
+export interface AnalyticsFeed {
+ items: AnalyticsItem[]
+ initialized: boolean
+ loading: boolean
+ hasMore: boolean
+ failedTypes: AnalyticsType[]
+ loadFailed: boolean
+}
+
+// Only dashboards and insights carry tags, so a tag filter leaves the other types out of the read.
+const TAGGABLE_ANALYTICS_TYPES: ReadonlySet<AnalyticsType> = new Set<AnalyticsType>(['dashboard', 'insight'])
+
+export function analyticsFeedTypes(query: AnalyticsFeedQuery): AnalyticsType[] {
+ const types = query.type === 'all' ? ANALYTICS_TYPES.map((info) => info.type) : [query.type]
+ return query.tags.length ? types.filter((type) => TAGGABLE_ANALYTICS_TYPES.has(type)) : types
+}
+
+export function analyticsSourceKey(projectId: string, query: AnalyticsFeedQuery, type: AnalyticsType): string {
+ return JSON.stringify([projectId, query.search.trim(), query.createdBy, [...query.tags].sort(), type])
+}
+
+/** Keeps the rows a source's API could not filter itself. */
+export function matchesAnalyticsQuery(item: AnalyticsItem, query: AnalyticsFeedQuery): boolean {
+ return (
+ (!query.createdBy.length || (!!item.createdBy && query.createdBy.includes(item.createdBy.uuid))) &&
+ query.tags.every((tag) => item.tags.includes(tag))
+ )
+}
+
+// Insights file as `insight` or under a subtype such as `insight/trends`, so they match on the prefix.
+export function fileSystemTypeParams(type: AnalyticsType): { type?: string; type__startswith?: string } {
+ return type === 'insight' ? { type__startswith: 'insight' } : { type }
+}
+
+/** One page of a type's rows from the project file system, newest first, with the row's space. */
+export async function fetchAnalyticsSourcePage(
+ _projectId: string,
+ type: AnalyticsType,
+ query: AnalyticsFeedQuery,
+ offset: number
+): Promise<AnalyticsSourcePage> {
+ const limit = ANALYTICS_FEED_PAGE_SIZE
+ const result = await api.fileSystem.list({
+ ...fileSystemTypeParams(type),
+ search: query.search.trim() || undefined,
+ orderBy: '-created_at',
+ includeTags: true,
+ limit,
+ offset,
+ })
+ const items = result.results.flatMap((entry: FileSystemEntry) => {
+ const item = fileSystemEntryToAnalytics(entry, result.users ?? [])
+ return item && matchesAnalyticsQuery(item, query) ? [item] : []
+ })
+ return { items, fetched: result.results.length, hasMore: !!result.next && result.results.length > 0 }
+}
+
+export function analyticsTime(item: AnalyticsItem): number {
+ return item.timestamp ? new Date(item.timestamp).getTime() : 0
+}
+export function mergeAnalyticsSources(sources: (AnalyticsSourceState | undefined)[]): {
+ items: AnalyticsItem[]
+ blocking: AnalyticsSourceState[]
+} {
+ const states = sources.map(
+ (source) => source ?? ({ items: [], hasMore: true, initialized: false } as unknown as AnalyticsSourceState)
+ )
+ const positions = states.map(() => 0)
+ const items: AnalyticsItem[] = []
+ for (;;) {
+ const blocking = states.filter(
+ (state, index) => positions[index] >= state.items.length && (state.hasMore || !state.initialized)
+ )
+ if (blocking.length) {
+ return { items, blocking: blocking.filter((state) => sources.includes(state)) }
+ }
+ let best = -1
+ for (let index = 0; index < states.length; index++) {
+ if (
+ positions[index] < states[index].items.length &&
+ (best === -1 ||
+ analyticsTime(states[index].items[positions[index]]) >
+ analyticsTime(states[best].items[positions[best]]))
+ ) {
+ best = index
+ }
+ }
+ if (best === -1) {
+ return { items, blocking: [] }
+ }
+ items.push(states[best].items[positions[best]++])
+ }
+}
+
+export function analyticsFeedFromSources(sources: (AnalyticsSourceState | undefined)[]): AnalyticsFeed {
+ const { items, blocking } = mergeAnalyticsSources(sources)
+ const initialized = sources.every((source) => source?.initialized)
+ const failed = sources.filter((source): source is AnalyticsSourceState => !!source?.failed)
+ return {
+ items: initialized ? items : [],
+ initialized,
+ loading: sources.some((source) => !source || source.loading || source.refreshing),
+ hasMore: blocking.length > 0,
+ failedTypes: failed.map((source) => source.type),
+ loadFailed: initialized && failed.length === sources.length && items.length === 0,
+ }
+}
diff --git a/frontend/src/scenes/analytics/analyticsFeedLogic.test.ts b/frontend/src/scenes/analytics/analyticsFeedLogic.test.ts
new file mode 100644
index 000000000000..c6443970ed76
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsFeedLogic.test.ts
@@ -0,0 +1,160 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { AnalyticsFeedQuery, EMPTY_ANALYTICS_FEED_QUERY } from './analyticsFeed'
+import { analyticsFeedLogic, resetAnalyticsFeedSnapshot, selectAnalyticsFeed } from './analyticsFeedLogic'
+
+const ALL: AnalyticsFeedQuery = EMPTY_ANALYTICS_FEED_QUERY
+
+const at = (day: number): string => `2026-09-${String(day).padStart(2, '0')}T00:00:00Z`
+const ADA = { id: 1, uuid: 'u-ada', first_name: 'Ada', last_name: '', email: '[email protected]' }
+const GRACE = { id: 2, uuid: 'u-grace', first_name: 'Grace', last_name: '', email: '[email protected]' }
+const USERS = [ADA, GRACE]
+
+const entry = (
+ type: string,
+ ref: string,
+ path: string,
+ createdAt: string,
+ createdBy: typeof ADA
+): Record<string, unknown> => ({
+ id: `fs-${ref}`,
+ type,
+ ref,
+ path,
+ href: `/x/${ref}`,
+ created_at: createdAt,
+ last_viewed_at: null,
+ meta: { created_by: createdBy.id },
+})
+
+describe('analyticsFeedLogic', () => {
+ let requests: string[]
+
+ beforeEach(() => {
+ resetAnalyticsFeedSnapshot()
+ requests = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/task_channels/': [],
+ '/api/projects/:team_id/file_system/unfiled/': () => {
+ requests.push('unfiled')
+ return { count: 0 }
+ },
+ '/api/projects/:team_id/file_system/': ({ request }) => {
+ const params = new URL(request.url).searchParams
+ const type = params.get('type') ?? params.get('type__startswith') ?? ''
+ const offset = params.get('offset') ?? '0'
+ requests.push(`${type}:${offset}:${params.get('order_by')}`)
+ if (type === 'canvas') {
+ return { results: [entry('canvas', 'c7', 'Growth/C', at(7), GRACE)], users: USERS, next: null }
+ }
+ if (type === 'notebook') {
+ return {
+ results: [
+ entry('notebook', 'n9', 'Unfiled/Notebooks/N', at(9), ADA),
+ entry('notebook', 'n1', 'Growth/N', at(1), ADA),
+ ],
+ users: USERS,
+ next: null,
+ }
+ }
+ if (type === 'insight') {
+ return {
+ results: [entry('insight/trends', 'i5', 'Growth/I', at(5), ADA)],
+ users: USERS,
+ next: null,
+ }
+ }
+ return offset === '0'
+ ? {
+ results: [
+ entry('dashboard', '10', 'Growth/D', at(10), ADA),
+ entry('dashboard', '8', 'Unfiled/Dashboards/D', at(8), GRACE),
+ ],
+ users: USERS,
+ next: '?offset=2',
+ }
+ : {
+ results: [entry('dashboard', '3', 'Growth/D', at(3), ADA)],
+ users: USERS,
+ next: null,
+ }
+ },
+ },
+ })
+ initKeaTests()
+ })
+
+ const feed = (logic: ReturnType<typeof analyticsFeedLogic.build>, query: AnalyticsFeedQuery = ALL): string[] =>
+ selectAnalyticsFeed(logic.values.sources, teamLogic.values.currentTeamId, query).items.map(
+ (item) => `${item.type}:${item.id}`
+ )
+
+ it('shows only rows whose order is final, and loads more from the type that holds them back', async () => {
+ const logic = analyticsFeedLogic()
+ logic.mount()
+
+ await expectLogic(logic, () => logic.actions.refreshFeed(ALL)).toFinishAllListeners()
+ expect(feed(logic)).toEqual(['dashboard:10', 'notebook:n9', 'dashboard:8'])
+
+ await expectLogic(logic, () => logic.actions.ensureFeed(ALL, 100)).toFinishAllListeners()
+ expect(feed(logic)).toEqual([
+ 'dashboard:10',
+ 'notebook:n9',
+ 'dashboard:8',
+ 'canvas:c7',
+ 'insight:i5',
+ 'dashboard:3',
+ 'notebook:n1',
+ ])
+ // The unfiled sweep runs once, before any source is read, so pre-sync objects get their rows.
+ expect(requests[0]).toBe('unfiled')
+ expect(requests.filter((request) => request === 'unfiled')).toHaveLength(1)
+ expect(requests.filter((request) => request !== 'unfiled').sort()).toEqual([
+ 'canvas:0:-created_at',
+ 'dashboard:0:-created_at',
+ 'dashboard:2:-created_at',
+ 'insight:0:-created_at',
+ 'notebook:0:-created_at',
+ ])
+ const result = selectAnalyticsFeed(logic.values.sources, teamLogic.values.currentTeamId, ALL)
+ expect(result.hasMore).toBe(false)
+ expect(result.items.map((item) => item.spaceName)).toEqual([
+ 'Growth',
+ null,
+ null,
+ 'Growth',
+ 'Growth',
+ 'Growth',
+ 'Growth',
+ ])
+ })
+
+ it('narrows rows to a creator on the client, since the file system cannot', async () => {
+ const logic = analyticsFeedLogic()
+ logic.mount()
+ const byAda: AnalyticsFeedQuery = { ...ALL, createdBy: ['u-ada'] }
+
+ await expectLogic(logic, () => logic.actions.ensureFeed(byAda, 100)).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.ensureFeed(byAda, 100)).toFinishAllListeners()
+
+ expect(feed(logic, byAda)).toEqual(['dashboard:10', 'notebook:n9', 'insight:i5', 'dashboard:3', 'notebook:n1'])
+ })
+
+ it('keeps the loaded list after a remount, so a revisit shows rows at once', async () => {
+ const first = analyticsFeedLogic()
+ first.mount()
+ await expectLogic(first, () => first.actions.refreshFeed(ALL)).toFinishAllListeners()
+ first.unmount()
+
+ const second = analyticsFeedLogic()
+ second.mount()
+
+ expect(feed(second)).toEqual(['dashboard:10', 'notebook:n9', 'dashboard:8'])
+ })
+})
diff --git a/frontend/src/scenes/views/viewFeedLogic.ts b/frontend/src/scenes/analytics/analyticsFeedLogic.ts
similarity index 52%
rename from frontend/src/scenes/views/viewFeedLogic.ts
rename to frontend/src/scenes/analytics/analyticsFeedLogic.ts
index 85aead7d8b58..2cfe7a5615f1 100644
--- a/frontend/src/scenes/views/viewFeedLogic.ts
+++ b/frontend/src/scenes/analytics/analyticsFeedLogic.ts
@@ -1,40 +1,34 @@
import { MakeLogicType, actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers } from 'kea'
-import { loaders } from 'kea-loaders'
+import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'
-import { spaceLabel } from '~/layout/today/todaySpacesLogic'
-
-import { taskChannelsList } from 'products/tasks/frontend/generated/api'
-import type { ChannelDTOApi } from 'products/tasks/frontend/generated/api.schemas'
-
import {
- ViewFeed,
- ViewFeedQuery,
- ViewSourcePage,
- ViewSourceState,
- fetchViewSourcePage,
- mergeViewSources,
- viewFeedFromSources,
- viewFeedTypes,
- viewSourceKey,
-} from './viewFeed'
-import { ViewType } from './viewsUtils'
+ AnalyticsFeed,
+ AnalyticsFeedQuery,
+ AnalyticsSourcePage,
+ AnalyticsSourceState,
+ analyticsFeedFromSources,
+ analyticsFeedTypes,
+ analyticsSourceKey,
+ fetchAnalyticsSourcePage,
+ mergeAnalyticsSources,
+} from './analyticsFeed'
+import { AnalyticsType } from './analyticsUtils'
-const MAX_SEARCH_SOURCES = 30
+const MAX_FILTERED_SOURCES = 30
-interface ViewFeedSnapshot {
- sources: Record<string, ViewSourceState>
- spaceNames: Record<string, string>
+interface AnalyticsFeedSnapshot {
+ sources: Record<string, AnalyticsSourceState>
}
-let snapshot: ViewFeedSnapshot | null = null
+let snapshot: AnalyticsFeedSnapshot | null = null
-export function resetViewFeedSnapshot(): void {
+export function resetAnalyticsFeedSnapshot(): void {
snapshot = null
}
-function settledSources(sources: Record<string, ViewSourceState>): Record<string, ViewSourceState> {
+function settledSources(sources: Record<string, AnalyticsSourceState>): Record<string, AnalyticsSourceState> {
return Object.fromEntries(
Object.entries(sources)
.filter(([, source]) => source.initialized)
@@ -42,171 +36,132 @@ function settledSources(sources: Record<string, ViewSourceState>): Record<string
)
}
-function withoutOldSearches(sources: Record<string, ViewSourceState>): Record<string, ViewSourceState> {
- const searchKeys = Object.keys(sources).filter((key) => sources[key].search || sources[key].createdBy)
- const dropped = new Set(searchKeys.slice(0, Math.max(0, searchKeys.length - MAX_SEARCH_SOURCES)))
+function isFiltered(query: AnalyticsFeedQuery): boolean {
+ return !!query.search.trim() || query.createdBy.length > 0 || query.tags.length > 0
+}
+
+// Every search or filter combination is its own set of sources, so old ones are dropped to bound memory.
+function withoutOldFiltered(sources: Record<string, AnalyticsSourceState>): Record<string, AnalyticsSourceState> {
+ const filteredKeys = Object.keys(sources).filter((key) => isFiltered(sources[key].query))
+ const dropped = new Set(filteredKeys.slice(0, Math.max(0, filteredKeys.length - MAX_FILTERED_SOURCES)))
return dropped.size ? Object.fromEntries(Object.entries(sources).filter(([key]) => !dropped.has(key))) : sources
}
-export function selectViewFeed(
- sources: Record<string, ViewSourceState>,
- spaceNames: Record<string, string>,
+export function selectAnalyticsFeed(
+ sources: Record<string, AnalyticsSourceState>,
projectId: number | null,
- query: ViewFeedQuery
-): ViewFeed {
- return viewFeedFromSources(
- viewFeedTypes(query).map((type) =>
- projectId
- ? sources[viewSourceKey(String(projectId), query.search, type, query.createdBy ?? null)]
- : undefined
- ),
- spaceNames
+ query: AnalyticsFeedQuery
+): AnalyticsFeed {
+ return analyticsFeedFromSources(
+ analyticsFeedTypes(query).map((type) =>
+ projectId ? sources[analyticsSourceKey(String(projectId), query, type)] : undefined
+ )
)
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface viewFeedLogicValues {
+export interface analyticsFeedLogicValues {
currentTeamId: number | null // teamLogic
- sources: Record<string, ViewSourceState>
- spaceNames: Record<string, string>
- spaceNamesLoading: boolean
+ sources: Record<string, AnalyticsSourceState>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface viewFeedLogicActions {
+export interface analyticsFeedLogicActions {
ensureFeed: (
- query: ViewFeedQuery,
+ query: AnalyticsFeedQuery,
count: number
) => {
count: number
- query: ViewFeedQuery
+ query: AnalyticsFeedQuery
}
loadSourcePage: (key: string) => {
key: string
}
- loadSpaceNames: () => any
- loadSpaceNamesFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadSpaceNamesSuccess: (
- spaceNames: Record<string, string>,
- payload?: any
- ) => {
- spaceNames: Record<string, string>
- payload?: any
- }
- refreshFeed: (query: ViewFeedQuery) => {
- query: ViewFeedQuery
+ refreshFeed: (query: AnalyticsFeedQuery) => {
+ query: AnalyticsFeedQuery
}
refreshSource: (
key: string,
projectId: string,
- search: string,
- type: ViewType,
- createdBy: string | null
+ query: AnalyticsFeedQuery,
+ type: AnalyticsType
) => {
- createdBy: string | null
key: string
projectId: string
- search: string
- type: ViewType
+ query: AnalyticsFeedQuery
+ type: AnalyticsType
}
- restoreSnapshot: (snapshot: ViewFeedSnapshot) => {
- snapshot: ViewFeedSnapshot
+ restoreSnapshot: (snapshot: AnalyticsFeedSnapshot) => {
+ snapshot: AnalyticsFeedSnapshot
}
sourcePageLoaded: (
key: string,
generation: number,
offset: number,
- page: ViewSourcePage | null
+ page: AnalyticsSourcePage | null
) => {
generation: number
key: string
offset: number
- page: ViewSourcePage | null
+ page: AnalyticsSourcePage | null
}
sourceRefreshed: (
key: string,
generation: number,
- page: ViewSourcePage | null
+ page: AnalyticsSourcePage | null
) => {
generation: number
key: string
- page: ViewSourcePage | null
+ page: AnalyticsSourcePage | null
}
}
-export type viewFeedLogicType = MakeLogicType<viewFeedLogicValues, viewFeedLogicActions>
+export type analyticsFeedLogicType = MakeLogicType<analyticsFeedLogicValues, analyticsFeedLogicActions>
-export const viewFeedLogic = kea<viewFeedLogicType>([
- path(['scenes', 'views', 'viewFeedLogic']),
+/**
+ * The project's analytics, paged per type and merged newest first. Shared by the list page and the
+ * sidebar, so each query is fetched once and a revisit shows rows at once.
+ */
+export const analyticsFeedLogic = kea<analyticsFeedLogicType>([
+ path(['scenes', 'analytics', 'analyticsFeedLogic']),
connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
actions({
- ensureFeed: (query: ViewFeedQuery, count: number) => ({ query, count }),
- refreshFeed: (query: ViewFeedQuery) => ({ query }),
- refreshSource: (key: string, projectId: string, search: string, type: ViewType, createdBy: string | null) => ({
+ ensureFeed: (query: AnalyticsFeedQuery, count: number) => ({ query, count }),
+ refreshFeed: (query: AnalyticsFeedQuery) => ({ query }),
+ refreshSource: (key: string, projectId: string, query: AnalyticsFeedQuery, type: AnalyticsType) => ({
key,
projectId,
- search,
+ query,
type,
- createdBy,
}),
- sourceRefreshed: (key: string, generation: number, page: ViewSourcePage | null) => ({
+ sourceRefreshed: (key: string, generation: number, page: AnalyticsSourcePage | null) => ({
key,
generation,
page,
}),
loadSourcePage: (key: string) => ({ key }),
- sourcePageLoaded: (key: string, generation: number, offset: number, page: ViewSourcePage | null) => ({
+ sourcePageLoaded: (key: string, generation: number, offset: number, page: AnalyticsSourcePage | null) => ({
key,
generation,
offset,
page,
}),
- restoreSnapshot: (snapshot: ViewFeedSnapshot) => ({ snapshot }),
+ restoreSnapshot: (snapshot: AnalyticsFeedSnapshot) => ({ snapshot }),
}),
- loaders(({ values }) => ({
- spaceNames: [
- {} as Record<string, string>,
- {
- loadSpaceNames: async () => {
- if (!values.currentTeamId) {
- return values.spaceNames
- }
- try {
- const response = await taskChannelsList(String(values.currentTeamId))
- // Without `limit` the endpoint answers with a bare array rather than a page.
- const spaces = Array.isArray(response) ? (response as ChannelDTOApi[]) : response.results
- return Object.fromEntries(spaces.map((space) => [space.id, spaceLabel(space)]))
- } catch {
- return values.spaceNames
- }
- },
- },
- ],
- })),
reducers({
- spaceNames: {
- restoreSnapshot: (state, { snapshot }) => (Object.keys(state).length ? state : snapshot.spaceNames),
- },
sources: [
- {} as Record<string, ViewSourceState>,
+ {} as Record<string, AnalyticsSourceState>,
{
restoreSnapshot: (state, { snapshot }) => ({ ...snapshot.sources, ...state }),
- refreshSource: (state, { key, projectId, search, type, createdBy }) => {
+ refreshSource: (state, { key, projectId, query, type }) => {
const { [key]: current, ...rest } = state
- return withoutOldSearches({
+ return withoutOldFiltered({
...rest,
[key]: current
? { ...current, refreshing: true, generation: current.generation + 1 }
: {
projectId,
- search,
- createdBy,
+ query,
type,
items: [],
offset: 0,
@@ -224,7 +179,7 @@ export const viewFeedLogic = kea<viewFeedLogicType>([
if (!current || current.generation !== generation) {
return state
}
- const next: ViewSourceState = page
+ const next: AnalyticsSourceState = page
? {
...current,
items: page.items,
@@ -265,17 +220,20 @@ export const viewFeedLogic = kea<viewFeedLogicType>([
},
],
}),
- listeners(({ actions, values }) => ({
- refreshFeed: ({ query }) => {
+ listeners(({ actions, values, cache }) => ({
+ refreshFeed: async ({ query }) => {
if (!values.currentTeamId) {
return
}
+ // An object made before its product joined the file system has no row until the unfiled sweep
+ // files it, and Today never opens the project tree that runs that sweep, so the first read runs it.
+ cache.unfiledSweep ??= api.fileSystem.unfiled().catch(() => null)
+ await cache.unfiledSweep
const projectId = String(values.currentTeamId)
- const createdBy = query.createdBy ?? null
- for (const type of viewFeedTypes(query)) {
- const key = viewSourceKey(projectId, query.search, type, createdBy)
+ for (const type of analyticsFeedTypes(query)) {
+ const key = analyticsSourceKey(projectId, query, type)
if (!values.sources[key]?.refreshing) {
- actions.refreshSource(key, projectId, query.search.trim(), type, createdBy)
+ actions.refreshSource(key, projectId, { ...query, search: query.search.trim() }, type)
}
}
},
@@ -284,28 +242,24 @@ export const viewFeedLogic = kea<viewFeedLogicType>([
return
}
const projectId = String(values.currentTeamId)
- const keys = viewFeedTypes(query).map((type) =>
- viewSourceKey(projectId, query.search, type, query.createdBy ?? null)
- )
+ const keys = analyticsFeedTypes(query).map((type) => analyticsSourceKey(projectId, query, type))
if (keys.some((key) => !values.sources[key])) {
actions.refreshFeed(query)
return
}
- const { items, blocking } = mergeViewSources(keys.map((key) => values.sources[key]))
+ const { items, blocking } = mergeAnalyticsSources(keys.map((key) => values.sources[key]))
if (items.length >= count) {
return
}
for (const source of blocking) {
if (source.initialized && !source.loading && !source.refreshing) {
- actions.loadSourcePage(
- viewSourceKey(source.projectId, source.search, source.type, source.createdBy)
- )
+ actions.loadSourcePage(analyticsSourceKey(source.projectId, source.query, source.type))
}
}
},
- refreshSource: async ({ key, projectId, search, type, createdBy }) => {
+ refreshSource: async ({ key, projectId, query, type }) => {
const generation = values.sources[key].generation
- const page = await fetchViewSourcePage(projectId, type, search, createdBy, 0).catch(() => null)
+ const page = await fetchAnalyticsSourcePage(projectId, type, query, 0).catch(() => null)
actions.sourceRefreshed(key, generation, page)
},
loadSourcePage: async ({ key }) => {
@@ -314,13 +268,9 @@ export const viewFeedLogic = kea<viewFeedLogicType>([
return
}
const { generation, offset } = source
- const page = await fetchViewSourcePage(
- source.projectId,
- source.type,
- source.search,
- source.createdBy,
- offset
- ).catch(() => null)
+ const page = await fetchAnalyticsSourcePage(source.projectId, source.type, source.query, offset).catch(
+ () => null
+ )
actions.sourcePageLoaded(key, generation, offset, page)
},
})),
@@ -328,9 +278,8 @@ export const viewFeedLogic = kea<viewFeedLogicType>([
if (snapshot) {
actions.restoreSnapshot(snapshot)
}
- actions.loadSpaceNames()
}),
beforeUnmount(({ values }) => {
- snapshot = { sources: settledSources(values.sources), spaceNames: values.spaceNames }
+ snapshot = { sources: settledSources(values.sources) }
}),
])
diff --git a/frontend/src/scenes/analytics/analyticsListLogic.test.ts b/frontend/src/scenes/analytics/analyticsListLogic.test.ts
new file mode 100644
index 000000000000..5e1f86b77383
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsListLogic.test.ts
@@ -0,0 +1,97 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { urls } from 'scenes/urls'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { resetAnalyticsFeedSnapshot } from './analyticsFeedLogic'
+import { analyticsListLogic } from './analyticsListLogic'
+
+const ADA = { id: 1, uuid: 'u-ada', first_name: 'Ada', last_name: '', email: '[email protected]' }
+const entry = (type: string, ref: string, path: string): Record<string, unknown> => ({
+ id: `fs-${ref}`,
+ type,
+ ref,
+ path,
+ href: `/x/${ref}`,
+ created_at: '2026-09-01T00:00:00Z',
+ last_viewed_at: null,
+ meta: { created_by: ADA.id },
+})
+
+describe('analyticsListLogic', () => {
+ let capture: jest.SpyInstance
+
+ beforeEach(() => {
+ resetAnalyticsFeedSnapshot()
+ useMocks({
+ get: {
+ '/api/projects/:team_id/task_channels/': [],
+ '/api/projects/:team_id/file_system_shortcut/': { results: [] },
+ '/api/projects/:team_id/file_system/': ({ request }) => {
+ const params = new URL(request.url).searchParams
+ if (params.get('parent')) {
+ return { results: [entry('insight/trends', 'i2', 'Growth/I2')], users: [ADA], next: null }
+ }
+ const type = params.get('type') ?? params.get('type__startswith') ?? ''
+ const results =
+ type === 'insight'
+ ? [
+ entry('insight/trends', 'i1', 'Growth/I1'),
+ entry('insight/trends', 'i3', 'Unfiled/Insights/I3'),
+ ]
+ : type === 'notebook'
+ ? [entry('notebook', 'n1', 'Users/Ada/N1')]
+ : []
+ return { results, users: [ADA], next: null }
+ },
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TODAY_RAIL_NAV], {
+ [FEATURE_FLAGS.TODAY_RAIL_NAV]: true,
+ })
+ capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ })
+
+ afterEach(() => {
+ capture.mockRestore()
+ })
+
+ it('lists every row, in and out of collections, including home folder rows', async () => {
+ const logic = analyticsListLogic()
+ logic.mount()
+ router.actions.push(urls.analyticsList())
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.items.map((item) => [item.id, item.spaceName]).sort()).toEqual([
+ ['i1', 'Growth'],
+ ['i3', null],
+ ['n1', null],
+ ])
+ })
+
+ it('reports a folder visit once, however it starts, and a space only when it changes', async () => {
+ const logic = analyticsListLogic()
+ logic.mount()
+ router.actions.push(urls.analyticsList({ folder: 'Growth' }))
+ await expectLogic(logic).toFinishAllListeners()
+ router.actions.push(urls.analyticsList({ folder: 'Growth' }))
+ await expectLogic(logic).toFinishAllListeners()
+
+ const events = capture.mock.calls
+ .filter(([name]) => name !== '$pageview')
+ .map(([name, properties]) => [name, properties?.mode ?? properties?.nested])
+ expect(events).toEqual([
+ ['views list loaded', 'folder'],
+ ['analytics collection opened', false],
+ ['views list loaded', 'folder'],
+ ])
+ })
+})
diff --git a/frontend/src/scenes/analytics/analyticsListLogic.ts b/frontend/src/scenes/analytics/analyticsListLogic.ts
new file mode 100644
index 000000000000..ee705866e739
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsListLogic.ts
@@ -0,0 +1,835 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { actionToUrl, router, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
+
+import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { teamLogic } from 'scenes/teamLogic'
+import { AnalyticsListUrlParams, urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { isPathUnder, joinPath, splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+import { todayAnalyticsLogic } from '~/layout/today/todayAnalyticsLogic'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+import type { UserBasicType, UserType } from '~/types'
+
+import {
+ ANALYTICS_FEED_PAGE_SIZE,
+ AnalyticsFeed,
+ AnalyticsFeedQuery,
+ AnalyticsSourceState,
+ analyticsFeedTypes,
+ analyticsSourceKey,
+} from './analyticsFeed'
+import { analyticsFeedLogic, selectAnalyticsFeed } from './analyticsFeedLogic'
+import { analyticsShareLogic } from './analyticsShareLogic'
+import {
+ ANALYTICS_FILE_SYSTEM_TYPES,
+ AnalyticsItem,
+ AnalyticsTypeFilter,
+ fileSystemBaseType,
+ fileSystemEntryName,
+ fileSystemEntryToAnalytics,
+ isAnalyticsType,
+} from './analyticsUtils'
+
+export const ANALYTICS_PREFETCH_COUNT = ANALYTICS_FEED_PAGE_SIZE
+// A folder lists its direct children in one request. Deeper folders are opened by drilling in.
+const FOLDER_PAGE_SIZE = 100
+
+export interface AnalyticsListFilters {
+ type: AnalyticsTypeFilter
+ search: string
+ /** User uuids; empty means anyone. */
+ createdBy: string[]
+ /** A file system folder path to browse, '' for the project root, or null for the whole project. */
+ folder: string | null
+ tags: string[]
+}
+
+export const DEFAULT_ANALYTICS_LIST_FILTERS: AnalyticsListFilters = {
+ type: 'all',
+ search: '',
+ createdBy: [],
+ folder: null,
+ tags: [],
+}
+
+export type AnalyticsListMode = 'feed' | 'folder'
+/** `all` lists what the project shares; `mine` lists everything the person created, shared or not. */
+export type AnalyticsListScope = 'all' | 'mine'
+
+export interface FolderContents {
+ /** The folder these rows belong to, so a failed or slow load never shows another folder's rows. */
+ folder: string
+ hasMore: boolean
+ entries: FileSystemEntry[]
+ users: UserBasicType[]
+}
+
+export interface FolderRow {
+ path: string
+ name: string
+ entry?: FileSystemEntry
+ createdAt?: string | null
+ createdBy?: AnalyticsItem['createdBy']
+}
+
+export type AnalyticsListState = 'loading' | 'error' | 'empty' | 'no-matches' | 'ready'
+
+function stringList(value: unknown): string[] {
+ if (typeof value === 'string') {
+ return value ? [value] : []
+ }
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
+}
+
+export function analyticsListFiltersFromUrl(params: Record<string, any>): AnalyticsListFilters {
+ const type = typeof params.type === 'string' && isAnalyticsType(params.type) ? params.type : 'all'
+ const tags = Array.isArray(params.tags)
+ ? params.tags.filter((tag: unknown): tag is string => typeof tag === 'string')
+ : []
+ return {
+ type,
+ search: typeof params.search === 'string' ? params.search : '',
+ createdBy: stringList(params.createdBy),
+ folder: typeof params.folder === 'string' ? params.folder : null,
+ tags,
+ }
+}
+
+export function analyticsListUrlParams(filters: AnalyticsListFilters): AnalyticsListUrlParams {
+ return {
+ type: filters.type === 'all' ? undefined : filters.type,
+ search: filters.search.trim() || undefined,
+ createdBy: filters.createdBy.length ? filters.createdBy : undefined,
+ folder: filters.folder ?? undefined,
+ tags: filters.tags.length ? filters.tags : undefined,
+ }
+}
+
+export function analyticsListFiltersActive(filters: AnalyticsListFilters): boolean {
+ return filters.type !== 'all' || !!filters.search.trim() || filters.createdBy.length > 0 || filters.tags.length > 0
+}
+
+/** Narrows rows the server did not filter: folder contents come back whole. */
+export function filterAnalytics(items: AnalyticsItem[], filters: AnalyticsListFilters): AnalyticsItem[] {
+ const needle = filters.search.trim().toLowerCase()
+ const createdBy = filters.createdBy
+ return items.filter(
+ (item) =>
+ filters.tags.every((tag) => item.tags.includes(tag)) &&
+ (filters.type === 'all' || item.type === filters.type) &&
+ (!needle || item.name.toLowerCase().includes(needle)) &&
+ (!createdBy.length || (!!item.createdBy && createdBy.includes(item.createdBy.uuid)))
+ )
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsListLogicValues {
+ sources: Record<string, AnalyticsSourceState> // analyticsFeedLogic
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentTeamId: number | null // teamLogic
+ user: UserType | null // userLogic
+ creators: string[]
+ currentFeed: AnalyticsFeed
+ failedTypes: AnalyticsFeed['failedTypes']
+ feed: AnalyticsFeed
+ feedQuery: AnalyticsFeedQuery
+ feedSearch: string
+ feedStale: boolean
+ filters: AnalyticsListFilters
+ filtersActive: boolean
+ folderBreadcrumbs: FolderRow[]
+ folderContents: FolderContents | null
+ folderContentsLoading: boolean
+ folderFailed: boolean
+ hasMore: boolean
+ items: AnalyticsItem[]
+ listState: AnalyticsListState
+ loadedCount: number
+ loading: boolean
+ mode: AnalyticsListMode
+ scope: AnalyticsListScope
+ searchInput: string
+ shownQuery: AnalyticsFeedQuery | null
+ subfolders: FolderRow[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsListLogicActions {
+ ensureFeed: (
+ query: AnalyticsFeedQuery,
+ count: number
+ ) => {
+ count: number
+ query: AnalyticsFeedQuery
+ } // analyticsFeedLogic
+ refreshFeed: (query: AnalyticsFeedQuery) => {
+ query: AnalyticsFeedQuery
+ } // analyticsFeedLogic
+ sourceRefreshed: (
+ key: string,
+ generation: number,
+ page: null | import('./analyticsFeed').AnalyticsSourcePage
+ ) => {
+ generation: number
+ key: string
+ page: null | import('./analyticsFeed').AnalyticsSourcePage
+ } // analyticsFeedLogic
+ shareToSpaceDone: () => {
+ value: true
+ } // analyticsShareLogic
+ deleteSavedItem: (savedItem: FileSystemEntry) => {
+ savedItem: FileSystemEntry
+ } // projectTreeDataLogic
+ movesSettled: (moved: import('~/layout/panel-layout/ProjectTree/projectTreeDataLogic').MovedItem[]) => {
+ moved: import('~/layout/panel-layout/ProjectTree/projectTreeDataLogic').MovedItem[]
+ } // projectTreeDataLogic
+ folderCreated: () => {
+ value: true
+ } // todayAnalyticsLogic
+ clearFilters: () => {
+ value: true
+ }
+ loadFolderContents: (_: void) => void
+ loadFolderContentsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadFolderContentsSuccess: (
+ folderContents: {
+ entries: FileSystemEntry[]
+ folder: string
+ hasMore: boolean
+ users: UserBasicType[]
+ } | null,
+ payload?: void
+ ) => {
+ folderContents: {
+ entries: FileSystemEntry[]
+ folder: string
+ hasMore: boolean
+ users: UserBasicType[]
+ } | null
+ payload?: void
+ }
+ loadList: () => {
+ value: true
+ }
+ loadMore: () => {
+ value: true
+ }
+ loadMoreFolderContents: (_: void) => void
+ loadMoreFolderContentsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMoreFolderContentsSuccess: (
+ folderContents: FolderContents | null,
+ payload?: void
+ ) => {
+ folderContents: FolderContents | null
+ payload?: void
+ }
+ setFeedSearch: (search: string) => {
+ search: string
+ }
+ setFilters: (filters: Partial<AnalyticsListFilters>) => {
+ filters: Partial<AnalyticsListFilters>
+ }
+ setFiltersFromUrl: (filters: AnalyticsListFilters) => {
+ filters: AnalyticsListFilters
+ }
+ setScope: (scope: AnalyticsListScope) => {
+ scope: AnalyticsListScope
+ }
+ setSearchInput: (search: string) => {
+ search: string
+ }
+ setShownQuery: (query: AnalyticsFeedQuery) => {
+ query: AnalyticsFeedQuery
+ }
+ storeFilters: (filters: AnalyticsListFilters) => {
+ filters: AnalyticsListFilters
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsListLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ mode: (filters: AnalyticsListFilters) => AnalyticsListMode
+ filtersActive: (filters: AnalyticsListFilters) => boolean
+ creators: (filters: AnalyticsListFilters, user: UserType | null, scope: AnalyticsListScope) => string[]
+ feedQuery: (filters: AnalyticsListFilters, feedSearch: string, creators: string[]) => AnalyticsFeedQuery
+ currentFeed: (
+ sources: Record<string, AnalyticsSourceState>,
+ currentTeamId: number | null,
+ feedQuery: AnalyticsFeedQuery
+ ) => AnalyticsFeed
+ feed: (
+ currentFeed: AnalyticsFeed,
+ sources: Record<string, AnalyticsSourceState>,
+ currentTeamId: number | null,
+ shownQuery: AnalyticsFeedQuery | null
+ ) => AnalyticsFeed
+ feedStale: (currentFeed: AnalyticsFeed, feed: AnalyticsFeed) => boolean
+ items: (
+ mode: AnalyticsListMode,
+ feed: AnalyticsFeed,
+ folderContents: FolderContents | null,
+ filters: AnalyticsListFilters
+ ) => AnalyticsItem[]
+ subfolders: (
+ mode: AnalyticsListMode,
+ folderContents: FolderContents | null,
+ filters: AnalyticsListFilters
+ ) => FolderRow[]
+ folderBreadcrumbs: (filters: AnalyticsListFilters) => FolderRow[]
+ loading: (mode: AnalyticsListMode, feed: AnalyticsFeed, folderContentsLoading: boolean) => boolean
+ loadedCount: (
+ mode: AnalyticsListMode,
+ sources: Record<string, AnalyticsSourceState>,
+ feedQuery: AnalyticsFeedQuery,
+ currentTeamId: number | null,
+ folderContents: FolderContents | null
+ ) => number
+ hasMore: (
+ mode: AnalyticsListMode,
+ feed: AnalyticsFeed,
+ folderContents: FolderContents | null,
+ filters: AnalyticsListFilters
+ ) => boolean
+ failedTypes: (mode: AnalyticsListMode, feed: AnalyticsFeed) => AnalyticsFeed['failedTypes']
+ listState: (
+ mode: AnalyticsListMode,
+ feed: AnalyticsFeed,
+ folderContents: FolderContents | null,
+ folderFailed: boolean,
+ items: AnalyticsItem[],
+ subfolders: FolderRow[],
+ filtersActive: boolean
+ ) => AnalyticsListState
+ }
+}
+
+export type analyticsListLogicType = MakeLogicType<
+ analyticsListLogicValues,
+ analyticsListLogicActions,
+ Record<string, any>,
+ analyticsListLogicMeta
+>
+
+export const analyticsListLogic = kea<analyticsListLogicType>([
+ path(['scenes', 'analytics', 'analyticsListLogic']),
+ connect(() => ({
+ values: [
+ featureFlagLogic,
+ ['featureFlags'],
+ teamLogic,
+ ['currentTeamId'],
+ userLogic,
+ ['user'],
+ analyticsFeedLogic,
+ ['sources'],
+ ],
+ actions: [
+ analyticsFeedLogic,
+ ['ensureFeed', 'refreshFeed', 'sourceRefreshed'],
+ analyticsShareLogic,
+ ['shareToSpaceDone'],
+ todayAnalyticsLogic,
+ ['folderCreated'],
+ projectTreeDataLogic,
+ ['movesSettled', 'deleteSavedItem'],
+ ],
+ })),
+ actions({
+ setScope: (scope: AnalyticsListScope) => ({ scope }),
+ setFilters: (filters: Partial<AnalyticsListFilters>) => ({ filters }),
+ setFiltersFromUrl: (filters: AnalyticsListFilters) => ({ filters }),
+ /** Remembers URL filters without reading anything, for a visit the flag does not render yet. */
+ storeFilters: (filters: AnalyticsListFilters) => ({ filters }),
+ clearFilters: true,
+ setSearchInput: (search: string) => ({ search }),
+ setFeedSearch: (search: string) => ({ search }),
+ setShownQuery: (query: AnalyticsFeedQuery) => ({ query }),
+ loadList: true,
+ loadMore: true,
+ }),
+ loaders(({ values }) => ({
+ folderContents: [
+ null as FolderContents | null,
+ {
+ loadFolderContents: async (_: void, breakpoint) => {
+ const folder = values.filters.folder
+ if (folder === null) {
+ return null
+ }
+ const response = await api.fileSystem.list({
+ parent: folder,
+ depth: splitPath(folder).length + 1,
+ search: values.filters.search.trim() || undefined,
+ limit: FOLDER_PAGE_SIZE,
+ })
+ breakpoint()
+ return {
+ folder,
+ entries: response.results,
+ users: response.users,
+ hasMore: !!response.next,
+ }
+ },
+ loadMoreFolderContents: async (_: void, breakpoint) => {
+ const current = values.folderContents
+ if (!current || !current.hasMore || current.folder !== values.filters.folder) {
+ return current
+ }
+ const response = await api.fileSystem.list({
+ parent: current.folder,
+ depth: splitPath(current.folder).length + 1,
+ search: values.filters.search.trim() || undefined,
+ limit: FOLDER_PAGE_SIZE,
+ offset: current.entries.length,
+ })
+ breakpoint()
+ return {
+ ...current,
+ entries: [...current.entries, ...response.results],
+ users: [...current.users, ...response.users],
+ hasMore: !!response.next,
+ }
+ },
+ },
+ ],
+ })),
+ reducers({
+ scope: ['all' as AnalyticsListScope, { setScope: (_, { scope }) => scope }],
+ filters: [
+ DEFAULT_ANALYTICS_LIST_FILTERS,
+ {
+ setFilters: (state, { filters }) => ({ ...state, ...filters }),
+ setFiltersFromUrl: (_, { filters }) => filters,
+ storeFilters: (_, { filters }) => filters,
+ // The folder is where the person is, not a narrowing, so clearing keeps it.
+ clearFilters: (state) => ({ ...DEFAULT_ANALYTICS_LIST_FILTERS, folder: state.folder }),
+ },
+ ],
+ // What the person has typed. The filters take it after a pause, so each keystroke is not a request.
+ searchInput: [
+ '',
+ {
+ setSearchInput: (_, { search }) => search,
+ setFiltersFromUrl: (_, { filters }) => filters.search,
+ storeFilters: (_, { filters }) => filters.search,
+ clearFilters: () => '',
+ },
+ ],
+ feedSearch: ['', { setFeedSearch: (_, { search }) => search }],
+ shownQuery: [null as AnalyticsFeedQuery | null, { setShownQuery: (_, { query }) => query }],
+ folderFailed: [
+ false,
+ {
+ loadFolderContents: () => false,
+ loadFolderContentsFailure: () => true,
+ },
+ ],
+ }),
+ selectors({
+ mode: [
+ (s) => [s.filters],
+ (filters: AnalyticsListFilters): AnalyticsListMode => (filters.folder !== null ? 'folder' : 'feed'),
+ ],
+ filtersActive: [
+ (s) => [s.filters],
+ (filters: AnalyticsListFilters): boolean => analyticsListFiltersActive(filters),
+ ],
+ // My work narrows to the person; View all narrows to whoever they picked.
+ creators: [
+ (s) => [s.filters, s.user, s.scope],
+ (filters: AnalyticsListFilters, user: UserType | null, scope: AnalyticsListScope): string[] =>
+ scope === 'mine' ? (user?.uuid ? [user.uuid] : []) : filters.createdBy,
+ ],
+ feedQuery: [
+ (s) => [s.filters, s.feedSearch, s.creators],
+ (filters: AnalyticsListFilters, feedSearch: string, creators: string[]): AnalyticsFeedQuery => ({
+ type: filters.type,
+ search: feedSearch.trim(),
+ createdBy: creators,
+ tags: filters.tags,
+ }),
+ ],
+ currentFeed: [
+ (s) => [s.sources, s.currentTeamId, s.feedQuery],
+ (
+ sources: Record<string, AnalyticsSourceState>,
+ currentTeamId: number | null,
+ feedQuery: AnalyticsFeedQuery
+ ): AnalyticsFeed => selectAnalyticsFeed(sources, currentTeamId, feedQuery),
+ ],
+ // While a new query loads, the last loaded list stays on screen, dimmed, so the page does not blink.
+ feed: [
+ (s) => [s.currentFeed, s.sources, s.currentTeamId, s.shownQuery],
+ (
+ currentFeed: AnalyticsFeed,
+ sources: Record<string, AnalyticsSourceState>,
+ currentTeamId: number | null,
+ shownQuery: AnalyticsFeedQuery | null
+ ): AnalyticsFeed => {
+ if (currentFeed.initialized || !shownQuery) {
+ return currentFeed
+ }
+ const shownFeed = selectAnalyticsFeed(sources, currentTeamId, shownQuery)
+ return shownFeed.initialized ? { ...shownFeed, loading: true, hasMore: false } : currentFeed
+ },
+ ],
+ feedStale: [
+ (s) => [s.currentFeed, s.feed],
+ (currentFeed: AnalyticsFeed, feed: AnalyticsFeed): boolean => !currentFeed.initialized && feed.initialized,
+ ],
+ items: [
+ (s) => [s.mode, s.feed, s.folderContents, s.filters],
+ (
+ mode: AnalyticsListMode,
+ feed: AnalyticsFeed,
+ folderContents: FolderContents | null,
+ filters: AnalyticsListFilters
+ ): AnalyticsItem[] => {
+ if (mode === 'feed') {
+ return feed.items
+ }
+ const entries = folderContents?.folder === filters.folder ? folderContents.entries : []
+ const items = entries.flatMap((entry) => {
+ const item = ANALYTICS_FILE_SYSTEM_TYPES.has(fileSystemBaseType(entry.type))
+ ? fileSystemEntryToAnalytics(entry, folderContents?.users ?? [])
+ : null
+ return item ? [item] : []
+ })
+ return filterAnalytics(items, filters)
+ },
+ ],
+ subfolders: [
+ (s) => [s.mode, s.folderContents, s.filters],
+ (
+ mode: AnalyticsListMode,
+ folderContents: FolderContents | null,
+ filters: AnalyticsListFilters
+ ): FolderRow[] => {
+ if (mode !== 'folder' || !folderContents || folderContents.folder !== filters.folder) {
+ return []
+ }
+ // Folders carry no tags, so a tag filter leaves them out.
+ if (filters.tags.length) {
+ return []
+ }
+ const needle = filters.search.trim().toLowerCase()
+ return folderContents.entries
+ .filter((entry) => entry.type === 'folder')
+ .map((entry) => {
+ const creator = folderContents.users.find((user) => user.id === entry.meta?.created_by)
+ return {
+ path: entry.path,
+ name: fileSystemEntryName(entry),
+ entry,
+ createdAt: entry.created_at ?? null,
+ createdBy: creator
+ ? {
+ uuid: creator.uuid,
+ first_name: creator.first_name,
+ last_name: creator.last_name,
+ email: creator.email,
+ }
+ : null,
+ }
+ })
+ .filter((folder) => !needle || folder.name.toLowerCase().includes(needle))
+ .sort((first, second) => first.name.localeCompare(second.name))
+ },
+ ],
+ folderBreadcrumbs: [
+ (s) => [s.filters],
+ (filters: AnalyticsListFilters): FolderRow[] => {
+ if (filters.folder === null) {
+ return []
+ }
+ const segments = splitPath(filters.folder)
+ return segments.map((segment, index) => ({
+ name: segment,
+ path: joinPath(segments.slice(0, index + 1)),
+ }))
+ },
+ ],
+ loading: [
+ (s) => [s.mode, s.feed, s.folderContentsLoading],
+ (mode: AnalyticsListMode, feed: AnalyticsFeed, folderContentsLoading: boolean): boolean =>
+ mode === 'feed' ? feed.loading : folderContentsLoading,
+ ],
+ // Rows fetched so far, before the client-side filters, so the scroll sentinel re-checks after every page
+ // even when a page added nothing visible.
+ loadedCount: [
+ (s) => [s.mode, s.sources, s.feedQuery, s.currentTeamId, s.folderContents],
+ (
+ mode: AnalyticsListMode,
+ sources: Record<string, AnalyticsSourceState>,
+ feedQuery: AnalyticsFeedQuery,
+ currentTeamId: number | null,
+ folderContents: FolderContents | null
+ ): number =>
+ mode === 'folder'
+ ? (folderContents?.entries.length ?? 0)
+ : analyticsFeedTypes(feedQuery).reduce(
+ (sum, type) =>
+ sum + (sources[analyticsSourceKey(String(currentTeamId), feedQuery, type)]?.offset ?? 0),
+ 0
+ ),
+ ],
+ hasMore: [
+ (s) => [s.mode, s.feed, s.folderContents, s.filters],
+ (
+ mode: AnalyticsListMode,
+ feed: AnalyticsFeed,
+ folderContents: FolderContents | null,
+ filters: AnalyticsListFilters
+ ): boolean =>
+ mode === 'feed'
+ ? feed.hasMore
+ : !!folderContents && folderContents.folder === filters.folder && folderContents.hasMore,
+ ],
+ failedTypes: [
+ (s) => [s.mode, s.feed],
+ (mode: AnalyticsListMode, feed: AnalyticsFeed): AnalyticsFeed['failedTypes'] =>
+ mode === 'feed' ? feed.failedTypes : [],
+ ],
+ listState: [
+ (s) => [s.mode, s.feed, s.folderContents, s.folderFailed, s.items, s.subfolders, s.filtersActive],
+ (
+ mode: AnalyticsListMode,
+ feed: AnalyticsFeed,
+ folderContents: FolderContents | null,
+ folderFailed: boolean,
+ items: AnalyticsItem[],
+ subfolders: FolderRow[],
+ filtersActive: boolean
+ ): AnalyticsListState => {
+ const resolved = mode === 'feed' ? feed.initialized : folderContents !== null
+ const failed = mode === 'feed' ? feed.loadFailed : folderFailed
+ if (failed && !items.length) {
+ return 'error'
+ }
+ if (!resolved) {
+ return 'loading'
+ }
+ if (items.length || subfolders.length) {
+ return 'ready'
+ }
+ // Pages can still hold rows a client-side filter left out, so an empty list is not final yet.
+ if (mode === 'feed' && feed.hasMore) {
+ return 'loading'
+ }
+ return filtersActive ? 'no-matches' : 'empty'
+ },
+ ],
+ }),
+ listeners(({ actions, values, cache }) => {
+ // Once per visit, however many pages the visit reads.
+ const reportListLoaded = (viewCount: number, hasMore: boolean): void => {
+ if (cache.visitStartedAt === undefined) {
+ return
+ }
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('views list loaded', {
+ duration_ms: Math.round(performance.now() - cache.visitStartedAt),
+ cached: cache.visitCached,
+ view_count: viewCount,
+ has_more: hasMore,
+ mode: values.mode,
+ })
+ cache.visitStartedAt = undefined
+ }
+ const syncShownQuery = (): void => {
+ if (values.currentFeed.initialized) {
+ if (values.shownQuery !== values.feedQuery) {
+ actions.setShownQuery(values.feedQuery)
+ }
+ reportListLoaded(values.currentFeed.items.length, values.currentFeed.hasMore)
+ }
+ }
+ const loadCurrentMode = (): void => {
+ if (values.mode === 'feed') {
+ actions.ensureFeed(values.feedQuery, ANALYTICS_PREFETCH_COUNT)
+ syncShownQuery()
+ } else {
+ actions.loadFolderContents()
+ }
+ }
+ return {
+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
+ // Flags can arrive after urlToAction ran, so a visit that skipped the load must load now.
+ if (
+ values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] &&
+ cache.visitStartedAt === undefined &&
+ !values.loading &&
+ [urls.analyticsList(), urls.analyticsMine()].includes(
+ removeProjectIdIfPresent(router.values.location.pathname)
+ )
+ ) {
+ actions.loadList()
+ }
+ },
+ loadList: () => {
+ cache.visitStartedAt = performance.now()
+ cache.visitCached = values.mode === 'feed' ? values.currentFeed.initialized : !!values.folderContents
+ if (values.mode === 'feed') {
+ actions.refreshFeed(values.feedQuery)
+ syncShownQuery()
+ } else {
+ actions.loadFolderContents()
+ }
+ },
+ loadMore: () => {
+ if (!values.hasMore) {
+ return
+ }
+ if (values.mode === 'folder') {
+ actions.loadMoreFolderContents()
+ } else {
+ actions.ensureFeed(values.feedQuery, values.feed.items.length + ANALYTICS_PREFETCH_COUNT)
+ }
+ },
+ setSearchInput: async ({ search }, breakpoint) => {
+ if (search.trim() !== values.filters.search.trim()) {
+ await breakpoint(search.trim() ? 200 : 0)
+ }
+ actions.setFilters({ search })
+ },
+ setFilters: ({ filters }) => {
+ if (filters.search !== undefined) {
+ actions.setFeedSearch(filters.search)
+ }
+ const changed = Object.keys(filters).filter((key) => key !== 'search')
+ if (changed.length) {
+ // pinned: analytics event name and `type` property. Renaming them breaks dashboards.
+ posthog.capture('views list filtered', {
+ type: values.filters.type,
+ changed,
+ created_by: !values.filters.createdBy.length
+ ? 'anyone'
+ : values.user?.uuid && values.filters.createdBy.includes(values.user.uuid)
+ ? 'me'
+ : 'other',
+ folder: values.filters.folder !== null,
+ tag_count: values.filters.tags.length,
+ })
+ }
+ loadCurrentMode()
+ },
+ setFiltersFromUrl: () => {
+ actions.setFeedSearch(values.filters.search)
+ loadCurrentMode()
+ },
+ clearFilters: () => {
+ actions.setFeedSearch('')
+ loadCurrentMode()
+ },
+ sourceRefreshed: () => {
+ syncShownQuery()
+ // Unfiled rows stay hidden, so a page can add nothing visible; keep reading until the list fills.
+ if (values.mode === 'feed' && values.hasMore && values.items.length < ANALYTICS_PREFETCH_COUNT) {
+ actions.loadMore()
+ }
+ },
+ loadFolderContentsSuccess: ({ folderContents }) => {
+ if (!folderContents) {
+ return
+ }
+ reportListLoaded(folderContents.entries.length, folderContents.hasMore)
+ if (cache.openedFolder !== folderContents.folder) {
+ cache.openedFolder = folderContents.folder
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('analytics collection opened', {
+ nested: splitPath(folderContents.folder).length > 1,
+ item_count: folderContents.entries.length,
+ })
+ }
+ },
+ // A move or a new folder changes what this list holds, so it reads again.
+ shareToSpaceDone: () => actions.loadList(),
+ folderCreated: () => actions.loadList(),
+ // Drags and folder deletes go through the project tree, which reports here once they land.
+ movesSettled: () => actions.loadList(),
+ deleteSavedItem: ({ savedItem }) => {
+ const folder = values.filters.folder
+ if (savedItem.type === 'folder' && folder && isPathUnder(folder, savedItem.path)) {
+ const parent = splitPath(savedItem.path).slice(0, -1)
+ router.actions.push(
+ parent.length ? urls.analyticsList({ folder: joinPath(parent) }) : urls.analyticsSpaces()
+ )
+ return
+ }
+ actions.loadList()
+ },
+ }
+ }),
+ actionToUrl(({ values }) => {
+ const toUrl = (): string => {
+ return values.scope === 'mine'
+ ? urls.analyticsMine(analyticsListUrlParams(values.filters))
+ : urls.analyticsList(analyticsListUrlParams(values.filters))
+ }
+ return {
+ setFilters: toUrl,
+ clearFilters: toUrl,
+ }
+ }),
+ urlToAction(({ actions, values, cache }) => {
+ const listPaths = [urls.analyticsList(), urls.analyticsMine()]
+ // The router only writes a URL that differs from the current one, so our own write is the one location
+ // change that moves the URL within this scene while the scope and filters stay as they are.
+ const isOwnUrlWrite = (previous: { pathname: string; search: string }): boolean =>
+ listPaths.includes(removeProjectIdIfPresent(previous.pathname)) &&
+ previous.search !== router.values.location.search
+ const open = (
+ scope: AnalyticsListScope,
+ searchParams: Record<string, any>,
+ previous: { pathname: string; search: string }
+ ): void => {
+ const scopeChanged = values.scope !== scope
+ if (scopeChanged) {
+ actions.setScope(scope)
+ }
+ // The filters apply even before the flags arrive, so a cold open lands on the right list once they do.
+ const filters = analyticsListFiltersFromUrl(searchParams)
+ const filtersChanged = JSON.stringify(filters) !== JSON.stringify(values.filters)
+ // The scene renders nothing without the flag, so it must not load anything either.
+ if (!values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
+ if (filtersChanged) {
+ actions.storeFilters(filters)
+ }
+ return
+ }
+ if (filtersChanged) {
+ // A cold open with filters is a visit too, so it reports `views list loaded` like a plain one.
+ cache.visitStartedAt = performance.now()
+ cache.visitCached = false
+ actions.setFiltersFromUrl(filters)
+ } else if (scopeChanged || !isOwnUrlWrite(previous)) {
+ // A visit shows the last loaded rows at once and reads again, so a new item shows up on return.
+ actions.loadList()
+ }
+ }
+ return {
+ [urls.analyticsList()]: (_, searchParams, __, ___, previous) => open('all', searchParams, previous),
+ [urls.analyticsMine()]: (_, searchParams, __, ___, previous) => open('mine', searchParams, previous),
+ }
+ }),
+])
diff --git a/frontend/src/scenes/analytics/analyticsShareLogic.test.ts b/frontend/src/scenes/analytics/analyticsShareLogic.test.ts
new file mode 100644
index 000000000000..7ee9c3259e79
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsShareLogic.test.ts
@@ -0,0 +1,80 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { analyticsShareLogic } from './analyticsShareLogic'
+import { AnalyticsSpace } from './analyticsSpacesLogic'
+
+describe('analyticsShareLogic', () => {
+ let moves: string[]
+
+ beforeEach(() => {
+ moves = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/file_system_shortcut/': { results: [] },
+ '/api/projects/:team_id/canvases/:id/': ({ params }) => ({ id: params.id, channel: `ch-${params.id}` }),
+ '/api/projects/:team_id/task_channels/:id/': ({ params }) => ({
+ id: params.id,
+ channel_type: params.id === 'ch-c2' ? 'personal' : 'public',
+ }),
+ '/api/projects/:team_id/file_system/': ({ request }) => {
+ const params = new URL(request.url).searchParams
+ const ref = params.get('ref')
+ return ref
+ ? {
+ results: [{ id: `fs-${ref}`, type: 'insight/trends', ref, path: `Growth/${ref}` }],
+ next: null,
+ }
+ : { results: [], count: 0, next: null }
+ },
+ },
+ post: {
+ '/api/projects/:team_id/file_system/:id/move/': async ({ params, request }) => {
+ const body = (await request.json()) as { new_path: string }
+ moves.push(`${params.id} -> ${body.new_path}`)
+ return { id: params.id, path: body.new_path }
+ },
+ },
+ })
+ initKeaTests()
+ })
+
+ const FINANCE: AnalyticsSpace = {
+ path: 'Finance',
+ name: 'Finance',
+ counts: { canvas: 0, dashboard: 0, insight: 0, notebook: 0 },
+ total: 0,
+ lastAddedAt: null,
+ }
+
+ // The new path decides who sees the item, and a slash in a name would otherwise become a folder.
+ test.each([
+ ['insight', 'Weekly/active', FINANCE, 'fs-i1 -> Finance/Weekly\\/active'],
+ ['canvas', 'Run rate', FINANCE, 'fs-c1 -> Finance/Run rate'],
+ ['canvas', 'Run rate', null, 'fs-c1 -> Unfiled/Canvases/Run rate'],
+ ['dashboard', 'Board', null, 'fs-d1 -> Unfiled/Dashboards/Board'],
+ ] as const)('moves a %s named %p into %p', async (type, name, space, expected) => {
+ const logic = analyticsShareLogic()
+ logic.mount()
+ const ref = `${type[0]}1`
+ await expectLogic(logic, () => logic.actions.moveItem({ type, ref, name }, space)).toDispatchActions([
+ 'shareToSpaceDone',
+ ])
+
+ expect(moves).toEqual([expected])
+ expect(logic.values.itemSpaces[`${type}:${ref}`]).toBe(space?.name ?? null)
+ })
+
+ it('refuses to share a canvas from a private channel, since the space would not make it visible', async () => {
+ const logic = analyticsShareLogic()
+ logic.mount()
+ await expectLogic(logic, () =>
+ logic.actions.moveItem({ type: 'canvas', ref: 'c2', name: 'Private' }, FINANCE)
+ ).toDispatchActions(['shareToSpaceDone'])
+
+ expect(moves).toEqual([])
+ expect(logic.values.itemSpaces['canvas:c2']).toBeUndefined()
+ })
+})
diff --git a/frontend/src/scenes/analytics/analyticsShareLogic.ts b/frontend/src/scenes/analytics/analyticsShareLogic.ts
new file mode 100644
index 000000000000..5555ecc81aef
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsShareLogic.ts
@@ -0,0 +1,221 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { router } from 'kea-router'
+import posthog from 'posthog-js'
+
+import { toast } from '@posthog/quill'
+
+import api from 'lib/api'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { escapePath } from '~/layout/panel-layout/ProjectTree/utils'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+import { canvasesRetrieve } from 'products/canvas/frontend/generated/api'
+import { taskChannelsRetrieve } from 'products/tasks/frontend/generated/api'
+
+import { fileSystemTypeParams } from './analyticsFeed'
+import { AnalyticsSpace, analyticsSpacesLogic } from './analyticsSpacesLogic'
+import { ANALYTICS_TYPE_INFO, AnalyticsType, UNFILED_FOLDER, analyticsSpaceOfPath } from './analyticsUtils'
+
+export interface ShareToSpaceTarget {
+ type: AnalyticsType
+ ref: string
+ name: string
+}
+
+export function shareTargetKey(target: Pick<ShareToSpaceTarget, 'type' | 'ref'>): string {
+ return `${target.type}:${target.ref}`
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsShareLogicValues {
+ spaces: AnalyticsSpace[] // analyticsSpacesLogic
+ spacesLoading: boolean // analyticsSpacesLogic
+ currentSpace: string | null
+ entry: FileSystemEntry | null
+ entryLoading: boolean
+ itemSpaces: Record<string, string | null>
+ sharing: boolean
+ target: ShareToSpaceTarget | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsShareLogicActions {
+ loadSpaces: (_?: void | undefined) => void // analyticsSpacesLogic
+ closeShareToSpace: () => {
+ value: true
+ }
+ entryLoaded: (entry: FileSystemEntry | null) => {
+ entry: FileSystemEntry | null
+ }
+ itemSpaceLoaded: (
+ key: string,
+ space: string | null
+ ) => {
+ key: string
+ space: string | null
+ }
+ loadItemSpace: (target: ShareToSpaceTarget) => {
+ target: ShareToSpaceTarget
+ }
+ moveItem: (
+ target: ShareToSpaceTarget,
+ space: AnalyticsSpace | null
+ ) => {
+ space: AnalyticsSpace | null
+ target: ShareToSpaceTarget
+ }
+ openShareToSpace: (target: ShareToSpaceTarget) => {
+ target: ShareToSpaceTarget
+ }
+ shareToSpace: (space: AnalyticsSpace | null) => {
+ space: AnalyticsSpace | null
+ }
+ shareToSpaceDone: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsShareLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ currentSpace: (entry: FileSystemEntry | null) => string | null
+ }
+}
+
+export type analyticsShareLogicType = MakeLogicType<
+ analyticsShareLogicValues,
+ analyticsShareLogicActions,
+ Record<string, any>,
+ analyticsShareLogicMeta
+>
+
+// A canvas stays visible to its channel's members alone, whatever folder holds it, so a space can only
+// share one that sits in a public channel.
+async function assertCanvasShareable(ref: string): Promise<void> {
+ const projectId = String(teamLogic.values.currentTeamId)
+ const canvas = await canvasesRetrieve(projectId, ref)
+ const channel = await taskChannelsRetrieve(projectId, canvas.channel)
+ if (channel.channel_type !== 'public') {
+ throw new Error(
+ 'This canvas is in a private channel, so only its members can open it. Move it to a public channel first.'
+ )
+ }
+}
+
+async function findEntry(target: ShareToSpaceTarget): Promise<FileSystemEntry | null> {
+ const found = await api.fileSystem.list({ ref: target.ref, ...fileSystemTypeParams(target.type) })
+ return found.results[0] ?? null
+}
+
+/** Moves an item into a space, or back to personal, so the people in that space find it from the Analytics pane. */
+export const analyticsShareLogic = kea<analyticsShareLogicType>([
+ path(['scenes', 'analytics', 'analyticsShareLogic']),
+ connect(() => ({
+ values: [analyticsSpacesLogic, ['spaces', 'spacesLoading']],
+ actions: [analyticsSpacesLogic, ['loadSpaces']],
+ })),
+ actions({
+ openShareToSpace: (target: ShareToSpaceTarget) => ({ target }),
+ closeShareToSpace: true,
+ entryLoaded: (entry: FileSystemEntry | null) => ({ entry }),
+ /** Null moves the item out of every space, back to personal. */
+ shareToSpace: (space: AnalyticsSpace | null) => ({ space }),
+ shareToSpaceDone: true,
+ loadItemSpace: (target: ShareToSpaceTarget) => ({ target }),
+ /** Moves an item straight into a space, or to personal with null, with no dialog. */
+ moveItem: (target: ShareToSpaceTarget, space: AnalyticsSpace | null) => ({ target, space }),
+ itemSpaceLoaded: (key: string, space: string | null) => ({ key, space }),
+ }),
+ reducers({
+ target: [
+ null as ShareToSpaceTarget | null,
+ {
+ openShareToSpace: (_, { target }) => target,
+ closeShareToSpace: () => null,
+ shareToSpaceDone: () => null,
+ },
+ ],
+ entry: [
+ null as FileSystemEntry | null,
+ {
+ openShareToSpace: () => null,
+ entryLoaded: (_, { entry }) => entry,
+ closeShareToSpace: () => null,
+ },
+ ],
+ entryLoading: [
+ false,
+ { openShareToSpace: () => true, entryLoaded: () => false, closeShareToSpace: () => false },
+ ],
+ sharing: [false, { moveItem: () => true, shareToSpaceDone: () => false, closeShareToSpace: () => false }],
+ // The space each looked-up item sits in, so a page can label its action "Move" or "Share" before the dialog opens.
+ itemSpaces: [
+ {} as Record<string, string | null>,
+ {
+ itemSpaceLoaded: (state, { key, space }) => ({ ...state, [key]: space }),
+ },
+ ],
+ }),
+ selectors({
+ currentSpace: [
+ (s) => [s.entry],
+ (entry: FileSystemEntry | null): string | null => (entry ? analyticsSpaceOfPath(entry.path) : null),
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ openShareToSpace: async ({ target }, breakpoint) => {
+ // The collections and their counts change behind this dialog, so each open reads them again.
+ actions.loadSpaces()
+ const entry = await findEntry(target).catch(() => null)
+ breakpoint()
+ actions.entryLoaded(entry)
+ actions.itemSpaceLoaded(shareTargetKey(target), entry ? analyticsSpaceOfPath(entry.path) : null)
+ },
+ loadItemSpace: async ({ target }) => {
+ const entry = await findEntry(target).catch(() => null)
+ actions.itemSpaceLoaded(shareTargetKey(target), entry ? analyticsSpaceOfPath(entry.path) : null)
+ },
+ shareToSpace: ({ space }) => {
+ if (values.target) {
+ actions.moveItem(values.target, space)
+ }
+ },
+ moveItem: async ({ target, space }) => {
+ try {
+ const entry = values.target && values.entry ? values.entry : await findEntry(target)
+ if (!entry) {
+ throw new Error('This item has no row in the project file system yet.')
+ }
+ if (target.type === 'canvas' && space) {
+ await assertCanvasShareable(target.ref)
+ }
+ const wasShared = analyticsSpaceOfPath(entry.path) !== null
+ const folder = space ? space.path : `${UNFILED_FOLDER}/${ANALYTICS_TYPE_INFO[target.type].pluralLabel}`
+ await api.fileSystem.move(entry.id, `${folder}/${escapePath(target.name)}`)
+ toast.success({
+ title: space
+ ? wasShared
+ ? `Moved to ${space.name}`
+ : `Added to ${space.name}`
+ : 'Removed from its collection',
+ })
+ actions.itemSpaceLoaded(shareTargetKey(target), space ? space.name : null)
+ if (removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()) {
+ actions.loadSpaces()
+ }
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('analytics item moved', {
+ type: target.type,
+ from: wasShared ? 'space' : 'personal',
+ to: space ? 'space' : 'personal',
+ })
+ } catch (error) {
+ toast.error({ title: error instanceof Error ? error.message : 'Couldn’t move this item.' })
+ }
+ actions.shareToSpaceDone()
+ },
+ })),
+])
diff --git a/frontend/src/scenes/analytics/analyticsSpacesLogic.test.ts b/frontend/src/scenes/analytics/analyticsSpacesLogic.test.ts
new file mode 100644
index 000000000000..013ba5b1d1f1
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsSpacesLogic.test.ts
@@ -0,0 +1,99 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { analyticsSpacesLogic } from './analyticsSpacesLogic'
+
+// Ids stay slash-free so the mocked detail route matches them.
+const folder = (path: string): Record<string, unknown> => ({
+ id: `fs-${path.replace('/', '-')}`,
+ type: 'folder',
+ path,
+ meta: {},
+})
+const row = (type: string, ref: string, path: string): Record<string, unknown> => ({
+ id: `fs-${ref}`,
+ type,
+ ref,
+ path,
+ created_at: '2026-09-01T00:00:00Z',
+ meta: {},
+})
+
+describe('analyticsSpacesLogic', () => {
+ let requests: string[]
+
+ beforeEach(() => {
+ requests = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/file_system_shortcut/': {
+ results: [
+ { id: 'sc-home', type: 'folder', path: 'Ada', ref: 'Users/Ada' },
+ { id: 'sc-growth', type: 'folder', path: 'Growth', ref: 'Growth' },
+ ],
+ },
+ '/api/projects/:team_id/file_system/': ({ request }) => {
+ const params = new URL(request.url).searchParams
+ const parent = params.get('parent')
+ const type = params.get('type') ?? params.get('type__startswith')
+ if (params.get('depth') === '1' && type === 'folder') {
+ return {
+ results: ['Growth', 'Unfiled', 'Finance', 'Users'].map(folder),
+ count: 4,
+ next: null,
+ }
+ }
+ if (parent && type) {
+ // Per-type counts come from `count`, not from the one row the page holds.
+ const count = parent === 'Growth' ? ({ insight: 7, dashboard: 2 }[type] ?? 0) : 0
+ return { results: count ? [row(type, `${type}-x`, `${parent}/X`)] : [], count, next: null }
+ }
+ return { results: [], count: 0, next: null }
+ },
+ },
+ delete: {
+ '/api/projects/:team_id/file_system_shortcut/:id/': ({ params }) => {
+ requests.push(`delete shortcut ${params.id}`)
+ return [204, null]
+ },
+ },
+ })
+ initKeaTests()
+ })
+
+ it('lists spaces alphabetically with counts from the API, pinned ones first, leaving out Unfiled and Users', async () => {
+ const logic = analyticsSpacesLogic()
+ logic.mount()
+ await expectLogic(logic, () => {
+ logic.actions.loadShortcuts()
+ logic.actions.loadSpaces()
+ }).toDispatchActions(['loadShortcutsSuccess', 'loadSpacesSuccess'])
+
+ expect(logic.values.spaces.map((space) => [space.name, space.total])).toEqual([
+ ['Finance', 0],
+ ['Growth', 9],
+ ])
+ expect(logic.values.spaces[1].counts).toEqual({ canvas: 0, dashboard: 2, insight: 7, notebook: 0 })
+ // The shortcut's ref names the folder; a home folder shortcut is not a space.
+ expect(logic.values.pinnedSpaces.map((space) => space.path)).toEqual(['Growth'])
+ expect(logic.values.visibleSpaces.map((space) => space.name)).toEqual(['Growth', 'Finance'])
+ logic.actions.setSearch('fin')
+ expect(logic.values.visibleSpaces.map((space) => space.name)).toEqual(['Finance'])
+ })
+
+ it('drops the pin of a collection deleted through the project tree, and only for a top-level folder', async () => {
+ const logic = analyticsSpacesLogic()
+ logic.mount()
+ await expectLogic(logic, () => logic.actions.loadShortcuts()).toDispatchActions(['loadShortcutsSuccess'])
+
+ logic.actions.deleteSavedItem({ id: 'fs-Growth-Q4', type: 'folder', path: 'Growth/Q4' } as FileSystemEntry)
+ await expectLogic(logic, () =>
+ logic.actions.deleteSavedItem({ id: 'fs-Growth', type: 'folder', path: 'Growth' } as FileSystemEntry)
+ ).toDispatchActions(['loadShortcuts'])
+
+ expect(requests).toEqual(['delete shortcut sc-growth'])
+ })
+})
diff --git a/frontend/src/scenes/analytics/analyticsSpacesLogic.ts b/frontend/src/scenes/analytics/analyticsSpacesLogic.ts
new file mode 100644
index 000000000000..1749dc4078f4
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsSpacesLogic.ts
@@ -0,0 +1,334 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { router, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
+
+import { toast } from '@posthog/quill'
+
+import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { getCurrentTeamIdOrNone, getCurrentUserIdOrNone } from 'lib/utils/getAppContext'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { urls } from 'scenes/urls'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+import { todayAnalyticsLogic } from '~/layout/today/todayAnalyticsLogic'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+import { fileSystemTypeParams } from './analyticsFeed'
+import { ANALYTICS_TYPES, AnalyticsType, UNFILED_FOLDER, USERS_FOLDER, fileSystemEntryName } from './analyticsUtils'
+
+// Top-level folders come a page at a time; a project with more than this many is unlikely but handled.
+const SPACES_PAGE_SIZE = 200
+// Marks the shortcuts this page makes, so other folder shortcuts (such as a home folder) stay off the list.
+// kea-localstorage keys by logic path, and starred spaces belong to one person in one project. Without
+// both ids (OAuth mode can load this module early) nothing persists, so one account never sees another's.
+const SHORTCUTS_TEAM_ID = getCurrentTeamIdOrNone()
+const SHORTCUTS_USER_ID = getCurrentUserIdOrNone()
+const SHORTCUTS_PERSIST_OPTIONS =
+ SHORTCUTS_TEAM_ID && SHORTCUTS_USER_ID
+ ? { persist: true, prefix: `${SHORTCUTS_TEAM_ID}__${SHORTCUTS_USER_ID}__` }
+ : { persist: false }
+
+/** A space is a top-level folder that is not the unfiled area or someone's home folder. */
+export function isSpacePath(path: string): boolean {
+ const segments = splitPath(path)
+ return segments.length === 1 && !([UNFILED_FOLDER, USERS_FOLDER] as string[]).includes(segments[0])
+}
+
+/** A pinned space: its shortcut row, so the pin can be removed again. */
+export interface PinnedSpace {
+ shortcutId: NonNullable<FileSystemEntry['id']>
+ path: string
+ name: string
+}
+
+export interface AnalyticsSpace {
+ path: string
+ name: string
+ /** How many rows of each analytics type the space holds, from the API's own counts. */
+ counts: Record<AnalyticsType, number>
+ total: number
+ /** When something was last added, from the newest row. */
+ lastAddedAt: string | null
+}
+
+async function listAllTopLevelFolders(): Promise<FileSystemEntry[]> {
+ const folders: FileSystemEntry[] = []
+ for (let offset = 0; ; offset += SPACES_PAGE_SIZE) {
+ const page = await api.fileSystem.list({ depth: 1, type: 'folder', limit: SPACES_PAGE_SIZE, offset })
+ folders.push(...page.results)
+ if (!page.next || page.results.length === 0) {
+ return folders
+ }
+ }
+}
+
+/** One request per type reads the count and the newest row, so a big space costs four small calls. */
+export async function loadSpace(folder: FileSystemEntry): Promise<AnalyticsSpace> {
+ const pages = await Promise.all(
+ ANALYTICS_TYPES.map((info) =>
+ api.fileSystem.list({
+ parent: folder.path,
+ ...fileSystemTypeParams(info.type),
+ orderBy: '-created_at',
+ limit: 1,
+ })
+ )
+ )
+ const counts = Object.fromEntries(
+ ANALYTICS_TYPES.map((info, index) => [info.type, pages[index].count ?? pages[index].results.length])
+ ) as Record<AnalyticsType, number>
+ const lastAddedAt = pages
+ .map((page) => page.results[0]?.created_at ?? null)
+ .filter((value): value is string => !!value)
+ .sort()
+ .at(-1)
+ return {
+ path: folder.path,
+ name: fileSystemEntryName(folder),
+ counts,
+ total: Object.values(counts).reduce((sum, count) => sum + count, 0),
+ lastAddedAt: lastAddedAt ?? null,
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsSpacesLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ pinnedPaths: Set<string>
+ pinnedSpaces: PinnedSpace[]
+ pinning: string | null
+ search: string
+ shortcuts: FileSystemEntry[]
+ shortcutsLoading: boolean
+ spaces: AnalyticsSpace[]
+ spacesFailed: boolean
+ spacesLoading: boolean
+ visibleSpaces: AnalyticsSpace[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsSpacesLogicActions {
+ deleteSavedItem: (savedItem: FileSystemEntry) => {
+ savedItem: FileSystemEntry
+ } // projectTreeDataLogic
+ folderCreated: () => {
+ value: true
+ } // todayAnalyticsLogic
+ loadShortcuts: () => any
+ loadShortcutsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadShortcutsSuccess: (
+ shortcuts: FileSystemEntry[],
+ payload?: any
+ ) => {
+ shortcuts: FileSystemEntry[]
+ payload?: any
+ }
+ loadSpaces: (_: void) => void
+ loadSpacesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSpacesSuccess: (
+ spaces: AnalyticsSpace[],
+ payload?: void
+ ) => {
+ spaces: AnalyticsSpace[]
+ payload?: void
+ }
+ setSearch: (search: string) => {
+ search: string
+ }
+ togglePin: (space: Pick<AnalyticsSpace, 'name' | 'path'>) => {
+ space: Pick<AnalyticsSpace, 'name' | 'path'>
+ }
+ togglePinDone: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsSpacesLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ pinnedSpaces: (shortcuts: FileSystemEntry[]) => PinnedSpace[]
+ pinnedPaths: (pinnedSpaces: PinnedSpace[]) => Set<string>
+ visibleSpaces: (spaces: AnalyticsSpace[], pinnedPaths: Set<string>, search: string) => AnalyticsSpace[]
+ }
+}
+
+export type analyticsSpacesLogicType = MakeLogicType<
+ analyticsSpacesLogicValues,
+ analyticsSpacesLogicActions,
+ Record<string, any>,
+ analyticsSpacesLogicMeta
+>
+
+/** The project's spaces: its top-level folders, with what each one holds. */
+export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
+ path(['scenes', 'analytics', 'analyticsSpacesLogic']),
+ connect(() => ({
+ values: [featureFlagLogic, ['featureFlags']],
+ actions: [todayAnalyticsLogic, ['folderCreated'], projectTreeDataLogic, ['deleteSavedItem']],
+ })),
+ actions({
+ togglePin: (space: Pick<AnalyticsSpace, 'path' | 'name'>) => ({ space }),
+ togglePinDone: true,
+ setSearch: (search: string) => ({ search }),
+ }),
+ loaders(({ cache }) => ({
+ shortcuts: [
+ [] as FileSystemEntry[],
+ {
+ loadShortcuts: async () => (await api.fileSystemShortcuts.list()).results,
+ },
+ ],
+ spaces: [
+ [] as AnalyticsSpace[],
+ {
+ loadSpaces: async (_: void, breakpoint) => {
+ const folders = await listAllTopLevelFolders()
+ breakpoint()
+ const spaces = await Promise.all(
+ folders
+ .filter((folder) => ![UNFILED_FOLDER, USERS_FOLDER].includes(fileSystemEntryName(folder)))
+ .map(loadSpace)
+ )
+ breakpoint()
+ cache.loaded = true
+ return spaces.sort((first, second) => first.name.localeCompare(second.name))
+ },
+ },
+ ],
+ })),
+ reducers({
+ spacesFailed: [
+ false,
+ { loadSpaces: () => false, loadSpacesSuccess: () => false, loadSpacesFailure: () => true },
+ ],
+ // The last loaded shortcuts persist, so starred spaces show at once on the next visit and refresh in place.
+ shortcuts: [[] as FileSystemEntry[], SHORTCUTS_PERSIST_OPTIONS, {}],
+ // The path being pinned or unpinned, so its button shows progress and ignores a second click.
+ pinning: [null as string | null, { togglePin: (_, { space }) => space.path, togglePinDone: () => null }],
+ search: ['', { setSearch: (_, { search }) => search }],
+ }),
+ selectors({
+ // A starred space is a shortcut to its folder; the shortcut row carries the path.
+ pinnedSpaces: [
+ (s) => [s.shortcuts],
+ (shortcuts: FileSystemEntry[]): PinnedSpace[] =>
+ shortcuts.flatMap((shortcut) =>
+ // A shortcut's `path` is its display name; `ref` holds the folder it points at.
+ shortcut.type === 'folder' && shortcut.id && shortcut.ref && isSpacePath(shortcut.ref)
+ ? [
+ {
+ shortcutId: shortcut.id,
+ path: shortcut.ref,
+ name: fileSystemEntryName({ path: shortcut.ref }),
+ },
+ ]
+ : []
+ ),
+ ],
+ pinnedPaths: [
+ (s) => [s.pinnedSpaces],
+ (pinnedSpaces: PinnedSpace[]): Set<string> => new Set(pinnedSpaces.map((space) => space.path)),
+ ],
+ // Pinned spaces lead, then the rest alphabetically; a search narrows both by name.
+ visibleSpaces: [
+ (s) => [s.spaces, s.pinnedPaths, s.search],
+ (spaces: AnalyticsSpace[], pinnedPaths: Set<string>, search: string): AnalyticsSpace[] => {
+ const needle = search.trim().toLowerCase()
+ return spaces
+ .filter((space) => !needle || space.name.toLowerCase().includes(needle))
+ .sort((first, second) => {
+ const pinnedFirst = Number(pinnedPaths.has(second.path)) - Number(pinnedPaths.has(first.path))
+ return pinnedFirst || first.name.localeCompare(second.name)
+ })
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ togglePin: async ({ space }) => {
+ try {
+ const pinned = values.pinnedSpaces.find((candidate) => candidate.path === space.path)
+ if (pinned) {
+ await api.fileSystemShortcuts.delete(pinned.shortcutId)
+ toast.success({ title: `Unpinned ${space.name}` })
+ } else {
+ // A folder shortcut keeps its path as ref, so a rename moves the star with the folder.
+ await api.fileSystemShortcuts.create({ path: space.path, type: 'folder', ref: space.path })
+ toast.success({ title: `Pinned ${space.name} to the sidebar` })
+ }
+ actions.loadShortcuts()
+ } catch {
+ toast.error({ title: 'Couldn’t update the pin. Try again.' })
+ }
+ actions.togglePinDone()
+ },
+ })),
+ listeners(({ actions, values, cache }) => ({
+ // Flags can arrive after the mount, so a mount that skipped the load must load now.
+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
+ if (!values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] || cache.flagSeen) {
+ return
+ }
+ cache.flagSeen = true
+ actions.loadShortcuts()
+ if (removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()) {
+ actions.loadSpaces()
+ }
+ },
+ // A space made from the dialog shows up without a reload.
+ folderCreated: () => {
+ if (removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()) {
+ actions.loadSpaces()
+ }
+ },
+ // A collection is deleted like any folder, through the project tree. The server keeps its pin, so it goes here.
+ deleteSavedItem: async ({ savedItem }) => {
+ if (savedItem.type !== 'folder' || !isSpacePath(savedItem.path)) {
+ return
+ }
+ const pin = values.pinnedSpaces.find((candidate) => candidate.path === savedItem.path)
+ if (pin) {
+ await api.fileSystemShortcuts.delete(pin.shortcutId).catch(() => null)
+ }
+ // pinned: analytics event name. Renaming it breaks dashboards.
+ posthog.capture('analytics collection deleted')
+ actions.loadShortcuts()
+ if (removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()) {
+ actions.loadSpaces()
+ }
+ },
+ togglePinDone: () => {
+ // pinned: analytics event name and property. Renaming them breaks dashboards.
+ posthog.capture('analytics collection pinned', { pinned_count: values.pinnedSpaces.length })
+ },
+ })),
+ // The sidebar mounts this logic for the stars alone; counting every space is for the Spaces page.
+ urlToAction(({ actions, values }) => ({
+ [urls.analyticsSpaces()]: () => {
+ if (values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
+ actions.loadSpaces()
+ }
+ },
+ })),
+ afterMount(({ actions, values, cache }) => {
+ if (values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
+ cache.flagSeen = true
+ actions.loadShortcuts()
+ }
+ }),
+])
diff --git a/frontend/src/scenes/analytics/analyticsUtils.test.ts b/frontend/src/scenes/analytics/analyticsUtils.test.ts
new file mode 100644
index 000000000000..32e8aa6f94fd
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsUtils.test.ts
@@ -0,0 +1,57 @@
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'
+
+import { fileSystemEntryToAnalytics, newCanvasSpaceIdForPath } from './analyticsUtils'
+
+const canvas = (overrides: Partial<CanvasApi>): CanvasApi =>
+ ({
+ id: 'c',
+ name: 'Canvas',
+ kind: 'freeform',
+ channel: 'space-1',
+ updated_at: '2026-09-01T00:00:00Z',
+ ...overrides,
+ }) as CanvasApi
+
+const entry = (overrides: Partial<FileSystemEntry>): FileSystemEntry =>
+ ({
+ id: 'fs-1',
+ path: 'Unfiled/Dashboards/Revenue a\\/b',
+ type: 'dashboard',
+ ref: '12',
+ created_at: '2026-08-01T00:00:00Z',
+ meta: { created_by: 1 },
+ ...overrides,
+ }) as FileSystemEntry
+
+describe('analyticsUtils', () => {
+ it('reads an item from its file system row, resolving the creator and the escaped name', () => {
+ const users = [{ id: 1, uuid: 'u1', first_name: 'Ada', last_name: 'Lovelace', email: '[email protected]' }]
+ const analytics = fileSystemEntryToAnalytics(entry({}), users)
+ expect(analytics).toMatchObject({
+ type: 'dashboard',
+ id: '12',
+ name: 'Revenue a/b',
+ href: '/dashboard/12',
+ createdBy: { uuid: 'u1', first_name: 'Ada' },
+ })
+ })
+
+ test.each([
+ ['a non-analytics type', { type: 'feature_flag' }],
+ ['a folder', { type: 'folder', ref: undefined }],
+ ])('ignores %s in the file system', (_, overrides) => {
+ expect(fileSystemEntryToAnalytics(entry(overrides as Partial<FileSystemEntry>))).toBeNull()
+ })
+
+ test.each([
+ ['a space page', '/spaces/space-3', 'space-3'],
+ ['a canvas page', '/canvases/board', 'space-1'],
+ ['a different open canvas', '/canvases/other', null],
+ ['the start page', '/canvases/new', null],
+ ['a page with no space', '/analytics', null],
+ ])('defaults a new canvas from %s to the right space', (_, path, spaceId) => {
+ expect(newCanvasSpaceIdForPath(path, canvas({ id: 'board', channel: 'space-1' }))).toBe(spaceId)
+ })
+})
diff --git a/frontend/src/scenes/analytics/analyticsUtils.ts b/frontend/src/scenes/analytics/analyticsUtils.ts
new file mode 100644
index 000000000000..4369cb312d16
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsUtils.ts
@@ -0,0 +1,242 @@
+import { combineUrl } from 'kea-router'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { urls } from 'scenes/urls'
+
+import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+import { fileSystemTypes, getTreeItemsProducts } from '~/products'
+import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'
+import type { UserBasicType } from '~/types'
+
+import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'
+
+// pinned: these values are the `type` property of the `views new picked` and `views list filtered` events.
+export type AnalyticsType = 'canvas' | 'notebook' | 'dashboard' | 'insight'
+export type AnalyticsTypeFilter = AnalyticsType | 'all'
+
+export interface AnalyticsTypeInfo {
+ type: AnalyticsType
+ label: string
+ pluralLabel: string
+ description: string
+ /** The product colour for an icon that has to be told one, such as an icon stack. */
+ color: string
+}
+
+export const ANALYTICS_TYPES: AnalyticsTypeInfo[] = [
+ {
+ type: 'canvas',
+ label: 'Canvas',
+ pluralLabel: 'Canvases',
+ description: 'A fully customizable generative page for complete control',
+ color: 'var(--color-product-tasks-light)',
+ },
+ {
+ type: 'dashboard',
+ label: 'Dashboard',
+ pluralLabel: 'Dashboards',
+ description: 'A standardized grid with insights and widgets',
+ color: 'var(--color-product-dashboards-light)',
+ },
+ {
+ type: 'insight',
+ label: 'Insight',
+ pluralLabel: 'Insights',
+ description: 'A chart built on your PostHog data, like a trend or a funnel, for a one-off analysis',
+ color: 'var(--color-product-product-analytics-light)',
+ },
+ {
+ type: 'notebook',
+ label: 'Notebook',
+ pluralLabel: 'Notebooks',
+ description: 'An executable notebook for in-depth analyses and reports',
+ color: 'var(--color-product-notebooks-light)',
+ },
+]
+
+export const ANALYTICS_TYPE_INFO = Object.fromEntries(ANALYTICS_TYPES.map((info) => [info.type, info])) as Record<
+ AnalyticsType,
+ AnalyticsTypeInfo
+>
+
+/** The file system types that are analytics, so the project tree and recents can be narrowed to them. */
+export const ANALYTICS_FILE_SYSTEM_TYPES: ReadonlySet<string> = new Set<AnalyticsType>(
+ ANALYTICS_TYPES.map((info) => info.type)
+)
+
+export function isAnalyticsType(type: string): type is AnalyticsType {
+ return ANALYTICS_FILE_SYSTEM_TYPES.has(type)
+}
+
+/** The project tree icon type for each analytics type, which carries that product's colour. */
+
+export interface AnalyticsItem {
+ type: AnalyticsType
+ id: string
+ name: string
+ href: string
+ /** When the item last changed, or was last viewed or created when that is all the API knows. */
+ timestamp: string | null
+ createdAt: string | null
+ createdBy: Pick<UserBasicType, 'uuid' | 'first_name' | 'last_name' | 'email'> | null
+ tags: string[]
+ spaceId: string | null
+ spaceName: string | null
+ /** The file system row behind the item, which a drag hands to the project tree's move. */
+ entry?: FileSystemEntry
+}
+
+export const ANALYTICS_BACK_NAME = 'Analytics'
+
+/** The item's page, told where the person came from so its back control returns there rather than to the type's own list. */
+export function analyticsOpenHref(item: Pick<AnalyticsItem, 'href'>, backUrl: string): string {
+ return combineUrl(item.href, { backUrl, backName: ANALYTICS_BACK_NAME }).url
+}
+
+function stringTags(tags: unknown[] | undefined): string[] {
+ return (tags ?? []).filter((tag): tag is string => typeof tag === 'string')
+}
+
+/** The last segment of a file system path, with escaped slashes restored. */
+export function fileSystemEntryName(entry: Pick<FileSystemEntry, 'path'>): string {
+ const segments = entry.path.split(/(?<!\\)\//)
+ return (segments[segments.length - 1] || entry.path).replace(/\\\//g, '/')
+}
+
+/** The base type of a file system entry: `insight/trends` is an `insight`. */
+export function fileSystemBaseType(type: string | undefined): string {
+ return type?.split('/')[0] ?? ''
+}
+
+/**
+ * An analytics item from its file system row, for the folder tree and recents. The row knows the
+ * creator and the person's own last view, but no tags and no project-wide access time.
+ */
+/** The file system folder every product files new objects under until someone moves them. */
+export const UNFILED_FOLDER = 'Unfiled'
+
+/** The folder that holds every person's own home folder. Its contents are personal, not a team space. */
+export const USERS_FOLDER = 'Users'
+
+/** The space an entry sits in: its top-level folder, or null when it is still unfiled (personal). */
+export function analyticsSpaceOfPath(path: string): string | null {
+ const [top] = splitPath(path)
+ return top && top !== UNFILED_FOLDER && top !== USERS_FOLDER ? top : null
+}
+
+const SPACE_COLORS = [
+ 'var(--color-product-product-analytics-light)',
+ 'var(--color-product-dashboards-light)',
+ 'var(--color-product-notebooks-light)',
+ 'var(--color-product-feature-flags-light)',
+ 'var(--color-product-experiments-light)',
+ 'var(--color-product-surveys-light)',
+ 'var(--color-product-web-analytics-light)',
+ 'var(--color-product-session-replay-light)',
+]
+
+/** A stable colour for a space, from its name, so the same space looks the same everywhere. */
+export function analyticsSpaceColor(name: string): string {
+ let hash = 0
+ for (const char of name) {
+ hash = (hash * 31 + char.charCodeAt(0)) | 0
+ }
+ return SPACE_COLORS[Math.abs(hash) % SPACE_COLORS.length]
+}
+
+export function fileSystemEntryToAnalytics(
+ entry: FileSystemEntry,
+ users: Pick<UserBasicType, 'id' | 'uuid' | 'first_name' | 'last_name' | 'email'>[] = []
+): AnalyticsItem | null {
+ const type = fileSystemBaseType(entry.type)
+ if (!isAnalyticsType(type) || !entry.ref) {
+ return null
+ }
+ const definition = fileSystemTypes[type as keyof typeof fileSystemTypes]
+ const href = entry.href || definition?.href(entry.ref)
+ if (!href) {
+ return null
+ }
+ const createdById = entry.meta?.created_by
+ const creator = users.find((user) => user.id === createdById) ?? null
+ return {
+ type,
+ id: entry.ref,
+ name: fileSystemEntryName(entry),
+ href,
+ timestamp: entry.created_at ?? null,
+ createdAt: entry.created_at ?? null,
+ createdBy: creator
+ ? { uuid: creator.uuid, first_name: creator.first_name, last_name: creator.last_name, email: creator.email }
+ : null,
+ tags: stringTags(Array.isArray(entry.meta?.tags) ? entry.meta.tags : undefined),
+ spaceId: analyticsSpaceOfPath(entry.path),
+ spaceName: analyticsSpaceOfPath(entry.path),
+ entry,
+ }
+}
+
+// pinned: sidebar `iconType` values from the product manifests, in the order the sidebar lists them.
+export const FROM_POSTHOG_ICON_TYPES = ['web_analytics', 'marketing_analytics', 'mcp_analytics'] as const
+
+export interface FromPostHogItem {
+ key: string
+ label: string
+ href: string
+ item: FileSystemImport
+}
+
+export function isFromPostHogItem(item: Pick<FileSystemImport, 'iconType'>): boolean {
+ return (FROM_POSTHOG_ICON_TYPES as readonly string[]).includes(item.iconType ?? '')
+}
+
+export function fromPostHogProducts(): FromPostHogItem[] {
+ const products = getTreeItemsProducts()
+ // Product analytics has no page of its own in the manifest; its ready-made analysis is the home dashboard.
+ const productAnalytics = products.find((product) => product.type === 'insight' && product.href === urls.insights())
+ const home: FromPostHogItem[] = productAnalytics
+ ? [
+ {
+ key: 'product_analytics',
+ label: 'Product analytics',
+ href: urls.analyticsProductHome(),
+ item: {
+ ...productAnalytics,
+ iconType: 'product_analytics',
+ href: urls.analyticsProductHome(),
+ flag: FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB,
+ },
+ },
+ ]
+ : []
+ return [
+ ...home,
+ ...FROM_POSTHOG_ICON_TYPES.flatMap((iconType) => {
+ const item = products.find((product) => product.iconType === iconType)
+ return item?.href ? [{ key: iconType, label: fileSystemEntryName(item), href: item.href, item }] : []
+ }),
+ ]
+}
+
+export function fromPostHogItems(featureFlags: Record<string, unknown>): FromPostHogItem[] {
+ return fromPostHogProducts().filter(({ item }) => !item.flag || !!featureFlags[item.flag])
+}
+
+/**
+ * The space a new canvas defaults to from the page the person is on: the open space, or the open
+ * canvas's space. Null when the page names no space, so the start page falls back to the personal space.
+ */
+export function newCanvasSpaceIdForPath(
+ path: string,
+ openCanvas: Pick<CanvasApi, 'id' | 'channel'> | null
+): string | null {
+ const space = /^\/spaces\/([^/]+)/.exec(path)
+ if (space) {
+ return space[1]
+ }
+ const canvas = /^\/canvases\/([^/]+)$/.exec(path)
+ return canvas && openCanvas?.id === canvas[1] ? openCanvas.channel : null
+}
+
+/** Scopes the Analytics list's drag ids and drop targets apart from the project tree's own. */
+export const ANALYTICS_DRAG_SCOPE = 'analytics-list'
diff --git a/frontend/src/scenes/analytics/newAnalyticsLogic.ts b/frontend/src/scenes/analytics/newAnalyticsLogic.ts
new file mode 100644
index 000000000000..e77e3f91366a
--- /dev/null
+++ b/frontend/src/scenes/analytics/newAnalyticsLogic.ts
@@ -0,0 +1,115 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+import { router } from 'kea-router'
+import type { LocationChangedPayload } from 'kea-router/lib/types'
+import posthog from 'posthog-js'
+
+import { toast } from '@posthog/quill'
+
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
+import { urls } from 'scenes/urls'
+
+import { canvasSceneLogic } from 'products/canvas/frontend/scene/canvasSceneLogic'
+
+import { withBackLink } from './analyticsBackLink'
+import { AnalyticsType, newCanvasSpaceIdForPath } from './analyticsUtils'
+
+// pinned: analytics property values. Renaming them breaks dashboards.
+export type NewAnalyticsSource = 'menu' | 'sidebar' | 'home' | 'list'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface newAnalyticsLogicValues {
+ newInsightDialogOpen: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface newAnalyticsLogicActions {
+ locationChanged: ({
+ method,
+ pathname,
+ search,
+ searchParams,
+ hash,
+ hashParams,
+ initial,
+ url,
+ routerState,
+ }: LocationChangedPayload) => {
+ hash: string
+ hashParams: Record<string, any>
+ initial: boolean
+ method: 'POP' | 'PUSH' | 'REPLACE'
+ pathname: string
+ routerState: Record<string, any>
+ search: string
+ searchParams: Record<string, any>
+ url: string
+ } // router
+ pickNewAnalyticsType: (
+ type: AnalyticsType,
+ source: NewAnalyticsSource
+ ) => {
+ source: NewAnalyticsSource
+ type: AnalyticsType
+ }
+ setNewInsightDialogOpen: (open: boolean) => {
+ open: boolean
+ }
+}
+
+export type newAnalyticsLogicType = MakeLogicType<newAnalyticsLogicValues, newAnalyticsLogicActions>
+
+export const newAnalyticsLogic = kea<newAnalyticsLogicType>([
+ path(['scenes', 'analytics', 'newAnalyticsLogic']),
+ connect(() => ({ actions: [router, ['locationChanged']] })),
+ actions({
+ pickNewAnalyticsType: (type: AnalyticsType, source: NewAnalyticsSource) => ({ type, source }),
+ setNewInsightDialogOpen: (open: boolean) => ({ open }),
+ }),
+ reducers({
+ // Picking a type in the dialog navigates to the editor, which closes it.
+ newInsightDialogOpen: [
+ false,
+ {
+ setNewInsightDialogOpen: (_, { open }) => open,
+ locationChanged: () => false,
+ },
+ ],
+ }),
+ listeners(({ actions }) => ({
+ pickNewAnalyticsType: ({ type, source }) => {
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('views new picked', { type, source })
+ const pathname = removeProjectIdIfPresent(router.values.location.pathname)
+ // The Analytics pages host the pickers themselves, so creating there keeps the page in place.
+ const onAnalyticsPage = pathname === urls.analytics() || pathname.startsWith(`${urls.analytics()}/`)
+ if (type === 'canvas') {
+ const canvasId = /^\/canvases\/([^/]+)$/.exec(pathname)?.[1]
+ const canvas = canvasId ? canvasSceneLogic.findMounted({ id: canvasId })?.values.canvas : null
+ if (canvasId && canvasId !== 'new' && !canvas) {
+ toast.error({ title: 'Wait for the canvas to load, then try again.' })
+ return
+ }
+ const spaceId = newCanvasSpaceIdForPath(pathname, canvas ?? null)
+ router.actions.push(withBackLink(urls.canvasNew(spaceId)))
+ } else if (type === 'notebook') {
+ router.actions.push(withBackLink(urls.notebook('new')))
+ } else if (type === 'insight') {
+ if (onAnalyticsPage) {
+ actions.setNewInsightDialogOpen(true)
+ } else {
+ router.actions.push(urls.insightNew())
+ }
+ } else {
+ const dashboardModal = onAnalyticsPage ? newDashboardLogic.findMounted() : null
+ if (dashboardModal) {
+ dashboardModal.actions.showNewDashboardModal()
+ } else {
+ // The dashboards page opens its new-dashboard dialog from this hash. Some scenes already host
+ // that dialog, so a second host in the shell would open it twice on those pages.
+ router.actions.push(`${urls.dashboards()}#newDashboard=modal`)
+ }
+ }
+ },
+ })),
+])
diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.ts
index 8a540663f26b..41785cd2ebb6 100644
--- a/frontend/src/scenes/appScenes.ts
+++ b/frontend/src/scenes/appScenes.ts
@@ -79,8 +79,9 @@ export const appScenes: Record<Scene | string, () => any> = {
[Scene.ProjectCreateFirst]: () => import('./project/Create'),
[Scene.ProjectHomepage]: () => import('./project-homepage/ProjectHomepage'),
[Scene.Library]: () => import('./library/Library'),
- [Scene.Views]: () => import('./views/Views'),
- [Scene.ViewsNew]: () => import('./views/NewView'),
+ [Scene.AnalyticsList]: () => import('./analytics/AnalyticsList'),
+ [Scene.AnalyticsSpaces]: () => import('./analytics/AnalyticsSpaces'),
+ [Scene.AnalyticsProductHome]: () => import('./analytics/AnalyticsProductHome'),
[Scene.Tools]: () => import('./tools/Tools'),
[Scene.PropertyDefinitionEdit]: () => import('./data-management/definition/DefinitionEdit'),
[Scene.PropertyDefinition]: () => import('./data-management/definition/DefinitionView'),
diff --git a/frontend/src/scenes/dashboard/newDashboardLogic.ts b/frontend/src/scenes/dashboard/newDashboardLogic.ts
index 18b0b0058aa8..2b6d247ad319 100644
--- a/frontend/src/scenes/dashboard/newDashboardLogic.ts
+++ b/frontend/src/scenes/dashboard/newDashboardLogic.ts
@@ -19,6 +19,7 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { withBackLink } from 'scenes/analytics/analyticsBackLink'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'
import { autoRunMaxPrompt } from 'scenes/max/maxPrompt'
import { teamLogic } from 'scenes/teamLogic'
@@ -401,7 +402,7 @@ export const newDashboardLogic = kea<newDashboardLogicType>([
}
if (show && redirectAfterCreation) {
breakpoint()
- router.actions.push(urls.dashboard(result.id))
+ router.actions.push(withBackLink(urls.dashboard(result.id)))
}
} catch (e: any) {
if (!isBreakpoint(e)) {
@@ -507,7 +508,7 @@ export const newDashboardLogic = kea<newDashboardLogicType>([
})
if (redirectAfterCreation) {
- router.actions.push(urls.dashboard(result.id))
+ router.actions.push(withBackLink(urls.dashboard(result.id)))
}
} catch (e: any) {
if (!isBreakpoint(e)) {
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 8991db32d9eb..c606dbc748d1 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -49,6 +49,7 @@ import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual, removeUndefinedAndNull } from 'lib/utils/objects'
import { lazyWithRetry } from 'lib/utils/retryImport'
import { slugify } from 'lib/utils/strings'
+import { backLinkParams, withBackLink } from 'scenes/analytics/analyticsBackLink'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
@@ -2894,7 +2895,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
router.actions.push(urls.dashboard(dashboardId, insight.short_id))
} else {
lemonToast.info(`You're now viewing ${insight.name || insight.derived_name || name}`)
- router.actions.push(urls.insightView(insight.short_id))
+ router.actions.push(withBackLink(urls.insightView(insight.short_id)))
}
},
saveAsEndpoint: async () => {
@@ -3215,7 +3216,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
lemonToast.info(
`You're now viewing ${savedInsight.name || savedInsight.derived_name || insightName || 'Untitled'}`
)
- router.actions.push(urls.insightView(savedInsight.short_id))
+ router.actions.push(withBackLink(urls.insightView(savedInsight.short_id)))
}
},
discardChanges: async (_, breakpoint) => {
@@ -3368,7 +3369,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
if (!values.isEmbeddedMode) {
router.actions.replace(
values.editorUrl,
- undefined,
+ backLinkParams(router.values.searchParams),
getTabHash({ ...values, activeTab: nextTab })
)
}
@@ -4136,7 +4137,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
actions.setViewLoading(false)
actions.setViewQueryLoading(false)
tabAdded = true
- router.actions.replace(values.editorUrl, undefined, getTabHash(values))
+ router.actions.replace(
+ values.editorUrl,
+ backLinkParams(router.values.searchParams),
+ getTabHash(values)
+ )
} else if (
insightShortIdFromUrl &&
(searchParams.open_insight ||
@@ -4165,7 +4170,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
biEditorStateFromUrl ?? undefined
)
tabAdded = true
- router.actions.replace(values.editorUrl, undefined, getTabHash(values))
+ router.actions.replace(
+ values.editorUrl,
+ backLinkParams(router.values.searchParams),
+ getTabHash(values)
+ )
return
}
@@ -4260,7 +4269,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
}
tabAdded = true
- router.actions.replace(values.editorUrl, undefined, getTabHash(values))
+ router.actions.replace(
+ values.editorUrl,
+ backLinkParams(router.values.searchParams),
+ getTabHash(values)
+ )
} else if (searchParams.edit_metric) {
// edit_metric binds the "Update metric" button to overwrite a named metric.
// Both edit_metric and open_query are URL-controlled, so we never bind the
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index f0cf1c568f48..588505ce01fd 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -31,6 +31,7 @@ import { InsightEventSource, sanitizeInsight, sanitizeQuery } from 'lib/utils/ev
import { isEmptyObject, isObject } from 'lib/utils/guards'
import { objectsEqual } from 'lib/utils/objects'
import { RetainedValues } from 'lib/utils/retainedValues'
+import { withBackLink } from 'scenes/analytics/analyticsBackLink'
import { isDashboardFilterOverrideEmpty } from 'scenes/dashboard/dashboardFilterEmpty'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
@@ -1295,12 +1296,12 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
?.actions.setInsightMode(ItemMode.View, InsightEventSource.InsightHeader)
}
} else {
- router.actions.push(urls.insightView(savedInsight.short_id))
+ router.actions.push(withBackLink(urls.insightView(savedInsight.short_id)))
}
} else if (!insightNumericId) {
// If we've just saved a new insight without redirecting to view mode, we need to redirect to edit mode
// so that we aren't stuck on /insights/new
- router.actions.push(urls.insightEdit(savedInsight.short_id))
+ router.actions.push(withBackLink(urls.insightEdit(savedInsight.short_id)))
}
},
saveAs: async ({ redirectToViewMode, persist, folder }) => {
@@ -1345,9 +1346,9 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
actions.reloadSavedInsights() // Load insights afresh
if (redirectToViewMode) {
- router.actions.push(urls.insightView(insight.short_id))
+ router.actions.push(withBackLink(urls.insightView(insight.short_id)))
} else {
- router.actions.push(urls.insightEdit(insight.short_id))
+ router.actions.push(withBackLink(urls.insightEdit(insight.short_id)))
}
},
onRejectSuggestedInsight: () => {
@@ -1410,7 +1411,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
if (sidePanel?.values.modalMode) {
sidePanel.actions.closeSidePanel()
}
- router.actions.push(urls.insightEdit(newInsight.short_id))
+ router.actions.push(withBackLink(urls.insightEdit(newInsight.short_id)))
}
} catch (e: any) {
// Nothing downstream reports this: the copy is created by a plain listener rather than
diff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsx
index 39422e5ea861..645ea7840f21 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.tsx
+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx
@@ -20,6 +20,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { InsightEventSource, sanitizeQuery } from 'lib/utils/eventUsageLogic'
import { isEmptyObject, isObject } from 'lib/utils/guards'
+import { analyticsBackLink } from 'scenes/analytics/analyticsBackLink'
import { isDashboardFilterOverrideEmpty } from 'scenes/dashboard/dashboardFilterEmpty'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import {
@@ -292,7 +293,9 @@ export interface insightSceneLogicMeta {
dashboardName: string | null,
sceneSource: InsightSceneSource | null,
dashboardBackPath: string | null,
- arg: string | undefined
+ arg: string | undefined,
+ searchParams: Record<string, any>,
+ featureFlags: FeatureFlagsSet
) => Breadcrumb[]
projectTreeRef: (insightId: InsightId) => ProjectTreeRef
sidePanelContext: (
@@ -568,6 +571,8 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
s.sceneSource,
s.dashboardBackPath,
(state, props) => s.insightLogicRef(state, props)?.logic.selectors.insightName(state, props),
+ router.selectors.searchParams,
+ featureFlagLogic.selectors.featureFlags,
],
(
insightLogicRef: {
@@ -580,55 +585,68 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
dashboardName: DashboardType['name'] | null,
sceneSource: InsightSceneSource | null,
dashboardBackPath: string | null,
- insightName: string | undefined
+ insightName: string | undefined,
+ searchParams: Record<string, any>,
+ featureFlags: FeatureFlagsSet
): Breadcrumb[] => {
const dashboardLabel = dashboardName ?? 'Dashboard'
+ // The Analytics list that opened the insight names the way back, like the dashboard scene allows.
+ const backLink = analyticsBackLink(searchParams, featureFlags)
return [
- ...(dashboardId !== null
+ ...(backLink && dashboardId === null
? [
{
- key: Scene.Dashboards,
- name: 'Dashboards',
- path: urls.dashboards(),
- iconType: 'dashboard' as FileSystemIconType,
- },
- {
- key: Scene.Dashboard,
- name: dashboardLabel,
- // Going back must land on the dashboard as the user left it, not on its saved state
- path: dashboardBackPath ?? urls.dashboard(dashboardId),
- iconType: 'dashboard' as FileSystemIconType,
+ key: backLink.url,
+ name: backLink.name,
+ path: backLink.url,
+ iconType: 'product_analytics' as FileSystemIconType,
},
]
- : [
- sceneSource === 'web-analytics'
- ? {
- key: Scene.WebAnalytics,
- name: 'Web analytics',
- path: urls.webAnalytics(),
- iconType: 'web_analytics' as FileSystemIconType,
- }
- : sceneSource === 'llm-analytics'
+ : dashboardId !== null
+ ? [
+ {
+ key: Scene.Dashboards,
+ name: 'Dashboards',
+ path: urls.dashboards(),
+ iconType: 'dashboard' as FileSystemIconType,
+ },
+ {
+ key: Scene.Dashboard,
+ name: dashboardLabel,
+ // Going back must land on the dashboard as the user left it, not on its saved state
+ path: dashboardBackPath ?? urls.dashboard(dashboardId),
+ iconType: 'dashboard' as FileSystemIconType,
+ },
+ ]
+ : [
+ sceneSource === 'web-analytics'
? {
- key: 'AIObservability',
- name: 'AI observability',
- path: urls.aiObservabilityDashboard(),
- iconType: 'llm_analytics' as FileSystemIconType,
+ key: Scene.WebAnalytics,
+ name: 'Web analytics',
+ path: urls.webAnalytics(),
+ iconType: 'web_analytics' as FileSystemIconType,
}
- : sceneSource === 'endpoints'
+ : sceneSource === 'llm-analytics'
? {
- key: Scene.Endpoints,
- name: 'endpoints',
- path: urls.endpoints(),
- iconType: 'endpoints' as FileSystemIconType,
+ key: 'AIObservability',
+ name: 'AI observability',
+ path: urls.aiObservabilityDashboard(),
+ iconType: 'llm_analytics' as FileSystemIconType,
}
- : {
- key: Scene.SavedInsights,
- name: 'Product analytics',
- path: urls.savedInsights(),
- iconType: 'product_analytics' as FileSystemIconType,
- },
- ]),
+ : sceneSource === 'endpoints'
+ ? {
+ key: Scene.Endpoints,
+ name: 'endpoints',
+ path: urls.endpoints(),
+ iconType: 'endpoints' as FileSystemIconType,
+ }
+ : {
+ key: Scene.SavedInsights,
+ name: 'Product analytics',
+ path: urls.savedInsights(),
+ iconType: 'product_analytics' as FileSystemIconType,
+ },
+ ]),
{
key: [Scene.Insight, insight?.short_id || 'new'],
name: insightName,
diff --git a/frontend/src/scenes/library/Library.tsx b/frontend/src/scenes/library/Library.tsx
index aef4be4fb833..070cfbeed7e0 100644
--- a/frontend/src/scenes/library/Library.tsx
+++ b/frontend/src/scenes/library/Library.tsx
@@ -121,7 +121,7 @@ function LibraryContent(): JSX.Element {
? 'Nothing matches that search.'
: selectedType
? `No ${selectedType.pluralLabel.toLowerCase()} yet. Create one to see it here.`
- : 'Insights, dashboards, flags and everything else you save show up here.'
+ : 'Flags, experiments, cohorts and everything else you save show up here.'
}
/>
)}
diff --git a/frontend/src/scenes/library/libraryLogic.ts b/frontend/src/scenes/library/libraryLogic.ts
index a20354b5f1c7..cec2e77eb411 100644
--- a/frontend/src/scenes/library/libraryLogic.ts
+++ b/frontend/src/scenes/library/libraryLogic.ts
@@ -6,6 +6,7 @@ import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
+import { isAnalyticsType } from 'scenes/analytics/analyticsUtils'
import { urls } from 'scenes/urls'
import { fileSystemTypes, getTreeItemsNew } from '~/products'
@@ -220,7 +221,7 @@ export const libraryLogic = kea<libraryLogicType>([
return byType
},
],
- // "All objects" asks for every type, so drop the ones that live in Tools and Views.
+ // "All objects" asks for every type, so drop the ones that live in Tools and Analytics.
visibleObjects: [
(s) => [s.objects],
(objects: LibraryObjects): FileSystemEntry[] => objects.results.filter(isLibraryEntry),
@@ -238,7 +239,9 @@ export const libraryLogic = kea<libraryLogicType>([
return
}
if (objectType && !isLibraryType(objectType)) {
- router.actions.replace(urls.views())
+ router.actions.replace(
+ isAnalyticsType(objectType) ? urls.analyticsList({ type: objectType }) : urls.analyticsList()
+ )
return
}
const listHref = objectType ? libraryListHref(objectType) : null
diff --git a/frontend/src/scenes/library/libraryUtils.test.ts b/frontend/src/scenes/library/libraryUtils.test.ts
index 929a3744e907..8e4bd8aa9edc 100644
--- a/frontend/src/scenes/library/libraryUtils.test.ts
+++ b/frontend/src/scenes/library/libraryUtils.test.ts
@@ -8,7 +8,7 @@ import {
describe('libraryUtils', () => {
test.each([
- ['insight', true],
+ ['insight', false],
['feature_flag', true],
['dashboard', false],
['notebook', false],
@@ -51,7 +51,6 @@ describe('libraryUtils', () => {
test.each([
['feature_flag', '/feature_flags'],
- ['insight', '/insights'],
['cohort', '/cohorts'],
['session_recording_playlist', '/replay/playlists'],
['not_a_type', null],
diff --git a/frontend/src/scenes/library/libraryUtils.ts b/frontend/src/scenes/library/libraryUtils.ts
index a957f0393285..a49d78c1e149 100644
--- a/frontend/src/scenes/library/libraryUtils.ts
+++ b/frontend/src/scenes/library/libraryUtils.ts
@@ -1,3 +1,4 @@
+import { ANALYTICS_FILE_SYSTEM_TYPES } from 'scenes/analytics/analyticsUtils'
import { routes } from 'scenes/scenes'
import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
@@ -7,11 +8,8 @@ import { FileSystemType } from '~/types'
// These file system types are working pages rather than saved objects, so they belong to Tools.
export const TOOL_FILE_SYSTEM_TYPES = new Set(['endpoints', 'task'])
-// These file system types are views people open and read, so they belong to Views, next to canvases.
-export const VIEW_FILE_SYSTEM_TYPES = new Set(['dashboard', 'notebook'])
-
// The objects people reach for most come first. Any other type follows in name order.
-const LIBRARY_TYPE_ORDER = ['insight', 'feature_flag', 'experiment', 'survey', 'cohort', 'action']
+const LIBRARY_TYPE_ORDER = ['feature_flag', 'experiment', 'survey', 'cohort', 'action']
export interface LibraryObjectType {
value: string
@@ -30,9 +28,9 @@ export function productObjectType(item: Pick<FileSystemImport, 'type' | 'iconTyp
return baseObjectType(item.type) || item.iconType || ''
}
-/** Whether a file system type shows in Library, rather than in Tools or Views. */
+/** Whether a file system type shows in Library, rather than in Tools or Analytics. */
export function isLibraryType(type: string): boolean {
- return !TOOL_FILE_SYSTEM_TYPES.has(type) && !VIEW_FILE_SYSTEM_TYPES.has(type)
+ return !TOOL_FILE_SYSTEM_TYPES.has(type) && !ANALYTICS_FILE_SYSTEM_TYPES.has(type)
}
export function isLibraryEntry(entry: Pick<FileSystemEntry, 'type'>): boolean {
diff --git a/frontend/src/scenes/notebooks/notebookSceneLogic.ts b/frontend/src/scenes/notebooks/notebookSceneLogic.ts
index b8994316c48b..98f09000e2d0 100644
--- a/frontend/src/scenes/notebooks/notebookSceneLogic.ts
+++ b/frontend/src/scenes/notebooks/notebookSceneLogic.ts
@@ -2,6 +2,8 @@ import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, s
import type { BuiltLogic } from 'kea'
import { router } from 'kea-router'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { analyticsBackLink } from 'scenes/analytics/analyticsBackLink'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -102,7 +104,12 @@ export interface notebookSceneLogicMeta {
__keaTypeGenInternalSelectorTypes: {
notebookId: (shortId: string) => string
loading: (notebookLoading: boolean, notebooksLoading: boolean) => boolean
- breadcrumbs: (notebook: NotebookType | null, loading: boolean) => Breadcrumb[]
+ breadcrumbs: (
+ notebook: NotebookType | null,
+ loading: boolean,
+ searchParams: Record<string, any>,
+ featureFlags: FeatureFlagsSet
+ ) => Breadcrumb[]
projectTreeRef: (arg: string) => ProjectTreeRef | null
sidePanelContext: (notebookId: string, isLocalOnly: boolean) => SidePanelSceneContext | null
}
@@ -137,22 +144,35 @@ export const notebookSceneLogic = kea<notebookSceneLogicType>([
],
breadcrumbs: [
- (s) => [s.notebook, s.loading],
- (notebook: NotebookType | null, loading: boolean): Breadcrumb[] => {
- const parent: Breadcrumb =
- notebook?.parent_resource?.type === 'account'
- ? {
- key: Scene.CustomerAnalytics,
- name: 'Accounts',
- path: urls.customerAnalyticsAccount(notebook.parent_resource.id),
- iconType: 'group',
- }
- : {
- key: Scene.Notebooks,
- name: 'Notebooks',
- path: urls.notebooks(),
- iconType: 'notebook',
- }
+ (s) => [s.notebook, s.loading, router.selectors.searchParams, featureFlagLogic.selectors.featureFlags],
+ (
+ notebook: NotebookType | null,
+ loading: boolean,
+ searchParams: Record<string, any>,
+ featureFlags: FeatureFlagsSet
+ ): Breadcrumb[] => {
+ // The Analytics list that opened the notebook names the way back, like the dashboard scene allows.
+ const backLink = analyticsBackLink(searchParams, featureFlags)
+ const parent: Breadcrumb = backLink
+ ? {
+ key: backLink.url,
+ name: backLink.name,
+ path: backLink.url,
+ iconType: 'notebook',
+ }
+ : notebook?.parent_resource?.type === 'account'
+ ? {
+ key: Scene.CustomerAnalytics,
+ name: 'Accounts',
+ path: urls.customerAnalyticsAccount(notebook.parent_resource.id),
+ iconType: 'group',
+ }
+ : {
+ key: Scene.Notebooks,
+ name: 'Notebooks',
+ path: urls.notebooks(),
+ iconType: 'notebook',
+ }
return [
parent,
{
diff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
index 87f0f87e38f7..9e336729e101 100644
--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx
+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
@@ -18,7 +18,6 @@ import { todaySessionSelectionLogic } from '~/layout/today/todaySessionSelection
import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'
import { sessionItem } from '~/layout/today/todayWorkItems'
import { mswDecorator } from '~/mocks/browser'
-import { EMPTY_PAGINATED_RESPONSE } from '~/mocks/handlers'
import { makeReport, mockSignals } from 'products/signals/frontend/inbox/__mocks__/inboxMocks'
import { reportMetricQueryHandler } from 'products/signals/frontend/inbox/__mocks__/reportMetricMocks'
@@ -1173,28 +1172,3 @@ export const ListItemAppearanceDialog: Story = {
await within(document.body).findByText('Edit list item appearance')
},
}
-
-export const ViewsAll: Story = {
- parameters: { pageUrl: urls.views() },
-}
-
-export const ViewsEmpty: Story = {
- parameters: { pageUrl: urls.views() },
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/canvases/': EMPTY_PAGINATED_RESPONSE,
- '/api/projects/:team_id/notebooks/': EMPTY_PAGINATED_RESPONSE,
- '/api/projects/:team_id/dashboards/': EMPTY_PAGINATED_RESPONSE,
- },
- }),
- ],
-}
-
-export const ViewsNewMenu: Story = {
- parameters: { pageUrl: urls.views() },
- play: async ({ canvasElement }) => {
- const [newView] = await within(canvasElement).findAllByText('New view')
- await userEvent.click(newView)
- },
-}
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index fb00edb0d9a7..266acb5c3df6 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -107,8 +107,9 @@ export enum Scene {
LegalDocuments = 'LegalDocuments',
LegalDocumentNew = 'LegalDocumentNew',
Library = 'Library',
- Views = 'Views',
- ViewsNew = 'ViewsNew',
+ AnalyticsList = 'AnalyticsList',
+ AnalyticsSpaces = 'AnalyticsSpaces',
+ AnalyticsProductHome = 'AnalyticsProductHome',
Tools = 'Tools',
Activity = 'Activity',
LiveEvents = 'LiveEvents',
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index 1efd20d97bb1..9bdfa4682597 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -340,13 +340,17 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {
projectBased: true,
name: 'Library',
},
- [Scene.Views]: {
+ [Scene.AnalyticsList]: {
projectBased: true,
- name: 'Views',
+ name: 'Analytics',
},
- [Scene.ViewsNew]: {
+ [Scene.AnalyticsSpaces]: {
projectBased: true,
- name: 'New view',
+ name: 'Collections',
+ },
+ [Scene.AnalyticsProductHome]: {
+ projectBased: true,
+ name: 'Product analytics',
},
[Scene.Tools]: {
projectBased: true,
@@ -627,6 +631,11 @@ export const redirects: Record<
string | ((params: Params, searchParams: Params, hashParams: Params) => string)
> = {
'/action': urls.createAction(),
+ // The Views pane became Analytics; these keep old links in the Today navigation working.
+ '/views': urls.analyticsList(),
+ '/views/new': urls.analyticsList(),
+ // Analytics opens on View all; the bare path stays as the pane's prefix.
+ [urls.analytics()]: urls.analyticsList(),
'/action/:id': ({ id }) => urls.action(id),
'/actions': urls.actions(),
'/activity': urls.activity(),
@@ -848,8 +857,10 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.todayReport(':reportId')]: [Scene.ProjectHomepage, 'todayReport'],
[urls.library()]: [Scene.Library, 'library'],
[urls.library(':objectType')]: [Scene.Library, 'libraryObjectType'],
- [urls.views()]: [Scene.Views, 'views'],
- [urls.viewsNew()]: [Scene.ViewsNew, 'viewsNew'],
+ [urls.analyticsList()]: [Scene.AnalyticsList, 'analyticsList'],
+ [urls.analyticsMine()]: [Scene.AnalyticsList, 'analyticsMine'],
+ [urls.analyticsSpaces()]: [Scene.AnalyticsSpaces, 'analyticsSpaces'],
+ [urls.analyticsProductHome()]: [Scene.AnalyticsProductHome, 'analyticsProductHome'],
[urls.tools()]: [Scene.Tools, 'tools'],
[urls.aiHistory()]: [Scene.Max, 'maxHistory'],
[urls.ai()]: [Scene.Max, 'max'],
diff --git a/frontend/src/scenes/tools/toolsUtils.ts b/frontend/src/scenes/tools/toolsUtils.ts
index 169e43777fe1..a550cdcc1ab8 100644
--- a/frontend/src/scenes/tools/toolsUtils.ts
+++ b/frontend/src/scenes/tools/toolsUtils.ts
@@ -1,4 +1,5 @@
-import { VIEW_FILE_SYSTEM_TYPES, libraryRowOpensProduct, productObjectType } from 'scenes/library/libraryUtils'
+import { ANALYTICS_FILE_SYSTEM_TYPES, isFromPostHogItem } from 'scenes/analytics/analyticsUtils'
+import { libraryRowOpensProduct, productObjectType } from 'scenes/library/libraryUtils'
import { urls } from 'scenes/urls'
import { getDefaultTreePersons } from '~/layout/panel-layout/ProjectTree/defaultTree'
@@ -46,7 +47,13 @@ export function toolMatchesSearch(tool: FileSystemImport, search: string): boole
/** Whether a page gets its own row in the Products list. Library rows and the Views pane open the other pages. */
export function isToolItem(item: FileSystemImport): boolean {
- return !!item.href && !libraryRowOpensProduct(item) && !VIEW_FILE_SYSTEM_TYPES.has(productObjectType(item))
+ // The ready-made analytics products open from the Analytics pane, so they are not tools as well.
+ return (
+ !!item.href &&
+ !isFromPostHogItem(item) &&
+ !libraryRowOpensProduct(item) &&
+ !ANALYTICS_FILE_SYSTEM_TYPES.has(productObjectType(item))
+ )
}
let productLabelsByLibraryType: Map<string, string[]> | null = null
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 863b9fb387a7..67ad9378ee24 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -33,6 +33,15 @@ import type { SettingId, SettingLevelId, SettingSectionId } from './settings/typ
* Sync the paths with AutoProjectMiddleware!
*/
+/** The filters the analytics list reads from its URL. */
+export interface AnalyticsListUrlParams {
+ type?: string
+ createdBy?: string[]
+ folder?: string
+ search?: string
+ tags?: string[]
+}
+
export const urls = {
...productUrls,
absolute: (path = ''): string => window.location.origin + path,
@@ -172,8 +181,11 @@ export const urls = {
projectHomepage: (): string => '/home',
todayReport: (reportId: string): string => `/home/reports/${reportId}`,
library: (objectType?: string): string => (objectType ? `/library/${objectType}` : '/library'),
- views: (): string => '/views',
- viewsNew: (): string => '/views/new',
+ analytics: (): string => '/analytics',
+ analyticsList: (params: AnalyticsListUrlParams = {}): string => combineUrl('/analytics/all', params).url,
+ analyticsMine: (params: AnalyticsListUrlParams = {}): string => combineUrl('/analytics/mine', params).url,
+ analyticsSpaces: (): string => '/analytics/spaces',
+ analyticsProductHome: (): string => '/analytics/product-analytics',
tools: (): string => '/tools',
ai: (chat?: string, ask?: string): string => combineUrl('/ai', { ask, chat }).url,
aiTask: (taskId: string): string => combineUrl('/ai', { task: taskId }).url,
diff --git a/frontend/src/scenes/views/NewView.tsx b/frontend/src/scenes/views/NewView.tsx
deleted file mode 100644
index 94dc55049a7e..000000000000
--- a/frontend/src/scenes/views/NewView.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useActions } from 'kea'
-
-import { IconPlus } from '@posthog/icons'
-import { Item, ItemContent, ItemDescription, ItemGroup, ItemMedia, ItemTitle } from '@posthog/quill'
-
-import { SceneExport } from 'scenes/sceneTypes'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-
-import { newViewLogic } from './newViewLogic'
-import { VIEW_TYPES } from './viewsUtils'
-import { ViewTypeIcon } from './ViewTypeIcon'
-
-export const scene: SceneExport = {
- component: NewView,
-}
-
-export function NewView(): JSX.Element {
- const { pickNewViewType } = useActions(newViewLogic)
-
- return (
- <SceneContent>
- <SceneTitleSection
- name="New view"
- description="Pick what to create."
- resourceType={{ type: 'views', forceIcon: <IconPlus /> }}
- />
- <ItemGroup data-quill className="max-w-160 gap-2">
- {VIEW_TYPES.map((info) => (
- <Item
- key={info.type}
- variant="outline"
- render={<button type="button" />}
- className="text-start text-foreground hover:bg-fill-hover"
- onClick={() => pickNewViewType(info.type)}
- data-attr={`views-new-page-${info.type}`}
- >
- <ItemMedia variant="icon" aria-hidden>
- <ViewTypeIcon type={info.type} />
- </ItemMedia>
- <ItemContent>
- <ItemTitle>{info.label}</ItemTitle>
- <ItemDescription>{info.description}</ItemDescription>
- </ItemContent>
- </Item>
- ))}
- </ItemGroup>
- </SceneContent>
- )
-}
diff --git a/frontend/src/scenes/views/NewViewMenu.tsx b/frontend/src/scenes/views/NewViewMenu.tsx
deleted file mode 100644
index 0d3f985b4ab9..000000000000
--- a/frontend/src/scenes/views/NewViewMenu.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useActions } from 'kea'
-
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- ItemContent,
- ItemDescription,
- ItemTitle,
-} from '@posthog/quill'
-
-import { newViewLogic } from './newViewLogic'
-import { VIEW_TYPES } from './viewsUtils'
-import { ViewTypeIcon } from './ViewTypeIcon'
-
-interface NewViewMenuProps {
- /** The element that opens the menu, such as a quill `Button`. The menu merges its own props onto it. */
- trigger: JSX.Element
- children?: React.ReactNode
-}
-
-/** Asks which type of view to create, then hands off to that type's own create flow. */
-export function NewViewMenu({ trigger, children }: NewViewMenuProps): JSX.Element {
- const { pickNewViewType } = useActions(newViewLogic)
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger render={trigger}>{children}</DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="min-w-72">
- {VIEW_TYPES.map((info) => (
- <DropdownMenuItem
- key={info.type}
- className="h-auto items-start py-1.5 whitespace-normal [&>svg]:mt-1.5"
- onClick={() => pickNewViewType(info.type)}
- data-attr={`views-new-${info.type}`}
- >
- <ViewTypeIcon type={info.type} />
- <ItemContent variant="menuItem">
- <ItemTitle>{info.label}</ItemTitle>
- <ItemDescription>{info.description}</ItemDescription>
- </ItemContent>
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- )
-}
diff --git a/frontend/src/scenes/views/ViewRow.tsx b/frontend/src/scenes/views/ViewRow.tsx
deleted file mode 100644
index fa2049359a17..000000000000
--- a/frontend/src/scenes/views/ViewRow.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from '@posthog/quill'
-
-import { dayjs } from 'lib/dayjs'
-import { LinkPrimitive } from 'lib/lemon-ui/Link'
-
-import { VIEW_TYPE_INFO, ViewItem } from './viewsUtils'
-import { ViewTypeIcon } from './ViewTypeIcon'
-
-/** One view in the Views list: its type, name, space and when it last changed. The whole row opens the view. */
-export function ViewRow({ view }: { view: ViewItem }): JSX.Element {
- const meta = [
- VIEW_TYPE_INFO[view.type].label,
- view.spaceName && `#${view.spaceName}`,
- view.timestamp && `${view.timestampLabel} ${dayjs(view.timestamp).fromNow()}`,
- ]
- .filter(Boolean)
- .join(' · ')
-
- return (
- <Item
- variant="outline"
- size="sm"
- // The app styles every link in its accent color. A whole-row link reads as a row, so it keeps the text color.
- className="text-foreground hover:bg-fill-button-tertiary-hover hover:text-foreground"
- render={<LinkPrimitive to={view.href} data-attr={`views-row-${view.type}`} />}
- >
- <ItemMedia variant="icon" aria-hidden>
- <ViewTypeIcon type={view.type} />
- </ItemMedia>
- <ItemContent className="min-w-0">
- <ItemTitle className="truncate">{view.name}</ItemTitle>
- <ItemDescription className="truncate">{meta}</ItemDescription>
- </ItemContent>
- </Item>
- )
-}
diff --git a/frontend/src/scenes/views/ViewTypeIcon.tsx b/frontend/src/scenes/views/ViewTypeIcon.tsx
deleted file mode 100644
index 49b0da5f0ff3..000000000000
--- a/frontend/src/scenes/views/ViewTypeIcon.tsx
+++ /dev/null
@@ -1,8 +0,0 @@
-import { IconDashboard, IconNotebook, IconPalette } from '@posthog/icons'
-
-import { ViewType } from './viewsUtils'
-
-/** The icon that marks a view's type in lists, menus and the sidebar. */
-export function ViewTypeIcon({ type }: { type: ViewType }): JSX.Element {
- return type === 'canvas' ? <IconPalette /> : type === 'notebook' ? <IconNotebook /> : <IconDashboard />
-}
diff --git a/frontend/src/scenes/views/Views.tsx b/frontend/src/scenes/views/Views.tsx
deleted file mode 100644
index 9672d622810f..000000000000
--- a/frontend/src/scenes/views/Views.tsx
+++ /dev/null
@@ -1,216 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { useEffect } from 'react'
-import { useInView } from 'react-intersection-observer'
-
-import { IconGridMasonry, IconPlus, IconSearch } from '@posthog/icons'
-import {
- Button,
- Empty,
- EmptyContent,
- EmptyDescription,
- EmptyHeader,
- EmptyMedia,
- EmptyTitle,
- InputGroup,
- InputGroupAddon,
- InputGroupInput,
- InputGroupText,
- Item,
- ItemContent,
- ItemGroup,
- ItemMedia,
- Skeleton,
- Text,
- ToggleGroup,
- ToggleGroupItem,
-} from '@posthog/quill'
-
-import { NotFound } from 'lib/components/NotFound'
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { SceneExport } from 'scenes/sceneTypes'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-
-import { NewViewMenu } from './NewViewMenu'
-import { ViewRow } from './ViewRow'
-import { viewsLogic } from './viewsLogic'
-import { VIEW_TYPES, VIEW_TYPE_INFO, ViewTypeFilter } from './viewsUtils'
-
-const SCROLL_PREFETCH_MARGIN = '1200px 0px'
-
-export const scene: SceneExport = {
- component: Views,
- logic: viewsLogic,
-}
-
-const TYPE_FILTERS: { value: ViewTypeFilter; label: string }[] = [
- { value: 'all', label: 'All' },
- ...VIEW_TYPES.map((info) => ({ value: info.type, label: info.pluralLabel })),
-]
-
-/** Canvases, notebooks and dashboards in one list. */
-export function Views(): JSX.Element {
- const viewsEnabled = useFeatureFlag('TODAY_RAIL_NAV')
- // The page ships behind the Today navigation, so without the flag `/views` stays a missing page.
- return viewsEnabled ? <ViewsContent /> : <NotFound object="page" />
-}
-
-function ViewRowSkeletons({ count }: { count: number }): JSX.Element {
- return (
- <>
- {Array.from({ length: count }, (_, index) => (
- <Item key={index} variant="outline" size="sm">
- <ItemMedia variant="icon">
- <Skeleton className="size-4" />
- </ItemMedia>
- <ItemContent className="gap-1.5">
- <Skeleton className="h-3.5 w-48 max-w-full" />
- <Skeleton className="h-3 w-32 max-w-full" />
- </ItemContent>
- </Item>
- ))}
- </>
- )
-}
-
-function ViewsContent(): JSX.Element {
- const { feed, feedStale, search, typeFilter } = useValues(viewsLogic)
- const { setSearch, setTypeFilter, loadViews, loadMoreViews } = useActions(viewsLogic)
- const { ref: endRef, inView: endInView } = useInView({
- root: document.getElementById('main-content'),
- rootMargin: SCROLL_PREFETCH_MARGIN,
- })
- const { items, initialized, loading, hasMore, failedTypes, loadFailed } = feed
-
- useEffect(() => {
- if (endInView && hasMore) {
- loadMoreViews()
- }
- }, [endInView, hasMore, items.length, loadMoreViews])
-
- const newViewButton = (
- <NewViewMenu trigger={<Button variant="primary" size="sm" data-attr="views-new" />}>
- <IconPlus />
- New view
- </NewViewMenu>
- )
-
- const renderList = (): JSX.Element => {
- if (loadFailed) {
- return (
- <Empty>
- <EmptyHeader>
- <EmptyTitle>Couldn’t load your views</EmptyTitle>
- <EmptyDescription>Try again, and if it keeps happening contact support.</EmptyDescription>
- </EmptyHeader>
- <EmptyContent>
- <Button variant="outline" loading={loading} onClick={() => loadViews()} data-attr="views-retry">
- Try again
- </Button>
- </EmptyContent>
- </Empty>
- )
- }
- if (!initialized) {
- return (
- <ItemGroup combined aria-busy aria-label="Loading your views">
- <ViewRowSkeletons count={6} />
- </ItemGroup>
- )
- }
- if (!items.length) {
- const filterLabel = typeFilter === 'all' ? 'views' : VIEW_TYPE_INFO[typeFilter].pluralLabel.toLowerCase()
- return (
- <Empty>
- <EmptyHeader>
- <EmptyMedia variant="icon">
- <IconGridMasonry />
- </EmptyMedia>
- <EmptyTitle>{search ? 'Nothing matches that search' : `No ${filterLabel} yet`}</EmptyTitle>
- <EmptyDescription>
- {search
- ? 'Try a different name, or clear the search.'
- : 'Canvases, notebooks and dashboards you create show up here.'}
- </EmptyDescription>
- </EmptyHeader>
- {!search && <EmptyContent>{newViewButton}</EmptyContent>}
- </Empty>
- )
- }
- return (
- <ItemGroup
- combined
- aria-busy={feedStale || hasMore}
- className={feedStale ? 'opacity-60 transition-opacity' : 'transition-opacity'}
- >
- {items.map((view) => (
- <ViewRow key={`${view.type}-${view.id}`} view={view} />
- ))}
- {hasMore && <ViewRowSkeletons count={3} />}
- </ItemGroup>
- )
- }
-
- return (
- <SceneContent>
- <SceneTitleSection
- name="Views"
- description="Canvases, notebooks and dashboards in this project."
- resourceType={{ type: 'views', forceIcon: <IconGridMasonry /> }}
- actions={<div data-quill>{newViewButton}</div>}
- />
- <div data-quill className="@container/views flex flex-col gap-3">
- <div className="flex flex-wrap items-center gap-2">
- <InputGroup className="min-w-48 flex-1">
- <InputGroupAddon align="inline-start">
- <InputGroupText>
- <IconSearch />
- </InputGroupText>
- </InputGroupAddon>
- <InputGroupInput
- type="search"
- aria-label="Search views"
- placeholder="Search views"
- value={search}
- onChange={(event: React.ChangeEvent<HTMLInputElement>) => setSearch(event.target.value)}
- data-attr="views-search"
- />
- </InputGroup>
- <ToggleGroup
- size="sm"
- aria-label="Filter by type"
- value={[typeFilter]}
- onValueChange={(value: string[]) => value[0] && setTypeFilter(value[0] as ViewTypeFilter)}
- >
- {TYPE_FILTERS.map((filter) => (
- <ToggleGroupItem key={filter.value} value={filter.value} data-attr="views-type-filter">
- {filter.label}
- </ToggleGroupItem>
- ))}
- </ToggleGroup>
- </div>
- {initialized && !loadFailed && failedTypes.length > 0 && (
- <div className="flex flex-wrap items-center gap-2" role="alert">
- <Text size="sm" variant="destructive">
- {`${failedTypes
- .map((type) => VIEW_TYPE_INFO[type].pluralLabel)
- .join(' and ')} didn’t load, so this list may be incomplete.`}
- </Text>
- <Button
- variant="outline"
- size="xs"
- loading={loading}
- onClick={() => loadViews()}
- data-attr="views-retry"
- >
- Try again
- </Button>
- </div>
- )}
- {renderList()}
- <div ref={endRef} aria-hidden />
- </div>
- </SceneContent>
- )
-}
diff --git a/frontend/src/scenes/views/newViewLogic.ts b/frontend/src/scenes/views/newViewLogic.ts
deleted file mode 100644
index fc2dab06c0a3..000000000000
--- a/frontend/src/scenes/views/newViewLogic.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { MakeLogicType, actions, kea, listeners, path } from 'kea'
-import { router } from 'kea-router'
-import posthog from 'posthog-js'
-
-import { toast } from '@posthog/quill'
-
-import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { urls } from 'scenes/urls'
-
-import { canvasSceneLogic } from 'products/canvas/frontend/scene/canvasSceneLogic'
-
-import { ViewType, newCanvasSpaceIdForPath } from './viewsUtils'
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface newViewLogicActions {
- pickNewViewType: (type: ViewType) => {
- type: ViewType
- }
-}
-
-export type newViewLogicType = MakeLogicType<{}, newViewLogicActions>
-
-/** Hands a "New view" pick to the flow that creates that type. */
-export const newViewLogic = kea<newViewLogicType>([
- path(['scenes', 'views', 'newViewLogic']),
- actions({
- pickNewViewType: (type: ViewType) => ({ type }),
- }),
- listeners(() => ({
- pickNewViewType: ({ type }) => {
- // pinned: analytics event name and property. Renaming them breaks dashboards.
- posthog.capture('views new picked', { type })
- if (type === 'canvas') {
- const pathname = removeProjectIdIfPresent(router.values.location.pathname)
- const canvasId = /^\/canvases\/([^/]+)$/.exec(pathname)?.[1]
- const canvas = canvasId ? canvasSceneLogic.findMounted({ id: canvasId })?.values.canvas : null
- if (canvasId && canvasId !== 'new' && !canvas) {
- toast.error({ title: 'Wait for the canvas to load, then try again.' })
- return
- }
- const spaceId = newCanvasSpaceIdForPath(pathname, canvas ?? null)
- router.actions.push(urls.canvasNew(spaceId))
- } else if (type === 'notebook') {
- router.actions.push(urls.notebook('new'))
- } else {
- // The dashboards page opens its new-dashboard dialog from this hash. Some scenes already host
- // that dialog, so a second host in the shell would open it twice on those pages.
- router.actions.push(`${urls.dashboards()}#newDashboard=modal`)
- }
- },
- })),
-])
diff --git a/frontend/src/scenes/views/viewFeed.ts b/frontend/src/scenes/views/viewFeed.ts
deleted file mode 100644
index 00e32384ab67..000000000000
--- a/frontend/src/scenes/views/viewFeed.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import { canvasesList } from 'products/canvas/frontend/generated/api'
-import { dashboardsList } from 'products/dashboards/frontend/generated/api'
-import { notebooksList } from 'products/notebooks/frontend/generated/api'
-import type { NotebooksListParams } from 'products/notebooks/frontend/generated/api.schemas'
-
-import {
- LISTED_CANVAS_KIND,
- VIEW_TYPES,
- ViewItem,
- ViewType,
- ViewTypeFilter,
- canvasToView,
- dashboardToView,
- notebookToView,
-} from './viewsUtils'
-
-export const VIEW_FEED_PAGE_SIZE = 50
-
-export interface ViewFeedQuery {
- type: ViewTypeFilter
- search: string
- createdBy?: string | null
-}
-
-export interface ViewSourcePage {
- items: ViewItem[]
- fetched: number
- hasMore: boolean
-}
-
-export interface ViewSourceState {
- projectId: string
- search: string
- createdBy: string | null
- type: ViewType
- items: ViewItem[]
- offset: number
- hasMore: boolean
- initialized: boolean
- refreshing: boolean
- loading: boolean
- failed: boolean
- generation: number
-}
-
-export interface ViewFeed {
- items: ViewItem[]
- initialized: boolean
- loading: boolean
- hasMore: boolean
- failedTypes: ViewType[]
- loadFailed: boolean
-}
-
-export function viewFeedTypes(query: ViewFeedQuery): ViewType[] {
- return query.type === 'all' ? VIEW_TYPES.map((info) => info.type) : [query.type]
-}
-
-export function viewSourceKey(projectId: string, search: string, type: ViewType, createdBy: string | null): string {
- return JSON.stringify([projectId, search.trim(), type, createdBy])
-}
-
-export async function fetchViewSourcePage(
- projectId: string,
- type: ViewType,
- search: string,
- createdBy: string | null,
- offset: number
-): Promise<ViewSourcePage> {
- const limit = VIEW_FEED_PAGE_SIZE
- const query = search.trim() || undefined
- const created_by = createdBy ?? undefined
- if (type === 'canvas') {
- const page = await canvasesList(projectId, {
- kind: LISTED_CANVAS_KIND,
- search: query,
- created_by,
- ordering: '-updated_at',
- limit,
- offset,
- })
- return {
- items: page.results.map((canvas) => canvasToView(canvas, {})),
- fetched: page.results.length,
- hasMore: !!page.next && page.results.length > 0,
- }
- }
- if (type === 'notebook') {
- // The notebooks endpoint filters on `search`, but its schema does not declare the parameter.
- const params: NotebooksListParams & { search?: string } = { limit, offset, search: query, created_by }
- const page = await notebooksList(projectId, params)
- return {
- items: page.results.filter((notebook) => !notebook.deleted).map(notebookToView),
- fetched: page.results.length,
- hasMore: !!page.next && page.results.length > 0,
- }
- }
- const page = await dashboardsList(projectId, {
- search: query,
- created_by,
- ordering: '-last_viewed_at',
- limit,
- offset,
- })
- return {
- items: page.results.filter((dashboard) => !dashboard.deleted).map(dashboardToView),
- fetched: page.results.length,
- hasMore: !!page.next && page.results.length > 0,
- }
-}
-
-export function viewTime(item: ViewItem): number {
- return item.timestamp ? new Date(item.timestamp).getTime() : 0
-}
-
-export function mergeViewSources(sources: (ViewSourceState | undefined)[]): {
- items: ViewItem[]
- blocking: ViewSourceState[]
-} {
- const states = sources.map(
- (source) => source ?? ({ items: [], hasMore: true, initialized: false } as unknown as ViewSourceState)
- )
- const positions = states.map(() => 0)
- const items: ViewItem[] = []
- for (;;) {
- const blocking = states.filter(
- (state, index) => positions[index] >= state.items.length && (state.hasMore || !state.initialized)
- )
- if (blocking.length) {
- return { items, blocking: blocking.filter((state) => sources.includes(state)) }
- }
- let best = -1
- for (let index = 0; index < states.length; index++) {
- if (
- positions[index] < states[index].items.length &&
- (best === -1 ||
- viewTime(states[index].items[positions[index]]) > viewTime(states[best].items[positions[best]]))
- ) {
- best = index
- }
- }
- if (best === -1) {
- return { items, blocking: [] }
- }
- items.push(states[best].items[positions[best]++])
- }
-}
-
-export function viewFeedFromSources(
- sources: (ViewSourceState | undefined)[],
- spaceNames: Record<string, string>
-): ViewFeed {
- const { items, blocking } = mergeViewSources(sources)
- const initialized = sources.every((source) => source?.initialized)
- const failed = sources.filter((source): source is ViewSourceState => !!source?.failed)
- return {
- items: initialized
- ? items.map((item) =>
- item.spaceId && !item.spaceName && spaceNames[item.spaceId]
- ? { ...item, spaceName: spaceNames[item.spaceId] }
- : item
- )
- : [],
- initialized,
- loading: sources.some((source) => !source || source.loading || source.refreshing),
- hasMore: blocking.length > 0,
- failedTypes: failed.map((source) => source.type),
- loadFailed: initialized && failed.length === sources.length && items.length === 0,
- }
-}
diff --git a/frontend/src/scenes/views/viewFeedLogic.test.ts b/frontend/src/scenes/views/viewFeedLogic.test.ts
deleted file mode 100644
index 884dc1b3b342..000000000000
--- a/frontend/src/scenes/views/viewFeedLogic.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { teamLogic } from 'scenes/teamLogic'
-
-import { useMocks } from '~/mocks/jest'
-import { initKeaTests } from '~/test/init'
-
-import { ViewFeedQuery } from './viewFeed'
-import { resetViewFeedSnapshot, selectViewFeed, viewFeedLogic } from './viewFeedLogic'
-
-const ALL: ViewFeedQuery = { type: 'all', search: '' }
-
-const at = (day: number): string => `2026-09-${String(day).padStart(2, '0')}T00:00:00Z`
-
-describe('viewFeedLogic', () => {
- let requests: Record<string, string[]>
-
- beforeEach(() => {
- resetViewFeedSnapshot()
- requests = { canvases: [], notebooks: [], dashboards: [] }
- const record = (name: string, request: Request): URLSearchParams => {
- const params = new URL(request.url).searchParams
- requests[name].push(`${params.get('offset')}:${params.get('ordering') ?? ''}`)
- return params
- }
- useMocks({
- get: {
- '/api/projects/:team_id/task_channels/': [{ id: 'space-1', name: 'growth' }],
- '/api/projects/:team_id/canvases/': ({ request }) => {
- record('canvases', request)
- return {
- results: [{ id: 'c7', name: 'C', kind: 'freeform', channel: 'space-1', updated_at: at(7) }],
- next: null,
- }
- },
- '/api/projects/:team_id/notebooks/': ({ request }) => {
- record('notebooks', request)
- return {
- results: [
- { short_id: 'n9', title: 'N', deleted: false, last_modified_at: at(9) },
- { short_id: 'n1', title: 'N', deleted: false, last_modified_at: at(1) },
- ],
- next: null,
- }
- },
- '/api/projects/:team_id/dashboards/': ({ request }) => {
- const params = record('dashboards', request)
- return params.get('offset') === '0'
- ? {
- results: [
- { id: 10, name: 'D', last_viewed_at: at(10), created_at: at(1) },
- { id: 8, name: 'D', last_viewed_at: null, created_at: at(8) },
- ],
- next: '?offset=2',
- }
- : { results: [{ id: 3, name: 'D', last_viewed_at: at(3), created_at: at(1) }], next: null }
- },
- },
- })
- initKeaTests()
- })
-
- const feed = (logic: ReturnType<typeof viewFeedLogic.build>): string[] =>
- selectViewFeed(logic.values.sources, logic.values.spaceNames, teamLogic.values.currentTeamId, ALL).items.map(
- (item) => `${item.type}:${item.id}`
- )
-
- it('shows only rows whose order is final, and loads more from the type that holds them back', async () => {
- const logic = viewFeedLogic()
- logic.mount()
-
- await expectLogic(logic, () => logic.actions.refreshFeed(ALL)).toFinishAllListeners()
- expect(feed(logic)).toEqual(['dashboard:10', 'notebook:n9', 'dashboard:8'])
-
- await expectLogic(logic, () => logic.actions.ensureFeed(ALL, 100)).toFinishAllListeners()
- expect(feed(logic)).toEqual([
- 'dashboard:10',
- 'notebook:n9',
- 'dashboard:8',
- 'canvas:c7',
- 'dashboard:3',
- 'notebook:n1',
- ])
- expect(requests).toEqual({
- canvases: ['0:-updated_at'],
- notebooks: ['0:'],
- dashboards: ['0:-last_viewed_at', '2:-last_viewed_at'],
- })
- const result = selectViewFeed(
- logic.values.sources,
- logic.values.spaceNames,
- teamLogic.values.currentTeamId,
- ALL
- )
- expect(result.hasMore).toBe(false)
- expect(result.items.find((item) => item.type === 'canvas')?.spaceName).toBe('growth')
- expect(result.items.filter((item) => item.type === 'dashboard').map((item) => item.timestampLabel)).toEqual([
- 'Viewed',
- 'Created',
- 'Viewed',
- ])
- })
-
- it('keeps the loaded list after a remount, so a revisit shows rows at once', async () => {
- const first = viewFeedLogic()
- first.mount()
- await expectLogic(first, () => first.actions.refreshFeed(ALL)).toFinishAllListeners()
- first.unmount()
-
- const second = viewFeedLogic()
- second.mount()
-
- expect(feed(second)).toEqual(['dashboard:10', 'notebook:n9', 'dashboard:8'])
- })
-})
diff --git a/frontend/src/scenes/views/viewsLogic.ts b/frontend/src/scenes/views/viewsLogic.ts
deleted file mode 100644
index f0377ce20636..000000000000
--- a/frontend/src/scenes/views/viewsLogic.ts
+++ /dev/null
@@ -1,229 +0,0 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
-import { router, urlToAction } from 'kea-router'
-import posthog from 'posthog-js'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
-
-import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
-import { VIEW_FEED_PAGE_SIZE, ViewFeed, ViewFeedQuery, ViewSourceState } from './viewFeed'
-import { selectViewFeed, viewFeedLogic } from './viewFeedLogic'
-import { ViewTypeFilter } from './viewsUtils'
-
-export const VIEWS_PREFETCH_COUNT = VIEW_FEED_PAGE_SIZE
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface viewsLogicValues {
- featureFlags: FeatureFlagsSet // featureFlagLogic
- currentTeamId: number | null // teamLogic
- sources: Record<string, ViewSourceState> // viewFeedLogic
- spaceNames: Record<string, string> // viewFeedLogic
- currentFeed: ViewFeed
- feed: ViewFeed
- feedQuery: ViewFeedQuery
- feedSearch: string
- feedStale: boolean
- search: string
- shownQuery: ViewFeedQuery | null
- typeFilter: ViewTypeFilter
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface viewsLogicActions {
- ensureFeed: (
- query: ViewFeedQuery,
- count: number
- ) => {
- count: number
- query: ViewFeedQuery
- } // viewFeedLogic
- refreshFeed: (query: ViewFeedQuery) => {
- query: ViewFeedQuery
- } // viewFeedLogic
- sourceRefreshed: (
- key: string,
- generation: number,
- page: null | import('./viewFeed').ViewSourcePage
- ) => {
- generation: number
- key: string
- page: null | import('./viewFeed').ViewSourcePage
- } // viewFeedLogic
- loadMoreViews: () => {
- value: true
- }
- loadViews: () => {
- value: true
- }
- setFeedSearch: (search: string) => {
- search: string
- }
- setSearch: (search: string) => {
- search: string
- }
- setShownQuery: (query: ViewFeedQuery) => {
- query: ViewFeedQuery
- }
- setTypeFilter: (typeFilter: ViewTypeFilter) => {
- typeFilter: ViewTypeFilter
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface viewsLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- feedQuery: (typeFilter: ViewTypeFilter, feedSearch: string) => ViewFeedQuery
- currentFeed: (
- sources: Record<string, ViewSourceState>,
- spaceNames: Record<string, string>,
- currentTeamId: number | null,
- feedQuery: ViewFeedQuery
- ) => ViewFeed
- feed: (
- currentFeed: ViewFeed,
- sources: Record<string, ViewSourceState>,
- spaceNames: Record<string, string>,
- currentTeamId: number | null,
- shownQuery: ViewFeedQuery | null
- ) => ViewFeed
- feedStale: (currentFeed: ViewFeed, feed: ViewFeed) => boolean
- }
-}
-
-export type viewsLogicType = MakeLogicType<viewsLogicValues, viewsLogicActions, Record<string, any>, viewsLogicMeta>
-
-export const viewsLogic = kea<viewsLogicType>([
- path(['scenes', 'views', 'viewsLogic']),
- connect(() => ({
- values: [
- featureFlagLogic,
- ['featureFlags'],
- teamLogic,
- ['currentTeamId'],
- viewFeedLogic,
- ['sources', 'spaceNames'],
- ],
- actions: [viewFeedLogic, ['ensureFeed', 'refreshFeed', 'sourceRefreshed']],
- })),
- actions({
- setSearch: (search: string) => ({ search }),
- setFeedSearch: (search: string) => ({ search }),
- setTypeFilter: (typeFilter: ViewTypeFilter) => ({ typeFilter }),
- setShownQuery: (query: ViewFeedQuery) => ({ query }),
- loadViews: true,
- loadMoreViews: true,
- }),
- reducers({
- search: ['', { setSearch: (_, { search }) => search }],
- feedSearch: ['', { setFeedSearch: (_, { search }) => search }],
- typeFilter: ['all' as ViewTypeFilter, { setTypeFilter: (_, { typeFilter }) => typeFilter }],
- shownQuery: [null as ViewFeedQuery | null, { setShownQuery: (_, { query }) => query }],
- }),
- selectors({
- feedQuery: [
- (s) => [s.typeFilter, s.feedSearch],
- (typeFilter: ViewTypeFilter, feedSearch: string): ViewFeedQuery => ({
- type: typeFilter,
- search: feedSearch.trim(),
- }),
- ],
- currentFeed: [
- (s) => [s.sources, s.spaceNames, s.currentTeamId, s.feedQuery],
- (
- sources: Record<string, ViewSourceState>,
- spaceNames: Record<string, string>,
- currentTeamId: number | null,
- feedQuery: ViewFeedQuery
- ): ViewFeed => selectViewFeed(sources, spaceNames, currentTeamId, feedQuery),
- ],
- feed: [
- (s) => [s.currentFeed, s.sources, s.spaceNames, s.currentTeamId, s.shownQuery],
- (
- currentFeed: ViewFeed,
- sources: Record<string, ViewSourceState>,
- spaceNames: Record<string, string>,
- currentTeamId: number | null,
- shownQuery: ViewFeedQuery | null
- ): ViewFeed => {
- if (currentFeed.initialized || !shownQuery) {
- return currentFeed
- }
- const shownFeed = selectViewFeed(sources, spaceNames, currentTeamId, shownQuery)
- return shownFeed.initialized ? { ...shownFeed, loading: true, hasMore: false } : currentFeed
- },
- ],
- feedStale: [
- (s) => [s.currentFeed, s.feed],
- (currentFeed: ViewFeed, feed: ViewFeed): boolean => !currentFeed.initialized && feed.initialized,
- ],
- }),
- listeners(({ actions, values, cache }) => {
- const syncShownQuery = (): void => {
- if (values.currentFeed.initialized) {
- if (values.shownQuery !== values.feedQuery) {
- actions.setShownQuery(values.feedQuery)
- }
- if (cache.visitStartedAt !== undefined) {
- posthog.capture('views list loaded', {
- duration_ms: Math.round(performance.now() - cache.visitStartedAt),
- cached: cache.visitCached,
- view_count: values.currentFeed.items.length,
- has_more: values.currentFeed.hasMore,
- })
- cache.visitStartedAt = undefined
- }
- }
- }
- return {
- [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
- // Flags can arrive after urlToAction ran, so a visit that skipped the load must load now.
- if (
- values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] &&
- cache.visitStartedAt === undefined &&
- !values.currentFeed.initialized &&
- !values.currentFeed.loading &&
- removeProjectIdIfPresent(router.values.location.pathname) === urls.views()
- ) {
- actions.loadViews()
- }
- },
- loadViews: () => {
- cache.visitStartedAt = performance.now()
- cache.visitCached = values.currentFeed.initialized
- actions.refreshFeed(values.feedQuery)
- syncShownQuery()
- },
- loadMoreViews: () => {
- actions.ensureFeed(values.feedQuery, values.feed.items.length + VIEWS_PREFETCH_COUNT)
- },
- setSearch: async ({ search }, breakpoint) => {
- if (search.trim() !== values.feedSearch.trim()) {
- await breakpoint(search.trim() ? 200 : 0)
- }
- actions.setFeedSearch(search)
- },
- setFeedSearch: () => {
- actions.ensureFeed(values.feedQuery, VIEWS_PREFETCH_COUNT)
- syncShownQuery()
- },
- setTypeFilter: ({ typeFilter }) => {
- // pinned: analytics event name and property. Renaming them breaks dashboards.
- posthog.capture('views list filtered', { type: typeFilter })
- actions.ensureFeed(values.feedQuery, VIEWS_PREFETCH_COUNT)
- syncShownQuery()
- },
- sourceRefreshed: () => syncShownQuery(),
- }
- }),
- urlToAction(({ actions, values }) => ({
- [urls.views()]: () => {
- // The Views scene renders nothing without the flag, so it must not load anything either.
- if (values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
- actions.loadViews()
- }
- },
- })),
-])
diff --git a/frontend/src/scenes/views/viewsUtils.test.ts b/frontend/src/scenes/views/viewsUtils.test.ts
deleted file mode 100644
index 53a636201be3..000000000000
--- a/frontend/src/scenes/views/viewsUtils.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'
-
-import { newCanvasSpaceIdForPath } from './viewsUtils'
-
-const canvas = (overrides: Partial<CanvasApi>): CanvasApi =>
- ({
- id: 'c',
- name: 'Canvas',
- kind: 'freeform',
- channel: 'space-1',
- updated_at: '2026-09-01T00:00:00Z',
- ...overrides,
- }) as CanvasApi
-
-describe('viewsUtils', () => {
- test.each([
- ['a space page', '/spaces/space-3', 'space-3'],
- ['a canvas page', '/canvases/board', 'space-1'],
- ['a different open canvas', '/canvases/other', null],
- ['the start page', '/canvases/new', null],
- ['a page with no space', '/views', null],
- ])('defaults a new canvas from %s to the right space', (_, path, spaceId) => {
- expect(newCanvasSpaceIdForPath(path, canvas({ id: 'board', channel: 'space-1' }))).toBe(spaceId)
- })
-})
diff --git a/frontend/src/scenes/views/viewsUtils.ts b/frontend/src/scenes/views/viewsUtils.ts
deleted file mode 100644
index 2dd4a8c90962..000000000000
--- a/frontend/src/scenes/views/viewsUtils.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import { urls } from 'scenes/urls'
-
-import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'
-import type { DashboardBasicApi } from 'products/dashboards/frontend/generated/api.schemas'
-import type { NotebookMinimalApi } from 'products/notebooks/frontend/generated/api.schemas'
-
-// pinned: these values are the `type` property of the `views new picked` and `views list filtered` events.
-export type ViewType = 'canvas' | 'notebook' | 'dashboard'
-export type ViewTypeFilter = ViewType | 'all'
-
-export interface ViewTypeInfo {
- type: ViewType
- label: string
- pluralLabel: string
- /** One line for the "New" menu. */
- description: string
- color: string
-}
-
-export const VIEW_TYPES: ViewTypeInfo[] = [
- {
- type: 'canvas',
- label: 'Canvas',
- pluralLabel: 'Canvases',
- description: 'A freeform page that AI builds from your prompt',
- // Canvases have no product color of their own, so they take product analytics'.
- color: 'var(--color-product-product-analytics-light)',
- },
- {
- type: 'notebook',
- label: 'Notebook',
- pluralLabel: 'Notebooks',
- description: 'A doc that mixes your notes with live insights and replays',
- color: 'var(--color-product-notebooks-light)',
- },
- {
- type: 'dashboard',
- label: 'Dashboard',
- pluralLabel: 'Dashboards',
- description: 'A grid of saved insights for your key metrics',
- color: 'var(--color-product-dashboards-light)',
- },
-]
-
-export const VIEW_TYPE_INFO = Object.fromEntries(VIEW_TYPES.map((info) => [info.type, info])) as Record<
- ViewType,
- ViewTypeInfo
->
-
-// Component canvases are widgets that grids place, not views a person opens.
-export const LISTED_CANVAS_KIND = 'freeform'
-
-export interface ViewItem {
- type: ViewType
- id: string
- name: string
- href: string
- /** When the view last changed, or was last viewed or created when that is all the API knows. */
- timestamp: string | null
- timestampLabel: 'Edited' | 'Viewed' | 'Created'
- /** The space a canvas belongs to. Null for other types. */
- spaceId: string | null
- /** The space's name. Null for other types, or when the space is unknown. */
- spaceName: string | null
- createdByUuid: string | null
- /** The run building a canvas that has no version yet. Null once it has one, and for other types. */
- firstBuildTaskId: string | null
-}
-
-export function canvasToView(canvas: CanvasApi, spaceNames: Record<string, string>): ViewItem {
- return {
- type: 'canvas',
- id: canvas.id,
- name: canvas.name || 'Untitled canvas',
- href: urls.canvasDetail(canvas.id),
- timestamp: canvas.updated_at,
- timestampLabel: 'Edited',
- spaceId: canvas.channel,
- spaceName: spaceNames[canvas.channel] ?? null,
- createdByUuid: canvas.created_by?.uuid ?? null,
- firstBuildTaskId: canvas.current_version_id ? null : (canvas.generation_task_id ?? null),
- }
-}
-
-export function notebookToView(notebook: NotebookMinimalApi): ViewItem {
- return {
- type: 'notebook',
- id: notebook.short_id,
- name: notebook.title || 'Untitled notebook',
- href: urls.notebook(notebook.short_id),
- timestamp: notebook.last_modified_at,
- timestampLabel: 'Edited',
- spaceId: null,
- spaceName: null,
- createdByUuid: notebook.created_by?.uuid ?? null,
- firstBuildTaskId: null,
- }
-}
-
-export function dashboardToView(dashboard: DashboardBasicApi): ViewItem {
- return {
- type: 'dashboard',
- id: String(dashboard.id),
- name: dashboard.name || 'Untitled dashboard',
- href: urls.dashboard(dashboard.id),
- // Dashboards have no edit time in the list API, so the last view stands in for it.
- timestamp: dashboard.last_viewed_at ?? dashboard.created_at,
- timestampLabel: dashboard.last_viewed_at ? 'Viewed' : 'Created',
- spaceId: null,
- spaceName: null,
- createdByUuid: dashboard.created_by?.uuid ?? null,
- firstBuildTaskId: null,
- }
-}
-
-/**
- * The space a new canvas defaults to from the page the person is on: the open space, or the open
- * canvas's space. Null when the page names no space, so the start page falls back to the personal space.
- */
-export function newCanvasSpaceIdForPath(
- path: string,
- openCanvas: Pick<CanvasApi, 'id' | 'channel'> | null
-): string | null {
- const space = /^\/spaces\/([^/]+)/.exec(path)
- if (space) {
- return space[1]
- }
- const canvas = /^\/canvases\/([^/]+)$/.exec(path)
- return canvas && openCanvas?.id === canvas[1] ? openCanvas.channel : null
-}
diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.py
index 63cd00762498..1d352688aa73 100644
--- a/posthog/api/file_system/file_system.py
+++ b/posthog/api/file_system/file_system.py
@@ -20,6 +20,7 @@ from rest_framework.response import Response
from posthog.api.file_system.access_levels import (
FileSystemAccessLevelSerializerMixin,
+ _coerce_refs_for_lookup,
denied_short_id_refs,
entries_missing_access_level,
)
@@ -51,6 +52,8 @@ from posthog.models.file_system.file_system_representation import FileSystemRepr
from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
from posthog.models.file_system.file_system_view_log import get_recent_file_system_items, recent_view_logs
from posthog.models.file_system.unfiled_file_saver import save_unfiled_files
+from posthog.models.tagged_item import TaggedItem
+from posthog.models.tagged_item_registry import object_column_for
from posthog.models.team import Team
from posthog.models.user import User
from posthog.settings import EE_AVAILABLE
@@ -62,6 +65,11 @@ DELETE_PREVIEW_ENTRY_LIMIT = 200
# One message for every reason a restore is refused (missing, already live, or off-limits), so the
# endpoint can't be used to learn which refs exist.
+# The file system rows whose objects carry tags, with the model field the row's `ref` names.
+TAGGED_FILE_SYSTEM_TYPES: tuple[tuple[str, str, str, str], ...] = (
+ ("dashboard", "dashboards", "Dashboard", "id"),
+ ("insight", "product_analytics", "Insight", "short_id"),
+)
UNDO_DELETE_REFUSED = "Couldn't restore this. It may already be restored, or you may not have access to it."
# Paths the product itself builds are at most three segments deep ("Unfiled/Insights/<name>"), so
@@ -101,6 +109,10 @@ class FileSystemListQuerySerializer(serializers.Serializer):
default=False,
help_text="Include meta.content_type for notebooks and insights on this page, without their contents.",
)
+ include_tags = serializers.BooleanField(
+ default=False,
+ help_text="Include meta.tags, the tag names, for dashboards and insights on this page.",
+ )
class FileSystemDeleteQuerySerializer(serializers.Serializer):
@@ -579,13 +591,20 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return queryset
- def _add_object_types(self, results: builtins.list[dict[str, object]], *, include_content_type: bool) -> None:
+ def _add_object_types(
+ self, results: builtins.list[dict[str, object]], *, include_content_type: bool, include_tags: bool = False
+ ) -> None:
entry_types = ("notebook", "insight") if include_content_type else ("insight",)
+ tagged_types = {entry_type for entry_type, *_ in TAGGED_FILE_SYSTEM_TYPES} if include_tags else set()
entry_teams = {
str(entry_id): team_id
for entry_id, team_id in FileSystem.objects.filter(
team__project_id=self.team.project_id,
- id__in=[item["id"] for item in results if item.get("type") in entry_types],
+ id__in=[
+ item["id"]
+ for item in results
+ if item.get("type") in entry_types or item.get("type") in tagged_types
+ ],
).values_list("id", "team_id")
}
denied: set[tuple[str, str, int]] = set()
@@ -652,18 +671,50 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
if source_kind == "HogQLQuery":
content_types[(entry_type, team_id, ref)] = "application/sql"
+ tags_by_entry: dict[tuple[str, int, str], builtins.list[str]] = {}
+ if include_tags:
+ for entry_type, app_label, model_name, ref_field in TAGGED_FILE_SYSTEM_TYPES:
+ tag_refs: builtins.list[str] = []
+ for item in results:
+ ref = item.get("ref")
+ if (
+ item.get("type") == entry_type
+ and item.get("user_access_level") != "none"
+ and isinstance(ref, str)
+ and ref
+ ):
+ tag_refs.append(ref)
+ model = apps.get_model(app_label, model_name)
+ lookup_refs = _coerce_refs_for_lookup(model, ref_field, tag_refs)
+ if not lookup_refs:
+ continue
+ rows = model.objects.filter(
+ team__project_id=self.team.project_id, deleted=False, **{f"{ref_field}__in": lookup_refs}
+ ).values_list("pk", "team_id", ref_field)
+ key_by_pk = {pk: (team_id, str(ref)) for pk, team_id, ref in rows}
+ if not key_by_pk:
+ continue
+ tagged = TaggedItem.objects.for_objects(model, key_by_pk.keys()).values_list(
+ object_column_for(model), "tag__name"
+ )
+ for pk, tag_name in tagged:
+ team_id, ref = key_by_pk[pk]
+ if (entry_type, ref, team_id) not in denied:
+ tags_by_entry.setdefault((entry_type, team_id, ref), []).append(tag_name)
for item in results:
- if item.get("type") not in entry_types:
+ if item.get("type") not in entry_types and item.get("type") not in tagged_types:
continue
meta = item.get("meta")
metadata = {**(meta if isinstance(meta, dict) else {})}
team_id = entry_teams.get(str(item["id"]), -1)
ref = str(item.get("ref"))
+ if include_tags and item.get("type") in tagged_types:
+ metadata["tags"] = sorted(tags_by_entry.get((str(item["type"]), team_id, ref), []))
if item.get("type") == "insight":
metadata["insight_type"] = insight_types.get((team_id, ref))
if metadata["insight_type"] == "bi":
item["href"] = f"/bi/{ref}"
- if include_content_type:
+ if include_content_type and item.get("type") in entry_types:
metadata["content_type"] = content_types.get((str(item["type"]), team_id, ref), "application/json")
item["meta"] = metadata
@@ -682,6 +733,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
self._add_object_types(
response.data.get("results", []),
include_content_type=query_serializer.validated_data["include_content_type"],
+ include_tags=query_serializer.validated_data["include_tags"],
)
return response
diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.py
index 073a20faf672..b855b646dae9 100644
--- a/posthog/api/file_system/test/test_file_system.py
+++ b/posthog/api/file_system/test/test_file_system.py
@@ -7,6 +7,7 @@ import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.db import connection
from django.test import SimpleTestCase
@@ -30,6 +31,8 @@ from posthog.models import OrganizationMembership, Project, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.file_system.file_system import FileSystem
from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
+from posthog.models.tag import Tag
+from posthog.models.tagged_item import TaggedItem
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
from products.access_control.backend.models.access_control import AccessControl
@@ -69,6 +72,26 @@ class TestFileSystemAPI(APIBaseTest):
self.assertEqual(response_data["count"], 0)
self.assertEqual(response_data["results"], [])
+ def test_list_includes_tags_only_on_request(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name="Revenue")
+ insight = Insight.objects.create(team=self.team, short_id="tagged", name="Signups")
+ for tag_name, obj in (("finance", dashboard), ("weekly", dashboard), ("growth", insight)):
+ tag, _ = Tag.objects.get_or_create(name=tag_name, team=self.team)
+ TaggedItem.objects.create(
+ tag=tag, team=self.team, content_type=ContentType.objects.get_for_model(type(obj)), object_id=obj.id
+ )
+
+ plain = self.client.get(f"/api/projects/{self.team.id}/file_system/", {"depth": "3"}).json()["results"]
+ self.assertNotIn("tags", next(item["meta"] for item in plain if item["type"] == "dashboard"))
+
+ tagged = self.client.get(f"/api/projects/{self.team.id}/file_system/", {"depth": "3", "include_tags": "true"})
+ self.assertEqual(tagged.status_code, 200, tagged.content)
+ by_ref = {
+ (item["type"].split("/")[0], item["ref"]): item["meta"].get("tags") for item in tagged.json()["results"]
+ }
+ self.assertEqual(by_ref[("dashboard", str(dashboard.id))], ["finance", "weekly"])
+ self.assertEqual(by_ref[("insight", "tagged")], ["growth"])
+
@parameterized.expand([(False,), (True,)])
def test_list_content_types_without_object_contents(self, include_content_type: bool) -> None:
markdown = Notebook.objects.create(
diff --git a/products/canvas/frontend/newCanvas/canvasNewLogic.ts b/products/canvas/frontend/newCanvas/canvasNewLogic.ts
index 9b73f00c36c0..c6c9e23bc70c 100644
--- a/products/canvas/frontend/newCanvas/canvasNewLogic.ts
+++ b/products/canvas/frontend/newCanvas/canvasNewLogic.ts
@@ -6,6 +6,7 @@ import posthog from 'posthog-js'
import { toast } from '@posthog/quill'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { withBackLink } from 'scenes/analytics/analyticsBackLink'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'
@@ -305,7 +306,7 @@ export const canvasNewLogic = kea<canvasNewLogicType>([
breadcrumbs: [
() => [],
(): Breadcrumb[] => [
- { key: 'views', name: 'Views', path: urls.views() },
+ { key: 'analytics', name: 'Analytics', path: urls.analyticsList() },
{ key: 'CanvasNew', name: 'New canvas' },
],
],
@@ -375,7 +376,7 @@ export const canvasNewLogic = kea<canvasNewLogicType>([
})
}
if (stillOnStartPage()) {
- router.actions.replace(urls.canvasDetail(canvas.id))
+ router.actions.replace(withBackLink(urls.canvasDetail(canvas.id)))
}
} finally {
actions.sendFinished()
@@ -417,7 +418,7 @@ export const canvasNewLogic = kea<canvasNewLogicType>([
})
}
if (removeProjectIdIfPresent(router.values.location.pathname) === urls.canvasNew()) {
- router.actions.replace(urls.canvasDetail(canvas.id))
+ router.actions.replace(withBackLink(urls.canvasDetail(canvas.id)))
}
} finally {
actions.startBlankFinished()
diff --git a/products/canvas/frontend/scene/canvasSceneLogic.ts b/products/canvas/frontend/scene/canvasSceneLogic.ts
index 59398b0cb941..2e006533d0cf 100644
--- a/products/canvas/frontend/scene/canvasSceneLogic.ts
+++ b/products/canvas/frontend/scene/canvasSceneLogic.ts
@@ -2,7 +2,6 @@ import {
MakeLogicType,
actions,
afterMount,
- beforeUnmount,
connect,
getContext,
kea,
@@ -19,14 +18,15 @@ import posthog from 'posthog-js'
import { toast } from '@posthog/quill'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { analyticsBackLink } from 'scenes/analytics/analyticsBackLink'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
-import { todayViewsLogic } from '~/layout/today/todayViewsLogic'
import { Breadcrumb, SidePanelTab, UserType } from '~/types'
import { runStreamLogic } from 'products/posthog_ai/frontend/api/logics'
@@ -208,13 +208,6 @@ export interface canvasSceneLogicActions {
canvasId: string
tab: import('../sidePanel/canvasPanelTabs').CanvasPanelTab
} // canvasSidePanelLogic
- setOpenCanvasBuilding: (
- canvasId: string,
- building: boolean | null
- ) => {
- building: boolean | null
- canvasId: string
- } // todayViewsLogic
buildAction: (
action: CanvasBuildActionActionEnumApi,
buildId: string
@@ -422,7 +415,13 @@ export interface canvasSceneLogicMeta {
isGenerating: boolean,
buildStatus: CanvasBuildStatus
) => boolean
- breadcrumbs: (canvas: CanvasApi | null, space: CanvasSpace | null, arg: string) => Breadcrumb[]
+ breadcrumbs: (
+ canvas: CanvasApi | null,
+ space: CanvasSpace | null,
+ arg: string,
+ searchParams: Record<string, any>,
+ featureFlags: FeatureFlagsSet
+ ) => Breadcrumb[]
}
}
@@ -452,14 +451,7 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([
['user'],
],
// Connecting keeps the Views sidebar's logic mounted, so it knows this canvas's state when it opens.
- actions: [
- canvasNewLogic,
- ['clearStartHandoff'],
- canvasSidePanelLogic,
- ['openTab'],
- todayViewsLogic,
- ['setOpenCanvasBuilding'],
- ],
+ actions: [canvasNewLogic, ['clearStartHandoff'], canvasSidePanelLogic, ['openTab']],
})),
actions({
renameCanvas: (name: string) => ({ name }),
@@ -806,20 +798,37 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([
!!view && (isGenerating || buildStatus === 'building'),
],
breadcrumbs: [
- (s) => [s.canvas, s.space, (_, props: CanvasSceneLogicProps) => props.id],
- (canvas: CanvasApi | null, space: CanvasSpace | null, id: string): Breadcrumb[] => [
- ...(space
- ? [{ key: 'canvas-space', name: canvasSpaceLabel(space), path: urls.taskSpace(space.id) }]
- : []),
- { key: ['CanvasDetail', id], name: canvas?.name ?? 'Canvas' },
+ (s) => [
+ s.canvas,
+ s.space,
+ (_, props: CanvasSceneLogicProps) => props.id,
+ router.selectors.searchParams,
+ featureFlagLogic.selectors.featureFlags,
],
+ (
+ canvas: CanvasApi | null,
+ space: CanvasSpace | null,
+ id: string,
+ searchParams: Record<string, any>,
+ featureFlags: FeatureFlagsSet
+ ): Breadcrumb[] => {
+ // The Analytics list that opened the canvas names the way back, like the dashboard scene allows.
+ const backLink = analyticsBackLink(searchParams, featureFlags)
+ return [
+ ...(backLink
+ ? [{ key: backLink.url, name: backLink.name, path: backLink.url }]
+ : space
+ ? [{ key: 'canvas-space', name: canvasSpaceLabel(space), path: urls.taskSpace(space.id) }]
+ : []),
+ { key: ['CanvasDetail', id], name: canvas?.name ?? 'Canvas' },
+ ]
+ },
],
}),
listeners(({ actions, values, props, cache }) => ({
reportBusy: () => {
if (cache.reportedBusy !== values.busy) {
cache.reportedBusy = values.busy
- actions.setOpenCanvasBuilding(props.id, values.busy)
}
},
loadViewSuccess: ({ view }) => {
@@ -973,8 +982,6 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([
try {
const canvas = await canvasesPartialUpdate(String(values.currentProjectId), props.id, { name: trimmed })
actions.canvasUpdated(canvas)
- // The Views sidebar lists canvases by name.
- todayViewsLogic.findMounted()?.actions.loadRecentViews()
} catch (error) {
toast.error({
title: "Couldn't rename the canvas",
@@ -1044,7 +1051,6 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([
const unrestored = await restoreCanvasTasks(projectId, restoreTasks)
actions.canvasUpdated(updated)
actions.loadSpace()
- todayViewsLogic.findMounted()?.actions.loadRecentViews()
captureCanvasAction('visibility_change', { ...properties, channel_id: spaceId, success: true })
toast.success(
visibility
@@ -1203,7 +1209,4 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([
actions.loadBuilds()
actions.syncSidePanel()
}),
- beforeUnmount(({ actions, props }) => {
- actions.setOpenCanvasBuilding(props.id, null)
- }),
])
diff --git a/products/canvas/manifest.tsx b/products/canvas/manifest.tsx
index 2f3164d4ad20..a0b11e2a2170 100644
--- a/products/canvas/manifest.tsx
+++ b/products/canvas/manifest.tsx
@@ -45,7 +45,7 @@ export const manifest: ProductManifest = {
// Canvases open only under the Today navigation, so the old tree's type filters hide them with it.
flag: FEATURE_FLAGS.TODAY_RAIL_NAV,
href: (ref: string) => urls.canvasDetail(ref),
- listHref: () => urls.canvases(),
+ listHref: () => urls.analyticsList({ type: 'canvas' }),
iconColor: ['var(--color-product-tasks-light)', 'var(--color-product-tasks-dark)'],
filterKey: 'canvas',
},
diff --git a/products/product_analytics/frontend/insights/insightScene/InsightPageHeader.tsx b/products/product_analytics/frontend/insights/insightScene/InsightPageHeader.tsx
index 695fea9dfdc5..783739cc2118 100644
--- a/products/product_analytics/frontend/insights/insightScene/InsightPageHeader.tsx
+++ b/products/product_analytics/frontend/insights/insightScene/InsightPageHeader.tsx
@@ -32,6 +32,7 @@ import { AccessControlLevel, AccessControlResourceType, InsightLogicProps, ItemM
import { areAlertsSupportedForInsight } from 'products/alerts/frontend/logic/insightAlertsLogic'
import { insightModalsLogic } from 'products/product_analytics/frontend/insights/insightScene/insightModalsLogic'
import { InsightSaveButton } from 'products/product_analytics/frontend/insights/insightScene/InsightSaveButton'
+import { InsightShareMenu } from 'products/product_analytics/frontend/insights/insightScene/InsightShareMenu'
import { InsightSceneMenuBar } from './sidePanel/InsightSceneMenuBar'
import { InsightSidePanelContent } from './sidePanel/InsightSidePanelContent'
@@ -83,6 +84,7 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: In
typeof lastBreadcrumb?.name === 'string' ? lastBreadcrumb.name : insight.name || insight.derived_name
const metricsAlertsEnabled = useFeatureFlag('METRICS')
+ const spacesEnabled = useFeatureFlag('TODAY_RAIL_NAV')
const biEnabled = useFeatureFlag('SQL_EDITOR_BI_MODE')
const canCreateAlertForInsight = areAlertsSupportedForInsight(query, { metricsAlertsEnabled })
@@ -181,6 +183,10 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: In
</LemonButton>
)}
+ {insightMode !== ItemMode.Edit && isPersistedInsight && spacesEnabled && (
+ <InsightShareMenu insight={insight} />
+ )}
+
{insightMode !== ItemMode.Edit && isPersistedInsight && (
<InsightSubscribeProminentButton
insightShortId={insight.short_id!}
diff --git a/products/product_analytics/frontend/insights/insightScene/InsightScene.tsx b/products/product_analytics/frontend/insights/insightScene/InsightScene.tsx
index 1e75ae2d17b7..eb23190f1ab4 100644
--- a/products/product_analytics/frontend/insights/insightScene/InsightScene.tsx
+++ b/products/product_analytics/frontend/insights/insightScene/InsightScene.tsx
@@ -4,6 +4,7 @@ import { useEffect } from 'react'
import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { withBackLink } from 'scenes/analytics/analyticsBackLink'
import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -34,7 +35,7 @@ export function InsightScene(): JSX.Element {
insightMode === ItemMode.Edit
) {
if (isBIVisualizationNode(insight.query) && !biEnabled) {
- router.actions.replace(urls.insightView(insightId))
+ router.actions.replace(withBackLink(urls.insightView(insightId)))
return
}
const editorUrl = isBIVisualizationNode(insight.query) ? urls.businessIntelligence : urls.sqlEditor
diff --git a/products/product_analytics/frontend/insights/insightScene/InsightShareMenu.tsx b/products/product_analytics/frontend/insights/insightScene/InsightShareMenu.tsx
new file mode 100644
index 000000000000..acaf88bb523a
--- /dev/null
+++ b/products/product_analytics/frontend/insights/insightScene/InsightShareMenu.tsx
@@ -0,0 +1,64 @@
+import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+import { useEffect } from 'react'
+
+import { IconShare } from '@posthog/icons'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
+import { analyticsShareLogic, shareTargetKey } from 'scenes/analytics/analyticsShareLogic'
+import { ShareToSpaceModal } from 'scenes/analytics/ShareToSpaceModal'
+import { urls } from 'scenes/urls'
+
+import { InsightShortId } from '~/types'
+
+interface InsightShareMenuProps {
+ insight: { short_id?: string | null; name?: string | null; derived_name?: string | null }
+}
+
+/**
+ * The Share menu of a saved insight under the Today navigation. It lives apart from the header so the
+ * spaces logics, and the project tree they load, mount only for people with the flag.
+ */
+export function InsightShareMenu({ insight }: InsightShareMenuProps): JSX.Element | null {
+ const { push } = useActions(router)
+ const { openShareToSpace, loadItemSpace } = useActions(analyticsShareLogic)
+ const { itemSpaces } = useValues(analyticsShareLogic)
+ const shortId = insight.short_id
+ const insightName = insight.name || insight.derived_name || 'Untitled insight'
+ const insightSpace = shortId ? itemSpaces[shareTargetKey({ type: 'insight', ref: shortId })] : undefined
+
+ useEffect(() => {
+ if (shortId && insightSpace === undefined) {
+ loadItemSpace({ type: 'insight', ref: shortId, name: insightName })
+ }
+ }, [shortId, insightSpace, insightName, loadItemSpace])
+
+ if (!shortId) {
+ return null
+ }
+ return (
+ <>
+ <LemonMenu
+ items={[
+ {
+ label: insightSpace ? `Move from ${insightSpace}` : 'Add to a collection',
+ icon: <IconShare />,
+ onClick: () => openShareToSpace({ type: 'insight', ref: shortId, name: insightName }),
+ 'data-attr': 'insight-share-into-space',
+ },
+ {
+ label: 'Share publicly or embed',
+ onClick: () => push(urls.insightSharing(shortId as InsightShortId)),
+ 'data-attr': 'insight-share-publicly',
+ },
+ ]}
+ >
+ <LemonButton type="secondary" size="small" icon={<IconShare />} data-attr="insight-share-menu">
+ Share
+ </LemonButton>
+ </LemonMenu>
+ <ShareToSpaceModal />
+ </>
+ )
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 77ce58fe3f1b..2de400f5cc16 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -126459,6 +126459,10 @@ export namespace Schemas {
* Include meta.content_type for notebooks and insights on this page, without their contents.
*/
include_content_type?: boolean;
+ /**
+ * Include meta.tags, the tag names, for dashboards and insights on this page.
+ */
+ include_tags?: boolean;
/**
* Number of results to return per page.
*/
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index 641e540c60b0..4164d3a66f7f 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -214,6 +214,31 @@
"params": [],
"scope": "project"
},
+ "analytics": {
+ "template": "/analytics",
+ "params": [],
+ "scope": "project"
+ },
+ "analyticsList": {
+ "template": "/analytics/all",
+ "params": [],
+ "scope": "project"
+ },
+ "analyticsMine": {
+ "template": "/analytics/mine",
+ "params": [],
+ "scope": "project"
+ },
+ "analyticsProductHome": {
+ "template": "/analytics/product-analytics",
+ "params": [],
+ "scope": "project"
+ },
+ "analyticsSpaces": {
+ "template": "/analytics/spaces",
+ "params": [],
+ "scope": "project"
+ },
"annotation": {
"template": "/data-management/annotations/{id}",
"params": ["id"],
@@ -1839,16 +1864,6 @@
"params": [],
"scope": "project"
},
- "views": {
- "template": "/views",
- "params": [],
- "scope": "project"
- },
- "viewsNew": {
- "template": "/views/new",
- "params": [],
- "scope": "project"
- },
"visualReviewFlakiness": {
"template": "/visual-review/repos/{repoOwner}/{repoName}/flakiness",
"params": ["repoOwner", "repoName"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index ad5f0127e7c1..78faf5ac326f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/verify_email\n/views\n/views/new\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/analytics\n/analytics/all\n/analytics/mine\n/analytics/product-analytics\n/analytics/spaces\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/verify_email\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},