Luogu 显示比赛日历插件 V3.0
V3.0 更新啦!
主要优化
- 修复了一些漏洞。
- 根据反馈修复了弹窗尺寸的问题。
// ==UserScript==
// @name Luogu 比赛日历
// @namespace https://luogu.com.cn/
// @version 3.0
// @description 显示比赛详情,支持查/删/添操作,按钮可拖动且记忆位置,弹窗尺寸加大
// @author Kofy (modified)
// @match https://www.luogu.com.cn/*
// @match https://luogu.com.cn/*
// @icon https://www.luogu.com.cn/favicon.ico
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @require https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js
// ==/UserScript==
(function () {
'use strict';
window.addEventListener('load', function () {
setTimeout(initCalendar, 2000);
});
function initCalendar() {
if (document.getElementById('calendar-container')) return;
const CELL_WIDTH = 50;
const CELL_HEIGHT = 48;
const CELL_GAP = 5;
const GRID_ROWS = 6;
const GRID_COLS = 7;
// ---------- 创建容器 ----------
const mainContainer = document.createElement('div');
mainContainer.id = 'calendar-container';
mainContainer.style.cssText = `
position: fixed;
z-index: 9999;
background: rgba(30, 41, 59, 0.95);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 20px;
box-shadow: 0 10px 25px rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.1);
font-family: 'Segoe UI','Microsoft YaHei',sans-serif;
color: #f8fafc;
max-height: 80vh;
overflow-y: auto;
display: none;
width: ${CELL_WIDTH*GRID_COLS + CELL_GAP*(GRID_COLS-1) + 40}px;
`;
// ---------- 切换按钮(可拖动) ----------
const toggleBtn = document.createElement('button');
toggleBtn.id = 'calendar-toggle';
toggleBtn.style.cssText = `
position: fixed;
z-index: 10000;
background: #6366f1;
color: white;
border: none;
border-radius: 50%;
width: 50px;
height: 50px;
font-size: 20px;
cursor: grab;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
display: flex;
align-items: center;
justify-content: center;
user-select: none;
touch-action: none;
right: auto;
`;
toggleBtn.innerHTML = '<i class="fas fa-calendar-alt"></i>';
// ---------- 读取保存的位置 ----------
const savedPos = GM_getValue('toggleBtnPos');
if (savedPos && typeof savedPos.left === 'number' && typeof savedPos.top === 'number') {
const maxLeft = window.innerWidth - 50;
const maxTop = window.innerHeight - 50;
const left = Math.min(Math.max(savedPos.left, 0), maxLeft);
const top = Math.min(Math.max(savedPos.top, 0), maxTop);
toggleBtn.style.left = left + 'px';
toggleBtn.style.top = top + 'px';
} else {
const defaultLeft = window.innerWidth - 70;
const defaultTop = 80;
toggleBtn.style.left = defaultLeft + 'px';
toggleBtn.style.top = defaultTop + 'px';
}
// ---------- 容器内部组件 ----------
const closeBtn = document.createElement('button');
closeBtn.id = 'calendar-close';
closeBtn.style.cssText = `
position: absolute; top: 10px; right: 10px; background: transparent;
border: none; color: #94a3b8; font-size: 18px; cursor: pointer;
width: 30px; height: 30px; border-radius: 50%; display: flex;
align-items: center; justify-content: center;
`;
closeBtn.innerHTML = '<i class="fas fa-times"></i>';
const header = document.createElement('div');
header.style.cssText = `margin-bottom: 15px;`;
header.innerHTML = `<h3 style="margin:0; font-size:18px;display:flex;align-items:center;gap:8px;">
<i class="fas fa-calendar-alt"></i> 比赛日历
</h3>`;
const stats = document.createElement('div');
stats.style.cssText = `display:flex; gap:10px; margin-bottom:15px;align-items:center;`;
stats.innerHTML = `
<div style="flex:1; background:rgba(30,41,59,0.8); border-radius:10px; padding:12px; display:flex; align-items:center; gap:10px;">
<div style="width:36px; height:36px; border-radius:8px; display:grid; place-items:center;background:rgba(99,102,241,0.2); color:#6366f1;">
<i class="fas fa-trophy"></i>
</div>
<div>
<h4 style="margin:0;font-size:20px;" id="total-contests">0</h4>
<p style="margin:0;font-size:12px;color:#94a3b8;">总比赛</p>
</div>
</div>
<div style="flex:1; background:rgba(30,41,59,0.8); border-radius:10px; padding:12px; display:flex; align-items:center; gap:10px;">
<div style="width:36px; height:36px; border-radius:8px; display:grid; place-items:center;background:rgba(245,158,11,0.2); color:#f59e0b;">
<i class="fas fa-clock"></i>
</div>
<div>
<h4 style="margin:0;font-size:20px;" id="today-contests">0</h4>
<p style="margin:0;font-size:12px;color:#94a3b8;">今日比赛</p>
</div>
</div>
`;
const btnBar = document.createElement('div');
btnBar.style.cssText = `
height:70px; margin-bottom:15px; display:flex; flex-direction:column; gap:8px;
transform: translateZ(0); overflow:hidden;
`;
btnBar.innerHTML = `
<div style="display:flex; gap:6px;" id="btn-row">
<button id="add-contest" style="display:none; flex:1; padding:8px; border:none; border-radius:8px; font-weight:600; cursor:pointer; background:#6366f1; color:white;">
<i class="fas fa-plus"></i> 添加
</button>
<button id="del-contest" style="display:none; flex:1; padding:8px; border:none; border-radius:8px; font-weight:600; cursor:pointer; background:#ef4444; color:white;">
<i class="fas fa-trash"></i> 删除
</button>
<button id="view-contest" style="display:none; flex:1; padding:8px; border:none; border-radius:8px; font-weight:600; cursor:pointer; background:#10b981; color:white;">
<i class="fas fa-list"></i> 查看
</button>
<button id="go-today" style="flex:1; padding:8px; border:none; border-radius:8px; font-weight:600; cursor:pointer; background:rgba(255,255,255,0.1); color:white;">
<i class="fas fa-calendar-day"></i> 今日
</button>
</div>
<div id="selected-tip" style="display:none; text-align:center; color:#94a3b8; font-size:13px; line-height:1;">
已选中:<span id="selected-date"></span>
</div>
`;
const monthBar = document.createElement('div');
monthBar.style.cssText = `display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;`;
monthBar.innerHTML = `
<button id="prev-month" style="padding:8px 12px; border:none; border-radius:8px; background:rgba(255,255,255,0.1); color:white; cursor:pointer;">
<i class="fas fa-chevron-left"></i>
</button>
<h4 id="current-month" style="margin:0; font-size:16px;">2024年1月</h4>
<button id="next-month" style="padding:8px 12px; border:none; border-radius:8px; background:rgba(255,255,255,0.1); color:white; cursor:pointer;">
<i class="fas fa-chevron-right"></i>
</button>
`;
const weekdayBar = document.createElement('div');
weekdayBar.style.cssText = `
position: relative; width: ${CELL_WIDTH*GRID_COLS + CELL_GAP*(GRID_COLS-1)}px;
height: 25px; margin-bottom:5px;
`;
const weekdays = ['日','一','二','三','四','五','六'];
weekdays.forEach((day, idx) => {
const el = document.createElement('div');
el.style.cssText = `
position: absolute; left: ${idx*(CELL_WIDTH + CELL_GAP)}px; top:0;
width: ${CELL_WIDTH}px; height:25px; text-align:center; line-height:25px;
color:#94a3b8; font-weight:600; font-size:14px;
`;
el.textContent = day;
weekdayBar.appendChild(el);
});
const calendarGrid = document.createElement('div');
calendarGrid.id = 'calendar-grid';
calendarGrid.style.cssText = `
position: relative; width: ${CELL_WIDTH*GRID_COLS + CELL_GAP*(GRID_COLS-1)}px;
height: ${CELL_HEIGHT*GRID_ROWS + CELL_GAP*(GRID_ROWS-1)}px;
transform: translateZ(0);
`;
mainContainer.appendChild(closeBtn);
mainContainer.appendChild(header);
mainContainer.appendChild(stats);
mainContainer.appendChild(btnBar);
mainContainer.appendChild(monthBar);
mainContainer.appendChild(weekdayBar);
mainContainer.appendChild(calendarGrid);
document.body.appendChild(mainContainer);
document.body.appendChild(toggleBtn);
// ---------- 状态变量 ----------
let isVisible = false;
const state = {
currentDate: new Date(),
contests: JSON.parse(GM_getValue('contests', '{}')) || {},
today: new Date().toISOString().split('T')[0],
selectedDate: null,
selectedCell: null
};
// ---------- 拖动相关变量 ----------
let isDragging = false;
let isMouseDown = false;
let startX = 0, startY = 0;
let startLeft = 0, startTop = 0;
const DRAG_THRESHOLD = 5;
// ---------- 容器位置计算函数 ----------
function positionCalendarNearButton() {
const btnRect = toggleBtn.getBoundingClientRect();
const containerWidth = mainContainer.offsetWidth || (CELL_WIDTH * GRID_COLS + CELL_GAP * (GRID_COLS - 1) + 40);
const containerHeight = mainContainer.offsetHeight || 500;
let left = btnRect.right + 10;
let top = btnRect.top;
if (left + containerWidth > window.innerWidth) {
left = btnRect.left - containerWidth - 10;
}
if (left < 0) {
left = 10;
top = btnRect.bottom + 10;
}
if (top + containerHeight > window.innerHeight) {
top = window.innerHeight - containerHeight - 10;
}
if (top < 10) top = 10;
if (left < 10) left = 10;
if (left + containerWidth > window.innerWidth) left = window.innerWidth - containerWidth - 10;
mainContainer.style.left = left + 'px';
mainContainer.style.top = top + 'px';
}
// ---------- 渲染日历 ----------
function renderCalendar() {
calendarGrid.innerHTML = '';
const year = state.currentDate.getFullYear();
const month = state.currentDate.getMonth();
document.getElementById('current-month').textContent = `${year}年${month+1}月`;
const firstDayOfMonth = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month+1, 0).getDate();
const lastDayOfPrevMonth = new Date(year, month, 0).getDate();
let cellIndex = 0;
for (let i = firstDayOfMonth - 1; i >= 0; i--) {
const num = lastDayOfPrevMonth - i;
createCell(num, cellIndex, true);
cellIndex++;
}
const today = new Date();
for (let day = 1; day <= daysInMonth; day++) {
const dateStr = `${year}-${String(month+1).padStart(2,'0')}-${String(day).padStart(2,'0')}`;
const isToday = year === today.getFullYear() && month === today.getMonth() && day === today.getDate();
const hasContest = !!state.contests[dateStr]?.length;
const isSelected = state.selectedDate === dateStr;
const cell = createCell(day, cellIndex, false, isToday, hasContest, isSelected, dateStr);
cell.addEventListener('click', () => {
if (state.selectedCell) {
state.selectedCell.style.background = state.selectedCell.dataset.originalBg;
}
cell.dataset.originalBg = cell.style.background;
cell.style.background = 'rgba(245,158,11,0.3)';
state.selectedCell = cell;
state.selectedDate = dateStr;
document.getElementById('add-contest').style.display = 'block';
document.getElementById('del-contest').style.display = 'block';
document.getElementById('view-contest').style.display = 'block';
document.getElementById('selected-tip').style.display = 'block';
document.getElementById('selected-date').textContent = `${year}年${month+1}月${day}日`;
adjustBtnLayout();
});
cellIndex++;
}
while (cellIndex < GRID_ROWS * GRID_COLS) {
const num = cellIndex - (firstDayOfMonth + daysInMonth) + 1;
createCell(num, cellIndex, true);
cellIndex++;
}
updateStats();
adjustBtnLayout();
if (isVisible && mainContainer.style.display === 'block') {
positionCalendarNearButton();
}
}
function createCell(num, cellIndex, isOtherMonth, isToday = false, hasContest = false, isSelected = false, dateStr = '') {
const row = Math.floor(cellIndex / GRID_COLS);
const col = cellIndex % GRID_COLS;
const left = col * (CELL_WIDTH + CELL_GAP);
const top = row * (CELL_HEIGHT + CELL_GAP);
const cell = document.createElement('div');
cell.style.cssText = `
position: absolute; left: ${left}px; top: ${top}px;
width: ${CELL_WIDTH}px; height: ${CELL_HEIGHT}px;
border-radius: 8px; cursor: pointer;
display: flex; align-items: center; justify-content: center;
font-size: 14px; font-weight: 700; color: #f8fafc;
margin: 0 !important; padding: 0 !important;
border: 0 !important; transform: none !important;
box-shadow: none !important;
`;
if (isOtherMonth) {
cell.style.background = 'rgba(30,41,59,0.4)';
cell.style.color = '#64748b';
} else if (isToday) {
cell.style.background = 'rgba(99,102,241,0.3)';
} else if (hasContest) {
cell.style.background = 'rgba(99,102,241,0.4)';
} else {
cell.style.background = 'rgba(30,41,59,0.8)';
}
if (isSelected) {
cell.dataset.originalBg = cell.style.background;
cell.style.background = 'rgba(245,158,11,0.3)';
state.selectedCell = cell;
}
const numSpan = document.createElement('span');
numSpan.className = 'day-num';
numSpan.style.lineHeight = '1';
numSpan.textContent = num;
cell.appendChild(numSpan);
if (isToday) {
const todayBadge = document.createElement('span');
todayBadge.className = 'today-badge';
todayBadge.style.cssText = 'position:absolute;top:2px;right:2px;width:16px;height:16px;border-radius:50%;background:#6366f1;color:white;font-size:10px;display:grid;place-items:center;';
todayBadge.textContent = '今';
cell.appendChild(todayBadge);
}
if (hasContest && dateStr) {
const contestBadge = document.createElement('span');
contestBadge.className = 'contest-badge';
contestBadge.style.cssText = 'position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:#ef4444;color:white;font-size:10px;display:grid;place-items:center;';
contestBadge.textContent = state.contests[dateStr].length;
cell.appendChild(contestBadge);
}
if (dateStr) cell.dataset.date = dateStr;
calendarGrid.appendChild(cell);
return cell;
}
function updateStats() {
const total = Object.values(state.contests).flat().length;
const todayContests = state.contests[state.today]?.length || 0;
document.getElementById('total-contests').textContent = total;
document.getElementById('today-contests').textContent = todayContests;
}
function adjustBtnLayout() {
const addBtn = document.getElementById('add-contest');
const todayBtn = document.getElementById('go-today');
const hasSel = addBtn.style.display === 'block';
if (hasSel) {
todayBtn.style.flex = '1';
} else {
todayBtn.style.flex = '0 0 100%';
}
}
// ---------- 按钮点击切换 ----------
toggleBtn.addEventListener('click', function (e) {
if (isDragging) {
isDragging = false;
return;
}
if (isVisible) {
mainContainer.style.display = 'none';
} else {
mainContainer.style.display = 'block';
positionCalendarNearButton();
}
isVisible = !isVisible;
});
// ---------- 拖动事件 ----------
toggleBtn.addEventListener('mousedown', function (e) {
isMouseDown = true;
isDragging = false;
startX = e.clientX;
startY = e.clientY;
const rect = toggleBtn.getBoundingClientRect();
startLeft = rect.left;
startTop = rect.top;
toggleBtn.style.cursor = 'grabbing';
e.preventDefault();
});
document.addEventListener('mousemove', function (e) {
if (!isMouseDown) return;
const dx = e.clientX - startX;
const dy = e.clientY - startY;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist > DRAG_THRESHOLD) {
isDragging = true;
}
if (isDragging) {
let newLeft = startLeft + dx;
let newTop = startTop + dy;
newLeft = Math.max(0, Math.min(window.innerWidth - toggleBtn.offsetWidth, newLeft));
newTop = Math.max(0, Math.min(window.innerHeight - toggleBtn.offsetHeight, newTop));
toggleBtn.style.left = newLeft + 'px';
toggleBtn.style.top = newTop + 'px';
if (isVisible && mainContainer.style.display === 'block') {
positionCalendarNearButton();
}
}
});
document.addEventListener('mouseup', function () {
if (isMouseDown) {
isMouseDown = false;
toggleBtn.style.cursor = 'grab';
if (isDragging) {
const rect = toggleBtn.getBoundingClientRect();
GM_setValue('toggleBtnPos', { left: rect.left, top: rect.top });
}
}
});
window.addEventListener('resize', function () {
if (isVisible && mainContainer.style.display === 'block') {
positionCalendarNearButton();
}
});
// ---------- 事件绑定(所有 Swal 都加大尺寸) ----------
closeBtn.addEventListener('click', () => {
mainContainer.style.display = 'none';
isVisible = false;
});
// 添加比赛
document.getElementById('add-contest').addEventListener('click', async () => {
if (!state.selectedDate) return;
const { value: form } = await Swal.fire({
title: '添加',
html: `
<input id="c-name" class="swal2-input" placeholder="名称">
<input id="c-time" class="swal2-input" placeholder="时间(可选)">
`,
confirmButtonText: '保存',
showCancelButton: true,
width: '650px',
padding: '2em'
});
const name = document.getElementById('c-name')?.value?.trim();
const time = document.getElementById('c-time')?.value?.trim();
if (!name) return;
if (!state.contests[state.selectedDate]) state.contests[state.selectedDate] = [];
state.contests[state.selectedDate].push({ name, time });
GM_setValue('contests', JSON.stringify(state.contests));
let badge = state.selectedCell.querySelector('.contest-badge');
if (!badge) {
badge = document.createElement('span');
badge.className = 'contest-badge';
badge.style.cssText = 'position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:#ef4444;color:white;font-size:10px;display:grid;place-items:center;';
state.selectedCell.appendChild(badge);
}
badge.textContent = state.contests[state.selectedDate].length;
state.selectedCell.style.background = 'rgba(99,102,241,0.4)';
state.selectedCell.dataset.originalBg = 'rgba(99,102,241,0.4)';
updateStats();
Swal.fire({
icon: 'success',
title: '添加成功',
timer: 1500,
width: '650px',
padding: '2em',
showConfirmButton: false
});
});
// 删除比赛
document.getElementById('del-contest').addEventListener('click', async () => {
const date = state.selectedDate;
if (!date || !state.contests[date]?.length) {
return Swal.fire({
icon: 'info',
title: '暂无数据',
width: '650px',
padding: '2em'
});
}
const list = state.contests[date];
let html = '';
list.forEach((c, i) => {
html += `
<label style="display:flex;align-items:center;gap:8px;padding:6px;background:#f8f9fa;border-radius:6px;margin:4px 0;">
<input type="checkbox" value="${i}" class="del-item">
<span>${c.name}</span>
</label>`;
});
const res = await Swal.fire({
title: '删除',
html: `<div style="text-align:left;">${html}</div>`,
confirmButtonText: '删除选中',
confirmButtonColor: '#ef4444',
showCancelButton: true,
width: '650px',
padding: '2em'
});
if (!res.isConfirmed) return;
const checks = document.querySelectorAll('.del-item:checked');
if (!checks.length) {
return Swal.fire({
icon: 'warning',
title: '请选择',
width: '650px',
padding: '2em'
});
}
const indexes = Array.from(checks).map(x => +x.value).sort((a, b) => b - a);
indexes.forEach(i => list.splice(i, 1));
const badge = state.selectedCell.querySelector('.contest-badge');
if (list.length === 0) {
delete state.contests[date];
badge?.remove();
state.selectedCell.style.background = 'rgba(30,41,59,0.8)';
state.selectedCell.dataset.originalBg = 'rgba(30,41,59,0.8)';
} else {
badge.textContent = list.length;
}
GM_setValue('contests', JSON.stringify(state.contests));
updateStats();
Swal.fire({
icon: 'success',
title: '删除成功',
timer: 1500,
width: '650px',
padding: '2em',
showConfirmButton: false
});
});
// 查看比赛
document.getElementById('view-contest').addEventListener('click', async () => {
const date = state.selectedDate;
if (!date) return;
const list = state.contests[date] || [];
if (list.length === 0) {
return Swal.fire({
icon: 'info',
title: '暂无数据',
width: '650px',
padding: '2em'
});
}
let html = '';
list.forEach((c, i) => {
html += `
<div style="text-align:left; padding:8px 12px; background:#f9fafb; border-radius:8px; margin-bottom:8px;">
<div style="font-weight:600; font-size:15px;">${i + 1}. ${c.name}</div>
${c.time ? `<div style="color:#6b7280; font-size:13px; margin-top:2px;">🕒 ${c.time}</div>` : ''}
</div>`;
});
await Swal.fire({
title: '列表',
html: html,
icon: 'info',
confirmButtonText: '关闭',
width: '650px',
padding: '2em'
});
});
// 月份切换和今日按钮
document.getElementById('prev-month').addEventListener('click', () => {
state.currentDate.setMonth(state.currentDate.getMonth() - 1);
state.selectedDate = state.selectedCell = null;
document.getElementById('add-contest').style.display = 'none';
document.getElementById('del-contest').style.display = 'none';
document.getElementById('view-contest').style.display = 'none';
document.getElementById('selected-tip').style.display = 'none';
adjustBtnLayout();
renderCalendar();
});
document.getElementById('next-month').addEventListener('click', () => {
state.currentDate.setMonth(state.currentDate.getMonth() + 1);
state.selectedDate = state.selectedCell = null;
document.getElementById('add-contest').style.display = 'none';
document.getElementById('del-contest').style.display = 'none';
document.getElementById('view-contest').style.display = 'none';
document.getElementById('selected-tip').style.display = 'none';
adjustBtnLayout();
renderCalendar();
});
document.getElementById('go-today').addEventListener('click', () => {
state.currentDate = new Date();
state.selectedDate = state.selectedCell = null;
document.getElementById('add-contest').style.display = 'none';
document.getElementById('del-contest').style.display = 'none';
document.getElementById('view-contest').style.display = 'none';
document.getElementById('selected-tip').style.display = 'none';
adjustBtnLayout();
renderCalendar();
});
// 初始渲染
renderCalendar();
adjustBtnLayout();
}
})();