-
Notifications
You must be signed in to change notification settings - Fork 64
Add recents global nav action #4012
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
Open
k11kirky
wants to merge
4
commits into
main
Choose a base branch
from
posthog-code/add-recents-quick-action
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| import type { RecentsService } from "./recentsService"; | ||
|
|
||
| export const RECENTS_SERVICE = Symbol.for("posthog.core.recents.service"); | ||
| export type IRecentsService = Pick<RecentsService, "list" | "record">; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import { ContainerModule } from "inversify"; | ||
| import { RECENTS_SERVICE } from "./identifiers"; | ||
| import { RecentsService } from "./recentsService"; | ||
|
|
||
| export const recentsCoreModule = new ContainerModule(({ bind }) => { | ||
| bind(RecentsService).toSelf().inSingletonScope(); | ||
| bind(RECENTS_SERVICE).toService(RecentsService); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
| import type { DesktopFsClient, FsEntryBase } from "../canvas/desktopFsClient"; | ||
| import { RecentsService } from "./recentsService"; | ||
|
|
||
| function serviceWith(rows: Array<FsEntryBase & Record<string, unknown>>) { | ||
| const listByQuery = vi.fn(async () => rows); | ||
| const getEntry = vi.fn(async (id: string) => ({ | ||
| id, | ||
| path: `Canvases/${id}`, | ||
| type: "dashboard", | ||
| ref: null, | ||
| })); | ||
| const fetch = vi.fn(async () => new Response(null, { status: 204 })); | ||
| const fs = { listByQuery, getEntry, fetch } as unknown as DesktopFsClient; | ||
| return { service: new RecentsService(fs), listByQuery, getEntry, fetch }; | ||
| } | ||
|
|
||
| describe("RecentsService", () => { | ||
| it("returns the latest 20 task and canvas engagements from the backend", async () => { | ||
| const rows = Array.from({ length: 24 }, (_, index) => ({ | ||
| id: `row-${index}`, | ||
| path: `Space/Item ${index}`, | ||
| type: index % 2 === 0 ? "task" : "dashboard", | ||
| ref: `entity-${index}`, | ||
| last_viewed_at: new Date(index * 1_000).toISOString(), | ||
| meta: { channelId: "channel-1", templateId: "freeform" }, | ||
| })); | ||
| const { service, listByQuery } = serviceWith(rows); | ||
|
|
||
| const result = await service.list(); | ||
|
|
||
| expect(listByQuery).toHaveBeenCalledWith( | ||
| "order_by=-last_viewed_at&limit=100¬_type=folder", | ||
| "recent items", | ||
| ); | ||
| expect(result).toHaveLength(20); | ||
| expect(result[0]).toMatchObject({ id: "entity-23", kind: "canvas" }); | ||
| expect(result.at(-1)).toMatchObject({ id: "entity-4", kind: "task" }); | ||
| }); | ||
|
|
||
| it("makes a canvas hydratable before logging its engagement", async () => { | ||
| const { service, fetch } = serviceWith([]); | ||
|
|
||
| await service.record({ kind: "canvas", id: "canvas-1" }); | ||
|
|
||
| expect(fetch).toHaveBeenNthCalledWith( | ||
| 1, | ||
| "canvas-1/", | ||
| expect.objectContaining({ | ||
| method: "PATCH", | ||
| body: JSON.stringify({ ref: "canvas-1" }), | ||
| }), | ||
| ); | ||
| expect(fetch).toHaveBeenNthCalledWith( | ||
| 2, | ||
| "log_view/", | ||
| expect.objectContaining({ | ||
| method: "POST", | ||
| body: JSON.stringify({ type: "dashboard", ref: "canvas-1" }), | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it("logs task engagement without rewriting its existing file-system row", async () => { | ||
| const { service, getEntry, fetch } = serviceWith([]); | ||
|
|
||
| await service.record({ kind: "task", id: "task-1" }); | ||
|
|
||
| expect(getEntry).not.toHaveBeenCalled(); | ||
| expect(fetch).toHaveBeenCalledOnce(); | ||
| expect(fetch).toHaveBeenCalledWith( | ||
| "log_view/", | ||
| expect.objectContaining({ | ||
| body: JSON.stringify({ type: "task", ref: "task-1" }), | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it("does not rewrite a non-canvas row supplied as a canvas id", async () => { | ||
| const { service, getEntry, fetch } = serviceWith([]); | ||
| getEntry.mockResolvedValue({ | ||
| id: "task-row", | ||
| path: "Tasks/task-row", | ||
| type: "task", | ||
| ref: "task-row", | ||
| } as never); | ||
|
|
||
| await expect( | ||
| service.record({ kind: "canvas", id: "task-row" }), | ||
| ).rejects.toThrow("Canvas not found"); | ||
|
|
||
| expect(fetch).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import { | ||
| DESKTOP_FS_CLIENT, | ||
| type DesktopFsClient, | ||
| type FsEntryBase, | ||
| } from "@posthog/core/canvas/desktopFsClient"; | ||
| import { inject, injectable } from "inversify"; | ||
| import type { RecentEngagementInput, RecentItem } from "./schemas"; | ||
|
|
||
| const RECENTS_LIMIT = 20; | ||
| const RECENTS_SCAN_LIMIT = 100; | ||
|
|
||
| interface RecentFsEntry extends FsEntryBase { | ||
| last_viewed_at?: string | null; | ||
| meta?: { | ||
| channelId?: string; | ||
| templateId?: string; | ||
| } | null; | ||
| } | ||
|
|
||
| @injectable() | ||
| export class RecentsService { | ||
| constructor( | ||
| @inject(DESKTOP_FS_CLIENT) | ||
| private readonly fs: DesktopFsClient, | ||
| ) {} | ||
|
|
||
| async list(): Promise<RecentItem[]> { | ||
| const entries = await this.fs.listByQuery<RecentFsEntry>( | ||
| `order_by=-last_viewed_at&limit=${RECENTS_SCAN_LIMIT}¬_type=folder`, | ||
| "recent items", | ||
| ); | ||
| return entries | ||
| .flatMap((entry) => this.toRecentItem(entry)) | ||
| .sort((a, b) => b.engagedAt - a.engagedAt) | ||
| .slice(0, RECENTS_LIMIT); | ||
| } | ||
|
|
||
| async record(input: RecentEngagementInput): Promise<void> { | ||
| const type = input.kind === "canvas" ? "dashboard" : "task"; | ||
| if (input.kind === "canvas") { | ||
| await this.ensureCanvasReference(input.id); | ||
| } | ||
| const response = await this.fs.fetch("log_view/", { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ type, ref: input.id }), | ||
| }); | ||
| if (!response.ok) { | ||
| throw new Error( | ||
| `Failed to record recent engagement (${response.status})`, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| private async ensureCanvasReference(id: string): Promise<void> { | ||
| const entry = await this.fs.getEntry<RecentFsEntry>(id, "canvas"); | ||
| if (!entry || entry.type !== "dashboard") | ||
| throw new Error("Canvas not found"); | ||
| if (entry.ref === id) return; | ||
| const response = await this.fs.fetch(`${encodeURIComponent(id)}/`, { | ||
| method: "PATCH", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ ref: id }), | ||
| }); | ||
| if (!response.ok) { | ||
| throw new Error(`Failed to prepare canvas recents (${response.status})`); | ||
| } | ||
| } | ||
|
|
||
| private toRecentItem(entry: RecentFsEntry): RecentItem[] { | ||
| const engagedAt = entry.last_viewed_at | ||
| ? Date.parse(entry.last_viewed_at) | ||
| : 0; | ||
| if (!entry.ref || engagedAt <= 0) return []; | ||
| const title = entry.path.slice(entry.path.lastIndexOf("/") + 1); | ||
| if (entry.type === "task") { | ||
| return [{ kind: "task", id: entry.ref, title, engagedAt }]; | ||
| } | ||
| if (entry.type === "dashboard" && entry.meta?.channelId) { | ||
| return [ | ||
| { | ||
| kind: "canvas", | ||
| id: entry.ref, | ||
| channelId: entry.meta.channelId, | ||
| title, | ||
| templateId: entry.meta.templateId ?? "freeform", | ||
| engagedAt, | ||
| }, | ||
| ]; | ||
| } | ||
| return []; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import { z } from "zod"; | ||
|
|
||
| export const recentEngagementInputSchema = z.object({ | ||
| kind: z.enum(["task", "canvas"]), | ||
| id: z.string().min(1), | ||
| }); | ||
| export type RecentEngagementInput = z.infer<typeof recentEngagementInputSchema>; | ||
|
|
||
| export const recentItemSchema = z.discriminatedUnion("kind", [ | ||
| z.object({ | ||
| kind: z.literal("task"), | ||
| id: z.string(), | ||
| title: z.string(), | ||
| engagedAt: z.number(), | ||
| }), | ||
| z.object({ | ||
| kind: z.literal("canvas"), | ||
| id: z.string(), | ||
| channelId: z.string(), | ||
| title: z.string(), | ||
| templateId: z.string(), | ||
| engagedAt: z.number(), | ||
| }), | ||
| ]); | ||
| export type RecentItem = z.infer<typeof recentItemSchema>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import { | ||
| type IRecentsService, | ||
| RECENTS_SERVICE, | ||
| } from "@posthog/core/recents/identifiers"; | ||
| import { | ||
| recentEngagementInputSchema, | ||
| recentItemSchema, | ||
| } from "@posthog/core/recents/schemas"; | ||
| import { publicProcedure, router } from "@posthog/host-trpc/trpc"; | ||
| import { z } from "zod"; | ||
|
|
||
| export const recentsRouter = router({ | ||
| list: publicProcedure | ||
| .output(z.array(recentItemSchema)) | ||
| .query(({ ctx }) => | ||
| ctx.container.get<IRecentsService>(RECENTS_SERVICE).list(), | ||
| ), | ||
| record: publicProcedure | ||
| .input(recentEngagementInputSchema) | ||
| .output(z.void()) | ||
| .mutation(({ ctx, input }) => | ||
| ctx.container.get<IRecentsService>(RECENTS_SERVICE).record(input), | ||
| ), | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.