MSF commited on
Commit
4bbaf1c
·
1 Parent(s): dc70dbc

feat: Initialize Quadrant Chart Pro project structure

Browse files

Sets up the foundational files and dependencies for the Quadrant Chart Pro application. This includes configuring Vite for development, adding necessary React and charting libraries, and establishing basic project metadata and README information.

Files changed (13) hide show
  1. .env.example +9 -0
  2. .gitignore +8 -0
  3. README.md +14 -5
  4. index.html +13 -0
  5. metadata.json +5 -0
  6. package-lock.json +0 -0
  7. package.json +39 -0
  8. src/App.tsx +621 -0
  9. src/index.css +1 -0
  10. src/main.tsx +10 -0
  11. src/types.ts +26 -0
  12. tsconfig.json +26 -0
  13. vite.config.ts +24 -0
.env.example ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # GEMINI_API_KEY: Required for Gemini AI API calls.
2
+ # AI Studio automatically injects this at runtime from user secrets.
3
+ # Users configure this via the Secrets panel in the AI Studio UI.
4
+ GEMINI_API_KEY="MY_GEMINI_API_KEY"
5
+
6
+ # APP_URL: The URL where this applet is hosted.
7
+ # AI Studio automatically injects this at runtime with the Cloud Run service URL.
8
+ # Used for self-referential links, OAuth callbacks, and API endpoints.
9
+ APP_URL="MY_APP_URL"
.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+ build/
3
+ dist/
4
+ coverage/
5
+ .DS_Store
6
+ *.log
7
+ .env*
8
+ !.env.example
README.md CHANGED
@@ -1,11 +1,20 @@
1
  <div align="center">
2
-
3
  <img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
 
4
 
5
- <h1>Built with AI Studio</h2>
6
 
7
- <p>The fastest path from prompt to production with Gemini.</p>
8
 
9
- <a href="https://aistudio.google.com/apps">Start building</a>
10
 
11
- </div>
 
 
 
 
 
 
 
 
 
 
1
  <div align="center">
 
2
  <img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
3
+ </div>
4
 
5
+ # Run and deploy your AI Studio app
6
 
7
+ This contains everything you need to run your app locally.
8
 
9
+ View your app in AI Studio: https://ai.studio/apps/93231555-9e1d-45e8-aa4e-490db484e57a
10
 
11
+ ## Run Locally
12
+
13
+ **Prerequisites:** Node.js
14
+
15
+
16
+ 1. Install dependencies:
17
+ `npm install`
18
+ 2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
19
+ 3. Run the app:
20
+ `npm run dev`
index.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>My Google AI Studio App</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="/src/main.tsx"></script>
11
+ </body>
12
+ </html>
13
+
metadata.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "name": "Quadrant Chart Pro",
3
+ "description": "Upload Excel data to generate professional four-quadrant scatter plots with automatic mean calculation and labeling.",
4
+ "requestFramePermissions": []
5
+ }
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "react-example",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite --port=3000 --host=0.0.0.0",
8
+ "build": "vite build",
9
+ "preview": "vite preview",
10
+ "clean": "rm -rf dist",
11
+ "lint": "tsc --noEmit"
12
+ },
13
+ "dependencies": {
14
+ "@google/genai": "^1.29.0",
15
+ "@tailwindcss/vite": "^4.1.14",
16
+ "@vitejs/plugin-react": "^5.0.4",
17
+ "clsx": "^2.1.1",
18
+ "dotenv": "^17.2.3",
19
+ "express": "^4.21.2",
20
+ "html-to-image": "^1.11.13",
21
+ "lucide-react": "^0.546.0",
22
+ "motion": "^12.23.24",
23
+ "react": "^19.0.0",
24
+ "react-dom": "^19.0.0",
25
+ "recharts": "^3.8.0",
26
+ "tailwind-merge": "^3.5.0",
27
+ "vite": "^6.2.0",
28
+ "xlsx": "^0.18.5"
29
+ },
30
+ "devDependencies": {
31
+ "@types/express": "^4.17.21",
32
+ "@types/node": "^22.14.0",
33
+ "autoprefixer": "^10.4.21",
34
+ "tailwindcss": "^4.1.14",
35
+ "tsx": "^4.21.0",
36
+ "typescript": "~5.8.2",
37
+ "vite": "^6.2.0"
38
+ }
39
+ }
src/App.tsx ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useMemo, useCallback, useRef } from 'react';
2
+ import * as XLSX from 'xlsx';
3
+ import {
4
+ ScatterChart,
5
+ Scatter,
6
+ XAxis,
7
+ YAxis,
8
+ ZAxis,
9
+ CartesianGrid,
10
+ Tooltip,
11
+ ResponsiveContainer,
12
+ ReferenceLine,
13
+ LabelList,
14
+ Legend,
15
+ Text,
16
+ Cell
17
+ } from 'recharts';
18
+ import { Upload, Settings2, BarChart2, FileSpreadsheet, Info, Download, Image as ImageIcon, X, Palette, Trash2, Check, ChevronDown, ChevronUp, Copy } from 'lucide-react';
19
+ import { clsx, type ClassValue } from 'clsx';
20
+ import { twMerge } from 'tailwind-merge';
21
+ import { toPng, toBlob } from 'html-to-image';
22
+ import { ChartConfig, DataPoint, PointOverride } from './types';
23
+
24
+ // Utility for tailwind classes
25
+ function cn(...inputs: ClassValue[]) {
26
+ return twMerge(clsx(inputs));
27
+ }
28
+
29
+ export default function App() {
30
+ const [data, setData] = useState<DataPoint[]>([]);
31
+ const [columns, setColumns] = useState<string[]>([]);
32
+ const [config, setConfig] = useState<ChartConfig>({
33
+ xAxisKey: '',
34
+ yAxisKey: '',
35
+ labelKey: '',
36
+ categoryKey: '',
37
+ groupByKeys: [],
38
+ sizeKey: '',
39
+ title: 'Campaign Performance Quadrant',
40
+ });
41
+ const [pointOverrides, setPointOverrides] = useState<Record<string, PointOverride>>({});
42
+ const [selectedPoint, setSelectedPoint] = useState<{ id: string, label: string } | null>(null);
43
+ const [isDragging, setIsDragging] = useState(false);
44
+ const chartRef = useRef<HTMLDivElement>(null);
45
+
46
+ const parseNumeric = (val: any): number => {
47
+ if (val === null || val === undefined || val === '') return NaN;
48
+ if (typeof val === 'number') return val;
49
+ const str = String(val).trim();
50
+ if (str.endsWith('%')) {
51
+ return parseFloat(str.replace('%', '')) / 100;
52
+ }
53
+ const parsed = parseFloat(str);
54
+ return isNaN(parsed) ? NaN : parsed;
55
+ };
56
+
57
+ const handleFileUpload = (file: File) => {
58
+ const reader = new FileReader();
59
+ reader.onload = (e) => {
60
+ const bstr = e.target?.result;
61
+ const wb = XLSX.read(bstr, { type: 'binary' });
62
+ const wsname = wb.SheetNames[0];
63
+ const ws = wb.Sheets[wsname];
64
+ // Use defval: "" to ensure all keys are present even if empty in some rows
65
+ const jsonData = XLSX.utils.sheet_to_json(ws, { defval: "" }) as DataPoint[];
66
+
67
+ if (jsonData.length > 0) {
68
+ // Add unique ID to each row
69
+ const dataWithIds = jsonData.map((row, idx) => ({
70
+ ...row,
71
+ __id: `row-${idx}-${Date.now()}`
72
+ }));
73
+
74
+ // Get all keys from the sheet range if possible, or from the first row
75
+ const cols = Object.keys(jsonData[0]);
76
+ setColumns(cols);
77
+ setData(dataWithIds);
78
+
79
+ const numericCols = cols.filter(c => !isNaN(parseNumeric(jsonData[0][c])));
80
+
81
+ setConfig(prev => ({
82
+ ...prev,
83
+ xAxisKey: numericCols.find(c => c.toUpperCase().includes('CPM')) || numericCols[0] || cols[0],
84
+ yAxisKey: numericCols.find(c => c.toUpperCase().includes('CTR')) || numericCols[1] || cols[1],
85
+ labelKey: cols.find(c => /name|campaign|product/i.test(c)) || cols[0],
86
+ categoryKey: cols.find(c => /type|category/i.test(c)) || '',
87
+ groupByKeys: [],
88
+ sizeKey: numericCols.find(c => /spend|cost|budget|impression/i.test(c)) || '',
89
+ }));
90
+ setPointOverrides({});
91
+ }
92
+ };
93
+ reader.readAsBinaryString(file);
94
+ };
95
+
96
+ const onDrop = useCallback((e: React.DragEvent) => {
97
+ e.preventDefault();
98
+ setIsDragging(false);
99
+ const file = e.dataTransfer.files[0];
100
+ if (file && (file.name.endsWith('.xlsx') || file.name.endsWith('.xls') || file.name.endsWith('.csv'))) {
101
+ handleFileUpload(file);
102
+ }
103
+ }, []);
104
+
105
+ // Removed old stats useMemo as it is now calculated per chart
106
+
107
+ const chartData = useMemo(() => {
108
+ if (!data.length || !config.xAxisKey || !config.yAxisKey) return [];
109
+
110
+ // Keep the filtering logic if needed, but the user didn't ask to change it
111
+ const campaignsToRemove = ['Gender holiday promotion', 'AIOT March promotion'];
112
+
113
+ return data
114
+ .filter(d => {
115
+ const label = String(d[config.labelKey] || '').trim().toLowerCase();
116
+ const isHidden = pointOverrides[d.__id]?.hidden;
117
+
118
+ // Filter out abnormal points (CPC, CPV, ER = empty)
119
+ const cpc = String(d['CPC'] || '').trim();
120
+ const cpv = String(d['CPV'] || '').trim();
121
+ const er = String(d['ER'] || '').trim();
122
+
123
+ const isAbnormal = (d.hasOwnProperty('CPC') && cpc === '') ||
124
+ (d.hasOwnProperty('CPV') && cpv === '') ||
125
+ (d.hasOwnProperty('ER') && er === '');
126
+
127
+ return !campaignsToRemove.some(c => c.toLowerCase() === label) && !isHidden && !isAbnormal;
128
+ })
129
+ .map(d => ({
130
+ ...d,
131
+ x: parseNumeric(d[config.xAxisKey]),
132
+ y: parseNumeric(d[config.yAxisKey]),
133
+ z: config.sizeKey ? parseNumeric(d[config.sizeKey]) : 1,
134
+ color: pointOverrides[d.__id]?.color || '#6366f1'
135
+ }))
136
+ .filter(d => !isNaN(d.x) && !isNaN(d.y));
137
+ }, [data, config.xAxisKey, config.yAxisKey, config.labelKey, pointOverrides]);
138
+
139
+ const multiChartData = useMemo(() => {
140
+ if (!chartData.length) return [];
141
+
142
+ if (config.groupByKeys.length === 0) {
143
+ return [{ name: 'All Data', points: chartData }];
144
+ }
145
+
146
+ const groups: Record<string, DataPoint[]> = {};
147
+ chartData.forEach(d => {
148
+ const groupName = config.groupByKeys
149
+ .map(key => `${key}: ${d[key] || 'Other'}`)
150
+ .join(' | ');
151
+
152
+ if (!groups[groupName]) groups[groupName] = [];
153
+ groups[groupName].push(d);
154
+ });
155
+
156
+ return Object.entries(groups).map(([name, points]) => ({ name, points }));
157
+ }, [chartData, config.groupByKeys]);
158
+
159
+ const calculateStats = (points: DataPoint[]) => {
160
+ if (!points.length) return null;
161
+ const xValues = points.map(d => d.x).filter(v => !isNaN(v));
162
+ const yValues = points.map(d => d.y).filter(v => !isNaN(v));
163
+
164
+ if (xValues.length === 0 || yValues.length === 0) return null;
165
+
166
+ const xMean = xValues.reduce((a, b) => a + b, 0) / xValues.length;
167
+ const yMean = yValues.reduce((a, b) => a + b, 0) / yValues.length;
168
+
169
+ const xMin = Math.min(...xValues);
170
+ const xMax = Math.max(...xValues);
171
+ const yMin = Math.min(...yValues);
172
+ const yMax = Math.max(...yValues);
173
+
174
+ return { xMean, yMean, xMin, xMax, yMin, yMax };
175
+ };
176
+
177
+ const colors = ['#3b82f6', '#f97316', '#10b981', '#8b5cf6', '#ec4899', '#f59e0b'];
178
+ const shapes = ['circle', 'cross', 'diamond', 'square', 'star', 'triangle'];
179
+
180
+ const formatValue = (val: any) => {
181
+ const num = Number(val);
182
+ if (isNaN(num)) return val;
183
+ return num <= 1 && num >= 0 ? `${(num * 100).toFixed(2)}%` : num.toFixed(2);
184
+ };
185
+
186
+ const [copyingId, setCopyingId] = useState<string | null>(null);
187
+
188
+ const copyChart = useCallback((elementId: string) => {
189
+ const el = document.getElementById(elementId);
190
+ if (!el) return;
191
+
192
+ setCopyingId(elementId);
193
+ toBlob(el, { backgroundColor: '#ffffff' })
194
+ .then((blob) => {
195
+ if (blob) {
196
+ const item = new ClipboardItem({ 'image/png': blob });
197
+ navigator.clipboard.write([item]);
198
+ setTimeout(() => setCopyingId(null), 2000);
199
+ }
200
+ })
201
+ .catch((err) => {
202
+ console.error('Failed to copy chart', err);
203
+ setCopyingId(null);
204
+ });
205
+ }, []);
206
+
207
+ const downloadPng = useCallback(() => {
208
+ if (chartRef.current === null) return;
209
+ toPng(chartRef.current, { cacheBust: true, backgroundColor: '#ffffff' })
210
+ .then((dataUrl) => {
211
+ const link = document.createElement('a');
212
+ link.download = `${config.title || 'quadrant-chart'}.png`;
213
+ link.href = dataUrl;
214
+ link.click();
215
+ })
216
+ .catch((err) => {
217
+ console.error('oops, something went wrong!', err);
218
+ });
219
+ }, [config.title]);
220
+
221
+ const renderCustomShape = (props: any) => {
222
+ const { cx, cy, fill, shapeIndex } = props;
223
+ const shape = shapes[shapeIndex % shapes.length];
224
+
225
+ switch (shape) {
226
+ case 'cross':
227
+ return (
228
+ <g transform={`translate(${cx - 6}, ${cy - 6})`}>
229
+ <path d="M0 0 L12 12 M12 0 L0 12" stroke={fill} strokeWidth={3} fill="none" />
230
+ </g>
231
+ );
232
+ case 'diamond':
233
+ return <path d={`M${cx},${cy - 8} L${cx + 8},${cy} L${cx},${cy + 8} L${cx - 8},${cy} Z`} fill={fill} />;
234
+ case 'square':
235
+ return <rect x={cx - 6} y={cy - 6} width={12} height={12} fill={fill} />;
236
+ default:
237
+ return <circle cx={cx} cy={cy} r={6} fill={fill} />;
238
+ }
239
+ };
240
+
241
+ return (
242
+ <div className="min-h-screen bg-[#f8fafc] text-slate-900 font-sans pb-20">
243
+ <header className="bg-white border-b border-slate-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10">
244
+ <div className="flex items-center gap-3">
245
+ <div className="bg-indigo-600 p-2 rounded-lg">
246
+ <BarChart2 className="text-white w-6 h-6" />
247
+ </div>
248
+ <h1 className="text-xl font-bold tracking-tight">Quadrant Chart Pro</h1>
249
+ </div>
250
+ <div className="flex items-center gap-4">
251
+ <button
252
+ onClick={() => {
253
+ const sample = [
254
+ { Name: 'Redmi note 14 launch', CPM: 0.71, CTR: 0.80, Type: 'Launch' },
255
+ { Name: 'Xiaomi 15 launch', CPM: 0.67, CTR: 0.41, Type: 'Launch' },
256
+ { Name: 'Redmi 15/15C launch', CPM: 0.54, CTR: 0.43, Type: 'Launch' },
257
+ { Name: 'Redmi note 14XFF', CPM: 0.45, CTR: 0.48, Type: 'Promotion' },
258
+ { Name: 'Xiaomi Pad 7 Pro', CPM: 0.34, CTR: 0.66, Type: 'Launch' },
259
+ { Name: 'REDMI Pad 2 launch', CPM: 0.30, CTR: 0.56, Type: 'Launch' },
260
+ { Name: 'Smartphone NY Promo', CPM: 0.26, CTR: 0.37, Type: 'Promotion' },
261
+ { Name: 'TV March promotion', CPM: 0.27, CTR: 0.09, Type: 'Promotion' },
262
+ { Name: 'Xiaomi 15T series launch', CPM: 0.19, CTR: 0.31, Type: 'Launch' },
263
+ { Name: 'Redmi Pad 2 Pro launch', CPM: 0.15, CTR: 0.38, Type: 'Launch' },
264
+ { Name: 'Redmi A5 launch', CPM: 0.19, CTR: 0.27, Type: 'Launch' },
265
+ { Name: 'Xiaomi Robot Vacuum 5 launch', CPM: 0.11, CTR: 0.15, Type: 'Launch' },
266
+ { Name: 'Band10 launch', CPM: 0.12, CTR: 0.05, Type: 'Launch' },
267
+ ];
268
+ setColumns(Object.keys(sample[0]));
269
+ setData(sample);
270
+ setConfig({
271
+ xAxisKey: 'CPM',
272
+ yAxisKey: 'CTR',
273
+ labelKey: 'Name',
274
+ categoryKey: 'Type',
275
+ groupByKeys: [],
276
+ sizeKey: 'CPM', // Just for example
277
+ title: 'Campaign Performance Quadrant (CPM vs CTR)',
278
+ });
279
+ }}
280
+ className="text-sm font-medium text-indigo-600 hover:text-indigo-700"
281
+ >
282
+ Load Sample Data
283
+ </button>
284
+ <button
285
+ onClick={downloadPng}
286
+ disabled={multiChartData.length === 0}
287
+ className="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-indigo-600 text-white hover:bg-indigo-700 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
288
+ >
289
+ <ImageIcon size={18} />
290
+ Save as PNG
291
+ </button>
292
+ </div>
293
+ </header>
294
+
295
+ <main className="max-w-[1600px] mx-auto p-6 grid grid-cols-1 lg:grid-cols-4 gap-6">
296
+ <div className="lg:col-span-1 space-y-6">
297
+ <section className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
298
+ <h2 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mb-4 flex items-center gap-2">
299
+ <FileSpreadsheet size={16} />
300
+ Data Source
301
+ </h2>
302
+ <div
303
+ onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
304
+ onDragLeave={() => setIsDragging(false)}
305
+ onDrop={onDrop}
306
+ className={cn(
307
+ "border-2 border-dashed rounded-xl p-8 text-center transition-all cursor-pointer",
308
+ isDragging ? "border-indigo-500 bg-indigo-50" : "border-slate-200 hover:border-slate-300",
309
+ data.length > 0 ? "py-4" : "py-12"
310
+ )}
311
+ onClick={() => document.getElementById('file-upload')?.click()}
312
+ >
313
+ <input id="file-upload" type="file" className="hidden" accept=".xlsx,.xls,.csv" onChange={(e) => e.target.files?.[0] && handleFileUpload(e.target.files[0])} />
314
+ <Upload className={cn("mx-auto mb-3 text-slate-400", data.length > 0 ? "w-6 h-6" : "w-10 h-10")} />
315
+ <p className="text-sm font-medium text-slate-600">{data.length > 0 ? "Change File" : "Drop Excel file here"}</p>
316
+ </div>
317
+ </section>
318
+
319
+ <section className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
320
+ <h2 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mb-4 flex items-center gap-2">
321
+ <Settings2 size={16} />
322
+ Configuration
323
+ </h2>
324
+ <div className="space-y-4">
325
+ <div>
326
+ <label className="block text-xs font-bold text-slate-700 mb-1.5">Chart Title</label>
327
+ <input type="text" value={config.title} onChange={(e) => setConfig(prev => ({ ...prev, title: e.target.value }))} className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 outline-none" />
328
+ </div>
329
+ <div>
330
+ <label className="block text-xs font-bold text-slate-700 mb-1.5">X-Axis</label>
331
+ <select value={config.xAxisKey} onChange={(e) => setConfig(prev => ({ ...prev, xAxisKey: e.target.value }))} className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
332
+ {columns.map(col => <option key={col} value={col}>{col}</option>)}
333
+ </select>
334
+ </div>
335
+ <div>
336
+ <label className="block text-xs font-bold text-slate-700 mb-1.5">Y-Axis</label>
337
+ <select value={config.yAxisKey} onChange={(e) => setConfig(prev => ({ ...prev, yAxisKey: e.target.value }))} className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
338
+ {columns.map(col => <option key={col} value={col}>{col}</option>)}
339
+ </select>
340
+ </div>
341
+ <div>
342
+ <label className="block text-xs font-bold text-slate-700 mb-1.5">Label</label>
343
+ <select value={config.labelKey} onChange={(e) => setConfig(prev => ({ ...prev, labelKey: e.target.value }))} className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
344
+ {columns.map(col => <option key={col} value={col}>{col}</option>)}
345
+ </select>
346
+ </div>
347
+ <div>
348
+ <label className="block text-xs font-bold text-slate-700 mb-1.5">Point Size (Weight)</label>
349
+ <select value={config.sizeKey} onChange={(e) => setConfig(prev => ({ ...prev, sizeKey: e.target.value }))} className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
350
+ <option value="">Uniform Size</option>
351
+ {columns.map(col => <option key={col} value={col}>{col}</option>)}
352
+ </select>
353
+ </div>
354
+ <div>
355
+ <label className="block text-xs font-bold text-slate-700 mb-1.5">Group By (Separate Charts)</label>
356
+ <div className="space-y-1 max-h-40 overflow-y-auto p-2 bg-slate-50 border border-slate-200 rounded-lg">
357
+ {columns.map(col => (
358
+ <label key={col} className="flex items-center gap-2 text-sm cursor-pointer hover:bg-slate-100 p-1 rounded">
359
+ <input
360
+ type="checkbox"
361
+ checked={config.groupByKeys.includes(col)}
362
+ onChange={(e) => {
363
+ const newKeys = e.target.checked
364
+ ? [...config.groupByKeys, col]
365
+ : config.groupByKeys.filter(k => k !== col);
366
+ setConfig(prev => ({ ...prev, groupByKeys: newKeys }));
367
+ }}
368
+ className="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500"
369
+ />
370
+ <span className="truncate">{col}</span>
371
+ </label>
372
+ ))}
373
+ {columns.length === 0 && <p className="text-xs text-slate-400 italic">Upload data first</p>}
374
+ </div>
375
+ </div>
376
+ </div>
377
+ </section>
378
+ </div>
379
+
380
+ <div ref={chartRef} className="lg:col-span-3 space-y-8">
381
+ {multiChartData.length > 0 ? (
382
+ multiChartData.map((group, groupIndex) => {
383
+ const groupStats = calculateStats(group.points);
384
+ if (!groupStats) return null;
385
+
386
+ return (
387
+ <div key={group.name} id={`chart-container-${groupIndex}`} className="bg-white p-8 rounded-3xl border border-slate-200 shadow-sm h-[700px] flex flex-col overflow-hidden relative group">
388
+ <div className="absolute top-4 right-4 opacity-0 group-hover:opacity-100 transition-opacity flex gap-2 z-20">
389
+ <button
390
+ onClick={() => copyChart(`chart-container-${groupIndex}`)}
391
+ className="p-2 bg-white border border-slate-200 rounded-lg shadow-sm hover:bg-slate-50 transition-colors flex items-center gap-2 text-xs font-medium text-slate-600"
392
+ title="Copy to Clipboard"
393
+ >
394
+ {copyingId === `chart-container-${groupIndex}` ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
395
+ {copyingId === `chart-container-${groupIndex}` ? 'Copied!' : 'Copy'}
396
+ </button>
397
+ </div>
398
+ <div className="mb-6 text-center">
399
+ <h2 className="text-2xl font-bold text-slate-800 tracking-tight">{config.title}</h2>
400
+ <div className="flex flex-wrap justify-center gap-x-6 gap-y-1 mt-2 text-sm border-t border-slate-100 pt-2">
401
+ <span className="text-slate-500">
402
+ X-Axis: <span className="text-slate-900 font-semibold">{config.xAxisKey}</span>
403
+ </span>
404
+ <span className="text-slate-500">
405
+ Y-Axis: <span className="text-slate-900 font-semibold">{config.yAxisKey}</span>
406
+ </span>
407
+ {config.sizeKey && (
408
+ <span className="text-slate-500">
409
+ Size: <span className="text-slate-900 font-semibold">{config.sizeKey}</span>
410
+ </span>
411
+ )}
412
+ {config.groupByKeys.length > 0 && (
413
+ <span className="text-slate-500">
414
+ Group: <span className="text-indigo-600 font-bold">{group.name}</span>
415
+ </span>
416
+ )}
417
+ </div>
418
+ </div>
419
+ <div className="flex-1 w-full relative">
420
+ <ResponsiveContainer width="100%" height="100%">
421
+ <ScatterChart margin={{ top: 40, right: 40, bottom: 60, left: 60 }}>
422
+ <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
423
+ <XAxis
424
+ type="number"
425
+ dataKey="x"
426
+ name={config.xAxisKey}
427
+ stroke="#94a3b8"
428
+ fontSize={12}
429
+ domain={['auto', 'auto']}
430
+ tickFormatter={formatValue}
431
+ label={{ value: `${config.xAxisKey} | Mean = ${formatValue(groupStats.xMean)}`, position: 'bottom', offset: 40, style: { fill: '#475569', fontWeight: 600, fontSize: 14 } }}
432
+ />
433
+ <YAxis
434
+ type="number"
435
+ dataKey="y"
436
+ name={config.yAxisKey}
437
+ stroke="#94a3b8"
438
+ fontSize={12}
439
+ domain={['auto', 'auto']}
440
+ tickFormatter={formatValue}
441
+ label={{ value: `${config.yAxisKey} | Mean = ${formatValue(groupStats.yMean)}`, angle: -90, position: 'left', offset: 40, style: { fill: '#475569', fontWeight: 600, fontSize: 14 } }}
442
+ />
443
+ <ZAxis type="number" dataKey="z" range={config.sizeKey ? [50, 800] : [100, 100]} />
444
+ <Tooltip
445
+ content={({ active, payload }) => {
446
+ if (active && payload && payload.length) {
447
+ const d = payload[0].payload;
448
+ return (
449
+ <div className="bg-white p-4 border border-slate-200 shadow-2xl rounded-xl text-sm min-w-[220px]">
450
+ <p className="font-bold text-slate-900 mb-3 border-b border-slate-100 pb-2 text-base">{d[config.labelKey]}</p>
451
+ <div className="space-y-2 mb-3">
452
+ <div className="flex flex-col bg-slate-50 p-2 rounded-lg border border-slate-100">
453
+ <span className="text-[10px] uppercase tracking-wider text-slate-400 font-bold">{config.xAxisKey} (X)</span>
454
+ <span className="font-mono font-bold text-indigo-600 text-lg leading-none">{formatValue(d.x)}</span>
455
+ </div>
456
+ <div className="flex flex-col bg-slate-50 p-2 rounded-lg border border-slate-100">
457
+ <span className="text-[10px] uppercase tracking-wider text-slate-400 font-bold">{config.yAxisKey} (Y)</span>
458
+ <span className="font-mono font-bold text-indigo-600 text-lg leading-none">{formatValue(d.y)}</span>
459
+ </div>
460
+ {config.sizeKey && (
461
+ <div className="flex flex-col bg-slate-50 p-2 rounded-lg border border-slate-100">
462
+ <span className="text-[10px] uppercase tracking-wider text-slate-400 font-bold">{config.sizeKey} (Size)</span>
463
+ <span className="font-mono font-bold text-indigo-600 text-lg leading-none">{formatValue(d.z)}</span>
464
+ </div>
465
+ )}
466
+ </div>
467
+ <div className="space-y-1 pt-2 border-t border-slate-100">
468
+ {columns.filter(c => c !== config.xAxisKey && c !== config.yAxisKey && c !== config.labelKey && c !== config.sizeKey && !c.startsWith('__')).slice(0, 5).map(col => (
469
+ <p key={col} className="flex justify-between gap-4 text-[11px]">
470
+ <span className="text-slate-400 truncate max-w-[120px]">{col}:</span>
471
+ <span className="text-slate-600 font-medium">{String(d[col] || '')}</span>
472
+ </p>
473
+ ))}
474
+ </div>
475
+ <p className="mt-3 text-[10px] text-center text-indigo-400 italic font-medium animate-pulse">Click point to edit or remove</p>
476
+ </div>
477
+ );
478
+ }
479
+ return null;
480
+ }}
481
+ />
482
+ <ReferenceLine x={groupStats.xMean} stroke="#6366f1" strokeDasharray="5 5" strokeWidth={2} />
483
+ <ReferenceLine y={groupStats.yMean} stroke="#6366f1" strokeDasharray="5 5" strokeWidth={2} />
484
+
485
+ {/* Quadrant Labels */}
486
+ <Text x="25%" y="15%" textAnchor="middle" fill="#cbd5e1" fontSize={14} fontWeight="bold">LOW {config.xAxisKey} / HIGH {config.yAxisKey}</Text>
487
+ <Text x="75%" y="15%" textAnchor="middle" fill="#cbd5e1" fontSize={14} fontWeight="bold">HIGH {config.xAxisKey} / HIGH {config.yAxisKey}</Text>
488
+ <Text x="25%" y="85%" textAnchor="middle" fill="#cbd5e1" fontSize={14} fontWeight="bold">LOW {config.xAxisKey} / LOW {config.yAxisKey}</Text>
489
+ <Text x="75%" y="85%" textAnchor="middle" fill="#cbd5e1" fontSize={14} fontWeight="bold">HIGH {config.xAxisKey} / LOW {config.yAxisKey}</Text>
490
+
491
+ <Scatter
492
+ name={group.name}
493
+ data={group.points}
494
+ onClick={(data) => {
495
+ if (data && data.payload) {
496
+ setSelectedPoint({
497
+ id: data.payload.__id,
498
+ label: data.payload[config.labelKey]
499
+ });
500
+ }
501
+ }}
502
+ cursor="pointer"
503
+ >
504
+ {group.points.map((entry, index) => (
505
+ <Cell key={`cell-${index}`} fill={entry.color} />
506
+ ))}
507
+ <LabelList dataKey={config.labelKey} position="top" offset={10} style={{ fontSize: '10px', fill: '#64748b', fontWeight: 500 }} />
508
+ </Scatter>
509
+ </ScatterChart>
510
+ </ResponsiveContainer>
511
+ </div>
512
+ </div>
513
+ );
514
+ })
515
+ ) : (
516
+ <div className="bg-white p-8 rounded-3xl border border-slate-200 shadow-sm h-[700px] flex flex-col items-center justify-center text-slate-300">
517
+ <BarChart2 size={80} className="mb-4 opacity-20" />
518
+ <p>Upload data and configure axes to see the chart</p>
519
+ </div>
520
+ )}
521
+ </div>
522
+ </main>
523
+
524
+ {/* Point Interaction Modal */}
525
+ {selectedPoint && (
526
+ <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
527
+ <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in duration-200">
528
+ <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
529
+ <h3 className="font-bold text-slate-800 truncate pr-4">Edit Point: {selectedPoint.label}</h3>
530
+ <button onClick={() => setSelectedPoint(null)} className="p-1 hover:bg-slate-200 rounded-full transition-colors">
531
+ <X size={20} className="text-slate-500" />
532
+ </button>
533
+ </div>
534
+ <div className="p-6 space-y-6">
535
+ <div>
536
+ <label className="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-3 flex items-center gap-2">
537
+ <Palette size={14} />
538
+ Change Color
539
+ </label>
540
+ <div className="grid grid-cols-6 gap-3">
541
+ {['#6366f1', '#ef4444', '#10b981', '#f59e0b', '#ec4899', '#8b5cf6', '#06b6d4', '#475569', '#000000', '#f97316', '#84cc16', '#a855f7'].map(color => (
542
+ <button
543
+ key={color}
544
+ onClick={() => {
545
+ setPointOverrides(prev => ({
546
+ ...prev,
547
+ [selectedPoint.id]: { ...prev[selectedPoint.id], color }
548
+ }));
549
+ }}
550
+ className={cn(
551
+ "w-10 h-10 rounded-full border-2 transition-all hover:scale-110",
552
+ pointOverrides[selectedPoint.id]?.color === color || (!pointOverrides[selectedPoint.id]?.color && color === '#6366f1')
553
+ ? "border-slate-900 scale-110 shadow-lg"
554
+ : "border-transparent"
555
+ )}
556
+ style={{ backgroundColor: color }}
557
+ >
558
+ {(pointOverrides[selectedPoint.id]?.color === color || (!pointOverrides[selectedPoint.id]?.color && color === '#6366f1')) && (
559
+ <Check size={16} className="mx-auto text-white drop-shadow-md" />
560
+ )}
561
+ </button>
562
+ ))}
563
+ </div>
564
+ </div>
565
+
566
+ <div className="pt-4 border-t border-slate-100">
567
+ <button
568
+ onClick={() => {
569
+ setPointOverrides(prev => ({
570
+ ...prev,
571
+ [selectedPoint.id]: { ...prev[selectedPoint.id], hidden: true }
572
+ }));
573
+ setSelectedPoint(null);
574
+ }}
575
+ className="w-full flex items-center justify-center gap-2 py-3 px-4 bg-red-50 text-red-600 hover:bg-red-100 rounded-xl font-semibold transition-colors"
576
+ >
577
+ <Trash2 size={18} />
578
+ Remove Point from Chart
579
+ </button>
580
+ </div>
581
+ </div>
582
+ <div className="px-6 py-4 bg-slate-50 border-t border-slate-100 flex justify-end">
583
+ <button
584
+ onClick={() => setSelectedPoint(null)}
585
+ className="px-6 py-2 bg-slate-900 text-white rounded-xl font-semibold hover:bg-slate-800 transition-colors"
586
+ >
587
+ Done
588
+ </button>
589
+ </div>
590
+ </div>
591
+ </div>
592
+ )}
593
+
594
+ {data.length > 0 && (
595
+ <section className="max-w-[1600px] mx-auto px-6">
596
+ <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
597
+ <div className="px-6 py-4 border-b border-slate-100 bg-slate-50/50">
598
+ <h3 className="text-sm font-bold text-slate-700">Data Preview (First 10 rows)</h3>
599
+ </div>
600
+ <div className="overflow-x-auto">
601
+ <table className="w-full text-left text-sm border-collapse">
602
+ <thead>
603
+ <tr className="bg-slate-50">
604
+ {columns.map(col => <th key={col} className="px-6 py-3 font-semibold text-slate-600 border-b border-slate-100">{col}</th>)}
605
+ </tr>
606
+ </thead>
607
+ <tbody>
608
+ {data.slice(0, 10).map((row, i) => (
609
+ <tr key={i} className="hover:bg-slate-50 transition-colors">
610
+ {columns.map(col => <td key={col} className="px-6 py-3 text-slate-500 border-b border-slate-100">{String(row[col] || '')}</td>)}
611
+ </tr>
612
+ ))}
613
+ </tbody>
614
+ </table>
615
+ </div>
616
+ </div>
617
+ </section>
618
+ )}
619
+ </div>
620
+ );
621
+ }
src/index.css ADDED
@@ -0,0 +1 @@
 
 
1
+ @import "tailwindcss";
src/main.tsx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import {StrictMode} from 'react';
2
+ import {createRoot} from 'react-dom/client';
3
+ import App from './App.tsx';
4
+ import './index.css';
5
+
6
+ createRoot(document.getElementById('root')!).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>,
10
+ );
src/types.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface DataPoint {
2
+ [key: string]: any;
3
+ }
4
+
5
+ export interface ChartConfig {
6
+ xAxisKey: string;
7
+ yAxisKey: string;
8
+ labelKey: string;
9
+ categoryKey?: string;
10
+ groupByKeys: string[];
11
+ sizeKey?: string;
12
+ title: string;
13
+ }
14
+
15
+ export interface PointOverride {
16
+ color?: string;
17
+ hidden?: boolean;
18
+ }
19
+
20
+ export interface QuadrantData {
21
+ points: DataPoint[];
22
+ xMean: number;
23
+ yMean: number;
24
+ xLabel: string;
25
+ yLabel: string;
26
+ }
tsconfig.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "experimentalDecorators": true,
5
+ "useDefineForClassFields": false,
6
+ "module": "ESNext",
7
+ "lib": [
8
+ "ES2022",
9
+ "DOM",
10
+ "DOM.Iterable"
11
+ ],
12
+ "skipLibCheck": true,
13
+ "moduleResolution": "bundler",
14
+ "isolatedModules": true,
15
+ "moduleDetection": "force",
16
+ "allowJs": true,
17
+ "jsx": "react-jsx",
18
+ "paths": {
19
+ "@/*": [
20
+ "./*"
21
+ ]
22
+ },
23
+ "allowImportingTsExtensions": true,
24
+ "noEmit": true
25
+ }
26
+ }
vite.config.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tailwindcss from '@tailwindcss/vite';
2
+ import react from '@vitejs/plugin-react';
3
+ import path from 'path';
4
+ import {defineConfig, loadEnv} from 'vite';
5
+
6
+ export default defineConfig(({mode}) => {
7
+ const env = loadEnv(mode, '.', '');
8
+ return {
9
+ plugins: [react(), tailwindcss()],
10
+ define: {
11
+ 'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY),
12
+ },
13
+ resolve: {
14
+ alias: {
15
+ '@': path.resolve(__dirname, '.'),
16
+ },
17
+ },
18
+ server: {
19
+ // HMR is disabled in AI Studio via DISABLE_HMR env var.
20
+ // Do not modify—file watching is disabled to prevent flickering during agent edits.
21
+ hmr: process.env.DISABLE_HMR !== 'true',
22
+ },
23
+ };
24
+ });