From be2f01beaaef38e309b05ee611edc96d9cfdd9c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20P?= Date: Mon, 16 Dec 2024 17:54:56 +0100 Subject: [PATCH] Add Stimulus + basic form --- .gitignore | 3 +- controllers/form_controller.js | 60 ++++++++++++++++++++++++++++++++ css/bim.css | 4 +-- index.html | 62 ++++++++++++++++++++++++---------- main.js | 12 ++++++- package.json | 1 + yarn.lock | 5 +++ 7 files changed, 126 insertions(+), 21 deletions(-) create mode 100644 controllers/form_controller.js diff --git a/.gitignore b/.gitignore index b09b978..0b895cf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *.sql *.log -vendor/ \ No newline at end of file +vendor/ +config.js \ No newline at end of file diff --git a/controllers/form_controller.js b/controllers/form_controller.js new file mode 100644 index 0000000..2fbc133 --- /dev/null +++ b/controllers/form_controller.js @@ -0,0 +1,60 @@ +import { Controller } from "@hotwired/stimulus" +import API_CONFIG from "../config.js"; + +/** + * @todo Handle errors + */ +export default class extends Controller { + static targets = [ + 'building', + 'showBuilding', + 'buildingName', + 'buildingForm' + ]; + + API_BASE = API_CONFIG.dev; + + async submit(event) { + event.preventDefault(); + + if (event.currentTarget === this.buildingFormTarget) { + const options = this.prepare( + JSON.stringify({name: this.buildingTarget.value}), + 'POST' + ); + + const res = await this.send( + `${this.API_BASE}/api/buildings`, + options + ); + + if (res.id) { + this.buildingTarget.setAttribute('data-id', res.id); + this.showBuildingTarget.classList.remove('is-hidden'); + this.buildingNameTarget.textContent = res.name; + } + } + } + + prepare(data, method) { + return { + headers: { + "Content-Type": "application/json", + }, + body: data, + method, + } + } + + /** + * @todo Return Exception on response error + * @param {string} endpoint + * @param {object} options + * @returns + */ + async send(endpoint, options) { + return await fetch(endpoint, options) + .then(res => res.json()) + .catch(error => console.log(error)); + } +} diff --git a/css/bim.css b/css/bim.css index 5a15dae..ca635ae 100644 --- a/css/bim.css +++ b/css/bim.css @@ -3,12 +3,12 @@ #scene { min-height: 93vh; - margin-left: 25vw; + margin-left: 20vw; overflow: hidden; } #ui { position: absolute; top: 3.5rem; - max-width: 25vw; + max-width: 20vw; z-index: 5; } \ No newline at end of file diff --git a/index.html b/index.html index df2c0b7..a107ac9 100644 --- a/index.html +++ b/index.html @@ -8,6 +8,7 @@