luxon#Interval TypeScript Examples

The following examples show how to use luxon#Interval. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: getDurationFromDates.ts    From backstage with Apache License 2.0 6 votes vote down vote up
getDurationFromDates = (
  startTime?: string,
  finishTime?: string,
): string => {
  if (!startTime || (!startTime && !finishTime)) {
    return '';
  }

  const start = DateTime.fromISO(startTime);
  const finish = finishTime ? DateTime.fromISO(finishTime) : DateTime.now();

  const formatted = Interval.fromDateTimes(start, finish)
    .toDuration()
    .valueOf();

  const shortEnglishHumanizer = humanizeDuration.humanizer({
    language: 'shortEn',
    languages: {
      shortEn: {
        y: () => 'y',
        mo: () => 'mo',
        w: () => 'w',
        d: () => 'd',
        h: () => 'h',
        m: () => 'm',
        s: () => 's',
        ms: () => 'ms',
      },
    },
  });

  return shortEnglishHumanizer(formatted, {
    largest: 2,
    round: true,
    spacer: '',
  });
}
Example #2
Source File: time.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export function durationHumanized(
  startDateTimeISOString?: string,
  endDateTimeISOString?: string,
): string {
  if (!startDateTimeISOString || !endDateTimeISOString) {
    return '';
  }

  const startDateTime = DateTime.fromISO(startDateTimeISOString);
  const endDateTime = DateTime.fromISO(endDateTimeISOString);
  const duration = Interval.fromDateTimes(
    startDateTime,
    endDateTime,
  ).toDuration();

  return humanizeDuration(duration.as('milliseconds'), {
    largest: 1,
  });
}
Example #3
Source File: TaskPage.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
StepTimeTicker = ({ step }: { step: TaskStep }) => {
  const [time, setTime] = useState('');

  useInterval(() => {
    if (!step.startedAt) {
      setTime('');
      return;
    }

    const end = step.endedAt
      ? DateTime.fromISO(step.endedAt)
      : DateTime.local();

    const startedAt = DateTime.fromISO(step.startedAt);
    const formatted = Interval.fromDateTimes(startedAt, end)
      .toDuration()
      .valueOf();

    setTime(humanizeDuration(formatted, { round: true }));
  }, 1000);

  return <Typography variant="caption">{time}</Typography>;
}
Example #4
Source File: bitriseApi.client.ts    From backstage with Apache License 2.0 5 votes vote down vote up
async getBuilds(
    appSlug: string,
    params?: BitriseQueryParams,
  ): Promise<BitriseBuildListResponse> {
    const baseUrl = await this.discoveryApi.getBaseUrl('proxy');
    let url = `${baseUrl}/bitrise/apps/${appSlug}/builds`;

    if (params) {
      url = `${url}?${qs.stringify(pickBy(params, identity))}`;
    }

    const response = await fetch(url);
    const data = await response.json();
    const builds: BitriseBuildResponseItem[] = data.data;

    return {
      data: builds.map(
        (build: BitriseBuildResponseItem): BitriseBuildResult => {
          const duration = String(
            Math.round(
              Interval.fromDateTimes(
                DateTime.fromISO(build.started_on_worker_at),
                DateTime.fromISO(build.finished_at),
              ).length('minutes'),
            ),
          );

          return {
            id: build.build_number,
            source: build.commit_view_url,
            status: build.status,
            statusText: build.status_text,
            buildSlug: build.slug,
            message: `${build.branch}`,
            workflow: build.triggered_workflow,
            commitHash: `${build.commit_hash}`,
            triggerTime: build.triggered_at,
            duration: `${duration} minutes`,
            appSlug,
          };
        },
      ),
      paging: data.paging,
    };
  }
Example #5
Source File: CreatedAtColumn.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
CreatedAtColumn = ({ createdAt }: { createdAt: string }) => {
  const createdAtTime = DateTime.fromISO(createdAt);
  const formatted = Interval.fromDateTimes(createdAtTime, DateTime.local())
    .toDuration()
    .valueOf();

  return <p>{humanizeDuration(formatted, { round: true })} ago</p>;
}
Example #6
Source File: IncidentsTable.tsx    From backstage with Apache License 2.0 4 votes vote down vote up
IncidentsTable = ({
  incidents,
  incidentsCount,
  tableState,
  states,
  isLoading,
  onIncidentChanged,
  setIsLoading,
  onIncidentStatesChange,
  onChangePage,
  onChangeRowsPerPage,
  compact,
}: {
  incidents: Incident[];
  incidentsCount: number;
  tableState: TableState;
  states: IncidentStatus[];
  isLoading: boolean;
  onIncidentChanged: (incident: Incident) => void;
  setIsLoading: (isLoading: boolean) => void;
  onIncidentStatesChange: (states: IncidentStatus[]) => void;
  onChangePage: (page: number) => void;
  onChangeRowsPerPage: (pageSize: number) => void;
  compact?: boolean;
}) => {
  const ilertApi = useApi(ilertApiRef);
  const classes = useStyles();

  const xsColumnStyle = {
    width: '5%',
    maxWidth: '5%',
  };
  const smColumnStyle = {
    width: '10%',
    maxWidth: '10%',
  };
  const mdColumnStyle = {
    width: '15%',
    maxWidth: '15%',
  };
  const lgColumnStyle = {
    width: '20%',
    maxWidth: '20%',
  };
  const xlColumnStyle = {
    width: '30%',
    maxWidth: '30%',
  };

  const idColumn: TableColumn = {
    title: 'ID',
    field: 'id',
    highlight: true,
    cellStyle: smColumnStyle,
    headerStyle: smColumnStyle,
    render: rowData => <IncidentLink incident={rowData as Incident} />,
  };
  const summaryColumn: TableColumn = {
    title: 'Summary',
    field: 'summary',
    cellStyle: !compact ? xlColumnStyle : undefined,
    headerStyle: !compact ? xlColumnStyle : undefined,
    render: rowData => <Typography>{(rowData as Incident).summary}</Typography>,
  };
  const sourceColumn: TableColumn = {
    title: 'Source',
    field: 'source',
    cellStyle: mdColumnStyle,
    headerStyle: mdColumnStyle,
    render: rowData => (
      <AlertSourceLink alertSource={(rowData as Incident).alertSource} />
    ),
  };
  const durationColumn: TableColumn = {
    title: 'Duration',
    field: 'reportTime',
    type: 'datetime',
    cellStyle: smColumnStyle,
    headerStyle: smColumnStyle,
    render: rowData => (
      <Typography noWrap>
        {(rowData as Incident).status !== 'RESOLVED'
          ? humanizeDuration(
              Interval.fromDateTimes(
                dt.fromISO((rowData as Incident).reportTime),
                dt.now(),
              )
                .toDuration()
                .valueOf(),
              { units: ['h', 'm', 's'], largest: 2, round: true },
            )
          : humanizeDuration(
              Interval.fromDateTimes(
                dt.fromISO((rowData as Incident).reportTime),
                dt.fromISO((rowData as Incident).resolvedOn),
              )
                .toDuration()
                .valueOf(),
              { units: ['h', 'm', 's'], largest: 2, round: true },
            )}
      </Typography>
    ),
  };
  const assignedToColumn: TableColumn = {
    title: 'Assigned to',
    field: 'assignedTo',
    cellStyle: !compact ? mdColumnStyle : lgColumnStyle,
    headerStyle: !compact ? mdColumnStyle : lgColumnStyle,
    render: rowData => (
      <Typography noWrap>
        {ilertApi.getUserInitials((rowData as Incident).assignedTo)}
      </Typography>
    ),
  };
  const priorityColumn: TableColumn = {
    title: 'Priority',
    field: 'priority',
    cellStyle: smColumnStyle,
    headerStyle: smColumnStyle,
    render: rowData => (
      <Typography noWrap>
        {(rowData as Incident).priority === 'HIGH' ? 'High' : 'Low'}
      </Typography>
    ),
  };
  const statusColumn: TableColumn = {
    title: 'Status',
    field: 'status',
    cellStyle: xsColumnStyle,
    headerStyle: xsColumnStyle,
    render: rowData => <StatusChip incident={rowData as Incident} />,
  };
  const actionsColumn: TableColumn = {
    title: '',
    field: '',
    cellStyle: xsColumnStyle,
    headerStyle: xsColumnStyle,
    render: rowData => (
      <IncidentActionsMenu
        incident={rowData as Incident}
        onIncidentChanged={onIncidentChanged}
        setIsLoading={setIsLoading}
      />
    ),
  };

  const columns: TableColumn[] = compact
    ? [
        summaryColumn,
        durationColumn,
        assignedToColumn,
        statusColumn,
        actionsColumn,
      ]
    : [
        idColumn,
        summaryColumn,
        sourceColumn,
        durationColumn,
        assignedToColumn,
        priorityColumn,
        statusColumn,
        actionsColumn,
      ];
  let tableStyle: React.CSSProperties = {};
  if (compact) {
    tableStyle = {
      width: '100%',
      maxWidth: '100%',
      minWidth: '0',
      height: 'calc(100% - 10px)',
      boxShadow: 'none !important',
      borderRadius: 'none !important',
    };
  } else {
    tableStyle = {
      width: '100%',
      maxWidth: '100%',
    };
  }

  return (
    <Table
      style={tableStyle}
      options={{
        sorting: false,
        search: !compact,
        paging: !compact,
        actionsColumnIndex: -1,
        pageSize: tableState.pageSize,
        pageSizeOptions: !compact ? [10, 20, 50, 100] : [3, 10, 20, 50, 100],
        padding: 'dense',
        loadingType: 'overlay',
        showEmptyDataSourceMessage: !isLoading,
        showTitle: true,
        toolbar: true,
      }}
      emptyContent={
        <Typography color="textSecondary" className={classes.empty}>
          No incidents right now
        </Typography>
      }
      title={
        !compact ? (
          <TableTitle
            incidentStates={states}
            onIncidentStatesChange={onIncidentStatesChange}
          />
        ) : (
          <Typography variant="button" color="textSecondary">
            INCIDENTS
          </Typography>
        )
      }
      page={tableState.page}
      totalCount={incidentsCount}
      onPageChange={onChangePage}
      onRowsPerPageChange={onChangeRowsPerPage}
      // localization={{ header: { actions: undefined } }}
      columns={columns}
      data={incidents}
      isLoading={isLoading}
    />
  );
}
Example #7
Source File: UptimeMonitorsTable.tsx    From backstage with Apache License 2.0 4 votes vote down vote up
UptimeMonitorsTable = ({
  uptimeMonitors,
  tableState,
  isLoading,
  onChangePage,
  onChangeRowsPerPage,
  onUptimeMonitorChanged,
}: {
  uptimeMonitors: UptimeMonitor[];
  tableState: TableState;
  isLoading: boolean;
  onChangePage: (page: number) => void;
  onChangeRowsPerPage: (pageSize: number) => void;
  onUptimeMonitorChanged: (uptimeMonitor: UptimeMonitor) => void;
}) => {
  const classes = useStyles();

  const smColumnStyle = {
    width: '5%',
    maxWidth: '5%',
  };
  const mdColumnStyle = {
    width: '10%',
    maxWidth: '10%',
  };
  const lgColumnStyle = {
    width: '15%',
    maxWidth: '15%',
  };

  const columns: TableColumn[] = [
    {
      title: 'ID',
      field: 'id',
      highlight: true,
      cellStyle: mdColumnStyle,
      headerStyle: mdColumnStyle,
      render: rowData => (
        <UptimeMonitorLink uptimeMonitor={rowData as UptimeMonitor} />
      ),
    },
    {
      title: 'Name',
      field: 'name',
      render: rowData => (
        <Typography>{(rowData as UptimeMonitor).name}</Typography>
      ),
    },
    {
      title: 'Check Type',
      field: 'checkType',
      cellStyle: lgColumnStyle,
      headerStyle: lgColumnStyle,
      render: rowData => (
        <UptimeMonitorCheckType uptimeMonitor={rowData as UptimeMonitor} />
      ),
    },
    {
      title: 'Last state change',
      field: 'lastStatusChange',
      type: 'datetime',
      cellStyle: mdColumnStyle,
      headerStyle: mdColumnStyle,
      render: rowData => (
        <Typography noWrap>
          {humanizeDuration(
            Interval.fromDateTimes(
              dt.fromISO((rowData as UptimeMonitor).lastStatusChange),
              dt.now(),
            )
              .toDuration()
              .valueOf(),
            { units: ['h', 'm', 's'], largest: 2, round: true },
          )}
        </Typography>
      ),
    },
    {
      title: 'Escalation policy',
      field: 'assignedTo',
      cellStyle: lgColumnStyle,
      headerStyle: lgColumnStyle,
      render: rowData => (
        <EscalationPolicyLink
          escalationPolicy={(rowData as UptimeMonitor).escalationPolicy}
        />
      ),
    },
    {
      title: 'Status',
      field: 'status',
      cellStyle: smColumnStyle,
      headerStyle: smColumnStyle,
      render: rowData => (
        <StatusChip uptimeMonitor={rowData as UptimeMonitor} />
      ),
    },
    {
      title: '',
      field: '',
      cellStyle: smColumnStyle,
      headerStyle: smColumnStyle,
      render: rowData => (
        <UptimeMonitorActionsMenu
          uptimeMonitor={rowData as UptimeMonitor}
          onUptimeMonitorChanged={onUptimeMonitorChanged}
        />
      ),
    },
  ];

  return (
    <Table
      options={{
        sorting: true,
        search: true,
        paging: true,
        actionsColumnIndex: -1,
        pageSize: tableState.pageSize,
        pageSizeOptions: [10, 20, 50, 100],
        padding: 'dense',
        loadingType: 'overlay',
        showEmptyDataSourceMessage: !isLoading,
      }}
      emptyContent={
        <Typography color="textSecondary" className={classes.empty}>
          No uptime monitor
        </Typography>
      }
      page={tableState.page}
      onPageChange={onChangePage}
      onRowsPerPageChange={onChangeRowsPerPage}
      localization={{ header: { actions: undefined } }}
      isLoading={isLoading}
      columns={columns}
      data={uptimeMonitors}
    />
  );
}