Skip to content

Commit f8822b6

Browse files
committed
Reorder apps in the sidebar by dragging, synced to the server
- Apps are dragged within their server in the sidebar (mouse after 5px, touch after a hold) or moved with Move up / Move down in their menu. - The order is gotify's own (sortKey, 2.9 and later): moving an app gives it a fractional key between its neighbors, like the web UI, through PUT /application/{id}. internal/fracdex is the server's copy of the keys. - Apps are stored with their sort key and listed in the server's order. A move fetches the apps first and runs while the supervisor's refresh of them cannot, so neither a new app's key nor an older refresh undoes it. - Servers before 2.9 keep no order; their apps can't be dragged.
1 parent 83fe155 commit f8822b6

24 files changed

Lines changed: 1098 additions & 46 deletions

‎frontend/bun.lock‎

Lines changed: 14 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎frontend/package.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,16 @@
1010
"test:messages": "bun scripts/messages-test.ts",
1111
"test:context-menu": "bun scripts/context-menu-test.ts",
1212
"test:selection": "bun scripts/selection-test.ts",
13+
"test:sidebar-order": "bun scripts/sidebar-order-test.ts",
1314
"screenshots": "node scripts/screenshots.ts"
1415
},
1516
"dependencies": {
1617
"@astryxdesign/core": "0.6.3",
1718
"@astryxdesign/theme-neutral": "0.6.3",
19+
"@dnd-kit/core": "6.3.1",
20+
"@dnd-kit/modifiers": "9.0.0",
21+
"@dnd-kit/sortable": "10.0.0",
22+
"@dnd-kit/utilities": "3.2.2",
1823
"@stylexjs/stylex": "0.19.1",
1924
"@tanstack/react-virtual": "3.14.13",
2025
"lucide-react": "1.48.0",
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
// Drags apps in the sidebar and moves them from their menu, against the
2+
// production preview over demo data, in Chrome through playwright-core.
3+
import assert from "node:assert/strict";
4+
import { execFileSync, spawn } from "node:child_process";
5+
import { mkdtempSync, rmSync } from "node:fs";
6+
import { tmpdir } from "node:os";
7+
import { dirname, join } from "node:path";
8+
import { createInterface } from "node:readline";
9+
import { fileURLToPath } from "node:url";
10+
import { chromium } from "playwright-core";
11+
12+
const root = join(dirname(fileURLToPath(import.meta.url)), "../..");
13+
const temp = mkdtempSync(join(tmpdir(), "gotify-sidebar-order-test-"));
14+
const binary = join(temp, process.platform === "win32" ? "preview.exe" : "preview");
15+
execFileSync("go", ["build", "-o", binary, "./cmd/preview"], { cwd: root });
16+
const preview = spawn(binary, ["-addr", "127.0.0.1:0"], { cwd: root, stdio: ["ignore", "pipe", "inherit"], windowsHide: true });
17+
const exited = new Promise<void>((resolve) => preview.once("exit", () => resolve()));
18+
let browser;
19+
try {
20+
const url = await new Promise<string>((resolve, reject) => {
21+
createInterface({ input: preview.stdout! }).once("line", resolve);
22+
preview.once("exit", () => reject(new Error("preview exited before listening")));
23+
});
24+
browser = await chromium.launch({
25+
executablePath: process.env.CHROME ?? (process.platform === "win32" ? "C:/Program Files/Google/Chrome/Application/chrome.exe" : "/usr/bin/google-chrome"),
26+
});
27+
const page = await browser.newPage({ viewport: { width: 1400, height: 800 } });
28+
const errors: string[] = [];
29+
page.on("pageerror", (error) => errors.push(error.message));
30+
await page.goto(url);
31+
await page.locator(".sidenav-app").first().waitFor();
32+
33+
// An app's name, from the label of its menu.
34+
const names = () =>
35+
[...document.querySelectorAll(".sidenav-app")].map((el) => el.querySelector("[aria-label$=' options']")?.getAttribute("aria-label")?.replace(/ options$/, ""));
36+
const order = () => page.evaluate(names);
37+
const row = (name: string) => page.locator(".sidenav-app").filter({ hasText: name });
38+
const settled = async (want: string[]) => {
39+
await page.waitForFunction(`JSON.stringify((${names})()) === ${JSON.stringify(JSON.stringify(want))}`);
40+
assert.deepEqual(
41+
await page.evaluate(async () => {
42+
const s = await (window as any).mygo.call("Desktop.State");
43+
return s.servers.flatMap((sv: any) => sv.apps.map((a: any) => a.name));
44+
}),
45+
want,
46+
"the backend's order",
47+
);
48+
};
49+
assert.deepEqual(await order(), ["Backup", "Monitoring", "Home Assistant", "CI", "Deploys"]);
50+
51+
// Drag Home Assistant above Backup.
52+
const from = (await row("Home Assistant").boundingBox())!;
53+
const to = (await row("Backup").boundingBox())!;
54+
await page.mouse.move(from.x + 40, from.y + from.height / 2);
55+
await page.mouse.down();
56+
await page.mouse.move(from.x + 40, from.y + from.height / 2 - 10, { steps: 3 });
57+
await page.mouse.move(from.x + 40, to.y + 4, { steps: 10 });
58+
await page.mouse.up();
59+
await settled(["Home Assistant", "Backup", "Monitoring", "CI", "Deploys"]);
60+
assert.ok(!page.url().includes("/a/3"), "the drag must not open the app");
61+
62+
// A click still opens it.
63+
await row("Monitoring").getByText("Monitoring", { exact: true }).click();
64+
await page.waitForURL(/#\/s\/1\/a\/2$/);
65+
66+
// Move down from the app's menu.
67+
await row("CI").getByRole("button", { name: "CI options" }).click();
68+
await page.getByRole("menuitem", { name: "Move down" }).click();
69+
await settled(["Home Assistant", "Backup", "Monitoring", "Deploys", "CI"]);
70+
await row("CI").getByRole("button", { name: "CI options" }).click();
71+
assert.equal(await page.getByRole("menuitem", { name: "Move down" }).getAttribute("aria-disabled"), "true", "the last app can't move down");
72+
await page.keyboard.press("Escape");
73+
74+
// Drag does not cross servers: Deploys stays in Work Gotify.
75+
const deploys = (await row("Deploys").boundingBox())!;
76+
const top = (await row("Home Assistant").boundingBox())!;
77+
await page.mouse.move(deploys.x + 40, deploys.y + deploys.height / 2);
78+
await page.mouse.down();
79+
await page.mouse.move(deploys.x + 40, deploys.y - 10, { steps: 3 });
80+
await page.mouse.move(deploys.x + 40, top.y + 4, { steps: 10 });
81+
await page.mouse.up();
82+
await settled(["Home Assistant", "Backup", "Monitoring", "Deploys", "CI"]);
83+
84+
// A finger drags after holding still; a swipe leaves the order alone.
85+
const touch = await (await browser.newContext({ viewport: { width: 1400, height: 800 }, hasTouch: true })).newPage();
86+
touch.on("pageerror", (error) => errors.push(error.message));
87+
await touch.goto(url);
88+
await touch.locator(".sidenav-app").first().waitFor();
89+
const cdp = await touch.context().newCDPSession(touch);
90+
const touchRow = (name: string) => touch.locator(".sidenav-app").filter({ hasText: name });
91+
const drag = async (name: string, to: string, hold: number) => {
92+
const box = (await touchRow(name).boundingBox())!;
93+
const x = box.x + 40;
94+
const y = box.y + box.height / 2;
95+
await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] });
96+
await touch.waitForTimeout(hold);
97+
const end = (await touchRow(to).boundingBox())!.y + 4;
98+
for (let i = 1; i <= 10; i++) {
99+
await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x, y: y + ((end - y) * i) / 10 }] });
100+
await touch.waitForTimeout(16);
101+
}
102+
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
103+
};
104+
const touchOrder = () => touch.evaluate(names);
105+
const before = await touchOrder();
106+
await drag("Backup", "CI", 0);
107+
await touch.waitForTimeout(300);
108+
assert.deepEqual(await touchOrder(), before, "a swipe must not reorder");
109+
await drag("Monitoring", "Backup", 400);
110+
await touch.waitForFunction(`JSON.stringify((${names})()) === ${JSON.stringify(JSON.stringify(["Home Assistant", "Monitoring", "Backup", "Deploys", "CI"]))}`);
111+
112+
assert.deepEqual(errors, []);
113+
console.log("sidebar order: ok");
114+
} finally {
115+
await browser?.close();
116+
preview.kill();
117+
await exited;
118+
rmSync(temp, { recursive: true, force: true });
119+
}

‎frontend/src/App.tsx‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,14 @@ export function App() {
153153
}
154154
})(),
155155
appPrefs: (sv: Server, a: GotifyApp) => setPrefs({ serverId: sv.id, appId: a.id }),
156+
moveApp: async (server, appId, beforeId) => {
157+
try {
158+
await Desktop.moveApp(server.id, appId, beforeId);
159+
await refreshState();
160+
} catch (err) {
161+
onError(t.couldNotMoveApp(errorText(err)));
162+
}
163+
},
156164
};
157165
const openAdd = () => setDialog({ kind: "add" });
158166

‎frontend/src/Sidebar.tsx‎

Lines changed: 96 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ import { MoreMenu } from "@astryxdesign/core/MoreMenu";
66
import { MobileNav } from "@astryxdesign/core/MobileNav";
77
import { SideNav, SideNavItem, SideNavSection } from "@astryxdesign/core/SideNav";
88
import { StatusDot } from "@astryxdesign/core/StatusDot";
9+
import { DndContext, MouseSensor, TouchSensor, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
10+
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
11+
import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
12+
import { CSS } from "@dnd-kit/utilities";
913
import { BellIcon, BellOffIcon, InboxIcon, PlusIcon, SettingsIcon } from "lucide-react";
14+
import { useState, type ReactNode } from "react";
1015
import type { App, Server, State } from "./mygo";
1116
import { useT, type Messages } from "./i18n";
1217
import { go as goTo, useAppImage, useNow, type Route } from "./store";
@@ -19,6 +24,8 @@ export interface ServerActions {
1924
/** Deletes the messages of an app, or of the server without one. */
2025
clear(sv: Server, app?: App): void;
2126
appPrefs(sv: Server, app: App): void;
27+
/** Moves an app before another, or last when beforeId is 0, and settles once the state shows it. */
28+
moveApp(sv: Server, appId: number, beforeId: number): Promise<void>;
2229
}
2330

2431
function count(n: number) {
@@ -55,6 +62,94 @@ export function AppAvatar({ serverId, app, size }: { serverId: number; app: App
5562
return <Avatar size={size} shape="rounded" name={app?.name || "?"} src={src} tooltip={false} />;
5663
}
5764

65+
/** An app's row, which the pointer drags to reorder the apps of its server. */
66+
function SortableApp({ id, disabled, children }: { id: number; disabled: boolean; children: ReactNode }) {
67+
const { setNodeRef, listeners, transform, transition, isDragging } = useSortable({ id, disabled });
68+
return (
69+
<div
70+
ref={setNodeRef}
71+
className={isDragging ? "sidenav-app dragging" : "sidenav-app"}
72+
style={{ transform: CSS.Translate.toString(transform), transition }}
73+
{...listeners}
74+
>
75+
{children}
76+
</div>
77+
);
78+
}
79+
80+
/** The apps of a server in their order; the pointer drags them, the menu moves them up and down. */
81+
function ServerApps({
82+
sv,
83+
actions,
84+
isSel,
85+
go,
86+
}: {
87+
sv: Server;
88+
actions: ServerActions;
89+
isSel(serverId: number, appId: number): boolean;
90+
go(r: Route): void;
91+
}) {
92+
const t = useT();
93+
// A moved app keeps its new place until the call settles, so it does not
94+
// jump back while the server answers.
95+
const [moving, setMoving] = useState<number[] | null>(null);
96+
// A small distance tells a drag from a click. A finger first holds still, so
97+
// that a swipe still scrolls the sidebar.
98+
const sensors = useSensors(
99+
useSensor(MouseSensor, { activationConstraint: { distance: 5 } }),
100+
useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),
101+
);
102+
const byId = new Map(sv.apps.map((a) => [a.id, a]));
103+
const apps = moving && moving.length === sv.apps.length && moving.every((id) => byId.has(id)) ? moving.map((id) => byId.get(id)!) : sv.apps;
104+
const ids = apps.map((a) => a.id);
105+
const move = (from: number, to: number) => {
106+
if (from === to || to < 0 || to >= ids.length) return;
107+
const next = arrayMove(ids, from, to);
108+
setMoving(next);
109+
void actions.moveApp(sv, ids[from]!, next[to + 1] ?? 0).finally(() => setMoving(null));
110+
};
111+
const onDragEnd = ({ active, over }: DragEndEvent) => {
112+
if (over) move(ids.indexOf(Number(active.id)), ids.indexOf(Number(over.id)));
113+
};
114+
const sortable = sv.appsSortable && moving === null;
115+
return (
116+
<DndContext sensors={sensors} modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
117+
<SortableContext items={ids} strategy={verticalListSortingStrategy} disabled={!sortable}>
118+
{apps.map((a, i) => (
119+
<SortableApp key={a.id} id={a.id} disabled={!sortable}>
120+
<SideNavItem
121+
label={a.name}
122+
icon={<AppAvatar serverId={sv.id} app={a} size="xsm" />}
123+
isSelected={isSel(sv.id, a.id)}
124+
onClick={() => go({ page: "messages", serverId: sv.id, appId: a.id })}
125+
endContent={a.muted ? <Icon icon={BellOffIcon} size="sm" color="secondary" label={t.muted} /> : count(a.unread)}
126+
actions={
127+
<MoreMenu
128+
size="sm"
129+
label={t.appOptions(a.name)}
130+
items={[
131+
{ label: t.notificationSettings, onClick: () => actions.appPrefs(sv, a) },
132+
{ label: t.markAllRead, onClick: () => actions.markAllRead(sv.id, a.id), isDisabled: a.unread === 0 },
133+
...(sv.appsSortable
134+
? [
135+
{ type: "divider" as const },
136+
{ label: t.moveUp, onClick: () => move(i, i - 1), isDisabled: !sortable || i === 0 },
137+
{ label: t.moveDown, onClick: () => move(i, i + 1), isDisabled: !sortable || i === apps.length - 1 },
138+
]
139+
: []),
140+
{ type: "divider" },
141+
{ label: t.clearMessages, variant: "destructive", onClick: () => actions.clear(sv, a) },
142+
]}
143+
/>
144+
}
145+
/>
146+
</SortableApp>
147+
))}
148+
</SortableContext>
149+
</DndContext>
150+
);
151+
}
152+
58153
function SidebarTop() {
59154
const t = useT();
60155
return (
@@ -146,28 +241,7 @@ export function Sidebar({
146241
/>
147242
}
148243
/>
149-
{sv.apps.map((a) => (
150-
<SideNavItem
151-
key={a.id}
152-
label={a.name}
153-
icon={<AppAvatar serverId={sv.id} app={a} size="xsm" />}
154-
isSelected={isSel(sv.id, a.id)}
155-
onClick={() => go({ page: "messages", serverId: sv.id, appId: a.id })}
156-
endContent={a.muted ? <Icon icon={BellOffIcon} size="sm" color="secondary" label={t.muted} /> : count(a.unread)}
157-
actions={
158-
<MoreMenu
159-
size="sm"
160-
label={t.appOptions(a.name)}
161-
items={[
162-
{ label: t.notificationSettings, onClick: () => actions.appPrefs(sv, a) },
163-
{ label: t.markAllRead, onClick: () => actions.markAllRead(sv.id, a.id), isDisabled: a.unread === 0 },
164-
{ type: "divider" },
165-
{ label: t.clearMessages, variant: "destructive", onClick: () => actions.clear(sv, a) },
166-
]}
167-
/>
168-
}
169-
/>
170-
))}
244+
<ServerApps sv={sv} actions={actions} isSel={isSel} go={go} />
171245
</SideNavSection>
172246
))}
173247
</>

‎frontend/src/app.css‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,12 @@ html[data-material="sidebar"] .astryx-app-shell [role="main"] {
279279
border-bottom: 1px solid var(--color-border);
280280
}
281281

282+
/* An app's row while the pointer drags it over the others. */
283+
.sidenav-app.dragging {
284+
position: relative;
285+
z-index: 1;
286+
}
287+
282288
/* The image of a message (bigImageUrl), at its own proportions, no wider than
283289
the card nor taller than 360px. align-self keeps the column from stretching it. */
284290
.msg-image {

‎frontend/src/i18n.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ const en = {
2020
removeServer: "Remove server…",
2121
clearMessages: "Delete all messages…",
2222
notificationSettings: "Notification settings…",
23+
moveUp: "Move up",
24+
moveDown: "Move down",
2325
muted: "Muted",
2426

2527
connected: "Connected",
@@ -101,6 +103,7 @@ const en = {
101103
removeText: "Its messages are deleted from this computer and this device signs out of the server.",
102104
removeAction: "Remove server",
103105
couldNotRemove: (e: string) => `Couldn't remove the server: ${e}`,
106+
couldNotMoveApp: (e: string) => `Couldn't move the app: ${e}`,
104107

105108
clearAppTitle: (name: string) => `Delete all messages of “${name}”?`,
106109
clearServerTitle: (name: string) => `Delete all messages on “${name}”?`,
@@ -175,6 +178,8 @@ const zh: Messages = {
175178
removeServer: "移除服务器…",
176179
clearMessages: "删除全部消息…",
177180
notificationSettings: "通知设置…",
181+
moveUp: "上移",
182+
moveDown: "下移",
178183
muted: "已静音",
179184

180185
connected: "已连接",
@@ -256,6 +261,7 @@ const zh: Messages = {
256261
removeText: "这台电脑上它的消息会被删除,并且此设备会从该服务器注销。",
257262
removeAction: "移除服务器",
258263
couldNotRemove: (e) => `无法移除服务器:${e}`,
264+
couldNotMoveApp: (e) => `无法移动应用:${e}`,
259265

260266
clearAppTitle: (name) => `删除“${name}”的全部消息?`,
261267
clearServerTitle: (name) => `删除“${name}”上的全部消息?`,

‎frontend/src/mygo.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,8 @@ export interface Server {
139139
/** RetryAt is when a server in backoff tries again. */
140140
retryAt: string | null;
141141
apps: App[];
142+
/** AppsSortable is whether MoveApp can reorder the apps (gotify 2.9 and later). */
143+
appsSortable: boolean;
142144
unread: number;
143145
}
144146

@@ -250,6 +252,13 @@ export const Desktop = {
250252
messages(q: Query): Promise<MessagePage> {
251253
return call("Desktop.Messages", q);
252254
},
255+
/**
256+
* MoveApp moves an app of a server before another, or last when beforeAppID
257+
* is 0, in the order the server keeps for the apps.
258+
*/
259+
moveApp(serverID: number, appID: number, beforeAppID: number): Promise<void> {
260+
return call("Desktop.MoveApp", serverID, appID, beforeAppID);
261+
},
253262
/** OpenURL opens an http(s) or mailto URL in the default app. */
254263
openURL(raw: string): Promise<void> {
255264
return call("Desktop.OpenURL", raw);

0 commit comments

Comments
 (0)