All files / src/UI ExpressionContent.tsx

8.09% Statements 19/235
0% Branches 0/158
0% Functions 0/27
8.19% Lines 19/232

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                              3x               3x   3x               3x 3x   3x 3x   3x   3x   3x 3x 3x 3x 3x 3x 3x 3x                                                                                                                                                                                                               3x                                     3x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
/*
    Copyright (C) 2017 Red Hat, Inc.
 
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
 
            http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
import {
  Button,
  Form,
  FormGroup,
  InputGroup,
  TextInput,
  Tooltip,
} from '@patternfly/react-core';
import { EnumValue, useToggle } from '../impl/utils';
import { Observable, Subscription } from 'rxjs';
import React, {
  FunctionComponent,
  KeyboardEvent,
  MouseEvent,
  useCallback,
  useEffect,
} from 'react';
 
import { ExpressionEnumSelect } from './ExpressionEnumSelect';
import { ExpressionFieldSearch } from './ExpressionFieldSearch';
import { IExpressionNode } from '@atlasmap/core';
import { css } from '@patternfly/react-styles';
import styles from '@patternfly/react-styles/css/components/FormControl/form-control';
 
let atIndex = -1;
let atContainer: Node | undefined;
let enumCandidates: EnumValue[] = [];
let expressionUpdatedSubscription: Subscription | null;
let lastUpdatedEvent: IExpressionUpdatedEvent | null = null;
let mappedFieldCandidates: string[][] = [];
let markup: HTMLDivElement | null = null;
let searchFilter = '';
let searchMode = false;
let selectedNodeId: string = '';
let trailerHTML = '';
let trailerID = '';
let getMappingExpression: () => string;
let mappingExprInit: () => void;
let mappingExprObservable: () => Observable<IExpressionUpdatedEvent> | null;
 
interface IExpressionUpdatedEvent {
  node: IExpressionNode;
  offset: number;
}
 
export interface IExpressionContentProps {
  executeFieldSearch: (searchFilter: string, isSource: boolean) => string[][];
  getFieldEnums: (nodeId: string) => EnumValue[];
  mappingExpressionAddField: (
    selectedDocId: string,
    selectedField: string,
    newTextNode: IExpressionNode,
    atIndex: number,
    isTrailer: boolean,
  ) => void;
  mappingExpressionClearText: (
    nodeId?: string,
    startOffset?: number,
    endOffset?: number,
  ) => IExpressionNode | null;
  isMappingExpressionEmpty: boolean;
  mappingExpressionInit: () => void;
  mappingExpressionInsertText: (
    str: string,
    nodeId?: string | undefined,
    offset?: number | undefined,
  ) => void;
  mappingExpressionObservable: () => Observable<IExpressionUpdatedEvent> | null;
  mappingExpressionRemoveField: (
    tokenPosition?: string,
    offset?: number,
    removeNext?: boolean,
  ) => void;
  mappingExpression?: string;
  trailerId: string;
  disabled: boolean;
  onToggle: () => void;
  setSelectedEnumValue: (
    selectedEnum: string,
    selectedEnumValueIndex: number,
  ) => void;
}
 
function updateExpressionMarkup(reset?: boolean) {
  if (!markup) {
    return;
  }
  if (reset) {
    markup.innerHTML = trailerHTML;
  } else {
    const currentExpression = getMappingExpression();
    markup.innerHTML = currentExpression + trailerHTML;
  }
}
 
function moveCaretToEnd() {
  if (!markup || trailerID.length === 0) {
    return;
  }
  const trailerNode = markup.querySelector('#' + trailerID);
  if (!trailerNode) {
    return;
  }
  let range;
  if (window.getSelection()!.rangeCount > 0) {
    range = window.getSelection()!.getRangeAt(0);
  } else {
    range = document.createRange();
    window.getSelection()!.addRange(range);
  }
  range.selectNode(trailerNode.childNodes[0]);
  range.setStart(trailerNode.childNodes[0], 0);
  range.collapse(true);
}
 
function restoreCaretPosition(event: IExpressionUpdatedEvent) {
  if (!markup || !event || !event.node) {
    return;
  }
 
  for (let i = 0; i < markup.childNodes.length; i++) {
    const target: any = markup.childNodes[i];
    if (target.id === event.node.uuid) {
      const selection = window.getSelection();
      if (selection && selection.rangeCount) {
        const range = selection.getRangeAt(0);
        const actualNode = target.childNodes[0] ? target.childNodes[0] : target;
        range.selectNode(actualNode);
        if (event.offset <= actualNode.length) {
          range.setStart(actualNode, event.offset);
        }
        range.collapse(true);
      }
      return;
    }
  }
  moveCaretToEnd();
}
 
export function initializeMappingExpression() {
  mappingExprInit();
  const mappingExprObs = mappingExprObservable();
  if (mappingExprObs) {
    expressionUpdatedSubscription = mappingExprObs.subscribe(
      (updatedEvent: IExpressionUpdatedEvent) => {
        lastUpdatedEvent = updatedEvent;
      },
    );
  }
  updateExpressionMarkup();
  if (!lastUpdatedEvent) {
    moveCaretToEnd();
  } else {
    restoreCaretPosition(lastUpdatedEvent);
    lastUpdatedEvent = null;
  }
}
 
export const ExpressionContent: FunctionComponent<IExpressionContentProps> = ({
  executeFieldSearch,
  getFieldEnums,
  mappingExpressionAddField,
  mappingExpressionClearText,
  isMappingExpressionEmpty,
  mappingExpressionInit,
  mappingExpressionInsertText,
  mappingExpressionObservable,
  mappingExpressionRemoveField,
  mappingExpression,
  trailerId,
  disabled,
  onToggle,
  setSelectedEnumValue,
}) => {
  let addFieldToExpression: (
    selectedDocId: string,
    selectedField: string,
    newTextNode: IExpressionNode,
    atIndex: number,
    isTrailer: boolean,
  ) => void;
  let clearText: (
    nodeId?: string,
    startOffset?: number,
    endOffset?: number,
  ) => IExpressionNode | null;
  let fieldSearch: (searchFilter: string, isSource: boolean) => string[][];
  let getEnums: (enumFieldName: string) => EnumValue[];
  let setSelEnumValue: (
    selectedEnumNodeId: string,
    selectedEnumValueIndex: number,
  ) => void;
 
  const {
    state: showEnumSelect,
    toggleOn: toggleEnumSelOn,
    toggleOff: toggleEnumSelOff,
  } = useToggle(false);
 
  /**
   * An enumeration value has been selected for the specified selected field node ID.
   *
   * @param selectedEnumNodeId - selected field node ID
   * @param selectedEnumValueIndex - selected enumeration index
   */
  function onEnumSelect(
    selectedEnumNodeId: string,
    selectedEnumValueIndex: number,
  ) {
    setSelEnumValue(selectedEnumNodeId, selectedEnumValueIndex);
    clearEnumSelect();
  }
 
  function insertTextAtCaretPosition(key: string) {
    const range = window.getSelection()!.getRangeAt(0);
    const startContainer = range.startContainer;
    const startOffset = range.startOffset;
 
    // On initial caret positioning before the first field node, the markup
    // and start container are the same.
    if (markup && startContainer === markup) {
      if (startOffset === 0) {
        const initialElement = startContainer.childNodes[0] as Element;
        mappingExpressionInsertText(key, initialElement.getAttribute('id')!, 0);
      } else {
        mappingExpressionInsertText(key);
      }
      return;
    }
    const nodeId = getCaretPositionNodeId();
 
    if (nodeId === trailerID) {
      mappingExpressionInsertText(key);
    } else {
      mappingExpressionInsertText(key, nodeId, startOffset);
    }
  }
 
  function removeTokenAtCaretPosition(before: boolean) {
    const selection = window.getSelection();
    let removeNext: boolean = false;
    if (!selection || !markup) {
      return;
    }
    if (!selection.rangeCount) {
      if (getCaretPositionNodeId() === trailerID) {
        if (before) {
          mappingExpressionRemoveField();
          moveCaretToEnd();
        }
      }
      return;
    }
    // The window selection node will be the text node if the cursor lies
    // at the boundary between the text node and a field node.  In that
    // case remove the next node.
    removeNext =
      !before &&
      selection.focusNode &&
      selection.focusNode.nodeType === selection.focusNode.TEXT_NODE &&
      selection.focusOffset === selection.focusNode.textContent?.length
        ? true
        : false;
    const range = selection.getRangeAt(0);
    const startContainer = range.startContainer;
    const startOffset = range.startOffset;
 
    if (startContainer === markup) {
      if (startOffset === 0) {
        // head of expression
        if (!before && !isMappingExpressionEmpty) {
          mappingExpressionRemoveField(getCaretPositionNodeId(), 0);
        }
        return;
      }
      // end of expression
      if (before && !isMappingExpressionEmpty) {
        mappingExpressionRemoveField();
      }
      return;
    }
 
    if (getCaretPositionNodeId(startContainer) === trailerID) {
      if (before) {
        mappingExpressionRemoveField();
      }
      moveCaretToEnd();
      return;
    }
    mappingExpressionRemoveField(
      getCaretPositionNodeId(),
      before ? startOffset - 1 : startOffset,
      removeNext,
    );
    if (getCaretPositionNodeId() === trailerID) {
      moveCaretToEnd();
    }
  }
 
  /**
   * Handle key down events.
   *
   * @param event - expression keyboard event
   */
  function onKeyDown(event: KeyboardEvent<HTMLDivElement>): void {
    if ('Backspace' === event.key) {
      // TODO handle cursor position
      event.preventDefault();
      removeTokenAtCaretPosition(true);
      if (searchMode) {
        updateSearchMode();
      }
    } else if ('Delete' === event.key) {
      event.preventDefault();
      removeTokenAtCaretPosition(false);
      if (searchMode) {
        updateSearchMode();
      }
    }
  }
 
  /**
   * A mouse click has occurred within the expression box.
   *
   * @param event - mouse event
   */
  function onExprClick(event: MouseEvent<HTMLElement>) {
    selectedNodeId = getCaretPositionNodeId();
 
    // Check for clicking on an enumeration field node.
    enumCandidates = getEnums(selectedNodeId);
    if (enumCandidates.length > 0) {
      event.preventDefault();
      toggleEnumSelOn();
    }
  }
 
  function onKeyPress(event: KeyboardEvent<HTMLDivElement>) {
    if (event.ctrlKey || event.metaKey || event.altKey) {
      return;
    }
    if (event.key.length > 1) {
      return;
    }
    event.preventDefault();
 
    if (isMappingExpressionEmpty) {
      initializeMappingExpression();
    }
    if (searchMode) {
      if (event.key.match(/[a-z0-9]/i)) {
        searchFilter += event.key;
        mappedFieldCandidates = fieldSearch(searchFilter, true);
      }
    } else {
      searchMode = event.key === '@' ? true : false;
      if (searchMode) {
        atContainer = window.getSelection()!.getRangeAt(0).startContainer;
        atIndex = window.getSelection()!.getRangeAt(0).startOffset;
        searchFilter = '';
        mappedFieldCandidates = fieldSearch(searchFilter, true);
      }
    }
    insertTextAtCaretPosition(event.key);
  }
 
  function onChange(_event: React.FormEvent<HTMLDivElement>) {
    if (isMappingExpressionEmpty) {
      initMappingExpression();
    }
    if (expressionUpdatedSubscription) {
      expressionUpdatedSubscription.unsubscribe();
    }
    expressionUpdatedSubscription = mappingExprObservable()!.subscribe(
      (updatedEvent: IExpressionUpdatedEvent) => {
        updateExpressionMarkup();
        restoreCaretPosition(updatedEvent);
      },
    );
    updateExpressionMarkup();
  }
 
  function onPaste(event: React.ClipboardEvent<HTMLDivElement>) {
    if (!event || !event.clipboardData) {
      return;
    }
    event.preventDefault();
    const pasted = event.clipboardData.getData('text/plain');
    // TODO handle cursor position... for now just append to the end
    mappingExpressionInsertText(pasted);
  }
 
  /**
   * The user has selected a field from the search select menu.  Extract
   * the field name and the scope if it is present.
   *
   * @param selectedDocId
   * @param selectedField
   * @returns
   */
  function insertSelectedField(
    selectedDocId: string,
    selectedField: string,
  ): void {
    const newTextNode = clearAtText(getCaretPositionNodeId(atContainer));
    if (newTextNode === null) {
      return;
    }
    const isTrailer = getCaretPositionNodeId(atContainer) === trailerID;
    addFieldToExpression(
      selectedDocId,
      selectedField,
      newTextNode,
      atIndex,
      isTrailer,
    );
    clearSearchMode(false);
    markup!.focus();
  }
 
  /**
   * Clear user input from the selected range offset within the TextNode at
   * the specified node ID.  The input will become a FieldNode so we don't
   * need the text.  Return the new UUID position indicator.
   */
  function clearAtText(nodeId: string): IExpressionNode | null {
    if (atIndex === -1) {
      return null;
    }
    const startOffset = atIndex;
    const endOffset = startOffset + searchFilter.length + 1;
    let updatedTextNode = null;
 
    if (nodeId === trailerID) {
      updatedTextNode = clearText();
    } else {
      updatedTextNode = clearText(nodeId, startOffset, endOffset);
    }
    return updatedTextNode;
  }
 
  /**
   * Return the UUID string representing the caret position as defined
   * by the user-specified starting container.  If no container is
   * specified then return the current caret position node ID value.
   *
   * @param startContainer
   */
  function getCaretPositionNodeId(startContainer?: Node): string {
    const selection = window.getSelection();
    if (!startContainer) {
      if (!selection || selection.rangeCount === 0) {
        return trailerID;
      }
      startContainer = selection!.getRangeAt(0).startContainer;
    }
    if (startContainer.nodeType === selection?.focusNode?.TEXT_NODE) {
      return startContainer.parentElement!.getAttribute('id')!;
    } else {
      return (startContainer.firstChild! as HTMLElement)?.getAttribute('id')!;
    }
  }
 
  /**
   * Clear elements associated with mapped-field searching.
   */
  function clearSearchMode(clearAtSign: boolean): void {
    if (clearAtSign) {
      clearAtText(getCaretPositionNodeId(atContainer));
    }
    atIndex = -1;
    atContainer = undefined;
    searchMode = false;
    searchFilter = '';
    mappedFieldCandidates = [];
  }
 
  function updateSearchMode(): void {
    if (searchFilter.length === 0) {
      mappedFieldCandidates = [];
      searchMode = false;
    } else {
      searchFilter = searchFilter.substr(0, searchFilter.length - 1);
      mappedFieldCandidates = fieldSearch(searchFilter, true);
    }
  }
 
  function clearEnumSelect() {
    selectedNodeId = '';
    enumCandidates = [];
    toggleEnumSelOff();
  }
 
  const initMappingExpression = useCallback(() => {
    initializeMappingExpression();
  }, []);
 
  addFieldToExpression = mappingExpressionAddField;
  clearText = mappingExpressionClearText;
  fieldSearch = executeFieldSearch;
  getEnums = getFieldEnums;
  setSelEnumValue = setSelectedEnumValue;
 
  getMappingExpression = () => mappingExpression || '';
  mappingExprInit = mappingExpressionInit;
  mappingExprObservable = mappingExpressionObservable;
  trailerID = trailerId;
  trailerHTML = `<span id="${trailerID}">&nbsp;</span>`;
 
  const uninitializeMappingExpression = () => {
    if (expressionUpdatedSubscription) {
      expressionUpdatedSubscription.unsubscribe();
    }
  };
 
  useEffect(() => {
    if (mappingExpression !== undefined) {
      initMappingExpression();
      return () => uninitializeMappingExpression();
    }
    return;
  }, [mappingExpression, initMappingExpression]);
 
  return (
    <>
      <Form>
        <FormGroup fieldId="expressionContent">
          <InputGroup>
            <Tooltip
              content={'Enable/ Disable conditional mapping expression.'}
              enableFlip={true}
              entryDelay={750}
              exitDelay={100}
              position={'left'}
            >
              <Button
                variant={'control'}
                aria-label="Enable/ Disable conditional mapping expression"
                tabIndex={-1}
                onClick={onToggle}
                data-testid={
                  'enable-disable-conditional-mapping-expression-button'
                }
                isDisabled={disabled}
              >
                <i>
                  f
                  <small style={{ position: 'relative', bottom: -3 }}>
                    (x)
                  </small>
                </i>
              </Button>
            </Tooltip>
            {!disabled && mappingExpression !== undefined ? (
              <Tooltip
                content={"Enter text or '@' for sourceĀ fields menu."}
                enableFlip={true}
                entryDelay={750}
                exitDelay={100}
                position={'left'}
              >
                <div
                  id="expressionMarkup"
                  key="expressionMarkup-div"
                  aria-label="Expression Content"
                  contentEditable
                  className={css(styles.formControl, 'ExpressionFieldSearch')}
                  suppressContentEditableWarning={true}
                  onChange={onChange}
                  onKeyDown={onKeyDown}
                  onKeyPress={onKeyPress}
                  onPaste={onPaste}
                  onClick={onExprClick}
                  ref={(el) => (markup = el)}
                  tabIndex={-1}
                  style={{ paddingLeft: 8 }}
                />
              </Tooltip>
            ) : (
              <TextInput
                isDisabled={true}
                aria-label={'Expression content'}
              /> /* this to render a disabled field */
            )}
          </InputGroup>
        </FormGroup>
      </Form>
      <div>
        {mappedFieldCandidates.length > 0 && (
          <span>
            <ExpressionFieldSearch
              clearSearchMode={clearSearchMode}
              insertSelectedField={insertSelectedField}
              mappedFieldCandidates={mappedFieldCandidates}
            />
          </span>
        )}
        {showEnumSelect && (
          <span>
            <ExpressionEnumSelect
              selectedNodeId={selectedNodeId}
              enumCandidates={enumCandidates!}
              clearEnumSelect={clearEnumSelect}
              onEnumSelect={onEnumSelect}
            />
          </span>
        )}
      </div>
    </>
  );
};