File size: 4,976 Bytes
0ca967a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useRef, useState } from "react";

interface MethodsReport {
  protocol_id: string;
  generated_at: string;
  text: string;
  warnings: string[];
}

interface MethodsExportProps {
  protocolId: string;
}

/** The report is written in Markdown; show it as plain text so it pastes
 * cleanly into Word (no ## marks or backticks). */
function toPlain(markdown: string): string {
  return markdown.replace(/^## /gm, "").replace(/`/g, "");
}

export function MethodsExport({ protocolId }: MethodsExportProps) {
  const [includeRanking, setIncludeRanking] = useState(false);
  const [report, setReport] = useState<MethodsReport | null>(null);
  const [text, setText] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [copyNote, setCopyNote] = useState<string | null>(null);
  const areaRef = useRef<HTMLTextAreaElement>(null);

  async function generate() {
    setBusy(true);
    setError(null);
    setCopyNote(null);
    try {
      const response = await fetch(
        `/api/v1/protocols/${encodeURIComponent(protocolId)}/methods-report?ranking=${includeRanking}`
      );
      if (!response.ok) {
        let message = `Could not create the text (status ${response.status}).`;
        try {
          const body: unknown = await response.json();
          const detail = (body as { detail?: unknown }).detail;
          if (typeof detail === "string") message = detail;
        } catch {
          /* keep the generic message */
        }
        throw new Error(message);
      }
      const data = (await response.json()) as MethodsReport;
      setReport(data);
      setText(toPlain(data.text));
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not create the text.");
    } finally {
      setBusy(false);
    }
  }

  async function copy() {
    setCopyNote(null);
    try {
      await navigator.clipboard.writeText(text);
      setCopyNote("Copied.");
      return;
    } catch {
      /* the page may be embedded; try the older method below */
    }
    const area = areaRef.current;
    if (area) {
      area.focus();
      area.select();
      try {
        if (document.execCommand("copy")) {
          setCopyNote("Copied.");
          return;
        }
      } catch {
        /* fall through */
      }
    }
    setCopyNote("Could not copy automatically. Click in the text, press Ctrl+A, then Ctrl+C.");
  }

  function download() {
    const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "methods-report.txt";
    document.body.appendChild(link);
    link.click();
    link.remove();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="methods-export">
      <p className="form-hint">
        Creates draft text for your methods and results sections from the protocol, the search
        and the PRISMA numbers stored in this tool. Check it and edit it before you use it.
      </p>

      <label className="ranking-toggle">
        <input
          type="checkbox"
          checked={includeRanking}
          onChange={(e) => setIncludeRanking(e.target.checked)}
        />
        Include the paragraph about the AI-assisted screening ranking (tick it only if you used
        the ranking)
      </label>

      <div className="form-actions" style={{ justifyContent: "flex-start" }}>
        <button className="primary-btn" onClick={() => void generate()} disabled={busy}>
          {busy ? "Creating…" : report ? "Create again" : "Create text"}
        </button>
      </div>

      {error && <div className="form-error">{error}</div>}

      {report && (
        <>
          {report.warnings.length > 0 && (
            <div className="notice notice-warn">
              <strong>Check before you use this text:</strong>
              <ul>
                {report.warnings.map((w, i) => (
                  <li key={i}>{w}</li>
                ))}
              </ul>
            </div>
          )}

          <textarea
            ref={areaRef}
            className="methods-text"
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
          <p className="form-hint">
            You can edit the text here. Created {new Date(report.generated_at).toLocaleString()}.
            Numbers do not update after this point, so create it again if you screen more records.
          </p>

          <div className="form-actions" style={{ justifyContent: "flex-start" }}>
            <button className="secondary-btn" onClick={() => void copy()}>
              Copy text
            </button>
            <button className="secondary-btn" onClick={download}>
              Download as .txt
            </button>
            {copyNote && <span className="form-hint">{copyNote}</span>}
          </div>
        </>
      )}
    </div>
  );
}