📦 EqualifyEverything / equalify

📄 AuditPagesInput.tsx · 457 lines
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457import { useEffect, useState } from "react";
import { useGlobalStore } from "../utils";
import { StyledButton } from "./StyledButton";
import { AuditPagesInputTable } from "./AuditPagesInputTable";
import { StyledLabeledInput } from "./StyledLabeledInput";
import { Card } from "./Card";
import style from "./AuditPagesInput.module.scss";

interface Page {
  url: string;
  type: "html" | "pdf";
  id?: string;
}
interface ChildProps {
  initialPages: Page[];
  setParentPages: (newValue: Page[]) => void; // Callback function prop
  addParentPages?: (newValue: Page[]) => void; // Callback function prop
  removeParentPages?: (newValue: Page[]) => void; // Callback function prop
  updateParentPageType?: (newValue: Page) => void; // Callback function prop
  returnMutation?: boolean; // if true, only return changed rows
  isShared?: boolean;
}

export const AuditPagesInput: React.FC<ChildProps> = ({
  initialPages,
  setParentPages,
  addParentPages,
  removeParentPages,
  updateParentPageType,
  returnMutation = false,
  isShared = false,
}) => {
  const { setAnnounceMessage } = useGlobalStore();

  const [importBy, setImportBy] = useState("URLs");
  const [urlError, setUrlError] = useState<string | null>(null);
  const [pages, setPages] = useState<Page[]>(initialPages);
  //const [pagesToDeleteCount, setPagesToDeleteCount] = useState(0);
  const [csvError, setCsvError] = useState<string | null>(null);

  const handleCsvUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate file type
    if (
      !file.name.endsWith(".csv") &&
      !file.type.includes("csv") &&
      !file.type.includes("text")
    ) {
      setCsvError("Please upload a CSV or text file");
      return;
    }

    const reader = new FileReader();
    reader.onload = (event) => {
      const text = event.target?.result as string;
      if (!text) {
        setCsvError("Failed to read file");
        return;
      }

      // Parse CSV - expecting one URL per line
      const lines = text
        .split(/\r?\n/)
        .map((line) => line.trim())
        .filter((line) => line.length > 0);

      if (lines.length === 0) {
        setCsvError("No URLs found in the file");
        return;
      }

      const newPages: Page[] = [];
      const errors: string[] = [];
      const duplicates: string[] = [];
      const typeUpdates: Page[] = [];

      lines.forEach((line, index) => {
        // Skip empty lines and potential header rows
        if (!line || (line.toLowerCase().includes("url") && index === 0))
          return;

        // Parse line for URL and optional type (format: url,type)
        const { url: rawUrl, type: pageType } = parseUrlWithType(line);

        // Validate and format URL
        const validUrl = validateAndFormatUrl(rawUrl);
        if (!validUrl) {
          errors.push(`Line ${index + 1}: Invalid URL format`);
          return;
        }

        // Check for duplicates in existing pages - if type differs, update it
        const existingPage = pages.find((page) => page.url === validUrl);
        if (existingPage) {
          if (existingPage.type !== pageType) {
            // Type has changed, update it
            typeUpdates.push({ url: validUrl, type: pageType });
          } else {
            duplicates.push(validUrl);
          }
          return;
        }

        // Check for duplicates in new pages being added
        if (newPages.some((page) => page.url === validUrl)) {
          duplicates.push(validUrl);
          return;
        }

        newPages.push({ url: validUrl, type: pageType });
      });

      // Process type updates for existing URLs
      if (typeUpdates.length > 0) {
        setPages(prev => prev.map(page => {
          const update = typeUpdates.find(u => u.url === page.url);
          if (update) {
            // Also call the parent update function if available
            if (updateParentPageType) {
              updateParentPageType({ url: update.url, type: update.type });
            }
            return { ...page, type: update.type };
          }
          return page;
        }));
      }

      // Add all valid URLs to the pages
      if (newPages.length > 0) {
        setPages(prev => [...prev, ...newPages]);
      }

      // Show success message
      if (newPages.length > 0 || typeUpdates.length > 0) {
        const successMessages: string[] = [];
        if (newPages.length > 0) {
          successMessages.push(`${newPages.length} URL(s) added`);
        }
        if (typeUpdates.length > 0) {
          successMessages.push(`${typeUpdates.length} URL type(s) updated`);
        }
        setAnnounceMessage(
          `Successfully processed CSV: ${successMessages.join(", ")}`, "success"
        );
        setCsvError(null);
      }

      // Show warnings if there were issues
      if (errors.length > 0 || duplicates.length > 0) {
        const messages: string[] = [];
        if (newPages.length > 0 || typeUpdates.length > 0) {
          const successParts: string[] = [];
          if (newPages.length > 0) successParts.push(`${newPages.length} URL(s) added`);
          if (typeUpdates.length > 0) successParts.push(`${typeUpdates.length} type(s) updated`);
          messages.push(`Successfully processed: ${successParts.join(", ")}.`);
        }
        if (duplicates.length > 0) {
          messages.push(`${duplicates.length} unchanged duplicate(s) skipped.`);
        }
        if (errors.length > 0) {
          messages.push(`${errors.length} invalid URL(s) skipped.`);
        }
        setCsvError(messages.join(" "));
      }

      // Clear the file input
      e.target.value = "";
    };

    reader.onerror = () => {
      setCsvError("Error reading file");
    };

    reader.readAsText(file);
  };

  const addPage = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    const button = e.currentTarget;
    const form = button.closest("form");
    if (!form) return;

    const formData = new FormData(form);
    const input = formData.get("pageInput") as string;
    if (!input || input.length === 0) {
      return;
    }

    // Parse input for URL and optional type
    const { url: rawUrl, type: pageType } = parseUrlWithType(input);

    // Validate and format URL
    const validUrl = validateAndFormatUrl(rawUrl);
    if (!validUrl) return;

    // Check for duplicates
    if (pages.some((page) => page.url === validUrl)) {
      setUrlError("This URL has already been added");
      return;
    }

    // Add page with parsed type (defaults to 'html')
    setPages(prev => [...prev, { url: validUrl, type: pageType }]);
    // Clear the input field
    const inputField = form.querySelector(
      '[name="pageInput"]'
    ) as HTMLInputElement;
    if (inputField) inputField.value = "";
    setUrlError(null);
    setAnnounceMessage(`Added URL ${validUrl}!`, "success");
    //console.log(pages);
    return;
  };

  /**
   * Normalize a URL by removing trailing slashes from the path
   * This ensures URLs like "https://example.com/" and "https://example.com" are treated as the same
   */
  const normalizeUrl = (url: string): string => {
    // Remove trailing slash unless it's just the root path
    return url.replace(/\/+$/, '') || url;
  };

  const validateAndFormatUrl = (input: string): string | null => {
    // Trim whitespace
    let url = input.trim();
    if (!url) return null;

    // Add https:// if no protocol is specified
    if (!url.match(/^https?:\/\//i)) {
      url = "https://" + url;
    }

    // Validate URL format
    try {
      const urlObj = new URL(url);
      // Check if it's http or https
      if (!["http:", "https:"].includes(urlObj.protocol)) {
        setUrlError("Only HTTP and HTTPS URLs are supported");
        return null;
      }
      setUrlError(null);
      // Normalize the URL to remove trailing slashes
      return normalizeUrl(urlObj.href);
    } catch {
      setUrlError(
        "Invalid URL format. Please enter a valid URL (e.g., example.com or https://example.com)"
      );
      return null;
    }
  };

  /**
   * Parse a line that may contain a URL and optional type separated by comma
   * Format: url,type (e.g., "https://example.com,html" or "https://example.com/doc.pdf,pdf")
   * If no type specified, defaults to "html"
   */
  const parseUrlWithType = (line: string): { url: string; type: "html" | "pdf" } => {
    const trimmedLine = line.trim();
    
    // Check if the line ends with ,html or ,pdf (case-insensitive)
    const htmlMatch = trimmedLine.match(/^(.+),\s*html\s*$/i);
    const pdfMatch = trimmedLine.match(/^(.+),\s*pdf\s*$/i);
    
    if (pdfMatch) {
      return { url: pdfMatch[1].trim(), type: "pdf" };
    }
    if (htmlMatch) {
      return { url: htmlMatch[1].trim(), type: "html" };
    }
    
    // No type specified, default to html
    return { url: trimmedLine, type: "html" };
  };

  const downloadCsvTemplate = (e:any) => {
    e.preventDefault();
    const csvContent = `url,type
    https://example.com,html
    https://example.com/about,html
    https://example.com/document.pdf,pdf
    https://example.com/contact,html`;
    
    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.setAttribute("href", url);
    link.setAttribute("download", "url-import-template.csv");
    link.style.visibility = "hidden";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const removePages = (pagesToRemove: Page[]) => {
    //console.log("After Removal:", pages.filter((row) => !pagesToRemove.includes(row)));
    setPages(pages.filter((row) => !pagesToRemove.includes(row)));
    setAnnounceMessage(`Removed ${pagesToRemove.length} URLs!`, "success");
    return;
  };

  const updatePageType = (url: string, type: "html" | "pdf") => {
    //console.log("updatePagesType...", pages);
    setPages(
      pages.map((page) => (page.url === url ? { ...page, type } : page))
    ); 

    if (updateParentPageType) {
      //update in DB if we have a function to do so
      updateParentPageType({ url: url, type: type });
    }
  };

  const handleUrlInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      const input = e.currentTarget;
      const form = input.closest("form");
      if (!form) return;

      const inputValue = input.value;
      if (!inputValue || inputValue.length === 0) {
        return;
      }

      // Parse input for URL and optional type
      const { url: rawUrl, type: pageType } = parseUrlWithType(inputValue);

      // Validate and format URL
      const validUrl = validateAndFormatUrl(rawUrl);
      if (!validUrl) return;

      // Check for duplicates
      if (pages.some((page) => page.url === validUrl)) {
        setUrlError("This URL has already been added");
        return;
      }

      // Add page with parsed type (defaults to 'html')
      setPages(prev => [...prev, { url: validUrl, type: pageType }]);
      // Clear the input field
      input.value = "";
      setUrlError(null);
    }
  };

  // update parent value on change
  useEffect(() => {
    //console.log("Updating pages...", pages);
    //console.log("InitialPages", initialPages);

    if (returnMutation) { // return only the delta, ie modified URLs
      let arrDelta: Page[] = [];
      if (initialPages === pages) return;
      if (initialPages.length < pages.length) {
        // adding pages
        //console.log("Adding...")
        arrDelta = pages.filter((page) => !initialPages.includes(page));
        if (addParentPages) addParentPages(arrDelta);
      }
      if (initialPages.length > pages.length) {
        // removing pages
        //console.log("Removing...")
        const initialUrls = initialPages.map((page) => page.url);
        const pageUrls = pages.map((page) => page.url);
        const overlap = initialUrls.filter((page) => !pageUrls.includes(page));
        arrDelta = initialPages.filter((page) => overlap.includes(page.url));
        //console.log("To remove:",arrDelta);
        if (removeParentPages) removeParentPages(arrDelta);
      }
      setParentPages(arrDelta);
    } else {
      setParentPages(pages);
    }
  }, [pages]);
  //console.log(pages);

  return (
    <div className={style.AuditPagesInput}>
      {/* {pages.length > 0 && ( */}
        <>
          <AuditPagesInputTable
            pages={pages}
            removePages={removePages}
            isShared={isShared}
            updatePageType={updatePageType}
          />
          {!isShared && (
            <Card variant="inset-light">
              <h3>Add URLs to Scan</h3>
              <div className={style["input-area"]}>
                <StyledLabeledInput>
                  <label htmlFor="importBy">Import By:</label>
                  <select
                    id="importBy"
                    name="importBy"
                    value={importBy}
                    onChange={(e) => setImportBy(e.target.value)}
                  >
                    <option>URLs</option>
                    <option>CSV</option>
                  </select>
                </StyledLabeledInput>
                {["URLs"].includes(importBy) && (
                  <div>
                    <StyledLabeledInput>
                      <label htmlFor="pageInput">URLs:</label>
                      <input
                        id="pageInput"
                        name="pageInput"
                        onKeyDown={handleUrlInputKeyDown}
                        placeholder="example.com"
                      />
                    </StyledLabeledInput>
                    {urlError && <p>{urlError}</p>}
                  </div>
                )}
                {["CSV"].includes(importBy) && (
                  <div>
                    <StyledLabeledInput>
                      <label htmlFor="csvInput">CSV Upload:</label>
                      <input
                        id="csvInput"
                        name="csvInput"
                        type="file"
                        accept=".csv,.txt,text/csv,text/plain"
                        onChange={handleCsvUpload}
                      />
                    </StyledLabeledInput>
                    <p className="font-small">
                      Upload a CSV with one URL per line. Optionally specify type as <code>url,type</code> (e.g., <code>https://example.com/doc.pdf,pdf</code>). If no type is provided, HTML is assumed.
                    </p>
                    <StyledButton
                      label="Download Template CSV"
                      onClick={downloadCsvTemplate}
                      variant="secondary"
                    />
                    {csvError && (
                      <p className="text-red-500 text-sm mt-1">{csvError}</p>
                    )}
                  </div>
                )}
              </div>
              <div className={style["button-area"]}>
              <StyledButton label="Add Urls" onClick={addPage} />
              </div>
            </Card>
          )}
        </>
      {/* )} */}
    </div>
  );
};