All files / publisher/pages/AccountKeys AccountKeysTable.tsx

100% Statements 25/25
84% Branches 42/50
100% Functions 8/8
100% Lines 25/25

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                            1x 1x         5x   5x 5x 5x 5x   5x             5x         5x           5x                             2x   2x   2x 2x   2x                 1x                                   2x                                                               4x   4x 4x                   4x   4x   5x                                               4x                                
import {
  Button,
  Chip,
  Icon,
  MainTable,
  TablePagination,
} from "@canonical/react-components";
import {
  MainTableHeader,
  MainTableRow,
} from "@canonical/react-components/dist/components/MainTable/MainTable";
import { useMemo, useState } from "react";
import type { AccountKeyData } from "../../types/accountKeysTypes";
 
const MS_IN_A_DAY = 1000 * 60 * 60 * 24;
const MAX_DATE = new Date(8640000000000000);
 
function AccountKeyStatus(props: { accountKey: AccountKeyData }) {
  const {
    accountKey: { until: _until },
  } = props;
 
  const hasUntil = !!_until; // valid keys don't have an "until" value by default
  const until = hasUntil ? new Date(_until) : MAX_DATE;
  const isExpired = until < new Date();
  const willExpireSoon = (until.getTime() - Date.now()) / MS_IN_A_DAY <= 30; // expires in 30 days or less
 
  const iconName = isExpired
    ? "error"
    : willExpireSoon
      ? "warning"
      : hasUntil
        ? "success"
        : "success-grey";
  const statusText = isExpired
    ? "Expired"
    : willExpireSoon
      ? "Expiring soon"
      : "Valid";
  const untilText = isExpired
    ? `On ${until.toLocaleDateString()}`
    : hasUntil
      ? `Until ${until.toLocaleDateString()}`
      : `No end date`;
 
  return (
    <p className="u-no-padding u-whitespace-nowrap">
      <Icon name={iconName} style={{ marginRight: "0.5rem" }} />
      <span>{statusText}</span>
      <br />
      <span className="u-text-muted" style={{ marginLeft: "1.5rem" }}>
        {untilText}
      </span>
    </p>
  );
}
 
function AccountKeyConstraints(props: { accountKey: AccountKeyData }) {
  const {
    accountKey: { constraints },
  } = props;
 
  const [expanded, setExpanded] = useState(false);
 
  const [c0, c1] = constraints ?? []; // get first two constraints
  const remaining = (constraints?.length ?? 0) - 2;
 
  return constraints ? (
    <>
      <div style={{ display: "flex", alignItems: "baseline" }}>
        <Button
          style={{ marginRight: "0.5rem" }}
          appearance="base"
          hasIcon
          aria-label={expanded ? "Hide constraints" : "Show constraints"}
          isDense
          onClick={() => setExpanded(!expanded)}
        >
          <Icon name={expanded ? "chevron-down" : "chevron-right"} />
        </Button>
        {c0 && <Chip isReadOnly value={c0.headers.type} />}
        {c1 && <Chip isReadOnly value={c1.headers.type} />}
        {remaining > 0 && <Chip isReadOnly value={`+${remaining}`} />}
      </div>
      {constraints?.length && expanded && (
        <table>
          <thead>
            <tr>
              <th>Assertion type</th>
              <th>Values</th>
            </tr>
          </thead>
          <tbody>
            {constraints.map((c, i) => (
              <tr key={i}>
                <td>{c.headers.type}</td>
                <td className="u-truncate">
                  {c.headers.type === "system-user" ? (
                    typeof c.headers.models === "object" ? (
                      c.headers.models.join(", ")
                    ) : (
                      c.headers.models
                    )
                  ) : c.headers.type === "serial" ||
                    c.headers.type === "model" ||
                    c.headers.type === "preseed" ? (
                    c.headers.model
                  ) : (
                    <span className="u-text-muted">No attribute</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </>
  ) : (
    <span className="u-text-muted">No constraints</span>
  );
}
 
function AccountKeysTable(props: {
  keys: AccountKeyData[];
  hasConstraints?: boolean;
}): React.JSX.Element {
  const { keys, hasConstraints } = props;
 
  const headers: MainTableHeader[] = useMemo(
    () => [
      { content: "Name", sortKey: "name" },
      { content: "Registered", sortKey: "since" },
      { content: "Status", sortKey: "until" },
      hasConstraints ? { content: "Constraints" } : {},
      { content: "Fingerprint" },
    ],
    [],
  );
 
  const rows: MainTableRow[] = useMemo(
    () =>
      keys.map(
        (k) =>
          ({
            columns: [
              { content: k.name },
              { content: new Date(k.since).toLocaleDateString() },
              { content: <AccountKeyStatus accountKey={k} /> },
              hasConstraints
                ? { content: <AccountKeyConstraints accountKey={k} /> }
                : {},
              {
                content: k["public-key-sha3-384"],
                className: "u-truncate",
              },
            ],
            sortData: {
              name: k.name,
              since: new Date(k.since),
              until: k.until ? new Date(k.until) : MAX_DATE,
            },
            key: k["public-key-sha3-384"],
          }) as MainTableRow,
      ),
    [keys],
  );
 
  return (
    <TablePagination data={rows} pageLimits={[10, 25, 50]}>
      <MainTable
        className="u-table-layout--auto"
        headers={headers}
        rows={rows}
        sortable
        defaultSort="since"
        defaultSortDirection="ascending"
        emptyStateMsg="There are no keys that match the criteria"
      />
    </TablePagination>
  );
}
 
export default AccountKeysTable;