diff --git a/apps/web/src/dashboard/lib/collections.ts b/apps/web/src/dashboard/lib/collections.ts index 543a6f213..eaa7c8cc0 100644 --- a/apps/web/src/dashboard/lib/collections.ts +++ b/apps/web/src/dashboard/lib/collections.ts @@ -1,5 +1,6 @@ import { writableChangelogStatus } from "@feeblo/domain/changelog/machine"; import type { CommentReaction } from "@feeblo/domain/comment-reaction/schema"; +import { HELP_CENTER_ARTICLE_LIST_MAX_LIMIT } from "@feeblo/domain/help-center-article/schema"; import type { TPostActivity } from "@feeblo/domain/post-activity/schema"; import type { PostReaction } from "@feeblo/domain/post-reaction/schema"; import type { PostSubscription } from "@feeblo/domain/post-subscription/schema"; @@ -33,6 +34,7 @@ import { BasicIndex, collectionOptions, DbClient, + getLoadSubsetDemandKey, parseLoadSubsetOptions, } from "@tanstack/react-db"; import type { @@ -733,10 +735,10 @@ export const HELP_CENTER_SECTION_ARTICLE_PAGE_SIZE = 25; * drift between the two would leave the section page showing the article as it * was before the save. * - * It is the section's prefix, not a page: the on-demand collection appends the - * `LoadSubsetOptions` it is asked for (the window and the filters) to this key, - * which is what gives each page its own cache entry while the editor can still - * invalidate every page of a section by its prefix. + * It is the section's prefix, not a page: the collection's key function appends + * the demand's identity (the window and the filters) to this key, which is what + * gives each page its own cache entry while the editor can still invalidate + * every page of a section by its prefix. */ export function helpCenterArticleTopicQueryKey( organizationId: string | undefined, @@ -764,6 +766,15 @@ export function helpCenterArticleTopicQueryKey( * order `sort: "updated"` names. The section page must order by the same two * columns the repository sorts by, or a window would be cut from one order and * rendered in another. + * + * The key is a function because a static on-demand key leaves the library a + * second, windowless "full source" query under the base key. That query asks + * for the whole section — the read pagination exists to remove — so the + * operation refuses it, and the editor's post-write invalidation, which + * refreshes this collection by its key, refetched the refused query and + * replaced the section page with its "Help center unavailable" state. A key + * function has no full-source query; the demand key it appends is the same + * identity the library appends to a static on-demand key itself. */ export function helpCenterTopicArticleCollection( scope: DashboardCollectionScope, @@ -778,7 +789,19 @@ export function helpCenterTopicArticleCollection( queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), - queryKey: helpCenterArticleTopicQueryKey(scope.organizationId, topicId), + // Each window is its own cache entry, so invalidating the section's + // prefix refreshes the pages that were asked for and cannot ask for the + // whole section to refresh them. + queryKey: (opts) => { + const base = helpCenterArticleTopicQueryKey( + scope.organizationId, + topicId + ); + + const demand = getLoadSubsetDemandKey(opts); + + return demand === undefined ? base : [...base, demand]; + }, queryFn: async (ctx) => { const organizationId = scope.organizationId; @@ -788,28 +811,36 @@ export function helpCenterTopicArticleCollection( const window = ctx.meta?.loadSubsetOptions; - // The page windows every read, and the operation refuses a - // section-scoped list without one: a demand that named no window would - // ask the server for the whole section, which is the read this - // collection exists to avoid. It fails there rather than quietly - // returning a page a windowless demander would take as complete. - // - // The list operation filters by workspace and section on the server; - // the live query keeps its predicate as a second guard. The - // workspace-wide collection stays for the plan-usage meter, which is - // the one caller allowed to read without a window. + /** + * The window this demand asks for, or the whole browsable section. + * + * The page's demands name a window, but the collection's loader also + * asks for subsets that an offset/limit operation cannot express: an + * authoritative re-read after a write, and the boundary repair it runs + * when a refetched page moved a row (a publication sends the article to + * the top). Those demands name no limit, and the operation refuses a + * section-scoped read without one — so answering them with the list's + * own ceiling is what keeps the section page alive instead of failing + * its list. A single page would be worse than the cost: the loader + * would take it as the extent of the source and drop rows that sit + * past it. + * + * The list operation filters by workspace and section on the server; + * the live query keeps its predicate as a second guard. The + * workspace-wide collection stays for the plan-usage meter, which is + * the one caller allowed to read without a topic. + */ + const limit = window?.limit ?? HELP_CENTER_ARTICLE_LIST_MAX_LIMIT; + const offset = window?.offset ?? 0; + const data = await fetchRpc( (rpc) => rpc.ListHelpCenterArticles({ organizationId, + limit, + offset, sort: "updated", topicId, - ...(window?.limit === undefined - ? undefined - : { limit: window.limit }), - ...(window?.offset === undefined - ? undefined - : { offset: window.offset }), }), { signal: ctx.signal } ); diff --git a/apps/web/src/routes/s/help/articles/$articleSlug.tsx b/apps/web/src/routes/s/help/articles/$articleSlug.tsx index 872287ffe..773af46d9 100644 --- a/apps/web/src/routes/s/help/articles/$articleSlug.tsx +++ b/apps/web/src/routes/s/help/articles/$articleSlug.tsx @@ -1,8 +1,15 @@ +import { PublicBoardPending } from "@feeblo/public-feature-board/components/pending"; import { createFileRoute } from "@tanstack/react-router"; import { HelpCenterArticlePage } from "@/portal/help-center/help-center-article-page"; export const Route = createFileRoute("/s/help/articles/$articleSlug")({ + // Same shape as the help center index: the article arrives through the + // portal's Effect atoms, which the server cannot build a protocol for and + // does not dehydrate, so the body renders in the browser. The layout above + // still resolves the article's metadata and JSON-LD for crawlers. + pendingComponent: PublicBoardPending, + ssr: false, component: RouteComponent, }); diff --git a/apps/web/src/routes/s/help/index.tsx b/apps/web/src/routes/s/help/index.tsx index 169654b76..ac739bad1 100644 --- a/apps/web/src/routes/s/help/index.tsx +++ b/apps/web/src/routes/s/help/index.tsx @@ -1,7 +1,21 @@ +import { PublicBoardPending } from "@feeblo/public-feature-board/components/pending"; import { createFileRoute } from "@tanstack/react-router"; import { HelpCenterPage } from "@/portal/help-center/help-center-page"; export const Route = createFileRoute("/s/help/")({ + // The body is client-rendered: it reads its documentation through Effect + // atoms, whose protocol is built from the browser's injected env and whose + // values are not dehydrated into the document. A server render would build + // the protocol from `undefined` and throw, and with that patched it would + // still produce markup the browser cannot reproduce on its first render — + // a hydration mismatch rather than a flash. The layout above still resolves + // the site and the page metadata for crawlers. + // + // The pending state must be the board's own: the router's default is the + // dashboard's skeleton, and for an `ssr: false` route that skeleton is what + // the server renders into the board shell. + pendingComponent: PublicBoardPending, + ssr: false, component: HelpCenterPage, }); diff --git a/docs/help-center.md b/docs/help-center.md index a4efb1fa8..2eee2b62b 100644 --- a/docs/help-center.md +++ b/docs/help-center.md @@ -51,10 +51,12 @@ A flip is an `UPDATE` of the same row. Flipping to helpful clears `reason`, beca **Portal** (`ListHelpCenterTopicsPublic`, `ListHelpCenterArticlesPublic`, `GetHelpCenterArticlePublic`, `GetHelpCenterArticleFeedbackPublic`, `SetHelpCenterArticleFeedback`, `AddHelpCenterArticleView`, `GetHelpCenterAvailabilityPublic`) sees `published` and `archived` only, reads by slug, and gates on `SitePolicy.canViewHelpCenter`. A section that holds no published article is not listed, so publishing an empty section cannot disclose the draft pipeline. `GetHelpCenterAvailabilityPublic` is the same gate answered as a yes/no: the board's navbar draws its Help tab from it, so a public help center nobody has written into yet gets no tab that opens onto “No documentation yet” — the rule the widget already applies to its own tab. -**Dashboard routes.** `/$organizationId/help-center` lists the sections and their article counts, and is the only place a section is created; its row menu also moves a section up or down, sending the complete order to `ReorderHelpCenterTopics`. `/$organizationId/help-center/$topicId` is one section: its articles with the three counters, a page at a time — the list asks the collection for a window and `Load more` widens it — plus the section's edit and delete actions. `/$organizationId/help-center/$topicId/new` and `/$organizationId/help-center/article/$articleId` are the editor, opened on the create page with its section already chosen. It has the changelog editor's shape: a cover image, a title, the body, and a sidebar with the section. The slug is not a field — it is chosen in the publish dialog, so a save cannot move a live page's URL — and saving keeps the current status while publishing asks for the slug and date. A save carries the status **and** `updatedAt` the editor loaded, so a colleague's same-status save is a conflict rather than an overwrite; a refreshed row shows a reload banner and disables the write actions. The state changes the lifecycle does not derive from those (`archive`, `restore`) are offered beside the article's delete action, which asks for confirmation because a hard delete breaks the public URL. The body is edited in the same ProseKit editor the changelog uses and stored as Markdown — the editor serializes its document to Markdown and parses it back — so pasted images are written to `tmp/editor-media/` and the write's `assetIds` let the handler promote them to permanent objects before the row stores their URLs. The list collection holds summaries only — the editor reads one article by id and writes through the RPC operations, then invalidates the section's query key rather than waiting on a workspace-wide list. The editor's sidebar also shows the article's recent unhelpful votes with reasons, manager-only. The dashboard's search is a command dialog behind an icon in the index toolbar; it reads the dashboard `SearchHelpCenterArticles` operation, so drafts are findable. +**Dashboard routes.** `/$organizationId/help-center` lists the sections and their article counts, and is the only place a section is created; its row menu also moves a section up or down, sending the complete order to `ReorderHelpCenterTopics`. `/$organizationId/help-center/$topicId` is one section: its articles with the three counters, a page at a time — the list asks the collection for a window and `Load more` widens it — plus the section's edit and delete actions. `/$organizationId/help-center/$topicId/new` and `/$organizationId/help-center/article/$articleId` are the editor, opened on the create page with its section already chosen. It has the changelog editor's shape: a cover image, a title, the body, and a sidebar with the section. The slug is not a field — it is chosen in the publish dialog, so a save cannot move a live page's URL — and saving keeps the current status while publishing asks for the slug and date. A save carries the status **and** `updatedAt` the editor loaded, so a colleague's same-status save is a conflict rather than an overwrite; a refreshed row shows a reload banner and disables the write actions. The state changes the lifecycle does not derive from those (`archive`, `restore`) are offered beside the article's delete action, which asks for confirmation because a hard delete breaks the public URL. The body is edited in the same ProseKit editor the changelog uses and stored as Markdown — the editor serializes its document to Markdown and parses it back — so pasted images are written to `tmp/editor-media/` and the write's `assetIds` let the handler promote them to permanent objects before the row stores their URLs. The list collection holds summaries only — the editor reads one article by id and writes through the RPC operations, then invalidates the section's query key rather than waiting on a workspace-wide list. That key is a function of the demanded window rather than a static base key: a static on-demand key leaves the library a second, windowless query for the whole section, which the operation refuses. The collection also answers the loader's windowless authoritative reads — the re-read after a write and the boundary repair when a refetched page moved a row — with the list's 500-row ceiling, because an offset/limit operation cannot express the boundary and refusing the read replaced the section page with its unavailable state after a save. The editor's sidebar also shows the article's recent unhelpful votes with reasons, manager-only. The dashboard's search is a command dialog behind an icon in the index toolbar; it reads the dashboard `SearchHelpCenterArticles` operation, so drafts are findable. **Portal routes.** `/s/help` and `/s/help/articles/$articleSlug`, in three columns: a rail of sections that opens in place, the article — cover image, title, section, reading time, the stored Markdown with heading anchors, the verdict — and a rail with "On this page", the article's actions, and a pointer to the board. The actions are Copy as Markdown, Export (download the Markdown mirror or print to PDF), Open in chat (a prefilled prompt pointed at the Markdown mirror), and Connect to MCP (the board's help-center MCP endpoint, with copy-ready client commands). Below `xl` they ride under the "On this page" disclosure, or in an "Article actions" disclosure when the article has no outline. Previous/next stay inside the section. The rails render from the public list, so navigating between articles never unmounts them: sections the reader opened stay open while the next body loads. +Both portal routes are `ssr: false`: their bodies read the public projections through Effect atoms, whose protocol is built from the browser's injected env and whose values are not dehydrated into the document, so a server render would produce markup the browser cannot reproduce on its first render. The layout above still server-renders the site, the page metadata and the article's JSON-LD for crawlers. + **Widget.** The same documentation is a widget module (`help`) beside `feedback` and `updates`, for a customer who would rather read than post. Two endpoints serve it: `POST /api/widget/v1/help-center` lists every published article with its section, ordered by section then article, so the iframe groups them without a topic read; `POST /api/widget/v1/help-center/article` answers one article by slug, rendered to HTML through the cached pipeline the updates module uses, or `article: null` for a slug that is not published — a reader cannot tell a draft from a typo. Both answer `enabled: false` under the same conditions as the deflection below — and the list also answers it when nothing is readable, because the widget's tab is decided by that one value and an empty documentation page is worse than no tab. Archived articles travel with `isArchived`, like the portal's carrier: a withdrawn page still resolves and says it is out of date. A hub whose only remaining surface is one tab renders no tab bar, so a reader who landed on `/help` is moved to the first module that exists rather than being left on a page that will never fill; a single-module `help` embed keeps its own empty state, since there is nowhere else to send them. ## Search diff --git a/e2e/helpers/help-center.ts b/e2e/helpers/help-center.ts new file mode 100644 index 000000000..e2193ac63 --- /dev/null +++ b/e2e/helpers/help-center.ts @@ -0,0 +1,186 @@ +import { expect, type Page } from "@playwright/test"; + +import { waitForHydration } from "./hydration"; +import { fillEditor } from "./posts"; +import { publicBoardUrl } from "./urls"; + +/** + * The dashboard's help center, exercised the way an editor uses it. + * + * The article editor is reached through the section it belongs to rather than + * by URL: the section page is where "New article" lives and where a saved + * article lands, so walking that path is what a save has to keep working. + */ + +/** The section row on the help center index, by name. */ +const sectionLink = (page: Page, name: string) => + page.getByRole("link").filter({ has: page.getByText(name, { exact: true }) }); + +/** One section's row in the help center index's table. */ +export const helpCenterSectionRow = (page: Page, name: string) => + page.getByRole("row").filter({ has: page.getByText(name, { exact: true }) }); + +/** + * One article's row in a section's table. + * + * The title link is the row's whole identity, so filtering by it also keeps the + * assertion working when another row's title contains this one. + */ +export const helpCenterArticleRow = (page: Page, title: string) => + page + .getByRole("row") + .filter({ has: page.getByRole("link", { name: title, exact: true }) }); + +/** + * One article's link on the public help center index. + * + * Not matched by accessible name: the row's link also carries the excerpt and + * the archived badge, so the name is "title, excerpt…" rather than the title + * alone. Filtering on the title's own element is what keeps the locator stable + * as the excerpt changes. + */ +export const publicHelpCenterArticleLink = (page: Page, title: string) => + page + .getByRole("link") + .filter({ has: page.getByText(title, { exact: true }) }); + +/** + * One section's card on the public index. + * + * The index renders each section as a `section` holding its heading, so the + * card is what a test scopes to when it cares which section an article is + * listed under — not merely that both exist on the page. + */ +export const publicHelpCenterSection = (page: Page, name: string) => + page + .getByRole("heading", { name, exact: true }) + .locator("xpath=ancestor::section[1]"); + +export const helpCenterUrl = (workspaceName: string) => + `${publicBoardUrl(workspaceName)}/help`; + +export const helpCenterArticleUrl = (workspaceName: string, slug: string) => + `${helpCenterUrl(workspaceName)}/articles/${slug}`; + +/** Opens the dashboard's help center from the sidebar. */ +export async function openHelpCenter(page: Page) { + await page.getByRole("link", { name: "Help center", exact: true }).click(); + await expect(page).toHaveURL(/\/help-center\/?$/); +} + +/** + * Creates a section through the index dialog and resolves on the index, with + * the new row visible. + */ +export async function createHelpCenterSection( + page: Page, + name: string, + description?: string +) { + await openHelpCenter(page); + await page.getByRole("button", { name: "New section" }).click(); + + const dialog = page.getByRole("dialog", { name: "New section" }); + await expect(dialog).toBeVisible(); + await dialog.getByLabel("Name").fill(name); + + if (description !== undefined) { + await dialog.getByLabel("Description").fill(description); + } + + await dialog.getByRole("button", { name: "Create section" }).click(); + await expect(dialog).toBeHidden(); + await expect(sectionLink(page, name)).toBeVisible(); +} + +/** + * Opens a section from the index. + * + * The index is re-read every time rather than assuming the page is already + * there, because a save navigates back to a section and a later call would + * otherwise run against whichever page the previous step left behind. + */ +export async function openHelpCenterSection(page: Page, name: string) { + await openHelpCenter(page); + await sectionLink(page, name).click(); + await expect(page.getByRole("heading", { name, exact: true })).toBeVisible(); +} + +/** + * Writes an article in the given section and saves it as a draft. + * + * A fresh article is a draft — publication is the dialog's job — so this is the + * plain save an editor makes first, and it must land back on the section with + * the row present. + */ +export async function createHelpCenterArticle( + page: Page, + input: { + content: string; + section: string; + title: string; + } +) { + await openHelpCenterSection(page, input.section); + + // A link, not a button: the create action is a `Button` rendered as a router + // `Link`, which gives it the anchor role and the client-side navigation. + await page.getByRole("link", { name: "New article" }).click(); + await expect(page).toHaveURL(/\/help-center\/[^/]+\/new$/); + + const title = page.getByLabel("Title", { exact: true }); + await title.fill(input.title); + await fillEditor(page, input.content); + + await page.getByRole("button", { name: "Save", exact: true }).click(); + + await expect(page).toHaveURL(/\/help-center\/[^/]+\/?$/); + await expect(helpCenterArticleRow(page, input.title)).toBeVisible(); +} + +/** Opens a saved article's editor from its section's table. */ +export async function openHelpCenterArticle(page: Page, title: string) { + const link = page.getByRole("link", { name: title, exact: true }); + await expect(link).toBeVisible(); + await link.click(); + + await expect(page).toHaveURL(/\/help-center\/article\/[^/]+$/); + await expect(page.getByLabel("Title", { exact: true })).toHaveValue(title); +} + +/** + * Publishes an article under the given slug. + * + * Opens the article from its section's table first, because a save already + * navigated away: the editor is never the page a previous step left open. + * Publishing then navigates to the section the write landed in, so the row's + * state is what the caller reads afterwards. + */ +export async function publishHelpCenterArticle( + page: Page, + input: { slug: string; title: string } +) { + await openHelpCenterArticle(page, input.title); + + await page.getByRole("button", { name: "Publish", exact: true }).click(); + + const dialog = page.getByRole("alertdialog", { name: "Publish article" }); + await expect(dialog).toBeVisible(); + await dialog.getByLabel("Slug").fill(input.slug); + await dialog.getByRole("button", { name: "Publish", exact: true }).click(); + await expect(dialog).toBeHidden(); + + await expect(page).toHaveURL(/\/help-center\/[^/]+\/?$/); + await expect(helpCenterArticleRow(page, input.title)).toContainText( + "Published" + ); +} + +/** + * Opens a workspace's public help center as a visitor and resolves once the + * page is interactive. + */ +export async function openPublicHelpCenter(page: Page, workspaceName: string) { + await page.goto(helpCenterUrl(workspaceName)); + await waitForHydration(page); +} diff --git a/e2e/tests/help-center-articles.spec.ts b/e2e/tests/help-center-articles.spec.ts new file mode 100644 index 000000000..d4b83fbfb --- /dev/null +++ b/e2e/tests/help-center-articles.spec.ts @@ -0,0 +1,707 @@ +import { randomUUID } from "node:crypto"; + +import { expect, type Page, test } from "../fixtures"; +import { createAuthenticatedWorkspace } from "../helpers/auth"; +import { + createHelpCenterArticle, + createHelpCenterSection, + helpCenterArticleRow, + helpCenterArticleUrl, + helpCenterSectionRow, + helpCenterUrl, + openHelpCenter, + openHelpCenterArticle, + openHelpCenterSection, + openPublicHelpCenter, + publicHelpCenterArticleLink, + publicHelpCenterSection, + publishHelpCenterArticle, +} from "../helpers/help-center"; +import { waitForHydration } from "../helpers/hydration"; +import { assertNoPageErrors, trackPageErrors } from "../helpers/page-errors"; +import { waitForRpc } from "../helpers/rpc"; +import { createTestUser } from "../helpers/test-users"; +import { publicBoardUrl } from "../helpers/urls"; + +/** + * The dashboard's article table, in column order: title, status, views, + * helpful, published, updated. + */ +const VIEWS_CELL = 2; + +const viewsCell = (page: Page, title: string) => + helpCenterArticleRow(page, title).getByRole("cell").nth(VIEWS_CELL); + +test.describe("help center articles", () => { + test.beforeEach(({ page }) => { + trackPageErrors(page); + }); + + test.afterEach(async ({ page }) => { + await assertNoPageErrors(page); + }); + + test("a draft article is not published to the public help center", async ({ + page, + }) => { + const user = createTestUser(); + await createAuthenticatedWorkspace(page, user); + + const section = "Getting started"; + await createHelpCenterSection( + page, + section, + "Everything a new account needs." + ); + + const title = `Draft article ${randomUUID().slice(0, 8)}`; + await createHelpCenterArticle(page, { + content: "This article is still being written.", + section, + title, + }); + + // The dashboard sees every lifecycle state, so the row is there the moment + // it is saved — as a draft, because publishing is a separate decision. + await expect(helpCenterArticleRow(page, title)).toContainText("Draft"); + + await openPublicHelpCenter(page, user.workspaceName); + + // Nothing is published, so the portal has nothing to list and the board has + // no Help tab to open: the tab is drawn from the availability read, not + // from the visibility switch alone. + await expect( + page.getByText("No documentation yet", { exact: true }) + ).toBeVisible(); + await expect(page.getByText(title)).toHaveCount(0); + await expect( + page.getByRole("link", { name: "Help", exact: true }) + ).toHaveCount(0); + }); + + test("a visitor reads a published article and rates it", async ({ + browser, + page, + }) => { + const user = createTestUser(); + await createAuthenticatedWorkspace(page, user); + + const section = "Getting started"; + await createHelpCenterSection( + page, + section, + "Everything a new account needs." + ); + + // A second section with nothing published in it: publishing a section that + // holds only drafts would disclose the shape of documentation nobody can + // read yet, so the portal must not list it. + await createHelpCenterSection(page, "Billing", "Plans and invoices."); + + const title = `Getting started article ${randomUUID().slice(0, 8)}`; + const body = "Invite your team from the members page."; + const slug = `getting-started-${randomUUID().slice(0, 8)}`; + const reason = "It does not say what happens to pending invitations."; + + await createHelpCenterArticle(page, { content: body, section, title }); + await publishHelpCenterArticle(page, { slug, title }); + + // The mirror is the same article's agent surface: the stored Markdown, with + // no robots indexing of a copy that would compete with the page. + const mirror = await page.request.get( + `${publicBoardUrl(user.workspaceName)}/help/articles/raw/${slug}.md` + ); + + expect(mirror.status()).toBe(200); + expect(mirror.headers()["x-robots-tag"]).toContain("noindex"); + expect(await mirror.text()).toContain(body); + + // The body renders in the browser, but the document a crawler reads keeps + // the article's own metadata: the layout resolves it on the server, so + // client-rendering the body must not take the search result with it. + const document = await page.request.get( + helpCenterArticleUrl(user.workspaceName, slug) + ); + + const html = await document.text(); + + expect(document.status()).toBe(200); + expect(html).toContain( + `${title} — ${user.workspaceName} help center` + ); + expect(html).toContain('"@type":"TechArticle"'); + + const visitorContext = await browser.newContext(); + const visitorPage = await visitorContext.newPage(); + trackPageErrors(visitorPage); + + try { + await visitorPage.goto(publicBoardUrl(user.workspaceName)); + await waitForHydration(visitorPage); + + // The tab exists because there is something to open. + await visitorPage + .getByRole("link", { name: "Help", exact: true }) + .click(); + await expect(visitorPage).toHaveURL(/\/help$/); + await expect( + visitorPage.getByRole("heading", { name: "Help center", exact: true }) + ).toBeVisible(); + + await expect( + visitorPage.getByRole("heading", { name: section, exact: true }) + ).toBeVisible(); + await expect( + visitorPage.getByRole("heading", { name: "Billing", exact: true }) + ).toHaveCount(0); + + // The view beacon fires once the article is on the page, so capturing it + // before the click turns the counter assertion below into a round trip + // rather than a race against the write. + const view = waitForRpc(visitorPage, "AddHelpCenterArticleView"); + + await publicHelpCenterArticleLink(visitorPage, title).click(); + await expect( + visitorPage.getByRole("heading", { name: title, exact: true }) + ).toBeVisible(); + expect((await view).ok()).toBeTruthy(); + + await expect(visitorPage.getByText(body, { exact: true })).toBeVisible(); + await expect(visitorPage.getByText("Was this helpful?")).toBeVisible(); + await expect(visitorPage.getByText("No votes yet.")).toBeVisible(); + + // One verdict per reader, flipped in place: the second answer replaces the + // first rather than adding a second vote to the tally. + await visitorPage + .getByRole("button", { name: "Yes", exact: true }) + .click(); + await expect( + visitorPage.getByText("1 of 1 readers found this helpful.") + ).toBeVisible(); + await expect( + visitorPage.getByRole("button", { name: "Yes", exact: true }) + ).toHaveAttribute("aria-pressed", "true"); + + await visitorPage + .getByRole("button", { name: "No", exact: true }) + .click(); + + // "No" asks what was missing: the verdict is recorded, and the reason is + // the second half of the same answer. + const reasonField = visitorPage.getByLabel("What was missing?"); + await expect(reasonField).toBeVisible(); + await expect( + visitorPage.getByText("0 of 1 readers found this helpful.") + ).toBeVisible(); + + await reasonField.fill(reason); + await visitorPage + .getByRole("button", { name: "Send feedback", exact: true }) + .click(); + await expect(reasonField).toBeHidden(); + + // The verdict survives a reload, which means it was stored against this + // reader rather than drawn from the press that made it. + await visitorPage.reload(); + await waitForHydration(visitorPage); + await expect( + visitorPage.getByText("0 of 1 readers found this helpful.") + ).toBeVisible(); + await expect( + visitorPage.getByRole("button", { name: "No", exact: true }) + ).toHaveAttribute("aria-pressed", "true"); + await assertNoPageErrors(visitorPage); + } finally { + await visitorContext.close(); + } + + // A reload is what makes the counters server-read rather than cached from + // before the visit: the dashboard's table counts what the reader did. + await page.reload(); + await expect(viewsCell(page, title)).toHaveText("1"); + + // The reason is what the editor's Reader feedback panel exists for, so the + // reader's answer has to survive the trip back into the dashboard. + await openHelpCenterArticle(page, title); + await expect( + page.getByRole("heading", { name: "Reader feedback", exact: true }) + ).toBeVisible(); + await expect(page.getByText(reason, { exact: true })).toBeVisible(); + }); + + test("archiving keeps the public link working and deleting ends it", async ({ + browser, + page, + }) => { + const user = createTestUser(); + await createAuthenticatedWorkspace(page, user); + + const section = "Getting started"; + await createHelpCenterSection(page, section); + + const title = `Archivable article ${randomUUID().slice(0, 8)}`; + const slug = `archivable-${randomUUID().slice(0, 8)}`; + + await createHelpCenterArticle(page, { + content: "This page is about to be withdrawn.", + section, + title, + }); + await publishHelpCenterArticle(page, { slug, title }); + + // Archiving is not deleting: the page is withdrawn from the documentation + // but its URL keeps resolving for the links already written down. + await openHelpCenterArticle(page, title); + await page.getByRole("button", { name: "More article actions" }).click(); + await page.getByRole("menuitem", { name: "Archive article" }).click(); + await expect(helpCenterArticleRow(page, title)).toContainText("Archived"); + + const visitorContext = await browser.newContext(); + const visitorPage = await visitorContext.newPage(); + trackPageErrors(visitorPage); + + try { + await visitorPage.goto(helpCenterUrl(user.workspaceName)); + await waitForHydration(visitorPage); + + const articleLink = publicHelpCenterArticleLink(visitorPage, title); + await expect(articleLink).toBeVisible(); + await expect(articleLink.getByText("Out of date")).toBeVisible(); + await articleLink.click(); + + await expect( + visitorPage.getByRole("heading", { name: title, exact: true }) + ).toBeVisible(); + await expect( + visitorPage.getByText( + "This article describes behaviour that is no longer current." + ) + ).toBeVisible(); + + // Deleting is the one action that breaks a URL readers may have + // bookmarked, so it asks first and names the article it would remove. + await openHelpCenterArticle(page, title); + await page.getByRole("button", { name: "Delete article" }).click(); + + const dialog = page.getByRole("alertdialog", { + name: `Delete "${title}"?`, + }); + + await expect(dialog).toBeVisible(); + await dialog.getByRole("button", { name: "Delete article" }).click(); + await expect(dialog).toBeHidden(); + await expect( + page.getByRole("link", { name: title, exact: true }) + ).toHaveCount(0); + + // Both the page and its Markdown mirror stop answering, which is what + // "permanent" means for the URL the dialog warned about. + const mirror = await page.request.get( + `${publicBoardUrl(user.workspaceName)}/help/articles/raw/${slug}.md` + ); + + expect(mirror.status()).toBe(404); + + const missing = await visitorPage.goto( + helpCenterArticleUrl(user.workspaceName, slug) + ); + + await waitForHydration(visitorPage); + + // A deleted article is gone at the URL, not merely unpublished: the + // board's own 404 page answers the request with a 404, so a crawler does + // not keep a link that will never work again. + expect(missing?.status()).toBe(404); + await expect( + visitorPage.getByText("Page not found", { exact: true }) + ).toBeVisible(); + await assertNoPageErrors(visitorPage, [ + // The document is deliberately a 404, and Chromium reports that + // status as a failed resource for the navigation itself. + /Failed to load resource: the server responded with a status of 404/, + ]); + } finally { + await visitorContext.close(); + } + }); + + test("publishing under a URL another article already uses is refused in place", async ({ + page, + }) => { + const user = createTestUser(); + await createAuthenticatedWorkspace(page, user); + + const section = "Getting started"; + await createHelpCenterSection(page, section); + + const firstTitle = `First article ${randomUUID().slice(0, 8)}`; + const takenSlug = `taken-${randomUUID().slice(0, 8)}`; + + await createHelpCenterArticle(page, { + content: "The first page to own this URL.", + section, + title: firstTitle, + }); + await publishHelpCenterArticle(page, { + slug: takenSlug, + title: firstTitle, + }); + + const secondTitle = `Second article ${randomUUID().slice(0, 8)}`; + + await createHelpCenterArticle(page, { + content: "The second page to ask for it.", + section, + title: secondTitle, + }); + await openHelpCenterArticle(page, secondTitle); + + await page.getByRole("button", { name: "Publish", exact: true }).click(); + + const dialog = page.getByRole("alertdialog", { name: "Publish article" }); + await expect(dialog).toBeVisible(); + await dialog.getByLabel("Slug").fill(takenSlug); + await dialog.getByRole("button", { name: "Publish", exact: true }).click(); + + // A refused publication keeps the dialog open on the values the editor + // entered, so the slug can be fixed without retyping the date. + await expect( + page.getByText( + "That URL is already used by another article. Choose a different slug." + ) + ).toBeVisible(); + await expect(dialog).toBeVisible(); + await expect(dialog.getByLabel("Slug")).toHaveValue(takenSlug); + + const secondSlug = `second-${randomUUID().slice(0, 8)}`; + + await dialog.getByLabel("Slug").fill(secondSlug); + await dialog.getByRole("button", { name: "Publish", exact: true }).click(); + await expect(dialog).toBeHidden(); + await expect(helpCenterArticleRow(page, secondTitle)).toContainText( + "Published" + ); + + // The slug is not a form field, so a later save cannot move the URL the + // publication chose: editing a live page's title is not renaming its link. + await openHelpCenterArticle(page, secondTitle); + + const renamedTitle = `${secondTitle} renamed`; + await page.getByLabel("Title", { exact: true }).fill(renamedTitle); + await page.getByRole("button", { name: "Save", exact: true }).click(); + await expect(page).toHaveURL(/\/help-center\/[^/]+\/?$/); + + const renamed = await page.request.get( + `${publicBoardUrl(user.workspaceName)}/help/articles/${secondSlug}` + ); + + expect(renamed.status()).toBe(200); + expect(await renamed.text()).toContain(renamedTitle); + }); + + test("a section's description and icon reach the portal", async ({ + page, + }) => { + const user = createTestUser(); + await createAuthenticatedWorkspace(page, user); + + const section = "Getting started"; + const description = "Everything a new account needs."; + + await createHelpCenterSection(page, section, description); + + // A section is only listed on the portal while it holds something a reader + // can open, so the description assertion needs a published article. + const title = `Section article ${randomUUID().slice(0, 8)}`; + + await createHelpCenterArticle(page, { + content: "A page so the section is public.", + section, + title, + }); + await publishHelpCenterArticle(page, { + slug: `section-${randomUUID().slice(0, 8)}`, + title, + }); + + // The row carries what the dialog wrote, not only the name. + await openHelpCenter(page); + await expect(helpCenterSectionRow(page, section)).toContainText( + description + ); + + // Renaming keeps the section's URL and its articles — the dialog edits all + // three fields at once. + await page.getByRole("button", { name: `Actions for ${section}` }).click(); + await page.getByRole("menuitem", { name: "Edit section" }).click(); + + const dialog = page.getByRole("dialog", { name: "Edit section" }); + + await expect(dialog).toBeVisible(); + await dialog.getByLabel("Name").fill("Getting set up"); + await dialog + .getByLabel("Description") + .fill("Setup steps for a new account."); + + // The picker is a popover with a searchable icon grid; the trigger shows + // only the label, so the row's sprite is where the choice becomes visible. + await dialog.getByRole("button", { name: "Choose icon" }).click(); + await page.getByPlaceholder("Search icons…").fill("jetpack"); + await page.getByRole("gridcell", { name: "Jetpack" }).click(); + + const save = waitForRpc(page, "UpdateHelpCenterTopic"); + + await dialog.getByRole("button", { name: "Save section" }).click(); + expect((await save).ok()).toBeTruthy(); + await expect(dialog).toBeHidden(); + + const renamed = helpCenterSectionRow(page, "Getting set up"); + + await expect(renamed).toContainText("Setup steps for a new account."); + await expect( + renamed.locator( + 'svg[data-slot="tabler-icon"] use[href="#tabler-filled-jetpack"]' + ) + ).toHaveCount(1); + + await openPublicHelpCenter(page, user.workspaceName); + + await expect( + page.getByRole("heading", { name: "Getting set up", exact: true }) + ).toBeVisible(); + await expect( + page.getByText("Setup steps for a new account.", { exact: true }) + ).toBeVisible(); + }); + + test("moving an article between sections refreshes both lists", async ({ + page, + }) => { + const user = createTestUser(); + await createAuthenticatedWorkspace(page, user); + + const from = "Getting started"; + const to = "Billing"; + + await createHelpCenterSection( + page, + from, + "Everything a new account needs." + ); + await createHelpCenterSection(page, to, "Plans and invoices."); + + const title = `Movable article ${randomUUID().slice(0, 8)}`; + const slug = `movable-${randomUUID().slice(0, 8)}`; + + await createHelpCenterArticle(page, { + content: "This article changes sections.", + section: from, + title, + }); + await publishHelpCenterArticle(page, { slug, title }); + + // The section control is a set of pressed chips rather than a select. + await openHelpCenterArticle(page, title); + + const billingChip = page.getByRole("button", { name: to, exact: true }); + + await billingChip.click(); + await expect(billingChip).toHaveAttribute("aria-pressed", "true"); + await page.getByRole("button", { name: "Save", exact: true }).click(); + + // The save lands on the section the article joined, and the old list is + // refetched too — the pair of reads the editor's invalidation covers. + await expect( + page.getByRole("heading", { name: to, exact: true }) + ).toBeVisible(); + await expect(helpCenterArticleRow(page, title)).toContainText("Published"); + + await openHelpCenterSection(page, from); + // The list starts empty and loads its window separately from the heading, + // so a bare count of zero would pass before the page had read anything. + // The empty state is the page's own answer that the section holds none. + await expect( + page.getByText("No articles yet", { exact: true }) + ).toBeVisible(); + await expect( + page.getByRole("link", { name: title, exact: true }) + ).toHaveCount(0); + + // The portal groups the article under the section it now belongs to, and + // the section it left is not listed while it holds nothing readable. + await openPublicHelpCenter(page, user.workspaceName); + + const billing = publicHelpCenterSection(page, to); + + await expect(billing).toBeVisible(); + await expect( + billing + .getByRole("link") + .filter({ has: page.getByText(title, { exact: true }) }) + ).toBeVisible(); + await expect( + page.getByRole("heading", { name: from, exact: true }) + ).toHaveCount(0); + + // Moving a page is not renaming its URL. + const response = await page.request.get( + helpCenterArticleUrl(user.workspaceName, slug) + ); + + expect(response.status()).toBe(200); + }); + + test("unpublishing and restoring an article changes what readers can open", async ({ + page, + }) => { + const user = createTestUser(); + await createAuthenticatedWorkspace(page, user); + + const section = "Getting started"; + + await createHelpCenterSection(page, section); + + const title = `Withdrawn article ${randomUUID().slice(0, 8)}`; + const slug = `withdrawn-${randomUUID().slice(0, 8)}`; + const articleUrl = helpCenterArticleUrl(user.workspaceName, slug); + const mirrorUrl = `${publicBoardUrl(user.workspaceName)}/help/articles/raw/${slug}.md`; + + await createHelpCenterArticle(page, { + content: "The article is withdrawn and restored.", + section, + title, + }); + await publishHelpCenterArticle(page, { slug, title }); + + // Published: the page and its mirror both answer. + expect((await page.request.get(articleUrl)).status()).toBe(200); + expect((await page.request.get(mirrorUrl)).status()).toBe(200); + + // Turning it into a draft keeps the row but takes the URL away. + await openHelpCenterArticle(page, title); + await page + .getByRole("button", { name: "Turn into draft", exact: true }) + .click(); + await expect(helpCenterArticleRow(page, title)).toContainText("Draft"); + expect((await page.request.get(articleUrl)).status()).toBe(404); + expect((await page.request.get(mirrorUrl)).status()).toBe(404); + + // Publishing again brings the same URL back — the slug did not move. + await publishHelpCenterArticle(page, { slug, title }); + expect((await page.request.get(articleUrl)).status()).toBe(200); + + // Archiving is the softer withdrawal: the page stays and says so. + await openHelpCenterArticle(page, title); + await page.getByRole("button", { name: "More article actions" }).click(); + await page.getByRole("menuitem", { name: "Archive article" }).click(); + await expect(helpCenterArticleRow(page, title)).toContainText("Archived"); + expect((await page.request.get(articleUrl)).status()).toBe(200); + + // Restoring goes back to a draft, not straight to what readers had. + await openHelpCenterArticle(page, title); + await page + .getByRole("button", { name: "Restore to draft", exact: true }) + .click(); + await expect(helpCenterArticleRow(page, title)).toContainText("Draft"); + expect((await page.request.get(articleUrl)).status()).toBe(404); + }); + + test("hiding the help center takes its pages and Markdown mirror away", async ({ + page, + }) => { + const user = createTestUser(); + const workspace = await createAuthenticatedWorkspace(page, user); + + const section = "Getting started"; + + await createHelpCenterSection(page, section); + + const title = `Private article ${randomUUID().slice(0, 8)}`; + const slug = `private-${randomUUID().slice(0, 8)}`; + const articleUrl = helpCenterArticleUrl(user.workspaceName, slug); + const mirrorUrl = `${publicBoardUrl(user.workspaceName)}/help/articles/raw/${slug}.md`; + + await createHelpCenterArticle(page, { + content: "Documentation the workspace can hide.", + section, + title, + }); + await publishHelpCenterArticle(page, { slug, title }); + + expect((await page.request.get(articleUrl)).status()).toBe(200); + + await page.goto( + `${workspace.organizationUrl}/settings/help-center-privacy` + ); + + const privacy = page.getByRole("switch"); + + await expect(privacy).toBeChecked(); + await privacy.click(); + await expect(page.getByText("Help center privacy updated")).toBeVisible(); + await expect(privacy).not.toBeChecked(); + + // The gate is read per request, so the article page, the mirror and the + // index all stop answering. Hiding is not just a missing tab. + await expect + .poll(async () => (await page.request.get(articleUrl)).status(), { + timeout: 15_000, + }) + .toBe(404); + expect((await page.request.get(mirrorUrl)).status()).toBe(404); + expect( + (await page.request.get(helpCenterUrl(user.workspaceName))).status() + ).toBe(404); + + // Switching it back restores the documentation without republishing. + await expect(privacy).toBeEnabled(); + await privacy.click(); + await expect(privacy).toBeChecked(); + await expect + .poll(async () => (await page.request.get(articleUrl)).status(), { + timeout: 15_000, + }) + .toBe(200); + }); + + test("the portal search finds an article and says when nothing matches", async ({ + page, + }) => { + const user = createTestUser(); + await createAuthenticatedWorkspace(page, user); + + const section = "Getting started"; + + await createHelpCenterSection(page, section); + + const title = `Searchable article ${randomUUID().slice(0, 8)}`; + + await createHelpCenterArticle(page, { + content: "Exports are documented on this page.", + section, + title, + }); + await publishHelpCenterArticle(page, { + slug: `searchable-${randomUUID().slice(0, 8)}`, + title, + }); + + await openPublicHelpCenter(page, user.workspaceName); + + const search = page.getByRole("searchbox", { + name: "Search the help center", + }); + + await search.fill("searchable"); + + // Ranked results replace the section tree rather than filtering it. + await expect(publicHelpCenterArticleLink(page, title)).toBeVisible(); + await expect(page.getByText("1 article", { exact: true })).toBeVisible(); + + await search.fill(`zzzz${randomUUID().replaceAll("-", "").slice(0, 8)}`); + await expect( + page.getByText("No matching articles", { exact: true }) + ).toBeVisible(); + await expect(publicHelpCenterArticleLink(page, title)).toHaveCount(0); + }); +});