Skip to content
Open
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
143 changes: 132 additions & 11 deletions e2e/team-review-fixes.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test, type Page } from "@playwright/test";
import { openApp, waitForIdle } from "./support/app";
import { openApp, storedTags, waitForIdle } from "./support/app";
import { ADMIN_INVITE, MEMBER_INVITE, joinTeam, menu, space, toast } from "./support/team";

// A team's member and admin against the backend as the Rust and the team server judge them
Expand All @@ -18,7 +18,7 @@ type M = {
teamStatus: (s: Record<string, unknown>) => void;
teamWithdraw: (kind: "revoked" | "replaced") => void;
};
__TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record<string, unknown>) => Promise<unknown> };
__TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record<string, unknown>, options?: unknown) => Promise<unknown> };
};

const TEAM: Scope = { kind: "team" };
Expand Down Expand Up @@ -291,23 +291,26 @@ test("leaving a team closes its profiles open here, saved to it; a withdrawal cl

test("a queued write goes to the space it was made in, never the one in use after a switch", async ({ page }) => {
await asMember(page, allow(TEAM, "see", "start", "edit", "create"));
// The new tag's write waits on a slow server; the launcher moves to Personal meanwhile.
await page.evaluate(() => { (window as unknown as { __shardxMockSlow: Record<string, number> }).__shardxMockSlow = { tag_save: 800 }; });
await holdQuickTagWrite(page, "tag_save");
const etsy = row(page, "tp-shop-1");
await etsy.click({ button: "right" });
await item(page, /^Edit tags/).click();
await page.getByPlaceholder("Find or create a tag…").fill("Team only");
await page.keyboard.press("Enter");
const picker = page.getByRole("dialog", { name: "Tags", exact: true });
await pickNewQuickTag(picker, "Team only");
await waitForQuickTagWrite(page);
await page.keyboard.press("Escape");
await expect(picker).toHaveCount(0);
const asked = await page.evaluate(() => (window as unknown as M).__shardxMock.epoch);
await page.evaluate(() => (window as unknown as { __shardxMock: { moveSpace: (s: unknown) => void } }).__shardxMock.moveSpace({ kind: "personal" }));
await expect(space(page)).toHaveText("Personal");
// The assign queued behind the save still names the team's edition, so it is refused there.
await expect.poll(async () => (await callsOf(page, "tag_assign")).length).toBeGreaterThan(0);
for (const w of [...await callsOf(page, "tag_save"), ...await callsOf(page, "tag_assign")]) expect(w.epoch).toBe(asked);
// The create carries the team's edition when it reaches the backend.
await releaseQuickTagWrite(page);
await expect(toast(page, "switched to another space before this was saved").first()).toBeVisible();
const personal = await page.evaluate(() => (window as unknown as M).__shardxMock.state.tags?.tags ?? []);
expect(personal.map((x: { name: string }) => x.name)).not.toContain("Team only");
await waitForIdle(page);
expect((await callsOf(page, "tag_save")).map((write) => write.epoch)).toEqual([asked]);
expect(await callsOf(page, "tag_assign")).toEqual([]);
await expect(toast(page, "Tags saved")).toHaveCount(0);
expect((await storedTags(page)).tags.map((tag) => tag.name)).not.toContain("Team only");
});

test("in Russian at 1280 px with Peek open, the row's Start and Peek's name are whole", async ({ page }) => {
Expand Down Expand Up @@ -346,3 +349,121 @@ test("the Team page in the personal space leads back to the team this launcher i
await page.locator("main").getByRole("button", { name: "Switch to “Shops team”" }).click();
await expect(space(page)).toHaveText("Shops team");
});

const QUICK_TAG_PROFILE = "tp-shop-1";
const QUICK_TAG = { id: "t-quick-review", name: "Needs review", color: "orange" };

async function openQuickTeamTagPicker(page: Page) {
await asMember(page, allow(TEAM, "see", "edit", "create"));
await page.evaluate((tag) => {
const mock = (window as unknown as M).__shardxMock;
mock.state.tags = { tags: [tag], by_profile: {} };
mock.emit("store-changed", "tags");
}, QUICK_TAG);
await row(page, QUICK_TAG_PROFILE).click({ button: "right" });
await item(page, /^Edit tags/).click();
return page.getByRole("dialog", { name: "Tags", exact: true });
}

type HeldQuickTagWrite = M & {
quickTagWriteStarted?: boolean;
releaseQuickTagWrite: () => void;
__shardxMockFailWith?: Record<string, string>;
};

async function holdQuickTagWrite(page: Page, command: "tag_assign" | "tag_save", failure?: string) {
await page.evaluate(({ command, failure }) => {
const w = window as unknown as HeldQuickTagWrite;
const ipc = w.__TAURI_INTERNALS__;
const invoke = ipc.invoke;
w.quickTagWriteStarted = false;
const held = new Promise<void>((resolve) => { w.releaseQuickTagWrite = resolve; });
ipc.invoke = async (cmd, args, options) => {
if (cmd !== command) return invoke(cmd, args, options);
ipc.invoke = invoke;
w.quickTagWriteStarted = true;
await held;
if (failure) w.__shardxMockFailWith = { ...w.__shardxMockFailWith, [command]: failure };
return invoke(cmd, args, options);
};
}, { command, failure });
}

const waitForQuickTagWrite = (page: Page) =>
page.waitForFunction(() => (window as unknown as HeldQuickTagWrite).quickTagWriteStarted);
const releaseQuickTagWrite = (page: Page) =>
page.evaluate(() => (window as unknown as HeldQuickTagWrite).releaseQuickTagWrite());

async function pickNewQuickTag(picker: ReturnType<Page["getByRole"]>, name: string) {
await picker.getByRole("combobox", { name: "Find or create a tag" }).fill(name);
await picker.getByRole("option", { name: `Create “${name}”`, exact: true }).click();
}

for (const outcome of ["accepted", "rejected"] as const) {
test(`quick team tag save waits for the server when the assignment is ${outcome}`, async ({ page }) => {
const picker = await openQuickTeamTagPicker(page);
const option = picker.getByRole("option", { name: QUICK_TAG.name, exact: true });
await expect(option).toHaveAttribute("aria-selected", "false");
await holdQuickTagWrite(page, "tag_assign", outcome === "rejected" ? "the team server did not answer" : undefined);

await option.click();
await expect(option).toHaveAttribute("aria-selected", "true");
await waitForQuickTagWrite(page);
const saved = toast(page, "Tags saved");
await expect(saved).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(picker).toHaveCount(0);
await expect(saved).toHaveCount(0);
expect((await storedTags(page)).by_profile[QUICK_TAG_PROFILE] ?? []).toEqual([]);

await releaseQuickTagWrite(page);
if (outcome === "accepted") {
await expect(saved).toHaveCount(1);
expect((await storedTags(page)).by_profile[QUICK_TAG_PROFILE]).toEqual([QUICK_TAG.id]);
} else {
await expect(toast(page, "Couldn’t save tags")).toContainText("The team server isn’t answering. Try again once it’s back.");
await row(page, QUICK_TAG_PROFILE).click({ button: "right" });
await item(page, /^Edit tags/).click();
await expect(option).toHaveAttribute("aria-selected", "false");
await expect(saved).toHaveCount(0);
expect((await storedTags(page)).by_profile[QUICK_TAG_PROFILE] ?? []).toEqual([]);
}
});
}

test("a rejected quick team tag creation does not try to assign the tag", async ({ page }) => {
const picker = await openQuickTeamTagPicker(page);
const name = "New team tag";
await holdQuickTagWrite(page, "tag_save", "the team server did not answer");
await pickNewQuickTag(picker, name);
await waitForQuickTagWrite(page);
await page.keyboard.press("Escape");
await expect(picker).toHaveCount(0);

await releaseQuickTagWrite(page);
await expect(toast(page, "Couldn’t save tags")).toContainText("The team server isn’t answering. Try again once it’s back.");
await waitForIdle(page);
expect(await callsOf(page, "tag_save")).toHaveLength(1);
expect(await callsOf(page, "tag_assign")).toEqual([]);
const saved = await storedTags(page);
expect(saved.tags.map((tag) => tag.name)).not.toContain(name);
expect(saved.by_profile[QUICK_TAG_PROFILE] ?? []).toEqual([]);
await expect(toast(page, "Tags saved")).toHaveCount(0);
});

test("closing the quick team tag picker after a teammate's edit reports no save", async ({ page }) => {
const picker = await openQuickTeamTagPicker(page);
const option = picker.getByRole("option", { name: QUICK_TAG.name, exact: true });
await expect(option).toHaveAttribute("aria-selected", "false");
await page.evaluate(({ profileId, tagId }) => {
const mock = (window as unknown as M).__shardxMock;
mock.state.tags.by_profile[profileId] = [tagId];
mock.emit("store-changed", "tags");
}, { profileId: QUICK_TAG_PROFILE, tagId: QUICK_TAG.id });
await expect(option).toHaveAttribute("aria-selected", "true");

await page.keyboard.press("Escape");
await expect(picker).toHaveCount(0);
await expect(toast(page, "Tags saved")).toHaveCount(0);
expect(await callsOf(page, "tag_assign")).toEqual([]);
});
104 changes: 82 additions & 22 deletions src/entities/tag/lib/useTags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { create } from "zustand";
import { LABEL_COLORS, type LabelColorId } from "../../../shared/constants";
import { handOver, windowStorage } from "../../../shared/lib/handOver";
import { writeQueue } from "../../../shared/lib/writeQueue";
import { onSpaceMoved } from "../../../shared/api/invoke";
import { onSpaceMoved, spaceEpoch } from "../../../shared/api/invoke";
import { toast } from "../../../shared/model/toast";
import { t } from "../../../shared/i18n";
import type { Tag } from "../model/types";
Expand All @@ -19,8 +19,33 @@ export function setTagAssignGuard(fn: AssignGuard): void { assignGuard = fn; }
/** A tag a team's server saved under another id than sent (tag_save in a team): the new one. */
const renamed = new Map<string, string>();
const finalId = (id: string) => renamed.get(id) ?? id;
const remapped = (byProfile: Record<string, string[]>) =>
Object.fromEntries(Object.entries(byProfile).map(([pid, ids]) => [pid, ids.map(finalId)]));
type TagCreation = { saved: boolean };
const remapped = (byProfile: Record<string, string[]>, creations: ReadonlyMap<string, TagCreation>) =>
Object.fromEntries(Object.entries(byProfile).map(([pid, ids]) => [
pid, ids.filter((id) => creations.get(id)?.saved !== false).map(finalId),
]));

export type TagToggle = {
tagId: string;
profileIds: string[];
adding: boolean;
saved: Promise<boolean>;
};

/** Opposite picks cancel, including when a newly created tag received its server ID. */
export function tagsChanged(picks: readonly TagToggle[]): boolean {
const changes = new Map<string, { before: boolean; after: boolean }>();
for (const { tagId, profileIds, adding } of picks) {
const id = finalId(tagId);
for (const pid of profileIds) {
const key = JSON.stringify([pid, id]);
const change = changes.get(key);
if (change) change.after = adding;
else changes.set(key, { before: !adding, after: adding });
}
}
return [...changes.values()].some(({ before, after }) => before !== after);
}

/// Tags, and tag ids by profile id. The backend keeps them (tags.rs); this
/// store shows each change at once and sends it after.
Expand Down Expand Up @@ -77,7 +102,7 @@ export type TagStore = {
* a tag made since with its name gets those profiles instead. */
restoreTag: (tag: Tag, byProfile: Record<string, string[]>, at?: number) => void;
/** Gives the tag to every profile, or takes it off all when all have it. */
toggle: (profileIds: string[], tagId: string) => void;
toggle: (profileIds: string[], tagId: string) => TagToggle | null;
/** Takes one tag off one profile. */
untag: (profileId: string, tagId: string) => void;
/** Gives one profile exactly these tags (the profile form's Save). */
Expand All @@ -92,6 +117,7 @@ let loading: Promise<void> | null = null;

export const useTags = create<TagStore>((set, get) => {
let queue: ReturnType<typeof writeQueue> | null = null;
const creating = new Map<string, TagCreation>();
const read = async () => {
const s = await tagList();
set(whole(s.tags, s.by_profile, COLOR_IDS));
Expand All @@ -107,13 +133,19 @@ export const useTags = create<TagStore>((set, get) => {
}
})();
// Sent after the first read, in order: a change can never land before the handed-over copy.
const send = (call: () => Promise<unknown>) => {
const send = (call: () => Promise<unknown>, creation?: TagCreation): Promise<boolean> => {
queue ??= writeQueue(load(), (e) => toast.fail({ title: t("useTags.saveFailed"), detail: e }), read);
void queue(call);
let saved = false;
return queue(async () => {
// The creation was queued first and has already reported any failure.
if (creation?.saved === false) return;
await call();
saved = true;
}).then(() => saved);
};
/** Shows the new lists and sends the profiles whose list changed. A profile a
* team does not let this person tag keeps its list, and the toast says why. */
const assign = (wanted: Record<string, string[]>, touched: Iterable<string>) => {
const assign = (wanted: Record<string, string[]>, touched: Iterable<string>, creation?: TagCreation) => {
const asked = [...touched];
const { refused, reason } = assignGuard(asked);
const byProfile = { ...wanted };
Expand All @@ -125,7 +157,9 @@ export const useTags = create<TagStore>((set, get) => {
const changes = changedLists(get().byProfile, byProfile, asked.filter((pid) => !refused.includes(pid)));
set({ byProfile });
// Ids read as it goes: a tag the team saved under another id is sent by that one.
if (Object.keys(changes).length) send(() => tagAssign(remapped(changes)));
const pending = new Map(creating);
const saved = Object.keys(changes).length ? send(() => tagAssign(remapped(changes, pending)), creation) : Promise.resolve(true);
return saved.then((ok) => ok && refused.length === 0);
};
/** A team's server answered a new tag with its own id: everything that names it follows. */
const settleId = (sent: Tag, saved: Tag | null | undefined) => {
Expand All @@ -136,6 +170,33 @@ export const useTags = create<TagStore>((set, get) => {
byProfile: Object.fromEntries(Object.entries(get().byProfile).map(([pid, ids]) => [pid, ids.map((x) => (x === sent.id ? saved.id : x))])),
});
};
const forgetTag = (id: string) => {
const byProfile: Record<string, string[]> = {};
for (const [pid, ids] of Object.entries(get().byProfile)) {
const kept = ids.filter((x) => x !== id);
if (kept.length) byProfile[pid] = kept;
}
set({ tags: get().tags.filter((t) => t.id !== id), byProfile });
};
const saveNewTag = (tag: Tag, at?: number): TagCreation => {
const epoch = spaceEpoch();
const here = () => epoch === undefined || epoch === spaceEpoch();
const creation: TagCreation = { saved: false };
creating.set(tag.id, creation);
// A team can return a different ID, which also follows its assignments.
void send(async () => {
const saved = await tagSave(tag, at);
if (!saved?.id) throw new Error(t("useTags.saveFailed"));
if (here()) settleId(tag, saved);
creation.saved = true;
}).then((saved) => {
if (creating.get(tag.id) !== creation) return;
// A fresh list may already have replaced the optimistic tag.
if (!saved && here() && get().tags.includes(tag)) forgetTag(tag.id);
creating.delete(tag.id);
});
return creation;
};
/** Why a team does not take this tag change, said once; null when it does. */
const refuse = (action: "create" | "edit" | "delete"): boolean => {
const why = teamRefusal(action);
Expand All @@ -158,8 +219,7 @@ export const useTags = create<TagStore>((set, get) => {
if (refuse("create")) return null;
const tag: Tag = { id: newId(), name: n, color: color ?? nextTagColor(get().tags) };
set({ tags: [...get().tags, tag] });
// A team lists its tags by name and may answer another id: the reply's is kept.
send(async () => settleId(tag, await tagSave(tag)));
saveNewTag(tag);
return tag;
},
rename: (id, name) => {
Expand All @@ -183,23 +243,19 @@ export const useTags = create<TagStore>((set, get) => {
},
remove: (id) => {
if (refuse("delete")) return;
const byProfile: Record<string, string[]> = {};
for (const [pid, ids] of Object.entries(get().byProfile)) {
const kept = ids.filter((x) => x !== id);
if (kept.length) byProfile[pid] = kept;
}
set({ tags: get().tags.filter((t) => t.id !== id), byProfile });
forgetTag(id);
send(() => tagDelete(id));
},
restoreTag: (tag, byProfile, at) => {
// A tag made since under its name takes its profiles: no two tags share a name.
const twin = get().tags.find((x) => x.id !== tag.id && same(x.name, tag.name));
let creation: TagCreation | undefined;
if (!twin) {
if (refuse("create")) return;
const tags = [...get().tags];
if (!tags.some((x) => x.id === tag.id)) tags.splice(at ?? tags.length, 0, tag);
set({ tags });
send(async () => settleId(tag, await tagSave(tag, at)));
creation = saveNewTag(tag, at);
}
const back = twin?.id ?? tag.id;
const merged = { ...get().byProfile };
Expand All @@ -209,18 +265,22 @@ export const useTags = create<TagStore>((set, get) => {
merged[pid] = [...new Set([...(merged[pid] ?? []), back])];
touched.push(pid);
}
assign(merged, touched);
assign(merged, touched, creation);
},
toggle: (profileIds, tagId) => {
const id = finalId(tagId);
const cur = get().byProfile;
const all = profileIds.every((pid) => cur[pid]?.includes(tagId));
const all = profileIds.every((pid) => cur[pid]?.includes(id));
const touched = all ? profileIds : profileIds.filter((pid) => !cur[pid]?.includes(id));
if (touched.length === 0) return null;
const byProfile = { ...cur };
for (const pid of profileIds) {
for (const pid of touched) {
const ids = cur[pid] ?? [];
const next = all ? ids.filter((x) => x !== tagId) : ids.includes(tagId) ? ids : [...ids, tagId];
const next = all ? ids.filter((x) => x !== id) : [...ids, id];
if (next.length) byProfile[pid] = next; else delete byProfile[pid];
}
assign(byProfile, profileIds);
const saved = assign(byProfile, touched, creating.get(id));
return { tagId: id, profileIds: touched, adding: !all, saved };
},
untag: (profileId, tagId) => {
const ids = (get().byProfile[profileId] ?? []).filter((x) => x !== tagId);
Expand Down
Loading