Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 | 93x 132x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 93x 438x 438x 93x 118x 118x 118x 118x 93x 93x 985x 985x 985x 985x 35x 35x 5x 5x 35x 30x 30x 30x 30x 93x 93x 93x 17x 17x 17x 22x 22x 22x 22x 22x 22x 22x 22x 93x 93x 93x 93x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 282x 282x 282x 282x 5x 5x 5x 5x 5x 282x 277x 146x 146x 146x 208x 131x 131x 131x 131x 131x 131x 131x 131x 131x 136x 131x 136x 136x 136x 136x 5x 136x 136x 62x 5x 5x 5x 5x 5x 136x 5x 5x 62x 5x 136x 5x 62x 62x 62x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 136x 136x 136x 93x 135x 135x 4x 4x 4x 4x 4x 4x 4x 4x 135x 135x 135x 4x 4x 4x 4x 4x 4x 93x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 93x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 232x 232x 232x 54x 54x 54x 93x 17x 17x 17x 17x 17x 17x 2x 2x 2x 2x 2x 2x 2x 17x 15x 15x 15x 15x 17x 17x 17x 17x 17x 93x 93x 93x 93x 135x 135x 135x 135x 135x 93x 135x 135x 135x 135x 135x 135x 52x 135x 93x 135x 135x 135x 227x 227x 88x 88x 88x 88x 88x 6x 135x 135x 135x 135x 135x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 131x 131x 131x 131x 131x 135x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 405x 405x 405x 405x 405x 405x 405x 93x 405x 405x 405x 405x 405x 405x 405x 405x 95x 273x 273x 405x 405x 405x 405x 132x 132x 132x 273x 273x 273x 37x 37x 37x 405x 405x 405x 405x 405x 405x 405x 405x 405x 405x 405x 17x 17x 17x 17x 15x 15x 17x 17x 17x 405x 405x 405x 4x 4x 405x 236x 227x 227x 227x 227x 227x 227x 227x 227x 227x 227x 227x 227x 442x 442x 442x 74x 74x 74x 74x 74x 405x 405x 405x 405x 236x 405x 405x 405x 405x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x 135x | import { html, css, TemplateResult } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { FieldConfig } from '../flow/types';
import { BaseListEditor, ListItem } from './BaseListEditor';
import { FieldRenderer } from './FieldRenderer';
import '../list/SortableList';
import { Icon } from '../Icons';
@customElement('temba-array-editor')
export class TembaArrayEditor extends BaseListEditor<ListItem> {
@property({ type: Object })
itemConfig: Record<string, FieldConfig> = {};
@property({ type: String })
itemLabel = 'Item';
@property({ type: Function })
onItemChange?: (
itemIndex: number,
field: string,
value: any,
allItems: any[]
) => any[];
@property({ type: Function })
isEmptyItemFn?: (item: any) => boolean;
@property({ type: Function })
createEmptyItemFn?: (items: any[]) => any;
@property({ type: Boolean })
sortable = false;
@property({ type: Boolean })
maintainEmptyItem = true; // Enable by default for better UX
// Focus preservation properties
private focusInfo: {
itemIndex: number;
fieldName: string;
selectionStart?: number;
selectionEnd?: number;
} | null = null;
constructor() {
super();
this._items = [];
}
// External API
@property({ type: Array })
get value(): any[] {
return [...this._items];
}
set value(newValue: any[]) {
this._items = newValue || [];
this.requestUpdate();
}
// Implement abstract methods
isEmptyItem(item: ListItem): boolean {
// Use configurable function if provided
if (this.isEmptyItemFn) {
return this.isEmptyItemFn(item);
}
// Default behavior: check if all values are empty
const values = Object.values(item);
if (values.length === 0) {
return true;
}
return values.every(
(value) => value === undefined || value === null || value === ''
);
}
// Override cleanItems to be more permissive for form data
protected cleanItems(items: ListItem[]): any {
// For runtime attachments, keep items that have at least one non-empty field
return items.filter((item) => {
const values = Object.values(item);
return (
values.length > 0 &&
values.some(
(value) => value !== undefined && value !== null && value !== ''
)
);
});
}
// Capture focus information before update
private captureFocus(): void {
const activeElement = this.shadowRoot?.activeElement as HTMLElement;
// Also try document.activeElement as a fallback
const globalActive = document.activeElement as HTMLElement;
let targetElement = activeElement || globalActive;
// If active element is within this component's shadow root, use it
if (globalActive && this.shadowRoot?.contains(globalActive)) {
targetElement = globalActive;
}
if (!targetElement) {
this.focusInfo = null;
return;
}
// Find the array item container by traversing up the DOM
let currentElement = targetElement;
let arrayItemElement: HTMLElement | null = null;
// Traverse up through shadow DOM boundaries
while (currentElement) {
if (currentElement.classList?.contains('array-item')) {
arrayItemElement = currentElement;
break;
}
// Move up to parent, or cross shadow boundaries
if (currentElement.parentElement) {
currentElement = currentElement.parentElement;
} else if (
currentElement.parentNode &&
(currentElement.parentNode as any).host
) {
// Cross shadow boundary
currentElement = (currentElement.parentNode as any).host;
} else {
break;
}
}
if (!arrayItemElement) {
this.focusInfo = null;
return;
}
// Find the item index by looking at the item ID
const itemIdMatch = arrayItemElement.id?.match(/array-item-(\d+)/);
if (!itemIdMatch) {
this.focusInfo = null;
return;
}
const itemIndex = parseInt(itemIdMatch[1], 10);
// Determine the field name by examining the input element and its containers
let fieldName = '';
// First, check if it's a temba component with a name attribute
if (targetElement.tagName?.toLowerCase().startsWith('temba-')) {
fieldName =
(targetElement as any).name || targetElement.getAttribute('name') || '';
}
// If not found, check regular HTML elements
if (
!fieldName &&
targetElement.hasAttribute &&
targetElement.hasAttribute('name')
) {
fieldName = targetElement.getAttribute('name') || '';
}
// If still not found, look for data-field-name in parent containers
if (!fieldName) {
let searchElement = targetElement;
while (searchElement && searchElement !== arrayItemElement) {
if (
searchElement.hasAttribute &&
searchElement.hasAttribute('data-field-name')
) {
fieldName = searchElement.getAttribute('data-field-name') || '';
break;
}
searchElement = searchElement.parentElement;
}
}
if (!fieldName) {
this.focusInfo = null;
return;
}
const inputForSelection = this.getSelectionElement(targetElement);
const selectionStart = (inputForSelection as any).selectionStart;
const selectionEnd = (inputForSelection as any).selectionEnd;
this.focusInfo = {
itemIndex,
fieldName,
selectionStart:
selectionStart === null || selectionStart === undefined
? undefined
: selectionStart,
selectionEnd:
selectionEnd === null || selectionEnd === undefined
? undefined
: selectionEnd
};
}
// Restore focus after update
private restoreFocus(): void {
if (!this.focusInfo) {
return;
}
const { itemIndex, fieldName, selectionStart, selectionEnd } =
this.focusInfo;
// Find the target element by array item index
const arrayItemId = `array-item-${itemIndex}`;
const arrayItemElement = this.shadowRoot?.getElementById(arrayItemId);
if (!arrayItemElement) {
// If the exact item doesn't exist (e.g., due to reordering), try to find by field name
const allItems = this.shadowRoot?.querySelectorAll('.array-item');
if (allItems && allItems.length > itemIndex) {
const fallbackItem = allItems[itemIndex];
if (fallbackItem) {
this.attemptFocusRestore(
fallbackItem as HTMLElement,
fieldName,
selectionStart,
selectionEnd
);
}
}
this.focusInfo = null;
return;
}
this.attemptFocusRestore(
arrayItemElement,
fieldName,
selectionStart,
selectionEnd
);
this.focusInfo = null;
}
private attemptFocusRestore(
container: HTMLElement,
fieldName: string,
selectionStart?: number,
selectionEnd?: number
): void {
// Look for the field container first
const fieldContainer = container.querySelector(
`[data-field-name="${fieldName}"]`
);
let targetElement: HTMLElement | null = null;
if (fieldContainer) {
// Look for temba components or input elements within the field container
targetElement = fieldContainer.querySelector(
'temba-textinput, temba-completion, temba-rich-edit, input, textarea'
) as HTMLElement;
}
// Fallback: search entire container
if (!targetElement) {
const selectors = [
`temba-textinput[name="${fieldName}"]`,
`temba-completion[name="${fieldName}"]`,
`temba-rich-edit[name="${fieldName}"]`,
`input[name="${fieldName}"]`,
`textarea[name="${fieldName}"]`,
`[name="${fieldName}"]`
];
for (const selector of selectors) {
targetElement = container.querySelector(selector) as HTMLElement;
if (targetElement) break;
}
}
if (targetElement) {
// Use multiple animation frames to ensure DOM is fully settled
requestAnimationFrame(() => {
requestAnimationFrame(() => {
try {
// Avoid resetting cursor position if the target already has focus.
const currentlyFocused =
this.shadowRoot?.activeElement || document.activeElement;
const targetAlreadyFocused =
currentlyFocused === targetElement ||
targetElement.contains(currentlyFocused);
if (!targetAlreadyFocused) {
targetElement.focus();
}
// Restore selection if it's a text input
if (selectionStart !== undefined && selectionEnd !== undefined) {
// For temba components, we need to focus the actual editable node.
const inputForSelection = this.getSelectionElement(targetElement);
if ('setSelectionRange' in inputForSelection) {
(inputForSelection as any).setSelectionRange(
selectionStart,
selectionEnd
);
}
}
} catch (error) {
// Ignore focus errors - element might not be focusable
// Focus restoration failed, silently continue
}
});
});
}
}
private getSelectionElement(targetElement: HTMLElement): HTMLElement {
if (!targetElement.tagName?.toLowerCase().startsWith('temba-')) {
return targetElement;
}
// Prefer the component's actual editable node and avoid hidden form mirrors.
const editableSelector =
'input:not([type="hidden"]), textarea, [contenteditable="true"]';
const innerInput =
targetElement.shadowRoot?.querySelector(editableSelector) ||
targetElement.querySelector(editableSelector);
return (innerInput as HTMLElement) || targetElement;
}
createEmptyItem(): ListItem {
if (this.createEmptyItemFn) {
return this.createEmptyItemFn(this._items);
}
return {};
}
protected handleFieldChange(
itemIndex: number,
fieldName: string,
newValue: any
) {
// Use displayItems so the empty row's pre-filled data (e.g. operator) is preserved
const sourceItems = this.displayItems;
let updatedItems: any[];
if (this.onItemChange) {
updatedItems = this.onItemChange(
itemIndex,
fieldName,
newValue,
sourceItems
);
} else {
updatedItems = [...sourceItems];
updatedItems[itemIndex] = {
...updatedItems[itemIndex],
[fieldName]: newValue
};
}
this.updateValue(updatedItems);
}
// Override Lit's update lifecycle methods for focus preservation
protected willUpdate(changedProperties: Map<string, any>): void {
super.willUpdate(changedProperties);
// Capture focus before update if items are changing
if (changedProperties.has('_items') || changedProperties.has('value')) {
this.captureFocus();
}
}
updated(changedProperties: Map<string, any>): void {
super.updated(changedProperties);
// Restore focus after update if items changed
if (changedProperties.has('_items') || changedProperties.has('value')) {
this.restoreFocus();
}
}
private handleOrderChanged(event: CustomEvent): void {
const detail = event.detail;
// Handle swap-based logic from SortableList
if (detail.swap && Array.isArray(detail.swap) && detail.swap.length === 2) {
const [fromIdx, toIdx] = detail.swap;
// Only reorder if the indexes are different and valid
if (
fromIdx !== toIdx &&
fromIdx >= 0 &&
toIdx >= 0 &&
fromIdx < this._items.length &&
toIdx < this._items.length
) {
const updatedItems = [...this._items];
// Move the item using splice operations
const movedItem = updatedItems.splice(fromIdx, 1)[0];
updatedItems.splice(toIdx, 0, movedItem);
this.updateValue(updatedItems);
}
}
}
renderWidget(): TemplateResult {
const items = this.displayItems;
const itemsContent = items.map((item, index) => {
const renderedItem = this.renderItem(item, index);
if (this.sortable && !this.isEmptyItem(item)) {
// Wrap non-empty items with sortable class and unique ID for drag-and-drop
return html`
<div class="sortable" id="array-item-${index}">${renderedItem}</div>
`;
} else {
// Non-sortable items or empty items don't get the sortable wrapper
return renderedItem;
}
});
if (this.sortable) {
return html`
<div class=${this.getContainerClass()}>
<temba-sortable-list
dragHandle="drag-handle"
gap="0.4em"
@temba-order-changed=${this.handleOrderChanged}
style="display: grid; grid-template-columns: 1fr; gap: 8px;"
>
${itemsContent}
</temba-sortable-list>
${this.shouldShowAddButton() ? this.renderAddButton() : ''}
</div>
`;
} else {
// Non-sortable rendering (original behavior)
return html`
<div class=${this.getContainerClass()}>
<div
class="list-items"
style="display: grid; grid-template-columns: 1fr; gap: 8px;"
>
${itemsContent}
</div>
${this.shouldShowAddButton() ? this.renderAddButton() : ''}
</div>
`;
}
}
private computeFieldValue(
item: ListItem,
fieldName: string,
config: FieldConfig
): any {
const currentValue = item[fieldName];
if (config.computeValue) {
return config.computeValue(item, currentValue);
}
// For select fields, ensure we return the right type
/*if (config.type === 'select') {
console.log('computeFieldValue select', currentValue, config);
const selectConfig = config as SelectFieldConfig;
if (currentValue === undefined || currentValue === null) {
return selectConfig.multi ? [] : '';
}
}*/
return currentValue;
}
private renderArrayField(
item: ListItem,
itemIndex: number,
fieldName: string,
config: FieldConfig
): TemplateResult {
const computedValue = this.computeFieldValue(item, fieldName, config);
// Extract flavor from select config if available
const flavor =
config.type === 'select' ? (config as any).flavor || 'small' : 'small';
// Build container style with width/maxWidth if specified
let containerStyle = '';
if (config.width) {
containerStyle = `width: ${config.width};`;
} else if (config.maxWidth) {
containerStyle = `max-width: ${config.maxWidth};`;
}
// Use FieldRenderer for consistent field rendering
const fieldContent = FieldRenderer.renderField(
fieldName,
config,
computedValue,
{
showLabel: false, // ArrayEditor doesn't show labels for individual fields
flavor: flavor,
extraClasses: 'form-control',
formData: item,
onChange: (e: Event) => {
let value: any;
const target = e.target as any;
// Handle different field types and their change events
if (config.type === 'select') {
// Use consistent temba-select value normalization
value = target.values;
} else {
// For other field types, use the target value directly
value = target.value;
}
this.handleFieldChange(itemIndex, fieldName, value);
}
}
);
// Wrap in container with style if maxWidth is specified
if (containerStyle) {
return html`<div style="${containerStyle}">${fieldContent}</div>`;
}
return fieldContent;
}
renderItem(item: ListItem, index: number): TemplateResult {
const canRemove = this.canRemoveItem(index);
// Render fields and track if any value fields are visible
const fieldElements: TemplateResult[] = [];
let hasVisibleValueField = false;
Object.entries(this.itemConfig).forEach(([fieldName, config]) => {
// Check visibility condition
let isVisible = true;
if (config.conditions?.visible) {
try {
isVisible = config.conditions.visible(item);
} catch (error) {
console.error(`Error checking visibility for ${fieldName}:`, error);
}
}
if (isVisible) {
// Check if this is a value field (text input without fixed sizing)
const isValueField =
!config.width && !config.maxWidth && config.type === 'text';
if (isValueField) {
hasVisibleValueField = true;
}
fieldElements.push(html`
<div
data-field-name="${fieldName}"
style="${config.width || config.maxWidth || config.type === 'select'
? 'flex:none'
: 'flex:1;min-width:0'}"
>
${this.renderArrayField(item, index, fieldName, config)}
</div>
`);
}
});
// If no value fields are visible, add a spacer to maintain alignment
if (!hasVisibleValueField) {
// Insert spacer after operator (first field) and before category (last field)
fieldElements.splice(
-1,
0,
html`<div class="field field-flex spacer" style="flex-grow:1"></div>`
);
}
return html`
<div class="array-item" id="array-item-${index}">
<div
class="item-fields ${canRemove ? '' : 'removable'}"
style="display: flex; gap: 12px; align-items: center"
>
${this.sortable
? html`<temba-icon
name=${Icon.sort}
style="margin-right: -6px;"
class="drag-handle"
></temba-icon>`
: null}
${fieldElements}
<button
@click=${canRemove ? () => this.removeItem(index) : undefined}
class="remove-btn"
style="
padding: 4px;
border: 1px solid #ccc;
border-radius: 4px;
background: white;
cursor: pointer;
background: #fefefe;
color: #999;
font-size: 14px;
"
?disabled=${!canRemove}
>
<temba-icon name="x"></temba-icon>
</button>
</div>
</div>
`;
}
protected getContainerClass(): string {
return 'array-editor';
}
static get styles() {
return css`
${super.styles}
.item-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.item-title {
font-weight: 600;
color: #333;
}
.field {
/* Base field styles */
}
.spacer {
/* Empty spacer to maintain layout alignment */
}
.add-btn,
.remove-btn {
padding: 4px;
border: 1px solid #ccc;
border-radius: 4px;
background: white;
cursor: pointer;
font-size: 14px;
}
.add-btn:hover,
.remove-btn:hover {
background: #f8f8f8;
}
.remove-btn {
background: #fefefe;
color: #999;
}
.removable .remove-btn {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.removable .drag-handle {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.drag-handle {
cursor: grab;
color: #ccc;
}
`;
}
}
|