User:AlternateTorg/personal-notes.js

/* * This script adds a "Personal Notes" editor to the right rail on the page. * Anything written in this editor is stored locally in the user's browser, and * is only visible to that user. */

var KEY = mw.config.get('wgDBname') + '|' + mw.config.get('wgPageName'); var RIGHT_RAIL_SELECTOR = 'aside .right-rail-wrapper'; var NAMESPACE = '__com_walkertribe_rjw_fandom-personal-notes__'; var TEXTAREA_ID = NAMESPACE + 'textarea'; var MIN_TEXTAREA_HEIGHT = 100; var AUTO_SAVE_DELAY_MS = 1000;

var timer;

/** * Loads any stored data into the editor. */ function load { document.getElementById(TEXTAREA_ID).value = localStorage.getItem(KEY) || ''; }

/** * Stores the contents of the editor into local storage. */ function save { var value = document.getElementById(TEXTAREA_ID).value;

if (value.length) { localStorage.setItem(KEY, value); } else { localStorage.removeItem(KEY); } }

/** * Fires when the editor gets focus. Adds the border to the field. */ function onFocus { document.getElementById(TEXTAREA_ID).style.borderColor = 'unset'; }

/** * Fires when the editor loses focus. Saves the contents and removes the border * from the field. */ function onBlur { clearTimeout(timer); save; document.getElementById(TEXTAREA_ID).style.borderColor = 'transparent'; }

/** * Fires when the editor contents change. Auto-adjusts the height of the field, * and sets a timer to save the contents if the user stops typing. */ function onInput { clearTimeout(timer); var editor = document.getElementById(TEXTAREA_ID); editor.style.height = 'auto'; editor.style.height = Math.max(editor.scrollHeight, MIN_TEXTAREA_HEIGHT) + 'px'; timer = setTimeout(save, AUTO_SAVE_DELAY_MS); }

/** * Builds the notes editor. */ function init { var el = document.querySelector(RIGHT_RAIL_SELECTOR);

if (!el) { return; }

var notesDiv = document.createElement('div'); notesDiv.style.marginTop = '24px'; notesDiv.style.borderBottom = '1px solid var(--theme-border-color)'; var h2 = document.createElement('h2'); h2.className = 'rail-module__header'; h2.textContent = 'Personal Notes'; notesDiv.appendChild(h2); var textarea = document.createElement('textarea'); textarea.id = TEXTAREA_ID; textarea.autocomplete = false; textarea.placeholder = 'Whatever you write here is visible only to you.'; textarea.style.display = 'block'; textarea.style.boxSizing = 'border-box'; textarea.style.width = '100%'; textarea.style.resize = 'none'; textarea.style.overflow = 'hidden'; textarea.style.fontFamily = 'inherit'; textarea.style.fontSize = '100%'; textarea.style.backgroundColor = 'transparent'; textarea.style.color = 'inherit'; textarea.style.borderColor = 'transparent'; textarea.style.marginBottom = '24px'; notesDiv.appendChild(textarea); el.insertBefore(notesDiv, el.firstChild); load; onInput; textarea.addEventListener('input', onInput); textarea.addEventListener('focus', onFocus); textarea.addEventListener('blur', onBlur); }

init;