All files / modules/10-common/components/MonacoTextField MonacoTextField.tsx

72.22% Statements 26/36
57.14% Branches 20/35
44.44% Functions 4/9
72.22% Lines 26/36

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              109x   109x 109x 109x 109x 109x   109x 109x 109x   109x                                   109x 109x   109x 54x 54x 54x 54x   54x 32x   32x                                                         32x 25x         54x                                                       1x                             54x                                     109x  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React from 'react'
import type { MonacoEditorBaseProps, MonacoEditorProps } from 'react-monaco-editor'
import { FormikProps, connect } from 'formik'
import { defaultTo, get } from 'lodash-es'
import cx from 'classnames'
import { Dialog, Classes } from '@blueprintjs/core'
import { Button, Container } from '@harness/uicore'
import type { languages, IDisposable } from 'monaco-editor/esm/vs/editor/editor.api'
import { useStrings } from 'framework/strings'
import MonacoEditor from '@common/components/MonacoEditor/MonacoEditor'
import { useDeepCompareEffect } from '@common/hooks'
 
import css from './MonacoTextField.module.scss'
 
type Languages = typeof languages
 
export interface MonacoTextFieldProps {
  name: string
  height?: MonacoEditorBaseProps['height']
  disabled?: boolean
  expressions?: string[]
  'data-testid'?: string
  fullScreenAllowed?: boolean
  fullScreenTitle?: string
}
 
export interface ConnectedMonacoTextFieldProps extends MonacoTextFieldProps {
  formik: FormikProps<unknown>
}
 
const VAR_REGEX = /.*<\+.*?/
const LANG_ID = 'plaintext'
 
export function MonacoText(props: ConnectedMonacoTextFieldProps): React.ReactElement {
  const { formik, name, disabled, expressions, height = 70, fullScreenAllowed, fullScreenTitle } = props
  const [isFullScreen, setFullScreen] = React.useState(false)
  const { getString } = useStrings()
  const value = get(formik.values, name) || ''
 
  useDeepCompareEffect(() => {
    let disposable: IDisposable | null = null
 
    Iif (Array.isArray(expressions) && expressions.length > 0) {
      const suggestions: Array<Partial<languages.CompletionItem>> = expressions
        .filter(label => label)
        .map(label => ({
          label,
          insertText: label + '>',
          kind: 13
        }))
 
      disposable = (monaco?.languages as Languages)?.registerCompletionItemProvider(LANG_ID, {
        triggerCharacters: ['+', '.'],
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        provideCompletionItems(model, position): any {
          const prevText = model.getValueInRange({
            startLineNumber: position.lineNumber,
            startColumn: 0,
            endLineNumber: position.lineNumber,
            endColumn: position.column
          })
 
          if (VAR_REGEX.test(prevText)) {
            return { suggestions }
          }
 
          return { suggestions: [] }
        }
      })
    }
 
    return () => {
      disposable?.dispose()
    }
  }, [expressions])
 
  const editor = (
    <div className={cx(css.main, { [css.disabled]: disabled })}>
      <MonacoEditor
        height={fullScreenAllowed && isFullScreen ? '70vh' : height}
        value={value}
        language={LANG_ID}
        options={
          {
            fontFamily: "'Roboto Mono', monospace",
            fontSize: 14,
            minimap: {
              enabled: false
            },
            readOnly: disabled,
            scrollBeyondLastLine: false,
            lineNumbers: 'off',
            glyphMargin: false,
            folding: false,
            lineDecorationsWidth: 0,
            wordWrap: 'on',
            scrollbar: {
              verticalScrollbarSize: 0
            },
            renderLineHighlight: 'none',
            wordWrapBreakBeforeCharacters: '',
            mouseStyle: disabled ? 'default' : 'text',
            lineNumbersMinChars: 0
          } as MonacoEditorProps['options']
        }
        onChange={txt => formik.setFieldValue(name, txt)}
        {...({ name: props.name, 'data-testid': props['data-testid'] } as any)} // this is required for test cases
      />
      {fullScreenAllowed && !isFullScreen ? (
        <Button
          className={css.expandBtn}
          icon="fullscreen"
          small
          onClick={() => setFullScreen(true)}
          iconProps={{ size: 10 }}
        />
      ) : null}
    </div>
  )
 
  return (
    <React.Fragment>
      {fullScreenAllowed && isFullScreen ? <Container className={css.main} /> : editor}
      <Dialog
        lazy
        enforceFocus={false}
        isOpen={isFullScreen}
        isCloseButtonShown
        canOutsideClickClose={false}
        onClose={() => setFullScreen(false)}
        title={defaultTo(fullScreenTitle, getString('common.input'))}
        className={css.monacoDialog}
      >
        <div className={Classes.DIALOG_BODY}>{editor}</div>
      </Dialog>
    </React.Fragment>
  )
}
 
export const MonacoTextField = connect<MonacoTextFieldProps>(MonacoText)