JavaScript// ==UserScript==
// @name 快捷输入
// @namespace http://tampermonkey.net/
// @version 9.6
// @description 快捷输入
// @author p1
// @match https://www.luogu.com.cn/*
// @match https://www.luogu.com/*
// @grant GM_addStyle
// @grant GM_getResourceText
// @resource FONTAWESOME_CSS https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css
// @run-at document-end
// ==/UserScript==
(function() {
'use strict';
const faCss = GM_getResourceText("FONTAWESOME_CSS");
GM_addStyle(faCss);
const TRIGGER_CHAR = '$';// 触发字符
const GRID_COLUMNS = 3;// 网格列数
const FIXED_ITEM_SIZE = 60;// 方框固定大小
const MAX_WIDTH = 600;// 最大宽度
const MIN_WIDTH = GRID_COLUMNS * FIXED_ITEM_SIZE + (GRID_COLUMNS - 1) * 8 + 20;// 最小宽度
const MIN_HEIGHT = 120;// 最小高度
const INITIAL_HEIGHT = 150;// 初始高度
const CONTENT_EXTRA_SPACE = 60;// 内容外额外空间
const MAX_EXTRA_SPACE = 20;// 最大额外空间限制
const INPUT_LINE_HEIGHT = 1.6;// 输入框行高
const OPEN_SCALE = 0.9;// 开启时的缩放比例V
const ALLOW_HORIZONTAL_RESIZE = false;// 允许横向拉伸
const ALLOW_VERTICAL_RESIZE = true;// 允许竖向拉伸
const AUTO_RESIZE_ON_CONTENT_CHANGE = false;// 添加/删除内容时自动调整大小
const INPUT_PLUS_CHAR = "+";// 添加按钮显示的字符
const INPUT_PLUS_SIZE = "24px";// 字符大小
const INPUT_PLUS_COLOR = "#666";// 字符颜色
const INPUT_BACKGROUND = "#f8f9fa";// 输入框背景色
const INPUT_BORDER = "1px dashed #ccc";// 输入框边框
const INPUT_BORDER_RADIUS = "4px";// 输入框边框圆角
const INPUT_BOX_SHADOW = "0 2px 5px rgba(0,0,0,0.1)";// 输入框阴影
function loadCustomItems() {
const saved = localStorage.getItem('customRightClickItems');
return saved ? JSON.parse(saved) : [];
}
function saveCustomItems(items) {
localStorage.setItem('customRightClickItems', JSON.stringify(items));
}
function isImageFormat(content) {
const regex = /^!\[\]\((.*?)\)$/;
return regex.test(content);
}
function extractImageUrl(content) {
const regex = /^!\[\]\((.*?)\)$/;
const match = content.match(regex);
return match ? match[1] : null;
}
function calculateContentHeight(list) {
const resizeContainer = list.querySelector('.resize-handle-container');
if (!resizeContainer) return 0;
let totalHeight = 0;
let child = list.firstChild;
while (child && child !== resizeContainer) {
totalHeight += child.offsetHeight + 8;
child = child.nextSibling;
}
return totalHeight + 20;
}
function adjustHeightToContent(list) {
if (!AUTO_RESIZE_ON_CONTENT_CHANGE) return;
const contentHeight = calculateContentHeight(list);
const newHeight = Math.max(MIN_HEIGHT, Math.min(contentHeight + CONTENT_EXTRA_SPACE, contentHeight + MAX_EXTRA_SPACE));
list.style.height = `${newHeight}px`;
}
GM_addStyle(`
.custom-right-click-list {
position: absolute;
background: white;
border: 1px solid #ccc;
border-radius: 4px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
padding: 10px;
margin: 0;
list-style: none;
z-index: 99999;
display: grid;
grid-template-columns: repeat(${GRID_COLUMNS}, 1fr);
gap: 8px;
opacity: 0;
transform-origin: top left;
transition: all 0.2s ease-out;
pointer-events: none;
overflow: auto;
box-sizing: border-box;
justify-items: start;
align-items: start;
align-content: start;
scrollbar-width: none;
}
.custom-right-click-list::-webkit-scrollbar {
display: none;
}
.custom-right-click-list.visible {
opacity: 1;
transform: scale(1);
pointer-events: auto;
}
.custom-right-click-list li {
width: ${FIXED_ITEM_SIZE}px;
height: ${FIXED_ITEM_SIZE}px;
padding: 8px;
cursor: pointer;
transition: all 0.2s;
position: relative;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
box-sizing: border-box;
border: 1px solid transparent;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.08);
}
.custom-right-click-list li:hover {
background-color: #f0f0f0;
border-color: #ddd;
border-radius: 3px;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.12);
}
.custom-right-click-list li:active {
background-color: #e0e0e0;
transform: scale(0.95);
transition: all 0.1s;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.custom-right-click-list li.separator {
grid-column: 1 / -1;
border-top: 1px solid #eee;
margin: 5px 0;
padding: 0;
width: 100%;
height: 1px;
box-shadow: none;
}
.custom-right-click-active {
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.3) !important;
transition: box-shadow 0.2s;
}
.resize-handle-container {
position: fixed;
pointer-events: none;
z-index: 10;
}
.resize-handle {
position: absolute;
right: -2px;
bottom: -2px;
width: 15px;
height: 15px;
cursor: nwse-resize;
background: linear-gradient(135deg, transparent 50%, #ccc 50%);
z-index: 11;
transition: background 0.2s;
pointer-events: auto;
}
.resize-handle.disabled {
cursor: default;
background: linear-gradient(135deg, transparent 50%, #eee 50%);
}
.resize-handle:hover:not(.disabled), .resize-handle:active:not(.disabled) {
background: linear-gradient(135deg, transparent 50%, #666 50%);
}
.custom-item-input-container {
width: ${FIXED_ITEM_SIZE}px;
height: ${FIXED_ITEM_SIZE}px;
padding: 0;
cursor: pointer;
position: relative;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
border-radius: ${INPUT_BORDER_RADIUS};
box-shadow: ${INPUT_BOX_SHADOW};
background-color: ${INPUT_BACKGROUND};
border: ${INPUT_BORDER};
}
.custom-item-plus-char {
font-size: ${INPUT_PLUS_SIZE};
color: ${INPUT_PLUS_COLOR};
font-weight: bold;
user-select: none;
}
.custom-item-input {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 80%;
max-width: 500px;
padding: 15px;
border: 1px solid #ccc;
border-radius: 6px;
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
background: white;
z-index: 100000;
min-height: 120px;
font-size: 16px;
line-height: ${INPUT_LINE_HEIGHT};
resize: vertical;
max-height: 300px;
}
.custom-item-input.visible {
display: block;
}
.input-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
z-index: 99999;
}
.input-overlay.visible {
display: block;
}
.delete-item-btn {
position: absolute;
right: 2px;
top: 2px;
color: #ff4444;
opacity: 0;
transition: opacity 0.2s;
font-size: 12px;
padding: 2px 5px;
background: rgba(255,255,255,0.8);
border-radius: 50%;
}
li:hover .delete-item-btn {
opacity: 1;
}
.menu-image-preview {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border-radius: 3px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.add-item-btn {
width: ${FIXED_ITEM_SIZE}px;
height: ${FIXED_ITEM_SIZE}px;
display: flex;
align-items: center;
justify-content: center;
background-color: #f8f9fa;
border: 1px dashed #ccc;
color: #666;
font-weight: bold;
font-size: 20px;
padding: 0;
margin: 0;
cursor: pointer;
}
.add-item-btn:hover {
background-color: #f0f0f0;
border-color: #999;
color: #333;
}
.item-text {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
max-height: 100%;
}
`);
function createList() {
const existingList = document.getElementById('customRightClickList');
if (existingList) {
existingList.remove();
}
document.querySelectorAll('.custom-item-input, .input-overlay').forEach(el => el.remove());
const list = document.createElement('ul');
list.className = 'custom-right-click-list';
list.id = 'customRightClickList';
list.style.width = `${MIN_WIDTH}px`;
list.style.height = `${INITIAL_HEIGHT}px`;
list.style.transform = `scale(${OPEN_SCALE})`;
const resizeContainer = document.createElement('div');
resizeContainer.className = 'resize-handle-container';
const resizeHandle = document.createElement('div');
resizeHandle.className = 'resize-handle';
if (!ALLOW_HORIZONTAL_RESIZE && !ALLOW_VERTICAL_RESIZE) {
resizeHandle.classList.add('disabled');
resizeHandle.title = '拉伸功能已禁用';
} else if (!ALLOW_HORIZONTAL_RESIZE) {
resizeHandle.title = '仅允许竖向拉伸';
resizeHandle.style.cursor = 'ns-resize';
} else if (!ALLOW_VERTICAL_RESIZE) {
resizeHandle.title = '仅允许横向拉伸';
resizeHandle.style.cursor = 'ew-resize';
} else {
resizeHandle.title = '拉伸调整大小';
}
resizeContainer.appendChild(resizeHandle);
document.body.appendChild(resizeContainer);
list.appendChild(resizeContainer);
renderListItems(list);
document.body.appendChild(list);
initResizeFunctionality(list);
updateResizeHandlePosition(list);
list.addEventListener('scroll', () => {
updateResizeHandlePosition(list);
});
return list;
}
function updateResizeHandlePosition(list) {
const resizeContainer = list.querySelector('.resize-handle-container');
if (!resizeContainer) return;
const rect = list.getBoundingClientRect();
resizeContainer.style.left = `${rect.left + rect.width - 15}px`;
resizeContainer.style.top = `${rect.top + rect.height - 15}px`;
}
function renderListItems(list) {
const resizeContainer = list.querySelector('.resize-handle-container');
while (list.firstChild !== resizeContainer) {
list.removeChild(list.firstChild);
}
const customItems = loadCustomItems();
customItems.forEach(item => {
addItemToList(list, item, true);
});
const inputContainer = document.createElement('li');
inputContainer.className = 'custom-item-input-container';
inputContainer.title = "添加新内容";
const plusChar = document.createElement('span');
plusChar.className = 'custom-item-plus-char';
plusChar.textContent = INPUT_PLUS_CHAR;
inputContainer.appendChild(plusChar);
list.insertBefore(inputContainer, resizeContainer);
inputContainer.addEventListener('click', function(e) {
showAddItemInput(list);
e.stopPropagation();
});
adjustHeightToContent(list);
updateResizeHandlePosition(list);
}
function replaceAllTriggerChars(inputElement, content) {
const triggerRegex = new RegExp(TRIGGER_CHAR, 'g');
if (inputElement.isContentEditable) {
const walker = document.createTreeWalker(
inputElement,
NodeFilter.SHOW_TEXT,
null,
false
);
const textNodes = [];
let currentNode;
while (currentNode = walker.nextNode()) {
textNodes.push(currentNode);
}
textNodes.forEach(node => {
if (node.textContent.includes(TRIGGER_CHAR)) {
node.textContent = node.textContent.replace(triggerRegex, content);
}
});
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(inputElement);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
return true;
} else {
const currentValue = inputElement.value;
const newValue = currentValue.replace(triggerRegex, content);
const cursorPos = inputElement.selectionStart;
const replacedCount = (currentValue.substring(0, cursorPos).match(triggerRegex) || []).length;
const newCursorPos = cursorPos + (content.length - TRIGGER_CHAR.length) * replacedCount;
return {
value: newValue,
cursorPos: newCursorPos
};
}
}
function addItemToList(list, text, isCustom) {
const li = document.createElement('li');
if (isImageFormat(text)) {
const imageUrl = extractImageUrl(text);
const img = document.createElement('img');
img.src = imageUrl;
img.alt = '预览图';
img.className = 'menu-image-preview';
img.onerror = function() {
this.alt = '图片加载失败';
this.style.display = 'none';
const errorText = document.createElement('span');
errorText.textContent = '图片加载失败';
errorText.style.color = '#ff4444';
li.appendChild(errorText);
};
li.appendChild(img);
} else {
const textSpan = document.createElement('span');
textSpan.className = 'item-text';
textSpan.textContent = text;
li.appendChild(textSpan);
}
const deleteBtn = document.createElement('span');
deleteBtn.className = 'delete-item-btn';
deleteBtn.textContent = '×';
li.appendChild(deleteBtn);
deleteBtn.addEventListener('click', function(e) {
const customItems = loadCustomItems();
const updatedItems = customItems.filter(item => item !== text);
saveCustomItems(updatedItems);
renderListItems(list);
e.stopPropagation();
});
li.addEventListener('click', function(e) {
const activeInput = document.querySelector('.custom-right-click-active');
if (activeInput) {
activeInput.classList.add('custom-right-click-active');
setTimeout(() => activeInput.classList.remove('custom-right-click-active'), 300);
if (activeInput.isContentEditable) {
if (isImageFormat(text)) {
const imageUrl = extractImageUrl(text);
const img = document.createElement('img');
img.src = imageUrl;
img.alt = '插入的图片';
img.style.maxWidth = '100%';
replaceAllTriggerChars(activeInput, '');
const selection = window.getSelection();
if (selection.rangeCount) {
const range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(img);
const spaceNode = document.createTextNode(' ');
range.setStartAfter(img);
range.setEndAfter(img);
range.insertNode(spaceNode);
range.setStartAfter(spaceNode);
range.setEndAfter(spaceNode);
selection.removeAllRanges();
selection.addRange(range);
}
} else {
replaceAllTriggerChars(activeInput, text);
}
} else {
const result = replaceAllTriggerChars(activeInput, text);
if (result) {
activeInput.value = result.value;
activeInput.focus();
const safeCursorPos = Math.min(result.cursorPos, activeInput.value.length);
activeInput.setSelectionRange(safeCursorPos, safeCursorPos);
}
}
}
hideList();
e.stopPropagation();
});
const inputContainer = list.querySelector('.custom-item-input-container');
if (inputContainer) {
list.insertBefore(li, inputContainer);
} else {
const resizeContainer = list.querySelector('.resize-handle-container');
list.insertBefore(li, resizeContainer);
}
}
function showAddItemInput(list) {
document.querySelectorAll('.custom-item-input, .input-overlay').forEach(el => el.remove());
const overlay = document.createElement('div');
overlay.className = 'input-overlay visible';
document.body.appendChild(overlay);
const input = document.createElement('textarea');
input.className = 'custom-item-input visible';
input.placeholder = ``;
document.body.appendChild(input);
input.focus();
function closeInput(save = false) {
if (save && input.value.trim()) {
const customItems = loadCustomItems();
if (!customItems.includes(input.value.trim())) {
customItems.push(input.value.trim());
saveCustomItems(customItems);
renderListItems(list);
}
}
input.remove();
overlay.remove();
}
input.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
closeInput(true);
} else if (e.key === 'Escape') {
closeInput(false);
}
});
overlay.addEventListener('click', () => closeInput(false));
input.addEventListener('blur', function() {
closeInput(true);
});
}
function initResizeFunctionality(list) {
const resizeHandle = list.querySelector('.resize-handle');
let isResizing = false;
let startX, startY, startWidth, startHeight;
if (!ALLOW_HORIZONTAL_RESIZE && !ALLOW_VERTICAL_RESIZE) {
return;
}
list.style.transition = 'width 0.05s ease-out, height 0.05s ease-out';
resizeHandle.addEventListener('mousedown', function(e) {
isResizing = true;
startX = e.clientX;
startY = e.clientY;
startWidth = list.offsetWidth;
startHeight = list.offsetHeight;
list.classList.add('resizing');
document.body.style.userSelect = 'none';
document.addEventListener('mousemove', handleMouseMove, true);
document.addEventListener('mouseup', handleMouseUp, true);
e.stopPropagation();
e.preventDefault();
});
function handleMouseMove(e) {
if (!isResizing) return;
let newWidth = startWidth;
let newHeight = startHeight;
if (ALLOW_HORIZONTAL_RESIZE) {
newWidth = startWidth + (e.clientX - startX);
}
if (ALLOW_VERTICAL_RESIZE) {
newHeight = startHeight + (e.clientY - startY);
}
const contentHeight = calculateContentHeight(list);
if (ALLOW_HORIZONTAL_RESIZE) {
newWidth = Math.max(MIN_WIDTH, Math.min(newWidth, MAX_WIDTH));
}
if (ALLOW_VERTICAL_RESIZE) {
newHeight = Math.max(
MIN_HEIGHT,
Math.min(
newHeight,
Math.max(contentHeight + CONTENT_EXTRA_SPACE, contentHeight + MAX_EXTRA_SPACE)
)
);
}
requestAnimationFrame(() => {
if (ALLOW_HORIZONTAL_RESIZE) {
list.style.width = `${newWidth}px`;
}
if (ALLOW_VERTICAL_RESIZE) {
list.style.height = `${newHeight}px`;
}
// 调整大小时更新手柄位置
updateResizeHandlePosition(list);
});
e.stopPropagation();
e.preventDefault();
}
function handleMouseUp() {
if (isResizing) {
isResizing = false;
list.classList.remove('resizing');
document.body.style.userSelect = '';
document.removeEventListener('mousemove', handleMouseMove, true);
document.removeEventListener('mouseup', handleMouseUp, true);
}
}
window.isResizingRightClickList = () => isResizing;
}
function showList(inputElement) {
const list = document.getElementById('customRightClickList') || createList();
list.classList.remove('visible');
list.style.transform = `scale(${OPEN_SCALE})`;
document.querySelectorAll('.custom-right-click-active').forEach(el => {
el.classList.remove('custom-right-click-active');
});
if (inputElement) {
inputElement.classList.add('custom-right-click-active');
}
let newX, newY;
if (inputElement) {
const rect = inputElement.getBoundingClientRect();
newX = rect.left + window.scrollX;
newY = rect.bottom + window.scrollY + 5;
} else {
newX = window.innerWidth / 2 - MIN_WIDTH / 2 + window.scrollX;
newY = window.innerHeight / 2 - INITIAL_HEIGHT / 2 + window.scrollY;
}
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const listWidth = list.offsetWidth || MIN_WIDTH;
const listHeight = list.offsetHeight || INITIAL_HEIGHT;
if (newX + listWidth > viewportWidth + window.scrollX) {
newX = Math.max(0, viewportWidth + window.scrollX - listWidth - 10);
}
if (newY + listHeight > viewportHeight + window.scrollY) {
newY = Math.max(0, (inputElement ? inputElement.getBoundingClientRect().top : newY) + window.scrollY - listHeight - 5);
}
list.style.left = `${newX}px`;
list.style.top = `${newY}px`;
void list.offsetWidth;
setTimeout(() => {
list.classList.add('visible');
// 显示列表后更新手柄位置
updateResizeHandlePosition(list);
}, 10);
}
function hideList() {
if (window.isResizingRightClickList && window.isResizingRightClickList()) {
return;
}
const list = document.getElementById('customRightClickList');
if (list) {
list.classList.remove('visible');
}
document.querySelectorAll('.custom-right-click-active').forEach(el => {
el.classList.remove('custom-right-click-active');
});
}
function isInputElement(element) {
const tagName = element.tagName.toLowerCase();
return (tagName === 'input' && !['checkbox', 'radio', 'file', 'submit', 'reset', 'button'].includes(element.type)) ||
tagName === 'textarea' ||
element.isContentEditable;
}
function setupTriggerCharListener() {
document.addEventListener('keydown', function(e) {
if (e.key === TRIGGER_CHAR && isInputElement(e.target)) {
const list = document.getElementById('customRightClickList');
if (!list || !list.classList.contains('visible')) {
showList(e.target);
}
}
});
}
document.addEventListener('contextmenu', function(e) {
if (isInputElement(e.target)) {
e.preventDefault();
const list = document.getElementById('customRightClickList');
if (window.isResizingRightClickList && window.isResizingRightClickList()) {
const mouseUpEvent = new MouseEvent('mouseup', {
bubbles: true,
cancelable: true,
view: window
});
document.dispatchEvent(mouseUpEvent);
}
if (list && list.classList.contains('visible')) {
hideList();
} else {
showList(e.target);
}
} else {
hideList();
}
});
document.addEventListener('click', function(e) {
if (window.isResizingRightClickList && window.isResizingRightClickList()) {
return;
}
if (!e.target.closest('.custom-right-click-list') &&
!e.target.closest('.custom-item-input') &&
!e.target.closest('.input-overlay') &&
!isInputElement(e.target)) {
hideList();
}
});
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
const input = document.querySelector('.custom-item-input');
const overlay = document.querySelector('.input-overlay');
if (input && overlay) {
input.remove();
overlay.remove();
} else {
hideList();
}
}
});
window.addEventListener('scroll', function() {
const list = document.getElementById('customRightClickList');
if (list && list.classList.contains('visible')) {
const activeInput = document.querySelector('.custom-right-click-active');
if (activeInput) {
const rect = activeInput.getBoundingClientRect();
list.style.left = `${rect.left + window.scrollX}px`;
list.style.top = `${rect.bottom + window.scrollY + 5}px`;
updateResizeHandlePosition(list);
}
}
});
setupTriggerCharListener();
})();