Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 45 additions & 5 deletions apps/mobile/src/features/chats/KinRulesScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { AsyncResult, Atom } from "effect/reactivity";
import * as Clipboard from "expo-clipboard";
import { useState } from "react";
import { View } from "react-native";
import { useEffect, useState } from "react";
import { AccessibilityInfo, Platform, View } from "react-native";

import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import { AppText as Text } from "../../components/ui/AppText";
Expand All @@ -28,6 +28,8 @@ import * as Dialog from "../../components/ui/Dialog";
import { EmptyState } from "../../components/ui/EmptyState";
import { ListSection } from "../../components/ui/ListSection";
import { Notice } from "../../components/ui/Notice";
import { useNowMinuteMs } from "../../lib/clock";
import { cn } from "../../lib/cn";
import { appAtomRegistry } from "../../state/atom-registry";
import { useAtomCommand } from "../../state/use-atom-command";
import { SettingsRow } from "../settings/components/SettingsRow";
Expand All @@ -38,7 +40,7 @@ import {
useKinAskBeforeDiscard,
} from "./components/KinWorkPieces";
import { kinClient } from "./state/kinClient";
import { useKinGate } from "./state/useKinHost";
import { useKinGate, useKinHostAt } from "./state/useKinHost";

export type KinRulesParams = { readonly environmentId: string; readonly orgId: string };

Expand Down Expand Up @@ -108,7 +110,15 @@ function KinRulesBody({ environmentId, orgId }: KinRulesTarget) {
);
// What was last read stays up while it is read again, and the draft stays over it.
const read = kinRulesRead(result);
const view = read === null ? null : kinRulesView(read, edits);
// The minute clock moves "Kin checked … ago" on while the screen sits, one render a minute.
const now = new Date(useNowMinuteMs());
const host = useKinHostAt(environmentId);
// The name the host signs the owner's own changes with; a host too old to say keeps the name.
const myName =
host._tag === "host" && host.probe._tag === "ready"
? (host.probe.orgs.me.find((entry) => entry.orgId === orgId)?.displayName ?? null)
: null;
const view = read === null ? null : kinRulesView(read, edits, { now, me: myName });
// Kept while saving too: a save that fails or finds the rules changed leaves the draft here.
const guarded = view !== null && view.dirty;
useKinAskBeforeDiscard(guarded);
Expand Down Expand Up @@ -204,10 +214,14 @@ function KinRulesBody({ environmentId, orgId }: KinRulesTarget) {
placeholder={KIN_RULES_COPY.placeholder}
multiline
disabled={view.saving}
hint={view.tooLarge ?? view.status ?? undefined}
onChangeText={(text) => editor.type(view.held, text)}
/>
</ListSection>
{view.tooLarge !== null ? (
<KinRulesSaid key="too-large" message={view.tooLarge} danger />
) : view.status === null ? null : (
<KinRulesSaid key={view.status} message={view.status} />
)}
{view.facts.length === 0 ? null : (
<Text textRole="footnote" className="px-2 text-foreground-muted">
{view.facts.join("\n")}
Expand All @@ -219,6 +233,32 @@ function KinRulesBody({ environmentId, orgId }: KinRulesTarget) {
);
}

/**
* What the editor's last change or save came to, said aloud as it appears: TalkBack hears the live
* region, VoiceOver the announcement. Keyed by what it says, so a too-large line that only moves
* by a few bytes while typing is not read again on every key.
*/
function KinRulesSaid(props: { readonly message: string; readonly danger?: boolean }) {
const [said] = useState(props.message);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- announces the line to VoiceOver through AccessibilityInfo when it appears
useEffect(() => {
if (Platform.OS === "ios") AccessibilityInfo.announceForAccessibility(said);
}, [said]);
return (
<Text
textRole="footnote"
accessibilityLiveRegion="polite"
{...(props.danger === true ? { accessibilityRole: "alert" as const } : {})}
className={cn(
"px-2",
props.danger === true ? "text-danger-foreground" : "text-foreground-muted",
)}
>
{props.message}
</Text>
);
}

function KinRulesLoadFailed(props: {
readonly result: AsyncResult.Failure<KinMemoryRules, unknown>;
readonly onRetry: () => void;
Expand Down
7 changes: 5 additions & 2 deletions apps/web/src/components/AppRouteModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { XIcon } from "lucide-react";
import { useRef, useState, type CSSProperties, type ReactNode } from "react";

import { getCommandPaletteOpener } from "../commandPaletteStore";
import { useKinModalCloseGuardHost } from "../kin/KinRouteModalGuard";
import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay";
import { requestWorkspaceFocus } from "../lib/workspaceFocus";
import { useCloseAppModal } from "./sidebar/mainAppLocation";
Expand Down Expand Up @@ -35,6 +36,7 @@ export function AppRouteModal({
// On close, return focus to the opener only after a keyboard close; after a pointer close it
// would paint a focus ring.
const popupRef = useRef<HTMLDivElement>(null);
const kinGuard = useKinModalCloseGuardHost(popupRef, setOpen);
const [opener] = useState(
() =>
getCommandPaletteOpener() ??
Expand Down Expand Up @@ -62,6 +64,7 @@ export function AppRouteModal({
) {
return eventDetails.cancel();
}
if (kinGuard.holds(eventDetails)) return;
// Closing unmounts a focused field without a blur, so commit-on-blur rows would
// drop what was typed. Blur first so they commit.
const focused = document.activeElement;
Expand Down Expand Up @@ -89,7 +92,7 @@ export function AppRouteModal({
backdropPressRef.current = event.target === event.currentTarget;
}}
onClick={(event) => {
if (backdropPressRef.current && event.target === event.currentTarget) setOpen(false);
if (backdropPressRef.current && event.target === event.currentTarget) kinGuard.close();
backdropPressRef.current = false;
}}
>
Expand All @@ -116,7 +119,7 @@ export function AppRouteModal({
aria-hidden
className="absolute inset-x-0 top-0 hidden h-(--app-modal-titlebar-height) [-webkit-app-region:drag] max-sm:block"
/>
{children}
{kinGuard.provide(children)}
<GlobalVoiceInputIndicator />
</DialogPrimitive.Popup>
</DialogPrimitive.Viewport>
Expand Down
11 changes: 2 additions & 9 deletions apps/web/src/kin/KinCheckIns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import { Textarea } from "../components/ui/textarea";
import { Toggle, ToggleGroup } from "../components/ui/toggle-group";
import { useAtomCommand } from "../state/use-atom-command";
import { KinConfirm } from "./KinConfirm";
import { kinNewLeadTarget } from "./KinNewLeadButton";
import { kinClient, refreshKinBriefs } from "./kinClient";
import {
KinSettingsField,
Expand All @@ -48,16 +47,10 @@ import {
KinSettingsSection,
KinSettingsStatus,
} from "./settings/KinSettingsLayout";
import { useKinHost } from "./useKinHost";
import type { KinWorkTarget } from "./useKinWork";

/** Settings → Check-ins, for the owner or a co-owner; nothing shows where there is no Kin. */
export function KinCheckInsPage() {
const target = kinNewLeadTarget(useKinHost());
return target === null ? null : <CheckIns {...target} />;
}

function CheckIns(props: KinWorkTarget) {
/** Settings → Check-ins, for the owner or a co-owner. */
export function KinCheckInsPage(props: KinWorkTarget) {
const searchableSetting = useSearchableSetting();
const query = { environmentId: props.environmentId, input: { orgId: props.orgId } };
const result = useAtomValue(kinClient.checkIns(query));
Expand Down
54 changes: 53 additions & 1 deletion apps/web/src/kin/KinFormDiscard.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { KIN_FORM_DISCARD } from "@t3tools/client-runtime/kin/kinWorkForms";
import { useState } from "react";
import { useBlocker } from "@tanstack/react-router";
import { useRef, useState } from "react";

import {
AlertDialog,
Expand All @@ -10,6 +11,7 @@ import {
AlertDialogTitle,
} from "../components/ui/alert-dialog";
import { Button } from "../components/ui/button";
import { useKinModalCloseGuard } from "./KinRouteModalGuard";

/**
* Closing a form that holds unsaved typing asks "Discard what you typed?" first; an untouched
Expand Down Expand Up @@ -47,3 +49,53 @@ export function useKinFormDiscard(typed: boolean, onClose: () => void) {
);
return { close, ask };
}

/**
* A page that holds unsaved typing asks "Discard what you typed?" (Keep editing / Discard) before
* any way out: another route or Settings page, browser Back, reload or tab close, and closing the
* modal it sits in (Esc, the close button, a backdrop press). Render `ask` in the page.
*/
export function useKinLeaveGuard(typed: boolean) {
// Set once the person chose Discard, so the route's blocker lets the same leave through.
const released = useRef(false);
const [closing, setClosing] = useState<((leave: boolean) => void) | null>(null);
const blocker = useBlocker({
shouldBlockFn: () => typed && !released.current,
enableBeforeUnload: () => typed && !released.current,
withResolver: true,
});
const [askBeforeClose] = useState(
() => () => new Promise<boolean>((resolve) => setClosing(() => resolve)),
);
useKinModalCloseGuard(typed ? askBeforeClose : null);
const answer = (leave: boolean) => {
if (leave) released.current = true;
closing?.(leave);
setClosing(null);
if (leave) blocker.proceed?.();
else blocker.reset?.();
};
const ask = (
<AlertDialog
open={closing !== null || blocker.status === "blocked"}
onOpenChange={(open) => {
if (!open) answer(false);
}}
>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>{KIN_FORM_DISCARD.title}</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>
{KIN_FORM_DISCARD.keep}
</AlertDialogClose>
<Button variant="destructive" onClick={() => answer(true)}>
{KIN_FORM_DISCARD.discard}
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
);
return ask;
}
68 changes: 68 additions & 0 deletions apps/web/src/kin/KinRouteModalGuard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import {
createContext,
use,
useEffect,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";

/** Answers whether the modal may close now: false keeps it open, as it was. */
type KinCloseGuard = () => boolean | Promise<boolean>;
const KinCloseGuardContext = createContext<((guard: KinCloseGuard | null) => void) | null>(null);

/**
* For a page inside T3's route modal (Settings): veto its close (Esc, the close button, a backdrop
* press) while it holds unsaved work. The route's own blocker answers too late: the popup is gone.
*/
export function useKinModalCloseGuard(guard: KinCloseGuard | null) {
const register = use(KinCloseGuardContext);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this page's guard with the modal that owns the close, and takes it back on unmount
useEffect(() => {
if (register === null || guard === null) return;
register(guard);
return () => register(null);
}, [register, guard]);
}

/**
* The route modal's side, its hook into Kin: with no page guarding, every close goes on exactly as
* the modal does it; with one, the close waits for the page's answer.
*/
export function useKinModalCloseGuardHost(
popupRef: RefObject<HTMLElement | null>,
setOpen: (open: boolean) => void,
) {
const guardRef = useRef<KinCloseGuard | null>(null);
const [register] = useState(() => (guard: KinCloseGuard | null) => {
guardRef.current = guard;
});
const ask = (guard: KinCloseGuard) =>
void Promise.resolve(guard()).then((may) => {
if (!may) return;
// As the modal's own close: blur first, so commit-on-blur rows keep what was typed.
const focused = document.activeElement;
if (focused instanceof HTMLElement && popupRef.current?.contains(focused)) focused.blur();
setOpen(false);
});
return {
/** Esc or the close button: true when a page guards, after cancelling this close to ask. */
holds: (details: { readonly cancel: () => void }) => {
const guard = guardRef.current;
if (guard === null) return false;
details.cancel();
ask(guard);
return true;
},
/** A backdrop press: asks first when a page guards, otherwise closes. */
close: () => {
const guard = guardRef.current;
if (guard === null) setOpen(false);
else ask(guard);
},
provide: (children: ReactNode) => (
<KinCloseGuardContext value={register}>{children}</KinCloseGuardContext>
),
};
}
81 changes: 81 additions & 0 deletions apps/web/src/kin/KinSettingsOffline.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { page, userEvent } from "vite-plus/test/browser";

vi.mock("../components/chat/GlobalVoiceInputIndicator", () => ({
GlobalVoiceInputIndicator: () => null,
}));

// The company's host after its connection dropped: its last answer is still known.
vi.mock(import("./useKinHost"), async (importOriginal) => ({
...(await importOriginal()),
useKinHost: () =>
({
_tag: "host",
environmentId: "env-1",
connected: false,
probe: { _tag: "ready", orgs: { me: [{ orgId: "org-1", personId: "p-owner" }] } },
}) as never,
}));

vi.mock(import("./useKinOwnerLevel"), async (importOriginal) => ({
...(await importOriginal()),
useKinOwnerLevel: () => true,
useKinPlaceReach: () => null,
useKinSeesClients: () => true,
}));

vi.mock(import("./useKinShell"), async (importOriginal) => ({
...(await importOriginal()),
useKinSectionOn: () => true,
}));

vi.mock(import("./kinClient"), async (importOriginal) => {
const real = await importOriginal();
const { Atom: A } = await import("effect/reactivity");
const allowed = A.make(true);
const granted = <C extends object>(command: C) => ({ ...command, permissionAtom: () => allowed });
return {
...real,
kinClient: {
...real.kinClient,
recommendationAskAgain: granted(real.kinClient.recommendationAskAgain),
memorySaveRules: granted(real.kinClient.memorySaveRules),
},
};
});

// The page itself has its own tests; here it is only what the owner is typing into.
vi.mock("./settings/KinRulesPage", () => ({
KinRulesPage: () => <textarea aria-label="Standing rules" />,
}));

import { KIN_SECTIONS_PAGE } from "@t3tools/client-runtime/kin/kinShell";

import { render } from "../../test/render";
import { SidebarProvider } from "../components/ui/sidebar";
import { KinSettingsModalHost } from "./KinSettingsView";

describe("Kin's Settings while its host is offline", () => {
it("stays open on the page being typed into, with the typing kept", async () => {
await using _screen = await render(
<SidebarProvider>
<KinSettingsModalHost />
</SidebarProvider>,
{ router: "/kin?settings=rules" },
);
const rules = page.getByRole("textbox", { name: "Standing rules" });
await userEvent.fill(rules.element(), "Invented rule: mine.");
await expect.element(page.getByRole("dialog", { name: "Settings" })).toBeVisible();
await expect.element(rules).toHaveValue("Invented rule: mine.");
});

it("shows a page that once looked its host up itself, not a blank one", async () => {
await using _screen = await render(
<SidebarProvider>
<KinSettingsModalHost />
</SidebarProvider>,
{ router: "/kin?settings=sections" },
);
await expect.element(page.getByText(KIN_SECTIONS_PAGE.intro)).toBeVisible();
});
});
Loading
Loading