File size: 10,729 Bytes
084a9db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import React, { useState, useEffect, useRef } from 'react';
import { QRCodeCanvas } from 'qrcode.react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Slider } from '@/components/ui/slider';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Download, ImagePlus, Palette, Settings, Trash2, XCircle } from 'lucide-react';
import { AppLogoIcon } from '@/components/icons/app-logo-icon';
import { useToast } from "@/hooks/use-toast";

type ErrorCorrectionLevel = 'L' | 'M' | 'Q' | 'H';

export default function QRCodeCanvasPage() {
  const [text, setText] = useState<string>('hello qr');
  const [fgColor, setFgColor] = useState<string>('#805CFF'); // Default to new dark primary
  const [bgColor, setBgColor] = useState<string>('#FFFFFF');
  const [level, setLevel] = useState<ErrorCorrectionLevel>('M');
  const [qrSize, setQrSize] = useState<number>(256);
  const [logoSrc, setLogoSrc] = useState<string | null>(null);
  const [logoFile, setLogoFile] = useState<File | null>(null);
  const [mounted, setMounted] = useState(false);

  const { toast } = useToast();
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setMounted(true); 
  }, []);

  const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setLogoFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setLogoSrc(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const removeLogo = () => {
    setLogoSrc(null);
    setLogoFile(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = ''; 
    }
  };

  const downloadQRCode = () => {
    if (!text) {
      toast({
        title: "Error",
        description: "Please enter text or URL to generate QR code.",
        variant: "destructive",
      });
      return;
    }
    const canvas = document.getElementById('qr-canvas') as HTMLCanvasElement;
    if (canvas) {
      try {
        const pngUrl = canvas.toDataURL('image/png');
        const downloadLink = document.createElement('a');
        downloadLink.href = pngUrl;
        downloadLink.download = 'qrcode.png';
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        toast({
          title: "Success!",
          description: "QR Code downloaded successfully.",
        });
      } catch (error) {
        console.error("Failed to download QR Code:", error);
        toast({
          title: "Error",
          description: "Failed to download QR Code. The logo might be from a restricted source if hosted externally. Try uploading it directly.",
          variant: "destructive",
        });
      }
    }
  };

  const imageSettings = logoSrc
    ? {
        src: logoSrc,
        height: qrSize * 0.22,
        width: qrSize * 0.22,
        excavate: true,
        x: undefined, 
        y: undefined, 
      }
    : undefined;
  
  const qrKey = JSON.stringify({ text, fgColor, bgColor, level, qrSize, logoSrc });

  return (
    <div className="min-h-screen bg-background text-foreground flex flex-col items-center p-4 sm:p-6 md:p-8">
      <header className="w-full max-w-6xl mb-8">
        <div className="flex items-center gap-3">
          <AppLogoIcon className="h-10 w-10 text-primary" />
          <h1 className="text-4xl font-headline font-semibold text-primary tracking-tight">QRCode Canvas</h1>
        </div>
        <p className="text-lg text-muted-foreground font-body mt-1">
          Create and customize your QR codes with ease.
        </p>
      </header>

      <main className="w-full max-w-6xl flex-grow">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <Card className="lg:col-span-1 rounded-xl shadow-xl">
            <CardHeader>
              <CardTitle className="font-headline text-2xl flex items-center gap-2">
                <Settings className="h-6 w-6 text-accent" />
                Customize
              </CardTitle>
              <CardDescription className="font-body">
                Tailor your QR code to match your style.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-2">
                <Label htmlFor="text-input" className="font-body font-medium">Content (URL or Text)</Label>
                <Textarea
                  id="text-input"
                  value={text}
                  onChange={(e) => setText(e.target.value)}
                  placeholder="Enter URL or text"
                  rows={3}
                  className="font-body"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="fg-color" className="font-body font-medium flex items-center gap-1.5">
                    <Palette size={16} /> Foreground
                  </Label>
                  <Input
                    id="fg-color"
                    type="color"
                    value={fgColor}
                    onChange={(e) => setFgColor(e.target.value)}
                    className="h-10 w-full p-1"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="bg-color" className="font-body font-medium flex items-center gap-1.5">
                     <Palette size={16} /> Background
                  </Label>
                  <Input
                    id="bg-color"
                    type="color"
                    value={bgColor}
                    onChange={(e) => setBgColor(e.target.value)}
                    className="h-10 w-full p-1"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="error-correction" className="font-body font-medium">Error Correction</Label>
                <Select value={level} onValueChange={(value: string) => setLevel(value as ErrorCorrectionLevel)}>
                  <SelectTrigger id="error-correction" className="font-body">
                    <SelectValue placeholder="Select level" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="L">Low (L)</SelectItem>
                    <SelectItem value="M">Medium (M)</SelectItem>
                    <SelectItem value="Q">Quartile (Q)</SelectItem>
                    <SelectItem value="H">High (H)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="qr-size" className="font-body font-medium">Size ({qrSize}px)</Label>
                <Slider
                  id="qr-size"
                  min={64}
                  max={1024}
                  step={8}
                  value={[qrSize]}
                  onValueChange={(value) => setQrSize(value[0])}
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="logo-upload" className="font-body font-medium">Logo (Optional)</Label>
                <div className="flex items-center gap-2">
                  <Input
                    id="logo-upload"
                    type="file"
                    accept="image/png, image/jpeg, image/svg+xml"
                    onChange={handleLogoChange}
                    ref={fileInputRef}
                    className="font-body flex-grow"
                  />
                  {logoSrc && (
                    <Button variant="ghost" size="icon" onClick={removeLogo} aria-label="Remove logo" className="text-destructive hover:text-destructive">
                      <XCircle size={20} />
                    </Button>
                  )}
                </div>
                 {logoFile && (
                  <p className="text-xs text-muted-foreground font-body truncate">
                    Selected: {logoFile.name}
                  </p>
                )}
              </div>
            </CardContent>
          </Card>

          <Card className="lg:col-span-2 rounded-xl shadow-xl flex flex-col">
            <CardHeader>
              <CardTitle className="font-headline text-2xl">Preview</CardTitle>
              <CardDescription className="font-body">
                Your generated QR code will appear here.
              </CardDescription>
            </CardHeader>
            <CardContent className="flex-grow flex items-center justify-center p-6 bg-muted/30 rounded-md aspect-square overflow-hidden">
              {mounted && text ? (
                 <div style={{ width: qrSize, height: qrSize }} className="transition-all duration-300 ease-in-out">
                    <QRCodeCanvas
                        id="qr-canvas"
                        value={text}
                        size={qrSize}
                        fgColor={fgColor}
                        bgColor={bgColor}
                        level={level}
                        imageSettings={imageSettings}
                        includeMargin={true}
                        key={qrKey} 
                    />
                 </div>
              ) : (
                <div className="flex flex-col items-center justify-center text-muted-foreground p-8 aspect-square w-full max-w-[256px]">
                  <ImagePlus size={64} className="mb-4" />
                  <p className="text-center font-body">
                    {text ? "Generating QR Code..." : "Enter content to generate a QR code."}
                  </p>
                </div>
              )}
            </CardContent>
            <CardFooter className="mt-auto pt-6">
              <Button onClick={downloadQRCode} className="w-full font-body text-base py-3" size="lg" disabled={!text}>
                <Download size={20} className="mr-2" />
                Download QR Code
              </Button>
            </CardFooter>
          </Card>
        </div>
      </main>
      <footer className="w-full max-w-6xl mt-12 text-center">
        <p className="text-sm text-muted-foreground font-body">
          &copy; {new Date().getFullYear()} QRCode Canvas. Created by Sameer Banchhor, SlimShadow Org. All rights reserved.
        </p>
      </footer>
    </div>
  );
}