all repos — NoPaste @ af0c4eef8ec957f75c58417e0f3024c89b836bd1

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.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 =
117        `${location.protocol}//${location.host}${location.pathname}` +
118        `?lang=${encodeURIComponent(select.selected())}` +
119        (mode === 'iframe' ? '&readonly' : '') +
120        `#${rawData}`;
121    if (mode === 'markdown') {
122        return `[NoPaste snippet](${url})`;
123    }
124    if (mode === 'iframe') {
125        const height = document.getElementsByClassName('CodeMirror-sizer')[0].clientHeight + 8;
126        return `<iframe width="100%" height="${height}" frameborder="0" src="${url}"></iframe>`;
127    }
128    return url;
129};
130
131// Transform a compressed base64 string into a plain text string
132const decompress = (base64, cb) => {
133    const progressBar = document.getElementById('progress');
134
135    const req = new XMLHttpRequest();
136    req.open('GET', 'data:application/octet;base64,' + base64);
137    req.responseType = 'arraybuffer';
138    req.onload = (e) => {
139        lzma.decompress(
140            new Uint8Array(e.target.response),
141            (result, err) => {
142                progressBar.style.width = '0';
143                cb(result, err);
144            },
145            (progress) => {
146                progressBar.style.width = 100 * progress + '%';
147            }
148        );
149    };
150    req.send();
151};
152
153// Transform a plain text string into a compressed base64 string
154const compress = (str, cb) => {
155    const progressBar = document.getElementById('progress');
156
157    lzma.compress(
158        str,
159        1,
160        (compressed, err) => {
161            if (err) {
162                progressBar.style.width = '0';
163                cb(compressed, err);
164                return;
165            }
166            const reader = new FileReader();
167            reader.onload = () => {
168                progressBar.style.width = '0';
169                cb(reader.result.substr(reader.result.indexOf(',') + 1));
170            };
171            reader.readAsDataURL(new Blob([new Uint8Array(compressed)]));
172        },
173        (progress) => {
174            progressBar.style.width = 100 * progress + '%';
175        }
176    );
177};
178
179const slugify = (str) =>
180    str
181        .toString()
182        .toLowerCase()
183        .replace(/\s+/g, '-')
184        .replace(/\+/g, '-p')
185        .replace(/#/g, '-sharp')
186        .replace(/[^\w\-]+/g, '');
187
188/* Only for tests purposes */
189const testAllModes = () => {
190    for (const [index, language] of Object.entries(CodeMirror.modeInfo)) {
191        setTimeout(() => {
192            console.info(language.name);
193            select.set(slugify(language.name));
194        }, 1000 * index);
195    }
196};
197
198init();