176 lines
10 KiB
JavaScript
176 lines
10 KiB
JavaScript
const pickerFrame = document.querySelector('#selector-picker');
|
|
const loadPicker = document.querySelector('#load-picker');
|
|
const pickerStatus = document.querySelector('#picker-status');
|
|
const pickerSelection = document.querySelector('#picker-selection');
|
|
const pickedSelector = document.querySelector('#picked-selector');
|
|
const pickedText = document.querySelector('#picked-text');
|
|
const pickedCount = document.querySelector('#picked-count');
|
|
const pickedContainer = document.querySelector('#picked-container');
|
|
const pickedRelative = document.querySelector('#picked-relative');
|
|
const applySelector = document.querySelector('#apply-selector');
|
|
const resetPicker = document.querySelector('#reset-picker');
|
|
const pickerSteps = document.querySelector('#picker-steps');
|
|
const pickerWorkspace = document.querySelector('#picker-workspace');
|
|
const pickerContainerCount = document.querySelector('#picker-container-count');
|
|
const pickerWarning = document.querySelector('#picker-warning');
|
|
const pickerPreviewEmpty = document.querySelector('#picker-preview-empty');
|
|
const pickerPreviewRows = document.querySelector('#picker-preview-rows');
|
|
const guidedTargets = ['item_selector', 'title_selector', 'date_selector', 'time_selector'];
|
|
const targetLabels = { item_selector: 'event container', title_selector: 'title', date_selector: 'date or range', time_selector: 'time' };
|
|
let currentSelection = null;
|
|
let pickerStep = 0;
|
|
let containerSelector = '';
|
|
let fieldSelectors = {};
|
|
|
|
function currentTarget() { return guidedTargets[Math.min(pickerStep, guidedTargets.length - 1)]; }
|
|
function renderPickerSteps() {
|
|
pickerSteps?.querySelectorAll('li').forEach((step, index) => {
|
|
step.classList.toggle('active', index === pickerStep);
|
|
step.classList.toggle('complete', index < pickerStep);
|
|
});
|
|
}
|
|
function sendPickerConfig() {
|
|
pickerFrame?.contentWindow?.postMessage({ type: 'what2do-picker-config', containerSelector, fieldSelectors }, location.origin);
|
|
}
|
|
function resetPickerState() {
|
|
currentSelection = null; pickerStep = 0; containerSelector = ''; fieldSelectors = {};
|
|
pickerSelection.hidden = true; pickerWarning.hidden = true; pickerPreviewRows.replaceChildren(); pickerPreviewEmpty.hidden = false;
|
|
pickerContainerCount.textContent = ''; pickerStatus.textContent = 'Step 1: click one complete event container.';
|
|
renderPickerSteps(); sendPickerConfig();
|
|
}
|
|
|
|
if (loadPicker && pickerFrame) loadPicker.addEventListener('click', async () => {
|
|
const url = document.querySelector('input[name="url"]')?.value.trim();
|
|
if (!url) { pickerStatus.textContent = 'Enter a page URL first.'; return; }
|
|
loadPicker.disabled = true; pickerStatus.textContent = 'Downloading and sanitizing page…';
|
|
try {
|
|
const body = new FormData(); body.append('url', url);
|
|
const response = await fetch('/picker/snapshots', { method: 'POST', body });
|
|
const result = await response.json();
|
|
if (!response.ok) throw new Error(result.error || 'Unable to create preview');
|
|
pickerFrame.src = result.preview_url; pickerWorkspace.hidden = false; pickerSteps.hidden = false; resetPicker.hidden = false;
|
|
resetPickerState();
|
|
} catch (error) { pickerStatus.textContent = error.message; }
|
|
finally { loadPicker.disabled = false; }
|
|
});
|
|
if (resetPicker) resetPicker.addEventListener('click', resetPickerState);
|
|
if (pickerFrame) pickerFrame.addEventListener('load', sendPickerConfig);
|
|
|
|
window.addEventListener('message', event => {
|
|
if (!pickerFrame || event.source !== pickerFrame.contentWindow) return;
|
|
if (event.data?.type === 'what2do-selector') {
|
|
if (pickerStep >= guidedTargets.length) return;
|
|
currentSelection = event.data;
|
|
const target = currentTarget();
|
|
pickedSelector.textContent = target === 'item_selector' ? (event.data.containerSelector || event.data.generalizedSelector) : event.data.relativeSelector;
|
|
pickedCount.textContent = target === 'item_selector' ? `${event.data.containerCount || event.data.generalizedCount} matching containers` : 'Corresponding field selector';
|
|
pickedContainer.textContent = target === 'item_selector' ? (event.data.containerSelector || event.data.generalizedSelector) : containerSelector;
|
|
pickedRelative.textContent = target === 'item_selector' ? 'All matches will be highlighted.' : event.data.relativeSelector;
|
|
pickedText.textContent = event.data.text || event.data.tag;
|
|
applySelector.disabled = target !== 'item_selector' && !event.data.withinConfiguredContainer;
|
|
applySelector.textContent = `Use as ${targetLabels[target]}`;
|
|
pickerSelection.hidden = false;
|
|
pickerStatus.textContent = applySelector.disabled ? 'Pick a field inside one of the highlighted event containers.' : `Review this ${targetLabels[target]}, then confirm.`;
|
|
}
|
|
if (event.data?.type === 'what2do-picker-preview') renderExtractionPreview(event.data);
|
|
});
|
|
|
|
function updateSelectorField(target, selector) {
|
|
const input = document.querySelector(`[name="${target}"]`);
|
|
if (input) input.value = selector;
|
|
try {
|
|
const strategy = JSON.parse(strategyJson.value || '{}');
|
|
if ((strategy.mode || 'html') === 'html') {
|
|
strategy[target] = selector;
|
|
strategyJson.value = JSON.stringify(strategy, null, 2);
|
|
}
|
|
} catch (_) {}
|
|
}
|
|
|
|
function renderExtractionPreview(data) {
|
|
pickerContainerCount.textContent = data.containerCount ? `${data.containerCount} containers` : '';
|
|
pickerPreviewRows.replaceChildren();
|
|
data.rows.forEach(row => {
|
|
const item = document.createElement('div');
|
|
item.className = 'picker-preview-row';
|
|
const title = document.createElement('strong'); title.textContent = row.title_selector || `Container ${row.index}`; item.append(title);
|
|
const details = [row.date_selector, row.time_selector].filter(Boolean).join(' · ');
|
|
if (details) { const meta = document.createElement('span'); meta.textContent = details; item.append(meta); }
|
|
pickerPreviewRows.append(item);
|
|
});
|
|
pickerPreviewEmpty.hidden = data.rows.length > 0;
|
|
if (data.inconsistencies.length) {
|
|
pickerWarning.textContent = data.inconsistencies.map(issue => `${targetLabels[issue.target] || issue.target}: exactly one match in ${issue.present}/${issue.total} containers${issue.multiple ? `; multiple matches in ${issue.multiple}` : ''}`).join(' ');
|
|
pickerWarning.hidden = false;
|
|
} else pickerWarning.hidden = true;
|
|
}
|
|
|
|
if (applySelector) applySelector.addEventListener('click', () => {
|
|
if (!currentSelection) return;
|
|
const target = currentTarget();
|
|
if (target === 'item_selector') {
|
|
containerSelector = currentSelection.containerSelector || currentSelection.generalizedSelector;
|
|
if (!containerSelector) return;
|
|
updateSelectorField(target, containerSelector);
|
|
} else {
|
|
if (!currentSelection.withinConfiguredContainer) return;
|
|
fieldSelectors[target] = currentSelection.relativeSelector;
|
|
updateSelectorField(target, currentSelection.relativeSelector);
|
|
}
|
|
pickerStep += 1; currentSelection = null; pickerSelection.hidden = true; sendPickerConfig(); renderPickerSteps();
|
|
if (pickerStep < guidedTargets.length) pickerStatus.textContent = `Step ${pickerStep + 1}: pick the ${targetLabels[currentTarget()]} inside a highlighted container.`;
|
|
else pickerStatus.textContent = 'Guided setup complete. Review the preview and any consistency warnings.';
|
|
});
|
|
|
|
const strategyTemplates = {
|
|
html: { mode: 'html', request_url: 'https://example.org/events', method: 'GET', item_selector: '.event-card', title_selector: '.title', date_selector: '.date', time_selector: '.time', link_selector: 'a', link_attribute: 'href', description_selector: '.description', location_selector: '.venue', date_format: '' },
|
|
json: { mode: 'json', request_url: 'https://example.org/api/events', method: 'GET', items_path: 'results', title_path: 'title', date_path: 'startDate', end_path: 'endDate', description_path: 'description', location_path: 'location.address', link_path: 'url', disabled_path: 'disabled' },
|
|
json_join: { mode: 'json', request_url: 'https://example.org/api/sessions', method: 'GET', items_path: '', date_path: 'startDate', link_path: 'url', join_item_key: 'itemId', join_title_path: 'name', join_description_path: 'description', join_duration_path: 'duration', join: { request_url: 'https://example.org/api/items', method: 'GET', items_path: '', key_path: 'id' } },
|
|
html_fragment: { mode: 'html_fragment', request_url: 'https://example.org/ajax', method: 'POST', body: { action: 'events' }, html_path: 'html', item_selector: '.event-card', title_selector: '.title', date_selector: '.date', link_selector: 'a', link_attribute: 'href', page_parameter: 'page', page_start: 1, max_pages: 10, total_pages_path: 'pages_total' }
|
|
};
|
|
const strategyTemplate = document.querySelector('#strategy-template');
|
|
const strategyJson = document.querySelector('#strategy-json');
|
|
if (strategyTemplate && strategyJson) strategyTemplate.addEventListener('change', () => {
|
|
const template = strategyTemplates[strategyTemplate.value];
|
|
if (template) strategyJson.value = JSON.stringify(template, null, 2);
|
|
});
|
|
|
|
const addressInput = document.querySelector('#venue-address');
|
|
const addressOptions = document.querySelector('#address-options');
|
|
const latitudeInput = document.querySelector('#venue-latitude');
|
|
const longitudeInput = document.querySelector('#venue-longitude');
|
|
let addressTimer;
|
|
|
|
if (addressInput && addressOptions) {
|
|
addressInput.addEventListener('input', () => {
|
|
clearTimeout(addressTimer);
|
|
latitudeInput.value = '';
|
|
longitudeInput.value = '';
|
|
const query = addressInput.value.trim();
|
|
if (query.length < 3) { addressOptions.hidden = true; return; }
|
|
addressTimer = setTimeout(async () => {
|
|
try {
|
|
const response = await fetch(`/api/addresses?q=${encodeURIComponent(query)}`);
|
|
const addresses = await response.json();
|
|
addressOptions.replaceChildren();
|
|
addresses.forEach(address => {
|
|
const button = document.createElement('button');
|
|
button.type = 'button';
|
|
button.textContent = address.label;
|
|
button.addEventListener('click', () => {
|
|
addressInput.value = address.label;
|
|
latitudeInput.value = address.latitude;
|
|
longitudeInput.value = address.longitude;
|
|
addressOptions.hidden = true;
|
|
});
|
|
addressOptions.append(button);
|
|
});
|
|
addressOptions.hidden = addresses.length === 0;
|
|
} catch (_) { addressOptions.hidden = true; }
|
|
}, 300);
|
|
});
|
|
document.addEventListener('click', event => {
|
|
if (!event.target.closest('.address-field')) addressOptions.hidden = true;
|
|
});
|
|
}
|