From 4574b7f03ccc85c4bebdbfd9475788456086704f Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Thu, 8 Aug 2024 12:27:40 -0400
Subject: many changes to add typing in place of 'any's etc

---
 src/client/views/nodes/ScriptingBox.tsx | 96 ++++++++++++++++-----------------
 1 file changed, 45 insertions(+), 51 deletions(-)

(limited to 'src/client/views/nodes/ScriptingBox.tsx')

diff --git a/src/client/views/nodes/ScriptingBox.tsx b/src/client/views/nodes/ScriptingBox.tsx
index bc19d7ad1..8da422039 100644
--- a/src/client/views/nodes/ScriptingBox.tsx
+++ b/src/client/views/nodes/ScriptingBox.tsx
@@ -1,8 +1,8 @@
 /* eslint-disable react/button-has-type */
-/* eslint-disable jsx-a11y/no-static-element-interactions */
 import { action, computed, makeObservable, observable } from 'mobx';
 import { observer } from 'mobx-react';
 import * as React from 'react';
+import ResizeObserver from 'resize-observer-polyfill';
 import { returnAlways, returnEmptyString } from '../../../ClientUtils';
 import { Doc } from '../../../fields/Doc';
 import { List } from '../../../fields/List';
@@ -10,21 +10,26 @@ import { listSpec } from '../../../fields/Schema';
 import { ScriptField } from '../../../fields/ScriptField';
 import { BoolCast, Cast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
 import { TraceMobx } from '../../../fields/util';
+import { DocumentType } from '../../documents/DocumentTypes';
+import { Docs } from '../../documents/Documents';
 import { DragManager } from '../../util/DragManager';
 import { ScriptManager } from '../../util/ScriptManager';
-import { CompileScript, ScriptParam } from '../../util/Scripting';
+import { CompileError, CompileScript, ScriptParam } from '../../util/Scripting';
 import { ScriptingGlobals } from '../../util/ScriptingGlobals';
 import { ContextMenu } from '../ContextMenu';
 import { ViewBoxAnnotatableComponent } from '../DocComponent';
 import { EditableView } from '../EditableView';
 import { OverlayView } from '../OverlayView';
-import { FieldView, FieldViewProps } from './FieldView';
 import { DocumentIconContainer } from './DocumentIcon';
+import { FieldView, FieldViewProps } from './FieldView';
 import './ScriptingBox.scss';
-import { Docs } from '../../documents/Documents';
-import { DocumentType } from '../../documents/DocumentTypes';
+import * as ts from 'typescript';
+import { FieldType } from '../../../fields/ObjectField';
+
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const getCaretCoordinates = require('textarea-caret');
 
-const _global = (window /* browser */ || global) /* node */ as any;
+// eslint-disable-next-line @typescript-eslint/no-var-requires
 const ReactTextareaAutocomplete = require('@webscopeio/react-textarea-autocomplete').default;
 
 @observer
@@ -41,9 +46,9 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     @observable private _function: boolean = false;
     @observable private _spaced: boolean = false;
 
-    @observable private _scriptKeys: any = ScriptingGlobals.getGlobals();
-    @observable private _scriptingDescriptions: any = ScriptingGlobals.getDescriptions();
-    @observable private _scriptingParams: any = ScriptingGlobals.getParameters();
+    @observable private _scriptKeys = ScriptingGlobals.getGlobals();
+    @observable private _scriptingDescriptions = ScriptingGlobals.getDescriptions();
+    @observable private _scriptingParams = ScriptingGlobals.getParameters();
 
     @observable private _currWord: string = '';
     @observable private _suggestions: string[] = [];
@@ -52,20 +57,20 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     @observable private _suggestionBoxY: number = 0;
     @observable private _lastChar: string = '';
 
-    @observable private _suggestionRef: any = React.createRef();
-    @observable private _scriptTextRef: any = React.createRef();
+    @observable private _suggestionRef = React.createRef<HTMLDivElement>();
+    @observable private _scriptTextRef = React.createRef<HTMLDivElement>();
 
-    @observable private _selection: any = 0;
+    @observable private _selection = 0;
 
     @observable private _paramSuggestion: boolean = false;
-    @observable private _scriptSuggestedParams: any = '';
-    @observable private _scriptParamsText: any = '';
+    @observable private _scriptSuggestedParams: JSX.Element | string = '';
+    @observable private _scriptParamsText = '';
 
     constructor(props: FieldViewProps) {
         super(props);
         makeObservable(this);
         if (!this.compileParams.length) {
-            const params = ScriptCast(this.dataDoc[this._props.fieldKey])?.script.options.params as { [key: string]: any };
+            const params = ScriptCast(this.dataDoc[this._props.fieldKey])?.script.options.params as { [key: string]: string };
             if (params) {
                 this.compileParams = Array.from(Object.keys(params))
                     .filter(p => !p.startsWith('_'))
@@ -106,26 +111,16 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
         this.dataDoc[this.fieldKey + '-params'] = new List<string>(value);
     }
 
-    getValue(result: any, descrip: boolean) {
-        if (typeof result === 'object') {
-            const text = descrip ? result[1] : result[2];
-            return text !== undefined ? text : '';
-        }
-        return '';
-    }
-
     onClickScriptDisable = returnAlways;
 
     @action
     componentDidMount() {
         this._props.setContentViewBox?.(this);
         this.rawText = this.rawScript;
-        const resizeObserver = new _global.ResizeObserver(
+        const resizeObserver = new ResizeObserver(
             action(() => {
                 const area = document.querySelector('textarea');
                 if (area) {
-                    // eslint-disable-next-line global-require
-                    const getCaretCoordinates = require('textarea-caret');
                     const caret = getCaretCoordinates(area, this._selection);
                     this.resetSuggestionPos(caret);
                 }
@@ -135,12 +130,12 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     }
 
     @action
-    resetSuggestionPos(caret: any) {
+    resetSuggestionPos(caret: { top: number; left: number; height: number }) {
         if (!this._suggestionRef.current || !this._scriptTextRef.current) return;
         const suggestionWidth = this._suggestionRef.current.offsetWidth;
         const scriptWidth = this._scriptTextRef.current.offsetWidth;
         const { top } = caret;
-        const { x } = this.dataDoc;
+        const x = NumCast(this.layoutDoc.x);
         let { left } = caret;
         if (left + suggestionWidth > x + scriptWidth) {
             const diff = left + suggestionWidth - (x + scriptWidth);
@@ -171,8 +166,8 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
 
     // displays error message
     @action
-    onError = (error: any) => {
-        this._errorMessage = error?.message ? error.message : error?.map((entry: any) => entry.messageText).join('  ') || '';
+    onError = (errors: ts.Diagnostic[] | string) => {
+        this._errorMessage = typeof errors === 'string' ? errors : errors.map(entry => entry.toString()).join('  ') || '';
     };
 
     // checks if the script compiles using CompileScript method and inputting params
@@ -184,7 +179,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
         });
 
         const result = !this.rawText.trim()
-            ? ({ compiled: false, errors: undefined } as any)
+            ? ({ compiled: false, errors: [] } as CompileError)
             : CompileScript(this.rawText, {
                   editable: true,
                   transformer: DocumentIconContainer.getTransformer(),
@@ -192,7 +187,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                   typecheck: false,
               });
         this.dataDoc[this.fieldKey] = result.compiled ? new ScriptField(result, undefined, this.rawText) : undefined;
-        this.onError(result.compiled ? undefined : result.errors);
+        this.onError(result.compiled ? [] : result.errors);
         return result.compiled;
     };
 
@@ -200,7 +195,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     @action
     onRun = () => {
         if (this.onCompile()) {
-            const bindings: { [name: string]: any } = {};
+            const bindings: { [name: string]: unknown } = {};
             this.paramsNames.forEach(key => {
                 bindings[key] = this.dataDoc[key];
             });
@@ -294,8 +289,8 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
 
     // sets field of the param name to the selected value in drop down box
     @action
-    viewChanged = (e: React.ChangeEvent, name: string) => {
-        const val = (e.target as any).selectedOptions[0].value;
+    viewChanged = (e: React.ChangeEvent<HTMLSelectElement>, name: string) => {
+        const val = e.target.selectedOptions[0].value;
         this.dataDoc[name] = val[0] === 'S' ? val.substring(1) : val[0] === 'N' ? parseInt(val.substring(1)) : val.substring(1) === 'true';
     };
 
@@ -309,7 +304,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     // adds option to create a copy to the context menu
     specificContextMenu = (): void => {
         const existingOptions = ContextMenu.Instance.findByDescription('Options...');
-        const options = existingOptions && 'subitems' in existingOptions ? existingOptions.subitems : [];
+        const options = existingOptions?.subitems ?? [];
         options.push({ description: 'Create a Copy', event: this.onCopy, icon: 'copy' });
         !existingOptions && ContextMenu.Instance.addItem({ description: 'Options...', subitems: options, icon: 'hand-point-right' });
     };
@@ -381,7 +376,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                         const results = script.compiled && script.run();
                         if (results && results.success) {
                             this._errorMessage = '';
-                            this.dataDoc[parameter] = results.result;
+                            this.dataDoc[parameter] = results.result as FieldType;
                             return true;
                         }
                         this._errorMessage = 'invalid document';
@@ -524,18 +519,17 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
 
     @action
     suggestionPos = () => {
-        // eslint-disable-next-line global-require
-        const getCaretCoordinates = require('textarea-caret');
+        // eslint-disable-next-line @typescript-eslint/no-this-alias
         const This = this;
         document.querySelector('textarea')?.addEventListener('input', function () {
-            const caret = getCaretCoordinates(this, this.selectionEnd);
-            This._selection = this;
+            const caret = getCaretCoordinates(this, this.selectionEnd) as { top: number; left: number; height: number };
+            // This._selection = this;
             This.resetSuggestionPos(caret);
         });
     };
 
     @action
-    keyHandler(e: any, pos: number) {
+    keyHandler(e: React.KeyboardEvent, pos: number) {
         e.stopPropagation();
         if (this._lastChar === 'Enter') {
             this.rawText += ' ';
@@ -602,7 +596,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     }
 
     @action
-    handlePosChange(number: any) {
+    handlePosChange(number: number) {
         this._caretPos = number;
         if (this._caretPos === 0) {
             this.rawText = ' ' + this.rawText;
@@ -625,7 +619,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                     placeholder="write your script here"
                     onFocus={this.onFocus}
                     onBlur={() => this._overlayDisposer?.()}
-                    onChange={action((e: any) => {
+                    onChange={action((e: React.ChangeEvent<HTMLSelectElement>) => {
                         this.rawText = e.target.value;
                     })}
                     value={this.rawText}
@@ -633,24 +627,24 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                     loadingComponent={() => <span>Loading</span>}
                     trigger={{
                         ' ': {
-                            dataProvider: (token: any) => this.handleToken(token),
-                            component: (blob: any) => this.renderFuncListElement(blob.entity),
-                            output: (item: any, trigger: any) => {
+                            dataProvider: this.handleToken,
+                            component: (blob: { entity: string }) => this.renderFuncListElement(blob.entity),
+                            output: (item: string, trigger: string) => {
                                 this._spaced = true;
                                 return trigger + item.trim();
                             },
                         },
                         '.': {
-                            dataProvider: (token: any) => this.handleToken(token),
-                            component: (blob: any) => this.renderFuncListElement(blob.entity),
-                            output: (item: any, trigger: any) => {
+                            dataProvider: this.handleToken,
+                            component: (blob: { entity: string }) => this.renderFuncListElement(blob.entity),
+                            output: (item: string, trigger: string) => {
                                 this._spaced = true;
                                 return trigger + item.trim();
                             },
                         },
                     }}
                     onKeyDown={(e: React.KeyboardEvent) => this.keyHandler(e, this._caretPos)}
-                    onCaretPositionChange={(number: any) => this.handlePosChange(number)}
+                    onCaretPositionChange={this.handlePosChange}
                 />
             </div>
         );
-- 
cgit v1.2.3-70-g09d2

