: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
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, listSpaceFolders, loadSpace } 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 {
currentSpace: string | null
entry: FileSystemEntry | null
entryLoading: boolean
itemSpaces: Record<string, string | null>
sharing: boolean
spaces: AnalyticsSpace[]
spacesLoading: boolean
target: ShareToSpaceTarget | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface analyticsShareLogicActions {
refreshSpaces: () => {
value: true
} // 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
}
loadSpaces: (_: void) => void
loadSpacesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadSpacesSuccess: (
spaces: AnalyticsSpace[],
payload?: void
) => {
spaces: AnalyticsSpace[]
payload?: void
}
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(() => ({
actions: [analyticsSpacesLogic, ['refreshSpaces']],
})),
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 }),
}),
loaders({
spaces: [
[] as AnalyticsSpace[],
{
loadSpaces: async (_: void, breakpoint): Promise<AnalyticsSpace[]> => {
const folders = await listSpaceFolders()
breakpoint()
const spaces = await Promise.all(folders.map((folder) => loadSpace(folder)))
breakpoint()
return spaces.sort((first, second) => first.name.localeCompare(second.name))
},
},
],
}),
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.refreshSpaces()
}
// 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()
},
})),
])