generated from CodeYourFuture/Module-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathbloom-form.mjs
More file actions
64 lines (57 loc) · 1.72 KB
/
bloom-form.mjs
File metadata and controls
64 lines (57 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { apiService } from "../index.mjs";
/**
* Create a bloom form component
* @param {string} template - The ID of the template to clone
* @param {Object} isLoggedIn - only logged in users see the bloom form
* @returns {DocumentFragment} - The bloom form fragment
*/
function createBloomForm(template, isLoggedIn) {
if (!isLoggedIn) return;
const bloomFormElement = document
.getElementById(template)
.content.cloneNode(true);
return bloomFormElement;
}
/**
* Handle bloom form submission
* @param {Event} event - The form submission event
*/
async function handleBloomSubmit(event) {
event.preventDefault();
const form = event.target;
const submitButton = form.querySelector("[data-submit]");
const originalText = submitButton.textContent;
const textarea = form.querySelector("textarea");
const content = textarea.value.trim();
//add char limit
if (content.length > 280) {
alert("Too long! Maximum 280 characters.");
return;
}
try {
// Make form inert while we call the back end
form.inert = true;
submitButton.textContent = "Posting...";
await apiService.postBloom(content);
textarea.value = "";
} catch (error) {
throw error;
} finally {
// Restore form
submitButton.textContent = originalText;
form.inert = false;
}
}
/**
* Handle textarea input for bloom form
* @param {Event} event - The input event from textarea drives the character counter
*/
function handleTyping(event) {
const textarea = event.target;
const counter = textarea
.closest("[data-form]")
?.querySelector("[data-counter]");
const maxLength = parseInt(textarea.getAttribute("maxlength"), 10);
counter.textContent = `${textarea.value.length} / ${maxLength}`;
}
export { createBloomForm, handleBloomSubmit, handleTyping };