Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add and remove insight from dashboard modal #27138

Merged
merged 18 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cypress/productAnalytics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ export const dashboard = {

cy.get('[data-attr=dashboard-add-graph-header]').contains('Add insight').click()
cy.get('[data-attr=toast-close-button]').click({ multiple: true })
cy.get('[data-attr=dashboard-add-new-insight]').contains('New insight').click()

if (insightName) {
cy.get('[data-attr="top-bar-name"] button').click()
Expand Down
37 changes: 37 additions & 0 deletions frontend/src/scenes/dashboard/AddInsightToDashboardModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useActions, useValues } from 'kea'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { addInsightToDashboardLogic } from 'scenes/dashboard/addInsightToDasboardModalLogic'
import { AddSavedInsightsToDashboard } from 'scenes/saved-insights/AddSavedInsightsToDashboard'
import { urls } from 'scenes/urls'

import { dashboardLogic } from './dashboardLogic'

export function AddInsightToDashboardModal(): JSX.Element {
const { hideAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)
const { addInsightToDashboardModalVisible } = useValues(addInsightToDashboardLogic)
const { dashboard } = useValues(dashboardLogic)
return (
<LemonModal
title="Add insight to dashboard"
onClose={hideAddInsightToDashboardModal}
isOpen={addInsightToDashboardModalVisible}
footer={
<>
<LemonButton type="secondary" data-attr="dashboard-cancel" onClick={hideAddInsightToDashboardModal}>
Cancel
</LemonButton>
<LemonButton
type="primary"
data-attr="dashboard-add-new-insight"
to={urls.insightNew(undefined, dashboard?.id)}
>
New insight
</LemonButton>
</>
}
>
<AddSavedInsightsToDashboard />
</LemonModal>
)
}
9 changes: 7 additions & 2 deletions frontend/src/scenes/dashboard/DashboardHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import { notebooksModel } from '~/models/notebooksModel'
import { tagsModel } from '~/models/tagsModel'
import { DashboardMode, DashboardType, ExporterFormat, QueryBasedInsightModel } from '~/types'

import { addInsightToDashboardLogic } from './addInsightToDasboardModalLogic'
import { AddInsightToDashboardModal } from './AddInsightToDashboardModal'
import { DASHBOARD_RESTRICTION_OPTIONS } from './DashboardCollaborators'
import { dashboardCollaboratorsLogic } from './dashboardCollaboratorsLogic'
import { dashboardLogic } from './dashboardLogic'
Expand All @@ -53,7 +55,7 @@ export function DashboardHeader(): JSX.Element | null {
const { asDashboardTemplate } = useValues(dashboardLogic)
const { updateDashboard, pinDashboard, unpinDashboard } = useActions(dashboardsModel)
const { createNotebookFromDashboard } = useActions(notebooksModel)

const { showAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)
const { setDashboardTemplate, openDashboardTemplateEditor } = useActions(dashboardTemplateEditorLogic)

const { user } = useValues(userLogic)
Expand Down Expand Up @@ -114,6 +116,7 @@ export function DashboardHeader(): JSX.Element | null {
)}
{canEditDashboard && <DeleteDashboardModal />}
{canEditDashboard && <DuplicateDashboardModal />}
{canEditDashboard && <AddInsightToDashboardModal />}
</>
)}

Expand Down Expand Up @@ -290,7 +293,9 @@ export function DashboardHeader(): JSX.Element | null {
)}
{dashboard ? (
<LemonButton
to={urls.insightNew(undefined, dashboard.id)}
onClick={() => {
showAddInsightToDashboardModal()
}}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit

Suggested change
onClick={() => {
showAddInsightToDashboardModal()
}}
onClick={showAddInsightToDashboardModal}

type="primary"
data-attr="dashboard-add-graph-header"
disabledReason={canEditDashboard ? null : DASHBOARD_CANNOT_EDIT_MESSAGE}
Expand Down
12 changes: 6 additions & 6 deletions frontend/src/scenes/dashboard/EmptyDashboardComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import './EmptyDashboardComponent.scss'

import { IconPlus } from '@posthog/icons'
import { useValues } from 'kea'
import { useActions } from 'kea'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import React from 'react'
import { urls } from 'scenes/urls'

import { addInsightToDashboardLogic } from './addInsightToDasboardModalLogic'
import { DASHBOARD_CANNOT_EDIT_MESSAGE } from './DashboardHeader'
import { dashboardLogic } from './dashboardLogic'

function SkeletonCard({ children, active }: { children: React.ReactNode; active: boolean }): JSX.Element {
return (
Expand Down Expand Up @@ -77,8 +76,7 @@ function SkeletonCardTwo({ active }: { active: boolean }): JSX.Element {
}

export function EmptyDashboardComponent({ loading, canEdit }: { loading: boolean; canEdit: boolean }): JSX.Element {
const { dashboard } = useValues(dashboardLogic)

const { showAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)
return (
<div className="EmptyDashboard">
{!loading && (
Expand All @@ -88,7 +86,9 @@ export function EmptyDashboardComponent({ loading, canEdit }: { loading: boolean
<div className="mt-4 text-center">
<LemonButton
data-attr="dashboard-add-graph-header"
to={urls.insightNew(undefined, dashboard?.id)}
onClick={() => {
showAddInsightToDashboardModal()
}}
type="primary"
icon={<IconPlus />}
center
Expand Down
20 changes: 20 additions & 0 deletions frontend/src/scenes/dashboard/addInsightToDasboardModalLogic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { actions, kea, path, reducers } from 'kea'

import type { addInsightToDashboardLogicType } from './addInsightToDasboardModalLogicType'

export const addInsightToDashboardLogic = kea<addInsightToDashboardLogicType>([
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the file is called addInsightToDasboard**Modal**Logic, but the logic is called just addInsightToDashboardLogic

path(['scenes', 'dashboard', 'addInsightToDashboardLogic']),
actions({
showAddInsightToDashboardModal: true,
hideAddInsightToDashboardModal: true,
}),
reducers({
addInsightToDashboardModalVisible: [
false,
{
showAddInsightToDashboardModal: () => true,
hideAddInsightToDashboardModal: () => false,
},
],
}),
])
1 change: 0 additions & 1 deletion frontend/src/scenes/insights/insightLogic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
if (!Object.entries(insightUpdate).length) {
return values.insight
}

const response = await insightsApi.update(values.insight.id as number, insightUpdate)
breakpoint()
const updatedInsight: QueryBasedInsightModel = {
Expand Down
238 changes: 238 additions & 0 deletions frontend/src/scenes/saved-insights/AddSavedInsightsToDashboard.tsx
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file seems to contain a lot of duplication from the saved insights page. Can we dry up the code and at least import all the metadata from there?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree and updated

Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
import './SavedInsights.scss'

import { IconMinusSmall, IconPlusSmall } from '@posthog/icons'
import { useActions, useValues } from 'kea'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { Alerts } from 'lib/components/Alerts/views/Alerts'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { isNonEmptyObject } from 'lib/utils'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { SavedInsightsEmptyState } from 'scenes/insights/EmptyStates'
import { useSummarizeInsight } from 'scenes/insights/summarizeInsight'
import { organizationLogic } from 'scenes/organizationLogic'
import { overlayForNewInsightMenu } from 'scenes/saved-insights/newInsightsMenu'
import { SavedInsightsFilters } from 'scenes/saved-insights/SavedInsightsFilters'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { isNodeWithSource } from '~/queries/utils'
import { ActivityScope, QueryBasedInsightModel, SavedInsightsTabs } from '~/types'

import { addSavedInsightsModalLogic } from './addSavedInsightsModalLogic'
import { QUERY_TYPES_METADATA } from './SavedInsights'
import { savedInsightsLogic } from './savedInsightsLogic'

interface NewInsightButtonProps {
dataAttr: string
}

const INSIGHTS_PER_PAGE = 15

export const scene: SceneExport = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no need for a scene export. Scenes are "routes" in our app and since this is a modal, we don't need one. Assuming this is a leftover from copying the saved insights page.

component: AddSavedInsightsToDashboard,
logic: savedInsightsLogic,
}

export function InsightIcon({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This icon can reuse the one from the saved insights page.

insight,
className,
}: {
insight: QueryBasedInsightModel
className?: string
}): JSX.Element | null {
let Icon: (props?: any) => JSX.Element | null = () => null

if ('query' in insight && isNonEmptyObject(insight.query)) {
const insightType = isNodeWithSource(insight.query) ? insight.query.source.kind : insight.query.kind
const insightMetadata = QUERY_TYPES_METADATA[insightType]
Icon = insightMetadata && insightMetadata.icon
}

return Icon ? <Icon className={className} /> : null
}

export function NewInsightButton({ dataAttr }: NewInsightButtonProps): JSX.Element {
return (
<LemonButton
type="primary"
to={urls.insightNew()}
sideAction={{
dropdown: {
placement: 'bottom-end',
className: 'new-insight-overlay',
actionable: true,
overlay: overlayForNewInsightMenu(dataAttr),
},
'data-attr': 'saved-insights-new-insight-dropdown',
}}
data-attr="saved-insights-new-insight-button"
size="small"
icon={<IconPlusSmall />}
>
New insight
</LemonButton>
)
}

export function AddSavedInsightsToDashboard(): JSX.Element {
const { modalPage } = useValues(addSavedInsightsModalLogic)
const { setModalPage } = useActions(addSavedInsightsModalLogic)

const { insights, count, insightsLoading, filters, sorting, alertModalId, dashboardUpdatesInProgress } =
useValues(savedInsightsLogic)
const { setSavedInsightsFilters, addInsightToDashboard, removeInsightFromDashboard } =
useActions(savedInsightsLogic)

const { hasTagging } = useValues(organizationLogic)
const { dashboard } = useValues(dashboardLogic)

const summarizeInsight = useSummarizeInsight()

const { tab } = filters

const startCount = (modalPage - 1) * INSIGHTS_PER_PAGE + 1
const endCount = Math.min(modalPage * INSIGHTS_PER_PAGE, count)

const columns: LemonTableColumns<QueryBasedInsightModel> = [
{
key: 'id',
width: 32,
render: function renderType(_, insight) {
return <InsightIcon insight={insight} className="text-muted text-2xl" />
},
},
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: function renderName(name: string, insight) {
return (
<>
<LemonTableLink
to={urls.insightView(insight.short_id)}
title={<>{name || <i>{summarizeInsight(insight.query)}</i>}</>}
description={insight.description}
/>
</>
)
},
},
...(hasTagging
? [
{
title: 'Tags',
dataIndex: 'tags' as keyof QueryBasedInsightModel,
key: 'tags',
render: function renderTags(tags: string[]) {
return <ObjectTags tags={tags} staticOnly />
},
},
]
: []),
...(tab === SavedInsightsTabs.Yours
? []
: [
createdByColumn() as LemonTableColumn<
QueryBasedInsightModel,
keyof QueryBasedInsightModel | undefined
>,
]),
createdAtColumn() as LemonTableColumn<QueryBasedInsightModel, keyof QueryBasedInsightModel | undefined>,
{
title: 'Last modified',
sorter: true,
dataIndex: 'last_modified_at',
render: function renderLastModified(last_modified_at: string) {
return (
<div className="whitespace-nowrap">{last_modified_at && <TZLabel time={last_modified_at} />}</div>
)
},
},
{
width: 0,
render: function Render(_, insight) {
const isInDashboard = dashboard?.tiles.some((tile) => tile.insight?.id === insight.id)
return (
<LemonButton
type="secondary"
status={isInDashboard ? 'danger' : 'default'}
loading={dashboardUpdatesInProgress[insight.id]}
size="small"
fullWidth
onClick={(e) => {
e.preventDefault()
if (dashboardUpdatesInProgress[insight.id]) {
return
}
isInDashboard
? removeInsightFromDashboard(insight, dashboard?.id || 0)
: addInsightToDashboard(insight, dashboard?.id || 0)
}}
>
{isInDashboard ? <IconMinusSmall /> : <IconPlusSmall />}
</LemonButton>
)
},
},
]

return (
<div className="saved-insights">
{tab === SavedInsightsTabs.History ? (
<ActivityLog scope={ActivityScope.INSIGHT} />
) : tab === SavedInsightsTabs.Alerts ? (
<Alerts alertId={alertModalId} />
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't necessary here.

) : (
<>
<SavedInsightsFilters />
<LemonDivider className="my-4" />
<div className="flex justify-between mb-4 gap-2 flex-wrap mt-2 items-center">
<span className="text-muted-alt">
{count
? `${startCount}${endCount - startCount > 1 ? '-' + endCount : ''} of ${count} insight${
count === 1 ? '' : 's'
}`
: null}
</span>
</div>
{!insightsLoading && insights.count < 1 ? (
<SavedInsightsEmptyState />
) : (
<>
<LemonTable
loading={insightsLoading}
columns={columns}
dataSource={insights.results}
pagination={{
controlled: true,
currentPage: modalPage,
pageSize: INSIGHTS_PER_PAGE,
entryCount: count,
onForward: () => setModalPage(modalPage + 1),
onBackward: () => setModalPage(modalPage - 1),
}}
sorting={sorting}
onSort={(newSorting) =>
setSavedInsightsFilters({
order: newSorting
? `${newSorting.order === -1 ? '-' : ''}${newSorting.columnKey}`
: undefined,
})
}
rowKey="id"
loadingSkeletonRows={INSIGHTS_PER_PAGE}
nouns={['insight', 'insights']}
/>
</>
)}
</>
)}
</div>
)
}
Loading
Loading