Files
window-axis-innovators-box/javascript/HtmlViewer.html
tzdwindows 7 adf659853d feat(browser): 实现Java字体和主题动态同步到HTML界面
- 添加javaFontsLoaded和javaThemeChanged事件监听机制
- 在BrowserWindow和BrowserWindowJDialog中实现字体信息获取和注入
- 前端HTML文件增加对应的字体应用逻辑和样式更新
- 创建WindowRegistry统一管理窗口主题更新
- 更新README文档说明HTML事件使用方法- 支持Monaco和CodeMirror编辑器的字体动态调整
-优化CEF浏览器与Java UI的字体和主题同步流程
2025-10-05 19:49:53 +08:00

518 lines
17 KiB
HTML

<!DOCTYPE html>
<html lang="zh-CN" data-theme="dark">
<head>
<meta charset="UTF-8">
<title>Axis Innovators Pro</title>
<!-- CodeMirror 资源 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/theme/material-darker.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/theme/nord.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/show-hint.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/mode/xml/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/edit/closetag.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/show-hint.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/xml-hint.min.js"></script>
<style>
:root {
--bg-color: #1a1a1a;
--text-color: #e0e0e0;
--border-color: #404040;
--toolbar-bg: #2d2d2d;
--primary-color: #4dabf7;
--hover-color: #339af0;
--success: #69db7c;
--warning: #ffd43b;
--error: #ff6b6b;
--radius: 6px;
}
[data-theme="light"] {
--bg-color: #f8f9fa;
--text-color: #343a40;
--border-color: #dee2e6;
--toolbar-bg: #e9ecef;
--primary-color: #4dabf7;
--hover-color: #339af0;
}
* {
box-sizing: border-box;
font-family: 'Fira Code', 'JetBrains Mono', monospace;
}
body {
margin: 0;
height: 100vh;
display: flex;
flex-direction: column;
background-color: var(--bg-color);
color: var(--text-color);
}
.toolbar {
padding: 12px 24px;
background-color: var(--toolbar-bg);
display: flex;
gap: 18px;
align-items: center;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.container {
flex: 1;
display: flex;
height: calc(100vh - 56px);
}
.editor-pane {
width: 50%;
position: relative;
border-right: 1px solid var(--border-color);
}
.preview-container {
width: 50%;
display: flex;
flex-direction: column;
background: var(--bg-color);
}
#preview {
flex: 1;
border: none;
background: white;
}
.output-pane {
height: 200px;
border-top: 1px solid var(--border-color);
background: var(--toolbar-bg);
overflow-y: auto;
padding: 12px;
}
.log-item {
padding: 8px 12px;
margin: 4px 0;
border-radius: var(--radius);
display: flex;
align-items: center;
gap: 10px;
font-size: 13px;
background: rgba(0,0,0,0.1);
}
.log-item.error {
color: var(--error);
border-left: 3px solid var(--error);
}
.log-item.warning {
color: var(--warning);
border-left: 3px solid var(--warning);
}
.CodeMirror {
height: 100% !important;
font-size: 14px;
line-height: 1.5;
padding: 16px 0;
}
.cm-editor {
border-radius: 0;
}
button {
background: var(--primary-color);
color: white;
border: none;
padding: 8px 16px;
border-radius: var(--radius);
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
button:hover {
background: var(--hover-color);
transform: translateY(-1px);
}
select {
padding: 8px 32px 8px 12px;
border-radius: var(--radius);
border: 1px solid var(--border-color);
background: var(--bg-color) url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23ffffff'%3e%3cpath d='M7 10l5 5 5-5z'/%3e%3c/svg%3e") no-repeat right 8px center/12px;
color: var(--text-color);
appearance: none;
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23999'%3e%3cpath d='M7 10l5 5 5-5z'/%3e%3c/svg%3e");
}
.file-info {
margin-left: auto;
display: flex;
align-items: center;
gap: 12px;
font-size: 13px;
}
.resizer {
width: 8px;
background: var(--primary-color);
cursor: col-resize;
position: absolute;
right: -4px;
top: 0;
bottom: 0;
z-index: 10;
opacity: 0;
transition: opacity 0.2s;
}
.editor-pane:hover .resizer {
opacity: 1;
}
</style>
</head>
<body>
<div class="toolbar">
<select id="theme-selector" onchange="toggleTheme(this.value)">
<option value="dark">🌙 深色主题</option>
<option value="light">☀️ 浅色主题</option>
</select>
</div>
<div class="container">
<div class="editor-pane">
<textarea id="code-editor"></textarea>
<div class="resizer" onmousedown="startResize(event)"></div>
</div>
<div class="preview-container">
<iframe id="preview"></iframe>
<div class="output-pane" id="output"></div>
</div>
</div>
<input type="file" id="file-input" accept=".html" onchange="loadFile(this.files[0])">
<script>
// 初始化代码编辑器
const editor = CodeMirror.fromTextArea(document.getElementById('code-editor'), {
mode: "xml",
theme: "material-darker",
lineNumbers: true,
lineWrapping: true,
autoCloseTags: true,
matchTags: {bothTags: true},
extraKeys: {
"'<'": function(cm) {
cm.showHint({completeSingle: false});
},
"Ctrl-Space": "autocomplete",
"Tab": "emmetExpandAbbreviation"
},
hintOptions: {
schemaInfo: {}
},
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
});
// 实时预览
let updateTimeout;
editor.on("change", () => {
clearTimeout(updateTimeout);
updateTimeout = setTimeout(updatePreview, 300);
});
function updatePreview() {
const content = editor.getValue();
const fullHTML = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
margin: 20px;
font-family: system-ui;
}
</style>
</head>
<body>${content}</body>
</html>
`;
const blob = new Blob([fullHTML], {type: 'text/html;charset=utf-8'});
const url = URL.createObjectURL(blob);
const iframe = document.getElementById('preview');
// 添加错误处理
iframe.onload = function() {
try {
const doc = iframe.contentDocument || iframe.contentWindow.document;
const errors = [];
// 检测解析错误
const parser = new DOMParser();
const parsedDoc = parser.parseFromString(content, "text/html");
const parserErrors = parsedDoc.getElementsByTagName("parsererror");
if (parserErrors.length > 0) {
errors.push({
type: 'error',
message: 'HTML语法错误: ' + parserErrors[0].textContent
});
}
// 检测控制台错误
const consoleErrors = [];
const originalConsoleError = console.error;
console.error = function(message) {
consoleErrors.push(message);
originalConsoleError.apply(console, arguments);
};
// 触发重新解析
doc.open();
doc.write(fullHTML);
doc.close();
consoleErrors.forEach(msg => {
errors.push({type: 'error', message: msg});
});
updateOutput(errors);
URL.revokeObjectURL(url); // 释放内存
} catch(e) {
addLog('error', '预览加载失败: ' + e.message);
}
};
// 设置src最后执行
iframe.src = url;
}
// 输出控制台
function addLog(type, message) {
const output = document.getElementById('output');
const item = document.createElement('div');
item.className = `log-item ${type}`;
item.innerHTML = `
<i class="fas ${type === 'error' ? 'fa-times-circle' : 'fa-exclamation-triangle'}"></i>
${new Date().toLocaleTimeString()}: ${message}
`;
output.appendChild(item);
output.scrollTop = output.scrollHeight;
}
function updateOutput(errors) {
const output = document.getElementById('output');
output.innerHTML = '';
errors.forEach(e => addLog(e.type, e.message));
}
// 主题切换
function toggleTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
editor.setOption("theme", theme === 'dark' ? 'material-darker' : 'nord');
}
// 文件操作
function loadFile(file) {
const reader = new FileReader();
reader.onload = (e) => {
editor.setValue(e.target.result);
document.getElementById('file-name').textContent = file.name;
};
reader.readAsText(file);
}
// 窗口大小调整
let isResizing = false;
function startResize(e) {
isResizing = true;
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', stopResize);
}
function onMouseMove(e) {
if (!isResizing) return;
const container = document.querySelector('.container');
const editorPane = document.querySelector('.editor-pane');
const previewPane = document.querySelector('.preview-container');
const containerWidth = container.offsetWidth;
const newWidth = (e.clientX / containerWidth) * 100;
editorPane.style.width = Math.min(Math.max(newWidth, 20), 80) + '%';
previewPane.style.width = (100 - newWidth) + '%';
}
function stopResize() {
isResizing = false;
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', stopResize);
}
window.addEventListener('error', function(e) {
addLog('error', `运行时错误: ${e.message} (${e.lineno}:${e.colno})`);
});
// 初始化
window.addEventListener('load', () => {
// 初始化后立即更新预览
updatePreview();
// 添加编辑器变更的防抖处理
editor.on("change", () => {
clearTimeout(updateTimeout);
updateTimeout = setTimeout(() => {
updatePreview();
}, 500); // 调整为500ms防抖
});
});
(function() {
// 存储回调的映射
const callbacks = new Map();
let requestId = 0;
// 实现cefQuery规范
window.cefQuery = function(config) {
const currentId = ++requestId;
callbacks.set(currentId, {
onSuccess: config.onSuccess,
onFailure: config.onFailure
});
// 发送到Java端
window.javaMessageRouterQuery({
request: JSON.stringify({
id: currentId,
data: config.request
}),
onSuccess: (response) => {
const cb = callbacks.get(currentId);
cb?.onSuccess(response);
callbacks.delete(currentId);
},
onFailure: (error, code) => {
const cb = callbacks.get(currentId);
cb?.onFailure?.(error, code);
callbacks.delete(currentId);
}
});
};
// 初始化逻辑
document.addEventListener('DOMContentLoaded', () => {
window.cefQuery({
request: JSON.stringify({ type: "loadInitialContent" }),
onSuccess: (response) => {
try {
if (window.javaMessageHandler?.loadContent) {
javaMessageHandler.loadContent(response, '默认文档');
}
} catch(e) {
console.error('内容处理失败:', e);
}
},
onFailure: (error, code) => {
console.error(`加载失败 (CODE ${code}):`, error);
showErrorDialog(`加载失败: ${error}`);
}
});
});
// 错误显示函数
function showErrorDialog(msg) {
const dialog = document.createElement('div');
dialog.style = `/* 样式代码 */`;
dialog.innerHTML = `
<div class="error-dialog">
<i class="fa fa-exclamation-triangle"></i>
<p>${msg}</p>
<button onclick="this.parentElement.remove()">确定</button>
</div>
`;
document.body.appendChild(dialog);
}
})();
// 监听Java字体加载事件
document.addEventListener('javaFontsLoaded', function(event) {
const fontInfo = event.detail;
console.log('接收到Java字体信息:', fontInfo);
// 应用Java字体到编辑器
applyJavaFonts(fontInfo);
});
// 应用Java字体的函数
function applyJavaFonts(fontInfo) {
const uiFonts = fontInfo.uiFonts || {};
const defaultFont = fontInfo.defaultFont || uiFonts['Label.font'] || {};
if (defaultFont && defaultFont.family) {
const fontFamily = defaultFont.family;
const fontSize = defaultFont.size || 14;
const fontWeight = defaultFont.bold ? 'bold' : 'normal';
const fontStyle = defaultFont.italic ? 'italic' : 'normal';
// 创建字体样式
const style = document.createElement('style');
style.textContent = `
body, html {
font-family: '${fontFamily}', 'Fira Code', 'JetBrains Mono', monospace !important;
}
.toolbar, button, select {
font-family: '${fontFamily}', 'Fira Code', 'JetBrains Mono', monospace !important;
}
.log-item {
font-family: '${fontFamily}', 'Fira Code', 'JetBrains Mono', monospace !important;
font-size: ${fontSize}px !important;
}
.CodeMirror {
font-family: '${fontFamily}', 'Fira Code', 'JetBrains Mono', monospace !important;
font-size: ${fontSize}px !important;
}
`;
// 添加到文档头
document.head.appendChild(style);
// 更新CodeMirror编辑器字体
if (window.editor) {
editor.refresh(); // 刷新编辑器以应用新字体
}
console.log('Java字体已应用到HTML编辑器:', fontFamily, fontSize + 'px');
}
}
// 如果字体信息已经存在,立即应用
if (typeof window.javaFontInfo !== 'undefined') {
applyJavaFonts(window.javaFontInfo);
}
window.javaMessageHandler = {
loadContent: (content, fileName) => {
editor.setValue(content);
document.getElementById('file-name').textContent = fileName || '';
updatePreview();
},
setTheme: (theme) => {
toggleTheme(theme);
document.getElementById('theme-selector').value = theme;
}
};
</script>
</body>
</html>