// oxlint-disable typescript/no-explicit-any import type { BaseInputorContext, BaseInputorControllerOptions, BaseInputorSchema, InputorControllerInitializeHooks, } from "./base.ts" import { BaseInputorController } from "./base.ts" export const SELECT_INPUTOR_TYPE_NAME = "select" as const export type SelectInputorTypeName = typeof SELECT_INPUTOR_TYPE_NAME export interface SelectOption { name: string label: string value: Value isSelected: boolean description?: string | undefined isDisabled?: boolean | undefined } export type SelectOptions = Array> export type SelectInputorExternalValue = SelectOptions export type SelectInputorInternalValue = SelectOptions export interface SelectInputorSchema extends BaseInputorSchema< SelectInputorExternalValue > { inputorTypeName: SelectInputorTypeName } export interface SelectInputorContext extends BaseInputorContext< SelectInputorExternalValue, SelectInputorInternalValue > {} export interface SelectInputorControllerOptions extends BaseInputorControllerOptions< SelectInputorExternalValue, SelectInputorSchema > { /** * @description 是否允许取消选择。 * * @default false */ enableUnselect?: boolean } export class SelectInputorController extends BaseInputorController< SelectInputorExternalValue, SelectInputorInternalValue, SelectInputorSchema, SelectInputorContext > { declare schemaType: SelectInputorSchema declare optionsType: SelectInputorControllerOptions declare constructorType: typeof SelectInputorController static inputorTypeName: SelectInputorTypeName = SELECT_INPUTOR_TYPE_NAME inputorTypeName: SelectInputorTypeName = SELECT_INPUTOR_TYPE_NAME voidExternalValue = [] as SelectInputorExternalValue voidInternalValue = [] as SelectInputorInternalValue private enableUnselect!: boolean constructor(options: SelectInputorControllerOptions) { super(options) } protected override async initialize( options: SelectInputorControllerOptions, hooks?: InputorControllerInitializeHooks, ): Promise { await super.initialize(options, { ...hooks, onSchemaReady: async () => { this.enableUnselect = options.enableUnselect ?? false await hooks?.onSchemaReady?.() }, }) } async select(name: string): Promise { if (this.isDisabled === true) { return } const internalValue = this.getInternalValue() const disabledSelectedName = internalValue.find((option) => { return option.isSelected && option.isDisabled === true })?.name const updatedInternalValue = internalValue.map((option) => { const { name: optionName, isSelected: _isSelected, isDisabled } = option if (disabledSelectedName !== undefined) { return { ...option, isSelected: optionName === disabledSelectedName, } } if (isDisabled === true) { return option } if (optionName !== name) { return { ...option, isSelected: false, } } return { ...option, isSelected: this.enableUnselect ? !option.isSelected : true, } }) await this.updateInternalValue(updatedInternalValue) } }