mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
feat(admin-console): improve route and filter management (#10)
* fix(nuxt): pre-bundle the CommonJS deps of the markdown stack
`debug` and `extend` are imported by micromark and unified through
@elysola/ui. Served unbundled by the dev server they have no default
export, so the console page failed with a 500 in `nuxt dev`.
* docs(deployment): list the fragments and feishu link migrations
The manual `d1 execute` fallback stopped at 0008, and AGENTS.md named
0001..0010 although 0011 already exists.
* feat(storage): persist the per-group route order
Routes used to load in id order, so the order saved from the console
was lost on the next read. Migration 0012 adds `d1_routes.position`:
saving writes each route's index within its own group (saving one group
never shifts another), and routes load by `group_id, position, id`.
A database without the column keeps working: only a "no such column" /
"has no column named" error falls back to the legacy statements, and
nothing is cached, so a later migration is picked up on the next call.
* feat(console): add in-app destructive-action confirmation
Deleting a route or a group used `window.confirm`, which blocks the page
and ignores the console theme. A promise-based `useConfirm()` now drives
one <ConfirmDialog /> built on the reka-ui AlertDialog that
@elysola/ui ships; reka-ui is pre-bundled so dev keeps a single copy and
the dialog stacks with the Rc dialogs.
A request never outlives its asker: one made after the asking component
unmounted resolves false, and one still open when it unmounts is
cancelled.
* feat(console): confirm member and webhook removal
Removing a member, revoking an invite link and disabling a group's
webhook endpoint took effect on the first click. They now ask first;
disabling the webhook explains that senders still using the secret will
be rejected, and its button is styled as destructive.
* feat(console): confirm removing filled editor rows
Filter conditions and groups, delivery targets, saved fragments and forge
hosts vanished on a single click, taking whatever had been typed with
them. Rows holding content now ask first, while empty, never-filled
rows (`isBlankNode`: default operator, no path, no values, not negated)
are still removed directly.
* fix(i18n): remove duplicate button glyphs
"New Route", "New Group" and the group cards' "Open" link render a Plus
or ArrowRight icon next to their label, so the "+" and "→" baked into
the strings appeared twice.
* style(console): redesign route cards for narrow screens
The card was one flex row whose badges, filter chips, targets and five
hand-drawn icon buttons squeezed the route name on small screens. It is
now a grid driven by a container query: name and actions share the top
line, the filter summary (clamped to two lines) and targets follow, and
the tags wrap below; from 40rem the tags move up beside the title.
Targets of the same platform collapse into one tag with a count, long
ids truncate instead of widening the page, and the actions use lucide
icons with accessible labels.
* feat(console): reorder a group's routes by drag or keyboard
The per-card up/down arrows saved after every single step, so moving a
route five places took five writes. A Reorder mode on the group page now
swaps each card's switch for a drag handle: pointer drags (mouse and
touch) slide the neighbours out of the way and auto-scroll near the
viewport edges, Arrow Up/Down on a focused handle moves a card by one
and is announced to screen readers, and nothing is written until Save
order. Cancel or Escape (unless a dialog or list owns it) drops the
draft.
The cards move into a new RouteList component that owns the drag state.
* style(members): align member cards and invite actions
* style(group-editor): size forge and log target controls
Keep source hosts, platform selectors and remove actions aligned without stretching short controls across the dialog. Wrap component roots explicitly so their internal markup cannot break the grid.
* style(route-editor): group options and delivery target fields
Give each target labeled fields and a compact platform header, widen the filter workspace, and align fragment controls. Scroll failed validation into view when the footer is far from the affected section.
* feat(filters): add bilingual suggestions and value validation
Catalog forge events, actions, payload paths and known values with searchable English and Chinese descriptions. Match-value validation mirrors the server and only rejects inputs that cannot match.
* feat(filters): add searchable creatable value inputs
Build a theme-aligned combobox on the shared reka-ui primitives. Rank stored keys before bilingual descriptions, allow validated custom values, and preserve unconfirmed multi-value drafts instead of silently committing them.
* feat(filter-editor): integrate searchable condition inputs
Replace chip-only values with context-aware bilingual inputs and a compact condition grid. Preserve drafts across tree changes, block saves and tests until drafts are resolved, and keep keyword filters free of hidden operators.
* feat(filters): split pasted values without breaking regexes
Accept multiple values separated by commas or lines while retaining commas inside wrapped expressions and raw regex patterns. Pasting replaces the selected range and keeps rejected values as an explicit draft.
* fix(filters): adapt suggestions to the selected operator
Offer literal prefixes and suffixes for substring operators, escaped anchored patterns for regex, and numeric suggestions only for comparisons. Suggestion syntax must mean what the selected matcher actually reads.
* fix(filters): preserve regex meaning when changing operators
Swap wrapped and raw regex sources only when both compile identically after saving. Leave literal, glob, multiline and Unicode-sensitive comparisons unchanged rather than inventing non-equivalent conversions.
* a11y(filter-editor): label type and operator controls
Associate each fixed select with a stable per-condition label while keeping the compact visual layout unchanged.
* fix(editors): ignore accidental backdrop dismissal
Do not discard unsaved route or group edits when the user clicks outside the dialog. Preserve Escape, Cancel and explicit close, including popovers and confirmation dialogs stacked above the editor.
* feat(dispatch)!: scope stop and fallback to each group
A match in one group must not suppress delivery in another group. Track regular matches and stopped scopes independently, and document the routing-table boundary.
BREAKING CHANGE: stop and fallback no longer apply globally across
groups. Put mutually exclusive routes in the same group and define
fallback routes in each group that needs its own catch-all.
* fix(dispatch): honor stop on a matching fallback route
Once a fallback matches with stop enabled, skip later routes of the same group without affecting other groups. Cover multiple fallback routes in the group-isolation regression test.
* style(console): pin theme and language controls to the right
Separate utility controls from page actions so narrow screens retain a readable title column and right-aligned actions below. Wrap long headings without letting them push controls out of view.
* style(groups): place creation beside the aligned group count
Keep the new-group action inside the group list at every width and align the label and count on one baseline with a consistent type scale.
* style(groups): align card footers and keep role badges intact
Give long names two lines, show the current role in its own non-wrapping row, and anchor every card footer to the grid-row bottom regardless of optional source metadata.
* style(logs): prevent filter labels and metadata overflow
Keep filter labels on one line and allow long channel, thread and repository identifiers to wrap instead of widening the page.
* style(console): scale the sidebar and hide mobile tab tracks
Narrow the sidebar proportionally while retaining enough room for both locales. Keep mobile navigation swipeable without a visible horizontal scrollbar.
* feat(console): give each group its own routes URL
Resolve the selected group from /admin/groups/{groupId}, validate console paths, and use browser history for back navigation. Keep Groups active and let an active mobile-tab tap return to the list. Scope pending route loads to their group and retain the count beside long headings.
* feat(console): confirm leaving unsaved page work
Guard route changes when an editor or changed order draft is open. Cancel superseded questions and restore the shown history entry when repeated Back or Forward navigation is refused; only completed navigation resets page work.
* feat(console): confirm sign-out from desktop and mobile
Expose sign-out in the mobile topbar when the sidebar is hidden. Both entry points use the in-app confirmation before navigating to the server logout endpoint.
* fix(console): keep topbar tools clear of very narrow headings
Below 360px, place the full-width heading beneath the breadcrumb and utility row so the three top-right buttons cannot overlap it.
* feat(console): prioritize group titles over actions
Place New Route after Reorder in the group bar. Measure available space and remove the reorder label first, then the creation label, before truncating the group title; remeasure on resize, locale and font changes.
* fix(editors): focus the dialog without selecting its name field
Cancel the non-bubbling FocusScope mount event in the capture phase and focus the dialog itself. Keep keyboard navigation working without highlighting the name or opening the touch keyboard automatically.
* perf(console): preserve one instance across admin navigation
Use a fixed page key instead of remounting the whole console for each URL. Refresh each view when shown and isolate overview metrics and logs so page filters cannot leak into the dashboard.
* fix(console-data): discard superseded load responses
Only the latest request may update a list, its error or loading state. Invalidate pending group loads after a save so an older response cannot restore stale configuration during persistent-console navigation.
* fix(routes): serialize writes and reject unloaded route lists
Whole-list saves must start from loaded data and wait for other route writes. Lock switches and actions during saves, recheck deletion after confirmation, and rebuild saved ordering from the newest route objects.
* fix(editors): scope async results and fragment writes to sessions
A completed save or dry run must not close or overwrite a newer editor. Keep fragment state scoped by group, reject writes until the real list is ready, and retain in-flight fragment locks across navigation.
* fix(groups): serialize edits and isolate group detail panels
Prevent overlapping whole-list writes, avoid duplicate ids after rename, and discard delete confirmations prepared on a page that has since been left. Key member and webhook panels by group so local state cannot cross tenants.
* fix(console): omit the empty action row outside overview
Render the refresh-action container only where it has content so narrow layouts do not reserve a blank row after creation controls move into their page bars.
* perf(metrics): send all seven queries in one D1 batch
Avoid seven sequential network round trips and read totals, breakdowns and recent failures in one consistent transaction. Reuse the failed-send statement and row mapping while retaining group scoping.
* fix(admin-api): bypass browser cache locks for live requests
Use no-store on both client requests and admin responses. Personalized live data must not be reused, and one stalled same-URL cache entry must not block later log requests behind the browser cache lock.
* docs(routes): Clarify fallback hints and document group-scoped stop and fallback upgrade behavior
This commit is contained in:
55 files changed
+5778
-985
No files matched your search
@@ -9,16 +9,16 @@ Core pipeline: GitHub Webhook → Worker (verify + filter + format) → Discord
|
||||
## Key Decisions
|
||||
|
||||
- Runtime: Cloudflare Workers via the Nitro `cloudflare_module` preset (`_worker.js`), H3 event handlers in `server/routes/`
|
||||
- UI: Vue 3 + Tailwind CSS v4 (`@tailwindcss/vite`) + `@elysola/ui` (Nuxt module, `Rc` prefix); admin console is a client-side SPA (`routeRules: "/admin/**": { ssr: false }`), home/legal pages render server-side
|
||||
- UI: Vue 3 + Tailwind CSS v4 (`@tailwindcss/vite`) + `@elysola/ui` (Nuxt module, `Rc` prefix); admin console is a client-side SPA (`routeRules: "/admin/**": { ssr: false }`), home/legal pages render server-side; app-level composites (`FilterCombobox`, `ConfirmDialog`) are built on the reka-ui primitives that `@elysola/ui` ships (same copy, pre-bundled via `vite.optimizeDeps.include` so dev keeps a single instance and dialogs/popovers stack correctly) and styled like their Rc counterparts
|
||||
- Styling: Elysola UI supplies semantic components and blue theme tokens; `app/assets/css/main.css` retains `--wh-*` RGB-triplet aliases for app-specific Tailwind utilities and bespoke layouts (avoiding collision with Elysola's `--surface`/`--text`/`--border` hex tokens); theme switching supports auto/light/dark via `useTheme` / `ThemeToggle`, toggling `<html>.dark` with inline anti-flash head script
|
||||
- Discord interactions: HTTPS Interactions Endpoint (`POST /discord/interactions`, Ed25519-signed) — no Discord Gateway / Durable Object; bot stays offline, messages always sent via REST
|
||||
- Storage: D1 is the source of truth for config (routes/groups via `d1_routes`/`d1_groups`, see `server/lib/storage/config-store.ts`), send/audit logs, dedup (`dedup_keys`), delivery state (`delivery_state`) and message tracking (`message_tracking` via `server/lib/storage/d1.ts` `canUseD1` gate). KV keeps only cache + short-lived/ephemeral state (tokens, OAuth state, admin sessions, `msg:*`-adjacent locks, per-group secrets `tenant:*`, invites, i18n overrides) with explicit TTLs. R2 parks oversized queue payloads (`webhooks/YYYY/MM/DD/*.json`, `server/lib/storage/payload.ts`) instead of KV. A `storage-prune` scheduled task cleans up expired dedup/delivery/message-tracking rows
|
||||
- Storage: D1 is the source of truth for config (routes/groups via `d1_routes`/`d1_groups`, see `server/lib/storage/config-store.ts`; each route's per-group order lives in `d1_routes.position` — migration 0012 — and routes load ordered by `group_id, position, id`, falling back to id order on an unmigrated database), send/audit logs, dedup (`dedup_keys`), delivery state (`delivery_state`) and message tracking (`message_tracking` via `server/lib/storage/d1.ts` `canUseD1` gate). KV keeps only cache + short-lived/ephemeral state (tokens, OAuth state, admin sessions, `msg:*`-adjacent locks, per-group secrets `tenant:*`, invites, i18n overrides) with explicit TTLs. R2 parks oversized queue payloads (`webhooks/YYYY/MM/DD/*.json`, `server/lib/storage/payload.ts`) instead of KV. A `storage-prune` scheduled task cleans up expired dedup/delivery/message-tracking rows
|
||||
- Signature verification: Web Crypto API (HMAC-SHA256 for GitHub/Gitea, Ed25519 for Discord, timing-safe secret-token compare for Telegram)
|
||||
- Webhook providers: pluggable forge adapters under `server/lib/providers/` (github, gitea) — each verifies its own signature format and normalizes its payload to a GitHub-shaped `WebhookEvent`; a `custom` provider accepts arbitrary signed JSON posts (`X-WebHooker-Signature`) as `custom` events; GitLab etc. can be added later
|
||||
- Per-group webhook ingress: optional `POST /webhook/{groupId}` with a per-group secret in KV (`tenant:{groupId}`) — Gitea/classic-GitHub/custom webhooks are verified against the group's secret instead of the operator's global ones; only that group's routes fire. The legacy `POST /webhook` (global secrets, all routes) stays untouched
|
||||
- GitHub App tenant isolation: `Group.installationId` binds a group to one GitHub App installation; events whose `payload.installation.id` differs are rejected at dispatch (hard isolation on top of the optional `owners` list). The App's Setup URL points at `GET /auth/github/install`, which renders a choice page (create `inst-{installationId}` or bind to a group the signed-in user owns, verified by role); `POST /auth/github/install/bind` performs the provisioning. `installation.created` webhook events auto-provision as a fallback (create `inst-{installationId}` or bind existing groups whose `owners` match the installing account)
|
||||
- GitHub OAuth: octokit (token is stored hashed for reverse lookup)
|
||||
- Admin WebUI: `/admin` config console, OAuth-session protected via `ADMIN_USER_IDS` whitelist (local-only `DEBUG_MODE=true` bypasses authentication); left sidebar navigation (Overview / Groups / Send Logs / Audit / Stats) + topbar, deep-linkable routes (`/admin` overview · `/admin/groups` · `/admin/logs` · `/admin/audit` · `/admin/metrics`); the overview dashboard (`AdminHome.vue`) aggregates delivery KPIs, a routes table and recent send logs; the stats page (`MetricsPanel.vue`) renders KPI cards plus per-platform/per-event ok/failed bar legends and a per-status breakdown, and filters by group (`?groupId=`); the route/group editors (`RouteEditor.vue` / `GroupEditor.vue`) are centered, scrollable `RcDialog` forms with an eyebrow header and sectioned bodies
|
||||
- Admin WebUI: `/admin` config console, OAuth-session protected via `ADMIN_USER_IDS` whitelist (local-only `DEBUG_MODE=true` bypasses authentication); left sidebar navigation (Overview / Groups / Send Logs / Audit / Stats) + topbar, deep-linkable routes (`/admin` overview · `/admin/groups` · `/admin/groups/{groupId}` a group's routes, members and webhook · `/admin/logs` · `/admin/audit` · `/admin/metrics`, parsed by `app/utils/admin-path.ts`; the admin page's `validate` 404s any other path) — the page has a fixed `key`, so one console instance (and its in-flight saves) persists across these URLs while each view refreshes its data when shown; every page is a history entry, so the browser's back button returns from a group to the list (no in-page back button) and leaving with an open editor or an unsaved route order asks first; route switches/actions lock while a route write is in flight; sign-out asks for confirmation (sidebar, or a top-right button on narrow screens); editor dialogs open without focusing a field (`useDialogFocus`); the overview dashboard (`AdminHome.vue`) aggregates delivery KPIs, a routes table and recent send logs; the stats page (`MetricsPanel.vue`) renders KPI cards plus per-platform/per-event ok/failed bar legends and a per-status breakdown, and filters by group (`?groupId=`); the route/group editors (`RouteEditor.vue` / `GroupEditor.vue`) are centered, scrollable `RcDialog` forms with an eyebrow header and sectioned bodies
|
||||
- Access control: every group has role-based members (`owner` / `admin` / `viewer`); super admins bypass; legacy `adminIds` are read as owners (backward compatible); owners manage members + invites; `owners` field stays super-only
|
||||
- Invites: single-use 7-day links (`invite:{token}`) for joining a group as admin/viewer; `ALLOW_SELF_SIGNUP=1` gives access-less users a personal group on first login (self-service SaaS entry)
|
||||
- Audit log: every admin operation (logins, group/route/member/invite changes) recorded in D1 `audit_logs`; pruned by the scheduled trigger after `AUDIT_RETENTION_DAYS` (default 90)
|
||||
@@ -26,7 +26,7 @@ Core pipeline: GitHub Webhook → Worker (verify + filter + format) → Discord
|
||||
- Per-group forge branding: optional `Group.forgeSources` (a list of `{ host, type: "github" | "gitea", name? }` the group defines itself) labels each message's footer with the first entry whose type matches the event's provider and whose host matches the repository URL's hostname (GitHub matches `github.com`, so two Gitea instances can be `git1.example.com`/`git2.example.com`); the label is the entry's optional `name` (fallback: host); links are derived from the repo URL and footer icons use raster PNGs Discord renders (GitHub's `fluidicon.png`, Gitea's `/assets/img/favicon.png` — `.ico` favicons are silently ignored); Discord shows the footer icon + name, Telegram a linked name
|
||||
- Delivery queue: when the `QUEUE` binding is present, webhook ingress enqueues one message per event (not per target) to a Cloudflare Queue (`webhooker-delivery`); a Nitro `cloudflare:queue` plugin consumes batches, dispatches, and retries retryable failures (5xx/network/429-exhaustion) with exponential backoff (5s/30s/2m/10m) up to the queue `max_retries`, after which the DLQ (`webhooker-delivery-dlq`) marks the delivery dead. Oversized payloads (>~100 KB) are parked in R2 (`webhooks/YYYY/MM/DD/*.json`, falling back to KV `queue:payload:*` without the R2 binding) and resolved by the consumer; delivery state is tracked as the D1 `delivery_state` table (KV `delivery-state:*` fallback). Without the `QUEUE` binding, dispatch stays inline (existing behavior)
|
||||
- Storage quotas: the design avoids KV write pressure (Workers Free KV allows ~1,000 writes/day) by keeping high-frequency ephemeral writes in D1 instead — webhook dedup (`dedup_keys`, atomic `ON CONFLICT` UPSERT), delivery state and message tracking all use D1 rows via `canUseD1` (prepare+batch probe) with automatic KV fallback when D1 is unavailable or unmigrated. D1 Free allows 100,000 rows written/day, so the per-event KV write cost drops to ~0; config stays cached in memory + KV with D1 authoritative
|
||||
- Filter DSL: a route's flat `filters` can be replaced by a nested `ast` (`all`/`any`/`not` nodes, `server/lib/events/filter-ast.ts`) that takes precedence when present; the `field` filter type reads any payload value by JSONPath (`path`, arrays expand so any element matches) and 12 comparison operators (`op`: `eq`/`ne`/`contains`/`startsWith`/`endsWith`/`regex`/`gt`/`gte`/`lt`/`lte`/`in`/`exists`) extend the legacy glob/regex/case-insensitive-exact semantics; named filter fragments (D1 `d1_fragments` via `server/lib/fragments.ts`, per-group) are editor-side templates inlined into the route's `ast` on insert — the matcher never resolves fragment references; the route editor (`RouteEditor.vue`) exposes a recursive AST builder (`FilterNodeEditor.vue`), chip multi-value input (`TagInput.vue`), live explanation and a stateless `POST /admin/api/test-match` dry-run
|
||||
- Filter DSL: a route's flat `filters` can be replaced by a nested `ast` (`all`/`any`/`not` nodes, `server/lib/events/filter-ast.ts`) that takes precedence when present; the `field` filter type reads any payload value by JSONPath (`path`, arrays expand so any element matches) and 12 comparison operators (`op`: `eq`/`ne`/`contains`/`startsWith`/`endsWith`/`regex`/`gt`/`gte`/`lt`/`lte`/`in`/`exists`) extend the legacy glob/regex/case-insensitive-exact semantics; named filter fragments (D1 `d1_fragments` via `server/lib/fragments.ts`, per-group) are editor-side templates inlined into the route's `ast` on insert — the matcher never resolves fragment references; the route editor (`RouteEditor.vue`) exposes a recursive AST builder (`FilterNodeEditor.vue`: plain selects for filter type/operator, an all/any segmented toggle, NOT toggle + delete pinned per condition), searchable multi-value / path inputs (`FilterCombobox.vue`) fed by a bilingual suggestion catalog (`app/utils/filter-catalog.ts`: GitHub events/actions from `@octokit/webhooks` plus Gitea extras, common payload paths and their known values, English keys searchable in either language) where custom values are allowed but rejected when the matcher could never match them (`validateFilterValue`), a live explanation and a stateless `POST /admin/api/test-match` dry-run
|
||||
- Local dev: wrangler + Miniflare
|
||||
|
||||
## Architecture
|
||||
@@ -37,12 +37,16 @@ app/ # Vue 3 UI (Nuxt app dir)
|
||||
├── assets/css/main.css # Tailwind v4 entry: Elysola-compatible RGB aliases + bespoke layout classes + Vue transition glue
|
||||
├── pages/ # index (landing), terms, privacy, admin/[...slug] (console SPA)
|
||||
├── components/ # ConsolePage (sidebar shell + topbar), AdminHome (overview dashboard),
|
||||
│ # RouteCard/Editor (RouteEditor has FilterNodeEditor AST builder + TagInput chips),
|
||||
│ # GroupEditor, MembersPanel, WebhookPanel,
|
||||
│ # SendLogs, AuditLog, MetricsPanel, AppToasts, LegalLayout
|
||||
├── composables/ # useI18n, useToasts, useGroups, useGroupRoutes, useFilterNode (AST helpers), useFragments, useLogs, useAudit, useInvites, useWebhook
|
||||
│ # RouteList (drag/keyboard reorder mode) + RouteCard, RouteEditor (FilterNodeEditor
|
||||
│ # AST builder + FilterCombobox searchable inputs), GroupEditor, MembersPanel, WebhookPanel,
|
||||
│ # ConfirmDialog (app-wide destructive-action confirm), SendLogs, AuditLog, MetricsPanel,
|
||||
│ # AppToasts, LegalLayout
|
||||
├── composables/ # useI18n, useToasts, useConfirm (promise-based confirm), useBackdropGuard (editor dialogs ignore
|
||||
│ # backdrop clicks), useDialogFocus (editor dialogs open without focusing a field), useGroups, useGroupRoutes, useFilterNode (AST helpers), useFragments, useLogs,
|
||||
│ # useAudit, useInvites, useWebhook
|
||||
├── types.ts # shared client types (Route, Group, Filter, ...)
|
||||
└── utils/legal.ts # terms/privacy HTML bodies (zh/en)
|
||||
└── utils/ # legal.ts (terms/privacy HTML bodies, zh/en), format.ts, admin-path.ts (console URL parsing),
|
||||
# filter-catalog.ts (bilingual filter suggestions + value/path validators)
|
||||
server/ # Nitro server
|
||||
├── routes/ # H3 handlers: /health, /webhook[/:groupId], /discord/interactions, /telegram/webhook,
|
||||
│ # /auth/github*, /admin/{login,logout,invite,api/**}, /api/{comment,merge,close,react,richheader}
|
||||
@@ -123,10 +127,10 @@ server/ # Nitro server
|
||||
│ ├── tenants.ts # Per-group webhook secret CRUD (KV tenant:{groupId}, 32-byte random hex)
|
||||
│ └── richheader.ts # GET /api/richheader: Open Graph page for Telegram avatar link-preview card
|
||||
├── observability/ # delivery metrics aggregation
|
||||
│ └── metrics.ts # DeliveryMetrics + getDeliveryMetrics (SQL GROUP BY over send_logs: totals, per platform/event/status, duration, attempts, recent failures)
|
||||
│ └── metrics.ts # DeliveryMetrics + getDeliveryMetrics (SQL GROUP BY over send_logs in one D1 batch: totals, per platform/event/status, duration, attempts, recent failures)
|
||||
├── storage/ # storage primitives: canUseD1 probe, D1 config store (L1 memory → L2 KV cache → L3 D1), R2 payload store
|
||||
│ ├── d1.ts # canUseD1(db) — prepare+batch probe for D1 availability (falls back to KV)
|
||||
│ ├── config-store.ts # ConfigStore (loadRoutes/saveRoutes/loadGroups/saveGroups/invalidateCache) backed by d1_groups/d1_routes, seeds from KV + syncs cache
|
||||
│ ├── config-store.ts # ConfigStore (loadRoutes/saveRoutes/loadGroups/saveGroups/invalidateCache) backed by d1_groups/d1_routes (per-group `position` order when migrated), seeds from KV + syncs cache
|
||||
│ └── payload.ts # PayloadStore backed by R2 (webhooks/YYYY/MM/DD/*.json), no-binding stub throws
|
||||
└── lib/ # shared infra
|
||||
├── i18n.ts # loadTranslations (KV i18n:{lang} overrides), t() with param interpolation
|
||||
@@ -157,7 +161,7 @@ tests/__snapshots__/ # formatter snapshot golden files (toMatchSnapshot)
|
||||
- Store named filter fragments (D1 `d1_fragments`, per group, `GET`/`PUT /admin/api/groups/:groupId/fragments`) as editor-side templates; inserting a fragment inlines its node into the route's `ast` — dispatch never resolves fragment references
|
||||
- Offer a stateless filter dry-run (`POST /admin/api/test-match`, body `{ node | filters, event?, payload }`) that evaluates in memory and returns `{ matched, explanation }` — no event payload is stored
|
||||
- Validate route/group config against valibot schemas on load (non-destructive: invalid entries log a warning but still load); `CONFIG_SCHEMA_VERSION` marks the schema version and `migrateRoutes`/`migrateGroups` migrate legacy shapes (e.g. `target` → `targets`)
|
||||
- Filter routes by group owner restriction (`Group.owners`), group source-platform restriction (`Group.providers`: github/gitea), GitHub App installation restriction (`Group.installationId`), and skip fallback routes whenever a regular route matched; stop evaluating further routes when a matched route has `stop: true`
|
||||
- Filter routes by group owner restriction (`Group.owners`), group source-platform restriction (`Group.providers`: github/gitea), GitHub App installation restriction (`Group.installationId`), and skip a group's fallback routes whenever a regular route of that group matched; stop evaluating the group's further routes when a matched route has `stop: true` (both scoped per group, so one group's routes never silence another's)
|
||||
- Auto-provision GitHub App installs: the App's Setup URL flow (`/auth/github/install` choice page + `POST /auth/github/install/bind`, owner-role verified for existing groups) and the `installation.created` webhook fallback both create `inst-{installationId}` groups or bind existing groups
|
||||
- Enforce role-based access on every admin API: super admins bypass, `owner` manages the group (routes/members/invites/settings), `admin` edits routes, `viewer` is read-only; legacy `adminIds` groups resolve to `owner` members
|
||||
- Issue single-use 7-day group invite links (`invite:{token}`); accepting joins as admin/viewer (never owner); `ALLOW_SELF_SIGNUP=1` creates a deterministic personal group (`u-{userId}`) on first login
|
||||
@@ -168,7 +172,7 @@ tests/__snapshots__/ # formatter snapshot golden files (toMatchSnapshot)
|
||||
- Route messages to Discord channels/threads and Telegram chats/topics via REST
|
||||
- Edit already-sent messages in place for `workflow_run` / `check_run` progress (stable `updateKey`, `message_tracking` via D1 with KV `msg:*` fallback); `workflow_run` keys on the workflow id while `check_run` keys on check name + commit SHA (falling back to the run id) so providers that emit a fresh run id per phase — e.g. Cloudflare Pages — still edit the same message
|
||||
- Record every dispatch attempt to D1 `send_logs` (route id, event, target, ok/error, duration, error code)
|
||||
- Aggregate delivery metrics (`server/lib/observability/metrics.ts`) from `send_logs` — totals, ok/failed counts + failure rate, per-platform/per-event/per-status breakdowns, average duration and attempts, recent failures; `getDeliveryMetrics(db, groupId?)` scopes every query by `group_id` when a group is passed
|
||||
- Aggregate delivery metrics (`server/lib/observability/metrics.ts`) from `send_logs` — totals, ok/failed counts + failure rate, per-platform/per-event/per-status breakdowns, average duration and attempts, recent failures; `getDeliveryMetrics(db, groupId?)` sends all seven queries as one D1 `batch` (a single round trip and a consistent snapshot) and scopes every query by `group_id` when a group is passed
|
||||
- Expose admin observability endpoints — `GET /admin/api/metrics?groupId=` (delivery metrics, optional group scope; recent failures group-scoped for non-super) and `GET /admin/api/delivery/:deliveryId` (all send-log attempts for one delivery, group-scoped) — through the `/admin/api/[...slug]` catch-all route (`server/routes/admin/api/[...slug].ts`) that wires every admin API handler to its method+path
|
||||
- Serve a per-group webhook ingress (`POST /webhook/{groupId}`, per-group secret in KV `tenant:{groupId}`) for Gitea/classic-GitHub/custom senders; only that group's routes fire; dedup keys are provider- and tenant-scoped (`delivery:{provider}:{groupId}:{id}` via `idempotencyStore`, D1 `dedup_keys` with KV fallback)
|
||||
- Issue a per-request correlation id (`requestId`) in webhook responses and dispatch logs
|
||||
@@ -276,7 +280,7 @@ bunx wrangler d1 create webhooker
|
||||
bunx wrangler queues create webhooker-delivery
|
||||
bunx wrangler queues create webhooker-delivery-dlq
|
||||
# Queues are declared in wrangler.jsonc (QUEUE binding); no env var needed
|
||||
bun run db:migrate:prod # wrangler d1 migrations apply webhooker --remote (migrations/0001..0010)
|
||||
bun run db:migrate:prod # wrangler d1 migrations apply webhooker --remote (migrations/0001..0012)
|
||||
# R2 bucket for oversized payloads (P0): bunx wrangler r2 bucket create webhooker-payloads
|
||||
bunx wrangler deploy
|
||||
```
|
||||
|
||||
@@ -103,11 +103,11 @@ Routes are stored in D1 (`d1_routes`, seeded from legacy KV `config:routes` on f
|
||||
]
|
||||
```
|
||||
|
||||
`target.platform` selects the push target: `discord` (default), `telegram`, or `feishu`. Discord targets require `target.channelId` (optional `threadId` for a thread); Telegram targets require `target.chatId` (optional `topicId` for a topic); Feishu targets require `target.chatId` (optional `topicId` for a topic). A route may also set `stop: true` (skip later routes). Routes belong to **groups** (D1 `d1_groups`, seeded from legacy KV `config:groups`) that scope admin access and can restrict which org/user events flow in. See the [Routes & Targets](https://webhooker.docs.elysola.org/guide/routes) and [Groups & Access Control](https://webhooker.docs.elysola.org/guide/groups) guides for the full schema.
|
||||
`target.platform` selects the push target: `discord` (default), `telegram`, or `feishu`. Discord targets require `target.channelId` (optional `threadId` for a thread); Telegram targets require `target.chatId` (optional `topicId` for a topic); Feishu targets require `target.chatId` (optional `topicId` for a topic). A route may also set `stop: true` (skip later routes of its group). Routes belong to **groups** (D1 `d1_groups`, seeded from legacy KV `config:groups`) that scope admin access and can restrict which org/user events flow in. See the [Routes & Targets](https://webhooker.docs.elysola.org/guide/routes) and [Groups & Access Control](https://webhooker.docs.elysola.org/guide/groups) guides for the full schema.
|
||||
|
||||
### Web UI (`/admin`)
|
||||
|
||||
The built-in config console lets you manage routes and groups in the browser (add / edit / delete / toggle / reorder), inspect send logs, manage group members and invite links, and read the audit log — no KV access needed:
|
||||
The built-in config console lets you manage routes and groups in the browser (add / edit / delete / toggle / drag to reorder — the saved order is the evaluation order), inspect send logs, manage group members and invite links, and read the audit log — no KV access needed:
|
||||
|
||||
1. Set `ADMIN_USER_IDS` to the GitHub user IDs (or logins) allowed to manage the console, e.g. `ADMIN_USER_IDS=12345,RhenCloud`.
|
||||
2. Visit `/admin` and sign in with GitHub. Users with no access get `403` — unless `ALLOW_SELF_SIGNUP=1` (they receive a personal group) or they follow a group invite link.
|
||||
|
||||
+2
-2
@@ -103,11 +103,11 @@ bunx wrangler dev # 启动本地开发服务器
|
||||
]
|
||||
```
|
||||
|
||||
`target.platform` 选择推送目标:`discord`(默认)、`telegram` 或 `feishu`。Discord 目标需 `target.channelId`(可选 `threadId` 指向子区);Telegram 目标需 `target.chatId`(可选 `topicId` 指向话题);飞书目标需 `target.chatId`(可选 `topicId` 指向子话题)。路由还可设置 `stop: true`(跳过后续路由)。路由隶属于**分组**(D1 `d1_groups`,首次加载时从旧版 KV `config:groups` 同步),分组用于限定管理权限,并可限制哪些组织/用户的事件流入。完整模式见[路由与目标](https://webhooker.docs.elysola.org/zh/guide/routes)与[分组与访问控制](https://webhooker.docs.elysola.org/zh/guide/groups)指南。
|
||||
`target.platform` 选择推送目标:`discord`(默认)、`telegram` 或 `feishu`。Discord 目标需 `target.channelId`(可选 `threadId` 指向子区);Telegram 目标需 `target.chatId`(可选 `topicId` 指向话题);飞书目标需 `target.chatId`(可选 `topicId` 指向子话题)。路由还可设置 `stop: true`(跳过本分组的后续路由)。路由隶属于**分组**(D1 `d1_groups`,首次加载时从旧版 KV `config:groups` 同步),分组用于限定管理权限,并可限制哪些组织/用户的事件流入。完整模式见[路由与目标](https://webhooker.docs.elysola.org/zh/guide/routes)与[分组与访问控制](https://webhooker.docs.elysola.org/zh/guide/groups)指南。
|
||||
|
||||
### Web 控制台(`/admin`)
|
||||
|
||||
内置的配置控制台让你在浏览器中管理路由与分组(新增 / 编辑 / 删除 / 开关 / 排序)、查看发送日志、管理组成员与邀请链接、阅读审计日志——无需直接操作 D1 或 KV:
|
||||
内置的配置控制台让你在浏览器中管理路由与分组(新增 / 编辑 / 删除 / 开关 / 拖动排序——保存的顺序即评估顺序)、查看发送日志、管理组成员与邀请链接、阅读审计日志——无需直接操作 D1 或 KV:
|
||||
|
||||
1. 设置 `ADMIN_USER_IDS` 为允许管理控制台的 GitHub 用户 ID(或登录名),例如 `ADMIN_USER_IDS=12345,RhenCloud`。
|
||||
2. 访问 `/admin` 并用 GitHub 登录。无任何权限的用户收到 `403`——除非开启 `ALLOW_SELF_SIGNUP=1`(自动获得个人分组)或通过分组邀请链接加入。
|
||||
|
||||
+533
-143
@@ -213,26 +213,6 @@
|
||||
@apply px-6 py-3 text-sm;
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
@apply grid h-[30px] w-[30px] place-items-center cursor-pointer rounded-sm border border-border bg-transparent text-[13px] text-muted transition-all duration-150;
|
||||
}
|
||||
|
||||
.icon-btn:hover {
|
||||
@apply border-accent bg-accent-dim text-accent;
|
||||
}
|
||||
|
||||
.icon-btn:disabled {
|
||||
@apply cursor-not-allowed opacity-35;
|
||||
}
|
||||
|
||||
.icon-btn:disabled:hover {
|
||||
@apply border-border bg-transparent text-muted;
|
||||
}
|
||||
|
||||
.icon-btn.danger:hover {
|
||||
@apply border-bad bg-bad-dim text-bad;
|
||||
}
|
||||
|
||||
/* ---- Cards ---- */
|
||||
.card {
|
||||
@apply animate-rise rounded border border-border bg-surface p-5 transition-[border-color,transform] duration-150;
|
||||
@@ -283,8 +263,15 @@
|
||||
}
|
||||
|
||||
/* ---- Route cards ---- */
|
||||
.route-list {
|
||||
@apply flex flex-col gap-2.5;
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.route-card {
|
||||
@apply flex animate-rise items-center gap-4 rounded-xl border border-border bg-surface px-5 py-3.5 shadow-xs transition-all duration-150;
|
||||
@apply block animate-rise rounded-xl border border-border bg-surface px-4 py-3 shadow-xs transition-all duration-150;
|
||||
/* Only the entry delay keeps the hidden state: inline transforms (drag) must win afterwards. */
|
||||
animation-fill-mode: backwards;
|
||||
}
|
||||
|
||||
.route-card:hover {
|
||||
@@ -295,28 +282,70 @@
|
||||
@apply opacity-60;
|
||||
}
|
||||
|
||||
.route-card-main {
|
||||
@apply min-w-0 flex-1 space-y-2.5;
|
||||
/* Mobile-first: title row with actions, then filters/targets, then the tags. */
|
||||
.route-row {
|
||||
@apply grid items-center gap-x-3 gap-y-2;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
grid-template-areas:
|
||||
"lead title actions"
|
||||
"body body body"
|
||||
"tags tags tags";
|
||||
}
|
||||
|
||||
.route-card-header {
|
||||
@apply flex flex-wrap items-center gap-2.5;
|
||||
.route-lead {
|
||||
@apply flex items-center;
|
||||
grid-area: lead;
|
||||
}
|
||||
|
||||
.route-card-title {
|
||||
@apply flex min-w-0 flex-wrap items-center gap-2;
|
||||
.route-title {
|
||||
@apply flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1;
|
||||
grid-area: title;
|
||||
}
|
||||
|
||||
.route-name {
|
||||
@apply text-[15px] font-semibold tracking-tight text-text;
|
||||
@apply min-w-0 text-[15px] font-semibold tracking-tight text-text;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.route-id {
|
||||
@apply rounded-md bg-surface-2 px-1.5 py-0.5 font-mono text-[11px] text-faint;
|
||||
}
|
||||
|
||||
.route-card-badges {
|
||||
@apply ml-auto flex flex-wrap items-center gap-1.5;
|
||||
.route-position {
|
||||
@apply grid h-5 min-w-5 place-items-center rounded-md bg-accent-dim px-1 font-mono text-[11px] font-semibold text-accent-text tabular-nums;
|
||||
}
|
||||
|
||||
.route-tags {
|
||||
@apply flex flex-wrap items-center justify-end gap-1.5;
|
||||
grid-area: tags;
|
||||
}
|
||||
|
||||
.route-actions {
|
||||
@apply flex items-center gap-0.5;
|
||||
grid-area: actions;
|
||||
}
|
||||
|
||||
.route-body {
|
||||
@apply min-w-0 space-y-2;
|
||||
grid-area: body;
|
||||
}
|
||||
|
||||
@container (min-width: 40rem) {
|
||||
.route-row {
|
||||
grid-template-columns: auto minmax(0, 1fr) auto auto;
|
||||
grid-template-areas:
|
||||
"lead title tags actions"
|
||||
". body body body";
|
||||
}
|
||||
}
|
||||
|
||||
.route-summary {
|
||||
@apply line-clamp-2 text-[12.5px] leading-relaxed text-muted;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.route-summary.is-empty {
|
||||
@apply italic text-faint;
|
||||
}
|
||||
|
||||
.route-badge {
|
||||
@@ -324,18 +353,18 @@
|
||||
}
|
||||
|
||||
.route-badge-dot {
|
||||
@apply inline-block h-1.5 w-1.5 rounded-full;
|
||||
@apply inline-block h-1.5 w-1.5 rounded-full bg-current;
|
||||
}
|
||||
|
||||
.route-badge-dc {
|
||||
.route-badge-discord {
|
||||
@apply border-accent/20 bg-accent-dim/30 text-accent-text;
|
||||
}
|
||||
|
||||
.route-badge-tg {
|
||||
.route-badge-telegram {
|
||||
@apply border-info/20 bg-info-dim/30 text-info;
|
||||
}
|
||||
|
||||
.route-badge-fs {
|
||||
.route-badge-feishu {
|
||||
@apply border-warn/20 bg-warn-dim/30 text-warn;
|
||||
}
|
||||
|
||||
@@ -351,44 +380,12 @@
|
||||
@apply border-accent/30 bg-accent-dim/20 text-accent-text;
|
||||
}
|
||||
|
||||
.route-card-filters {
|
||||
@apply flex flex-wrap items-center gap-2 text-xs;
|
||||
}
|
||||
|
||||
.route-chip {
|
||||
@apply inline-flex items-center gap-1.5 rounded-md border border-border bg-surface-2 px-2.5 py-1 text-[11.5px];
|
||||
}
|
||||
|
||||
.route-chip-type {
|
||||
@apply font-bold uppercase tracking-wider text-faint text-[10px];
|
||||
}
|
||||
|
||||
.route-chip-val {
|
||||
@apply font-medium text-text;
|
||||
}
|
||||
|
||||
.route-chip.exclude {
|
||||
@apply border-bad/20 bg-bad-dim/20;
|
||||
}
|
||||
|
||||
.route-chip.exclude .route-chip-type {
|
||||
@apply text-bad;
|
||||
}
|
||||
|
||||
.route-chip-empty {
|
||||
@apply italic text-muted;
|
||||
}
|
||||
|
||||
.route-card-targets {
|
||||
@apply flex flex-wrap items-center gap-2 text-xs;
|
||||
}
|
||||
|
||||
.route-target {
|
||||
@apply inline-flex items-center;
|
||||
}
|
||||
|
||||
.route-target-row {
|
||||
@apply inline-flex items-center gap-1.5 rounded-md border border-border/80 bg-surface-2/60 px-2 py-0.5 text-xs;
|
||||
@apply inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-md border border-border/80 bg-surface-2/60 px-2 py-0.5 text-xs;
|
||||
}
|
||||
|
||||
.route-target-label {
|
||||
@@ -396,19 +393,53 @@
|
||||
}
|
||||
|
||||
.route-target-id {
|
||||
@apply font-mono text-[11.5px] text-text;
|
||||
@apply min-w-0 truncate font-mono text-[11.5px] text-text;
|
||||
}
|
||||
|
||||
.route-card-actions {
|
||||
@apply flex shrink-0 items-center gap-1 self-center;
|
||||
/* ---- Route reordering ---- */
|
||||
.route-handle {
|
||||
@apply grid h-9 w-9 cursor-grab place-items-center rounded-lg text-muted transition-colors hover:bg-surface-2 hover:text-text;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.route-action-btn {
|
||||
@apply flex h-7 w-7 items-center justify-center rounded-md text-muted transition-colors hover:bg-surface-2 hover:text-text disabled:pointer-events-none disabled:opacity-25;
|
||||
.route-handle:disabled {
|
||||
@apply cursor-not-allowed opacity-40 hover:bg-transparent;
|
||||
}
|
||||
|
||||
.route-action-btn-danger:hover {
|
||||
@apply bg-bad-dim/30 text-bad;
|
||||
.route-handle:focus-visible {
|
||||
@apply outline-2 outline-offset-2 outline-accent;
|
||||
}
|
||||
|
||||
.route-list.is-reordering .route-card {
|
||||
@apply select-none;
|
||||
}
|
||||
|
||||
.route-list.is-dragging .route-card {
|
||||
transition: transform 180ms ease;
|
||||
}
|
||||
|
||||
.route-list.is-dragging .route-handle {
|
||||
@apply cursor-grabbing;
|
||||
}
|
||||
|
||||
.route-list .route-card.is-dragged {
|
||||
@apply relative z-10 border-accent shadow-lg;
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.route-list .route-card.is-dragged.is-settling {
|
||||
transition: transform 150ms ease;
|
||||
}
|
||||
|
||||
.route-list.is-committing .route-card {
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.route-list.is-dragging .route-card,
|
||||
.route-list .route-card.is-dragged.is-settling {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Toggle switch ---- */
|
||||
@@ -522,6 +553,11 @@
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
/* The dialog itself takes focus on open (useDialogFocus); its fields show the ring. */
|
||||
.editor-dialog:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.editor-dialog > div:first-child {
|
||||
margin-bottom: 0 !important;
|
||||
flex-shrink: 0 !important;
|
||||
@@ -559,10 +595,6 @@
|
||||
@apply truncate text-base font-extrabold tracking-tight;
|
||||
}
|
||||
|
||||
.editor-head .icon-btn {
|
||||
@apply h-8 w-8 rounded-full;
|
||||
}
|
||||
|
||||
.editor-body {
|
||||
@apply flex-1 overflow-y-auto px-6 py-5;
|
||||
scrollbar-width: thin;
|
||||
@@ -668,29 +700,52 @@
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
.target-row {
|
||||
@apply mb-2 grid grid-cols-[minmax(130px,1fr)_auto] items-center gap-2 rounded-sm border border-border bg-surface-2 p-2.5 max-sm:grid-cols-[1fr_auto];
|
||||
grid-template-areas:
|
||||
"select del"
|
||||
"in1 in2";
|
||||
.option-list {
|
||||
@apply mb-4 flex flex-col gap-3;
|
||||
}
|
||||
|
||||
.target-row select {
|
||||
@apply w-full rounded border border-border-strong bg-surface px-2 py-1.5 font-ui text-[12.5px] font-medium text-text;
|
||||
grid-area: select;
|
||||
.option-row {
|
||||
@apply flex flex-col items-start gap-1;
|
||||
}
|
||||
|
||||
.target-row input.tg-in1 {
|
||||
grid-area: in1;
|
||||
/* Indented to line up with the checkbox label text. */
|
||||
.option-hint {
|
||||
@apply m-0 pl-[1.625rem] text-[11.5px] leading-snug text-faint;
|
||||
}
|
||||
|
||||
.target-row input.tg-in2 {
|
||||
grid-area: in2;
|
||||
.ctl-md {
|
||||
@apply w-full max-w-64;
|
||||
}
|
||||
|
||||
.target-row > .icon-btn {
|
||||
grid-area: del;
|
||||
justify-self: end;
|
||||
.ctl-stack {
|
||||
@apply mt-2 flex w-full max-w-md flex-col gap-2;
|
||||
}
|
||||
|
||||
.target-card {
|
||||
@apply mb-2 flex flex-col gap-2.5 rounded-lg border border-border bg-surface-2 p-3;
|
||||
}
|
||||
|
||||
.target-card-head {
|
||||
@apply flex items-center justify-between gap-2;
|
||||
}
|
||||
|
||||
.target-platform {
|
||||
@apply w-44 max-w-full;
|
||||
}
|
||||
|
||||
.target-field {
|
||||
@apply grid items-center gap-x-3 gap-y-1;
|
||||
grid-template-columns: 7rem minmax(0, 28rem);
|
||||
}
|
||||
|
||||
.target-field > label {
|
||||
@apply text-xs font-semibold text-muted;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.target-field {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.add-filter {
|
||||
@@ -698,91 +753,404 @@
|
||||
}
|
||||
|
||||
.forge-source-row {
|
||||
@apply mb-2 grid items-center gap-2 rounded-sm border border-border bg-surface-2 p-2.5;
|
||||
@apply mb-2 grid items-center gap-2 rounded-lg border border-border bg-surface-2 p-2.5;
|
||||
grid-template-areas:
|
||||
"host type del"
|
||||
"name name name";
|
||||
grid-template-columns: 1fr auto auto;
|
||||
grid-template-columns: minmax(0, 1fr) 8rem auto;
|
||||
}
|
||||
|
||||
.forge-source-row .f-host {
|
||||
grid-area: host;
|
||||
}
|
||||
|
||||
.forge-source-row .select.forge-type {
|
||||
.forge-source-row .f-type {
|
||||
grid-area: type;
|
||||
@apply w-[110px];
|
||||
}
|
||||
|
||||
.forge-source-row .f-del {
|
||||
grid-area: del;
|
||||
}
|
||||
|
||||
.forge-source-row .f-name {
|
||||
grid-area: name;
|
||||
}
|
||||
|
||||
.forge-source-row > .icon-btn {
|
||||
grid-area: del;
|
||||
justify-self: end;
|
||||
/* ---- Filter combobox (FilterCombobox.vue; its popover is portaled, so not scoped) ---- */
|
||||
.filter-combo {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.filter-combo-anchor {
|
||||
display: flex;
|
||||
min-height: 2.25rem;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
border-radius: 0.5rem;
|
||||
background: rgb(var(--wh-surface));
|
||||
padding: 0 0.375rem 0 0.75rem;
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgb(var(--wh-border-strong)),
|
||||
0 1px 2px rgb(0 0 0 / 0.05);
|
||||
cursor: text;
|
||||
transition: box-shadow 150ms ease;
|
||||
}
|
||||
.filter-combo-anchor:focus-within {
|
||||
box-shadow: inset 0 0 0 2px rgb(var(--wh-accent));
|
||||
}
|
||||
.filter-combo-anchor.is-invalid {
|
||||
box-shadow: inset 0 0 0 1px rgb(var(--wh-bad));
|
||||
}
|
||||
.filter-combo-anchor.is-invalid:focus-within {
|
||||
box-shadow: inset 0 0 0 2px rgb(var(--wh-bad));
|
||||
}
|
||||
.filter-combo-anchor.is-multi {
|
||||
flex-wrap: wrap;
|
||||
padding: 0.25rem 0.375rem 0.25rem 0.375rem;
|
||||
}
|
||||
.filter-combo-chip {
|
||||
display: inline-flex;
|
||||
max-width: 100%;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
border-radius: 0.375rem;
|
||||
background: rgb(var(--wh-accent-dim));
|
||||
padding: 0.125rem 0.25rem 0.125rem 0.5rem;
|
||||
color: rgb(var(--wh-accent-text));
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.72rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.25rem;
|
||||
}
|
||||
.filter-combo-chip.is-invalid {
|
||||
background: rgb(var(--wh-bad-dim));
|
||||
color: rgb(var(--wh-bad));
|
||||
text-decoration: line-through;
|
||||
text-decoration-color: rgb(var(--wh-bad) / 0.6);
|
||||
}
|
||||
.filter-combo-chip.is-invalid .filter-combo-chip-x {
|
||||
color: rgb(var(--wh-bad));
|
||||
}
|
||||
.filter-combo-chip-text {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.filter-combo-chip-x {
|
||||
display: grid;
|
||||
flex: none;
|
||||
width: 1.125rem;
|
||||
height: 1.125rem;
|
||||
place-items: center;
|
||||
border-radius: 9999px;
|
||||
color: rgb(var(--wh-accent));
|
||||
cursor: pointer;
|
||||
}
|
||||
.filter-combo-chip-x:hover {
|
||||
background: rgb(var(--wh-accent) / 0.15);
|
||||
}
|
||||
.filter-combo-chip-x:focus-visible {
|
||||
outline: 2px solid rgb(var(--wh-accent));
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.filter-combo-input {
|
||||
min-width: 4rem;
|
||||
flex: 1 1 4rem;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
padding: 0.375rem 0;
|
||||
color: rgb(var(--wh-text));
|
||||
font-size: 0.8125rem;
|
||||
outline: none;
|
||||
}
|
||||
.filter-combo-anchor.is-multi .filter-combo-input {
|
||||
padding-left: 0.375rem;
|
||||
}
|
||||
.filter-combo-input.is-mono {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
.filter-combo-input::placeholder {
|
||||
color: rgb(var(--wh-faint));
|
||||
}
|
||||
.filter-combo-trigger {
|
||||
display: grid;
|
||||
flex: none;
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
place-items: center;
|
||||
border-radius: 0.375rem;
|
||||
color: rgb(var(--wh-faint));
|
||||
}
|
||||
.filter-combo-trigger:hover {
|
||||
color: rgb(var(--wh-text));
|
||||
}
|
||||
.filter-combo-error {
|
||||
margin: 0.3rem 0 0;
|
||||
color: rgb(var(--wh-bad));
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
.filter-combo-pending {
|
||||
margin: 0.3rem 0 0;
|
||||
color: rgb(var(--wh-warn));
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
.filter-combo-content {
|
||||
z-index: 55;
|
||||
width: max(var(--reka-combobox-trigger-width), 17rem);
|
||||
max-width: calc(100vw - 1rem);
|
||||
overflow: hidden;
|
||||
border-radius: 0.5rem;
|
||||
background: rgb(var(--wh-surface));
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgb(var(--wh-border)),
|
||||
0 4px 6px -1px rgb(0 0 0 / 0.1),
|
||||
0 2px 4px -2px rgb(0 0 0 / 0.1);
|
||||
color: rgb(var(--wh-text));
|
||||
}
|
||||
.filter-combo-content[data-state="open"] {
|
||||
animation: filter-combo-in 120ms ease-out;
|
||||
}
|
||||
@keyframes filter-combo-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
}
|
||||
.filter-combo-viewport {
|
||||
max-height: min(18rem, var(--reka-combobox-content-available-height, 18rem));
|
||||
overflow-y: auto;
|
||||
padding: 0.25rem;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.filter-combo-group {
|
||||
padding: 0.5rem 0.625rem 0.25rem;
|
||||
color: rgb(var(--wh-faint));
|
||||
font-size: 0.65rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.filter-combo-item {
|
||||
position: relative;
|
||||
display: flex;
|
||||
min-height: 2rem;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
border-radius: 0.375rem;
|
||||
padding: 0.375rem 2rem 0.375rem 0.625rem;
|
||||
font-size: 0.8125rem;
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.filter-combo-item[data-highlighted] {
|
||||
background: rgb(var(--wh-surface-3));
|
||||
}
|
||||
.filter-combo-item-value {
|
||||
flex: none;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
.filter-combo-item-hint {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
overflow: hidden;
|
||||
color: rgb(var(--wh-muted));
|
||||
font-size: 0.75rem;
|
||||
text-align: right;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.filter-combo-item-check {
|
||||
position: absolute;
|
||||
right: 0.5rem;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: rgb(var(--wh-accent));
|
||||
}
|
||||
.filter-combo-item.is-create {
|
||||
color: rgb(var(--wh-accent));
|
||||
font-weight: 600;
|
||||
}
|
||||
.filter-combo-item-create {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.filter-combo-note {
|
||||
margin: 0;
|
||||
padding: 0.75rem 0.625rem;
|
||||
color: rgb(var(--wh-faint));
|
||||
font-size: 0.75rem;
|
||||
text-align: center;
|
||||
}
|
||||
.filter-combo-note.is-error {
|
||||
color: rgb(var(--wh-bad));
|
||||
text-align: left;
|
||||
}
|
||||
@media (pointer: coarse) {
|
||||
.filter-combo-item {
|
||||
min-height: 2.5rem;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.filter-combo-content[data-state="open"] {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Filter tree editor ---- */
|
||||
.node-editor {
|
||||
@apply mb-1;
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.node-nested {
|
||||
@apply ml-4 border-l border-border pl-3;
|
||||
@apply ml-3 border-l border-border pl-2.5;
|
||||
}
|
||||
|
||||
@container (max-width: 26rem) {
|
||||
.node-nested {
|
||||
@apply ml-1 pl-1.5;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* A condition: type · path · operator on one line with the NOT toggle and
|
||||
* delete pinned top-right, values below. Narrow containers stack the fields
|
||||
* under the type. Field filters add a path, keyword filters have no
|
||||
* operator, and `exists` has no values.
|
||||
*/
|
||||
.leaf-row {
|
||||
@apply mb-1.5 flex flex-wrap items-center gap-2 rounded-sm border border-border bg-surface-2 p-2.5;
|
||||
@apply grid items-start gap-2 rounded-lg border border-border bg-surface p-2.5;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
grid-template-areas:
|
||||
"type actions"
|
||||
"op op"
|
||||
"values values";
|
||||
}
|
||||
|
||||
.node-select {
|
||||
@apply w-[120px] shrink-0 rounded border border-border-strong bg-surface px-2 py-1.5 font-ui text-[12.5px] font-medium text-text;
|
||||
.leaf-row.is-field {
|
||||
grid-template-areas:
|
||||
"type actions"
|
||||
"path path"
|
||||
"op op"
|
||||
"values values";
|
||||
}
|
||||
|
||||
.node-path {
|
||||
@apply w-[160px] shrink-0;
|
||||
.leaf-row.is-keyword {
|
||||
grid-template-areas:
|
||||
"type actions"
|
||||
"values values";
|
||||
}
|
||||
|
||||
.node-values {
|
||||
@apply min-w-[180px] flex-1;
|
||||
.leaf-row.no-values {
|
||||
grid-template-areas:
|
||||
"type actions"
|
||||
"op op";
|
||||
}
|
||||
|
||||
.node-exclude {
|
||||
@apply flex shrink-0 cursor-pointer items-center gap-1.5 text-[12px] font-medium text-muted;
|
||||
.leaf-row.is-field.no-values {
|
||||
grid-template-areas:
|
||||
"type actions"
|
||||
"path path"
|
||||
"op op";
|
||||
}
|
||||
|
||||
@container (min-width: 34rem) {
|
||||
.leaf-row {
|
||||
grid-template-columns: 9.5rem 9.5rem minmax(0, 1fr) auto;
|
||||
grid-template-areas:
|
||||
"type op . actions"
|
||||
"values values values values";
|
||||
}
|
||||
|
||||
.leaf-row.is-field {
|
||||
grid-template-columns: 9.5rem minmax(0, 1fr) 9.5rem auto;
|
||||
grid-template-areas:
|
||||
"type path op actions"
|
||||
"values values values values";
|
||||
}
|
||||
|
||||
.leaf-row.is-keyword {
|
||||
grid-template-columns: 9.5rem minmax(0, 1fr) auto;
|
||||
grid-template-areas:
|
||||
"type . actions"
|
||||
"values values values";
|
||||
}
|
||||
|
||||
.leaf-row.no-values {
|
||||
grid-template-areas: "type op . actions";
|
||||
}
|
||||
|
||||
.leaf-row.is-field.no-values {
|
||||
grid-template-areas: "type path op actions";
|
||||
}
|
||||
}
|
||||
|
||||
.leaf-row.is-negated {
|
||||
@apply border-bad/40;
|
||||
}
|
||||
|
||||
.leaf-type {
|
||||
@apply min-w-0;
|
||||
grid-area: type;
|
||||
}
|
||||
|
||||
.leaf-path {
|
||||
@apply min-w-0;
|
||||
grid-area: path;
|
||||
}
|
||||
|
||||
.leaf-op {
|
||||
@apply min-w-0;
|
||||
grid-area: op;
|
||||
}
|
||||
|
||||
.leaf-values {
|
||||
@apply min-w-0;
|
||||
grid-area: values;
|
||||
}
|
||||
|
||||
.leaf-actions {
|
||||
@apply flex items-center gap-1 justify-self-end;
|
||||
grid-area: actions;
|
||||
}
|
||||
|
||||
.node-group {
|
||||
@apply mb-1.5 rounded-sm border border-border bg-surface-2 p-2.5;
|
||||
@apply flex flex-col gap-2 rounded-lg border border-border bg-surface-2 p-2.5;
|
||||
}
|
||||
|
||||
.node-group-head {
|
||||
@apply mb-2 flex flex-wrap items-center gap-2;
|
||||
@apply flex flex-wrap items-center gap-2;
|
||||
}
|
||||
|
||||
.node-combo {
|
||||
@apply w-[130px] rounded border border-border-strong bg-surface px-2 py-1.5 font-ui text-[12.5px] font-semibold text-text;
|
||||
.node-kind > * {
|
||||
@apply whitespace-nowrap;
|
||||
}
|
||||
|
||||
.node-combo-label {
|
||||
@apply inline-flex items-center rounded border border-border-strong bg-surface px-2 py-1.5 font-ui text-[12.5px] font-semibold text-text;
|
||||
}
|
||||
|
||||
.node-actions {
|
||||
@apply ml-auto flex flex-wrap items-center gap-1.5;
|
||||
}
|
||||
|
||||
.node-add {
|
||||
@apply px-2 py-1 text-[12px];
|
||||
.node-not-label {
|
||||
@apply inline-flex items-center rounded-md bg-bad-dim px-2.5 py-1 text-xs font-semibold text-bad;
|
||||
}
|
||||
|
||||
.node-children {
|
||||
@apply flex flex-col gap-1.5;
|
||||
@apply flex flex-col gap-2;
|
||||
}
|
||||
|
||||
.node-empty {
|
||||
@apply py-1 text-[12px] italic text-muted;
|
||||
}
|
||||
|
||||
.node-add {
|
||||
@apply flex flex-wrap items-center gap-1;
|
||||
}
|
||||
|
||||
.test-event {
|
||||
@apply max-w-sm;
|
||||
}
|
||||
|
||||
.test-payload {
|
||||
@apply font-mono text-[12px];
|
||||
}
|
||||
@@ -816,7 +1184,7 @@
|
||||
}
|
||||
|
||||
.fragment-row {
|
||||
@apply flex items-center gap-2 rounded-sm border border-border bg-surface-2 p-2;
|
||||
@apply flex items-center gap-2 rounded-lg border border-border bg-surface-2 py-1.5 pl-3 pr-1.5;
|
||||
}
|
||||
|
||||
.fragment-name {
|
||||
@@ -828,7 +1196,11 @@
|
||||
}
|
||||
|
||||
.fragment-save {
|
||||
@apply flex items-center gap-2;
|
||||
@apply flex max-w-lg items-center gap-2;
|
||||
}
|
||||
|
||||
.fragment-save-input {
|
||||
@apply min-w-0 flex-1;
|
||||
}
|
||||
|
||||
.log-block {
|
||||
@@ -908,11 +1280,12 @@
|
||||
}
|
||||
|
||||
.log-filters {
|
||||
@apply flex items-center gap-1.5;
|
||||
@apply flex min-w-0 items-center gap-1.5;
|
||||
}
|
||||
|
||||
/* Never squeezed into a column of single characters on narrow screens. */
|
||||
.filter-label {
|
||||
@apply text-[11px] font-bold uppercase tracking-wider text-muted;
|
||||
@apply shrink-0 whitespace-nowrap text-[11px] font-bold uppercase tracking-wider text-muted;
|
||||
}
|
||||
|
||||
.filter-select {
|
||||
@@ -967,6 +1340,11 @@
|
||||
@apply mr-1 font-semibold tracking-wider text-faint;
|
||||
}
|
||||
|
||||
/* Long ids (channel/thread, repo) wrap instead of widening the page. */
|
||||
.log-meta span {
|
||||
@apply min-w-0 [overflow-wrap:anywhere];
|
||||
}
|
||||
|
||||
.log-meta code {
|
||||
@apply rounded-[5px] bg-surface-2 px-1.5 py-px font-mono text-text;
|
||||
}
|
||||
@@ -1029,8 +1407,9 @@
|
||||
}
|
||||
|
||||
/* ---- Members / invites ---- */
|
||||
/* RcCard (padding="md") already pads the body; no second padding here. */
|
||||
.members-panel {
|
||||
@apply mt-7 rounded border border-border bg-surface p-5;
|
||||
@apply mt-7 rounded border border-border bg-surface;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
@@ -1045,17 +1424,31 @@
|
||||
@apply my-3.5 mb-2 text-xs;
|
||||
}
|
||||
|
||||
.member-list {
|
||||
@apply m-0 mb-3 flex list-none flex-col gap-2 p-0;
|
||||
/* Members flow as compact cards: name, role and remove on one line. */
|
||||
.member-grid {
|
||||
@apply m-0 mb-3.5 grid list-none gap-2.5 p-0;
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(100%, 17rem), 1fr));
|
||||
}
|
||||
|
||||
.member-card {
|
||||
@apply grid items-center gap-2 rounded-lg border border-border bg-surface-2 py-1.5 pl-3.5 pr-1.5;
|
||||
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||
}
|
||||
|
||||
.member-name {
|
||||
@apply truncate text-[15px] font-semibold tracking-tight text-text;
|
||||
}
|
||||
|
||||
.member-role {
|
||||
@apply flex w-32 shrink-0 justify-end;
|
||||
}
|
||||
|
||||
.member-row,
|
||||
.invite-row {
|
||||
@apply flex flex-wrap items-center gap-2.5 rounded-sm border border-border bg-surface-2 px-3 py-2;
|
||||
@apply flex flex-wrap items-center gap-x-2.5 gap-y-1.5 rounded-lg border border-border bg-surface-2 py-1.5 pl-3 pr-1.5;
|
||||
}
|
||||
|
||||
.member-login {
|
||||
@apply min-w-[120px] flex-1 text-[13px] font-semibold;
|
||||
.invite-actions {
|
||||
@apply ml-auto flex items-center gap-1;
|
||||
}
|
||||
|
||||
.role-pill {
|
||||
@@ -1079,12 +1472,9 @@
|
||||
@apply flex flex-wrap items-center gap-2;
|
||||
}
|
||||
|
||||
.text-input {
|
||||
@apply min-w-[200px] rounded border border-border bg-surface px-2.5 py-1.5 text-[13px] text-text outline-none;
|
||||
}
|
||||
|
||||
.text-input:focus {
|
||||
@apply border-accent;
|
||||
.member-add-login {
|
||||
@apply min-w-0 max-w-xs;
|
||||
flex: 1 1 14rem;
|
||||
}
|
||||
|
||||
.invite-box {
|
||||
|
||||
@@ -89,7 +89,7 @@ function fmtTime(ts: number): string {
|
||||
<RcCard variant="outline" padding="none">
|
||||
<div class="flex items-center justify-between border-b border-border px-5 py-4">
|
||||
<h2 class="text-sm font-bold tracking-tight">{{ t("overview.recent") }}</h2>
|
||||
<RcButton variant="link" size="xs" @click="router.replace('/admin/logs')">
|
||||
<RcButton variant="link" size="xs" @click="router.push('/admin/logs')">
|
||||
{{ t("overview.viewAll") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
<template>
|
||||
<AlertDialogRoot :open="!!request" @update:open="onOpenChange">
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay class="confirm-overlay" />
|
||||
<AlertDialogContent class="confirm-dialog">
|
||||
<div class="confirm-body">
|
||||
<span class="confirm-icon" aria-hidden="true"
|
||||
><component :is="KIND_ICONS[shown?.kind ?? 'delete']" :size="18"
|
||||
/></span>
|
||||
<div class="min-w-0 space-y-1.5">
|
||||
<AlertDialogTitle class="confirm-title">{{ shown?.title }}</AlertDialogTitle>
|
||||
<AlertDialogDescription v-if="shown?.description" class="confirm-description">
|
||||
{{ shown.description }}
|
||||
</AlertDialogDescription>
|
||||
</div>
|
||||
</div>
|
||||
<div class="confirm-actions">
|
||||
<AlertDialogCancel as-child>
|
||||
<RcButton variant="outline" color="neutral">{{ t("confirm.cancel") }}</RcButton>
|
||||
</AlertDialogCancel>
|
||||
<RcButton color="error" @click="settle(true)">
|
||||
{{ shown?.confirmText || t("confirm.delete") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
</AlertDialogContent>
|
||||
</AlertDialogPortal>
|
||||
</AlertDialogRoot>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { LogOut, Trash2, TriangleAlert } from "lucide-vue-next";
|
||||
import {
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogPortal,
|
||||
AlertDialogRoot,
|
||||
AlertDialogTitle,
|
||||
} from "reka-ui";
|
||||
import type { ConfirmOptions } from "~/composables/useConfirm";
|
||||
|
||||
const { t } = useI18n();
|
||||
const { pending: request, settle, attachHost } = useConfirm();
|
||||
|
||||
const KIND_ICONS = {
|
||||
delete: Trash2,
|
||||
leave: TriangleAlert,
|
||||
signOut: LogOut,
|
||||
} satisfies Record<NonNullable<ConfirmOptions["kind"]>, typeof Trash2>;
|
||||
|
||||
// Keep the last request on screen while the close animation plays.
|
||||
const shown = ref<ConfirmOptions | null>(null);
|
||||
watch(
|
||||
request,
|
||||
(next) => {
|
||||
if (next) shown.value = next;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
// A request must never outlive the console that asked for it: resolving it
|
||||
// later would resume a destructive action of an unmounted component.
|
||||
let detach: (() => void) | undefined;
|
||||
onMounted(() => (detach = attachHost()));
|
||||
onBeforeUnmount(() => detach?.());
|
||||
|
||||
function onOpenChange(open: boolean): void {
|
||||
if (!open) settle(false);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.confirm-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 60;
|
||||
background: var(--wh-scrim);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
.confirm-dialog {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
z-index: 60;
|
||||
display: grid;
|
||||
gap: 1.25rem;
|
||||
width: calc(100% - 2rem);
|
||||
max-width: 28rem;
|
||||
transform: translate(-50%, -50%);
|
||||
border-radius: 0.75rem;
|
||||
background: rgb(var(--wh-surface));
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgb(var(--wh-border)),
|
||||
0 20px 25px -5px rgb(0 0 0 / 0.1),
|
||||
0 8px 10px -6px rgb(0 0 0 / 0.1);
|
||||
padding: 1.5rem;
|
||||
color: rgb(var(--wh-text));
|
||||
}
|
||||
.confirm-dialog:focus {
|
||||
outline: none;
|
||||
}
|
||||
.confirm-body {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.875rem;
|
||||
}
|
||||
.confirm-icon {
|
||||
display: grid;
|
||||
flex: none;
|
||||
width: 2.25rem;
|
||||
height: 2.25rem;
|
||||
place-items: center;
|
||||
border-radius: 9999px;
|
||||
background: rgb(var(--wh-bad-dim));
|
||||
color: rgb(var(--wh-bad));
|
||||
}
|
||||
.confirm-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.01em;
|
||||
line-height: 1.5rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.confirm-description {
|
||||
color: rgb(var(--wh-muted));
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5rem;
|
||||
}
|
||||
.confirm-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.625rem;
|
||||
}
|
||||
.confirm-overlay[data-state="open"],
|
||||
.confirm-dialog[data-state="open"] {
|
||||
animation: confirm-in 150ms ease-out;
|
||||
}
|
||||
@keyframes confirm-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@media (max-width: 420px) {
|
||||
.confirm-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.confirm-overlay[data-state="open"],
|
||||
.confirm-dialog[data-state="open"] {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+758
-142
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,460 @@
|
||||
<template>
|
||||
<ComboboxRoot
|
||||
ref="rootRef"
|
||||
v-model:open="open"
|
||||
:model-value="multiple ? values : single || undefined"
|
||||
:multiple="multiple"
|
||||
ignore-filter
|
||||
open-on-click
|
||||
:reset-search-term-on-blur="false"
|
||||
:reset-search-term-on-select="false"
|
||||
class="filter-combo"
|
||||
>
|
||||
<ComboboxAnchor
|
||||
class="filter-combo-anchor"
|
||||
:class="{ 'is-multi': multiple, 'is-invalid': !!commitError }"
|
||||
@click="focusInput"
|
||||
>
|
||||
<template v-if="multiple">
|
||||
<span
|
||||
v-for="(v, i) in values"
|
||||
:key="v"
|
||||
class="filter-combo-chip"
|
||||
:class="{ 'is-invalid': !!chipError(v) }"
|
||||
:title="chipError(v) ? t(chipError(v)!) : hintOf(v)"
|
||||
>
|
||||
<span class="filter-combo-chip-text">{{ v }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="filter-combo-chip-x"
|
||||
:aria-label="t('combo.remove', { value: v })"
|
||||
@pointerdown.stop
|
||||
@click.stop="removeAt(i)"
|
||||
>
|
||||
<X :size="12" />
|
||||
</button>
|
||||
</span>
|
||||
</template>
|
||||
<ComboboxInput
|
||||
:id="inputId"
|
||||
v-model="inputText"
|
||||
class="filter-combo-input"
|
||||
:class="{ 'is-mono': mono }"
|
||||
:placeholder="multiple && values.length ? '' : placeholder"
|
||||
:aria-label="label"
|
||||
:aria-invalid="commitError ? true : undefined"
|
||||
:title="multiple ? undefined : hintOf(single) || undefined"
|
||||
@keydown="onKeydown"
|
||||
@focus="focused = true"
|
||||
@blur="onBlur"
|
||||
@paste="onPaste"
|
||||
/>
|
||||
<ComboboxTrigger class="filter-combo-trigger" tabindex="-1" :aria-label="label">
|
||||
<ChevronDown :size="14" />
|
||||
</ComboboxTrigger>
|
||||
</ComboboxAnchor>
|
||||
<p v-if="commitError" class="filter-combo-error">{{ t(commitError) }}</p>
|
||||
<p v-else-if="pending && !focused" class="filter-combo-pending">
|
||||
{{ t("combo.pending", { value: draftText }) }}
|
||||
</p>
|
||||
|
||||
<ComboboxPortal>
|
||||
<ComboboxContent
|
||||
position="popper"
|
||||
align="start"
|
||||
:side-offset="4"
|
||||
:collision-padding="8"
|
||||
:data-filter-combo="uid"
|
||||
class="filter-combo-content"
|
||||
@pointerdown="markPointerInside"
|
||||
>
|
||||
<ComboboxViewport class="filter-combo-viewport">
|
||||
<ComboboxGroup v-for="section in sections" :key="section.name">
|
||||
<ComboboxLabel v-if="section.name" class="filter-combo-group">
|
||||
{{ section.name }}
|
||||
</ComboboxLabel>
|
||||
<ComboboxItem
|
||||
v-for="opt in section.options"
|
||||
:key="opt.value"
|
||||
:value="opt.value"
|
||||
:title="opt.hint"
|
||||
class="filter-combo-item"
|
||||
@select="onPick($event, opt.value)"
|
||||
>
|
||||
<span class="filter-combo-item-value">{{ opt.value }}</span>
|
||||
<span v-if="opt.hint" class="filter-combo-item-hint">{{ opt.hint }}</span>
|
||||
<ComboboxItemIndicator class="filter-combo-item-check">
|
||||
<Check :size="14" />
|
||||
</ComboboxItemIndicator>
|
||||
</ComboboxItem>
|
||||
</ComboboxGroup>
|
||||
<ComboboxItem
|
||||
v-if="canCreate"
|
||||
:value="CREATE_VALUE"
|
||||
class="filter-combo-item is-create"
|
||||
@select="onCreate"
|
||||
>
|
||||
<Plus :size="14" class="shrink-0" />
|
||||
<span class="filter-combo-item-create">{{
|
||||
t("combo.useValue", { value: draftText })
|
||||
}}</span>
|
||||
</ComboboxItem>
|
||||
<p v-if="liveError && !sections.length" class="filter-combo-note is-error">
|
||||
{{ t(liveError) }}
|
||||
</p>
|
||||
<p v-else-if="!sections.length && !canCreate" class="filter-combo-note">
|
||||
{{ creatable ? t("combo.typeToAdd") : t("combo.empty") }}
|
||||
</p>
|
||||
</ComboboxViewport>
|
||||
</ComboboxContent>
|
||||
</ComboboxPortal>
|
||||
</ComboboxRoot>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Check, ChevronDown, Plus, X } from "lucide-vue-next";
|
||||
import {
|
||||
ComboboxAnchor,
|
||||
ComboboxContent,
|
||||
ComboboxGroup,
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxItemIndicator,
|
||||
ComboboxLabel,
|
||||
ComboboxPortal,
|
||||
ComboboxRoot,
|
||||
ComboboxTrigger,
|
||||
ComboboxViewport,
|
||||
} from "reka-ui";
|
||||
import type { ComboOption } from "~/utils/filter-catalog";
|
||||
import { commaEndsValue, splitFilterValues } from "~/utils/filter-catalog";
|
||||
|
||||
/**
|
||||
* Searchable dropdown for the filter editor. Options carry the stored English
|
||||
* key plus localized descriptions; search matches the key first, then either
|
||||
* language. With `creatable`, typed text can be added as a custom value once
|
||||
* `validate` accepts it — otherwise typing only searches.
|
||||
*
|
||||
* Built on the reka-ui primitives that @elysola/ui ships (and styled
|
||||
* like RcCombobox / RcTagInput). It deliberately uses that same reka-ui copy
|
||||
* rather than a separate dependency so its popover stacks with Rc dialogs.
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: string | string[];
|
||||
options: ComboOption[];
|
||||
multiple?: boolean;
|
||||
creatable?: boolean;
|
||||
/** Returns an i18n error key for an unusable custom value. */
|
||||
validate?: (value: string) => string | null;
|
||||
placeholder?: string;
|
||||
label?: string;
|
||||
mono?: boolean;
|
||||
/**
|
||||
* Multi-value fields: the typed text not added yet (`v-model:draft`), so
|
||||
* the owner can refuse to save it and restore it after a remount.
|
||||
*/
|
||||
draft?: string;
|
||||
/**
|
||||
* Multi-value fields: a comma adds the typed value. Off for raw regular
|
||||
* expressions, where a comma belongs to the pattern (`{1,3}`).
|
||||
*/
|
||||
splitOnComma?: boolean;
|
||||
}>(),
|
||||
{
|
||||
multiple: false,
|
||||
creatable: false,
|
||||
validate: undefined,
|
||||
placeholder: "",
|
||||
label: "",
|
||||
mono: true,
|
||||
draft: "",
|
||||
splitOnComma: true,
|
||||
},
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "update:modelValue", value: string | string[]): void;
|
||||
(e: "update:draft", value: string): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/** Item value of the "use typed text" entry (never a real option value). */
|
||||
const CREATE_VALUE = "\u0000create";
|
||||
|
||||
const uid = useId();
|
||||
const inputId = `filter-combo-${uid}`;
|
||||
const rootRef = ref<{ highlightedElement?: HTMLElement } | null>(null);
|
||||
const open = ref(false);
|
||||
// A multi-value draft kept by the owner comes back after a remount.
|
||||
const draft = ref(props.multiple ? props.draft : "");
|
||||
const typing = ref(!!draft.value.trim());
|
||||
const commitError = ref<string | null>(
|
||||
typing.value ? (props.validate?.(draft.value.trim()) ?? null) : null,
|
||||
);
|
||||
const pointerInside = ref(false);
|
||||
const focused = ref(false);
|
||||
|
||||
const values = computed(() =>
|
||||
Array.isArray(props.modelValue) ? props.modelValue : props.modelValue ? [props.modelValue] : [],
|
||||
);
|
||||
const single = computed(() => (Array.isArray(props.modelValue) ? "" : props.modelValue));
|
||||
const draftText = computed(() => draft.value.trim());
|
||||
const query = computed(() => (typing.value ? draftText.value.toLowerCase() : ""));
|
||||
|
||||
const inputText = computed({
|
||||
get: () => (props.multiple || typing.value ? draft.value : single.value),
|
||||
set: (text: string) => {
|
||||
draft.value = text;
|
||||
typing.value = true;
|
||||
commitError.value = null;
|
||||
},
|
||||
});
|
||||
|
||||
/** Search score: lower is better, -1 = no match. The English key ranks first. */
|
||||
function score(opt: ComboOption, q: string): number {
|
||||
const value = opt.value.toLowerCase();
|
||||
const snake = q.replace(/\s+/g, "_");
|
||||
if (value === q) return 0;
|
||||
if (value.startsWith(q) || value.startsWith(snake)) return 1;
|
||||
if (value.includes(q) || value.includes(snake)) return 2;
|
||||
if (opt.hint?.toLowerCase().includes(q)) return 3;
|
||||
if (opt.keywords?.some((k) => k.toLowerCase().includes(q))) return 4;
|
||||
return -1;
|
||||
}
|
||||
|
||||
const sections = computed(() => {
|
||||
const q = query.value;
|
||||
if (q) {
|
||||
const ranked = props.options
|
||||
.map((opt, index) => ({ opt, index, s: score(opt, q) }))
|
||||
.filter((r) => r.s >= 0)
|
||||
.sort((a, b) => a.s - b.s || a.index - b.index)
|
||||
.map((r) => r.opt);
|
||||
return ranked.length ? [{ name: "", options: ranked }] : [];
|
||||
}
|
||||
const groups: { name: string; options: ComboOption[] }[] = [];
|
||||
for (const opt of props.options) {
|
||||
const name = opt.group ?? "";
|
||||
const last = groups[groups.length - 1];
|
||||
if (last && last.name === name) last.options.push(opt);
|
||||
else groups.push({ name, options: [opt] });
|
||||
}
|
||||
return groups;
|
||||
});
|
||||
|
||||
const liveError = computed(() =>
|
||||
props.creatable && typing.value && draftText.value
|
||||
? (props.validate?.(draftText.value) ?? null)
|
||||
: null,
|
||||
);
|
||||
|
||||
const canCreate = computed(() => {
|
||||
if (!props.creatable || !typing.value || !draftText.value || liveError.value) return false;
|
||||
const text = draftText.value.toLowerCase();
|
||||
return (
|
||||
!props.options.some((o) => o.value.toLowerCase() === text) &&
|
||||
!values.value.some((v) => v.toLowerCase() === text)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Typed text in a multi-value field that has not been added yet. It is never
|
||||
* added implicitly (it may just be a search), so the route form refuses to
|
||||
* save until it is added with Enter or cleared.
|
||||
*/
|
||||
const pending = computed(
|
||||
() => props.multiple && typing.value && !!draftText.value && !commitError.value,
|
||||
);
|
||||
|
||||
watch(draft, (text) => {
|
||||
if (props.multiple) emit("update:draft", text);
|
||||
});
|
||||
|
||||
watch(open, (isOpen) => {
|
||||
if (isOpen) {
|
||||
// Single-value fields opened by a click or arrow key: typing replaces the
|
||||
// current value. Opened by typing, the typed text must stay as it is.
|
||||
if (!props.multiple) nextTick(() => !typing.value && inputEl()?.select());
|
||||
return;
|
||||
}
|
||||
if (!props.multiple && !props.creatable) resetDraft();
|
||||
});
|
||||
|
||||
/** Error of an already-added value (e.g. after the filter type changed). */
|
||||
function chipError(value: string): string | null {
|
||||
return props.validate?.(value) ?? null;
|
||||
}
|
||||
|
||||
function hintOf(value: string): string {
|
||||
return props.options.find((o) => o.value === value)?.hint ?? "";
|
||||
}
|
||||
|
||||
function inputEl(): HTMLInputElement | null {
|
||||
return document.getElementById(inputId) as HTMLInputElement | null;
|
||||
}
|
||||
|
||||
function focusInput(): void {
|
||||
inputEl()?.focus();
|
||||
}
|
||||
|
||||
function resetDraft(): void {
|
||||
draft.value = "";
|
||||
typing.value = false;
|
||||
commitError.value = null;
|
||||
}
|
||||
|
||||
function setValues(next: string[]): void {
|
||||
emit("update:modelValue", next);
|
||||
}
|
||||
|
||||
function choose(value: string): void {
|
||||
if (props.multiple) {
|
||||
const exists = values.value.includes(value);
|
||||
setValues(exists ? values.value.filter((v) => v !== value) : [...values.value, value]);
|
||||
resetDraft();
|
||||
nextTick(focusInput);
|
||||
return;
|
||||
}
|
||||
emit("update:modelValue", value);
|
||||
resetDraft();
|
||||
open.value = false;
|
||||
nextTick(focusInput);
|
||||
}
|
||||
|
||||
/** Commit typed text as a custom value; false (with an error shown) when invalid. */
|
||||
function commitDraft(): boolean {
|
||||
const text = draftText.value;
|
||||
if (!text) {
|
||||
// Clearing a single free-form value (e.g. the field path) removes it.
|
||||
if (!props.multiple && typing.value && single.value) emit("update:modelValue", "");
|
||||
resetDraft();
|
||||
return true;
|
||||
}
|
||||
const err = props.validate?.(text) ?? null;
|
||||
if (err) {
|
||||
commitError.value = err;
|
||||
return false;
|
||||
}
|
||||
if (props.multiple) {
|
||||
if (!values.value.includes(text)) setValues([...values.value, text]);
|
||||
} else if (text !== single.value) {
|
||||
emit("update:modelValue", text);
|
||||
}
|
||||
resetDraft();
|
||||
return true;
|
||||
}
|
||||
|
||||
function removeAt(index: number): void {
|
||||
setValues(values.value.filter((_, i) => i !== index));
|
||||
focusInput();
|
||||
}
|
||||
|
||||
function onPick(event: Event, value: string): void {
|
||||
// We own the model: stop reka from applying (or toggling) the value itself.
|
||||
event.preventDefault();
|
||||
choose(value);
|
||||
}
|
||||
|
||||
function onCreate(event: Event): void {
|
||||
event.preventDefault();
|
||||
if (commitDraft() && !props.multiple) open.value = false;
|
||||
nextTick(focusInput);
|
||||
}
|
||||
|
||||
function markPointerInside(): void {
|
||||
pointerInside.value = true;
|
||||
setTimeout(() => (pointerInside.value = false), 0);
|
||||
}
|
||||
|
||||
function onBlur(event: FocusEvent): void {
|
||||
focused.value = false;
|
||||
const next = event.relatedTarget as HTMLElement | null;
|
||||
// Focus moving into our own list means an option is being clicked.
|
||||
if (pointerInside.value || next?.closest?.(`[data-filter-combo="${uid}"]`)) return;
|
||||
if (!typing.value) return;
|
||||
if (!props.creatable) {
|
||||
resetDraft();
|
||||
return;
|
||||
}
|
||||
if (!props.multiple) {
|
||||
// A single free-form value (the field path) behaves like a text input.
|
||||
commitDraft();
|
||||
return;
|
||||
}
|
||||
// Only an exact suggestion is unambiguous enough to add on its own; any
|
||||
// other text stays pending (it may be a search) until Enter or clearing.
|
||||
const text = draftText.value.toLowerCase();
|
||||
const match = props.options.find((o) => o.value.toLowerCase() === text);
|
||||
if (!match) return;
|
||||
if (!values.value.includes(match.value)) setValues([...values.value, match.value]);
|
||||
resetDraft();
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
/** Whether the field shows text that was rejected and is not its value. */
|
||||
hasInvalidDraft: (): boolean => !!commitError.value,
|
||||
});
|
||||
|
||||
function isComposing(event: KeyboardEvent): boolean {
|
||||
return event.isComposing || event.keyCode === 229;
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (isComposing(event)) return;
|
||||
if (event.key === "Enter") {
|
||||
// Never let Enter submit the surrounding form.
|
||||
const handled = event.defaultPrevented;
|
||||
event.preventDefault();
|
||||
if (handled && rootRef.value?.highlightedElement) return;
|
||||
if (props.creatable && draftText.value) {
|
||||
if (commitDraft() && !props.multiple) open.value = false;
|
||||
} else if (!open.value) {
|
||||
open.value = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.key === "," && props.multiple && props.creatable) {
|
||||
const [start, end] = selectionOf(event);
|
||||
if (commaEndsValue(draft.value, start, end, props.splitOnComma)) {
|
||||
event.preventDefault();
|
||||
commitDraft();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.key === "Backspace" && props.multiple && !draft.value && values.value.length) {
|
||||
event.preventDefault();
|
||||
removeAt(values.value.length - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/** Selected range of the draft input (the caret when nothing is selected). */
|
||||
function selectionOf(event: Event): [number, number] {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const start = input.selectionStart ?? draft.value.length;
|
||||
return [start, input.selectionEnd ?? start];
|
||||
}
|
||||
|
||||
function onPaste(event: ClipboardEvent): void {
|
||||
if (!props.multiple || !props.creatable) return;
|
||||
const text = event.clipboardData?.getData("text") ?? "";
|
||||
const [start, end] = selectionOf(event);
|
||||
// The pasted text replaces the selection, exactly as a native paste would.
|
||||
const combined = draft.value.slice(0, start) + text + draft.value.slice(end);
|
||||
const parts = splitFilterValues(combined, props.splitOnComma);
|
||||
// Nothing to separate: the browser pastes into the draft as usual.
|
||||
if (parts.length <= 1 && (parts[0] ?? "") === combined.trim()) return;
|
||||
event.preventDefault();
|
||||
const next = [...values.value];
|
||||
const rejected: string[] = [];
|
||||
for (const part of parts) {
|
||||
if (props.validate?.(part)) rejected.push(part);
|
||||
else if (!next.includes(part)) next.push(part);
|
||||
}
|
||||
if (next.length !== values.value.length) setValues(next);
|
||||
draft.value = rejected.join(", ");
|
||||
typing.value = rejected.length > 0;
|
||||
commitError.value = rejected.length ? (props.validate?.(rejected[0]!) ?? null) : null;
|
||||
}
|
||||
</script>
|
||||
+224
-109
@@ -1,7 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { Plus, Trash2 } from "lucide-vue-next";
|
||||
import type { NodeForm } from "~/composables/useFilterNode";
|
||||
import { blankNode } from "~/composables/useFilterNode";
|
||||
import { FILTER_SCOPE_EVENTS, blankNode, isBlankNode, nodeKey } from "~/composables/useFilterNode";
|
||||
import { FILTER_TYPES, FILTER_OPS } from "~/types";
|
||||
import type { FilterOp, FilterType } from "~/types";
|
||||
import {
|
||||
convertValuesForOp,
|
||||
fieldPathOptions,
|
||||
isArrayFieldPath,
|
||||
validateFilterValue,
|
||||
valueOptions,
|
||||
} from "~/utils/filter-catalog";
|
||||
|
||||
defineOptions({ name: "FilterNodeEditor" });
|
||||
|
||||
@@ -12,19 +21,88 @@ const props = withDefaults(defineProps<{ node: NodeForm; depth?: number; deletab
|
||||
|
||||
const emit = defineEmits<{ (e: "remove"): void }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const { t, locale } = useI18n();
|
||||
const { confirm } = useConfirm();
|
||||
const fieldId = `filter-node-${useId()}`;
|
||||
const scopeEvents = inject(
|
||||
FILTER_SCOPE_EVENTS,
|
||||
computed((): string[] => []),
|
||||
);
|
||||
|
||||
const NODE_KINDS = ["all", "any"] as const;
|
||||
const filterTypeOptions = computed(() =>
|
||||
const typeOptions = computed(() =>
|
||||
FILTER_TYPES.map((value) => ({ label: t("filter." + value), value })),
|
||||
);
|
||||
const filterOpOptions = computed(() =>
|
||||
const opOptions = computed(() =>
|
||||
FILTER_OPS.map((value) => ({ label: t("filterOp." + value), value })),
|
||||
);
|
||||
const nodeKindOptions = computed(() =>
|
||||
NODE_KINDS.map((value) => ({ label: t("filterNode." + value), value })),
|
||||
const kindOptions = computed(() => [
|
||||
{ label: t("filterNode.all"), value: "all" },
|
||||
{ label: t("filterNode.any"), value: "any" },
|
||||
]);
|
||||
const pathOptions = computed(() => fieldPathOptions(locale.value, scopeEvents.value));
|
||||
const valueSuggestions = computed(() =>
|
||||
valueOptions(
|
||||
locale.value,
|
||||
props.node.leaf.type,
|
||||
props.node.leaf.op,
|
||||
props.node.leaf.path,
|
||||
scopeEvents.value,
|
||||
),
|
||||
);
|
||||
|
||||
const isField = computed(() => props.node.leaf.type === "field");
|
||||
const showOp = computed(() => props.node.leaf.type !== "keyword");
|
||||
const showValues = computed(
|
||||
() => props.node.leaf.type === "keyword" || props.node.leaf.op !== "exists",
|
||||
);
|
||||
|
||||
function validateValue(value: string): string | null {
|
||||
return validateFilterValue(props.node.leaf.type, props.node.leaf.op, value);
|
||||
}
|
||||
|
||||
/** Switch the operator, swapping `/x/` ↔ `x` when moving to or from `regex`. */
|
||||
function changeOp(next: FilterOp): void {
|
||||
const { leaf } = props.node;
|
||||
leaf.values = convertValuesForOp(leaf.values, leaf.op, next);
|
||||
leaf.op = next;
|
||||
}
|
||||
|
||||
function setType(value: string): void {
|
||||
if ((FILTER_TYPES as readonly string[]).includes(value)) {
|
||||
props.node.leaf.type = value as FilterType;
|
||||
// Keyword filters have no operator; a hidden `exists` would drop their values.
|
||||
if (value === "keyword") changeOp("eq");
|
||||
}
|
||||
}
|
||||
|
||||
function setOp(value: string): void {
|
||||
if (FILTER_OPS.includes(value as FilterOp)) {
|
||||
changeOp(value as FilterOp);
|
||||
// `exists` hides the values input: its unadded text must not block saving.
|
||||
if (!showValues.value) props.node.leaf.draft = "";
|
||||
}
|
||||
}
|
||||
|
||||
function setPath(value: string | string[]): void {
|
||||
props.node.leaf.path = typeof value === "string" ? value : "";
|
||||
// Paths ending on an array compare the whole array; `contains` matches an element.
|
||||
if (isArrayFieldPath(props.node.leaf.path) && props.node.leaf.op === "eq") {
|
||||
changeOp("contains");
|
||||
}
|
||||
}
|
||||
|
||||
function setValues(value: string | string[]): void {
|
||||
props.node.leaf.values = Array.isArray(value) ? value : value ? [value] : [];
|
||||
}
|
||||
|
||||
function setDraft(value: string): void {
|
||||
props.node.leaf.draft = value;
|
||||
}
|
||||
|
||||
function setKind(value: string): void {
|
||||
if (value === "all" || value === "any") props.node.kind = value;
|
||||
}
|
||||
|
||||
function addChild(kind: "leaf" | "all" | "any" | "not"): void {
|
||||
props.node.children.push(blankNode(kind));
|
||||
}
|
||||
@@ -37,103 +115,129 @@ function unwrapNot(): void {
|
||||
props.node.children = child.children;
|
||||
props.node.child = child.child;
|
||||
}
|
||||
|
||||
async function remove(): Promise<void> {
|
||||
// Text typed but not added yet (the leaf's draft) counts as content too.
|
||||
if (!isBlankNode(props.node)) {
|
||||
const confirmed = await confirm({
|
||||
title:
|
||||
props.node.kind === "leaf" ? t("confirm.removeCondition") : t("confirm.removeFilterGroup"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
}
|
||||
emit("remove");
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="node-editor" :class="{ 'node-nested': depth > 0 }">
|
||||
<div v-if="node.kind === 'leaf'" class="leaf-row">
|
||||
<RcSelect v-model="node.leaf.type" class="node-select" :options="filterTypeOptions" />
|
||||
|
||||
<RcInput
|
||||
v-if="node.leaf.type === 'field'"
|
||||
v-model="node.leaf.path"
|
||||
class="input node-path"
|
||||
:placeholder="t('routeEditor.pathPlaceholder')"
|
||||
/>
|
||||
|
||||
<RcSelect
|
||||
v-if="node.leaf.type !== 'keyword'"
|
||||
v-model="node.leaf.op"
|
||||
class="node-select"
|
||||
:options="filterOpOptions"
|
||||
:title="t('routeEditor.op')"
|
||||
/>
|
||||
|
||||
<TagInput
|
||||
v-if="node.leaf.type === 'keyword' || node.leaf.op !== 'exists'"
|
||||
v-model="node.leaf.values"
|
||||
class="node-values"
|
||||
:placeholder="t('routeEditor.valuesPlaceholder')"
|
||||
/>
|
||||
|
||||
<RcCheckbox
|
||||
v-model="node.leaf.exclude"
|
||||
class="node-exclude"
|
||||
:label="t('routeEditor.not')"
|
||||
:title="t('routeEditor.not')"
|
||||
/>
|
||||
|
||||
<RcButton
|
||||
v-if="deletable"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
class="icon-btn danger"
|
||||
:title="t('routeEditor.remove')"
|
||||
@click="emit('remove')"
|
||||
>
|
||||
✕
|
||||
</RcButton>
|
||||
<div
|
||||
v-if="node.kind === 'leaf'"
|
||||
class="leaf-row"
|
||||
:class="{
|
||||
'is-field': isField,
|
||||
'is-keyword': !showOp,
|
||||
'no-values': !showValues,
|
||||
'is-negated': node.leaf.exclude,
|
||||
}"
|
||||
>
|
||||
<div class="leaf-type">
|
||||
<label :for="`${fieldId}-type`" class="sr-only">{{ t("routeEditor.filterType") }}</label>
|
||||
<RcSelect
|
||||
:id="`${fieldId}-type`"
|
||||
:model-value="node.leaf.type"
|
||||
:options="typeOptions"
|
||||
@update:model-value="setType"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="isField" class="leaf-path">
|
||||
<FilterCombobox
|
||||
:model-value="node.leaf.path"
|
||||
:options="pathOptions"
|
||||
creatable
|
||||
:placeholder="t('routeEditor.pathPlaceholder')"
|
||||
:label="t('routeEditor.path')"
|
||||
@update:model-value="setPath"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="showOp" class="leaf-op">
|
||||
<label :for="`${fieldId}-op`" class="sr-only">{{ t("routeEditor.op") }}</label>
|
||||
<RcSelect
|
||||
:id="`${fieldId}-op`"
|
||||
:model-value="node.leaf.op"
|
||||
:options="opOptions"
|
||||
:title="t('routeEditor.op')"
|
||||
@update:model-value="setOp"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="showValues" class="leaf-values">
|
||||
<FilterCombobox
|
||||
:model-value="node.leaf.values"
|
||||
:options="valueSuggestions"
|
||||
multiple
|
||||
creatable
|
||||
:validate="validateValue"
|
||||
:split-on-comma="node.leaf.op !== 'regex'"
|
||||
:draft="node.leaf.draft"
|
||||
:placeholder="t('routeEditor.valuesPlaceholder')"
|
||||
:label="t('routeEditor.values')"
|
||||
@update:model-value="setValues"
|
||||
@update:draft="setDraft"
|
||||
/>
|
||||
</div>
|
||||
<div class="leaf-actions">
|
||||
<RcToggle
|
||||
:model-value="node.leaf.exclude"
|
||||
size="sm"
|
||||
class="w-auto px-2.5 text-xs font-semibold ring-1 ring-inset ring-border-strong"
|
||||
:title="t('routeEditor.notHint')"
|
||||
:aria-label="t('routeEditor.notHint')"
|
||||
@update:model-value="node.leaf.exclude = $event"
|
||||
>
|
||||
{{ t("routeEditor.not") }}
|
||||
</RcToggle>
|
||||
<RcButton
|
||||
v-if="deletable"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:title="t('routeEditor.removeCondition')"
|
||||
:aria-label="t('routeEditor.removeCondition')"
|
||||
@click="remove"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="node.kind === 'all' || node.kind === 'any'" class="node-group">
|
||||
<div class="node-group-head">
|
||||
<RcSelect v-model="node.kind" class="node-combo" :options="nodeKindOptions" />
|
||||
<div class="node-actions">
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
class="node-add"
|
||||
@click="addChild('leaf')"
|
||||
>
|
||||
+ {{ t("routeEditor.addLeaf") }}
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
class="node-add"
|
||||
@click="addChild('all')"
|
||||
>
|
||||
+ {{ t("routeEditor.addGroup") }}
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
class="node-add"
|
||||
@click="addChild('not')"
|
||||
>
|
||||
+ {{ t("routeEditor.addNot") }}
|
||||
</RcButton>
|
||||
<RcButton
|
||||
v-if="deletable"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
class="icon-btn danger"
|
||||
:title="t('routeEditor.remove')"
|
||||
@click="emit('remove')"
|
||||
>
|
||||
✕
|
||||
</RcButton>
|
||||
</div>
|
||||
<RcToggleGroup
|
||||
:model-value="node.kind"
|
||||
:options="kindOptions"
|
||||
class="node-kind w-auto"
|
||||
@update:model-value="setKind"
|
||||
/>
|
||||
<RcButton
|
||||
v-if="deletable"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="ml-auto h-8 w-8 text-muted hover:text-bad"
|
||||
:title="t('routeEditor.removeGroup')"
|
||||
:aria-label="t('routeEditor.removeGroup')"
|
||||
@click="remove"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
</div>
|
||||
<div class="node-children">
|
||||
<FilterNodeEditor
|
||||
v-for="(child, i) in node.children"
|
||||
:key="i"
|
||||
:key="nodeKey(child)"
|
||||
:node="child"
|
||||
:depth="depth + 1"
|
||||
deletable
|
||||
@@ -141,27 +245,38 @@ function unwrapNot(): void {
|
||||
/>
|
||||
<div v-if="node.children.length === 0" class="node-empty">{{ t("filterNode.empty") }}</div>
|
||||
</div>
|
||||
<div class="node-add">
|
||||
<RcButton type="button" variant="ghost" size="xs" @click="addChild('leaf')">
|
||||
<Plus :size="13" />{{ t("routeEditor.addLeaf") }}
|
||||
</RcButton>
|
||||
<RcButton type="button" variant="ghost" size="xs" @click="addChild('all')">
|
||||
<Plus :size="13" />{{ t("routeEditor.addGroup") }}
|
||||
</RcButton>
|
||||
<RcButton type="button" variant="ghost" size="xs" @click="addChild('not')">
|
||||
<Plus :size="13" />{{ t("routeEditor.addNot") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="node-group node-not">
|
||||
<div class="node-group-head">
|
||||
<span class="node-combo node-combo-label">{{ t("filterNode.not") }}</span>
|
||||
<div class="node-actions">
|
||||
<RcButton type="button" variant="ghost" size="xs" class="node-add" @click="unwrapNot">
|
||||
{{ t("filterNode.unwrap") }}
|
||||
</RcButton>
|
||||
<RcButton
|
||||
v-if="deletable"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
class="icon-btn danger"
|
||||
:title="t('routeEditor.remove')"
|
||||
@click="emit('remove')"
|
||||
>
|
||||
✕
|
||||
</RcButton>
|
||||
</div>
|
||||
<span class="node-not-label">{{ t("filterNode.not") }}</span>
|
||||
<RcButton type="button" variant="ghost" size="xs" class="ml-auto" @click="unwrapNot">
|
||||
{{ t("filterNode.unwrap") }}
|
||||
</RcButton>
|
||||
<RcButton
|
||||
v-if="deletable"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:title="t('routeEditor.removeGroup')"
|
||||
:aria-label="t('routeEditor.removeGroup')"
|
||||
@click="remove"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
</div>
|
||||
<div class="node-children">
|
||||
<FilterNodeEditor v-if="node.child" :node="node.child" :depth="depth + 1" />
|
||||
|
||||
@@ -66,35 +66,41 @@
|
||||
<span class="lbl-note">{{ t("groupEditor.forgeSourcesNote") }}</span></label
|
||||
>
|
||||
<div v-for="(s, i) in form.forgeSources" :key="i" class="forge-source-row">
|
||||
<RcInput
|
||||
v-model="s.host"
|
||||
type="text"
|
||||
class="[grid-area:host]"
|
||||
:placeholder="t('groupEditor.forgeSourcesHost')"
|
||||
/>
|
||||
<RcSelect
|
||||
v-model="s.type"
|
||||
class="w-[110px] [grid-area:type]"
|
||||
:options="[
|
||||
{ label: 'GitHub', value: 'github' },
|
||||
{ label: 'Gitea', value: 'gitea' },
|
||||
]"
|
||||
/>
|
||||
<div class="f-host">
|
||||
<RcInput
|
||||
v-model="s.host"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.forgeSourcesHost')"
|
||||
/>
|
||||
</div>
|
||||
<div class="f-type">
|
||||
<RcSelect
|
||||
v-model="s.type"
|
||||
:options="[
|
||||
{ label: 'GitHub', value: 'github' },
|
||||
{ label: 'Gitea', value: 'gitea' },
|
||||
]"
|
||||
/>
|
||||
</div>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="destructive"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="[grid-area:del] justify-self-end"
|
||||
@click="form.forgeSources.splice(i, 1)"
|
||||
class="f-del h-9 w-9 text-muted hover:text-bad"
|
||||
:title="t('groupEditor.forgeSourcesRemove')"
|
||||
:aria-label="t('groupEditor.forgeSourcesRemove')"
|
||||
@click="removeForgeSource(s)"
|
||||
>
|
||||
✕
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
<RcInput
|
||||
v-model="s.name"
|
||||
type="text"
|
||||
class="[grid-area:name]"
|
||||
:placeholder="t('groupEditor.forgeSourcesName')"
|
||||
/>
|
||||
<div class="f-name">
|
||||
<RcInput
|
||||
v-model="s.name"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.forgeSourcesName')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<RcButton type="button" variant="ghost" class="add-filter" @click="addForgeSource">
|
||||
{{ t("groupEditor.forgeSourcesAdd") }}
|
||||
@@ -159,12 +165,14 @@
|
||||
>{{ t("groupEditor.installationId") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.installationIdNote") }}</span></label
|
||||
>
|
||||
<RcInput
|
||||
v-model="form.installationId"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
:placeholder="t('groupEditor.installationIdPlaceholder')"
|
||||
/>
|
||||
<div class="ctl-md">
|
||||
<RcInput
|
||||
v-model="form.installationId"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
:placeholder="t('groupEditor.installationIdPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="hint">{{ t("groupEditor.installationIdHint") }}</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -175,48 +183,52 @@
|
||||
>{{ t("groupEditor.logTarget") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.logTargetNote") }}</span></label
|
||||
>
|
||||
<RcSelect
|
||||
:model-value="form.logPlatform || 'none'"
|
||||
:options="[
|
||||
{ label: t('groupEditor.logDisabled'), value: 'none' },
|
||||
{ label: 'Discord', value: 'discord' },
|
||||
{ label: 'Telegram', value: 'telegram' },
|
||||
{ label: t('groupEditor.logFeishu'), value: 'feishu' },
|
||||
]"
|
||||
@update:model-value="
|
||||
form.logPlatform = ($event === 'none' ? '' : $event) as
|
||||
'' | 'discord' | 'telegram' | 'feishu'
|
||||
"
|
||||
/>
|
||||
<template v-if="form.logPlatform === 'discord'">
|
||||
<RcInput
|
||||
v-model="form.logChannelId"
|
||||
type="text"
|
||||
class="mt-2"
|
||||
:placeholder="t('routeEditor.channelPlaceholder')"
|
||||
<div class="ctl-md">
|
||||
<RcSelect
|
||||
:model-value="form.logPlatform || 'none'"
|
||||
:options="[
|
||||
{ label: t('groupEditor.logDisabled'), value: 'none' },
|
||||
{ label: 'Discord', value: 'discord' },
|
||||
{ label: 'Telegram', value: 'telegram' },
|
||||
{ label: t('groupEditor.logFeishu'), value: 'feishu' },
|
||||
]"
|
||||
@update:model-value="
|
||||
form.logPlatform = ($event === 'none' ? '' : $event) as
|
||||
'' | 'discord' | 'telegram' | 'feishu'
|
||||
"
|
||||
/>
|
||||
<RcInput
|
||||
v-model="form.logThreadId"
|
||||
type="text"
|
||||
class="mt-2"
|
||||
:placeholder="t('routeEditor.threadPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="form.logPlatform === 'telegram' || form.logPlatform === 'feishu'">
|
||||
<RcInput
|
||||
v-model="form.logChatId"
|
||||
type="text"
|
||||
class="mt-2"
|
||||
:placeholder="t('routeEditor.chatPlaceholder')"
|
||||
/>
|
||||
<RcInput
|
||||
v-if="form.logPlatform === 'telegram'"
|
||||
v-model="form.logTopicId"
|
||||
type="text"
|
||||
class="mt-2"
|
||||
:placeholder="t('routeEditor.topicPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
<div v-if="form.logPlatform" class="ctl-stack">
|
||||
<template v-if="form.logPlatform === 'discord'">
|
||||
<RcInput
|
||||
v-model="form.logChannelId"
|
||||
type="text"
|
||||
:placeholder="t('routeEditor.channelPlaceholder')"
|
||||
/>
|
||||
<RcInput
|
||||
v-model="form.logThreadId"
|
||||
type="text"
|
||||
:placeholder="t('routeEditor.threadPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<RcInput
|
||||
v-model="form.logChatId"
|
||||
type="text"
|
||||
:placeholder="
|
||||
form.logPlatform === 'telegram'
|
||||
? t('routeEditor.chatPlaceholder')
|
||||
: t('routeEditor.feishuChatPlaceholder')
|
||||
"
|
||||
/>
|
||||
<RcInput
|
||||
v-if="form.logPlatform === 'telegram'"
|
||||
v-model="form.logTopicId"
|
||||
type="text"
|
||||
:placeholder="t('routeEditor.topicPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
<div class="hint">{{ t("groupEditor.logTargetHint") }}</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -237,9 +249,11 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { reactive, watch } from "vue";
|
||||
import { Trash2 } from "lucide-vue-next";
|
||||
import type { ForgeSource, Group } from "~/types";
|
||||
|
||||
const { t } = useI18n();
|
||||
const { confirm } = useConfirm();
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
@@ -285,6 +299,15 @@ const owners = computed({
|
||||
function addForgeSource(): void {
|
||||
form.forgeSources.push({ host: "", type: "github" });
|
||||
}
|
||||
|
||||
async function removeForgeSource(source: ForgeSource): Promise<void> {
|
||||
const label = source.host.trim() || source.name?.trim();
|
||||
if (label && !(await confirm({ title: t("confirm.removeForgeSource", { name: label }) }))) {
|
||||
return;
|
||||
}
|
||||
const index = form.forgeSources.indexOf(source);
|
||||
if (index >= 0) form.forgeSources.splice(index, 1);
|
||||
}
|
||||
function toggleProvider(p: "github" | "gitea", checked: boolean): void {
|
||||
form.providers = checked
|
||||
? [...new Set([...form.providers, p])]
|
||||
@@ -320,8 +343,12 @@ function close(): void {
|
||||
emit("close");
|
||||
}
|
||||
|
||||
// A click on the backdrop must not discard what has been typed so far.
|
||||
const { isBackdropClose } = useBackdropGuard(() => props.open, ".editor-dialog");
|
||||
useDialogFocus(() => props.open, ".editor-dialog");
|
||||
|
||||
function onOpenChange(open: boolean): void {
|
||||
if (!open) close();
|
||||
if (!open && !isBackdropClose()) close();
|
||||
}
|
||||
|
||||
function save(): void {
|
||||
|
||||
@@ -7,45 +7,52 @@
|
||||
|
||||
<p v-if="!members.length" class="empty-log">{{ t("members.empty") }}</p>
|
||||
|
||||
<ul class="member-list">
|
||||
<li v-for="m in members" :key="m.login.toLowerCase()" class="member-row">
|
||||
<span class="member-login">{{ m.login }}</span>
|
||||
<RcSelect
|
||||
v-if="canEdit"
|
||||
class="filter-select"
|
||||
:model-value="m.role"
|
||||
:options="roleOptions"
|
||||
:disabled="saving"
|
||||
@update:model-value="onRoleChange(m, $event)"
|
||||
/>
|
||||
<RcBadge v-else size="xs" class="role-pill" :class="m.role">{{
|
||||
t("roles." + m.role)
|
||||
}}</RcBadge>
|
||||
<ul class="member-grid">
|
||||
<li v-for="m in members" :key="m.login.toLowerCase()" class="member-card">
|
||||
<span class="member-name" :title="m.login">{{ m.login }}</span>
|
||||
<div class="member-role">
|
||||
<RcSelect
|
||||
v-if="canEdit"
|
||||
:model-value="m.role"
|
||||
:options="roleOptions"
|
||||
:disabled="saving"
|
||||
@update:model-value="onRoleChange(m, $event)"
|
||||
/>
|
||||
<RcBadge v-else size="xs" class="role-pill" :class="m.role">{{
|
||||
t("roles." + m.role)
|
||||
}}</RcBadge>
|
||||
</div>
|
||||
<RcButton
|
||||
v-if="canEdit"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="icon-btn danger"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:disabled="saving"
|
||||
:title="t('members.remove')"
|
||||
:aria-label="t('members.remove')"
|
||||
@click="removeMember(m)"
|
||||
>
|
||||
✕
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-if="canEdit" class="member-add">
|
||||
<RcInput
|
||||
v-model="newLogin"
|
||||
type="text"
|
||||
:placeholder="t('members.addPlaceholder')"
|
||||
class="text-input"
|
||||
@keydown.enter.prevent="addMember"
|
||||
/>
|
||||
<RcSelect v-model="newRole" class="filter-select" :options="roleOptions" />
|
||||
<RcButton type="button" size="sm" :disabled="saving" @click="addMember">
|
||||
<div class="member-add-login">
|
||||
<RcInput
|
||||
v-model="newLogin"
|
||||
type="text"
|
||||
size="sm"
|
||||
:placeholder="t('members.addPlaceholder')"
|
||||
@keydown.enter.prevent="addMember"
|
||||
/>
|
||||
</div>
|
||||
<div class="member-role">
|
||||
<RcSelect v-model="newRole" :options="roleOptions" />
|
||||
</div>
|
||||
<RcButton type="button" size="sm" class="h-9" :disabled="saving" @click="addMember">
|
||||
{{ t("members.addBtn") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
@@ -56,8 +63,16 @@
|
||||
<span class="lbl-note">{{ t("members.inviteNote") }}</span>
|
||||
</h4>
|
||||
<div class="invite-create">
|
||||
<RcSelect v-model="inviteRole" class="filter-select" :options="inviteRoleOptions" />
|
||||
<RcButton type="button" size="sm" :disabled="saving || inviting" @click="createInvite">
|
||||
<div class="member-role">
|
||||
<RcSelect v-model="inviteRole" :options="inviteRoleOptions" />
|
||||
</div>
|
||||
<RcButton
|
||||
type="button"
|
||||
size="sm"
|
||||
class="h-9"
|
||||
:disabled="saving || inviting"
|
||||
@click="createInvite"
|
||||
>
|
||||
{{ t("members.createInvite") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
@@ -68,17 +83,14 @@
|
||||
t("roles." + inv.role)
|
||||
}}</RcBadge>
|
||||
<span class="invite-exp">{{ fmtExp(inv.expiresAt) }}</span>
|
||||
<RcButton type="button" variant="ghost" size="sm" @click="copyInvite(inv)">
|
||||
{{ copied === inv.token ? t("members.copied") : t("members.copyLink") }}
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
class="icon-btn danger"
|
||||
@click="revoke(inv)"
|
||||
>{{ t("members.revoke") }}</RcButton
|
||||
>
|
||||
<div class="invite-actions">
|
||||
<RcButton type="button" variant="ghost" size="sm" @click="copyInvite(inv)">
|
||||
{{ copied === inv.token ? t("members.copied") : t("members.copyLink") }}
|
||||
</RcButton>
|
||||
<RcButton type="button" variant="ghost" color="error" size="sm" @click="revoke(inv)">{{
|
||||
t("members.revoke")
|
||||
}}</RcButton>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="empty-log">{{ t("members.noInvites") }}</p>
|
||||
@@ -90,10 +102,12 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from "vue";
|
||||
import { Trash2 } from "lucide-vue-next";
|
||||
import type { Group, GroupInvite, GroupMember, GroupRole } from "~/types";
|
||||
import { useInvitesApi } from "~/composables/useInvites";
|
||||
|
||||
const { t } = useI18n();
|
||||
const { confirm } = useConfirm();
|
||||
|
||||
const props = defineProps<{ group: Group; canEdit: boolean; saving: boolean }>();
|
||||
const emit = defineEmits<{ (e: "save", group: Group): void }>();
|
||||
@@ -156,11 +170,17 @@ function addMember(): void {
|
||||
emitSave();
|
||||
}
|
||||
|
||||
function removeMember(m: GroupMember): void {
|
||||
async function removeMember(m: GroupMember): Promise<void> {
|
||||
formError.value = "";
|
||||
if (m.role === "owner" && ownerCount() === 1) {
|
||||
formError.value = t("members.errLastOwner");
|
||||
return;
|
||||
}
|
||||
const confirmed = await confirm({
|
||||
title: t("confirm.removeMember", { name: m.login }),
|
||||
confirmText: t("members.remove"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
members.value = members.value.filter((x) => x !== m);
|
||||
emitSave();
|
||||
}
|
||||
@@ -202,6 +222,11 @@ async function copyInvite(inv: GroupInvite): Promise<void> {
|
||||
}
|
||||
|
||||
async function revoke(inv: GroupInvite): Promise<void> {
|
||||
const confirmed = await confirm({
|
||||
title: t("confirm.revokeInvite"),
|
||||
confirmText: t("members.revoke"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
try {
|
||||
await invitesApi.revoke(inv.token);
|
||||
invites.value = invites.value.filter((i) => i.token !== inv.token);
|
||||
|
||||
+155
-190
@@ -1,226 +1,191 @@
|
||||
<template>
|
||||
<RcCard variant="outline" padding="none" :class="cardClass">
|
||||
<div class="route-card-main">
|
||||
<div class="route-card-header">
|
||||
<div class="route-row">
|
||||
<div class="route-lead">
|
||||
<button
|
||||
v-if="reordering"
|
||||
type="button"
|
||||
class="route-handle"
|
||||
:data-route-handle="route.id"
|
||||
:aria-label="t('routes.dragHandle', { name: displayName })"
|
||||
:aria-describedby="hintId"
|
||||
:disabled="locked"
|
||||
@pointerdown="emit('dragStart', $event)"
|
||||
@keydown="onHandleKey"
|
||||
>
|
||||
<GripVertical :size="16" />
|
||||
</button>
|
||||
<RcSwitch
|
||||
v-if="!readonly"
|
||||
v-else-if="!readonly"
|
||||
:model-value="route.enabled"
|
||||
size="sm"
|
||||
:disabled="locked"
|
||||
@update:model-value="onToggle"
|
||||
/>
|
||||
<span v-if="readonly" class="dot" :class="route.enabled ? 'ok' : 'bad'"></span>
|
||||
<div class="route-card-title">
|
||||
<span class="route-name">{{ route.name || t("route.untitled") }}</span>
|
||||
<span class="route-id">{{ route.id }}</span>
|
||||
</div>
|
||||
<div class="route-card-badges">
|
||||
<RcBadge
|
||||
v-for="(tg, i) in route.targets"
|
||||
:key="i"
|
||||
size="xs"
|
||||
class="route-badge"
|
||||
:class="
|
||||
tg.platform === 'telegram'
|
||||
? 'route-badge-tg'
|
||||
: tg.platform === 'feishu'
|
||||
? 'route-badge-fs'
|
||||
: 'route-badge-dc'
|
||||
"
|
||||
>
|
||||
<span
|
||||
class="route-badge-dot"
|
||||
:class="
|
||||
tg.platform === 'telegram'
|
||||
? 'bg-info'
|
||||
: tg.platform === 'feishu'
|
||||
? 'bg-warn'
|
||||
: 'bg-accent'
|
||||
"
|
||||
></span>
|
||||
{{
|
||||
tg.platform === "telegram"
|
||||
? "Telegram"
|
||||
: tg.platform === "feishu"
|
||||
? t("route.feishu")
|
||||
: "Discord"
|
||||
}}
|
||||
</RcBadge>
|
||||
<RcBadge
|
||||
v-if="route.fallback"
|
||||
variant="warning"
|
||||
size="xs"
|
||||
class="route-badge route-badge-fallback"
|
||||
>{{ t("route.fallback") }}</RcBadge
|
||||
>
|
||||
<RcBadge
|
||||
v-if="route.stop"
|
||||
variant="destructive"
|
||||
size="xs"
|
||||
class="route-badge route-badge-stop"
|
||||
>{{ t("route.stop") }}</RcBadge
|
||||
>
|
||||
<RcBadge
|
||||
v-if="route.discordRoleIds?.length"
|
||||
size="xs"
|
||||
class="route-badge route-badge-role"
|
||||
>@roles</RcBadge
|
||||
>
|
||||
</div>
|
||||
<span v-else class="dot" :class="route.enabled ? 'ok' : 'bad'"></span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<div class="route-card-filters">
|
||||
<span v-if="summary" class="route-chip">
|
||||
<span class="route-chip-val">{{ summary }}</span>
|
||||
</span>
|
||||
<span v-else class="route-chip route-chip-empty">
|
||||
<span class="route-chip-type">{{ t("route.noFilters") }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="route-title">
|
||||
<span v-if="reordering" class="route-position">{{ position }}</span>
|
||||
<span class="route-name">{{ displayName }}</span>
|
||||
<span class="route-id">{{ route.id }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="hasTags" class="route-tags">
|
||||
<RcBadge
|
||||
v-for="p in platforms"
|
||||
:key="p.platform"
|
||||
size="xs"
|
||||
class="route-badge"
|
||||
:class="`route-badge-${p.platform}`"
|
||||
>
|
||||
<span class="route-badge-dot"></span>
|
||||
{{ platformLabel(p.platform) }}<template v-if="p.count > 1"> ×{{ p.count }}</template>
|
||||
</RcBadge>
|
||||
<RcBadge
|
||||
v-if="route.discordRoleIds?.length"
|
||||
size="xs"
|
||||
class="route-badge route-badge-role"
|
||||
:title="route.discordRoleIds.join(', ')"
|
||||
>@roles</RcBadge
|
||||
>
|
||||
<RcBadge v-if="route.fallback" size="xs" class="route-badge route-badge-fallback">{{
|
||||
t("route.fallback")
|
||||
}}</RcBadge>
|
||||
<RcBadge v-if="route.stop" size="xs" class="route-badge route-badge-stop">{{
|
||||
t("route.stop")
|
||||
}}</RcBadge>
|
||||
</div>
|
||||
|
||||
<div v-if="!readonly && !reordering" class="route-actions">
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-text"
|
||||
:disabled="locked"
|
||||
:title="t('routeEditor.editTitle')"
|
||||
:aria-label="t('routeEditor.editTitle')"
|
||||
@click="emit('edit', route)"
|
||||
>
|
||||
<Pencil :size="15" />
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:disabled="locked"
|
||||
:title="t('routes.delete')"
|
||||
:aria-label="t('routes.delete')"
|
||||
@click="emit('delete', route)"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
</div>
|
||||
|
||||
<div class="route-body">
|
||||
<p class="route-summary" :class="{ 'is-empty': !summary }" :title="summary || undefined">
|
||||
{{ summary || t("route.noFilters") }}
|
||||
</p>
|
||||
<div v-if="route.targets.length" class="route-card-targets">
|
||||
<div v-for="(tg, i) in route.targets" :key="i" class="route-target">
|
||||
<div class="route-target-row">
|
||||
<span class="route-target-label">
|
||||
<template v-if="tg.platform === 'telegram' || tg.platform === 'feishu'">{{
|
||||
t("route.chat")
|
||||
}}</template>
|
||||
<template v-else-if="tg.threadId">{{ t("route.thread") }}</template>
|
||||
<template v-else>{{ t("route.channel") }}</template>
|
||||
</span>
|
||||
<code class="route-target-id">
|
||||
<template v-if="tg.platform === 'telegram' || tg.platform === 'feishu'">{{
|
||||
tg.chatId
|
||||
}}</template>
|
||||
<template v-else-if="tg.threadId">{{ tg.threadId }}</template>
|
||||
<template v-else>{{ tg.channelId }}</template>
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
<span v-for="(tg, i) in route.targets" :key="i" class="route-target-row">
|
||||
<span class="route-target-label">
|
||||
<template v-if="tg.platform === 'telegram' || tg.platform === 'feishu'">{{
|
||||
t("route.chat")
|
||||
}}</template>
|
||||
<template v-else-if="tg.threadId">{{ t("route.thread") }}</template>
|
||||
<template v-else>{{ t("route.channel") }}</template>
|
||||
</span>
|
||||
<code class="route-target-id">
|
||||
<template v-if="tg.platform === 'telegram' || tg.platform === 'feishu'">{{
|
||||
tg.chatId
|
||||
}}</template>
|
||||
<template v-else-if="tg.threadId">{{ tg.threadId }}</template>
|
||||
<template v-else>{{ tg.channelId }}</template>
|
||||
</code>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!readonly" class="route-card-actions">
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="route-action-btn"
|
||||
:disabled="atFirst"
|
||||
:title="t('route.moveUp')"
|
||||
@click="$emit('move', route, -1)"
|
||||
>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="m18 15-6-6-6 6" />
|
||||
</svg>
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="route-action-btn"
|
||||
:disabled="atLast"
|
||||
:title="t('route.moveDown')"
|
||||
@click="$emit('move', route, 1)"
|
||||
>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="m6 9 6 6 6-6" />
|
||||
</svg>
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="route-action-btn"
|
||||
:title="t('routeEditor.editTitle')"
|
||||
@click="$emit('edit', route)"
|
||||
>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
|
||||
<path d="m15 5 4 4" />
|
||||
</svg>
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
class="route-action-btn route-action-btn-danger"
|
||||
:title="t('routeEditor.close')"
|
||||
@click="$emit('delete', route)"
|
||||
>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M18 6 6 18" />
|
||||
<path d="m6 6 12 12" />
|
||||
</svg>
|
||||
</RcButton>
|
||||
</div>
|
||||
</RcCard>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { FilterNode, Route } from "~/types";
|
||||
import { GripVertical, Pencil, Trash2 } from "lucide-vue-next";
|
||||
import type { FilterNode, Route, RouteTarget } from "~/types";
|
||||
import { describeNode } from "~/composables/useFilterNode";
|
||||
|
||||
type Platform = NonNullable<RouteTarget["platform"]>;
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const props = defineProps<{
|
||||
route: Route;
|
||||
atFirst?: boolean;
|
||||
atLast?: boolean;
|
||||
readonly?: boolean;
|
||||
/** Reorder mode: a drag handle replaces the switch and the actions hide. */
|
||||
reordering?: boolean;
|
||||
/**
|
||||
* The routes are being written (an order, a switch, a delete): every control
|
||||
* waits, so the next change builds on what was saved.
|
||||
*/
|
||||
locked?: boolean;
|
||||
/** 1-based position shown while reordering. */
|
||||
position?: number;
|
||||
/** Id of the element describing how to reorder (for the handle). */
|
||||
hintId?: string;
|
||||
}>();
|
||||
|
||||
const summary = computed(() => {
|
||||
const node: FilterNode = props.route.ast ?? { all: props.route.filters };
|
||||
return describeNode(node, t);
|
||||
});
|
||||
const cardClass = computed(() => `route-card${props.route.enabled ? "" : " disabled"}`);
|
||||
const emit = defineEmits<{
|
||||
(e: "toggle", route: Route): void;
|
||||
(e: "edit", route: Route): void;
|
||||
(e: "delete", route: Route): void;
|
||||
(e: "move", route: Route, dir: -1 | 1): void;
|
||||
(e: "dragStart", event: PointerEvent): void;
|
||||
(e: "nudge", dir: -1 | 1): void;
|
||||
}>();
|
||||
|
||||
const displayName = computed(() => props.route.name || t("route.untitled"));
|
||||
const summary = computed(() => {
|
||||
const node: FilterNode = props.route.ast ?? { all: props.route.filters };
|
||||
return describeNode(node, t);
|
||||
});
|
||||
const cardClass = computed(
|
||||
() =>
|
||||
`route-card${props.route.enabled ? "" : " disabled"}${props.reordering ? " is-reordering" : ""}`,
|
||||
);
|
||||
|
||||
/** One tag per platform (in target order) with how many targets use it. */
|
||||
const platforms = computed(() => {
|
||||
const counts = new Map<Platform, number>();
|
||||
for (const tg of props.route.targets) {
|
||||
const platform: Platform = tg.platform ?? "discord";
|
||||
counts.set(platform, (counts.get(platform) ?? 0) + 1);
|
||||
}
|
||||
return [...counts].map(([platform, count]) => ({ platform, count }));
|
||||
});
|
||||
const hasTags = computed(
|
||||
() =>
|
||||
platforms.value.length > 0 ||
|
||||
!!props.route.discordRoleIds?.length ||
|
||||
!!props.route.fallback ||
|
||||
!!props.route.stop,
|
||||
);
|
||||
|
||||
function platformLabel(platform: Platform): string {
|
||||
if (platform === "telegram") return "Telegram";
|
||||
if (platform === "feishu") return t("route.feishu");
|
||||
return "Discord";
|
||||
}
|
||||
|
||||
function onToggle(enabled: boolean): void {
|
||||
const next = { ...props.route, enabled };
|
||||
emit("toggle", next);
|
||||
emit("toggle", { ...props.route, enabled });
|
||||
}
|
||||
|
||||
function onHandleKey(event: KeyboardEvent): void {
|
||||
if (event.key === "ArrowUp" || event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
emit("nudge", event.key === "ArrowUp" ? -1 : 1);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
+266
-112
@@ -1,15 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from "vue";
|
||||
import { computed, nextTick, provide, reactive, ref, watch } from "vue";
|
||||
import { Trash2 } from "lucide-vue-next";
|
||||
import type { Filter, FilterNode, NamedFragment, Route, RouteTarget, RouteTemplate } from "~/types";
|
||||
import { FRAGMENT_PRESETS, ROUTE_TEMPLATES } from "~/types";
|
||||
import type { NodeForm } from "~/composables/useFilterNode";
|
||||
import {
|
||||
FILTER_SCOPE_EVENTS,
|
||||
blankLeafForm,
|
||||
blankNode,
|
||||
nodeToForm,
|
||||
nodeFormToRouteFilters,
|
||||
formToNode,
|
||||
hasPendingDraft,
|
||||
scopeEvents,
|
||||
} from "~/composables/useFilterNode";
|
||||
import { eventOptions, validateFilterValue } from "~/utils/filter-catalog";
|
||||
|
||||
interface TargetForm {
|
||||
platform: "discord" | "telegram" | "feishu";
|
||||
@@ -26,7 +31,8 @@ const props = withDefaults(
|
||||
|
||||
const emit = defineEmits<{ (e: "close"): void; (e: "save", route: Route): void }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const { t, locale } = useI18n();
|
||||
const { confirm } = useConfirm();
|
||||
|
||||
const isEdit = computed(() => props.route != null);
|
||||
const discordRoles = computed({
|
||||
@@ -39,6 +45,7 @@ const discordRoles = computed({
|
||||
form.discordRolesText = roles.join(", ");
|
||||
},
|
||||
});
|
||||
const bodyEl = ref<HTMLFormElement | null>(null);
|
||||
const filterError = ref("");
|
||||
const targetError = ref("");
|
||||
const formError = ref("");
|
||||
@@ -62,8 +69,20 @@ const form = reactive({
|
||||
});
|
||||
|
||||
const root = ref<NodeForm>(blankNode("all"));
|
||||
provide(
|
||||
FILTER_SCOPE_EVENTS,
|
||||
computed(() => scopeEvents(root.value)),
|
||||
);
|
||||
const eventSuggestions = computed(() => eventOptions(locale.value));
|
||||
|
||||
const { fragments, load: loadFragments, save: saveFragments } = useFragmentsApi();
|
||||
const {
|
||||
fragments,
|
||||
readyFor: fragmentsReadyFor,
|
||||
load: loadFragments,
|
||||
save: saveFragments,
|
||||
} = useFragmentsApi();
|
||||
/** This group's fragments are loaded and no fragment write is running. */
|
||||
const fragmentsWritable = computed(() => !!props.groupId && fragmentsReadyFor(props.groupId));
|
||||
const fragmentName = ref("");
|
||||
const fragmentError = ref("");
|
||||
|
||||
@@ -72,6 +91,7 @@ const testEvent = ref("");
|
||||
const testResult = ref<{ matched: boolean; explanation: string } | null>(null);
|
||||
const testError = ref("");
|
||||
const testing = ref(false);
|
||||
const testEventInput = ref<{ hasInvalidDraft: () => boolean } | null>(null);
|
||||
|
||||
function applyTemplate(tmpl: RouteTemplate): void {
|
||||
form.id = tmpl.id;
|
||||
@@ -84,11 +104,33 @@ function addTarget(): void {
|
||||
form.targets.push(blankTarget());
|
||||
}
|
||||
|
||||
async function removeTarget(target: TargetForm): Promise<void> {
|
||||
const filled = [target.channelId, target.threadId, target.chatId, target.topicId].some((v) =>
|
||||
v.trim(),
|
||||
);
|
||||
if (filled) {
|
||||
const n = form.targets.indexOf(target) + 1;
|
||||
if (!(await confirm({ title: t("confirm.removeTarget", { n }) }))) return;
|
||||
}
|
||||
const index = form.targets.indexOf(target);
|
||||
if (index >= 0) form.targets.splice(index, 1);
|
||||
}
|
||||
|
||||
function validateEventName(value: string): string | null {
|
||||
return /^[a-z0-9_]+$/i.test(value) ? null : "valid.eventName";
|
||||
}
|
||||
|
||||
function validateNode(nf: NodeForm): string | null {
|
||||
if (nf.kind === "leaf") {
|
||||
if (nf.leaf.type === "field" && !nf.leaf.path.trim()) return t("routeEditor.errPath");
|
||||
if (nf.leaf.op !== "exists" && nf.leaf.values.every((v) => !v.trim()))
|
||||
return t("routeEditor.errValues");
|
||||
const { type, op, path, values } = nf.leaf;
|
||||
if (type === "field" && !path.trim()) return t("routeEditor.errPath");
|
||||
if (type === "keyword" || op !== "exists") {
|
||||
if (values.every((v) => !v.trim())) return t("routeEditor.errValues");
|
||||
for (const value of values) {
|
||||
const err = validateFilterValue(type, op, value);
|
||||
if (err) return t("routeEditor.errInvalidValue", { value: value.trim(), reason: t(err) });
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (nf.kind === "all" || nf.kind === "any") {
|
||||
@@ -103,6 +145,12 @@ function validateNode(nf: NodeForm): string | null {
|
||||
return t("routeEditor.errGroupEmpty");
|
||||
}
|
||||
|
||||
/** Why the filter tree cannot be used as-is (unconfirmed input or an invalid value). */
|
||||
function filterTreeError(): string | null {
|
||||
if (hasPendingDraft(root.value)) return t("routeEditor.errDraft");
|
||||
return validateNode(root.value);
|
||||
}
|
||||
|
||||
function collect(): Route | null {
|
||||
filterError.value = "";
|
||||
targetError.value = "";
|
||||
@@ -168,20 +216,26 @@ function collect(): Route | null {
|
||||
};
|
||||
}
|
||||
|
||||
function save(): void {
|
||||
function validated(): Route | null {
|
||||
if (hasPendingDraft(root.value)) {
|
||||
targetError.value = "";
|
||||
formError.value = "";
|
||||
filterError.value = t("routeEditor.errDraft");
|
||||
return null;
|
||||
}
|
||||
const route = collect();
|
||||
if (!route) return;
|
||||
if (!route) return null;
|
||||
if (!/^[a-z0-9][a-z0-9-]*$/.test(route.id)) {
|
||||
formError.value = t("routeEditor.errIdFormat");
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
if (!route.name) {
|
||||
formError.value = t("routeEditor.errName");
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
if (!route.targets.length) {
|
||||
targetError.value = t("routeEditor.errTargets");
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
form.targets.forEach((tg, i) => {
|
||||
if ((tg.platform === "telegram" || tg.platform === "feishu") && !tg.chatId.trim()) {
|
||||
@@ -190,18 +244,42 @@ function save(): void {
|
||||
targetError.value = t("routeEditor.errChannel", { n: i + 1 });
|
||||
}
|
||||
});
|
||||
if (targetError.value) return;
|
||||
emit("save", route);
|
||||
return targetError.value ? null : route;
|
||||
}
|
||||
|
||||
function save(): void {
|
||||
const route = validated();
|
||||
if (route) {
|
||||
emit("save", route);
|
||||
return;
|
||||
}
|
||||
// The footer button may be far from the failing section: bring the error into view.
|
||||
nextTick(() =>
|
||||
bodyEl.value
|
||||
?.querySelector("[data-save-error]")
|
||||
?.scrollIntoView({ block: "center", behavior: "smooth" }),
|
||||
);
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit("close");
|
||||
}
|
||||
|
||||
// A click on the backdrop must not discard what has been typed so far.
|
||||
const { isBackdropClose } = useBackdropGuard(() => props.open, ".editor-dialog");
|
||||
useDialogFocus(() => props.open, ".editor-dialog");
|
||||
|
||||
function onOpenChange(open: boolean): void {
|
||||
if (!open) close();
|
||||
if (!open && !isBackdropClose()) close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bumped whenever the editor opens or closes. The console keeps one editor
|
||||
* for every group, so an async result (a test run, a fragment write) only
|
||||
* lands in the session that started it.
|
||||
*/
|
||||
let session = 0;
|
||||
|
||||
async function runTest(): Promise<void> {
|
||||
testError.value = "";
|
||||
testResult.value = null;
|
||||
@@ -212,24 +290,35 @@ async function runTest(): Promise<void> {
|
||||
testError.value = t("routeEditor.testInvalidJson");
|
||||
return;
|
||||
}
|
||||
if (testEventInput.value?.hasInvalidDraft()) {
|
||||
testError.value = t("routeEditor.testEventInvalid");
|
||||
return;
|
||||
}
|
||||
const problem = filterTreeError();
|
||||
if (problem) {
|
||||
testError.value = problem;
|
||||
return;
|
||||
}
|
||||
const node = formToNode(root.value);
|
||||
if (!node) {
|
||||
testError.value = t("routeEditor.errAddFilter");
|
||||
return;
|
||||
}
|
||||
const mine = session;
|
||||
testing.value = true;
|
||||
try {
|
||||
testResult.value = await apiFetch<{ matched: boolean; explanation: string }>(
|
||||
const result = await apiFetch<{ matched: boolean; explanation: string }>(
|
||||
"/admin/api/test-match",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ node, event: testEvent.value.trim() || undefined, payload }),
|
||||
},
|
||||
);
|
||||
if (mine === session) testResult.value = result;
|
||||
} catch (err) {
|
||||
testError.value = err instanceof Error ? err.message : String(err);
|
||||
if (mine === session) testError.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
testing.value = false;
|
||||
if (mine === session) testing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,35 +348,59 @@ async function saveAsFragment(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (!props.groupId) return;
|
||||
// A save replaces the group's whole list: never from one not loaded yet.
|
||||
if (!fragmentsReadyFor(props.groupId)) {
|
||||
fragmentError.value = t("routeEditor.fragmentsNotReady");
|
||||
return;
|
||||
}
|
||||
const problem = filterTreeError();
|
||||
if (problem) {
|
||||
fragmentError.value = problem;
|
||||
return;
|
||||
}
|
||||
const node = formToNode(root.value);
|
||||
if (!node) {
|
||||
fragmentError.value = t("routeEditor.errAddFilter");
|
||||
return;
|
||||
}
|
||||
const groupId = props.groupId;
|
||||
const id = `frag-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const next: NamedFragment[] = [
|
||||
...fragments.value.filter((f) => f.id !== id),
|
||||
{ id, groupId: props.groupId, name, node },
|
||||
{ id, groupId, name, node },
|
||||
];
|
||||
const mine = session;
|
||||
try {
|
||||
await saveFragments(props.groupId, next);
|
||||
fragmentName.value = "";
|
||||
await saveFragments(groupId, next);
|
||||
if (mine === session) fragmentName.value = "";
|
||||
} catch (err) {
|
||||
fragmentError.value = err instanceof Error ? err.message : String(err);
|
||||
if (mine === session) fragmentError.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
|
||||
function deleteFragment(frag: NamedFragment): void {
|
||||
if (!props.groupId) return;
|
||||
async function deleteFragment(frag: NamedFragment): Promise<void> {
|
||||
const groupId = props.groupId;
|
||||
if (!groupId) return;
|
||||
const mine = session;
|
||||
if (!(await confirm({ title: t("confirm.deleteFragment", { name: frag.name }) }))) return;
|
||||
if (mine !== session) return;
|
||||
fragmentError.value = "";
|
||||
if (props.groupId !== groupId || !fragmentsReadyFor(groupId)) {
|
||||
fragmentError.value = t("routeEditor.fragmentsNotReady");
|
||||
return;
|
||||
}
|
||||
const next = fragments.value.filter((f) => f.id !== frag.id);
|
||||
saveFragments(props.groupId, next).catch((err) => {
|
||||
fragmentError.value = err instanceof Error ? err.message : String(err);
|
||||
});
|
||||
try {
|
||||
await saveFragments(groupId, next);
|
||||
} catch (err) {
|
||||
if (mine === session) fragmentError.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
session++;
|
||||
if (!open) return;
|
||||
const r = props.route;
|
||||
form.id = r?.id ?? "";
|
||||
@@ -321,6 +434,7 @@ watch(
|
||||
testEvent.value = "";
|
||||
testResult.value = null;
|
||||
testError.value = "";
|
||||
testing.value = false;
|
||||
fragmentName.value = "";
|
||||
fragmentError.value = "";
|
||||
if (props.groupId) loadFragments(props.groupId);
|
||||
@@ -332,7 +446,7 @@ watch(
|
||||
<RcDialog
|
||||
:open="open"
|
||||
:title="isEdit ? t('routeEditor.editTitle') : t('routeEditor.newTitle')"
|
||||
class="editor-dialog flex flex-col gap-0 max-h-[calc(100dvh-2rem)] overflow-hidden p-0 max-w-3xl"
|
||||
class="editor-dialog flex flex-col gap-0 max-h-[calc(100dvh-2rem)] overflow-hidden p-0 max-w-4xl"
|
||||
@update:open="onOpenChange"
|
||||
>
|
||||
<template #header>
|
||||
@@ -344,7 +458,7 @@ watch(
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<form class="editor-body" @submit.prevent="save">
|
||||
<form ref="bodyEl" class="editor-body" @submit.prevent="save">
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionBasic") }}</h3>
|
||||
<div v-if="!isEdit" class="templates">
|
||||
@@ -360,29 +474,33 @@ watch(
|
||||
{{ t(tmpl.nameKey) }}
|
||||
</RcButton>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.name") }}</label>
|
||||
<RcInput v-model="form.name" :placeholder="t('routeEditor.namePlaceholder')" required />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.id") }}</label>
|
||||
<RcInput v-model="form.id" placeholder="my-route" required />
|
||||
<div class="hint">{{ t("routeEditor.idHint") }}</div>
|
||||
<div class="row2">
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.name") }}</label>
|
||||
<RcInput v-model="form.name" :placeholder="t('routeEditor.namePlaceholder')" required />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.id") }}</label>
|
||||
<RcInput v-model="form.id" placeholder="my-route" required />
|
||||
<div class="hint">{{ t("routeEditor.idHint") }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionOptions") }}</h3>
|
||||
<div class="field inline">
|
||||
<RcSwitch v-model="form.enabled" :label="t('routeEditor.enabled')" />
|
||||
</div>
|
||||
<div class="field inline">
|
||||
<RcCheckbox v-model="form.fallback" :label="t('routeEditor.fallback')" />
|
||||
<span class="lbl-note">{{ t("routeEditor.fallbackHint") }}</span>
|
||||
</div>
|
||||
<div class="field inline">
|
||||
<RcCheckbox v-model="form.stop" :label="t('routeEditor.stop')" />
|
||||
<span class="lbl-note">{{ t("routeEditor.stopHint") }}</span>
|
||||
<div class="option-list">
|
||||
<div class="option-row">
|
||||
<RcSwitch v-model="form.enabled" :label="t('routeEditor.enabled')" />
|
||||
</div>
|
||||
<div class="option-row">
|
||||
<RcCheckbox v-model="form.fallback" :label="t('routeEditor.fallback')" />
|
||||
<p class="option-hint">{{ t("routeEditor.fallbackHint") }}</p>
|
||||
</div>
|
||||
<div class="option-row">
|
||||
<RcCheckbox v-model="form.stop" :label="t('routeEditor.stop')" />
|
||||
<p class="option-hint">{{ t("routeEditor.stopHint") }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.discordRoles") }}</label>
|
||||
@@ -397,19 +515,23 @@ watch(
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionFilters") }}</h3>
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.filters") }}</label>
|
||||
</div>
|
||||
<div class="field">
|
||||
<FilterNodeEditor :node="root" />
|
||||
</div>
|
||||
<div v-if="filterError" class="err">{{ filterError }}</div>
|
||||
<FilterNodeEditor :node="root" />
|
||||
<div v-if="filterError" class="err" data-save-error>{{ filterError }}</div>
|
||||
</section>
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.testMatch") }}</h3>
|
||||
<div class="field">
|
||||
<RcInput v-model="testEvent" :placeholder="t('routeEditor.testEvent')" />
|
||||
<div class="field test-event">
|
||||
<FilterCombobox
|
||||
ref="testEventInput"
|
||||
:model-value="testEvent"
|
||||
:options="eventSuggestions"
|
||||
creatable
|
||||
:validate="validateEventName"
|
||||
:placeholder="t('routeEditor.testEvent')"
|
||||
:label="t('routeEditor.testEvent')"
|
||||
@update:model-value="testEvent = typeof $event === 'string' ? $event : ''"
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<RcTextarea
|
||||
@@ -467,21 +589,33 @@ watch(
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="destructive"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:disabled="!fragmentsWritable"
|
||||
:title="t('routeEditor.fragmentsDelete')"
|
||||
:aria-label="t('routeEditor.fragmentsDelete')"
|
||||
@click="deleteFragment(frag)"
|
||||
>
|
||||
✕
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field fragment-save">
|
||||
<RcInput
|
||||
v-model="fragmentName"
|
||||
:placeholder="t('routeEditor.fragmentsNamePlaceholder')"
|
||||
/>
|
||||
<RcButton type="button" variant="ghost" @click="saveAsFragment">
|
||||
<div class="fragment-save">
|
||||
<div class="fragment-save-input">
|
||||
<RcInput
|
||||
v-model="fragmentName"
|
||||
:placeholder="t('routeEditor.fragmentsNamePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
class="shrink-0 whitespace-nowrap"
|
||||
:disabled="!fragmentsWritable"
|
||||
@click="saveAsFragment"
|
||||
>
|
||||
{{ t("routeEditor.fragmentsSave") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
@@ -490,65 +624,85 @@ watch(
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionTargets") }}</h3>
|
||||
<div v-for="(tg, i) in form.targets" :key="i" class="target-row">
|
||||
<RcSelect
|
||||
v-model="tg.platform"
|
||||
class="[grid-area:select]"
|
||||
:options="[
|
||||
{ label: 'Discord', value: 'discord' },
|
||||
{ label: 'Telegram', value: 'telegram' },
|
||||
{ label: t('routeEditor.platformFeishu'), value: 'feishu' },
|
||||
]"
|
||||
/>
|
||||
<div v-for="(tg, i) in form.targets" :key="i" class="target-card">
|
||||
<div class="target-card-head">
|
||||
<div class="target-platform">
|
||||
<RcSelect
|
||||
v-model="tg.platform"
|
||||
:options="[
|
||||
{ label: 'Discord', value: 'discord' },
|
||||
{ label: 'Telegram', value: 'telegram' },
|
||||
{ label: t('routeEditor.platformFeishu'), value: 'feishu' },
|
||||
]"
|
||||
/>
|
||||
</div>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:title="t('routeEditor.removeTarget')"
|
||||
:aria-label="t('routeEditor.removeTarget')"
|
||||
@click="removeTarget(tg)"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
</div>
|
||||
<template v-if="tg.platform === 'discord'">
|
||||
<RcInput
|
||||
v-model="tg.channelId"
|
||||
class="[grid-area:in1]"
|
||||
:placeholder="t('routeEditor.channelPlaceholder')"
|
||||
/>
|
||||
<RcInput
|
||||
v-model="tg.threadId"
|
||||
class="[grid-area:in2]"
|
||||
:placeholder="t('routeEditor.threadPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="tg.platform === 'telegram'">
|
||||
<RcInput
|
||||
v-model="tg.chatId"
|
||||
class="[grid-area:in1]"
|
||||
:placeholder="t('routeEditor.chatPlaceholder')"
|
||||
/>
|
||||
<RcInput
|
||||
v-model="tg.topicId"
|
||||
class="[grid-area:in2]"
|
||||
:placeholder="t('routeEditor.topicPlaceholder')"
|
||||
/>
|
||||
<div class="target-field">
|
||||
<label :for="`target-${i}-channel`">{{ t("routeEditor.channel") }}</label>
|
||||
<RcInput
|
||||
:id="`target-${i}-channel`"
|
||||
v-model="tg.channelId"
|
||||
:placeholder="t('routeEditor.channelPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="target-field">
|
||||
<label :for="`target-${i}-thread`"
|
||||
>{{ t("routeEditor.thread") }}
|
||||
<span class="lbl-note">{{ t("routeEditor.threadNote") }}</span></label
|
||||
>
|
||||
<RcInput
|
||||
:id="`target-${i}-thread`"
|
||||
v-model="tg.threadId"
|
||||
:placeholder="t('routeEditor.threadPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<RcInput
|
||||
v-model="tg.chatId"
|
||||
class="[grid-area:in1]"
|
||||
:placeholder="t('routeEditor.feishuChatPlaceholder')"
|
||||
/>
|
||||
<div class="target-field">
|
||||
<label :for="`target-${i}-chat`">{{ t("routeEditor.chat") }}</label>
|
||||
<RcInput
|
||||
:id="`target-${i}-chat`"
|
||||
v-model="tg.chatId"
|
||||
:placeholder="
|
||||
tg.platform === 'telegram'
|
||||
? t('routeEditor.chatPlaceholder')
|
||||
: t('routeEditor.feishuChatPlaceholder')
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="tg.platform === 'telegram'" class="target-field">
|
||||
<label :for="`target-${i}-topic`"
|
||||
>{{ t("routeEditor.topic") }}
|
||||
<span class="lbl-note">{{ t("routeEditor.topicNote") }}</span></label
|
||||
>
|
||||
<RcInput
|
||||
:id="`target-${i}-topic`"
|
||||
v-model="tg.topicId"
|
||||
:placeholder="t('routeEditor.topicPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
class="[grid-area:del] justify-self-end"
|
||||
:title="t('routeEditor.remove')"
|
||||
@click="form.targets.splice(i, 1)"
|
||||
>
|
||||
✕
|
||||
</RcButton>
|
||||
</div>
|
||||
<RcButton type="button" variant="ghost" class="add-filter" @click="addTarget">
|
||||
{{ t("routeEditor.addTarget") }}
|
||||
</RcButton>
|
||||
<div v-if="targetError" class="err">{{ targetError }}</div>
|
||||
<div v-if="targetError" class="err" data-save-error>{{ targetError }}</div>
|
||||
</section>
|
||||
|
||||
<div v-if="formError" class="err">{{ formError }}</div>
|
||||
<div v-if="formError" class="err" data-save-error>{{ formError }}</div>
|
||||
</form>
|
||||
|
||||
<template #footer>
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
<template>
|
||||
<div
|
||||
ref="listEl"
|
||||
class="route-list"
|
||||
:class="{
|
||||
'is-reordering': reordering,
|
||||
'is-dragging': dragIndex >= 0,
|
||||
'is-committing': committing,
|
||||
}"
|
||||
>
|
||||
<p v-if="reordering" :id="hintId" class="sr-only">{{ t("routes.reorderKeyboardHint") }}</p>
|
||||
<RouteCard
|
||||
v-for="(r, i) in routes"
|
||||
:key="r.id"
|
||||
:data-route-id="r.id"
|
||||
:route="r"
|
||||
:readonly="readonly"
|
||||
:reordering="reordering"
|
||||
:locked="locked"
|
||||
:position="i + 1"
|
||||
:hint-id="hintId"
|
||||
:class="{ 'is-dragged': i === dragIndex, 'is-settling': i === dragIndex && settling }"
|
||||
:style="itemStyle(i)"
|
||||
@toggle="emit('toggle', $event)"
|
||||
@edit="emit('edit', $event)"
|
||||
@delete="emit('delete', $event)"
|
||||
@drag-start="onDragStart(i, $event)"
|
||||
@nudge="nudge(i, $event)"
|
||||
/>
|
||||
<p class="sr-only" aria-live="assertive">{{ announcement }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { Route } from "~/types";
|
||||
|
||||
/**
|
||||
* The routes of one group. In reorder mode each card gets a drag handle:
|
||||
* pointer drags (mouse and touch) move a card while its neighbours slide out
|
||||
* of the way, and the new order is emitted on drop; Arrow Up / Down on a
|
||||
* focused handle moves it by one. `locked` freezes the order (e.g. while it
|
||||
* is being saved); `busy` reports a drag that has not been committed yet.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
routes: Route[];
|
||||
reordering?: boolean;
|
||||
readonly?: boolean;
|
||||
locked?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "update:routes", routes: Route[]): void;
|
||||
(e: "update:busy", busy: boolean): void;
|
||||
(e: "toggle", route: Route): void;
|
||||
(e: "edit", route: Route): void;
|
||||
(e: "delete", route: Route): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const hintId = `route-reorder-hint-${useId()}`;
|
||||
const listEl = ref<HTMLElement | null>(null);
|
||||
const dragIndex = ref(-1);
|
||||
const overIndex = ref(-1);
|
||||
const dragDelta = ref(0);
|
||||
const settling = ref(false);
|
||||
const committing = ref(false);
|
||||
const announcement = ref("");
|
||||
|
||||
interface DragSession {
|
||||
pointerId: number;
|
||||
startY: number;
|
||||
startScroll: number;
|
||||
lastY: number;
|
||||
/** Document-relative tops and heights of every card when the drag began. */
|
||||
tops: number[];
|
||||
heights: number[];
|
||||
gap: number;
|
||||
}
|
||||
|
||||
let session: DragSession | null = null;
|
||||
let scrollSpeed = 0;
|
||||
let scrollFrame = 0;
|
||||
let settleTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
/** Distance the cards between the drag origin and the drop slot move by. */
|
||||
function shiftPx(): number {
|
||||
return session && dragIndex.value >= 0 ? session.heights[dragIndex.value]! + session.gap : 0;
|
||||
}
|
||||
|
||||
function itemStyle(i: number): Record<string, string> | undefined {
|
||||
const from = dragIndex.value;
|
||||
if (from < 0) return undefined;
|
||||
if (i === from) return { transform: `translateY(${dragDelta.value}px)` };
|
||||
const to = overIndex.value;
|
||||
if (to > from && i > from && i <= to) return { transform: `translateY(${-shiftPx()}px)` };
|
||||
if (to < from && i >= to && i < from) return { transform: `translateY(${shiftPx()}px)` };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function measure(): Pick<DragSession, "tops" | "heights" | "gap"> | null {
|
||||
const list = listEl.value;
|
||||
if (!list) return null;
|
||||
const cards = [...list.querySelectorAll<HTMLElement>("[data-route-id]")];
|
||||
if (cards.length !== props.routes.length) return null;
|
||||
const rects = cards.map((el) => el.getBoundingClientRect());
|
||||
return {
|
||||
tops: rects.map((r) => r.top + window.scrollY),
|
||||
heights: rects.map((r) => r.height),
|
||||
gap: parseFloat(getComputedStyle(list).rowGap) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
function onDragStart(index: number, event: PointerEvent): void {
|
||||
if (!props.reordering || props.locked || session || settling.value) return;
|
||||
if (event.pointerType === "mouse" && event.button !== 0) return;
|
||||
const geometry = measure();
|
||||
if (!geometry) return;
|
||||
event.preventDefault();
|
||||
session = {
|
||||
pointerId: event.pointerId,
|
||||
startY: event.clientY,
|
||||
startScroll: window.scrollY,
|
||||
lastY: event.clientY,
|
||||
...geometry,
|
||||
};
|
||||
dragIndex.value = index;
|
||||
overIndex.value = index;
|
||||
dragDelta.value = 0;
|
||||
window.addEventListener("pointermove", onPointerMove);
|
||||
window.addEventListener("pointerup", onPointerUp);
|
||||
window.addEventListener("pointercancel", onPointerUp);
|
||||
}
|
||||
|
||||
function update(): void {
|
||||
const s = session;
|
||||
const from = dragIndex.value;
|
||||
if (!s || from < 0) return;
|
||||
const delta = s.lastY - s.startY + (window.scrollY - s.startScroll);
|
||||
const center = s.tops[from]! + delta + s.heights[from]! / 2;
|
||||
// Slot = how many other cards' original centers lie above the dragged center.
|
||||
let slot = 0;
|
||||
for (let i = 0; i < s.tops.length; i++) {
|
||||
if (i !== from && s.tops[i]! + s.heights[i]! / 2 < center) slot++;
|
||||
}
|
||||
dragDelta.value = delta;
|
||||
overIndex.value = slot;
|
||||
}
|
||||
|
||||
function onPointerMove(event: PointerEvent): void {
|
||||
if (!session || event.pointerId !== session.pointerId) return;
|
||||
session.lastY = event.clientY;
|
||||
update();
|
||||
autoScroll(event.clientY);
|
||||
}
|
||||
|
||||
/** Scroll the page while the pointer rests near the viewport's top or bottom edge. */
|
||||
function autoScroll(clientY: number): void {
|
||||
const top = 140;
|
||||
const bottom = window.innerHeight - 80;
|
||||
const raw = clientY < top ? (clientY - top) / 6 : clientY > bottom ? (clientY - bottom) / 6 : 0;
|
||||
scrollSpeed = Math.max(-18, Math.min(18, Math.round(raw)));
|
||||
if (!scrollSpeed || scrollFrame) return;
|
||||
const step = (): void => {
|
||||
if (!session || !scrollSpeed) {
|
||||
scrollFrame = 0;
|
||||
return;
|
||||
}
|
||||
window.scrollBy(0, scrollSpeed);
|
||||
update();
|
||||
scrollFrame = requestAnimationFrame(step);
|
||||
};
|
||||
scrollFrame = requestAnimationFrame(step);
|
||||
}
|
||||
|
||||
function stopListening(): void {
|
||||
window.removeEventListener("pointermove", onPointerMove);
|
||||
window.removeEventListener("pointerup", onPointerUp);
|
||||
window.removeEventListener("pointercancel", onPointerUp);
|
||||
cancelAnimationFrame(scrollFrame);
|
||||
scrollFrame = 0;
|
||||
scrollSpeed = 0;
|
||||
}
|
||||
|
||||
function onPointerUp(event: PointerEvent): void {
|
||||
const s = session;
|
||||
if (!s || event.pointerId !== s.pointerId) return;
|
||||
stopListening();
|
||||
const from = dragIndex.value;
|
||||
const to = overIndex.value;
|
||||
// Glide the card into its slot, then commit the order in one frame.
|
||||
let slotTop = s.tops[0]!;
|
||||
for (let i = 0, placed = 0; placed < to; i++) {
|
||||
if (i === from) continue;
|
||||
slotTop += s.heights[i]! + s.gap;
|
||||
placed++;
|
||||
}
|
||||
settling.value = true;
|
||||
dragDelta.value = slotTop - s.tops[from]!;
|
||||
settleTimer = setTimeout(() => commit(from, to), 160);
|
||||
}
|
||||
|
||||
function commit(from: number, to: number): void {
|
||||
committing.value = true;
|
||||
if (to !== from) {
|
||||
const next = [...props.routes];
|
||||
const [moved] = next.splice(from, 1);
|
||||
next.splice(to, 0, moved!);
|
||||
emit("update:routes", next);
|
||||
announce(moved!, to);
|
||||
}
|
||||
resetDrag();
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => (committing.value = false)));
|
||||
}
|
||||
|
||||
function resetDrag(): void {
|
||||
clearTimeout(settleTimer);
|
||||
session = null;
|
||||
dragIndex.value = -1;
|
||||
overIndex.value = -1;
|
||||
dragDelta.value = 0;
|
||||
settling.value = false;
|
||||
}
|
||||
|
||||
function cancelDrag(): void {
|
||||
stopListening();
|
||||
resetDrag();
|
||||
}
|
||||
|
||||
function nudge(index: number, dir: -1 | 1): void {
|
||||
const to = index + dir;
|
||||
if (props.locked || session || to < 0 || to >= props.routes.length) return;
|
||||
const next = [...props.routes];
|
||||
const [moved] = next.splice(index, 1);
|
||||
next.splice(to, 0, moved!);
|
||||
emit("update:routes", next);
|
||||
announce(moved!, to);
|
||||
nextTick(() => {
|
||||
listEl.value
|
||||
?.querySelector<HTMLElement>(`[data-route-handle="${CSS.escape(moved!.id)}"]`)
|
||||
?.focus();
|
||||
});
|
||||
}
|
||||
|
||||
function announce(route: Route, index: number): void {
|
||||
announcement.value = t("routes.moved", {
|
||||
name: route.name || route.id,
|
||||
n: index + 1,
|
||||
});
|
||||
}
|
||||
|
||||
watch(
|
||||
() => dragIndex.value >= 0,
|
||||
(busy) => emit("update:busy", busy),
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.reordering,
|
||||
(on) => {
|
||||
if (!on) cancelDrag();
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(cancelDrag);
|
||||
</script>
|
||||
@@ -1,15 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{ modelValue: string[]; placeholder?: string }>();
|
||||
const emit = defineEmits<{ (e: "update:modelValue", value: string[]): void }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<RcTagInput
|
||||
:model-value="props.modelValue"
|
||||
:placeholder="props.placeholder"
|
||||
separator=","
|
||||
unique
|
||||
size="sm"
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
/>
|
||||
</template>
|
||||
@@ -41,6 +41,7 @@
|
||||
v-if="info.hasSecret"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="sm"
|
||||
:disabled="busy"
|
||||
@click="onDisable"
|
||||
@@ -67,6 +68,7 @@ import { ref, watch } from "vue";
|
||||
import { useWebhookApi, type GroupWebhookInfo } from "~/composables/useWebhook";
|
||||
|
||||
const { t } = useI18n();
|
||||
const { confirm } = useConfirm();
|
||||
|
||||
const props = defineProps<{ groupId: string; canEdit: boolean }>();
|
||||
|
||||
@@ -123,6 +125,12 @@ async function onRegenerate(): Promise<void> {
|
||||
}
|
||||
|
||||
async function onDisable(): Promise<void> {
|
||||
const confirmed = await confirm({
|
||||
title: t("confirm.disableWebhook"),
|
||||
description: t("confirm.disableWebhookDetail"),
|
||||
confirmText: t("webhook.disable"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
|
||||
@@ -15,6 +15,10 @@ export function useAuthState() {
|
||||
export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(path, {
|
||||
credentials: "same-origin",
|
||||
// Live data, never from the browser cache. This also keeps requests out of
|
||||
// its per-URL cache lock: otherwise one request that never answers makes
|
||||
// every later request for the same URL wait up to 20 s behind it.
|
||||
cache: "no-store",
|
||||
...init,
|
||||
// JSON in/out: h3's readBody only parses JSON bodies when the request
|
||||
// declares application/json, and the browser defaults string bodies to
|
||||
|
||||
@@ -5,8 +5,12 @@ export function useAuditApi() {
|
||||
const entries = ref<AuditEntry[]>([]);
|
||||
const loading = ref(false);
|
||||
const error = ref("");
|
||||
// Bumped by every load, so only the latest request may land (an older one,
|
||||
// e.g. from the page the user just left, must not overwrite newer data).
|
||||
let request = 0;
|
||||
|
||||
async function load(limit = 50, groupId?: string): Promise<void> {
|
||||
const mine = ++request;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
needLogin.value = false;
|
||||
@@ -14,11 +18,12 @@ export function useAuditApi() {
|
||||
let url = `/admin/api/audit?limit=${limit}`;
|
||||
if (groupId) url += `&groupId=${encodeURIComponent(groupId)}`;
|
||||
const data = await apiFetch<{ audit?: AuditEntry[] }>(url);
|
||||
entries.value = data.audit ?? [];
|
||||
if (mine === request) entries.value = data.audit ?? [];
|
||||
} catch (err) {
|
||||
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
|
||||
if (mine === request && !needLogin.value)
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (mine === request) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Keeps an editor dialog open when the user clicks outside it, so a stray click
|
||||
* on the backdrop never throws away unsaved input. RcDialog exposes no hook for
|
||||
* reka's `interactOutside`, so this watches pointer-downs while the dialog is
|
||||
* open: a press outside the dialog (and outside any popover or dialog stacked
|
||||
* above it) marks the close request it triggers as one to ignore. Escape, the
|
||||
* close button and Cancel keep closing the dialog.
|
||||
*/
|
||||
export function useBackdropGuard(isOpen: () => boolean, dialogSelector: string) {
|
||||
let pressedOutside = false;
|
||||
|
||||
function onPointerDown(event: PointerEvent): void {
|
||||
const target = event.target as Element | null;
|
||||
pressedOutside = !target?.closest?.(
|
||||
`${dialogSelector}, [data-dismissable-layer], [data-reka-popper-content-wrapper]`,
|
||||
);
|
||||
}
|
||||
|
||||
function onKeyDown(): void {
|
||||
pressedOutside = false;
|
||||
}
|
||||
|
||||
function listen(on: boolean): void {
|
||||
if (typeof document === "undefined") return;
|
||||
if (on) {
|
||||
document.addEventListener("pointerdown", onPointerDown, true);
|
||||
document.addEventListener("keydown", onKeyDown, true);
|
||||
return;
|
||||
}
|
||||
document.removeEventListener("pointerdown", onPointerDown, true);
|
||||
document.removeEventListener("keydown", onKeyDown, true);
|
||||
pressedOutside = false;
|
||||
}
|
||||
|
||||
watch(isOpen, listen, { immediate: true });
|
||||
onBeforeUnmount(() => listen(false));
|
||||
|
||||
/** Whether the pending close request came from a press outside the dialog. */
|
||||
function isBackdropClose(): boolean {
|
||||
const outside = pressedOutside;
|
||||
pressedOutside = false;
|
||||
return outside;
|
||||
}
|
||||
|
||||
return { isBackdropClose };
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
export interface ConfirmOptions {
|
||||
/** The question, shown as the dialog title. */
|
||||
title: string;
|
||||
/** Optional consequence text under the title. */
|
||||
description?: string;
|
||||
/** Label of the destructive button (defaults to "Delete"). */
|
||||
confirmText?: string;
|
||||
/** What the action does, shown as the dialog icon (defaults to "delete"). */
|
||||
kind?: "delete" | "leave" | "signOut";
|
||||
}
|
||||
|
||||
interface ConfirmRequest extends ConfirmOptions {
|
||||
resolve: (confirmed: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Promise-based destructive-action confirmation shared by the whole console.
|
||||
* <ConfirmDialog /> (mounted once by ConsolePage) renders the pending request;
|
||||
* `confirm()` resolves true on confirm and false on cancel / Escape.
|
||||
*/
|
||||
export function useConfirm() {
|
||||
const pending = useState<ConfirmRequest | null>("wh-confirm", () => null);
|
||||
const hosts = useState<number>("wh-confirm-hosts", () => 0);
|
||||
// The component that asks; a request it makes after unmounting is refused,
|
||||
// and one still on screen when it unmounts is cancelled.
|
||||
const owner = getCurrentInstance();
|
||||
let asked: ConfirmRequest | null = null;
|
||||
if (owner) {
|
||||
onBeforeUnmount(() => {
|
||||
// Only our own request: another component's newer one stays open.
|
||||
if (asked && toRaw(pending.value) === asked) settle(false);
|
||||
asked = null;
|
||||
});
|
||||
}
|
||||
|
||||
function confirm(options: ConfirmOptions): Promise<boolean> {
|
||||
// Nobody can answer, or the asker is gone (the console was left while the
|
||||
// request was being prepared): never resume a stale destructive action.
|
||||
if (!hosts.value || owner?.isUnmounted) return Promise.resolve(false);
|
||||
// A newer request supersedes (and cancels) one still on screen.
|
||||
pending.value?.resolve(false);
|
||||
return new Promise((resolve) => {
|
||||
asked = { ...options, resolve };
|
||||
pending.value = asked;
|
||||
});
|
||||
}
|
||||
|
||||
function settle(confirmed: boolean): void {
|
||||
const request = pending.value;
|
||||
if (!request) return;
|
||||
pending.value = null;
|
||||
request.resolve(confirmed);
|
||||
}
|
||||
|
||||
/** Register the dialog that renders requests; the returned detach cancels any pending one. */
|
||||
function attachHost(): () => void {
|
||||
hosts.value++;
|
||||
return () => {
|
||||
hosts.value--;
|
||||
settle(false);
|
||||
};
|
||||
}
|
||||
|
||||
return { pending, confirm, settle, attachHost };
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Opens an editor dialog without jumping into its first field. reka-ui's
|
||||
* FocusScope focuses and *selects* the first input on open, which highlights
|
||||
* the name as if about to overwrite it and pops up the keyboard on touch
|
||||
* screens. Its mount auto-focus is announced with a non-bubbling, cancelable
|
||||
* event — RcDialog exposes no `openAutoFocus` hook — so it is caught here in
|
||||
* the capture phase and focus goes to the dialog itself instead: Escape and
|
||||
* Tab keep working, the fields stay untouched until the user picks one.
|
||||
*/
|
||||
export function useDialogFocus(isOpen: () => boolean, dialogSelector: string) {
|
||||
function onMountAutoFocus(event: Event): void {
|
||||
const dialog = event.target;
|
||||
if (!(dialog instanceof HTMLElement) || !dialog.matches(dialogSelector)) return;
|
||||
event.preventDefault();
|
||||
dialog.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
function listen(on: boolean): void {
|
||||
if (typeof document === "undefined") return;
|
||||
if (on) document.addEventListener("focusScope.autoFocusOnMount", onMountAutoFocus, true);
|
||||
else document.removeEventListener("focusScope.autoFocusOnMount", onMountAutoFocus, true);
|
||||
}
|
||||
|
||||
watch(isOpen, listen, { immediate: true });
|
||||
onBeforeUnmount(() => listen(false));
|
||||
}
|
||||
@@ -1,11 +1,22 @@
|
||||
import { toRaw } from "vue";
|
||||
import type { ComputedRef, InjectionKey } from "vue";
|
||||
import type { Filter, FilterNode, FilterOp, FilterType } from "~/types";
|
||||
|
||||
/** Exact event names the edited route filters on (see `scopeEvents`). */
|
||||
export const FILTER_SCOPE_EVENTS: InjectionKey<ComputedRef<string[]>> = Symbol("filter-scope");
|
||||
|
||||
export interface LeafForm {
|
||||
type: FilterType;
|
||||
path: string;
|
||||
op: FilterOp;
|
||||
values: string[];
|
||||
exclude: boolean;
|
||||
/**
|
||||
* Text typed into the values input but not added yet (editor-only, never
|
||||
* saved). It lives on the leaf so it follows the condition when the input
|
||||
* remounts (a NOT unwrapped, the root wrapped by an inserted fragment).
|
||||
*/
|
||||
draft: string;
|
||||
}
|
||||
|
||||
export type NodeKind = "leaf" | "all" | "any" | "not";
|
||||
@@ -17,8 +28,22 @@ export interface NodeForm {
|
||||
child: NodeForm | null;
|
||||
}
|
||||
|
||||
const nodeKeys = new WeakMap<object, number>();
|
||||
let lastNodeKey = 0;
|
||||
|
||||
/** Stable render key of a node form (list indexes shift when siblings are removed). */
|
||||
export function nodeKey(nf: NodeForm): number {
|
||||
const raw = toRaw(nf);
|
||||
let key = nodeKeys.get(raw);
|
||||
if (key === undefined) {
|
||||
key = ++lastNodeKey;
|
||||
nodeKeys.set(raw, key);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
export function blankLeafForm(): LeafForm {
|
||||
return { type: "event", path: "", op: "eq", values: [], exclude: false };
|
||||
return { type: "event", path: "", op: "eq", values: [], exclude: false, draft: "" };
|
||||
}
|
||||
|
||||
export function blankNode(kind: NodeKind): NodeForm {
|
||||
@@ -42,6 +67,7 @@ function leafToForm(f: Filter): LeafForm {
|
||||
op: f.op ?? "eq",
|
||||
values: matchToValues(f.match),
|
||||
exclude: !!f.exclude,
|
||||
draft: "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -60,12 +86,14 @@ export function nodeToForm(node: FilterNode): NodeForm {
|
||||
|
||||
export function formToLeaf(lf: LeafForm): Filter | null {
|
||||
const values = lf.values.map((v) => v.trim()).filter((v) => v.length > 0);
|
||||
if (lf.op !== "exists" && values.length === 0) return null;
|
||||
// Keyword filters ignore the operator on the server, so never store one.
|
||||
const op: FilterOp = lf.type === "keyword" ? "eq" : lf.op;
|
||||
if (op !== "exists" && values.length === 0) return null;
|
||||
if (lf.type === "field" && lf.path.trim().length === 0) return null;
|
||||
const filter: Filter = { type: lf.type };
|
||||
if (lf.type === "field") filter.path = lf.path.trim();
|
||||
if (lf.op !== "eq") filter.op = lf.op;
|
||||
if (lf.op !== "exists") filter.match = values.length === 1 ? values[0] : values;
|
||||
if (op !== "eq") filter.op = op;
|
||||
if (op !== "exists") filter.match = values.length === 1 ? values[0] : values;
|
||||
if (lf.exclude) filter.exclude = true;
|
||||
return filter;
|
||||
}
|
||||
@@ -116,6 +144,53 @@ export function nodeFormToRouteFilters(nf: NodeForm): { filters: Filter[]; ast?:
|
||||
return { filters: [], ast: ast ?? undefined };
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact event names a route positively filters on (negated conditions,
|
||||
* `not` groups, globs and regexes are skipped) — the context the filter
|
||||
* editor uses to rank action and field suggestions.
|
||||
*/
|
||||
export function scopeEvents(nf: NodeForm): string[] {
|
||||
const out = new Set<string>();
|
||||
const walk = (n: NodeForm): void => {
|
||||
if (n.kind === "leaf") {
|
||||
const { type, op, exclude, values } = n.leaf;
|
||||
if (type !== "event" || exclude || (op !== "eq" && op !== "in")) return;
|
||||
for (const v of values) {
|
||||
const value = v.trim();
|
||||
if (/^[a-z0-9_]+$/i.test(value)) out.add(value.toLowerCase());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (n.kind === "all" || n.kind === "any") n.children.forEach(walk);
|
||||
};
|
||||
walk(nf);
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a node holds nothing worth confirming before it is removed: an
|
||||
* untouched condition (default operator, no path, no values, not negated) or
|
||||
* groups made only of those. A changed operator counts as content, since
|
||||
* e.g. `exists` is a complete condition without values.
|
||||
*/
|
||||
export function isBlankNode(nf: NodeForm): boolean {
|
||||
if (nf.kind === "leaf") {
|
||||
const { draft, exclude, op, path, values } = nf.leaf;
|
||||
return (
|
||||
!exclude && op === "eq" && !path.trim() && values.every((v) => !v.trim()) && !draft.trim()
|
||||
);
|
||||
}
|
||||
if (nf.kind === "all" || nf.kind === "any") return nf.children.every(isBlankNode);
|
||||
return !nf.child || isBlankNode(nf.child);
|
||||
}
|
||||
|
||||
/** Whether a condition of the tree still holds typed text that was not added. */
|
||||
export function hasPendingDraft(nf: NodeForm): boolean {
|
||||
if (nf.kind === "leaf") return !!nf.leaf.draft.trim();
|
||||
if (nf.kind === "all" || nf.kind === "any") return nf.children.some(hasPendingDraft);
|
||||
return !!nf.child && hasPendingDraft(nf.child);
|
||||
}
|
||||
|
||||
export function collectEvents(node: FilterNode): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (n: FilterNode): void => {
|
||||
|
||||
@@ -4,9 +4,37 @@ export function useFragmentsApi() {
|
||||
const { needLogin } = useAuthState();
|
||||
const fragments = ref<NamedFragment[]>([]);
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const error = ref("");
|
||||
/** Group whose fragments are shown; responses for any other group are dropped. */
|
||||
const shownGroupId = ref<string | null>(null);
|
||||
/** Group whose fragments were last loaded (or saved) successfully. */
|
||||
const loadedGroupId = ref<string | null>(null);
|
||||
// Bumped by every load/save, so only the latest request may land.
|
||||
let request = 0;
|
||||
|
||||
/**
|
||||
* Whether a write may start for `groupId`: the shown list is that group's
|
||||
* real fragments and nothing is loading or saving. Saving replaces a group's
|
||||
* whole fragment list, so each write must build on the previous one.
|
||||
*/
|
||||
function readyFor(groupId: string): boolean {
|
||||
return (
|
||||
shownGroupId.value === groupId &&
|
||||
loadedGroupId.value === groupId &&
|
||||
!error.value &&
|
||||
!loading.value &&
|
||||
!saving.value
|
||||
);
|
||||
}
|
||||
|
||||
async function load(groupId: string): Promise<void> {
|
||||
const mine = ++request;
|
||||
if (shownGroupId.value !== groupId) {
|
||||
fragments.value = [];
|
||||
loadedGroupId.value = null;
|
||||
}
|
||||
shownGroupId.value = groupId;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
needLogin.value = false;
|
||||
@@ -14,21 +42,34 @@ export function useFragmentsApi() {
|
||||
const data = await apiFetch<{ fragments?: NamedFragment[] }>(
|
||||
`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`,
|
||||
);
|
||||
if (mine !== request) return;
|
||||
fragments.value = data.fragments ?? [];
|
||||
loadedGroupId.value = groupId;
|
||||
} catch (err) {
|
||||
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
|
||||
if (mine === request && !needLogin.value)
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (mine === request) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save(groupId: string, next: NamedFragment[]): Promise<void> {
|
||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ fragments: next }),
|
||||
});
|
||||
saving.value = true;
|
||||
try {
|
||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ fragments: next }),
|
||||
});
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
if (shownGroupId.value !== groupId) return;
|
||||
request++;
|
||||
loading.value = false;
|
||||
error.value = "";
|
||||
fragments.value = next;
|
||||
loadedGroupId.value = groupId;
|
||||
}
|
||||
|
||||
return { fragments, loading, needLogin, error, load, save };
|
||||
return { fragments, loading, needLogin, error, readyFor, load, save };
|
||||
}
|
||||
@@ -5,30 +5,70 @@ export function useGroupRoutesApi() {
|
||||
const routes = ref<Route[]>([]);
|
||||
const loading = ref(false);
|
||||
const error = ref("");
|
||||
/** Group whose routes are shown; responses for any other group are dropped. */
|
||||
const groupId = ref<string | null>(null);
|
||||
/** Group whose routes were last loaded (or saved) successfully. */
|
||||
const loadedId = ref<string | null>(null);
|
||||
// Bumped by every load/clear, so only the latest request may land.
|
||||
let request = 0;
|
||||
|
||||
async function load(groupId: string): Promise<void> {
|
||||
/**
|
||||
* The shown routes are the group's real routes. Saving replaces a group's
|
||||
* whole route list, so a write is only safe from here — never from the
|
||||
* empty list of a load still running or one that failed.
|
||||
*/
|
||||
const ready = computed(() => !!groupId.value && loadedId.value === groupId.value && !error.value);
|
||||
|
||||
async function load(id: string): Promise<void> {
|
||||
const mine = ++request;
|
||||
if (groupId.value !== id) {
|
||||
routes.value = [];
|
||||
loadedId.value = null;
|
||||
}
|
||||
groupId.value = id;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
needLogin.value = false;
|
||||
try {
|
||||
const data = await apiFetch<{ routes?: Route[] }>(
|
||||
`/admin/api/groups/${encodeURIComponent(groupId)}/routes`,
|
||||
`/admin/api/groups/${encodeURIComponent(id)}/routes`,
|
||||
);
|
||||
if (mine !== request) return;
|
||||
routes.value = data.routes ?? [];
|
||||
loadedId.value = id;
|
||||
} catch (err) {
|
||||
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
|
||||
if (mine === request && !needLogin.value)
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (mine === request) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save(groupId: string, next: Route[]): Promise<void> {
|
||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(groupId)}/routes`, {
|
||||
/** Forget the shown group (its page was left); late responses are ignored. */
|
||||
function clear(): void {
|
||||
request++;
|
||||
groupId.value = null;
|
||||
loadedId.value = null;
|
||||
routes.value = [];
|
||||
loading.value = false;
|
||||
error.value = "";
|
||||
}
|
||||
|
||||
async function save(id: string, next: Route[]): Promise<void> {
|
||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(id)}/routes`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ routes: next }),
|
||||
});
|
||||
// The page may have moved on to another group while the request ran.
|
||||
if (groupId.value !== id) return;
|
||||
// What was just written is the newest state: a load of this group that
|
||||
// started earlier may return the old routes, so it must not land.
|
||||
request++;
|
||||
loading.value = false;
|
||||
error.value = "";
|
||||
routes.value = next;
|
||||
loadedId.value = id;
|
||||
}
|
||||
|
||||
return { routes, loading, needLogin, error, load, save };
|
||||
return { routes, loading, needLogin, error, groupId, ready, load, clear, save };
|
||||
}
|
||||
@@ -8,6 +8,11 @@ export function useGroupsApi() {
|
||||
const roles = ref<Record<string, GroupRole>>({});
|
||||
const loading = ref(false);
|
||||
const error = ref("");
|
||||
/** A load has succeeded: an id missing from `groups` really is unknown. */
|
||||
const loaded = ref(false);
|
||||
// Bumped by every load and save, so only the latest request may land: a
|
||||
// load that started before a save must not bring back the old groups.
|
||||
let request = 0;
|
||||
|
||||
function roleOf(groupId: string): GroupRole | undefined {
|
||||
return isSuper.value ? "owner" : roles.value[groupId];
|
||||
@@ -24,6 +29,7 @@ export function useGroupsApi() {
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
const mine = ++request;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
needLogin.value = false;
|
||||
@@ -33,13 +39,16 @@ export function useGroupsApi() {
|
||||
isSuper?: boolean;
|
||||
roles?: Record<string, GroupRole>;
|
||||
}>("/admin/api/groups");
|
||||
if (mine !== request) return;
|
||||
groups.value = data.groups ?? [];
|
||||
isSuper.value = data.isSuper ?? false;
|
||||
roles.value = data.roles ?? {};
|
||||
loaded.value = true;
|
||||
} catch (err) {
|
||||
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
|
||||
if (mine === request && !needLogin.value)
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (mine === request) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +57,8 @@ export function useGroupsApi() {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ groups: next }),
|
||||
});
|
||||
request++;
|
||||
loading.value = false;
|
||||
groups.value = next;
|
||||
}
|
||||
|
||||
@@ -67,6 +78,7 @@ export function useGroupsApi() {
|
||||
canEditGroup,
|
||||
canEditRoutes,
|
||||
loading,
|
||||
loaded,
|
||||
needLogin,
|
||||
error,
|
||||
load,
|
||||
|
||||
+124
-14
@@ -6,8 +6,8 @@ type Dict = Record<string, string>;
|
||||
|
||||
const en: Dict = {
|
||||
"app.tagline": "CONFIG CONSOLE",
|
||||
"app.newRoute": "+ New Route",
|
||||
"app.newGroup": "+ New Group",
|
||||
"app.newRoute": "New Route",
|
||||
"app.newGroup": "New Group",
|
||||
"app.signOut": "Sign out",
|
||||
"app.langToggle": "中文",
|
||||
"login.title": "Config Console",
|
||||
@@ -84,7 +84,6 @@ const en: Dict = {
|
||||
"role.owner": "Owner",
|
||||
"role.admin": "Admin",
|
||||
"role.viewer": "Viewer",
|
||||
"role.badge": "You: {role}",
|
||||
"roles.owner": "Owner",
|
||||
"roles.admin": "Admin",
|
||||
"roles.viewer": "Viewer",
|
||||
@@ -136,12 +135,24 @@ const en: Dict = {
|
||||
"groups.admins": "ADMINS",
|
||||
"groups.owners": "OWNERS",
|
||||
"groups.members": "MEMBERS",
|
||||
"groups.myRole": "MY ROLE",
|
||||
"groups.any": "any",
|
||||
"groups.open": "Open →",
|
||||
"group.back": "Groups",
|
||||
"groups.open": "Open",
|
||||
"groups.delete": "Delete group",
|
||||
"group.notFound": "This group does not exist, or you have no access to it",
|
||||
"group.allGroups": "All groups",
|
||||
"group.routeCount": "{count} routes",
|
||||
"group.routesIn": "Routes in {name}",
|
||||
"routes.emptyGroup": "No routes in this group yet.",
|
||||
"routes.createFirst": "Create your first route",
|
||||
"routes.reorder": "Reorder",
|
||||
"routes.reorderHint": "Drag routes by their handle to change the evaluation order, then save.",
|
||||
"routes.reorderKeyboardHint": "Press Arrow Up or Arrow Down to move this route.",
|
||||
"routes.reorderSave": "Save order",
|
||||
"routes.reorderCancel": "Cancel",
|
||||
"routes.dragHandle": "Reorder {name}",
|
||||
"routes.moved": "{name} moved to position {n}",
|
||||
"routes.delete": "Delete route",
|
||||
"route.untitled": "(untitled)",
|
||||
"route.noFilters": "no filters",
|
||||
"route.channel": "CHANNEL",
|
||||
@@ -211,9 +222,11 @@ const en: Dict = {
|
||||
"routeEditor.idHint": "Unique, use a-z / 0-9 / dashes",
|
||||
"routeEditor.enabled": "Route enabled",
|
||||
"routeEditor.fallback": "Fallback route",
|
||||
"routeEditor.fallbackHint": "Only fires when no other route matched; filters still apply",
|
||||
"routeEditor.fallbackHint":
|
||||
"Only fires when no regular (non-fallback) route in this group matched; its filters still apply",
|
||||
"routeEditor.stop": "Stop on match",
|
||||
"routeEditor.stopHint": "When matched, no further routes are evaluated for this event",
|
||||
"routeEditor.stopHint":
|
||||
"When matched, later routes in this group are not evaluated for this event",
|
||||
"routeEditor.filters": "Filters",
|
||||
"routeEditor.filtersNote": "(all must match · AND)",
|
||||
"routeEditor.matchPlaceholder": "match value (* ? wildcards, /regex/)",
|
||||
@@ -253,7 +266,16 @@ const en: Dict = {
|
||||
"routeEditor.addGroup": "Add group",
|
||||
"routeEditor.addNot": "Add not",
|
||||
"routeEditor.remove": "Remove",
|
||||
"routeEditor.removeCondition": "Delete condition",
|
||||
"routeEditor.removeGroup": "Delete condition group",
|
||||
"routeEditor.removeTarget": "Remove target",
|
||||
"routeEditor.path": "Field path",
|
||||
"routeEditor.values": "Values",
|
||||
"routeEditor.notHint": "Negate this condition",
|
||||
"routeEditor.errDraft": "Add (press Enter) or clear the filter value still being typed",
|
||||
"routeEditor.errInvalidValue": 'Invalid value "{value}": {reason}',
|
||||
"routeEditor.op": "Operator",
|
||||
"routeEditor.filterType": "Filter type",
|
||||
"routeEditor.pathPlaceholder": "payload.path",
|
||||
"routeEditor.valuesPlaceholder": "Type a value and press Enter",
|
||||
"routeEditor.testMatch": "Test match",
|
||||
@@ -263,6 +285,7 @@ const en: Dict = {
|
||||
"routeEditor.testMatched": "Matches",
|
||||
"routeEditor.testNotMatched": "Does not match",
|
||||
"routeEditor.testInvalidJson": "Invalid JSON",
|
||||
"routeEditor.testEventInvalid": "Fix or clear the event type first",
|
||||
"routeEditor.fragments": "Fragments",
|
||||
"routeEditor.fragmentsPresets": "Presets",
|
||||
"routeEditor.fragmentsEmpty": "No fragments yet",
|
||||
@@ -271,9 +294,23 @@ const en: Dict = {
|
||||
"routeEditor.fragmentsSave": "Save as fragment",
|
||||
"routeEditor.fragmentsNamePlaceholder": "Fragment name",
|
||||
"routeEditor.fragmentsNameRequired": "Fragment name is required",
|
||||
"routeEditor.fragmentsNotReady": "The group's fragments are still loading; try again in a moment",
|
||||
"routeEditor.errPath": "Field filters need a path",
|
||||
"routeEditor.errValues": "Add at least one value",
|
||||
"routeEditor.errGroupEmpty": "Group needs at least one condition",
|
||||
"combo.empty": "No matches",
|
||||
"combo.typeToAdd": "Type a value to add it",
|
||||
"combo.useValue": "Use “{value}”",
|
||||
"combo.remove": "Remove {value}",
|
||||
"combo.pending": 'Not added yet: press Enter to add "{value}"',
|
||||
"valid.tooLong": "Patterns longer than 200 characters never match",
|
||||
"valid.regex": "Invalid regular expression",
|
||||
"valid.number": "Comparison operators need a number",
|
||||
"valid.event": "Event names use letters, digits and _ (or * ? wildcards, /regex/)",
|
||||
"valid.eventName": "Event names use letters, digits and _",
|
||||
"valid.branch": "Branch names cannot contain spaces or ~ ^ : \\ [",
|
||||
"valid.branchLiteral":
|
||||
"This operator compares text as-is: branch names never contain * ? [ ~ ^ : \\ or spaces",
|
||||
"fragmentPreset.prBot": "PR by a bot",
|
||||
"fragmentPreset.dependabot": "Dependabot PR",
|
||||
"fragmentPreset.releasePublished": "Release published",
|
||||
@@ -329,6 +366,7 @@ const en: Dict = {
|
||||
"groupEditor.forgeSourcesHost": "git.example.com",
|
||||
"groupEditor.forgeSourcesName": "Optional display name",
|
||||
"groupEditor.forgeSourcesAdd": "+ Add host",
|
||||
"groupEditor.forgeSourcesRemove": "Remove host",
|
||||
"groupEditor.forgeSourcesHint":
|
||||
"Events whose repository host matches an entry are labeled in the message footer with its display name (or the host when none is set) — e.g. git1.example.com and git2.example.com for two Gitea instances. GitHub events match github.com.",
|
||||
"groupEditor.errForgeSourceHost": "Every forge host must be a valid hostname",
|
||||
@@ -384,6 +422,8 @@ const en: Dict = {
|
||||
"audit.allGroups": "All groups",
|
||||
"audit.refresh": "⟳ Refresh",
|
||||
"toast.routesSaved": "Routes saved",
|
||||
"toast.groupsBusy": "Another group change is still saving; try again in a moment",
|
||||
"toast.routesNotReady": "The routes are still loading or saving; try again in a moment",
|
||||
"toast.routeDeleted": "Route deleted",
|
||||
"toast.groupSaved": "Groups saved",
|
||||
"toast.groupDeleted": "Group deleted",
|
||||
@@ -391,15 +431,31 @@ const en: Dict = {
|
||||
"toast.groupIdExists": "Group ID already exists",
|
||||
"toast.saveFailed": "Save failed: {msg}",
|
||||
"toast.deleteFailed": "Delete failed: {msg}",
|
||||
"toast.orderSaved": "Route order saved",
|
||||
"confirm.deleteRoute": 'Delete route "{name}"?',
|
||||
"confirm.deleteGroup": 'Delete group "{name}"?',
|
||||
"confirm.deleteGroupWarn": " {n} route(s) reference it and will lose their group.",
|
||||
"confirm.cancel": "Cancel",
|
||||
"confirm.delete": "Delete",
|
||||
"confirm.removeCondition": "Delete this condition?",
|
||||
"confirm.removeFilterGroup": "Delete this condition group and everything in it?",
|
||||
"confirm.removeTarget": "Remove target {n}?",
|
||||
"confirm.deleteFragment": 'Delete fragment "{name}"?',
|
||||
"confirm.removeMember": 'Remove member "{name}"?',
|
||||
"confirm.revokeInvite": "Revoke this invite link?",
|
||||
"confirm.disableWebhook": "Disable this group's webhook endpoint?",
|
||||
"confirm.disableWebhookDetail": "The secret is deleted; senders still using it will be rejected.",
|
||||
"confirm.removeForgeSource": 'Remove host "{name}"?',
|
||||
"confirm.leaveUnsaved": "Leave this page?",
|
||||
"confirm.leaveUnsavedDesc": "Your unsaved changes will be lost.",
|
||||
"confirm.leave": "Leave",
|
||||
"confirm.signOut": "Sign out of the console?",
|
||||
};
|
||||
|
||||
const zh: Dict = {
|
||||
"app.tagline": "配置控制台",
|
||||
"app.newRoute": "+ 新建路由",
|
||||
"app.newGroup": "+ 新建分组",
|
||||
"app.newRoute": "新建路由",
|
||||
"app.newGroup": "新建分组",
|
||||
"app.signOut": "退出登录",
|
||||
"app.langToggle": "EN",
|
||||
"login.title": "配置控制台",
|
||||
@@ -476,7 +532,6 @@ const zh: Dict = {
|
||||
"role.owner": "拥有者",
|
||||
"role.admin": "管理员",
|
||||
"role.viewer": "只读",
|
||||
"role.badge": "我的角色:{role}",
|
||||
"roles.owner": "拥有者",
|
||||
"roles.admin": "管理员",
|
||||
"roles.viewer": "只读",
|
||||
@@ -526,12 +581,24 @@ const zh: Dict = {
|
||||
"groups.admins": "管理员",
|
||||
"groups.owners": "来源",
|
||||
"groups.members": "成员",
|
||||
"groups.myRole": "我的角色",
|
||||
"groups.any": "任意",
|
||||
"groups.open": "进入 →",
|
||||
"group.back": "返回分组",
|
||||
"groups.open": "进入",
|
||||
"groups.delete": "删除分组",
|
||||
"group.notFound": "分组不存在,或你没有访问权限",
|
||||
"group.allGroups": "全部分组",
|
||||
"group.routeCount": "{count} 条路由",
|
||||
"group.routesIn": "{name} 的路由",
|
||||
"routes.emptyGroup": "该分组还没有路由。",
|
||||
"routes.createFirst": "创建第一个路由",
|
||||
"routes.reorder": "调整顺序",
|
||||
"routes.reorderHint": "拖动手柄调整路由的评估顺序,完成后保存。",
|
||||
"routes.reorderKeyboardHint": "按上下方向键移动该路由。",
|
||||
"routes.reorderSave": "保存顺序",
|
||||
"routes.reorderCancel": "取消",
|
||||
"routes.dragHandle": "调整“{name}”的顺序",
|
||||
"routes.moved": "“{name}”已移到第 {n} 位",
|
||||
"routes.delete": "删除路由",
|
||||
"route.untitled": "(未命名)",
|
||||
"route.noFilters": "无过滤器",
|
||||
"route.channel": "频道",
|
||||
@@ -601,9 +668,10 @@ const zh: Dict = {
|
||||
"routeEditor.idHint": "唯一,使用 a-z / 0-9 / 短横线",
|
||||
"routeEditor.enabled": "启用路由",
|
||||
"routeEditor.fallback": "兜底路由",
|
||||
"routeEditor.fallbackHint": "仅当没有其它路由匹配该事件时才发送,其过滤器仍会生效",
|
||||
"routeEditor.fallbackHint":
|
||||
"仅当本分组没有普通(非兜底)路由匹配该事件时才发送,其过滤器仍会生效",
|
||||
"routeEditor.stop": "匹配后停止",
|
||||
"routeEditor.stopHint": "该路由匹配后,不再评估后续路由",
|
||||
"routeEditor.stopHint": "该路由匹配后,不再评估本分组的后续路由",
|
||||
"routeEditor.filters": "过滤器",
|
||||
"routeEditor.filtersNote": "(全部匹配 · AND)",
|
||||
"routeEditor.matchPlaceholder": "匹配值(支持 * ? 通配符、/正则/)",
|
||||
@@ -642,7 +710,16 @@ const zh: Dict = {
|
||||
"routeEditor.addGroup": "添加分组",
|
||||
"routeEditor.addNot": "添加非",
|
||||
"routeEditor.remove": "删除",
|
||||
"routeEditor.removeCondition": "删除条件",
|
||||
"routeEditor.removeGroup": "删除条件组",
|
||||
"routeEditor.removeTarget": "删除目标",
|
||||
"routeEditor.path": "字段路径",
|
||||
"routeEditor.values": "匹配值",
|
||||
"routeEditor.notHint": "对该条件取反",
|
||||
"routeEditor.errDraft": "请先确认(回车)或清除尚未添加的过滤值",
|
||||
"routeEditor.errInvalidValue": "无效的值“{value}”:{reason}",
|
||||
"routeEditor.op": "操作符",
|
||||
"routeEditor.filterType": "过滤类型",
|
||||
"routeEditor.pathPlaceholder": "payload.path",
|
||||
"routeEditor.valuesPlaceholder": "输入值后回车",
|
||||
"routeEditor.testMatch": "测试匹配",
|
||||
@@ -652,6 +729,7 @@ const zh: Dict = {
|
||||
"routeEditor.testMatched": "匹配",
|
||||
"routeEditor.testNotMatched": "不匹配",
|
||||
"routeEditor.testInvalidJson": "无效的 JSON",
|
||||
"routeEditor.testEventInvalid": "请先修正或清空事件类型",
|
||||
"routeEditor.fragments": "过滤器片段",
|
||||
"routeEditor.fragmentsPresets": "预设",
|
||||
"routeEditor.fragmentsEmpty": "暂无片段",
|
||||
@@ -660,9 +738,22 @@ const zh: Dict = {
|
||||
"routeEditor.fragmentsSave": "存为片段",
|
||||
"routeEditor.fragmentsNamePlaceholder": "片段名称",
|
||||
"routeEditor.fragmentsNameRequired": "请填写片段名称",
|
||||
"routeEditor.fragmentsNotReady": "分组的片段仍在加载,请稍后再试",
|
||||
"routeEditor.errPath": "字段过滤需要路径",
|
||||
"routeEditor.errValues": "至少需要一个值",
|
||||
"routeEditor.errGroupEmpty": "分组至少需要一个条件",
|
||||
"combo.empty": "无匹配项",
|
||||
"combo.typeToAdd": "输入内容后即可添加",
|
||||
"combo.useValue": "使用“{value}”",
|
||||
"combo.remove": "移除 {value}",
|
||||
"combo.pending": "尚未添加:按回车添加“{value}”",
|
||||
"valid.tooLong": "超过 200 个字符的模式永远不会匹配",
|
||||
"valid.regex": "无效的正则表达式",
|
||||
"valid.number": "比较运算需要数字",
|
||||
"valid.event": "事件名只能包含字母、数字和 _(也可用 * ? 通配符或 /正则/)",
|
||||
"valid.eventName": "事件名只能包含字母、数字和 _",
|
||||
"valid.branch": "分支名不能包含空格或 ~ ^ : \\ [",
|
||||
"valid.branchLiteral": "该运算符按字面比较:分支名不会包含 * ? [ ~ ^ : \\ 或空格",
|
||||
"fragmentPreset.prBot": "机器人提交的 PR",
|
||||
"fragmentPreset.dependabot": "Dependabot PR",
|
||||
"fragmentPreset.releasePublished": "发布 Release",
|
||||
@@ -717,6 +808,7 @@ const zh: Dict = {
|
||||
"groupEditor.forgeSourcesHost": "git.example.com",
|
||||
"groupEditor.forgeSourcesName": "可选显示名称",
|
||||
"groupEditor.forgeSourcesAdd": "+ 添加主机",
|
||||
"groupEditor.forgeSourcesRemove": "删除主机",
|
||||
"groupEditor.forgeSourcesHint":
|
||||
"仓库主机与条目匹配的事件,会在消息底部用该条目的显示名称标注(未填名称则用主机名)——例如两个 Gitea 实例可分别填 git1.example.com 和 git2.example.com。GitHub 事件匹配 github.com。",
|
||||
"groupEditor.errForgeSourceHost": "每个来源主机必须是有效的主机名",
|
||||
@@ -772,6 +864,8 @@ const zh: Dict = {
|
||||
"audit.allGroups": "全部分组",
|
||||
"audit.refresh": "⟳ 刷新",
|
||||
"toast.routesSaved": "路由已保存",
|
||||
"toast.groupsBusy": "另一项分组修改仍在保存,请稍后再试",
|
||||
"toast.routesNotReady": "路由仍在加载或保存中,请稍后再试",
|
||||
"toast.routeDeleted": "路由已删除",
|
||||
"toast.groupSaved": "分组已保存",
|
||||
"toast.groupDeleted": "分组已删除",
|
||||
@@ -779,9 +873,25 @@ const zh: Dict = {
|
||||
"toast.groupIdExists": "分组 ID 已存在",
|
||||
"toast.saveFailed": "保存失败:{msg}",
|
||||
"toast.deleteFailed": "删除失败:{msg}",
|
||||
"toast.orderSaved": "路由顺序已保存",
|
||||
"confirm.deleteRoute": "确定删除路由“{name}”吗?",
|
||||
"confirm.deleteGroup": "确定删除分组“{name}”吗?",
|
||||
"confirm.deleteGroupWarn": " 有 {n} 条路由引用它,将失去所属分组。",
|
||||
"confirm.cancel": "取消",
|
||||
"confirm.delete": "删除",
|
||||
"confirm.removeCondition": "确定删除该条件吗?",
|
||||
"confirm.removeFilterGroup": "确定删除该条件组及其中的全部条件吗?",
|
||||
"confirm.removeTarget": "确定删除第 {n} 个目标吗?",
|
||||
"confirm.deleteFragment": "确定删除片段“{name}”吗?",
|
||||
"confirm.removeMember": "确定移除成员“{name}”吗?",
|
||||
"confirm.revokeInvite": "确定撤销该邀请链接吗?",
|
||||
"confirm.disableWebhook": "确定停用该分组的 webhook 入口吗?",
|
||||
"confirm.disableWebhookDetail": "secret 将被删除,仍在使用它的发送方会被拒绝。",
|
||||
"confirm.removeForgeSource": "确定删除来源主机“{name}”吗?",
|
||||
"confirm.leaveUnsaved": "确定离开此页面吗?",
|
||||
"confirm.leaveUnsavedDesc": "尚未保存的修改将会丢失。",
|
||||
"confirm.leave": "离开",
|
||||
"confirm.signOut": "确定退出登录吗?",
|
||||
};
|
||||
|
||||
const messages: Record<Locale, Dict> = { en, zh };
|
||||
|
||||
@@ -5,8 +5,12 @@ export function useSendLogs() {
|
||||
const logs = ref<SendRecord[]>([]);
|
||||
const loading = ref(false);
|
||||
const error = ref("");
|
||||
// Bumped by every load, so only the latest request may land (an older one,
|
||||
// e.g. from the page the user just left, must not overwrite newer data).
|
||||
let request = 0;
|
||||
|
||||
async function load(limit = 50, groupId?: string): Promise<void> {
|
||||
const mine = ++request;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
needLogin.value = false;
|
||||
@@ -14,11 +18,12 @@ export function useSendLogs() {
|
||||
let url = `/admin/api/logs?limit=${limit}`;
|
||||
if (groupId) url += `&groupId=${encodeURIComponent(groupId)}`;
|
||||
const data = await apiFetch<{ logs?: SendRecord[] }>(url);
|
||||
logs.value = data.logs ?? [];
|
||||
if (mine === request) logs.value = data.logs ?? [];
|
||||
} catch (err) {
|
||||
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
|
||||
if (mine === request && !needLogin.value)
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (mine === request) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,19 +5,24 @@ export function useMetrics() {
|
||||
const metrics = ref<DeliveryMetrics | null>(null);
|
||||
const loading = ref(false);
|
||||
const error = ref("");
|
||||
// Bumped by every load, so only the latest request may land: Overview
|
||||
// (all groups) and Stats (maybe one group) share this state.
|
||||
let request = 0;
|
||||
|
||||
async function load(groupId?: string): Promise<void> {
|
||||
const mine = ++request;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
needLogin.value = false;
|
||||
try {
|
||||
const qs = groupId ? `?groupId=${encodeURIComponent(groupId)}` : "";
|
||||
const data = await apiFetch<{ metrics?: DeliveryMetrics }>(`/admin/api/metrics${qs}`);
|
||||
metrics.value = data.metrics ?? null;
|
||||
if (mine === request) metrics.value = data.metrics ?? null;
|
||||
} catch (err) {
|
||||
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
|
||||
if (mine === request && !needLogin.value)
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (mine === request) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { parseAdminPath } from "~/utils/admin-path";
|
||||
|
||||
definePageMeta({
|
||||
// One console for every /admin path: switching pages keeps its state (and
|
||||
// its in-flight saves) instead of mounting a fresh copy per URL.
|
||||
key: "admin-console",
|
||||
// Unknown console paths (e.g. /admin/foo, /admin/groups/a/b) 404 before rendering.
|
||||
validate: (route) => parseAdminPath(route.params.slug) !== null,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ConsolePage />
|
||||
</template>
|
||||
@@ -0,0 +1,27 @@
|
||||
/** Top-level pages of the admin console. */
|
||||
export type AdminView = "overview" | "groups" | "logs" | "audit" | "metrics";
|
||||
|
||||
const VIEWS: readonly string[] = ["overview", "groups", "logs", "audit", "metrics"];
|
||||
|
||||
/**
|
||||
* Read the console page from the segments after /admin: `[]` (overview),
|
||||
* `["groups"]`, `["groups", groupId]` (that group's routes), `["logs"]`,
|
||||
* `["audit"]`, `["metrics"]`. Anything else is no console page (null → 404).
|
||||
*/
|
||||
export function parseAdminPath(
|
||||
slug: string | string[] | undefined,
|
||||
): { view: AdminView; groupId: string | null } | null {
|
||||
// A trailing slash adds an empty segment.
|
||||
const [view, groupId, ...rest] = (Array.isArray(slug) ? slug : slug ? [slug] : []).filter(
|
||||
Boolean,
|
||||
);
|
||||
if (!view) return { view: "overview", groupId: null };
|
||||
if (!VIEWS.includes(view) || rest.length) return null;
|
||||
// Only groups have sub-pages.
|
||||
if (groupId !== undefined && view !== "groups") return null;
|
||||
return { view: view as AdminView, groupId: groupId ?? null };
|
||||
}
|
||||
|
||||
export function adminGroupPath(groupId: string): string {
|
||||
return `/admin/groups/${encodeURIComponent(groupId)}`;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -106,7 +106,7 @@ routes:
|
||||
# - platform: telegram
|
||||
# chatId: "-1001234567890"
|
||||
|
||||
# Stop routes stop processing further routes when matched.
|
||||
# Stop routes stop processing further routes of their group when matched.
|
||||
# - id: exclusive-push
|
||||
# name: "Exclusive Push"
|
||||
# enabled: true
|
||||
|
||||
@@ -63,7 +63,9 @@ WebHooker ships with a built-in config console at `/admin` for managing routes,
|
||||
|
||||
For local debugging only, set `DEBUG_MODE=true` to bypass GitHub OAuth and grant complete console access. Do not set this variable in a deployed environment.
|
||||
|
||||
The console is served as an SPA at `/admin`; its tabs are deep-linkable via the URL path (`/admin/groups`, `/admin/logs`, `/admin/audit`). URLs outside `/admin` that do not match an endpoint return a plain `404` instead of the console.
|
||||
The console is served as an SPA at `/admin`; its tabs are deep-linkable via the URL path (`/admin/groups`, `/admin/logs`, `/admin/audit`), and each group's routes page has its own URL (`/admin/groups/{groupId}`). Pages are browser history entries: use the browser's (or device's) back button to return from a group to the group list; leaving a page with an open editor or an unsaved route order asks for confirmation first. Unknown console paths return the console's 404 page. URLs outside `/admin` that do not match an endpoint return a plain `404` instead of the console.
|
||||
|
||||
Destructive actions — deleting routes, groups, filter conditions, fragments, targets or forge hosts, removing members, revoking invites, disabling a group's webhook — ask for confirmation in an in-app dialog (empty, never-filled rows are removed directly). The route and group editors ignore clicks on the backdrop so unsaved input is never lost; close them with Cancel, ✕ or <kbd>Esc</kbd>.
|
||||
|
||||
All management endpoints (`/admin/api/*`) are documented in the [Admin API](../api/admin). Saved routes and groups are persisted to D1 (`d1_routes` / `d1_groups`) immediately, the KV cache is invalidated and the config cache is refreshed so the webhook pipeline picks them up on the next run.
|
||||
|
||||
|
||||
@@ -86,6 +86,9 @@ bunx wrangler d1 execute webhooker --remote --file ./migrations/0005_audit_logs.
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0006_config_d1.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0007_send_logs_index.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0008_storage_d1.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0010_fragments.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0011_feishu_links.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0012_route_position.sql
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
@@ -256,6 +256,8 @@ A route can use a nested `ast` to combine filters with explicit grouping instead
|
||||
|
||||
When `ast` is present it takes precedence over `filters`. The admin console's route editor builds `ast` visually (all/any/not groups), shows a live explanation of the tree, and can test it against a pasted JSON payload via the **Test match** panel.
|
||||
|
||||
Values, field paths and the test event use searchable dropdowns. Suggestions come from GitHub's and Gitea's webhook definitions — events, the actions of the events the route filters on, common payload paths and their known values — each shown as its English key with a description in the console language; search matches the key first, then the English or Chinese description. Anything outside the list can still be typed and is validated before it is added; only values that can never match are rejected (an event name with spaces, a branch with characters git forbids, invalid regex syntax, a non-number for a comparison operator, …). Repository and actor values stay free-form because custom webhooks may carry any string. Text that is typed but not added with <kbd>Enter</kbd> blocks saving, fragment saving and test runs instead of being added or dropped silently. Several values can be typed or pasted at once, separated by commas or new lines; a `/regex/` keeps its own commas, and with the **matches regex** (`regex`) operator only new lines separate values (a raw pattern such as `^v{1,3}` may contain commas). Suggestions follow the operator: the substring operators compare text literally, so a glob suggestion becomes the text it implies (`release/*` → `release/` for **starts with**, `*[bot]` → `[bot]` for **ends with**), **matches regex** offers each suggestion as the escaped, anchored pattern it means (`^dependabot\[bot\]$`, `^release/`), and comparison operators get no suggestions. Switching between **equals** / **not equals** / **in** and **matches regex** rewrites `/x/` ↔ `x` in the values already added — both forms compile to the same regular expression, so the condition keeps matching exactly the same. Other values stay as typed (literal, glob and substring comparisons differ from regular expressions on line breaks and Unicode case folding), and values that can never match under the new operator are flagged. Arrays are expanded along a `field` path, but a path that **ends** on an array (e.g. `commits.modified`) is compared as a whole — match one of its elements with `contains`; the editor switches to `contains` when such a suggested path is picked.
|
||||
|
||||
### Named filter fragments
|
||||
|
||||
The route editor can save the current filter tree as a **named fragment** and insert it into other routes. Fragments are editor-side templates stored in D1 (`d1_fragments`); inserting a fragment inlines its node into the route's `ast`, so the matching engine itself never resolves fragment references.
|
||||
|
||||
@@ -34,11 +34,17 @@ Each entry of `targets` is a push destination, so one route can forward to sever
|
||||
| Field | Type | Required | Description |
|
||||
| ---------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `groupId` | string | Yes | Id of the [group](./groups) this route belongs to |
|
||||
| `fallback` | boolean | No | When `true`, fires only if no non-fallback route matched the event; its own filters are ignored |
|
||||
| `stop` | boolean | No | When `true` and this route matches, no further routes are evaluated for this event |
|
||||
| `fallback` | boolean | No | When `true`, fires only if no non-fallback route of the same group matched the event; its filters still apply |
|
||||
| `stop` | boolean | No | When `true` and this route matches, no further routes of the same group are evaluated for this event |
|
||||
| `discordRoleIds` | string[] | No | Discord role ids to ping when this route fires; applied to Discord targets only |
|
||||
| `ast` | object | No | Boolean filter tree (`{all:[...]}` / `{any:[...]}` / `{not:{...}}`); takes precedence over `filters` when present |
|
||||
|
||||
## Route Order
|
||||
|
||||
Routes are evaluated in the order the console shows them, group by group. `stop` and `fallback` act within a group: a matching `stop` route skips the later routes of its own group only, and a group's fallback routes stay silent only when one of that group's regular routes matched — one group never silences another. To change it, click **Reorder** on the group page, drag routes by their handle (or focus a handle and press <kbd>↑</kbd> / <kbd>↓</kbd>), then **Save order**. The order is stored per group in D1 (`d1_routes.position`, migration `0012`); a database without that migration keeps loading routes in id order.
|
||||
|
||||
**Upgrade note:** If your configuration relied on `stop` in one group preventing routes in another group from running, or on a regular route match in one group suppressing fallback sends in another, review your existing routes when upgrading. These effects now apply only within the same group, so routes in other groups may start sending. Move routes that need to be mutually exclusive into the same group, then check their order and `stop` / `fallback` settings.
|
||||
|
||||
## Discord Role Mentions
|
||||
|
||||
Set `discordRoleIds` on a route to ping one or more Discord roles (身份组) whenever that route fires. The mention (`<@&roleId>`) is prepended to the message content of every **Discord** target of the route; Telegram targets ignore this field. Mentions only trigger notifications when the bot has the `Mention Everyone` permission (or the role is marked mentionable), and the bot must be able to see the role.
|
||||
|
||||
@@ -62,7 +62,9 @@ WebHooker 在 `/admin` 提供内置配置控制台,可在浏览器中管理路
|
||||
|
||||
仅供本地调试:设置 `DEBUG_MODE=true` 可跳过 GitHub OAuth,并授予完整控制台权限。部署环境切勿设置此变量。
|
||||
|
||||
控制台以 SPA 形式在 `/admin` 提供;其标签页可通过 URL 路径直达(`/admin/groups`、`/admin/logs`、`/admin/audit`)。`/admin` 之外未匹配到端点的 URL 直接返回 `404`,而不会展示控制台。
|
||||
控制台以 SPA 形式在 `/admin` 提供;其标签页可通过 URL 路径直达(`/admin/groups`、`/admin/logs`、`/admin/audit`),每个分组的路由页也有独立 URL(`/admin/groups/{groupId}`)。各页面都会记入浏览器历史:从分组返回分组列表请使用浏览器(或设备)自带的返回;若页面上有打开的编辑器或未保存的路由顺序,离开前会先确认。未知的控制台路径显示控制台的 404 页面。`/admin` 之外未匹配到端点的 URL 直接返回 `404`,而不会展示控制台。
|
||||
|
||||
删除类操作——删除路由、分组、过滤条件、片段、目标或来源主机,移除成员,撤销邀请,停用分组 webhook——都会先弹出应用内确认框(从未填写过的空行直接删除)。路由与分组编辑弹窗点击遮罩不会关闭,避免丢失未保存的内容;请用「取消」、✕ 或 <kbd>Esc</kbd> 关闭。
|
||||
|
||||
所有管理端点(`/admin/api/*`)见 [Admin API](../api/admin)。保存的路由和分组会立即持久化到 D1(`d1_routes` / `d1_groups`),并使 KV 缓存失效、刷新配置缓存,下一次 webhook 处理即会生效。
|
||||
|
||||
|
||||
@@ -86,6 +86,9 @@ bunx wrangler d1 execute webhooker --remote --file ./migrations/0005_audit_logs.
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0006_config_d1.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0007_send_logs_index.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0008_storage_d1.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0010_fragments.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0011_feishu_links.sql
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0012_route_position.sql
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
@@ -256,6 +256,8 @@
|
||||
|
||||
当 `ast` 存在时,它优先于 `filters`。管理后台的路由编辑器会以可视化方式构建 `ast`(all/any/not 分组)、实时展示树状解释,并可通过「测试匹配」面板粘贴 JSON 载荷进行试匹配。
|
||||
|
||||
匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 GitHub 与 Gitea 的 webhook 定义——事件、路由所选事件的动作、常用载荷路径及其已知取值——以英文 key 展示,并附当前界面语言的说明;搜索优先匹配 key,其次匹配英文或中文说明。列表之外的值仍可直接输入,添加前会按匹配规则校验,只拒绝永远不可能匹配的值(含空格的事件名、含 git 禁用字符的分支、无效的正则、比较运算中的非数字等);仓库与操作者不做格式限制,因为自定义 webhook 可以携带任意字符串。已输入但未按<kbd>回车</kbd>添加的内容会阻止保存路由、存为片段和测试匹配,而不会被静默添加或丢弃。可一次输入或粘贴多个值,以逗号或换行分隔;`/正则/` 内的逗号会保留,选择「正则匹配」运算符时只按换行分隔(如 `^v{1,3}` 这样的原始模式可以包含逗号)。候选值会随运算符调整:「包含 / 开头是 / 结尾是」按字面比较,因此通配候选会换成其对应的文本(「开头是」用 `release/` 代替 `release/*`,「结尾是」用 `[bot]` 代替 `*[bot]`);「正则匹配」会把候选换成已转义并加锚点的等价正则(如 `^dependabot\[bot\]$`、`^release/`);比较运算符不提供候选。在「等于 / 不等于 / 属于」与「正则匹配」之间切换时,已添加的值会做 `/x/` ↔ `x` 改写——两种写法编译成同一个正则,匹配结果完全不变。其他值保持原样(字面、通配与按字面比较在换行和 Unicode 大小写折叠上与正则并不等价),在新运算符下永远无法匹配的值会被标出。`field` 路径中途的数组会被展开,但以数组**结尾**的路径(如 `commits.modified`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。
|
||||
|
||||
### 命名过滤器片段
|
||||
|
||||
路由编辑器可将当前过滤器树保存为**命名片段**并插入其他路由。片段是编辑器侧的模板,存储在 D1(`d1_fragments`)中;插入片段会将其节点内联进路由的 `ast`,因此匹配引擎本身从不解析片段引用。
|
||||
|
||||
@@ -34,11 +34,17 @@
|
||||
| 字段 | 类型 | 必需 | 说明 |
|
||||
| ---------------- | -------- | ---- | ------------------------------------------------------------------------------------- |
|
||||
| `groupId` | string | 是 | 路由所属[分组](./groups)的 id |
|
||||
| `fallback` | boolean | 否 | 为 `true` 时仅在没有其他非 fallback 路由匹配时才触发;其自身过滤器被忽略 |
|
||||
| `stop` | boolean | 否 | 为 `true` 且该路由匹配时,不再评估后续路由 |
|
||||
| `fallback` | boolean | 否 | 为 `true` 时仅在本分组没有其他非 fallback 路由匹配时才触发;其过滤器仍会生效 |
|
||||
| `stop` | boolean | 否 | 为 `true` 且该路由匹配时,不再评估本分组的后续路由 |
|
||||
| `discordRoleIds` | string[] | 否 | 路由触发时要提醒的 Discord 身份组 id;仅对 Discord 目标生效 |
|
||||
| `ast` | object | 否 | 布尔过滤器树(`{all:[...]}` / `{any:[...]}` / `{not:{...}}`);存在时优先于 `filters` |
|
||||
|
||||
## 路由顺序
|
||||
|
||||
路由按控制台中显示的顺序逐个分组评估。`stop` 与 `fallback` 只在分组内生效:匹配的 `stop` 路由只跳过本分组的后续路由;只有本分组的普通路由匹配时,本分组的兜底路由才不发送——一个分组永远不会屏蔽另一个分组。在分组页点击**调整顺序**,拖动路由左侧的手柄(或聚焦手柄后按 <kbd>↑</kbd> / <kbd>↓</kbd>),再点击**保存顺序**。顺序按分组保存在 D1(`d1_routes.position`,迁移 `0012`);未执行该迁移的数据库会继续按 id 顺序加载路由。
|
||||
|
||||
**升级提示:** 如果现有配置依赖某个分组的 `stop` 阻止其他分组的路由执行,或依赖某个分组的普通路由匹配来抑制其他分组的兜底路由发送,请在升级时检查现有路由。这些行为现在仅在同一分组内生效,因此其他分组的路由可能开始发送消息。请将需要共同排他的路由移至同一分组,再检查它们的顺序及 `stop` / `fallback` 设置。
|
||||
|
||||
## Discord 身份组提醒
|
||||
|
||||
在路由上设置 `discordRoleIds` 可在其触发时提醒一个或多个 Discord 身份组(角色)。提醒(`<@&roleId>`)会加在路由所有 **Discord** 目标的消息内容前;Telegram 目标忽略该字段。只有当机器人拥有 `Mention Everyone` 权限(或身份组标记为可提及)且能看到该身份组时,提醒才会触发通知。
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Persist the user-defined route order inside each group. Routes load ordered by
|
||||
-- (group_id, position, id); rows written before this migration keep position 0
|
||||
-- and therefore stay in id order until their group's routes are saved again.
|
||||
ALTER TABLE d1_routes ADD COLUMN position INTEGER NOT NULL DEFAULT 0;
|
||||
CREATE INDEX IF NOT EXISTS idx_d1_routes_group_position ON d1_routes (group_id, position);
|
||||
@@ -37,6 +37,16 @@ export default defineNuxtConfig({
|
||||
},
|
||||
vite: {
|
||||
plugins: [tailwindcss()],
|
||||
// App components use reka-ui primitives directly, alongside the copy
|
||||
// @elysola/ui imports. Pre-bundling it up front keeps both on one
|
||||
// dev instance; otherwise a mid-session discovery splits them and dialogs
|
||||
// and popovers stop stacking (Escape / outside clicks reach the wrong layer).
|
||||
// `debug` and `extend` are CommonJS packages @elysola/ui's markdown stack
|
||||
// (micromark, unified) imports; served unbundled in dev they lack a default
|
||||
// export and the console fails to start.
|
||||
optimizeDeps: {
|
||||
include: ["reka-ui", "debug", "extend"],
|
||||
},
|
||||
},
|
||||
devtools: { enabled: false },
|
||||
runtimeConfig: {
|
||||
|
||||
@@ -61,10 +61,15 @@ export async function dispatchEvent(
|
||||
if (!groupAcceptsOwners(group, owners)) return false;
|
||||
return groupAcceptsProvider(group, event.provider);
|
||||
};
|
||||
const matched = config.routes.filter(
|
||||
(route) => !route.fallback && matchRoute(route, event) && accepted(route),
|
||||
// `stop` and `fallback` act within a route's own group (its routing table), so
|
||||
// one group's routes can never silence another group's.
|
||||
const scopeOf = (route: Route): string => route.groupId ?? "";
|
||||
const regularMatched = new Set(
|
||||
config.routes
|
||||
.filter((route) => !route.fallback && matchRoute(route, event) && accepted(route))
|
||||
.map(scopeOf),
|
||||
);
|
||||
const anyRegularMatched = matched.length > 0;
|
||||
const stopped = new Set<string>();
|
||||
|
||||
const attempts: DispatchAttempt[] = [];
|
||||
const sendLogs: SendRecord[] = [];
|
||||
@@ -88,16 +93,18 @@ export async function dispatchEvent(
|
||||
|
||||
const tasks: Promise<void>[] = [];
|
||||
for (const route of config.routes) {
|
||||
if (!accepted(route)) continue;
|
||||
const scope = scopeOf(route);
|
||||
if (stopped.has(scope) || !accepted(route)) continue;
|
||||
if (route.fallback) {
|
||||
if (!anyRegularMatched && matchRoute(route, event)) {
|
||||
if (!regularMatched.has(scope) && matchRoute(route, event)) {
|
||||
tasks.push(processRoute(route));
|
||||
if (route.stop) stopped.add(scope);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (matchRoute(route, event)) {
|
||||
tasks.push(processRoute(route));
|
||||
if (route.stop) break;
|
||||
if (route.stop) stopped.add(scope);
|
||||
}
|
||||
}
|
||||
await Promise.allSettled(tasks);
|
||||
|
||||
+20
-12
@@ -25,7 +25,7 @@ export interface SendRecord {
|
||||
const COLUMNS =
|
||||
"id, ts, route_id, group_id, event, repo, target, ok, error, status, message_id, delivery_id, platform, actor, action, duration_ms, error_code, attempts, detail";
|
||||
|
||||
interface LogRow {
|
||||
export interface LogRow {
|
||||
id: number;
|
||||
ts: number;
|
||||
route_id: string;
|
||||
@@ -47,7 +47,7 @@ interface LogRow {
|
||||
detail: string | null;
|
||||
}
|
||||
|
||||
function toRecord(r: LogRow): SendRecord {
|
||||
export function toRecord(r: LogRow): SendRecord {
|
||||
return {
|
||||
id: r.id,
|
||||
ts: r.ts,
|
||||
@@ -147,22 +147,30 @@ export async function getSendLogByDelivery(
|
||||
}
|
||||
}
|
||||
|
||||
/** The latest failed sends, optionally of one group (rows map with `toRecord`). */
|
||||
export function failedSendLogStatement(
|
||||
db: D1Database,
|
||||
limit = 20,
|
||||
groupId?: string,
|
||||
): D1PreparedStatement {
|
||||
return groupId
|
||||
? db
|
||||
.prepare(
|
||||
`SELECT ${COLUMNS} FROM send_logs WHERE ok = 0 AND group_id = ? ORDER BY ts DESC LIMIT ?`,
|
||||
)
|
||||
.bind(groupId, limit)
|
||||
: db
|
||||
.prepare(`SELECT ${COLUMNS} FROM send_logs WHERE ok = 0 ORDER BY ts DESC LIMIT ?`)
|
||||
.bind(limit);
|
||||
}
|
||||
|
||||
export async function getFailedSendLog(
|
||||
db: D1Database,
|
||||
limit = 20,
|
||||
groupId?: string,
|
||||
): Promise<SendRecord[]> {
|
||||
try {
|
||||
const stmt = groupId
|
||||
? db
|
||||
.prepare(
|
||||
`SELECT ${COLUMNS} FROM send_logs WHERE ok = 0 AND group_id = ? ORDER BY ts DESC LIMIT ?`,
|
||||
)
|
||||
.bind(groupId, limit)
|
||||
: db
|
||||
.prepare(`SELECT ${COLUMNS} FROM send_logs WHERE ok = 0 ORDER BY ts DESC LIMIT ?`)
|
||||
.bind(limit);
|
||||
const { results } = await stmt.all<LogRow>();
|
||||
const { results } = await failedSendLogStatement(db, limit, groupId).all<LogRow>();
|
||||
return results.map(toRecord);
|
||||
} catch (err) {
|
||||
log.warn({ err }, "Failed to load failed send log");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { log } from "../lib/log";
|
||||
import { getFailedSendLog, type SendRecord } from "../lib/send-log";
|
||||
import { failedSendLogStatement, toRecord, type LogRow, type SendRecord } from "../lib/send-log";
|
||||
|
||||
export interface DeliveryMetrics {
|
||||
total: number;
|
||||
@@ -64,65 +64,77 @@ export async function getDeliveryMetrics(
|
||||
groupId ? stmt.bind(groupId) : stmt;
|
||||
|
||||
try {
|
||||
const totals = await bindGroup(
|
||||
db.prepare(`SELECT COUNT(*) AS total, COALESCE(SUM(ok), 0) AS ok FROM send_logs${where}`),
|
||||
).all<TotalsRow>();
|
||||
const total = Number(totals.results[0]?.total) || 0;
|
||||
const ok = Number(totals.results[0]?.ok) || 0;
|
||||
// One round trip for all seven queries (each D1 call is a network hop), and
|
||||
// a batch runs as one transaction, so the totals and breakdowns agree.
|
||||
const results = await db.batch([
|
||||
bindGroup(
|
||||
db.prepare(`SELECT COUNT(*) AS total, COALESCE(SUM(ok), 0) AS ok FROM send_logs${where}`),
|
||||
),
|
||||
bindGroup(
|
||||
db.prepare(
|
||||
`SELECT platform AS key, COUNT(*) AS total, COALESCE(SUM(ok), 0) AS ok
|
||||
FROM send_logs${where} GROUP BY platform`,
|
||||
),
|
||||
),
|
||||
bindGroup(
|
||||
db.prepare(
|
||||
`SELECT event AS key, COUNT(*) AS total, COALESCE(SUM(ok), 0) AS ok
|
||||
FROM send_logs${where} GROUP BY event`,
|
||||
),
|
||||
),
|
||||
bindGroup(
|
||||
db.prepare(
|
||||
`SELECT status, COUNT(*) AS count FROM send_logs
|
||||
WHERE status IS NOT NULL${and} GROUP BY status`,
|
||||
),
|
||||
),
|
||||
bindGroup(
|
||||
db.prepare(
|
||||
`SELECT AVG(duration_ms) AS avg FROM send_logs WHERE duration_ms IS NOT NULL${and}`,
|
||||
),
|
||||
),
|
||||
bindGroup(
|
||||
db.prepare(
|
||||
`SELECT COALESCE(SUM(attempts), 0) AS total, AVG(attempts) AS avg
|
||||
FROM send_logs WHERE attempts IS NOT NULL${and}`,
|
||||
),
|
||||
),
|
||||
failedSendLogStatement(db, 20, groupId),
|
||||
]);
|
||||
const rows = <T>(i: number): T[] => (results[i]?.results ?? []) as T[];
|
||||
const totals = rows<TotalsRow>(0);
|
||||
const byPlatform = rows<BreakdownRow>(1);
|
||||
const byEvent = rows<BreakdownRow>(2);
|
||||
const byStatus = rows<StatusRow>(3);
|
||||
const duration = rows<AvgRow>(4);
|
||||
const attempts = rows<AttemptsRow>(5);
|
||||
const recentFailures = rows<LogRow>(6).map(toRecord);
|
||||
|
||||
const byPlatform = await bindGroup(
|
||||
db.prepare(
|
||||
`SELECT platform AS key, COUNT(*) AS total, COALESCE(SUM(ok), 0) AS ok
|
||||
FROM send_logs${where} GROUP BY platform`,
|
||||
),
|
||||
).all<BreakdownRow>();
|
||||
const byEvent = await bindGroup(
|
||||
db.prepare(
|
||||
`SELECT event AS key, COUNT(*) AS total, COALESCE(SUM(ok), 0) AS ok
|
||||
FROM send_logs${where} GROUP BY event`,
|
||||
),
|
||||
).all<BreakdownRow>();
|
||||
const byStatus = await bindGroup(
|
||||
db.prepare(
|
||||
`SELECT status, COUNT(*) AS count FROM send_logs
|
||||
WHERE status IS NOT NULL${and} GROUP BY status`,
|
||||
),
|
||||
).all<StatusRow>();
|
||||
const duration = await bindGroup(
|
||||
db.prepare(
|
||||
`SELECT AVG(duration_ms) AS avg FROM send_logs WHERE duration_ms IS NOT NULL${and}`,
|
||||
),
|
||||
).all<AvgRow>();
|
||||
const attempts = await bindGroup(
|
||||
db.prepare(
|
||||
`SELECT COALESCE(SUM(attempts), 0) AS total, AVG(attempts) AS avg
|
||||
FROM send_logs WHERE attempts IS NOT NULL${and}`,
|
||||
),
|
||||
).all<AttemptsRow>();
|
||||
const recentFailures = await getFailedSendLog(db, 20, groupId);
|
||||
const total = Number(totals[0]?.total) || 0;
|
||||
const ok = Number(totals[0]?.ok) || 0;
|
||||
|
||||
return {
|
||||
total,
|
||||
ok,
|
||||
failed: total - ok,
|
||||
failureRate: total > 0 ? (total - ok) / total : 0,
|
||||
byPlatform: byPlatform.results.map((r) => {
|
||||
byPlatform: byPlatform.map((r) => {
|
||||
const t = Number(r.total) || 0;
|
||||
const o = Number(r.ok) || 0;
|
||||
return { platform: r.key ?? "unknown", total: t, ok: o, failed: t - o };
|
||||
}),
|
||||
byEvent: byEvent.results.map((r) => {
|
||||
byEvent: byEvent.map((r) => {
|
||||
const t = Number(r.total) || 0;
|
||||
const o = Number(r.ok) || 0;
|
||||
return { event: r.key ?? "unknown", total: t, ok: o, failed: t - o };
|
||||
}),
|
||||
byStatus: byStatus.results.map((r) => ({
|
||||
byStatus: byStatus.map((r) => ({
|
||||
status: String(r.status),
|
||||
count: Number(r.count) || 0,
|
||||
})),
|
||||
avgDurationMs: Number(duration.results[0]?.avg) || 0,
|
||||
totalAttempts: Number(attempts.results[0]?.total) || 0,
|
||||
avgAttempts: Number(attempts.results[0]?.avg) || 0,
|
||||
avgDurationMs: Number(duration[0]?.avg) || 0,
|
||||
totalAttempts: Number(attempts[0]?.total) || 0,
|
||||
avgAttempts: Number(attempts[0]?.avg) || 0,
|
||||
recentFailures,
|
||||
};
|
||||
} catch (err) {
|
||||
|
||||
@@ -48,12 +48,32 @@ export function d1ConfigStore(db: D1Database, kv: KVNamespace): ConfigStore {
|
||||
let routesCache: { routes: Route[]; expiresAt: number } | null = null;
|
||||
let groupsCache: { groups: Group[]; expiresAt: number } | null = null;
|
||||
|
||||
/**
|
||||
* Run a statement that uses the `position` column (migration 0012) and fall
|
||||
* back to its legacy form only when the database confirms the column is
|
||||
* missing. Any other error propagates exactly as before, and nothing is
|
||||
* remembered, so a database migrated later is picked up on the next call.
|
||||
*/
|
||||
async function withPosition<T>(run: (positioned: boolean) => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await run(true);
|
||||
} catch (err) {
|
||||
// SQLite says "no such column: position" for reads and "has no column
|
||||
// named position" for inserts.
|
||||
if (!/no such column: position|no column named position/i.test(String(err))) throw err;
|
||||
return run(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRoutesFromD1(): Promise<Route[]> {
|
||||
const stmt = db.prepare(
|
||||
"SELECT id, group_id, name, enabled, filters, targets, stop, fallback, discord_role_ids, ast FROM d1_routes ORDER BY id",
|
||||
);
|
||||
if (typeof stmt.all !== "function") return [];
|
||||
const { results } = await stmt.all<D1RouteRow>();
|
||||
const results = await withPosition(async (positioned) => {
|
||||
const order = positioned ? "group_id, position, id" : "id";
|
||||
const stmt = db.prepare(
|
||||
`SELECT id, group_id, name, enabled, filters, targets, stop, fallback, discord_role_ids, ast FROM d1_routes ORDER BY ${order}`,
|
||||
);
|
||||
if (typeof stmt.all !== "function") return [];
|
||||
return (await stmt.all<D1RouteRow>()).results;
|
||||
});
|
||||
if (!results || results.length === 0) return [];
|
||||
return results.flatMap((r) => {
|
||||
const filters = parseJson<Route["filters"]>(r.filters, `route:${r.id}:filters`);
|
||||
@@ -115,10 +135,14 @@ export function d1ConfigStore(db: D1Database, kv: KVNamespace): ConfigStore {
|
||||
|
||||
function routeStatements(
|
||||
routes: Route[],
|
||||
positioned: boolean,
|
||||
existingRouteKeys?: Set<string>,
|
||||
): D1PreparedStatement[] {
|
||||
const now = Date.now();
|
||||
const statements: D1PreparedStatement[] = [];
|
||||
// A route's position is its index among the routes of its own group, so
|
||||
// saving one group never shifts the order of another.
|
||||
const nextPosition = new Map<string, number>();
|
||||
|
||||
// If we have existing routes, delete those not in the new set
|
||||
if (existingRouteKeys) {
|
||||
@@ -138,6 +162,43 @@ export function d1ConfigStore(db: D1Database, kv: KVNamespace): ConfigStore {
|
||||
|
||||
// Upsert all routes
|
||||
for (const r of routes) {
|
||||
const groupId = r.groupId ?? "";
|
||||
const values = [
|
||||
r.id,
|
||||
groupId,
|
||||
r.name,
|
||||
r.enabled ? 1 : 0,
|
||||
JSON.stringify(r.filters),
|
||||
JSON.stringify(r.targets),
|
||||
r.stop ? 1 : 0,
|
||||
r.fallback ? 1 : 0,
|
||||
r.discordRoleIds ? JSON.stringify(r.discordRoleIds) : null,
|
||||
r.ast ? JSON.stringify(r.ast) : null,
|
||||
];
|
||||
if (positioned) {
|
||||
const position = nextPosition.get(groupId) ?? 0;
|
||||
nextPosition.set(groupId, position + 1);
|
||||
statements.push(
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO d1_routes (id, group_id, name, enabled, filters, targets, stop, fallback, discord_role_ids, ast, position, version, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
|
||||
ON CONFLICT(id, group_id) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
enabled = excluded.enabled,
|
||||
filters = excluded.filters,
|
||||
targets = excluded.targets,
|
||||
stop = excluded.stop,
|
||||
fallback = excluded.fallback,
|
||||
discord_role_ids = excluded.discord_role_ids,
|
||||
ast = excluded.ast,
|
||||
position = excluded.position,
|
||||
updated_at = excluded.updated_at`,
|
||||
)
|
||||
.bind(...values, position, now, now),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
statements.push(
|
||||
db
|
||||
.prepare(
|
||||
@@ -154,20 +215,7 @@ export function d1ConfigStore(db: D1Database, kv: KVNamespace): ConfigStore {
|
||||
ast = excluded.ast,
|
||||
updated_at = excluded.updated_at`,
|
||||
)
|
||||
.bind(
|
||||
r.id,
|
||||
r.groupId ?? "",
|
||||
r.name,
|
||||
r.enabled ? 1 : 0,
|
||||
JSON.stringify(r.filters),
|
||||
JSON.stringify(r.targets),
|
||||
r.stop ? 1 : 0,
|
||||
r.fallback ? 1 : 0,
|
||||
r.discordRoleIds ? JSON.stringify(r.discordRoleIds) : null,
|
||||
r.ast ? JSON.stringify(r.ast) : null,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
.bind(...values, now, now),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -214,7 +262,7 @@ export function d1ConfigStore(db: D1Database, kv: KVNamespace): ConfigStore {
|
||||
|
||||
async function seedRoutesToD1(routes: Route[]): Promise<void> {
|
||||
if (routes.length === 0) return;
|
||||
await db.batch(routeStatements(routes));
|
||||
await withPosition((positioned) => db.batch(routeStatements(routes, positioned)));
|
||||
}
|
||||
|
||||
async function seedGroupsToD1(groups: Group[]): Promise<void> {
|
||||
@@ -269,7 +317,7 @@ export function d1ConfigStore(db: D1Database, kv: KVNamespace): ConfigStore {
|
||||
|
||||
async saveRoutes(routes: Route[]): Promise<void> {
|
||||
try {
|
||||
await db.batch(routeStatements(routes));
|
||||
await withPosition((positioned) => db.batch(routeStatements(routes, positioned)));
|
||||
await syncRoutesToKV(routes, KV_CACHE_TTL);
|
||||
} catch (err) {
|
||||
log.warn({ err }, "D1 routes unavailable, falling back to KV");
|
||||
|
||||
+8
-6
@@ -67,15 +67,17 @@ export interface Route {
|
||||
*/
|
||||
ast?: FilterNode;
|
||||
/**
|
||||
* Fallback route: only fires when no other (non-fallback) route matched the
|
||||
* event. Multiple fallback routes may exist; they are all skipped whenever at
|
||||
* least one regular route matches. Its own filters are ignored.
|
||||
* Fallback route: only fires when no other (non-fallback) route of the same
|
||||
* group matched the event. Multiple fallback routes may exist; a group's are
|
||||
* all skipped whenever one of its regular routes matches. Its own filters
|
||||
* still apply.
|
||||
*/
|
||||
fallback?: boolean;
|
||||
/**
|
||||
* Stop: when true and this route matches, no further routes are evaluated
|
||||
* for this event. Useful for exclusive routing where a match should prevent
|
||||
* fallthrough to subsequent routes.
|
||||
* Stop: when true and this route matches, no further routes of the same
|
||||
* group are evaluated for this event (other groups are unaffected). Useful
|
||||
* for exclusive routing where a match should prevent fallthrough to the
|
||||
* group's subsequent routes.
|
||||
*/
|
||||
stop?: boolean;
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { defineEventHandler, getMethod, getRouterParam, setResponseStatus } from "h3";
|
||||
import {
|
||||
defineEventHandler,
|
||||
getMethod,
|
||||
getRouterParam,
|
||||
setResponseHeader,
|
||||
setResponseStatus,
|
||||
} from "h3";
|
||||
import {
|
||||
adminApiMe,
|
||||
adminApiGroupsGet,
|
||||
@@ -27,6 +33,8 @@ import {
|
||||
export default defineEventHandler((event) => {
|
||||
const method = getMethod(event);
|
||||
const seg = (getRouterParam(event, "slug") ?? "").split("/").filter(Boolean);
|
||||
// Per-user, live admin data: no browser or proxy may store or reuse it.
|
||||
setResponseHeader(event, "Cache-Control", "no-store");
|
||||
|
||||
if (seg[0] === "me" && method === "GET") return adminApiMe(event);
|
||||
if (seg[0] === "groups" && seg.length === 1) {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import handler from "../server/routes/admin/api/[...slug]";
|
||||
import { makeEvent, responseHeader, responseStatus } from "./helpers";
|
||||
|
||||
describe("admin API route", () => {
|
||||
it("never lets a response be cached", async () => {
|
||||
const event = makeEvent("/admin/api/nope", { env: { GITHUB_WEBHOOK_SECRET: "s" } as never });
|
||||
event.context.params = { slug: "nope" };
|
||||
const res = await handler(event);
|
||||
expect(responseStatus(event)).toBe(404);
|
||||
expect(res).toEqual({ error: "Not found" });
|
||||
expect(responseHeader(event, "cache-control")).toBe("no-store");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { adminGroupPath, parseAdminPath } from "../app/utils/admin-path";
|
||||
|
||||
describe("parseAdminPath", () => {
|
||||
it("maps the console pages", () => {
|
||||
expect(parseAdminPath(undefined)).toEqual({ view: "overview", groupId: null });
|
||||
expect(parseAdminPath([])).toEqual({ view: "overview", groupId: null });
|
||||
expect(parseAdminPath("logs")).toEqual({ view: "logs", groupId: null });
|
||||
expect(parseAdminPath(["groups"])).toEqual({ view: "groups", groupId: null });
|
||||
expect(parseAdminPath(["metrics"])).toEqual({ view: "metrics", groupId: null });
|
||||
});
|
||||
|
||||
it("opens a group's routes under /admin/groups/{groupId}", () => {
|
||||
expect(parseAdminPath(["groups", "inst-12345678"])).toEqual({
|
||||
view: "groups",
|
||||
groupId: "inst-12345678",
|
||||
});
|
||||
// A trailing slash adds an empty segment.
|
||||
expect(parseAdminPath(["groups", ""])).toEqual({ view: "groups", groupId: null });
|
||||
expect(parseAdminPath(["groups", "acme", ""])).toEqual({ view: "groups", groupId: "acme" });
|
||||
});
|
||||
|
||||
it("rejects unknown pages and sub-pages", () => {
|
||||
expect(parseAdminPath(["foo"])).toBeNull();
|
||||
expect(parseAdminPath(["logs", "x"])).toBeNull();
|
||||
expect(parseAdminPath(["groups", "acme", "routes"])).toBeNull();
|
||||
expect(parseAdminPath(["constructor"])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("adminGroupPath", () => {
|
||||
it("encodes the group id", () => {
|
||||
expect(adminGroupPath("acme")).toBe("/admin/groups/acme");
|
||||
expect(adminGroupPath("a/b c")).toBe("/admin/groups/a%2Fb%20c");
|
||||
});
|
||||
});
|
||||
+102
-5
@@ -3,6 +3,8 @@ import { d1ConfigStore, type ConfigStore } from "../server/lib/storage/config-st
|
||||
import type { Route, Group } from "../server/lib/types";
|
||||
|
||||
interface Stmt {
|
||||
sql: string;
|
||||
bound: unknown[];
|
||||
bind: (...args: unknown[]) => Stmt;
|
||||
all: () => Promise<{ results: Array<Record<string, unknown>> }>;
|
||||
}
|
||||
@@ -12,6 +14,13 @@ interface FakeDB {
|
||||
batch: (stmts: Stmt[]) => Promise<unknown[]>;
|
||||
}
|
||||
|
||||
interface FakeDBOptions {
|
||||
/** Whether `d1_routes` has the `position` column (migration 0012). */
|
||||
positionColumn?: boolean;
|
||||
/** How many batches fail with a transient (non-schema) error first. */
|
||||
batchFailures?: number;
|
||||
}
|
||||
|
||||
function route(id: string, groupId: string, overrides: Partial<Route> = {}): Route {
|
||||
return {
|
||||
id,
|
||||
@@ -30,18 +39,32 @@ function group(id: string): Group {
|
||||
return { id, name: `group-${id}`, adminIds: [] };
|
||||
}
|
||||
|
||||
function createDB(): { db: FakeDB & D1Database; routesTable: Route[]; groupsTable: Group[] } {
|
||||
function createDB(options: FakeDBOptions = {}): {
|
||||
db: FakeDB & D1Database;
|
||||
routesTable: Route[];
|
||||
groupsTable: Group[];
|
||||
queries: string[];
|
||||
batches: Stmt[][];
|
||||
} {
|
||||
const routesTable: Route[] = [];
|
||||
const groupsTable: Group[] = [];
|
||||
const queries: string[] = [];
|
||||
const batches: Stmt[][] = [];
|
||||
let batchFailures = options.batchFailures ?? 0;
|
||||
const db: FakeDB = {
|
||||
prepare(sql: string): Stmt {
|
||||
let _bound: unknown[] = [];
|
||||
const stmt: Stmt = {
|
||||
sql,
|
||||
bound: [],
|
||||
bind(...args: unknown[]): Stmt {
|
||||
_bound = args;
|
||||
stmt.bound = args;
|
||||
return stmt;
|
||||
},
|
||||
async all(): Promise<{ results: Array<Record<string, unknown>> }> {
|
||||
queries.push(sql);
|
||||
if (sql.includes("position") && !options.positionColumn) {
|
||||
throw new Error("D1_ERROR: no such column: position at offset 33: SQLITE_ERROR");
|
||||
}
|
||||
if (sql.includes("FROM d1_routes")) {
|
||||
return {
|
||||
results: routesTable.map((r) => ({
|
||||
@@ -74,11 +97,25 @@ function createDB(): { db: FakeDB & D1Database; routesTable: Route[]; groupsTabl
|
||||
return stmt;
|
||||
},
|
||||
async batch(stmts: Stmt[]): Promise<unknown[]> {
|
||||
void stmts;
|
||||
batches.push(stmts);
|
||||
if (batchFailures > 0) {
|
||||
batchFailures--;
|
||||
throw new Error("D1_ERROR: network connection lost");
|
||||
}
|
||||
if (!options.positionColumn && stmts.some((st) => st.sql.includes("position,"))) {
|
||||
throw new Error("D1_ERROR: table d1_routes has no column named position: SQLITE_ERROR");
|
||||
}
|
||||
return [];
|
||||
},
|
||||
};
|
||||
return { db: db as FakeDB & D1Database, routesTable, groupsTable };
|
||||
return { db: db as FakeDB & D1Database, routesTable, groupsTable, queries, batches };
|
||||
}
|
||||
|
||||
/** Bound `(id, position)` pairs of every route upsert in a batch. */
|
||||
function upsertPositions(stmts: Stmt[]): Array<[unknown, unknown]> {
|
||||
return stmts
|
||||
.filter((s) => s.sql.includes("INSERT INTO d1_routes"))
|
||||
.map((s) => [s.bound[0], s.sql.includes("position") ? s.bound[10] : undefined]);
|
||||
}
|
||||
|
||||
function createKV(): { kv: KVNamespace; store: Map<string, string> } {
|
||||
@@ -172,6 +209,66 @@ describe("d1ConfigStore", () => {
|
||||
expect(second).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("persists the per-group route order when the position column exists", async () => {
|
||||
const { db, batches } = createDB({ positionColumn: true });
|
||||
const { kv } = createKV();
|
||||
const cfg: ConfigStore = d1ConfigStore(db, kv);
|
||||
await cfg.saveRoutes([route("b", "g1"), route("x", "g2"), route("a", "g1")]);
|
||||
expect(upsertPositions(batches[0]!)).toEqual([
|
||||
["b", 0],
|
||||
["x", 0],
|
||||
["a", 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads routes ordered by group and position when the column exists", async () => {
|
||||
const { db, queries } = createDB({ positionColumn: true });
|
||||
const { kv } = createKV();
|
||||
await d1ConfigStore(db, kv).loadRoutes();
|
||||
expect(queries.some((q) => q.includes("FROM d1_routes ORDER BY group_id, position, id"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the legacy id order and inserts on an unmigrated database", async () => {
|
||||
const { db, queries, batches } = createDB();
|
||||
const { kv } = createKV();
|
||||
const cfg: ConfigStore = d1ConfigStore(db, kv);
|
||||
await cfg.loadRoutes();
|
||||
expect(queries.at(-1)).toContain("FROM d1_routes ORDER BY id");
|
||||
await cfg.saveRoutes([route("r1", "g1")]);
|
||||
expect(upsertPositions(batches.at(-1)!)).toEqual([["r1", undefined]]);
|
||||
});
|
||||
|
||||
it("picks up the position column once the database is migrated", async () => {
|
||||
const options: FakeDBOptions = {};
|
||||
const { db, queries } = createDB(options);
|
||||
const { kv } = createKV();
|
||||
const cfg: ConfigStore = d1ConfigStore(db, kv);
|
||||
await cfg.loadRoutes();
|
||||
expect(queries.at(-1)).toContain("ORDER BY id");
|
||||
options.positionColumn = true;
|
||||
cfg.invalidateCache();
|
||||
await cfg.loadRoutes();
|
||||
expect(queries.at(-1)).toContain("ORDER BY group_id, position, id");
|
||||
});
|
||||
|
||||
it("never retries without positions when D1 fails for another reason", async () => {
|
||||
const { db, batches } = createDB({ positionColumn: true, batchFailures: 1 });
|
||||
const { kv, store } = createKV();
|
||||
const cfg: ConfigStore = d1ConfigStore(db, kv);
|
||||
const routes = [route("b", "g1"), route("a", "g1")];
|
||||
await cfg.saveRoutes(routes);
|
||||
// Only the positioned batch was attempted; the save took the existing
|
||||
// "D1 unavailable" path instead of writing rows that lose the order.
|
||||
expect(batches).toHaveLength(1);
|
||||
expect(upsertPositions(batches[0]!)).toEqual([
|
||||
["b", 0],
|
||||
["a", 1],
|
||||
]);
|
||||
expect(store.get("config:routes")).toBe(JSON.stringify(routes));
|
||||
});
|
||||
|
||||
it("updating groups does not cascade-delete routes", async () => {
|
||||
const { db, routesTable, groupsTable } = createDB();
|
||||
const { kv } = createKV();
|
||||
|
||||
@@ -50,6 +50,7 @@ function createMetricsDB(rowsBySql: Record<string, unknown[]>): D1Database {
|
||||
}
|
||||
return { results: [] };
|
||||
};
|
||||
let batches = 0;
|
||||
return {
|
||||
prepare: (sql: string) => ({
|
||||
all: all(sql),
|
||||
@@ -58,6 +59,13 @@ function createMetricsDB(rowsBySql: Record<string, unknown[]>): D1Database {
|
||||
run: async () => ({ success: true }),
|
||||
}),
|
||||
}),
|
||||
batch: async (statements: Array<{ all: () => Promise<unknown> }>) => {
|
||||
batches++;
|
||||
return Promise.all(statements.map((s) => s.all()));
|
||||
},
|
||||
get batches(): number {
|
||||
return batches;
|
||||
},
|
||||
} as unknown as D1Database;
|
||||
}
|
||||
|
||||
@@ -102,6 +110,8 @@ describe("delivery metrics", () => {
|
||||
"COUNT(*) AS total": [{ total: 10, ok: 8 }],
|
||||
});
|
||||
const m = await getDeliveryMetrics(db);
|
||||
// Every query goes out in a single batch (one D1 round trip).
|
||||
expect((db as unknown as { batches: number }).batches).toBe(1);
|
||||
expect(m.total).toBe(10);
|
||||
expect(m.ok).toBe(8);
|
||||
expect(m.failed).toBe(2);
|
||||
|
||||
@@ -215,6 +215,49 @@ describe("dispatchEvent fallback routing", () => {
|
||||
expect(sent.filter((u) => u.includes("/222/"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("scopes stop and fallback to the route's own group", async () => {
|
||||
const sent: string[] = [];
|
||||
mockFetch((url) => {
|
||||
sent.push(url);
|
||||
return new Response("{}", { status: 200 });
|
||||
});
|
||||
const env = createEnv({ KV: createMockKV(), DB: createMockDB() });
|
||||
const route = (
|
||||
id: string,
|
||||
groupId: string,
|
||||
extra: Partial<Route>,
|
||||
channelId: string,
|
||||
): Route => ({
|
||||
id,
|
||||
name: id,
|
||||
enabled: true,
|
||||
filters: [{ type: "event", match: "push" }],
|
||||
targets: [{ channelId }],
|
||||
groupId,
|
||||
...extra,
|
||||
});
|
||||
const routes: Route[] = [
|
||||
route("alpha-stop", "alpha", { stop: true }, "301"),
|
||||
route("alpha-later", "alpha", {}, "302"),
|
||||
route("zeta-push", "zeta", {}, "303"),
|
||||
route("zeta-catch-all", "zeta", { fallback: true, filters: [] }, "304"),
|
||||
route("omega-catch-all", "omega", { fallback: true, stop: true, filters: [] }, "305"),
|
||||
route("omega-catch-all-2", "omega", { fallback: true, filters: [] }, "306"),
|
||||
];
|
||||
|
||||
await dispatchEvent({ ...baseConfig, routes }, { event: "push", payload: {} }, env);
|
||||
const hits = (channel: string): number => sent.filter((u) => u.includes(`/${channel}/`)).length;
|
||||
// alpha stops after its first match without silencing zeta.
|
||||
expect(hits("301")).toBe(1);
|
||||
expect(hits("302")).toBe(0);
|
||||
expect(hits("303")).toBe(1);
|
||||
// zeta matched a regular route, omega did not: only omega's fallback fires,
|
||||
// and its `stop` keeps omega's later fallback silent.
|
||||
expect(hits("304")).toBe(0);
|
||||
expect(hits("305")).toBe(1);
|
||||
expect(hits("306")).toBe(0);
|
||||
});
|
||||
|
||||
it("prepends role mentions to the Discord message content", async () => {
|
||||
const bodies: string[] = [];
|
||||
mockFetch((url, init) => {
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import {
|
||||
actionOptions,
|
||||
commaEndsValue,
|
||||
convertValuesForOp,
|
||||
eventOptions,
|
||||
fieldPathOptions,
|
||||
fieldValueOptions,
|
||||
isArrayFieldPath,
|
||||
splitFilterValues,
|
||||
validateFilterValue,
|
||||
valueOptions,
|
||||
} from "../app/utils/filter-catalog";
|
||||
import { formToLeaf } from "../app/composables/useFilterNode";
|
||||
import { evaluateFilterNode } from "../server/lib/events/filter-ast";
|
||||
import type { FilterOp, WebhookEvent } from "../server/lib/types";
|
||||
|
||||
function values(opts: { value: string }[]): string[] {
|
||||
return opts.map((o) => o.value);
|
||||
}
|
||||
|
||||
describe("filter catalog options", () => {
|
||||
it("lists every event once, formatted events first and Gitea-only events last", () => {
|
||||
const opts = eventOptions("en");
|
||||
const names = values(opts);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
expect(names[0]).toBe("push");
|
||||
expect(names).toContain("custom");
|
||||
expect(names).toContain("merge_group");
|
||||
expect(names.slice(-3)).toEqual(["pull_request_approved", "pull_request_rejected", "wiki"]);
|
||||
});
|
||||
|
||||
it("describes every option in both languages and shows the active one", () => {
|
||||
for (const locale of ["en", "zh"] as const) {
|
||||
for (const opt of [
|
||||
...eventOptions(locale),
|
||||
...actionOptions(locale, []),
|
||||
...fieldPathOptions(locale, []),
|
||||
]) {
|
||||
expect(opt.hint).toBeTruthy();
|
||||
expect(opt.keywords?.length).toBeGreaterThanOrEqual(2);
|
||||
expect(opt.keywords).toContain(opt.hint!);
|
||||
}
|
||||
}
|
||||
const push = eventOptions("zh").find((o) => o.value === "push")!;
|
||||
expect(push.hint).toBe("推送提交到分支或标签");
|
||||
expect(push.keywords).toContain("Commits pushed to a branch or tag");
|
||||
});
|
||||
|
||||
it("puts the actions of the route's events first without duplicates", () => {
|
||||
const opts = actionOptions("en", ["pull_request"]);
|
||||
const names = values(opts);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
expect(opts[0]!.group).toBe("For the selected events");
|
||||
expect(names.indexOf("synchronize")).toBeLessThan(names.indexOf("published"));
|
||||
// Actions stay searchable by the events that send them.
|
||||
expect(opts.find((o) => o.value === "published")!.keywords).toContain("release");
|
||||
});
|
||||
|
||||
it("offers the full action list when no event is known", () => {
|
||||
const opts = actionOptions("en", []);
|
||||
expect(opts.every((o) => o.group === undefined)).toBe(true);
|
||||
expect(values(opts)).toContain("label_updated");
|
||||
});
|
||||
|
||||
it("ranks field paths of the route's events first", () => {
|
||||
const opts = fieldPathOptions("en", ["workflow_run"]);
|
||||
const names = values(opts);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
expect(opts[0]!.value.startsWith("workflow_run.")).toBe(true);
|
||||
expect(opts.find((o) => o.value === "sender.login")!.group).toBe("All events");
|
||||
});
|
||||
|
||||
it("knows the values of enumerated fields", () => {
|
||||
expect(values(fieldValueOptions("en", "workflow_run.conclusion"))).toContain("failure");
|
||||
expect(values(fieldValueOptions("en", " pull_request.draft "))).toEqual(["true", "false"]);
|
||||
expect(fieldValueOptions("en", "comment.body")).toEqual([]);
|
||||
for (const path of ["review.state", "deployment_status.state", "alert.rule.severity"]) {
|
||||
expect(fieldValueOptions("zh", path).every((o) => !!o.hint)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("suggests values per filter type and none for free-form ones", () => {
|
||||
expect(values(valueOptions("en", "actor", "eq", "", []))).toContain("*[bot]");
|
||||
expect(values(valueOptions("en", "branch", "eq", "", []))).toContain("main");
|
||||
expect(valueOptions("en", "repo", "eq", "", [])).toEqual([]);
|
||||
expect(valueOptions("en", "keyword", "eq", "", [])).toEqual([]);
|
||||
});
|
||||
|
||||
it("turns glob suggestions into the literal text the operator compares", () => {
|
||||
const branch = (op: "startsWith" | "endsWith" | "contains"): string[] =>
|
||||
values(valueOptions("en", "branch", op, "", []));
|
||||
expect(branch("startsWith")).toContain("release/");
|
||||
expect(branch("startsWith")).not.toContain("release/*");
|
||||
expect(branch("endsWith")).not.toContain("release/");
|
||||
expect(branch("contains")).toContain("release/");
|
||||
const actor = (op: "startsWith" | "endsWith"): string[] =>
|
||||
values(valueOptions("en", "actor", op, "", []));
|
||||
expect(actor("endsWith")).toContain("[bot]");
|
||||
expect(actor("startsWith")).not.toContain("[bot]");
|
||||
});
|
||||
|
||||
it("offers regex suggestions that match exactly what the suggestion means", () => {
|
||||
const sender = (login: string): WebhookEvent => ({
|
||||
event: "push",
|
||||
payload: { sender: { login } },
|
||||
});
|
||||
const matches = (pattern: string, login: string): boolean =>
|
||||
evaluateFilterNode({ type: "actor", op: "regex", match: pattern }, sender(login));
|
||||
const actor = values(valueOptions("en", "actor", "regex", "", []));
|
||||
expect(actor).toEqual([
|
||||
"\\[bot\\]$",
|
||||
"^dependabot\\[bot\\]$",
|
||||
"^github-actions\\[bot\\]$",
|
||||
"^renovate\\[bot\\]$",
|
||||
]);
|
||||
for (const login of ["dependabot[bot]", "github-actions[bot]", "renovate[bot]"]) {
|
||||
expect(matches(actor[0]!, login)).toBe(true);
|
||||
expect(actor.slice(1).filter((p) => matches(p, login))).toHaveLength(1);
|
||||
}
|
||||
expect(matches("^dependabot\\[bot\\]$", "dependabotb")).toBe(false);
|
||||
expect(values(valueOptions("en", "branch", "regex", "", []))).toEqual([
|
||||
"^main$",
|
||||
"^master$",
|
||||
"^develop$",
|
||||
"^release/",
|
||||
]);
|
||||
// Anchored: `pull_request` must not also match `pull_request_review`.
|
||||
const events = values(valueOptions("en", "event", "regex", "", []));
|
||||
expect(events).toContain("^pull_request$");
|
||||
const review: WebhookEvent = { event: "pull_request_review", payload: {} };
|
||||
expect(
|
||||
evaluateFilterNode({ type: "event", op: "regex", match: "^pull_request$" }, review),
|
||||
).toBe(false);
|
||||
for (const pattern of events) {
|
||||
expect(validateFilterValue("event", "regex", pattern)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("offers no non-numeric suggestion to comparison operators", () => {
|
||||
expect(valueOptions("en", "field", "gt", "pull_request.draft", [])).toEqual([]);
|
||||
expect(valueOptions("en", "event", "lte", "", [])).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores typed event names that are not catalog entries", () => {
|
||||
for (const name of ["constructor", "__proto__", "toString"]) {
|
||||
const opts = actionOptions("en", [name]);
|
||||
expect(opts.every((o) => typeof o.value === "string")).toBe(true);
|
||||
expect(opts.every((o) => o.group === undefined)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateFilterValue", () => {
|
||||
it("accepts event names, globs and regexes", () => {
|
||||
expect(validateFilterValue("event", "eq", "pull_request")).toBeNull();
|
||||
expect(validateFilterValue("event", "eq", "pull_request*")).toBeNull();
|
||||
expect(validateFilterValue("event", "eq", "/^issue/")).toBeNull();
|
||||
expect(validateFilterValue("event", "eq", "pull request")).toBe("valid.event");
|
||||
expect(validateFilterValue("event", "eq", "/(/")).toBe("valid.regex");
|
||||
});
|
||||
|
||||
it("keeps repository and actor values free-form (custom webhooks carry any string)", () => {
|
||||
expect(validateFilterValue("repo", "eq", "acme/widget")).toBeNull();
|
||||
expect(validateFilterValue("repo", "eq", "monitoring/production cluster")).toBeNull();
|
||||
expect(validateFilterValue("actor", "eq", "*[bot]*")).toBeNull();
|
||||
expect(validateFilterValue("actor", "eq", "CI Agent")).toBeNull();
|
||||
});
|
||||
|
||||
it("checks branches and numbers", () => {
|
||||
expect(validateFilterValue("branch", "eq", "release/*")).toBeNull();
|
||||
expect(validateFilterValue("branch", "eq", "refs/tags/v*")).toBeNull();
|
||||
// code_scanning_alert carries the full ref, so refs/heads/... can match.
|
||||
expect(validateFilterValue("branch", "eq", "refs/heads/main")).toBeNull();
|
||||
expect(validateFilterValue("branch", "eq", "a:b")).toBe("valid.branch");
|
||||
expect(validateFilterValue("branch", "eq", "feature x")).toBe("valid.branch");
|
||||
expect(validateFilterValue("branch", "eq", "fix\tbug")).toBe("valid.branch");
|
||||
// Git allows non-ASCII whitespace inside refs.
|
||||
expect(validateFilterValue("branch", "eq", "release/版本\u30001")).toBeNull();
|
||||
expect(validateFilterValue("branch", "eq", "topic\u00a0a")).toBeNull();
|
||||
// `[` is literal for every operator; substring operators read `*`/`?` literally too.
|
||||
expect(validateFilterValue("branch", "eq", "release/[0-9]")).toBe("valid.branch");
|
||||
expect(validateFilterValue("branch", "eq", "/^release\\/[0-9]+$/")).toBeNull();
|
||||
expect(validateFilterValue("branch", "startsWith", "release/")).toBeNull();
|
||||
expect(validateFilterValue("branch", "startsWith", "release/*")).toBe("valid.branchLiteral");
|
||||
expect(validateFilterValue("branch", "contains", "a b")).toBe("valid.branchLiteral");
|
||||
expect(validateFilterValue("repo", "contains", "a*b")).toBeNull();
|
||||
expect(validateFilterValue("field", "gte", "10")).toBeNull();
|
||||
expect(validateFilterValue("field", "lt", "ten")).toBe("valid.number");
|
||||
});
|
||||
|
||||
it("treats the regex operator as a raw pattern and keyword as free text", () => {
|
||||
expect(validateFilterValue("repo", "regex", "^acme/")).toBeNull();
|
||||
expect(validateFilterValue("repo", "regex", "(")).toBe("valid.regex");
|
||||
expect(validateFilterValue("keyword", "exists", "any text")).toBeNull();
|
||||
expect(validateFilterValue("keyword", "eq", "/[/")).toBe("valid.regex");
|
||||
expect(validateFilterValue("action", "eq", "Deploy Docs")).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects patterns the server would never match", () => {
|
||||
expect(validateFilterValue("event", "eq", "a*".repeat(101))).toBe("valid.tooLong");
|
||||
expect(validateFilterValue("field", "regex", "a".repeat(201))).toBe("valid.tooLong");
|
||||
});
|
||||
});
|
||||
|
||||
describe("splitFilterValues", () => {
|
||||
it("splits on commas and lines", () => {
|
||||
expect(splitFilterValues("push, issues\nrelease,")).toEqual(["push", "issues", "release"]);
|
||||
expect(splitFilterValues(" , \r\n ")).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps the commas of a wrapped regex", () => {
|
||||
expect(splitFilterValues("main,/release-[0-9]{1,3}/")).toEqual([
|
||||
"main",
|
||||
"/release-[0-9]{1,3}/",
|
||||
]);
|
||||
expect(splitFilterValues("/a,b/ , /c/d,e/,f")).toEqual(["/a,b/", "/c/d,e/", "f"]);
|
||||
// An unterminated regex is ordinary text.
|
||||
expect(splitFilterValues("/a{1,2")).toEqual(["/a{1", "2"]);
|
||||
});
|
||||
|
||||
it("never closes a regex at an escaped slash or inside a character class", () => {
|
||||
expect(splitFilterValues("/[/,]/")).toEqual(["/[/,]/"]);
|
||||
expect(splitFilterValues("/a\\/,b/,c")).toEqual(["/a\\/,b/", "c"]);
|
||||
expect(splitFilterValues("/[\\]/,]x/")).toEqual(["/[\\]/,]x/"]);
|
||||
});
|
||||
|
||||
it("splits raw regex patterns on lines only", () => {
|
||||
expect(splitFilterValues("^v{1,3}$\n[a,b]", false)).toEqual(["^v{1,3}$", "[a,b]"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("convertValuesForOp", () => {
|
||||
// Branch names and payload text, including line breaks and Unicode case
|
||||
// variants (Kelvin sign, final sigma) that literal and regex comparisons fold
|
||||
// differently.
|
||||
const subjects = [
|
||||
"main",
|
||||
" main ",
|
||||
"Main",
|
||||
"mainline",
|
||||
"release/v1",
|
||||
"release/a\u2028b",
|
||||
"build\nagent",
|
||||
"please run ci\nthanks",
|
||||
"\u212A",
|
||||
"k",
|
||||
"\u03C2",
|
||||
"\u03A3",
|
||||
];
|
||||
const actor = (login: string): WebhookEvent => ({
|
||||
event: "push",
|
||||
payload: { sender: { login } },
|
||||
});
|
||||
/** Subjects the condition matches once saved (the form trims every value). */
|
||||
const matched = (op: FilterOp, value: string): string[] => {
|
||||
const filter = formToLeaf({
|
||||
type: "actor",
|
||||
path: "",
|
||||
op,
|
||||
values: [value],
|
||||
exclude: false,
|
||||
draft: "",
|
||||
});
|
||||
return filter ? subjects.filter((s) => evaluateFilterNode(filter, actor(s))) : [];
|
||||
};
|
||||
|
||||
it("swaps a wrapped regex and the raw regex, which match exactly the same", () => {
|
||||
const cases: Array<[FilterOp, FilterOp, string, string]> = [
|
||||
["eq", "regex", "/^main/", "^main"],
|
||||
["ne", "regex", "/ci$/", "ci$"],
|
||||
["in", "regex", "/k/", "k"],
|
||||
["eq", "regex", "/\u03A3/", "\u03A3"],
|
||||
["regex", "eq", "^release/", "/^release//"],
|
||||
["regex", "in", "run ci", "/run ci/"],
|
||||
["regex", "eq", "/api/", "//api//"],
|
||||
];
|
||||
for (const [from, to, value, expected] of cases) {
|
||||
const [converted] = convertValuesForOp([value], from, to);
|
||||
expect(converted).toBe(expected);
|
||||
// `ne` negates per value; compare the value's own matches through `eq`.
|
||||
const plain = (op: FilterOp): FilterOp => (op === "ne" ? "eq" : op);
|
||||
expect(matched(plain(to), converted!)).toEqual(matched(plain(from), value));
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps wrapped sources that saving would change", () => {
|
||||
// Saving trims values: `/ main /` must not become `main`, nor `//` empty.
|
||||
for (const value of ["/ main /", "/main /", "//"]) {
|
||||
expect(convertValuesForOp([value], "eq", "regex")).toEqual([value]);
|
||||
}
|
||||
expect(matched("eq", "/ main /")).toEqual([" main "]);
|
||||
expect(convertValuesForOp([" "], "regex", "eq")).toEqual([" "]);
|
||||
});
|
||||
|
||||
it("keeps every other value as typed", () => {
|
||||
// Literal, glob and substring values have no exact regex equivalent.
|
||||
const values = ["main", "release/*", "*[bot]", "k"];
|
||||
const pairs: Array<[FilterOp, FilterOp]> = [
|
||||
["eq", "regex"],
|
||||
["eq", "startsWith"],
|
||||
["contains", "eq"],
|
||||
["contains", "regex"],
|
||||
["gt", "eq"],
|
||||
["eq", "ne"],
|
||||
];
|
||||
for (const [from, to] of pairs) expect(convertValuesForOp(values, from, to)).toEqual(values);
|
||||
expect(convertValuesForOp(["/x/"], "eq", "contains")).toEqual(["/x/"]);
|
||||
expect(convertValuesForOp(["^main"], "regex", "startsWith")).toEqual(["^main"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("commaEndsValue", () => {
|
||||
it("ends a value only when the comma is typed at its end", () => {
|
||||
expect(commaEndsValue("push", 4, 4)).toBe(true);
|
||||
expect(commaEndsValue("push ", 5, 5)).toBe(true);
|
||||
expect(commaEndsValue("push", 2, 2)).toBe(false);
|
||||
// Typing over a selection replaces it, like any other character.
|
||||
expect(commaEndsValue("push", 0, 4)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps commas inside a regex that is still open", () => {
|
||||
expect(commaEndsValue("/a{1", 4, 4)).toBe(false);
|
||||
expect(commaEndsValue("/[/", 3, 3)).toBe(false);
|
||||
expect(commaEndsValue("/a{1,3}/", 8, 8)).toBe(true);
|
||||
// Editing a finished regex: the caret sits inside it.
|
||||
expect(commaEndsValue("/a{13}/", 4, 4)).toBe(false);
|
||||
});
|
||||
|
||||
it("never ends raw patterns", () => {
|
||||
expect(commaEndsValue("^v{1", 4, 4, false)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isArrayFieldPath", () => {
|
||||
it("flags suggested paths that end on an array", () => {
|
||||
expect(isArrayFieldPath("commits.modified")).toBe(true);
|
||||
expect(isArrayFieldPath(" repository.topics ")).toBe(true);
|
||||
expect(isArrayFieldPath("commits.message")).toBe(false);
|
||||
expect(isArrayFieldPath("build status")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import {
|
||||
blankNode,
|
||||
formToLeaf,
|
||||
hasPendingDraft,
|
||||
isBlankNode,
|
||||
nodeKey,
|
||||
nodeToForm,
|
||||
scopeEvents,
|
||||
} from "../app/composables/useFilterNode";
|
||||
import type { LeafForm } from "../app/composables/useFilterNode";
|
||||
|
||||
function leaf(overrides: Partial<LeafForm>): LeafForm {
|
||||
return {
|
||||
type: "event",
|
||||
path: "",
|
||||
op: "eq",
|
||||
values: [],
|
||||
exclude: false,
|
||||
draft: "",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("scopeEvents", () => {
|
||||
it("collects exact event names the route positively filters on", () => {
|
||||
const form = nodeToForm({
|
||||
all: [
|
||||
{ type: "event", match: ["pull_request", "Issues"] },
|
||||
{
|
||||
any: [
|
||||
{ type: "event", match: "release" },
|
||||
{ type: "repo", match: "acme/*" },
|
||||
],
|
||||
},
|
||||
{ type: "event", match: "push", exclude: true },
|
||||
{ not: { type: "event", match: "star" } },
|
||||
{ type: "event", match: "check_*" },
|
||||
{ type: "event", op: "ne", match: "fork" },
|
||||
],
|
||||
});
|
||||
expect(scopeEvents(form).sort()).toEqual(["issues", "pull_request", "release"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isBlankNode", () => {
|
||||
it("treats untouched conditions and groups as blank", () => {
|
||||
expect(isBlankNode(blankNode("leaf"))).toBe(true);
|
||||
expect(isBlankNode(blankNode("all"))).toBe(true);
|
||||
expect(isBlankNode(blankNode("not"))).toBe(true);
|
||||
});
|
||||
|
||||
it("treats any value, path or negation as content", () => {
|
||||
const withValue = blankNode("all");
|
||||
withValue.children[0]!.leaf.values = ["push"];
|
||||
expect(isBlankNode(withValue)).toBe(false);
|
||||
const negated = blankNode("leaf");
|
||||
negated.leaf.exclude = true;
|
||||
expect(isBlankNode(negated)).toBe(false);
|
||||
const withPath = blankNode("leaf");
|
||||
withPath.leaf.path = "sender.login";
|
||||
expect(isBlankNode(withPath)).toBe(false);
|
||||
// `exists` is a complete condition without any value.
|
||||
const exists = blankNode("all");
|
||||
exists.children[0]!.leaf.type = "branch";
|
||||
exists.children[0]!.leaf.op = "exists";
|
||||
expect(isBlankNode(exists)).toBe(false);
|
||||
// Typed text not added yet is content as well.
|
||||
const typed = blankNode("not");
|
||||
typed.child!.leaf.draft = "my_event";
|
||||
expect(isBlankNode(typed)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasPendingDraft", () => {
|
||||
it("finds unadded text anywhere in the tree", () => {
|
||||
const form = nodeToForm({ all: [{ type: "event", match: "push" }, { not: { type: "repo" } }] });
|
||||
expect(hasPendingDraft(form)).toBe(false);
|
||||
form.children[1]!.child!.leaf.draft = " ";
|
||||
expect(hasPendingDraft(form)).toBe(false);
|
||||
form.children[1]!.child!.leaf.draft = "acme/*";
|
||||
expect(hasPendingDraft(form)).toBe(true);
|
||||
});
|
||||
|
||||
it("follows the leaf when a NOT is unwrapped or the root is wrapped", () => {
|
||||
const not = blankNode("not");
|
||||
not.child!.leaf.draft = "my_event";
|
||||
// What FilterNodeEditor's unwrap and RouteEditor's fragment insert do.
|
||||
const unwrapped = { ...not, kind: not.child!.kind, leaf: not.child!.leaf };
|
||||
expect(hasPendingDraft(unwrapped)).toBe(true);
|
||||
const wrapped = { ...blankNode("all"), children: [unwrapped, blankNode("leaf")] };
|
||||
expect(hasPendingDraft(wrapped)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formToLeaf", () => {
|
||||
it("never stores an operator on keyword filters", () => {
|
||||
expect(formToLeaf(leaf({ type: "keyword", op: "exists", values: ["hotfix"] }))).toEqual({
|
||||
type: "keyword",
|
||||
match: "hotfix",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps operators on other filters", () => {
|
||||
expect(formToLeaf(leaf({ type: "field", path: "pull_request.draft", op: "exists" }))).toEqual({
|
||||
type: "field",
|
||||
path: "pull_request.draft",
|
||||
op: "exists",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("nodeKey", () => {
|
||||
it("is stable per node and unique across nodes", () => {
|
||||
const a = blankNode("leaf");
|
||||
const b = blankNode("leaf");
|
||||
expect(nodeKey(a)).toBe(nodeKey(a));
|
||||
expect(nodeKey(a)).not.toBe(nodeKey(b));
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user