import Handlebars from "handlebars"; import {Controller} from "@hotwired/stimulus"; const processorFrame = Handlebars.compile(`
{{name}} X
{{{props}}}
`); const processorUIs = { "shadow": { label: "Shadow", template: Handlebars.compile(`This processor has no properties.`), }, "resize": { label: "Resize", template: Handlebars.compile(`
`), }, }; export default class UploadEditController extends Controller { static targets = ['processList', 'preview']; static values = { uploadId: Number, siteId: Number, }; connect() { this._rebuildProcessList(); this._createSession(); } async addProcessor(ev) { ev.preventDefault(); await this._addProcessor({ type: "shadow" }); } async removeProcessor(ev) { ev.preventDefault(); let id = ev.params.id; console.log(ev.params); await this._removeProcessor(id); } _rebuildProcessList() { let el = this.processListTarget; if ((!this._state) || (!this._state.session) || (!this._state.session.processors)) { return; } el.innerHTML = ""; for (let p of this._state.session.processors) { let ui = processorUIs[p.type]; if (!ui) { continue; } let cardOuter = processorFrame({ id: p.id, name: ui.label, props: ui.template(p), }); el.innerHTML += cardOuter; } } async _createSession() { try { let resp = await fetch(`/sites/${this.siteIdValue}/imageedit/`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ "base_upload": this.uploadIdValue, }) }); this._state = await resp.json(); this._rebuildProcessList(); this.previewTarget.src = this._state.preview_url; } catch (e) { console.error(e); } } async _addProcessor(processor) { try { let resp = await fetch(`/sites/${this.siteIdValue}/imageedit/${this._state.session.guid}/processors`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(processor) }); this._state = await resp.json(); this._rebuildProcessList(); this.previewTarget.src = this._state.preview_url; } catch (e) { console.error(e); } } async _removeProcessor(processorID) { await this._doReturningState(async () => { return (await fetch(`/sites/${this.siteIdValue}/imageedit/${this._state.session.guid}/processors/${processorID}`, { method: 'DELETE', })).json(); }) } async _doReturningState(fn) { try { this._state = await fn(); this._rebuildProcessList(); this.previewTarget.src = this._state.preview_url; } catch (e) { console.error(e); } } }