ninalanyon / Insert Multi-Item Context Menu with Settings

// ==UserScript==
// @name         Insert Multi-Item Context Menu with Settings
// @namespace    http://tampermonkey.net/
// @version      1.0,0
// @description  Ctrl + Right Click to insert items. Shows "Label: Value" in menu and settings.
// @author       Nina Lanyon
// @match        *://*/*
// @grant        GM_setValue
// @grant        GM_getValue
// @copyright 2026, Nina Lanyon (https://openuserjs.org/users/ninalanyon)
// @updateURL https://openuserjs.org/meta/ninalanyon/Insert_Multi-Item_Context_Menu_with_Settings.meta.js
// @downloadURL https://openuserjs.org/install/ninalanyon/Insert_Multi-Item_Context_Menu_with_Settings.user.js
// @license MIT
// ==/UserScript==

// Created with the assistance of Duck.ai.
(function () {
    'use strict';

    if (window.__multiItemContextMenuInitialized) return;
    window.__multiItemContextMenuInitialized = true;

    const defaultOptions = [
        { label: 'Date & Time', getValue: () => new Date().toLocaleString() },
        { label: 'Date Only', getValue: () => new Date().toLocaleDateString() },
        { label: 'Time Only', getValue: () => new Date().toLocaleTimeString() },
        { label: 'ISO Timestamp', getValue: () => new Date().toISOString() }
    ];

    let customEntries = loadCustomEntries();
    let lastFocusedElement = null;
    let editingIndex = null;

    const menu = document.createElement('div');
    Object.assign(menu.style, {
        position: 'fixed',
        zIndex: '2147483647',
        backgroundColor: '#fff',
        border: '1px solid #ccc',
        boxShadow: '2px 2px 5px rgba(0,0,0,0.2)',
        borderRadius: '4px',
        padding: '4px 0',
        display: 'none',
        cursor: 'default',
        fontFamily: 'Arial, sans-serif',
        fontSize: '13px',
        color: '#333',
        minWidth: '200px',
        maxWidth: '400px'
    });

    const settingsPanel = document.createElement('div');
    Object.assign(settingsPanel.style, {
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        zIndex: '2147483648',
        backgroundColor: '#fff',
        border: '1px solid #ccc',
        boxShadow: '0 0 15px rgba(0,0,0,0.3)',
        borderRadius: '8px',
        padding: '20px',
        display: 'none',
        fontFamily: 'Arial, sans-serif',
        color: '#333',
        width: '400px',
        maxWidth: 'calc(100vw - 40px)'
    });

    function loadCustomEntries() {
        const saved = GM_getValue('customEntries', []);
        return normalizeEntries(saved);
    }

    function normalizeEntries(value) {
        const entries = Array.isArray(value)
            ? value
            : value && Array.isArray(value.customEntries)
                ? value.customEntries
                : [];

        return entries
            .filter(entry =>
                entry &&
                typeof entry === 'object' &&
                typeof entry.label === 'string' &&
                (
                    typeof entry.format === 'string' ||
                    typeof entry.value === 'string' ||
                    typeof entry.value === 'number'
                )
            )
            .map(entry => {
                const normalized = {
                    label: entry.label
                };

                if (Object.prototype.hasOwnProperty.call(entry, 'format')) {
                    normalized.format = String(entry.format);
                } else {
                    normalized.value = String(entry.value);
                }

                return normalized;
            });
    }

    function saveCustomEntries() {
        GM_setValue('customEntries', customEntries);
    }

    function getEntryFormat(entry) {
        // Entries from older versions use "value".
        // New entries use "format".
        return Object.prototype.hasOwnProperty.call(entry, 'format')
            ? String(entry.format ?? '')
            : String(entry.value ?? '');
    }

    function getEntryValue(entry) {
        if (Object.prototype.hasOwnProperty.call(entry, 'format')) {
            return formatStrftime(entry.format);
        }

        // Preserve the behavior of older literal-value entries.
        return String(entry.value ?? '');
    }

    function pad(value, length = 2, character = '0') {
        return String(value).padStart(length, character);
    }

    function getDayOfYear(date) {
        const start = new Date(date.getFullYear(), 0, 1);
        const current = new Date(
            date.getFullYear(),
            date.getMonth(),
            date.getDate()
        );

        return Math.floor((current - start) / 86400000) + 1;
    }

    function getWeekNumber(date, firstDayOfWeek) {
        const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
        const dayOfYear = getDayOfYear(date);
        const offset = (firstDayOfYear.getDay() - firstDayOfWeek + 7) % 7;

        return Math.floor((dayOfYear + offset - 1) / 7);
    }

    function getIsoWeek(date) {
        const target = new Date(date);
        target.setHours(0, 0, 0, 0);

        const day = target.getDay() || 7;
        target.setDate(target.getDate() + 4 - day);

        const year = target.getFullYear();
        const yearStart = new Date(year, 0, 1);
        const week = Math.ceil(
            (((target - yearStart) / 86400000) + 1) / 7
        );

        return { year, week };
    }

    function getOrdinalDay(day) {
        const remainder100 = day % 100;

        if (remainder100 >= 11 && remainder100 <= 13) {
            return `${day}th`;
        }

        switch (day % 10) {
            case 1:
                return `${day}st`;
            case 2:
                return `${day}nd`;
            case 3:
                return `${day}rd`;
            default:
                return `${day}th`;
        }
    }

    function getTimezoneOffset(date) {
        const offset = -date.getTimezoneOffset();
        const sign = offset >= 0 ? '+' : '-';
        const absoluteOffset = Math.abs(offset);

        return `${sign}${pad(Math.floor(absoluteOffset / 60))}${pad(absoluteOffset % 60)}`;
    }

    function getTimezoneName(date) {
        try {
            const parts = new Intl.DateTimeFormat(undefined, {
                timeZoneName: 'short'
            }).formatToParts(date);

            return parts.find(part => part.type === 'timeZoneName')?.value || '';
        } catch {
            return '';
        }
    }

    function formatStrftime(format, date = new Date()) {
        const shortDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

        const longDays = [
            'Sunday',
            'Monday',
            'Tuesday',
            'Wednesday',
            'Thursday',
            'Friday',
            'Saturday'
        ];

        const shortMonths = [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
        ];

        const longMonths = [
            'January',
            'February',
            'March',
            'April',
            'May',
            'June',
            'July',
            'August',
            'September',
            'October',
            'November',
            'December'
        ];

        const isoWeek = getIsoWeek(date);
        const hour12 = (date.getHours() % 12) || 12;
        const isPm = date.getHours() >= 12;

        const replacements = {
            '%': '%',

            a: shortDays[date.getDay()],
            A: longDays[date.getDay()],

            b: shortMonths[date.getMonth()],
            B: longMonths[date.getMonth()],

            c: date.toLocaleString(),
            C: pad(Math.floor(date.getFullYear() / 100)),

            d: pad(date.getDate()),
            D: `${pad(date.getMonth() + 1)}/${pad(date.getDate())}/${pad(date.getFullYear() % 100)}`,

            // Nonstandard strftime-style extensions:
            // %-d = day without zero padding
            // %-m = month without zero padding
            // %o  = ordinal day of month
            '-d': date.getDate(),
            '-m': date.getMonth() + 1,
            o: getOrdinalDay(date.getDate()),

            // %e is the traditional space-padded day.
            e: String(date.getDate()).padStart(2, ' '),

            F: `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`,

            g: pad(isoWeek.year % 100),
            G: isoWeek.year,

            h: shortMonths[date.getMonth()],
            H: pad(date.getHours()),
            I: pad(hour12),
            j: pad(getDayOfYear(date), 3),
            k: String(date.getHours()).padStart(2, ' '),
            l: String(hour12).padStart(2, ' '),

            m: pad(date.getMonth() + 1),
            M: pad(date.getMinutes()),

            n: '\n',

            p: isPm ? 'PM' : 'AM',
            P: isPm ? 'pm' : 'am',

            r: `${pad(hour12)}:${pad(date.getMinutes())}:${pad(date.getSeconds())} ${isPm ? 'PM' : 'AM'}`,
            R: `${pad(date.getHours())}:${pad(date.getMinutes())}`,

            s: Math.floor(date.getTime() / 1000),
            S: pad(date.getSeconds()),

            t: '\t',
            T: `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`,

            u: date.getDay() === 0 ? 7 : date.getDay(),
            U: pad(getWeekNumber(date, 0)),
            V: pad(isoWeek.week),
            w: date.getDay(),
            W: pad(getWeekNumber(date, 1)),

            x: date.toLocaleDateString(),
            X: date.toLocaleTimeString(),

            y: pad(date.getFullYear() % 100),
            Y: date.getFullYear(),

            z: getTimezoneOffset(date),
            Z: getTimezoneName(date)
        };

        return String(format).replace(
            /%(-?[a-zA-Z%])/g,
            (match, code) => {
                return Object.prototype.hasOwnProperty.call(replacements, code)
                    ? String(replacements[code])
                    : match;
            }
        );
    }

    function createMenuItem(displayText, valueProvider) {
        const item = document.createElement('div');
        item.textContent = displayText;

        Object.assign(item.style, {
            padding: '6px 12px',
            cursor: 'default',
            userSelect: 'none',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
        });

        item.addEventListener('mouseenter', () => {
            item.style.backgroundColor = '#f0f0f0';
        });

        item.addEventListener('mouseleave', () => {
            item.style.backgroundColor = 'transparent';
        });

        item.addEventListener('click', event => {
            event.preventDefault();
            event.stopPropagation();

            insertTextAtCursor(valueProvider(), lastFocusedElement);
            hideMenu();
            lastFocusedElement = null;
        });

        menu.appendChild(item);
    }

    function rebuildMenu() {
        menu.replaceChildren();

        defaultOptions.forEach(option => {
            createMenuItem(
                `${option.label}: ${option.getValue()}`,
                option.getValue
            );
        });

        const separator = document.createElement('div');
        separator.textContent = '----------------------------------------';

        Object.assign(separator.style, {
            padding: '4px 12px',
            color: '#aaa',
            fontSize: '10px'
        });

        menu.appendChild(separator);

        customEntries.forEach(entry => {
            createMenuItem(
                `${entry.label}: ${getEntryValue(entry)}`,
                () => getEntryValue(entry)
            );
        });

        const settingsButton = document.createElement('div');
        settingsButton.textContent = '⚙️ Settings';

        Object.assign(settingsButton.style, {
            padding: '6px 12px',
            fontWeight: 'bold',
            color: '#0066cc',
            cursor: 'pointer'
        });

        settingsButton.addEventListener('mouseenter', () => {
            settingsButton.style.backgroundColor = '#f0f0f0';
        });

        settingsButton.addEventListener('mouseleave', () => {
            settingsButton.style.backgroundColor = 'transparent';
        });

        settingsButton.addEventListener('click', event => {
            event.preventDefault();
            event.stopPropagation();

            hideMenu();
            showSettings();
        });

        menu.appendChild(settingsButton);
    }

    function createSettingsButton(text, onClick) {
        const button = document.createElement('button');
        button.type = 'button';
        button.textContent = text;
        button.style.cursor = 'pointer';
        button.addEventListener('click', onClick);
        return button;
    }

    function showSettings() {
        const editingEntry = editingIndex === null
            ? null
            : customEntries[editingIndex];

        const currentLabel = editingEntry?.label ?? '';
        const currentFormat = editingEntry
            ? getEntryFormat(editingEntry)
            : '';

        settingsPanel.innerHTML = `
            <h3 style="margin-top:0">Menu Settings</h3>

            <div style="margin-bottom:10px">
                <input
                    id="set-label"
                    placeholder="Label"
                    value="${escapeAttribute(currentLabel)}"
                    style="width:120px; margin-bottom:5px"
                >
                <br>

                <input
                    id="set-format"
                    placeholder="strftime format, e.g. %Y-%m-%d %H:%M:%S"
                    value="${escapeAttribute(currentFormat)}"
                    style="width:340px; margin-bottom:5px"
                >

                <div style="font-size:11px; color:#666; margin-bottom:8px">
                    Examples:
                    %Y-%m-%d,
                    %-m/%-d/%Y,
                    %A, %B %e,
                    %H:%M:%S,
                    %o
                </div>

                <button id="set-save" type="button" style="cursor:pointer">
                    ${editingIndex === null ? 'Add Entry' : 'Save Changes'}
                </button>

                ${
                    editingIndex === null
                        ? ''
                        : '<button id="set-cancel" type="button" style="cursor:pointer; margin-left:5px">Cancel</button>'
                }
            </div>

            <hr>

            <div
                id="set-list"
                style="max-height:200px; overflow-y:auto; margin-bottom:15px"
            ></div>

            <div style="display:flex; gap:5px; margin-bottom:8px">
                <button id="set-export" type="button" style="cursor:pointer">
                    Export Items
                </button>

                <button id="set-import" type="button" style="cursor:pointer">
                    Import Items
                </button>
            </div>

            <div style="font-size:11px; color:#666; margin-bottom:15px">
                Export saves your custom menu items as a JSON file.
                Import replaces the current custom items.
            </div>

            <button
                id="set-close"
                type="button"
                style="cursor:pointer; width:100%"
            >
                Close
            </button>
        `;

        const list = settingsPanel.querySelector('#set-list');

        customEntries.forEach((entry, index) => {
            const row = document.createElement('div');

            Object.assign(row.style, {
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                gap: '6px',
                marginBottom: '5px',
                fontSize: '12px',
                borderBottom: '1px solid #eee',
                paddingBottom: '4px'
            });

            const description = document.createElement('span');
            description.textContent = `${entry.label}: ${getEntryFormat(entry)}`;

            Object.assign(description.style, {
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                marginRight: 'auto'
            });

            const editButton = document.createElement('button');
            editButton.type = 'button';
            editButton.textContent = 'Edit';
            editButton.style.cssText = 'cursor:pointer; flex-shrink:0';

            editButton.addEventListener('click', () => {
                editingIndex = index;
                showSettings();
            });

            const deleteButton = document.createElement('button');
            deleteButton.type = 'button';
            deleteButton.textContent = 'Delete';
            deleteButton.style.cssText = 'cursor:pointer; flex-shrink:0';

            deleteButton.addEventListener('click', () => {
                customEntries.splice(index, 1);

                if (editingIndex === index) {
                    editingIndex = null;
                } else if (
                    editingIndex !== null &&
                    index < editingIndex
                ) {
                    editingIndex -= 1;
                }

                saveCustomEntries();
                rebuildMenu();
                showSettings();
            });

            row.append(description, editButton, deleteButton);
            list.appendChild(row);
        });

        settingsPanel.querySelector('#set-save').addEventListener('click', () => {
            const label = settingsPanel.querySelector('#set-label').value.trim();
            const format = settingsPanel.querySelector('#set-format').value;

            if (!label || !format) {
                return;
            }

            const updatedEntry = { label, format };

            if (editingIndex === null) {
                customEntries.push(updatedEntry);
            } else if (customEntries[editingIndex]) {
                customEntries[editingIndex] = updatedEntry;
            }

            editingIndex = null;
            saveCustomEntries();
            rebuildMenu();
            showSettings();
        });

        const cancelButton = settingsPanel.querySelector('#set-cancel');

        if (cancelButton) {
            cancelButton.addEventListener('click', () => {
                editingIndex = null;
                showSettings();
            });
        }

        settingsPanel.querySelector('#set-export').addEventListener(
            'click',
            exportCustomEntries
        );

        settingsPanel.querySelector('#set-import').addEventListener(
            'click',
            importCustomEntries
        );

        settingsPanel.querySelector('#set-close').addEventListener('click', () => {
            editingIndex = null;
            settingsPanel.style.display = 'none';
        });

        settingsPanel.style.display = 'block';
    }

    function exportCustomEntries() {
        const exportData = {
            format: 'multi-item-context-menu',
            version: 1,
            customEntries
        };

        const blob = new Blob(
            [JSON.stringify(exportData, null, 2)],
            { type: 'application/json' }
        );

        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');

        link.href = url;
        link.download = 'multi-item-context-menu-items.json';
        document.body.appendChild(link);
        link.click();
        link.remove();

        setTimeout(() => URL.revokeObjectURL(url), 0);
    }

    function importCustomEntries() {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.json,application/json';
        fileInput.style.display = 'none';

        fileInput.addEventListener('change', async () => {
            const [file] = fileInput.files || [];

            if (!file) {
                fileInput.remove();
                return;
            }

            try {
                const parsed = JSON.parse(await file.text());
                const importedEntries = normalizeEntries(parsed);

                if (
                    !Array.isArray(parsed) &&
                    !(
                        parsed &&
                        typeof parsed === 'object' &&
                        Array.isArray(parsed.customEntries)
                    )
                ) {
                    throw new Error('The selected file does not contain menu items.');
                }

                if (!confirm(
                    `Replace the current ${customEntries.length} custom item(s) ` +
                    `with ${importedEntries.length} imported item(s)?`
                )) {
                    return;
                }

                customEntries = importedEntries;
                editingIndex = null;
                saveCustomEntries();
                rebuildMenu();
                showSettings();
            } catch (error) {
                alert(`Could not import menu items: ${error.message}`);
            } finally {
                fileInput.remove();
            }
        }, { once: true });

        document.body.appendChild(fileInput);
        fileInput.click();
    }

    function escapeAttribute(value) {
        return String(value)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    function insertTextAtCursor(text, element) {
        if (!element) return;

        if (
            element instanceof HTMLInputElement ||
            element instanceof HTMLTextAreaElement
        ) {
            const start = element.selectionStart ?? element.value.length;
            const end = element.selectionEnd ?? start;

            element.value =
                element.value.slice(0, start) +
                text +
                element.value.slice(end);

            const cursorPosition = start + text.length;
            element.selectionStart = cursorPosition;
            element.selectionEnd = cursorPosition;

            element.dispatchEvent(new Event('input', { bubbles: true }));
            element.focus();
            return;
        }

        if (element.isContentEditable) {
            const selection = window.getSelection();

            if (!selection || !selection.rangeCount) {
                element.focus();
                return;
            }

            const range = selection.getRangeAt(0);
            range.deleteContents();
            range.insertNode(document.createTextNode(text));
            range.collapse(false);

            selection.removeAllRanges();
            selection.addRange(range);

            element.dispatchEvent(new Event('input', { bubbles: true }));
            element.focus();
        }
    }

    function getEditableElement(target) {
        if (!(target instanceof Element)) return null;

        const element = target.closest(
            'input, textarea, [contenteditable="true"]'
        );

        if (
            element instanceof HTMLInputElement ||
            element instanceof HTMLTextAreaElement ||
            element?.isContentEditable
        ) {
            return element;
        }

        return null;
    }

    function hideMenu() {
        menu.style.display = 'none';
    }

    window.addEventListener(
        'mousedown',
        event => {
            if (event.button !== 2 || !event.ctrlKey) return;

            const editableElement = getEditableElement(event.target);

            if (!editableElement) return;

            lastFocusedElement = editableElement;

            event.preventDefault();
            event.stopImmediatePropagation();

            menu.style.display = 'block';
            menu.style.left = `${event.clientX}px`;
            menu.style.top = `${event.clientY}px`;
        },
        true
    );

    window.addEventListener(
        'contextmenu',
        event => {
            if (event.ctrlKey) {
                event.preventDefault();
            }
        },
        true
    );

    document.addEventListener('click', event => {
        if (!menu.contains(event.target)) {
            hideMenu();
        }
    });

    document.addEventListener('keydown', event => {
        if (event.key === 'Escape') {
            hideMenu();
            editingIndex = null;
            settingsPanel.style.display = 'none';
        }
    });

    function initializeInterface() {
        if (!document.body.contains(menu)) {
            document.body.appendChild(menu);
        }

        if (!document.body.contains(settingsPanel)) {
            document.body.appendChild(settingsPanel);
        }

        rebuildMenu();
    }

    if (document.body) {
        initializeInterface();
    } else {
        document.addEventListener('DOMContentLoaded', initializeInterface, {
            once: true
        });
    }
})();