diff --git a/apps/web/src/page/status-pages/builder/view.ts b/apps/web/src/page/status-pages/builder/view.ts index a74a3c872a..3f171973c9 100644 --- a/apps/web/src/page/status-pages/builder/view.ts +++ b/apps/web/src/page/status-pages/builder/view.ts @@ -25,6 +25,7 @@ import { publicAddress, publicUrl, STATUS_PAGE_BASE_URL, statusPagesHref } from import { textField } from "../shared/fields" import { APPEARANCES, presetCards } from "../shared/look" import { monitorStatusOf } from "../shared/derive" +import { orNull } from "../shared/form" import { checkedRows } from "../shared/picker" import { pickerView } from "../shared/picker-view" import { daysOf, previewDocument, previewFrame, previewTheme } from "../shared/preview" @@ -182,7 +183,7 @@ const draftDocument = (model: Model): string => { id: draftComponentId(index), name: Str.trim(row.name) === "" ? "Untitled component" : Str.trim(row.name), description: null, - group: Str.trim(row.group) === "" ? null : Str.trim(row.group), + group: orNull(row.group), monitorStatus: monitorStatusOf(monitors, row.monitorId), manualStatus: row.monitorId === null ? row.manualStatus : null, showUptime: true, @@ -196,7 +197,6 @@ const draftDocument = (model: Model): string => { snapshot, nowMs, isSelectable: false, - selectedIds: [], publicUrl: isSlug(model.slug) ? publicUrl(STATUS_PAGE_BASE_URL, model.slug) : null, }) } diff --git a/apps/web/src/page/status-pages/editor/analyst.scene.test.ts b/apps/web/src/page/status-pages/editor/analyst.scene.test.ts index 2101d07174..194c0e6fc6 100644 --- a/apps/web/src/page/status-pages/editor/analyst.scene.test.ts +++ b/apps/web/src/page/status-pages/editor/analyst.scene.test.ts @@ -2,7 +2,9 @@ import { OrgId } from "@maple/domain" import { StatusPagePublicId } from "@maple/domain/http/v2" import * as Policy from "@maple/domain/policy" import { Result, Schema, Array as Arr } from "effect" -import { expect as expectView, given, role, scene, text, withViewInputs } from "foldkit/scene" +import { expect as expectView, given, Mount, role, scene, text, withViewInputs } from "foldkit/scene" +import * as Dialog from "@maple/views/ui/dialog" +import { MountDialog } from "@maple/views/ui/dialog" import { describe, test } from "vitest" import type { PageContext } from "../../contract" import { ORG } from "../../kit/alert-test-rows" @@ -23,13 +25,17 @@ const view = withViewInputs(pageView, { context })() const MEMBER = Policy.grantsOf(["org:member"]) const ANALYST = Policy.grantsOf(["org:analyst"]) -/** The editor's Page tab over `incidents`, read by a session holding `grants`. */ +/** The editor's Incidents tab over `incidents`, read by a session holding `grants`. */ const loaded = ( grants: ReadonlyArray, incidents: ReadonlyArray>, ): Model => { const entered = init( - { _tag: "StatusPage", pageId: Schema.encodeSync(StatusPagePublicId)(statusPage().id), search: {} }, + { + _tag: "StatusPage", + pageId: Schema.encodeSync(StatusPagePublicId)(statusPage().id), + search: { view: "incidents" }, + }, context, ).model return Arr.reduce( @@ -58,22 +64,23 @@ const loaded = ( const DRAFT = incident(1, { published: false }) const MAINTENANCE = incident(2, { kind: "maintenance", title: "Database upgrade" }) +const mounted = Mount.resolve(MountDialog, Dialog.Message.CompletedMountDialog()) + const opened = (grants: ReadonlyArray, row: ReturnType, n: number) => pageUpdate(loaded(grants, [row]), Message.ClickedIncident({ incidentId: incidentId(n) })).model describe("status page editor, analyst", () => { - test("Post incident is offered to a member and not to an analyst", () => { + test("Declare incident is offered to a member and not to an analyst", () => { scene( { update: pageUpdate, view }, given(loaded(ANALYST, [])), - expectView(text("Nothing posted.")).toExist(), - expectView(role("button", { name: "Post incident" })).toBeAbsent(), + expectView(text("No open incidents.")).toExist(), + expectView(role("button", { name: "Declare incident" })).toBeAbsent(), ) scene( { update: pageUpdate, view }, given(loaded(MEMBER, [])), - expectView(text("Nothing posted. Post incident when something breaks.")).toExist(), - expectView(role("button", { name: "Post incident" })).toExist(), + expectView(role("button", { name: "Declare incident" })).toExist(), ) }) @@ -81,6 +88,7 @@ describe("status page editor, analyst", () => { scene( { update: pageUpdate, view }, given(opened(ANALYST, DRAFT, 1)), + mounted, expectView(text("Draft, not public")).toExist(), expectView(role("region", { name: "Updates" })).toExist(), expectView(role("button", { name: "Publish" })).toBeAbsent(), @@ -95,6 +103,7 @@ describe("status page editor, analyst", () => { scene( { update: pageUpdate, view }, given(opened(MEMBER, DRAFT, 1)), + mounted, expectView(role("button", { name: "Publish" })).toExist(), expectView(role("button", { name: "Post update" })).toExist(), expectView(role("button", { name: "Resolve" })).toExist(), @@ -107,12 +116,14 @@ describe("status page editor, analyst", () => { scene( { update: pageUpdate, view }, given(opened(ANALYST, MAINTENANCE, 2)), + mounted, expectView(role("button", { name: "Complete" })).toBeAbsent(), expectView(role("button", { name: "Delete maintenance" })).toBeAbsent(), ) scene( { update: pageUpdate, view }, given(opened(MEMBER, MAINTENANCE, 2)), + mounted, expectView(role("button", { name: "Complete" })).toExist(), expectView(role("button", { name: "Delete maintenance" })).toExist(), ) diff --git a/apps/web/src/page/status-pages/editor/command.ts b/apps/web/src/page/status-pages/editor/command.ts index 69962feda3..df205206fc 100644 --- a/apps/web/src/page/status-pages/editor/command.ts +++ b/apps/web/src/page/status-pages/editor/command.ts @@ -349,6 +349,15 @@ export const FocusEditorElement = Command.define("FocusStatusPageEditorElement", Dom.focus(`#${CSS.escape(id)}`).pipe(Effect.ignore, Effect.as(Message.CompletedFocus())), }) +/** Scrolls an opened component's row into view as it mounts: it may open from the live page. */ +export const RevealOpenComponent = Mount.define("RevealStatusPageComponent", { + messages: [Message.CompletedFocus], + execute: ({ element }) => + Effect.sync(() => element.scrollIntoView({ block: "nearest" })).pipe( + Effect.as(Message.CompletedFocus()), + ), +}) + /** Focuses the element as it mounts, in the same render, so no keystroke lands elsewhere first. */ export const FocusNewRow = Mount.define("FocusStatusPageEditorRow", { messages: [Message.CompletedFocus], diff --git a/apps/web/src/page/status-pages/editor/editor.scene.test.ts b/apps/web/src/page/status-pages/editor/editor.scene.test.ts index efb947dd90..837085bc62 100644 --- a/apps/web/src/page/status-pages/editor/editor.scene.test.ts +++ b/apps/web/src/page/status-pages/editor/editor.scene.test.ts @@ -1,3 +1,4 @@ +import * as Animation from "@foldkit/ui/animation" import * as Policy from "@maple/domain/policy" import { OrgId } from "@maple/domain" import { @@ -30,12 +31,13 @@ import { type, withViewInputs, } from "foldkit/scene" +import { AsyncData } from "foldkit" import { describe, expect, test } from "vitest" import * as Dialog from "@maple/views/ui/dialog" import { MountDialog } from "@maple/views/ui/dialog" import { toLoadFailure } from "@maple/views/data/load-failure" import { PageOutMessage, type PageContext } from "../../contract" -import { statusPagesHref } from "../shared/commands" +import { statusPageHref, statusPagesHref } from "../shared/commands" import { selectionOf } from "../shared/preview" import { ORG } from "../../kit/alert-test-rows" import { downMonitor, httpMonitor } from "../../kit/uptime/test-monitors" @@ -52,15 +54,18 @@ import { CheckCustomDomain, FocusEditorElement, RemoveCustomDomain, + RevealOpenComponent, SaveVisibility, SetCustomDomain, } from "./command" import { Message } from "./message" import type { Model } from "./model" import { init, routeChanged, update } from "./update" -import { moved } from "./update-components" +import { groupedOrder, moved } from "./update-components" import { customDomainOf } from "./update-domain" import { canvasDocument } from "./view-canvas" +import { maintenanceDurationMs } from "./view-incidents" +import { type Focused, popupOwnsEscape } from "./subscription" import { removeComponentCopy, view as pageView } from "./view" const ADMIN = Policy.grantsOf(["org:admin"]) @@ -76,6 +81,7 @@ const PUBLIC_ID = Schema.encodeSync(StatusPagePublicId)(statusPage().id) type Fixture = Readonly<{ tab?: string + section?: string page?: V2StatusPage grants?: ReadonlyArray components?: ReturnType[] @@ -126,7 +132,7 @@ const loaded = (fixture: Fixture = {}): Model => { { _tag: "StatusPage", pageId: PUBLIC_ID, - search: fixture.tab === undefined ? {} : { view: fixture.tab }, + search: { view: fixture.tab, section: fixture.section }, }, context, ).model @@ -158,7 +164,7 @@ const loaded = (fixture: Fixture = {}): Model => { key: entered.customDomain.key ?? "", result: Result.succeed(fixture.customDomain ?? customDomain()), }), - // Only the JSON tab reads the config. + // Only Settings > Advanced reads the config. ...(entered.config.key === null ? [] : [ @@ -266,11 +272,27 @@ describe("read failures", () => { }) }) -describe("the page as the editor", () => { - const selected = (componentNumber: number, fixture: Fixture = {}) => - pageUpdate(loaded(fixture), Message.ClickedComponent({ componentId: componentId(componentNumber) })) - .model +const MONITORS = { tab: "settings", section: "monitors" } as const + +/** The `srcdoc` of the frame titled `title`; "" without one. */ +const srcdocOf = + (title: string) => + (html: Parameters>[0]): string => + Option.getOrElse(Option.flatMap(find(`iframe[title="${title}"]`)(html), attr("srcdoc")), () => "") +const APPEARANCE = { tab: "settings", section: "appearance" } as const +const ACCESS = { tab: "settings", section: "access" } as const +const ADVANCED = { tab: "settings", section: "advanced" } as const + +/** Settings > Monitors with one component open. */ +const selected = (componentNumber: number, fixture: Fixture = {}) => + pageUpdate( + loaded({ ...MONITORS, ...fixture }), + Message.ClickedComponent({ componentId: componentId(componentNumber) }), + ).model + +const revealed = Mount.resolve(RevealOpenComponent, Message.CompletedFocus()) +describe("components under Settings > Monitors", () => { test("moving a component down sends the whole new order once and shows it at once", () => { const moving = pageUpdate( loaded(), @@ -296,48 +318,149 @@ describe("the page as the editor", () => { expect(moved(rows, componentId(2), 1)).toBeNull() scene( { update: pageUpdate, view }, - given(loaded({ components: rows })), + given(loaded({ ...MONITORS, components: rows })), expectView(role("button", { name: "Move Component 1 up" })).toBeDisabled(), expectView(role("button", { name: "Move Component 2 down" })).toBeDisabled(), expectView(role("button", { name: "Move Component 1 down" })).not.toBeDisabled(), ) }) - test("a component picked in the On this page list opens in its place, and Back returns to the list", () => { + test("a component opens in its row with its fields, and a second click closes it", () => { const target = component(2, { name: "API", group: "Core", manual_status: "degraded" }) scene( { update: pageUpdate, view }, - given(loaded({ components: [component(1), target] })), + given(loaded({ ...MONITORS, components: [component(1), target] })), click(role("button", { name: /^API/u })), - Command.resolve(FocusEditorElement, Message.CompletedFocus()), + revealed, + expectView(role("button", { name: /^API/u })).toHaveAttr("aria-expanded", "true"), expectView(role("textbox", { name: "Shown as" })).toHaveValue("API"), expectView(role("textbox", { name: "Group" })).toHaveValue("Core"), - expectView(role("navigation", { name: "On this page" })).not.toExist(), - click(role("button", { name: "On this page" })), + expectView(text("Degraded, set under Override status.")).toExist(), + click(role("button", { name: /^API/u })), Command.resolve(FocusEditorElement, Message.CompletedFocus()), - expectView(role("button", { name: /^API/u })).toHaveAttr("aria-pressed", "false"), + Mount.expectEnded(RevealOpenComponent), + expectView(role("textbox", { name: "Shown as" })).not.toExist(), + expectView(role("button", { name: /^API/u })).toHaveAttr("aria-expanded", "false"), + ) + }) + + test("groups list where their first member is, as on the public page, ungrouped ones too", () => { + // The page opens on an ungrouped component, so "No group" leads. + const rows = [ + component(1), + component(2, { group: "Core" }), + component(3), + component(4, { group: "Core" }), + ] + expect(Arr.map(groupedOrder(rows), (row) => row.id)).toEqual([ + componentId(1), + componentId(3), + componentId(2), + componentId(4), + ]) + scene( + { update: pageUpdate, view }, + given(loaded({ ...MONITORS, components: rows })), + expectAll(all.role("list")).toHaveCount(2), + tap(({ html }) => + expect( + Option.flatMap(find('[aria-label="Components"] ul')(html), attr("aria-label")), + ).toEqual(Option.some("No group")), + ), + expectView(role("button", { name: "Move Component 1 up" })).toBeDisabled(), + expectView(role("button", { name: "Move Component 3 down" })).toBeDisabled(), + expectView(role("button", { name: "Move Component 2 up" })).toBeDisabled(), + expectView(role("button", { name: "Move Component 4 down" })).toBeDisabled(), ) }) - test("a click in the preview selects the component or incident it names; unknown ids do nothing", () => { - const model = loaded({ incidents: [incident(1)] }) + test("a move swaps a component with its neighbour in its group and leaves every other where it was", () => { + const rows = [ + component(1), + component(2, { group: "Core" }), + component(3), + component(4, { group: "Core" }), + ] + expect( + pageUpdate( + loaded({ components: rows }), + Message.ClickedMoveComponent({ componentId: componentId(3), offset: -1 }), + ).commands, + ).toMatchObject([ + { + name: "ReorderStatusPageComponents", + args: { componentIds: [componentId(3), componentId(2), componentId(1), componentId(4)] }, + }, + ]) + expect(moved(rows, componentId(4), 1)).toBeNull() + }) + + test("the open component's row shows how it reads on the page, as typed", () => { + const editing = pageUpdate( + selected(2, { components: [component(1, { group: "Core" }), component(2, { group: "Core" })] }), + Message.ChangedComponentField({ field: "name", value: "Payments" }), + ).model + scene( + { update: pageUpdate, view }, + given(editing), + revealed, + expectView(selector('iframe[title="Component 2 as visitors see it"]')).toHaveAttr("sandbox", ""), + tap(({ html }) => { + const srcdoc = Option.getOrElse( + Option.flatMap( + find('iframe[title="Component 2 as visitors see it"]')(html), + attr("srcdoc"), + ), + () => "", + ) + expect(srcdoc).toContain("Payments") + expect(srcdoc).toContain("Core") + expect(srcdoc).not.toContain("Component 1") + }), + ) + }) + + test("a click in the live page opens the component under Monitors and the incident under its tab", () => { + const model = loaded({ incidents: [incident(1), incident(2, { kind: "maintenance" })] }) const picked = pageUpdate( model, Message.ReceivedPreviewSelection({ kind: "component", id: componentId(3) }), ) expect(picked.model.panel).toEqual({ _tag: "Component", componentId: componentId(3) }) expect(picked.model.componentForm.name).toBe("Component 3") + expect(picked.outMessage).toMatchObject({ + _tag: "RequestedNavigation", + url: statusPageHref(statusPage().id, "settings", "monitors"), + }) + // Landing on Monitors keeps the component open. + const landed = routeChanged( + picked.model, + { _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "settings", section: "monitors" } }, + context, + ) + expect(landed.model.panel).toEqual({ _tag: "Component", componentId: componentId(3) }) const incidentPicked = pageUpdate( model, Message.ReceivedPreviewSelection({ kind: "incident", id: incidentId(1) }), ) expect(incidentPicked.model.panel).toEqual({ _tag: "Incident", incidentId: incidentId(1) }) + expect(incidentPicked.model.panelSheet.isOpen).toBe(true) + expect(incidentPicked.outMessage).toMatchObject({ url: statusPageHref(statusPage().id, "incidents") }) + expect( + pageUpdate(model, Message.ReceivedPreviewSelection({ kind: "incident", id: incidentId(2) })) + .outMessage, + ).toMatchObject({ url: statusPageHref(statusPage().id, "maintenance") }) expect( pageUpdate(model, Message.ReceivedPreviewSelection({ kind: "component", id: "elsewhere" })).model .panel, ).toBeNull() }) + test("switching to a tab that does not show the open component closes it", () => { + const left = routeChanged(selected(1), { _tag: "StatusPage", pageId: PUBLIC_ID, search: {} }, context) + expect(left.model.panel).toBeNull() + }) + test("a preview message that is not exactly a selection is ignored", () => { expect(selectionOf({ type: "select", kind: "component", id: componentId(1) })).toEqual( Option.some({ kind: "component", id: componentId(1) }), @@ -350,17 +473,14 @@ describe("the page as the editor", () => { expect(selectionOf("select")).toEqual(Option.none()) }) - test("the preview outlines the selection and marks components and incidents to click", () => { - const model = selected(2, { incidents: [incident(1)] }) + test("the live page is a sandboxed frame whose components and incidents can be clicked", () => { + const model = loaded({ incidents: [incident(1)] }) scene( { update: pageUpdate, view }, given(model), expectView(selector("iframe")).toHaveAttr("sandbox", "allow-scripts"), ) const document = canvasDocument(model, statusPage()) - const outlined = (id: string) => new RegExp(`\\[data-component-id="${id}"\\][^{]*\\{outline:2px`, "u") - expect(document).toMatch(outlined(componentId(2))) - expect(document).not.toMatch(outlined(componentId(1))) expect(document).toContain(`data-incident-id="${incidentId(1)}"`) expect(document).toContain(`data-component-id="${componentId(1)}"`) }) @@ -402,7 +522,7 @@ describe("the page as the editor", () => { saving.model, Message.CompletedSaveComponent({ result: Result.succeed(component(2, { name: "Payments" })) }), ) - scene({ update: pageUpdate, view }, given(saved.model), expectView(text("Saved")).toExist()) + scene({ update: pageUpdate, view }, given(saved.model), revealed, expectView(text("Saved")).toExist()) }) test("a description typed in the panel saves on blur and shows in the preview as typed", () => { @@ -420,6 +540,7 @@ describe("the page as the editor", () => { scene( { update: pageUpdate, view }, given(editing.model), + revealed, expectView(role("textbox", { name: "Description" })).toHaveValue(" Card payments and payouts "), ) }) @@ -430,6 +551,7 @@ describe("the page as the editor", () => { scene( { update: pageUpdate, view }, given(open), + revealed, expectView(role("button", { name: "Core" })).toExist(), ) const picked = pageUpdate(open, Message.PickedComponentField({ field: "group", value: "Core" })) @@ -439,6 +561,7 @@ describe("the page as the editor", () => { scene( { update: pageUpdate, view }, given(picked.model), + revealed, expectView(role("textbox", { name: "Group" })).toHaveValue("Core"), expectView(role("group", { name: "Groups on this page" })).not.toExist(), ) @@ -460,6 +583,7 @@ describe("the page as the editor", () => { scene( { update: pageUpdate, view }, given(failed), + revealed, expectView(text("Not saved")).toExist(), expectView(text("Couldn't save the component")).toExist(), ) @@ -469,6 +593,7 @@ describe("the page as the editor", () => { scene( { update: pageUpdate, view }, given(selected(1)), + revealed, expectView(role("checkbox", { name: "Show uptime bars" })).toBeChecked(), expectView(role("checkbox", { name: "Show uptime bars" })).toBeDisabled(), expectView(text("Uptime bars need a monitor.")).toExist(), @@ -549,7 +674,10 @@ describe("the page as the editor", () => { }, { name: "TrackStatusPageEditorMonitorCreated", args: { kind: monitor.kind } }, ]) - const closed = pageUpdate(adding, Message.ClickedClosePanel()).model + const closed = pageUpdate( + adding, + Message.GotPanelSheetMessage({ message: Dialog.Message.ClickedClose() }), + ).model expect(names(pageUpdate(closed, created).commands)).not.toContain("AddStatusPageComponents") // Reopened before the first monitor arrived: the new panel's picker stays its own. const reopened = pageUpdate(closed, Message.ClickedAddComponent()).model @@ -569,6 +697,7 @@ describe("the page as the editor", () => { scene( { update: pageUpdate, view }, given({ ...adding, addPicker: { ...adding.addPicker, isCreatingMonitor: true } }), + mounted, expectView(role("button", { name: "Add a component without a monitor" })).toBeDisabled(), expectView(role("button", { name: "Add component" })).toBeDisabled(), ) @@ -597,6 +726,7 @@ describe("the page as the editor", () => { scene( { update: pageUpdate, view }, given(selected(1, { grants: MEMBER })), + revealed, expectView(text("Component 1")).toExist(), expectView(role("button", { name: "Add monitor" })).not.toExist(), expectView(role("button", { name: "Move Component 1 down" })).not.toExist(), @@ -615,8 +745,8 @@ const steps = (model: Model, messages: ReadonlyArray, ctx: PageContext const mounted = Mount.resolve(MountDialog, Dialog.Message.CompletedMountDialog()) -/** The reviewed message as the public page's markup renders it. */ -const updateBodyOf = find('[role="dialog"] [data-slot="update-body"]') +/** The reviewed message as the public page's markup renders it; the incident's sheet is a dialog too. */ +const updateBodyOf = find('[role="dialog"]:not(#status-page-panel-popup) [data-slot="update-body"]') const messageHtml = (html: Parameters[0]): string => Option.getOrElse(Option.flatMap(updateBodyOf(html), attr("innerHTML")), () => "") @@ -961,6 +1091,7 @@ describe("posting an update", () => { scene( { update: pageUpdate, view }, given(model), + mounted, expectView(text("Draft, not public")).toExist(), expectView(role("button", { name: "Publish" })).toExist(), expectView(role("button", { name: "Resolve" })).toExist(), @@ -982,6 +1113,7 @@ describe("posting an update", () => { { update: pageUpdate, view }, given(opened), mounted, + mounted, expectView(role("dialog", { name: "Post update" })).toExist(), // The last update reads as the page renders it. tap(({ html }) => @@ -1006,6 +1138,7 @@ describe("posting an update", () => { { update: pageUpdate, view }, given(model), mounted, + mounted, inside(role("region", { name: "On the page" }), expectView(text("Resolved")).toExist()), tap(({ html }) => expect(messageHtml(html)).toBe("

This incident has been resolved.

")), inside( @@ -1060,6 +1193,7 @@ describe("posting an update", () => { { update: pageUpdate, view }, given(late), mounted, + mounted, expectView(text("It can't end in the future.")).toExist(), expectView(role("button", { name: "Review" })).toBeDisabled(), ) @@ -1085,6 +1219,7 @@ describe("posting an update", () => { { update: pageUpdate, view }, given(early), mounted, + mounted, expectView(text("It can't end before it started.")).toExist(), expectView(role("button", { name: "Review" })).toBeDisabled(), ) @@ -1109,6 +1244,7 @@ describe("posting an update", () => { { update: pageUpdate, view }, given(opened), mounted, + mounted, expectView(role("textbox", { name: "Ended" })).not.toExist(), ) }) @@ -1129,6 +1265,7 @@ describe("posting an update", () => { { update: pageUpdate, view }, given(failed), mounted, + mounted, expectView(text("Couldn't post the update")).toExist(), expectView(role("button", { name: "Publish update" })).toBeEnabled(), ) @@ -1147,6 +1284,7 @@ describe("posting an update", () => { { update: pageUpdate, view }, given(typed), mounted, + mounted, expectView(role("button", { name: "Change title, impact, times or components" })).toHaveHandler( "click", ), @@ -1156,6 +1294,7 @@ describe("posting an update", () => { given(editing), mounted, mounted, + mounted, expectView(role("dialog", { name: "Post update" })).toExist(), expectView(role("dialog", { name: "Edit details" })).toExist(), expectView(role("textbox", { name: "Title" })).toHaveValue("Elevated errors"), @@ -1174,6 +1313,7 @@ describe("editing an incident's details", () => { { update: pageUpdate, view }, given(opened), mounted, + mounted, expectView(role("textbox", { name: "Title" })).toHaveValue("Elevated errors"), expectView(role("checkbox", { name: "Component 1" })).toBeChecked(), expectView(role("checkbox", { name: "Component 2" })).not.toBeChecked(), @@ -1234,6 +1374,7 @@ describe("editing an incident's details", () => { { update: pageUpdate, view }, given(refused), mounted, + mounted, expectView(text("Couldn't save the changes")).toExist(), expectView(role("button", { name: "Save changes" })).toBeEnabled(), ) @@ -1256,6 +1397,7 @@ describe("editing an incident's details", () => { { update: pageUpdate, view }, given(opened), mounted, + mounted, expectView(role("textbox", { name: "Title" })).toExist(), expectView(role("combobox", { name: "Impact" })).not.toExist(), ) @@ -1305,6 +1447,7 @@ describe("editing an incident's details", () => { { update: pageUpdate, view }, given(opened), mounted, + mounted, expectView(role("textbox", { name: "Starts" })).not.toExist(), expectView(role("textbox", { name: "Ends" })).not.toExist(), ) @@ -1323,6 +1466,7 @@ describe("editing an incident's details", () => { { update: pageUpdate, view }, given(lateEnd), mounted, + mounted, expectView(text("It can't end in the future.")).toExist(), expectView(role("button", { name: "Save changes" })).toBeDisabled(), ) @@ -1336,6 +1480,7 @@ describe("editing an incident's details", () => { { update: pageUpdate, view }, given(lateStart), mounted, + mounted, expectView(text("It can't start in the future.")).toExist(), ) }) @@ -1353,6 +1498,7 @@ describe("editing an incident's details", () => { { update: pageUpdate, view }, given(inverted), mounted, + mounted, expectView(text("It can't end before it started.")).toExist(), expectView(role("button", { name: "Save changes" })).toBeDisabled(), ) @@ -1452,18 +1598,93 @@ describe("an update in flight", () => { }) describe("header", () => { - test("Post incident is offered on the Page tab, whose panel shows the posted incident", () => { + test("Incidents leads with Declare incident and Maintenance with Schedule maintenance", () => { + const declaring = pageUpdate( + loaded({ tab: "incidents" }), + Message.ClickedNewIncident({ kind: "incident" }), + ) + expect(declaring.model.incidentForm.kind).toBe("incident") + scene( + { update: pageUpdate, view }, + given(loaded({ tab: "incidents" })), + expectView(role("button", { name: "Declare incident" })).toExist(), + expectView(role("link", { name: "Open page" })).not.toExist(), + ) + scene( + { update: pageUpdate, view }, + given(loaded({ tab: "maintenance" })), + expectView(role("button", { name: "Schedule maintenance" })).toExist(), + expectView(text("No maintenance scheduled.")).toExist(), + ) scene( { update: pageUpdate, view }, given(loaded()), - expectView(role("button", { name: "Post incident" })).toExist(), + expectView(role("button", { name: "Declare incident" })).not.toExist(), + expectView(role("link", { name: "Live page" })).toHaveAttr("aria-current", "page"), ) + }) + + test("the Incidents tab counts open incidents and lists them apart from resolved ones", () => { + const model = loaded({ + tab: "incidents", + incidents: [ + incident(1, { title: "Elevated errors" }), + incident(2, { + title: "Old outage", + status: "resolved", + resolved_at: "2026-09-30T12:00:00.000Z", + }), + incident(3, { kind: "maintenance", title: "Database upgrade" }), + ], + }) + scene( + { update: pageUpdate, view }, + given(model), + expectView(role("link", { name: /^Incidents\s*1$/u })).toHaveAttr("aria-current", "page"), + inside(role("table", { name: "Active" }), expectView(text("Elevated errors")).toExist()), + inside(role("table", { name: "Resolved" }), expectView(text("Old outage")).toExist()), + expectView(text("Database upgrade")).not.toExist(), + click(role("button", { name: "Elevated errors" })), + mounted, + Command.resolve( + Animation.WaitForPaint, + Animation.Message.CompletedWaitForPaint({ generation: 1 }), + ), + Command.resolve( + Animation.WaitForAnimationSettled, + Animation.Message.EndedAnimation({ generation: 1 }), + ), + expectView(role("dialog", { name: "Elevated errors" })).toExist(), + expectView(role("button", { name: "Post update" })).toExist(), + ) + }) + + test("closing the incident's sheet closes the incident", () => { + const open = pageUpdate( + loaded({ tab: "incidents", incidents: [incident(1)] }), + Message.ClickedIncident({ incidentId: incidentId(1) }), + ).model + expect(open.panelSheet.isOpen).toBe(true) + const closed = pageUpdate( + open, + Message.GotPanelSheetMessage({ message: Dialog.Message.ClickedClose() }), + ).model + expect(closed.panel).toBeNull() + expect(closed.panelSheet.isOpen).toBe(false) + }) + + test("old Appearance and JSON links open those Settings sections", () => { scene( { update: pageUpdate, view }, given(loaded({ tab: "appearance" })), - expectView(role("button", { name: "Post incident" })).not.toExist(), + expectView(role("link", { name: "Settings" })).toHaveAttr("aria-current", "page"), expectView(role("link", { name: "Appearance" })).toHaveAttr("aria-current", "page"), ) + expect( + names( + init({ _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "json" } }, context).commands, + ), + ).toContain("FetchStatusPageConfig") }) test("Open page opens the published page in a new tab", () => { @@ -1565,7 +1786,7 @@ describe("live screen", () => { expectView(role("button", { name: "Get break-glass token" })).toExist(), expectView(role("link", { name: "Page JSON" })).toHaveAttr( "href", - `/status-pages/${PUBLIC_ID}?view=json`, + `/status-pages/${PUBLIC_ID}?view=settings§ion=advanced`, ), ) }) @@ -1644,11 +1865,11 @@ describe("live screen", () => { }) }) -describe("settings and appearance views", () => { +describe("settings", () => { test("an edit raises the save bar, and a bad color blocks the save", () => { scene( { update: pageUpdate, view }, - given(loaded({ tab: "appearance" })), + given(loaded(APPEARANCE)), expectView(text("Unsaved changes")).not.toExist(), type(role("textbox", { name: "Accent" }), "teal"), expectView(text("Unsaved changes")).toExist(), @@ -1657,15 +1878,15 @@ describe("settings and appearance views", () => { ) }) - test("a bad field on Settings blocks the save on Appearance too, and the bar names its tab", () => { + test("a bad field in Basic settings blocks the save on Appearance too, and the bar names its section", () => { const edited = pageUpdate( loaded({ tab: "settings" }), Message.ChangedSetting({ field: "termsUrl", value: "http://acme.example/terms" }), ).model scene( { update: pageUpdate, view }, - given({ ...edited, search: { view: "appearance" } }), - expectView(text("Fix the fields marked on the Settings tab.")).toExist(), + given({ ...edited, search: { view: "settings", section: "appearance" } }), + expectView(text("Fix the fields marked in Basic settings.")).toExist(), expectView(role("button", { name: "Save" })).toBeDisabled(), ) }) @@ -1738,7 +1959,7 @@ describe("settings and appearance views", () => { test("Auto disables the colour overrides but not the accent", () => { scene( { update: pageUpdate, view }, - given(loaded({ tab: "appearance" })), + given(loaded(APPEARANCE)), expectView(role("textbox", { name: "Background" })).toBeDisabled(), expectView(role("textbox", { name: "Text" })).toBeDisabled(), expectView(role("textbox", { name: "Accent" })).toBeEnabled(), @@ -1750,7 +1971,7 @@ describe("settings and appearance views", () => { test("an unreadable text colour shows its contrast and blocks the save", () => { scene( { update: pageUpdate, view }, - given(loaded({ tab: "appearance" })), + given(loaded(APPEARANCE)), inside(role("group", { name: "Mode" }), click(role("button", { name: "Light" }))), type(role("textbox", { name: "Text" }), "#757575"), expectView( @@ -1760,64 +1981,107 @@ describe("settings and appearance views", () => { ) }) - test("the preview is a sandboxed page that follows the draft accent and preview mode", () => { - const iframeOf = find("iframe") - const srcdoc = (html: Parameters[0]): string => - Option.getOrElse(Option.flatMap(iframeOf(html), attr("srcdoc")), () => "") + test("the theme preview is the page's own renderer, sandboxed, following the unsaved theme", () => { + const theme = srcdocOf("The theme as visitors see it") scene( { update: pageUpdate, view }, - given(loaded({ tab: "appearance" })), - // Scripts page the bars; without `allow-same-origin` the page still reaches nothing of ours. - expectView(selector("iframe")).toHaveAttr("sandbox", "allow-scripts"), + given(loaded(APPEARANCE)), + expectView(selector('iframe[title="The theme as visitors see it"]')).toHaveAttr("sandbox", ""), tap(({ html }) => { - expect(srcdoc(html)).toContain("Acme Status") - expect(srcdoc(html)).toContain("color-scheme:light;") + expect(theme(html)).toContain("Acme Status") + expect(theme(html)).toContain("Component 1") + expect(theme(html)).not.toContain("Component 2") + expect(theme(html)).toContain("color-scheme:light;") }), - // The preview mode is for looking only: it is not a page edit. - inside(role("group", { name: "Preview mode" }), click(role("button", { name: "Dark" }))), - tap(({ html }) => expect(srcdoc(html)).toContain("color-scheme:dark;")), - expectView(text("Unsaved changes")).not.toExist(), + inside(role("group", { name: "Mode" }), click(role("button", { name: "Dark" }))), + tap(({ html }) => expect(theme(html)).toContain("color-scheme:dark;")), type(role("textbox", { name: "Accent" }), "#ff0066"), - tap(({ html }) => expect(srcdoc(html)).toContain("--link:#ff0066")), + tap(({ html }) => expect(theme(html)).toContain("--link:#ff0066")), ) }) - test("the branding links preview at once: the dark logo in dark mode and the favicon", () => { - const iframeOf = find("iframe") - const srcdoc = (html: Parameters[0]): string => - Option.getOrElse(Option.flatMap(iframeOf(html), attr("srcdoc")), () => "") + test("the branding links preview at once: the logo in the header, the favicon in the tab", () => { + const header = srcdocOf("The page header as visitors see it") scene( { update: pageUpdate, view }, - given(loaded({ tab: "appearance" })), + given(loaded(APPEARANCE)), type(role("textbox", { name: "Logo URL" }), "https://acme.example/logo.svg"), type(role("textbox", { name: "Dark mode logo URL" }), "https://acme.example/logo-dark.svg"), type(role("textbox", { name: "Favicon URL" }), "https://acme.example/favicon.png"), tap(({ html }) => { - expect(srcdoc(html)).toContain(``) + expect(header(html)).toContain(``) }), - inside(role("group", { name: "Preview mode" }), click(role("button", { name: "Dark" }))), + expectView(selector('img[src="https://acme.example/favicon.png"]')).toExist(), + inside(role("group", { name: "Mode" }), click(role("button", { name: "Dark" }))), tap(({ html }) => - expect(srcdoc(html)).toContain(` { + const footer = srcdocOf("The page footer as visitors see it") + scene( + { update: pageUpdate, view }, + given(loaded({ tab: "settings" })), + type(role("textbox", { name: "Name" }), "Globex"), + type(role("textbox", { name: "Description" }), "Live status of Globex"), + expectAll(all.text("Globex status")).toHaveCount(2), + expectView(text("Live status of Globex")).toExist(), + tap(({ html }) => expect(footer(html)).toContain("Powered by")), + click(role("switch", { name: "Show powered by Maple" })), + tap(({ html }) => expect(footer(html)).not.toContain("Powered by")), + ) + }) + + test("a password-protected page previews the password form visitors meet", () => { + const gate = srcdocOf("The password form visitors see first") + scene( + { update: pageUpdate, view }, + given(loaded({ ...ACCESS, page: statusPage({ visibility: "password", has_password: true }) })), + tap(({ html }) => { + expect(gate(html)).toContain("This status page is password-protected") + expect(gate(html)).toContain("Acme Status") + }), + ) + scene( + { update: pageUpdate, view }, + given(loaded(ACCESS)), + expectView(selector('iframe[title="The password form visitors see first"]')).not.toExist(), + ) + }) + + test("the settings menu links each section and marks the open one", () => { + scene( + { update: pageUpdate, view }, + given(loaded(MONITORS)), + inside( + role("navigation", { name: "Settings sections" }), + expectView(role("link", { name: "Monitors" })).toHaveAttr("aria-current", "page"), + expectView(role("link", { name: "Advanced" })).toHaveAttr( + "href", + `/status-pages/${PUBLIC_ID}?view=settings§ion=advanced`, + ), ), ) }) test("a bad branding link is marked on Appearance, and the Settings save bar points there", () => { const edited = pageUpdate( - loaded({ tab: "appearance" }), + loaded(APPEARANCE), Message.ChangedSetting({ field: "faviconUrl", value: "http://acme.example/favicon.png" }), ).model scene({ update: pageUpdate, view }, given(edited), expectView(text("Use an https URL.")).toExist()) scene( { update: pageUpdate, view }, given({ ...edited, search: { view: "settings" } }), - expectView(text("Fix the fields marked on the Appearance tab.")).toExist(), + expectView(text("Fix the fields marked in Appearance.")).toExist(), expectView(role("button", { name: "Save" })).toBeDisabled(), ) }) - test("the preview can show a state the page is not in, and says it is an example", () => { + test("the live page can show a state the page is not in, and says it is an example", () => { const iframeOf = find("iframe") const srcdoc = (html: Parameters[0]): string => Option.getOrElse(Option.flatMap(iframeOf(html), attr("srcdoc")), () => "") @@ -1826,7 +2090,7 @@ describe("settings and appearance views", () => { inside(role("group", { name: "Preview state" }), click(role("button", { name }))) scene( { update: pageUpdate, view }, - given(loaded({ tab: "appearance" })), + given(loaded()), expectView(note).not.toExist(), tap(({ html }) => expect(srcdoc(html)).not.toContain("Example incident")), pick("Outage"), @@ -1852,7 +2116,7 @@ describe("settings and appearance views", () => { inside(role("group", { name: "Preview width" }), click(role("button", { name }))) scene( { update: pageUpdate, view }, - given(loaded({ tab: "appearance" })), + given(loaded()), expectView(selector("iframe")).toHaveAttr("data-width", "desktop"), pick("Mobile"), expectView(selector("iframe")).toHaveAttr("data-width", "mobile"), @@ -1866,7 +2130,7 @@ describe("settings and appearance views", () => { const accent = selector('[aria-label="Accent color"]') scene( { update: pageUpdate, view }, - given(loaded({ tab: "appearance" })), + given(loaded(APPEARANCE)), // Empty field: the preset's own colour, the one the placeholder names. expectView(accent).toHaveValue("#000000"), type(role("textbox", { name: "Accent" }), "#FF0066"), @@ -1880,7 +2144,7 @@ describe("settings and appearance views", () => { }) test("the first break-glass token is issued at once and shown once", () => { - const issuing = pageUpdate(loaded({ tab: "settings" }), Message.ClickedRotateToken()) + const issuing = pageUpdate(loaded(ADVANCED), Message.ClickedRotateToken()) expect(names(issuing.commands)).toEqual(["RotateStatusPageBreakGlassToken"]) const issued = pageUpdate( issuing.model, @@ -1909,7 +2173,7 @@ describe("settings and appearance views", () => { test("a password is set before the page can be password-protected, and never rides a command's args", () => { scene( { update: pageUpdate, view }, - given(loaded({ tab: "settings" })), + given(loaded(ACCESS)), expectView(role("radio", { name: "Password-protected" })).toBeDisabled(), expectView(text("Set a password below first.")).toExist(), click(role("button", { name: "Set password" })), @@ -1918,7 +2182,7 @@ describe("settings and appearance views", () => { expectView(role("button", { name: "Save password" })).toBeDisabled(), ) const typed = pageUpdate( - pageUpdate(loaded({ tab: "settings" }), Message.ClickedChangePassword()).model, + pageUpdate(loaded(ACCESS), Message.ClickedChangePassword()).model, Message.ChangedPassword({ value: "correct horse battery" }), ).model const saving = pageUpdate(typed, Message.SubmittedPassword()) @@ -1953,11 +2217,11 @@ describe("settings and appearance views", () => { test("a page with a custom domain cannot go internal, and only admins change who can view", () => { scene( { update: pageUpdate, view }, - given(loaded({ tab: "settings", customDomain: pendingDomain })), + given(loaded({ ...ACCESS, customDomain: pendingDomain })), expectView(role("radio", { name: "Internal" })).toBeDisabled(), expectView(text("Remove the custom domain first.")).toExist(), ) - const engineer = loaded({ tab: "settings", grants: Policy.grantsOf(["org:engineer"]) }) + const engineer = loaded({ ...ACCESS, grants: Policy.grantsOf(["org:engineer"]) }) scene( { update: pageUpdate, view }, given(engineer), @@ -1970,7 +2234,7 @@ describe("settings and appearance views", () => { }) test("replacing or revoking an issued token asks first", () => { - const model = loaded({ tab: "settings", page: statusPage({ break_glass_token_suffix: "ABC123" }) }) + const model = loaded({ ...ADVANCED, page: statusPage({ break_glass_token_suffix: "ABC123" }) }) const replacing = pageUpdate(model, Message.ClickedRotateToken()) expect(names(replacing.commands)).not.toContain("RotateStatusPageBreakGlassToken") expect(replacing.model.breakGlassDialog.isOpen).toBe(true) @@ -2154,7 +2418,7 @@ describe("custom domain", () => { }) }) -describe("json view", () => { +describe("the JSON editor under Advanced", () => { const publicComponentId = (n: number) => Schema.encodeSync(StatusPageComponentPublicId)(componentId(n)) /** The document the tab shows, as the user would edit it. */ const documentOf = (components: ReadonlyArray) => ({ @@ -2165,16 +2429,16 @@ describe("json view", () => { const editing = (draft: string, fixture: Fixture = {}) => Arr.reduce( [Message.ClickedEditJson(), Message.ChangedJson({ value: draft })], - loaded({ tab: "json", ...fixture }), + loaded({ ...ADVANCED, ...fixture }), (model, message) => pageUpdate(model, message).model, ) test("shows the page as its config document, with public ids", () => { scene( { update: pageUpdate, view }, - given(loaded({ tab: "json" })), - expectView(role("link", { name: "Page" })).toHaveAttr("href", `/status-pages/${PUBLIC_ID}`), - expectView(role("link", { name: "JSON" })).toHaveAttr("aria-current", "page"), + given(loaded(ADVANCED)), + expectView(role("link", { name: "Live page" })).toHaveAttr("href", `/status-pages/${PUBLIC_ID}`), + expectView(role("link", { name: "Advanced" })).toHaveAttr("aria-current", "page"), expectView(selector("pre")).toContainText('"slug": "acme-status"'), expectView(selector("pre")).toContainText(`"id": "${publicComponentId(2)}"`), expectView(selector("pre")).toContainText('"auto_incidents": "draft"'), @@ -2186,19 +2450,19 @@ describe("json view", () => { test("members read the document but cannot edit it", () => { scene( { update: pageUpdate, view }, - given(loaded({ tab: "json", grants: MEMBER })), + given(loaded({ ...ADVANCED, grants: MEMBER })), expectView(selector("pre")).toContainText('"name": "Acme Status"'), expectView(role("button", { name: "Edit JSON" })).not.toExist(), expectView(role("textbox", { name: "Config JSON" })).not.toExist(), ) - const tried = pageUpdate(loaded({ tab: "json", grants: MEMBER }), Message.ClickedEditJson()) + const tried = pageUpdate(loaded({ ...ADVANCED, grants: MEMBER }), Message.ClickedEditJson()) expect(tried.model.jsonEdit).toBeNull() }) test("Edit fills the editor with the current document, and Reset brings it back", () => { scene( { update: pageUpdate, view }, - given(loaded({ tab: "json" })), + given(loaded(ADVANCED)), click(role("button", { name: "Edit JSON" })), expectView(role("textbox", { name: "Config JSON" })).toExist(), expectView(text("No changes yet")).toExist(), @@ -2323,11 +2587,14 @@ describe("json view", () => { }) test("the document comes from the config read, so components past the list's first page stay", () => { - const entered = init({ _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "json" } }, context) + const entered = init( + { _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "settings", section: "advanced" } }, + context, + ) expect(names(entered.commands)).toContain("FetchStatusPageConfig") const listed = [component(1), component(2)] const config = statusPageConfig(statusPage(), [...listed, component(3), component(4)]) - const model = loaded({ tab: "json", components: listed, config }) + const model = loaded({ ...ADVANCED, components: listed, config }) scene( { update: pageUpdate, view }, given(model), @@ -2352,7 +2619,7 @@ describe("json view", () => { test("the tab shows the config read's loading and failure states", () => { const entered = init( - { _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "json" } }, + { _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "settings", section: "advanced" } }, context, ).model const pageIn = pageUpdate( @@ -2365,7 +2632,7 @@ describe("json view", () => { expectView(selector("pre")).not.toExist(), expectView(role("button", { name: "Edit JSON" })).not.toExist(), ) - const failed = loaded({ tab: "json", configFail: true }) + const failed = loaded({ ...ADVANCED, configFail: true }) scene( { update: pageUpdate, view }, given(failed), @@ -2374,15 +2641,15 @@ describe("json view", () => { expect(names(pageUpdate(failed, Message.ClickedRetry()).commands)).toContain("FetchStatusPageConfig") }) - test("opening the tab re-reads the config, since other tabs write the page too", () => { + test("opening Advanced re-reads the config, since other sections write the page too", () => { const onSettings = loaded({ tab: "settings" }) expect(onSettings.config.key).toBeNull() const opened = routeChanged( onSettings, - { _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "json" } }, + { _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "settings", section: "advanced" } }, context, ) - expect(names(opened.commands)).toEqual(["FetchStatusPageConfig"]) + expect(names(opened.commands)).toContain("FetchStatusPageConfig") }) test("Apply sends the version the document was read with", () => { @@ -2662,3 +2929,270 @@ describe("json view", () => { ) }) }) + +describe("the sheet, the previews and the reads they wait on", () => { + test("a closing sheet keeps showing its incident until it has animated out", () => { + const open = pageUpdate( + loaded({ tab: "incidents", incidents: [incident(1, { title: "Elevated errors" })] }), + Message.ClickedIncident({ incidentId: incidentId(1) }), + ).model + const closing = pageUpdate( + open, + Message.GotPanelSheetMessage({ message: Dialog.Message.ClickedClose() }), + ).model + expect(closing.panel).toBeNull() + expect(closing.sheetPanel).toEqual({ _tag: "Incident", incidentId: incidentId(1) }) + }) + + test("a created incident shows in its sheet at once, before the re-read lands", () => { + const created = pageUpdate( + pageUpdate(loaded({ tab: "incidents" }), Message.ClickedNewIncident({ kind: "incident" })).model, + Message.CompletedCreateIncident({ + result: Result.succeed(incident(2, { title: "Slow checkout" })), + }), + ).model + scene( + { update: pageUpdate, view }, + given(created), + mounted, + mounted, + expectView(role("dialog", { name: "Slow checkout" })).toExist(), + ) + }) + + test("an incident missing from a failed read says so in its sheet, with a retry", () => { + const open = pageUpdate( + loaded({ tab: "incidents", incidents: [incident(1)] }), + Message.ClickedIncident({ incidentId: incidentId(1) }), + ).model + const failed = { + ...open, + incidents: { + ...open.incidents, + data: AsyncData.Failure({ error: toLoadFailure(new Error("down")) }), + }, + } + scene( + { update: pageUpdate, view }, + given(failed), + mounted, + expectView(text("Couldn't load the incident")).toExist(), + ) + const reading = { ...open, incidents: { ...open.incidents, data: AsyncData.Loading() } } + scene( + { update: pageUpdate, view }, + given(reading), + mounted, + expectView(text("Couldn't load the incident")).not.toExist(), + inside( + role("dialog", { name: "Incident" }), + expectView(selector('[aria-busy="true"]')).toExist(), + ), + ) + }) + + test("the theme preview waits for the statuses' reads, and says so when they fail", () => { + const entered = init( + { _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "settings", section: "appearance" } }, + context, + ).model + const withPage = pageUpdate( + entered, + Message.CompletedFetchPage({ key: entered.page.key ?? "", result: Result.succeed(statusPage()) }), + ).model + scene( + { update: pageUpdate, view }, + given(withPage), + expectView(selector('iframe[title="The theme as visitors see it"]')).not.toExist(), + expectView(selector('iframe[title="The page header as visitors see it"]')).toExist(), + ) + scene( + { update: pageUpdate, view }, + given(loaded({ ...APPEARANCE, monitorsFail: true })), + expectView(selector('iframe[title="The theme as visitors see it"]')).not.toExist(), + expectView(text("No preview: the page's components didn't load.")).toExist(), + ) + }) + + test("opening another component saves the typed edit first and keeps a save in flight", () => { + const typed = pageUpdate( + selected(1), + Message.ChangedComponentField({ field: "name", value: "Payments" }), + ).model + const switched = pageUpdate(typed, Message.ClickedComponent({ componentId: componentId(2) })) + expect(switched.commands).toMatchObject([ + { + name: "SaveStatusPageComponent", + args: { componentId: componentId(1), payload: { name: "Payments" } }, + }, + ]) + expect(switched.model.componentSave).toEqual({ _tag: "Saving", componentId: componentId(1) }) + expect(switched.model.componentForm.name).toBe("Component 2") + }) + + /** Component 1's name blurred (its save in flight), then its description typed. */ + const savingThenTyped = () => + steps(selected(1), [ + Message.ChangedComponentField({ field: "name", value: "Payments" }), + Message.CommittedComponent(), + Message.ChangedComponentField({ field: "description", value: "Card payments" }), + ]) + + test("an edit typed while a save is in flight is queued when another component opens, and sent once the save lands", () => { + const switched = pageUpdate( + savingThenTyped(), + Message.ClickedComponent({ componentId: componentId(2) }), + ) + expect(names(switched.commands)).not.toContain("SaveStatusPageComponent") + const landed = pageUpdate( + switched.model, + Message.CompletedSaveComponent({ result: Result.succeed(component(1, { name: "Payments" })) }), + ) + expect(landed.commands).toContainEqual( + expect.objectContaining({ + name: "SaveStatusPageComponent", + args: expect.objectContaining({ + componentId: componentId(1), + payload: expect.objectContaining({ name: "Payments", description: "Card payments" }), + }), + }), + ) + expect(landed.model.queuedComponentForms).toEqual([]) + }) + + test("Escape queues an edit typed while a save is in flight, too", () => { + const escaped = pageUpdate(savingThenTyped(), Message.PressedEscape()).model + expect(Arr.map(escaped.queuedComponentForms, (form) => form.description)).toEqual(["Card payments"]) + }) + + test("a refused save stays on its own component and its queued edit is never sent behind its back", () => { + const switched = pageUpdate( + savingThenTyped(), + Message.ClickedComponent({ componentId: componentId(2) }), + ).model + const refused = pageUpdate( + switched, + Message.CompletedSaveComponent({ result: Result.fail(toLoadFailure(new Error("refused"))) }), + ) + expect(names(refused.commands)).not.toContain("SaveStatusPageComponent") + expect(refused.model.queuedComponentForms).toEqual([]) + expect(refused.model.componentSave).toMatchObject({ _tag: "Failed", componentId: componentId(1) }) + scene( + { update: pageUpdate, view }, + given(refused.model), + revealed, + expectView(text("Couldn't save the component")).not.toExist(), + ) + // Closing the other component or opening a third sends nothing of the abandoned form. + expect(names(pageUpdate(refused.model, Message.PressedEscape()).commands)).not.toContain( + "SaveStatusPageComponent", + ) + const third = pageUpdate(refused.model, Message.ClickedComponent({ componentId: componentId(3) })) + expect(names(third.commands)).not.toContain("SaveStatusPageComponent") + scene( + { update: pageUpdate, view }, + given(pageUpdate(refused.model, Message.ClickedComponent({ componentId: componentId(1) })).model), + revealed, + expectView(text("Couldn't save the component")).toExist(), + ) + }) + + test("opening a component after a JSON apply renamed an untouched one sends no stale PATCH", () => { + const opened = selected(1, { components: [component(1, { name: "API" }), component(2)] }) + const advanced = routeChanged( + opened, + { _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "settings", section: "advanced" } }, + context, + ).model + // The apply's re-read lands the rename made in the JSON. + const renamed = pageUpdate( + advanced, + Message.CompletedFetchComponents({ + key: advanced.components.key ?? "", + result: Result.succeed([component(1, { name: "Payments" }), component(2)]), + }), + ).model + const back = routeChanged( + renamed, + { _tag: "StatusPage", pageId: PUBLIC_ID, search: { view: "settings", section: "monitors" } }, + context, + ).model + expect( + names(pageUpdate(back, Message.ClickedComponent({ componentId: componentId(2) })).commands), + ).not.toContain("SaveStatusPageComponent") + }) + + test("Escape closes an expanded component row, but an open popup trigger or list keeps it", () => { + const focused = (attributes: Readonly>, inList = false): Focused => ({ + getAttribute: (name) => attributes[name] ?? null, + isInside: () => inList, + }) + expect(popupOwnsEscape(focused({ "aria-expanded": "true" }))).toBe(false) + expect(popupOwnsEscape(focused({ "aria-expanded": "true", "aria-haspopup": "listbox" }))).toBe(true) + expect(popupOwnsEscape(focused({ "aria-expanded": "false", "aria-haspopup": "menu" }))).toBe(false) + expect(popupOwnsEscape(focused({}, true))).toBe(true) + }) + + test("a deleted incident's closing sheet keeps showing it after the re-read drops it", () => { + const deleting = steps( + pageUpdate( + loaded({ tab: "incidents", incidents: [incident(1)] }), + Message.ClickedIncident({ incidentId: incidentId(1) }), + ).model, + [ + Message.ClickedDeleteIncident({ incidentId: incidentId(1) }), + Message.ClickedConfirmDeleteIncident(), + ], + ) + const deleted = pageUpdate( + deleting, + Message.CompletedDeleteIncident({ result: Result.succeed(undefined) }), + ).model + const reread = pageUpdate( + deleted, + Message.CompletedFetchIncidents({ key: deleted.incidents.key ?? "", result: Result.succeed([]) }), + ).model + expect(reread.panel).toBeNull() + expect(reread.sheetIncident?.id).toBe(incidentId(1)) + }) + + test("completed maintenance lasts from its first In progress update to completion, else its window", () => { + const done = incident(1, { + kind: "maintenance", + status: "completed", + scheduled_start: "2026-10-01T02:00:00.000Z", + scheduled_end: "2026-10-01T03:00:00.000Z", + started_at: "2026-10-01T02:00:00.000Z", + resolved_at: "2026-10-01T02:24:00.000Z", + updates: Arr.map(incident(1).updates, (update) => ({ + ...update, + status: "in_progress" as const, + created_at: "2026-10-01T02:05:00.000Z", + })), + }) + expect(maintenanceDurationMs(done)).toBe(19 * 60_000) + expect(maintenanceDurationMs({ ...done, updates: [] })).toBe(60 * 60_000) + }) + + test("a failed custom domain read can be retried, and Access does not offer Internal until it is known", () => { + const failed = { + ...loaded({ tab: "settings" }), + customDomain: { + key: "custom-domain", + data: AsyncData.Failure({ error: toLoadFailure(new Error("unreachable")) }), + }, + } + scene( + { update: pageUpdate, view }, + given(failed), + expectView(text("Couldn't load the custom domain")).toExist(), + expectView(role("button", { name: "Try again" })).toExist(), + ) + scene( + { update: pageUpdate, view }, + given({ ...failed, search: { view: "settings", section: "access" } }), + expectView(role("radio", { name: "Internal" })).toBeDisabled(), + expectView(text("Couldn't check for a custom domain. Try again under Basic settings.")).toExist(), + ) + }) +}) diff --git a/apps/web/src/page/status-pages/editor/index.ts b/apps/web/src/page/status-pages/editor/index.ts index 9cc92a3510..82405315d2 100644 --- a/apps/web/src/page/status-pages/editor/index.ts +++ b/apps/web/src/page/status-pages/editor/index.ts @@ -5,7 +5,7 @@ import { subscriptions } from "./subscription" import { init, routeChanged, update } from "./update" import { breadcrumbsOf, view } from "./view" -/** `/status-pages/$pageId`: one instance per page; Settings, JSON and the live screen are search. */ +/** `/status-pages/$pageId`: one instance per page; its tabs and settings sections are search. */ export const page = definePage( "StatusPage", { Model, Message }, diff --git a/apps/web/src/page/status-pages/editor/message.ts b/apps/web/src/page/status-pages/editor/message.ts index f8127576e5..f9cecdbc00 100644 --- a/apps/web/src/page/status-pages/editor/message.ts +++ b/apps/web/src/page/status-pages/editor/message.ts @@ -65,7 +65,7 @@ export const Message = defineMessageUnion({ ReceivedPreviewSelection: { kind: PreviewSelection.fields.kind, id: Schema.String }, ClickedComponent: { componentId: StatusPageComponentId }, ClickedIncident: { incidentId: StatusPageIncidentId }, - ClickedClosePanel: {}, + GotPanelSheetMessage: { message: Dialog.Message }, PressedEscape: {}, // Components ChangedComponentField: { field: ComponentTextField, value: Schema.String }, @@ -155,6 +155,7 @@ export const Message = defineMessageUnion({ CompletedAccessChange: { action: AccessAction, result: LoadOutcome(V2StatusPage) }, // Custom domain CompletedFetchCustomDomain: { key: Schema.String, result: LoadOutcome(V2StatusPageCustomDomain) }, + ClickedRetryCustomDomain: {}, ChangedCustomDomain: { value: Schema.String }, SubmittedCustomDomain: {}, CompletedSetCustomDomain: { result: LoadOutcome(V2StatusPageCustomDomain) }, diff --git a/apps/web/src/page/status-pages/editor/model.ts b/apps/web/src/page/status-pages/editor/model.ts index 7afe503652..90f7d0af43 100644 --- a/apps/web/src/page/status-pages/editor/model.ts +++ b/apps/web/src/page/status-pages/editor/model.ts @@ -19,8 +19,8 @@ import { ComponentForm, IncidentEditForm, IncidentForm, SettingsForm, UpdateForm import { Picker } from "../shared/picker" import { PreviewHistory, PreviewScheme, PreviewState, PreviewWidth } from "../shared/preview" -// `/status-pages/$pageId`: the page itself is the editor. A component or incident picked in the -// preview or the list opens in the side panel; Settings and JSON are views of their own. +// `/status-pages/$pageId`: the live page, its incidents, its maintenance and its settings. A +// component opens in place under Settings > Monitors; an incident, or Add monitors, in a side sheet. /** Where the Post incident dialog is: writing it, or reviewing what publishing it changes. */ export const ComposeStep = Schema.Literals(["write", "review"]) @@ -59,7 +59,7 @@ export type AccessAction = typeof AccessAction.Type /** A freshly issued break-glass token: shown once, never read back. */ export const RevealedToken = Schema.Struct({ token: Schema.String, suffix: Schema.String }) -/** What the side panel shows: one component or incident, or Add component. */ +/** What is open: one component (in its Monitors row), or an incident or Add monitors (in the sheet). */ export const Panel = Schema.Union([ Schema.TaggedStruct("Component", { componentId: StatusPageComponentId }), Schema.TaggedStruct("Incident", { incidentId: StatusPageIncidentId }), @@ -68,9 +68,16 @@ export const Panel = Schema.Union([ ]) export type Panel = typeof Panel.Type -/** The component panel's autosave: each commit is a PATCH, its outcome shown next to the title. */ -export const SaveState = Schema.Literals(["idle", "saving", "saved", "failed"]) -export type SaveState = typeof SaveState.Type +/** + * The last component save, for the component it belongs to: in flight, landed, or refused with why. + * Its row shows it; another component's row shows nothing of it. + */ +export const ComponentSave = Schema.Union([ + Schema.TaggedStruct("Saving", { componentId: StatusPageComponentId }), + Schema.TaggedStruct("Saved", { componentId: StatusPageComponentId }), + Schema.TaggedStruct("Failed", { componentId: StatusPageComponentId, failure: LoadFailure }), +]) +export type ComponentSave = typeof ComponentSave.Type export const Model = Schema.Struct({ search: StatusPageSearch, @@ -88,6 +95,12 @@ export const Model = Schema.Struct({ isSessionLoaded: Schema.Boolean, pageMenu: Menu.Model, panel: Schema.NullOr(Panel), + /** The side sheet an incident or Add monitors opens in; open while `panel` is one of those. */ + panelSheet: Dialog.Model, + /** What the sheet shows: the last incident or Add `panel` held, kept while the sheet closes. */ + sheetPanel: Schema.NullOr(Panel), + /** The incident the sheet last showed, so a closing sheet keeps it after a delete. */ + sheetIncident: Schema.NullOr(V2StatusPageIncident), // Preview previewScheme: PreviewScheme, /** Looking only, like the scheme: neither is saved with the page. */ @@ -99,8 +112,9 @@ export const Model = Schema.Struct({ // Components /** The selected component as its inputs hold it; each commit saves what differs. */ componentForm: ComponentForm, - componentSave: SaveState, - componentFailure: Schema.NullOr(LoadFailure), + componentSave: Schema.NullOr(ComponentSave), + /** Forms committed while a save was in flight, one per component, sent in turn as saves land. */ + queuedComponentForms: Schema.Array(ComponentForm), confirmDeleteComponentId: Schema.NullOr(StatusPageComponentId), deleteComponentDialog: Dialog.Model, isDeletingComponent: Schema.Boolean, diff --git a/apps/web/src/page/status-pages/editor/reads.ts b/apps/web/src/page/status-pages/editor/reads.ts index 0e03e4218d..40b28a81ce 100644 --- a/apps/web/src/page/status-pages/editor/reads.ts +++ b/apps/web/src/page/status-pages/editor/reads.ts @@ -117,6 +117,12 @@ export const statusReadsReady = (model: Model): boolean => AsyncData.hasData(model.monitors.data) && AsyncData.hasData(model.incidents.data) +/** A statuses' read failed: a component's status cannot be told. */ +export const statusReadsFailed = (model: Model): boolean => + AsyncData.hasError(model.components.data) || + AsyncData.hasError(model.monitors.data) || + AsyncData.hasError(model.incidents.data) + export const toast = (type: "success" | "error", title: string, description = ""): PageOutMessage => PageOutMessage.RequestedToast({ type, title, description }) diff --git a/apps/web/src/page/status-pages/editor/subscription.ts b/apps/web/src/page/status-pages/editor/subscription.ts index 703a9099c2..ce1d4888e2 100644 --- a/apps/web/src/page/status-pages/editor/subscription.ts +++ b/apps/web/src/page/status-pages/editor/subscription.ts @@ -7,21 +7,35 @@ import { Message } from "./message" import type { Model } from "./model" import { resolveView } from "./update" -// Escape closes the side panel, from its inputs too; an open dialog, menu or listbox keeps its own -// Escape. A click in the preview frame selects what it landed on. +// Escape closes the open component, from its inputs too; an open dialog (the sheet included), menu +// or listbox keeps its own Escape. A click in the live page's frame opens what it landed on. -/** An open popup owns Escape: a dialog, or a dropdown whose trigger or list has focus. */ -const isPopupOpen = (target: EventTarget | null): boolean => - isDialogOpen() || - (target instanceof Element && - (target.getAttribute("aria-expanded") === "true" || - target.closest('[role="listbox"], [role="menu"]') !== null)) +/** What Escape's owner is read from on the focused element. */ +export type Focused = Readonly<{ + getAttribute: (name: string) => string | null + isInside: (selector: string) => boolean +}> + +/** + * A focused popup owns Escape: an open popup trigger, or a list or menu. A disclosure such as a + * component's row is expanded but no popup, so Escape still closes it. + */ +export const popupOwnsEscape = (focused: Focused): boolean => + (focused.getAttribute("aria-expanded") === "true" && focused.getAttribute("aria-haspopup") !== null) || + focused.isInside('[role="listbox"], [role="menu"]') + +const focusedOf = (element: Element): Focused => ({ + getAttribute: (name) => element.getAttribute(name), + isInside: (selector) => element.closest(selector) !== null, +}) const escapes: Stream.Stream = Dom.streamFromEventFilterMap({ target: () => document, type: "keydown", filterMapEvent: (event) => - event.key !== "Escape" || isPopupOpen(event.target) + event.key !== "Escape" || + isDialogOpen() || + (event.target instanceof Element && popupOwnsEscape(focusedOf(event.target))) ? Option.none() : Option.some(Message.PressedEscape()), }) @@ -37,7 +51,7 @@ export const subscriptions = Subscription.make, Mes previewSelection: entry( { isCanvas: Schema.Boolean }, { - modelToDependencies: ({ model }) => ({ isCanvas: resolveView(model.search.view) === "page" }), + modelToDependencies: ({ model }) => ({ isCanvas: resolveView(model.search).tab === "page" }), dependenciesToStream: ({ isCanvas }) => isCanvas ? previewSelections.pipe( diff --git a/apps/web/src/page/status-pages/editor/update-components.ts b/apps/web/src/page/status-pages/editor/update-components.ts index 3205503a4a..0b490ff021 100644 --- a/apps/web/src/page/status-pages/editor/update-components.ts +++ b/apps/web/src/page/status-pages/editor/update-components.ts @@ -25,7 +25,6 @@ import { AddComponents, CreateEditorMonitor, DeleteComponent, - FocusEditorElement, ReorderComponents, SaveComponent, TrackMonitorCreated, @@ -44,12 +43,15 @@ import { toast, } from "./reads" -// Components in the side panel: saved as you go, removed behind a confirm, moved in the list, -// and added from the same checklist the builder uses. +// Components under Settings > Monitors: opened in place, saved as you go, removed behind a +// confirm, moved within their group, and added from the same checklist the builder uses. -export const PANEL_TITLE_ID = "status-page-panel-title" export const ADD_PICKER_ID = "status-page-add" +/** A component's row in the Monitors list: the button that opens and closes it. */ +export const componentRowId = (componentId: StatusPageComponentId): string => + `status-page-item-${componentId}` + export const deleteComponentDialog = (model: Model, step: ReturnType): Return => { const lifted = liftDialog( model, @@ -62,23 +64,20 @@ export const deleteComponentDialog = (model: Model, step: ReturnType ({ - model, - commands: [FocusEditorElement({ id: PANEL_TITLE_ID })], -}) - +/** + * Opens the component in its row, which scrolls itself into view as it mounts. The one open before + * saves what was typed first, or queues it behind a save in flight. + */ export const selectComponent = (model: Model, componentId: StatusPageComponentId): Return => { const found = Arr.findFirst(componentsOf(model), (row) => row.id === componentId) if (Option.isNone(found)) return { model } - const component = found.value - return focusPanel({ - ...model, - panel: { _tag: "Component", componentId }, - componentForm: componentFormOf(component), - componentSave: "idle", - componentFailure: null, - }) + return chain(model, commitComponent, (next) => ({ + model: { + ...next, + panel: { _tag: "Component", componentId }, + componentForm: componentFormOf(found.value), + }, + })) } export const changeComponent = (model: Model, field: ComponentTextField, value: string): Return => ({ @@ -88,43 +87,74 @@ export const changeComponent = (model: Model, field: ComponentTextField, value: const isSame = (form: ComponentForm, component: V2StatusPageComponent): boolean => encodeJson(componentPayload(form)) === encodeJson(componentPayload(componentFormOf(component))) -/** Saves the form when it differs from the component; a save in flight re-commits when it lands. */ -export const commitComponent = (model: Model): Return => { - const form = model.componentForm +const withoutQueued = (model: Model, componentId: string | null): Model => ({ + ...model, + queuedComponentForms: Arr.filter(model.queuedComponentForms, (form) => form.editingId !== componentId), +}) + +/** + * Saves `form` when it differs from its component. With a save in flight it waits in the queue, + * replacing any older form of the same component. + */ +const commitForm = (model: Model, form: ComponentForm): Return => { const found = Arr.findFirst(componentsOf(model), (row) => row.id === form.editingId) if ( !canManage(model) || model.pageId === null || Option.isNone(found) || - model.componentSave === "saving" || Str.trim(form.name) === "" || isSame(form, found.value) ) - return { model } - const saved = found.value + return { model: withoutQueued(model, form.editingId) } + const rest = withoutQueued(model, form.editingId) + if (model.componentSave?._tag === "Saving") + return { model: { ...rest, queuedComponentForms: [...rest.queuedComponentForms, form] } } return { - model: { ...model, componentSave: "saving", componentFailure: null }, + model: { ...rest, componentSave: { _tag: "Saving", componentId: found.value.id } }, commands: [ - SaveComponent({ pageId: model.pageId, componentId: saved.id, payload: componentPayload(form) }), + SaveComponent({ + pageId: model.pageId, + componentId: found.value.id, + payload: componentPayload(form), + }), ], } } +/** Saves the open component's form; nothing while no component is open. */ +export const commitComponent = (model: Model): Return => + model.panel?._tag === "Component" && model.panel.componentId === model.componentForm.editingId + ? commitForm(model, model.componentForm) + : { model } + +/** The next queued form, once the save before it landed. */ +const commitQueued = (model: Model): Return => + Option.match(Arr.head(model.queuedComponentForms), { + onNone: () => ({ model }), + onSome: (form) => commitForm(model, form), + }) + /** Components and the page revision change together: both are read again. */ const reread = (model: Model, context: PageContext): Return => chain(model, readComponents(context, "Supersede"), readPage(context, "Supersede")) +/** + * A save landed for the component it was sent for. A refused one is shown on that component's row, + * and its queued edits are dropped rather than sent behind its back; other components' queue on. + */ export const savedComponent = ( model: Model, result: Result.Result, context: PageContext, -): Return => - Result.match(result, { +): Return => { + const save = model.componentSave + if (save?._tag !== "Saving") return { model } + return Result.match(result, { onSuccess: (component): Return => { // The saved row replaces the listed one at once, so the next commit diffs against it. const next: Model = { ...model, - componentSave: "saved", + componentSave: { _tag: "Saved", componentId: save.componentId }, components: { ...model.components, data: AsyncData.map(model.components.data, (rows) => @@ -132,27 +162,50 @@ export const savedComponent = ( ), }, } - return chain(next, (settled) => reread(settled, context), commitComponent) + return chain(next, (settled) => reread(settled, context), commitQueued) }, - onFailure: (componentFailure): Return => ({ - model: { ...model, componentSave: "failed", componentFailure }, - }), + onFailure: (failure): Return => + commitQueued( + withoutQueued( + { ...model, componentSave: { _tag: "Failed", componentId: save.componentId, failure } }, + save.componentId, + ), + ), }) +} -/** The list with `componentId` moved by `offset`, or `null` when it cannot move that way. */ -export const moved = ( +type Groupable = { readonly id: StatusPageComponentId; readonly group: string | null } + +/** + * The components as the public page lists them: each group, ungrouped ones too, where its first + * member is, then its members in page order. + */ +export const groupedOrder = (components: ReadonlyArray): ReadonlyArray => + Arr.flatMap(Arr.dedupe(Arr.map(components, (component) => component.group)), (group) => + Arr.filter(components, (component) => component.group === group), + ) + +/** + * The list with `componentId` swapped with its neighbour in its group (`offset` -1 or 1), every + * other component where it was; `null` when it has no neighbour that way. + */ +export const moved = ( components: ReadonlyArray, componentId: StatusPageComponentId, offset: number, ): ReadonlyArray | null => { - const found = Arr.findFirstIndex(components, (component) => component.id === componentId) - if (Option.isNone(found)) return null - const from = found.value - const to = from + offset - const item = components[from] - if (to < 0 || to >= components.length || item === undefined) return null - const rest = Arr.filter(components, (_, index) => index !== from) - return [...rest.slice(0, to), item, ...rest.slice(to)] + const item = Arr.findFirst(components, (component) => component.id === componentId) + if (Option.isNone(item)) return null + const group = Arr.filter(components, (component) => component.group === item.value.group) + const neighbour = Option.flatMap( + Arr.findFirstIndex(group, (component) => component.id === componentId), + (index) => Arr.get(group, index + offset), + ) + if (Option.isNone(neighbour)) return null + const other = neighbour.value + return Arr.map(components, (component) => + component.id === componentId ? other : component.id === other.id ? item.value : component, + ) } /** Moves the row at once; the server's order lands with the re-read. */ @@ -221,7 +274,7 @@ export const deletedComponent = ( closed.model.panel?._tag === "Component" && closed.model.panel.componentId === removedId ? null : closed.model.panel - const refreshed = reread({ ...closed.model, panel }, context) + const refreshed = reread(withoutQueued({ ...closed.model, panel }, removedId), context) return { model: refreshed.model, commands: [...(closed.commands ?? []), ...(refreshed.commands ?? [])], @@ -248,7 +301,7 @@ export const openAdd = (model: Model): Return => { false, ) const session = model.addSession + 1 - return focusPanel({ ...model, panel: { _tag: "Add", session }, addSession: session, addPicker: picker }) + return { model: { ...model, panel: { _tag: "Add", session }, addSession: session, addPicker: picker } } } /** Whether the Add panel open now is the one `session` started in. */ @@ -308,20 +361,12 @@ export const submitAdd = (model: Model): Return => { } } -/** Closes the Add panel it came from and hands focus back; any panel opened since stays open. */ -const settleAdd = (model: Model, session: number, context: PageContext): Return => { - const isAddOpen = isAddSession(model, session) - const next = reread( - { ...model, isAddingComponents: false, panel: isAddOpen ? null : model.panel }, +/** Closes the Add sheet it came from; anything opened since stays open. */ +const settleAdd = (model: Model, session: number, context: PageContext): Return => + reread( + { ...model, isAddingComponents: false, panel: isAddSession(model, session) ? null : model.panel }, context, ) - return isAddOpen - ? { - ...next, - commands: [...(next.commands ?? []), FocusEditorElement({ id: "status-page-on-this-page" })], - } - : next -} export const addedComponents = ( model: Model, diff --git a/apps/web/src/page/status-pages/editor/update-incidents.ts b/apps/web/src/page/status-pages/editor/update-incidents.ts index 9391899f2e..69d5cfbdb2 100644 --- a/apps/web/src/page/status-pages/editor/update-incidents.ts +++ b/apps/web/src/page/status-pages/editor/update-incidents.ts @@ -8,6 +8,7 @@ import { StatusPageIncidentImpact, StatusPageIncidentStatus } from "@maple/domai import { worstStatus } from "@maple/domain/status-page" import type { V2StatusPageIncident } from "@maple/domain/http/v2" import { Option, Result, Schema, Array as Arr, String as Str } from "effect" +import { AsyncData } from "foldkit" import type { LoadFailure } from "@maple/views/data/load-failure" import type { PageContext } from "../../contract" import { componentStatus, isOpenIncident, STATUSES_OF_KIND } from "../shared/derive" @@ -50,7 +51,6 @@ import { type Return, toast, } from "./reads" -import { focusPanel } from "./update-components" // Incidents: the Post incident, Post update and Edit details dialogs, publishing a draft, deleting. @@ -202,7 +202,7 @@ export const submitIncident = (model: Model, context: PageContext, isPublished: } } -/** A created incident closes the dialog and opens in the panel; a refused one stays on review with why. */ +/** A created incident closes the dialog and opens in the sheet; a refused one stays on review with why. */ export const createdIncident = ( model: Model, result: Result.Result, @@ -214,7 +214,18 @@ export const createdIncident = ( const noun = incident.kind === "incident" ? "Incident" : "Maintenance" return { ...chain( - { ...settled, panel: { _tag: "Incident", incidentId: incident.id } }, + { + ...settled, + panel: { _tag: "Incident", incidentId: incident.id }, + // The sheet shows it at once; the re-read confirms it. + incidents: { + ...settled.incidents, + data: AsyncData.map(settled.incidents.data, (rows) => [ + incident, + ...Arr.filter(rows, (row) => row.id !== incident.id), + ]), + }, + }, (next) => composeDialog(next, Dialog.close(next.composeDialog)), (next) => reread(next, context), ), @@ -229,10 +240,10 @@ export const createdIncident = ( }) } -/** Opens the incident in the panel. */ +/** Opens the incident in the sheet. */ export const selectIncident = (model: Model, incidentId: StatusPageIncidentId): Return => Arr.some(incidentsOf(model), (incident) => incident.id === incidentId) - ? focusPanel({ ...model, panel: { _tag: "Incident", incidentId } }) + ? { model: { ...model, panel: { _tag: "Incident", incidentId } } } : { model } /** The Post update dialog on its write step: the next status along, or the closing one for Resolve. */ diff --git a/apps/web/src/page/status-pages/editor/update.ts b/apps/web/src/page/status-pages/editor/update.ts index 486b45e684..664392ac19 100644 --- a/apps/web/src/page/status-pages/editor/update.ts +++ b/apps/web/src/page/status-pages/editor/update.ts @@ -8,7 +8,14 @@ import * as CopyButton from "@maple/views/ui/copy-button" import * as Dialog from "@maple/views/ui/dialog" import * as Menu from "@maple/views/ui/menu" import { type PageContext, PageOutMessage } from "../../contract" -import { type EditorView, pageIdFromUrl, STATUS_PAGE_BASE_URL, statusPageHref } from "../shared/commands" +import type { StatusPageSearch } from "../../../route/search" +import { + pageIdFromUrl, + SETTINGS_SECTIONS, + type SettingsSection, + STATUS_PAGE_BASE_URL, + statusPageHref, +} from "../shared/commands" import { emptyComponentForm, emptyIncidentForm } from "../shared/form" import { emptyPicker } from "../shared/picker" import { historyFrom } from "../shared/preview" @@ -24,6 +31,7 @@ import type { Model } from "./model" import { chain, componentsOf, + incidentsOf, pageOf, readComponents, readConfig, @@ -39,6 +47,7 @@ import { askDeleteComponent, changeComponent, commitComponent, + componentRowId, confirmDeleteComponent, deleteComponentDialog, deletedComponent, @@ -132,9 +141,46 @@ import { acceptGrants } from "../../kit/session-grants" type EditorRoute = Extract -/** The view the search names; anything else is the page itself, so an old or mistyped link lands. */ -export const resolveView = (view: string | undefined): EditorView | "page" => - view === "appearance" || view === "settings" || view === "json" || view === "live" ? view : "page" +/** The editor's tabs: the live page, incidents, maintenance, settings, and the just-published screen. */ +export type EditorTab = "page" | "incidents" | "maintenance" | "settings" | "live" + +export type EditorLocation = Readonly<{ tab: EditorTab; section: SettingsSection }> + +const isSection = (value: string | undefined): value is SettingsSection => + Arr.some(SETTINGS_SECTIONS, (section) => section === value) + +/** + * Where the search points; anything unknown is the live page, so an old or mistyped link lands. + * The old Appearance and JSON tabs are Settings sections now. + */ +export const resolveView = (search: typeof StatusPageSearch.Type): EditorLocation => { + const section = isSection(search.section) ? search.section : "basic" + switch (search.view) { + case "incidents": + case "maintenance": + case "settings": + case "live": + return { tab: search.view, section } + case "appearance": + return { tab: "settings", section: "appearance" } + case "json": + return { tab: "settings", section: "advanced" } + default: + return { tab: "page", section } + } +} + +/** Whether the tab shows what is open: a component under Monitors, an incident under its tab. */ +const showsPanel = (panel: Model["panel"], location: EditorLocation): boolean => { + if (panel === null) return false + switch (panel._tag) { + case "Component": + case "Add": + return location.tab === "settings" && location.section === "monitors" + case "Incident": + return location.tab === "incidents" || location.tab === "maintenance" + } +} export const PAGE_MENU_ID = "status-page-menu" @@ -153,6 +199,9 @@ export const init = (route: EditorRoute, context: PageContext): Return => { isSessionLoaded: false, pageMenu: Menu.init(PAGE_MENU_ID), panel: null, + panelSheet: Dialog.init("status-page-panel", "sheet"), + sheetPanel: null, + sheetIncident: null, previewScheme: "light", previewWidth: "desktop", previewState: "live", @@ -160,8 +209,8 @@ export const init = (route: EditorRoute, context: PageContext): Return => { previewShown: 0, previewHistory: [], componentForm: emptyComponentForm, - componentSave: "idle", - componentFailure: null, + componentSave: null, + queuedComponentForms: [], confirmDeleteComponentId: null, deleteComponentDialog: Dialog.init("status-page-delete-component", "alert-dialog"), isDeletingComponent: false, @@ -231,24 +280,35 @@ export const init = (route: EditorRoute, context: PageContext): Return => { } } -/** The config read, only while the JSON view is open: the document must be current when edited. */ +/** The config read, only while Advanced (the JSON editor) is open: the document must be current when edited. */ const whenJson = (context: PageContext, mode: Keyed.ReadMode) => - (model: Model): Return => - resolveView(model.search.view) === "json" ? readConfig(context, mode)(model) : { model } + (model: Model): Return => { + const location = resolveView(model.search) + return location.tab === "settings" && location.section === "advanced" + ? readConfig(context, mode)(model) + : { model } + } /** The custom domain moves on the server's schedule: opening Settings shows where it is now. */ const whenSettings = (context: PageContext, mode: Keyed.ReadMode) => (model: Model): Return => - resolveView(model.search.view) === "settings" ? readCustomDomain(context, mode)(model) : { model } + resolveView(model.search).tab === "settings" ? readCustomDomain(context, mode)(model) : { model } -/** A view switch is a search change; opening JSON re-reads the config, since other views write too. */ +/** + * A tab switch is a search change; what is open stays open only where the new tab shows it. + * Opening Advanced re-reads the config, since other sections write too. + */ export const routeChanged = (model: Model, route: EditorRoute, context: PageContext): Return => - chain( - { ...model, search: route.search, panel: null }, - whenJson(context, "Refresh"), - whenSettings(context, "Refresh"), + withSheet( + chain( + showsPanel(model.panel, resolveView(route.search)) + ? { ...model, search: route.search } + : { ...model, search: route.search, panel: null, componentForm: emptyComponentForm }, + whenJson(context, "Refresh"), + whenSettings(context, "Refresh"), + ), ) /** The dialogs ignore dismissal while their write is in flight, as `ConfirmDialog` does. */ @@ -280,21 +340,92 @@ const schedulePreview = (model: Model): Return => { // PANEL -/** Closing hands focus back to the row that opened the panel, or the list. */ +/** Closing a component hands focus back to its row; the sheet hands it back on its own. */ const closePanel = (model: Model): Return => { const panel = model.panel - const target = - panel?._tag === "Component" - ? `status-page-item-${panel.componentId}` - : panel?._tag === "Incident" - ? `status-page-item-${panel.incidentId}` - : "status-page-on-this-page" - return panel === null - ? { model } - : { - model: { ...model, panel: null }, - commands: [FocusEditorElement({ id: target })], + if (panel === null) return { model } + return panel._tag === "Component" + ? { + model: { ...model, panel: null, componentForm: emptyComponentForm }, + commands: [FocusEditorElement({ id: componentRowId(panel.componentId) })], } + : { model: { ...model, panel: null } } +} + +const sheetCommands = (step: ReturnType) => + FoldkitCommand.mapMessages(step.commands ?? [], (message) => Message.GotPanelSheetMessage({ message })) + +/** The open incident as listed, else the one the sheet last showed. */ +const shownIncident = (model: Model): Model["sheetIncident"] => { + const panel = model.panel + if (panel?._tag !== "Incident") return model.sheetIncident + return Option.getOrElse( + Arr.findFirst(incidentsOf(model), (row) => row.id === panel.incidentId), + () => model.sheetIncident, + ) +} + +/** + * Opens the sheet while an incident or Add is open and closes it otherwise, whatever opened them. + * The sheet keeps showing the last of them, the incident as last listed, while it animates out. + */ +const withSheet = (result: Return): Return => { + const isWanted = result.model.panel !== null && result.model.panel._tag !== "Component" + const model = { + ...result.model, + sheetPanel: isWanted ? result.model.panel : result.model.sheetPanel, + sheetIncident: shownIncident(result.model), + } + if (isWanted === model.panelSheet.isOpen) return { ...result, model } + const step = isWanted ? Dialog.open(model.panelSheet) : Dialog.close(model.panelSheet) + return { + ...result, + model: { ...model, panelSheet: step.model }, + commands: [...(result.commands ?? []), ...sheetCommands(step)], + } +} + +/** The sheet closed itself (Escape, backdrop, close button): what it showed closes with it. */ +const updatePanelSheet = (model: Model, message: Dialog.Message): Return => { + const step = Dialog.update(model.panelSheet, message) + return { + model: { + ...model, + panelSheet: step.model, + panel: step.outMessage?._tag === "Closed" ? null : model.panel, + }, + commands: sheetCommands(step), + } +} + +/** A click in the live page opens what it landed on where it is edited. */ +const selectFromPreview = (model: Model, kind: "component" | "incident", id: string): Return => { + const navigate = (url: string) => PageOutMessage.RequestedNavigation({ url, isReplace: false }) + if (model.pageId === null) return { model } + const pageId = model.pageId + if (kind === "component") + return Option.match( + Arr.findFirst(componentsOf(model), (row) => row.id === id), + { + onNone: () => ({ model }), + onSome: (component) => ({ + ...selectComponent(model, component.id), + outMessage: navigate(statusPageHref(pageId, "settings", "monitors")), + }), + }, + ) + return Option.match( + Arr.findFirst(incidentsOf(model), (row) => row.id === id), + { + onNone: () => ({ model }), + onSome: (incident) => ({ + ...selectIncident(model, incident.id), + outMessage: navigate( + statusPageHref(pageId, incident.kind === "incident" ? "incidents" : "maintenance"), + ), + }), + }, + ) } /** The "..." menu: links navigate, the rest are this page's own actions. */ @@ -312,7 +443,9 @@ const updatePageMenu = (model: Model, message: Menu.Message): Return => { }) switch (result.outMessage.value) { case "break-glass": - return navigate(`${statusPageHref(model.pageId, "settings")}#status-page-settings-break-glass`) + return navigate( + `${statusPageHref(model.pageId, "settings", "advanced")}#status-page-settings-break-glass`, + ) case "delete": return deletePageDialog(next, Dialog.open(next.deletePageDialog)) default: @@ -321,6 +454,9 @@ const updatePageMenu = (model: Model, message: Menu.Message): Return => { } export const update = (model: Model, message: Message, context: PageContext): Return => + withSheet(step(model, message, context)) + +const step = (model: Model, message: Message, context: PageContext): Return => Message.match(message, { ReadClock: ({ nowMs }) => ({ model: { ...model, nowMs } }), // Each fresh read re-reads the clock, so "published 2m ago" and update times never drift into the future. @@ -395,29 +531,14 @@ export const update = (model: Model, message: Message, context: PageContext): Re }, }), }), - ReceivedPreviewSelection: ({ kind, id }) => { - return kind === "component" - ? Option.match( - Arr.findFirst(componentsOf(model), (row) => row.id === id), - { - onNone: () => ({ model }), - onSome: (component) => selectComponent(model, component.id), - }, - ) - : Option.match( - Arr.findFirst( - AsyncData.getOrElse(model.incidents.data, () => []), - (row) => row.id === id, - ), - { - onNone: () => ({ model }), - onSome: (incident) => selectIncident(model, incident.id), - }, - ) - }, - ClickedComponent: ({ componentId }) => selectComponent(model, componentId), + ReceivedPreviewSelection: ({ kind, id }) => selectFromPreview(model, kind, id), + // A second click on the open component closes it; its fields saved on blur. + ClickedComponent: ({ componentId }) => + model.panel?._tag === "Component" && model.panel.componentId === componentId + ? closePanel(model) + : selectComponent(model, componentId), ClickedIncident: ({ incidentId }) => selectIncident(model, incidentId), - ClickedClosePanel: () => closePanel(model), + GotPanelSheetMessage: ({ message: child }) => updatePanelSheet(model, child), // Escape skips the field's blur, so a component panel saves its typed edits before it closes. PressedEscape: () => model.panel?._tag === "Component" ? chain(model, commitComponent, closePanel) : closePanel(model), @@ -539,6 +660,7 @@ export const update = (model: Model, message: Message, context: PageContext): Re CompletedFetchCustomDomain: ({ key, result }) => ({ model: { ...model, customDomain: Keyed.accept(model.customDomain, key, result) }, }), + ClickedRetryCustomDomain: () => readCustomDomain(context, "Refresh")(model), ChangedCustomDomain: ({ value }) => changeCustomDomain(model, value), SubmittedCustomDomain: () => submitCustomDomain(model), CompletedSetCustomDomain: ({ result }) => savedCustomDomain(model, result), diff --git a/apps/web/src/page/status-pages/editor/view-access.ts b/apps/web/src/page/status-pages/editor/view-access.ts index 8afd2273bb..9968746eef 100644 --- a/apps/web/src/page/status-pages/editor/view-access.ts +++ b/apps/web/src/page/status-pages/editor/view-access.ts @@ -1,6 +1,7 @@ import type { StatusPageVisibility } from "@maple/domain" import type { V2StatusPage } from "@maple/domain/http/v2" import { Option, Array as Arr } from "effect" +import { AsyncData } from "foldkit" import type { Html, HtmlBuilder } from "foldkit/html" import { alert, alertDescription, alertTitle } from "@maple/views/ui/alert" import { button, linkButton } from "@maple/views/ui/button" @@ -12,12 +13,16 @@ import { failureMessage } from "@maple/views/data/load-failure" import { adminOnlyNote, settingsSection } from "../../kit/settings-section" import { statusPageViewHref } from "../shared/commands" import { textField } from "../shared/fields" +import type { SettingsForm } from "../shared/form" +import { fragmentFrame, onYourPage } from "../shared/preview" +import { draftSnapshot } from "./view-canvas" +import { renderAccessPage } from "@maple/status-page" import { Message } from "./message" import { canChangeAccess, type Model } from "./model" import { passwordIssue } from "./update-access" import { customDomainOf } from "./update-domain" -// The Settings tab's Access section: public, behind a password, or members only. +// Settings > Access: public, behind a password, or members only, and the password form visitors meet. type H = HtmlBuilder @@ -49,12 +54,15 @@ const VISIBILITIES: ReadonlyArray<{ const blockedReason = (model: Model, page: V2StatusPage, value: StatusPageVisibility): string | null => { if (value === page.visibility) return null if (value === "password" && !page.has_password) return "Set a password below first." - const hasDomain = Option.match(customDomainOf(model), { - onNone: () => false, - onSome: (domain) => domain.hostname !== null, + if (value !== "internal") return null + // An internal page answers no custom domain, so one must be known to be absent first. + return Option.match(customDomainOf(model), { + onSome: (domain) => (domain.hostname === null ? null : "Remove the custom domain first."), + onNone: () => + AsyncData.hasError(model.customDomain.data) + ? "Couldn't check for a custom domain. Try again under Basic settings." + : "Checking for a custom domain…", }) - if (value === "internal" && hasDomain) return "Remove the custom domain first." - return null } const visibilityChoice = (h: H, model: Model, page: V2StatusPage, option: (typeof VISIBILITIES)[number]) => { @@ -115,9 +123,12 @@ const passwordForm = (h: H, model: Model, draft: string): Html => { } const passwordRow = (h: H, model: Model, page: V2StatusPage): Html => { - if (model.passwordDraft !== null && canChangeAccess(model)) return passwordForm(h, model, model.passwordDraft) + if (model.passwordDraft !== null && canChangeAccess(model)) + return passwordForm(h, model, model.passwordDraft) return hstack(h, { gap: "3", justify: "between", wrap: true }, [ - typography(h, { size: "sm", as: "p" }, [page.has_password ? "A page password is set" : "No page password"]), + typography(h, { size: "sm", as: "p" }, [ + page.has_password ? "A page password is set" : "No page password", + ]), ...(canChangeAccess(model) ? [ hstack(h, { gap: "2" }, [ @@ -153,7 +164,7 @@ const passwordRow = (h: H, model: Model, page: V2StatusPage): Html => { ]) } -export const accessSection = (h: H, model: Model, page: V2StatusPage): Html => +export const accessSection = (h: H, model: Model, page: V2StatusPage, form: SettingsForm): Html => settingsSection( h, { @@ -177,10 +188,11 @@ export const accessSection = (h: H, model: Model, page: V2StatusPage): Html => typography(h, { size: "xs", tone: "muted", as: "p" }, [ "Members read the page inside Maple.", ]), - linkButton(h, { size: "sm", variant: "outline", href: statusPageViewHref(page.id) }, [ - icon(h, "EyeIcon"), - "Open page", - ]), + linkButton( + h, + { size: "sm", variant: "outline", href: statusPageViewHref(page.id) }, + [icon(h, "EyeIcon"), "Open page"], + ), ]), ] : []), @@ -193,6 +205,25 @@ export const accessSection = (h: H, model: Model, page: V2StatusPage): Html => alertDescription(h, [failureMessage(model.accessFailure)]), ]), ]), + ...(page.visibility === "password" + ? [ + onYourPage( + h, + fragmentFrame(h, { + title: "The password form visitors see first", + document: renderAccessPage( + draftSnapshot(model, page, form, "live"), + undefined, + { + inDashboard: true, + }, + ), + className: "h-96", + }), + "What visitors see", + ), + ] + : []), ]), ], ) diff --git a/apps/web/src/page/status-pages/editor/view-appearance.ts b/apps/web/src/page/status-pages/editor/view-appearance.ts index b4e5626fd7..6222e66e58 100644 --- a/apps/web/src/page/status-pages/editor/view-appearance.ts +++ b/apps/web/src/page/status-pages/editor/view-appearance.ts @@ -6,14 +6,11 @@ import { StatusPageThemeRadius, type StatusPageThemeTokens, } from "@maple/domain/status-page" -import { previewSnapshot } from "@maple/status-page" import { Schema, Array as Arr, String as Str } from "effect" import type { Html, HtmlBuilder } from "foldkit/html" import { alert, alertDescription, alertTitle } from "@maple/views/ui/alert" import { colorInput } from "@maple/views/ui/color-input" import { segmentedSelect } from "@maple/views/ui/segmented-select" -import { skeleton } from "@maple/views/ui/skeleton" -import { heading } from "@maple/views/ui/heading" import { settingsSection } from "../../kit/settings-section" import { selectField, textField } from "../shared/fields" import { @@ -24,30 +21,18 @@ import { settingsIssues, themeColorIssues, themeContrastOf, - themeOf, } from "../shared/form" import { Message } from "./message" -import { pageUrlOf } from "./update-domain" import { canManage, type Model } from "./model" -import { monitorStatusOf } from "../shared/derive" import { APPEARANCES, presetCards } from "../shared/look" -import { - daysOf, - isListedIncident, - previewControls, - previewDocument, - previewExampleNote, - previewFrame, - previewTheme, - simulatePreview, - toSnapshotIncident, -} from "../shared/preview" -import { componentsOf, incidentsOf, monitorsOf, statusReadsReady } from "./reads" +import { onYourPage } from "../shared/preview" +import { componentsOf } from "./reads" +import { fragmentPreview, tabPreview } from "./view-canvas" import { typography } from "@maple/views/ui/typography" +import { grid } from "@maple/views/ui/grid" import { hstack, vstack } from "@maple/views/ui/stack" -import { toEpochMs } from "@maple/ui/lib/time-format" -// The Settings view's Appearance section and the live preview of the public page. +// Settings > Appearance: the brand (logos, tab icon) and the theme, each with how it reads on the page. type H = HtmlBuilder @@ -124,7 +109,7 @@ const colorField = ( } /** The logos and tab icon: what carries the brand besides the colours. */ -export const brandingSection = (h: H, model: Model, form: SettingsForm): Html => { +export const brandingSection = (h: H, model: Model, page: V2StatusPage, form: SettingsForm): Html => { const issues = settingsIssues(form) const isReadOnly = !canManage(model) return settingsSection( @@ -132,12 +117,13 @@ export const brandingSection = (h: H, model: Model, form: SettingsForm): Html => { id: "status-page-settings-branding", title: "Branding", - description: ["Your logo in the page header and the icon in the browser tab."], + description: [ + "Your logo in the page header and the icon in the browser tab. Without a logo, the page shows its initial in your accent colour.", + ], }, [ - h.div( - [h.Class("grid gap-4 sm:grid-cols-2")], - [ + vstack(h, { gap: "4" }, [ + grid(h, { sm: 2, gap: "4" }, [ textField(h, { id: "status-page-logo", label: "Logo URL", @@ -167,13 +153,31 @@ export const brandingSection = (h: H, model: Model, form: SettingsForm): Html => error: issues.faviconUrl, onInput: (value) => Message.ChangedSetting({ field: "faviconUrl", value }), }), - ], - ), + ]), + onYourPage(h, tabPreview(h, model, page, form, null)), + ]), ], ) } -export const appearanceSection = (h: H, model: Model, form: SettingsForm): Html => { +/** The theme on the banner, one component and a link: the first component stands for the rest. */ +const themePreview = (h: H, model: Model, page: V2StatusPage, form: SettingsForm): Html => { + const first = componentsOf(model)[0] + const title = "The theme as visitors see it" + return onYourPage( + h, + first === undefined + ? fragmentPreview(h, model, page, form, { title, parts: ["header", "hero"], className: "h-48" }) + : fragmentPreview(h, model, page, form, { + title, + parts: ["header", "hero", "components"], + componentId: first.id, + className: "h-96", + }), + ) +} + +export const appearanceSection = (h: H, model: Model, page: V2StatusPage, form: SettingsForm): Html => { const theme = form.theme const isReadOnly = !canManage(model) const isAuto = theme.appearance === "auto" @@ -183,7 +187,7 @@ export const appearanceSection = (h: H, model: Model, form: SettingsForm): Html h, { id: "status-page-settings-appearance", - title: "Appearance", + title: "Theme", description: ["Colors, corners and type of the public page."], }, [ @@ -212,8 +216,9 @@ export const appearanceSection = (h: H, model: Model, form: SettingsForm): Html : `Every visitor sees the ${theme.appearance} page.`, ]), ]), - h.div( - [h.Class("grid gap-4 sm:grid-cols-2")], + grid( + h, + { sm: 2, gap: "4" }, Arr.map(COLOR_FIELDS, (entry) => colorField( h, @@ -232,122 +237,30 @@ export const appearanceSection = (h: H, model: Model, form: SettingsForm): Html alertDescription(h, [contrast]), ]), ]), - h.div( - [h.Class("grid gap-4 sm:grid-cols-2")], - [ - selectField(h, { - id: "status-page-theme-radius", - label: "Corners", - value: theme.radius, - entries: RADII, - isDisabled: isReadOnly, - onInput: (value) => - Message.PickedThemeRadius({ - radius: isRadius(value) ? value : theme.radius, - }), - }), - selectField(h, { - id: "status-page-theme-font", - label: "Font", - value: theme.font, - entries: FONTS, - isDisabled: isReadOnly, - onInput: (value) => - Message.PickedThemeFont({ font: isFont(value) ? value : theme.font }), - }), - ], - ), + grid(h, { sm: 2, gap: "4" }, [ + selectField(h, { + id: "status-page-theme-radius", + label: "Corners", + value: theme.radius, + entries: RADII, + isDisabled: isReadOnly, + onInput: (value) => + Message.PickedThemeRadius({ + radius: isRadius(value) ? value : theme.radius, + }), + }), + selectField(h, { + id: "status-page-theme-font", + label: "Font", + value: theme.font, + entries: FONTS, + isDisabled: isReadOnly, + onInput: (value) => + Message.PickedThemeFont({ font: isFont(value) ? value : theme.font }), + }), + ]), + themePreview(h, model, page, form), ]), ], ) } - -const orNull = (value: string): string | null => (Str.trim(value) === "" ? null : Str.trim(value)) - -/** The public page as the draft would render it, from the loaded components and incidents. */ -export const settingsDocument = (model: Model, page: V2StatusPage, form: SettingsForm): string => { - const nowMs = model.nowMs ?? toEpochMs(page.updated_at) - const monitors = monitorsOf(model) - const shown = simulatePreview(model.previewState, { - components: Arr.map(componentsOf(model), (component) => ({ - id: component.id, - name: component.name, - description: component.description, - group: component.group, - monitorStatus: monitorStatusOf(monitors, component.monitor_id), - manualStatus: component.manual_status, - showUptime: component.show_uptime, - monitored: component.monitor_id !== null, - days: daysOf(model.previewHistory, component.monitor_id), - })), - incidents: Arr.map( - Arr.filter(incidentsOf(model), (incident) => isListedIncident(incident, nowMs)), - toSnapshotIncident, - ), - nowMs, - }) - const snapshot = previewSnapshot({ - pageId: page.id, - page: { - name: Str.trim(form.name) === "" ? page.name : Str.trim(form.name), - slug: form.slug, - description: orNull(form.description), - websiteUrl: orNull(form.websiteUrl), - logoUrl: orNull(form.logoUrl), - logoDarkUrl: orNull(form.logoDarkUrl), - faviconUrl: orNull(form.faviconUrl), - supportUrl: orNull(form.supportUrl), - privacyUrl: orNull(form.privacyUrl), - termsUrl: orNull(form.termsUrl), - customDomain: null, - visibility: page.visibility, - showPoweredBy: form.showPoweredBy, - theme: previewTheme(themeOf(form.theme), model.previewScheme), - }, - components: shown.components, - incidents: shown.incidents, - nowMs, - }) - return previewDocument({ - snapshot, - nowMs, - isSelectable: false, - selectedIds: [], - publicUrl: pageUrlOf(model, page), - }) -} - -export const previewPanel = (h: H, model: Model, page: V2StatusPage, form: SettingsForm): Html => - vstack( - h, - { - gap: "3", - shrink: true, - as: "section", - className: "xl:sticky xl:top-6", - attributes: [h.AriaLabelledBy("status-page-preview-title")], - }, - [ - hstack(h, { gap: "3", justify: "between", wrap: true, className: "min-h-7" }, [ - heading(h, { level: 2, variant: "subsection", id: "status-page-preview-title" }, ["Preview"]), - previewControls(h, { - state: model.previewState, - width: model.previewWidth, - scheme: form.theme.appearance === "auto" ? model.previewScheme : null, - onState: (state) => Message.PickedPreviewState({ state }), - onWidth: (width) => Message.PickedPreviewWidth({ width }), - onScheme: (scheme) => Message.PickedPreviewScheme({ scheme }), - }), - ]), - ...previewExampleNote(h, model.previewState), - statusReadsReady(model) - ? previewFrame(h, { - title: "Status page preview", - document: settingsDocument(model, page, form), - width: model.previewWidth, - className: "h-[640px]", - }) - : skeleton(h, "h-[640px] w-full"), - typography(h, { size: "xs", tone: "muted", as: "p" }, ["Unsaved changes show here first."]), - ], - ) diff --git a/apps/web/src/page/status-pages/editor/view-canvas.ts b/apps/web/src/page/status-pages/editor/view-canvas.ts index baf1842825..9281a16090 100644 --- a/apps/web/src/page/status-pages/editor/view-canvas.ts +++ b/apps/web/src/page/status-pages/editor/view-canvas.ts @@ -1,83 +1,69 @@ import { StatusPageComponentStatus, UptimeMonitorId } from "@maple/domain" -import type { V2StatusPage, V2StatusPageComponent, V2StatusPageIncident } from "@maple/domain/http/v2" -import { previewSnapshot } from "@maple/status-page" -import { TONE_FILL } from "@maple/ui/lib/tone" -import { cn } from "@maple/ui/lib/utils" +import type { V2StatusPage, V2StatusPageComponent } from "@maple/domain/http/v2" +import type { StatusPageSnapshot } from "@maple/domain/status-page" +import { type FragmentPart, pageTitle, previewSnapshot, renderFragment } from "@maple/status-page" +import { toEpochMs } from "@maple/ui/lib/time-format" import { Option, Schema, Array as Arr, String as Str } from "effect" import type { Html, HtmlBuilder } from "foldkit/html" -import { button } from "@maple/views/ui/button" -import { eyebrow } from "@maple/views/ui/eyebrow" -import { icon } from "@maple/views/ui/icon" -import { iconButton } from "@maple/views/ui/icon-button" -import { pressable } from "@maple/views/ui/pressable" -import { - COMPONENT_STATUS_LABEL, - COMPONENT_STATUS_TONE, - componentStatus, - isOpenIncident, - monitorStatusOf, -} from "../shared/derive" +import { browserTabMockup } from "@maple/views/ui/page-mockup" +import { skeleton } from "@maple/views/ui/skeleton" +import { hstack, vstack } from "@maple/views/ui/stack" +import { typography } from "@maple/views/ui/typography" +import { monitorStatusOf } from "../shared/derive" +import { orNull, type SettingsForm, settingsFormOf, themeOf } from "../shared/form" import { daysOf, + fragmentFrame, isListedIncident, previewControls, previewDocument, previewExampleNote, previewFrame, + type PreviewState, previewTheme, simulatePreview, toSnapshotIncident, } from "../shared/preview" import { Message } from "./message" +import type { Model } from "./model" +import { componentsOf, incidentsOf, monitorsOf, statusReadsFailed, statusReadsReady } from "./reads" import { pageUrlOf } from "./update-domain" -import { canManage, canPostIncidents, type Model } from "./model" -import { componentsOf, incidentsOf, monitorsOf } from "./reads" -import { addPanel, componentPanel, incidentPanel, type TimeInputs } from "./view-panel" -import { typography } from "@maple/views/ui/typography" -import { hstack, vstack } from "@maple/views/ui/stack" -// The page itself as the editor: a sidebar beside the preview. The sidebar lists what is on the -// page; an opened component, incident or Add takes its place. Below `lg` the sidebar stacks on top. +// The Live page tab: the page as visitors get it, full width; a click on a component or incident +// opens it where it is edited. Also the snapshot every smaller preview of a setting renders from. type H = HtmlBuilder const decodeMonitorId = Schema.decodeUnknownOption(UptimeMonitorId) const decodeStatus = Schema.decodeUnknownOption(StatusPageComponentStatus) -/** The component as the panel's unsaved inputs have it, so the preview follows every keystroke. */ -const asEdited = (model: Model, component: V2StatusPageComponent) => { +/** The component as its open form has it, so previews follow every keystroke. */ +const asEdited = (model: Model, component: V2StatusPageComponent): V2StatusPageComponent => { const form = model.componentForm if (model.panel?._tag !== "Component" || form.editingId !== component.id) return component return { ...component, name: Str.trim(form.name) === "" ? component.name : Str.trim(form.name), - description: Str.trim(form.description) === "" ? null : Str.trim(form.description), - group: Str.trim(form.group) === "" ? null : Str.trim(form.group), + description: orNull(form.description), + group: orNull(form.group), monitor_id: Option.getOrNull(decodeMonitorId(form.monitorId)), manual_status: Option.getOrNull(decodeStatus(form.manualStatus)), show_uptime: form.showUptime, } } -/** What the preview outlines: the open component or incident. */ -export const selectedIds = (model: Model): ReadonlyArray => { - const panel = model.panel - if (panel === null) return [] - switch (panel._tag) { - case "Component": - return [panel.componentId] - case "Incident": - return [panel.incidentId] - case "Add": - return [] - } -} +const nowOf = (model: Model, page: V2StatusPage): number => model.nowMs ?? toEpochMs(page.updated_at) -/** The saved page as visitors get it, with the monitors' history and the panel's edits. */ -export const canvasDocument = (model: Model, page: V2StatusPage): string => { - const nowMs = model.nowMs ?? 0 +/** The page as the editor would publish it: `form`'s fields, the open component's edits, in `state`. */ +export const draftSnapshot = ( + model: Model, + page: V2StatusPage, + form: SettingsForm, + state: PreviewState, +): StatusPageSnapshot => { + const nowMs = nowOf(model, page) const monitors = monitorsOf(model) - const shown = simulatePreview(model.previewState, { + const shown = simulatePreview(state, { components: Arr.map(componentsOf(model), (saved) => { const component = asEdited(model, saved) return { @@ -98,263 +84,98 @@ export const canvasDocument = (model: Model, page: V2StatusPage): string => { ), nowMs, }) - const snapshot = previewSnapshot({ + return previewSnapshot({ pageId: page.id, page: { - name: page.name, - slug: page.slug, - description: page.description, - websiteUrl: page.website_url, - logoUrl: page.logo_url, - logoDarkUrl: page.logo_dark_url, - faviconUrl: page.favicon_url, - supportUrl: page.support_url, - privacyUrl: page.privacy_url, - termsUrl: page.terms_url, + name: draftName(page, form), + slug: form.slug, + description: orNull(form.description), + websiteUrl: orNull(form.websiteUrl), + logoUrl: orNull(form.logoUrl), + logoDarkUrl: orNull(form.logoDarkUrl), + faviconUrl: orNull(form.faviconUrl), + supportUrl: orNull(form.supportUrl), + privacyUrl: orNull(form.privacyUrl), + termsUrl: orNull(form.termsUrl), customDomain: null, visibility: page.visibility, - showPoweredBy: page.show_powered_by, - theme: previewTheme(page.theme, model.previewScheme), + showPoweredBy: form.showPoweredBy, + theme: previewTheme(themeOf(form.theme), model.previewScheme), }, components: shown.components, incidents: shown.incidents, nowMs, }) - return previewDocument({ - snapshot, - nowMs, - isSelectable: true, - selectedIds: selectedIds(model), - publicUrl: pageUrlOf(model, page), - }) } -const statusDot = (h: H, status: StatusPageComponentStatus): Html => - h.span( - [ - h.AriaHidden(true), - h.Class(cn("inline-block size-2 shrink-0 rounded-xs", TONE_FILL[COMPONENT_STATUS_TONE[status]])), - ], - [], - ) +/** The name the unsaved `form` gives the page; the saved one while the field is empty. */ +export const draftName = (page: V2StatusPage, form: SettingsForm): string => orNull(form.name) ?? page.name -const itemClass = (isSelected: boolean) => - cn( - "flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring", - isSelected - ? "bg-muted font-medium text-foreground" - : "text-muted-foreground hover:bg-surface-sunken hover:text-foreground active:bg-surface-sunken active:text-foreground", - ) - -const componentItem = ( +/** + * One part of the page as the unsaved `form` would render it, in a small inert frame: a setting's + * own preview. A banner or component waits for the statuses' reads, and says so when they failed, + * rather than read all clear. + */ +export const fragmentPreview = ( h: H, model: Model, - component: V2StatusPageComponent, - position: Readonly<{ isFirst: boolean; isLast: boolean }>, + page: V2StatusPage, + form: SettingsForm, + options: Readonly<{ + title: string + parts: ReadonlyArray + componentId?: string + className: string + }>, ): Html => { - const status = componentStatus(component, monitorsOf(model), incidentsOf(model)) - const isSelected = model.panel?._tag === "Component" && model.panel.componentId === component.id - return hstack( - h, - { gap: "1", align: "center", as: "li", className: "group", attributes: [h.Key(component.id)] }, - [ - pressable( - h, - { - onClick: Message.ClickedComponent({ componentId: component.id }), - isSelected, - className: itemClass(isSelected), - attributes: [h.Id(`status-page-item-${component.id}`)], - }, - [ - statusDot(h, status), - typography(h, { truncate: true }, [component.name]), - h.span([h.Class("sr-only")], [`: ${COMPONENT_STATUS_LABEL[status]}`]), - ...(component.group === null - ? [] - : [ - h.span( - [h.Class("ml-auto truncate font-mono text-2xs text-muted-foreground")], - [component.group], - ), - ]), - ], - ), - ...(canManage(model) - ? [ - hstack( - h, - { - align: "stretch", - className: - "shrink-0 opacity-60 group-hover:opacity-100 group-focus-within:opacity-100", - }, - [ - iconButton( - h, - { - label: `Move ${component.name} up`, - size: "icon-2xs", - isDisabled: position.isFirst || model.isReordering, - attributes: [ - h.OnClick( - Message.ClickedMoveComponent({ - componentId: component.id, - offset: -1, - }), - ), - ], - }, - [icon(h, "ChevronUpIcon")], - ), - iconButton( - h, - { - label: `Move ${component.name} down`, - size: "icon-2xs", - isDisabled: position.isLast || model.isReordering, - attributes: [ - h.OnClick( - Message.ClickedMoveComponent({ - componentId: component.id, - offset: 1, - }), - ), - ], - }, - [icon(h, "ChevronDownIcon")], - ), - ], - ), - ] - : []), - ], - ) -} - -const incidentItem = (h: H, model: Model, incident: V2StatusPageIncident): Html => { - const isSelected = model.panel?._tag === "Incident" && model.panel.incidentId === incident.id - return h.li( - [h.Key(incident.id)], - [ - pressable( - h, - { - onClick: Message.ClickedIncident({ incidentId: incident.id }), - isSelected, - className: itemClass(isSelected), - attributes: [h.Id(`status-page-item-${incident.id}`)], - }, - [ - icon(h, incident.kind === "incident" ? "CircleWarningIcon" : "CalendarIcon", { - size: 14, - className: isOpenIncident(incident) ? "text-severity-warn" : "text-muted-foreground", - }), - typography(h, { truncate: true }, [incident.title]), - ...(incident.published - ? [] - : [h.span([h.Class("ml-auto font-mono text-2xs text-muted-foreground")], ["Draft"])]), - ], - ), - ], - ) + const needsStatuses = Arr.some(options.parts, (part) => part === "hero" || part === "components") + if (needsStatuses && !statusReadsReady(model)) + return statusReadsFailed(model) + ? typography(h, { size: "xs", tone: "muted", as: "p" }, [ + "No preview: the page's components didn't load.", + ]) + : skeleton(h, `w-full rounded-lg ${options.className}`) + return fragmentFrame(h, { + title: options.title, + document: renderFragment( + draftSnapshot(model, page, form, "live"), + { parts: options.parts, componentId: options.componentId, nowMs: nowOf(model, page) }, + { inDashboard: true }, + ), + className: options.className, + }) } -const onThisPage = (h: H, model: Model): Html => { - const components = componentsOf(model) - const open = Arr.filter(incidentsOf(model), isOpenIncident) - const recent = Arr.filter(incidentsOf(model), (incident) => !isOpenIncident(incident)).slice(0, 5) - return vstack( +/** The page's browser tab (title, favicon, address) over its header, as the unsaved `form` has them. */ +export const tabPreview = ( + h: H, + model: Model, + page: V2StatusPage, + form: SettingsForm, + address: string | null, +): Html => + browserTabMockup( h, - { - gap: "5", - shrink: true, - as: "nav", - className: "outline-none", - attributes: [h.Id("status-page-on-this-page"), h.Tabindex(-1), h.AriaLabel("On this page")], - }, + { title: pageTitle(draftName(page, form)), iconUrl: orNull(form.faviconUrl), address }, [ - vstack(h, { gap: "1.5" }, [ - eyebrow(h, { as: "h2", className: "px-2" }, ["On this page"]), - components.length === 0 - ? h.p( - [h.Class("px-2 text-xs text-muted-foreground")], - [ - canManage(model) - ? "Nothing yet. Add a monitor and visitors see its status and uptime." - : "No monitors on this page yet.", - ], - ) - : vstack( - h, - { gap: "0.5", as: "ul", attributes: [h.AriaLabel("Components")] }, - Arr.map(components, (component, index) => - componentItem(h, model, component, { - isFirst: index === 0, - isLast: index === components.length - 1, - }), - ), - ), - ...(canManage(model) - ? [ - button( - h, - { - size: "sm", - variant: "outline", - className: "mt-1.5", - // Reopened mid-save, Add would list the monitors being added again. - isLoading: model.isAddingComponents, - attributes: [h.OnClick(Message.ClickedAddComponent())], - }, - [icon(h, "PlusIcon"), "Add monitor"], - ), - ] - : []), - ]), - vstack(h, { gap: "1.5" }, [ - eyebrow(h, { as: "h2", className: "px-2" }, ["Incidents"]), - open.length + recent.length === 0 - ? h.p( - [h.Class("px-2 text-xs text-muted-foreground")], - [ - canPostIncidents(model) - ? "Nothing posted. Post incident when something breaks." - : "Nothing posted.", - ], - ) - : vstack( - h, - { gap: "0.5", as: "ul", attributes: [h.AriaLabel("Incidents")] }, - Arr.map([...open, ...recent], (incident) => incidentItem(h, model, incident)), - ), - ]), + fragmentPreview(h, model, page, form, { + title: "The page header as visitors see it", + parts: ["header"], + className: "h-20 rounded-none border-0", + }), ], ) -} -const panelView = (h: H, model: Model, time: TimeInputs): ReadonlyArray => { - const panel = model.panel - if (panel === null) return [] - switch (panel._tag) { - case "Component": { - return Option.match( - Arr.findFirst(componentsOf(model), (row) => row.id === panel.componentId), - { onNone: () => [], onSome: (component) => [componentPanel(h, model, component)] }, - ) - } - case "Incident": { - return Option.match( - Arr.findFirst(incidentsOf(model), (row) => row.id === panel.incidentId), - { onNone: () => [], onSome: (incident) => [incidentPanel(h, model, incident, time)] }, - ) - } - case "Add": - return [addPanel(h, model)] - } -} +/** The saved page as visitors get it, with the monitors' history; components and incidents click. */ +export const canvasDocument = (model: Model, page: V2StatusPage): string => + previewDocument({ + snapshot: draftSnapshot(model, page, settingsFormOf(page), model.previewState), + nowMs: nowOf(model, page), + isSelectable: true, + publicUrl: pageUrlOf(model, page), + }) -const previewColumn = (h: H, model: Model, page: V2StatusPage): Html => +export const livePage = (h: H, model: Model, page: V2StatusPage): Html => vstack(h, { gap: "2", shrink: true, as: "section", attributes: [h.AriaLabel("Page preview")] }, [ hstack(h, { gap: "3", justify: "between", wrap: true, className: "min-h-7" }, [ typography(h, { size: "xs", tone: "muted", as: "p" }, [ @@ -379,22 +200,3 @@ const previewColumn = (h: H, model: Model, page: V2StatusPage): Html => className: "h-[640px] lg:h-[calc(100vh-16rem)] lg:min-h-[520px]", }), ]) - -export const canvas = (h: H, model: Model, page: V2StatusPage, time: TimeInputs): Html => { - const panel = panelView(h, model, time) - return h.div( - [ - h.Class( - "grid items-start gap-6 lg:grid-cols-[18rem_minmax(0,1fr)] xl:grid-cols-[22rem_minmax(0,1fr)]", - ), - ], - [ - h.div( - // Only the short list pins; a tall panel scrolls with the page to its buttons. - [h.Class(cn("min-w-0", panel.length === 0 && "lg:sticky lg:top-0"))], - panel.length === 0 ? [onThisPage(h, model)] : panel, - ), - h.div([h.Class("min-w-0")], [previewColumn(h, model, page)]), - ], - ) -} diff --git a/apps/web/src/page/status-pages/editor/view-domain.ts b/apps/web/src/page/status-pages/editor/view-domain.ts index 29a59a3fa9..356e50da33 100644 --- a/apps/web/src/page/status-pages/editor/view-domain.ts +++ b/apps/web/src/page/status-pages/editor/view-domain.ts @@ -3,7 +3,7 @@ import type { StatusPageCustomDomainRecordPurpose } from "@maple/domain/status-p import { Array as Arr, Option } from "effect" import { AsyncData } from "foldkit" import type { Html, HtmlBuilder } from "foldkit/html" -import { alert, alertDescription, alertTitle } from "@maple/views/ui/alert" +import { alert, alertAction, alertDescription, alertTitle } from "@maple/views/ui/alert" import { button } from "@maple/views/ui/button" import { confirmDialog } from "@maple/views/ui/confirm-dialog" import * as CopyButton from "@maple/views/ui/copy-button" @@ -228,6 +228,18 @@ export const customDomainSection = (h: H, model: Model, page: V2StatusPage): Htm icon(h, "CircleXmarkIcon"), alertTitle(h, ["Couldn't load the custom domain"]), alertDescription(h, [failureMessage(failure)]), + alertAction(h, [ + button( + h, + { + size: "sm", + variant: "outline", + isLoading: model.customDomain.retrying === true, + attributes: [h.OnClick(Message.ClickedRetryCustomDomain())], + }, + ["Try again"], + ), + ]), ]), }), }), diff --git a/apps/web/src/page/status-pages/editor/view-incidents.ts b/apps/web/src/page/status-pages/editor/view-incidents.ts new file mode 100644 index 0000000000..e5dba14099 --- /dev/null +++ b/apps/web/src/page/status-pages/editor/view-incidents.ts @@ -0,0 +1,256 @@ +import type { StatusPageIncidentKind } from "@maple/domain" +import type { V2StatusPageIncident } from "@maple/domain/http/v2" +import { INCIDENT_STATUS_LABEL } from "@maple/status-page" +import { toEpochMs } from "@maple/ui/lib/time-format" +import { formatDateInTimezone } from "@maple/ui/lib/timezone-format" +import { Array as Arr } from "effect" +import type { Html, HtmlBuilder } from "foldkit/html" +import { badge } from "@maple/views/ui/display" +import { emptyMessage } from "@maple/views/ui/empty" +import { panel } from "@maple/views/ui/panel" +import { pressable } from "@maple/views/ui/pressable" +import { hstack, vstack } from "@maple/views/ui/stack" +import { statusDot } from "@maple/views/ui/status-dot" +import { + clickableRowClass, + table, + tableBody, + tableCell, + tableHead, + tableHeader, + tableRow, + truncatedTableCell, +} from "@maple/views/ui/table" +import { timestamp } from "@maple/views/ui/timestamp" +import { relativeTime } from "../../kit/relative-time" +import { sectionHeading } from "../../kit/section-heading" +import { IMPACT_LABEL, IMPACT_TONE, isOpenIncident } from "../shared/derive" +import { Message } from "./message" +import type { Model } from "./model" +import { componentsOf, incidentsOf } from "./reads" +import { type TimeInputs, windowLine } from "./view-panel" + +// The Incidents and Maintenance tabs: what is open or coming, then what is over. A row opens the +// incident in the side sheet. + +type H = HtmlBuilder + +type Column = Readonly<{ + label: string + className?: string + cell: (incident: V2StatusPageIncident) => ReadonlyArray +}> + +/** "2h 40m", "24m", "<1m". */ +const durationLabel = (ms: number): string => { + const minutes = Math.round(ms / 60_000) + if (minutes < 1) return "<1m" + const hours = Math.floor(minutes / 60) + const rest = minutes % 60 + return hours === 0 ? `${rest}m` : rest === 0 ? `${hours}h` : `${hours}h ${rest}m` +} + +/** + * How long completed maintenance ran: from its first In progress update to its completion, else + * its scheduled window; `null` with neither. + */ +export const maintenanceDurationMs = (incident: V2StatusPageIncident): number | null => { + const started = Arr.reduce(incident.updates, null as number | null, (earliest, update) => + update.status !== "in_progress" + ? earliest + : Math.min(earliest ?? Infinity, toEpochMs(update.created_at)), + ) + if (started !== null && incident.resolved_at !== null) return toEpochMs(incident.resolved_at) - started + return incident.scheduled_start === null || incident.scheduled_end === null + ? null + : toEpochMs(incident.scheduled_end) - toEpochMs(incident.scheduled_start) +} + +const componentNames = (model: Model, incident: V2StatusPageIncident): string => { + const names = Arr.map( + Arr.filter(componentsOf(model), (component) => incident.component_ids.includes(component.id)), + (component) => component.name, + ) + return names.length === 0 ? "None" : Arr.join(names, ", ") +} + +/** The title cell: the button that opens the incident, with its tone square and a draft marker. */ +const titleCell = (h: H, incident: V2StatusPageIncident): Html => + truncatedTableCell(h, [ + hstack(h, { gap: "2" }, [ + ...(isOpenIncident(incident) + ? [ + statusDot(h, { + tone: incident.kind === "maintenance" ? "info" : IMPACT_TONE[incident.impact], + size: "lg", + className: "rounded-xs", + }), + ] + : []), + pressable( + h, + { + onClick: Message.ClickedIncident({ incidentId: incident.id }), + className: "min-w-0 truncate text-left text-sm font-medium", + }, + [incident.title], + ), + ...(incident.published ? [] : [badge(h, { variant: "meta" }, ["Draft"])]), + ]), + ]) + +const incidentTable = ( + h: H, + options: Readonly<{ + title: string + empty: string + rows: ReadonlyArray + first: string + columns: ReadonlyArray + }>, +): Html => + vstack(h, { gap: "3", as: "section", attributes: [h.AriaLabel(options.title)] }, [ + sectionHeading(h, { title: options.title }), + options.rows.length === 0 + ? emptyMessage(h, { dashed: true, className: "px-4 py-6" }, [options.empty]) + : panel(h, {}, [ + table(h, { ariaLabel: options.title, className: "table-fixed" }, [ + tableHeader(h, [ + tableRow(h, [ + tableHead(h, [options.first], "px-4"), + ...Arr.map(options.columns, (column) => + tableHead(h, [column.label], column.className ?? "w-40 px-3"), + ), + ]), + ]), + tableBody( + h, + Arr.map(options.rows, (incident) => + tableRow( + h, + [ + titleCell(h, incident), + ...Arr.map(options.columns, (column) => + tableCell( + h, + column.cell(incident), + "px-3 text-xs text-muted-foreground", + ), + ), + ], + clickableRowClass(false), + [ + h.Key(incident.id), + h.OnClick(Message.ClickedIncident({ incidentId: incident.id })), + ], + ), + ), + ), + ]), + ]), + ]) + +const ofKind = (model: Model, kind: StatusPageIncidentKind) => + Arr.filter(incidentsOf(model), (incident) => incident.kind === kind) + +export const incidentsTab = (h: H, model: Model, time: TimeInputs): Html => { + const incidents = ofKind(model, "incident") + const components = (incident: V2StatusPageIncident) => [componentNames(model, incident)] + return vstack(h, { gap: "8" }, [ + incidentTable(h, { + title: "Active", + empty: "No open incidents.", + first: "Incident", + rows: Arr.filter(incidents, isOpenIncident), + columns: [ + { label: "Status", cell: (incident) => [INCIDENT_STATUS_LABEL[incident.status]] }, + { label: "Components", cell: components }, + { + label: "Started", + cell: (incident) => [ + relativeTime(h, { + value: incident.started_at, + nowMs: time.nowMs, + timeZone: time.timeZone, + }), + ], + }, + ], + }), + incidentTable(h, { + title: "Resolved", + empty: "No resolved incidents yet.", + first: "Incident", + rows: Arr.filter(incidents, (incident) => !isOpenIncident(incident)), + columns: [ + { label: "Impact", cell: (incident) => [IMPACT_LABEL[incident.impact]] }, + { label: "Components", cell: components }, + { + label: "Date", + cell: (incident) => [ + timestamp(h, { + value: incident.resolved_at ?? incident.started_at, + timeZone: time.timeZone, + label: formatDateInTimezone(incident.resolved_at ?? incident.started_at, { + timeZone: time.timeZone, + withYear: false, + }), + }), + ], + }, + ], + }), + ]) +} + +export const maintenanceTab = (h: H, model: Model, time: TimeInputs): Html => { + const maintenance = ofKind(model, "maintenance") + const components = (incident: V2StatusPageIncident) => [componentNames(model, incident)] + const window = (incident: V2StatusPageIncident) => windowLine(h, incident, time.timeZone) ?? ["Not set"] + return vstack(h, { gap: "8" }, [ + incidentTable(h, { + title: "Upcoming", + empty: "No maintenance scheduled.", + first: "Maintenance", + rows: Arr.filter(maintenance, isOpenIncident), + columns: [ + { label: "Window", className: "w-72 px-3", cell: window }, + { label: "Components", cell: components }, + { + label: "Starts", + cell: (incident) => + incident.status === "in_progress" + ? ["In progress"] + : [ + relativeTime(h, { + value: incident.scheduled_start ?? incident.started_at, + nowMs: time.nowMs, + timeZone: time.timeZone, + }), + ], + }, + ], + }), + incidentTable(h, { + title: "Completed", + empty: "No completed maintenance yet.", + first: "Maintenance", + rows: Arr.filter(maintenance, (incident) => !isOpenIncident(incident)), + columns: [ + { label: "Window", className: "w-72 px-3", cell: window }, + { label: "Components", cell: components }, + { + label: "Duration", + cell: (incident) => { + const ms = maintenanceDurationMs(incident) + return [ms === null ? "–" : durationLabel(ms)] + }, + }, + ], + }), + ]) +} + +/** The open incident count on the Incidents tab. */ +export const openIncidentCount = (model: Model): number => + Arr.filter(ofKind(model, "incident"), isOpenIncident).length diff --git a/apps/web/src/page/status-pages/editor/view-json.ts b/apps/web/src/page/status-pages/editor/view-json.ts index fcefacf8d6..62620dd982 100644 --- a/apps/web/src/page/status-pages/editor/view-json.ts +++ b/apps/web/src/page/status-pages/editor/view-json.ts @@ -18,7 +18,7 @@ import { isSettingsDirty } from "./update-settings" import { typography, typographyClass } from "@maple/views/ui/typography" import { hstack, vstack } from "@maple/views/ui/stack" -// The JSON tab: the page as one document to copy, and for admins an editor that applies it. +// Settings > Advanced: the page as one document to copy, and for admins an editor that applies it. type H = HtmlBuilder diff --git a/apps/web/src/page/status-pages/editor/view-live.ts b/apps/web/src/page/status-pages/editor/view-live.ts index aaf73558e6..3863c08447 100644 --- a/apps/web/src/page/status-pages/editor/view-live.ts +++ b/apps/web/src/page/status-pages/editor/view-live.ts @@ -185,10 +185,15 @@ export const liveView = (h: H, model: Model, page: V2StatusPage): Html => description: "Agents read and change the page as one JSON document through the API or Maple's MCP server, and post incidents the same way.", actions: [ - linkButton(h, { size: "sm", variant: "outline", href: statusPageHref(page.id, "json") }, [ - icon(h, "BracketsCurlyIcon"), - "Page JSON", - ]), + linkButton( + h, + { + size: "sm", + variant: "outline", + href: statusPageHref(page.id, "settings", "advanced"), + }, + [icon(h, "BracketsCurlyIcon"), "Page JSON"], + ), linkButton( h, { diff --git a/apps/web/src/page/status-pages/editor/view-monitors.ts b/apps/web/src/page/status-pages/editor/view-monitors.ts new file mode 100644 index 0000000000..224e6728e9 --- /dev/null +++ b/apps/web/src/page/status-pages/editor/view-monitors.ts @@ -0,0 +1,391 @@ +import type { V2StatusPage, V2StatusPageComponent } from "@maple/domain/http/v2" +import { Array as Arr, Option, String as Str } from "effect" +import type { Html, HtmlBuilder } from "foldkit/html" +import { alert, alertDescription } from "@maple/views/ui/alert" +import { button } from "@maple/views/ui/button" +import * as Checkbox from "@maple/views/ui/checkbox" +import { eyebrow } from "@maple/views/ui/eyebrow" +import { icon } from "@maple/views/ui/icon" +import { iconButton } from "@maple/views/ui/icon-button" +import { label } from "@maple/views/ui/label" +import { pressable } from "@maple/views/ui/pressable" +import { grid } from "@maple/views/ui/grid" +import { hstack, vstack } from "@maple/views/ui/stack" +import { statusDot } from "@maple/views/ui/status-dot" +import { type TypographyTone, typography } from "@maple/views/ui/typography" +import type { Tone } from "@maple/ui/lib/tone" +import { cn } from "@maple/ui/lib/utils" +import { expandChevron } from "../../kit/expand-chevron" +import { adminOnlyNote, settingsSection } from "../../kit/settings-section" +import { + COMPONENT_STATUS_LABEL, + COMPONENT_STATUS_OPTIONS, + COMPONENT_STATUS_TONE, + componentStatus, + statusReason, +} from "../shared/derive" +import { selectField, textField } from "../shared/fields" +import { onYourPage } from "../shared/preview" +import { RevealOpenComponent } from "./command" +import { Message } from "./message" +import { canManage, type ComponentSave, type Model } from "./model" +import { componentsOf, incidentsOf, monitorsOf } from "./reads" +import { componentRowId, groupedOrder, moved } from "./update-components" +import { settingsOf } from "./update-settings" +import { settingsFormOf } from "../shared/form" +import { failureAlert } from "./view-panel" +import { fragmentPreview } from "./view-canvas" + +// Settings > Monitors: the page's components by group, each opening in place with its fields and +// how its row reads on the page. + +type H = HtmlBuilder + +const LABEL_TONE = { + ok: "muted", + info: "muted", + warn: "warning", + crit: "error", +} as const satisfies Partial> + +const SAVE_LABEL = { Saving: "Saving", Saved: "Saved", Failed: "Not saved" } as const satisfies Record< + ComponentSave["_tag"], + string +> + +/** The last save, when it was this component's. */ +const saveOf = (model: Model, component: V2StatusPageComponent): ComponentSave | null => + model.componentSave?.componentId === component.id ? model.componentSave : null + +const saveIndicator = (h: H, save: ComponentSave | null): Html => + typography( + h, + { + size: "xs", + mono: true, + tone: save?._tag === "Failed" ? "destructive" : "muted", + attributes: [h.AriaLive("polite")], + }, + [save === null ? "" : SAVE_LABEL[save._tag]], + ) + +/** The page's other groups as one-click picks, so a group is never retyped (or mistyped). */ +const groupSuggestions = (h: H, model: Model, isReadOnly: boolean): ReadonlyArray => { + const current = Str.trim(model.componentForm.group) + const groups = Arr.filter( + Arr.dedupe(Arr.flatMap(componentsOf(model), (row) => (row.group === null ? [] : [row.group]))), + (group) => group !== current, + ) + return isReadOnly || groups.length === 0 + ? [] + : [ + hstack( + h, + { + gap: "1.5", + wrap: true, + className: "sm:col-span-2", + attributes: [h.Role("group"), h.AriaLabel("Groups on this page")], + }, + Arr.map(groups, (group) => + button( + h, + { + size: "xs", + variant: "outline", + attributes: [ + h.Key(group), + h.OnClick(Message.PickedComponentField({ field: "group", value: group })), + ], + }, + [group], + ), + ), + ), + ] +} + +/** The open component's fields, why it shows what it shows, and its row as visitors see it. */ +const componentForm = (h: H, model: Model, page: V2StatusPage, component: V2StatusPageComponent): Html => { + const form = model.componentForm + const isReadOnly = !canManage(model) + const hasMonitor = form.monitorId !== "" + const uptimeId = "status-page-panel-uptime" + const reason = statusReason(component, monitorsOf(model), incidentsOf(model)) + const save = saveOf(model, component) + const settings = Option.getOrElse(settingsOf(model), () => settingsFormOf(page)) + return vstack( + h, + { + gap: "4", + className: "px-4 pt-1 pb-4 sm:pl-12", + attributes: [h.OnMount(RevealOpenComponent())], + }, + [ + ...(isReadOnly + ? [adminOnlyNote(h, ["Only org admins and engineers can change components."])] + : []), + grid(h, { sm: 2, gap: "4" }, [ + textField(h, { + id: "status-page-panel-name", + label: "Shown as", + value: form.name, + isDisabled: isReadOnly, + error: Str.trim(form.name) === "" ? "Add a name." : null, + onInput: (value) => Message.ChangedComponentField({ field: "name", value }), + onBlur: Message.CommittedComponent(), + }), + textField(h, { + id: "status-page-panel-group", + label: "Group", + value: form.group, + placeholder: "None", + hint: "Components with one group are listed under it.", + isDisabled: isReadOnly, + onInput: (value) => Message.ChangedComponentField({ field: "group", value }), + onBlur: Message.CommittedComponent(), + }), + ...groupSuggestions(h, model, isReadOnly), + textField(h, { + id: "status-page-panel-description", + label: "Description", + value: form.description, + placeholder: "None", + hint: "A line under the name, for what this covers.", + isDisabled: isReadOnly, + className: "sm:col-span-2", + onInput: (value) => Message.ChangedComponentField({ field: "description", value }), + onBlur: Message.CommittedComponent(), + }), + selectField(h, { + id: "status-page-panel-monitor", + label: "Driven by", + value: form.monitorId, + isDisabled: isReadOnly, + entries: [ + { value: "", label: "No monitor" }, + ...Arr.map(monitorsOf(model), (monitor) => ({ + value: monitor.id, + label: monitor.name, + })), + ], + onInput: (value) => Message.PickedComponentField({ field: "monitorId", value }), + }), + selectField(h, { + id: "status-page-panel-status", + label: "Override status", + value: form.manualStatus, + isDisabled: isReadOnly, + hint: hasMonitor + ? "Automatic follows the monitor and open incidents." + : "Automatic follows open incidents.", + entries: [ + { value: "", label: "Automatic" }, + ...Arr.map(COMPONENT_STATUS_OPTIONS, (value) => ({ + value, + label: COMPONENT_STATUS_LABEL[value], + })), + ], + onInput: (value) => Message.PickedComponentField({ field: "manualStatus", value }), + }), + ]), + ...(reason === null + ? [] + : [ + alert(h, { variant: "warn", size: "sm" }, [ + icon(h, "AlertWarningIcon"), + alertDescription(h, [reason]), + ]), + ]), + vstack(h, { gap: "1" }, [ + label( + h, + { + className: "flex font-normal text-sm sm:text-sm", + attributes: [h.Id(Checkbox.labelId(uptimeId))], + }, + [ + ...Checkbox.view(h, { + // The stored value, shown as is; it only takes effect once a monitor drives the component. + model: { isChecked: form.showUptime }, + toParentMessage: () => Message.ToggledComponentUptime(), + id: `${uptimeId}-root`, + inputId: uptimeId, + isDisabled: isReadOnly || !hasMonitor, + }), + h.span([], ["Show uptime bars"]), + ], + ), + ...(hasMonitor + ? [] + : [ + typography(h, { size: "xs", tone: "muted", as: "p" }, [ + "Uptime bars need a monitor.", + ]), + ]), + ]), + onYourPage( + h, + fragmentPreview(h, model, page, settings, { + title: `${component.name} as visitors see it`, + parts: ["components"], + componentId: component.id, + className: "h-48", + }), + ), + ...failureAlert(h, "Couldn't save the component", save?._tag === "Failed" ? save.failure : null), + hstack(h, { gap: "3", justify: "between", wrap: true }, [ + isReadOnly + ? h.span([], []) + : button( + h, + { + size: "sm", + variant: "destructive-outline", + attributes: [ + h.OnClick(Message.ClickedDeleteComponent({ componentId: component.id })), + ], + }, + ["Remove from page"], + ), + saveIndicator(h, save), + ]), + ], + ) +} + +const moveButtons = (h: H, model: Model, component: V2StatusPageComponent): Html => { + const rows = componentsOf(model) + const move = (offset: number, glyph: "ChevronUpIcon" | "ChevronDownIcon", word: string) => + iconButton( + h, + { + label: `Move ${component.name} ${word}`, + size: "icon-2xs", + isDisabled: model.isReordering || moved(rows, component.id, offset) === null, + attributes: [h.OnClick(Message.ClickedMoveComponent({ componentId: component.id, offset }))], + }, + [icon(h, glyph)], + ) + return vstack(h, { className: "shrink-0" }, [ + move(-1, "ChevronUpIcon", "up"), + move(1, "ChevronDownIcon", "down"), + ]) +} + +/** What drives the component: its monitor by name, or incidents alone. */ +const sourceLine = (model: Model, component: V2StatusPageComponent): string => + component.monitor_id === null + ? "No monitor. Follows incidents only" + : Option.match( + Arr.findFirst(monitorsOf(model), (monitor) => monitor.id === component.monitor_id), + { onNone: () => "Monitor not found", onSome: (monitor) => `Monitor: ${monitor.name}` }, + ) + +const componentRow = (h: H, model: Model, page: V2StatusPage, component: V2StatusPageComponent): Html => { + const status = componentStatus(component, monitorsOf(model), incidentsOf(model)) + const isOpen = model.panel?._tag === "Component" && model.panel.componentId === component.id + return h.li( + [h.Key(component.id), h.Class("border-t first:border-t-0")], + [ + hstack(h, { gap: "1", className: "pl-2" }, [ + ...(canManage(model) ? [moveButtons(h, model, component)] : []), + pressable( + h, + { + onClick: Message.ClickedComponent({ componentId: component.id }), + className: cn( + "flex min-w-0 flex-1 items-center gap-3 px-2 py-3 text-left hover:bg-surface-sunken active:bg-surface-sunken", + isOpen && "bg-surface-sunken", + ), + attributes: [h.Id(componentRowId(component.id)), h.AriaExpanded(isOpen)], + }, + [ + statusDot(h, { tone: COMPONENT_STATUS_TONE[status], size: "lg" }), + typography( + h, + { size: "sm", weight: "medium", truncate: true, className: "shrink-0" }, + [component.name], + ), + typography(h, { size: "xs", tone: "muted", mono: true, truncate: true }, [ + sourceLine(model, component), + ]), + typography( + h, + { + size: "xs", + tone: LABEL_TONE[COMPONENT_STATUS_TONE[status]], + className: "ml-auto shrink-0", + }, + [COMPONENT_STATUS_LABEL[status]], + ), + expandChevron(h, isOpen), + ], + ), + ]), + ...(isOpen ? [componentForm(h, model, page, component)] : []), + ], + ) +} + +/** The components under each group's head, in page order, ungrouped last. */ +const componentList = (h: H, model: Model, page: V2StatusPage): Html => { + const rows = groupedOrder(componentsOf(model)) + const groups = Arr.dedupe(Arr.map(rows, (row) => row.group)) + const hasGroups = Arr.some(groups, (group) => group !== null) + return vstack( + h, + { attributes: [h.AriaLabel("Components")] }, + Arr.map(groups, (group) => + vstack(h, { attributes: [h.Key(group ?? "")] }, [ + ...(hasGroups + ? [ + h.div( + [h.Class("bg-surface-sunken px-4 py-2")], + [eyebrow(h, {}, [group ?? "No group"])], + ), + ] + : []), + h.ul( + [h.AriaLabel(group ?? "No group")], + Arr.map( + Arr.filter(rows, (row) => row.group === group), + (component) => componentRow(h, model, page, component), + ), + ), + ]), + ), + ) +} + +export const monitorsSection = (h: H, model: Model, page: V2StatusPage): Html => + settingsSection( + h, + { + id: "status-page-settings-monitors", + title: "Monitors", + description: ["Each one is a row under System status, in this order."], + padded: false, + actions: canManage(model) + ? button( + h, + { + size: "sm", + // Reopened mid-save, Add would list the monitors being added again. + isLoading: model.isAddingComponents, + attributes: [h.OnClick(Message.ClickedAddComponent())], + }, + [icon(h, "PlusIcon"), "Add monitors"], + ) + : undefined, + }, + [ + componentsOf(model).length === 0 + ? typography(h, { size: "sm", tone: "muted", as: "p", className: "p-4" }, [ + canManage(model) + ? "Nothing yet. Add a monitor and visitors see its status and uptime." + : "No monitors on this page yet.", + ]) + : componentList(h, model, page), + ], + ) diff --git a/apps/web/src/page/status-pages/editor/view-panel.ts b/apps/web/src/page/status-pages/editor/view-panel.ts index 3b1285a72e..e1c52823b0 100644 --- a/apps/web/src/page/status-pages/editor/view-panel.ts +++ b/apps/web/src/page/status-pages/editor/view-panel.ts @@ -1,41 +1,30 @@ import type { StatusPageIncidentImpact } from "@maple/domain" -import type { V2StatusPageComponent, V2StatusPageIncident } from "@maple/domain/http/v2" +import type { V2StatusPageIncident } from "@maple/domain/http/v2" import { formatTimestampInTimezone } from "@maple/ui/lib/timezone-format" -import type { Html, HtmlBuilder } from "foldkit/html" +import type { ChildAttribute, Html, HtmlBuilder } from "foldkit/html" import { failureMessage, type LoadFailure } from "@maple/views/data/load-failure" import { alert, alertDescription, alertTitle } from "@maple/views/ui/alert" import { button } from "@maple/views/ui/button" -import * as Checkbox from "@maple/views/ui/checkbox" import { badge } from "@maple/views/ui/display" import { eyebrow } from "@maple/views/ui/eyebrow" import { icon } from "@maple/views/ui/icon" import { timestamp } from "@maple/views/ui/timestamp" -import { heading } from "@maple/views/ui/heading" -import { label } from "@maple/views/ui/label" import { INCIDENT_STATUS_LABEL, renderUpdateBody } from "@maple/status-page" import { cn } from "@maple/ui/lib/utils" import { relativeTime } from "../../kit/relative-time" -import { - COMPONENT_STATUS_LABEL, - COMPONENT_STATUS_OPTIONS, - componentStatus, - IMPACT_LABEL, - IMPACT_TONE, - isOpenIncident, -} from "../shared/derive" -import { selectField, textField } from "../shared/fields" +import { IMPACT_LABEL, IMPACT_TONE, isOpenIncident } from "../shared/derive" import { checkedRows, hasRowIssues } from "../shared/picker" import { pickerView } from "../shared/picker-view" import { FocusNewRow } from "./command" import { Message } from "./message" -import { canManage, canPostIncidents, type Model } from "./model" -import { componentsOf, incidentsOf, monitorsOf } from "./reads" -import { ADD_PICKER_ID, PANEL_TITLE_ID } from "./update-components" -import { typography, typographyClass } from "@maple/views/ui/typography" +import { canPostIncidents, type Model } from "./model" +import { componentsOf, monitorsOf } from "./reads" +import { ADD_PICKER_ID } from "./update-components" +import { typography } from "@maple/views/ui/typography" import { hstack, vstack, vstackClass } from "@maple/views/ui/stack" -import { Array as Arr, String as Str } from "effect" +import { Array as Arr } from "effect" -// The side panel: one component (saved as you go), one incident, or Add component. +// The side sheet: one incident or maintenance with its actions and updates, or Add monitors. type H = HtmlBuilder @@ -56,48 +45,6 @@ export const updateBody = (h: H, body: string, className?: string): Html => [], ) -const frame = ( - h: H, - options: Readonly<{ kind: string; title: string; status?: Html }>, - children: ReadonlyArray, -): Html => - h.aside( - [ - h.AriaLabelledBy(PANEL_TITLE_ID), - h.Class("flex min-w-0 flex-col gap-5 rounded-lg border bg-background p-4"), - ], - [ - vstack(h, { gap: "3", align: "start" }, [ - button( - h, - { - size: "xs", - variant: "ghost", - className: "-ml-2", - attributes: [h.OnClick(Message.ClickedClosePanel())], - }, - [icon(h, "ArrowLeftIcon"), "On this page"], - ), - vstack(h, { gap: "1", shrink: true, className: "max-w-full" }, [ - eyebrow(h, {}, [options.kind]), - heading( - h, - { - level: 2, - variant: "subsection", - id: PANEL_TITLE_ID, - className: "truncate outline-none", - attributes: [h.Tabindex(-1)], - }, - [options.title], - ), - ...(options.status === undefined ? [] : [options.status]), - ]), - ]), - ...children, - ], - ) - export const failureAlert = (h: H, title: string, failure: LoadFailure | null): ReadonlyArray => failure === null ? [] @@ -109,200 +56,6 @@ export const failureAlert = (h: H, title: string, failure: LoadFailure | null): ]), ] -// COMPONENT - -const SAVE_LABEL = { idle: "", saving: "Saving", saved: "Saved", failed: "Not saved" } as const - -const saveIndicator = (h: H, model: Model): Html => - h.span( - [ - h.AriaLive("polite"), - h.Class( - model.componentSave === "failed" - ? "font-mono text-xs text-destructive-foreground" - : typographyClass({ size: "xs", tone: "muted", mono: true }), - ), - ], - [SAVE_LABEL[model.componentSave]], - ) - -/** The page's other groups as one-click picks, so a group is never retyped (or mistyped). */ -const groupSuggestions = (h: H, model: Model, isReadOnly: boolean): ReadonlyArray => { - const current = Str.trim(model.componentForm.group) - const groups = Arr.filter( - Arr.dedupe(Arr.flatMap(componentsOf(model), (row) => (row.group === null ? [] : [row.group]))), - (group) => group !== current, - ) - return isReadOnly || groups.length === 0 - ? [] - : [ - hstack( - h, - { - gap: "1.5", - wrap: true, - className: "-mt-2", - attributes: [h.Role("group"), h.AriaLabel("Groups on this page")], - }, - Arr.map(groups, (group) => - button( - h, - { - size: "xs", - variant: "outline", - attributes: [ - h.Key(group), - h.OnClick(Message.PickedComponentField({ field: "group", value: group })), - ], - }, - [group], - ), - ), - ), - ] -} - -export const componentPanel = (h: H, model: Model, component: V2StatusPageComponent): Html => { - const form = model.componentForm - const isReadOnly = !canManage(model) - const status = componentStatus(component, monitorsOf(model), incidentsOf(model)) - const hasMonitor = form.monitorId !== "" - const uptimeId = "status-page-panel-uptime" - return frame( - h, - { - kind: "Component", - title: Str.trim(form.name) === "" ? component.name : Str.trim(form.name), - status: hstack( - h, - { gap: "2", align: "center", className: typographyClass({ size: "xs", tone: "muted" }) }, - [`Visitors see ${COMPONENT_STATUS_LABEL[status]}`, saveIndicator(h, model)], - ), - }, - [ - ...(isReadOnly - ? [ - typography(h, { size: "xs", tone: "muted", as: "p" }, [ - "Only org admins and engineers can change components.", - ]), - ] - : []), - vstack(h, { gap: "4" }, [ - textField(h, { - id: "status-page-panel-name", - label: "Shown as", - value: form.name, - isDisabled: isReadOnly, - error: Str.trim(form.name) === "" ? "Add a name." : null, - onInput: (value) => Message.ChangedComponentField({ field: "name", value }), - onBlur: Message.CommittedComponent(), - }), - textField(h, { - id: "status-page-panel-group", - label: "Group", - value: form.group, - placeholder: "None", - hint: "Components with one group are listed under it.", - isDisabled: isReadOnly, - onInput: (value) => Message.ChangedComponentField({ field: "group", value }), - onBlur: Message.CommittedComponent(), - }), - ...groupSuggestions(h, model, isReadOnly), - textField(h, { - id: "status-page-panel-description", - label: "Description", - value: form.description, - placeholder: "None", - hint: "A line under the name, for what this covers.", - isDisabled: isReadOnly, - onInput: (value) => Message.ChangedComponentField({ field: "description", value }), - onBlur: Message.CommittedComponent(), - }), - selectField(h, { - id: "status-page-panel-monitor", - label: "Driven by", - value: form.monitorId, - isDisabled: isReadOnly, - entries: [ - { value: "", label: "No monitor" }, - ...Arr.map(monitorsOf(model), (monitor) => ({ - value: monitor.id, - label: monitor.name, - })), - ], - onInput: (value) => Message.PickedComponentField({ field: "monitorId", value }), - }), - selectField(h, { - id: "status-page-panel-status", - label: "Override status", - value: form.manualStatus, - isDisabled: isReadOnly, - hint: hasMonitor - ? "Automatic follows the monitor and open incidents." - : "Automatic follows open incidents.", - entries: [ - { value: "", label: "Automatic" }, - ...Arr.map(COMPONENT_STATUS_OPTIONS, (value) => ({ - value, - label: COMPONENT_STATUS_LABEL[value], - })), - ], - onInput: (value) => Message.PickedComponentField({ field: "manualStatus", value }), - }), - label( - h, - { - className: "flex font-normal text-sm sm:text-sm", - attributes: [h.Id(Checkbox.labelId(uptimeId))], - }, - [ - ...Checkbox.view(h, { - // The stored value, shown as is; it only takes effect once a monitor drives the component. - model: { isChecked: form.showUptime }, - toParentMessage: () => Message.ToggledComponentUptime(), - id: `${uptimeId}-root`, - inputId: uptimeId, - isDisabled: isReadOnly || !hasMonitor, - }), - h.span([], ["Show uptime bars"]), - ], - ), - ...(hasMonitor - ? [] - : [ - h.p( - [h.Class("-mt-2 text-xs text-muted-foreground")], - ["Uptime bars need a monitor."], - ), - ]), - ]), - ...failureAlert(h, "Couldn't save the component", model.componentFailure), - ...(isReadOnly - ? [] - : [ - h.div( - [h.Class("border-t pt-4")], - [ - button( - h, - { - size: "sm", - variant: "destructive-outline", - attributes: [ - h.OnClick( - Message.ClickedDeleteComponent({ componentId: component.id }), - ), - ], - }, - ["Remove from page"], - ), - ], - ), - ]), - ], - ) -} - // INCIDENT /** @@ -398,35 +151,42 @@ const incidentActions = (h: H, model: Model, incident: V2StatusPageIncident): Ht ]) } -export const incidentPanel = (h: H, model: Model, incident: V2StatusPageIncident, time: TimeInputs): Html => { +/** The sheet's heading line: status, impact, and whether visitors can see it yet. */ +const incidentBadges = (h: H, incident: V2StatusPageIncident): Html => + hstack(h, { gap: "1.5", wrap: true }, [ + badge(h, { variant: isOpenIncident(incident) ? "info" : "muted" }, [ + INCIDENT_STATUS_LABEL[incident.status], + ]), + ...(incident.kind === "incident" + ? [ + badge(h, { variant: impactBadgeVariant(incident.impact) }, [ + `${IMPACT_LABEL[incident.impact]} impact`, + ]), + ] + : []), + ...(incident.published ? [] : [badge(h, { variant: "meta" }, ["Draft, not public"])]), + ]) + +/** What the sheet shows for an incident or maintenance: where it stands, what to do next, its updates. */ +export const incidentSheetBody = ( + h: H, + model: Model, + incident: V2StatusPageIncident, + time: TimeInputs, +): ReadonlyArray => { const names = Arr.map( Arr.filter(componentsOf(model), (component) => incident.component_ids.includes(component.id)), (component) => component.name, ) const window = windowLine(h, incident, time.timeZone) - return frame( - h, - { - kind: incident.kind === "incident" ? "Incident" : "Maintenance", - title: incident.title, - status: hstack(h, { gap: "1.5", wrap: true }, [ - badge(h, { variant: isOpenIncident(incident) ? "info" : "muted" }, [ - INCIDENT_STATUS_LABEL[incident.status], + return [ + vstack(h, { gap: "5" }, [ + vstack(h, { gap: "2" }, [ + incidentBadges(h, incident), + typography(h, { size: "xs", tone: "muted", as: "p" }, [ + names.length === 0 ? "No components named" : Arr.join(names, ", "), + ...(window === null ? [] : [" · ", ...window]), ]), - ...(incident.kind === "incident" - ? [ - badge(h, { variant: impactBadgeVariant(incident.impact) }, [ - `${IMPACT_LABEL[incident.impact]} impact`, - ]), - ] - : []), - ...(incident.published ? [] : [badge(h, { variant: "meta" }, ["Draft, not public"])]), - ]), - }, - [ - typography(h, { size: "xs", tone: "muted", as: "p" }, [ - names.length === 0 ? "No components named" : Arr.join(names, ", "), - ...(window === null ? [] : [" · ", ...window]), ]), ...(canPostIncidents(model) ? [incidentActions(h, model, incident)] : []), vstack(h, { gap: "2", as: "section", attributes: [h.AriaLabel("Updates")] }, [ @@ -461,8 +221,8 @@ export const incidentPanel = (h: H, model: Model, incident: V2StatusPageIncident ), ]), ...(canPostIncidents(model) ? [deleteIncidentAction(h, incident)] : []), - ], - ) + ]), + ] } const deleteIncidentAction = (h: H, incident: V2StatusPageIncident): Html => @@ -483,31 +243,36 @@ const deleteIncidentAction = (h: H, incident: V2StatusPageIncident): Html => // ADD -export const addPanel = (h: H, model: Model): Html => { +/** Add monitors: the builder's checklist of the monitors not on the page yet. */ +export const addSheetBody = (h: H, model: Model): ReadonlyArray => [ + pickerView(h, { + picker: model.addPicker, + monitors: monitorsOf(model), + toMessage: (message) => Message.GotAddPickerMessage({ message }), + idPrefix: ADD_PICKER_ID, + // Locked while a URL is being monitored: its completion submits what is ticked. + isDisabled: model.isAddingComponents || model.addPicker.isCreatingMonitor, + focusOnMount: h.OnMount(FocusNewRow()), + isOrderable: false, + }), +] + +export const addSheetFooter = ( + h: H, + model: Model, + close: ReadonlyArray, +): ReadonlyArray => { const count = checkedRows(model.addPicker).length - return frame(h, { kind: "Add", title: "Add monitors" }, [ - pickerView(h, { - picker: model.addPicker, - monitors: monitorsOf(model), - toMessage: (message) => Message.GotAddPickerMessage({ message }), - idPrefix: ADD_PICKER_ID, - // Locked while a URL is being monitored: its completion submits what is ticked. - isDisabled: model.isAddingComponents || model.addPicker.isCreatingMonitor, - focusOnMount: h.OnMount(FocusNewRow()), - isOrderable: false, - }), - hstack(h, { align: "stretch", justify: "end", className: "border-t pt-4" }, [ - button( - h, - { - size: "sm", - isLoading: model.isAddingComponents, - isDisabled: - count === 0 || hasRowIssues(model.addPicker) || model.addPicker.isCreatingMonitor, - attributes: [h.OnClick(Message.ClickedSubmitAdd())], - }, - [count <= 1 ? "Add component" : `Add ${count} components`], - ), - ]), - ]) + return [ + button(h, { variant: "outline", attributes: close }, ["Cancel"]), + button( + h, + { + isLoading: model.isAddingComponents, + isDisabled: count === 0 || hasRowIssues(model.addPicker) || model.addPicker.isCreatingMonitor, + attributes: [h.OnClick(Message.ClickedSubmitAdd())], + }, + [count <= 1 ? "Add component" : `Add ${count} components`], + ), + ] } diff --git a/apps/web/src/page/status-pages/editor/view-settings.ts b/apps/web/src/page/status-pages/editor/view-settings.ts index a165787ef7..ba771ea31c 100644 --- a/apps/web/src/page/status-pages/editor/view-settings.ts +++ b/apps/web/src/page/status-pages/editor/view-settings.ts @@ -1,86 +1,126 @@ import type { V2StatusPage } from "@maple/domain/http/v2" -import { Option } from "effect" +import { Array as Arr, Option } from "effect" +import { AsyncData } from "foldkit" import type { Html, HtmlBuilder } from "foldkit/html" import { alert, alertDescription, alertTitle } from "@maple/views/ui/alert" import { button } from "@maple/views/ui/button" import { confirmDialog } from "@maple/views/ui/confirm-dialog" import { copyableField } from "@maple/views/ui/copyable-field" +import { errorState } from "@maple/views/ui/error-state" import { icon } from "@maple/views/ui/icon" +import { navRailRow } from "@maple/views/ui/nav-rail-row" +import { searchResultMockup } from "@maple/views/ui/page-mockup" +import { pageTitle } from "@maple/status-page" +import { skeleton } from "@maple/views/ui/skeleton" import { failureMessage } from "@maple/views/data/load-failure" import { dangerRow, dangerZone } from "../../kit/danger-zone" import { saveBar } from "../../kit/save-bar" import { adminOnlyNote, settingsSection, settingsSections } from "../../kit/settings-section" import { switchRow } from "../../kit/switch-row" -import { publicAddress } from "../shared/commands" +import { + canonicalUrl, + publicAddress, + SETTINGS_SECTIONS, + type SettingsSection, + statusPageHref, +} from "../shared/commands" import { selectField, textareaField, textField } from "../shared/fields" import { + hasAppearanceIssues, hasPageFieldIssues, hasSettingsIssues, - hasAppearanceIssues, + orNull, type SettingsForm, settingsFormOf, settingsIssues, } from "../shared/form" +import { onYourPage } from "../shared/preview" import { accessSection } from "./view-access" -import { appearanceSection, brandingSection, previewPanel } from "./view-appearance" +import { appearanceSection, brandingSection } from "./view-appearance" import { customDomainSection } from "./view-domain" -import { pageUrlOf } from "./update-domain" +import { jsonTab } from "./view-json" +import { monitorsSection } from "./view-monitors" +import { draftName, fragmentPreview, tabPreview } from "./view-canvas" +import { activeCustomDomain, pageUrlOf } from "./update-domain" import { Message } from "./message" import { canBreakGlass, canManage, type Model } from "./model" import { isSettingsDirty, settingsOf } from "./update-settings" import { typography, typographyClass } from "@maple/views/ui/typography" +import { grid } from "@maple/views/ui/grid" import { hstack, vstack } from "@maple/views/ui/stack" -// The Settings tab: the page's fields, who can view it, the break-glass token and deleting the page. +// The Settings tab: a menu of sections beside the open one. Basic settings and Appearance edit one +// form with one save bar; each setting shows how it reads on the page. type H = HtmlBuilder +const SECTION_LABEL = { + basic: "Basic settings", + monitors: "Monitors", + appearance: "Appearance", + access: "Access", + advanced: "Advanced", +} as const satisfies Record + const AUTO_INCIDENT_ENTRIES = [ { value: "off", label: "Off" }, { value: "draft", label: "Open a draft for me to publish" }, { value: "publish", label: "Open and publish an incident" }, ] -const pageSection = (h: H, model: Model, form: SettingsForm): Html => { +/** The address the form's slug gives the page, for the previews; the custom domain wins once active. */ +const draftAddress = (model: Model, form: SettingsForm): string => + canonicalUrl(model.publicBaseUrl, form.slug, activeCustomDomain(model)) ?? publicAddress(form.slug) + +const pageSection = (h: H, model: Model, page: V2StatusPage, form: SettingsForm): Html => { const issues = settingsIssues(form) const isReadOnly = !canManage(model) + const address = draftAddress(model, form) return settingsSection( h, { id: "status-page-settings-page", title: "Page", - description: ["What visitors see at the top of the page."], + description: ["How the page introduces itself to visitors."], }, [ - h.div( - [h.Class("grid gap-4 sm:grid-cols-2")], - [ - textField(h, { - id: "status-page-name", - label: "Name", - value: form.name, - isDisabled: isReadOnly, - error: issues.name, - onInput: (value) => Message.ChangedSetting({ field: "name", value }), - }), - textField(h, { - id: "status-page-slug", - label: "Address", - value: form.slug, - isMono: true, - isDisabled: isReadOnly, - error: issues.slug, - hint: `${publicAddress(form.slug)}. Changing it moves the page; the old address stops working.`, - onInput: (value) => Message.ChangedSetting({ field: "slug", value }), - }), - textareaField(h, { - id: "status-page-description", - label: "Description", - value: form.description, - isDisabled: isReadOnly, - className: "sm:col-span-2", - onInput: (value) => Message.ChangedSetting({ field: "description", value }), + vstack(h, { gap: "4" }, [ + textField(h, { + id: "status-page-name", + label: "Name", + value: form.name, + isDisabled: isReadOnly, + error: issues.name, + onInput: (value) => Message.ChangedSetting({ field: "name", value }), + }), + textField(h, { + id: "status-page-slug", + label: "Address", + value: form.slug, + isMono: true, + isDisabled: isReadOnly, + error: issues.slug, + hint: `${publicAddress(form.slug)}. Changing it moves the page; the old address stops working.`, + onInput: (value) => Message.ChangedSetting({ field: "slug", value }), + }), + onYourPage(h, tabPreview(h, model, page, form, address)), + textareaField(h, { + id: "status-page-description", + label: "Description", + value: form.description, + isDisabled: isReadOnly, + onInput: (value) => Message.ChangedSetting({ field: "description", value }), + }), + onYourPage( + h, + searchResultMockup(h, { + address, + title: pageTitle(draftName(page, form)), + description: orNull(form.description), }), + "In search results and link previews", + ), + grid(h, { sm: 2, gap: "4" }, [ textField(h, { id: "status-page-website", label: "Website URL", @@ -88,8 +128,19 @@ const pageSection = (h: H, model: Model, form: SettingsForm): Html => { placeholder: "https://acme.example", isDisabled: isReadOnly, error: issues.websiteUrl, + hint: "Linked in the page header as Visit website.", onInput: (value) => Message.ChangedSetting({ field: "websiteUrl", value }), }), + textField(h, { + id: "status-page-support", + label: "Support URL", + value: form.supportUrl, + placeholder: "https://acme.example/support", + isDisabled: isReadOnly, + error: issues.supportUrl, + hint: "Linked in the page header as Contact support.", + onInput: (value) => Message.ChangedSetting({ field: "supportUrl", value }), + }), textField(h, { id: "status-page-privacy", label: "Privacy policy URL", @@ -110,52 +161,41 @@ const pageSection = (h: H, model: Model, form: SettingsForm): Html => { hint: "Linked in the page footer.", onInput: (value) => Message.ChangedSetting({ field: "termsUrl", value }), }), - textField(h, { - id: "status-page-support", - label: "Support URL", - value: form.supportUrl, - placeholder: "https://acme.example/support", - isDisabled: isReadOnly, - error: issues.supportUrl, - hint: "Linked in the page header as Contact support.", - onInput: (value) => Message.ChangedSetting({ field: "supportUrl", value }), - }), - ], - ), + ]), + ]), ], ) } -const behaviourSection = (h: H, model: Model, form: SettingsForm): Html => - settingsSection(h, { id: "status-page-settings-behaviour", title: "Behaviour", padded: false }, [ - h.div( - [h.Class("divide-y")], - [ - switchRow(h, { - id: "status-page-powered-by", - label: "Show powered by Maple", - description: "A small credit in the page footer.", - isChecked: form.showPoweredBy, - isDisabled: !canManage(model), - onToggle: Message.ToggledPoweredBy(), - className: "p-4", +const behaviourSection = (h: H, model: Model, page: V2StatusPage, form: SettingsForm): Html => + settingsSection(h, { id: "status-page-settings-behaviour", title: "Behaviour" }, [ + vstack(h, { gap: "4" }, [ + selectField(h, { + id: "status-page-auto-incidents", + label: "When a linked monitor goes down", + value: form.autoIncidents, + entries: AUTO_INCIDENT_ENTRIES, + isDisabled: !canManage(model), + hint: "A draft waits for you under Incidents; a published one shows on the page at once.", + onInput: (value) => Message.ChangedSetting({ field: "autoIncidents", value }), + }), + switchRow(h, { + id: "status-page-powered-by", + label: "Show powered by Maple", + description: "A small credit in the page footer.", + isChecked: form.showPoweredBy, + isDisabled: !canManage(model), + onToggle: Message.ToggledPoweredBy(), + }), + onYourPage( + h, + fragmentPreview(h, model, page, form, { + title: "The page footer as visitors see it", + parts: ["footer"], + className: "h-32", }), - h.div( - [h.Class("p-4")], - [ - selectField(h, { - id: "status-page-auto-incidents", - label: "When a linked monitor goes down", - value: form.autoIncidents, - entries: AUTO_INCIDENT_ENTRIES, - isDisabled: !canManage(model), - hint: "A draft waits for you under Incidents in the editor's On this page list; a published one shows on the page at once.", - onInput: (value) => Message.ChangedSetting({ field: "autoIncidents", value }), - }), - ], - ), - ], - ), + ), + ]), ]) export const revealedToken = (h: H, model: Model): ReadonlyArray => @@ -257,6 +297,23 @@ const breakGlassSection = (h: H, model: Model, page: V2StatusPage): Html => { ) } +/** The page as one JSON document, with its read's loading and failure states. */ +const jsonSection = (h: H, model: Model): Html => { + const failure = AsyncData.getError(model.config.data) + return settingsSection(h, { id: "status-page-settings-json", title: "Page JSON", framed: false }, [ + Option.isSome(failure) + ? errorState(h, { + failure: failure.value, + title: "Couldn't load the config", + onRetry: Message.ClickedRetry(), + className: "py-12", + }) + : AsyncData.hasData(model.config.data) + ? jsonTab(h, model) + : skeleton(h, "h-48 w-full"), + ]) +} + const deleteSection = (h: H): Html => dangerZone(h, { id: "status-page-settings-danger" }, [ dangerRow(h, { @@ -272,79 +329,110 @@ const deleteSection = (h: H): Html => }), ]) -/** - * Settings and Appearance edit one form: each shows its sections beside the preview, one save bar. - * A problem on the other tab still blocks the save, so the bar names that tab. - */ -const formView = ( +/** Basic settings and Appearance share one form: a problem in the other still blocks the save. */ +const saveContext = (model: Model, form: SettingsForm, section: SettingsSection): string | undefined => { + if (hasSettingsIssues(form)) { + const isHere = section === "appearance" ? hasAppearanceIssues(form) : hasPageFieldIssues(form) + return isHere + ? "Fix the fields marked above." + : `Fix the fields marked in ${hasPageFieldIssues(form) ? "Basic settings" : "Appearance"}.` + } + return model.isApplyingJson ? "Saving waits for the JSON apply to finish." : undefined +} + +const sectionBody = ( h: H, model: Model, page: V2StatusPage, - tab: "settings" | "appearance", - sections: (form: SettingsForm) => ReadonlyArray, -): Html => { + form: SettingsForm, + section: SettingsSection, +): ReadonlyArray => { + switch (section) { + case "basic": + return [ + pageSection(h, model, page, form), + customDomainSection(h, model, page), + behaviourSection(h, model, page, form), + ] + case "monitors": + return [monitorsSection(h, model, page)] + case "appearance": + return [brandingSection(h, model, page, form), appearanceSection(h, model, page, form)] + case "access": + return [accessSection(h, model, page, form)] + case "advanced": + return [ + // Break-glass posts at the public address, which an internal page does not answer on. + ...(page.visibility === "internal" ? [] : [breakGlassSection(h, model, page)]), + jsonSection(h, model), + ...(canManage(model) ? [deleteSection(h)] : []), + ] + } +} + +const sectionMenu = (h: H, page: V2StatusPage, section: SettingsSection): Html => + h.nav( + [h.AriaLabel("Settings sections"), h.Class("md:sticky md:top-6")], + [ + vstack( + h, + { gap: "0.5" }, + Arr.map(SETTINGS_SECTIONS, (entry) => + navRailRow( + h, + { + isActive: entry === section, + href: statusPageHref(page.id, "settings", entry), + attributes: [h.Key(entry)], + }, + [SECTION_LABEL[entry]], + ), + ), + ), + ], + ) + +export const settingsView = (h: H, model: Model, page: V2StatusPage, section: SettingsSection): Html => { const form = Option.getOrElse(settingsOf(model), () => settingsFormOf(page)) - const hasIssues = hasSettingsIssues(form) - const isHere = tab === "settings" ? hasPageFieldIssues(form) : hasAppearanceIssues(form) - return vstack(h, { className: "max-w-4xl xl:max-w-7xl" }, [ - h.div( - [h.Class("grid gap-10 xl:grid-cols-[minmax(0,1fr)_minmax(0,30rem)] xl:items-start")], - [ + return h.div( + [h.Class("grid items-start gap-6 md:grid-cols-[12rem_minmax(0,1fr)] lg:gap-10")], + [ + sectionMenu(h, page, section), + vstack(h, { className: "min-w-0 max-w-3xl" }, [ settingsSections(h, [ - ...(canManage(model) + ...(canManage(model) || section === "access" ? [] : [ adminOnlyNote(h, [ "Only org admins and engineers can change a status page. You can still post incident updates.", ]), ]), - ...sections(form), + ...sectionBody(h, model, page, form, section), ]), - previewPanel(h, model, page, form), - ], - ), - ...(model.settingsFailure === null - ? [] - : [ - alert(h, { variant: "crit", size: "sm", className: "mt-6" }, [ - icon(h, "CircleXmarkIcon"), - alertTitle(h, ["Couldn't save the settings"]), - alertDescription(h, [failureMessage(model.settingsFailure)]), - ]), - ]), - ...saveBar(h, { - isDirty: isSettingsDirty(model), - isPending: model.isSavingSettings, - context: hasIssues - ? isHere - ? "Fix the fields marked above." - : `Fix the fields marked on the ${tab === "settings" ? "Appearance" : "Settings"} tab.` - : model.isApplyingJson - ? "Saving waits for the JSON apply to finish." - : undefined, - onDiscard: Message.ClickedDiscardSettings(), - onSave: Message.ClickedSaveSettings(), - isSaveDisabled: hasIssues || model.isApplyingJson, - }), - ]) + ...(model.settingsFailure === null + ? [] + : [ + alert(h, { variant: "crit", size: "sm", className: "mt-6" }, [ + icon(h, "CircleXmarkIcon"), + alertTitle(h, ["Couldn't save the settings"]), + alertDescription(h, [failureMessage(model.settingsFailure)]), + ]), + ]), + ...saveBar(h, { + isDirty: isSettingsDirty(model), + isPending: model.isSavingSettings, + context: saveContext(model, form, section), + onDiscard: Message.ClickedDiscardSettings(), + onSave: Message.ClickedSaveSettings(), + isSaveDisabled: hasSettingsIssues(form) || model.isApplyingJson, + }), + ]), + ], + ) } -export const settingsView = (h: H, model: Model, page: V2StatusPage): Html => - formView(h, model, page, "settings", (form) => [ - pageSection(h, model, form), - behaviourSection(h, model, form), - accessSection(h, model, page), - customDomainSection(h, model, page), - // Break-glass posts at the public address, which an internal page does not answer on. - ...(page.visibility === "internal" ? [] : [breakGlassSection(h, model, page)]), - ...(canManage(model) ? [deleteSection(h)] : []), - ]) - -export const appearanceView = (h: H, model: Model, page: V2StatusPage): Html => - formView(h, model, page, "appearance", (form) => [ - brandingSection(h, model, form), - appearanceSection(h, model, form), - ]) +/** The section's name, for the breadcrumb. */ +export const sectionLabel = (section: SettingsSection): string => SECTION_LABEL[section] export const breakGlassDialog = (h: H, model: Model): Html => confirmDialog(h, { diff --git a/apps/web/src/page/status-pages/editor/view.ts b/apps/web/src/page/status-pages/editor/view.ts index 3d63c1a336..30f1b28a2d 100644 --- a/apps/web/src/page/status-pages/editor/view.ts +++ b/apps/web/src/page/status-pages/editor/view.ts @@ -19,7 +19,9 @@ import { dashboardPage } from "../../kit/dashboard-page" import { detailActions, detailTitle, detailTitleSkeleton } from "../../kit/detail-header" import { relativeTime } from "../../kit/relative-time" import { linkTabStrip } from "../../kit/underline-tabs" -import { type EditorView, statusPageHref, statusPagesHref, statusPageViewHref } from "../shared/commands" +import type * as Dialog from "@maple/views/ui/dialog" +import { sidePanelSheet } from "@maple/views/ui/sheet" +import { statusPageHref, statusPagesHref, statusPageViewHref } from "../shared/commands" import { statusPageNotFound } from "../shared/not-found" import { pageUrlOf } from "./update-domain" import { @@ -31,18 +33,19 @@ import { import { Message } from "./message" import { canBreakGlass, canManage, canPostIncidents, type Model } from "./model" import { componentsOf, incidentsOf, monitorsOf, pageOf, statusReadsReady } from "./reads" -import { PAGE_MENU_ID, resolveView } from "./update" -import { canvas } from "./view-canvas" -import { jsonTab } from "./view-json" +import { type EditorTab, PAGE_MENU_ID, resolveView } from "./update" +import { livePage } from "./view-canvas" +import { incidentsTab, maintenanceTab, openIncidentCount } from "./view-incidents" import { addressLine, liveView } from "./view-live" -import { appearanceView, breakGlassDialog, deletePageDialog, settingsView } from "./view-settings" +import { addSheetBody, addSheetFooter, incidentSheetBody, type TimeInputs } from "./view-panel" +import { breakGlassDialog, deletePageDialog, sectionLabel, settingsView } from "./view-settings" import { removeCustomDomainDialog } from "./view-domain" import { incidentDialogs } from "./view-incident-dialogs" import { typography, typographyClass } from "@maple/views/ui/typography" import { hstack, vstack } from "@maple/views/ui/stack" -// `/status-pages/$pageId`: the header and tabs, then the page as the editor, its Appearance, its -// Settings, its JSON, or the screen right after it went live. +// `/status-pages/$pageId`: the header and tabs, then the live page, its incidents, its maintenance, +// its settings, or the screen right after it went live. type H = HtmlBuilder @@ -136,27 +139,36 @@ const openPageButton = (h: H, model: Model, page: V2StatusPage): Html => { ) } -/** A draft's next step is publishing it, so Publish leads and Post incident steps back. */ +/** Incidents and Maintenance lead with posting one; the other tabs with the page itself. */ const headerActions = (h: H, model: Model, page: V2StatusPage): Html => { - const canPublish = canManage(model) && page.draft - // A posted incident opens in the Page tab's panel, so Post incident lives on that tab. - const isPageView = resolveView(model.search.view) === "page" + const tab = resolveView(model.search).tab + if (tab === "incidents" || tab === "maintenance") + return detailActions( + h, + canPostIncidents(model) + ? [ + button( + h, + { + size: "sm", + attributes: [ + h.OnClick( + Message.ClickedNewIncident({ + kind: tab === "incidents" ? "incident" : "maintenance", + }), + ), + ], + }, + tab === "incidents" + ? [icon(h, "PlusIcon"), "Declare incident"] + : [icon(h, "CalendarIcon"), "Schedule maintenance"], + ), + ] + : [], + ) const entries = menuEntries(model, page) return detailActions(h, [ - ...(isPageView && canPostIncidents(model) - ? [ - button( - h, - { - size: "sm", - variant: canPublish ? "outline" : "default", - attributes: [h.OnClick(Message.ClickedNewIncident({ kind: "incident" }))], - }, - [icon(h, "PlusIcon"), "Post incident"], - ), - ] - : []), - ...(canPublish ? [publishButton(h, model)] : []), + ...(canManage(model) && page.draft ? [publishButton(h, model)] : []), openPageButton(h, model, page), ...(entries.length === 0 ? [] @@ -173,39 +185,39 @@ const headerActions = (h: H, model: Model, page: V2StatusPage): Html => { } const TAB_LABELS = { - page: "Page", - appearance: "Appearance", + page: "Live page", + incidents: "Incidents", + maintenance: "Maintenance", settings: "Settings", - json: "JSON", -} as const satisfies Record<"page" | Exclude, string> +} as const satisfies Record, string> -const TABS = Arr.map(["page", "appearance", "settings", "json"] as const, (view) => ({ - view, - label: TAB_LABELS[view], -})) +const TABS = ["page", "incidents", "maintenance", "settings"] as const const tabs = (h: H, model: Model, page: V2StatusPage): Html => { - const current = resolveView(model.search.view) + const current = resolveView(model.search).tab + const open = openIncidentCount(model) return linkTabStrip( h, "Status page views", Arr.map(TABS, (tab) => ({ - key: tab.view, - href: statusPageHref(page.id, tab.view === "page" ? undefined : tab.view), - label: tab.label, - isCurrent: current === tab.view, - isRouteActive: current === tab.view, + key: tab, + href: statusPageHref(page.id, tab === "page" ? undefined : tab), + label: TAB_LABELS[tab], + count: tab === "incidents" && open > 0 ? open : undefined, + countTone: "error", + isCurrent: current === tab, + isRouteActive: current === tab, })), ) } -/** Over a draft's editor: nothing is public yet, and Publish page in the header changes that. */ +/** Over a draft's live page: nothing is public yet, and Publish page in the header changes that. */ const draftCallout = (h: H): Html => alert(h, { variant: "info", size: "sm", role: "status" }, [ icon(h, "LockIcon"), alertTitle(h, ["This page is a draft"]), alertDescription(h, [ - "Visitors can't see it yet. Add your monitors, pick a look in Appearance, then click Publish page.", + "Visitors can't see it yet. Add your monitors and pick a look under Settings, then click Publish page.", ]), ]) @@ -218,53 +230,82 @@ const canvasRead = (model: Model): { failure: Option.Option; isRead isReady: statusReadsReady(model), }) -const body = (h: H, model: Model, page: V2StatusPage, timeZone: string): Html => { - const view = resolveView(model.search.view) - switch (view) { - case "appearance": - return appearanceView(h, model, page) +/** The statuses' reads failed, or are still on their way: the tabs that list or draw them wait. */ +const awaitingReads = (h: H, model: Model): Html | null => { + const read = canvasRead(model) + if (Option.isSome(read.failure)) + return errorState(h, { + failure: read.failure.value, + title: "Couldn't load the page's components", + onRetry: Message.ClickedRetry(), + className: "py-12", + }) + return read.isReady ? null : h.div([h.AriaBusy(true)], [skeleton(h, "h-[560px] w-full")]) +} + +const body = (h: H, model: Model, page: V2StatusPage, time: TimeInputs): Html => { + const location = resolveView(model.search) + if (location.tab === "live") return liveView(h, model, page) + if (location.tab === "settings" && location.section !== "monitors") + return settingsView(h, model, page, location.section) + const waiting = awaitingReads(h, model) + if (waiting !== null) return waiting + switch (location.tab) { case "settings": - return settingsView(h, model, page) - case "live": - return liveView(h, model, page) - case "json": { - const failure = AsyncData.getError(model.config.data) - if (Option.isSome(failure)) - return errorState(h, { - failure: failure.value, - title: "Couldn't load the config", - onRetry: Message.ClickedRetry(), - className: "py-12", - }) - return AsyncData.hasData(model.config.data) ? jsonTab(h, model) : skeleton(h, "h-48 w-full") - } - case "page": { - const read = canvasRead(model) - if (Option.isSome(read.failure)) - return errorState(h, { - failure: read.failure.value, - title: "Couldn't load the page's components", - onRetry: Message.ClickedRetry(), - className: "py-12", - }) - if (!read.isReady) - return h.div( - [ - h.Class( - "grid gap-6 lg:grid-cols-[18rem_minmax(0,1fr)] xl:grid-cols-[22rem_minmax(0,1fr)]", - ), - h.AriaBusy(true), - ], - [skeleton(h, "h-48 w-full"), skeleton(h, "h-[560px] w-full")], - ) - const editor = canvas(h, model, page, { nowMs: model.nowMs ?? 0, timeZone }) + return settingsView(h, model, page, location.section) + case "incidents": + return incidentsTab(h, model, time) + case "maintenance": + return maintenanceTab(h, model, time) + case "page": return canManage(model) && page.draft - ? vstack(h, { gap: "4" }, [draftCallout(h), editor]) - : editor - } + ? vstack(h, { gap: "4" }, [draftCallout(h), livePage(h, model, page)]) + : livePage(h, model, page) } } +/** The side sheet: the open incident, or Add monitors; it keeps its last content while it closes. */ +const panelSheet = (h: H, model: Model, time: TimeInputs): Html => { + const panel = model.sheetPanel + const toParentMessage = (message: Dialog.Message) => Message.GotPanelSheetMessage({ message }) + if (panel?._tag === "Add") + return sidePanelSheet(h, { + sheet: model.panelSheet, + title: "Add monitors", + body: addSheetBody(h, model), + footer: (close) => addSheetFooter(h, model, close), + toParentMessage, + }) + const id = panel?._tag === "Incident" ? panel.incidentId : null + const listed = Option.getOrUndefined(Arr.findFirst(incidentsOf(model), (row) => row.id === id)) + // A closing sheet (its incident just deleted) keeps what it showed. + const kept = model.panel === null && model.sheetIncident?.id === id ? model.sheetIncident : undefined + const incident = listed ?? kept + return sidePanelSheet(h, { + sheet: model.panelSheet, + title: incident?.title ?? "Incident", + body: + incident === undefined + ? [missingIncident(h, model)] + : incidentSheetBody(h, model, incident, time), + toParentMessage, + }) +} + +/** The sheet's incident is not in the list: still being read, the read failed, or it is gone. */ +const missingIncident = (h: H, model: Model): Html => { + const data = model.incidents.data + if (AsyncData.isPending(data)) return h.div([h.AriaBusy(true)], [skeleton(h, "h-48 w-full")]) + return Option.match(AsyncData.getError(data), { + onSome: (failure) => + errorState(h, { failure, title: "Couldn't load the incident", onRetry: Message.ClickedRetry() }), + onNone: () => + typography(h, { size: "sm", tone: "muted", as: "p" }, [ + "This incident is no longer on the page.", + ]), + }) +} + /** What removing it does: a draft has no visitors yet, and only a monitored component has a monitor. */ export const removeComponentCopy = ( page: V2StatusPage, @@ -320,6 +361,7 @@ const deleteIncidentDialog = (h: H, model: Model, page: V2StatusPage): Html => { const loaded = (h: H, model: Model, page: V2StatusPage, inputs: PageViewInputs): Html => { const timeZone = inputs.context.timeZone + const time = { nowMs: model.nowMs ?? 0, timeZone } const overall = overallOf(model) const hasStatus = canvasRead(model).isReady && componentsOf(model).length > 0 return h.div( @@ -350,10 +392,11 @@ const loaded = (h: H, model: Model, page: V2StatusPage, inputs: PageViewInputs): tabs: tabs(h, model, page), gap: "md", }, - [body(h, model, page, timeZone)], + [body(h, model, page, time)], ), + panelSheet(h, model, time), deleteComponentDialog(h, model, page), - ...incidentDialogs(h, model, page, { nowMs: model.nowMs ?? 0, timeZone }), + ...incidentDialogs(h, model, page, time), deleteIncidentDialog(h, model, page), breakGlassDialog(h, model), deletePageDialog(h, model, page), @@ -387,16 +430,24 @@ export const view = Submodel.defineView((model, }) }) -/** The H1 names the page; a sub-view adds its name. */ +/** The H1 names the page; a tab adds its name, and Settings its section. */ export const breadcrumbsOf = (model: Model) => { const page = Option.getOrUndefined(pageOf(model)) - const view = resolveView(model.search.view) + const { tab, section } = resolveView(model.search) return [ { label: "Status pages", href: statusPagesHref() }, ...(page === undefined ? [] - : view === "page" || view === "live" + : tab === "page" || tab === "live" ? [{ label: page.name }] - : [{ label: page.name, href: statusPageHref(page.id) }, { label: TAB_LABELS[view] }]), + : [ + { label: page.name, href: statusPageHref(page.id) }, + ...(tab === "settings" + ? [ + { label: TAB_LABELS.settings, href: statusPageHref(page.id, "settings") }, + { label: sectionLabel(section) }, + ] + : [{ label: TAB_LABELS[tab] }]), + ]), ] } diff --git a/apps/web/src/page/status-pages/shared/commands.ts b/apps/web/src/page/status-pages/shared/commands.ts index 0e9d07c1c7..02543146d3 100644 --- a/apps/web/src/page/status-pages/shared/commands.ts +++ b/apps/web/src/page/status-pages/shared/commands.ts @@ -259,14 +259,18 @@ const decodeInternalId = Schema.decodeUnknownOption(StatusPageId) export const pageIdFromUrl = (raw: string): Option.Option => Option.orElse(decodePublicId(raw), () => decodeInternalId(raw)) -/** The editor's views: the page itself (none), its settings, its JSON, or the just-published screen. */ -export type EditorView = "appearance" | "settings" | "json" | "live" +/** The editor's tabs after the live page (none), and the screen right after publishing. */ +export type EditorView = "incidents" | "maintenance" | "settings" | "live" -export const statusPageHref = (id: StatusPageId, view?: EditorView): string => +/** The Settings tab's sections, in menu order. */ +export const SETTINGS_SECTIONS = ["basic", "monitors", "appearance", "access", "advanced"] as const +export type SettingsSection = (typeof SETTINGS_SECTIONS)[number] + +export const statusPageHref = (id: StatusPageId, view?: EditorView, section?: SettingsSection): string => hrefOf( AppRoute.StatusPage({ pageId: encodePublicId(id), - search: view === undefined ? {} : { view }, + search: { view, section }, }), ) diff --git a/apps/web/src/page/status-pages/shared/derive.test.ts b/apps/web/src/page/status-pages/shared/derive.test.ts index c0e0ee1dab..44269d7cca 100644 --- a/apps/web/src/page/status-pages/shared/derive.test.ts +++ b/apps/web/src/page/status-pages/shared/derive.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "vitest" import { component, componentId, incident, statusPage } from "./test-pages" -import { summarizePage } from "./derive" +import { statusReason, summarizePage } from "./derive" import { downMonitor, httpMonitor } from "../../kit/uptime/test-monitors" describe("status page summary", () => { @@ -41,3 +41,25 @@ describe("status page summary", () => { expect(summary.openIncidents).toBe(1) }) }) + +describe("status reason", () => { + test("an open incident behind a status is named, with what the monitor says", () => { + const up = httpMonitor() + const row = component(1, { monitor_id: up.id }) + expect(statusReason(row, [up], [incident(1, { title: "Slow loads", impact: "minor" })])).toBe( + 'Degraded by the open incident "Slow loads". The monitor is up.', + ) + }) + + test("a component that shows what its monitor says has no reason, nor does a draft incident", () => { + const down = downMonitor() + expect(statusReason(component(1, { monitor_id: down.id }), [down], [])).toBeNull() + expect(statusReason(component(1), [], [incident(1, { published: false })])).toBeNull() + }) + + test("an override is the reason when no incident is", () => { + expect(statusReason(component(1, { manual_status: "maintenance" }), [], [])).toBe( + "Maintenance, set under Override status.", + ) + }) +}) diff --git a/apps/web/src/page/status-pages/shared/derive.ts b/apps/web/src/page/status-pages/shared/derive.ts index 1e3b5544f2..c1780d7e13 100644 --- a/apps/web/src/page/status-pages/shared/derive.ts +++ b/apps/web/src/page/status-pages/shared/derive.ts @@ -120,6 +120,42 @@ export const componentStatus = ( ), }) +const MONITOR_STATE = { + up: "up", + down: "down", + pending: "waiting for its first check", + paused: "paused", +} as const satisfies Record, string> + +/** + * Why visitors see a status the monitor alone would not give: the open incident behind it, or the + * override. `null` when the component shows what its monitor says. + */ +export const statusReason = ( + component: V2StatusPageComponent, + monitors: ReadonlyArray, + incidents: ReadonlyArray, +): string | null => { + const monitorStatus = monitorStatusOf(monitors, component.monitor_id) + const shown = componentStatus(component, monitors, incidents) + if (shown === (monitorStatus === "down" ? "major_outage" : "operational")) return null + const label = COMPONENT_STATUS_LABEL[shown] + const cause = Arr.findFirst( + incidents, + (incident) => + incident.published && + isActiveIncident(incident) && + incident.component_ids.includes(component.id) && + incidentComponentStatus(incident) === shown, + ) + const why = Option.match(cause, { + onSome: (incident) => + `${label} by the open ${incident.kind === "incident" ? "incident" : "maintenance"} "${incident.title}".`, + onNone: () => `${label}, set under Override status.`, + }) + return monitorStatus === null ? why : `${why} The monitor is ${MONITOR_STATE[monitorStatus]}.` +} + /** The page banner: the worst component, as the public page derives it. */ export const pageStatus = ( components: ReadonlyArray, diff --git a/apps/web/src/page/status-pages/shared/form.ts b/apps/web/src/page/status-pages/shared/form.ts index faf77d318d..1b516f694e 100644 --- a/apps/web/src/page/status-pages/shared/form.ts +++ b/apps/web/src/page/status-pages/shared/form.ts @@ -80,7 +80,8 @@ export const componentFormOf = (component: V2StatusPageComponent): ComponentForm showUptime: component.show_uptime, }) -const orNull = (value: string): string | null => (Str.trim(value) === "" ? null : Str.trim(value)) +/** A typed value trimmed, or `null` when nothing is left. */ +export const orNull = (value: string): string | null => (Str.trim(value) === "" ? null : Str.trim(value)) const decodeMonitorId = Schema.decodeUnknownOption(UptimeMonitorId) const decodeComponentStatus = Schema.decodeUnknownOption(StatusPageComponentStatus) diff --git a/apps/web/src/page/status-pages/shared/picker.ts b/apps/web/src/page/status-pages/shared/picker.ts index f05b226ed7..d7168bbb15 100644 --- a/apps/web/src/page/status-pages/shared/picker.ts +++ b/apps/web/src/page/status-pages/shared/picker.ts @@ -6,6 +6,7 @@ import { defineMessageUnion } from "foldkit/message" import { bareUrl } from "../../kit/uptime/derive" import { formIssues, nameFromUrl, wirePayload } from "../../kit/uptime/form-derive" import { emptyForm } from "../../kit/uptime/form" +import { orNull } from "./form" // "What's on it": the org's monitors as a checklist, components without a monitor, and a URL // that becomes a new HTTP monitor. The builder and the editor's Add component share it. @@ -244,8 +245,6 @@ export const rowIssue = (row: PickerRow): string | null => export const hasRowIssues = (picker: Picker): boolean => Arr.some(picker.rows, (row) => rowIssue(row) !== null) -const orNull = (value: string): string | null => (Str.trim(value) === "" ? null : Str.trim(value)) - /** * The page's components as the create and the preview take them, in list order. A row with no * name yet is left out: the API refuses a blank name, and `rowIssue` blocks the create meanwhile. diff --git a/apps/web/src/page/status-pages/shared/preview.ts b/apps/web/src/page/status-pages/shared/preview.ts index b65c9be278..b1527e3251 100644 --- a/apps/web/src/page/status-pages/shared/preview.ts +++ b/apps/web/src/page/status-pages/shared/preview.ts @@ -10,15 +10,16 @@ import { } from "@maple/domain/status-page" import { type PreviewComponent, renderPage } from "@maple/status-page" import { cn } from "@maple/ui/lib/utils" +import { eyebrow } from "@maple/views/ui/eyebrow" import { segmentedSelect } from "@maple/views/ui/segmented-select" -import { hstack } from "@maple/views/ui/stack" +import { hstack, vstack } from "@maple/views/ui/stack" import { typography } from "@maple/views/ui/typography" import { Option, Schema, Stream, Array as Arr, String as Str } from "effect" import type { Html, HtmlBuilder } from "foldkit/html" import { toEpochMs } from "@maple/ui/lib/time-format" // The live preview: the public renderer's page in a sandboxed frame, with the monitors' real -// history, and in the editor a click on a component or incident posted back to select it. +// history, and in the editor a click on a component or incident posted back to open it. /** The scheme the preview shows an Auto page in; the page itself follows each visitor. */ export const PreviewScheme = Schema.Literals(["light", "dark"]) @@ -193,44 +194,16 @@ const decodeSelect = Schema.decodeUnknownOption(SelectMessage) export const selectionOf = (data: unknown): Option.Option => Option.map(decodeSelect(data), ({ kind, id }) => ({ kind, id })) -const isSafeId = (id: string) => /^[A-Za-z0-9_-]{1,64}$/u.test(id) - /** Inert in the frame: it only posts what was clicked; the frame has no same-origin access. */ -const SELECT_SCRIPT = `(function(){var q="[data-component-id],[data-incident-id]";document.addEventListener("click",function(e){var t=e.target&&e.target.closest?e.target.closest(q):null;if(!t)return;e.preventDefault();var c=t.getAttribute("data-component-id");parent.postMessage(c?{type:"select",kind:"component",id:c}:{type:"select",kind:"incident",id:t.getAttribute("data-incident-id")},"*")});var s=document.querySelector("[data-sp-first]");if(s)window.scrollTo(0,Math.max(0,s.getBoundingClientRect().top+window.scrollY-window.innerHeight/3))})();` - -const selectionStyles = (selectedIds: ReadonlyArray): string => { - const ids = Arr.filter(selectedIds, isSafeId) - const selected = Arr.join( - Arr.flatMap(ids, (id) => [`[data-component-id="${id}"]`, `[data-incident-id="${id}"]`]), - ",", - ) - return Arr.join( - [ - `[data-component-id],[data-incident-id]{cursor:pointer;border-radius:6px;transition:outline-color .12s}`, - `[data-component-id]:hover,[data-incident-id]:hover{outline:1px dashed color-mix(in srgb,currentColor 35%,transparent);outline-offset:3px}`, - selected === "" ? "" : `${selected}{outline:2px solid #3b82f6;outline-offset:3px}`, - ], - "", - ) -} +const SELECT_SCRIPT = `(function(){var q="[data-component-id],[data-incident-id]";document.addEventListener("click",function(e){var t=e.target&&e.target.closest?e.target.closest(q):null;if(!t)return;e.preventDefault();var c=t.getAttribute("data-component-id");parent.postMessage(c?{type:"select",kind:"component",id:c}:{type:"select",kind:"incident",id:t.getAttribute("data-incident-id")},"*")})})();` -/** Marks the first selected element so the frame scrolls its own view to it after a reload. */ -const markFirst = (html: string, selectedIds: ReadonlyArray): string => { - const found = Arr.findFirst(selectedIds, isSafeId) - if (Option.isNone(found)) return html - const first = found.value - const attr = Str.includes(`data-component-id="${first}"`)(html) - ? `data-component-id="${first}"` - : `data-incident-id="${first}"` - return Str.replace(attr, `${attr} data-sp-first`)(html) -} +const SELECTABLE_STYLES = `[data-component-id],[data-incident-id]{cursor:pointer;border-radius:6px}[data-component-id]:hover,[data-incident-id]:hover{outline:1px dashed color-mix(in srgb,currentColor 35%,transparent);outline-offset:3px}` export type PreviewDocumentOptions = Readonly<{ snapshot: StatusPagePublicSnapshot nowMs: number - /** The editor's preview: components and incidents can be clicked, and the selection drawn. */ + /** The editor's preview: components and incidents can be clicked. */ isSelectable: boolean - selectedIds: ReadonlyArray /** Where visitors read the page, for its Slack command; `null` while no status domain is configured. */ publicUrl: string | null /** @@ -261,8 +234,8 @@ export const previewDocument = (options: PreviewDocumentOptions): string => { ) const stay = `` if (!options.isSelectable) return Str.replace("", `${stay}`)(html) - const extra = `${stay}` - return Str.replace("", `${extra}`)(markFirst(html, options.selectedIds)) + const extra = `${stay}` + return Str.replace("", `${extra}`)(html) } export const PREVIEW_FRAME_ID = "status-page-preview-frame" @@ -391,3 +364,28 @@ export const previewFrame = ( ], [], ) + +/** + * A small frame of one part of the page (`renderFragment`): fully sandboxed, no scripts, and it + * takes no clicks, so nothing in it navigates the frame. + */ +export const fragmentFrame = ( + h: HtmlBuilder, + options: Readonly<{ document: string; title: string; className?: string }>, +): Html => + h.iframe( + [ + h.Title(options.title), + h.Sandbox(""), + h.Tabindex(-1), + h.Srcdoc(options.document), + h.Class( + cn("pointer-events-none block w-full rounded-lg border bg-background", options.className), + ), + ], + [], + ) + +/** A setting's preview: a label, then the part of the page the setting changes. */ +export const onYourPage = (h: HtmlBuilder, preview: Html, label = "On your page"): Html => + vstack(h, { gap: "1.5" }, [eyebrow(h, {}, [label]), preview]) diff --git a/apps/web/src/page/status-pages/viewer/view.ts b/apps/web/src/page/status-pages/viewer/view.ts index e040b280cf..62cdf5dbc4 100644 --- a/apps/web/src/page/status-pages/viewer/view.ts +++ b/apps/web/src/page/status-pages/viewer/view.ts @@ -1,4 +1,5 @@ import { Option } from "effect" +import { pageTitle } from "@maple/status-page" import { AsyncData, Submodel } from "foldkit" import type { Html, HtmlBuilder } from "foldkit/html" import { errorState } from "@maple/views/ui/error-state" @@ -39,12 +40,11 @@ const body = (h: H, model: Model): Html => { vstack(h, { gap: "2" }, [ typography(h, { size: "xs", tone: "muted", as: "p" }, [NOTE[snapshot.page.visibility]]), previewFrame(h, { - title: `${snapshot.page.name} status`, + title: pageTitle(snapshot.page.name), document: previewDocument({ snapshot, nowMs: snapshot.generatedAt, isSelectable: false, - selectedIds: [], publicUrl: null, opensLinks: true, }), diff --git a/apps/web/src/route/search.ts b/apps/web/src/route/search.ts index 19a16c3986..58dadd9513 100644 --- a/apps/web/src/route/search.ts +++ b/apps/web/src/route/search.ts @@ -400,9 +400,13 @@ export const AlertsStatusPageSearch = Schema.Struct({ tab: StringParam, }) -/** `/status-pages/$pageId`: `view` is `appearance`, `settings`, `json` or `live`; none is the page itself. */ +/** + * `/status-pages/$pageId`: `view` is `incidents`, `maintenance`, `settings` or `live` (just + * published); none is the live page. `section` picks the Settings section. + */ export const StatusPageSearch = Schema.Struct({ view: StringParam, + section: StringParam, }) export const CodeReviewCiSearch = Schema.Struct(CodeReviewCiSearchFields) diff --git a/packages/status-page/src/access.ts b/packages/status-page/src/access.ts index 14738e994b..3577caad56 100644 --- a/packages/status-page/src/access.ts +++ b/packages/status-page/src/access.ts @@ -2,6 +2,7 @@ import type { StatusPagePublicSnapshot } from "@maple/domain/status-page" import { escapeHtml } from "@maple/strings" import { Array as Arr } from "effect" import { pageHref, type RenderOptions, renderDocument, renderHeader } from "./document" +import { pageTitle } from "./format" import { manageStyles } from "./styles" /** Where the password form posts, under the page's base path. */ @@ -35,7 +36,7 @@ export const renderAccessPage = ( return renderDocument({ snapshot, options, - title: `${snapshot.page.name} status`, + title: pageTitle(snapshot.page.name), styles: manageStyles, body, head: ``, diff --git a/packages/status-page/src/feed.ts b/packages/status-page/src/feed.ts index bc422f0c62..512096e1a6 100644 --- a/packages/status-page/src/feed.ts +++ b/packages/status-page/src/feed.ts @@ -1,7 +1,7 @@ import type { StatusPagePublicSnapshot } from "@maple/domain/status-page" import { escapeHtml } from "@maple/strings" import { escapeXml } from "./escape" -import { INCIDENT_STATUS_LABEL } from "./format" +import { INCIDENT_STATUS_LABEL, pageTitle } from "./format" import { latestActivityAt } from "./select" import { Array as Arr, String as Str } from "effect" @@ -45,7 +45,7 @@ export const renderAtomFeed = (snapshot: StatusPagePublicSnapshot, pageUrl: stri ), "", ) - return `urn:maple:status:${escapeXml(snapshot.pageId)}${escapeXml(`${snapshot.page.name} status`)}${iso(latestActivityAt(snapshot))}${escapeXml(snapshot.page.name)}${entries}` + return `urn:maple:status:${escapeXml(snapshot.pageId)}${escapeXml(pageTitle(snapshot.page.name))}${iso(latestActivityAt(snapshot))}${escapeXml(snapshot.page.name)}${entries}` } /** RFC 822 date, as RSS 2.0 requires. */ @@ -62,6 +62,6 @@ export const renderRssFeed = (snapshot: StatusPagePublicSnapshot, pageUrl: strin ), "", ) - const title = escapeXml(`${snapshot.page.name} status`) + const title = escapeXml(pageTitle(snapshot.page.name)) return `${title}${escapeXml(`${base}/`)}${title}${rfc822(latestActivityAt(snapshot))}${items}` } diff --git a/packages/status-page/src/format.ts b/packages/status-page/src/format.ts index e8a571440e..5ced445da5 100644 --- a/packages/status-page/src/format.ts +++ b/packages/status-page/src/format.ts @@ -23,6 +23,9 @@ export const HERO_SENTENCE = { major_outage: "We're experiencing a major outage", } as const satisfies Record +/** The page's title: its browser tab, feeds and search results. */ +export const pageTitle = (name: string): string => `${name} status` + export const INCIDENT_STATUS_LABEL = { investigating: "Investigating", identified: "Identified", diff --git a/packages/status-page/src/fragment.test.ts b/packages/status-page/src/fragment.test.ts new file mode 100644 index 0000000000..728d59f4b2 --- /dev/null +++ b/packages/status-page/src/fragment.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from "vitest" +import { FIXTURE_NOW, fixtureComponentId, makeComponent, makeSnapshot } from "./fixtures" +import { renderFragment } from "./index" + +describe("renderFragment", () => { + const snapshot = makeSnapshot({ + components: [ + makeComponent(0, { name: "API", group: "Platform", status: "major_outage" }), + makeComponent(1, { name: "Dashboard", group: "Platform" }), + makeComponent(2, { name: "Docs", showUptime: false, monitored: false, days: [] }), + ], + }) + + it("narrowed to one component, shows it under its group's head and leaves the others and the rest of the page out", () => { + const html = renderFragment(snapshot, { + parts: ["components"], + nowMs: FIXTURE_NOW, + componentId: fixtureComponentId(1), + }) + expect(html).toContain("Dashboard") + expect(html).toContain(`class="group-head"`) + expect(html).toContain("Platform") + expect(html).not.toContain(">API<") + expect(html).not.toContain(">Docs<") + expect(html).not.toContain("Past incidents") + expect(html).not.toContain("