All files / src/form KeyValueEditor.ts

77.81% Statements 242/311
73.8% Branches 31/42
87.5% Functions 14/16
77.81% Lines 242/311

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 31293x 99x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 93x 21x 21x 17x 93x 4x 4x 1x 3x 3x 3x 4x 4x 4x 4x     4x 93x 93x 37x 37x 37x 93x 93x 93x 93x 1x 1x 1x 1x 1x 93x 93x 93x                   93x 93x 93x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                     1x 1x 1x 93x 93x 93x 93x 1x 1x 1x 93x 93x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 93x 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 93x                             93x 93x 93x 93x 93x                                           8x 8x 93x 15x 15x 15x 2x 2x 2x 2x 2x 2x 2x 2x 2x 15x 15x 15x 15x 1x 1x 1x 1x 1x 15x 15x 15x       15x 15x 2x 2x 2x 2x 2x 2x 2x 2x     15x 2x 2x 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 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x  
import { html, css, TemplateResult } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { BaseListEditor, ListItem } from './BaseListEditor';
 
interface KeyValueItem extends ListItem {
  key: string;
  value: string;
}
 
@customElement('temba-key-value-editor')
export class KeyValueEditor extends BaseListEditor<KeyValueItem> {
  @property({ type: String })
  keyPlaceholder = 'Key';
 
  @property({ type: String })
  valuePlaceholder = 'Value';
 
  @property({ type: Boolean })
  showValidation = true;
 
  @property({ type: Boolean })
  readOnlyKeys = false;
 
  @state()
  private keyErrors: { [index: number]: string } = {};
 
  // Configure to maintain empty items
  maintainEmptyItem = true;
 
  constructor() {
    super();
    this._items = [];
  }
 
  // External API uses array format to preserve duplicate keys
  @property({ type: Array })
  get value(): KeyValueItem[] | any[] {
    return this._items.filter(
      ({ key, value }) => key.trim() !== '' || value.trim() !== ''
    );
  }
 
  set value(newValue: KeyValueItem[] | Record<string, string> | any) {
    if (Array.isArray(newValue)) {
      this._items = [...newValue];
    } else {
      // Convert Record to array format
      this._items = Object.entries(newValue || {}).map(([key, value]) => ({
        key,
        value: typeof value === 'string' ? value : String(value)
      }));
    }
    this.requestUpdate();
  }
 
  // Implement abstract methods
  isEmptyItem(item: KeyValueItem): boolean {
    return item.key.trim() === '' && item.value.trim() === '';
  }

  createEmptyItem(): KeyValueItem {
    return { key: '', value: '' };
  }
 
  // Override cleanItems to return array format to preserve duplicate keys
  protected cleanItems(items: KeyValueItem[]): KeyValueItem[] {
    return items.filter(
      ({ key, value }) => key.trim() !== '' || value.trim() !== ''
    );
  }
 
  // Method to convert to Record format for final form submission
  toRecord(): Record<string, string> {
    const result: Record<string, string> = {};
    this._items.forEach(({ key, value }) => {
      if (key.trim() !== '' || value.trim() !== '') {
        result[key] = value;
      }
    });
    return result;
  }

  // Method to validate and set key errors for duplicates and empty keys with values
  validateKeys(): boolean {
    const newKeyErrors: { [index: number]: string } = {};

    // Check for empty keys with values
    this._items.forEach(({ key, value }, index) => {
      if (key.trim() === '' && value.trim() !== '') {
        newKeyErrors[index] = 'Key is required when value is provided';
      }
    });
 
    // Check for duplicate keys (only non-empty ones)
    const nonEmptyKeys = this._items
      .map(({ key }, index) => ({ key: key.trim(), index }))
      .filter(({ key }) => key !== '');

    const keyCount = new Map<string, number[]>();
    nonEmptyKeys.forEach(({ key, index }) => {
      if (!keyCount.has(key)) {
        keyCount.set(key, []);
      }
      keyCount.get(key)!.push(index);
    });
 
    // Mark duplicate keys with errors
    keyCount.forEach((indices, key) => {
      if (indices.length > 1) {
        indices.forEach((index) => {
          // Only show duplicate error if there's no empty key error already
          if (!newKeyErrors[index]) {
            newKeyErrors[index] = `Duplicate key "${key}"`;
          }
        });
      }
    });

    this.keyErrors = newKeyErrors;
    return Object.keys(newKeyErrors).length === 0;
  }

  // Clear key errors
  clearKeyErrors(): void {
    this.keyErrors = {};
  }
 
  // Override updateValue to emit array format and validate keys
  protected updateValue(newValue: KeyValueItem[]) {
    this._items = newValue;
 
    // Clear errors and re-validate when items change
    this.clearKeyErrors();
    this.validateKeys();
 
    this.dispatchEvent(
      new CustomEvent('change', {
        detail: { value: this.cleanItems(newValue) },
        bubbles: true
      })
    );
    this.requestUpdate();
  }
 
  private handleKeyChange(index: number, newKey: string) {
    const items = this.displayItems;
    const currentItem = items[index];
 
    // Clear any existing error for this key when it's modified
    if (this.keyErrors[index]) {
      const newKeyErrors = { ...this.keyErrors };
      delete newKeyErrors[index];
      this.keyErrors = newKeyErrors;
    }
 
    this.handleItemChange(index, {
      key: newKey,
      value: currentItem.value
    });
  }

  private handleValueChange(index: number, newValue: string) {
    const items = this.displayItems;
    const currentItem = items[index];
 
    // Clear any existing error for this key when value is modified
    if (this.keyErrors[index]) {
      const newKeyErrors = { ...this.keyErrors };
      delete newKeyErrors[index];
      this.keyErrors = newKeyErrors;
    }

    this.handleItemChange(index, {
      key: currentItem.key,
      value: newValue
    });
  }

  // Override renderWidget for readOnlyKeys to use a single grid
  // so all key labels share one auto-sized column
  renderWidget(): TemplateResult {
    if (this.readOnlyKeys) {
      const items = this.displayItems;
      return html`
        <div class="readonly-keys-grid">
          ${items.map(
            (item, index) => html`
              <div class="key-label">${item.key}</div>
              <temba-textinput
                .value=${item.value}
                .placeholder=${this.valuePlaceholder}
                @change=${(e: any) =>
                  this.handleValueChange(index, e.target.value)}
              ></temba-textinput>
            `
          )}
        </div>
      `;
    }
    return super.renderWidget();
  }

  renderItem(item: KeyValueItem, index: number): TemplateResult {
    const canRemove = this.canRemoveItem(index);
    const keyError =
      this.showValidation && this.keyErrors[index] ? this.keyErrors[index] : '';

    return html`
      <div class="row">
        <temba-textinput
          .value=${item.key}
          .placeholder=${this.keyPlaceholder}
          .errors=${keyError ? [keyError] : []}
          @change=${(e: any) => this.handleKeyChange(index, e.target.value)}
        ></temba-textinput>
        <temba-textinput
          .value=${item.value}
          .placeholder=${this.valuePlaceholder}
          @change=${(e: any) => this.handleValueChange(index, e.target.value)}
        ></temba-textinput>
        ${canRemove
          ? html`
              <button class="remove-btn" @click=${() => this.removeItem(index)}>
                ×
              </button>
            `
          : html`<div class="remove-btn-spacer"></div>`}
      </div>
    `;
  }
 
  protected get displayItems(): KeyValueItem[] {
    if (this.readOnlyKeys) {
      // In readOnlyKeys mode, show only the actual items (no empty row)
      return [...this._items];
    }
    return super.displayItems;
  }
 
  protected shouldShowAddButton(): boolean {
    if (this.readOnlyKeys) {
      return false;
    }
    return super.shouldShowAddButton();
  }
 
  protected getContainerClass(): string {
    return 'key-value-editor';
  }

  static get styles() {
    return css`
      ${super.styles}
 
      .key-value-editor {
        display: flex;
        flex-direction: column;
        gap: 8px;
      }
 
      .row {
        display: grid;
        grid-template-columns: 1fr 1fr auto;
        align-items: center;
        column-gap: 6px;
      }
 
      .readonly-keys-grid {
        display: grid;
        grid-template-columns: auto 1fr;
        gap: 8px 10px;
        align-items: center;
      }
 
      .key-label {
        font-size: 14px;
        color: #555;
        padding: 6px 10px;
        white-space: nowrap;
      }
 
      .remove-btn {
        width: 32px;
        height: 32px;
        border: 1px solid #ccc;
        border-radius: 4px;
        background: #f8f8f8;
        color: #666;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
      }
 
      .remove-btn:hover:not(:disabled) {
        background: #f0f0f0;
      }
 
      .remove-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
 
      .remove-btn-spacer {
        width: 32px;
        height: 32px;
      }
    `;
  }
}