Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
3669 lines (3467 loc) · 156 KB
/
Copy pathscript.js
File metadata and controls
3669 lines (3467 loc) · 156 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(){
"use strict";
/* =========================================================================
DEFAULT SAVE — shown automatically on a visitor's first visit (before
any autosave exists in their browser). A deep clone is used as the
starting point so this constant is never mutated.
========================================================================= */
const DEFAULT_SAVE_DATA = {"name":"Save 1","version":"1.0","created":1783875699379,"updated":0,"instances":[],"items":[{"id":0,"text":"Water","emoji":"💧"},{"id":1,"text":"Fire","emoji":"🔥"},{"id":2,"text":"Wind","emoji":"🌬️"},{"id":3,"text":"Earth","emoji":"🌍"}]};
/* =========================================================================
STATE
========================================================================= */
const state = {
save: null, // {name, version, created, updated, instances, items}
filePath: null,
history: [], // undo stack of save snapshots (JSON strings)
future: [], // redo stack
selectedId: null, // currently inspected element id
selectedIds: new Set(),// multi-select for bulk ops
search: "",
filters: { dup:false, dead:false, first:false, unreachable:false, custom:false, noRecipe:false },
sort: { key: "id", dir: "asc" },
centerTab: "elements",
graph: {
nodes: new Map(), // id -> {x,y,vx,vy}
zoom: 1, panX: 0, panY: 0,
showLabels: true, showEmoji: true,
dragNode: null, panning: false, lastMouse: null,
selected: null,
width: 800, height: 300
},
darkmode: true,
lowEndMode: false, // when true, graph view is fully disabled and its space reclaimed
recipeFilterElement: null, // when set from inspector, filter recipe tab to this element
};
const BASE_ELEMENT_NAMES = new Set(["Water","Fire","Wind","Earth"]);
function clone(o){ return JSON.parse(JSON.stringify(o)); }
function uid(){ return Date.now().toString(36)+Math.random().toString(36).slice(2,7); }
/* =========================================================================
TOAST
========================================================================= */
function toast(msg, type){
const stack = document.getElementById("toast-stack");
const el = document.createElement("div");
el.className = "toast" + (type ? " "+type : "");
el.textContent = msg;
stack.appendChild(el);
setTimeout(()=>{ el.style.opacity="0"; el.style.transition="opacity .25s"; setTimeout(()=>el.remove(),260); }, 2600);
}
/* Global safety net: surface otherwise-silent errors instead of failing
invisibly. Existing try/catch blocks around specific operations (file
load, export, etc.) still handle their own errors first; this only
catches what falls outside them. */
window.addEventListener("error", (e)=>{
console.error("Unhandled error:", e.error || e.message);
toast("Something went wrong: " + ((e.error && e.error.message) || e.message || "unknown error"), "error");
});
window.addEventListener("unhandledrejection", (e)=>{
console.error("Unhandled promise rejection:", e.reason);
toast("Something went wrong: " + ((e.reason && e.reason.message) || String(e.reason)), "error");
});
/* =========================================================================
GZIP (DEFLATE) — minimal pure-JS implementation for decode + encode
We implement a raw DEFLATE decoder/encoder (stored + dynamic-free,
using fixed Huffman for encode and full inflate for decode) wrapped
in gzip framing, since no external libraries are allowed.
We prefer native CompressionStream/DecompressionStream ("gzip") when
available (modern Chrome/Edge/Firefox/Safari) and fall back to a
pure-JS implementation otherwise.
========================================================================= */
const GZ = (function(){
async function nativeAvailable(){
return typeof window.DecompressionStream === "function" && typeof window.CompressionStream === "function";
}
async function gunzipNative(u8){
const ds = new DecompressionStream("gzip");
const stream = new Blob([u8]).stream().pipeThrough(ds);
const buf = await new Response(stream).arrayBuffer();
return new Uint8Array(buf);
}
async function gzipNative(u8){
const cs = new CompressionStream("gzip");
const stream = new Blob([u8]).stream().pipeThrough(cs);
const buf = await new Response(stream).arrayBuffer();
return new Uint8Array(buf);
}
/* ---------------- Pure JS fallback: INFLATE ---------------- */
function inflateRaw(data, startOffset){
let pos = startOffset*8; // bit position
const out = [];
function getBit(){
const byteIndex = pos >>> 3;
const bit = (data[byteIndex] >>> (pos & 7)) & 1;
pos++;
return bit;
}
function getBits(n){
let v = 0;
for(let i=0;i<n;i++) v |= getBit() << i;
return v;
}
function alignByte(){ pos = (pos + 7) & ~7; }
// Build Huffman decode table from code lengths array
function buildHuffman(lengths){
const maxBits = Math.max(0, ...lengths);
const blCount = new Array(maxBits+1).fill(0);
for(const l of lengths) if(l>0) blCount[l]++;
const nextCode = new Array(maxBits+1).fill(0);
let code = 0;
for(let bits=1; bits<=maxBits; bits++){
code = (code + blCount[bits-1]) << 1;
nextCode[bits] = code;
}
const codes = new Array(lengths.length).fill(0);
for(let n=0;n<lengths.length;n++){
const len = lengths[n];
if(len>0){ codes[n] = nextCode[len]; nextCode[len]++; }
}
// map: for decoding, build a tree as nested object keyed by bit-string is slow;
// instead use a map from (len,code)->symbol via length-grouped dict for speed.
const table = new Map(); // key: len*100000+code -> symbol
for(let n=0;n<lengths.length;n++){
if(lengths[n]>0){
table.set(lengths[n]*1000000+codes[n], n);
}
}
return {table, maxBits};
}
function decodeSymbol(huff){
let code = 0, len = 0;
while(len < huff.maxBits+1){
code = (code<<1) | getBit();
len++;
const sym = huff.table.get(len*1000000+code);
if(sym !== undefined) return sym;
}
throw new Error("Invalid huffman code");
}
const LEN_BASE = [3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258];
const LEN_EXTRA= [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
const DIST_BASE= [1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577];
const DIST_EXTRA=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
let finalBlock = false;
while(!finalBlock){
finalBlock = getBit() === 1;
const btype = getBits(2);
if(btype === 0){
// stored
alignByte();
const byteIndex = pos>>>3;
const len = data[byteIndex] | (data[byteIndex+1]<<8);
pos += 32; // skip LEN and NLEN
const start = pos>>>3;
for(let i=0;i<len;i++) out.push(data[start+i]);
pos += len*8;
} else if(btype === 1 || btype === 2){
let litHuff, distHuff;
if(btype === 1){
// fixed huffman
const litLengths = new Array(288);
for(let i=0;i<144;i++) litLengths[i]=8;
for(let i=144;i<256;i++) litLengths[i]=9;
for(let i=256;i<280;i++) litLengths[i]=7;
for(let i=280;i<288;i++) litLengths[i]=8;
const distLengths = new Array(30).fill(5);
litHuff = buildHuffman(litLengths);
distHuff = buildHuffman(distLengths);
} else {
const hlit = getBits(5)+257;
const hdist = getBits(5)+1;
const hclen = getBits(4)+4;
const ORDER = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
const clLengths = new Array(19).fill(0);
for(let i=0;i<hclen;i++) clLengths[ORDER[i]] = getBits(3);
const clHuff = buildHuffman(clLengths);
const lengths = [];
while(lengths.length < hlit+hdist){
const sym = decodeSymbol(clHuff);
if(sym < 16){ lengths.push(sym); }
else if(sym === 16){
const rep = getBits(2)+3;
const prev = lengths[lengths.length-1];
for(let i=0;i<rep;i++) lengths.push(prev);
} else if(sym === 17){
const rep = getBits(3)+3;
for(let i=0;i<rep;i++) lengths.push(0);
} else {
const rep = getBits(7)+11;
for(let i=0;i<rep;i++) lengths.push(0);
}
}
const litLengths = lengths.slice(0, hlit);
const distLengths = lengths.slice(hlit, hlit+hdist);
litHuff = buildHuffman(litLengths);
distHuff = buildHuffman(distLengths);
}
while(true){
const sym = decodeSymbol(litHuff);
if(sym < 256){ out.push(sym); }
else if(sym === 256){ break; }
else {
const idx = sym-257;
const len = LEN_BASE[idx] + getBits(LEN_EXTRA[idx]);
const dsym = decodeSymbol(distHuff);
const dist = DIST_BASE[dsym] + getBits(DIST_EXTRA[dsym]);
const startIdx = out.length - dist;
for(let i=0;i<len;i++) out.push(out[startIdx+i]);
}
}
} else {
throw new Error("Unsupported block type");
}
}
return new Uint8Array(out);
}
function gunzipPureJS(u8){
if(u8[0] !== 0x1f || u8[1] !== 0x8b) throw new Error("Not a gzip file");
const flg = u8[3];
let offset = 10;
if(flg & 0x04){ const xlen = u8[offset] | (u8[offset+1]<<8); offset += 2+xlen; }
if(flg & 0x08){ while(u8[offset] !== 0) offset++; offset++; }
if(flg & 0x10){ while(u8[offset] !== 0) offset++; offset++; }
if(flg & 0x02){ offset += 2; }
return inflateRaw(u8, offset);
}
/* ---------------- Pure JS fallback: DEFLATE (store + fixed huffman) + GZIP wrap ---------------- */
function crc32(u8){
let c, crc = 0xFFFFFFFF;
const table = crc32.table || (crc32.table = (function(){
const t = new Uint32Array(256);
for(let n=0;n<256;n++){
c = n;
for(let k=0;k<8;k++) c = (c & 1) ? (0xEDB88320 ^ (c>>>1)) : (c>>>1);
t[n] = c;
}
return t;
})());
for(let i=0;i<u8.length;i++){
crc = table[(crc ^ u8[i]) & 0xFF] ^ (crc >>> 8);
}
return (crc ^ 0xFFFFFFFF) >>> 0;
}
// Simple deflate: emit stored blocks (type 0). Valid, decompressible DEFLATE,
// just without compression ratio benefits. This guarantees correctness.
function deflateStore(u8){
const blocks = [];
const MAXLEN = 65535;
let i = 0;
if(u8.length === 0){
// one empty final stored block
blocks.push({final:true, data:new Uint8Array(0)});
}
while(i < u8.length){
const remaining = u8.length - i;
const len = Math.min(MAXLEN, remaining);
const chunk = u8.subarray(i, i+len);
const final = (i+len) >= u8.length;
blocks.push({final, data:chunk});
i += len;
}
// bit writer
const bytes = [];
let bitBuf = 0, bitCount = 0;
function writeBit(b){
bitBuf |= (b&1) << bitCount;
bitCount++;
if(bitCount === 8){ bytes.push(bitBuf); bitBuf=0; bitCount=0; }
}
function writeBits(v,n){ for(let k=0;k<n;k++) writeBit((v>>>k)&1); }
function alignByte(){ if(bitCount>0){ bytes.push(bitBuf); bitBuf=0; bitCount=0; } }
for(const blk of blocks){
writeBit(blk.final ? 1:0);
writeBits(0,2); // type 0 = stored
alignByte();
const len = blk.data.length;
const nlen = (~len) & 0xFFFF;
bytes.push(len & 0xFF, (len>>>8)&0xFF, nlen & 0xFF, (nlen>>>8)&0xFF);
for(let k=0;k<blk.data.length;k++) bytes.push(blk.data[k]);
}
return new Uint8Array(bytes);
}
function gzipPureJS(u8){
const header = new Uint8Array([0x1f,0x8b,0x08,0x00,0,0,0,0,0,0xff]);
const deflated = deflateStore(u8);
const crc = crc32(u8);
const size = u8.length >>> 0;
const footer = new Uint8Array(8);
footer[0]=crc&0xFF; footer[1]=(crc>>>8)&0xFF; footer[2]=(crc>>>16)&0xFF; footer[3]=(crc>>>24)&0xFF;
footer[4]=size&0xFF; footer[5]=(size>>>8)&0xFF; footer[6]=(size>>>16)&0xFF; footer[7]=(size>>>24)&0xFF;
const result = new Uint8Array(header.length + deflated.length + footer.length);
result.set(header,0);
result.set(deflated, header.length);
result.set(footer, header.length+deflated.length);
return result;
}
async function gunzip(u8){
if(await nativeAvailable()){
try{ return await gunzipNative(u8); }
catch(e){ console.warn("native gunzip failed, falling back", e); }
}
return gunzipPureJS(u8);
}
async function gzip(u8){
if(await nativeAvailable()){
try{ return await gzipNative(u8); }
catch(e){ console.warn("native gzip failed, falling back", e); }
}
return gzipPureJS(u8);
}
return { gunzip, gzip };
})();
/* =========================================================================
SAVE FORMAT HELPERS
========================================================================= */
function newEmptySave(){
return { name:"New Save", version:"1.0", created:Date.now(), updated:Date.now(), instances:[], items:[] };
}
/* Sets or removes the "discovery": 1 flag on an item, matching Infinite Craft's
own save schema. When set, the key is positioned immediately before "recipes"
(rebuilding the object to control key order, since JS preserves insertion order
and JSON.stringify follows it). When unset, the key is removed entirely so
elements without the flag look exactly like the original save format. */
function setDiscoveryFlag(item, isFirst){
if(isFirst){
const rebuilt = {};
for(const k of Object.keys(item)){
if(k === "recipes" || k === "discovery") continue;
rebuilt[k] = item[k];
}
rebuilt.discovery = 1;
rebuilt.recipes = item.recipes || [];
for(const k of Object.keys(item)) delete item[k];
Object.assign(item, rebuilt);
} else {
delete item.discovery;
}
}
function itemsById(save){
const m = new Map();
for(const it of save.items) m.set(it.id, it);
return m;
}
function nextFreeId(save){
let max = -1;
for(const it of save.items) max = Math.max(max, it.id);
return max+1;
}
/* Build derived analysis of the save. Memoized: cached by (save reference)
and invalidated whenever the save is mutated (see markSaveDirty()). */
let _analysisCache = null;
let _analysisFor = null;
function markSaveDirty(){ _analysisCache = null; _analysisFor = null; _byIdCache = null; _byIdFor = null; }
let _byIdCache = null, _byIdFor = null;
const _origItemsById = itemsById;
itemsById = function(save){
if(save === _byIdFor && _byIdCache) return _byIdCache;
_byIdCache = _origItemsById(save);
_byIdFor = save;
return _byIdCache;
};
function analyze(save){
if(save === _analysisFor && _analysisCache) return _analysisCache;
const items = save.items;
const byId = itemsById(save);
const nameCount = new Map();
for(const it of items){
const key = it.text.trim().toLowerCase();
nameCount.set(key, (nameCount.get(key)||0)+1);
}
const ingredientUsage = new Map();
const usedAsResultBy = new Map();
let totalRecipes = 0;
const missingDeps = [];
// Reachability worklist: unsat[itemId:recipeIdx] = # missing ingredients still unreachable.
const roots = new Set();
const reachable = new Set();
const dep = new Map(); // ingredientId -> [{itemId, key}]
const unsat = new Map();
for(const it of items){
const recipes = it.recipes || [];
if(recipes.length === 0){
roots.add(it.id);
reachable.add(it.id);
}
for(let idx=0; idx<recipes.length; idx++){
const r = recipes[idx];
totalRecipes++;
const key = it.id + ":" + idx;
let missing = 0;
for(let k=0;k<r.length;k++){
const ingId = r[k];
ingredientUsage.set(ingId, (ingredientUsage.get(ingId)||0)+1);
if(!byId.has(ingId)){
missingDeps.push({itemId: it.id, ingredientId: ingId});
// treat missing-ingredient recipes as never-satisfiable
missing++;
} else {
if(!usedAsResultBy.has(ingId)) usedAsResultBy.set(ingId, new Set());
usedAsResultBy.get(ingId).add(it.id);
if(!dep.has(ingId)) dep.set(ingId, []);
dep.get(ingId).push({itemId: it.id, key});
missing++;
}
}
unsat.set(key, missing);
}
}
// BFS/worklist propagation of reachability
const queue = [...roots];
while(queue.length){
const id = queue.pop();
const deps = dep.get(id);
if(!deps) continue;
for(let d=0; d<deps.length; d++){
const info = deps[d];
if(reachable.has(info.itemId)) continue;
const c = unsat.get(info.key) - 1;
unsat.set(info.key, c);
if(c === 0){
reachable.add(info.itemId);
queue.push(info.itemId);
}
}
}
const unreachable = items.filter(it => !reachable.has(it.id) && it.recipes && it.recipes.length>0);
const deadEnds = items.filter(it => !ingredientUsage.has(it.id));
const duplicates = items.filter(it => nameCount.get(it.text.trim().toLowerCase()) > 1);
const noRecipeItems = items.filter(it => !it.recipes || it.recipes.length===0);
const firstDiscoveries = items.filter(it => it.discovery === 1 || BASE_ELEMENT_NAMES.has(it.text));
const customElements = items.filter(it => (!it.recipes || it.recipes.length===0) && !BASE_ELEMENT_NAMES.has(it.text) && it.discovery !== 1);
const usageList = [...ingredientUsage.entries()]
.map(([id,count]) => ({id, count, item: byId.get(id)}))
.filter(x=>x.item)
.sort((a,b)=>b.count-a.count);
const totalElements = items.length;
const avgRecipes = totalElements ? (totalRecipes/totalElements) : 0;
const result = {
byId, totalElements, totalRecipes, avgRecipes,
duplicates, deadEnds, unreachable, missingDeps, noRecipeItems,
firstDiscoveries, customElements, usageList, reachable, roots,
usedAsResultBy, ingredientUsage
};
_analysisCache = result;
_analysisFor = save;
return result;
}
/* =========================================================================
HISTORY (undo/redo)
========================================================================= */
function pushHistory(){
if(!state.save) return;
state.history.push(JSON.stringify(state.save));
if(state.history.length > 100) state.history.shift();
state.future = [];
markSaveDirty();
updateUndoRedoButtons();
}
function undo(){
if(state.history.length === 0) return;
if(!state.save) return;
state.future.push(JSON.stringify(state.save));
const prev = state.history.pop();
state.save = JSON.parse(prev);
markSaveDirty();
fullRender();
toast("Undid last change");
updateUndoRedoButtons();
autosave();
}
function redo(){
if(state.future.length === 0) return;
state.history.push(JSON.stringify(state.save));
const next = state.future.pop();
state.save = JSON.parse(next);
markSaveDirty();
fullRender();
toast("Redid change");
updateUndoRedoButtons();
autosave();
}
function updateUndoRedoButtons(){
document.getElementById("btn-undo").disabled = state.history.length===0;
document.getElementById("btn-redo").disabled = state.future.length===0;
}
function commit(label){
// call BEFORE mutation via pushHistory(); this is called AFTER mutation for bookkeeping
state.save.updated = Date.now();
markSaveDirty();
autosave();
}
/* =========================================================================
AUTOSAVE / LOCALSTORAGE
========================================================================= */
const LS_AUTOSAVE = "icse_autosave_v1";
const LS_BACKUPS = "icse_backups_v1";
const LS_THEME = "icse_theme_v1";
const LS_LOWEND = "icse_lowend_v1";
function autosave(){
try{
if(state.save) localStorage.setItem(LS_AUTOSAVE, JSON.stringify(state.save));
}catch(e){ console.warn("autosave failed", e); }
}
function loadAutosave(){
try{
const raw = localStorage.getItem(LS_AUTOSAVE);
if(raw) return JSON.parse(raw);
}catch(e){}
return null;
}
function getBackups(){
try{
const raw = localStorage.getItem(LS_BACKUPS);
return raw ? JSON.parse(raw) : [];
}catch(e){ return []; }
}
function saveBackups(list){
try{ localStorage.setItem(LS_BACKUPS, JSON.stringify(list)); }catch(e){
toast("Could not save backup (storage full?)", "error");
}
}
function createBackup(){
if(!state.save){ toast("Nothing to back up", "error"); return; }
const list = getBackups();
list.unshift({ id: uid(), at: Date.now(), name: state.save.name, data: state.save });
if(list.length > 20) list.pop();
saveBackups(list);
toast("Backup created");
renderBackupsModalIfOpen();
}
/* =========================================================================
FILE I/O
========================================================================= */
async function openFileObject(file){
try{
const buf = await file.arrayBuffer();
const u8 = new Uint8Array(buf);
let jsonBytes;
if(u8[0]===0x1f && u8[1]===0x8b){
jsonBytes = await GZ.gunzip(u8);
} else {
jsonBytes = u8; // allow loading raw JSON too
}
const text = new TextDecoder("utf-8").decode(jsonBytes);
const data = JSON.parse(text);
if(!data.items || !Array.isArray(data.items)) throw new Error("Not a recognized Infinite Craft save (missing items array)");
state.save = data;
markSaveDirty();
state.history = [];
state.future = [];
state.selectedId = null;
state.selectedIds.clear();
state.filePath = file.name;
fullRender();
toast("Loaded "+file.name, "success");
autosave();
}catch(e){
console.error(e);
toast("Failed to open file: "+e.message, "error");
}
}
async function exportIc(){
if(!state.save){ toast("Nothing to export", "error"); return; }
try{
const json = JSON.stringify(state.save);
const bytes = new TextEncoder().encode(json);
const gz = await GZ.gzip(bytes);
downloadBlob(new Blob([gz], {type:"application/octet-stream"}), (state.save.name||"save").replace(/[^a-z0-9_\- ]/gi,"_")+".ic");
toast("Exported .ic", "success");
}catch(e){
console.error(e);
toast("Export failed: "+e.message, "error");
}
}
function exportJson(){
if(!state.save){ toast("Nothing to export", "error"); return; }
const json = JSON.stringify(state.save, null, 2);
downloadBlob(new Blob([json], {type:"application/json"}), (state.save.name||"save").replace(/[^a-z0-9_\- ]/gi,"_")+".json");
toast("Exported JSON", "success");
}
function downloadBlob(blob, filename){
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(()=>{ document.body.removeChild(a); URL.revokeObjectURL(url); }, 200);
}
/* =========================================================================
MODAL SYSTEM
========================================================================= */
let _modalPreviouslyFocused = null;
function openModal({title, bodyHtml, footerButtons, wide, onMount}){
closeModal();
_modalPreviouslyFocused = document.activeElement;
const root = document.getElementById("modal-root");
const overlay = document.createElement("div");
overlay.className = "modal-overlay";
overlay.id = "active-modal-overlay";
overlay.innerHTML = `
<div class="modal ${wide?'wide':''}" role="dialog" aria-modal="true" aria-labelledby="modal-title-heading" tabindex="-1">
<div class="modal-header"><h3 id="modal-title-heading">${title}</h3><button class="modal-close" id="modal-close-x" aria-label="Close dialog">×</button></div>
<div class="modal-body" id="modal-body-content">${bodyHtml}</div>
<div class="modal-footer" id="modal-footer-content"></div>
</div>`;
root.appendChild(overlay);
const footer = overlay.querySelector("#modal-footer-content");
(footerButtons||[]).forEach(btn=>{
const b = document.createElement("button");
b.className = "tbtn" + (btn.primary?" primary":"") + (btn.danger?" danger":"");
b.textContent = btn.label;
b.onclick = btn.onClick;
footer.appendChild(b);
});
overlay.querySelector("#modal-close-x").onclick = closeModal;
overlay.addEventListener("mousedown", (e)=>{ if(e.target===overlay) closeModal(); });
if(onMount) onMount(overlay);
document.addEventListener("keydown", modalEscHandler);
document.addEventListener("keydown", modalFocusTrapHandler);
const modalEl = overlay.querySelector(".modal");
const focusable = modalEl.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
(focusable[0] || modalEl).focus();
}
function modalEscHandler(e){ if(e.key === "Escape") closeModal(); }
function modalFocusTrapHandler(e){
if(e.key !== "Tab") return;
const overlay = document.getElementById("active-modal-overlay");
if(!overlay) return;
const focusable = Array.from(overlay.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(el=>!el.disabled && el.offsetParent !== null);
if(focusable.length === 0) return;
const first = focusable[0], last = focusable[focusable.length-1];
if(e.shiftKey && document.activeElement === first){ e.preventDefault(); last.focus(); }
else if(!e.shiftKey && document.activeElement === last){ e.preventDefault(); first.focus(); }
}
function closeModal(){
const el = document.getElementById("active-modal-overlay");
if(el) el.remove();
document.removeEventListener("keydown", modalEscHandler);
document.removeEventListener("keydown", modalFocusTrapHandler);
if(_modalPreviouslyFocused && _modalPreviouslyFocused.focus) _modalPreviouslyFocused.focus();
_modalPreviouslyFocused = null;
}
const COMMON_EMOJI = ["💧","🔥","🌬️","🌍","🌫️","🌪️","🏖️","🌵","🌀","🌊","🌋","🏔️","💨","💩","🏝️","🏜️","🗿","🐫","🧩","🪐","☁️","🌧️","🌈","💥","✨","⚡","🌱","🌳","🪨","🧱","🏠","🚗","🐍","🐉","👽","🤖","💎","🪙","📦","🧪","🔮","🦠","🧬","🌑","🌕","☀️","⭐","🍄","🐦","🐟","🐛","🦋"];
/* =========================================================================
ELEMENT CRUD
========================================================================= */
function addElement(){
const autoId = nextFreeId(state.save);
openModal({
title: "Add Element",
bodyHtml: `
<label class="field-label">Name</label>
<div class="ingredient-picker">
<input class="field-input" id="f-name" placeholder="e.g. Lava" autocomplete="off">
<div class="ingredient-results" id="f-name-suggest" style="display:none;"></div>
</div>
<label class="field-label">Emoji</label>
<div class="emoji-input-row">
<input class="field-input" id="f-emoji" placeholder="🔥" maxlength="4">
<input class="field-input search-input" id="f-emoji-search" placeholder="search common emoji…">
</div>
<div class="emoji-picker-list" id="emoji-picker"></div>
<div class="small muted" style="margin-top:10px;">ID <code>#${autoId}</code> will be assigned automatically.</div>
<label class="field-label" style="display:flex;align-items:center;gap:8px;cursor:pointer;user-select:none;margin-top:14px;">
<input type="checkbox" id="f-first-discovery" style="cursor:pointer;width:16px;height:16px;">
<span>Mark as first discovery</span>
</label>
<div class="small muted">Adds <code>"discovery": 1</code> to this element in the save file.</div>
<label class="field-label" style="display:flex;align-items:center;gap:8px;cursor:pointer;user-select:none;margin-top:14px;">
<input type="checkbox" id="f-auto-recipe" checked style="cursor:pointer;width:16px;height:16px;">
<span>🔍 Auto-fetch recipe from InfiniBrowser API</span>
</label>
<div class="small muted">Same lookup as API Lookup, but applied automatically once the element is added.</div>
`,
footerButtons: [
{label:"Paste recipes instead", onClick: ()=>{ closeModal(); openImportRecipesModal(); }},
{label:"Cancel", onClick: closeModal},
{label:"Add Element", primary:true, onClick: async ()=>{
const name = document.getElementById("f-name").value.trim();
const emoji = document.getElementById("f-emoji").value.trim() || "❓";
const isFirst = document.getElementById("f-first-discovery").checked;
const autoRecipe = document.getElementById("f-auto-recipe").checked;
if(!name){ toast("Name is required","error"); return; }
const id = nextFreeId(state.save);
pushHistory();
const newItem = {id, text:name, emoji, recipes:[]};
if(isFirst) setDiscoveryFlag(newItem, true);
state.save.items.push(newItem);
commit();
fullRender();
closeModal();
toast("Added "+name, "success");
if(autoRecipe){
toast(`Looking up recipe for ${name} on InfiniBrowser…`);
await autoImportRecipeFor(name);
}
}}
],
onMount: (overlay)=>{
const picker = overlay.querySelector("#emoji-picker");
function renderPicker(filter){
picker.innerHTML = "";
COMMON_EMOJI.filter(e=>!filter || true).forEach(e=>{
const span = document.createElement("span");
span.textContent = e;
span.onclick = ()=>{ document.getElementById("f-emoji").value = e; };
picker.appendChild(span);
});
}
renderPicker();
const nameInput = overlay.querySelector("#f-name");
const nameSuggest = overlay.querySelector("#f-name-suggest");
wireInfiniBrowserAutocomplete(nameInput, nameSuggest, (name, emoji)=>{
nameInput.value = name;
if(emoji) document.getElementById("f-emoji").value = emoji;
});
nameInput.focus();
}
});
}
function editElement(id){
const it = state.save.items.find(x=>x.id===id);
if(!it) return;
const isFirstDiscovery = it.discovery === 1;
openModal({
title: "Edit Element",
bodyHtml: `
<label class="field-label">Name</label>
<input class="field-input" id="f-name" value="${escapeAttr(it.text)}">
<label class="field-label">Emoji</label>
<div class="emoji-input-row">
<input class="field-input" id="f-emoji" value="${escapeAttr(it.emoji)}" maxlength="4">
</div>
<div class="emoji-picker-list" id="emoji-picker"></div>
<label class="field-label">ID</label>
<input class="field-input" id="f-id" type="number" value="${it.id}">
<div class="small muted" style="margin-top:4px;">Changing the ID will update all recipes referencing it.</div>
<label class="field-label" style="display:flex;align-items:center;gap:8px;cursor:pointer;user-select:none;margin-top:14px;">
<input type="checkbox" id="f-first-discovery" ${isFirstDiscovery?'checked':''} style="cursor:pointer;width:16px;height:16px;">
<span>Mark as first discovery</span>
</label>
<div class="small muted">Adds <code>"discovery": 1</code> to this element in the save file (the flag Infinite Craft uses for elements you discovered first, before <code>recipes</code>).</div>
`,
footerButtons: [
{label:"Cancel", onClick: closeModal},
{label:"Save Changes", primary:true, onClick: ()=>{
const name = document.getElementById("f-name").value.trim();
const emoji = document.getElementById("f-emoji").value.trim() || "❓";
const newId = parseInt(document.getElementById("f-id").value, 10);
const isFirst = document.getElementById("f-first-discovery").checked;
if(!name){ toast("Name is required","error"); return; }
if(newId !== id && state.save.items.some(x=>x.id===newId)){ toast("ID already in use","error"); return; }
pushHistory();
if(newId !== id){
// update all recipe references across all items
for(const other of state.save.items){
for(const r of (other.recipes||[])){
for(let i=0;i<r.length;i++) if(r[i]===id) r[i]=newId;
}
}
it.id = newId;
}
it.text = name; it.emoji = emoji;
setDiscoveryFlag(it, isFirst);
commit();
if(state.selectedId === id) state.selectedId = newId;
fullRender();
closeModal();
toast("Saved changes", "success");
}},
],
onMount: (overlay)=>{
const picker = overlay.querySelector("#emoji-picker");
COMMON_EMOJI.forEach(e=>{
const span = document.createElement("span");
span.textContent = e;
span.onclick = ()=>{ document.getElementById("f-emoji").value = e; };
picker.appendChild(span);
});
document.getElementById("f-name").focus();
}
});
}
/* Removes any recipe (on any item) that uses one of the given ids as an
ingredient. Called automatically before removing elements so recipes
never point at ingredients that no longer exist. Returns how many
recipes were removed, for the toast message. */
function removeRecipesReferencing(ids){
const idSet = new Set(ids);
let removed = 0;
state.save.items.forEach(x=>{
if(!x.recipes || !x.recipes.length) return;
const before = x.recipes.length;
x.recipes = x.recipes.filter(r=>!r.some(rid=>idSet.has(rid)));
removed += before - x.recipes.length;
});
return removed;
}
/* Given a root id about to be deleted, finds every other element that would become
uncraftable as a result — i.e. every one of its recipes ends up referencing an
already-doomed id — applied transitively (doomed -> makes dependents doomed -> ...).
Elements with zero recipes to begin with (base/manual elements) are never doomed. */
function computeUnreachableCascade(rootId){
const doomed = new Set([rootId]);
let changed = true;
while(changed){
changed = false;
for(const it of state.save.items){
if(doomed.has(it.id)) continue;
if(!it.recipes || it.recipes.length===0) continue;
const stillCraftable = it.recipes.some(r=>!r.some(rid=>doomed.has(rid)));
if(!stillCraftable){ doomed.add(it.id); changed = true; }
}
}
doomed.delete(rootId);
return [...doomed];
}
function deleteElement(id, opts){
opts = opts || {};
const it = state.save.items.find(x=>x.id===id);
if(!it) return;
const usedIn = state.save.items.filter(x => (x.recipes||[]).some(r=>r.includes(id)));
const recipeCount = usedIn.reduce((n,x)=> n + x.recipes.filter(r=>r.includes(id)).length, 0);
const ownRecipeCount = (it.recipes||[]).length;
const cascadeItems = computeUnreachableCascade(id)
.map(cid=>state.save.items.find(x=>x.id===cid))
.filter(Boolean);
const bodyHtml = `
<p>Delete <strong>${escapeHtml(it.emoji)} ${escapeHtml(it.text)}</strong> (id ${it.id})? This cannot be undone except via Undo.</p>
<div class="section" style="margin-top:12px;display:flex;flex-direction:column;gap:8px;">
<label style="display:flex;align-items:center;gap:8px;opacity:.65;cursor:not-allowed;">
<span class="checkbox-cell"><input type="checkbox" checked disabled></span>
<span class="small">Remove its own recipe${ownRecipeCount===1?"":"s"} (${ownRecipeCount} — automatic, the element can't exist without it)</span>
</label>
<label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
<span class="checkbox-cell"><input type="checkbox" id="del-strip-refs" checked></span>
<span class="small">Remove ${recipeCount} recipe(s) elsewhere that use it as an ingredient${usedIn.length?` (${usedIn.length} element${usedIn.length===1?"":"s"})`:""}</span>
</label>
${cascadeItems.length ? `
<label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
<span class="checkbox-cell"><input type="checkbox" id="del-cascade"></span>
<span class="small">Also delete ${cascadeItems.length} element${cascadeItems.length===1?"":"s"} that would become uncraftable as a result</span>
</label>
<button class="btn-text" id="del-advanced-toggle" style="align-self:flex-start;margin-top:2px;">Advanced: review which elements ▾</button>
<div class="stat-list" id="del-advanced-list" style="max-height:220px;overflow-y:auto;display:none;">
${cascadeItems.map(x=>`<div class="stat-list-row">
<span class="k"><span class="checkbox-cell"><input type="checkbox" class="del-cascade-item" data-id="${x.id}" checked disabled></span> ${escapeHtml(x.emoji)} ${escapeHtml(x.text)}</span>
<span class="v muted">#${x.id}</span>
</div>`).join("")}
</div>` : ""}
</div>
`;
openModal({
title: "Delete Element",
wide: cascadeItems.length>0,
bodyHtml,
footerButtons: [
{label:"Cancel", onClick: closeModal},
{label:"Delete", danger:true, onClick: ()=>{
const stripRefs = document.getElementById("del-strip-refs")?.checked ?? true;
const cascadeOn = document.getElementById("del-cascade")?.checked ?? false;
const cascadeIds = cascadeOn
? [...document.querySelectorAll(".del-cascade-item")].filter(c=>c.checked).map(c=>Number(c.dataset.id))
: [];
pushHistory();
const toDelete = new Set([id, ...cascadeIds]);
const removedRecipes = stripRefs ? removeRecipesReferencing([...toDelete]) : 0;
state.save.items = state.save.items.filter(x=>!toDelete.has(x.id));
if(toDelete.has(state.selectedId)) state.selectedId = null;
commit();
fullRender();
closeModal();
const extra = toDelete.size>1 ? `, ${toDelete.size-1} dependent element(s)` : "";
toast("Deleted "+it.text+extra+(removedRecipes ? " and "+removedRecipes+" recipe(s)" : ""), "success");
}}
],
onMount: (overlay)=>{
const toggleBtn = overlay.querySelector("#del-advanced-toggle");
const list = overlay.querySelector("#del-advanced-list");
if(toggleBtn && list){
toggleBtn.onclick = ()=>{
const opening = list.style.display === "none";
list.style.display = opening ? "block" : "none";
toggleBtn.textContent = opening ? "Advanced: review which elements ▴" : "Advanced: review which elements ▾";
};
}
const cascadeCb = overlay.querySelector("#del-cascade");
if(cascadeCb){
cascadeCb.onchange = ()=>{
overlay.querySelectorAll(".del-cascade-item").forEach(c=>{ c.checked = cascadeCb.checked; c.disabled = !cascadeCb.checked; });
};
}
}
});
}
function bulkDelete(){
if(state.selectedIds.size===0){ toast("No elements selected","error"); return; }
const n = state.selectedIds.size;
openModal({
title: "Bulk Delete",
bodyHtml: `<p>Delete <strong>${n}</strong> selected element(s)? Any recipes using them will also be removed. This cannot be undone except via Undo.</p>`,
footerButtons: [
{label:"Cancel", onClick: closeModal},
{label:"Delete All", danger:true, onClick: ()=>{
pushHistory();
const removedRecipes = removeRecipesReferencing([...state.selectedIds]);
state.save.items = state.save.items.filter(x=>!state.selectedIds.has(x.id));
state.selectedIds.clear();
state.selectedId = null;
commit();
fullRender();
closeModal();
toast("Deleted "+n+" elements"+(removedRecipes ? " and "+removedRecipes+" recipe(s)" : ""), "success");
}}
]
});
}
/* =========================================================================
DEDUPE: merge elements that are 100% identical — same name text (exact,
case-sensitive, symbols included) AND same emoji. Looser near-duplicates
(different casing/emoji, the existing "Duplicate" tag) are left alone.
========================================================================= */
function findExactDuplicateGroups(save){
const groups = new Map(); // "text\u0001emoji" -> items[]
for(const it of save.items){
const key = it.text + "\u0001" + it.emoji;
if(!groups.has(key)) groups.set(key, []);
groups.get(key).push(it);
}
return [...groups.values()].filter(g=>g.length>1);
}
function recipePairKey(r){ return [...r].sort((a,b)=>a-b).join(","); }
function openDedupeModal(){
if(!state.save){ toast("Open or create a save file first", "error"); return; }
const groups = findExactDuplicateGroups(state.save);
if(groups.length===0){
toast("No exact duplicates found — every name+emoji is unique", "success");
return;
}
const totalLosers = groups.reduce((s,g)=>s+g.length-1, 0);
openModal({
title: "Dedupe Elements",
wide: true,
bodyHtml: `
<p class="small muted">Found <strong>${groups.length}</strong> set(s) of exact duplicates (same name, emoji, and symbols) — <strong>${totalLosers}</strong> element(s) will be merged away. The kept element in each set keeps its first-discovery flag and combined recipes; every recipe elsewhere that pointed at a merged-away id will be repointed automatically.</p>
<div class="stat-list" style="max-height:280px;overflow-y:auto;margin-top:10px;">
${groups.map(g=>{
const canonical = g.find(it=>it.discovery===1) || g.reduce((a,b)=>a.id<b.id?a:b);
const losers = g.filter(it=>it.id!==canonical.id);
return `<div class="stat-list-row" style="align-items:flex-start;">
<span class="k">${escapeHtml(canonical.emoji)} ${escapeHtml(canonical.text)}</span>
<span class="v muted">keep #${canonical.id}, merge ${losers.map(l=>"#"+l.id).join(", ")}</span>
</div>`;
}).join("")}