Fully custom titlebar, search status/sort filters, and import by link

- Replace Window Controls Overlay with a fully frameless window and
  custom minimize/maximize/close buttons, since even the native
  overlay always paints a flat rect that can't blend into this app's
  gradient/glass backgrounds. Sidebar and content now reach the true
  top of the window instead of leaving a reserved gap.
- Add ranked-status filter chips (ranked/qualified/loved/pending/wip/
  graveyard/approved) and a sort dropdown (favourites, plays,
  difficulty, newest/oldest) to Find maps, backed by real Favourites/
  Playcount fields confirmed present on catboy.best's API.
- Add "Import by link": paste an osu! beatmapset URL or bare numeric
  ID to fetch and install it directly, without a text search.
This commit is contained in:
pvrzz
2026-09-17 21:26:12 -04:00
parent 211025f840
commit 902e59f974
14 changed files with 406 additions and 31 deletions
+6 -1
View File
@@ -39,6 +39,7 @@ export interface DirectifyIpcApi {
restoreBackup(zipPath: string): Promise<void>; restoreBackup(zipPath: string): Promise<void>;
searchBeatmaps(query: BeatmapSearchQuery): Promise<BeatmapSearchResult>; searchBeatmaps(query: BeatmapSearchQuery): Promise<BeatmapSearchResult>;
getBeatmapSetById(beatmapSetId: number): Promise<BeatmapSet | null>;
installBeatmapSet(set: BeatmapSet): Promise<void>; installBeatmapSet(set: BeatmapSet): Promise<void>;
readCollections(): Promise<CollectionDatabase>; readCollections(): Promise<CollectionDatabase>;
@@ -47,5 +48,9 @@ export interface DirectifyIpcApi {
checkForUpdate(): Promise<UpdateCheckResult>; checkForUpdate(): Promise<UpdateCheckResult>;
openExternal(url: string): Promise<void>; openExternal(url: string): Promise<void>;
setTitleBarOverlay(colors: { color: string; symbolColor: string }): Promise<void>; minimizeWindow(): Promise<void>;
toggleMaximizeWindow(): Promise<void>;
closeWindow(): Promise<void>;
isWindowMaximized(): Promise<boolean>;
onWindowMaximizedChange(callback: (maximized: boolean) => void): () => void;
} }
+22 -13
View File
@@ -22,7 +22,11 @@ import {
import { applyProxySettings } from "./network.js"; import { applyProxySettings } from "./network.js";
import { collectionDbPath, detectOsuInstallDir, isValidOsuInstallDir } from "./osu-install.js"; import { collectionDbPath, detectOsuInstallDir, isValidOsuInstallDir } from "./osu-install.js";
import { loadSettings, saveSettings, type AppSettings } from "./settings.js"; import { loadSettings, saveSettings, type AppSettings } from "./settings.js";
import { resolveDownloadUrlForResult, searchWithFallback } from "./source-registry.js"; import {
getBeatmapSetByIdWithFallback,
resolveDownloadUrlForResult,
searchWithFallback,
} from "./source-registry.js";
import { checkForUpdate } from "./updates.js"; import { checkForUpdate } from "./updates.js";
const ALLOWED_EXTERNAL_HOSTS = ["github.com", "www.github.com"]; const ALLOWED_EXTERNAL_HOSTS = ["github.com", "www.github.com"];
@@ -82,6 +86,9 @@ function registerIpcHandlers(): void {
ipcMain.handle("beatmaps:search", (_e, query: BeatmapSearchQuery) => ipcMain.handle("beatmaps:search", (_e, query: BeatmapSearchQuery) =>
searchWithFallback(loadSettings().searchSources, query) searchWithFallback(loadSettings().searchSources, query)
); );
ipcMain.handle("beatmaps:getById", (_e, beatmapSetId: number) =>
getBeatmapSetByIdWithFallback(loadSettings().searchSources, beatmapSetId)
);
ipcMain.handle("beatmaps:install", async (_e, set: BeatmapSet) => { ipcMain.handle("beatmaps:install", async (_e, set: BeatmapSet) => {
const downloadUrl = await resolveDownloadUrlForResult( const downloadUrl = await resolveDownloadUrlForResult(
loadSettings().searchSources, loadSettings().searchSources,
@@ -111,9 +118,14 @@ function registerIpcHandlers(): void {
await writeFile(path, writeCollectionDb(db)); await writeFile(path, writeCollectionDb(db));
}); });
ipcMain.handle("window:setTitleBarOverlay", (_e, colors: { color: string; symbolColor: string }) => { ipcMain.handle("window:minimize", () => mainWindow?.minimize());
mainWindow?.setTitleBarOverlay({ ...colors, height: 40 }); ipcMain.handle("window:toggleMaximize", () => {
if (!mainWindow) return;
if (mainWindow.isMaximized()) mainWindow.unmaximize();
else mainWindow.maximize();
}); });
ipcMain.handle("window:close", () => mainWindow?.close());
ipcMain.handle("window:isMaximized", () => mainWindow?.isMaximized() ?? false);
ipcMain.handle("app:checkForUpdate", () => checkForUpdate(app.getVersion())); ipcMain.handle("app:checkForUpdate", () => checkForUpdate(app.getVersion()));
ipcMain.handle("app:openExternal", (_e, url: string) => { ipcMain.handle("app:openExternal", (_e, url: string) => {
@@ -137,16 +149,11 @@ function createWindow(): void {
height: 800, height: 800,
backgroundColor: "#171a1c", backgroundColor: "#171a1c",
icon: resolveIconPath(), icon: resolveIconPath(),
// Hides the default titlebar/menu chrome but keeps real, natively-drawn // Fully custom titlebar: the native one (and Windows' Window Controls
// minimize/maximize/close buttons (Windows' Window Controls Overlay) — // Overlay, which always paints a flat-color rect behind its buttons)
// the renderer supplies its own draggable title strip and re-colors the // can't blend into this app's gradient/glass backgrounds. The renderer
// overlay to match the active theme via window:setTitleBarOverlay. // draws its own drag strip and minimize/maximize/close buttons instead.
titleBarStyle: "hidden", frame: false,
titleBarOverlay: {
color: "#171a1c",
symbolColor: "#f4f2f7",
height: 40,
},
webPreferences: { webPreferences: {
preload: join(__dirname, "../preload/index.js"), preload: join(__dirname, "../preload/index.js"),
contextIsolation: true, contextIsolation: true,
@@ -158,6 +165,8 @@ function createWindow(): void {
win.on("closed", () => { win.on("closed", () => {
if (mainWindow === win) mainWindow = null; if (mainWindow === win) mainWindow = null;
}); });
win.on("maximize", () => win.webContents.send("window:maximizedChange", true));
win.on("unmaximize", () => win.webContents.send("window:maximizedChange", false));
if (process.env.ELECTRON_RENDERER_URL) { if (process.env.ELECTRON_RENDERER_URL) {
win.loadURL(process.env.ELECTRON_RENDERER_URL); win.loadURL(process.env.ELECTRON_RENDERER_URL);
+29 -1
View File
@@ -5,7 +5,12 @@
// goes back to the specific mirror a result came from — each mirror has its // goes back to the specific mirror a result came from — each mirror has its
// own independent id space, so a numeric id from one can't be assumed to // own independent id space, so a numeric id from one can't be assumed to
// exist, let alone mean the same thing, on another. // exist, let alone mean the same thing, on another.
import type { BeatmapSearchQuery, BeatmapSearchResult, BeatmapSourceConfig } from "@directify/shared"; import type {
BeatmapSearchQuery,
BeatmapSearchResult,
BeatmapSet,
BeatmapSourceConfig,
} from "@directify/shared";
import { MirrorSource } from "./sources/mirror-source.js"; import { MirrorSource } from "./sources/mirror-source.js";
const MIN_REQUEST_INTERVAL_MS = 350; const MIN_REQUEST_INTERVAL_MS = 350;
@@ -43,6 +48,29 @@ export async function searchWithFallback(
throw lastError instanceof Error ? lastError : new Error("All beatmap sources failed."); throw lastError instanceof Error ? lastError : new Error("All beatmap sources failed.");
} }
export async function getBeatmapSetByIdWithFallback(
sources: BeatmapSourceConfig[],
beatmapSetId: number
): Promise<BeatmapSet | null> {
const candidates = enabledInOrder(sources);
if (candidates.length === 0) {
throw new Error("No beatmap search sources are enabled.");
}
let lastError: unknown;
for (const config of candidates) {
try {
await throttle(config.id);
const set = await new MirrorSource(config).getBeatmapSet(beatmapSetId);
if (set) return set;
} catch (err) {
lastError = err;
}
}
if (lastError) throw lastError instanceof Error ? lastError : new Error("All beatmap sources failed.");
return null;
}
export async function resolveDownloadUrlForResult( export async function resolveDownloadUrlForResult(
sources: BeatmapSourceConfig[], sources: BeatmapSourceConfig[],
sourceName: string, sourceName: string,
@@ -11,6 +11,7 @@ import type {
BeatmapSearchQuery, BeatmapSearchQuery,
BeatmapSearchResult, BeatmapSearchResult,
BeatmapSet, BeatmapSet,
BeatmapSortOption,
OsuMode, OsuMode,
RankedStatus, RankedStatus,
} from "@directify/shared"; } from "@directify/shared";
@@ -58,6 +59,7 @@ interface MirrorSearchBeatmap {
OD: number; OD: number;
HP: number; HP: number;
FileMD5: string; FileMD5: string;
Playcount?: number;
} }
interface MirrorSearchResult { interface MirrorSearchResult {
@@ -71,6 +73,7 @@ interface MirrorSearchResult {
Genre?: { ID: number; Name: string }; Genre?: { ID: number; Name: string };
Language?: { ID: number; Name: string }; Language?: { ID: number; Name: string };
ChildrenBeatmaps: MirrorSearchBeatmap[]; ChildrenBeatmaps: MirrorSearchBeatmap[];
Favourites?: number;
} }
function coverUrl(setId: number): string { function coverUrl(setId: number): string {
@@ -81,6 +84,35 @@ function previewUrl(setId: number): string {
return `https://b.ppy.sh/preview/${setId}.mp3`; return `https://b.ppy.sh/preview/${setId}.mp3`;
} }
function maxDifficulty(set: BeatmapSet): number {
return set.beatmaps.reduce((max, b) => Math.max(max, b.difficultyRating), 0);
}
// The search API returns results in the mirror's own relevance order, which
// is left untouched unless the user explicitly asked for something else.
function sortResults(results: BeatmapSet[], sort: BeatmapSortOption | undefined): void {
switch (sort) {
case "favourites":
results.sort((a, b) => (b.favouriteCount ?? 0) - (a.favouriteCount ?? 0));
break;
case "plays":
results.sort((a, b) => (b.playCount ?? 0) - (a.playCount ?? 0));
break;
case "difficulty-desc":
results.sort((a, b) => maxDifficulty(b) - maxDifficulty(a));
break;
case "difficulty-asc":
results.sort((a, b) => maxDifficulty(a) - maxDifficulty(b));
break;
case "newest":
results.sort((a, b) => Date.parse(b.submittedAt) - Date.parse(a.submittedAt));
break;
case "oldest":
results.sort((a, b) => Date.parse(a.submittedAt) - Date.parse(b.submittedAt));
break;
}
}
export class MirrorSource implements BeatmapSource { export class MirrorSource implements BeatmapSource {
readonly id: string; readonly id: string;
readonly name: string; readonly name: string;
@@ -123,6 +155,8 @@ export class MirrorSource implements BeatmapSource {
updatedAt: raw.LastUpdate, updatedAt: raw.LastUpdate,
beatmaps, beatmaps,
source: this.name, source: this.name,
favouriteCount: raw.Favourites,
playCount: raw.ChildrenBeatmaps.reduce((sum, b) => sum + (b.Playcount ?? 0), 0),
}; };
} }
@@ -173,6 +207,8 @@ export class MirrorSource implements BeatmapSource {
return true; return true;
}); });
sortResults(results, query.sort);
return { results, page, pageSize, total: results.length }; return { results, page, pageSize, total: results.length };
} }
@@ -210,6 +246,8 @@ export class MirrorSource implements BeatmapSource {
updatedAt: raw.last_updated ?? "", updatedAt: raw.last_updated ?? "",
beatmaps, beatmaps,
source: this.name, source: this.name,
favouriteCount: raw.favourite_count,
playCount: raw.play_count,
}; };
} }
+10 -1
View File
@@ -19,6 +19,7 @@ const api: DirectifyIpcApi = {
restoreBackup: (zipPath) => ipcRenderer.invoke("backup:restore", zipPath), restoreBackup: (zipPath) => ipcRenderer.invoke("backup:restore", zipPath),
searchBeatmaps: (query) => ipcRenderer.invoke("beatmaps:search", query), searchBeatmaps: (query) => ipcRenderer.invoke("beatmaps:search", query),
getBeatmapSetById: (beatmapSetId) => ipcRenderer.invoke("beatmaps:getById", beatmapSetId),
installBeatmapSet: (set) => ipcRenderer.invoke("beatmaps:install", set), installBeatmapSet: (set) => ipcRenderer.invoke("beatmaps:install", set),
readCollections: () => ipcRenderer.invoke("collections:read"), readCollections: () => ipcRenderer.invoke("collections:read"),
@@ -27,7 +28,15 @@ const api: DirectifyIpcApi = {
checkForUpdate: () => ipcRenderer.invoke("app:checkForUpdate"), checkForUpdate: () => ipcRenderer.invoke("app:checkForUpdate"),
openExternal: (url) => ipcRenderer.invoke("app:openExternal", url), openExternal: (url) => ipcRenderer.invoke("app:openExternal", url),
setTitleBarOverlay: (colors) => ipcRenderer.invoke("window:setTitleBarOverlay", colors), minimizeWindow: () => ipcRenderer.invoke("window:minimize"),
toggleMaximizeWindow: () => ipcRenderer.invoke("window:toggleMaximize"),
closeWindow: () => ipcRenderer.invoke("window:close"),
isWindowMaximized: () => ipcRenderer.invoke("window:isMaximized"),
onWindowMaximizedChange: (callback) => {
const listener = (_e: unknown, maximized: boolean) => callback(maximized);
ipcRenderer.on("window:maximizedChange", listener);
return () => ipcRenderer.removeListener("window:maximizedChange", listener);
},
}; };
contextBridge.exposeInMainWorld("directify", api); contextBridge.exposeInMainWorld("directify", api);
+9 -8
View File
@@ -13,6 +13,7 @@ import { SettingsPage } from "./pages/SettingsPage";
import { useSettings } from "./settings-context"; import { useSettings } from "./settings-context";
import { ShortcutsHelp } from "./ShortcutsHelp"; import { ShortcutsHelp } from "./ShortcutsHelp";
import { UpdateBanner } from "./UpdateBanner"; import { UpdateBanner } from "./UpdateBanner";
import { WindowControls } from "./WindowControls";
import type { UpdateCheckResult } from "../../main/updates"; import type { UpdateCheckResult } from "../../main/updates";
const SHORTCUT_ROUTES = ["/", "/search", "/collections", "/backup", "/settings"]; const SHORTCUT_ROUTES = ["/", "/search", "/collections", "/backup", "/settings"];
@@ -61,11 +62,6 @@ export function App() {
function applyTheme(resolved: "dark" | "light") { function applyTheme(resolved: "dark" | "light") {
root.dataset.theme = resolved; root.dataset.theme = resolved;
window.directify.setTitleBarOverlay(
resolved === "dark"
? { color: "#171a1c", symbolColor: "#f4f2f7" }
: { color: "#f4f5f6", symbolColor: "#171a1c" }
);
} }
if (settings.theme === "system") { if (settings.theme === "system") {
@@ -101,12 +97,17 @@ export function App() {
<div <div
style={ style={
{ {
height: 40, position: "fixed",
flexShrink: 0, top: 0,
left: 0,
right: 0,
height: 32,
zIndex: 90,
WebkitAppRegion: "drag", WebkitAppRegion: "drag",
} as React.CSSProperties } as React.CSSProperties
} }
/> />
<WindowControls />
{updateInfo?.hasUpdate && updateInfo.latestVersion && updateInfo.releaseUrl && ( {updateInfo?.hasUpdate && updateInfo.latestVersion && updateInfo.releaseUrl && (
<UpdateBanner <UpdateBanner
latestVersion={updateInfo.latestVersion} latestVersion={updateInfo.latestVersion}
@@ -119,7 +120,7 @@ export function App() {
aria-label="Primary" aria-label="Primary"
style={{ style={{
width: 220, width: 220,
padding: "24px 12px", padding: "36px 12px 24px",
borderRight: "1px solid var(--df-border)", borderRight: "1px solid var(--df-border)",
background: "var(--df-glass-bg)", background: "var(--df-glass-bg)",
backdropFilter: "var(--df-glass-blur)", backdropFilter: "var(--df-glass-blur)",
@@ -19,6 +19,9 @@ export function UpdateBanner({
initial={{ opacity: 0, y: -12 }} initial={{ opacity: 0, y: -12 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
style={{ style={{
// Below the app's fixed title/window-controls strip (32px), so this
// banner's own buttons don't collide with it.
marginTop: 32,
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "space-between", justifyContent: "space-between",
@@ -0,0 +1,91 @@
// Custom titlebar buttons: Electron's native title bar (and even the Windows
// "Window Controls Overlay" API) always paints a flat, opaque rect behind
// itself, which can't blend into this app's gradient/glass backgrounds — so
// minimize/maximize/close are drawn here instead, themed to match.
import { useEffect, useState } from "react";
function WindowButton({
label,
onClick,
danger,
children,
}: {
label: string;
onClick: () => void;
danger?: boolean;
children: React.ReactNode;
}) {
return (
<button
aria-label={label}
onClick={onClick}
style={
{
WebkitAppRegion: "no-drag",
width: 46,
height: 32,
display: "flex",
alignItems: "center",
justifyContent: "center",
background: "transparent",
border: "none",
color: "var(--df-text-muted)",
cursor: "pointer",
} as React.CSSProperties
}
onMouseEnter={(e) => {
e.currentTarget.style.background = danger ? "#e81123" : "var(--df-surface-3)";
e.currentTarget.style.color = danger ? "#ffffff" : "var(--df-text)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = "transparent";
e.currentTarget.style.color = "var(--df-text-muted)";
}}
>
{children}
</button>
);
}
export function WindowControls() {
const [maximized, setMaximized] = useState(false);
useEffect(() => {
window.directify.isWindowMaximized().then(setMaximized);
return window.directify.onWindowMaximizedChange(setMaximized);
}, []);
return (
<div style={{ display: "flex", position: "fixed", top: 0, right: 0, zIndex: 100 }}>
<WindowButton label="Minimize" onClick={() => window.directify.minimizeWindow()}>
<svg width="10" height="10" viewBox="0 0 10 10">
<path d="M0 5h10" stroke="currentColor" strokeWidth="1" />
</svg>
</WindowButton>
<WindowButton
label={maximized ? "Restore" : "Maximize"}
onClick={() => window.directify.toggleMaximizeWindow()}
>
{maximized ? (
<svg width="10" height="10" viewBox="0 0 10 10">
<path
d="M2 0h8v8h-2M0 2h8v8H0z"
fill="none"
stroke="currentColor"
strokeWidth="1"
/>
</svg>
) : (
<svg width="10" height="10" viewBox="0 0 10 10">
<rect x="0.5" y="0.5" width="9" height="9" fill="none" stroke="currentColor" strokeWidth="1" />
</svg>
)}
</WindowButton>
<WindowButton label="Close" danger onClick={() => window.directify.closeWindow()}>
<svg width="10" height="10" viewBox="0 0 10 10">
<path d="M0 0l10 10M10 0L0 10" stroke="currentColor" strokeWidth="1" />
</svg>
</WindowButton>
</div>
);
}
+16 -1
View File
@@ -36,7 +36,22 @@
"genre": "Genre", "genre": "Genre",
"language": "Language", "language": "Language",
"any": "Any", "any": "Any",
"starRating": "Star rating" "all": "All",
"starRating": "Star rating",
"status": "Status",
"sortBy": "Sort by",
"sortRelevance": "Relevance",
"sortFavourites": "Most favourited",
"sortPlays": "Most played",
"sortDifficultyDesc": "Difficulty: high to low",
"sortDifficultyAsc": "Difficulty: low to high",
"sortNewest": "Newest",
"sortOldest": "Oldest",
"importByLink": "Import by link",
"importByLinkPlaceholder": "Paste a beatmap link or ID...",
"importButton": "Import",
"importNotFound": "Couldn't find a beatmapset at that link.",
"importInvalidLink": "That doesn't look like a beatmap link or ID."
}, },
"collections": { "collections": {
"title": "Collections", "title": "Collections",
+16 -1
View File
@@ -36,7 +36,22 @@
"genre": "Género", "genre": "Género",
"language": "Idioma", "language": "Idioma",
"any": "Cualquiera", "any": "Cualquiera",
"starRating": "Dificultad (estrellas)" "all": "Todos",
"starRating": "Dificultad (estrellas)",
"status": "Estado",
"sortBy": "Ordenar por",
"sortRelevance": "Relevancia",
"sortFavourites": "Más favoritos",
"sortPlays": "Más jugados",
"sortDifficultyDesc": "Dificultad: mayor a menor",
"sortDifficultyAsc": "Dificultad: menor a mayor",
"sortNewest": "Más recientes",
"sortOldest": "Más antiguos",
"importByLink": "Importar por enlace",
"importByLinkPlaceholder": "Pega un enlace o ID de beatmap...",
"importButton": "Importar",
"importNotFound": "No se encontró ningún beatmapset en ese enlace.",
"importInvalidLink": "Eso no parece un enlace o ID de beatmap válido."
}, },
"collections": { "collections": {
"title": "Colecciones", "title": "Colecciones",
+16 -1
View File
@@ -35,7 +35,22 @@
"genre": "ジャンル", "genre": "ジャンル",
"language": "言語", "language": "言語",
"any": "指定なし", "any": "指定なし",
"starRating": "スター難易度" "all": "すべて",
"starRating": "スター難易度",
"status": "ステータス",
"sortBy": "並び替え",
"sortRelevance": "関連度",
"sortFavourites": "お気に入り数",
"sortPlays": "プレイ数",
"sortDifficultyDesc": "難易度: 高い順",
"sortDifficultyAsc": "難易度: 低い順",
"sortNewest": "新しい順",
"sortOldest": "古い順",
"importByLink": "リンクからインポート",
"importByLinkPlaceholder": "譜面のリンクまたはIDを貼り付け...",
"importButton": "インポート",
"importNotFound": "そのリンクの譜面セットが見つかりませんでした。",
"importInvalidLink": "有効な譜面リンクまたはIDではないようです。"
}, },
"collections": { "collections": {
"title": "コレクション", "title": "コレクション",
@@ -185,6 +185,7 @@ export function installMockDirectifyIfNeeded(): void {
pageSize: 30, pageSize: 30,
total: 2, total: 2,
}), }),
getBeatmapSetById: async () => null,
installBeatmapSet: async () => {}, installBeatmapSet: async () => {},
readCollections: async () => collections, readCollections: async () => collections,
@@ -197,7 +198,11 @@ export function installMockDirectifyIfNeeded(): void {
window.open(url, "_blank"); window.open(url, "_blank");
}, },
setTitleBarOverlay: async () => {}, minimizeWindow: async () => {},
toggleMaximizeWindow: async () => {},
closeWindow: async () => {},
isWindowMaximized: async () => false,
onWindowMaximizedChange: () => () => {},
}; };
window.directify = mock; window.directify = mock;
@@ -1,5 +1,12 @@
// Find-maps page: osu!lazer-style search — free text plus mode, key count, genre, language, and star-rating filters — against the active (fallback-chain) beatmap source. // Find-maps page: osu!lazer-style search — free text plus mode, key count, genre, language, status, star-rating, and sort filters — against the active (fallback-chain) beatmap source. Also supports pasting a beatmapset link/ID to fetch it directly.
import { GENRES, LANGUAGES, type BeatmapSet, type OsuMode } from "@directify/shared"; import {
GENRES,
LANGUAGES,
type BeatmapSet,
type BeatmapSortOption,
type OsuMode,
type RankedStatus,
} from "@directify/shared";
import { Button, Card, DualRangeSlider, Icon, StatusBadge, TextInput } from "@directify/ui"; import { Button, Card, DualRangeSlider, Icon, StatusBadge, TextInput } from "@directify/ui";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -14,6 +21,47 @@ const MODES: { value: OsuMode | ""; label: string }[] = [
const MANIA_KEY_COUNTS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const MANIA_KEY_COUNTS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const STATUSES: RankedStatus[] = [
"ranked",
"qualified",
"loved",
"pending",
"wip",
"graveyard",
"approved",
];
const SORT_OPTIONS: BeatmapSortOption[] = [
"relevance",
"favourites",
"plays",
"difficulty-desc",
"difficulty-asc",
"newest",
"oldest",
];
const SORT_LABEL_KEY: Record<BeatmapSortOption, string> = {
relevance: "search.sortRelevance",
favourites: "search.sortFavourites",
plays: "search.sortPlays",
"difficulty-desc": "search.sortDifficultyDesc",
"difficulty-asc": "search.sortDifficultyAsc",
newest: "search.sortNewest",
oldest: "search.sortOldest",
};
/** Pulls a beatmapset id out of an osu!/mirror URL, or a bare numeric id typed/pasted directly. */
function parseBeatmapSetId(input: string): number | null {
const trimmed = input.trim();
if (/^\d+$/.test(trimmed)) return Number(trimmed);
const match = trimmed.match(/beatmapsets\/(\d+)/);
if (match) return Number(match[1]);
return null;
}
function chipStyle(active: boolean): React.CSSProperties { function chipStyle(active: boolean): React.CSSProperties {
return { return {
padding: "6px 12px", padding: "6px 12px",
@@ -46,11 +94,15 @@ export function SearchPage() {
const [keys, setKeys] = useState<number | null>(null); const [keys, setKeys] = useState<number | null>(null);
const [genre, setGenre] = useState<number | "">(""); const [genre, setGenre] = useState<number | "">("");
const [language, setLanguage] = useState<number | "">(""); const [language, setLanguage] = useState<number | "">("");
const [rankedStatus, setRankedStatus] = useState<RankedStatus | "">("");
const [sort, setSort] = useState<BeatmapSortOption>("relevance");
const [starRange, setStarRange] = useState<[number, number]>([0, 10]); const [starRange, setStarRange] = useState<[number, number]>([0, 10]);
const [results, setResults] = useState<BeatmapSet[]>([]); const [results, setResults] = useState<BeatmapSet[]>([]);
const [status, setStatus] = useState(""); const [status, setStatus] = useState("");
const [installing, setInstalling] = useState<number | null>(null); const [installing, setInstalling] = useState<number | null>(null);
const [importLink, setImportLink] = useState("");
const [importing, setImporting] = useState(false);
const debounceRef = useRef<ReturnType<typeof setTimeout>>(); const debounceRef = useRef<ReturnType<typeof setTimeout>>();
async function search() { async function search() {
@@ -62,6 +114,8 @@ export function SearchPage() {
keys: mode === "mania" && keys ? keys : undefined, keys: mode === "mania" && keys ? keys : undefined,
genre: genre === "" ? undefined : genre, genre: genre === "" ? undefined : genre,
language: language === "" ? undefined : language, language: language === "" ? undefined : language,
status: rankedStatus || undefined,
sort,
minStars: starRange[0] > 0 ? starRange[0] : undefined, minStars: starRange[0] > 0 ? starRange[0] : undefined,
maxStars: starRange[1] < 10 ? starRange[1] : undefined, maxStars: starRange[1] < 10 ? starRange[1] : undefined,
page: 1, page: 1,
@@ -82,7 +136,32 @@ export function SearchPage() {
debounceRef.current = setTimeout(search, 450); debounceRef.current = setTimeout(search, 450);
return () => clearTimeout(debounceRef.current); return () => clearTimeout(debounceRef.current);
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [query, mode, keys, genre, language, starRange[0], starRange[1]]); }, [query, mode, keys, genre, language, rankedStatus, sort, starRange[0], starRange[1]]);
async function importByLink() {
const beatmapSetId = parseBeatmapSetId(importLink);
if (!beatmapSetId) {
setStatus(t("search.importInvalidLink"));
return;
}
setImporting(true);
setStatus(t("common.loading"));
try {
const set = await window.directify.getBeatmapSetById(beatmapSetId);
if (!set) {
setStatus(t("search.importNotFound"));
return;
}
setResults([set]);
setStatus(t("search.resultCount", { count: 1 }));
setImportLink("");
} catch (err) {
setStatus((err as Error).message);
} finally {
setImporting(false);
}
}
async function install(set: BeatmapSet) { async function install(set: BeatmapSet) {
setInstalling(set.id); setInstalling(set.id);
@@ -114,6 +193,23 @@ export function SearchPage() {
/> />
</div> </div>
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
<span style={{ fontSize: 12, color: "var(--df-text-muted)" }}>{t("search.importByLink")}</span>
<div style={{ display: "flex", gap: 8 }}>
<TextInput
value={importLink}
onChange={(e) => setImportLink(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && importByLink()}
placeholder={t("search.importByLinkPlaceholder")}
aria-label={t("search.importByLink")}
style={{ flex: 1 }}
/>
<Button variant="secondary" onClick={importByLink} disabled={importing || !importLink.trim()}>
{t("search.importButton")}
</Button>
</div>
</div>
<div <div
style={{ style={{
display: "flex", display: "flex",
@@ -147,7 +243,40 @@ export function SearchPage() {
</div> </div>
)} )}
<div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
<span style={{ fontSize: 12, color: "var(--df-text-muted)" }}>{t("search.status")}</span>
<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
<button style={chipStyle(rankedStatus === "")} onClick={() => setRankedStatus("")}>
{t("search.all")}
</button>
{STATUSES.map((s) => (
<button
key={s}
style={{ ...chipStyle(rankedStatus === s), textTransform: "capitalize" }}
onClick={() => setRankedStatus(rankedStatus === s ? "" : s)}
>
{s}
</button>
))}
</div>
</div>
<div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}> <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
<label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
<span style={{ fontSize: 12, color: "var(--df-text-muted)" }}>{t("search.sortBy")}</span>
<select
value={sort}
onChange={(e) => setSort(e.target.value as BeatmapSortOption)}
style={selectStyle()}
>
{SORT_OPTIONS.map((opt) => (
<option key={opt} value={opt}>
{t(SORT_LABEL_KEY[opt])}
</option>
))}
</select>
</label>
<label style={{ display: "flex", flexDirection: "column", gap: 4 }}> <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
<span style={{ fontSize: 12, color: "var(--df-text-muted)" }}>{t("search.genre")}</span> <span style={{ fontSize: 12, color: "var(--df-text-muted)" }}>{t("search.genre")}</span>
<select <select
+12
View File
@@ -48,6 +48,8 @@ export interface BeatmapSet {
source: string; source: string;
/** Present for beatmapsets found on disk; the Songs subfolder name, used for file operations. */ /** Present for beatmapsets found on disk; the Songs subfolder name, used for file operations. */
folderName?: string; folderName?: string;
favouriteCount?: number;
playCount?: number;
} }
/** osu!'s own genre enum (matches the IDs osu!/mirrors report; "any" omitted since it means "no filter"). */ /** osu!'s own genre enum (matches the IDs osu!/mirrors report; "any" omitted since it means "no filter"). */
@@ -85,6 +87,15 @@ export const LANGUAGES: Record<number, string> = {
14: "Other", 14: "Other",
}; };
export type BeatmapSortOption =
| "relevance"
| "favourites"
| "plays"
| "difficulty-asc"
| "difficulty-desc"
| "newest"
| "oldest";
export interface BeatmapSearchQuery { export interface BeatmapSearchQuery {
query?: string; query?: string;
mode?: OsuMode; mode?: OsuMode;
@@ -97,6 +108,7 @@ export interface BeatmapSearchQuery {
language?: number; language?: number;
/** Mania key count (4, 7, ...) — matched against difficulty CS. Ignored unless mode is "mania". */ /** Mania key count (4, 7, ...) — matched against difficulty CS. Ignored unless mode is "mania". */
keys?: number; keys?: number;
sort?: BeatmapSortOption;
page?: number; page?: number;
pageSize?: number; pageSize?: number;
} }