Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
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
/**
 * A standard React component for the POC table UI.
 * It receives all context and functionality as props.
 */
export const POCUI = ({
  // React dependencies (from context)
  useState,
  useEffect,
  useMemo,
 
  // Component Data & State
  data, // Expect `data` prop, not `loadedData`
  regions,
  state,
  metadata,
 
  // Actions
  addRegion,
  saveState,
  saveMetadata,
  getTagValue,
  setTagValue,
}) => {
  // All style objects, helper functions, and sub-components are now defined inside the main component's closure.
 
  const tableStyle = {
    width: "100%",
    borderCollapse: "collapse",
    marginTop: "15px",
  };
  const thStyle = {
    borderWidth: "1px",
    borderStyle: "solid",
    borderColor: "#ddd",
    padding: "8px",
    backgroundColor: "#f2f2f2",
    textAlign: "left",
  };
  const tdStyle = {
    borderWidth: "1px",
    borderStyle: "solid",
    borderColor: "#ddd",
    padding: "8px",
  };
  const buttonStyle = {
    marginRight: "5px",
    padding: "5px 10px",
    borderWidth: "1px",
    borderStyle: "solid",
    borderColor: "#ccc",
    borderRadius: "4px",
    cursor: "pointer",
    backgroundColor: "white",
  };
  const selectedButtonStyle = {
    ...buttonStyle,
    backgroundColor: "#4CAF50",
    color: "white",
    borderColor: "#4CAF50",
  };
  const selectedBadButtonStyle = {
    ...buttonStyle,
    backgroundColor: "#f44336", // Red color
    color: "white",
    borderColor: "#f44336",
  };
  const textareaStyle = {
    width: "100%",
    padding: "5px",
    borderWidth: "1px",
    borderStyle: "solid",
    borderColor: "#ccc",
    borderRadius: "4px",
    minHeight: "40px",
    resize: "vertical",
  };
 
  // A simple, dependency-free CSV parser.
  const simpleCSVParser = (csvText) => {
    if (!csvText || typeof csvText !== "string") {
      return { headers: [], rows: [] };
    }
 
    const lines = csvText.trim().split(/\r?\n/);
    const headers = lines[0].split(",");
    const rows = lines.slice(1).map((line) => {
      const values = line.split(",");
      return headers.reduce((obj, header, index) => {
        obj[header.trim()] = values[index]?.trim();
        return obj;
      }, {});
    });
 
    return { headers, rows };
  };
 
  // A single star component
  const Star = ({ selected, onSelect }) => (
    <button
      type="button"
      onClick={onSelect}
      style={{
        cursor: "pointer",
        color: selected ? "gold" : "grey",
        fontSize: "20px",
        background: "none",
        border: "none",
        padding: 0,
        margin: 0,
      }}
    >
      ★
    </button>
  );
 
  // The component that groups stars together
  const StarRating = ({ totalStars = 5, rating = 0, onRate }) => {
    return (
      <div>
        {[...Array(totalStars)].map((_, i) => (
          <Star key={i} selected={i < rating} onSelect={() => onRate(i + 1)} />
        ))}
      </div>
    );
  };
 
  // New component for the two questions
  const QuestionUI = ({ getTagValue, setTagValue }) => {
    // The names of the <Choices> tags in your LS config
    const tagAB = "choice1";
    const tagXY = "choice2";
 
    // Get the current values directly on every render.
    const choiceAB = getTagValue(tagAB)?.choices[0];
    const choiceXY = getTagValue(tagXY)?.choices[0];
 
    const handleSelect = (tag, value) => {
      const currentVal = getTagValue(tag)?.[0];
      const newValue = currentVal === value ? null : value;
      setTagValue(tag, newValue);
    };
 
    return (
      <div
        style={{
          marginBottom: "20px",
          padding: "10px",
          borderWidth: "1px",
          borderStyle: "solid",
          borderColor: "#eee",
          borderRadius: "4px",
        }}
      >
        <h4>Quick Questions</h4>
        <div style={{ marginBottom: "10px" }}>
          <p style={{ margin: "0 0 5px 0" }}>1. Is it an 'A' or a 'B'?</p>
          <button
            type="button"
            style={choiceAB === "A" ? selectedButtonStyle : buttonStyle}
            onClick={() => handleSelect(tagAB, "A")}
          >
            A
          </button>
          <button
            type="button"
            style={choiceAB === "B" ? selectedButtonStyle : buttonStyle}
            onClick={() => handleSelect(tagAB, "B")}
          >
            B
          </button>
        </div>
        <div>
          <p style={{ margin: "0 0 5px 0" }}>2. Is it an 'X' or a 'Y'?</p>
          <button
            type="button"
            style={choiceXY === "X" ? selectedButtonStyle : buttonStyle}
            onClick={() => handleSelect(tagXY, "X")}
          >
            X
          </button>
          <button
            type="button"
            style={choiceXY === "Y" ? selectedButtonStyle : buttonStyle}
            onClick={() => handleSelect(tagXY, "Y")}
          >
            Y
          </button>
        </div>
        <p style={{ fontSize: "11px", color: "#888", marginTop: "10px" }}>
          This updates Choices tags named '<code>{tagAB}</code>' and '<code>{tagXY}</code>'.
        </p>
      </div>
    );
  };
 
  const [tableData, setTableData] = useState({ headers: [], rows: [] });
  const [classifications, setClassifications] = useState({});
  const [comments, setComments] = useState({});
  const [ratings, setRatings] = useState({}); // New state for star ratings
 
  // Effect to parse CSV data when the component loads or data changes
  useEffect(() => {
    if (typeof data === "string" && data) {
      const results = simpleCSVParser(data);
      setTableData({ headers: results.headers, rows: results.rows });
    }
  }, [data]);
 
  // Effect to hydrate component state from saved annotation data
  useEffect(() => {
    // Hydrate classifications from regions
    const initialClassifications = {};
    regions.forEach((region) => {
      const { rowId, classification } = region._value;
      if (rowId !== undefined) {
        initialClassifications[rowId] = classification;
      }
    });
    setClassifications(initialClassifications);
 
    // Hydrate comments from global state
    if (state?.comments) {
      setComments(state.comments);
    }
 
    // Hydrate ratings from metadata
    if (metadata) {
      const latestRatings = {};
      metadata.forEach((entry) => {
        if (entry.action === "RATING_SET" && entry.data?.rowId !== undefined) {
          // The last entry in the metadata log for a given row wins
          latestRatings[entry.data.rowId] = entry.data.rating;
        }
      });
      setRatings(latestRatings);
    }
  }, [regions, state, metadata]);
 
  // Memoize the unique row identifier.
  const getRowId = useMemo(() => {
    return (row, index) => index;
  }, []);
 
  const handleClassify = (row, index, classification) => {
    const rowId = getRowId(row, index);
 
    setClassifications((prev) => ({
      ...prev,
      [rowId]: classification,
    }));
 
    // Find if a region for this row already exists
    const existingRegion = regions.find((r) => r._value.rowId === rowId);
 
    const regionData = {
      rowId,
      classification,
      rowData: row,
    };
 
    if (existingRegion) {
      // If the region for this row already exists, just update its value
      // using the new, sanctioned action on the region model.
      existingRegion.updateValue(regionData);
    } else {
      // If this is the first time classifying this row, create a new region.
      addRegion(regionData);
    }
  };
 
  const handleCommentChange = (row, index, text) => {
    const rowId = getRowId(row, index);
    setComments((prev) => ({
      ...prev,
      [rowId]: text,
    }));
  };
 
  const handleCommentBlur = (row, index) => {
    const rowId = getRowId(row, index);
    const commentText = comments[rowId] || "";
    const newComments = { ...state.comments };
 
    if (commentText) {
      newComments[rowId] = commentText;
    } else {
      delete newComments[rowId];
    }
 
    saveState({
      comments: newComments,
    });
  };
 
  // New handler for saving star ratings
  const handleRate = (row, index, rating) => {
    const rowId = getRowId(row, index);
 
    // If the user clicks the same star value again, toggle it off (rate 0)
    const newRating = ratings[rowId] === rating ? 0 : rating;
 
    setRatings((prev) => ({
      ...prev,
      [rowId]: newRating,
    }));
 
    // Use the saveMetadata function to log the action
    saveMetadata("RATING_SET", { rowId, rating: newRating });
  };
 
  if (!data || (tableData.headers.length === 0 && tableData.rows.length === 0)) {
    return <div>No CSV data to display or data is still loading.</div>;
  }
 
  return (
    <div>
      {/* Add the new Question UI */}
      <QuestionUI getTagValue={getTagValue} setTagValue={setTagValue} />
      <h4>POC Data Classification</h4>
      <table style={tableStyle}>
        <thead>
          <tr>
            {tableData.headers.map((header) => (
              <th key={header} style={thStyle}>
                {header}
              </th>
            ))}
            <th style={thStyle}>Classification</th>
            <th style={thStyle}>Comments</th>
            <th style={thStyle}>Rating</th>
          </tr>
        </thead>
        <tbody>
          {tableData.rows.map((row, index) => {
            const rowId = getRowId(row, index);
            const selectedClass = classifications[rowId];
 
            return (
              <tr key={rowId}>
                {tableData.headers.map((header) => (
                  <td key={`${rowId}-${header}`} style={tdStyle}>
                    {row[header]}
                  </td>
                ))}
                <td style={tdStyle}>
                  <button
                    type="button"
                    style={selectedClass === "Good" ? selectedButtonStyle : buttonStyle}
                    onClick={() => handleClassify(row, index, "Good")}
                  >
                    Good
                  </button>
                  <button
                    type="button"
                    style={selectedClass === "Bad" ? selectedBadButtonStyle : buttonStyle}
                    onClick={() => handleClassify(row, index, "Bad")}
                  >
                    Bad
                  </button>
                </td>
                <td style={tdStyle}>
                  <textarea
                    style={textareaStyle}
                    value={comments[rowId] || ""}
                    onChange={(e) => handleCommentChange(row, index, e.target.value)}
                    onBlur={() => handleCommentBlur(row, index)}
                    placeholder="Add a comment..."
                  />
                </td>
                <td style={tdStyle}>
                  <StarRating rating={ratings[rowId] || 0} onRate={(newRating) => handleRate(row, index, newRating)} />
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};