Skip to content

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

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

import { toast } from '@posthog/quill'

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

import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'

import { taskChannelsCreate, taskChannelsStarCreate } from '../generated/api'
import { ChannelDTOApi } from '../generated/api.schemas'

export const NEW_SPACE_NAME_MAX_LENGTH = 80

// The server stores names as lowercase letters, numbers, and hyphens, so the field shows that shape as the user types.
export function normalizeSpaceNameInput(name: string): string {
    return name
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+/, '')
}

export function normalizeSpaceName(name: string): string {
    return normalizeSpaceNameInput(name).replace(/-+$/, '')
}

export function spaceNameError(name: string, spaces: Pick<ChannelDTOApi, 'name'>[]): string | null {
    if (name === 'me' || name === 'personal') {
        return `"${name}" is reserved for your personal space.`
    }
    if (name === 'general') {
        return `"${name}" is reserved for your team's shared space.`
    }
    if (spaces.some((space) => space.name === name)) {
        return `#${name} already exists. Try another name.`
    }
    return null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newSpaceLogicValues {
    currentTeamId: number | null // teamLogic
    spaces: ChannelDTOApi[] // todaySpacesLogic
    isOpen: boolean
    name: string
    nameError: string | null
    normalizedName: string
    submitAttempted: boolean
    submitting: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newSpaceLogicActions {
    loadSpaces: () => any // todaySpacesLogic
    closeNewSpace: () => {
        value: true
    }
    createSpace: (name: string) => {
        name: string
    }
    createSpaceFailure: () => {
        value: true
    }
    createSpaceSuccess: (space: ChannelDTOApi) => {
        space: ChannelDTOApi
    }
    openNewSpace: () => {
        value: true
    }
    setName: (name: string) => {
        name: string
    }
    submitNewSpace: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newSpaceLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        normalizedName: (name: string) => string
        nameError: (normalizedName: string, spaces: ChannelDTOApi[], submitAttempted: boolean) => string | null
    }
}

export type newSpaceLogicType = MakeLogicType<
    newSpaceLogicValues,
    newSpaceLogicActions,
    Record<string, any>,
    newSpaceLogicMeta
>

export const newSpaceLogic = kea<newSpaceLogicType>([
    path(['products', 'tasks', 'spaces', 'newSpaceLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamId'], todaySpacesLogic, ['spaces']],
        actions: [todaySpacesLogic, ['loadSpaces']],
    })),
    actions({
        openNewSpace: true,
        closeNewSpace: true,
        setName: (name: string) => ({ name }),
        submitNewSpace: true,
        createSpace: (name: string) => ({ name }),
        createSpaceSuccess: (space: ChannelDTOApi) => ({ space }),
        createSpaceFailure: true,
    }),
    reducers({
        isOpen: [
            false,
            {
                openNewSpace: () => true,
                closeNewSpace: () => false,
                createSpaceSuccess: () => false,
            },
        ],
        name: ['', { openNewSpace: () => '', setName: (_, { name }) => normalizeSpaceNameInput(name) }],
        submitAttempted: [false, { openNewSpace: () => false, submitNewSpace: () => true }],
        submitting: [
            false,
            {
                createSpace: () => true,
                createSpaceSuccess: () => false,
                createSpaceFailure: () => false,
            },
        ],
    }),
    selectors({
        normalizedName: [(s) => [s.name], (name: string): string => normalizeSpaceName(name)],
        nameError: [
            (s) => [s.normalizedName, s.spaces, s.submitAttempted],
            (normalizedName: string, spaces: ChannelDTOApi[], submitAttempted: boolean): string | null =>
                normalizedName
                    ? spaceNameError(normalizedName, spaces)
                    : submitAttempted
                      ? 'Enter a name for the space.'
                      : null,
        ],
    }),
    listeners(({ actions, values }) => ({
        submitNewSpace: () => {
            if (values.submitting || !values.normalizedName || values.nameError) {
                return
            }
            actions.createSpace(values.normalizedName)
        },
        createSpace: async ({ name }) => {
            const projectId = String(values.currentTeamId)
            let space: ChannelDTOApi
            try {
                space = await taskChannelsCreate(projectId, { name, channel_type: 'public', star: true })
            } catch {
                toast.error({ title: 'Couldn’t create the space. Try again.' })
                actions.createSpaceFailure()
                return
            }
            if (!space.starred) {
                try {
                    // Create returns an existing public space with that name unchanged, so star it here to match what the user asked for.
                    await taskChannelsStarCreate(projectId, space.id, { starred: true })
                    space = { ...space, starred: true }
                } catch {
                    // The space exists either way, and starring it later is one click.
                }
            }
            actions.createSpaceSuccess(space)
        },
        createSpaceSuccess: ({ space }) => {
            actions.loadSpaces()
            router.actions.push(urls.taskSpace(space.id))
        },
    })),
])