-
-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathcombine.js
More file actions
568 lines (540 loc) · 22.7 KB
/
Copy pathcombine.js
File metadata and controls
568 lines (540 loc) · 22.7 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
(function () {
'use strict';
var MAX_LAYERS = 8;
var MAX_CONFIG_LENGTH = 100000;
var STORAGE_KEY = 'ssn.combine.v1';
var TRANSPARENT_PAGES = ['dock.html', 'featured.html', 'multi-alerts.html', 'minecraft.html'];
var encodedConfig = { json: '', hash: '' };
var layers = [];
var LAYOUT_FIELDS = ['width', 'height', 'left', 'top'];
var LAYOUT_LABELS = { width: 'Width', height: 'Height', left: 'Left', top: 'Top' };
var LAYOUT_DEFAULTS = { width: '100%', height: '100%', left: '0', top: '0' };
var nextId = 0;
var editor = document.getElementById('editor');
var list = document.getElementById('layers');
var output = document.getElementById('output');
var preview = document.getElementById('preview-stage');
var previewEmpty = document.getElementById('preview-empty');
var status = document.getElementById('status');
var linkPanel = document.getElementById('link-panel');
var linkField = document.getElementById('combined-url');
var qrPanel = document.getElementById('qr-panel');
var qrCode = document.getElementById('qr-code');
var saveStatus = document.getElementById('save-status');
function draftConfig() {
return { v: 1, layers: layers.map(function (layer) {
return { url: layer.url, interactive: layer.interactive, transparent: layer.transparent, layout: layer.layout };
}) };
}
function saveDraft(config) {
try {
var json = JSON.stringify(config);
if (json.length > MAX_CONFIG_LENGTH) throw new Error('Setup too large');
localStorage.setItem(STORAGE_KEY, json);
saveStatus.textContent = 'Saved in this browser. Scan the QR code to open on another device.';
} catch (_) {
saveStatus.textContent = 'Browser saving is unavailable. Keep your combined link or QR code.';
}
}
function loadDraft() {
try {
var json = localStorage.getItem(STORAGE_KEY);
if (!json || json.length > MAX_CONFIG_LENGTH) return null;
var config = JSON.parse(json);
validateConfig(config, false);
saveStatus.textContent = 'Restored your saved setup from this browser.';
return config;
} catch (_) {
return null;
}
}
function setStatus(message, error) {
status.textContent = message;
status.classList.toggle('error', !!error);
}
function makeLayer(url, interactive, transparent, layout) {
return { id: ++nextId, url: url || '', interactive: !!interactive, transparent: transparent !== false,
layout: Object.assign({}, layout || {}) };
}
function layoutValue(value, key) {
if (value === undefined || value.trim() === '') return LAYOUT_DEFAULTS[key];
var match = /^(-?(?:\d+(?:\.\d+)?|\.\d+))(px|%)?$/.exec(value.trim());
var size = match ? Number(match[1]) : NaN;
if (!isFinite(size) || Math.abs(size) > 16384 || ((key === 'width' || key === 'height') && size <= 0)) {
throw new Error(LAYOUT_LABELS[key] + ': enter ' + (key === 'width' || key === 'height' ? 'a positive size' : 'an offset') + ' in pixels or %, up to 16384 (for example, 450 or 100%).');
}
return String(size) + (match[2] || 'px');
}
function parseOverlayUrl(value) {
var url;
try {
url = new URL(value.trim());
} catch (_) {
throw new Error('Paste a complete link starting with https:// or http://.');
}
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
throw new Error('Use an https:// or http:// link.');
}
if (url.username || url.password) {
throw new Error('Use a link without a username or password before the site address.');
}
if (url.pathname.split('/').pop() === 'combine.html') {
throw new Error('Paste an individual overlay link rather than another combined link.');
}
if (location.protocol === 'https:' && url.protocol === 'http:') {
throw new Error('This page needs an https:// overlay link.');
}
return url;
}
function supportsTransparency(url) {
return TRANSPARENT_PAGES.some(function (name) {
var local = new URL(name, location.href);
return (url.origin === local.origin && url.pathname === local.pathname) ||
((url.hostname === 'socialstream.ninja' || url.hostname === 'www.socialstream.ninja') &&
(url.pathname === '/' + name || url.pathname === '/beta/' + name));
});
}
function frameUrl(layer) {
var url = parseOverlayUrl(layer.url);
if (layer.transparent && supportsTransparency(url)) {
url.searchParams.set('transparent', '1');
}
return url.href;
}
function collectConfig(reportError) {
var valid = true;
var firstInvalid = null;
var config = { v: 1, layers: [] };
layers.forEach(function (layer, index) {
var input = document.getElementById('url-' + layer.id);
var entry;
try {
var url = parseOverlayUrl(layer.url);
entry = { url: url.href, interactive: layer.interactive, transparent: layer.transparent };
config.layers.push(entry);
if (input) input.removeAttribute('aria-invalid');
} catch (error) {
valid = false;
if (reportError && !firstInvalid) {
firstInvalid = input;
setStatus('Layer ' + (index + 1) + ': ' + error.message, true);
}
if (reportError && input) input.setAttribute('aria-invalid', 'true');
}
var layout = {};
LAYOUT_FIELDS.forEach(function (key) {
var field = document.getElementById(key + '-' + layer.id);
try {
layoutValue(layer.layout[key], key);
if (layer.layout[key] && layer.layout[key].trim()) layout[key] = layer.layout[key].trim();
if (field) field.removeAttribute('aria-invalid');
} catch (error) {
valid = false;
if (reportError && !firstInvalid) {
firstInvalid = field;
document.getElementById('layout-' + layer.id).open = true;
setStatus('Layer ' + (index + 1) + ': ' + error.message, true);
}
if (reportError && field) field.setAttribute('aria-invalid', 'true');
}
});
if (entry && Object.keys(layout).length) entry.layout = layout;
});
if (firstInvalid) firstInvalid.focus();
if (JSON.stringify(config).length > MAX_CONFIG_LENGTH) {
if (reportError) setStatus('These overlay links are too long. Use shorter links or fewer layers.', true);
valid = false;
}
return valid ? config : null;
}
// Compress the complete layout for easier QR transfer; no server stores the links.
function configHash(config) {
var json = JSON.stringify(config);
if (json === encodedConfig.json) return encodedConfig.hash;
var hash = encodeURIComponent(json);
if (window.pako) {
var compressed = pako.deflate(json);
var binary = '';
for (var i = 0; i < compressed.length; i++) binary += String.fromCharCode(compressed[i]);
hash = 'v1=' + btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
encodedConfig = { json: json, hash: hash };
return hash;
}
function combinedUrl(config, edit) {
var url = new URL(location.href);
url.search = edit ? '?edit=1' : '';
url.hash = configHash(config);
return url.href;
}
function updateLinks() {
var config = collectConfig(false);
linkPanel.hidden = !config;
linkField.value = config ? combinedUrl(config, false) : '';
['open-link', 'edit-link'].forEach(function (id) {
var link = document.getElementById(id);
if (config) link.href = combinedUrl(config, id === 'edit-link');
else link.removeAttribute('href');
});
return config;
}
function changed() {
preview.textContent = '';
previewEmpty.hidden = false;
qrPanel.hidden = true;
qrCode.textContent = '';
setStatus('');
saveDraft(draftConfig());
var config = updateLinks();
// Keep an editable shared link current too: reloading must not restore the
// old fragment over a newer autosaved draft.
history.replaceState(null, '', config ? combinedUrl(config, true) : location.pathname + '?edit=1');
}
function button(text, label, handler) {
var element = document.createElement('button');
element.type = 'button';
element.textContent = text;
element.setAttribute('aria-label', label);
element.addEventListener('click', handler);
return element;
}
function option(layer, key, text) {
var label = document.createElement('label');
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = layer[key];
checkbox.dataset.option = key;
checkbox.addEventListener('change', function () {
layer[key] = checkbox.checked;
changed();
});
label.appendChild(checkbox);
label.appendChild(document.createTextNode(text));
return label;
}
function moveLayer(index, offset) {
var layer = layers.splice(index, 1)[0];
layers.splice(index + offset, 0, layer);
renderEditor();
changed();
document.getElementById('url-' + layer.id).focus();
}
function renderEditor() {
list.textContent = '';
layers.forEach(function (layer, index) {
var row = document.createElement('li');
row.className = 'layer';
var header = document.createElement('div');
header.className = 'layer-header';
var title = document.createElement('span');
title.className = 'layer-title';
title.textContent = 'Layer ' + (index + 1) + (index === 0 ? ' · Bottom' : index === layers.length - 1 ? ' · Top' : '');
var tools = document.createElement('div');
tools.className = 'layer-tools';
var lower = button('↑', 'Move layer ' + (index + 1) + ' behind', function () { moveLayer(index, -1); });
var higher = button('↓', 'Move layer ' + (index + 1) + ' in front', function () { moveLayer(index, 1); });
lower.disabled = index === 0;
higher.disabled = index === layers.length - 1;
var remove = button('Remove', 'Remove layer ' + (index + 1), function () {
layers.splice(index, 1);
renderEditor();
changed();
document.getElementById('url-' + layers[Math.min(index, layers.length - 1)].id).focus();
});
remove.disabled = layers.length === 1;
tools.appendChild(lower);
tools.appendChild(higher);
tools.appendChild(remove);
header.appendChild(title);
header.appendChild(tools);
row.appendChild(header);
var label = document.createElement('label');
label.className = 'url-label';
label.htmlFor = 'url-' + layer.id;
label.textContent = 'Overlay URL';
var input = document.createElement('input');
input.id = label.htmlFor;
input.className = 'url-input';
input.type = 'url';
input.autocomplete = 'off';
input.spellcheck = false;
input.placeholder = index === 0 ? 'Paste your chat URL' : 'Paste your alerts or other overlay URL';
input.value = layer.url;
input.addEventListener('input', function () {
layer.url = input.value;
changed();
});
row.appendChild(label);
row.appendChild(input);
var options = document.createElement('div');
options.className = 'layer-options';
options.appendChild(option(layer, 'transparent', 'Transparent SSN background'));
options.appendChild(option(layer, 'interactive', 'Allow taps and scrolling on this layer'));
row.appendChild(options);
var placement = document.createElement('details');
placement.id = 'layout-' + layer.id;
placement.className = 'layer-layout';
placement.open = Object.keys(layer.layout).some(function (key) { return !!layer.layout[key]; });
var summary = document.createElement('summary');
summary.textContent = 'Size and position';
placement.appendChild(summary);
var hint = document.createElement('p');
hint.className = 'hint';
hint.id = 'layout-hint-' + layer.id;
hint.textContent = 'Use pixels (450) or percentages (100%). Blank width and height fill the browser. Left and top offset the layer from the top-left corner; blank means 0.';
placement.appendChild(hint);
var fields = document.createElement('div');
fields.className = 'size-fields';
LAYOUT_FIELDS.forEach(function (key) {
var fieldLabel = document.createElement('label');
fieldLabel.textContent = LAYOUT_LABELS[key];
var field = document.createElement('input');
field.id = key + '-' + layer.id;
fieldLabel.htmlFor = field.id;
field.type = 'text';
field.className = 'size-input';
field.placeholder = LAYOUT_DEFAULTS[key];
field.value = layer.layout[key] || '';
field.setAttribute('aria-describedby', hint.id);
field.addEventListener('input', function () {
layer.layout[key] = field.value;
changed();
});
fieldLabel.appendChild(field);
fields.appendChild(fieldLabel);
});
placement.appendChild(fields);
var reset = button('Reset to fullscreen', 'Reset layer ' + (index + 1) + ' to fullscreen', function () {
layer.layout = {};
LAYOUT_FIELDS.forEach(function (key) {
var field = document.getElementById(key + '-' + layer.id);
field.value = '';
field.removeAttribute('aria-invalid');
});
changed();
});
reset.className = 'layout-reset';
placement.appendChild(reset);
row.appendChild(placement);
list.appendChild(row);
});
document.getElementById('add-layer').disabled = layers.length >= MAX_LAYERS;
}
function mountFrames(target, config) {
target.textContent = '';
config.layers.forEach(function (layer, index) {
var frame = document.createElement('iframe');
frame.className = 'overlay-frame' + (layer.interactive ? '' : ' pass-through');
frame.title = 'Overlay layer ' + (index + 1) + ': ' + new URL(layer.url).hostname;
frame.style.zIndex = String(index);
if (layer.layout) {
LAYOUT_FIELDS.forEach(function (key) {
frame.style[key] = layoutValue(layer.layout[key], key);
});
}
frame.setAttribute('allow', 'autoplay; fullscreen');
frame.setAttribute('referrerpolicy', 'no-referrer');
frame.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation allow-downloads');
if (!layer.interactive) frame.tabIndex = -1;
frame.src = frameUrl(layer);
target.appendChild(frame);
});
}
function validateConfig(config, checkUrls) {
if (!config || config.v !== 1 || !Array.isArray(config.layers) || !config.layers.length || config.layers.length > MAX_LAYERS) {
throw new Error('This combined link needs between 1 and ' + MAX_LAYERS + ' overlay URLs.');
}
config.layers.forEach(function (layer) {
if (!layer || typeof layer.url !== 'string' || typeof layer.interactive !== 'boolean' || typeof layer.transparent !== 'boolean') {
throw new Error('This combined link contains an invalid layer.');
}
if (checkUrls) parseOverlayUrl(layer.url);
if (layer.layout !== undefined) {
if (!layer.layout || typeof layer.layout !== 'object' || Array.isArray(layer.layout)) {
throw new Error('This combined link contains an invalid layer layout.');
}
LAYOUT_FIELDS.forEach(function (key) {
if (layer.layout[key] !== undefined && typeof layer.layout[key] !== 'string') {
throw new Error('This combined link contains an invalid layer size or position.');
}
if (checkUrls) layoutValue(layer.layout[key], key);
});
}
});
}
function decodeConfig(hash) {
if (hash.indexOf('v1=') !== 0) return decodeURIComponent(hash);
if (!window.pako) throw new Error('The link decoder could not load. Refresh the page and try again.');
var binary = atob(hash.slice(3).replace(/-/g, '+').replace(/_/g, '/'));
var bytes = new Uint8Array(binary.length);
for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
var json = '';
var inflater = new pako.Inflate({ to: 'string', chunkSize: 8192 });
inflater.onData = function (chunk) {
if (json.length + chunk.length > MAX_CONFIG_LENGTH) throw new Error('Setup too large');
json += chunk;
};
inflater.push(bytes, true);
if (inflater.err || !inflater.ended) throw new Error('Invalid compressed link');
return json;
}
function loadConfig() {
if (!location.hash || location.hash === '#') return null;
if (location.hash.length > MAX_CONFIG_LENGTH) throw new Error('This combined link is too long.');
var config;
try {
config = JSON.parse(decodeConfig(location.hash.slice(1)));
} catch (_) {
throw new Error('This combined link is incomplete or invalid. Paste your overlay URLs below to rebuild it.');
}
validateConfig(config, true);
return config;
}
function initialize() {
var config = null;
var errorMessage = '';
try { config = loadConfig(); }
catch (error) { errorMessage = error.message; }
var editing = !config || new URLSearchParams(location.search).has('edit');
document.documentElement.classList.toggle('viewing', !editing);
document.body.classList.toggle('editing', editing);
editor.hidden = !editing;
output.hidden = editing;
output.textContent = '';
preview.textContent = '';
previewEmpty.hidden = false;
qrPanel.hidden = true;
if (config) saveDraft(config);
if (!editing) {
mountFrames(output, config);
return;
}
var draft = config || loadDraft();
layers = draft ? draft.layers.map(function (layer) {
return makeLayer(layer.url, layer.interactive, layer.transparent, layer.layout);
}) : [makeLayer('', true), makeLayer('', false)];
renderEditor();
resizePreview();
updateLinks();
setStatus(errorMessage, !!errorMessage);
}
function resizePreview() {
var widthInput = document.getElementById('preview-width');
var heightInput = document.getElementById('preview-height');
var valid = true;
[widthInput, heightInput].forEach(function (input) {
var size = Number(input.value);
if (!Number.isInteger(size) || size < 1 || size > 16384) {
input.setAttribute('aria-invalid', 'true');
valid = false;
} else input.removeAttribute('aria-invalid');
});
if (!valid) return false;
var width = Number(widthInput.value);
var height = Number(heightInput.value);
var box = document.getElementById('preview');
var scale = box.clientWidth / width;
box.style.height = (height * scale + 2) + 'px';
preview.style.width = width + 'px';
preview.style.height = height + 'px';
preview.style.transform = 'scale(' + scale + ')';
return true;
}
['preview-width', 'preview-height'].forEach(function (id) {
document.getElementById(id).addEventListener('input', resizePreview);
});
window.addEventListener('resize', resizePreview);
document.getElementById('add-layer').addEventListener('click', function () {
if (layers.length >= MAX_LAYERS) return;
var layer = makeLayer('', false);
layers.push(layer);
renderEditor();
changed();
document.getElementById('url-' + layer.id).focus();
});
document.getElementById('clear-saved').addEventListener('click', function () {
try {
localStorage.removeItem(STORAGE_KEY);
saveStatus.textContent = 'Saved setup cleared.';
} catch (_) {
saveStatus.textContent = 'Browser storage could not be cleared.';
}
layers = [makeLayer('', true), makeLayer('', false)];
history.replaceState(null, '', location.pathname);
renderEditor();
preview.textContent = '';
previewEmpty.hidden = false;
qrPanel.hidden = true;
updateLinks();
setStatus('');
document.getElementById('url-' + layers[0].id).focus();
});
document.getElementById('show-qr').addEventListener('click', function () {
var config = collectConfig(true);
if (!config) return;
updateLinks();
qrCode.textContent = '';
qrPanel.hidden = false;
var qrStatus = document.getElementById('qr-status');
try {
if (!window.QRCode) throw new Error('QR library unavailable');
var qr = new QRCode(document.createElement('div'), { text: linkField.value, width: 320, height: 320,
colorDark: '#000000', colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.M });
// Use the bundled encoder's matrix with whole-pixel cells and a four-cell
// quiet zone. Fractional canvas cells can be hard for phone cameras to read.
var model = qr._oQRCode;
var count = model.getModuleCount();
var cell = Math.max(1, Math.floor(Math.min(384, qrPanel.clientWidth) / (count + 8)));
var canvas = document.createElement('canvas');
canvas.width = canvas.height = (count + 8) * cell;
var context = canvas.getContext('2d');
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = '#000';
for (var row = 0; row < count; row++) {
for (var column = 0; column < count; column++) {
if (model.isDark(row, column)) context.fillRect((column + 4) * cell, (row + 4) * cell, cell, cell);
}
}
qrCode.appendChild(canvas);
qrStatus.textContent = 'Bookmark the combined view on your phone to reopen it later. Generate a new code after changing the layout.';
setStatus('QR code ready.');
} catch (_) {
qrCode.textContent = '';
qrStatus.textContent = 'A QR code could not be made for this link. Copy the combined link instead, or use fewer or shorter overlay URLs.';
setStatus('Use the combined link below to transfer this setup.');
}
});
document.getElementById('preview-button').addEventListener('click', function () {
var config = collectConfig(true);
if (!config) return;
if (!resizePreview()) {
setStatus('Enter whole preview dimensions between 1 and 16384 pixels.', true);
document.querySelector('.preview-size [aria-invalid="true"]').focus();
return;
}
mountFrames(preview, config);
previewEmpty.hidden = true;
setStatus('Preview opened. Live overlays may stay empty until a message or alert arrives.');
});
document.getElementById('copy-link').addEventListener('click', async function () {
var config = collectConfig(true);
if (!config) return;
updateLinks();
var value = linkField.value;
try {
if (!navigator.clipboard || !navigator.clipboard.writeText) throw new Error('Clipboard unavailable');
await navigator.clipboard.writeText(value);
setStatus('Copied. Open this link on your phone or paste it into a browser source.');
} catch (_) {
linkField.focus();
linkField.select();
linkField.setSelectionRange(0, value.length);
var copied = false;
try { copied = document.execCommand('copy'); } catch (_) {}
setStatus(copied ? 'Combined link copied.' : 'Select and copy the combined link below.');
}
});
window.addEventListener('hashchange', initialize);
initialize();
})();