Dictionary.js:修订间差异
来自卡厄思梦境WIKI
创建页面,内容为“(function() { 'use strict'; if (mw.config.get('wgPageName') !== 'MediaWiki:Dictionary') { return; } var API_URL = mw.util.wikiScript('api'); var dictionaryData = {}; // 加载词典数据 function loadDictionaryData() { $.ajax({ url: API_URL, data: { action: 'scribunto-console', title: 'Module:词典/data', question: 'return require…” |
无编辑摘要 |
||
| 第2行: | 第2行: | ||
'use strict'; | 'use strict'; | ||
// 添加调试日志 | |||
console.log('词典编辑器脚本已加载'); | |||
console.log('当前页面:', mw.config.get('wgPageName')); | |||
// 检查页面名称 | |||
if (mw.config.get('wgPageName') !== 'MediaWiki:Dictionary') { | if (mw.config.get('wgPageName') !== 'MediaWiki:Dictionary') { | ||
console.log('不是目标页面,脚本退出'); | |||
return; | return; | ||
} | } | ||
| 第11行: | 第17行: | ||
// 加载词典数据 | // 加载词典数据 | ||
function loadDictionaryData() { | function loadDictionaryData() { | ||
console.log('开始加载词典数据'); | |||
// 直接使用备用方案:从模块页面加载 | |||
loadFromModulePage(); | |||
} | |||
// 从模块页面加载数据 | |||
function loadFromModulePage() { | |||
console.log('从模块页面加载数据'); | |||
$.ajax({ | $.ajax({ | ||
url: | url: mw.util.getUrl('Module:词典/data', {action: 'raw'}), | ||
dataType: 'text', | |||
success: function(content) { | |||
console.log('成功获取模块内容'); | |||
try { | |||
dictionaryData = parseLuaTable(content); | |||
console.log('解析的数据:', dictionaryData); | |||
dataType: ' | renderDictionary(); | ||
success: function( | } catch(e) { | ||
console.error('解析Lua失败:', e); | |||
showError('解析数据失败: ' + e.message); | |||
} | } | ||
}, | }, | ||
error: function() { | error: function(xhr, status, error) { | ||
console.error('加载模块失败:', status, error); | |||
showError('加载数据失败,请检查Module:词典/data是否存在'); | |||
} | } | ||
}); | }); | ||
} | } | ||
// | // 显示错误信息 | ||
function | function showError(message) { | ||
$. | var container = findContentContainer(); | ||
container.empty(); | |||
$('<div>').addClass('errorbox').css({ | |||
'padding': '10px', | |||
'margin': '10px 0', | |||
console. | 'border': '1px solid #d33', | ||
'background-color': '#fee', | |||
'color': '#d33' | |||
}).text(message).appendTo(container); | |||
} | |||
// 查找内容容器 | |||
function findContentContainer() { | |||
// 尝试多个可能的选择器 | |||
var selectors = [ | |||
'#dictionary-editor', | |||
'#mw-content-text', | |||
'.mw-parser-output', | |||
'#bodyContent', | |||
'#content' | |||
]; | |||
var container; | |||
for (var i = 0; i < selectors.length; i++) { | |||
container = $(selectors[i]); | |||
if (container.length) { | |||
console.log('找到容器:', selectors[i]); | |||
break; | |||
} | } | ||
}); | } | ||
if (!container || !container.length) { | |||
console.error('找不到内容容器'); | |||
container = $('body'); | |||
} | |||
return container; | |||
} | } | ||
// | // 简单的Lua表解析器(改进版) | ||
function parseLuaTable(luaContent) { | function parseLuaTable(luaContent) { | ||
var result = {}; | var result = {}; | ||
var dictMatch = luaContent.match(/data\.dictionary\s*=\s*\{([\s\S]*?)\}/); | console.log('开始解析Lua表'); | ||
if (!dictMatch) | |||
// 查找 dictionary 表 | |||
var dictMatch = luaContent.match(/data\.dictionary\s*=\s*\{([\s\S]*?)\n\}/); | |||
if (!dictMatch) { | |||
console.error('找不到dictionary表'); | |||
throw new Error('找不到dictionary表定义'); | |||
} | |||
var content = dictMatch[1]; | var content = dictMatch[1]; | ||
var entryRegex = /\["([^"]+)"\]\s*=\s*\{([\s\S]*?)\} | console.log('提取的内容长度:', content.length); | ||
// 匹配每个词条 | |||
var entryRegex = /\["([^"]+)"\]\s*=\s*\{([\s\S]*?)\n \}/g; | |||
var match; | var match; | ||
var count = 0; | |||
while ((match = entryRegex.exec(content)) !== null) { | while ((match = entryRegex.exec(content)) !== null) { | ||
| 第63行: | 第113行: | ||
var itemsContent = match[2]; | var itemsContent = match[2]; | ||
result[key] = []; | result[key] = []; | ||
count++; | |||
// 匹配每个定义 | |||
var itemRegex = /\{([^}]+)\}/g; | var itemRegex = /\{([^}]+)\}/g; | ||
var itemMatch; | var itemMatch; | ||
| 第78行: | 第130行: | ||
} | } | ||
} | } | ||
console.log('解析了', count, '个词条'); | |||
return result; | return result; | ||
} | } | ||
| 第83行: | 第137行: | ||
// 渲染词典界面 | // 渲染词典界面 | ||
function renderDictionary() { | function renderDictionary() { | ||
var container = | console.log('开始渲染词典界面'); | ||
container = $('<div>').attr('id', 'dictionary-editor').appendTo( | var container = findContentContainer(); | ||
// 清空现有内容 | |||
if (container.attr('id') !== 'dictionary-editor') { | |||
container.empty(); | |||
container = $('<div>').attr('id', 'dictionary-editor').appendTo(container); | |||
} else { | |||
container.empty(); | |||
} | } | ||
// 添加样式 | |||
addStyles(); | |||
// 添加标题和新建按钮 | // 添加标题和新建按钮 | ||
| 第98行: | 第160行: | ||
var list = $('<div>').addClass('dict-list').appendTo(container); | var list = $('<div>').addClass('dict-list').appendTo(container); | ||
Object.keys(dictionaryData).sort().forEach(function(key) { | var keys = Object.keys(dictionaryData).sort(); | ||
console.log('渲染', keys.length, '个词条'); | |||
if (keys.length === 0) { | |||
$('<div>').css({'padding': '20px', 'text-align': 'center', 'color': '#666'}) | |||
.text('暂无词条,点击"新建词条"添加') | |||
.appendTo(list); | |||
return; | |||
} | |||
keys.forEach(function(key) { | |||
var items = dictionaryData[key]; | var items = dictionaryData[key]; | ||
items.forEach(function(item, index) { | items.forEach(function(item, index) { | ||
| 第121行: | 第193行: | ||
}); | }); | ||
}); | }); | ||
console.log('渲染完成'); | |||
} | |||
// 添加样式 | |||
function addStyles() { | |||
if ($('#dict-editor-styles').length) return; | |||
var css = ` | |||
.dict-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px; } | |||
.dict-title { font-size: 24px; font-weight: bold; } | |||
.dict-btn { padding: 8px 16px; border-radius: 4px; cursor: pointer; display: inline-block; transition: all 0.2s; } | |||
.dict-btn:hover { opacity: 0.8; } | |||
.dict-btn-primary { background: #0645ad; color: white; } | |||
.dict-btn-secondary { background: #eee; color: #333; } | |||
.dict-btn-danger { background: #d33; color: white; } | |||
.dict-btn-small { padding: 4px 12px; font-size: 12px; } | |||
.dict-list { display: flex; flex-direction: column; gap: 15px; } | |||
.dict-entry { border: 1px solid #ddd; border-radius: 8px; overflow: hidden; } | |||
.dict-entry-header { background: #f8f9fa; padding: 12px; display: flex; justify-content: space-between; align-items: center; } | |||
.dict-entry-name { font-weight: bold; font-size: 16px; } | |||
.dict-entry-actions { display: flex; gap: 8px; } | |||
.dict-entry-body { padding: 12px; } | |||
.dict-field { margin: 8px 0; } | |||
.dict-label { font-weight: bold; color: #666; } | |||
.dict-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center; } | |||
.dict-dialog { background: white; border-radius: 8px; width: 500px; max-width: 90%; max-height: 90vh; overflow-y: auto; } | |||
.dict-dialog-title { padding: 16px; border-bottom: 1px solid #ddd; font-size: 18px; font-weight: bold; } | |||
.dict-form { padding: 16px; } | |||
.dict-form-group { margin-bottom: 16px; } | |||
.dict-form-label { margin-bottom: 4px; font-weight: bold; } | |||
.dict-input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; } | |||
.dict-dialog-actions { padding: 16px; border-top: 1px solid #ddd; display: flex; justify-content: flex-end; gap: 8px; } | |||
.dict-select-wrapper { position: relative; } | |||
.dict-select { padding: 8px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; background: white; } | |||
.dict-dropdown { position: absolute; top: 100%; left: 0; right: 0; border: 1px solid #ddd; border-radius: 4px; background: white; margin-top: 4px; display: none; z-index: 1000; max-height: 200px; overflow-y: auto; } | |||
.dict-option { padding: 8px; cursor: pointer; } | |||
.dict-option:hover { background: #f0f0f0; } | |||
`; | |||
$('<style>').attr('id', 'dict-editor-styles').text(css).appendTo('head'); | |||
} | } | ||
| 第139行: | 第252行: | ||
// 显示编辑对话框 | // 显示编辑对话框 | ||
function showEditDialog(key, index) { | function showEditDialog(key, index) { | ||
var item = dictionaryData[key]; | var item = dictionaryData[key][index]; | ||
var data = $.extend({name: key}, item | var data = $.extend({name: key}, item); | ||
showDialog('编辑词条', data, function(newData) { | showDialog('编辑词条', data, function(newData) { | ||
| 第286行: | 第399行: | ||
var luaCode = generateLuaCode(); | var luaCode = generateLuaCode(); | ||
// 使用新的API获取token | |||
new mw.Api().postWithToken('csrf', { | |||
action: 'edit', | action: 'edit', | ||
title: 'Module:词典/data', | title: 'Module:词典/data', | ||
text: luaCode, | text: luaCode, | ||
summary: '通过词典编辑器更新 | summary: '通过词典编辑器更新' | ||
}).done(function(response) { | }).done(function(response) { | ||
if (response.edit && response.edit.result === 'Success') { | if (response.edit && response.edit.result === 'Success') { | ||
mw.notify('保存成功!', {type: 'success'}); | mw.notify('保存成功!', {type: 'success'}); | ||
loadDictionaryData(); // 重新加载数据 | |||
} else { | } else { | ||
mw.notify('保存失败:' + (response.error ? response.error.info : '未知错误'), {type: 'error'}); | mw.notify('保存失败:' + (response.error ? response.error.info : '未知错误'), {type: 'error'}); | ||
} | } | ||
}).fail(function() { | }).fail(function(code, result) { | ||
mw.notify(' | console.error('保存失败:', code, result); | ||
mw.notify('保存失败:' + (result.error ? result.error.info : '网络错误'), {type: 'error'}); | |||
}); | }); | ||
} | } | ||
| 第325行: | 第438行: | ||
}); | }); | ||
lines.push('}', '', 'return data | lines.push('}', '', 'return data'); | ||
return lines.join('\n'); | return lines.join('\n'); | ||
} | } | ||
// 初始化 | // 初始化 - 确保DOM已加载 | ||
$(function() { | if (document.readyState === 'loading') { | ||
$(document).ready(function() { | |||
console.log('DOM已加载,初始化词典编辑器'); | |||
loadDictionaryData(); | |||
}); | |||
} else { | |||
console.log('DOM已经准备好,立即初始化'); | |||
loadDictionaryData(); | loadDictionaryData(); | ||
} | } | ||
})(); | })(); | ||
2025年10月3日 (五) 19:02的版本
(function() {
'use strict';
// 添加调试日志
console.log('词典编辑器脚本已加载');
console.log('当前页面:', mw.config.get('wgPageName'));
// 检查页面名称
if (mw.config.get('wgPageName') !== 'MediaWiki:Dictionary') {
console.log('不是目标页面,脚本退出');
return;
}
var API_URL = mw.util.wikiScript('api');
var dictionaryData = {};
// 加载词典数据
function loadDictionaryData() {
console.log('开始加载词典数据');
// 直接使用备用方案:从模块页面加载
loadFromModulePage();
}
// 从模块页面加载数据
function loadFromModulePage() {
console.log('从模块页面加载数据');
$.ajax({
url: mw.util.getUrl('Module:词典/data', {action: 'raw'}),
dataType: 'text',
success: function(content) {
console.log('成功获取模块内容');
try {
dictionaryData = parseLuaTable(content);
console.log('解析的数据:', dictionaryData);
renderDictionary();
} catch(e) {
console.error('解析Lua失败:', e);
showError('解析数据失败: ' + e.message);
}
},
error: function(xhr, status, error) {
console.error('加载模块失败:', status, error);
showError('加载数据失败,请检查Module:词典/data是否存在');
}
});
}
// 显示错误信息
function showError(message) {
var container = findContentContainer();
container.empty();
$('<div>').addClass('errorbox').css({
'padding': '10px',
'margin': '10px 0',
'border': '1px solid #d33',
'background-color': '#fee',
'color': '#d33'
}).text(message).appendTo(container);
}
// 查找内容容器
function findContentContainer() {
// 尝试多个可能的选择器
var selectors = [
'#dictionary-editor',
'#mw-content-text',
'.mw-parser-output',
'#bodyContent',
'#content'
];
var container;
for (var i = 0; i < selectors.length; i++) {
container = $(selectors[i]);
if (container.length) {
console.log('找到容器:', selectors[i]);
break;
}
}
if (!container || !container.length) {
console.error('找不到内容容器');
container = $('body');
}
return container;
}
// 简单的Lua表解析器(改进版)
function parseLuaTable(luaContent) {
var result = {};
console.log('开始解析Lua表');
// 查找 dictionary 表
var dictMatch = luaContent.match(/data\.dictionary\s*=\s*\{([\s\S]*?)\n\}/);
if (!dictMatch) {
console.error('找不到dictionary表');
throw new Error('找不到dictionary表定义');
}
var content = dictMatch[1];
console.log('提取的内容长度:', content.length);
// 匹配每个词条
var entryRegex = /\["([^"]+)"\]\s*=\s*\{([\s\S]*?)\n \}/g;
var match;
var count = 0;
while ((match = entryRegex.exec(content)) !== null) {
var key = match[1];
var itemsContent = match[2];
result[key] = [];
count++;
// 匹配每个定义
var itemRegex = /\{([^}]+)\}/g;
var itemMatch;
while ((itemMatch = itemRegex.exec(itemsContent)) !== null) {
var item = {};
var props = itemMatch[1].split(',');
props.forEach(function(prop) {
var propMatch = prop.match(/\["([^"]+)"\]\s*=\s*"([^"]*)"/);
if (propMatch) {
item[propMatch[1]] = propMatch[2];
}
});
result[key].push(item);
}
}
console.log('解析了', count, '个词条');
return result;
}
// 渲染词典界面
function renderDictionary() {
console.log('开始渲染词典界面');
var container = findContentContainer();
// 清空现有内容
if (container.attr('id') !== 'dictionary-editor') {
container.empty();
container = $('<div>').attr('id', 'dictionary-editor').appendTo(container);
} else {
container.empty();
}
// 添加样式
addStyles();
// 添加标题和新建按钮
var header = $('<div>').addClass('dict-header').appendTo(container);
$('<div>').addClass('dict-title').text('词典编辑器').appendTo(header);
$('<div>').addClass('dict-btn dict-btn-primary').text('+ 新建词条').click(showAddEntryDialog).appendTo(header);
// 渲染词条列表
var list = $('<div>').addClass('dict-list').appendTo(container);
var keys = Object.keys(dictionaryData).sort();
console.log('渲染', keys.length, '个词条');
if (keys.length === 0) {
$('<div>').css({'padding': '20px', 'text-align': 'center', 'color': '#666'})
.text('暂无词条,点击"新建词条"添加')
.appendTo(list);
return;
}
keys.forEach(function(key) {
var items = dictionaryData[key];
items.forEach(function(item, index) {
var entry = $('<div>').addClass('dict-entry').appendTo(list);
var entryHeader = $('<div>').addClass('dict-entry-header').appendTo(entry);
$('<div>').addClass('dict-entry-name').text(key).appendTo(entryHeader);
var actions = $('<div>').addClass('dict-entry-actions').appendTo(entryHeader);
$('<div>').addClass('dict-btn dict-btn-small').text('编辑')
.click(function() { showEditDialog(key, index); }).appendTo(actions);
$('<div>').addClass('dict-btn dict-btn-small dict-btn-danger').text('删除')
.click(function() { deleteEntry(key, index); }).appendTo(actions);
var entryBody = $('<div>').addClass('dict-entry-body').appendTo(entry);
var colorClass = 'dict-color-' + (item['颜色'] || 'white');
$('<div>').addClass('dict-field').html('<span class="dict-label">颜色:</span> <span class="' + colorClass + '">' + (item['颜色'] || '') + '</span>').appendTo(entryBody);
$('<div>').addClass('dict-field').html('<span class="dict-label">类型:</span> ' + (item['类型'] || '')).appendTo(entryBody);
$('<div>').addClass('dict-field').html('<span class="dict-label">图标:</span> ' + (item['icon'] || '')).appendTo(entryBody);
$('<div>').addClass('dict-field').html('<span class="dict-label">描述:</span> ' + (item['描述'] || '')).appendTo(entryBody);
});
});
console.log('渲染完成');
}
// 添加样式
function addStyles() {
if ($('#dict-editor-styles').length) return;
var css = `
.dict-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px; }
.dict-title { font-size: 24px; font-weight: bold; }
.dict-btn { padding: 8px 16px; border-radius: 4px; cursor: pointer; display: inline-block; transition: all 0.2s; }
.dict-btn:hover { opacity: 0.8; }
.dict-btn-primary { background: #0645ad; color: white; }
.dict-btn-secondary { background: #eee; color: #333; }
.dict-btn-danger { background: #d33; color: white; }
.dict-btn-small { padding: 4px 12px; font-size: 12px; }
.dict-list { display: flex; flex-direction: column; gap: 15px; }
.dict-entry { border: 1px solid #ddd; border-radius: 8px; overflow: hidden; }
.dict-entry-header { background: #f8f9fa; padding: 12px; display: flex; justify-content: space-between; align-items: center; }
.dict-entry-name { font-weight: bold; font-size: 16px; }
.dict-entry-actions { display: flex; gap: 8px; }
.dict-entry-body { padding: 12px; }
.dict-field { margin: 8px 0; }
.dict-label { font-weight: bold; color: #666; }
.dict-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center; }
.dict-dialog { background: white; border-radius: 8px; width: 500px; max-width: 90%; max-height: 90vh; overflow-y: auto; }
.dict-dialog-title { padding: 16px; border-bottom: 1px solid #ddd; font-size: 18px; font-weight: bold; }
.dict-form { padding: 16px; }
.dict-form-group { margin-bottom: 16px; }
.dict-form-label { margin-bottom: 4px; font-weight: bold; }
.dict-input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
.dict-dialog-actions { padding: 16px; border-top: 1px solid #ddd; display: flex; justify-content: flex-end; gap: 8px; }
.dict-select-wrapper { position: relative; }
.dict-select { padding: 8px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; background: white; }
.dict-dropdown { position: absolute; top: 100%; left: 0; right: 0; border: 1px solid #ddd; border-radius: 4px; background: white; margin-top: 4px; display: none; z-index: 1000; max-height: 200px; overflow-y: auto; }
.dict-option { padding: 8px; cursor: pointer; }
.dict-option:hover { background: #f0f0f0; }
`;
$('<style>').attr('id', 'dict-editor-styles').text(css).appendTo('head');
}
// 显示添加词条对话框
function showAddEntryDialog() {
showDialog('新建词条', {}, function(data) {
var name = data.name;
delete data.name;
if (!dictionaryData[name]) {
dictionaryData[name] = [];
}
dictionaryData[name].push(data);
saveDictionary();
}, true);
}
// 显示编辑对话框
function showEditDialog(key, index) {
var item = dictionaryData[key][index];
var data = $.extend({name: key}, item);
showDialog('编辑词条', data, function(newData) {
var newName = newData.name;
delete newData.name;
if (newName !== key) {
// 名称改变,删除旧的
dictionaryData[key].splice(index, 1);
if (dictionaryData[key].length === 0) {
delete dictionaryData[key];
}
if (!dictionaryData[newName]) {
dictionaryData[newName] = [];
}
dictionaryData[newName].push(newData);
} else {
dictionaryData[key][index] = newData;
}
saveDictionary();
}, false);
}
// 显示对话框
function showDialog(title, data, callback, isNew) {
var overlay = $('<div>').addClass('dict-overlay').appendTo('body');
var dialog = $('<div>').addClass('dict-dialog').appendTo(overlay);
$('<div>').addClass('dict-dialog-title').text(title).appendTo(dialog);
var form = $('<div>').addClass('dict-form').appendTo(dialog);
// 名称字段
var nameField = createField('名称', 'text', data.name || '', isNew);
form.append(nameField);
// 类型字段(下拉)
var typeField = createSelectField('类型', ['卡牌机制', '战斗员专属机制', 'buff', 'debuff'], data['类型'] || '');
form.append(typeField);
// 颜色字段(下拉)
var colorField = createSelectField('颜色', ['白', '蓝', '红', '橙', '彩'], data['颜色'] || '');
form.append(colorField);
// 图标字段
var iconField = createField('图标', 'text', data['icon'] || '', true);
form.append(iconField);
// 描述字段
var descField = createField('描述', 'textarea', data['描述'] || '', true);
form.append(descField);
var actions = $('<div>').addClass('dict-dialog-actions').appendTo(dialog);
$('<div>').addClass('dict-btn dict-btn-secondary').text('取消').click(function() {
overlay.remove();
}).appendTo(actions);
$('<div>').addClass('dict-btn dict-btn-primary').text('保存').click(function() {
var formData = {
name: nameField.find('input').val(),
'类型': typeField.find('.dict-select').attr('data-value'),
'颜色': colorField.find('.dict-select').attr('data-value'),
'icon': iconField.find('input').val(),
'描述': descField.find('textarea').val()
};
if (!formData.name) {
alert('请输入名称');
return;
}
overlay.remove();
callback(formData);
}).appendTo(actions);
}
// 创建表单字段
function createField(label, type, value, editable) {
var field = $('<div>').addClass('dict-form-group');
$('<div>').addClass('dict-form-label').text(label + ':').appendTo(field);
var input;
if (type === 'textarea') {
input = $('<textarea>').addClass('dict-input').val(value).attr('rows', 3);
} else {
input = $('<input>').addClass('dict-input').attr('type', type).val(value);
}
if (!editable) {
input.attr('readonly', 'readonly');
}
input.appendTo(field);
return field;
}
// 创建下拉选择字段
function createSelectField(label, options, value) {
var field = $('<div>').addClass('dict-form-group');
$('<div>').addClass('dict-form-label').text(label + ':').appendTo(field);
var selectWrapper = $('<div>').addClass('dict-select-wrapper').appendTo(field);
var selectDisplay = $('<div>').addClass('dict-select')
.attr('data-value', value || options[0])
.text(value || options[0])
.appendTo(selectWrapper);
var dropdown = $('<div>').addClass('dict-dropdown').appendTo(selectWrapper);
options.forEach(function(opt) {
$('<div>').addClass('dict-option').text(opt).click(function() {
selectDisplay.text(opt).attr('data-value', opt);
dropdown.hide();
}).appendTo(dropdown);
});
selectDisplay.click(function(e) {
e.stopPropagation();
$('.dict-dropdown').hide();
dropdown.toggle();
});
$(document).click(function() {
dropdown.hide();
});
return field;
}
// 删除词条
function deleteEntry(key, index) {
if (!confirm('确定要删除这个词条吗?')) {
return;
}
dictionaryData[key].splice(index, 1);
if (dictionaryData[key].length === 0) {
delete dictionaryData[key];
}
saveDictionary();
}
// 保存词典到模块
function saveDictionary() {
var luaCode = generateLuaCode();
// 使用新的API获取token
new mw.Api().postWithToken('csrf', {
action: 'edit',
title: 'Module:词典/data',
text: luaCode,
summary: '通过词典编辑器更新'
}).done(function(response) {
if (response.edit && response.edit.result === 'Success') {
mw.notify('保存成功!', {type: 'success'});
loadDictionaryData(); // 重新加载数据
} else {
mw.notify('保存失败:' + (response.error ? response.error.info : '未知错误'), {type: 'error'});
}
}).fail(function(code, result) {
console.error('保存失败:', code, result);
mw.notify('保存失败:' + (result.error ? result.error.info : '网络错误'), {type: 'error'});
});
}
// 生成Lua代码
function generateLuaCode() {
var lines = ['local data = {}', '', 'data.dictionary = {'];
var keys = Object.keys(dictionaryData).sort();
keys.forEach(function(key, keyIndex) {
lines.push(' ["' + key + '"] = {');
dictionaryData[key].forEach(function(item, itemIndex) {
lines.push(' {');
lines.push(' ["icon"] = "' + (item.icon || '') + '",');
lines.push(' ["类型"] = "' + (item['类型'] || '') + '",');
lines.push(' ["颜色"] = "' + (item['颜色'] || '') + '",');
lines.push(' ["描述"] = "' + (item['描述'] || '') + '",');
lines.push(' }' + (itemIndex < dictionaryData[key].length - 1 ? ',' : ''));
});
lines.push(' }' + (keyIndex < keys.length - 1 ? ',' : ''));
});
lines.push('}', '', 'return data');
return lines.join('\n');
}
// 初始化 - 确保DOM已加载
if (document.readyState === 'loading') {
$(document).ready(function() {
console.log('DOM已加载,初始化词典编辑器');
loadDictionaryData();
});
} else {
console.log('DOM已经准备好,立即初始化');
loadDictionaryData();
}
})();