All files / src/form FieldRenderer.ts

96.48% Statements 522/541
75.86% Branches 88/116
100% Functions 10/10
96.48% Lines 522/541

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 542127x 109x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 2000x 2000x 2000x 2000x 2000x 2000x 565x 565x 565x 2000x 132x 132x 132x 132x 132x 132x 132x 2000x 575x 575x 575x 575x 575x 575x 575x 2000x 102x 102x 102x 102x 102x 102x 102x 102x 13x 13x 13x 13x 13x 13x 13x 185x 185x 185x 185x 185x 185x 185x 185x 178x 178x 178x 178x 178x 178x 178x 178x 76x 76x 76x 76x 76x 76x 76x 76x 76x 2000x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 2000x         2000x 127x 565x 565x 565x 565x 565x 565x 565x 565x 565x 565x 565x 565x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 314x 314x 314x 314x 314x 314x 469x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 565x 101x 565x 565x 565x 565x 565x 565x 127x 132x 132x 132x 132x 118x 118x 118x 132x 132x 132x 131x 131x 131x 131x 8x 8x 8x 8x 8x 8x 8x 8x 8x 131x 131x 131x 131x 131x 131x 131x 131x 131x     131x 132x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 132x 132x 132x 132x 132x 132x 132x 575x 575x 575x 575x 575x 57x 575x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 443x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 575x 465x 465x 465x 84x 84x 3x 3x 3x 84x 2240x 8x 2324x 102x 102x 102x 102x 102x 102x 102x 16x 16x 16x 16x 86x 102x 102x 102x 102x 102x 102x 26x 102x 76x 102x 102x 102x 102x 102x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 102x 102x 102x 102x   102x 102x 102x 102x 1x 1x 1x 1x 1x 1x 1x 1x 127x 13x 13x 13x 13x 13x 13x 13x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 13x 13x 13x 13x 13x 13x 13x 13x     127x 185x 185x 185x 185x 185x 185x 185x 185x 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 185x 4x 4x 4x 4x 4x 185x 185x 185x 185x 185x 185x 185x       127x           76x 76x 76x     76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 127x 76x 76x 76x 76x 76x 76x 76x 1x 1x 1x 1x 1x 1x 76x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 76x 76x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x  
import { html, TemplateResult } from 'lit';
import { spread } from '@open-wc/lit-helpers';
import {
  FieldConfig,
  TextFieldConfig,
  TextareaFieldConfig,
  SelectFieldConfig,
  CheckboxFieldConfig,
  MessageEditorFieldConfig,
  KeyValueFieldConfig,
  ArrayFieldConfig,
  MediaFieldConfig,
  TemplateEditorFieldConfig
} from '../flow/types';
import { Attachment } from '../interfaces';
import { DEFAULT_MEDIA_ENDPOINT } from '../utils';
 
/**
 * FieldRenderer provides a consistent way to render field configurations
 * into web components across different contexts (NodeEditor, ArrayEditor, etc.)
 */
export class FieldRenderer {
  /**
   * Renders a field based on its configuration
   * @param fieldName - The name of the field
   * @param config - The field configuration
   * @param value - The current value of the field
   * @param context - Additional context for rendering
   * @returns A TemplateResult for the rendered field
   */
  static renderField(
    fieldName: string,
    config: FieldConfig,
    value: any,
    context: FieldRenderContext = {}
  ): TemplateResult {
    /*const {
      errors = [],
      onChange,
      showLabel = true,
      flavor,
      extraClasses = '',
      style = ''
    } = context;*/
    switch (config.type) {
      case 'text':
        return FieldRenderer.renderTextInput(fieldName, config, value, context);
 
      case 'textarea':
        return FieldRenderer.renderTextarea(
          fieldName,
          config as TextareaFieldConfig,
          value,
          context
        );
 
      case 'select':
        return FieldRenderer.renderSelect(
          fieldName,
          config as SelectFieldConfig,
          value,
          context
        );
 
      case 'checkbox':
        return FieldRenderer.renderCheckbox(
          fieldName,
          config as CheckboxFieldConfig,
          value,
          context
        );
 
      case 'key-value':
        return FieldRenderer.renderKeyValue(
          fieldName,
          config as KeyValueFieldConfig,
          value,
          context
        );
 
      case 'array':
        return FieldRenderer.renderArray(
          fieldName,
          config as ArrayFieldConfig,
          value,
          context
        );
 
      case 'message-editor':
        return FieldRenderer.renderMessageEditor(
          fieldName,
          config as MessageEditorFieldConfig,
          value,
          context
        );
 
      case 'media':
        return FieldRenderer.renderMedia(
          fieldName,
          config as MediaFieldConfig,
          value,
          context
        );
 
      case 'template-editor':
        return FieldRenderer.renderTemplateEditor(
          fieldName,
          config as TemplateEditorFieldConfig,
          value,
          context
        );
 
      default:
        return html`<div>Unsupported field type: ${(config as any).type}</div>`;
    }
  }
 
  private static renderTextInput(
    fieldName: string,
    config: TextFieldConfig,
    value: any,
    context: FieldRenderContext
  ): TemplateResult {
    const {
      errors = [],
      onChange,
      showLabel = true,
      extraClasses,
      style
    } = context;

    // Resolve placeholder (supports static string or dynamic function)
    const placeholder =
      typeof config.placeholder === 'function'
        ? config.placeholder(context.formData || {})
        : config.placeholder || '';
 
    // If field supports expression evaluation, use temba-completion
    if (config.evaluated) {
      return html`<temba-rich-edit
        name="${fieldName}"
        label="${showLabel ? config.label : ''}"
        ?required="${config.required}"
        .errors="${errors}"
        .value="${value || ''}"
        placeholder="${placeholder}"
        session
        flavor="${config.flavor || 'default'}"
        .helpText="${config.helpText || ''}"
        class="${extraClasses}"
        style="${style}"
        @change="${onChange || (() => {})}"
      ></temba-rich-edit>`;
    }
 
    return html`<temba-textinput
      name="${fieldName}"
      label="${showLabel ? config.label : ''}"
      ?required="${config.required}"
      .errors="${errors}"
      .value="${value || ''}"
      placeholder="${placeholder}"
      .helpText="${config.helpText || ''}"
      flavor="${config.flavor || 'default'}"
      class="${extraClasses}"
      style="${style}"
      @input="${onChange || (() => {})}"
    ></temba-textinput>`;
  }
 
  private static renderTextarea(
    fieldName: string,
    config: TextareaFieldConfig,
    value: any,
    context: FieldRenderContext
  ): TemplateResult {
    const {
      errors = [],
      onChange,
      showLabel = true,
      extraClasses,
      style
    } = context;
 
    const minHeightStyle = config.minHeight
      ? `--textarea-min-height: ${config.minHeight}px;`
      : '';
    const combinedStyle = `${minHeightStyle}${style}`;
 
    // If field supports expression evaluation, use temba-rich-edit
    if (config.evaluated) {
      return html`<temba-rich-edit
        name="${fieldName}"
        label="${showLabel ? config.label : ''}"
        ?required="${config.required}"
        .errors="${errors}"
        .value="${value || ''}"
        placeholder="${config.placeholder || ''}"
        textarea
        session
        .helpText="${config.helpText || ''}"
        class="${extraClasses}"
        style="${combinedStyle}"
        @change="${onChange || (() => {})}"
      ></temba-rich-edit>`;
    }
 
    return html`<temba-textinput
      name="${fieldName}"
      label="${showLabel ? config.label : ''}"
      ?required="${config.required}"
      .errors="${errors}"
      .value="${value || ''}"
      placeholder="${config.placeholder || ''}"
      textarea
      .rows="${config.rows || 3}"
      .helpText="${config.helpText || ''}"
      class="${extraClasses}"
      style="${combinedStyle}"
      @input="${onChange || (() => {})}"
    ></temba-textinput>`;
  }
 
  private static renderSelect(
    fieldName: string,
    config: SelectFieldConfig,
    value: any,
    context: FieldRenderContext
  ): TemplateResult {
    const {
      errors = [],
      onChange,
      showLabel = true,
      flavor,
      extraClasses,
      style
    } = context;
 
    // Get options - use dynamic options if available, otherwise use static options
    const optionsToRender = config.getDynamicOptions
      ? config.getDynamicOptions()
      : config.options;
 
    return html`<temba-select
      name="${fieldName}"
      label="${showLabel ? config.label : ''}"
      ?required="${config.required}"
      .errors="${errors}"
      .values=${value}
      ?multi="${config.multi}"
      ?searchable="${config.searchable}"
      ?tags="${config.tags}"
      ?emails="${config.emails}"
      expressions="${config.expressions || ''}"
      ?clearable="${config.clearable || false}"
      placeholder="${config.placeholder || ''}"
      maxItems="${config.maxItems || 0}"
      valueKey="${config.valueKey || 'value'}"
      nameKey="${config.nameKey || 'name'}"
      endpoint="${config.endpoint || ''}"
      queryParam="${config.queryParam || ''}"
      .helpText="${config.helpText || ''}"
      flavor="${flavor || config.flavor || 'small'}"
      class="${extraClasses}"
      style="${style}"
      .getName=${config.getName}
      .shouldExclude=${config.shouldExclude}
      .createArbitraryOption=${config.createArbitraryOption}
      ?allowCreate="${config.allowCreate || false}"
      @change="${onChange || (() => {})}"
    >
      ${optionsToRender?.map((option: any) => {
        if (typeof option === 'string') {
          return html`<temba-option
            name="${option}"
            value="${option}"
          ></temba-option>`;
        } else {
          return html`<temba-option ${spread(option)}></temba-option>`;
        }
      })}
    </temba-select>`;
  }
 
  private static renderCheckbox(
    fieldName: string,
    config: CheckboxFieldConfig,
    value: any,
    context: FieldRenderContext
  ): TemplateResult {
    const {
      errors = [],
      onChange,
      extraClasses,
      style,
      formData = {}
    } = context;
 
    // Handle dynamic labels
    const label =
      typeof config.label === 'function'
        ? config.label(formData)
        : config.label;
 
    const helpText =
      typeof config.helpText === 'function'
        ? config.helpText(formData)
        : config.helpText;
 
    // Build custom style including labelPadding
    const customStyle = config.labelPadding
      ? `--checkbox-padding: ${config.labelPadding}; ${style || ''}`
      : style || '';
 
    return html`<div class="form-field">
      <temba-checkbox
        name="${fieldName}"
        label="${label}"
        .helpText="${helpText || ''}"
        ?required="${config.required}"
        .errors="${errors}"
        ?checked="${value || false}"
        size="${config.size || 1.2}"
        animateChange="${config.animateChange || 'pulse'}"
        class="${extraClasses}"
        style="${customStyle}"
        @change="${onChange || (() => {})}"
      ></temba-checkbox>
      ${errors.length
        ? html`<div class="field-errors">${errors.join(', ')}</div>`
        : ''}
    </div>`;
  }
 
  private static renderKeyValue(
    fieldName: string,
    config: KeyValueFieldConfig,
    value: any,
    context: FieldRenderContext
  ): TemplateResult {
    const {
      errors = [],
      onChange,
      showLabel = true,
      extraClasses,
      style
    } = context;
 
    return html`<div class="form-field">
      ${showLabel ? html`<label>${config.label}</label>` : ''}
      <temba-key-value-editor
        name="${fieldName}"
        .value="${value || []}"
        .sortable="${config.sortable}"
        .keyPlaceholder="${config.keyPlaceholder || 'Key'}"
        .valuePlaceholder="${config.valuePlaceholder || 'Value'}"
        .minRows="${config.minRows || 0}"
        ?readOnlyKeys="${config.readOnlyKeys}"
        class="${extraClasses}"
        style="${style}"
        @change="${onChange || (() => {})}"
      ></temba-key-value-editor>
      ${errors.length
        ? html`<div class="field-errors">${errors.join(', ')}</div>`
        : ''}
    </div>`;
  }
 
  private static renderArray(
    fieldName: string,
    config: ArrayFieldConfig,
    value: any,
    context: FieldRenderContext
  ): TemplateResult {
    const {
      errors = [],
      onChange,
      showLabel = true,
      extraClasses,
      style
    } = context;
 
    return html`<div class="form-field">
      ${config.helpText
        ? html`<div style="color: #666; font-size: 13px; margin-bottom: 14px;">
            ${config.helpText}
          </div>`
        : ''}
      <temba-array-editor
        name="${fieldName}"
        .label="${showLabel ? config.label : ''}"
        .value="${value || []}"
        .itemConfig="${config.itemConfig}"
        .sortable="${config.sortable}"
        .itemLabel="${config.itemLabel || 'Item'}"
        .minItems="${config.minItems || 0}"
        .maxItems="${config.maxItems || 0}"
        ?maintainEmptyItem="${config.maintainEmptyItem !== false}"
        .onItemChange="${config.onItemChange}"
        .isEmptyItemFn="${config.isEmptyItem}"
        .createEmptyItemFn="${config.createEmptyItem}"
        class="${extraClasses}"
        style="${style}"
        @change="${onChange || (() => {})}"
      ></temba-array-editor>
      ${errors.length
        ? html`<div class="field-errors">${errors.join(', ')}</div>`
        : ''}
    </div>`;
  }
 
  private static urlToAttachments(url: string): Attachment[] {
    if (!url || !url.trim()) return [];
    const filename = url.split('/').pop() || 'recording';
    const ext = filename.split('.').pop()?.toLowerCase() || '';
    const contentTypes: Record<string, string> = {
      mp3: 'audio/mpeg',
      wav: 'audio/wav',
      ogg: 'audio/ogg',
      m4a: 'audio/mp4'
    };
    return [
      {
        uuid: '',
        content_type: contentTypes[ext] || 'audio/mpeg',
        url,
        filename,
        size: 0,
        error: ''
      }
    ];
  }
 
  private static renderMedia(
    fieldName: string,
    config: MediaFieldConfig,
    value: any,
    context: FieldRenderContext
  ): TemplateResult {
    const { onChange, showLabel = true } = context;
    const endpoint = config.endpoint || DEFAULT_MEDIA_ENDPOINT;
    const attachments = FieldRenderer.urlToAttachments(value);
 
    return html`
      <div>
        ${showLabel && config.label
          ? html`<label
              style="margin-bottom: 5px; margin-left: 4px; display: block; font-weight: 400; font-size: var(--label-size); letter-spacing: 0.05em; line-height: normal; color: var(--color-label, #777);"
              >${config.label}</label
            >`
          : ''}
        <temba-media-picker
          name="${fieldName}"
          accept="${config.accept || ''}"
          endpoint="${endpoint}"
          max="1"
          .attachments="${attachments}"
          @change="${onChange || (() => {})}"
        ></temba-media-picker>
      </div>
    `;
  }

  private static renderMessageEditor(
    fieldName: string,
    config: MessageEditorFieldConfig,
    value: any,
    context: FieldRenderContext
  ): TemplateResult {
    const {
      errors = [],
      onChange,
      showLabel = true,
      extraClasses,
      style,
      additionalData = {}
    } = context;
 
    return html`<temba-message-editor
      name="${fieldName}"
      label="${showLabel ? config.label : ''}"
      ?required="${config.required}"
      .errors="${errors}"
      .value="${value || ''}"
      .attachments="${additionalData.attachments || []}"
      placeholder="${config.placeholder || ''}"
      .helpText="${config.helpText || ''}"
      ?autogrow="${config.autogrow}"
      ?gsm="${config.gsm}"
      ?disableCompletion="${config.disableCompletion}"
      session
      counter="${config.counter || ''}"
      accept="${config.accept || ''}"
      endpoint="${config.endpoint || ''}"
      max-attachments="${config.maxAttachments || 3}"
      minHeight="${config.minHeight || 92}"
      class="${extraClasses}"
      style="${style}"
      @change="${onChange || (() => {})}"
    ></temba-message-editor>`;
  }
 
  private static renderTemplateEditor(
    _fieldName: string,
    config: TemplateEditorFieldConfig,
    value: any,
    context: FieldRenderContext
  ): TemplateResult {
    const { onChange, additionalData = {} } = context;
    const templateUuid = value?.uuid || '';
    const variables = JSON.stringify(additionalData.template_variables || []);
 
    return html`<temba-template-editor
      url="${config.endpoint || '/api/internal/templates.json'}"
      template="${templateUuid}"
      variables="${variables}"
      session
      @temba-context-changed="${onChange || (() => {})}"
      @temba-content-changed="${onChange || (() => {})}"
    ></temba-template-editor>`;
  }
}
 
export interface FieldRenderContext {
  /** Array of error messages for the field */
  errors?: string[];
  /** Change event handler */
  onChange?: (event: Event) => void;
  /** Whether to show the field label */
  showLabel?: boolean;
  /** Flavor for components that support it (like temba-select) */
  flavor?: string;
  /** Additional CSS classes to apply */
  extraClasses?: string;
  /** Additional CSS styles to apply */
  style?: string;
  /** Additional data needed for specific field types */
  additionalData?: Record<string, any>;
  /** Form data for dynamic field configurations */
  formData?: Record<string, any>;
}