show newly created reminders. fix color rendering.

This commit is contained in:
jude 2022-03-27 14:15:01 +01:00
parent f8547bba70
commit f4ef7afea0
5 changed files with 197 additions and 123 deletions

View File

@ -225,6 +225,8 @@ pub async fn create_reminder(
let attachment_data = reminder.attachment.as_ref().map(|s| base64::decode(s).ok()).flatten(); let attachment_data = reminder.attachment.as_ref().map(|s| base64::decode(s).ok()).flatten();
let name = if reminder.name.is_empty() { name_default() } else { reminder.name.clone() }; let name = if reminder.name.is_empty() { name_default() } else { reminder.name.clone() };
let new_uid = generate_uid();
// write to db // write to db
match sqlx::query!( match sqlx::query!(
"INSERT INTO reminders ( "INSERT INTO reminders (
@ -254,7 +256,7 @@ pub async fn create_reminder(
username, username,
`utc_time` `utc_time`
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
generate_uid(), new_uid,
attachment_data, attachment_data,
reminder.attachment_name, reminder.attachment_name,
channel, channel,
@ -283,7 +285,47 @@ pub async fn create_reminder(
.execute(pool.inner()) .execute(pool.inner())
.await .await
{ {
Ok(_) => json!({}), Ok(_) => sqlx::query_as_unchecked!(
Reminder,
"SELECT
reminders.attachment,
reminders.attachment_name,
reminders.avatar,
channels.channel,
reminders.content,
reminders.embed_author,
reminders.embed_author_url,
reminders.embed_color,
reminders.embed_description,
reminders.embed_footer,
reminders.embed_footer_url,
reminders.embed_image_url,
reminders.embed_thumbnail_url,
reminders.embed_title,
reminders.enabled,
reminders.expires,
reminders.interval_seconds,
reminders.interval_months,
reminders.name,
reminders.pin,
reminders.restartable,
reminders.tts,
reminders.uid,
reminders.username,
reminders.utc_time
FROM reminders
LEFT JOIN channels ON channels.id = reminders.channel_id
WHERE uid = ?",
new_uid
)
.fetch_one(pool.inner())
.await
.map(|r| json!(r))
.unwrap_or_else(|e| {
warn!("Failed to complete SQL query: {:?}", e);
json!({"error": "Could not load reminders"})
}),
Err(e) => { Err(e) => {
warn!("Error in `create_reminder`: Could not execute query: {:?}", e); warn!("Error in `create_reminder`: Could not execute query: {:?}", e);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 762 B

After

Width:  |  Height:  |  Size: 762 B

View File

@ -4,6 +4,7 @@ const $loader = document.querySelector("#loader");
const $colorPickerModal = document.querySelector("div#pickColorModal"); const $colorPickerModal = document.querySelector("div#pickColorModal");
const $colorPickerInput = $colorPickerModal.querySelector("input"); const $colorPickerInput = $colorPickerModal.querySelector("input");
const $deleteReminderBtn = document.querySelector("#delete-reminder-confirm"); const $deleteReminderBtn = document.querySelector("#delete-reminder-confirm");
const $reminderTemplate = document.querySelector("template#guildReminder");
let channels; let channels;
let roles; let roles;
@ -14,7 +15,7 @@ function colorToInt(r, g, b) {
} }
function intToColor(i) { function intToColor(i) {
return `#${i.toString(16)}`; return `#${i.toString(16).padStart(6, "0")}`;
} }
function resize_textareas() { function resize_textareas() {
@ -114,41 +115,13 @@ async function fetch_reminders(guild_id) {
if (data.error) { if (data.error) {
show_error(data.error); show_error(data.error);
} else { } else {
const $template = document.querySelector("template#guildReminder");
for (let reminder of data) { for (let reminder of data) {
let newFrame = $template.content.cloneNode(true); let newFrame = $reminderTemplate.content.cloneNode(true);
newFrame.querySelector(".reminderContent").dataset.uid = newFrame.querySelector(".reminderContent").dataset.uid =
reminder["uid"]; reminder["uid"];
// populate channels render_reminder(reminder, newFrame);
set_channels(newFrame.querySelector("select.channel-selector"));
// populate majority of items
for (let prop in reminder) {
if (reminder.hasOwnProperty(prop) && reminder[prop] !== null) {
let $input = newFrame.querySelector(`*[name="${prop}"]`);
let $image = newFrame.querySelector(`img.${prop}`);
if ($input !== null) {
$input.value = reminder[prop];
} else if ($image !== null) {
$image.src = reminder[prop];
}
}
}
let $enableBtn = newFrame.querySelector(".disable-enable");
$enableBtn.dataset.action = reminder["enabled"]
? "disable"
: "enable";
let timeInput = newFrame.querySelector('input[name="time"]');
let localTime = luxon.DateTime.fromISO(reminder["utc_time"]).setZone(
timezone
);
timeInput.value = localTime.toFormat("yyyy-LL-dd'T'HH:mm:ss");
$reminderBox.appendChild(newFrame); $reminderBox.appendChild(newFrame);
@ -164,6 +137,40 @@ async function fetch_reminders(guild_id) {
}); });
} }
function render_reminder(reminder, frame) {
// populate channels
set_channels(frame.querySelector("select.channel-selector"));
// populate majority of items
for (let prop in reminder) {
if (reminder.hasOwnProperty(prop) && reminder[prop] !== null) {
if (prop === "attachment") {
} else if (prop === "attachment_name") {
frame.querySelector(".file-cta > .file-label").textContent =
reminder[prop];
} else {
let $input = frame.querySelector(`*[name="${prop}"]`);
let $image = frame.querySelector(`img.${prop}`);
if ($input !== null) {
$input.value = reminder[prop];
} else if ($image !== null) {
$image.src = reminder[prop];
}
}
}
}
let $enableBtn = frame.querySelector(".disable-enable");
$enableBtn.dataset.action = reminder["enabled"] ? "disable" : "enable";
let timeInput = frame.querySelector('input[name="time"]');
let localTime = luxon.DateTime.fromISO(reminder["utc_time"], { zone: "UTC" }).setZone(
timezone
);
timeInput.value = localTime.toFormat("yyyy-LL-dd'T'HH:mm:ss");
}
document.addEventListener("guildSwitched", async (e) => { document.addEventListener("guildSwitched", async (e) => {
$loader.classList.remove("is-hidden"); $loader.classList.remove("is-hidden");
@ -500,100 +507,127 @@ function has_source(string) {
} }
let $createReminder = document.querySelector("#reminderCreator"); let $createReminder = document.querySelector("#reminderCreator");
let $createBtn = $createReminder.querySelector("button#createReminder");
$createReminder $createBtn.addEventListener("click", async () => {
.querySelector("button#createReminder") $createBtn.querySelector("span.icon > i").classList = ["fas fa-spinner fa-spin"];
.addEventListener("click", async () => {
// create reminder object
let seconds =
parseInt(
$createReminder.querySelector('input[name="interval_seconds"]').value
) || null;
let months =
parseInt(
$createReminder.querySelector('input[name="interval_months"]').value
) || null;
let rgb_color = window.getComputedStyle( // create reminder object
$createReminder.querySelector("div.discord-embed") let seconds =
).borderLeftColor; parseInt($createReminder.querySelector('input[name="interval_seconds"]').value) ||
let rgb = rgb_color.match(/\d+/g); null;
let color = colorToInt(parseInt(rgb[0]), parseInt(rgb[1]), parseInt(rgb[2])); let months =
parseInt($createReminder.querySelector('input[name="interval_months"]').value) ||
null;
let utc_time = luxon.DateTime.fromISO( let rgb_color = window.getComputedStyle(
$createReminder.querySelector('input[name="time"]').value $createReminder.querySelector("div.discord-embed")
).setZone("UTC"); ).borderLeftColor;
let rgb = rgb_color.match(/\d+/g);
let color = colorToInt(parseInt(rgb[0]), parseInt(rgb[1]), parseInt(rgb[2]));
let attachment = null; let utc_time = luxon.DateTime.fromISO(
let attachment_name = null; $createReminder.querySelector('input[name="time"]').value
).setZone("UTC");
if ($createReminder.querySelector('input[name="attachment"]').files.length > 0) { if (utc_time.invalid) {
let file = $createReminder.querySelector('input[name="attachment"]').files[0]; show_error("Time provided invalid.");
$createBtn.querySelector("span.icon > i").classList = ["fas fa-sparkles"];
return;
}
attachment = await new Promise((resolve) => { let attachment = null;
let fileReader = new FileReader(); let attachment_name = null;
fileReader.onload = (e) => resolve(fileReader.result);
fileReader.readAsDataURL(file);
});
attachment = attachment.split(",")[1];
attachment_name = file.name;
}
let reminder = { if ($createReminder.querySelector('input[name="attachment"]').files.length > 0) {
attachment: attachment, let file = $createReminder.querySelector('input[name="attachment"]').files[0];
attachment_name: attachment_name,
avatar: has_source($createReminder.querySelector("img.discord-avatar").src),
channel: $createReminder.querySelector("select.channel-selector").value,
content: $createReminder.querySelector("textarea#messageContent").value,
embed_author_url: has_source(
$createReminder.querySelector("img.embed_author_url").src
),
embed_author: $createReminder.querySelector("textarea#embedAuthor").value,
embed_color: color,
embed_description: $createReminder.querySelector("textarea#embedDescription")
.value,
embed_footer: $createReminder.querySelector("textarea#embedFooter").value,
embed_footer_url: has_source(
$createReminder.querySelector("img.embed_footer_url").src
),
embed_image_url: has_source(
$createReminder.querySelector("img.embed_image_url").src
),
embed_thumbnail_url: has_source(
$createReminder.querySelector("img.embed_thumbnail_url").src
),
embed_title: $createReminder.querySelector("textarea#embedTitle").value,
embed_fields: [],
enabled: true,
expires: null,
interval_seconds: seconds,
interval_months: months,
name: $createReminder.querySelector('input[name="name"]').value,
pin: $createReminder.querySelector('input[name="pin"]').checked,
restartable: false,
tts: $createReminder.querySelector('input[name="tts"]').checked,
username: $createReminder.querySelector("input#reminderUsername").value,
utc_time: utc_time.toFormat("yyyy-LL-dd'T'HH:mm:ss"),
};
// send to server attachment = await new Promise((resolve) => {
let guild = document.querySelector(".guildList a.is-active").dataset["guild"]; let fileReader = new FileReader();
fileReader.onload = (e) => resolve(fileReader.result);
fileReader.readAsDataURL(file);
});
attachment = attachment.split(",")[1];
attachment_name = file.name;
}
fetch(`/dashboard/api/guild/${guild}/reminders`, { let reminder = {
method: "POST", attachment: attachment,
headers: { attachment_name: attachment_name,
"Content-Type": "application/json", avatar: has_source($createReminder.querySelector("img.discord-avatar").src),
}, channel: $createReminder.querySelector("select.channel-selector").value,
body: JSON.stringify(reminder), content: $createReminder.querySelector("textarea#messageContent").value,
}) embed_author_url: has_source(
.then((response) => response.json()) $createReminder.querySelector("img.embed_author_url").src
.then((data) => console.log(data)); ),
embed_author: $createReminder.querySelector("textarea#embedAuthor").value,
embed_color: color,
embed_description: $createReminder.querySelector("textarea#embedDescription")
.value,
embed_footer: $createReminder.querySelector("textarea#embedFooter").value,
embed_footer_url: has_source(
$createReminder.querySelector("img.embed_footer_url").src
),
embed_image_url: has_source(
$createReminder.querySelector("img.embed_image_url").src
),
embed_thumbnail_url: has_source(
$createReminder.querySelector("img.embed_thumbnail_url").src
),
embed_title: $createReminder.querySelector("textarea#embedTitle").value,
embed_fields: [],
enabled: true,
expires: null,
interval_seconds: seconds,
interval_months: months,
name: $createReminder.querySelector('input[name="name"]').value,
pin: $createReminder.querySelector('input[name="pin"]').checked,
restartable: false,
tts: $createReminder.querySelector('input[name="tts"]').checked,
username: $createReminder.querySelector("input#reminderUsername").value,
utc_time: utc_time.toFormat("yyyy-LL-dd'T'HH:mm:ss"),
};
// process response // send to server
fetch_reminders(guild); let guild = document.querySelector(".guildList a.is-active").dataset["guild"];
// reset inputs fetch(`/dashboard/api/guild/${guild}/reminders`, {
}); method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(reminder),
})
.then((response) => response.json())
.then((data) => {
if (data.error) {
show_error(data.error);
} else {
const $reminderBox = document.querySelector("div#guildReminders");
let newFrame = $reminderTemplate.content.cloneNode(true);
newFrame.querySelector(".reminderContent").dataset["uid"] = data["uid"];
render_reminder(data, newFrame);
$reminderBox.appendChild(newFrame);
data.node = $reminderBox.lastElementChild;
document.dispatchEvent(
new CustomEvent("remindersLoaded", {
detail: [data],
})
);
}
$createBtn.querySelector("span.icon > i").classList = ["fas fa-check"];
window.setTimeout(() => {
$createBtn.querySelector("span.icon > i").classList = ["fas fa-sparkles"];
}, 1500);
});
});
document.querySelectorAll("textarea.autoresize").forEach((element) => { document.querySelectorAll("textarea.autoresize").forEach((element) => {
element.addEventListener("input", () => { element.addEventListener("input", () => {

View File

@ -66,7 +66,5 @@ selector.addEventListener("change", () => {
}); });
document.addEventListener("remindersLoaded", () => { document.addEventListener("remindersLoaded", () => {
let select = document.querySelector("#orderBy"); sort_by(selector.value);
sort_by(select.value);
}); });

View File

@ -166,17 +166,17 @@
<div class="columns"> <div class="columns">
<div class="column has-text-centered"> <div class="column has-text-centered">
<div style="display: inline-block;"> <div class="is-boxed">
<label class="label">Enable TTS <input type="checkbox" name="tts"></label> <label class="label">Enable TTS <input type="checkbox" name="tts"></label>
</div> </div>
</div> </div>
<div class="column has-text-centered"> <div class="column has-text-centered">
<div style="display: inline-block;"> <div class="is-boxed">
<label class="label">Pin Message <input type="checkbox" name="pin"></label> <label class="label">Pin Message <input type="checkbox" name="pin"></label>
</div> </div>
</div> </div>
<div class="column has-text-centered"> <div class="column has-text-centered">
<div class="file is-boxed"> <div class="file is-small is-boxed">
<label class="file-label"> <label class="file-label">
<input class="file-input" type="file" name="attachment"> <input class="file-input" type="file" name="attachment">
<span class="file-cta"> <span class="file-cta">
@ -201,7 +201,7 @@
Create Template Create Template
</button> </button>
<button class="button is-success" id="createReminder"> <button class="button is-success" id="createReminder">
Create Reminder <span>Create Reminder</span> <span class="icon"><i class="fas fa-sparkles"></i></span>
</button> </button>
{% else %} {% else %}
<button class="button is-primary save-btn"> <button class="button is-primary save-btn">