: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, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import api from 'lib/api'
import { getTextContent } from 'lib/components/Comments/utils'
import { JSONContent, RichContentEditorType } from 'lib/components/RichContentEditor/types'
import { Dayjs, dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { colonDelimitedDuration } from 'lib/utils/durations'
import { playerCommentModel } from 'scenes/session-recordings/player/commenting/playerCommentModel'
import { isSingleEmoji } from 'scenes/session-recordings/utils'
import { membersLogic } from '~/models/membersLogic'
import { CommentType, OrganizationMemberType } from '~/types'
import type { SessionPlayerData } from '../../../../types'
import { SessionRecordingPlayerLogicProps, sessionRecordingPlayerLogic } from '../sessionRecordingPlayerLogic'
export interface RecordingCommentForm {
// formatted time in recording, e.g. 00:00:00, 00:00:01, 00:00:02, etc.
// this is a string because we want to be able to display the time in the recording
timeInRecording?: string | null
// number of seconds into recording
timestampInRecording?: number | null
// the date that the timeInRecording represents
dateForTimestamp?: Dayjs | null
content: string
richContent: JSONContent | null
recordingId: string | null
commentId: CommentType['id'] | null
}
export interface PlayerCommentOverlayLogicProps extends SessionRecordingPlayerLogicProps {
recordingId: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface playerCommentOverlayLogicValues {
meFirstMembers: OrganizationMemberType[] // membersLogic
currentPlayerTime: number // sessionRecordingPlayerLogic
currentTimestamp: number | undefined // sessionRecordingPlayerLogic
sessionPlayerData: SessionPlayerData // sessionRecordingPlayerLogic
asTask: boolean
dateForCurrentTimestamp: Dayjs | null
formattedTimestamp: string
isEmpty: boolean
isLoading: boolean
isRecordingCommentSubmitting: boolean
isRecordingCommentValid: boolean
recordingComment: RecordingCommentForm
recordingCommentAllErrors: Record<string, any>
recordingCommentChanged: boolean
recordingCommentErrors: DeepPartialMap<RecordingCommentForm, ValidationErrorType>
recordingCommentHasErrors: boolean
recordingCommentManualErrors: Record<string, any>
recordingCommentTouched: boolean
recordingCommentTouches: Record<string, boolean>
recordingCommentValidationErrors: DeepPartialMap<RecordingCommentForm, ValidationErrorType>
richContentEditor: RichContentEditorType | null
showRecordingCommentErrors: boolean
timestampUnits: 2 | 3
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface playerCommentOverlayLogicActions {
ensureAllMembersLoaded: () => {
value: true
} // membersLogic
commentEdited: (recordingId: string) => {
recordingId: string
} // playerCommentModel
setIsCommenting: (isCommenting: boolean) => {
isCommenting: boolean
} // sessionRecordingPlayerLogic
addEmojiComment: (emoji: string) => {
emoji: string
}
editComment: (comment: RecordingCommentForm) => {
comment: RecordingCommentForm
}
onRichContentEditorUpdate: (isEmpty: boolean) => {
isEmpty: boolean
}
resetRecordingComment: (values?: RecordingCommentForm) => {
values?: RecordingCommentForm
}
setAsTask: (asTask: boolean) => {
asTask: boolean
}
setLoading: (isLoading: boolean) => {
isLoading: boolean
}
setRecordingCommentManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
setRecordingCommentValue: (
key: FieldName,
value: any
) => {
name: FieldName
value: any
}
setRecordingCommentValues: (values: DeepPartial<RecordingCommentForm>) => {
values: DeepPartial<RecordingCommentForm>
}
setRichContent: (richContent: JSONContent | null) => {
richContent: JSONContent | null
}
setRichContentEditor: (editor: RichContentEditorType) => {
editor: RichContentEditorType
}
submitRecordingComment: () => {
value: boolean
}
submitRecordingCommentFailure: (
error: Error,
errors: Record<string, any>
) => {
error: Error
errors: Record<string, any>
}
submitRecordingCommentRequest: (recordingComment: RecordingCommentForm) => {
recordingComment: RecordingCommentForm
}
submitRecordingCommentSuccess: (recordingComment: RecordingCommentForm) => {
recordingComment: RecordingCommentForm
}
touchRecordingCommentField: (key: string) => {
key: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface playerCommentOverlayLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
timestampUnits: (sessionPlayerData: SessionPlayerData) => 2 | 3
formattedTimestamp: (currentPlayerTime: number, timestampUnits: 2 | 3) => string
dateForCurrentTimestamp: (
currentTimestamp: number | undefined,
currentPlayerTime: number,
sessionPlayerData: SessionPlayerData
) => Dayjs | null
}
}
export type playerCommentOverlayLogicType = MakeLogicType<
playerCommentOverlayLogicValues,
playerCommentOverlayLogicActions,
PlayerCommentOverlayLogicProps,
playerCommentOverlayLogicMeta
>
export const playerCommentOverlayLogic = kea<playerCommentOverlayLogicType>([
path(['scenes', 'session-recordings', 'player', 'PlayerFrameAnnotationOverlay']),
key((props) => props.recordingId ?? 'unknown'),
props({} as PlayerCommentOverlayLogicProps),
connect((props: PlayerCommentOverlayLogicProps) => ({
values: [
sessionRecordingPlayerLogic(props),
['currentPlayerTime', 'currentTimestamp', 'sessionPlayerData'],
membersLogic,
['meFirstMembers'],
],
actions: [
sessionRecordingPlayerLogic(props),
['setIsCommenting'],
membersLogic,
['ensureAllMembersLoaded'],
// bound at build time, so notifying the bus can't depend on it still being mounted
playerCommentModel,
['commentEdited'],
],
})),
actions({
editComment: (comment: RecordingCommentForm) => ({ comment }),
addEmojiComment: (emoji: string) => ({ emoji }),
setLoading: (isLoading: boolean) => ({ isLoading }),
setRichContent: (richContent: JSONContent | null) => ({ richContent }),
setAsTask: (asTask: boolean) => ({ asTask }),
// copied from comments logic
setRichContentEditor: (editor: RichContentEditorType) => ({ editor }),
onRichContentEditorUpdate: (isEmpty: boolean) => ({ isEmpty }),
}),
reducers({
isLoading: [
false,
{
setLoading: (_, { isLoading }: { isLoading: boolean }) => isLoading,
},
],
asTask: [
false as boolean,
{
setAsTask: (_, { asTask }) => asTask,
},
],
// copied from comments logic
isEmpty: [
true as boolean,
{
onRichContentEditorUpdate: (_, { isEmpty }) => isEmpty,
},
],
richContentEditor: [
null as RichContentEditorType | null,
{
setRichContentEditor: (_, { editor }) => editor,
},
],
}),
selectors({
timestampUnits: [
(s) => [s.sessionPlayerData],
(sessionPlayerData: import('~/types').SessionPlayerData) => {
const endTimeSeconds = Math.floor(sessionPlayerData.durationMs / 1000)
return endTimeSeconds > 3600 ? 3 : 2
},
],
formattedTimestamp: [
(s) => [s.currentPlayerTime, s.timestampUnits],
(currentPlayerTime: number, timestampUnits: 2 | 3) => {
return colonDelimitedDuration(currentPlayerTime / 1000, timestampUnits)
},
],
// currentTimestamp is unset until the player seeks, so fall back to the recording start
// plus the playhead offset rather than leaving a comment with no date to anchor to
dateForCurrentTimestamp: [
(s) => [s.currentTimestamp, s.currentPlayerTime, s.sessionPlayerData],
(
currentTimestamp: number | undefined,
currentPlayerTime: number,
sessionPlayerData: SessionPlayerData
): Dayjs | null => {
if (currentTimestamp) {
return dayjs(currentTimestamp)
}
return sessionPlayerData?.start ? sessionPlayerData.start.add(currentPlayerTime, 'milliseconds') : null
},
],
}),
subscriptions(({ actions, values }) => ({
formattedTimestamp: (formattedTimestamp) => {
// as the timestamp from the player changes we track three representations of it
actions.setRecordingCommentValue('timeInRecording', formattedTimestamp)
actions.setRecordingCommentValue('timestampInRecording', values.currentPlayerTime)
actions.setRecordingCommentValue('dateForTimestamp', values.dateForCurrentTimestamp)
},
})),
listeners(({ actions, props, values }) => ({
setRichContent: ({ richContent }) => {
actions.setRecordingCommentValue('richContent', richContent)
},
editComment: ({ comment }) => {
actions.setRecordingCommentValue('content', comment.content)
actions.setRecordingCommentValue('richContent', comment.richContent)
actions.setRecordingCommentValue('recordingId', comment.recordingId)
actions.setRecordingCommentValue('commentId', comment.commentId)
// opening to edit also sets the player timestamp, which will update the timestamps in the form
actions.setIsCommenting(true)
if (values.richContentEditor && comment.richContent) {
values.richContentEditor.setContent(comment.richContent)
}
},
setRichContentEditor: ({ editor }) => {
const richContent = values.recordingComment.richContent
if (richContent && values.recordingComment.commentId) {
editor.setContent(richContent)
}
},
setIsCommenting: ({ isCommenting }) => {
if (isCommenting) {
// Load org members so @-mentions in the comment editor can resolve.
actions.ensureAllMembersLoaded()
} else {
actions.resetRecordingComment()
// Don't let "Add as task" leak into the next overlay session.
actions.setAsTask(false)
}
},
addEmojiComment: async ({ emoji }) => {
if (!isSingleEmoji(emoji)) {
lemonToast.error(`Emoji comments must be emojis 🙈, this string was too long: "${emoji}"`)
return
}
const dateForTimestamp = values.dateForCurrentTimestamp
if (!dateForTimestamp) {
lemonToast.error('Could not save your comment: the recording has no timestamp yet.')
return
}
const loadingTimeout = setTimeout(() => {
actions.setLoading(true)
}, 250)
try {
await api.comments.create({
content: emoji,
scope: 'Replay',
item_id: props.recordingId,
item_context: {
is_emoji: true,
time_in_recording: dateForTimestamp.toISOString(),
milliseconds_into_recording: values.currentPlayerTime,
},
slug: `/replay/${props.recordingId}#panel=discussion`,
})
posthog.capture('comment created', { scope: 'Replay', is_reply: false, is_emoji: true })
actions.commentEdited(props.recordingId)
} catch (e) {
lemonToast.error(`Could not save your comment: ${(e as Error).message}`)
} finally {
if (loadingTimeout) {
clearTimeout(loadingTimeout)
}
actions.setLoading(false)
}
},
})),
forms(({ props, values, actions }) => ({
recordingComment: {
defaults: {
timeInRecording: values.formattedTimestamp ?? '00:00:00',
dateForTimestamp: null,
content: '',
richContent: null,
recordingId: null,
commentId: null,
} as RecordingCommentForm,
errors: ({ content, richContent }) => {
return {
content:
!content?.trim() && !Object.keys(richContent ?? {}).length
? 'A comment must have some content.'
: null,
}
},
submit: async (data) => {
const { commentId, content, richContent } = data
// the form's copy only refreshes on whole-second changes, so read the live position
// to keep this in step with milliseconds_into_recording below
const dateForTimestamp = values.dateForCurrentTimestamp
if (!dateForTimestamp) {
throw new Error('Cannot comment without a timestamp.')
}
const apiPayload = {
content: richContent ? getTextContent(richContent, values.meFirstMembers) : content,
rich_content: richContent,
scope: 'Replay',
item_id: props.recordingId,
item_context: {
time_in_recording: dateForTimestamp.toISOString(),
milliseconds_into_recording: values.currentPlayerTime,
},
slug: `/replay/${props.recordingId}#panel=discussion`,
}
if (commentId) {
await api.comments.update(commentId, apiPayload)
} else {
await api.comments.create({ ...apiPayload, is_task: values.asTask })
posthog.capture('comment created', { scope: 'Replay', is_reply: false, is_emoji: false })
}
actions.commentEdited(props.recordingId)
actions.resetRecordingComment()
actions.setAsTask(false)
actions.setIsCommenting(false)
},
},
})),
listeners(({ values }) => ({
// kea-forms discards anything thrown in submit, so a failed save is otherwise silent
submitRecordingCommentFailure: ({ error }) => {
if (values.recordingCommentHasErrors) {
// already rendered against the field
return
}
lemonToast.error(`Could not save your comment: ${error.message}`)
},
})),
])