File size: 7,688 Bytes
19e93fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/* ============================================================
 * Galerie-Speicher: IndexedDB (unbegrenzt) mit localStorage-Migration
 * ============================================================ */

export type GalleryTag = "design" | "shop";

export interface GalleryImage {
  id: string;
  image: string; // base64 (ohne data:-Prefix)
  contentType: string;
  provider: string;
  model: string;
  tag: GalleryTag;
  addedAt: number;
}

export const toDataUrl = (img: { image: string; contentType?: string }) =>
  `data:${img.contentType || "image/png"};base64,${img.image}`;

const DB_NAME = "drip-gallery-db";
const DB_VERSION = 1;
const STORE = "images";

function openDB(): Promise<IDBDatabase> {
  return new Promise((resolve, reject) => {
    const req = indexedDB.open(DB_NAME, DB_VERSION);
    req.onupgradeneeded = () => {
      const db = req.result;
      if (!db.objectStoreNames.contains(STORE)) {
        db.createObjectStore(STORE, { keyPath: "id" });
      }
    };
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error || new Error("IndexedDB konnte nicht geöffnet werden."));
  });
}

async function withStore<T>(fn: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
  const db = await openDB();
  return new Promise<T>((resolve, reject) => {
    const tx = db.transaction(STORE, "readwrite");
    const req = fn(tx.objectStore(STORE));
    req.onsuccess = () => {
      resolve(req.result);
      // Nur schließen, wenn keine weiteren Requests anstehen
      tx.oncomplete = () => db.close();
    };
    req.onerror = () => {
      reject(req.error || new Error("IndexedDB-Operation fehlgeschlagen."));
      db.close();
    };
  });
}

/* ---------- Migration aus localStorage (einmalig) ---------- */
function migrateFromLocalStorage(): GalleryImage[] {
  try {
    const raw = localStorage.getItem("drip-gallery");
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    const migrated: GalleryImage[] = parsed
      .filter((x) => x && x.image)
      .map((x) => ({
        id: `migrated-${crypto.randomUUID()}`,
        image: x.image,
        contentType: x.contentType || "image/png",
        provider: x.provider || "Migriert",
        model: x.model || "Design",
        tag: x.tag === "shop" ? "shop" : "design",
        addedAt: Date.now(),
      }));
    if (migrated.length > 0) {
      localStorage.removeItem("drip-gallery");
    }
    return migrated;
  } catch {
    return [];
  }
}

/* ---------- Öffentliche API ---------- */
export async function galleryGetAll(): Promise<GalleryImage[]> {
  // Migration einmalig beim ersten Zugriff
  const migrated = migrateFromLocalStorage();
  try {
    const db = await openDB();
    const all = await new Promise<GalleryImage[]>((resolve, reject) => {
      const tx = db.transaction(STORE, "readonly");
      const req = tx.objectStore(STORE).getAll();
      req.onsuccess = () => resolve(req.result as GalleryImage[]);
      req.onerror = () => reject(req.error);
      tx.oncomplete = () => db.close();
    });
    if (migrated.length > 0) {
      await galleryAdd(migrated);
      return [...migrated, ...all];
    }
    return all;
  } catch {
    return migrated;
  }
}

export async function galleryAdd(items: GalleryImage[]): Promise<void> {
  if (!items.length) return;
  try {
    const db = await openDB();
    return await new Promise<void>((resolve, reject) => {
      const tx = db.transaction(STORE, "readwrite");
      const store = tx.objectStore(STORE);
      for (const item of items) store.put(item);
      tx.oncomplete = () => {
        resolve();
        db.close();
      };
      tx.onerror = () => {
        reject(tx.error);
        db.close();
      };
    });
  } catch (e) {
    // IndexedDB nicht verfügbar (z. B. privater Modus) → still ignorieren
    console.warn("Galerie-Speicher nicht verfügbar:", e);
  }
}

export async function galleryRemove(ids: string[]): Promise<void> {
  if (!ids.length) return;
  try {
    const db = await openDB();
    return await new Promise<void>((resolve, reject) => {
      const tx = db.transaction(STORE, "readwrite");
      const store = tx.objectStore(STORE);
      for (const id of ids) store.delete(id);
      tx.oncomplete = () => {
        resolve();
        db.close();
      };
      tx.onerror = () => {
        reject(tx.error);
        db.close();
      };
    });
  } catch {
    /* ignorieren */
  }
}

export async function galleryUpdate(id: string, patch: Partial<GalleryImage>): Promise<void> {
  try {
    const db = await openDB();
    return await new Promise<void>((resolve, reject) => {
      const tx = db.transaction(STORE, "readwrite");
      const store = tx.objectStore(STORE);
      const req = store.get(id);
      req.onsuccess = () => {
        const existing = req.result as GalleryImage | undefined;
        if (existing) store.put({ ...existing, ...patch });
      };
      tx.oncomplete = () => {
        resolve();
        db.close();
      };
      tx.onerror = () => {
        reject(tx.error);
        db.close();
      };
    });
  } catch {
    /* ignorieren */
  }
}

/** Aktive Auswahl fürs Studio merken (Galerie → Workspace) */
export function setStudioSelection(img: GalleryImage) {
  try {
    sessionStorage.setItem("drip-selected", JSON.stringify(img));
  } catch {
    /* ignorieren */
  }
}

export function takeStudioSelection(): GalleryImage | null {
  try {
    const raw = sessionStorage.getItem("drip-selected");
    if (!raw) return null;
    sessionStorage.removeItem("drip-selected");
    return JSON.parse(raw) as GalleryImage;
  } catch {
    return null;
  }
}

/* ---------- Bildverarbeitung (Upload) ---------- */
export async function fileToDataUrl(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = () => reject(new Error("Datei konnte nicht gelesen werden."));
    reader.readAsDataURL(file);
  });
}

/** Bild verkleinern (max. Kantenlänge) → JPEG-DataURL (base64 ohne Prefix) */
export async function resizeImage(
  dataUrl: string,
  max = 1024,
  quality = 0.85
): Promise<{ data: string; contentType: string }> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      try {
        const scale = Math.min(1, max / Math.max(img.naturalWidth, img.naturalHeight));
        const canvas = document.createElement("canvas");
        canvas.width = Math.max(1, Math.round(img.naturalWidth * scale));
        canvas.height = Math.max(1, Math.round(img.naturalHeight * scale));
        const ctx = canvas.getContext("2d");
        if (!ctx) throw new Error("Canvas nicht verfügbar.");
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        const out = canvas.toDataURL("image/jpeg", quality);
        resolve({ data: out.split(",")[1] || out, contentType: "image/jpeg" });
      } catch (e) {
        reject(e);
      }
    };
    img.onerror = () => reject(new Error("Bild konnte nicht geladen werden."));
    img.src = dataUrl;
  });
}

/** Datei → Galerie-Bild (verkleinert) */
export async function fileToGalleryImage(file: File, tag: GalleryTag): Promise<GalleryImage> {
  const dataUrl = await fileToDataUrl(file);
  const resized = await resizeImage(dataUrl);
  return {
    id: crypto.randomUUID(),
    image: resized.data,
    contentType: resized.contentType,
    provider: tag === "design" ? "Upload (Design)" : "Upload (Shop-Foto)",
    model: file.name || (tag === "design" ? "Design" : "Shop-Foto"),
    tag,
    addedAt: Date.now(),
  };
}