All files / publisher-admin/pages/Listing Listing.tsx

48.14% Statements 26/54
62.79% Branches 27/43
54.54% Functions 6/11
48.14% Lines 26/54

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                                  136x 136x 136x 136x   136x   136x 136x                       136x             136x         117x 117x     136x 272x 252x     20x       20x       20x       20x     136x 136x           136x           136x                                                                                 136x 9x     136x                                                       1x                                                                                                                                                                                                                                              
import { useState, useEffect, SyntheticEvent, FormEvent } from "react";
import { useParams } from "react-router-dom";
import { useRecoilState } from "recoil";
import {
  Notification,
  Row,
  Col,
  Button,
  Icon,
} from "@canonical/react-components";
 
import ListingInputField from "./ListingInputField";
 
import { packageDataState } from "../../state/atoms";
import { capitalize } from "../../utils";
 
function Listing() {
  const { packageName } = useParams();
  const [packageData, setPackageData] = useRecoilState(packageDataState);
  const [isSaving, setIsSaving] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string>("");
  const [showSuccessNotification, setShowSuccessNotification] =
    useState<boolean>(false);
  const [showErrorNotification, setShowErrorNotification] =
    useState<boolean>(false);
  const [formData, setFormData] = useState<{
    title: string | null;
    summary: string | null;
    website: string | undefined;
    contact: string | undefined;
  }>({
    title: null,
    summary: null,
    website: undefined,
    contact: undefined,
  });
 
  const defaultFormData = {
    title: packageData?.title || null,
    summary: packageData?.summary || null,
    website: packageData?.links?.website?.[0] || undefined,
    contact: packageData?.links?.contact?.[0] || undefined,
  };
 
  const handleInputChange = (
    e: SyntheticEvent<HTMLInputElement> & {
      target: HTMLInputElement;
    }
  ) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };
 
  const isDisabled = () => {
    if (formData.title !== packageData?.title) {
      return false;
    }
 
    Iif (formData.summary !== packageData?.summary) {
      return false;
    }
 
    Iif (formData.website !== packageData?.links?.website?.[0]) {
      return false;
    }
 
    Iif (formData.contact !== packageData?.links?.contact?.[0]) {
      return false;
    }
 
    return true;
  };
 
  const getCharmIcon = () => {
    Eif (
      packageData &&
      packageData.media &&
      packageData.media.length &&
      packageData.media[0].url
    ) {
      return packageData?.media?.[0]?.url;
    }
 
    return "https://assets.ubuntu.com/v1/be6eb412-snapcraft-missing-icon.svg";
  };
 
  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
 
    setShowSuccessNotification(false);
    setShowErrorNotification(false);
    setErrorMessage("");
    setIsSaving(true);
 
    const response = await fetch(`/api/packages/${packageName}`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-Token": window.CSRF_TOKEN,
      },
      body: JSON.stringify(formData),
    });
 
    if (!response.ok) {
      setErrorMessage(response.statusText);
      setShowErrorNotification(true);
      setIsSaving(false);
      throw new Error(response.statusText);
    }
 
    const data = await response.json();
 
    if (!data.success) {
      setErrorMessage(data.message);
      setShowErrorNotification(true);
      setIsSaving(false);
      throw new Error(data.message);
    }
 
    setPackageData(data.data);
 
    setTimeout(() => {
      setShowSuccessNotification(true);
      setIsSaving(false);
    }, 500);
  };
 
  useEffect(() => {
    setFormData(defaultFormData);
  }, [packageData]);
 
  return (
    <form
      method="POST"
      className="p-form--stacked"
      onSubmit={(e) => {
        handleSubmit(e);
      }}
    >
      {packageData && packageData?.status !== "published" && (
        <Notification severity="caution">
          A published {packageData?.type} is required to successfully save this
          form.
        </Notification>
      )}
 
      <Row>
        <Col size={7}>
          <p>
            Updates to this information will appear immediately on the{" "}
            <a href={`/${packageName}`}>{packageData?.type} listing page</a>.
          </p>
        </Col>
        <Col size={5} className="u-align--right">
          <Button
            type="button"
            appearance="base"
            disabled={isDisabled()}
            onClick={() => {
              setFormData(defaultFormData);
            }}
          >
            Revert
          </Button>
          <Button
            type="submit"
            appearance="positive"
            className="is-dark"
            disabled={isSaving || isDisabled()}
          >
            {isSaving ? (
              <>
                <Icon name="spinner" className="u-animation--spin" />
                &nbsp;Saving...
              </>
            ) : (
              <>Save</>
            )}
          </Button>
        </Col>
      </Row>
 
      <hr className="u-no-margin--bottom" />
 
      {showSuccessNotification && (
        <Notification
          severity="positive"
          className="u-no-margin--bottom"
          onDismiss={() => {
            setShowSuccessNotification(false);
          }}
          role="alert"
          aria-live="polite"
        >
          {packageData?.name} has been updated successfully
        </Notification>
      )}
 
      {showErrorNotification && (
        <Notification
          severity="negative"
          className="u-no-margin--bottom"
          onDismiss={() => {
            setShowErrorNotification(false);
          }}
          role="alert"
          aria-live="polite"
        >
          {errorMessage
            ? errorMessage
            : `There was a problem updating ${packageData?.name}`}
        </Notification>
      )}
 
      <section className="p-strip is-shallow">
        <h2 className="p-heading--4">Listing details</h2>
        <Row className="p-form__group p-form-validation">
          <Col size={2}>
            <p>{capitalize(packageData?.type)} icon:</p>
          </Col>
          <Col size={8} className="col-x-large-6 u-sv2">
            <div className="p-form__control">
              <img
                src={getCharmIcon()}
                alt={`${packageName} icon`}
                width="48"
                height="48"
                className="p-media-object__image"
                style={{ borderRadius: "50%" }}
              />
            </div>
          </Col>
        </Row>
 
        <ListingInputField
          label="Title"
          name="title"
          maxLength={40}
          value={formData.title || undefined}
          handleInputChange={handleInputChange}
        />
 
        <ListingInputField
          label="Summary"
          name="summary"
          maxLength={100}
          value={formData.summary || undefined}
          handleInputChange={handleInputChange}
        />
      </section>
 
      <hr className="u-no-margin--bottom" />
 
      <section className="p-strip is-shallow">
        <h2 className="p-heading--4">Additional information</h2>
 
        <ListingInputField
          label="Project homepage"
          name="website"
          maxLength={256}
          value={formData.website}
          placeholder="https://charmhub.io"
          handleInputChange={handleInputChange}
        />
 
        <ListingInputField
          label="Contact"
          name="contact"
          maxLength={256}
          value={formData.contact}
          handleInputChange={handleInputChange}
        />
      </section>
    </form>
  );
}
 
export default Listing;