feat(spotlight): rework !bang search UX (#4813)
Co-authored-by: Meier Lukas <meierschlumpf@gmail.com>
This commit is contained in:
1 parent
831b6221fd
commit
b5c316b825
32 files changed
+6985
-151
No files matched your search
@@ -0,0 +1,191 @@
|
||||
---
|
||||
description: Comprehensive Homarr codebase architecture and conventions reference
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Homarr Codebase Context
|
||||
|
||||
Homarr is an open-source, self-hosted dashboard for managing homelab services. It integrates with 50+ self-hosted apps (media servers, download clients, DNS, NAS, etc.) and provides a drag-and-drop widget-based UI.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Monorepo**: pnpm workspaces + Turborepo
|
||||
- **Framework**: Next.js (App Router, `output: "standalone"`) — T3 Stack
|
||||
- **Language**: TypeScript throughout
|
||||
- **ORM**: Drizzle (supports SQLite via better-sqlite3, MySQL, PostgreSQL)
|
||||
- **API**: tRPC (HTTP + WebSocket subscriptions) with superjson + OpenAPI bridge via `trpc-to-openapi`
|
||||
- **Auth**: NextAuth v5 (database sessions, Credentials/LDAP/OIDC providers)
|
||||
- **UI**: Mantine v7 (not Tailwind) + Tabler icons
|
||||
- **State**: Jotai (atoms), TanStack Query (server state via tRPC)
|
||||
- **Realtime**: WebSocket server (`ws`) for tRPC subscriptions, backed by Redis pub/sub
|
||||
- **Cron**: `node-cron` in a standalone Fastify service (`apps/tasks`)
|
||||
- **i18n**: next-intl with `[locale]` dynamic segment (prefix mode: `"never"`, locale from cookie)
|
||||
- **Testing**: Vitest + jsdom, Playwright for E2E
|
||||
- **Package manager**: pnpm 10.33.2, Node >= 24.15.0
|
||||
|
||||
## Repository Structure
|
||||
|
||||
```
|
||||
homarr/
|
||||
├── apps/
|
||||
│ ├── nextjs/ # Main Next.js application (port 3000)
|
||||
│ ├── tasks/ # Cron job runner + Fastify tRPC API (port 3002)
|
||||
│ └── websocket/ # Standalone tRPC WebSocket server (port 3001)
|
||||
├── packages/
|
||||
│ ├── api/ # tRPC appRouter, procedures, OpenAPI
|
||||
│ ├── auth/ # NextAuth config, providers, session, API keys
|
||||
│ ├── db/ # Drizzle schema (3 DB drivers), migrations, queries
|
||||
│ ├── core/ # Env validation, DB/Redis driver factories, logging
|
||||
│ ├── definitions/ # Domain enums: WidgetKind, IntegrationKind, permissions
|
||||
│ ├── widgets/ # All 39 dashboard widgets (definitions + components)
|
||||
│ ├── integrations/ # Integration classes (HTTP clients to external apps)
|
||||
│ ├── redis/ # Redis pub/sub channels, caching abstractions
|
||||
│ ├── translation/ # next-intl setup, locale configs, lang JSON files
|
||||
│ ├── ui/ # Shared Mantine components, theme, hooks
|
||||
│ ├── validation/ # Shared zod schemas for API/forms
|
||||
│ ├── common/ # Shared utilities, IDs, errors
|
||||
│ ├── cron-jobs/ # Cron job implementations (25+ jobs)
|
||||
│ ├── cron-jobs-core/ # Cron scheduling primitives
|
||||
│ ├── cron-job-api/ # tRPC router for job management (start/stop/trigger)
|
||||
│ ├── cron-job-status/ # Cron status via Redis
|
||||
│ ├── boards/ # Board context, edit mode, cache updater
|
||||
│ ├── modals/ # Modal primitives on Mantine
|
||||
│ ├── modals-collection/ # Feature modals (apps, boards, docker, etc.)
|
||||
│ ├── form/ # useZodForm (Mantine + zod resolver)
|
||||
│ ├── forms-collection/# Reusable form UIs (new app, icon picker, upload)
|
||||
│ ├── spotlight/ # Command palette / search with multiple modes
|
||||
│ ├── request-handler/ # Server request handlers (feeds, integrations)
|
||||
│ ├── notifications/ # Mantine notifications wrapper
|
||||
│ ├── docker/ # Dockerode-based Docker access
|
||||
│ ├── icons/ # Icon DB/repo integration
|
||||
│ ├── image-proxy/ # Image proxy + caching
|
||||
│ ├── ping/ # Reachability / ping utilities
|
||||
│ ├── analytics/ # Server-side analytics (Umami)
|
||||
│ ├── server-settings/ # Server setting keys/types
|
||||
│ ├── settings/ # User-facing settings UI context
|
||||
│ ├── old-import/ # Legacy Homarr import
|
||||
│ ├── old-schema/ # Legacy Homarr zod schemas
|
||||
│ └── cli/ # Node CLI for ops (brocli)
|
||||
├── tooling/
|
||||
│ ├── eslint/ # Shared ESLint configs
|
||||
│ ├── prettier/ # Shared Prettier config
|
||||
│ ├── typescript/ # Base tsconfig
|
||||
│ └── github/ # CI setup action
|
||||
├── development/ # Dev docker-compose (Redis, MySQL, PostgreSQL)
|
||||
├── e2e/ # E2E test specs
|
||||
└── Dockerfile # Multi-stage production build
|
||||
```
|
||||
|
||||
## Three Runtime Services
|
||||
|
||||
| Service | Port | Role |
|
||||
|---------|------|------|
|
||||
| Next.js | 3000 | Main web app (SSR + API routes) |
|
||||
| WebSocket | 3001 | tRPC subscriptions via `ws` |
|
||||
| Tasks | 3002 | Cron job runner + management API via Fastify |
|
||||
|
||||
In Docker, nginx listens on **7575** and proxies to all three. The tasks service authenticates via `CRON_JOB_API_KEY` header.
|
||||
|
||||
## Package Dependency Layers
|
||||
|
||||
1. **Foundation**: `core` (env, DB drivers, Redis client, logging) → no `@homarr` deps
|
||||
2. **Domain**: `definitions` → `common` → `core`
|
||||
3. **Data**: `db` → `core`, `definitions`, `common`
|
||||
4. **Auth**: `auth` → `db`, `definitions`, `core`, `validation`
|
||||
5. **Cross-cutting**: `translation`, `validation`, `redis`, `server-settings`
|
||||
6. **Feature backends**: `integrations`, `request-handler`, `cron-jobs`, `docker`, `ping`
|
||||
7. **API surface**: `api` → pulls in auth, db, redis, integrations, etc.
|
||||
8. **UI stack**: `ui`, `modals`, `form`, `notifications`, `boards`, `spotlight`
|
||||
9. **Composed features**: `widgets`, `modals-collection`, `forms-collection`
|
||||
|
||||
## Key Patterns
|
||||
|
||||
### tRPC
|
||||
|
||||
- **Server caller** (RSC): `import { api } from "@homarr/api/server"` → cached caller with auth context
|
||||
- **Client hooks**: `import { clientApi } from "@homarr/api/client"` → React Query hooks
|
||||
- **Router structure**: `packages/api/src/root.ts` defines top-level namespaces (`user`, `board`, `widget`, `integration`, `docker`, `kubernetes`, etc.)
|
||||
- **Procedures**: `publicProcedure`, `protectedProcedure`, `permissionRequiredProcedure`, `onboardingProcedure`
|
||||
- **WebSocket subscriptions**: Client uses `wsLink` when `type === "subscription"`, connects to port 3001
|
||||
|
||||
### Multi-Database Support
|
||||
|
||||
Drizzle schemas exist in three parallel implementations:
|
||||
- `packages/db/schema/sqlite.ts`
|
||||
- `packages/db/schema/mysql.ts`
|
||||
- `packages/db/schema/postgresql.ts`
|
||||
|
||||
Selected at runtime via `DB_DRIVER` env (`better-sqlite3` | `mysql2` | `node-postgres`). Migrations are per-engine in `packages/db/migrations/{sqlite,mysql,postgresql}/`.
|
||||
|
||||
### Widget System
|
||||
|
||||
Widgets are registered in `packages/widgets/src/index.tsx` as `widgetImports` (must satisfy `Record<WidgetKind, ...>`). Each widget:
|
||||
- Has a `definition` created via `createWidgetDefinition(kind, { icon, createOptions, supportedIntegrations? })`
|
||||
- Uses `optionsBuilder.from(factory => ({ ... }))` for typed options
|
||||
- Loads dynamically via `next/dynamic`
|
||||
- Fetches data via tRPC client hooks (backed by cron job caches)
|
||||
|
||||
### Integration System
|
||||
|
||||
Integrations are defined in `packages/definitions/src/integration.ts` (`integrationDefs`) and instantiated via `createIntegrationAsync` in `packages/integrations/src/base/creator.ts`. Each extends abstract `Integration` class with `testConnectionAsync` and typed methods.
|
||||
|
||||
### Cron Job System
|
||||
|
||||
Jobs defined in `packages/cron-jobs/src/jobs/`. Each job:
|
||||
- Uses `createCronJob` with a cron expression
|
||||
- Publishes results to Redis channels
|
||||
- Widget subscriptions consume those channels via tRPC subscriptions
|
||||
- Job management (start/stop/trigger) via `cronJobApi` HTTP client to port 3002
|
||||
|
||||
### Modals
|
||||
|
||||
Created with `createModal(component).withOptions({ defaultTitle })` from `@homarr/modals`. Opened via `useModalAction(SomeModal)`. Feature modals live in `packages/modals-collection/`.
|
||||
|
||||
### Forms
|
||||
|
||||
`useZodForm` from `@homarr/form` wraps Mantine `useForm` with zod validation. Shared form UIs in `packages/forms-collection/`.
|
||||
|
||||
### Routing (App Router)
|
||||
|
||||
- `apps/nextjs/src/app/[locale]/` — all UI routes under locale segment
|
||||
- Route groups: `(home)`, `(content)`, `(board)` — don't affect URLs
|
||||
- Key routes: `boards/[name]`, `manage/...` (admin), `auth/login`, `init` (onboarding), `widgets/[kind]`
|
||||
- Locale driven by cookie (no URL prefix)
|
||||
|
||||
### Auth Providers
|
||||
|
||||
Configured via `AUTH_PROVIDERS` env. Supports: `credentials` (local), `ldap`, `oidc`. Database sessions with httpOnly cookies. API key auth for programmatic access.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Key env vars (from `.env.example`):
|
||||
- `DB_DRIVER`: `better-sqlite3` | `mysql2` | `node-postgres`
|
||||
- `DB_URL`: Database connection string
|
||||
- `AUTH_SECRET`: NextAuth secret
|
||||
- `SECRET_ENCRYPTION_KEY`: AES-256-CBC for integration secrets
|
||||
- `AUTH_PROVIDERS`: Comma-separated (`credentials`, `ldap`, `oidc`)
|
||||
- `CRON_JOB_API_KEY`: Shared key between Next.js and tasks service
|
||||
- `REDIS_*`: Redis connection (host, port, password)
|
||||
- `ENABLE_KUBERNETES`: Optional Kubernetes integration
|
||||
|
||||
## Development Commands
|
||||
|
||||
- `pnpm dev` — runs all three services in parallel via Turborepo
|
||||
- `pnpm docker:dev` — starts Redis + MySQL + PostgreSQL containers
|
||||
- `pnpm db:push` — push schema to SQLite (dev)
|
||||
- `pnpm db:studio` — Drizzle Studio
|
||||
- `pnpm test` — Vitest unit tests
|
||||
- `pnpm test:e2e` — Playwright E2E
|
||||
- `pnpm lint` / `pnpm format` — ESLint + Prettier
|
||||
- `pnpm typecheck` — tsc --noEmit across all packages
|
||||
|
||||
## Conventions
|
||||
|
||||
- Workspace packages use `@homarr/` scope
|
||||
- All versions managed via pnpm `catalog:` in workspace
|
||||
- Path alias `~/*` → `./src/*` in Next.js app
|
||||
- Mantine for all UI (no Tailwind) — primary color is red, `autoContrast: true`
|
||||
- Icons from `@tabler/icons-react`
|
||||
- Drag-and-drop via `@dnd-kit/*`
|
||||
- `typescript.ignoreBuildErrors: true` in next.config (types checked separately via `typecheck`)
|
||||
- `serverExternalPackages`: `dockerode`, `isomorphic-dompurify`, `jsdom`
|
||||
+6
@@ -26,6 +26,7 @@ export const ChangeSearchPreferencesForm = ({ user, searchEnginesData }: ChangeS
|
||||
form.setInitialValues({
|
||||
defaultSearchEngineId: variables.defaultSearchEngineId,
|
||||
openInNewTab: variables.openInNewTab,
|
||||
ddgBangsEnabled: variables.ddgBangsEnabled,
|
||||
});
|
||||
showSuccessNotification({
|
||||
message: t("user.action.changeSearchPreferences.notification.success.message"),
|
||||
@@ -41,6 +42,7 @@ export const ChangeSearchPreferencesForm = ({ user, searchEnginesData }: ChangeS
|
||||
initialValues: {
|
||||
defaultSearchEngineId: user.defaultSearchEngineId,
|
||||
openInNewTab: user.openSearchInNewTab,
|
||||
ddgBangsEnabled: user.ddgBangs,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -64,6 +66,10 @@ export const ChangeSearchPreferencesForm = ({ user, searchEnginesData }: ChangeS
|
||||
label={t("user.field.openSearchInNewTab.label")}
|
||||
{...form.getInputProps("openInNewTab", { type: "checkbox" })}
|
||||
/>
|
||||
<Switch
|
||||
label={t("user.field.ddgBangs.label")}
|
||||
{...form.getInputProps("ddgBangsEnabled", { type: "checkbox" })}
|
||||
/>
|
||||
|
||||
<Group justify="end">
|
||||
<Button type="submit" loading={isPending}>
|
||||
|
||||
@@ -26,6 +26,7 @@ export const appRouter = createTRPCRouter({
|
||||
media: lazy(() => import("./router/medias/media-router").then((mod) => mod.mediaRouter)),
|
||||
updateChecker: lazy(() => import("./router/update-checker").then((mod) => mod.updateCheckerRouter)),
|
||||
certificates: lazy(() => import("./router/certificates/certificate-router").then((mod) => mod.certificateRouter)),
|
||||
bangs: lazy(() => import("./router/bangs/bangs-router").then((mod) => mod.bangsRouter)),
|
||||
info: lazy(() => import("./router/info").then((mod) => mod.infoRouter)),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { searchDuckDuckGoBangsAsync } from "../../services/duckduckgo-bangs";
|
||||
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||
|
||||
export const bangsRouter = createTRPCRouter({
|
||||
search: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
query: z.string(),
|
||||
limit: z.number().int().min(1).max(50).default(20),
|
||||
}),
|
||||
)
|
||||
.query(async ({ input }) => {
|
||||
return await searchDuckDuckGoBangsAsync({ query: input.query, limit: input.limit });
|
||||
}),
|
||||
});
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
userChangePasswordApiSchema,
|
||||
userChangeSearchPreferencesSchema,
|
||||
userCreateSchema,
|
||||
userDdgBangsSchema,
|
||||
userEditProfileSchema,
|
||||
userFirstDayOfWeekSchema,
|
||||
userInitSchema,
|
||||
@@ -276,6 +277,7 @@ export const userRouter = createTRPCRouter({
|
||||
pingIconsEnabled: true,
|
||||
defaultSearchEngineId: true,
|
||||
openSearchInNewTab: true,
|
||||
ddgBangs: true,
|
||||
}),
|
||||
)
|
||||
.meta({ openapi: { method: "GET", path: "/api/users/{userId}", tags: ["users"], protect: true } })
|
||||
@@ -301,6 +303,7 @@ export const userRouter = createTRPCRouter({
|
||||
pingIconsEnabled: true,
|
||||
defaultSearchEngineId: true,
|
||||
openSearchInNewTab: true,
|
||||
ddgBangs: true,
|
||||
},
|
||||
where: eq(users.id, input.userId),
|
||||
});
|
||||
@@ -541,6 +544,33 @@ export const userRouter = createTRPCRouter({
|
||||
})
|
||||
.where(eq(users.id, ctx.session.user.id));
|
||||
}),
|
||||
changeDdgBangs: protectedProcedure
|
||||
.input(convertIntersectionToZodObject(userDdgBangsSchema.and(byIdSchema)))
|
||||
.output(z.void())
|
||||
.meta({
|
||||
openapi: {
|
||||
method: "PATCH",
|
||||
path: "/api/users/ddg-bangs",
|
||||
tags: ["users"],
|
||||
protect: true,
|
||||
deprecated: true,
|
||||
},
|
||||
})
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
if (!ctx.session.user.permissions.includes("admin") && ctx.session.user.id !== input.id) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "User not found",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db
|
||||
.update(users)
|
||||
.set({
|
||||
ddgBangs: input.ddgBangs,
|
||||
})
|
||||
.where(eq(users.id, input.id));
|
||||
}),
|
||||
changeFirstDayOfWeek: protectedProcedure
|
||||
.input(convertIntersectionToZodObject(userFirstDayOfWeekSchema.and(byIdSchema)))
|
||||
.output(z.void())
|
||||
|
||||
@@ -15,10 +15,13 @@ export const changeSearchPreferencesInputSchema = userChangeSearchPreferencesSch
|
||||
export const changeSearchPreferencesAsync = async (
|
||||
db: Database,
|
||||
session: Session,
|
||||
input: Modify<z.infer<typeof changeSearchPreferencesInputSchema>, { openInNewTab: boolean | undefined }>,
|
||||
input: Modify<
|
||||
z.infer<typeof changeSearchPreferencesInputSchema>,
|
||||
{ openInNewTab: boolean | undefined; ddgBangsEnabled: boolean | undefined }
|
||||
>,
|
||||
) => {
|
||||
const user = session.user;
|
||||
// Only admins can change other users passwords
|
||||
// Only admins can change other users search preferences
|
||||
if (!user.permissions.includes("admin") && user.id !== input.userId) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
@@ -45,6 +48,7 @@ export const changeSearchPreferencesAsync = async (
|
||||
.set({
|
||||
defaultSearchEngineId: input.defaultSearchEngineId,
|
||||
openSearchInNewTab: input.openInNewTab,
|
||||
ddgBangs: input.ddgBangsEnabled,
|
||||
})
|
||||
.where(eq(users.id, input.userId));
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import { duckDuckGoBangsRequestHandler } from "@homarr/request-handler/duckduckgo-bangs";
|
||||
import type { DuckDuckGoBang } from "@homarr/request-handler/duckduckgo-bangs";
|
||||
|
||||
// DuckDuckGo bang keys are intentionally short:
|
||||
// - `t`: token (e.g. "yt"), `s`: display name, `u`: URL template (contains `{{{s}}}`)
|
||||
// - `d`: domain, `c`: category, `sc`: subcategory, `r`: rank (optional)
|
||||
|
||||
const normalizeBangToken = (token: string) => token.toLowerCase().trim();
|
||||
|
||||
/**
|
||||
* Binary search to find the first index where bang.t >= tokenPrefix.
|
||||
* This is O(log n) vs O(n) for findIndex, which matters because DuckDuckGo
|
||||
* has ~13,000+ bangs. Combined with the pre-sorted data, this allows
|
||||
* efficient prefix matching by finding the start position and iterating
|
||||
* only through consecutive matches.
|
||||
*/
|
||||
const lowerBound = (arr: DuckDuckGoBang[], tokenPrefix: string) => {
|
||||
let low = 0;
|
||||
let high = arr.length;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >> 1;
|
||||
const midBang = arr[mid];
|
||||
// Must use the same ordering as the source list sort (localeCompare),
|
||||
// otherwise binary search can miss tokens with symbols like "&" or "_".
|
||||
if (!midBang || midBang.t.localeCompare(tokenPrefix) >= 0) {
|
||||
high = mid;
|
||||
continue;
|
||||
}
|
||||
|
||||
low = mid + 1;
|
||||
}
|
||||
return low;
|
||||
};
|
||||
|
||||
export const searchDuckDuckGoBangsAsync = async (input: {
|
||||
query: string;
|
||||
limit: number;
|
||||
}): Promise<DuckDuckGoBang[]> => {
|
||||
const queryTokenPrefix = normalizeBangToken(input.query);
|
||||
if (!queryTokenPrefix) return [];
|
||||
|
||||
const { data: allBangs } = await duckDuckGoBangsRequestHandler.handler({}).getCachedOrUpdatedDataAsync({});
|
||||
const startIndex = lowerBound(allBangs, queryTokenPrefix);
|
||||
const matches: DuckDuckGoBang[] = [];
|
||||
|
||||
for (let index = startIndex; index < allBangs.length; index++) {
|
||||
const bang = allBangs[index];
|
||||
if (!bang) break;
|
||||
if (!bang.t.startsWith(queryTokenPrefix)) break;
|
||||
matches.push(bang);
|
||||
if (matches.length >= input.limit) break;
|
||||
}
|
||||
|
||||
return matches;
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `user` ADD `ddg_bangs` boolean DEFAULT true NOT NULL;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -267,6 +267,13 @@
|
||||
"when": 1775399941430,
|
||||
"tag": "0037_remove_salt",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 38,
|
||||
"version": "5",
|
||||
"when": 1775400000000,
|
||||
"tag": "0038_add_user_ddg_bangs",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "user" ADD COLUMN "ddg_bangs" boolean DEFAULT true NOT NULL;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,13 @@
|
||||
"when": 1775399963041,
|
||||
"tag": "0003_remove_salt",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1775400000000,
|
||||
"tag": "0004_add_user_ddg_bangs",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `user` ADD `ddg_bangs` integer DEFAULT true NOT NULL;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -253,6 +253,13 @@
|
||||
"when": 1775399918831,
|
||||
"tag": "0035_remove_salt",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 36,
|
||||
"version": "6",
|
||||
"when": 1775400000000,
|
||||
"tag": "0036_add_user_ddg_bangs",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -76,6 +76,7 @@ export const users = mysqlTable("user", {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
openSearchInNewTab: boolean().default(false).notNull(),
|
||||
ddgBangs: boolean().default(true).notNull(),
|
||||
colorScheme: varchar({ length: 5 }).$type<ColorScheme>().default("dark").notNull(),
|
||||
firstDayOfWeek: tinyint().$type<DayOfWeek>().default(1).notNull(), // Defaults to Monday
|
||||
pingIconsEnabled: boolean().default(false).notNull(),
|
||||
|
||||
@@ -75,6 +75,7 @@ export const users = pgTable("user", {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
openSearchInNewTab: boolean().default(false).notNull(),
|
||||
ddgBangs: boolean().default(true).notNull(),
|
||||
colorScheme: varchar({ length: 5 }).$type<ColorScheme>().default("dark").notNull(),
|
||||
firstDayOfWeek: smallint().$type<DayOfWeek>().default(1).notNull(), // Defaults to Monday
|
||||
pingIconsEnabled: boolean().default(false).notNull(),
|
||||
|
||||
@@ -58,6 +58,7 @@ export const users = sqliteTable("user", {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
openSearchInNewTab: int({ mode: "boolean" }).default(true).notNull(),
|
||||
ddgBangs: int({ mode: "boolean" }).default(true).notNull(),
|
||||
colorScheme: text().$type<ColorScheme>().default("dark").notNull(),
|
||||
firstDayOfWeek: int().$type<DayOfWeek>().default(1).notNull(), // Defaults to Monday
|
||||
pingIconsEnabled: int({ mode: "boolean" }).default(false).notNull(),
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import dayjs from "dayjs";
|
||||
import { z } from "zod";
|
||||
|
||||
import { env } from "@homarr/common/env";
|
||||
import { ResponseError } from "@homarr/common/server";
|
||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||
import { withTimeoutAsync } from "@homarr/core/infrastructure/http/timeout";
|
||||
import { createChannelWithLatestAndEvents } from "@homarr/redis";
|
||||
import { createCachedRequestHandler } from "@homarr/request-handler/lib/cached-request-handler";
|
||||
|
||||
export type DuckDuckGoBang = z.infer<typeof duckDuckGoBangSchema>;
|
||||
|
||||
const DUCKDUCKGO_BANGS_URL = "https://duckduckgo.com/bang.js";
|
||||
|
||||
/**
|
||||
* DuckDuckGo `bang.js` uses short keys (to reduce the payload size):
|
||||
* - `t`: bang token (e.g. `"yt"`)
|
||||
* - `s`: display name
|
||||
* - `d`: domain (optional)
|
||||
* - `u`: URL template (contains `{{{s}}}`)
|
||||
* - `c`: category (optional)
|
||||
* - `sc`: subcategory (optional)
|
||||
* - `r`: rank (optional)
|
||||
*/
|
||||
export const duckDuckGoBangSchema = z.object({
|
||||
t: z.string(),
|
||||
s: z.string(),
|
||||
d: z.string().optional(),
|
||||
u: z.string(),
|
||||
c: z.string().optional(),
|
||||
sc: z.string().optional(),
|
||||
r: z.number().optional(),
|
||||
});
|
||||
|
||||
const duckDuckGoBangsResponseSchema = z.array(duckDuckGoBangSchema);
|
||||
|
||||
const normalizeBangToken = (token: string) => token.toLowerCase().trim();
|
||||
|
||||
const compareBangTokenAsc = (left: DuckDuckGoBang, right: DuckDuckGoBang) => left.t.localeCompare(right.t);
|
||||
|
||||
export const duckDuckGoBangsRequestHandler = createCachedRequestHandler({
|
||||
queryKey: "duckduckgo-bangs",
|
||||
cacheDuration: dayjs.duration(1, "day"),
|
||||
async requestAsync(_) {
|
||||
if (env.NO_EXTERNAL_CONNECTION) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const res = await withTimeoutAsync(async (signal) => {
|
||||
return await fetchWithTrustedCertificatesAsync(DUCKDUCKGO_BANGS_URL, {
|
||||
signal,
|
||||
headers: {
|
||||
accept: "application/json,text/plain,*/*",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new ResponseError(res);
|
||||
}
|
||||
|
||||
const json: unknown = await res.json();
|
||||
const bangs = await duckDuckGoBangsResponseSchema.parseAsync(json);
|
||||
|
||||
const normalized = bangs
|
||||
.map((bang) => ({
|
||||
...bang,
|
||||
t: normalizeBangToken(bang.t),
|
||||
}))
|
||||
.filter((bang) => bang.t.length > 0);
|
||||
|
||||
normalized.sort(compareBangTokenAsc);
|
||||
|
||||
return normalized;
|
||||
},
|
||||
createRedisChannel() {
|
||||
return createChannelWithLatestAndEvents<DuckDuckGoBang[]>("homarr:duckduckgo-bangs");
|
||||
},
|
||||
});
|
||||
@@ -8,6 +8,7 @@ export type SettingsContextProps = Pick<
|
||||
| "homeBoardId"
|
||||
| "mobileHomeBoardId"
|
||||
| "openSearchInNewTab"
|
||||
| "ddgBangs"
|
||||
| "pingIconsEnabled"
|
||||
> &
|
||||
Pick<ServerSettings["board"], "enableStatusByDefault" | "forceDisableStatus"> &
|
||||
@@ -29,6 +30,7 @@ export type UserSettings = Pick<
|
||||
| "homeBoardId"
|
||||
| "mobileHomeBoardId"
|
||||
| "openSearchInNewTab"
|
||||
| "ddgBangs"
|
||||
| "pingIconsEnabled"
|
||||
>;
|
||||
|
||||
@@ -41,6 +43,7 @@ export const createSettings = ({
|
||||
}) => ({
|
||||
defaultSearchEngineId: user?.defaultSearchEngineId ?? serverSettings.search.defaultSearchEngineId,
|
||||
openSearchInNewTab: user?.openSearchInNewTab ?? true,
|
||||
ddgBangs: user?.ddgBangs ?? true,
|
||||
firstDayOfWeek: user?.firstDayOfWeek ?? (1 as const),
|
||||
homeBoardId: user?.homeBoardId ?? serverSettings.board.homeBoardId,
|
||||
mobileHomeBoardId: user?.mobileHomeBoardId ?? serverSettings.board.mobileHomeBoardId,
|
||||
|
||||
@@ -12,6 +12,7 @@ import { SpotlightGroupActionItem } from "./items/group-action-item";
|
||||
interface GroupActionsProps<TOption extends Record<string, unknown>> {
|
||||
group: SearchGroup<TOption>;
|
||||
query: string;
|
||||
setQuery: (query: string) => void;
|
||||
setMode: (mode: keyof TranslationObject["search"]["mode"]) => void;
|
||||
setChildrenOptions: (options: inferSearchInteractionOptions<"children">) => void;
|
||||
}
|
||||
@@ -19,6 +20,7 @@ interface GroupActionsProps<TOption extends Record<string, unknown>> {
|
||||
export const SpotlightGroupActions = <TOption extends Record<string, unknown>>({
|
||||
group,
|
||||
query,
|
||||
setQuery,
|
||||
setMode,
|
||||
setChildrenOptions,
|
||||
}: GroupActionsProps<TOption>) => {
|
||||
@@ -58,6 +60,7 @@ export const SpotlightGroupActions = <TOption extends Record<string, unknown>>({
|
||||
option={option}
|
||||
group={group}
|
||||
query={query}
|
||||
setQuery={setQuery}
|
||||
setMode={setMode}
|
||||
setChildrenOptions={setChildrenOptions}
|
||||
/>
|
||||
@@ -90,6 +93,7 @@ export const SpotlightGroupActions = <TOption extends Record<string, unknown>>({
|
||||
option={option}
|
||||
group={group}
|
||||
query={query}
|
||||
setQuery={setQuery}
|
||||
setMode={setMode}
|
||||
setChildrenOptions={setChildrenOptions}
|
||||
/>
|
||||
|
||||
@@ -11,6 +11,7 @@ import { SpotlightGroupActions } from "../group-actions";
|
||||
interface SpotlightActionGroupsProps {
|
||||
groups: SearchGroup[];
|
||||
query: string;
|
||||
setQuery: (query: string) => void;
|
||||
setMode: (mode: keyof TranslationObject["search"]["mode"]) => void;
|
||||
setChildrenOptions: (options: inferSearchInteractionOptions<"children">) => void;
|
||||
}
|
||||
@@ -19,7 +20,10 @@ export const SpotlightActionGroups = ({ groups, ...others }: SpotlightActionGrou
|
||||
const t = useI18n();
|
||||
|
||||
return groups.map((group) => (
|
||||
<Spotlight.ActionsGroup key={translateIfNecessary(t, group.title)} label={translateIfNecessary(t, group.title)}>
|
||||
<Spotlight.ActionsGroup
|
||||
key={`${translateIfNecessary(t, group.title)}::${String(group.keyPath)}`}
|
||||
label={translateIfNecessary(t, group.title)}
|
||||
>
|
||||
{/*eslint-disable-next-line @typescript-eslint/no-explicit-any */}
|
||||
<SpotlightGroupActions<any> group={group} {...others} />
|
||||
</Spotlight.ActionsGroup>
|
||||
|
||||
@@ -5,11 +5,13 @@ import { Link } from "@homarr/ui";
|
||||
|
||||
import type { SearchGroup } from "../../../lib/group";
|
||||
import type { inferSearchInteractionOptions } from "../../../lib/interaction";
|
||||
import { selectAction, spotlightStore } from "../../../spotlight-store";
|
||||
import classes from "./action-item.module.css";
|
||||
|
||||
interface SpotlightGroupActionItemProps<TOption extends Record<string, unknown>> {
|
||||
option: TOption;
|
||||
query: string;
|
||||
setQuery: (query: string) => void;
|
||||
setMode: (mode: keyof TranslationObject["search"]["mode"]) => void;
|
||||
setChildrenOptions: (options: inferSearchInteractionOptions<"children">) => void;
|
||||
group: SearchGroup<TOption>;
|
||||
@@ -18,11 +20,15 @@ interface SpotlightGroupActionItemProps<TOption extends Record<string, unknown>>
|
||||
export const SpotlightGroupActionItem = <TOption extends Record<string, unknown>>({
|
||||
group,
|
||||
query,
|
||||
setQuery,
|
||||
setMode,
|
||||
setChildrenOptions,
|
||||
option,
|
||||
}: SpotlightGroupActionItemProps<TOption>) => {
|
||||
const interaction = group.useInteraction(option, query);
|
||||
// Avoid passing React's special `key` prop via spread
|
||||
|
||||
const { key: _reactKey, ...optionProps } = option as unknown as { key?: unknown } & Record<string, unknown>;
|
||||
|
||||
const renderRoot =
|
||||
interaction.type === "link"
|
||||
@@ -34,6 +40,9 @@ export const SpotlightGroupActionItem = <TOption extends Record<string, unknown>
|
||||
const handleClickAsync = async () => {
|
||||
if (interaction.type === "javaScript") {
|
||||
await interaction.onSelect();
|
||||
} else if (interaction.type === "setQuery") {
|
||||
setQuery(interaction.query);
|
||||
setTimeout(() => selectAction(0, spotlightStore));
|
||||
} else if (interaction.type === "mode") {
|
||||
setMode(interaction.mode);
|
||||
} else if (interaction.type === "children") {
|
||||
@@ -46,11 +55,14 @@ export const SpotlightGroupActionItem = <TOption extends Record<string, unknown>
|
||||
renderRoot={renderRoot}
|
||||
onClick={handleClickAsync}
|
||||
closeSpotlightOnTrigger={
|
||||
interaction.type !== "mode" && interaction.type !== "children" && interaction.type !== "none"
|
||||
interaction.type !== "mode" &&
|
||||
interaction.type !== "children" &&
|
||||
interaction.type !== "none" &&
|
||||
interaction.type !== "setQuery"
|
||||
}
|
||||
className={classes.spotlightAction}
|
||||
>
|
||||
<group.Component {...option} />
|
||||
<group.Component {...(optionProps as TOption)} />
|
||||
</Spotlight.Action>
|
||||
);
|
||||
};
|
||||
@@ -4,7 +4,7 @@ import type { Dispatch, SetStateAction } from "react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { ActionIcon, Center, Group, Kbd } from "@mantine/core";
|
||||
import { Spotlight as MantineSpotlight } from "@mantine/spotlight";
|
||||
import { IconQuestionMark, IconSearch, IconX } from "@tabler/icons-react";
|
||||
import { IconSearch, IconX } from "@tabler/icons-react";
|
||||
|
||||
import { hotkeys } from "@homarr/definitions";
|
||||
import type { TranslationObject } from "@homarr/translation";
|
||||
@@ -13,6 +13,7 @@ import { useI18n } from "@homarr/translation/client";
|
||||
import type { inferSearchInteractionOptions } from "../lib/interaction";
|
||||
import type { SearchMode } from "../lib/mode";
|
||||
import { searchModes } from "../modes";
|
||||
import { useHomeEmptyGroups } from "../modes/help/home-empty-groups";
|
||||
import { selectAction, spotlightStore } from "../spotlight-store";
|
||||
import { SpotlightChildrenActions } from "./actions/children-actions";
|
||||
import { SpotlightActionGroups } from "./actions/groups/action-group";
|
||||
@@ -22,6 +23,7 @@ type SearchModeKey = keyof TranslationObject["search"]["mode"];
|
||||
const defaultMode = "home";
|
||||
export const Spotlight = () => {
|
||||
const searchModeState = useState<SearchModeKey>(defaultMode);
|
||||
const queryState = useState("");
|
||||
const mode = searchModeState[0];
|
||||
const activeMode = useMemo(() => searchModes.find((searchMode) => searchMode.modeKey === mode), [mode]);
|
||||
|
||||
@@ -30,16 +32,19 @@ export const Spotlight = () => {
|
||||
}
|
||||
|
||||
// We use the "key" below to prevent the 'Different amounts of hooks' error
|
||||
return <SpotlightWithActiveMode key={mode} modeState={searchModeState} activeMode={activeMode} />;
|
||||
return (
|
||||
<SpotlightWithActiveMode key={mode} modeState={searchModeState} queryState={queryState} activeMode={activeMode} />
|
||||
);
|
||||
};
|
||||
|
||||
interface SpotlightWithActiveModeProps {
|
||||
modeState: [SearchModeKey, Dispatch<SetStateAction<SearchModeKey>>];
|
||||
queryState: [string, Dispatch<SetStateAction<string>>];
|
||||
activeMode: SearchMode;
|
||||
}
|
||||
|
||||
const SpotlightWithActiveMode = ({ modeState, activeMode }: SpotlightWithActiveModeProps) => {
|
||||
const [query, setQuery] = useState("");
|
||||
const SpotlightWithActiveMode = ({ modeState, queryState, activeMode }: SpotlightWithActiveModeProps) => {
|
||||
const [query, setQuery] = queryState;
|
||||
const [mode, setMode] = modeState;
|
||||
const [childrenOptions, setChildrenOptions] = useState<inferSearchInteractionOptions<"children"> | null>(null);
|
||||
const t = useI18n();
|
||||
@@ -47,28 +52,34 @@ const SpotlightWithActiveMode = ({ modeState, activeMode }: SpotlightWithActiveM
|
||||
// Works as always the same amount of hooks are executed
|
||||
const useGroups = "groups" in activeMode ? () => activeMode.groups : activeMode.useGroups;
|
||||
const groups = useGroups();
|
||||
const homeEmptyGroups = useHomeEmptyGroups();
|
||||
|
||||
return (
|
||||
<MantineSpotlight.Root
|
||||
shortcut={hotkeys.openSpotlight}
|
||||
yOffset={8}
|
||||
overlayProps={{ blur: 2, backgroundOpacity: 0.2 }}
|
||||
onSpotlightClose={() => {
|
||||
setMode(defaultMode);
|
||||
setChildrenOptions(null);
|
||||
setQuery("");
|
||||
}}
|
||||
query={query}
|
||||
onQueryChange={(query) => {
|
||||
if (mode !== "help" || query.length !== 1) {
|
||||
setQuery(query);
|
||||
}
|
||||
onQueryChange={(nextQuery) => {
|
||||
const sanitizedQuery = mode === "external" && nextQuery.startsWith("!") ? nextQuery.slice(1) : nextQuery;
|
||||
setQuery(sanitizedQuery);
|
||||
|
||||
const modeToActivate = searchModes.find((mode) => mode.character === query);
|
||||
if (!modeToActivate) {
|
||||
return;
|
||||
}
|
||||
// Only switch modes when a single trigger character is typed
|
||||
if (sanitizedQuery.length !== 1) return;
|
||||
|
||||
const modeToActivate = searchModes.find((mode) => mode.character === sanitizedQuery);
|
||||
if (!modeToActivate) return;
|
||||
|
||||
setMode(modeToActivate.modeKey);
|
||||
setChildrenOptions(null);
|
||||
|
||||
setQuery("");
|
||||
|
||||
setTimeout(() => selectAction(0, spotlightStore));
|
||||
}}
|
||||
store={spotlightStore}
|
||||
@@ -91,17 +102,7 @@ const SpotlightWithActiveMode = ({ modeState, activeMode }: SpotlightWithActiveM
|
||||
},
|
||||
}}
|
||||
rightSection={
|
||||
mode === defaultMode ? (
|
||||
<ActionIcon
|
||||
onClick={() => {
|
||||
setMode("help");
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
variant="subtle"
|
||||
>
|
||||
<IconQuestionMark stroke={1.5} />
|
||||
</ActionIcon>
|
||||
) : (
|
||||
mode === defaultMode ? null : (
|
||||
<ActionIcon
|
||||
onClick={() => {
|
||||
setMode(defaultMode);
|
||||
@@ -138,6 +139,7 @@ const SpotlightWithActiveMode = ({ modeState, activeMode }: SpotlightWithActiveM
|
||||
/>
|
||||
) : (
|
||||
<SpotlightActionGroups
|
||||
setQuery={setQuery}
|
||||
setMode={(mode) => {
|
||||
setMode(mode);
|
||||
setChildrenOptions(null);
|
||||
@@ -152,7 +154,7 @@ const SpotlightWithActiveMode = ({ modeState, activeMode }: SpotlightWithActiveM
|
||||
});
|
||||
}}
|
||||
query={query}
|
||||
groups={groups}
|
||||
groups={mode === defaultMode && query.length === 0 ? [...homeEmptyGroups] : groups}
|
||||
/>
|
||||
)}
|
||||
</MantineSpotlight.ActionsList>
|
||||
|
||||
@@ -11,6 +11,7 @@ const createSearchInteraction = <TType extends string>(type: TType) => ({
|
||||
const searchInteractions = [
|
||||
createSearchInteraction("link").optionsType<{ href: string; newTab?: boolean }>(),
|
||||
createSearchInteraction("javaScript").optionsType<{ onSelect: () => MaybePromise<void> }>(),
|
||||
createSearchInteraction("setQuery").optionsType<{ query: string }>(),
|
||||
createSearchInteraction("mode").optionsType<{ mode: keyof TranslationObject["search"]["mode"] }>(),
|
||||
createSearchInteraction("children").optionsType<{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Group, Image, Kbd, Stack, Text } from "@mantine/core";
|
||||
import { useDebouncedValue } from "@mantine/hooks";
|
||||
import { IconDownload, IconSearch } from "@tabler/icons-react";
|
||||
import { keepPreviousData } from "@tanstack/react-query";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
@@ -17,6 +19,35 @@ import { interaction } from "../../lib/interaction";
|
||||
|
||||
type SearchEngine = RouterOutputs["searchEngine"]["search"][number];
|
||||
type FromIntegrationSearchResult = RouterOutputs["integration"]["searchInIntegration"][number];
|
||||
type DuckDuckGoBang = RouterOutputs["bangs"]["search"][number];
|
||||
|
||||
type ExternalOption =
|
||||
| {
|
||||
key: string;
|
||||
kind: "hint";
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
| {
|
||||
key: string;
|
||||
kind: "search";
|
||||
label: string;
|
||||
description?: string;
|
||||
iconUrl?: string;
|
||||
bang: string;
|
||||
urlTemplate: string;
|
||||
searchText: string;
|
||||
}
|
||||
| {
|
||||
key: string;
|
||||
kind: "engine";
|
||||
engine: SearchEngine;
|
||||
}
|
||||
| {
|
||||
key: string;
|
||||
kind: "ddg";
|
||||
bang: DuckDuckGoBang;
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
||||
type MediaRequestChildrenProps = {
|
||||
@@ -235,57 +266,217 @@ export const searchEnginesChildrenOptions = createChildrenOptions<SearchEngine>(
|
||||
},
|
||||
});
|
||||
|
||||
export const searchEnginesSearchGroups = createGroup<SearchEngine>({
|
||||
keyPath: "short",
|
||||
const parseBangQuery = (query: string) => {
|
||||
const withBangPrefix = query.startsWith("!") ? query.slice(1) : query;
|
||||
const bangIdx = withBangPrefix.indexOf(" ");
|
||||
const bangToken = (bangIdx === -1 ? withBangPrefix : withBangPrefix.slice(0, bangIdx)).toLowerCase().trim();
|
||||
const searchText = bangIdx === -1 ? "" : withBangPrefix.slice(bangIdx + 1);
|
||||
const locked = bangIdx !== -1;
|
||||
return { bangToken, searchText, locked };
|
||||
};
|
||||
|
||||
const buildSearchUrl = (template: string, query: string) => {
|
||||
const encoded = encodeURIComponent(query);
|
||||
if (template.includes("{{{s}}}")) {
|
||||
return template.replaceAll("{{{s}}}", encoded);
|
||||
}
|
||||
|
||||
return template.replaceAll("%s", encoded);
|
||||
};
|
||||
|
||||
export const searchEnginesSearchGroups = createGroup<ExternalOption>({
|
||||
keyPath: "key",
|
||||
title: (t) => t("search.mode.external.group.searchEngine.title"),
|
||||
Component: ({ iconUrl, name, short, description }) => {
|
||||
Component: (option) => {
|
||||
if (option.kind === "hint") {
|
||||
return (
|
||||
<Group w="100%" wrap="nowrap" align="center" px="md" py="xs">
|
||||
<IconSearch stroke={1.5} />
|
||||
<Stack gap={0}>
|
||||
<Text size="sm">{option.label}</Text>
|
||||
{option.description ? (
|
||||
<Text size="xs" c="gray.6">
|
||||
{option.description}
|
||||
</Text>
|
||||
) : null}
|
||||
</Stack>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
if (option.kind === "search") {
|
||||
return (
|
||||
<Group w="100%" wrap="nowrap" justify="space-between" align="center" px="md" py="xs">
|
||||
<Group wrap="nowrap">
|
||||
{option.iconUrl ? (
|
||||
<img height={24} width={24} src={option.iconUrl} alt={option.label} />
|
||||
) : (
|
||||
<IconSearch stroke={1.5} />
|
||||
)}
|
||||
<Stack gap={0} justify="center">
|
||||
<Text size="sm">{option.label}</Text>
|
||||
{option.description ? (
|
||||
<Text size="xs" c="gray.6">
|
||||
{option.description}
|
||||
</Text>
|
||||
) : null}
|
||||
</Stack>
|
||||
</Group>
|
||||
|
||||
<Kbd size="sm">!{option.bang}</Kbd>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
if (option.kind === "engine") {
|
||||
const { iconUrl, name, short, description } = option.engine;
|
||||
return (
|
||||
<Group w="100%" wrap="nowrap" justify="space-between" align="center" px="md" py="xs">
|
||||
<Group wrap="nowrap">
|
||||
<img height={24} width={24} src={iconUrl} alt={name} />
|
||||
<Stack gap={0} justify="center">
|
||||
<Text size="sm">{name}</Text>
|
||||
<Text size="xs" c="gray.6">
|
||||
{description}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
|
||||
<Kbd size="sm">!{short}</Kbd>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
const { s: name, t: short, d: domain } = option.bang;
|
||||
return (
|
||||
<Group w="100%" wrap="nowrap" justify="space-between" align="center" px="md" py="xs">
|
||||
<Group wrap="nowrap">
|
||||
<img height={24} width={24} src={iconUrl} alt={name} />
|
||||
<IconSearch stroke={1.5} />
|
||||
<Stack gap={0} justify="center">
|
||||
<Text size="sm">{name}</Text>
|
||||
<Text size="xs" c="gray.6">
|
||||
{description}
|
||||
{domain ?? "DuckDuckGo bang"}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
|
||||
<Kbd size="sm">{short}</Kbd>
|
||||
<Kbd size="sm">!{short}</Kbd>
|
||||
</Group>
|
||||
);
|
||||
},
|
||||
onKeyDown(event, options, query, { setChildrenOptions }) {
|
||||
if (event.code !== "Space") return;
|
||||
|
||||
const engine = options.find((option) => option.short === query);
|
||||
if (!engine) return;
|
||||
|
||||
setChildrenOptions(searchEnginesChildrenOptions(engine));
|
||||
},
|
||||
useInteraction: (searchEngine, query) => {
|
||||
useInteraction(option, query) {
|
||||
const { openSearchInNewTab } = useSettings();
|
||||
if (searchEngine.type === "generic" && searchEngine.urlTemplate) {
|
||||
const { bangToken, searchText } = parseBangQuery(query);
|
||||
|
||||
if (option.kind === "search") {
|
||||
return {
|
||||
type: "link" as const,
|
||||
href: searchEngine.urlTemplate.replace("%s", query),
|
||||
type: "link",
|
||||
href: buildSearchUrl(option.urlTemplate, option.searchText),
|
||||
newTab: openSearchInNewTab,
|
||||
};
|
||||
}
|
||||
|
||||
if (searchEngine.type === "fromIntegration" && searchEngine.integrationId !== null) {
|
||||
return {
|
||||
type: "children",
|
||||
...searchEnginesChildrenOptions(searchEngine),
|
||||
};
|
||||
if (option.kind === "engine") {
|
||||
const nextBang = option.engine.short;
|
||||
const nextQuery = `${`${nextBang} ${searchText}`.trimEnd()} `;
|
||||
return { type: "setQuery", query: bangToken === nextBang && query.endsWith(" ") ? query : nextQuery };
|
||||
}
|
||||
|
||||
throw new Error(`Unable to process search engine with type ${searchEngine.type}`);
|
||||
if (option.kind === "ddg") {
|
||||
const nextBang = option.bang.t;
|
||||
const nextQuery = `${`${nextBang} ${searchText}`.trimEnd()} `;
|
||||
return { type: "setQuery", query: bangToken === nextBang && query.endsWith(" ") ? query : nextQuery };
|
||||
}
|
||||
|
||||
return { type: "none" };
|
||||
},
|
||||
useQueryOptions(query) {
|
||||
return clientApi.searchEngine.search.useQuery({
|
||||
query: query.trim(),
|
||||
limit: 5,
|
||||
});
|
||||
const tExternal = useScopedI18n("search.mode.external.group.searchEngine");
|
||||
const { ddgBangs } = useSettings();
|
||||
const { bangToken, searchText, locked } = parseBangQuery(query);
|
||||
const [debouncedBangToken] = useDebouncedValue(bangToken, 150);
|
||||
|
||||
const enginesQuery = clientApi.searchEngine.search.useQuery(
|
||||
{ query: debouncedBangToken, limit: 10 },
|
||||
{ placeholderData: keepPreviousData },
|
||||
);
|
||||
|
||||
const ddgQuery = clientApi.bangs.search.useQuery(
|
||||
{ query: debouncedBangToken, limit: 10 },
|
||||
{
|
||||
enabled: ddgBangs && debouncedBangToken.length >= 1,
|
||||
placeholderData: keepPreviousData,
|
||||
},
|
||||
);
|
||||
|
||||
const isLoading = enginesQuery.isLoading || ddgQuery.isLoading;
|
||||
const isError = enginesQuery.isError || ddgQuery.isError;
|
||||
|
||||
const engineOptions = (enginesQuery.data ?? []).map(
|
||||
(engine): ExternalOption => ({
|
||||
key: `engine-${engine.short}`,
|
||||
kind: "engine",
|
||||
engine,
|
||||
}),
|
||||
);
|
||||
|
||||
const ddgOptions = (ddgQuery.data ?? [])
|
||||
.filter((bang) => !engineOptions.some((option) => option.kind === "engine" && option.engine.short === bang.t))
|
||||
.map(
|
||||
(bang): ExternalOption => ({
|
||||
key: `ddg-${bang.t}`,
|
||||
kind: "ddg",
|
||||
bang,
|
||||
}),
|
||||
);
|
||||
|
||||
const searchActions: ExternalOption[] = [];
|
||||
if (locked && bangToken.length > 0) {
|
||||
const matchedEngine = (enginesQuery.data ?? []).find((engine) => engine.short === bangToken);
|
||||
const matchedDdg = (ddgQuery.data ?? []).find((bang) => bang.t === bangToken);
|
||||
|
||||
const label = matchedEngine?.name ?? matchedDdg?.s;
|
||||
const iconUrl = matchedEngine?.iconUrl;
|
||||
const urlTemplate = matchedEngine?.type === "generic" ? matchedEngine.urlTemplate : matchedDdg?.u;
|
||||
|
||||
if (label && urlTemplate) {
|
||||
if (searchText.trim().length > 0) {
|
||||
searchActions.push({
|
||||
key: "search-action",
|
||||
kind: "search",
|
||||
label: tExternal("bang.searchWithQuery", {
|
||||
query: searchText.trim(),
|
||||
label,
|
||||
}),
|
||||
description: tExternal("bang.pressEnterToOpen"),
|
||||
bang: bangToken,
|
||||
iconUrl,
|
||||
urlTemplate,
|
||||
searchText: searchText.trim(),
|
||||
});
|
||||
} else {
|
||||
searchActions.push({
|
||||
key: "search-hint",
|
||||
kind: "hint",
|
||||
label: tExternal("bang.engineSelected", { label, bang: bangToken }),
|
||||
description: tExternal("bang.typeQueryToContinue"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (query.length === 0) {
|
||||
searchActions.push({
|
||||
key: "hint",
|
||||
kind: "hint",
|
||||
label: tExternal("bang.emptyBangHint"),
|
||||
description: ddgBangs ? tExternal("tipDdgBangs") : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
isError,
|
||||
data: [...searchActions, ...engineOptions, ...ddgOptions].slice(0, 10),
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { Group, Kbd, Text } from "@mantine/core";
|
||||
import {
|
||||
IconBook2,
|
||||
IconBrandDiscord,
|
||||
IconBrandGithub,
|
||||
IconLayoutDashboard,
|
||||
IconSearch,
|
||||
IconSettings,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { createDocumentationLink } from "@homarr/definitions";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import type { TablerIcon } from "@homarr/ui";
|
||||
|
||||
import { createGroup } from "../../lib/group";
|
||||
import { interaction } from "../../lib/interaction";
|
||||
import type { SearchMode } from "../../lib/mode";
|
||||
import { appIntegrationBoardMode } from "../app-integration-board";
|
||||
import { commandMode } from "../command";
|
||||
import { externalMode } from "../external";
|
||||
import { pageMode } from "../page";
|
||||
import { userGroupMode } from "../user-group";
|
||||
|
||||
// We need type to allow it as generic type for Record<string, unknown>
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
||||
type QuickLinkOption = {
|
||||
icon: TablerIcon;
|
||||
name: string;
|
||||
path: string;
|
||||
};
|
||||
|
||||
export const useHomeEmptyGroups = () => {
|
||||
const { data: session } = useSession();
|
||||
const tPages = useScopedI18n("search.mode.page.group.page.option");
|
||||
const visibleSearchModes: SearchMode[] = [appIntegrationBoardMode, externalMode, commandMode, pageMode];
|
||||
|
||||
if (session?.user.permissions.includes("admin")) {
|
||||
visibleSearchModes.unshift(userGroupMode);
|
||||
}
|
||||
|
||||
return [
|
||||
createGroup({
|
||||
keyPath: "path",
|
||||
title: () => "Quick links",
|
||||
options: (() => {
|
||||
const quickLinks: QuickLinkOption[] = [];
|
||||
if (session?.user) {
|
||||
quickLinks.push({
|
||||
icon: IconSettings,
|
||||
path: `/manage/users/${session.user.id}/general`,
|
||||
name: tPages("preferences.label"),
|
||||
});
|
||||
}
|
||||
|
||||
quickLinks.push({
|
||||
icon: IconLayoutDashboard,
|
||||
path: "/manage/boards",
|
||||
name: tPages("manageBoard.label"),
|
||||
});
|
||||
|
||||
if (session?.user.permissions.includes("admin")) {
|
||||
quickLinks.push({
|
||||
icon: IconSettings,
|
||||
path: "/manage/settings",
|
||||
name: tPages("manageSettings.label"),
|
||||
});
|
||||
}
|
||||
|
||||
if (session) {
|
||||
quickLinks.push({
|
||||
icon: IconSearch,
|
||||
path: "/manage/search-engines",
|
||||
name: tPages("manageSearchEngine.label"),
|
||||
});
|
||||
}
|
||||
|
||||
return quickLinks;
|
||||
})(),
|
||||
Component: ({ name, icon: Icon }) => (
|
||||
<Group px="md" py="xs" w="100%" wrap="nowrap" align="center">
|
||||
<Icon stroke={1.5} />
|
||||
<Text>{name}</Text>
|
||||
</Group>
|
||||
),
|
||||
filter: () => true,
|
||||
useInteraction: interaction.link(({ path }) => ({ href: path })),
|
||||
}),
|
||||
createGroup({
|
||||
keyPath: "character",
|
||||
title: (t) => t("search.mode.help.group.mode.title"),
|
||||
options: visibleSearchModes.map(({ character, modeKey }) => ({ character, modeKey })),
|
||||
Component: ({ modeKey, character }) => {
|
||||
const t = useScopedI18n(`search.mode.${modeKey}`);
|
||||
|
||||
return (
|
||||
<Group px="md" py="xs" w="100%" wrap="nowrap" align="center" justify="space-between">
|
||||
<Text>{t("help")}</Text>
|
||||
<Kbd size="sm">{character}</Kbd>
|
||||
</Group>
|
||||
);
|
||||
},
|
||||
filter: () => true,
|
||||
useInteraction: interaction.mode(({ modeKey }) => ({ mode: modeKey })),
|
||||
}),
|
||||
createGroup({
|
||||
keyPath: "href",
|
||||
title: (t) => t("search.mode.help.group.help.title"),
|
||||
useOptions() {
|
||||
const t = useScopedI18n("search.mode.help.group.help.option");
|
||||
|
||||
return [
|
||||
{
|
||||
href: createDocumentationLink("/docs/getting-started"),
|
||||
icon: IconBook2,
|
||||
label: t("documentation.label"),
|
||||
},
|
||||
{
|
||||
href: "https://github.com/homarr-labs/homarr/issues/new/choose",
|
||||
icon: IconBrandGithub,
|
||||
label: t("submitIssue.label"),
|
||||
},
|
||||
{
|
||||
href: "https://discord.com/invite/aCsmEV5RgA",
|
||||
icon: IconBrandDiscord,
|
||||
label: t("discord.label"),
|
||||
},
|
||||
];
|
||||
},
|
||||
Component: (props) => (
|
||||
<Group px="md" py="xs" w="100%" wrap="nowrap" align="center">
|
||||
<props.icon stroke={1.5} />
|
||||
<Text>{props.label}</Text>
|
||||
</Group>
|
||||
),
|
||||
filter: () => true,
|
||||
useInteraction: interaction.link(({ href }) => ({ href, newTab: true })),
|
||||
}),
|
||||
] as const;
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Box, Group, Stack, Text } from "@mantine/core";
|
||||
import { IconCaretUpDown, IconSearch, IconSearchOff } from "@tabler/icons-react";
|
||||
import { IconSearch, IconSearchOff } from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
@@ -79,20 +79,7 @@ export const homeSearchEngineGroup = createGroup<GroupItem>({
|
||||
isLoading:
|
||||
defaultSearchEngineQuery.isLoading || (resultQuery.isLoading && fromIntegrationEnabled) || status === "loading",
|
||||
isError: defaultSearchEngineQuery.isError || (resultQuery.isError && fromIntegrationEnabled),
|
||||
data: [
|
||||
...createDefaultSearchEntries(defaultSearchEngine, results, session, query, t),
|
||||
{
|
||||
id: "other",
|
||||
name: t("search.mode.home.group.search.option.other.label"),
|
||||
icon: IconCaretUpDown,
|
||||
useInteraction() {
|
||||
return {
|
||||
type: "mode",
|
||||
mode: "external",
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
data: createDefaultSearchEntries(defaultSearchEngine, results, session, query, t),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,13 +1,3 @@
|
||||
import { Group, Kbd, Text } from "@mantine/core";
|
||||
import { IconBook2, IconBrandDiscord, IconBrandGithub } from "@tabler/icons-react";
|
||||
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { createDocumentationLink } from "@homarr/definitions";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { createGroup } from "../lib/group";
|
||||
import { interaction } from "../lib/interaction";
|
||||
import type { SearchMode } from "../lib/mode";
|
||||
import { appIntegrationBoardMode } from "./app-integration-board";
|
||||
import { commandMode } from "./command";
|
||||
import { externalMode } from "./external";
|
||||
@@ -15,72 +5,11 @@ import { homeMode } from "./home";
|
||||
import { pageMode } from "./page";
|
||||
import { userGroupMode } from "./user-group";
|
||||
|
||||
const searchModesForHelp = [userGroupMode, appIntegrationBoardMode, externalMode, commandMode, pageMode] as const;
|
||||
|
||||
const helpMode = {
|
||||
modeKey: "help",
|
||||
character: "?",
|
||||
useGroups() {
|
||||
const { data: session } = useSession();
|
||||
const visibleSearchModes: SearchMode[] = [appIntegrationBoardMode, externalMode, commandMode, pageMode];
|
||||
|
||||
if (session?.user.permissions.includes("admin")) {
|
||||
visibleSearchModes.unshift(userGroupMode);
|
||||
}
|
||||
|
||||
return [
|
||||
createGroup({
|
||||
keyPath: "character",
|
||||
title: (t) => t("search.mode.help.group.mode.title"),
|
||||
options: visibleSearchModes.map(({ character, modeKey }) => ({ character, modeKey })),
|
||||
Component: ({ modeKey, character }) => {
|
||||
const t = useScopedI18n(`search.mode.${modeKey}`);
|
||||
|
||||
return (
|
||||
<Group px="md" py="xs" w="100%" wrap="nowrap" align="center" justify="space-between">
|
||||
<Text>{t("help")}</Text>
|
||||
<Kbd size="sm">{character}</Kbd>
|
||||
</Group>
|
||||
);
|
||||
},
|
||||
filter: () => true,
|
||||
useInteraction: interaction.mode(({ modeKey }) => ({ mode: modeKey })),
|
||||
}),
|
||||
createGroup({
|
||||
keyPath: "href",
|
||||
title: (t) => t("search.mode.help.group.help.title"),
|
||||
useOptions() {
|
||||
const t = useScopedI18n("search.mode.help.group.help.option");
|
||||
|
||||
return [
|
||||
{
|
||||
label: t("documentation.label"),
|
||||
icon: IconBook2,
|
||||
href: createDocumentationLink("/docs/getting-started"),
|
||||
},
|
||||
{
|
||||
label: t("submitIssue.label"),
|
||||
icon: IconBrandGithub,
|
||||
href: "https://github.com/homarr-labs/homarr/issues/new/choose",
|
||||
},
|
||||
{
|
||||
label: t("discord.label"),
|
||||
icon: IconBrandDiscord,
|
||||
href: "https://discord.com/invite/aCsmEV5RgA",
|
||||
},
|
||||
];
|
||||
},
|
||||
Component: (props) => (
|
||||
<Group px="md" py="xs" w="100%" wrap="nowrap" align="center">
|
||||
<props.icon />
|
||||
<Text>{props.label}</Text>
|
||||
</Group>
|
||||
),
|
||||
filter: () => true,
|
||||
useInteraction: interaction.link(({ href }) => ({ href, newTab: true })),
|
||||
}),
|
||||
];
|
||||
},
|
||||
} satisfies SearchMode;
|
||||
|
||||
export const searchModes = [...searchModesForHelp, helpMode, homeMode] as const;
|
||||
export const searchModes = [
|
||||
userGroupMode,
|
||||
appIntegrationBoardMode,
|
||||
externalMode,
|
||||
commandMode,
|
||||
pageMode,
|
||||
homeMode,
|
||||
] as const;
|
||||
@@ -157,6 +157,9 @@
|
||||
},
|
||||
"openSearchInNewTab": {
|
||||
"label": "Open search results in new tab"
|
||||
},
|
||||
"ddgBangs": {
|
||||
"label": "Enable DuckDuckGo bangs"
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
@@ -246,6 +249,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"changeDdgBangs": {
|
||||
"notification": {
|
||||
"success": {
|
||||
"message": "DuckDuckGo bangs toggled successfully"
|
||||
},
|
||||
"error": {
|
||||
"message": "Unable to toggle DuckDuckGo bangs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"manageAvatar": {
|
||||
"changeImage": {
|
||||
"label": "Change image",
|
||||
@@ -4535,6 +4548,14 @@
|
||||
"group": {
|
||||
"searchEngine": {
|
||||
"title": "Search engines",
|
||||
"tipDdgBangs": "Tip: You can use any DuckDuckGo bangs here as well, e.g. !something",
|
||||
"bang": {
|
||||
"searchWithQuery": "Search \"{query}\" with {label}",
|
||||
"pressEnterToOpen": "Press Enter to open",
|
||||
"engineSelected": "{label} selected (!{bang})",
|
||||
"typeQueryToContinue": "Type your search query to continue",
|
||||
"emptyBangHint": "Type a bang, e.g. !yt, then press Space to select"
|
||||
},
|
||||
"children": {
|
||||
"action": {
|
||||
"search": {
|
||||
|
||||
@@ -130,6 +130,7 @@ export const userChangeHomeBoardsSchema = z.object({
|
||||
export const userChangeSearchPreferencesSchema = z.object({
|
||||
defaultSearchEngineId: z.string().min(1).nullable(),
|
||||
openInNewTab: z.boolean(),
|
||||
ddgBangsEnabled: z.boolean(),
|
||||
});
|
||||
|
||||
export const userChangeColorSchemeSchema = z.object({
|
||||
@@ -147,3 +148,7 @@ export const userFirstDayOfWeekSchema = z.object({
|
||||
export const userPingIconsEnabledSchema = z.object({
|
||||
pingIconsEnabled: z.boolean(),
|
||||
});
|
||||
|
||||
export const userDdgBangsSchema = z.object({
|
||||
ddgBangs: z.boolean(),
|
||||
});
|
||||
Reference in new issue
Block a user