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(analytics): add pinned items to analytics sidebar (#124120)

Mike Warren2fb2522d902c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a280bfc473c5..926b69289cc7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9975,9 +9975,9 @@ snapshots:
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.1c7c84c6c869ae3a1578a031c5451cd839b8a60870c0fe988a2bad424c510432.BG4IUVQvKulDFLhazoBcvGoarwURK1Zu_L6Z7nRXDps
+ hash: v1.k794b7964.e2b3df655260624d8df50a1bbb9a18eaad654d12da3ef512a592072aa5c2382e.Aht2-rzvHA_nth4ZO2tbqY1JHHa8WvMlFqu9OdQT2cA
scenes-app-analytics--list--light:
- hash: v1.k794b7964.78906bdd72263285cee826a1b1c8fdfb0b89387234fe2dcdaf3269384793f159.EbVW9wQWemeAUl1ayHtCcyRJzP8NslB-vSjnAXshf0c
+ hash: v1.k794b7964.93c2da87f3755d44ff76151998d316d8bbfe331338d6b0926f807c3f62736a0f.A2fR-fWKVFojN-VZneH3-6ql3IbWtygSKCAtL8RBHBI
scenes-app-analytics--list-empty--dark:
hash: v1.k794b7964.7c39061eb8737ec9ba5b858ad3ffa9167688f7bdf3c3e5be524c87fc81f7daf4.4pPWDF6HSXEhVN0CubKXJVzgVI0lMVaJVX49tqlmU0M
scenes-app-analytics--list-empty--light:
@@ -9987,33 +9987,33 @@ snapshots:
scenes-app-analytics--list-error--light:
hash: v1.k794b7964.3b77e8cfcf643e336919da33b6a12bcc2e9943eda7bbaac535f875a62cd94b07.4wktcNBCgjAQ7oaVK18hX6ofrRkeFN6g08ZdBdF-SUc
scenes-app-analytics--list-filtered--dark:
- hash: v1.k794b7964.44eb47417035f3b62861dad79acea53fc949070bab6f07f144adacb35c3c23bd.bnHNEeCNqMbIDlVCDjuh6ts4FGLp1XvulEWlyhCiWN8
+ hash: v1.k794b7964.4d17b600e47c392b1260f8ebdcc642430c4495cdf0b7f548ff0c192d073da754.-f7FCa_tpsGq8KDl-Mj3QTG_PvrL1gAMS9uPIMymcko
scenes-app-analytics--list-filtered--light:
- hash: v1.k794b7964.75b7eca92b8ad7e321f78513f4fb33383f517cde5e4ae7bcac160b1259543c4f.tYcmIIkK_KR_C5Iov8CLAP-v9k65O6Ys8I8apAfmG1U
+ hash: v1.k794b7964.113ef44c356f429d8607b4b19759d158dd43e83aeed955ce051191d4802ddc58.bZ_OygxLLs_MXpKYOOGw_gsaDGBeKE2tuthP-BYISU0
scenes-app-analytics--list-new-insight-dialog--dark:
- hash: v1.k794b7964.45c16754a22f5cd764ec0bbe81c5408e0ef66afecb667585b18f761d3041bdb9.guaW1CUKOZ-Jy9OWDyCDLhOyCzPArrUSB0dEiEBwD20
+ hash: v1.k794b7964.7351c67a99aaca7572b229a18e3a012e646fe186dcdf519c8cdbb941a64d22cc.ZGEpI7Yj8iTpzQW8hWyA6b3kWackb6oecz3stYXmd7k
scenes-app-analytics--list-new-insight-dialog--light:
- hash: v1.k794b7964.590d2207f39d9035ac2bf84d91e113ef618a4802635aab5740ff2a1b1ad3e27f.z3HMfF_fcbYYLF8vFl2PRijsWb-_6-FaW9Hqxg8p19s
+ hash: v1.k794b7964.fd968168e3a45e796d6ab780973d0cc2f00d9d4df8c928e72929ed0c5c43329e.tEYr0M-xJVRnN3y60n79st-JCzaN2Xui2MagB24bA4s
scenes-app-analytics--list-no-matches--dark:
- hash: v1.k794b7964.ceb8e53319e50984dd11887fca87d887b42c7e1a659ce40ac2986d792f0904d7.vYLLOu-3-RNpVNuDhoB1Mw1HicAzpsua4A9-PnawtVc
+ hash: v1.k794b7964.d59de941410f1403ad53f475891cab5abf0f108b1d28d3cd214b8d1434a8074e.FVmKqWG1tDJlFyuCYKiYmHYjaOmVqxFw7e1yntqlahM
scenes-app-analytics--list-no-matches--light:
- hash: v1.k794b7964.39ce5f1e3425267d0314d9c95df93627baf8dcc311db559d70b8ab89a788df83.0eVSUlUGcImwkGH3tnJpiTD0dyzCKwwVrhDGfmGemVU
+ hash: v1.k794b7964.57a666ae9920becaf7fea2a5aa5b148f025a8fdd1929f80959334ab94f872cee.6il2qKsu7TdRenfqTvosPOh0vdYz04wGRtdsFsCsXpY
scenes-app-analytics--list-share-dialog--dark:
hash: v1.k794b7964.5d73b355d980270198e7ce6c2f8df4ad6231f74517b815e3ec48db433a612b41.qG99vq4HpkVoboXGFkQHI0RTQxHCzHbH8BIBcSJiG54
scenes-app-analytics--list-share-dialog--light:
hash: v1.k794b7964.d1e4f3264ce1ce3cc926bd0fd7ca481116962c956da863d14f55a18eab5ab03c.3sPci23BXnf6Gj2PoDh1z6PhFaXePUVwibiEkKVsJjA
scenes-app-analytics--list-space--dark:
- hash: v1.k794b7964.ace1ba35b28b32792d1d864a7d62287d03cff4f3e1c43a324fc6118e53eb4735.SbDceA6BYtuaH3Y5_JeybqZsbwpjPjUMUFtR6Sss8c0
+ hash: v1.k794b7964.690ac92a7e0541239bf9f34af2afb37190d8bc9ff05ff4295988db3240e871c1.yp5BZHegpEJknJt6C5j2FOvmQuAXmZskWMnql__T3pY
scenes-app-analytics--list-space--light:
- hash: v1.k794b7964.fe34ef2a5d95d0525dbee232204e4d4f9cd3870b56d1431f10a31829b9fd84a9.mJXzesK_WAXem-kNAjWLubkTOT-IKHsoOxCxLsbzO3Y
+ hash: v1.k794b7964.b0b3d3663806b923eb1da41c84dfd4e230f2f8197e70eb4ef6c27b5901df58e0.y2y2wdLWEbyQnIJDZCior34SZD5NQq3Swz4iziJLA1w
scenes-app-analytics--mine--dark:
- hash: v1.k794b7964.76628f683198e65ad97a09eb2c97f2b482d150b8e3fa5ee89f101e152ab9b45a.7zkevOg9kF0Ou6YlMeOfcH5ptFi_mLuZPDHwcjCjz58
+ hash: v1.k794b7964.9dc8cb3ff02d9d3e02053feeee8b7d601946628556f69ba82cb10b9a873a9d8b.uFod9Cu6f-58SYwGLFveqOnezwgUePJD8FLatb46Fmw
scenes-app-analytics--mine--light:
- hash: v1.k794b7964.2ee049cee8f63fd3cc1677a81d5c539426169504761b9c14d398a731f684e792.K7DLYr7NNlIho4mIeJa4-1-6lvUtvmLxWWgmzJntYts
+ hash: v1.k794b7964.9e10193fe52e3b6ac811b27aa21a70e06a52c74faa3a36c754c27e8df2d1565a.UCOaf7E2z1dOuP2cHWSLXiIe1MdRrDad2gfnDCu-dKE
scenes-app-analytics--spaces--dark:
- hash: v1.k794b7964.dda48c6563a285f17b8197f8227e1452c0e344d08bd5eb8d52235ab4ddc628a2.7HFlW-y05cw7zoua83w90JfInwTZ0db4ncKh-n9N4yA
+ hash: v1.k794b7964.83d713490aa8c83bb30d3e7ad6b22a77fe043313d8b28d8006d758bd0d2e8853.m8_tPhCdyW6UkHKwcyVy7ealY2OscaIJBFpPTWvzrZY
scenes-app-analytics--spaces--light:
- hash: v1.k794b7964.6c394a707ec271f3e088e28506e05b68a6df12a8a6e400893e904f6e8714c192.EDHy76nNpXWdILAfWeCsQRaqrujIDe2VpEOLtkjGvqk
+ hash: v1.k794b7964.ba7d6366ac4c9a8396d50b4179c48b78e0b909e06be3bfc57531677ffd771a02.p9n5hEHhSfnpjHOOApRU0PCcNfvzZS3m-WJNHp4f9uc
scenes-app-annotations--annotations--dark:
hash: v1.k794b7964.651aae7146d31971a314f627499eafdaa3d35933cde8dd0ad47abc6eab722148.H9u02T71vFBWS4vd-5sVVqacwrqXc9xeeOHs7b4qnL4
scenes-app-annotations--annotations--light:
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index 82891d926da5..f7e3c699af12 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -296,8 +296,12 @@ export interface projectTreeDataLogicActions {
addLoadedUsers: (users: UserBasicType[]) => {
users: UserBasicType[]
}
- addShortcutItem: (item: FileSystemEntry) => {
+ addShortcutItem: (
+ item: FileSystemEntry,
+ successMessage?: string
+ ) => {
item: FileSystemEntry
+ successMessage: string | undefined
}
addShortcutItemFailure: (
error: string,
@@ -310,11 +314,13 @@ export interface projectTreeDataLogicActions {
shortcutData: FileSystemEntry[],
payload?: {
item: FileSystemEntry
+ successMessage: string | undefined
}
) => {
shortcutData: FileSystemEntry[]
payload?: {
item: FileSystemEntry
+ successMessage: string | undefined
}
}
createSavedItem: (savedItem: FileSystemEntry) => {
@@ -330,8 +336,12 @@ export interface projectTreeDataLogicActions {
deleteSavedItem: (savedItem: FileSystemEntry) => {
savedItem: FileSystemEntry
}
- deleteShortcut: (id: FileSystemEntry['id']) => {
+ deleteShortcut: (
+ id: FileSystemEntry['id'],
+ successMessage?: string
+ ) => {
id: string
+ successMessage: string | undefined
}
deleteShortcutFailure: (
error: string,
@@ -344,11 +354,13 @@ export interface projectTreeDataLogicActions {
shortcutData: FileSystemEntry[],
payload?: {
id: string
+ successMessage: string | undefined
}
) => {
shortcutData: FileSystemEntry[]
payload?: {
id: string
+ successMessage: string | undefined
}
}
deleteTypeAndRef: (
@@ -747,8 +759,8 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
setLastNewFolder: (folder: string | null) => ({ folder }),
- addShortcutItem: (item: FileSystemEntry) => ({ item }),
- deleteShortcut: (id: FileSystemEntry['id']) => ({ id }),
+ addShortcutItem: (item: FileSystemEntry, successMessage?: string) => ({ item, successMessage }),
+ deleteShortcut: (id: FileSystemEntry['id'], successMessage?: string) => ({ id, successMessage }),
loadShortcuts: true,
reorderShortcuts: (orderedIds: NonNullable<FileSystemEntry['id']>[]) => ({ orderedIds }),
// Resolves a sibling drag ('before' / 'after' a target row) into a new ordered list and
@@ -1077,7 +1089,7 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
)
return response.results.map(withProductShortcutHref)
},
- addShortcutItem: async ({ item }) => {
+ addShortcutItem: async ({ item, successMessage }) => {
const shortcutItem = shortcutFromEntry(item)
const { shortcut: response, created } = await api.fileSystemShortcuts.create(shortcutItem)
// A star the user already has, for example from another tab, is not a new add.
@@ -1087,7 +1099,7 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
item_name: shortcutItem.path,
})
}
- lemonToast.success('Added to starred')
+ lemonToast.success(successMessage ?? 'Added to starred')
// The API returns the existing shortcut when the item is already starred, so
// appending it unconditionally would show the same star twice until a reload.
if (values.shortcutData.some((shortcut) => shortcut.id === response.id)) {
@@ -1107,14 +1119,14 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
// when kea-loaders' success handler sets `shortcutData` to the resolved value.
return values.shortcutData
},
- deleteShortcut: async ({ id }) => {
+ deleteShortcut: async ({ id, successMessage }) => {
const shortcut = values.shortcutData.find((s) => s.id === id)
await api.fileSystemShortcuts.delete(id)
posthog.capture('navbar starred item removed', {
item_type: shortcut?.type ?? 'unknown',
item_name: shortcut?.path ?? 'unknown',
})
- lemonToast.success('Removed from starred')
+ lemonToast.success(successMessage ?? 'Removed from starred')
return values.shortcutData.filter((s) => s.id !== id)
},
},
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts
index bea20164ec36..c06f9db6dcdb 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts
+++ b/frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts
@@ -79,11 +79,13 @@ export interface navProductsTabLogicActions {
payload?:
| {
id: string
+ successMessage: string | undefined
}
| undefined
) => {
payload?: {
id: string
+ successMessage: string | undefined
}
shortcutData: FileSystemEntry[]
} // projectTreeDataLogic
diff --git a/frontend/src/layout/today/TodayAnalyticsSidebar.tsx b/frontend/src/layout/today/TodayAnalyticsSidebar.tsx
index 9e3aa1c37774..abff328f2b55 100644
--- a/frontend/src/layout/today/TodayAnalyticsSidebar.tsx
+++ b/frontend/src/layout/today/TodayAnalyticsSidebar.tsx
@@ -2,16 +2,16 @@ import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { Fragment, useMemo } from 'react'
-import { IconBell, IconBox, IconList, IconNotification, IconPerson, IconPinFilled } from '@posthog/icons'
-import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'
+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 { AnalyticsPinButton } from 'scenes/analytics/AnalyticsPinButton'
+import { analyticsPinnedLogic } from 'scenes/analytics/analyticsPinnedLogic'
import { AnalyticsSpaceGlyph } from 'scenes/analytics/AnalyticsSpaceGlyph'
-import { analyticsSpacesLogic } from 'scenes/analytics/analyticsSpacesLogic'
import { AnalyticsTypeIcon } from 'scenes/analytics/AnalyticsTypeIcon'
-import { ANALYTICS_TYPE_INFO } from 'scenes/analytics/analyticsUtils'
+import { ANALYTICS_TYPE_INFO, AnalyticsType } from 'scenes/analytics/analyticsUtils'
import { urls } from 'scenes/urls'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
@@ -67,12 +67,20 @@ const EXPLAINERS = {
},
} satisfies Record<string, TodayExplainerPreview>
-/** The Analytics sub-nav: the ways to browse, pinned collections, recently viewed items, PostHog's own analytics, and what to keep an eye on. */
+function AnalyticsItemIcon({ type }: { type: AnalyticsType }): JSX.Element {
+ return (
+ // eslint-disable-next-line react/forbid-dom-props
+ <span style={{ color: ANALYTICS_TYPE_INFO[type].color }}>
+ <AnalyticsTypeIcon type={type} />
+ </span>
+ )
+}
+
+/** The Analytics sub-nav: the ways to browse, pinned items and collections, recently viewed items, PostHog's own analytics, and what to keep an eye on. */
export function TodayAnalyticsSidebar(): JSX.Element {
const { collapsedSections, fromPostHog, recentAnalytics } = useValues(todayAnalyticsLogic)
const { toggleSection } = useActions(todayAnalyticsLogic)
- const { pinnedSpaces, pinning } = useValues(analyticsSpacesLogic)
- const { togglePin } = useActions(analyticsSpacesLogic)
+ const { pinnedAnalytics } = useValues(analyticsPinnedLogic)
const { location, searchParams } = useValues(router)
const path = removeProjectIdIfPresent(location.pathname)
const isOpen = (section: TodayAnalyticsSection): boolean => !collapsedSections.includes(section)
@@ -96,14 +104,7 @@ export function TodayAnalyticsSidebar(): JSX.Element {
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"
- >
+ <div className="flex flex-col gap-px pb-2">
<TodayPreviewTrigger payload={EXPLAINERS.all}>
<TodayPaneRow
value="browse:all"
@@ -134,37 +135,60 @@ export function TodayAnalyticsSidebar(): JSX.Element {
dataAttr="analytics-sidebar-browse"
/>
</TodayPreviewTrigger>
- {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}
- action={
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="default"
- size="icon-sm"
- aria-label={`Unpin ${space.name}`}
- loading={pinning === space.path}
- onClick={() => togglePin(space)}
- data-attr="analytics-sidebar-unpin-space"
- />
- }
- >
- <IconPinFilled />
- </TooltipTrigger>
- <TooltipContent>Unpin</TooltipContent>
- </Tooltip>
- }
- dataAttr="analytics-sidebar-starred-space"
- />
- ))}
- </TodayPaneSection>
+ </div>
+ {pinnedAnalytics.length > 0 && (
+ <TodayPaneSection
+ label="Pinned"
+ open={isOpen('pinned')}
+ count={pinnedAnalytics.length}
+ showCount={false}
+ onToggle={() => toggleSection('pinned')}
+ dataAttr="analytics-section-pinned"
+ >
+ {pinnedAnalytics.map((pinned) =>
+ pinned.kind === 'collection' ? (
+ <TodayPaneRow
+ key={pinned.key}
+ value={`pinned:${pinned.key}`}
+ label={pinned.name}
+ icon={<AnalyticsSpaceGlyph name={pinned.name} />}
+ to={urls.analyticsList({ folder: pinned.path })}
+ active={openFolder === pinned.path}
+ action={
+ <AnalyticsPinButton
+ target={{ type: 'folder', ref: pinned.path, name: pinned.name }}
+ // pinned: tracking API, do not rename.
+ dataAttr="analytics-sidebar-unpin-space"
+ />
+ }
+ // pinned: tracking API, do not rename.
+ dataAttr="analytics-sidebar-starred-space"
+ />
+ ) : (
+ <TodayPaneRow
+ key={pinned.key}
+ value={`pinned:${pinned.key}`}
+ label={pinned.item.name}
+ icon={<AnalyticsItemIcon type={pinned.item.type} />}
+ to={pinned.item.href}
+ active={path === removeProjectIdIfPresent(pinned.item.href)}
+ action={
+ <AnalyticsPinButton
+ target={{
+ type: pinned.item.type,
+ ref: pinned.item.id,
+ name: pinned.item.name,
+ href: pinned.item.href,
+ }}
+ dataAttr="analytics-sidebar-unpin"
+ />
+ }
+ dataAttr="analytics-sidebar-pinned"
+ />
+ )
+ )}
+ </TodayPaneSection>
+ )}
{recentAnalytics.length > 0 && (
<TodayPaneSection
label="Recents"
@@ -180,14 +204,15 @@ export function TodayAnalyticsSidebar(): JSX.Element {
key={`${item.type}:${item.id}`}
value={`recent:${item.type}:${item.id}`}
label={item.name}
- icon={
- // eslint-disable-next-line react/forbid-dom-props
- <span style={{ color: ANALYTICS_TYPE_INFO[item.type].color }}>
- <AnalyticsTypeIcon type={item.type} />
- </span>
- }
+ icon={<AnalyticsItemIcon type={item.type} />}
to={item.href}
active={path === removeProjectIdIfPresent(item.href)}
+ action={
+ <AnalyticsPinButton
+ target={{ type: item.type, ref: item.id, name: item.name, href: item.href }}
+ dataAttr="analytics-sidebar-recent-pin"
+ />
+ }
dataAttr="analytics-sidebar-recent"
/>
))}
diff --git a/frontend/src/layout/today/todayAnalyticsLogic.test.ts b/frontend/src/layout/today/todayAnalyticsLogic.test.ts
index 7b47dfb3939e..e51fdd0da6ba 100644
--- a/frontend/src/layout/today/todayAnalyticsLogic.test.ts
+++ b/frontend/src/layout/today/todayAnalyticsLogic.test.ts
@@ -1,3 +1,8 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { fileSystemEntryToAnalytics } from 'scenes/analytics/analyticsUtils'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { useMocks } from '~/mocks/jest'
import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'
@@ -14,6 +19,9 @@ describe('todayAnalyticsLogic', () => {
'/api/projects/:team_id/notebooks/': { results: [], next: null },
'/api/projects/:team_id/dashboards/': { results: [], next: null },
'/api/projects/:team_id/insights/': { results: [], next: null },
+ '/api/projects/:team_id/file_system_shortcut/': {
+ results: [{ id: 'sc-pinned', type: 'insight/trends', path: 'Retention', ref: 'i2' }],
+ },
},
})
initKeaTests()
@@ -35,20 +43,35 @@ describe('todayAnalyticsLogic', () => {
expect(remounted.values.collapsedSections).toEqual(['monitor'])
})
- it('lists recently viewed analytics, insights included, and clears them when the shared list loads empty', () => {
+ it('lists recently viewed analytics up to the limit, leaving out pinned items, and clears them when the shared list loads empty', async () => {
const logic = todayAnalyticsLogic()
logic.mount()
+ await expectLogic(projectTreeDataLogic).toDispatchActions(['loadShortcutsSuccess'])
const row = (type: string, ref: string, name: string): FileSystemEntry =>
({ id: `fs-${ref}`, type, ref, path: `Unfiled/${name}`, meta: {} }) as FileSystemEntry
+ await expectLogic(logic, () =>
+ logic.actions.storeRecentAnalytics(
+ [row('insight', 'i1', 'Signups'), row('insight', 'i2', 'Retention')].flatMap(
+ (entry) => fileSystemEntryToAnalytics(entry) ?? []
+ )
+ )
+ )
+ .toDispatchActions(['storeRecentAnalytics'])
+ .toNotHaveDispatchedActions(['storeRecentAnalytics'])
+ expect(logic.values.recentAnalytics.map((item) => item.name)).toEqual(['Signups'])
+
recentItemsModel.actions.loadRecentsSuccess([
row('insight', 'i1', 'Signups'),
+ row('insight', 'i2', 'Retention'),
row('feature_flag', 'f1', 'New nav'),
row('dashboard', '7', 'Revenue'),
+ row('dashboard', '8', 'Costs'),
])
expect(logic.values.recentAnalytics.map((item) => [item.type, item.name])).toEqual([
['insight', 'Signups'],
['dashboard', 'Revenue'],
+ ['dashboard', 'Costs'],
])
recentItemsModel.actions.loadRecentsSuccess([])
diff --git a/frontend/src/layout/today/todayAnalyticsLogic.ts b/frontend/src/layout/today/todayAnalyticsLogic.ts
index 149264d73dc2..78d2544add1b 100644
--- a/frontend/src/layout/today/todayAnalyticsLogic.ts
+++ b/frontend/src/layout/today/todayAnalyticsLogic.ts
@@ -7,6 +7,7 @@ import { toast } from '@posthog/quill'
import api from 'lib/api'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getCurrentTeamIdOrNone, getCurrentUserIdOrNone } from 'lib/utils/getAppContext'
+import { analyticsPinnedLogic, pinKey } from 'scenes/analytics/analyticsPinnedLogic'
import {
AnalyticsItem,
FromPostHogItem,
@@ -20,7 +21,7 @@ import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'
// pinned: persisted section ids and the `section` property of `analytics section toggled`.
-export type TodayAnalyticsSection = 'browse' | 'recents' | 'monitor' | 'by-posthog'
+export type TodayAnalyticsSection = 'pinned' | 'recents' | 'monitor' | 'by-posthog'
export const DEFAULT_COLLAPSED_SECTIONS: TodayAnalyticsSection[] = []
@@ -37,6 +38,7 @@ const RECENTS_PERSIST_OPTIONS =
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayAnalyticsLogicValues {
+ pinnedShortcutIds: Map<string, string> // analyticsPinnedLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
recents: FileSystemEntry[] // recentItemsModel
recentsHasLoaded: boolean // recentItemsModel
@@ -83,11 +85,12 @@ export interface todayAnalyticsLogicActions {
export interface todayAnalyticsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
fromPostHog: (featureFlags: FeatureFlagsSet) => FromPostHogItem[]
- freshRecentAnalytics: (recents: FileSystemEntry[]) => AnalyticsItem[]
+ freshRecentAnalytics: (recents: FileSystemEntry[], pinnedShortcutIds: Map<string, string>) => AnalyticsItem[]
recentAnalytics: (
recentsHasLoaded: boolean,
freshRecentAnalytics: AnalyticsItem[],
- savedRecentAnalytics: AnalyticsItem[]
+ savedRecentAnalytics: AnalyticsItem[],
+ pinnedShortcutIds: Map<string, string>
) => AnalyticsItem[]
}
}
@@ -102,7 +105,14 @@ export type todayAnalyticsLogicType = MakeLogicType<
export const todayAnalyticsLogic = kea<todayAnalyticsLogicType>([
path(['layout', 'today', 'todayAnalyticsLogic']),
connect(() => ({
- values: [featureFlagLogic, ['featureFlags'], recentItemsModel, ['recents', 'recentsHasLoaded']],
+ values: [
+ featureFlagLogic,
+ ['featureFlags'],
+ recentItemsModel,
+ ['recents', 'recentsHasLoaded'],
+ analyticsPinnedLogic,
+ ['pinnedShortcutIds'],
+ ],
actions: [projectTreeDataLogic, ['createSavedItem']],
})),
actions({
@@ -153,21 +163,27 @@ export const todayAnalyticsLogic = kea<todayAnalyticsLogicType>([
(featureFlags: FeatureFlagsSet): FromPostHogItem[] => fromPostHogItems(featureFlags),
],
// The app loads recently viewed items once and keeps them, so this section needs no request of its own.
+ // Pinned items already show in the Pinned section, so Recents leaves them out before it applies the limit.
freshRecentAnalytics: [
- (s) => [s.recents],
- (recents: FileSystemEntry[]): AnalyticsItem[] =>
+ (s) => [s.recents, s.pinnedShortcutIds],
+ (recents: FileSystemEntry[], pinnedShortcutIds: Map<string, string>): AnalyticsItem[] =>
recents
.flatMap((entry) => {
const item = fileSystemEntryToAnalytics(entry)
- return item ? [item] : []
+ return item && !pinnedShortcutIds.has(pinKey(item.type, item.id)) ? [item] : []
})
.slice(0, TODAY_ANALYTICS_RECENTS_LIMIT),
],
// The saved list covers only the wait for the shared list. Once it has loaded, even empty, it is the answer.
recentAnalytics: [
- (s) => [s.recentsHasLoaded, s.freshRecentAnalytics, s.savedRecentAnalytics],
- (recentsHasLoaded: boolean, fresh: AnalyticsItem[], saved: AnalyticsItem[]): AnalyticsItem[] =>
- recentsHasLoaded ? fresh : saved,
+ (s) => [s.recentsHasLoaded, s.freshRecentAnalytics, s.savedRecentAnalytics, s.pinnedShortcutIds],
+ (
+ recentsHasLoaded: boolean,
+ fresh: AnalyticsItem[],
+ saved: AnalyticsItem[],
+ pinnedShortcutIds: Map<string, string>
+ ): AnalyticsItem[] =>
+ recentsHasLoaded ? fresh : saved.filter((item) => !pinnedShortcutIds.has(pinKey(item.type, item.id))),
],
}),
listeners(({ actions, values }) => ({
@@ -204,8 +220,13 @@ export const todayAnalyticsLogic = kea<todayAnalyticsLogicType>([
}
},
})),
- subscriptions(({ actions }) => ({
- // Saves what the section shows, so the next page load starts from it.
- recentAnalytics: (items: AnalyticsItem[]) => actions.storeRecentAnalytics(items),
+ subscriptions(({ actions, values }) => ({
+ // Saves what the section shows, so the next page load starts from it. Before the shared list loads, the
+ // section shows a filtered copy of the saved list, and saving that copy would start the subscription again.
+ recentAnalytics: (items: AnalyticsItem[]) => {
+ if (values.recentsHasLoaded) {
+ actions.storeRecentAnalytics(items)
+ }
+ },
})),
])
diff --git a/frontend/src/layout/today/todayProductsLogic.ts b/frontend/src/layout/today/todayProductsLogic.ts
index 5ec9f973fa6c..1ac9df8ba677 100644
--- a/frontend/src/layout/today/todayProductsLogic.ts
+++ b/frontend/src/layout/today/todayProductsLogic.ts
@@ -45,11 +45,19 @@ export interface todayProductsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayProductsLogicActions {
- addShortcutItem: (item: FileSystemEntry) => {
+ addShortcutItem: (
+ item: FileSystemEntry,
+ successMessage?: string | undefined
+ ) => {
item: FileSystemEntry
+ successMessage: string | undefined
} // projectTreeDataLogic
- deleteShortcut: (id: string) => {
+ deleteShortcut: (
+ id: string,
+ successMessage?: string | undefined
+ ) => {
id: string
+ successMessage: string | undefined
} // projectTreeDataLogic
setAllProductsOpen: (open: boolean) => {
open: boolean
diff --git a/frontend/src/lib/components/FileSystem/ItemSelectModal/itemSelectModalLogic.tsx b/frontend/src/lib/components/FileSystem/ItemSelectModal/itemSelectModalLogic.tsx
index 221128304bd5..722a2115ad07 100644
--- a/frontend/src/lib/components/FileSystem/ItemSelectModal/itemSelectModalLogic.tsx
+++ b/frontend/src/lib/components/FileSystem/ItemSelectModal/itemSelectModalLogic.tsx
@@ -46,8 +46,12 @@ export interface itemSelectModalLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface itemSelectModalLogicActions {
- addShortcutItem: (item: FileSystemEntry) => {
+ addShortcutItem: (
+ item: FileSystemEntry,
+ successMessage?: string | undefined
+ ) => {
item: FileSystemEntry
+ successMessage: string | undefined
} // projectTreeDataLogic
closeItemSelectModal: () => {
value: true
diff --git a/frontend/src/lib/components/Scenes/SceneMenuBarPinItem.tsx b/frontend/src/lib/components/Scenes/SceneMenuBarPinItem.tsx
new file mode 100644
index 000000000000..59480ed179d7
--- /dev/null
+++ b/frontend/src/lib/components/Scenes/SceneMenuBarPinItem.tsx
@@ -0,0 +1,45 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+
+import { IconPin, IconPinFilled } from '@posthog/icons'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { analyticsPinnedLogic, pinKey } from 'scenes/analytics/analyticsPinnedLogic'
+import { fileSystemBaseType, fileSystemEntryName, isAnalyticsType } from 'scenes/analytics/analyticsUtils'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { SceneMenuBarItem } from '~/layout/scenes/components/SceneMenuBar'
+
+import { sceneFileLogic } from './sceneFileLogic'
+
+/** The Today layout drops the File menu's project tree items, so the pin for an analytics item lives in Edit. */
+export function SceneMenuBarPinItem({ dataAttrKey }: { dataAttrKey: string }): JSX.Element | null {
+ useMountedLogic(sceneFileLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { projectTreeRefEntry } = useValues(projectTreeDataLogic)
+ const { pinnedShortcutIds, shortcutDataLoading } = useValues(analyticsPinnedLogic)
+ const { togglePinned } = useActions(analyticsPinnedLogic)
+ const type = fileSystemBaseType(projectTreeRefEntry?.type)
+ if (!featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] || !projectTreeRefEntry?.ref || !isAnalyticsType(type)) {
+ return null
+ }
+ const ref = projectTreeRefEntry.ref
+ const pinned = pinnedShortcutIds.has(pinKey(type, ref))
+ return (
+ <SceneMenuBarItem
+ disabled={shortcutDataLoading}
+ onClick={() =>
+ togglePinned({
+ type,
+ ref,
+ name: fileSystemEntryName(projectTreeRefEntry),
+ href: projectTreeRefEntry.href,
+ })
+ }
+ data-attr={pinned ? `${dataAttrKey}-menubar-unpin` : `${dataAttrKey}-menubar-pin`}
+ >
+ {pinned ? <IconPinFilled /> : <IconPin />}
+ {pinned ? 'Unpin from sidebar' : 'Pin to sidebar'}
+ </SceneMenuBarItem>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsList.tsx b/frontend/src/scenes/analytics/AnalyticsList.tsx
index 6aa99a521dd9..5fcfc0746690 100644
--- a/frontend/src/scenes/analytics/AnalyticsList.tsx
+++ b/frontend/src/scenes/analytics/AnalyticsList.tsx
@@ -47,6 +47,7 @@ import { AnalyticsListRow, analyticsListColumns } from './AnalyticsListColumns'
import { AnalyticsListFilters } from './AnalyticsListFilters'
import { analyticsListLogic, analyticsListUrlParams } from './analyticsListLogic'
import { AnalyticsListSkeleton } from './AnalyticsListSkeleton'
+import { AnalyticsPinMenuItem } from './AnalyticsPinMenuItem'
import { AnalyticsSpaceGlyph } from './AnalyticsSpaceGlyph'
import { ANALYTICS_DRAG_SCOPE, ANALYTICS_TYPE_INFO, USERS_FOLDER, analyticsSpaceOfPath } from './analyticsUtils'
import { NewAnalyticsMenu } from './NewAnalyticsMenu'
@@ -275,6 +276,14 @@ function AnalyticsListContent(): JSX.Element {
<IconChevronDown />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-48">
+ <AnalyticsPinMenuItem
+ target={{
+ type: 'folder',
+ ref: filters.folder!,
+ name: spaceName ?? topLevelSpace,
+ }}
+ dataAttr="analytics-space-pin-manage"
+ />
<DropdownMenuItem
variant="destructive"
onClick={() =>
diff --git a/frontend/src/scenes/analytics/AnalyticsListColumns.tsx b/frontend/src/scenes/analytics/AnalyticsListColumns.tsx
index ded1677a3708..e64f1ffd4299 100644
--- a/frontend/src/scenes/analytics/AnalyticsListColumns.tsx
+++ b/frontend/src/scenes/analytics/AnalyticsListColumns.tsx
@@ -38,10 +38,17 @@ import type { AnalyticsFeedQuery } from './analyticsFeed'
import { AnalyticsFolderDropTarget } from './AnalyticsFolderDropTarget'
import type { FolderRow } from './analyticsListLogic'
import { AnalyticsOwner } from './AnalyticsOwner'
+import { AnalyticsPinMenuItem } from './AnalyticsPinMenuItem'
import { analyticsShareLogic } from './analyticsShareLogic'
import { AnalyticsSpaceGlyph } from './AnalyticsSpaceGlyph'
import { AnalyticsTypeIcon } from './AnalyticsTypeIcon'
-import { ANALYTICS_DRAG_SCOPE, ANALYTICS_TYPE_INFO, AnalyticsItem, analyticsOpenHref } from './analyticsUtils'
+import {
+ ANALYTICS_DRAG_SCOPE,
+ ANALYTICS_TYPE_INFO,
+ AnalyticsItem,
+ analyticsOpenHref,
+ isSpacePath,
+} from './analyticsUtils'
export type AnalyticsListRow = { kind: 'folder'; folder: FolderRow } | { kind: 'item'; item: AnalyticsItem }
@@ -158,25 +165,36 @@ function SpaceCell({ item }: { item: AnalyticsItem }): JSX.Element {
)
}
-function MoveCell({ item }: { item: AnalyticsItem }): JSX.Element {
+function ItemMenuCell({ item }: { item: AnalyticsItem }): JSX.Element {
const { openShareToSpace } = useActions(analyticsShareLogic)
return (
- <Tooltip>
- <TooltipTrigger
+ <DropdownMenu>
+ <DropdownMenuTrigger
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"
+ aria-label={`Actions for ${item.name}`}
+ data-attr="analytics-list-row-menu"
/>
}
>
- <IconFolderMove />
- </TooltipTrigger>
- <TooltipContent>Move to another collection</TooltipContent>
- </Tooltip>
+ <IconEllipsis />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-56">
+ <AnalyticsPinMenuItem
+ target={{ type: item.type, ref: item.id, name: item.name, href: item.href }}
+ dataAttr="analytics-list-row-pin"
+ />
+ <DropdownMenuItem
+ onClick={() => openShareToSpace({ type: item.type, ref: item.id, name: item.name })}
+ data-attr="analytics-list-row-move"
+ >
+ <IconFolderMove />
+ Move to another collection
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
)
}
@@ -208,6 +226,12 @@ function FolderMenuCell({ folder }: { folder: FolderRow }): JSX.Element | null {
<IconFolderOpen />
Open folder
</DropdownMenuItem>
+ {isSpacePath(folder.path) && (
+ <AnalyticsPinMenuItem
+ target={{ type: 'folder', ref: folder.path, name: folder.name }}
+ dataAttr="analytics-list-folder-pin"
+ />
+ )}
<DropdownMenuItem
variant="destructive"
onClick={() => deleteItem(entry, ANALYTICS_DRAG_SCOPE)}
@@ -428,24 +452,19 @@ export function analyticsListColumns({
</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)),
+ {
+ id: 'actions',
+ header: '',
+ enableSorting: false,
+ cell: ({ row }) => (
+ <div className="flex w-8 justify-end">
+ {row.original.kind === 'item' ? (
+ <ItemMenuCell item={row.original.item} />
+ ) : (
+ <FolderMenuCell folder={row.original.folder} />
+ )}
+ </div>
+ ),
+ },
]
}
diff --git a/frontend/src/scenes/analytics/AnalyticsPinButton.tsx b/frontend/src/scenes/analytics/AnalyticsPinButton.tsx
new file mode 100644
index 000000000000..31995e76058b
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsPinButton.tsx
@@ -0,0 +1,41 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPin, IconPinFilled } from '@posthog/icons'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'
+
+import { PinTarget, analyticsPinnedLogic, pinKey } from './analyticsPinnedLogic'
+
+export function AnalyticsPinButton({
+ target,
+ size = 'icon-xs',
+ dataAttr,
+}: {
+ target: PinTarget
+ size?: 'icon' | 'icon-sm' | 'icon-xs'
+ dataAttr: string
+}): JSX.Element {
+ const { pinnedShortcutIds, shortcutDataLoading } = useValues(analyticsPinnedLogic)
+ const { togglePinned } = useActions(analyticsPinnedLogic)
+ const pinned = pinnedShortcutIds.has(pinKey(target.type, target.ref))
+ const label = pinned ? 'Unpin from sidebar' : 'Pin to sidebar'
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ delay={0}
+ render={
+ <Button
+ size={size}
+ aria-label={`${label}: ${target.name}`}
+ aria-pressed={pinned}
+ disabled={shortcutDataLoading}
+ onClick={() => togglePinned(target)}
+ data-attr={dataAttr}
+ />
+ }
+ >
+ {pinned ? <IconPinFilled /> : <IconPin />}
+ </TooltipTrigger>
+ <TooltipContent>{shortcutDataLoading ? 'Updating pinned items' : label}</TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsPinMenuItem.tsx b/frontend/src/scenes/analytics/AnalyticsPinMenuItem.tsx
new file mode 100644
index 000000000000..8825f24109f5
--- /dev/null
+++ b/frontend/src/scenes/analytics/AnalyticsPinMenuItem.tsx
@@ -0,0 +1,18 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPin, IconPinFilled } from '@posthog/icons'
+import { DropdownMenuItem } from '@posthog/quill'
+
+import { PinTarget, analyticsPinnedLogic, pinKey } from './analyticsPinnedLogic'
+
+export function AnalyticsPinMenuItem({ target, dataAttr }: { target: PinTarget; dataAttr: string }): JSX.Element {
+ const { pinnedShortcutIds, shortcutDataLoading } = useValues(analyticsPinnedLogic)
+ const { togglePinned } = useActions(analyticsPinnedLogic)
+ const pinned = pinnedShortcutIds.has(pinKey(target.type, target.ref))
+ return (
+ <DropdownMenuItem disabled={shortcutDataLoading} onClick={() => togglePinned(target)} data-attr={dataAttr}>
+ {pinned ? <IconPinFilled /> : <IconPin />}
+ {pinned ? 'Unpin from sidebar' : 'Pin to sidebar'}
+ </DropdownMenuItem>
+ )
+}
diff --git a/frontend/src/scenes/analytics/AnalyticsSpaces.tsx b/frontend/src/scenes/analytics/AnalyticsSpaces.tsx
index 0f8edca79c0c..4fd8559f1950 100644
--- a/frontend/src/scenes/analytics/AnalyticsSpaces.tsx
+++ b/frontend/src/scenes/analytics/AnalyticsSpaces.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconBox, IconPin, IconPinFilled, IconPlus, IconSearch } from '@posthog/icons'
+import { IconBox, IconPlus, IconSearch } from '@posthog/icons'
import {
Button,
Empty,
@@ -18,9 +18,6 @@ import {
ItemTitle,
Skeleton,
Spinner,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
} from '@posthog/quill'
import { NotFound } from 'lib/components/NotFound'
@@ -37,6 +34,7 @@ import { todayAnalyticsLogic } from '~/layout/today/todayAnalyticsLogic'
import { TodayAnalyticsNewFolderDialog } from '~/layout/today/TodayAnalyticsNewFolderDialog'
import { AnalyticsCreateModals } from './AnalyticsCreateModals'
+import { AnalyticsPinButton } from './AnalyticsPinButton'
import { AnalyticsSearchInput } from './AnalyticsSearchInput'
import { AnalyticsSpaceGlyph } from './AnalyticsSpaceGlyph'
import { AnalyticsSpace, analyticsSpacesLogic } from './analyticsSpacesLogic'
@@ -78,9 +76,6 @@ function SpaceCounts({ space, className }: { space: AnalyticsSpace; className?:
}
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"
@@ -113,24 +108,12 @@ function SpaceRow({ space }: { space: AnalyticsSpace }): JSX.Element {
</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>
+ <AnalyticsPinButton
+ target={{ type: 'folder', ref: space.path, name: space.name }}
+ size="icon"
+ // pinned: tracking API, do not rename.
+ dataAttr="analytics-space-star"
+ />
</ItemActions>
</Item>
)
diff --git a/frontend/src/scenes/analytics/analyticsPinnedLogic.test.ts b/frontend/src/scenes/analytics/analyticsPinnedLogic.test.ts
new file mode 100644
index 000000000000..b8c850dc080e
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsPinnedLogic.test.ts
@@ -0,0 +1,53 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { analyticsPinnedLogic } from './analyticsPinnedLogic'
+
+describe('analyticsPinnedLogic', () => {
+ let requests: string[]
+
+ beforeEach(() => {
+ requests = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/file_system_shortcut/': {
+ results: [
+ { id: 'sc-product', type: 'session_replay', path: 'Session replay', href: '/replay' },
+ { id: 'sc-home', type: 'folder', path: 'Ada', ref: 'Users/Ada' },
+ { id: 'sc-growth', type: 'folder', path: 'Growth', ref: 'Growth' },
+ { id: 'sc-insight', type: 'insight/trends', path: 'Signups', ref: 'abc123' },
+ { id: 'sc-dashboard', type: 'dashboard', path: 'KPIs', ref: '7', href: '/dashboard/7' },
+ ],
+ },
+ },
+ delete: {
+ '/api/projects/:team_id/file_system_shortcut/:id/': ({ params }) => {
+ requests.push(`delete ${params.id}`)
+ return [204, null]
+ },
+ },
+ })
+ initKeaTests()
+ })
+
+ it('keeps only analytics items and collections, and unpins an item whatever subtype it was pinned as', async () => {
+ const logic = analyticsPinnedLogic()
+ logic.mount()
+ await expectLogic(projectTreeDataLogic).toDispatchActions(['loadShortcutsSuccess'])
+
+ expect(logic.values.pinnedAnalytics.map((pinned) => pinned.key)).toEqual([
+ 'folder:Growth',
+ 'insight:abc123',
+ 'dashboard:7',
+ ])
+
+ await expectLogic(logic, () =>
+ logic.actions.togglePinned({ type: 'insight', ref: 'abc123', name: 'Signups' })
+ ).toDispatchActions(projectTreeDataLogic, ['deleteShortcutSuccess'])
+ expect(requests).toEqual(['delete sc-insight'])
+ expect(logic.values.pinnedAnalytics.map((pinned) => pinned.key)).toEqual(['folder:Growth', 'dashboard:7'])
+ })
+})
diff --git a/frontend/src/scenes/analytics/analyticsPinnedLogic.ts b/frontend/src/scenes/analytics/analyticsPinnedLogic.ts
new file mode 100644
index 000000000000..a652c7c99b33
--- /dev/null
+++ b/frontend/src/scenes/analytics/analyticsPinnedLogic.ts
@@ -0,0 +1,154 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, selectors } from 'kea'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
+import { escapePath } from '~/layout/panel-layout/ProjectTree/utils'
+import { FileSystemEntry } from '~/queries/schema/schema-general'
+
+import {
+ AnalyticsItem,
+ fileSystemBaseType,
+ fileSystemEntryName,
+ fileSystemEntryToAnalytics,
+ isSpacePath,
+} from './analyticsUtils'
+
+export interface PinTarget {
+ type: string
+ ref: string
+ name: string
+ href?: string
+}
+
+export type PinnedAnalytics =
+ | { kind: 'item'; key: string; shortcutId: string; item: AnalyticsItem }
+ | { kind: 'collection'; key: string; shortcutId: string; path: string; name: string }
+
+/** One key per pinnable thing. `insight/trends` and `insight` share a key, since the shortcut keeps whichever it was given. */
+export function pinKey(type: string, ref: string): string {
+ return `${fileSystemBaseType(type)}:${ref}`
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsPinnedLogicValues {
+ shortcutData: FileSystemEntry[] // projectTreeDataLogic
+ shortcutDataLoading: boolean // projectTreeDataLogic
+ pinnedAnalytics: PinnedAnalytics[]
+ pinnedCollectionPaths: Set<string>
+ pinnedShortcutIds: Map<string, string>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsPinnedLogicActions {
+ addShortcutItem: (
+ item: FileSystemEntry,
+ successMessage?: string | undefined
+ ) => {
+ item: FileSystemEntry
+ successMessage: string | undefined
+ } // projectTreeDataLogic
+ deleteShortcut: (
+ id: string,
+ successMessage?: string | undefined
+ ) => {
+ id: string
+ successMessage: string | undefined
+ } // projectTreeDataLogic
+ togglePinned: (target: PinTarget) => {
+ target: PinTarget
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface analyticsPinnedLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ pinnedAnalytics: (shortcutData: FileSystemEntry[]) => PinnedAnalytics[]
+ pinnedShortcutIds: (pinnedAnalytics: PinnedAnalytics[]) => Map<string, string>
+ pinnedCollectionPaths: (pinnedAnalytics: PinnedAnalytics[]) => Set<string>
+ }
+}
+
+export type analyticsPinnedLogicType = MakeLogicType<
+ analyticsPinnedLogicValues,
+ analyticsPinnedLogicActions,
+ Record<string, any>,
+ analyticsPinnedLogicMeta
+>
+
+/**
+ * The analytics items and collections a person pinned. Pins are the project tree's shortcuts, which the
+ * classic navigation lists as Starred, so a pin made here shows in every other place that lists them, and the reverse.
+ */
+export const analyticsPinnedLogic = kea<analyticsPinnedLogicType>([
+ path(['scenes', 'analytics', 'analyticsPinnedLogic']),
+ connect(() => ({
+ values: [projectTreeDataLogic, ['shortcutData', 'shortcutDataLoading']],
+ actions: [projectTreeDataLogic, ['addShortcutItem', 'deleteShortcut']],
+ })),
+ actions({
+ togglePinned: (target: PinTarget) => ({ target }),
+ }),
+ selectors({
+ pinnedAnalytics: [
+ (s) => [s.shortcutData],
+ (shortcutData: FileSystemEntry[]): PinnedAnalytics[] =>
+ shortcutData.flatMap((shortcut): PinnedAnalytics[] => {
+ if (!shortcut.id || !shortcut.ref) {
+ return []
+ }
+ // A folder shortcut's `path` is its display name; `ref` holds the folder it points at.
+ if (shortcut.type === 'folder') {
+ return isSpacePath(shortcut.ref)
+ ? [
+ {
+ kind: 'collection',
+ key: pinKey('folder', shortcut.ref),
+ shortcutId: shortcut.id,
+ path: shortcut.ref,
+ name: fileSystemEntryName({ path: shortcut.ref }),
+ },
+ ]
+ : []
+ }
+ const item = fileSystemEntryToAnalytics(shortcut)
+ return item
+ ? [{ kind: 'item', key: pinKey(item.type, item.id), shortcutId: shortcut.id, item }]
+ : []
+ }),
+ ],
+ pinnedShortcutIds: [
+ (s) => [s.pinnedAnalytics],
+ (pinnedAnalytics: PinnedAnalytics[]): Map<string, string> =>
+ new Map(pinnedAnalytics.map((pinned) => [pinned.key, pinned.shortcutId])),
+ ],
+ pinnedCollectionPaths: [
+ (s) => [s.pinnedAnalytics],
+ (pinnedAnalytics: PinnedAnalytics[]): Set<string> =>
+ new Set(pinnedAnalytics.flatMap((pinned) => (pinned.kind === 'collection' ? [pinned.path] : []))),
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ togglePinned: ({ target }) => {
+ // Every pin control is disabled while a change saves. This also stops a repeated dispatch.
+ if (values.shortcutDataLoading) {
+ return
+ }
+ const shortcutId = values.pinnedShortcutIds.get(pinKey(target.type, target.ref))
+ if (shortcutId) {
+ actions.deleteShortcut(shortcutId, 'Unpinned from sidebar')
+ } else if (target.type === 'folder') {
+ // A folder shortcut keeps its path as ref, so a rename moves the pin with the folder.
+ actions.addShortcutItem({ path: target.ref, type: 'folder' } as FileSystemEntry, 'Pinned to sidebar')
+ } else {
+ actions.addShortcutItem(
+ {
+ path: escapePath(target.name),
+ type: target.type,
+ ref: target.ref,
+ href: target.href,
+ } as FileSystemEntry,
+ 'Pinned to sidebar'
+ )
+ }
+ },
+ })),
+])
diff --git a/frontend/src/scenes/analytics/analyticsSpacesLogic.test.ts b/frontend/src/scenes/analytics/analyticsSpacesLogic.test.ts
index b8a3f6319e3f..4677c2914345 100644
--- a/frontend/src/scenes/analytics/analyticsSpacesLogic.test.ts
+++ b/frontend/src/scenes/analytics/analyticsSpacesLogic.test.ts
@@ -1,5 +1,9 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { urls } from 'scenes/urls'
+
+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { useMocks } from '~/mocks/jest'
import { FileSystemEntry } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
@@ -79,10 +83,8 @@ describe('analyticsSpacesLogic', () => {
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'])
+ await expectLogic(projectTreeDataLogic).toDispatchActions(['loadShortcutsSuccess'])
+ await expectLogic(logic, () => logic.actions.loadSpaces()).toDispatchActions(['loadSpacesSuccess'])
expect(logic.values.spaces.map((space) => [space.name, space.total])).toEqual([
['Finance', 0],
@@ -90,7 +92,7 @@ describe('analyticsSpacesLogic', () => {
])
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.pinnedCollectionPaths]).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'])
@@ -99,7 +101,7 @@ describe('analyticsSpacesLogic', () => {
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'])
+ await expectLogic(projectTreeDataLogic).toDispatchActions(['loadShortcutsSuccess'])
logic.actions.deleteSavedItem({ id: 'fs-Growth-Q4', type: 'folder', path: 'Growth/Q4' } as FileSystemEntry)
await expectLogic(logic, () =>
@@ -117,6 +119,7 @@ describe('analyticsSpacesLogic', () => {
]
const logic = analyticsSpacesLogic()
logic.mount()
+ await expectLogic(projectTreeDataLogic).toDispatchActions(['loadShortcutsSuccess'])
await expectLogic(logic, () => logic.actions.loadSpaces()).toDispatchActions(['loadSpacesSuccess'])
expect(logic.values.spaces).toHaveLength(20)
@@ -143,4 +146,24 @@ describe('analyticsSpacesLogic', () => {
expect(folderRequests).toHaveLength(1)
expect(metadataRequests).toHaveLength(24 * 4)
})
+
+ it('loads the first page again when a collection is unpinned after paging', async () => {
+ folders = [
+ ...Array.from({ length: 22 }, (_, index) => `Collection ${String(index + 1).padStart(2, '0')}`),
+ 'Growth',
+ ]
+ router.actions.push(urls.analyticsSpaces())
+ const logic = analyticsSpacesLogic()
+ logic.mount()
+ await expectLogic(projectTreeDataLogic).toDispatchActions(['loadShortcutsSuccess'])
+ await expectLogic(logic, () => logic.actions.loadSpaces()).toDispatchActions(['loadSpacesSuccess'])
+ await expectLogic(logic, () => logic.actions.loadMore()).toDispatchActions(['loadSpacesSuccess'])
+ expect(logic.values.pagination).toEqual({ offset: 23, hasMore: false })
+
+ await expectLogic(logic, () => projectTreeDataLogic.actions.deleteShortcut('sc-growth')).toDispatchActions([
+ 'loadSpacesSuccess',
+ ])
+ expect(logic.values.pagination).toEqual({ offset: 20, hasMore: true })
+ expect(logic.values.spaces.map((space) => space.name)).toEqual(folders.slice(0, 20))
+ })
})
diff --git a/frontend/src/scenes/analytics/analyticsSpacesLogic.ts b/frontend/src/scenes/analytics/analyticsSpacesLogic.ts
index 045d40781594..05c7b72139ff 100644
--- a/frontend/src/scenes/analytics/analyticsSpacesLogic.ts
+++ b/frontend/src/scenes/analytics/analyticsSpacesLogic.ts
@@ -1,47 +1,22 @@
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
+import { subscriptions } from 'kea-subscriptions'
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 { ANALYTICS_FEED_PAGE_SIZE, fileSystemTypeParams } from './analyticsFeed'
-import { ANALYTICS_TYPES, AnalyticsType, UNFILED_FOLDER, USERS_FOLDER, fileSystemEntryName } from './analyticsUtils'
-
-// 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
-}
+import { analyticsPinnedLogic, pinKey } from './analyticsPinnedLogic'
+import { ANALYTICS_TYPES, AnalyticsType, fileSystemEntryName, isSpacePath } from './analyticsUtils'
export interface AnalyticsSpace {
path: string
@@ -105,14 +80,11 @@ export async function listSpaceFolders(signal?: AbortSignal): Promise<FileSystem
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface analyticsSpacesLogicValues {
+ pinnedCollectionPaths: Set<string> // analyticsPinnedLogic
+ pinnedShortcutIds: Map<string, string> // analyticsPinnedLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
pagination: SpacesPagination
- pinnedPaths: Set<string>
- pinnedSpaces: PinnedSpace[]
- pinning: string | null
search: string
- shortcuts: FileSystemEntry[]
- shortcutsLoading: boolean
spaces: AnalyticsSpace[]
spacesFailed: boolean
spacesLoading: boolean
@@ -124,27 +96,15 @@ export interface analyticsSpacesLogicActions {
deleteSavedItem: (savedItem: FileSystemEntry) => {
savedItem: FileSystemEntry
} // projectTreeDataLogic
+ loadShortcuts: () => {
+ value: true
+ } // projectTreeDataLogic
folderCreated: () => {
value: true
} // todayAnalyticsLogic
loadMore: () => {
value: true
}
- loadShortcuts: () => any
- loadShortcutsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadShortcutsSuccess: (
- shortcuts: FileSystemEntry[],
- payload?: any
- ) => {
- shortcuts: FileSystemEntry[]
- payload?: any
- }
loadSpaces: (append?: boolean) => boolean
loadSpacesFailure: (
error: string,
@@ -173,20 +133,16 @@ export interface analyticsSpacesLogicActions {
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[]
+ visibleSpaces: (
+ spaces: AnalyticsSpace[],
+ pinnedCollectionPaths: Set<string>,
+ search: string
+ ) => AnalyticsSpace[]
}
}
@@ -201,27 +157,21 @@ export type analyticsSpacesLogicType = MakeLogicType<
export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
path(['scenes', 'analytics', 'analyticsSpacesLogic']),
connect(() => ({
- values: [featureFlagLogic, ['featureFlags']],
- actions: [todayAnalyticsLogic, ['folderCreated'], projectTreeDataLogic, ['deleteSavedItem']],
+ values: [
+ featureFlagLogic,
+ ['featureFlags'],
+ analyticsPinnedLogic,
+ ['pinnedCollectionPaths', 'pinnedShortcutIds'],
+ ],
+ actions: [todayAnalyticsLogic, ['folderCreated'], projectTreeDataLogic, ['deleteSavedItem', 'loadShortcuts']],
})),
actions({
- togglePin: (space: Pick<AnalyticsSpace, 'path' | 'name'>) => ({ space }),
- togglePinDone: true,
setSearch: (search: string) => ({ search }),
loadMore: true,
refreshSpaces: true,
setPagination: (offset: number, hasMore: boolean) => ({ offset, hasMore }),
}),
loaders(({ actions, values, cache }) => ({
- shortcuts: [
- [] as FileSystemEntry[],
- {
- loadShortcuts: async () => {
- cache.shortcutsRequest = api.fileSystemShortcuts.list()
- return (await cache.shortcutsRequest).results
- },
- },
- ],
spaces: [
[] as AnalyticsSpace[],
{
@@ -235,12 +185,7 @@ export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
breakpoint()
cache.folders = folders
}
- if (!cache.shortcutsRequest) {
- actions.loadShortcuts()
- }
- const shortcuts: FileSystemEntry[] = (await cache.shortcutsRequest).results
- breakpoint()
- const pinned = new Set(shortcuts.filter((item) => item.type === 'folder').map((item) => item.ref))
+ const pinned = values.pinnedCollectionPaths
const needle = values.search.trim().toLowerCase()
const matches = folders
.filter(
@@ -285,43 +230,20 @@ export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
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[] => {
+ (s) => [s.spaces, s.pinnedCollectionPaths, s.search],
+ (spaces: AnalyticsSpace[], pinnedCollectionPaths: 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))
+ const pinnedFirst =
+ Number(pinnedCollectionPaths.has(second.path)) -
+ Number(pinnedCollectionPaths.has(first.path))
return pinnedFirst || first.name.localeCompare(second.name)
})
},
@@ -333,14 +255,6 @@ export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
cache.metadata = new Map<string, AnalyticsSpace>()
actions.loadSpaces()
},
- loadShortcutsFailure: () => {
- cache.shortcutsRequest = undefined
- },
- loadShortcutsSuccess: () => {
- if (cache.loaded && removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()) {
- actions.loadSpaces()
- }
- },
loadMore: () => {
if (!values.spacesLoading && values.pagination.hasMore) {
actions.loadSpaces(true)
@@ -350,23 +264,6 @@ export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
await breakpoint(200)
actions.loadSpaces()
},
- 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.
@@ -375,7 +272,6 @@ export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
return
}
cache.flagSeen = true
- actions.loadShortcuts()
if (removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()) {
actions.refreshSpaces()
}
@@ -391,9 +287,9 @@ export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
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)
+ const shortcutId = values.pinnedShortcutIds.get(pinKey('folder', savedItem.path))
+ if (shortcutId) {
+ await api.fileSystemShortcuts.delete(shortcutId).catch(() => null)
}
// pinned: analytics event name. Renaming it breaks dashboards.
posthog.capture('analytics collection deleted')
@@ -402,12 +298,23 @@ export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
actions.refreshSpaces()
}
},
- togglePinDone: () => {
- // pinned: analytics event name and property. Renaming them breaks dashboards.
- posthog.capture('analytics collection pinned', { pinned_count: values.pinnedSpaces.length })
+ })),
+ subscriptions(({ actions, cache }) => ({
+ // Pinned spaces page first, so a change to the pins changes which spaces each page holds. Paging on from the
+ // old order would skip some spaces and repeat others, so the list loads again from the first page.
+ pinnedCollectionPaths: (paths: Set<string>, previous: Set<string> | undefined) => {
+ const unchanged =
+ !!previous && paths.size === previous.size && [...paths].every((path) => previous.has(path))
+ if (
+ !unchanged &&
+ cache.loaded &&
+ removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()
+ ) {
+ actions.loadSpaces()
+ }
},
})),
- // The sidebar mounts this logic for the stars alone; counting every space is for the Spaces page.
+ // The sidebar mounts this logic for the pins alone; counting every space is for the Spaces page.
urlToAction(({ actions, values }) => ({
[urls.analyticsSpaces()]: () => {
if (values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
@@ -415,10 +322,9 @@ export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
}
},
})),
- afterMount(({ actions, values, cache }) => {
+ afterMount(({ values, cache }) => {
if (values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
cache.flagSeen = true
- actions.loadShortcuts()
}
}),
])
diff --git a/frontend/src/scenes/analytics/analyticsUtils.ts b/frontend/src/scenes/analytics/analyticsUtils.ts
index c006b7c6540a..6b0a272933a0 100644
--- a/frontend/src/scenes/analytics/analyticsUtils.ts
+++ b/frontend/src/scenes/analytics/analyticsUtils.ts
@@ -118,6 +118,12 @@ 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'
+/** 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])
+}
+
/** 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)
diff --git a/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx b/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx
index ab3dd9afaac5..c1dc6cd0c22d 100644
--- a/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx
+++ b/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx
@@ -20,6 +20,7 @@ import { AccessControlAction } from 'lib/components/AccessControlAction'
import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { metalyticsLogic } from 'lib/components/Metalytics/metalyticsLogic'
import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'
+import { SceneMenuBarPinItem } from 'lib/components/Scenes/SceneMenuBarPinItem'
import { SceneTagsCombobox } from 'lib/components/Scenes/SceneTagsCombobox'
import { SceneActivityIndicator } from 'lib/components/Scenes/SceneUpdateActivityInfo'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -332,6 +333,7 @@ function DashboardSceneMenuBarInner(): JSX.Element | null {
Save as dashboard template
</SceneMenuBarItem>
)}
+ <SceneMenuBarPinItem dataAttrKey={RESOURCE_TYPE} />
{/* Toggle group — separated from regular Edit actions */}
<SceneMenuBarSeparator />
<SceneMenuBarCheckboxItem
diff --git a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx
index 4df84d418998..de53d15b79fc 100644
--- a/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx
+++ b/frontend/src/scenes/notebooks/NotebookSceneMenuBar.tsx
@@ -3,6 +3,7 @@ import { router } from 'kea-router'
import { IconCopy, IconDownload, IconOpenSidebar, IconShare, IconTrash } from '@posthog/icons'
+import { SceneMenuBarPinItem } from 'lib/components/Scenes/SceneMenuBarPinItem'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
@@ -104,6 +105,7 @@ function NotebookSceneMenuBarInner({ shortId }: { shortId: string }): JSX.Elemen
<IconCopy />
Duplicate
</SceneMenuBarItem>
+ <SceneMenuBarPinItem dataAttrKey={RESOURCE_TYPE} />
<SceneMenuBarSeparator />
<SceneMenuBarCheckboxItem
checked={showHistory}
diff --git a/products/product_analytics/frontend/insights/insightScene/sidePanel/InsightPanelActions.tsx b/products/product_analytics/frontend/insights/insightScene/sidePanel/InsightPanelActions.tsx
index 6b815883e265..415b6f6579c9 100644
--- a/products/product_analytics/frontend/insights/insightScene/sidePanel/InsightPanelActions.tsx
+++ b/products/product_analytics/frontend/insights/insightScene/sidePanel/InsightPanelActions.tsx
@@ -13,6 +13,7 @@ import { SceneDuplicate } from 'lib/components/Scenes/SceneDuplicate'
import { SceneFavorite } from 'lib/components/Scenes/SceneFavorite'
import { SceneMetalyticsSummaryButton } from 'lib/components/Scenes/SceneMetalyticsSummaryButton'
import { SceneShareButton } from 'lib/components/Scenes/SceneShareButton'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { Link } from 'lib/lemon-ui/Link'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
@@ -57,6 +58,7 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:
const { createStaticCohort } = useActions(exportsLogic)
const { openCreateFromInsightModal } = useActions(endpointLogic)
const { push } = useActions(router)
+ const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
const { openAddToDashboardModal, openTerraformModal } = useActions(insightModalsLogic(insightLogicProps))
const { canCopyToProject } = useValues(interProjectCopyLogic)
@@ -117,14 +119,17 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:
disabledReasons={captureDisabledReasons}
/>
)}
- <SceneFavorite
- dataAttrKey={RESOURCE_TYPE}
- onClick={() => setInsightMetadata({ favorited: !insight.favorited })}
- isFavorited={insight.favorited ?? false}
- disabledReasons={
- !isSavedInsight ? { 'You must save the insight first before favoriting it': true } : undefined
- }
- />
+ {/* The Today layout pins insights per person instead, so the project-wide favorite would read as a duplicate. */}
+ {!todayRailNav && (
+ <SceneFavorite
+ dataAttrKey={RESOURCE_TYPE}
+ onClick={() => setInsightMetadata({ favorited: !insight.favorited })}
+ isFavorited={insight.favorited ?? false}
+ disabledReasons={
+ !isSavedInsight ? { 'You must save the insight first before favoriting it': true } : undefined
+ }
+ />
+ )}
<SceneAddToNotebookDropdownMenu
shortId={insight.short_id}
diff --git a/products/product_analytics/frontend/insights/insightScene/sidePanel/InsightSceneMenuBar.tsx b/products/product_analytics/frontend/insights/insightScene/sidePanel/InsightSceneMenuBar.tsx
index 5bdab8bdea66..337410332bf8 100644
--- a/products/product_analytics/frontend/insights/insightScene/sidePanel/InsightSceneMenuBar.tsx
+++ b/products/product_analytics/frontend/insights/insightScene/sidePanel/InsightSceneMenuBar.tsx
@@ -25,6 +25,7 @@ import { metalyticsLogic } from 'lib/components/Metalytics/metalyticsLogic'
import { captureImageLogic } from 'lib/components/Scenes/InsightOrDashboard/captureImageLogic'
import { SceneMenuBarAddToNotebook } from 'lib/components/Scenes/SceneMenuBarAddToNotebook'
import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'
+import { SceneMenuBarPinItem } from 'lib/components/Scenes/SceneMenuBarPinItem'
import { SceneTagsCombobox } from 'lib/components/Scenes/SceneTagsCombobox'
import { SceneActivityIndicator } from 'lib/components/Scenes/SceneUpdateActivityInfo'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -198,6 +199,8 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: In
isSavedInsight /* add-to-dashboard, add-to-notebook, subscribe, alerts, share */
const showMetadataMenu = true // tags + activity always shown
const showStateMenu = isSavedInsight // favorite + view-source toggle
+ // The Today layout pins insights per person instead, so the project-wide favorite would read as a duplicate.
+ const showFavorite = !featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]
const showStaffMenu = canShowDebugPanel
return (
@@ -411,16 +414,19 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: In
Edit in SQL editor
</SceneMenuBarItem>
)}
+ <SceneMenuBarPinItem dataAttrKey={RESOURCE_TYPE} />
{showStateMenu && (
<>
<SceneMenuBarSeparator />
- <SceneMenuBarCheckboxItem
- checked={!!insight.favorited}
- onCheckedChange={(checked) => setInsightMetadata({ favorited: checked })}
- data-attr={`${RESOURCE_TYPE}-menubar-favorite`}
- >
- Favorite
- </SceneMenuBarCheckboxItem>
+ {showFavorite && (
+ <SceneMenuBarCheckboxItem
+ checked={!!insight.favorited}
+ onCheckedChange={(checked) => setInsightMetadata({ favorited: checked })}
+ data-attr={`${RESOURCE_TYPE}-menubar-favorite`}
+ >
+ Favorite
+ </SceneMenuBarCheckboxItem>
+ )}
<SceneMenuBarCheckboxItem
checked={showQueryEditor}
onCheckedChange={handleToggleQueryEditorPanel}