@optona/otofill 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2260 @@
1
+ // \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, flags) => {
4
+ let target = Object.setPrototypeOf({}, null);
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return flags & 2 ? target : Object.preventExtensions(target);
11
+ };
12
+ // src/util.ts
13
+ var TR = {
14
+ ı: "i",
15
+ ğ: "g",
16
+ ü: "u",
17
+ ş: "s",
18
+ ö: "o",
19
+ ç: "c",
20
+ â: "a",
21
+ î: "i",
22
+ û: "u"
23
+ };
24
+ /** Karşılaştırma için metni düzleştirir: Türkçe karakterler, büyük/küçük harf, noktalama. */
25
+ function norm(s) {
26
+ if (!s) return "";
27
+ return s.toLocaleLowerCase("tr").replace(/[ığüşöçâîû]/g, (c) => TR[c] ?? c).normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9]+/g, " ").trim();
28
+ }
29
+ /** İki metnin benzerliği (0..1), harf ikilileriyle Dice katsayısı. */
30
+ function similarity(a, b) {
31
+ a = norm(a).replace(/ /g, "");
32
+ b = norm(b).replace(/ /g, "");
33
+ if (!a || !b) return 0;
34
+ if (a === b) return 1;
35
+ if (a.length < 2 || b.length < 2) return 0;
36
+ const grams = /* @__PURE__ */ new Map();
37
+ for (let i = 0; i < a.length - 1; i++) {
38
+ const g = a.slice(i, i + 2);
39
+ grams.set(g, (grams.get(g) ?? 0) + 1);
40
+ }
41
+ let hit = 0;
42
+ for (let i = 0; i < b.length - 1; i++) {
43
+ const g = b.slice(i, i + 2);
44
+ const n = grams.get(g) ?? 0;
45
+ if (n > 0) {
46
+ grams.set(g, n - 1);
47
+ hit++;
48
+ }
49
+ }
50
+ return 2 * hit / (a.length + b.length - 2);
51
+ }
52
+ /** Metinden anahtar önerisi: "Adı Soyadı" → "adi_soyadi". */
53
+ function slug(s) {
54
+ return norm(s).replace(/ /g, "_").slice(0, 40);
55
+ }
56
+ function uid() {
57
+ const c = globalThis.crypto;
58
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
59
+ return Date.now().toString(36) + Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 6);
60
+ }
61
+ function nowIso() {
62
+ return (/* @__PURE__ */ new Date()).toISOString();
63
+ }
64
+ function globToRegExp(pattern) {
65
+ const esc = pattern.trim().replace(/[.+^${}()|[\]\\?]/g, "\\$&").replace(/\*/g, ".*");
66
+ return new RegExp("^" + esc + "$", "i");
67
+ }
68
+ /** Alanın sayfa desenlerinden biri adrese uyuyor mu? Boş liste her sayfaya uyar. */
69
+ function pageMatches(pages, url) {
70
+ const list = (pages ?? []).map((p) => p.trim()).filter(Boolean);
71
+ if (list.length === 0) return true;
72
+ return list.some((p) => {
73
+ try {
74
+ return globToRegExp(p).test(url);
75
+ } catch {
76
+ return false;
77
+ }
78
+ });
79
+ }
80
+ /** Bulunulan sayfa için önerilen desen: sayısal parçalar * olur. */
81
+ function suggestPagePattern(loc = location) {
82
+ const path = loc.pathname.replace(/\/\d+(?=\/|$)/g, "/*");
83
+ if (loc.hash.startsWith("#/")) {
84
+ const hashPath = loc.hash.split("?")[0].replace(/\/\d+(?=\/|$)/g, "/*");
85
+ return `${loc.origin}${path}*${hashPath}*`;
86
+ }
87
+ return `${loc.origin}${path}*`;
88
+ }
89
+ function sitePattern(loc = location) {
90
+ return `${loc.origin}/*`;
91
+ }
92
+ /** Framework'lerin her render'da ürettiği kararsız id'ler (el-id-1234-5, :r3:, v-12 ...). */
93
+ function isDynamicId(id) {
94
+ return /\d{3,}/.test(id) || /[0-9a-f]{8,}/i.test(id) || /^(el-id-|v-\d|:r|mui-|pv_id|react-|ember|ext-|ui-id-|__|input-\d|headlessui-|radix-|n-\d)/i.test(id);
95
+ }
96
+ function cssEsc(s) {
97
+ return typeof CSS !== "undefined" && CSS.escape ? CSS.escape(s) : s.replace(/["\\#.:[\]()>+~*^$|=\s]/g, "\\$&");
98
+ }
99
+ /** Alan için kısa ve mümkün olduğunca kararlı bir CSS seçici üretir. */
100
+ function cssPath(el) {
101
+ if (el.id && !isDynamicId(el.id)) return `#${cssEsc(el.id)}`;
102
+ const parts = [];
103
+ let cur = el;
104
+ while (cur && parts.length < 6) {
105
+ if (cur !== el && cur.id && !isDynamicId(cur.id)) {
106
+ parts.unshift(`#${cssEsc(cur.id)}`);
107
+ break;
108
+ }
109
+ let part = cur.tagName.toLowerCase();
110
+ const name = cur.getAttribute("name");
111
+ if (cur === el && name) part += `[name="${cssEsc(name)}"]`;
112
+ const parent = cur.parentElement;
113
+ if (parent) {
114
+ const tag = cur.tagName;
115
+ const same = Array.from(parent.children).filter((c) => c.tagName === tag);
116
+ if (same.length > 1) part += `:nth-of-type(${same.indexOf(cur) + 1})`;
117
+ }
118
+ parts.unshift(part);
119
+ if (cur.tagName === "FORM" || cur.tagName === "BODY") break;
120
+ cur = parent;
121
+ }
122
+ return parts.join(" > ");
123
+ }
124
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
125
+ // src/scanner.ts
126
+ var HOST_TAG = "optona-otofill";
127
+ var FIELD_SEL = "input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]";
128
+ var SKIP_TYPES = /* @__PURE__ */ new Set([
129
+ "hidden",
130
+ "submit",
131
+ "button",
132
+ "reset",
133
+ "image",
134
+ "file"
135
+ ]);
136
+ var FORM_ITEM_SEL = ".el-form-item, .ant-form-item, .n-form-item, .v-input, .q-field, .p-field, .p-float-label, .field, .form-group, .form-item, .form-field, .mb-3";
137
+ var FORM_ITEM_LABEL_SEL = "label, .el-form-item__label, .ant-form-item-label, .n-form-item-label, .v-label, .q-field__label, legend";
138
+ var tag = (el) => el.tagName.toLowerCase();
139
+ function kindOf(el) {
140
+ const t = tag(el);
141
+ if (t === "textarea") return "textarea";
142
+ if (t === "select") return "select";
143
+ if (t === "input") {
144
+ if (el.closest(".el-select, .el-cascader")) return "select";
145
+ if (el.closest(".el-date-editor")) return "date";
146
+ const ty = (el.getAttribute("type") ?? "text").toLowerCase();
147
+ if (ty === "checkbox") return "checkbox";
148
+ if (ty === "radio") return "radio";
149
+ if ([
150
+ "date",
151
+ "datetime-local",
152
+ "month",
153
+ "time",
154
+ "week"
155
+ ].includes(ty)) return "date";
156
+ return "text";
157
+ }
158
+ if (el.isContentEditable) return "contenteditable";
159
+ return "other";
160
+ }
161
+ function isFieldElement(el) {
162
+ if (!el || !el.matches?.(FIELD_SEL)) return false;
163
+ if (tag(el) === "input" && SKIP_TYPES.has((el.getAttribute("type") ?? "text").toLowerCase())) return false;
164
+ return true;
165
+ }
166
+ /** Tıklanan düğümden ilgili alanı bulur (label'a tıklandıysa bağlı input). */
167
+ function fieldFromTarget(target) {
168
+ if (!target) return null;
169
+ if (isFieldElement(target)) return target;
170
+ const label = target.closest("label");
171
+ if (label?.control && isFieldElement(label.control)) return label.control;
172
+ const inner = target.closest(FIELD_SEL);
173
+ if (inner && isFieldElement(inner)) return inner;
174
+ const f = target.closest(".el-select, .el-input, .el-date-editor, .p-dropdown, .v-field, .ant-select, .n-input, .q-field")?.querySelector(FIELD_SEL);
175
+ return f && isFieldElement(f) ? f : null;
176
+ }
177
+ function boxVisible(el) {
178
+ if (!el.getClientRects().length) return false;
179
+ const s = getComputedStyle(el);
180
+ return s.visibility !== "hidden" && s.display !== "none";
181
+ }
182
+ function isVisible(el) {
183
+ const k = kindOf(el);
184
+ if (k === "checkbox" || k === "radio") {
185
+ if (boxVisible(el)) return true;
186
+ const lbl = el.closest("label") ?? (el.id ? el.getRootNode() : null)?.querySelector?.(`label[for="${cssEsc(el.id)}"]`);
187
+ return !!(lbl && boxVisible(lbl)) || !!(el.parentElement && boxVisible(el.parentElement));
188
+ }
189
+ return boxVisible(el);
190
+ }
191
+ function clean(s) {
192
+ return (s ?? "").replace(/\s+/g, " ").replace(/^[*\s]+|[*:\s]+$/g, "").trim().slice(0, 80);
193
+ }
194
+ function textWithout(container, el) {
195
+ let s = "";
196
+ const w = container.ownerDocument.createTreeWalker(container, NodeFilter.SHOW_TEXT);
197
+ let n;
198
+ while (n = w.nextNode()) {
199
+ const p = n.parentElement;
200
+ if (!p || el.contains(n) || p.closest("select, option, textarea, script, style, button")) continue;
201
+ s += " " + n.textContent;
202
+ }
203
+ return clean(s);
204
+ }
205
+ function byId(el, id) {
206
+ return el.getRootNode().getElementById?.(id) ?? el.ownerDocument.getElementById(id);
207
+ }
208
+ /** Alanın yakınındaki, ona ait olması muhtemel metin (tablo düzeni, etiketsiz div'ler). */
209
+ function nearbyText(el) {
210
+ let cur = el;
211
+ for (let depth = 0; cur && depth < 4; depth++) {
212
+ let prev = cur.previousSibling;
213
+ while (prev) {
214
+ if (prev.nodeType === Node.TEXT_NODE) {
215
+ const t = clean(prev.textContent);
216
+ if (t) return t;
217
+ } else if (prev.nodeType === Node.ELEMENT_NODE) {
218
+ const e = prev;
219
+ if (e.matches(FIELD_SEL) || e.querySelector(FIELD_SEL)) return "";
220
+ const t = clean(e.textContent);
221
+ if (t) return t;
222
+ }
223
+ prev = prev.previousSibling;
224
+ }
225
+ cur = cur.parentElement;
226
+ if (!cur || cur.tagName === "FORM" || cur.tagName === "BODY") break;
227
+ }
228
+ return "";
229
+ }
230
+ /** Alanın etiketini bulur: aria-labelledby, label[for], saran label, aria-label, form-item etiketi, yakın metin. */
231
+ function labelOf(el) {
232
+ const lb = el.getAttribute("aria-labelledby");
233
+ if (lb) {
234
+ const t = clean(lb.split(/\s+/).map((i) => byId(el, i)?.textContent ?? "").join(" "));
235
+ if (t) return t;
236
+ }
237
+ if (el.id) {
238
+ const l = el.getRootNode().querySelector?.(`label[for="${cssEsc(el.id)}"]`);
239
+ if (l) {
240
+ const t = textWithout(l, el);
241
+ if (t) return t;
242
+ }
243
+ }
244
+ const wrap = el.closest("label");
245
+ if (wrap) {
246
+ const t = textWithout(wrap, el);
247
+ if (t) return t;
248
+ }
249
+ const al = clean(el.getAttribute("aria-label"));
250
+ if (al) return al;
251
+ const item = el.closest(FORM_ITEM_SEL);
252
+ if (item) {
253
+ const l = item.querySelector(FORM_ITEM_LABEL_SEL);
254
+ if (l && !l.contains(el)) {
255
+ const t = textWithout(l, el);
256
+ if (t) return t;
257
+ }
258
+ }
259
+ return nearbyText(el);
260
+ }
261
+ /** Aynı gruptaki radio'lar (aynı name, aynı form). */
262
+ function radioGroup(el) {
263
+ const name = el.getAttribute("name");
264
+ if (!name) return [el];
265
+ const scope = el.closest("form") ?? el.getRootNode();
266
+ return Array.from(scope.querySelectorAll(`input[type="radio"][name="${cssEsc(name)}"]`));
267
+ }
268
+ /** Tek bir radio/checkbox seçeneğinin kendi etiketi ("Kadın", "Erkek"). */
269
+ function optionLabel(el) {
270
+ if (el.id) {
271
+ const l = el.getRootNode().querySelector?.(`label[for="${cssEsc(el.id)}"]`);
272
+ if (l) return textWithout(l, el);
273
+ }
274
+ const wrap = el.closest("label");
275
+ if (wrap) return textWithout(wrap, el);
276
+ let n = el.nextSibling;
277
+ while (n && n.nodeType === Node.TEXT_NODE && !clean(n.textContent)) n = n.nextSibling;
278
+ return clean(n?.textContent);
279
+ }
280
+ function radioGroupLabel(el) {
281
+ const group = radioGroup(el);
282
+ const legend = el.closest("fieldset")?.querySelector("legend");
283
+ if (legend) return clean(legend.textContent);
284
+ const rg = el.closest("[role=\"radiogroup\"]");
285
+ if (rg) {
286
+ const t = clean(rg.getAttribute("aria-label")) || (rg.getAttribute("aria-labelledby") ? clean(byId(el, rg.getAttribute("aria-labelledby"))?.textContent) : "");
287
+ if (t) return t;
288
+ }
289
+ const item = el.closest(FORM_ITEM_SEL);
290
+ if (item) {
291
+ const l = Array.from(item.querySelectorAll(FORM_ITEM_LABEL_SEL)).find((x) => !group.some((r) => x.contains(r) || r.id && x.getAttribute("for") === r.id));
292
+ if (l) return clean(l.textContent);
293
+ }
294
+ let box = el.parentElement;
295
+ while (box && !group.every((r) => box.contains(r))) box = box.parentElement;
296
+ return box ? nearbyText(box) : "";
297
+ }
298
+ /** name'i kararsız radio grubu için: grubu saran kapsayıcının yolu + içindeki ilk radio. */
299
+ function radioCss(el) {
300
+ const group = radioGroup(el);
301
+ let box = el.parentElement;
302
+ while (box && !group.every((r) => box.contains(r))) box = box.parentElement;
303
+ return box ? `${cssPath(box)} input[type="radio"]` : cssPath(el);
304
+ }
305
+ function formKeyOf(el) {
306
+ const f = el.closest("form");
307
+ if (!f) return void 0;
308
+ return (f.id && !isDynamicId(f.id) ? f.id : "") || f.getAttribute("name") || void 0;
309
+ }
310
+ function fingerprint(el, index = 0) {
311
+ const kind = kindOf(el);
312
+ const rawName = el.getAttribute("name") || void 0;
313
+ const name = rawName && !isDynamicId(rawName) ? rawName : void 0;
314
+ return {
315
+ el,
316
+ kind,
317
+ tag: tag(el),
318
+ type: el.getAttribute("type")?.toLowerCase() || void 0,
319
+ otofill: el.getAttribute("data-otofill") || void 0,
320
+ id: el.id && !isDynamicId(el.id) ? el.id : void 0,
321
+ name,
322
+ label: (kind === "radio" ? radioGroupLabel(el) : labelOf(el)) || void 0,
323
+ placeholder: el.getAttribute("placeholder") || void 0,
324
+ ariaLabel: el.getAttribute("aria-label") || void 0,
325
+ css: kind === "radio" ? name ? `input[type="radio"][name="${cssEsc(name)}"]` : radioCss(el) : cssPath(el),
326
+ formKey: formKeyOf(el),
327
+ index
328
+ };
329
+ }
330
+ function collect(root, out) {
331
+ root.querySelectorAll(FIELD_SEL).forEach((el) => {
332
+ if (isFieldElement(el) && !el.disabled && isVisible(el)) out.push(el);
333
+ });
334
+ root.querySelectorAll("*").forEach((el) => {
335
+ if (el.tagName.toLowerCase() === "optona-otofill") return;
336
+ const sr = el.shadowRoot;
337
+ if (sr) collect(sr, out);
338
+ if (el.tagName === "IFRAME") try {
339
+ const d = el.contentDocument;
340
+ if (d) collect(d, out);
341
+ } catch {}
342
+ });
343
+ }
344
+ /** Sayfadaki görünür alanları tarar. Radio grupları tek alan sayılır (ilk seçenek temsil eder). */
345
+ function scanPage(root = document) {
346
+ const els = [];
347
+ collect(root, els);
348
+ const seenGroups = /* @__PURE__ */ new Set();
349
+ const result = [];
350
+ for (const el of els) if (kindOf(el) === "radio") {
351
+ const g = radioGroup(el);
352
+ if (seenGroups.has(g[0])) continue;
353
+ seenGroups.add(g[0]);
354
+ result.push(fingerprint(g[0], result.length));
355
+ } else result.push(fingerprint(el, result.length));
356
+ return result;
357
+ }
358
+ /** Parmak izinden saklanacak ipuçlarını üretir (el hariç). */
359
+ function hintsOf(fp) {
360
+ const { el: _el, kind: _kind, ...hints } = fp;
361
+ return hints;
362
+ }
363
+ // src/fill-utils.ts
364
+ function fire(el, type) {
365
+ el.dispatchEvent(new Event(type, { bubbles: true }));
366
+ }
367
+ function pressKey(el, key) {
368
+ const init = {
369
+ key,
370
+ code: key,
371
+ bubbles: true,
372
+ cancelable: true
373
+ };
374
+ el.dispatchEvent(new KeyboardEvent("keydown", init));
375
+ el.dispatchEvent(new KeyboardEvent("keyup", init));
376
+ }
377
+ /**
378
+ * Vue v-model (ve React) değeri `input` olayıyla okur; `el.value = x` tek başına yetmez.
379
+ * Değeri prototipteki native setter ile yazıp olayları tetikliyoruz.
380
+ */
381
+ function setNativeValue(el, value) {
382
+ let proto = Object.getPrototypeOf(el);
383
+ let desc;
384
+ while (proto && !(desc = Object.getOwnPropertyDescriptor(proto, "value"))) proto = Object.getPrototypeOf(proto);
385
+ if (desc?.set) desc.set.call(el, value);
386
+ else el.value = value;
387
+ }
388
+ function isShown(el) {
389
+ if (!el || !el.isConnected || !el.getClientRects().length) return false;
390
+ const s = getComputedStyle(el);
391
+ return s.visibility !== "hidden" && s.display !== "none";
392
+ }
393
+ /** Koşul sağlanana kadar bekler; zaman aşımında null döner. */
394
+ async function waitFor(fn, timeout = 800, step = 25) {
395
+ const end = Date.now() + timeout;
396
+ for (;;) {
397
+ const v = fn();
398
+ if (v) return v;
399
+ if (Date.now() > end) return null;
400
+ await sleep(step);
401
+ }
402
+ }
403
+ /** Seçenekler arasından metne göre en iyi eşleşmeyi bulur: tam, baş, benzer. */
404
+ function pickByText(items, value, text = (e) => e.textContent ?? "") {
405
+ const n = norm(value);
406
+ if (!n) return void 0;
407
+ return items.find((i) => norm(text(i)) === n) ?? items.find((i) => norm(text(i)).startsWith(n)) ?? items.find((i) => similarity(text(i), value) >= .85);
408
+ }
409
+ /** Çoklu değer ayırıcı: "Spor | Müzik" */
410
+ var splitMulti = (v) => v.split("|").map((s) => s.trim()).filter(Boolean);
411
+ /** Bir tarihi farklı yazım biçimlerinde dener: girilen, ISO, 31.12.1990, 31/12/1990, 12/31/1990, 1990/12/31. */
412
+ function dateCandidates(value) {
413
+ const v = value.trim();
414
+ let y = "", m = "", d = "", rest = "";
415
+ let r = v.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})(.*)$/);
416
+ if (r) [, d, m, y, rest] = r;
417
+ else if (r = v.match(/^(\d{4})[./-](\d{1,2})[./-](\d{1,2})(.*)$/)) [, y, m, d, rest] = r;
418
+ if (!y) return [v];
419
+ m = m.padStart(2, "0");
420
+ d = d.padStart(2, "0");
421
+ rest = rest.replace(/^T/, " ");
422
+ return [.../* @__PURE__ */ new Set([
423
+ `${y}-${m}-${d}${rest}`,
424
+ v,
425
+ `${d}.${m}.${y}${rest}`,
426
+ `${d}/${m}/${y}${rest}`,
427
+ `${m}/${d}/${y}${rest}`,
428
+ `${y}/${m}/${d}${rest}`
429
+ ])];
430
+ }
431
+ /**
432
+ * Bileşen yazılan değeri aynen kabul etti mi? Gösterilen değerin sayıları yazılanla aynı sırada başlamalı
433
+ * ("09:15" → "09:15:00" olur). Sıra farklıysa bileşen başka biçimle okuyup gün/ayı karıştırmış olabilir.
434
+ */
435
+ function sameNumbers(shown, typed) {
436
+ const nums = (s) => (s.match(/\d+/g) ?? []).map(Number);
437
+ const a = nums(shown);
438
+ const b = nums(typed);
439
+ return b.length > 0 && b.every((x, i) => a[i] === x);
440
+ }
441
+ // src/ui/element-plus.ts
442
+ var isInput = (el) => el.tagName === "INPUT";
443
+ function selectParts(el) {
444
+ const root = el.closest(".el-select");
445
+ const input = el;
446
+ const wrapper = root.querySelector(".el-select__wrapper") ?? root;
447
+ const listbox = () => {
448
+ const id = input.getAttribute("aria-controls");
449
+ return id ? el.ownerDocument.getElementById(id) : null;
450
+ };
451
+ const isOpen = () => input.getAttribute("aria-expanded") === "true" && isShown(listbox());
452
+ const items = () => Array.from(listbox()?.querySelectorAll(".el-select-dropdown__item") ?? []).filter((i) => isShown(i) && !i.classList.contains("is-disabled"));
453
+ return {
454
+ root,
455
+ input,
456
+ wrapper,
457
+ listbox,
458
+ isOpen,
459
+ items
460
+ };
461
+ }
462
+ async function closeSelect(p) {
463
+ if (!p.isOpen()) return;
464
+ pressKey(p.input, "Escape");
465
+ if (await waitFor(() => !p.isOpen(), 300)) return;
466
+ p.wrapper.click();
467
+ await waitFor(() => !p.isOpen(), 300);
468
+ }
469
+ var epSelect = {
470
+ name: "element-plus-select",
471
+ detect: (el) => isInput(el) && !!el.closest(".el-select"),
472
+ async fill(el, value) {
473
+ const p = selectParts(el);
474
+ const wanted = splitMulti(value);
475
+ if (!wanted.length) return true;
476
+ if (!p.isOpen()) p.wrapper.click();
477
+ if (!await waitFor(() => p.isOpen(), 800)) return false;
478
+ const multiple = p.listbox()?.getAttribute("aria-multiselectable") === "true" || p.root.querySelector(".el-select__selection .el-tag") != null || wanted.length > 1;
479
+ const filterable = !p.input.readOnly;
480
+ if (multiple) {
481
+ for (const it of p.items().filter((i) => i.classList.contains("is-selected"))) if (!wanted.some((w) => pickByText([it], w))) {
482
+ it.click();
483
+ await sleep(30);
484
+ }
485
+ }
486
+ let ok = true;
487
+ for (const w of wanted) {
488
+ if (filterable) {
489
+ setNativeValue(p.input, w);
490
+ fire(p.input, "input");
491
+ await sleep(120);
492
+ }
493
+ const item = await waitFor(() => pickByText(p.items(), w), 500);
494
+ if (!item) {
495
+ ok = false;
496
+ continue;
497
+ }
498
+ if (multiple && item.classList.contains("is-selected")) continue;
499
+ item.click();
500
+ await sleep(40);
501
+ if (!multiple) break;
502
+ if (!p.isOpen()) p.wrapper.click();
503
+ }
504
+ await closeSelect(p);
505
+ return ok;
506
+ },
507
+ read(el) {
508
+ const root = el.closest(".el-select");
509
+ const tags = Array.from(root.querySelectorAll(".el-tag .el-select__tags-text")).map((t) => t.textContent?.trim() ?? "");
510
+ if (tags.length) return tags.join(" | ");
511
+ return root.querySelector(".el-select__placeholder:not(.is-transparent)")?.textContent?.trim() ?? "";
512
+ }
513
+ };
514
+ function cascaderPanel() {
515
+ const panels = Array.from(document.querySelectorAll(".el-popper .el-cascader-panel")).filter(isShown);
516
+ return panels[panels.length - 1] ?? null;
517
+ }
518
+ var elementPlusDrivers = [
519
+ epSelect,
520
+ {
521
+ name: "element-plus-cascader",
522
+ detect: (el) => isInput(el) && !!el.closest(".el-cascader"),
523
+ async fill(el, value) {
524
+ const root = el.closest(".el-cascader");
525
+ const path = value.split(/\s*[/>]\s*/).map((s) => s.trim()).filter(Boolean);
526
+ if (!path.length) return true;
527
+ let panel = cascaderPanel();
528
+ if (!panel) {
529
+ root.click();
530
+ panel = await waitFor(cascaderPanel, 800);
531
+ if (!panel) return false;
532
+ }
533
+ for (let level = 0; level < path.length; level++) {
534
+ const node = await waitFor(() => {
535
+ const menu = panel.querySelectorAll(".el-cascader-menu")[level];
536
+ return pickByText(Array.from(menu?.querySelectorAll(".el-cascader-node:not(.is-disabled)") ?? []), path[level], (n) => n.querySelector(".el-cascader-node__label")?.textContent ?? n.textContent ?? "");
537
+ }, 600);
538
+ if (!node) {
539
+ pressKey(el, "Escape");
540
+ document.body.click();
541
+ return false;
542
+ }
543
+ node.click();
544
+ await sleep(60);
545
+ }
546
+ if (cascaderPanel()) {
547
+ pressKey(el, "Escape");
548
+ await sleep(50);
549
+ if (cascaderPanel()) document.body.click();
550
+ }
551
+ return true;
552
+ },
553
+ read: (el) => el.value
554
+ },
555
+ {
556
+ name: "element-plus-date",
557
+ detect: (el) => isInput(el) && !!el.closest(".el-date-editor"),
558
+ async fill(el, value) {
559
+ const input = el;
560
+ for (const c of dateCandidates(value)) {
561
+ input.focus({ preventScroll: true });
562
+ setNativeValue(input, c);
563
+ fire(input, "input");
564
+ fire(input, "change");
565
+ await sleep(40);
566
+ pressKey(input, "Escape");
567
+ input.blur();
568
+ await sleep(40);
569
+ if (input.value && sameNumbers(input.value, c)) return true;
570
+ }
571
+ return false;
572
+ },
573
+ read: (el) => el.value
574
+ }
575
+ ];
576
+ // src/drivers.ts
577
+ var TRUE_WORDS = /* @__PURE__ */ new Set([
578
+ "1",
579
+ "true",
580
+ "evet",
581
+ "e",
582
+ "yes",
583
+ "y",
584
+ "on",
585
+ "x",
586
+ "secili",
587
+ "checked"
588
+ ]);
589
+ var truthy = (v) => TRUE_WORDS.has(norm(v)) || v.trim() === "✓";
590
+ /** "31.12.1990" / "31/12/1990" → "1990-12-31" (date input'u ISO ister). */
591
+ function toIsoDate(v, type) {
592
+ const m = v.trim().match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})(?:[ T](\d{1,2}):(\d{2}))?$/);
593
+ if (!m) return v;
594
+ const date = `${m[3]}-${m[2].padStart(2, "0")}-${m[1].padStart(2, "0")}`;
595
+ if (type === "datetime-local") return `${date}T${(m[4] ?? "00").padStart(2, "0")}:${m[5] ?? "00"}`;
596
+ if (type === "month") return date.slice(0, 7);
597
+ return date;
598
+ }
599
+ var textDriver = {
600
+ name: "native-text",
601
+ detect: (el) => [
602
+ "text",
603
+ "textarea",
604
+ "date"
605
+ ].includes(kindOf(el)),
606
+ fill(el, value) {
607
+ const input = el;
608
+ const type = (input.getAttribute("type") ?? "text").toLowerCase();
609
+ const v = kindOf(el) === "date" ? toIsoDate(value, type) : value;
610
+ input.focus({ preventScroll: true });
611
+ setNativeValue(input, v);
612
+ fire(input, "input");
613
+ fire(input, "change");
614
+ input.blur();
615
+ return kindOf(el) !== "date" || input.value !== "" || v === "";
616
+ },
617
+ read: (el) => el.value
618
+ };
619
+ function findOption(sel, value) {
620
+ const opts = Array.from(sel.options);
621
+ const n = norm(value);
622
+ return opts.find((o) => o.value === value) ?? opts.find((o) => norm(o.text) === n) ?? opts.find((o) => n && norm(o.text).startsWith(n)) ?? opts.find((o) => similarity(o.text, value) >= .85);
623
+ }
624
+ var selectDriver = {
625
+ name: "native-select",
626
+ detect: (el) => el.tagName === "SELECT",
627
+ fill(el, value) {
628
+ const sel = el;
629
+ const opt = findOption(sel, value);
630
+ if (!opt) return false;
631
+ setNativeValue(sel, opt.value);
632
+ fire(sel, "input");
633
+ fire(sel, "change");
634
+ return true;
635
+ },
636
+ read: (el) => el.selectedOptions[0]?.text.trim()
637
+ };
638
+ var checkboxDriver = {
639
+ name: "native-checkbox",
640
+ detect: (el) => kindOf(el) === "checkbox",
641
+ fill(el, value) {
642
+ const cb = el;
643
+ if (cb.checked !== truthy(value)) cb.click();
644
+ return true;
645
+ },
646
+ read: (el) => el.checked ? "true" : "false"
647
+ };
648
+ var radioDriver = {
649
+ name: "native-radio",
650
+ detect: (el) => kindOf(el) === "radio",
651
+ fill(el, value) {
652
+ const group = radioGroup(el);
653
+ const n = norm(value);
654
+ const pick = group.find((r) => r.value === value) ?? group.find((r) => norm(optionLabel(r)) === n) ?? group.find((r) => norm(r.value) === n) ?? group.find((r) => similarity(optionLabel(r), value) >= .8);
655
+ if (!pick) return false;
656
+ if (!pick.checked) pick.click();
657
+ return true;
658
+ },
659
+ read(el) {
660
+ const on = radioGroup(el).find((r) => r.checked);
661
+ return on ? optionLabel(on) || on.value : "";
662
+ }
663
+ };
664
+ var editableDriver = {
665
+ name: "contenteditable",
666
+ detect: (el) => kindOf(el) === "contenteditable",
667
+ fill(el, value) {
668
+ const h = el;
669
+ h.focus({ preventScroll: true });
670
+ h.textContent = value;
671
+ h.dispatchEvent(new InputEvent("input", {
672
+ bubbles: true,
673
+ inputType: "insertText",
674
+ data: value
675
+ }));
676
+ h.blur();
677
+ return true;
678
+ },
679
+ read: (el) => el.textContent ?? ""
680
+ };
681
+ var builtIn = [
682
+ ...elementPlusDrivers,
683
+ checkboxDriver,
684
+ radioDriver,
685
+ selectDriver,
686
+ editableDriver,
687
+ textDriver
688
+ ];
689
+ var custom = [];
690
+ /** Özel sürücü kaydeder; yerleşik sürücülerden önce denenir. */
691
+ function registerDriver(d) {
692
+ const i = custom.findIndex((x) => x.name === d.name);
693
+ if (i >= 0) custom[i] = d;
694
+ else custom.unshift(d);
695
+ }
696
+ function driverFor(el) {
697
+ return custom.find((d) => d.detect(el)) ?? builtIn.find((d) => d.detect(el));
698
+ }
699
+ async function fillElement(el, value) {
700
+ const d = driverFor(el);
701
+ if (!d) return false;
702
+ return await d.fill(el, value);
703
+ }
704
+ function readElement(el) {
705
+ return driverFor(el)?.read?.(el);
706
+ }
707
+ // src/matcher.ts
708
+ /** Sinyal ağırlıkları. data-otofill eşleşmesi kesindir. */
709
+ var WEIGHTS = {
710
+ otofill: 100,
711
+ id: 50,
712
+ name: 40,
713
+ labelExact: 35,
714
+ css: 30,
715
+ labelFuzzy: 25,
716
+ placeholder: 15,
717
+ ariaLabel: 15,
718
+ type: 5,
719
+ index: 5,
720
+ mismatch: -10,
721
+ wrongTag: -25,
722
+ wrongKind: -40
723
+ };
724
+ /** Bu puanın altındaki eşleşmeler kullanılmaz: yanlış alanı doldurmaktansa boş bırakmak iyidir. */
725
+ var THRESHOLD = 30;
726
+ function score(def, fp) {
727
+ const h = def.match;
728
+ const W = WEIGHTS;
729
+ if (h.otofill && fp.otofill) return h.otofill === fp.otofill ? W.otofill : 0;
730
+ let s = 0;
731
+ if (h.id && fp.id) s += h.id === fp.id ? W.id : W.mismatch;
732
+ if (h.name && fp.name) s += h.name === fp.name ? W.name : W.mismatch;
733
+ if (h.css) try {
734
+ if (fp.el.matches(h.css)) s += W.css;
735
+ } catch {}
736
+ if (h.label && fp.label) {
737
+ const a = norm(h.label);
738
+ const b = norm(fp.label);
739
+ if (a === b) s += W.labelExact;
740
+ else {
741
+ const sim = similarity(a, b);
742
+ if (sim >= .6) s += Math.round(W.labelFuzzy * sim);
743
+ }
744
+ }
745
+ if (h.placeholder && fp.placeholder && norm(h.placeholder) === norm(fp.placeholder)) s += W.placeholder;
746
+ if (h.ariaLabel && fp.ariaLabel && norm(h.ariaLabel) === norm(fp.ariaLabel)) s += W.ariaLabel;
747
+ if (h.type && fp.type && h.type === fp.type) s += W.type;
748
+ if (h.index != null && h.index === fp.index && h.formKey === fp.formKey) s += W.index;
749
+ if (h.tag && fp.tag && h.tag !== fp.tag) s += W.wrongTag;
750
+ if (def.kind && def.kind !== fp.kind) s += W.wrongKind;
751
+ return s;
752
+ }
753
+ /** Tanımları sayfadaki alanlarla eşler; en yüksek puandan başlayarak her alan en fazla bir kez kullanılır. */
754
+ function matchFields(allDefs, fps, url = location.href) {
755
+ const defs = allDefs.filter((d) => pageMatches(d.pages, url));
756
+ const pairs = [];
757
+ for (const def of defs) for (const fp of fps) {
758
+ const s = score(def, fp);
759
+ if (s >= 30) pairs.push({
760
+ def,
761
+ fp,
762
+ score: s
763
+ });
764
+ }
765
+ pairs.sort((a, b) => b.score - a.score);
766
+ const usedDef = /* @__PURE__ */ new Set();
767
+ const usedFp = /* @__PURE__ */ new Set();
768
+ const matches = [];
769
+ for (const p of pairs) {
770
+ if (usedDef.has(p.def.id) || usedFp.has(p.fp)) continue;
771
+ usedDef.add(p.def.id);
772
+ usedFp.add(p.fp);
773
+ matches.push(p);
774
+ }
775
+ matches.sort((a, b) => (a.fp.index ?? 0) - (b.fp.index ?? 0));
776
+ return {
777
+ defs,
778
+ matches,
779
+ missing: defs.filter((d) => !usedDef.has(d.id)),
780
+ free: fps.filter((f) => !usedFp.has(f))
781
+ };
782
+ }
783
+ // src/store.ts
784
+ var store_exports = /* @__PURE__ */ __exportAll({
785
+ STATE_VERSION: () => 1,
786
+ STORAGE_KEY: () => STORAGE_KEY,
787
+ addRow: () => addRow,
788
+ clearAll: () => clearAll,
789
+ createDataset: () => createDataset,
790
+ datasetKeys: () => datasetKeys,
791
+ load: () => load,
792
+ migrate: () => migrate,
793
+ removeDataset: () => removeDataset,
794
+ removeField: () => removeField,
795
+ removeRow: () => removeRow,
796
+ save: () => save,
797
+ subscribe: () => subscribe,
798
+ update: () => update,
799
+ upsertDataset: () => upsertDataset,
800
+ upsertField: () => upsertField
801
+ });
802
+ /**
803
+ * Veriler bulunulan sitenin (origin) localStorage'ında durur; kütüphane hiçbir yere istek atmaz.
804
+ * Kod güncellense de veri silinmez. Biçim değişirse migrate() eski veriyi yükseltir.
805
+ */
806
+ var STORAGE_KEY = "optona-otofill";
807
+ var listeners = /* @__PURE__ */ new Set();
808
+ var memory = null;
809
+ function emptyState() {
810
+ return {
811
+ v: 1,
812
+ fields: [],
813
+ datasets: [],
814
+ prefs: {
815
+ cursor: {},
816
+ closeAfterFill: true
817
+ }
818
+ };
819
+ }
820
+ function readRaw() {
821
+ try {
822
+ return localStorage.getItem(STORAGE_KEY);
823
+ } catch {
824
+ return memory;
825
+ }
826
+ }
827
+ function writeRaw(s) {
828
+ try {
829
+ localStorage.setItem(STORAGE_KEY, s);
830
+ } catch {
831
+ memory = s;
832
+ }
833
+ }
834
+ /** Eski sürümlerin verisini güncel biçime taşır. Yeni biçim eklendiğinde buraya adım eklenir. */
835
+ function migrate(raw) {
836
+ const base = emptyState();
837
+ if (!raw || typeof raw !== "object") return base;
838
+ const r = raw;
839
+ return {
840
+ v: 1,
841
+ fields: Array.isArray(r.fields) ? r.fields : [],
842
+ datasets: Array.isArray(r.datasets) ? r.datasets : [],
843
+ prefs: {
844
+ ...base.prefs,
845
+ ...r.prefs ?? {},
846
+ cursor: { ...r.prefs?.cursor ?? {} }
847
+ }
848
+ };
849
+ }
850
+ function load() {
851
+ const raw = readRaw();
852
+ if (!raw) return emptyState();
853
+ try {
854
+ return migrate(JSON.parse(raw));
855
+ } catch {
856
+ return emptyState();
857
+ }
858
+ }
859
+ function save(s) {
860
+ writeRaw(JSON.stringify(s));
861
+ listeners.forEach((l) => l(s));
862
+ }
863
+ /** Durumu okuyup değiştirir ve kaydeder. */
864
+ function update(fn) {
865
+ const s = load();
866
+ fn(s);
867
+ save(s);
868
+ return s;
869
+ }
870
+ function subscribe(fn) {
871
+ listeners.add(fn);
872
+ return () => listeners.delete(fn);
873
+ }
874
+ if (typeof window !== "undefined") window.addEventListener("storage", (e) => {
875
+ if (e.key === "optona-otofill") {
876
+ const s = load();
877
+ listeners.forEach((l) => l(s));
878
+ }
879
+ });
880
+ function clearAll() {
881
+ save(emptyState());
882
+ }
883
+ function upsertField(def) {
884
+ const full = {
885
+ ...def,
886
+ id: def.id ?? uid(),
887
+ updatedAt: nowIso()
888
+ };
889
+ update((s) => {
890
+ const i = s.fields.findIndex((f) => f.id === full.id);
891
+ if (i >= 0) s.fields[i] = full;
892
+ else s.fields.push(full);
893
+ });
894
+ return full;
895
+ }
896
+ function removeField(id) {
897
+ update((s) => {
898
+ s.fields = s.fields.filter((f) => f.id !== id);
899
+ });
900
+ }
901
+ function createDataset(name, rows = []) {
902
+ const ds = {
903
+ id: uid(),
904
+ name,
905
+ rows,
906
+ updatedAt: nowIso()
907
+ };
908
+ update((s) => {
909
+ s.datasets.push(ds);
910
+ });
911
+ return ds;
912
+ }
913
+ function upsertDataset(ds) {
914
+ update((s) => {
915
+ const full = {
916
+ ...ds,
917
+ updatedAt: nowIso()
918
+ };
919
+ const i = s.datasets.findIndex((d) => d.id === ds.id);
920
+ if (i >= 0) s.datasets[i] = full;
921
+ else s.datasets.push(full);
922
+ });
923
+ }
924
+ function removeDataset(id) {
925
+ update((s) => {
926
+ s.datasets = s.datasets.filter((d) => d.id !== id);
927
+ delete s.prefs.cursor[id];
928
+ });
929
+ }
930
+ function addRow(datasetId, row) {
931
+ const full = {
932
+ ...row,
933
+ _id: row._id ?? uid()
934
+ };
935
+ update((s) => {
936
+ const ds = s.datasets.find((d) => d.id === datasetId);
937
+ if (ds) {
938
+ ds.rows.push(full);
939
+ ds.updatedAt = nowIso();
940
+ }
941
+ });
942
+ return full;
943
+ }
944
+ function removeRow(datasetId, rowId) {
945
+ update((s) => {
946
+ const ds = s.datasets.find((d) => d.id === datasetId);
947
+ if (ds) ds.rows = ds.rows.filter((r) => r._id !== rowId);
948
+ });
949
+ }
950
+ /** Veri setindeki tüm anahtarlar (sütunlar), _id/_label hariç. */
951
+ function datasetKeys(ds) {
952
+ const keys = /* @__PURE__ */ new Set();
953
+ ds.rows.forEach((r) => Object.keys(r).forEach((k) => !k.startsWith("_") && keys.add(k)));
954
+ return [...keys];
955
+ }
956
+ // src/engine.ts
957
+ /** Bulunulan sayfayı tarar ve kayıtlı tanımlarla eşler. */
958
+ function analyze(defs = load().fields, url = location.href) {
959
+ return matchFields(defs, scanPage(document), url);
960
+ }
961
+ /**
962
+ * Satırı sayfaya yazar. Bağımlı alanlar (il → ilçe gibi) sonradan yüklenebildiği için
963
+ * yazılamayan ya da bulunamayan alanlar kısa aralıklarla yeniden denenir.
964
+ */
965
+ async function fillRow(row, opts = {}) {
966
+ const retries = opts.retries ?? 3;
967
+ const delay = opts.delay ?? 300;
968
+ const done = /* @__PURE__ */ new Set();
969
+ const failed = /* @__PURE__ */ new Set();
970
+ let pending = analyze();
971
+ const noValue = /* @__PURE__ */ new Set();
972
+ for (let round = 0; round <= retries; round++) {
973
+ failed.clear();
974
+ for (const m of pending.matches) {
975
+ const key = m.def.key;
976
+ if (done.has(m.def.id)) continue;
977
+ const value = row[key];
978
+ if (value === void 0) {
979
+ noValue.add(key);
980
+ continue;
981
+ }
982
+ let ok = false;
983
+ try {
984
+ ok = await fillElement(m.fp.el, value);
985
+ } catch (e) {
986
+ console.warn("[otofill]", key, e);
987
+ }
988
+ if (ok) {
989
+ done.add(m.def.id);
990
+ opts.onFilled?.(m.fp.el);
991
+ } else failed.add(key);
992
+ }
993
+ const missingWithValue = pending.missing.filter((d) => row[d.key] !== void 0 && !done.has(d.id));
994
+ if (failed.size === 0 && missingWithValue.length === 0) break;
995
+ if (round === retries) break;
996
+ await sleep(delay);
997
+ pending = analyze();
998
+ }
999
+ const final = pending;
1000
+ const filledDefs = final.defs.filter((d) => done.has(d.id));
1001
+ return {
1002
+ filled: filledDefs.map((d) => d.key),
1003
+ notFound: final.missing.filter((d) => !done.has(d.id) && row[d.key] !== void 0).map((d) => d.key),
1004
+ failed: [...failed],
1005
+ noValue: [...noValue].filter((k) => !filledDefs.some((d) => d.key === k))
1006
+ };
1007
+ }
1008
+ /** Sayfadaki tanımlı alanların o anki değerlerini satır olarak okur. */
1009
+ function readRow(result = analyze()) {
1010
+ const row = {};
1011
+ for (const m of result.matches) {
1012
+ const v = readElement(m.fp.el);
1013
+ if (v !== void 0) row[m.def.key] = v;
1014
+ }
1015
+ return row;
1016
+ }
1017
+ /** Sayfadaki anahtarlarla en çok örtüşen veri setleri önce. */
1018
+ function rankDatasets(datasets, pageKeys) {
1019
+ const keys = new Set(pageKeys);
1020
+ return datasets.map((ds) => {
1021
+ const dsKeys = /* @__PURE__ */ new Set();
1022
+ ds.rows.forEach((r) => Object.keys(r).forEach((k) => dsKeys.add(k)));
1023
+ return {
1024
+ ds,
1025
+ overlap: [...keys].filter((k) => dsKeys.has(k)).length
1026
+ };
1027
+ }).sort((a, b) => b.overlap - a.overlap || a.ds.name.localeCompare(b.ds.name, "tr"));
1028
+ }
1029
+ function rowTitle(row, keys = []) {
1030
+ if (row._label) return row._label;
1031
+ return (keys.length ? keys : Object.keys(row).filter((k) => !k.startsWith("_"))).map((k) => row[k]).filter((v) => v && v !== "true" && v !== "false").slice(0, 2).join(" · ") || "(adsız satır)";
1032
+ }
1033
+ // src/types.ts
1034
+ var BUNDLE_FORMAT = "optona-otofill";
1035
+ var BUNDLE_VERSION = 1;
1036
+ // src/io.ts
1037
+ var io_exports = /* @__PURE__ */ __exportAll({
1038
+ ImportError: () => ImportError,
1039
+ applyBundle: () => applyBundle,
1040
+ csvToDataset: () => csvToDataset,
1041
+ datasetToCsv: () => datasetToCsv,
1042
+ download: () => download,
1043
+ exportCsv: () => exportCsv,
1044
+ exportJson: () => exportJson,
1045
+ importFile: () => importFile,
1046
+ importText: () => importText,
1047
+ makeBundle: () => makeBundle,
1048
+ parseCsv: () => parseCsv,
1049
+ summaryText: () => summaryText,
1050
+ validateBundle: () => validateBundle
1051
+ });
1052
+ function makeBundle(state = load(), opts = {
1053
+ fields: true,
1054
+ datasets: true
1055
+ }) {
1056
+ const b = {
1057
+ format: BUNDLE_FORMAT,
1058
+ version: 1,
1059
+ exportedAt: nowIso()
1060
+ };
1061
+ if (opts.fields) b.fields = state.fields;
1062
+ if (opts.datasets) b.datasets = Array.isArray(opts.datasets) ? state.datasets.filter((d) => opts.datasets.includes(d.id)) : state.datasets;
1063
+ return b;
1064
+ }
1065
+ var ImportError = class extends Error {};
1066
+ function isObj(x) {
1067
+ return !!x && typeof x === "object" && !Array.isArray(x);
1068
+ }
1069
+ /** Dosyayı doğrular, eksikleri tamamlar ve eski sürümleri günceller. Hatalıysa ImportError fırlatır. */
1070
+ function validateBundle(raw) {
1071
+ if (!isObj(raw)) throw new ImportError("Dosya bir JSON nesnesi değil.");
1072
+ if (raw.format !== "optona-otofill") throw new ImportError(`Bu bir Otofill dosyası değil (format: "${String(raw.format)}").`);
1073
+ const version = Number(raw.version);
1074
+ if (!version || version > 1) throw new ImportError(`Dosya sürümü (${String(raw.version)}) bu kütüphaneden yeni. Kütüphaneyi güncelleyin.`);
1075
+ const out = {
1076
+ format: BUNDLE_FORMAT,
1077
+ version: 1,
1078
+ exportedAt: String(raw.exportedAt ?? nowIso())
1079
+ };
1080
+ if (raw.fields !== void 0) {
1081
+ if (!Array.isArray(raw.fields)) throw new ImportError("\"fields\" bir dizi olmalı.");
1082
+ out.fields = raw.fields.map((f, i) => {
1083
+ if (!isObj(f) || typeof f.key !== "string" || !f.key.trim()) throw new ImportError(`fields[${i}]: "key" eksik.`);
1084
+ return {
1085
+ id: typeof f.id === "string" && f.id ? f.id : uid(),
1086
+ key: f.key.trim(),
1087
+ title: typeof f.title === "string" ? f.title : void 0,
1088
+ pages: Array.isArray(f.pages) ? f.pages.map(String) : [],
1089
+ kind: typeof f.kind === "string" ? f.kind : void 0,
1090
+ match: isObj(f.match) ? f.match : {},
1091
+ updatedAt: typeof f.updatedAt === "string" ? f.updatedAt : void 0
1092
+ };
1093
+ });
1094
+ }
1095
+ if (raw.datasets !== void 0) {
1096
+ if (!Array.isArray(raw.datasets)) throw new ImportError("\"datasets\" bir dizi olmalı.");
1097
+ out.datasets = raw.datasets.map((d, i) => {
1098
+ if (!isObj(d) || typeof d.name !== "string") throw new ImportError(`datasets[${i}]: "name" eksik.`);
1099
+ if (!Array.isArray(d.rows)) throw new ImportError(`datasets[${i}]: "rows" bir dizi olmalı.`);
1100
+ return {
1101
+ id: typeof d.id === "string" && d.id ? d.id : uid(),
1102
+ name: d.name,
1103
+ updatedAt: typeof d.updatedAt === "string" ? d.updatedAt : void 0,
1104
+ rows: d.rows.map((r, j) => {
1105
+ if (!isObj(r)) throw new ImportError(`datasets[${i}].rows[${j}] bir nesne değil.`);
1106
+ const row = { _id: typeof r._id === "string" && r._id ? r._id : uid() };
1107
+ for (const [k, v] of Object.entries(r)) if (k !== "_id" && v != null) row[k] = String(v);
1108
+ return row;
1109
+ })
1110
+ };
1111
+ });
1112
+ }
1113
+ if (!out.fields && !out.datasets) throw new ImportError("Dosyada ne alan tanımı ne de veri seti var.");
1114
+ return out;
1115
+ }
1116
+ /** Paketi duruma uygular (kaydetmez). */
1117
+ function applyBundle(state, b, mode) {
1118
+ const sum = {
1119
+ fieldsAdded: 0,
1120
+ fieldsUpdated: 0,
1121
+ datasetsAdded: 0,
1122
+ datasetsUpdated: 0,
1123
+ rows: 0
1124
+ };
1125
+ const fields = b.fields ?? [];
1126
+ const datasets = b.datasets ?? [];
1127
+ sum.rows = datasets.reduce((n, d) => n + d.rows.length, 0);
1128
+ if (mode === "copy") {
1129
+ fields.forEach((f) => state.fields.push({
1130
+ ...f,
1131
+ id: uid()
1132
+ }));
1133
+ datasets.forEach((d) => state.datasets.push({
1134
+ ...d,
1135
+ id: uid(),
1136
+ rows: d.rows.map((r) => ({
1137
+ ...r,
1138
+ _id: uid()
1139
+ }))
1140
+ }));
1141
+ sum.fieldsAdded = fields.length;
1142
+ sum.datasetsAdded = datasets.length;
1143
+ return sum;
1144
+ }
1145
+ if (mode === "replace") {
1146
+ if (b.fields) {
1147
+ state.fields = [...fields];
1148
+ sum.fieldsAdded = fields.length;
1149
+ }
1150
+ if (b.datasets) {
1151
+ state.datasets = [...datasets];
1152
+ sum.datasetsAdded = datasets.length;
1153
+ }
1154
+ return sum;
1155
+ }
1156
+ for (const f of fields) {
1157
+ const i = state.fields.findIndex((x) => x.id === f.id || x.key === f.key && x.pages.join("|") === f.pages.join("|"));
1158
+ if (i >= 0) {
1159
+ state.fields[i] = {
1160
+ ...f,
1161
+ id: state.fields[i].id
1162
+ };
1163
+ sum.fieldsUpdated++;
1164
+ } else {
1165
+ state.fields.push(f);
1166
+ sum.fieldsAdded++;
1167
+ }
1168
+ }
1169
+ for (const d of datasets) {
1170
+ const ex = state.datasets.find((x) => x.id === d.id) ?? state.datasets.find((x) => x.name === d.name);
1171
+ if (!ex) {
1172
+ state.datasets.push(d);
1173
+ sum.datasetsAdded++;
1174
+ continue;
1175
+ }
1176
+ for (const r of d.rows) {
1177
+ const j = ex.rows.findIndex((x) => x._id === r._id);
1178
+ if (j >= 0) ex.rows[j] = r;
1179
+ else ex.rows.push(r);
1180
+ }
1181
+ ex.updatedAt = nowIso();
1182
+ sum.datasetsUpdated++;
1183
+ }
1184
+ return sum;
1185
+ }
1186
+ /** Excel (Türkçe) ile uyumlu olsun diye ; ayırıcı ve UTF-8 BOM kullanılır. */
1187
+ function datasetToCsv(ds, keys = datasetKeys(ds)) {
1188
+ const cell = (v) => {
1189
+ const s = v ?? "";
1190
+ return /[;"\r\n]/.test(s) ? `"${s.replace(/"/g, "\"\"")}"` : s;
1191
+ };
1192
+ const header = ["_label", ...keys];
1193
+ const lines = [header.map(cell).join(";")];
1194
+ for (const r of ds.rows) lines.push(header.map((k) => cell(r[k])).join(";"));
1195
+ return "" + lines.join("\r\n");
1196
+ }
1197
+ function parseCsv(text) {
1198
+ text = text.replace(/^/, "");
1199
+ const first = text.split(/\r?\n/, 1)[0] ?? "";
1200
+ const count = (c) => first.split(c).length - 1;
1201
+ const delim = [
1202
+ ";",
1203
+ ",",
1204
+ " "
1205
+ ].sort((a, b) => count(b) - count(a))[0];
1206
+ const rows = [];
1207
+ let row = [];
1208
+ let cur = "";
1209
+ let q = false;
1210
+ for (let i = 0; i < text.length; i++) {
1211
+ const c = text[i];
1212
+ if (q) {
1213
+ if (c === "\"" && text[i + 1] === "\"") {
1214
+ cur += "\"";
1215
+ i++;
1216
+ } else if (c === "\"") q = false;
1217
+ else cur += c;
1218
+ } else if (c === "\"") q = true;
1219
+ else if (c === delim) {
1220
+ row.push(cur);
1221
+ cur = "";
1222
+ } else if (c === "\n" || c === "\r") {
1223
+ if (c === "\r" && text[i + 1] === "\n") i++;
1224
+ row.push(cur);
1225
+ rows.push(row);
1226
+ row = [];
1227
+ cur = "";
1228
+ } else cur += c;
1229
+ }
1230
+ if (cur !== "" || row.length) {
1231
+ row.push(cur);
1232
+ rows.push(row);
1233
+ }
1234
+ return rows.filter((r) => r.some((c) => c.trim() !== ""));
1235
+ }
1236
+ /** CSV'den veri seti üretir. Başlık satırı anahtarlardır; "_label" (ya da "Etiket") sütunu satır adıdır. */
1237
+ function csvToDataset(text, name) {
1238
+ const rows = parseCsv(text);
1239
+ if (rows.length < 1) throw new ImportError("CSV boş.");
1240
+ const header = rows[0].map((h) => h.trim());
1241
+ if (header.filter((h) => h && !h.startsWith("_")).length === 0) throw new ImportError("CSV başlık satırında anahtar yok.");
1242
+ return {
1243
+ id: uid(),
1244
+ name,
1245
+ updatedAt: nowIso(),
1246
+ rows: rows.slice(1).map((cells) => {
1247
+ const r = { _id: uid() };
1248
+ header.forEach((h, i) => {
1249
+ if (!h) return;
1250
+ const v = cells[i] ?? "";
1251
+ if (h === "_label" || h.toLocaleLowerCase("tr") === "etiket") r._label = v;
1252
+ else if (h === "_id") r._id = v || r._id;
1253
+ else if (v !== "") r[h] = v;
1254
+ });
1255
+ return r;
1256
+ })
1257
+ };
1258
+ }
1259
+ function download(filename, text, mime = "application/json") {
1260
+ const blob = new Blob([text], { type: `${mime};charset=utf-8` });
1261
+ const a = document.createElement("a");
1262
+ a.href = URL.createObjectURL(blob);
1263
+ a.download = filename;
1264
+ document.body.appendChild(a);
1265
+ a.click();
1266
+ setTimeout(() => {
1267
+ URL.revokeObjectURL(a.href);
1268
+ a.remove();
1269
+ }, 0);
1270
+ }
1271
+ function exportJson(opts, filename) {
1272
+ const b = makeBundle(load(), opts);
1273
+ const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1274
+ download(filename ?? `otofill-${date}.json`, JSON.stringify(b, null, 2));
1275
+ }
1276
+ function exportCsv(datasetId) {
1277
+ const ds = load().datasets.find((d) => d.id === datasetId);
1278
+ if (!ds) return;
1279
+ download(`${ds.name.replace(/[\\/:*?"<>|]+/g, "_")}.csv`, datasetToCsv(ds), "text/csv");
1280
+ }
1281
+ /** JSON ya da CSV metnini içe aktarır ve kaydeder. */
1282
+ function importText(text, mode, filename = "veri.json") {
1283
+ let bundle;
1284
+ const trimmed = text.replace(/^/, "").trimStart();
1285
+ if (/\.csv$/i.test(filename) || !(trimmed.startsWith("{") || trimmed.startsWith("["))) {
1286
+ const name = filename.replace(/\.[^.]+$/, "") || "CSV verisi";
1287
+ bundle = {
1288
+ format: BUNDLE_FORMAT,
1289
+ version: 1,
1290
+ exportedAt: nowIso(),
1291
+ datasets: [csvToDataset(text, name)]
1292
+ };
1293
+ } else {
1294
+ let raw;
1295
+ try {
1296
+ raw = JSON.parse(trimmed);
1297
+ } catch (e) {
1298
+ throw new ImportError("JSON okunamadı: " + e.message);
1299
+ }
1300
+ bundle = validateBundle(raw);
1301
+ }
1302
+ const state = load();
1303
+ const sum = applyBundle(state, bundle, mode);
1304
+ save(state);
1305
+ return sum;
1306
+ }
1307
+ async function importFile(file, mode) {
1308
+ return importText(await file.text(), mode, file.name);
1309
+ }
1310
+ function summaryText(s) {
1311
+ const parts = [];
1312
+ if (s.fieldsAdded) parts.push(`${s.fieldsAdded} alan eklendi`);
1313
+ if (s.fieldsUpdated) parts.push(`${s.fieldsUpdated} alan güncellendi`);
1314
+ if (s.datasetsAdded) parts.push(`${s.datasetsAdded} veri seti eklendi`);
1315
+ if (s.datasetsUpdated) parts.push(`${s.datasetsUpdated} veri seti güncellendi`);
1316
+ if (s.rows) parts.push(`${s.rows} satır`);
1317
+ return parts.join(", ") || "Değişiklik yok";
1318
+ }
1319
+ // src/panel/dom.ts
1320
+ /** Küçük DOM yardımcısı: h('button', { class: 'x', onClick }, 'Metin') */
1321
+ function h(tag, props = {}, ...children) {
1322
+ const el = document.createElement(tag);
1323
+ for (const [k, v] of Object.entries(props)) {
1324
+ if (v == null || v === false) continue;
1325
+ if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2).toLowerCase(), v);
1326
+ else if (k === "class") el.className = String(v);
1327
+ else if (k === "value") el.value = String(v);
1328
+ else if (k === "checked") el.checked = !!v;
1329
+ else if (k === "style" && typeof v === "object") Object.assign(el.style, v);
1330
+ else el.setAttribute(k, v === true ? "" : String(v));
1331
+ }
1332
+ append(el, children);
1333
+ return el;
1334
+ }
1335
+ function append(el, children) {
1336
+ for (const c of children) {
1337
+ if (c == null || c === false) continue;
1338
+ if (Array.isArray(c)) append(el, c);
1339
+ else el.appendChild(typeof c === "object" ? c : document.createTextNode(String(c)));
1340
+ }
1341
+ }
1342
+ /** "ctrl+q", "ctrl+shift+f" → Hotkey */
1343
+ function parseHotkey(s) {
1344
+ const parts = s.toLowerCase().split("+").map((p) => p.trim());
1345
+ const key = parts[parts.length - 1];
1346
+ const code = /^[a-z]$/.test(key) ? `Key${key.toUpperCase()}` : /^\d$/.test(key) ? `Digit${key}` : key[0].toUpperCase() + key.slice(1);
1347
+ return {
1348
+ ctrl: parts.includes("ctrl"),
1349
+ shift: parts.includes("shift"),
1350
+ alt: parts.includes("alt"),
1351
+ meta: parts.includes("meta") || parts.includes("cmd"),
1352
+ code
1353
+ };
1354
+ }
1355
+ function hotkeyMatches(e, k) {
1356
+ return e.code === k.code && e.ctrlKey === k.ctrl && e.shiftKey === k.shift && e.altKey === k.alt && e.metaKey === k.meta;
1357
+ }
1358
+ // src/panel/styles.ts
1359
+ var CSS$1 = `
1360
+ :host { all: initial; }
1361
+ * { box-sizing: border-box; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
1362
+ .panel {
1363
+ position: fixed; top: 16px; right: 16px; width: 380px; max-height: calc(100vh - 32px);
1364
+ display: flex; flex-direction: column; background: #fff; color: #1f2937; font-size: 13px; line-height: 1.4;
1365
+ border: 1px solid #d1d5db; border-radius: 10px; box-shadow: 0 12px 40px rgba(0,0,0,.22); z-index: 2147483646; overflow: hidden;
1366
+ }
1367
+ .head { display: flex; align-items: center; gap: 8px; padding: 8px 10px; background: #111827; color: #fff; cursor: move; user-select: none; }
1368
+ .head b { font-size: 13px; letter-spacing: .2px; }
1369
+ .head .sub { color: #9ca3af; font-size: 11px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1370
+ .head button { background: transparent; border: 0; color: #d1d5db; font-size: 16px; cursor: pointer; padding: 0 4px; }
1371
+ .tabs { display: flex; border-bottom: 1px solid #e5e7eb; background: #f9fafb; }
1372
+ .tabs button { flex: 1; border: 0; background: transparent; padding: 8px 4px; cursor: pointer; font-size: 12px; color: #4b5563; border-bottom: 2px solid transparent; }
1373
+ .tabs button.on { color: #111827; border-bottom-color: #2563eb; font-weight: 600; }
1374
+ .body { overflow: auto; padding: 10px; display: flex; flex-direction: column; gap: 10px; }
1375
+ .row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
1376
+ .muted { color: #6b7280; font-size: 12px; }
1377
+ .sec { font-weight: 600; font-size: 12px; color: #374151; margin-top: 2px; }
1378
+ button.btn { border: 1px solid #d1d5db; background: #fff; border-radius: 6px; padding: 5px 9px; cursor: pointer; font-size: 12px; color: #1f2937; }
1379
+ button.btn:hover { background: #f3f4f6; }
1380
+ button.pri { background: #2563eb; border-color: #2563eb; color: #fff; }
1381
+ button.pri:hover { background: #1d4ed8; }
1382
+ button.dng { color: #b91c1c; border-color: #fca5a5; }
1383
+ button.sm { padding: 2px 6px; font-size: 11px; }
1384
+ button:disabled { opacity: .5; cursor: default; }
1385
+ input[type=text], select, textarea { border: 1px solid #d1d5db; border-radius: 6px; padding: 5px 7px; font-size: 12px; color: #111827; background: #fff; min-width: 0; }
1386
+ input[type=text]:focus, select:focus, textarea:focus { outline: 2px solid #93c5fd; border-color: #2563eb; }
1387
+ textarea { width: 100%; min-height: 70px; font-family: ui-monospace, Consolas, monospace; font-size: 11px; }
1388
+ .grow { flex: 1; }
1389
+ .list { display: flex; flex-direction: column; border: 1px solid #e5e7eb; border-radius: 8px; overflow: hidden; }
1390
+ .item { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-top: 1px solid #f3f4f6; }
1391
+ .item:first-child { border-top: 0; }
1392
+ .item.click { cursor: pointer; }
1393
+ .item.click:hover, .item.cur { background: #eff6ff; }
1394
+ .num { min-width: 18px; height: 18px; border-radius: 4px; background: #e5e7eb; font-size: 11px; display: inline-flex; align-items: center; justify-content: center; color: #374151; }
1395
+ .key { font-family: ui-monospace, Consolas, monospace; font-size: 12px; color: #1e40af; }
1396
+ .ok { color: #15803d; } .bad { color: #b91c1c; } .warn { color: #b45309; }
1397
+ .toast { padding: 7px 9px; border-radius: 6px; font-size: 12px; }
1398
+ .toast.ok { background: #dcfce7; color: #14532d; } .toast.err { background: #fee2e2; color: #7f1d1d; }
1399
+ .drop { border: 2px dashed #cbd5e1; border-radius: 8px; padding: 14px; text-align: center; color: #64748b; cursor: pointer; }
1400
+ .drop.over { border-color: #2563eb; background: #eff6ff; }
1401
+ .empty { padding: 14px; text-align: center; color: #6b7280; }
1402
+ table { border-collapse: collapse; width: 100%; font-size: 11px; }
1403
+ th, td { border-bottom: 1px solid #f3f4f6; padding: 3px 4px; text-align: left; max-width: 90px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1404
+ th { color: #6b7280; font-weight: 600; }
1405
+ label.opt { display: flex; gap: 6px; align-items: flex-start; cursor: pointer; }
1406
+ .layer { position: fixed; inset: 0; pointer-events: none; z-index: 2147483645; }
1407
+ .hl { position: fixed; border: 2px solid #2563eb; background: rgba(37,99,235,.08); border-radius: 4px; transition: opacity .4s; }
1408
+ .hl.green { border-color: #16a34a; background: rgba(22,163,74,.12); }
1409
+ .badge { position: fixed; transform: translateY(-100%); font: 600 10px/1.6 ui-monospace, Consolas, monospace; padding: 0 5px; border-radius: 4px 4px 4px 0; background: #16a34a; color: #fff; white-space: nowrap; }
1410
+ .badge.free { background: #6b7280; }
1411
+ .teachbar { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); background: #111827; color: #fff; padding: 8px 14px; border-radius: 20px; font-size: 13px; pointer-events: auto; display: flex; gap: 10px; align-items: center; box-shadow: 0 6px 20px rgba(0,0,0,.3); }
1412
+ .teachbar button { background: #374151; color: #fff; border: 0; border-radius: 12px; padding: 3px 10px; cursor: pointer; }
1413
+ .pop { position: fixed; width: 300px; background: #fff; border: 1px solid #d1d5db; border-radius: 10px; box-shadow: 0 10px 30px rgba(0,0,0,.25); padding: 10px; pointer-events: auto; display: flex; flex-direction: column; gap: 7px; font-size: 12px; color: #1f2937; }
1414
+ .pop .lbl { font-size: 11px; color: #6b7280; }
1415
+ .pop input[type=text], .pop select { width: 100%; }
1416
+ `;
1417
+ // src/panel/panel.ts
1418
+ var KIND_TR = {
1419
+ text: "metin",
1420
+ textarea: "çok satır",
1421
+ select: "seçim",
1422
+ checkbox: "onay kutusu",
1423
+ radio: "seçenek grubu",
1424
+ date: "tarih",
1425
+ contenteditable: "zengin metin",
1426
+ other: "diğer"
1427
+ };
1428
+ var Panel = class {
1429
+ constructor(opts) {
1430
+ this.opts = opts;
1431
+ this.visible = false;
1432
+ this.view = "fill";
1433
+ this.result = null;
1434
+ this.lastFill = null;
1435
+ this.toastMsg = "";
1436
+ this.toastKind = "ok";
1437
+ this.toastTimer = 0;
1438
+ this.pattern = "";
1439
+ this.importMode = "merge";
1440
+ this.inspecting = false;
1441
+ this.teaching = false;
1442
+ this.teachPop = null;
1443
+ this.freeSel = /* @__PURE__ */ new Map();
1444
+ this.pos = null;
1445
+ this.raf = 0;
1446
+ this.onKey = (e) => {
1447
+ if (hotkeyMatches(e, this.opts.hotkey)) {
1448
+ e.preventDefault();
1449
+ e.stopPropagation();
1450
+ this.toggle();
1451
+ return;
1452
+ }
1453
+ if (e.key === "Escape") {
1454
+ if (this.teachPop) {
1455
+ this.closeTeachPop();
1456
+ e.preventDefault();
1457
+ } else if (this.teaching) {
1458
+ this.stopTeach();
1459
+ e.preventDefault();
1460
+ }
1461
+ return;
1462
+ }
1463
+ if (!this.visible || this.view !== "fill" || this.teaching) return;
1464
+ const active = this.root.activeElement ?? document.activeElement;
1465
+ if (active && (active.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(active.tagName))) return;
1466
+ const ds = this.currentDataset();
1467
+ if (!ds) return;
1468
+ if (/^Digit[1-9]$/.test(e.code) && !e.ctrlKey && !e.altKey && !e.metaKey) {
1469
+ const i = Number(e.code.slice(5)) - 1;
1470
+ if (ds.rows[i]) {
1471
+ e.preventDefault();
1472
+ this.fillWith(ds, i);
1473
+ }
1474
+ } else if (e.key === "Enter" && !e.ctrlKey) {
1475
+ e.preventDefault();
1476
+ this.fillNext(ds);
1477
+ }
1478
+ };
1479
+ this.startDrag = (e) => {
1480
+ if (e.target.tagName === "BUTTON") return;
1481
+ const rect = this.box.getBoundingClientRect();
1482
+ const dx = e.clientX - rect.left;
1483
+ const dy = e.clientY - rect.top;
1484
+ const move = (ev) => {
1485
+ this.pos = {
1486
+ left: Math.max(0, Math.min(window.innerWidth - 60, ev.clientX - dx)),
1487
+ top: Math.max(0, Math.min(window.innerHeight - 40, ev.clientY - dy))
1488
+ };
1489
+ Object.assign(this.box.style, {
1490
+ left: `${this.pos.left}px`,
1491
+ top: `${this.pos.top}px`,
1492
+ right: "auto"
1493
+ });
1494
+ };
1495
+ const up = () => {
1496
+ window.removeEventListener("mousemove", move, true);
1497
+ window.removeEventListener("mouseup", up, true);
1498
+ };
1499
+ window.addEventListener("mousemove", move, true);
1500
+ window.addEventListener("mouseup", up, true);
1501
+ e.preventDefault();
1502
+ };
1503
+ this.hoverEl = null;
1504
+ this.onViewport = () => {
1505
+ if (!this.inspecting && !this.hoverEl && !this.teaching) return;
1506
+ cancelAnimationFrame(this.raf);
1507
+ this.raf = requestAnimationFrame(() => this.drawLayer());
1508
+ };
1509
+ this.onTeachMove = (e) => {
1510
+ if (this.fromPanel(e) || this.teachPop) return;
1511
+ const el = fieldFromTarget(e.composedPath()[0]);
1512
+ if (el !== this.hoverEl) this.hover(el);
1513
+ };
1514
+ this.onTeachPointer = (e) => {
1515
+ if (this.fromPanel(e)) return;
1516
+ e.preventDefault();
1517
+ e.stopPropagation();
1518
+ e.stopImmediatePropagation();
1519
+ if (e.type !== "click") return;
1520
+ const el = fieldFromTarget(e.composedPath()[0]);
1521
+ if (el) this.openTeachPop(el);
1522
+ else if (this.teachPop) this.closeTeachPop();
1523
+ };
1524
+ }
1525
+ mount() {
1526
+ if (this.host) return;
1527
+ this.host = document.createElement(HOST_TAG);
1528
+ this.host.setAttribute("data-otofill-host", "");
1529
+ this.root = this.host.attachShadow({ mode: "open" });
1530
+ this.root.appendChild(h("style", {}, CSS$1));
1531
+ this.layer = h("div", { class: "layer" });
1532
+ this.box = h("div", {
1533
+ class: "panel",
1534
+ style: { display: "none" }
1535
+ });
1536
+ this.root.append(this.layer, this.box);
1537
+ document.documentElement.appendChild(this.host);
1538
+ for (const t of [
1539
+ "keydown",
1540
+ "keyup",
1541
+ "keypress"
1542
+ ]) this.host.addEventListener(t, (e) => e.stopPropagation());
1543
+ window.addEventListener("keydown", this.onKey, true);
1544
+ window.addEventListener("scroll", this.onViewport, true);
1545
+ window.addEventListener("resize", this.onViewport);
1546
+ subscribe(() => this.visible && this.refresh());
1547
+ }
1548
+ show() {
1549
+ this.mount();
1550
+ this.visible = true;
1551
+ this.pattern ||= suggestPagePattern();
1552
+ this.box.style.display = "flex";
1553
+ this.refresh();
1554
+ }
1555
+ hide() {
1556
+ this.visible = false;
1557
+ this.box.style.display = "none";
1558
+ this.stopTeach();
1559
+ this.inspecting = false;
1560
+ this.drawLayer();
1561
+ }
1562
+ toggle() {
1563
+ if (this.visible) this.hide();
1564
+ else this.show();
1565
+ }
1566
+ isOpen() {
1567
+ return this.visible;
1568
+ }
1569
+ refresh() {
1570
+ this.result = analyze();
1571
+ this.render();
1572
+ this.drawLayer();
1573
+ }
1574
+ toast(msg, kind = "ok") {
1575
+ this.toastMsg = msg;
1576
+ this.toastKind = kind;
1577
+ clearTimeout(this.toastTimer);
1578
+ this.toastTimer = window.setTimeout(() => {
1579
+ this.toastMsg = "";
1580
+ if (this.visible) this.render();
1581
+ }, 5e3);
1582
+ if (this.visible) this.render();
1583
+ }
1584
+ currentDataset() {
1585
+ const s = load();
1586
+ const pageKeys = this.pageKeys();
1587
+ const ranked = rankDatasets(s.datasets, pageKeys).filter((x) => x.overlap > 0);
1588
+ const want = this.dsId ?? s.prefs.lastDatasetId;
1589
+ return ranked.find((x) => x.ds.id === want)?.ds ?? ranked[0]?.ds;
1590
+ }
1591
+ pageKeys() {
1592
+ return [...new Set((this.result?.matches ?? []).map((m) => m.def.key))];
1593
+ }
1594
+ async fillWith(ds, i) {
1595
+ const row = ds.rows[i];
1596
+ if (!row) return;
1597
+ update((s) => {
1598
+ s.prefs.lastDatasetId = ds.id;
1599
+ s.prefs.cursor[ds.id] = (i + 1) % ds.rows.length;
1600
+ });
1601
+ const res = await fillRow(row, { onFilled: (el) => this.flash(el) });
1602
+ this.lastFill = res;
1603
+ const problems = res.notFound.length + res.failed.length;
1604
+ if (load().prefs.closeAfterFill && problems === 0) {
1605
+ this.hide();
1606
+ return;
1607
+ }
1608
+ this.toast(`"${rowTitle(row)}": ${res.filled.length} alan dolduruldu` + (problems ? `, ${problems} sorunlu` : ""), problems ? "err" : "ok");
1609
+ }
1610
+ fillNext(ds) {
1611
+ const i = load().prefs.cursor[ds.id] ?? 0;
1612
+ return this.fillWith(ds, i < ds.rows.length ? i : 0);
1613
+ }
1614
+ fillRandom(ds) {
1615
+ return this.fillWith(ds, Math.floor(Math.random() * ds.rows.length));
1616
+ }
1617
+ render() {
1618
+ const r = this.result;
1619
+ const header = h("div", {
1620
+ class: "head",
1621
+ onMousedown: this.startDrag
1622
+ }, h("b", {}, "Otofill"), h("span", { class: "sub" }, `${r.matches.length}/${r.defs.length} alan · ${location.host}`), h("button", {
1623
+ title: "Yeniden tara",
1624
+ onClick: () => this.refresh()
1625
+ }, "⟳"), h("button", {
1626
+ title: "Kapat (Ctrl+Q)",
1627
+ onClick: () => this.hide()
1628
+ }, "×"));
1629
+ const tab = (v, label) => h("button", {
1630
+ class: this.view === v ? "on" : "",
1631
+ onClick: () => {
1632
+ this.view = v;
1633
+ this.render();
1634
+ this.drawLayer();
1635
+ }
1636
+ }, label);
1637
+ const tabs = h("div", { class: "tabs" }, tab("fill", "Doldur"), tab("fields", "Alanlar"), tab("data", "Veri"), tab("io", "Aktar"));
1638
+ const body = h("div", { class: "body" });
1639
+ if (this.toastMsg) body.appendChild(h("div", { class: `toast ${this.toastKind}` }, this.toastMsg));
1640
+ if (this.view === "fill") this.renderFill(body);
1641
+ else if (this.view === "fields") this.renderFields(body);
1642
+ else if (this.view === "data") this.renderData(body);
1643
+ else this.renderIo(body);
1644
+ const scroll = this.box.querySelector(".body")?.scrollTop ?? 0;
1645
+ this.box.replaceChildren(header, tabs, body);
1646
+ body.scrollTop = scroll;
1647
+ if (this.pos) Object.assign(this.box.style, {
1648
+ left: `${this.pos.left}px`,
1649
+ top: `${this.pos.top}px`,
1650
+ right: "auto"
1651
+ });
1652
+ }
1653
+ renderFill(body) {
1654
+ const r = this.result;
1655
+ const s = load();
1656
+ if (r.defs.length === 0) {
1657
+ body.append(h("div", { class: "empty" }, "Bu sayfa için tanımlı alan yok.", h("br"), "Önce alanları tanıtın ya da tanımları içe aktarın."), h("div", { class: "row" }, h("button", {
1658
+ class: "btn pri grow",
1659
+ onClick: () => {
1660
+ this.view = "fields";
1661
+ this.startTeach();
1662
+ }
1663
+ }, "Tıklayarak alan tanıt"), h("button", {
1664
+ class: "btn grow",
1665
+ onClick: () => {
1666
+ this.view = "io";
1667
+ this.render();
1668
+ }
1669
+ }, "İçe aktar")));
1670
+ return;
1671
+ }
1672
+ const ranked = rankDatasets(s.datasets, this.pageKeys()).filter((x) => x.overlap > 0);
1673
+ if (ranked.length === 0) {
1674
+ body.append(h("div", { class: "empty" }, `${r.matches.length} alan tanındı ama bu alanlara uyan veri seti yok.`, h("br"), "Veri sekmesinden sayfadaki değerleri kaydedin ya da veri içe aktarın."), h("div", { class: "row" }, h("button", {
1675
+ class: "btn grow",
1676
+ onClick: () => {
1677
+ this.view = "data";
1678
+ this.render();
1679
+ }
1680
+ }, "Veri sekmesi")));
1681
+ return;
1682
+ }
1683
+ const ds = this.currentDataset();
1684
+ const keys = this.pageKeys();
1685
+ const cursor = s.prefs.cursor[ds.id] ?? 0;
1686
+ body.append(h("div", { class: "row" }, h("select", {
1687
+ class: "grow",
1688
+ onChange: (e) => {
1689
+ this.dsId = e.target.value;
1690
+ this.render();
1691
+ }
1692
+ }, ranked.map((x) => h("option", {
1693
+ value: x.ds.id,
1694
+ selected: x.ds.id === ds.id ? true : void 0
1695
+ }, `${x.ds.name} (${x.overlap} alan · ${x.ds.rows.length} satır)`)))), ds.rows.length === 0 ? h("div", { class: "empty" }, "Bu veri setinde satır yok.") : h("div", { class: "list" }, ds.rows.map((row, i) => h("div", {
1696
+ class: "item click" + (i === cursor ? " cur" : ""),
1697
+ title: "Bu satırla doldur",
1698
+ onClick: () => this.fillWith(ds, i)
1699
+ }, h("span", { class: "num" }, i < 9 ? String(i + 1) : "·"), h("span", { class: "grow" }, rowTitle(row, keys)), i === cursor ? h("span", { class: "muted" }, "sıradaki") : null))), h("div", { class: "row" }, h("button", {
1700
+ class: "btn pri grow",
1701
+ disabled: !ds.rows.length || void 0,
1702
+ onClick: () => this.fillNext(ds)
1703
+ }, "Sıradaki satır (Enter)"), h("button", {
1704
+ class: "btn",
1705
+ disabled: !ds.rows.length || void 0,
1706
+ onClick: () => this.fillRandom(ds)
1707
+ }, "Rastgele")), h("label", { class: "opt muted" }, h("input", {
1708
+ type: "checkbox",
1709
+ checked: s.prefs.closeAfterFill,
1710
+ onChange: (e) => update((st) => {
1711
+ st.prefs.closeAfterFill = e.target.checked;
1712
+ })
1713
+ }), "Sorunsuz doldurunca paneli kapat · 1-9: satır seç"));
1714
+ const lf = this.lastFill;
1715
+ if (lf) {
1716
+ const line = (cls, title, list) => list.length ? h("div", { class: cls }, `${title}: `, h("span", { class: "key" }, list.join(", "))) : null;
1717
+ body.append(h("div", {}, line("ok", "Dolduruldu", lf.filled), line("bad", "Sayfada bulunamadı", lf.notFound), line("bad", "Yazılamadı", lf.failed), line("muted", "Satırda değeri yok", lf.noValue)));
1718
+ }
1719
+ if (r.missing.length) body.append(h("div", { class: "muted" }, `Tanımlı ama bulunamayan: ${r.missing.map((d) => d.key).join(", ")}`));
1720
+ }
1721
+ renderFields(body) {
1722
+ const r = this.result;
1723
+ const site = sitePattern();
1724
+ const here = suggestPagePattern();
1725
+ body.append(h("div", { class: "row" }, h("button", {
1726
+ class: "btn pri grow",
1727
+ onClick: () => this.startTeach()
1728
+ }, "Tıklayarak tanıt"), h("button", {
1729
+ class: "btn" + (this.inspecting ? " pri" : ""),
1730
+ onClick: () => {
1731
+ this.inspecting = !this.inspecting;
1732
+ this.render();
1733
+ this.drawLayer();
1734
+ }
1735
+ }, this.inspecting ? "Göstermeyi kapat" : "Sayfada göster")), h("div", { class: "muted" }, "Yeni tanımların geçerli olacağı adres (* joker):"), h("div", { class: "row" }, h("input", {
1736
+ type: "text",
1737
+ class: "grow",
1738
+ value: this.pattern,
1739
+ onChange: (e) => {
1740
+ this.pattern = e.target.value.trim();
1741
+ }
1742
+ }), h("button", {
1743
+ class: "btn sm",
1744
+ title: here,
1745
+ onClick: () => {
1746
+ this.pattern = here;
1747
+ this.render();
1748
+ }
1749
+ }, "Bu sayfa"), h("button", {
1750
+ class: "btn sm",
1751
+ title: site,
1752
+ onClick: () => {
1753
+ this.pattern = site;
1754
+ this.render();
1755
+ }
1756
+ }, "Tüm site")), h("div", { class: "sec" }, `Bu sayfadaki tanımlar (${r.defs.length})`));
1757
+ if (r.defs.length === 0) body.append(h("div", { class: "muted" }, "Henüz yok."));
1758
+ else body.append(h("div", { class: "list" }, r.defs.map((def) => {
1759
+ const m = r.matches.find((x) => x.def.id === def.id);
1760
+ return h("div", {
1761
+ class: "item",
1762
+ onMouseenter: () => m && this.hover(m.fp.el),
1763
+ onMouseleave: () => this.hover(null)
1764
+ }, h("span", {
1765
+ class: m ? "ok" : "bad",
1766
+ title: m ? `puan ${m.score}` : "sayfada bulunamadı"
1767
+ }, m ? "●" : "○"), h("span", { class: "grow" }, h("span", { class: "key" }, def.key), def.title ? h("span", { class: "muted" }, ` · ${def.title}`) : null), h("span", { class: "muted" }, m ? String(m.score) : "—"), h("button", {
1768
+ class: "btn sm dng",
1769
+ title: "Tanımı sil",
1770
+ onClick: () => {
1771
+ if (confirm(`"${def.key}" tanımı silinsin mi?`)) removeField(def.id);
1772
+ }
1773
+ }, "Sil"));
1774
+ })));
1775
+ const existing = new Set(r.defs.map((f) => f.key));
1776
+ const used = /* @__PURE__ */ new Set();
1777
+ for (const fp of r.free) if (!this.freeSel.has(fp)) {
1778
+ let k = slug(fp.label || fp.name || fp.placeholder || fp.id) || `alan_${(fp.index ?? 0) + 1}`;
1779
+ let n = 2;
1780
+ const base = k;
1781
+ while (existing.has(k) || used.has(k)) k = `${base}_${n++}`;
1782
+ used.add(k);
1783
+ this.freeSel.set(fp, {
1784
+ on: false,
1785
+ key: k
1786
+ });
1787
+ }
1788
+ body.append(h("div", { class: "sec" }, `Tanımsız alanlar (${r.free.length})`));
1789
+ if (r.free.length === 0) {
1790
+ body.append(h("div", { class: "muted" }, "Sayfadaki tüm görünür alanlar tanımlı."));
1791
+ return;
1792
+ }
1793
+ body.append(h("div", { class: "list" }, r.free.map((fp) => {
1794
+ const st = this.freeSel.get(fp);
1795
+ return h("div", {
1796
+ class: "item",
1797
+ onMouseenter: () => this.hover(fp.el),
1798
+ onMouseleave: () => this.hover(null)
1799
+ }, h("input", {
1800
+ type: "checkbox",
1801
+ checked: st.on,
1802
+ onChange: (e) => {
1803
+ st.on = e.target.checked;
1804
+ }
1805
+ }), h("div", {
1806
+ class: "grow",
1807
+ style: {
1808
+ display: "flex",
1809
+ flexDirection: "column",
1810
+ gap: "2px",
1811
+ minWidth: "0"
1812
+ }
1813
+ }, h("input", {
1814
+ type: "text",
1815
+ value: st.key,
1816
+ onInput: (e) => {
1817
+ st.key = e.target.value.trim();
1818
+ st.on = true;
1819
+ e.target.parentElement.previousSibling.checked = true;
1820
+ }
1821
+ }), h("span", { class: "muted" }, `${fp.label || fp.placeholder || fp.name || "(etiketsiz)"} · ${KIND_TR[fp.kind]}`)));
1822
+ })), h("div", { class: "row" }, h("button", {
1823
+ class: "btn",
1824
+ onClick: () => {
1825
+ const all = [...this.freeSel.values()].every((x) => x.on);
1826
+ r.free.forEach((fp) => this.freeSel.get(fp).on = !all);
1827
+ this.render();
1828
+ }
1829
+ }, "Tümünü seç / bırak"), h("button", {
1830
+ class: "btn pri grow",
1831
+ onClick: () => this.saveFree()
1832
+ }, "Seçilenleri kaydet")));
1833
+ }
1834
+ saveFree() {
1835
+ const picked = this.result.free.filter((fp) => this.freeSel.get(fp)?.on && this.freeSel.get(fp).key);
1836
+ if (!picked.length) return this.toast("Kaydedilecek alan seçilmedi.", "err");
1837
+ update((s) => {
1838
+ for (const fp of picked) s.fields.push(this.defFrom(fp, this.freeSel.get(fp).key));
1839
+ });
1840
+ picked.forEach((fp) => this.freeSel.delete(fp));
1841
+ this.toast(`${picked.length} alan tanımlandı.`);
1842
+ }
1843
+ defFrom(fp, key, title, pages, id) {
1844
+ return {
1845
+ id: id ?? uid(),
1846
+ key,
1847
+ title: title ?? fp.label,
1848
+ pages: pages ?? [this.pattern || suggestPagePattern()],
1849
+ kind: fp.kind,
1850
+ match: hintsOf(fp),
1851
+ updatedAt: nowIso()
1852
+ };
1853
+ }
1854
+ renderData(body) {
1855
+ const r = this.result;
1856
+ const s = load();
1857
+ const keys = this.pageKeys();
1858
+ let target = s.datasets.find((d) => d.id === (this.openDsId ?? s.prefs.lastDatasetId))?.id ?? s.datasets[0]?.id ?? "__new";
1859
+ let newName = "";
1860
+ let label = "";
1861
+ body.append(h("div", { class: "sec" }, "Sayfadaki değerleri satır olarak kaydet"), h("div", { class: "muted" }, keys.length ? `Tanınan ${keys.length} alanın o anki değerleri okunur. Formu elle doldurup buradan kaydedebilirsiniz.` : "Önce bu sayfadaki alanları tanıtın."), h("div", { class: "row" }, h("select", {
1862
+ class: "grow",
1863
+ onChange: (e) => {
1864
+ target = e.target.value;
1865
+ nameInput.style.display = target === "__new" ? "" : "none";
1866
+ }
1867
+ }, s.datasets.map((d) => h("option", {
1868
+ value: d.id,
1869
+ selected: d.id === target ? true : void 0
1870
+ }, d.name)), h("option", {
1871
+ value: "__new",
1872
+ selected: target === "__new" ? true : void 0
1873
+ }, "+ Yeni veri seti"))));
1874
+ const nameInput = h("input", {
1875
+ type: "text",
1876
+ placeholder: "Yeni veri setinin adı",
1877
+ style: { display: target === "__new" ? "" : "none" },
1878
+ onInput: (e) => {
1879
+ newName = e.target.value;
1880
+ }
1881
+ });
1882
+ body.append(nameInput, h("div", { class: "row" }, h("input", {
1883
+ type: "text",
1884
+ class: "grow",
1885
+ placeholder: "Satır adı (ör. \"Bireysel - İstanbul\")",
1886
+ onInput: (e) => {
1887
+ label = e.target.value;
1888
+ }
1889
+ }), h("button", {
1890
+ class: "btn pri",
1891
+ disabled: !keys.length || void 0,
1892
+ onClick: () => {
1893
+ const values = readRow(r);
1894
+ let id = target;
1895
+ if (target === "__new") id = createDataset(newName.trim() || `Veri ${(/* @__PURE__ */ new Date()).toLocaleDateString("tr-TR")}`).id;
1896
+ addRow(id, {
1897
+ ...values,
1898
+ ...label.trim() ? { _label: label.trim() } : {}
1899
+ });
1900
+ this.openDsId = id;
1901
+ this.toast(`${Object.keys(values).length} değer satır olarak kaydedildi.`);
1902
+ }
1903
+ }, "Kaydet")), h("div", { class: "sec" }, `Veri setleri (${s.datasets.length})`));
1904
+ if (!s.datasets.length) {
1905
+ body.append(h("div", { class: "muted" }, "Henüz veri seti yok. Yukarıdan kaydedin ya da Aktar sekmesinden içe aktarın."));
1906
+ return;
1907
+ }
1908
+ body.append(h("div", { class: "list" }, s.datasets.map((d) => {
1909
+ const open = this.openDsId === d.id;
1910
+ const cols = (keys.length ? keys.filter((k) => datasetKeys(d).includes(k)) : datasetKeys(d)).slice(0, 5);
1911
+ return h("div", {}, h("div", {
1912
+ class: "item click",
1913
+ onClick: () => {
1914
+ this.openDsId = open ? void 0 : d.id;
1915
+ this.render();
1916
+ }
1917
+ }, h("span", {}, open ? "▾" : "▸"), h("span", { class: "grow" }, d.name), h("span", { class: "muted" }, `${d.rows.length} satır`), h("button", {
1918
+ class: "btn sm",
1919
+ title: "CSV indir",
1920
+ onClick: (e) => {
1921
+ e.stopPropagation();
1922
+ exportCsv(d.id);
1923
+ }
1924
+ }, "CSV"), h("button", {
1925
+ class: "btn sm dng",
1926
+ onClick: (e) => {
1927
+ e.stopPropagation();
1928
+ if (confirm(`"${d.name}" veri seti silinsin mi?`)) removeDataset(d.id);
1929
+ }
1930
+ }, "Sil")), open ? h("div", { style: {
1931
+ padding: "0 8px 8px",
1932
+ overflowX: "auto"
1933
+ } }, h("table", {}, h("tr", {}, h("th", {}, "Satır"), cols.map((c) => h("th", { title: c }, c)), h("th", {})), d.rows.map((row) => h("tr", {}, h("td", { title: rowTitle(row) }, rowTitle(row)), cols.map((c) => h("td", { title: row[c] ?? "" }, row[c] ?? "")), h("td", {}, h("button", {
1934
+ class: "btn sm dng",
1935
+ title: "Satırı sil",
1936
+ onClick: () => removeRow(d.id, row._id)
1937
+ }, "×"))))), h("div", {
1938
+ class: "muted",
1939
+ style: { marginTop: "4px" }
1940
+ }, "Ayrıntılı düzenleme için yönetim sayfasını kullanın.")) : null);
1941
+ })));
1942
+ }
1943
+ renderIo(body) {
1944
+ const s = load();
1945
+ let csvId = s.datasets[0]?.id;
1946
+ let pasted = "";
1947
+ const runImport = async (fn) => {
1948
+ try {
1949
+ this.toast(await fn());
1950
+ } catch (e) {
1951
+ this.toast(e instanceof ImportError ? e.message : "İçe aktarılamadı: " + e.message, "err");
1952
+ }
1953
+ };
1954
+ const fileInput = h("input", {
1955
+ type: "file",
1956
+ accept: ".json,.csv,application/json,text/csv",
1957
+ multiple: true,
1958
+ style: { display: "none" },
1959
+ onChange: (e) => {
1960
+ const files = Array.from(e.target.files ?? []);
1961
+ runImport(async () => {
1962
+ const out = [];
1963
+ for (const f of files) out.push(`${f.name}: ${summaryText(await importFile(f, this.importMode))}`);
1964
+ return out.join(" · ");
1965
+ });
1966
+ }
1967
+ });
1968
+ const drop = h("div", {
1969
+ class: "drop",
1970
+ onClick: () => fileInput.click(),
1971
+ onDragover: (e) => {
1972
+ e.preventDefault();
1973
+ drop.classList.add("over");
1974
+ },
1975
+ onDragleave: () => drop.classList.remove("over"),
1976
+ onDrop: (e) => {
1977
+ e.preventDefault();
1978
+ drop.classList.remove("over");
1979
+ const files = Array.from(e.dataTransfer?.files ?? []);
1980
+ runImport(async () => {
1981
+ const out = [];
1982
+ for (const f of files) out.push(`${f.name}: ${summaryText(await importFile(f, this.importMode))}`);
1983
+ return out.join(" · ");
1984
+ });
1985
+ }
1986
+ }, "JSON / CSV dosyasını buraya bırakın ya da tıklayıp seçin");
1987
+ const mode = (m, title, desc) => h("label", { class: "opt" }, h("input", {
1988
+ type: "radio",
1989
+ name: "mode",
1990
+ checked: this.importMode === m,
1991
+ onChange: () => {
1992
+ this.importMode = m;
1993
+ }
1994
+ }), h("span", {}, h("b", {}, title), h("span", { class: "muted" }, ` · ${desc}`)));
1995
+ body.append(h("div", { class: "sec" }, "Dışa aktar"), h("div", { class: "row" }, h("button", {
1996
+ class: "btn pri",
1997
+ onClick: () => exportJson({
1998
+ fields: true,
1999
+ datasets: true
2000
+ })
2001
+ }, "Hepsi (JSON)"), h("button", {
2002
+ class: "btn",
2003
+ onClick: () => exportJson({ fields: true }, `otofill-alanlar-${location.hostname}.json`)
2004
+ }, "Alan tanımları"), h("button", {
2005
+ class: "btn",
2006
+ onClick: () => exportJson({ datasets: true }, "otofill-veri.json")
2007
+ }, "Veri setleri")), s.datasets.length ? h("div", { class: "row" }, h("select", {
2008
+ class: "grow",
2009
+ onChange: (e) => {
2010
+ csvId = e.target.value;
2011
+ }
2012
+ }, s.datasets.map((d) => h("option", { value: d.id }, d.name))), h("button", {
2013
+ class: "btn",
2014
+ onClick: () => csvId && exportCsv(csvId)
2015
+ }, "CSV (Excel)")) : "", h("div", { class: "sec" }, "İçe aktar"), mode("merge", "Birleştir", "aynı kayıtları günceller, yenileri ekler"), mode("replace", "Üzerine yaz", "dosyadaki bölümü tamamen değiştirir"), mode("copy", "Kopya olarak ekle", "hepsini yeni kayıt olarak ekler"), drop, fileInput, h("textarea", {
2016
+ placeholder: "ya da JSON / CSV metnini buraya yapıştırın",
2017
+ onInput: (e) => {
2018
+ pasted = e.target.value;
2019
+ }
2020
+ }), h("div", { class: "row" }, h("button", {
2021
+ class: "btn grow",
2022
+ onClick: () => runImport(() => summaryText(importText(pasted, this.importMode, pasted.trimStart().startsWith("{") ? "yapistirilan.json" : `Yapıştırılan ${(/* @__PURE__ */ new Date()).toLocaleString("tr-TR")}.csv`)))
2023
+ }, "Metinden içe aktar")), h("div", { class: "sec" }, "Depolama"), h("div", { class: "muted" }, `Veriler yalnızca bu tarayıcıda, ${location.origin} için saklanır; hiçbir yere gönderilmez. ${s.fields.length} alan tanımı, ${s.datasets.length} veri seti. Sürüm 0.1.0.`), h("div", { class: "row" }, h("button", {
2024
+ class: "btn dng",
2025
+ onClick: () => {
2026
+ if (confirm(`${location.origin} için kayıtlı tüm Otofill alanları ve verileri silinsin mi? Bu işlem geri alınamaz; önce dışa aktarmanız önerilir.`)) {
2027
+ clearAll();
2028
+ this.toast("Tüm veriler silindi.");
2029
+ }
2030
+ }
2031
+ }, "Bu sitedeki tüm verileri sil")));
2032
+ }
2033
+ targetRectEl(el) {
2034
+ if (el.getClientRects().length && el.getBoundingClientRect().width > 2) return el;
2035
+ return el.closest("label") ?? el.parentElement ?? el;
2036
+ }
2037
+ boxFor(el, cls) {
2038
+ const r = this.targetRectEl(el).getBoundingClientRect();
2039
+ return h("div", {
2040
+ class: `hl ${cls}`,
2041
+ style: {
2042
+ left: `${r.left - 3}px`,
2043
+ top: `${r.top - 3}px`,
2044
+ width: `${r.width + 6}px`,
2045
+ height: `${r.height + 6}px`
2046
+ }
2047
+ });
2048
+ }
2049
+ hover(el) {
2050
+ this.hoverEl = el;
2051
+ this.drawLayer();
2052
+ }
2053
+ flash(el) {
2054
+ const b = this.boxFor(el, "green");
2055
+ this.layer.appendChild(b);
2056
+ setTimeout(() => b.style.opacity = "0", 700);
2057
+ setTimeout(() => b.remove(), 1200);
2058
+ }
2059
+ drawLayer() {
2060
+ const keep = [...this.layer.querySelectorAll(".pop, .teachbar")];
2061
+ this.layer.replaceChildren(...keep);
2062
+ if (!this.visible && !this.teaching) return;
2063
+ const r = this.result;
2064
+ if (r && (this.inspecting || this.teaching)) {
2065
+ for (const m of r.matches) {
2066
+ const rect = this.targetRectEl(m.fp.el).getBoundingClientRect();
2067
+ if (rect.bottom < 0 || rect.top > window.innerHeight) continue;
2068
+ this.layer.appendChild(h("div", {
2069
+ class: "badge",
2070
+ style: {
2071
+ left: `${rect.left}px`,
2072
+ top: `${rect.top}px`
2073
+ }
2074
+ }, `${m.def.key} · ${m.score}`));
2075
+ }
2076
+ if (this.inspecting) for (const fp of r.free) {
2077
+ const rect = this.targetRectEl(fp.el).getBoundingClientRect();
2078
+ if (rect.bottom < 0 || rect.top > window.innerHeight) continue;
2079
+ this.layer.appendChild(h("div", {
2080
+ class: "badge free",
2081
+ style: {
2082
+ left: `${rect.left}px`,
2083
+ top: `${rect.top}px`
2084
+ }
2085
+ }, "? tanımsız"));
2086
+ }
2087
+ }
2088
+ if (this.hoverEl?.isConnected) this.layer.appendChild(this.boxFor(this.hoverEl, ""));
2089
+ }
2090
+ startTeach() {
2091
+ this.mount();
2092
+ if (this.teaching) return;
2093
+ this.teaching = true;
2094
+ this.pattern ||= suggestPagePattern();
2095
+ if (!this.visible) this.show();
2096
+ this.result = analyze();
2097
+ this.render();
2098
+ const bar = h("div", { class: "teachbar" }, h("span", {}, "Tanıtma modu: bir alana tıklayın"), h("button", { onClick: () => this.stopTeach() }, "Bitir (Esc)"));
2099
+ this.layer.appendChild(bar);
2100
+ for (const t of [
2101
+ "pointerdown",
2102
+ "mousedown",
2103
+ "mouseup",
2104
+ "click"
2105
+ ]) document.addEventListener(t, this.onTeachPointer, true);
2106
+ document.addEventListener("mousemove", this.onTeachMove, true);
2107
+ this.drawLayer();
2108
+ }
2109
+ stopTeach() {
2110
+ if (!this.teaching) return;
2111
+ this.teaching = false;
2112
+ this.closeTeachPop();
2113
+ this.layer.querySelector(".teachbar")?.remove();
2114
+ for (const t of [
2115
+ "pointerdown",
2116
+ "mousedown",
2117
+ "mouseup",
2118
+ "click"
2119
+ ]) document.removeEventListener(t, this.onTeachPointer, true);
2120
+ document.removeEventListener("mousemove", this.onTeachMove, true);
2121
+ this.hoverEl = null;
2122
+ if (this.visible) this.refresh();
2123
+ else this.drawLayer();
2124
+ }
2125
+ fromPanel(e) {
2126
+ return e.composedPath().includes(this.host);
2127
+ }
2128
+ closeTeachPop() {
2129
+ this.teachPop?.remove();
2130
+ this.teachPop = null;
2131
+ }
2132
+ openTeachPop(target) {
2133
+ this.closeTeachPop();
2134
+ const el = kindOf(target) === "radio" ? radioGroup(target)[0] : target;
2135
+ const fp = scanPage(document).find((f) => f.el === el);
2136
+ if (!fp) {
2137
+ this.toast("Bu alan görünür değil ya da devre dışı.", "err");
2138
+ return;
2139
+ }
2140
+ const s = load();
2141
+ const r = analyze();
2142
+ this.result = r;
2143
+ const existing = r.matches.find((m) => m.fp.el === el)?.def;
2144
+ const knownKeys = [.../* @__PURE__ */ new Set([...s.fields.map((f) => f.key), ...s.datasets.flatMap(datasetKeys)])].sort();
2145
+ const listId = "otofill-keys";
2146
+ const here = suggestPagePattern();
2147
+ const site = sitePattern();
2148
+ const pagesOf = existing?.pages[0] ?? (this.pattern || here);
2149
+ const keyIn = h("input", {
2150
+ type: "text",
2151
+ list: listId,
2152
+ value: existing?.key ?? (slug(fp.label || fp.name || fp.placeholder || fp.id) || ""),
2153
+ placeholder: "ör. musteri.tckn"
2154
+ });
2155
+ const titleIn = h("input", {
2156
+ type: "text",
2157
+ value: existing?.title ?? fp.label ?? "",
2158
+ placeholder: "Açıklama (isteğe bağlı)"
2159
+ });
2160
+ const pageSel = h("select", {}, h("option", {
2161
+ value: here,
2162
+ selected: pagesOf === here ? true : void 0
2163
+ }, "Bu sayfa"), h("option", {
2164
+ value: site,
2165
+ selected: pagesOf === site ? true : void 0
2166
+ }, "Tüm site"), pagesOf !== here && pagesOf !== site ? h("option", {
2167
+ value: pagesOf,
2168
+ selected: true
2169
+ }, pagesOf) : null);
2170
+ const save = () => {
2171
+ const key = keyIn.value.trim();
2172
+ if (!key) {
2173
+ keyIn.focus();
2174
+ return;
2175
+ }
2176
+ const def = this.defFrom(fp, key, titleIn.value.trim() || void 0, [pageSel.value], existing?.id);
2177
+ update((st) => {
2178
+ const i = st.fields.findIndex((f) => f.id === def.id);
2179
+ if (i >= 0) st.fields[i] = def;
2180
+ else st.fields.push(def);
2181
+ });
2182
+ this.closeTeachPop();
2183
+ this.flash(el);
2184
+ this.toast(`"${key}" ${existing ? "güncellendi" : "tanımlandı"}.`);
2185
+ };
2186
+ const rect = this.targetRectEl(el).getBoundingClientRect();
2187
+ const top = rect.bottom + 8 + 230 > window.innerHeight ? Math.max(8, rect.top - 238) : rect.bottom + 8;
2188
+ const left = Math.min(Math.max(8, rect.left), window.innerWidth - 310);
2189
+ this.teachPop = h("div", {
2190
+ class: "pop",
2191
+ style: {
2192
+ left: `${left}px`,
2193
+ top: `${top}px`
2194
+ },
2195
+ onKeydown: (e) => {
2196
+ if (e.key === "Enter") save();
2197
+ }
2198
+ }, h("div", {}, h("b", {}, existing ? "Alanı düzenle" : "Alan tanıt"), h("span", { class: "muted" }, ` · ${KIND_TR[fp.kind]}${fp.label ? ` · "${fp.label}"` : ""}`)), h("span", { class: "lbl" }, "Anahtar (veri setindeki sütun adı)"), keyIn, h("datalist", { id: listId }, knownKeys.map((k) => h("option", { value: k }))), h("span", { class: "lbl" }, "Açıklama"), titleIn, h("span", { class: "lbl" }, "Geçerli olduğu yer"), pageSel, h("div", { class: "row" }, existing ? h("button", {
2199
+ class: "btn dng",
2200
+ onClick: () => {
2201
+ removeField(existing.id);
2202
+ this.closeTeachPop();
2203
+ this.toast(`"${existing.key}" silindi.`);
2204
+ }
2205
+ }, "Sil") : null, h("span", { class: "grow" }), h("button", {
2206
+ class: "btn",
2207
+ onClick: () => this.closeTeachPop()
2208
+ }, "İptal"), h("button", {
2209
+ class: "btn pri",
2210
+ onClick: save
2211
+ }, "Kaydet")));
2212
+ this.layer.appendChild(this.teachPop);
2213
+ keyIn.focus();
2214
+ keyIn.select();
2215
+ }
2216
+ };
2217
+ // src/index.ts
2218
+ /**
2219
+ * @optona/otofill
2220
+ * Ctrl+Q ile açılan form doldurucu. Alanları siz tanıtırsınız, verileri siz girer ya da içe aktarırsınız.
2221
+ * Kütüphane şirketinize ait hiçbir veri içermez ve hiçbir yere istek atmaz.
2222
+ */
2223
+ var version = "0.1.0";
2224
+ var panel = null;
2225
+ /** Kısayolu dinlemeye başlar. Birden fazla çağrılırsa ilk çağrı geçerlidir. */
2226
+ function init(opts = {}) {
2227
+ if (panel || typeof document === "undefined") return;
2228
+ panel = new Panel({ hotkey: parseHotkey(opts.hotkey ?? "ctrl+q") });
2229
+ const mount = () => panel.mount();
2230
+ if (document.body) mount();
2231
+ else document.addEventListener("DOMContentLoaded", mount, { once: true });
2232
+ }
2233
+ function open() {
2234
+ init();
2235
+ panel.show();
2236
+ }
2237
+ function close() {
2238
+ panel?.hide();
2239
+ }
2240
+ function toggle() {
2241
+ init();
2242
+ panel.toggle();
2243
+ }
2244
+ /** Tıklayarak alan tanıtma modunu başlatır. */
2245
+ function teach() {
2246
+ init();
2247
+ panel.startTeach();
2248
+ }
2249
+ /**
2250
+ * Programatik doldurma (testlerde, konsolda). Veri seti adı ya da id'si, satır sırası ya da _label verilir.
2251
+ * Örn: Otofill.fill('Bireysel müşteriler', 0)
2252
+ */
2253
+ async function fill(dataset, row = 0) {
2254
+ const ds = load().datasets.find((d) => d.id === dataset || d.name === dataset);
2255
+ if (!ds) throw new Error(`Veri seti bulunamadı: ${dataset}`);
2256
+ const r = typeof row === "number" ? ds.rows[row] : ds.rows.find((x) => x._label === row || x._id === row);
2257
+ if (!r) throw new Error(`Satır bulunamadı: ${row}`);
2258
+ return fillRow(r);
2259
+ }
2260
+ export { BUNDLE_FORMAT, BUNDLE_VERSION, THRESHOLD, WEIGHTS, analyze, close, fill, fillElement, fillRow, fingerprint, init, io_exports as io, labelOf, matchFields, open, readElement, readRow, registerDriver, scanPage, score, setNativeValue, store_exports as store, teach, toggle, version };