what2do/app/static/source.js
2026-09-07 11:52:41 +10:00

119 lines
6.9 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 pickerTarget = document.querySelector('#picker-target');
const applySelector = document.querySelector('#apply-selector');
const applyPattern = document.querySelector('#apply-pattern');
let currentSelection = null;
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; pickerFrame.hidden = false;
pickerStatus.textContent = 'Hover to highlight, then click an element.';
} catch (error) { pickerStatus.textContent = error.message; }
finally { loadPicker.disabled = false; }
});
window.addEventListener('message', event => {
if (!pickerFrame || event.source !== pickerFrame.contentWindow || event.data?.type !== 'what2do-selector') return;
currentSelection = event.data;
pickedSelector.textContent = event.data.selector;
pickedCount.textContent = `${event.data.selectorCount} exact match${event.data.selectorCount === 1 ? '' : 'es'}; ${event.data.generalizedCount} similar elements`;
pickedContainer.textContent = event.data.containerSelector || 'No repeated ancestor detected';
pickedRelative.textContent = event.data.containerSelector ? `${event.data.containerCount} containers · child: ${event.data.relativeSelector}` : '';
pickedText.textContent = event.data.text || event.data.tag;
applyPattern.disabled = !event.data.containerSelector;
pickerSelection.hidden = false;
});
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 (_) {}
}
if (applySelector) applySelector.addEventListener('click', () => {
if (!currentSelection) return;
updateSelectorField(pickerTarget.value, currentSelection.selector);
pickerStatus.textContent = `Applied exact selector to ${pickerTarget.options[pickerTarget.selectedIndex].text}.`;
});
if (applyPattern) applyPattern.addEventListener('click', () => {
if (!currentSelection?.containerSelector) return;
const target = pickerTarget.value;
updateSelectorField('item_selector', currentSelection.containerSelector);
updateSelectorField(target, target === 'item_selector' ? currentSelection.containerSelector : currentSelection.relativeSelector);
pickerStatus.textContent = `Matched ${currentSelection.containerCount} event containers and applied a relative ${pickerTarget.options[pickerTarget.selectedIndex].text.toLowerCase()} selector.`;
});
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;
});
}