Fix Alpine.js initialization by moving oraEditor function to <head>

- oraEditor function now defined in <head> before x-data directive
- Added <body> tag with x-data attribute
- Added canvas click handler using () to access Alpine instance
- Added id to imageContainer for canvas interaction
- All tests passing (16/16)
This commit is contained in:
2026-03-27 09:21:56 -07:00
parent 1a0b231a7b
commit e66fa4d715

View File

@@ -12,11 +12,342 @@
::-webkit-scrollbar-thumb { background: #6B7280; border-radius: 4px; }
.polygon-point { position: absolute; width: 8px; height: 8px; background: #0F0; border-radius: 50%; transform: translate(-50%, -50%); pointer-events: none; }
</style>
<!-- Alpine data component - MUST be defined before x-data directive -->
<script>
function oraEditor() {
return {
// File state
filePath: '',
oraPath: '',
layers: [],
// Image dimensions
imageWidth: 800,
imageHeight: 600,
// Selection state
selectedLayer: null,
// Polygon state
isDrawing: false,
polygonPoints: [],
polygonColor: '#FF0000',
polygonWidth: 2,
polygonPreviewUrl: null,
// Mask extraction state
maskSubject: '',
usePolygonHint: true,
isExtracting: false,
showMaskModal: false,
tempMaskPath: null,
tempMaskUrl: null,
lastError: '',
// Settings
showSettings: false,
comfyUrl: localStorage.getItem('ora_comfy_url') || '127.0.0.1:8188',
// Loading/error state
isLoading: false,
error: '',
init() {
console.log('ORA Editor initialized');
this.setupKeyHandlers();
},
setupKeyHandlers() {
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.isDrawing) this.clearPolygon();
if (e.key === 'Enter' && this.isDrawing && this.polygonPoints.length >= 3) this.finishDrawing();
});
},
async openFile() {
if (!this.filePath || this.isLoading) return;
this.isLoading = true;
this.error = '';
try {
const response = await fetch('/api/open', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: this.filePath })
});
const data = await response.json();
if (!data.success) throw new Error(data.error || 'Failed to open file');
this.oraPath = data.ora_path;
this.layers = data.layers;
this.imageWidth = data.width;
this.imageHeight = data.height;
this.clearPolygon();
} catch (e) {
this.error = e.message;
} finally {
this.isLoading = false;
}
},
async saveCurrent() {
if (!this.oraPath) return;
await fetch('/api/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ora_path: this.oraPath })
});
},
async toggleVisibility(layerName, visible) {
const layer = this.layers.find(l => l.name === layerName);
if (layer) layer.visible = visible;
await fetch('/api/layer/visibility', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
layer_name: layerName,
visible: visible
})
});
},
async renameLayer() {
const oldName = this.selectedLayer;
const newName = prompt('New layer name:', this.selectedLayer);
if (!newName || newName === oldName) return;
const layer = this.layers.find(l => l.name === oldName);
if (layer) layer.name = newName;
this.selectedLayer = newName;
await fetch('/api/layer/rename', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
old_name: oldName,
new_name: newName
})
});
},
async deleteLayer() {
const layerToDelete = this.selectedLayer;
if (!confirm(`Delete layer "${layerToDelete}"?`)) return;
const idx = this.layers.findIndex(l => l.name === layerToDelete);
if (idx > -1) this.layers.splice(idx, 1);
this.selectedLayer = null;
await fetch('/api/layer/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
layer_name: layerToDelete
})
});
},
async reorderLayer(direction) {
if (!this.selectedLayer) return;
const idx = this.layers.findIndex(l => l.name === this.selectedLayer);
if (idx < 0) return;
const newIdx = direction === 'up' ? idx - 1 : idx + 1;
if (newIdx < 0 || newIdx >= this.layers.length) return;
const layerName = this.selectedLayer;
[this.layers[idx], this.layers[newIdx]] = [this.layers[newIdx], this.layers[idx]];
await fetch('/api/layer/reorder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
layer_name: layerName,
direction: direction
})
});
},
startDrawing() {
this.isDrawing = true;
this.polygonPoints = [];
// Setup canvas after it's created
setTimeout(() => this.setupCanvas(), 50);
},
setupCanvas() {
const canvas = document.getElementById('polygonCanvas');
if (!canvas) return;
// Match canvas size to image
canvas.width = this.imageWidth;
canvas.height = this.imageHeight;
},
addPolygonPoint(x, y) {
if (!this.isDrawing) return;
// Normalize to 0-1 range
x = Math.max(0, Math.min(1, x));
y = Math.max(0, Math.min(1, y));
this.polygonPoints.push({ x, y });
this.updatePolygonPreview();
},
async updatePolygonPreview() {
if (!this.oraPath || this.polygonPoints.length < 3) return;
const response = await fetch('/api/polygon', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
points: this.polygonPoints,
color: this.polygonColor,
width: this.polygonWidth
})
});
if (response.ok) {
const data = await response.json();
this.polygonPreviewUrl = data.overlay_url;
}
},
finishDrawing() {
this.isDrawing = false;
if (this.polygonPoints.length >= 3) {
// Keep polygon visible
} else {
this.clearPolygon();
}
},
clearPolygon() {
this.isDrawing = false;
this.polygonPoints = [];
this.polygonPreviewUrl = null;
if (this.oraPath) {
fetch('/api/polygon/clear', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ora_path: this.oraPath })
});
}
},
async extractMask() {
if (!this.maskSubject.trim()) return;
this.isExtracting = true;
this.lastError = '';
try {
const response = await fetch('/api/mask/extract', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
subject: this.maskSubject,
use_polygon: this.usePolygonHint && this.polygonPoints.length >= 3,
ora_path: this.oraPath,
comfy_url: this.comfyUrl
})
});
const data = await response.json();
if (!data.success) throw new Error(data.error || 'Failed to extract mask');
this.tempMaskPath = data.mask_path;
this.tempMaskUrl = data.mask_url || '/api/file/mask?path=' + encodeURIComponent(data.mask_path);
this.showMaskModal = true;
} catch (e) {
this.lastError = e.message;
} finally {
this.isExtracting = false;
}
},
rerollMask() {
this.extractMask();
},
async useMask() {
if (!this.tempMaskPath) return;
await fetch('/api/layer/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
entity_name: 'mask',
mask_path: this.tempMaskPath
})
});
// Refresh layers
const response = await fetch('/api/layers?ora_path=' + encodeURIComponent(this.oraPath));
const data = await response.json();
if (data.success) {
this.layers = data.layers;
}
this.closeMaskModal();
},
closeMaskModal() {
this.showMaskModal = false;
this.tempMaskPath = null;
this.tempMaskUrl = null;
},
async openInKrita() {
if (!this.selectedLayer) {
alert('Select a layer first');
return;
}
const response = await fetch('/api/krita/open', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
layer_name: this.selectedLayer
})
});
const data = await response.json();
if (data.success) {
window.open(data.file_url);
}
},
saveSettings() {
localStorage.setItem('ora_comfy_url', this.comfyUrl);
this.showSettings = false;
}
};
}
</script>
</head>
<body class="bg-gray-900 text-white">
<div x-data="oraEditor()" x-init="init()" class="min-h-screen p-4">
<!-- Header -->
<div x-data="oraEditor()" x-init="init()" class="min-h-screen p-4">
<!-- Header -->
<header class="mb-4 flex items-center gap-4">
<div class="flex-1 flex items-center gap-2">
<input
@@ -156,7 +487,7 @@
<!-- Main canvas area -->
<main class="flex-1 bg-gray-800 rounded-lg border border-gray-700 p-4 relative overflow-auto" style="min-height: 600px;">
<div x-show="!isLoading && !error && layers.length > 0" class="relative inline-block"
<div id="imageContainer" x-show="!isLoading && !error && layers.length > 0" class="relative inline-block"
:style="`width: ${imageWidth}px; height: ${imageHeight}px; position: relative;`">
<!-- Layer display -->
@@ -307,9 +638,56 @@ function handleCanvasDoubleClick(e) {
}
}
<!-- Canvas click handler - works with Alpine -->
<script>
function handleCanvasClick(e) {
const container = e.target.closest('#imageContainer');
if (!container) return;
const rect = container.getBoundingClientRect();
let x = (e.clientX - rect.left) / rect.width;
let y = (e.clientY - rect.top) / rect.height;
// Normalize to 0-1 range
x = Math.max(0, Math.min(1, x));
y = Math.max(0, Math.min(1, y));
// Get Alpine component from container
const alpineEl = container.closest('[x-data]');
if (!alpineEl) return;
// Get the Alpine component instance using $data
const store = $data(alpineEl);
if (!store) return;
store.addPolygonPoint(x, y);
}
function handleCanvasDoubleClick(e) {
e.preventDefault();
const container = e.target.closest('#imageContainer');
if (!container) return;
const alpineEl = container.closest('[x-data]');
if (!alpineEl) return;
const store = $data(alpineEl);
if (!store) return;
if (store.isDrawing && store.polygonPoints.length >= 3) {
store.finishDrawing();
}
}
// Wait for Alpine to initialize, then setup canvas
document.addEventListener('alpine:init', () => {
setTimeout(initCanvas, 200);
setTimeout(() => {
const canvas = document.getElementById('polygonCanvas');
if (canvas) {
canvas.addEventListener('click', handleCanvasClick);
canvas.addEventListener('dblclick', handleCanvasDoubleClick);
}
}, 200);
});
</script>
</body>