HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
// ==UserScript==
// @name Mavens Hand History Saver
// @namespace http://tampermonkey.net/
// @version 1
// @description Saves poker hand histories and allows downloading them as ZIP files
// @author You
// @match *://<your mavens url>/*
// @grant none
// @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js
// @run-at document-idle
// ==/UserScript==
(function() {
'use strict';
// Track tables and their current hand histories
const tables = new Map(); // tableId -> TableHand
// Global variables
let downloadButton = null;
let clearButton = null;
let username = null;
let menuItem = null;
// Constants
const DB_PREFIX = 'PokerHandsDB_';
const STORE_NAME = 'hands';
// Get database name for current user
const getDBName = (username) => `${DB_PREFIX}${username}`;
// Structure for tracking a table's current hand
class TableHand {
constructor(tableId) {
this.tableId = tableId;
this.handNumber = null;
this.lines = [];
this.div = null;
this.observer = null;
}
async addLines(text) {
const handMatch = text.match(/Hand #(\d+-\d+)/);
if (!handMatch) return;
const handNumber = handMatch[1];
// If this is a new hand, save and clear the old one
if (this.handNumber !== handNumber) {
await this.save();
this.handNumber = handNumber;
}
// Split by <br> and clean up the lines
this.lines = text
.split('<br>')
.map(line => line.trim())
.filter(line => line);
}
async save() {
if (!username ||!this.handNumber) return;
const filename = `${this.tableId}-${this.handNumber}.txt`;
const content = this.lines.join('\n');
try {
await withDB(username, async (db) => {
const transaction = db.transaction([STORE_NAME], 'readwrite');
const store = transaction.objectStore(STORE_NAME);
await Promise.all([
new Promise((resolve, reject) => {
const request = store.put({
filename,
content,
contentType: 'text/plain'
});
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
}),
new Promise((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
})
]);
});
} catch (error) {
console.error('Error storing hand:', error);
}
this.handNumber = null;
this.lines = [];
}
attachTo(tableDiv) {
this.div = tableDiv;
this.observer = createTableObserver(tableDiv, this.tableId, username);
}
detach() {
if (this.observer) {
this.observer.disconnect();
this.observer = null;
}
this.div = null;
}
}
// Debounce helper
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Create observer for a table's history
function createTableObserver(tableDiv, tableId, username) {
const historyDiv = tableDiv.querySelector('div.historyinfo > div.memo');
if (!historyDiv) {
return null;
}
const observer = new MutationObserver(async (mutations) => {
const historyText = historyDiv.innerHTML;
const tableHand = tables.get(tableId);
await tableHand.addLines(historyText);
});
// Watch for changes to children and their text
observer.observe(historyDiv, {
childList: true,
characterData: true,
subtree: true
});
return observer;
}
// Helper for creating menu items
const createMenuItem = (id, text, handler) => {
const item = document.createElement('li');
item.id = id;
item.textContent = text;
$(item).on("touchstart mousedown", function(e) {
if (!menuItem) {
menuItem = this;
return false;
}
});
$(item).on("touchend mouseup", function(e) {
if (!menuItem) return;
const wasMenuItem = (this === menuItem);
$(this).parent().hide();
menuItem = null;
if (wasMenuItem) {
handler();
}
return false;
});
return item;
};
// Create UI elements
const createUI = () => {
// Find the Account menu span first
const accountSpan = document.querySelector('span#AccountMenu');
if (!accountSpan) {
console.error('Account menu span not found');
return null;
}
// Find the ul that follows the Account span
const accountMenu = accountSpan.nextElementSibling;
if (!accountMenu || accountMenu.tagName !== 'UL') {
console.error('Account menu ul not found');
return null;
}
// Get styles from the ul itself
const computedStyle = window.getComputedStyle(accountMenu);
const defaultColor = computedStyle.color;
const defaultBgColor = computedStyle.backgroundColor;
// Create Download Hands menu item
const downloadItem = createMenuItem('AccountDownloadHands', 'Download hand histories...', handleDownload);
const clearItem = createMenuItem('AccountClearHands', 'Clear hand histories...', handleClear);
// Set initial styles and add hover effects
[downloadItem, clearItem].forEach(item => {
item.style.color = defaultColor;
item.style.backgroundColor = defaultBgColor;
// Add hover effects
item.addEventListener('mouseenter', () => {
item.style.color = defaultBgColor;
item.style.backgroundColor = defaultColor;
});
item.addEventListener('mouseleave', () => {
item.style.color = defaultColor;
item.style.backgroundColor = defaultBgColor;
});
});
// Add items to menu
accountMenu.appendChild(downloadItem);
accountMenu.appendChild(clearItem);
return { downloadButton: downloadItem, clearButton: clearItem };
};
// Remove UI elements
const removeUI = () => {
const downloadItem = document.getElementById('AccountDownloadHands');
const clearItem = document.getElementById('AccountClearHands');
if (downloadItem) downloadItem.remove();
if (clearItem) clearItem.remove();
};
// Handle download click
const handleDownload = async () => {
if (!username) {
return;
}
let db = null;
try {
const dbName = getDBName(username);
// Open database
db = await new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, 1);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
// Get all hands
const transaction = db.transaction([STORE_NAME], 'readonly');
const store = transaction.objectStore(STORE_NAME);
const hands = await new Promise((resolve, reject) => {
const request = store.getAll();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
if (hands.length === 0) {
alert('No hand histories available to download.');
return;
}
// Create zip file
try {
const zip = new JSZip();
hands.forEach(hand => {
zip.file(hand.filename, hand.content);
});
const blob = await zip.generateAsync({
type: "blob",
compression: "DEFLATE"
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `poker_hands_${username}_${new Date().toISOString().split('T')[0]}.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (e) {
console.error('Error creating zip:', e);
}
} catch (error) {
console.error('Error downloading hands:', error);
} finally {
if (db) {
db.close();
}
}
};
// Handle clear click
const handleClear = async () => {
if (!username) {
return;
}
let db = null;
try {
const dbName = getDBName(username);
// Open database
db = await new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, 1);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
// Get count and size before confirming
const transaction = db.transaction([STORE_NAME], 'readonly');
const store = transaction.objectStore(STORE_NAME);
const hands = await new Promise((resolve, reject) => {
const request = store.getAll();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
if (hands.length === 0) {
alert('No hand histories to clear.');
return;
}
const totalBytes = hands.reduce((sum, hand) => sum + hand.content.length, 0);
const size = formatSize(totalBytes);
if (!confirm(`Are you sure you want to clear all stored hands?\n\nThis will delete ${hands.length} hands (${size}).`)) {
return;
}
// Clear all hands
const clearTransaction = db.transaction([STORE_NAME], 'readwrite');
const clearStore = clearTransaction.objectStore(STORE_NAME);
await new Promise((resolve, reject) => {
const request = clearStore.clear();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
} catch (error) {
console.error('Error clearing hands:', error);
} finally {
if (db) {
db.close();
}
}
};
// Track previous username to detect changes
let previousUsername = null;
// Add initializedDatabases Set to track which databases have been initialized
const initializedDatabases = new Set();
// Modify initDB to check initialization status
const initDB = () => {
if (!username) {
return;
}
const dbName = getDBName(username);
if (initializedDatabases.has(dbName)) {
return;
}
try {
const request = indexedDB.open(dbName, 1);
request.onerror = (event) => {
console.error('Failed to open database:', event.target.error);
};
request.onblocked = (event) => {
console.error('Database blocked:', event);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: 'filename' });
}
};
request.onsuccess = (event) => {
const db = event.target.result;
db.close();
initializedDatabases.add(dbName);
};
} catch (error) {
console.error('Error during database initialization:', error);
}
};
// Database helper
const withDB = async (username, callback) => {
if (!username) return null;
let db = null;
try {
const dbName = getDBName(username);
db = await new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, 1);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
return await callback(db);
} finally {
if (db) db.close();
}
};
// Initialize database for a user
const initializeDB = (username) => {
return new Promise((resolve, reject) => {
const dbName = getDBName(username);
const request = indexedDB.open(dbName, 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: 'filename' });
}
};
request.onsuccess = () => {
const db = request.result;
db.close();
resolve();
};
request.onerror = (event) => {
console.error('Database initialization error:', event.target.error);
reject(event.target.error);
};
});
};
// Update UI based on username changes
const updateUI = async (newUsername) => {
if (previousUsername !== newUsername) {
initializedDatabases.clear();
}
// Username changed from null to non-null
if (!previousUsername && newUsername) {
const elements = createUI();
if (elements) {
downloadButton = elements.downloadButton;
clearButton = elements.clearButton;
await initializeDB(newUsername);
}
}
// Username changed from non-null to null
else if (previousUsername && !newUsername) {
removeUI();
}
// Username changed to different user
else if (previousUsername && newUsername && previousUsername !== newUsername) {
await initializeDB(newUsername);
}
previousUsername = newUsername;
};
// Monitor client div for table additions/removals
const observer = new MutationObserver(
debounce(async (mutations) => {
// Get username from lobby
const lobbyTitle = document.querySelector('div#Lobby > div.header > div.title');
const newUsername = lobbyTitle ?
(lobbyTitle.textContent.match(/Lobby - ([^)]+) logged in/) || [])[1]?.trim() :
null;
// Update UI if username changed
if (newUsername !== username) {
updateUI(newUsername);
username = newUsername;
}
if (!username) {
for (const [tableId, table] of tables) {
await saveAndRemoveTable(tableId);
}
return;
}
// Initialize database if needed
initDB();
// Find active tables
const tableContentDivs = Array.from(document.querySelectorAll('div.dialog > div.tablecontent')).slice(1);
const activeTables = tableContentDivs
.map(tableContent => {
const tableDialog = tableContent.closest('div.dialog');
if (!tableDialog) return null;
let currentDialog = tableDialog.nextElementSibling;
while (currentDialog) {
if (currentDialog.classList.contains('dialog')) {
const infotabs = currentDialog.querySelector('div.infotabs');
if (infotabs) return infotabs;
}
currentDialog = currentDialog.nextElementSibling;
}
return null;
})
.filter(Boolean);
for (const [tableId, table] of tables) {
if (!activeTables.includes(table.div)) {
await saveAndRemoveTable(tableId);
}
}
// Process active tables
activeTables.forEach(tableDiv => {
const infoDiv = tableDiv.querySelector('div.generalinfo > div.memo > pre');
if (!infoDiv?.textContent) return;
const tableMatch = infoDiv.textContent.match(/Table name:\s+(.+)/);
const typeMatch = infoDiv.textContent.match(/Type:\s+(.+)/);
if (!tableMatch || !typeMatch) return;
const tableName = tableMatch[1].trim();
const tableType = typeMatch[1].trim();
const tableId = (tableType === 'Ring Game' ? 'R' : 'T') + tableName;
// Create new table tracking if it doesn't exist
if (!tables.has(tableId)) {
const tableHand = new TableHand(tableId);
tables.set(tableId, tableHand);
tableHand.attachTo(tableDiv);
}
});
}, 500)
);
// Helper function to save and remove a table
async function saveAndRemoveTable(tableId) {
const table = tables.get(tableId);
if (table) {
await table.save();
table.detach();
tables.delete(tableId);
}
}
// Start observing the client div
const startObserver = () => {
const clientDiv = document.getElementById('client_div');
if (clientDiv) {
observer.observe(clientDiv, {
childList: true,
subtree: true
});
// Immediately check for username and tables
const lobbyTitle = document.querySelector('div#Lobby > div.header > div.title');
const tableContentDivs = Array.from(document.querySelectorAll('div.dialog > div.tablecontent')).slice(1);
} else {
console.error('[PHHS] Client div not found, will retry in 1 second');
setTimeout(startObserver, 1000);
}
};
// Remove the DOMContentLoaded listener and start immediately
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startObserver);
} else {
startObserver();
}
// Helper function to format size
const formatSize = (bytes) => {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
return (bytes / (1024 * 1024 * 1024)).toFixed(1) + ' GB';
};
})();
Also see: Tab Triggers