diff --git a/app/components/FilterCombobox.vue b/app/components/FilterCombobox.vue index 5d16d11..5b974f2 100644 --- a/app/components/FilterCombobox.vue +++ b/app/components/FilterCombobox.vue @@ -47,6 +47,7 @@ @keydown="onKeydown" @focus="focused = true" @blur="onBlur" + @paste="onPaste" /> @@ -126,6 +127,7 @@ import { 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 @@ -153,6 +155,11 @@ const props = withDefaults( * 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, @@ -162,6 +169,7 @@ const props = withDefaults( label: "", mono: true, draft: "", + splitOnComma: true, }, ); @@ -407,10 +415,46 @@ function onKeydown(event: KeyboardEvent): void { } 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; +} diff --git a/app/components/FilterNodeEditor.vue b/app/components/FilterNodeEditor.vue index 1aa47db..1c89cb9 100644 --- a/app/components/FilterNodeEditor.vue +++ b/app/components/FilterNodeEditor.vue @@ -164,6 +164,7 @@ async function remove(): Promise { multiple creatable :validate="validateValue" + :split-on-comma="node.leaf.op !== 'regex'" :draft="node.leaf.draft" :placeholder="t('routeEditor.valuesPlaceholder')" :label="t('routeEditor.values')" diff --git a/app/utils/filter-catalog.ts b/app/utils/filter-catalog.ts index 53e38cf..c1a6e24 100644 --- a/app/utils/filter-catalog.ts +++ b/app/utils/filter-catalog.ts @@ -1161,6 +1161,60 @@ function isWrappedRegex(value: string): boolean { return value.length >= 2 && value.startsWith("/") && value.endsWith("/"); } +/** + * Length of the `/regex/` that `text` starts with: up to the first closing + * `/` followed by a comma or the end of the text, or -1 while it is still + * open. Escaped slashes (`\/`) and slashes in a character class (`[/,]`) + * never close it. + */ +function wrappedRegexLength(text: string): number { + if (!text.startsWith("/")) return -1; + let inClass = false; + for (let i = 1; i < text.length; i++) { + const char = text[i]; + if (char === "\\") i++; + else if (inClass) inClass = char !== "]"; + else if (char === "[") inClass = true; + else if (char === "/" && /^\s*(?:,|$)/.test(text.slice(i + 1))) return i + 1; + } + return -1; +} + +/** + * Split typed or pasted text into match values: one per line and, unless + * `commas` is off (the raw `regex` operator), one per comma. A `/regex/` + * keeps its own commas (`/v{1,3}/`, `/[/,]/`). + */ +export function splitFilterValues(text: string, commas = true): string[] { + const out: string[] = []; + for (const line of text.split(/\r?\n/)) { + if (!commas) { + out.push(line); + continue; + } + let rest = line.trimStart(); + while (rest) { + const regexLength = wrappedRegexLength(rest); + const token = regexLength > 0 ? rest.slice(0, regexLength) : rest.split(",", 1)[0]!; + out.push(token); + rest = rest.slice(token.length).replace(/^\s*,/, "").trimStart(); + } + } + return out.map((v) => v.trim()).filter(Boolean); +} + +/** + * Whether a comma typed over `text[start, end)` ends the value being typed — + * only when typed at its end (no selection) and outside an open `/regex/`. + * Anywhere else the comma is part of the text; raw patterns (`commas` off) + * keep every comma. + */ +export function commaEndsValue(text: string, start: number, end: number, commas = true): boolean { + if (!commas || start !== end || text.slice(end).trim()) return false; + const value = text.slice(0, start).trim(); + return !value.startsWith("/") || wrappedRegexLength(value) === value.length; +} + function isGlob(value: string): boolean { return value.includes("*") || value.includes("?"); } diff --git a/docs/guide/filters.md b/docs/guide/filters.md index edff881..8e09a9e 100644 --- a/docs/guide/filters.md +++ b/docs/guide/filters.md @@ -256,7 +256,7 @@ 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 Enter 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. +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 Enter 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). 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 diff --git a/docs/zh/guide/filters.md b/docs/zh/guide/filters.md index cb081f9..e5c7c72 100644 --- a/docs/zh/guide/filters.md +++ b/docs/zh/guide/filters.md @@ -256,7 +256,7 @@ 当 `ast` 存在时,它优先于 `filters`。管理后台的路由编辑器会以可视化方式构建 `ast`(all/any/not 分组)、实时展示树状解释,并可通过「测试匹配」面板粘贴 JSON 载荷进行试匹配。 -匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 GitHub 与 Gitea 的 webhook 定义——事件、路由所选事件的动作、常用载荷路径及其已知取值——以英文 key 展示,并附当前界面语言的说明;搜索优先匹配 key,其次匹配英文或中文说明。列表之外的值仍可直接输入,添加前会按匹配规则校验,只拒绝永远不可能匹配的值(含空格的事件名、含 git 禁用字符的分支、无效的正则、比较运算中的非数字等);仓库与操作者不做格式限制,因为自定义 webhook 可以携带任意字符串。已输入但未按回车添加的内容会阻止保存路由、存为片段和测试匹配,而不会被静默添加或丢弃。`field` 路径中途的数组会被展开,但以数组**结尾**的路径(如 `commits.modified`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。 +匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 GitHub 与 Gitea 的 webhook 定义——事件、路由所选事件的动作、常用载荷路径及其已知取值——以英文 key 展示,并附当前界面语言的说明;搜索优先匹配 key,其次匹配英文或中文说明。列表之外的值仍可直接输入,添加前会按匹配规则校验,只拒绝永远不可能匹配的值(含空格的事件名、含 git 禁用字符的分支、无效的正则、比较运算中的非数字等);仓库与操作者不做格式限制,因为自定义 webhook 可以携带任意字符串。已输入但未按回车添加的内容会阻止保存路由、存为片段和测试匹配,而不会被静默添加或丢弃。可一次输入或粘贴多个值,以逗号或换行分隔;`/正则/` 内的逗号会保留,选择「正则匹配」运算符时只按换行分隔(如 `^v{1,3}` 这样的原始模式可以包含逗号)。`field` 路径中途的数组会被展开,但以数组**结尾**的路径(如 `commits.modified`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。 ### 命名过滤器片段 diff --git a/tests/filter-catalog.test.ts b/tests/filter-catalog.test.ts index 7947def..1f68c36 100644 --- a/tests/filter-catalog.test.ts +++ b/tests/filter-catalog.test.ts @@ -1,6 +1,8 @@ import { describe, it, expect } from "bun:test"; import { actionOptions, + commaEndsValue, + splitFilterValues, eventOptions, fieldPathOptions, fieldValueOptions, @@ -142,6 +144,55 @@ describe("validateFilterValue", () => { }); }); +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("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);