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.
This commit is contained in:
翅膀 committed 2026-10-17 06:29:41 +08:00
1 parent 2ebce8495d
commit d693f70612
10 files changed
+557 -190

No files matched your search

+2 -2
View File
@@ -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
@@ -38,7 +38,7 @@ app/ # Vue 3 UI (Nuxt app dir)
├── pages/ # index (landing), terms, privacy, admin/[...slug] (console SPA)
├── components/ # ConsolePage (sidebar shell + topbar), AdminHome (overview dashboard),
│ # RouteList (drag/keyboard reorder mode) + RouteCard, RouteEditor (FilterNodeEditor
│ # AST builder + TagInput chips), GroupEditor, MembersPanel, WebhookPanel,
│ # 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), useGroups, useGroupRoutes, useFilterNode (AST helpers), useFragments, useLogs,
+115 -50
View File
@@ -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;
@@ -610,10 +590,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;
@@ -1021,66 +997,155 @@
}
}
/* ---- 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];
}
+198 -109
View File
@@ -1,7 +1,15 @@
<script setup lang="ts">
import { Plus, Trash2 } from "lucide-vue-next";
import type { NodeForm } from "~/composables/useFilterNode";
import { blankNode, isBlankNode } 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 {
fieldPathOptions,
isArrayFieldPath,
validateFilterValue,
valueOptions,
} from "~/utils/filter-catalog";
defineOptions({ name: "FilterNodeEditor" });
@@ -12,20 +20,80 @@ 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 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);
}
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") props.node.leaf.op = "eq";
}
}
function setOp(value: string): void {
if (FILTER_OPS.includes(value as FilterOp)) {
props.node.leaf.op = 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") {
props.node.leaf.op = "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));
}
@@ -40,6 +108,7 @@ function unwrapNot(): void {
}
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:
@@ -53,99 +122,108 @@ async function remove(): Promise<void> {
<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="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">
<RcSelect
: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">
<RcSelect
: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"
: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="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
@@ -153,27 +231,38 @@ async function remove(): Promise<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="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" />
+62 -7
View File
@@ -1,16 +1,20 @@
<script setup lang="ts">
import { computed, nextTick, 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";
@@ -27,7 +31,7 @@ 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);
@@ -65,6 +69,11 @@ 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 fragmentName = ref("");
@@ -75,6 +84,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;
@@ -99,11 +109,21 @@ async function removeTarget(target: TargetForm): Promise<void> {
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") {
@@ -118,6 +138,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 = "";
@@ -184,6 +210,12 @@ function collect(): Route | null {
}
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 null;
if (!/^[a-z0-9][a-z0-9-]*$/.test(route.id)) {
@@ -240,6 +272,15 @@ 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");
@@ -287,6 +328,11 @@ async function saveAsFragment(): Promise<void> {
return;
}
if (!props.groupId) return;
const problem = filterTreeError();
if (problem) {
fragmentError.value = problem;
return;
}
const node = formToNode(root.value);
if (!node) {
fragmentError.value = t("routeEditor.errAddFilter");
@@ -440,8 +486,17 @@ watch(
<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
-15
View File
@@ -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>
+66 -6
View File
@@ -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,29 @@ 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
@@ -124,13 +175,22 @@ export function nodeFormToRouteFilters(nf: NodeForm): { filters: Filter[]; ast?:
*/
export function isBlankNode(nf: NodeForm): boolean {
if (nf.kind === "leaf") {
const { exclude, op, path, values } = nf.leaf;
return !exclude && op === "eq" && !path.trim() && values.every((v) => !v.trim());
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 => {
+16
View File
@@ -261,7 +261,14 @@ 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.pathPlaceholder": "payload.path",
"routeEditor.valuesPlaceholder": "Type a value and press Enter",
@@ -272,6 +279,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",
@@ -685,7 +693,14 @@ 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.pathPlaceholder": "payload.path",
"routeEditor.valuesPlaceholder": "输入值后回车",
@@ -696,6 +711,7 @@ const zh: Dict = {
"routeEditor.testMatched": "匹配",
"routeEditor.testNotMatched": "不匹配",
"routeEditor.testInvalidJson": "无效的 JSON",
"routeEditor.testEventInvalid": "请先修正或清空事件类型",
"routeEditor.fragments": "过滤器片段",
"routeEditor.fragmentsPresets": "预设",
"routeEditor.fragmentsEmpty": "暂无片段",
+2
View File
@@ -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. 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.
+2
View File
@@ -256,6 +256,8 @@
当 `ast` 存在时,它优先于 `filters`。管理后台的路由编辑器会以可视化方式构建 `ast`(all/any/not 分组)、实时展示树状解释,并可通过「测试匹配」面板粘贴 JSON 载荷进行试匹配。
匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 GitHub 与 Gitea 的 webhook 定义——事件、路由所选事件的动作、常用载荷路径及其已知取值——以英文 key 展示,并附当前界面语言的说明;搜索优先匹配 key,其次匹配英文或中文说明。列表之外的值仍可直接输入,添加前会按匹配规则校验,只拒绝永远不可能匹配的值(含空格的事件名、含 git 禁用字符的分支、无效的正则、比较运算中的非数字等);仓库与操作者不做格式限制,因为自定义 webhook 可以携带任意字符串。已输入但未按<kbd>回车</kbd>添加的内容会阻止保存路由、存为片段和测试匹配,而不会被静默添加或丢弃。`field` 路径中途的数组会被展开,但以数组**结尾**的路径(如 `commits.modified`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。
### 命名过滤器片段
路由编辑器可将当前过滤器树保存为**命名片段**并插入其他路由。片段是编辑器侧的模板,存储在 D1(`d1_fragments`)中;插入片段会将其节点内联进路由的 `ast`,因此匹配引擎本身从不解析片段引用。
+94 -1
View File
@@ -1,5 +1,47 @@
import { describe, it, expect } from "bun:test";
import { blankNode, isBlankNode } from "../app/composables/useFilterNode";
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", () => {
@@ -23,5 +65,56 @@ describe("isBlankNode", () => {
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));
});
});