import type { Ctx } from '@milkdown/kit/ctx' type MenuItem = { index: number key: string onRun?: (ctx: Ctx) => void } & T type WithRange = HasIndex extends true ? T & { range: [start: number, end: number] } : T export type MenuItemGroup = WithRange< { key: string label: string items: HasIndex extends true ? MenuItem[] : Omit, 'index'>[] }, HasIndex > export class GroupBuilder { #groups: MenuItemGroup[] = [] clear = () => { this.#groups = [] return this } #getGroupInstance = (group: MenuItemGroup) => { const groupInstance = { group, addItem: (key: string, item: Omit, 'key' | 'index'>) => { const data = { ...item, key } as MenuItem group.items.push(data) return groupInstance }, clear: () => { group.items = [] return groupInstance }, } return groupInstance } addGroup = (key: string, label: string) => { const items: Omit, 'index'>[] = [] const group: MenuItemGroup = { key, label, items, } this.#groups.push(group) return this.#getGroupInstance(group) } getGroup = (key: string) => { const group = this.#groups.find((group) => group.key === key) if (!group) throw new Error(`Group with key ${key} not found`) return this.#getGroupInstance(group) } build = () => { return this.#groups } }