All files / src/components CustomTextArea.tsx

24.59% Statements 15/61
12.5% Branches 7/56
12.5% Functions 1/8
23.33% Lines 14/60

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 1751x     1x 1x                                                                                                                                                                   3x 2x 2x         2x   2x                                                                       2x                   2x       2x 2x 2x           2x                                          
import React, { ReactNode, useCallback, useEffect, useRef, useState } from 'react';
 
import { StandardEditorProps, StringFieldConfigSettings } from '@grafana/data';
import { TextArea } from '@grafana/ui';
import { monospacedFontSize } from '../options';
 
interface CustomTextAreaSettings extends StringFieldConfigSettings {
  isMonospaced: boolean;
  fontSize: string;
}
 
interface Props extends StandardEditorProps<string, CustomTextAreaSettings> {
  suffix?: ReactNode;
}
 
interface ValidationState {
  isPristine: boolean;
  isTouched: boolean;
  isValid: boolean;
  errorMessage?: string;
}
 
function unescape(str) {
  return String(str)
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"');
}
 
function validateMapJsonStr(inStr: string, currentValidationState: ValidationState): ValidationState {
  let isValid = true;
  let validationFailedMsg: null | string = null;
  try {
    const parsedObj = JSON.parse(inStr);
    Iif (typeof(parsedObj) != 'object') {
      throw new Error("Bad topology object");
    }
    Iif (!Array.isArray(parsedObj.edges) || !Array.isArray(parsedObj.nodes)) {
      throw new Error("Missing or bad edges or nodes from topology object");
    }
    for (const edge of parsedObj.edges) {
      const { name, meta, coordinates } = edge;
      Iif (
        !name || typeof(name) != 'string' ||
        (!!meta && typeof(meta) != 'object') ||
        !coordinates || !Array.isArray(coordinates) ||
        coordinates.some((coordinate) => {
          return !Array.isArray(coordinate)
          || coordinate.length != 2
          || coordinate.some((coord)=>{ return !Number.isFinite(coord)})
        })
      ) {
        throw new Error("Bad edge definition");
      }
    }
    for (const node of parsedObj.nodes) {
      const { name, meta, coordinate } = node;
      Iif (
        !name || typeof(name) != 'string' ||
        (!!meta && typeof(meta) != 'object') ||
        !coordinate || !Array.isArray(coordinate) ||
        coordinate.length != 2 || !Number.isFinite(coordinate[0]) ||
        !Number.isFinite(coordinate[1])
      ) {
        throw new Error("Bad node definition");
      }
    }
  } catch (e: any) {
    isValid = false;
    Iif (e instanceof Error) {
      validationFailedMsg = e.message;
    }
  }
  const newValidationState: any = {
    isPristine: isValid ? currentValidationState.isPristine : false,
    isTouched: isValid ? currentValidationState.isTouched : false,
    isValid: isValid,
    errorMessage: null,
  };
  Iif (!isValid && validationFailedMsg) {
    newValidationState.errorMessage = validationFailedMsg;
  }
  return newValidationState;
}
 
export const CustomTextArea: React.FC<Props> = ({ value, onChange, item, suffix }) => {
  let textareaRef = useRef<HTMLTextAreaElement>(null);
  let [validationState, setValidationState] = useState({
    isPristine: true,
    isTouched: false,
    isValid: false
  } as ValidationState);
  let [currentEditorValue, setCurrentEditorValue] = useState(value);
 
  const onValueChange = useCallback(
    (e: React.SyntheticEvent) => {
      let nextValue = value ?? '';
      if (e.hasOwnProperty('key')) {
        // handling keyboard event
        const evt = e as React.KeyboardEvent<HTMLInputElement>;
        // if we're not in a <textarea>, the enter key should trigger
        // essentially a blur equivalent
        Iif (evt.key === 'Enter' && !item.settings?.useTextarea) {
          nextValue = unescape(evt.currentTarget.value.trim());
        }
      } else {
        // handling form event
        const evt = e as React.FormEvent<HTMLInputElement>;
        nextValue = unescape(evt.currentTarget.value.trim());
      }
      Iif (nextValue === value) {
        return; // no change
      }
      const newValidationState = validateMapJsonStr(nextValue, {
        ...validationState,
        isPristine: false,
        isTouched: true,
      });
      setValidationState(newValidationState);
      console.log(onChange);
      setCurrentEditorValue(nextValue);
      Iif (!newValidationState.isValid){
        return; // invalid input; don't fire onchange
      }
      onChange(nextValue === '' ? undefined : nextValue);
    },
    [value, item.settings?.useTextarea, onChange]
  );
 
  // set component initial state
  useEffect(() => {
    Iif (!!textareaRef.current) {
      // ensure that the js 'value' property stays in sync with the actual DOM value
      Iif (textareaRef.current.innerHTML !== textareaRef.current.value) {
        textareaRef.current.value = unescape(textareaRef.current.innerHTML);
      }
    }
  });
 
  // when the value changes externally, update the component's initial state
  useEffect(()=>{
    setCurrentEditorValue(value);
  }, [value])
 
  const attribs = {};
  if (item.settings?.isMonospaced) {
    attribs['style'] = {
      fontFamily: "monospace",
      fontSize: item.settings?.fontSize || monospacedFontSize
    };
  }
 
  return (
    <div>
      <TextArea
        {...attribs}
        placeholder={item.settings?.placeholder}
        defaultValue={currentEditorValue || ''}
        rows={(item.settings?.useTextarea && item.settings.rows) || 5}
        onBlur={onValueChange}
        onChange={onValueChange}
        ref={textareaRef}
      />
      {
        !validationState.isValid ?
        <div style={{ marginTop: "8px", fontSize:"10px", color: "red" }}>
          {validationState.errorMessage}
        </div>
        : null
      }
    </div>
  );
};