File size: 12,252 Bytes
71174bc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | <template>
<div class="form-list-select-wrapper">
<div class="custom-input-group">
<div class="input-wrapper">
<FormInput :id="id" v-model="textValue" type="text" :placeHolder="placeHolder" :disabled="disabled"
:filterFunc="null" :warningFunc="null" :description="undefined"
:delayBetweenChangesDetected="delayBetweenChangesDetected" @update:modelValue="handleTextInput"
:ariaDescribedBy="id + '-dropdown-button'" />
</div>
<button v-if="options && options.length > 0"
:class="`btn btn-primary dropdown-toggle btn-sm custom-add-button ${disabled ? 'disabled' : ''}`"
type="button" :id="id + '-dropdown-button'" data-bs-toggle="dropdown" aria-expanded="false"
:disabled="disabled">
Add
</button>
<ul v-if="options && options.length > 0"
class="dropdown-menu dropdown-menu-end form-list-select-dropdown-menu"
:aria-labelledby="id + '-dropdown-button'">
<li v-for="option in actualOptions" :key="option.val">
<hr v-if="option.val === '--separator--'" class="dropdown-divider" />
<a v-else :class="`dropdown-item ${option.disabled ? 'disabled' : ''}`"
@click.prevent="handleDropdownItemClick(option)">
{{ option.description }}
</a>
</li>
</ul>
</div>
<FormElementDescription :description="description" :warning="currentWarningMessage" :validate="false" />
</div>
</template>
<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { Prop, Watch } from "vue-property-decorator";
import { IUserArgOption } from "./FormFull/FormFullInterfaces";
import { formInputDelayUpdate } from "@/Core/GlobalVars";
import FormInput from "./FormInput.vue";
// FormSelect is no longer directly used in the template
// import FormSelect from "./FormSelect.vue";
import FormElementDescription from "./FormElementDescription.vue";
interface ParsedListResult {
parsedList: string[] | number[];
isValid: boolean;
}
/**
* FormListSelect component allows users to input a list of items (text or
* numbers, with support for numeric ranges) via a text field. Optionally, a
* dropdown can be provided to append predefined items to the list.
*/
@Options({
components: {
FormInput,
// FormSelect, // No longer used here
FormElementDescription,
},
emits: ["update:modelValue", "onChange", "onRawValChange"],
})
export default class FormListSelect extends Vue {
/**
* The current list value, as an array of strings or numbers. This is the
* v-model prop.
*
* @type {(string[] | number[])}
* @required
*/
@Prop({ required: true }) modelValue!: string[] | number[];
/**
* A unique identifier for the form element.
*
* @type {string}
* @required
*/
@Prop({ required: true }) id!: string;
/**
* Specifies the type of items in the list: 'text' or 'number'. If 'number',
* the input supports numeric ranges (e.g., "1-5").
*
* @type {('text' | 'number')}
* @default 'text'
*/
@Prop({ default: 'text' }) inputType!: 'text' | 'number';
/**
* An optional array of predefined options for the dropdown select. Each
* option can be a string or an IUserArgOption object.
*
* @type {(string | IUserArgOption)[]}
*/
@Prop({ default: () => [] }) options!: (string | IUserArgOption)[];
/**
* A description of the form element, displayed below the input fields.
*
* @type {string}
*/
@Prop({ default: "" }) description!: string;
/**
* If true, disables the input fields.
*
* @type {boolean}
* @default false
*/
@Prop({ default: false }) disabled!: boolean;
/**
* Placeholder text for the text input field.
*
* @type {string}
* @default "Enter items, comma or space separated..."
*/
@Prop({ default: "Enter items, comma or space separated..." }) placeHolder!: string;
/**
* A function that returns a warning message string based on the current
* list value.
*
* @type {Function}
*/
@Prop({ default: null }) warningFunc!: ((val: string[] | number[]) => string) | null;
/**
* A function that validates the current list value.
*
* @type {Function}
*/
@Prop({ default: null }) validateFunc!: ((val: string[] | number[]) => boolean) | null;
/**
* Delay in milliseconds after input before triggering change detection for
* the text input.
*
* @type {number}
* @default formInputDelayUpdate
*/
@Prop({ default: formInputDelayUpdate }) delayBetweenChangesDetected!: number;
private textValue = "";
private isInputValid = true; // Tracks internal parsing validity
private currentWarningMessage = "";
/**
* Lifecycle hook called when the component is created. Initializes
* `textValue` from `modelValue`.
*/
created() {
this.updateTextValueFromModelValue(this.modelValue);
this.updateWarning();
}
/**
* Watcher for the `modelValue` prop. Updates `textValue` if `modelValue`
* changes externally.
*
* @param {string[] | number[]} newValue The new `modelValue`.
*/
@Watch("modelValue")
onModelValueChanged(newValue: string[] | number[]): void {
const { parsedList: currentParsedValue } = this.parseTextToList(this.textValue);
// Avoid feedback loop if the change originated from textValue internal update
if (JSON.stringify(newValue) !== JSON.stringify(currentParsedValue)) {
this.updateTextValueFromModelValue(newValue);
}
this.updateWarning();
}
/**
* Converts the `modelValue` (list) to a string and updates `textValue`.
*
* @param {string[] | number[]} listValue The list value.
*/
private updateTextValueFromModelValue(listValue: string[] | number[]): void {
this.textValue = listValue.join(', ');
}
/**
* Parses the text from the input field into a list of strings or numbers.
* Also determines if the entire input string was valid.
*
* @param {string} text The text to parse.
* @returns {ParsedListResult} An object containing the parsed list and a boolean indicating validity.
*/
private parseTextToList(text: string): ParsedListResult {
const trimmedText = text.trim();
let isValid = true;
if (trimmedText === "") {
return { parsedList: [], isValid: true };
}
this.$emit("onRawValChange", trimmedText); // Emit the raw string value
const parts = trimmedText.split(/[\s,]+/).map(s => s.trim()).filter(s => s.length > 0);
if (this.inputType === 'number') {
// A number. Could be a range.
const numericSet = new Set<number>();
for (const part of parts) {
if (part.includes("-")) {
const [startStr, endStr] = part.split("-");
const start = parseInt(startStr, 10);
const end = parseInt(endStr, 10);
if (!isNaN(start) && !isNaN(end) && start <= end) {
for (let i = start; i <= end; i++) {
numericSet.add(i);
}
} else {
isValid = false; // Invalid range or non-numeric parts
}
} else {
const num = parseInt(part, 10);
if (!isNaN(num)) {
numericSet.add(num);
} else {
isValid = false; // Non-numeric part
}
}
}
return { parsedList: Array.from(numericSet).sort((a, b) => a - b), isValid };
} else { // 'text'
const stringSet = new Set<string>();
parts.forEach(part => stringSet.add(part));
// For text input, parsing itself doesn't really "fail" unless specific rules were added.
// Assuming any non-empty part is a valid text item.
return { parsedList: Array.from(stringSet), isValid: true };
}
}
/**
* Handles input from the text field. Updates `textValue` and emits the parsed list.
* If parsing is not valid, emits an empty list to signal invalidity to FormFull.
*/
private handleTextInput(): void {
// textValue is already updated by v-model on FormInput
const { parsedList, isValid } = this.parseTextToList(this.textValue);
this.isInputValid = isValid;
if (!this.isInputValid) {
this.$emit("update:modelValue", []); // Emit empty list on parsing error
} else {
this.$emit("update:modelValue", parsedList);
}
this.$emit("onChange", this.isInputValid ? parsedList : []);
this.updateWarning();
}
/**
* Computed property for dropdown options, ensuring they are in IUserArgOption format.
*
* @returns {IUserArgOption[]} The options for the dropdown menu.
*/
get actualOptions(): IUserArgOption[] {
return this.options.map(opt =>
typeof opt === 'string' ? { description: opt, val: opt, disabled: false } : { ...opt, disabled: opt.disabled === true }
);
}
/**
* Handles selection from the dropdown. Appends the selected value to
* `textValue`.
*
* @param {IUserArgOption} selectedOption The option selected from the dropdown.
*/
private handleDropdownItemClick(selectedOption: IUserArgOption): void {
if (selectedOption.disabled) {
return;
}
const selectedValue = String(selectedOption.val); // Ensure it's a string
if (this.textValue.trim() === "") {
this.textValue = selectedValue;
} else {
// Check if the value already exists in the text input before appending
const currentListResult = this.parseTextToList(this.textValue);
const valueExists = currentListResult.parsedList.some(item => String(item) === selectedValue);
if (!valueExists) {
this.textValue += `, ${selectedValue}`;
}
}
this.handleTextInput(); // Process the updated textValue
// The dropdown will close automatically due to Bootstrap behavior.
}
/**
* Updates the warning message based on the `isInputValid` state and
* `warningFunc` prop.
*/
private updateWarning(): void {
if (!this.isInputValid) {
this.currentWarningMessage = "Invalid input. Please check list format (e.g., for numbers: 1, 2, 3-5).";
} else if (this.warningFunc) {
this.currentWarningMessage = this.warningFunc(this.modelValue);
} else {
this.currentWarningMessage = "";
}
}
}
</script>
<style scoped lang="scss">
.form-list-select-wrapper {
display: block;
width: 100%;
}
.custom-input-group {
display: flex;
width: 100%;
position: relative;
}
.input-wrapper {
flex: 1;
min-width: 0;
// Force the FormInput component to take full width
:deep(.form-control),
:deep(input) {
width: 100% !important;
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
// Ensure the entire FormInput component wrapper takes full width
:deep(.form-group),
:deep(.input-group),
:deep(div) {
width: 100% !important;
margin-bottom: 0 !important;
}
}
.custom-add-button {
flex-shrink: 0;
border-top-left-radius: 0 !important;
border-bottom-left-radius: 0 !important;
border-left: 0;
margin-left: -1px;
}
/* Styling for the dropdown menu itself to make it scrollable */
.form-list-select-dropdown-menu {
max-height: 300px;
overflow-y: auto;
overflow-x: hidden;
}
</style> |