All files / src create-job-form.tsx

0% Statements 0/100
0% Branches 0/37
0% Functions 0/23
0% Lines 0/95

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { ToolbarButtonComponent } from '@jupyterlab/apputils';
import { addIcon, Button, closeIcon, LabIcon } from '@jupyterlab/ui-components';
import React, { ChangeEvent, useEffect, useState } from 'react';
 
import { EnvironmentPicker } from './components/environment-picker';
import {
  OutputFormatOption,
  OutputFormatPicker,
  outputFormatsForEnvironment
} from './components/output-format-picker';
 
import { Scheduler, SchedulerService } from './handler';
import { useTranslator } from './hooks';
 
export type CreateJobFormProps = {
  initialState: CreateJobFormState;
  cancelClick: () => void;
  // Function to run after a create job request completes successfully
  postCreateJob: () => void;
};
 
export type JobParameter = {
  name: string;
  value: string;
};
 
// This type is based on ICreateJobInputModel, but parameters is ordered
// for use in the form's display.
export type CreateJobFormState = {
  jobName: string;
  inputFile: string;
  outputPath: string;
  environment: string;
  parameters?: JobParameter[];
  outputFormats?: OutputFormatOption[];
};
 
export function CreateJobForm(props: CreateJobFormProps) {
  const trans = useTranslator('jupyterlab');
 
  const [state, setState] = useState<CreateJobFormState>({
    jobName: '',
    inputFile: '',
    outputPath: '',
    environment: '',
    parameters: [],
    outputFormats: []
  });
 
  useEffect(() => {
    Iif (props.initialState) {
      setState(prevState => ({ ...props.initialState }));
    }
  }, [props.initialState]);
 
  const handleInputChange = (event: ChangeEvent) => {
    const target = event.target as HTMLInputElement;
 
    const parameterNameMatch = target.name.match(/^parameter-(\d+)-name$/);
    const parameterValueMatch = target.name.match(/^parameter-(\d+)-value$/);
    if (parameterNameMatch !== null) {
      const idx = parseInt(parameterNameMatch[1]);
      // Update the parameters
      const newParams = state.parameters || [];
      newParams[idx].name = target.value;
      setState({ ...state, parameters: newParams });
    } else if (parameterValueMatch !== null) {
      const idx = parseInt(parameterValueMatch[1]);
      // Update the parameters
      const newParams = state.parameters || [];
      newParams[idx].value = target.value;
      setState(prevState => ({ ...prevState, parameters: newParams }));
    } else {
      const value = target.type === 'checkbox' ? target.checked : target.value;
      const name = target.name;
      setState(prevState => ({ ...prevState, [name]: value }));
    }
  };
 
  const handleOutputFormatsChange = (event: ChangeEvent<HTMLInputElement>) => {
    const outputFormatsList = outputFormatsForEnvironment(state.environment);
    Iif (outputFormatsList === null) {
      return; // No data about output formats; give up
    }
 
    const formatName = event.target.value;
    const isChecked = event.target.checked;
 
    const wasChecked: boolean = state.outputFormats
      ? state.outputFormats.some(of => of.name === formatName)
      : false;
 
    const oldOutputFormats: OutputFormatOption[] = state.outputFormats || [];
 
    // Go from unchecked to checked
    if (isChecked && !wasChecked) {
      // Get the output format matching the given name
      const newFormat = outputFormatsList.find(of => of.name === formatName);
      Iif (newFormat) {
        setState({ ...state, outputFormats: [...oldOutputFormats, newFormat] });
      }
    }
    // Go from checked to unchecked
    else Iif (!isChecked && wasChecked) {
      setState({
        ...state,
        outputFormats: oldOutputFormats.filter(of => of.name !== formatName)
      });
    }
 
    // If no change in checkedness, don't do anything
  };
 
  const submitCreateJobRequest = async (event: React.MouseEvent) => {
    const api = new SchedulerService({});
 
    // Serialize parameters as an object.
    let jobOptions: Scheduler.ICreateJob = {
      name: state.jobName,
      input_uri: state.inputFile,
      output_prefix: state.outputPath,
      runtime_environment_name: state.environment
    };
 
    Iif (state.parameters !== undefined) {
      let jobParameters: { [key: string]: any } = {};
 
      state.parameters.forEach(param => {
        const { name, value } = param;
        if (jobParameters.hasOwnProperty(name)) {
          console.error(
            'Parameter ' +
              name +
              ' already set to ' +
              jobParameters[name] +
              ' and is about to be set again to ' +
              value
          );
        } else {
          jobParameters[name] = value;
        }
      });
 
      jobOptions.parameters = jobParameters;
    }
 
    Iif (state.outputFormats !== undefined) {
      jobOptions.output_formats = state.outputFormats.map(entry => entry.name);
    }
 
    api.createJob(jobOptions).then(response => {
      props.postCreateJob();
    });
  };
 
  const removeParameter = (idx: number) => {
    const newParams = state.parameters || [];
    newParams.splice(idx, 1);
 
    setState({ ...state, parameters: newParams });
  };
 
  const addParameter = () => {
    const newParams = state.parameters || [];
    newParams.push({ name: '', value: '' });
 
    setState({ ...state, parameters: newParams });
  };
 
  const api = new SchedulerService({});
  const environmentsPromise = async () => {
    const environmentsCache = sessionStorage.getItem('environments');
    Iif (environmentsCache !== null) {
      return JSON.parse(environmentsCache);
    }
 
    return api.getRuntimeEnvironments().then(envs => {
      sessionStorage.setItem('environments', JSON.stringify(envs));
      return envs;
    });
  };
 
  const nameInputName = 'jobName';
  const inputFileInputName = 'inputFile';
  const outputPathInputName = 'outputPath';
  const environmentInputName = 'environment';
  const outputFormatInputName = 'outputFormat';
  const formPrefix = 'jp-create-job-';
  const formRow = `${formPrefix}row`;
  const formLabel = `${formPrefix}label`;
  const formInput = `${formPrefix}input`;
 
  return (
    <div className={`${formPrefix}form-container`}>
      <form className={`${formPrefix}form`} onSubmit={e => e.preventDefault()}>
        <div className={formRow}>
          <label
            className={formLabel}
            htmlFor={`${formPrefix}${nameInputName}`}
          >
            {trans.__('Job name')}
          </label>
          <input
            type="text"
            className={formInput}
            name={nameInputName}
            id={`${formPrefix}${nameInputName}`}
            value={state.jobName}
            onChange={handleInputChange}
          />
        </div>
        <div className={formRow}>
          <label
            className={formLabel}
            htmlFor={`${formPrefix}${inputFileInputName}`}
          >
            {trans.__('Input file')}
          </label>
          <input
            type="text"
            className={formInput}
            name={inputFileInputName}
            id={`${formPrefix}${inputFileInputName}`}
            value={state.inputFile}
            onChange={handleInputChange}
          />
        </div>
        <div className={formRow}>
          <label
            className={formLabel}
            htmlFor={`${formPrefix}${outputPathInputName}`}
          >
            {trans.__('Output prefix')}
          </label>
          <input
            type="text"
            className={formInput}
            name={outputPathInputName}
            id={`${formPrefix}${outputPathInputName}`}
            value={state.outputPath}
            onChange={handleInputChange}
          />
        </div>
        <div className={formRow}>
          <label
            className={formLabel}
            htmlFor={`${formPrefix}${environmentInputName}`}
          >
            {trans.__('Environment')}
          </label>
          <div className={formInput}>
            <EnvironmentPicker
              name={environmentInputName}
              id={`${formPrefix}${environmentInputName}`}
              onChange={handleInputChange}
              environmentsPromise={environmentsPromise()}
              initialValue={state.environment}
            />
          </div>
        </div>
        <OutputFormatPicker
          name={outputFormatInputName}
          id={`${formPrefix}${outputFormatInputName}`}
          onChange={handleOutputFormatsChange}
          environment={state.environment}
          value={state.outputFormats || []}
          rowClassName={formRow}
          labelClassName={formLabel}
          inputClassName={formInput}
        />
        <div className={formRow}>
          <label className={formLabel}>{trans.__('Parameters')}</label>
          <div className={formInput}>
            {state.parameters &&
              state.parameters.map((param, idx) => (
                <div key={idx} className={`${formPrefix}parameter-row`}>
                  <input
                    name={`parameter-${idx}-name`}
                    size={15}
                    value={param.name}
                    type="text"
                    placeholder={trans.__('Name')}
                    onChange={handleInputChange}
                  />
                  <input
                    name={`parameter-${idx}-value`}
                    size={15}
                    value={param.value}
                    type="text"
                    placeholder={trans.__('Value')}
                    onChange={handleInputChange}
                  />
                  <ToolbarButtonComponent
                    className={`${formPrefix}inline-button`}
                    icon={closeIcon}
                    onClick={() => {
                      removeParameter(idx);
                      return false;
                    }}
                    tooltip={trans.__('Delete this parameter')}
                  />
                </div>
              ))}
            <Button
              minimal={true}
              onClick={(e: React.MouseEvent) => {
                addParameter();
                return false;
              }}
              title={trans.__('Add new parameter')}
            >
              <LabIcon.resolveReact icon={addIcon} tag="span" />
            </Button>
          </div>
        </div>
        <div className={formRow}>
          <div className={formLabel}>&nbsp;</div>
          <div className={`${formInput} ${formPrefix}submit-container`}>
            <Button
              type="button"
              className="jp-Dialog-button jp-mod-styled"
              onClick={props.cancelClick}
            >
              {trans.__('Cancel')}
            </Button>
            <Button
              type="submit"
              className="jp-Dialog-button jp-mod-accept jp-mod-styled"
              onClick={(e: React.MouseEvent) => {
                submitCreateJobRequest(e);
                return false;
              }}
            >
              {trans.__('Run Job')}
            </Button>
          </div>
        </div>
      </form>
    </div>
  );
}