All files / src/components notebook-jobs-list.tsx

0% Statements 0/58
0% Branches 0/41
0% Functions 0/14
0% Lines 0/56

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import React, { useEffect, useState } from 'react';
 
import { JupyterFrontEnd } from '@jupyterlab/application';
 
import { Signal } from '@lumino/signaling';
 
import { useTranslator } from '../hooks';
import { CreateJobFormState } from '../create-job-form';
 
import { JobRow } from './job-row';
import { INotebookJobsWithToken } from '../model';
import {
  Button,
  caretDownIcon,
  caretUpIcon,
  LabIcon
} from '@jupyterlab/ui-components';
import { Scheduler, SchedulerService } from '../handler';
 
const ListItemClass = 'jp-notebook-job-list-item';
 
export const JobListPageSize = 25;
 
interface LoadJobsProps {
  showHeaders?: boolean;
  startToken?: string;
  app: JupyterFrontEnd;
  createJobFormSignal: Signal<any, CreateJobFormState>;
  // Function that results in the create job form being made visible.
  showCreateJob: () => void;
  // Function that retrieves some jobs
  getJobs: (
    query: Scheduler.IListJobsQuery
  ) => Promise<INotebookJobsWithToken | undefined>;
}
 
// Used for table cells including headers
const jobTraitClass = 'jp-notebook-job-list-trait';
 
type GridColumn = {
  sortField: string | null;
  name: string;
};
 
export function NotebookJobsListBody(props: LoadJobsProps): JSX.Element {
  const [notebookJobs, setNotebookJobs] = useState<
    INotebookJobsWithToken | undefined
  >(undefined);
  const [jobsQuery, setJobsQuery] = useState<Scheduler.IListJobsQuery>({});
 
  const fetchInitialRows = () => {
    // Get initial job list (next_token is undefined)
    props.getJobs(jobsQuery).then(initialNotebookJobs => {
      setNotebookJobs(initialNotebookJobs);
    });
  };
 
  // Fetch the initial rows asynchronously on component creation
  // After setJobsQuery is called, force a reload.
  useEffect(() => fetchInitialRows(), [jobsQuery]);
 
  const fetchMoreRows = async (next_token: string) => {
    // Apply the custom token to the existing query parameters
    const newNotebookJobs = await props.getJobs({ ...jobsQuery, next_token });
 
    Iif (!newNotebookJobs) {
      return;
    }
 
    // Merge the two lists of jobs and keep the next token from the new response.
    setNotebookJobs({
      jobs: [...(notebookJobs?.jobs || []), ...(newNotebookJobs?.jobs || [])],
      next_token: newNotebookJobs.next_token
    });
  };
 
  const reloadButton = (
    <Button onClick={() => fetchInitialRows()}>Reload</Button>
  );
 
  const trans = useTranslator('jupyterlab');
 
  Iif (notebookJobs === undefined) {
    return (
      <p>
        <em>{trans.__('Loading …')}</em>
      </p>
    );
  }
 
  Iif (!notebookJobs?.jobs.length) {
    return (
      <>
        {reloadButton}
        <p className={'jp-notebook-job-list-empty'}>
          {trans.__(
            'There are no scheduled jobs. ' +
              'Right-click on a file in the file browser to run or schedule a notebook.'
          )}
        </p>
      </>
    );
  }
 
  // Display column headers with sort indicators.
  const columns: GridColumn[] = [
    {
      sortField: 'name',
      name: trans.__('Job name')
    },
    {
      sortField: 'input_uri',
      name: trans.__('Input file')
    },
    {
      sortField: null, // Output prefix is not visible in UI
      name: trans.__('Output files')
    },
    {
      sortField: 'start_time',
      name: trans.__('Start time')
    },
    {
      sortField: 'status', // This will sort on the server status, not localized
      name: trans.__('Status')
    },
    {
      sortField: null, // Non sortable
      name: trans.__('Actions')
    }
  ];
 
  return (
    <>
      {reloadButton}
      <div className={`${ListItemClass} jp-notebook-job-list-header`}>
        {columns.map((column, idx) => (
          <NotebookJobsColumnHeader
            key={idx}
            gridColumn={column}
            jobsQuery={jobsQuery}
            setJobsQuery={setJobsQuery}
          />
        ))}
      </div>
      {notebookJobs.jobs.map(job => (
        <JobRow
          key={job.job_id}
          job={job}
          createJobFormSignal={props.createJobFormSignal}
          rowClass={ListItemClass}
          cellClass={jobTraitClass}
          app={props.app}
          showCreateJob={props.showCreateJob}
        />
      ))}
      {notebookJobs.next_token && (
        <Button
          onClick={(e: React.MouseEvent<HTMLElement>) =>
            fetchMoreRows(notebookJobs.next_token!)
          }
        >
          {trans.__('Show more')}
        </Button>
      )}
    </>
  );
}
 
interface NotebookJobsColumnHeaderProps {
  gridColumn: GridColumn;
  jobsQuery: Scheduler.IListJobsQuery;
  setJobsQuery: React.Dispatch<React.SetStateAction<Scheduler.IListJobsQuery>>;
}
 
const sortAscendingIcon = (
  <LabIcon.resolveReact icon={caretUpIcon} tag="span" />
);
const sortDescendingIcon = (
  <LabIcon.resolveReact icon={caretDownIcon} tag="span" />
);
 
function NotebookJobsColumnHeader(
  props: NotebookJobsColumnHeaderProps
): JSX.Element {
  const sort = props.jobsQuery.sort_by;
  const defaultSort = sort?.[0];
 
  const headerIsDefaultSort =
    defaultSort && defaultSort.name === props.gridColumn.sortField;
  const isSortedAscending =
    headerIsDefaultSort &&
    defaultSort!.direction === Scheduler.SortDirection.ASC;
  const isSortedDescending =
    headerIsDefaultSort &&
    defaultSort!.direction === Scheduler.SortDirection.DESC;
 
  const sortByThisColumn = () => {
    // If this field is not sortable, do nothing.
    Iif (!props.gridColumn.sortField) {
      return;
    }
 
    // Change the sort of this column.
    // If not sorted at all or if sorted descending, sort ascending. If sorted ascending, sort descending.
    let newSortDirection = isSortedAscending
      ? Scheduler.SortDirection.DESC
      : Scheduler.SortDirection.ASC;
 
    // Set the new sort direction.
    const newSort: Scheduler.ISortField = {
      name: props.gridColumn.sortField,
      direction: newSortDirection
    };
 
    // If this field is already present in the sort list, remove it.
    const oldSortList = sort || [];
    const newSortList = [
      newSort,
      ...oldSortList.filter(item => item.name !== props.gridColumn.sortField)
    ];
 
    // Sub the new sort list in to the query.
    props.setJobsQuery({ ...props.jobsQuery, sort_by: newSortList });
  };
 
  return (
    <div className={jobTraitClass} onClick={sortByThisColumn}>
      {props.gridColumn.name}
      {isSortedAscending && sortAscendingIcon}
      {isSortedDescending && sortDescendingIcon}
    </div>
  );
}
 
function getJobs(
  jobQuery: Scheduler.IListJobsQuery
): Promise<INotebookJobsWithToken | undefined> {
  const api = new SchedulerService({});
 
  // Impose max_items if not otherwise specified.
  Iif (!jobQuery.hasOwnProperty('max_items')) {
    jobQuery.max_items = JobListPageSize;
  }
 
  return api.getJobs(jobQuery);
}
 
export function NotebookJobsList(
  props: NotebookJobsList.IOptions
): JSX.Element {
  const trans = useTranslator('jupyterlab');
  const header = <h1>{trans.__('Notebook Job Runs')}</h1>;
 
  // Retrieve the initial jobs list
  return (
    <div className={'jp-notebook-job-list'}>
      {header}
      <NotebookJobsListBody
        showHeaders={true}
        createJobFormSignal={props.createJobFormSignal}
        app={props.app}
        showCreateJob={props.showCreateJob}
        getJobs={getJobs}
      />
    </div>
  );
}
 
export namespace NotebookJobsList {
  export interface IOptions {
    app: JupyterFrontEnd;
    createJobFormSignal: Signal<any, CreateJobFormState>;
    // Function that results in the create-job form being made visible.
    showCreateJob: () => void;
  }
}