all repos — NoPaste @ eb7f87d6aa4f284754d7054a9e8c40ea65ca718e

Resurrected - The PussTheCat.org fork of NoPaste

index.js (view raw)

  1const blob = new Blob(['importScripts("https://cdn.jsdelivr.net/npm/lzma@2.3.2/src/lzma_worker.min.js");']);
  2const lzma = new LZMA(window.URL.createObjectURL(blob));
  3
  4let editor = null;
  5let select = null;
  6let clipboard = null;
  7let statsEl = null;
  8
  9const init = () => {
 10    initCodeEditor();
 11    initLangSelector();
 12    initCode();
 13    initClipboard();
 14};
 15
 16const initCodeEditor = () => {
 17    const readOnly = new URLSearchParams(window.location.search).has('readonly');
 18    CodeMirror.modeURL = 'https://cdn.jsdelivr.net/npm/codemirror@5.52.0/mode/%N/%N.js';
 19    editor = new CodeMirror(document.getElementById('editor'), {
 20        lineNumbers: true,
 21        theme: 'dracula',
 22        readOnly: readOnly,
 23        scrollbarStyle: 'simple',
 24    });
 25    if (readOnly) {
 26        document.body.classList.add('readonly');
 27    }
 28
 29    statsEl = document.getElementById('stats');
 30    editor.on('change', () => {
 31        statsEl.innerHTML = `Length: ${editor.getValue().length} |  Lines: ${editor['doc'].size}`;
 32    });
 33};
 34
 35const initLangSelector = () => {
 36    select = new SlimSelect({
 37        select: '#language',
 38        data: CodeMirror.modeInfo.map((e) => ({
 39            text: e.name,
 40            value: slugify(e.name),
 41            data: { mime: e.mime, mode: e.mode },
 42        })),
 43        showContent: 'down',
 44        onChange: (e) => {
 45            const language = e.data || { mime: null, mode: null };
 46            editor.setOption('mode', language.mime);
 47            CodeMirror.autoLoadMode(editor, language.mode);
 48        },
 49    });
 50
 51    select.set(decodeURIComponent(new URLSearchParams(window.location.search).get('lang') || 'plain-text'));
 52};
 53
 54const initCode = () => {
 55    const base64 = location.pathname.substr(1) || location.hash.substr(1);
 56    if (base64.length === 0) {
 57        return;
 58    }
 59    decompress(base64, (code, err) => {
 60        if (err) {
 61            alert('Failed to decompress data: ' + err);
 62            return;
 63        }
 64        editor.setValue(code);
 65    });
 66};
 67
 68const initClipboard = () => {
 69    clipboard = new ClipboardJS('.clipboard');
 70    clipboard.on('success', () => {
 71        hideCopyBar(true);
 72    });
 73};
 74
 75const generateLink = (mode) => {
 76    const data = editor.getValue();
 77    compress(data, (base64, err) => {
 78        if (err) {
 79            alert('Failed to compress data: ' + err);
 80            return;
 81        }
 82        const url = buildUrl(base64, mode);
 83        statsEl.innerHTML = `Data length: ${data.length} |  Link length: ${
 84            url.length
 85        } | Compression ratio: ${Math.round((100 * url.length) / data.length)}%`;
 86
 87        showCopyBar(url);
 88    });
 89};
 90
 91// Open the "Copy" bar and select the content
 92const showCopyBar = (dataToCopy) => {
 93    const linkInput = document.getElementById('copy-link');
 94    linkInput.value = dataToCopy;
 95    linkInput.setSelectionRange(0, dataToCopy.length);
 96    document.getElementById('copy').classList.remove('hidden');
 97};
 98
 99// Close the "Copy" bar
100const hideCopyBar = (success) => {
101    const copyButton = document.getElementById('copy-btn');
102    const copyBar = document.getElementById('copy');
103    if (!success) {
104        copyBar.classList.add('hidden');
105        return;
106    }
107    copyButton.innerText = 'Copied !';
108    setTimeout(() => {
109        copyBar.classList.add('hidden');
110        copyButton.innerText = 'Copy';
111    }, 800);
112};
113
114// Build a shareable URL
115const buildUrl = (rawData, mode) => {
116    const url = `${location.protocol}//${location.host}/` + rawData + `?lang=${encodeURIComponent(select.selected())}`;
117    if (mode === 'markdown') {
118        return `[NoPaste snippet](${url})`;
119    }
120    if (mode === 'iframe') {
121        const height = document.getElementsByClassName('CodeMirror-sizer')[0].clientHeight + 8;
122        return `<iframe width="100%" height="${height}" frameborder="0" src="${url}&readonly"></iframe>`;
123    }
124    return url;
125};
126
127// Transform a compressed base64 string into a plain text string
128const decompress = (base64, cb) => {
129    const progressBar = document.getElementById('progress');
130
131    const req = new XMLHttpRequest();
132    req.open('GET', 'data:application/octet;base64,' + base64);
133    req.responseType = 'arraybuffer';
134    req.onload = (e) => {
135        lzma.decompress(
136            new Uint8Array(e.target.response),
137            (result, err) => {
138                progressBar.style.width = '0';
139                cb(result, err);
140            },
141            (progress) => {
142                progressBar.style.width = 100 * progress + '%';
143            }
144        );
145    };
146    req.send();
147};
148
149// Transform a plain text string into a compressed base64 string
150const compress = (str, cb) => {
151    const progressBar = document.getElementById('progress');
152
153    lzma.compress(
154        str,
155        1,
156        (compressed, err) => {
157            if (err) {
158                progressBar.style.width = '0';
159                cb(compressed, err);
160                return;
161            }
162            const reader = new FileReader();
163            reader.onload = () => {
164                progressBar.style.width = '0';
165                cb(reader.result.substr(reader.result.indexOf(',') + 1));
166            };
167            reader.readAsDataURL(new Blob([new Uint8Array(compressed)]));
168        },
169        (progress) => {
170            progressBar.style.width = 100 * progress + '%';
171        }
172    );
173};
174
175const slugify = (str) =>
176    str
177        .toString()
178        .toLowerCase()
179        .replace(/\s+/g, '-')
180        .replace(/\+/g, '-p')
181        .replace(/#/g, '-sharp')
182        .replace(/[^\w\-]+/g, '');
183
184/* Only for tests purposes */
185const testAllModes = () => {
186    for (const [index, language] of Object.entries(CodeMirror.modeInfo)) {
187        setTimeout(() => {
188            console.info(language.name);
189            select.set(slugify(language.name));
190        }, 1000 * index);
191    }
192};
193
194init();