Compare commits

..

No commits in common. "e051095ce32c3a3ed04ffed5690f9fc875c78420" and "cab5981aaeb6ecbeb8acf6525bcfb964d6db976d" have entirely different histories.

3 changed files with 544 additions and 530 deletions

View File

@ -110,7 +110,7 @@ gw-comment-card.collapsed .comment-header-right time { display: none; }
.comment-header {
display: grid;
grid-template-columns: 0fr auto 1fr;
grid-template-columns: 0fr max-content 1fr;
gap: 0.4em;
align-items: baseline;
}
@ -136,5 +136,4 @@ gw-comment-card.collapsed .comment-header-right time { display: none; }
.commenter-name {
font-size: 1.1em;
font-weight: 700;
overflow-wrap: break-word;
}

View File

@ -1,13 +1,36 @@
/**
* @file Comments control
* @author Vera Konigin vera@groundedwren.com
* https://groundedwren.neocities.org
*/
* Author: Vera Konigin
* Site: https://groundedwren.neocities.org
* Contact: vera@groundedwren.com
*
* File Description: Comments Control
*/
window.GW = window.GW || {};
(function Controls(ns) {
ns.CommentForm = class CommentForm extends HTMLElement {
/**
* By default, any JavaScript code written is defined in the global namespace, which means it's accessible directly under the "window" element.
* If you have a lot of scripts, this can lead to clutter and naming collisions (what if two different scripts use a variable called "i"? They can inadvertently mess each other up).
* To get around this, we define the registerNamespace function in the global namespace, which just confines all the code in the function passed to it to a property under window.
* That property is represented as the "path" parameter. It is passed to the function for ease of access.
*/
function registerNamespace(path, nsFunc)
{
var ancestors = path.split(".");
var ns = window;
for(var i = 0; i < ancestors.length; i++)
{
ns[ancestors[i]] = ns[ancestors[i]] || {};
ns = ns[ancestors[i]];
}
nsFunc(ns);
}
registerNamespace("GW.Controls", function (ns)
{
ns.CommentForm = class CommentForm extends HTMLElement
{
//#region staticProperties
static observedAttributes = [];
static instanceCount = 0;
static instanceMap = {};
//#endregion
@ -36,17 +59,21 @@ window.GW = window.GW || {};
//#endregion
//#endregion
constructor() {
constructor()
{
super();
this.instanceId = CommentForm.instanceCount++;
CommentForm.instanceMap[this.instanceId] = this;
}
get idKey() {
get idKey()
{
return `gw-comment-form-${this.instanceId}`;
}
connectedCallback() {
//#region HTMLElement implementation
connectedCallback()
{
if (this.isInitialized) { return; }
this.titleText = this.getAttribute("titleText") || "Add a Comment";
@ -59,8 +86,10 @@ window.GW = window.GW || {};
this.isInitialized = true;
}
//#endregion
renderContent() {
renderContent()
{
//Markup
this.innerHTML = `
<form id="${this.idKey}-form"
@ -91,21 +120,19 @@ window.GW = window.GW || {};
</div>
</div>
<div class="comment-box-container">
<div class="input-vertical">
<label for="${this.idKey}-comment">
Comment<span aria-hidden="true">*</span>
</label>
<textarea id="${this.idKey}-comment"
minlength="1"
maxlength="1000"
maxlength="4000"
required="true"
rows="5"
></textarea>
</div>
</div>
<div id="${this.idKey}-banner" class="inline-banner" aria-live="polite">
<gw-icon iconKey="circle-info" title="info"></gw-icon>
<span>Comments are manually approved</span>
<gw-icon iconKey="circle-info"></gw-icon>
<p>Comments are manually approved</p>
</div>
<div class="form-footer">
<input id="${this.idKey}-reset" type="reset" value="Reset">
@ -135,11 +162,13 @@ window.GW = window.GW || {};
}
//#region Handlers
registerHandlers() {
registerHandlers()
{
this.formEl.onsubmit = this.onSubmit;
}
onSubmit = (event) => {
onSubmit = (event) =>
{
event.preventDefault();
const contentObj = {
@ -147,13 +176,12 @@ window.GW = window.GW || {};
email: this.emailInpt.value,
website: this.websiteInpt.value,
responseTo: this.respToInpt.value,
comment: (
this.commentInpt.value || ""
).replaceAll("\n", "<br>").replaceAll("(", "\\("),
comment: this.commentInpt.value,
timestamp: new Date().toUTCString(),
};
const contentAry = [];
for (let contentKey in contentObj) {
for (let contentKey in contentObj)
{
contentAry.push(`${contentKey}=${contentObj[contentKey]}`);
}
@ -165,33 +193,33 @@ window.GW = window.GW || {};
);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = () => {
request.onreadystatechange = () =>
{
if (request.readyState !== XMLHttpRequest.DONE) { return; }
if (Math.floor(request.status / 100) !== 2) {
if (Math.floor(request.status / 100) !== 2)
{
console.log(request.responseText);
this.bannerEl.classList.add("warning");
this.bannerEl.innerHTML =
`
<gw-icon iconKey="triangle-exclamation" title="warning"></gw-icon>
<gw-icon iconKey="triangle-exclamation"></gw-icon>
<span>
That didn't work.
${this.fallbackEmail
? `<a class="full" href="mailto:${this.fallbackEmail}?subject=Comment on ${document.title}&body=${contentAry.join("; ")}">Click here to send as an email instead</a>.`
? `<a class="full" href="mailto:${this.fallbackEmail}?subject=Comment on ${document.title}&body=${contentAry.join("; ")}">Send your comment as an email instead</a>.`
: ""
}
</span>
`;
}
else {
else
{
alert("Your comment has been submitted!");
}
};
request.send(JSON.stringify({
embeds: [{
fields: Object.keys(contentObj).map(key => { return { name: key, value: contentObj[key] }})
}]
}));
request.send(JSON.stringify({ content: contentAry.join("; ") }));
localStorage.setItem("comment-name", contentObj.name);
localStorage.setItem("comment-email", contentObj.email);
@ -206,11 +234,12 @@ window.GW = window.GW || {};
};
customElements.define("gw-comment-form", ns.CommentForm);
ns.CommentList = class CommentList extends HTMLElement {
ns.CommentList = class CommentList extends HTMLElement
{
//#region staticProperties
static observedAttributes = [];
static instanceCount = 0;
static instanceMap = {};
static Data = [];
//#endregion
//#region instance properties
@ -225,18 +254,21 @@ window.GW = window.GW || {};
//#endregion
//#endregion
constructor() {
constructor()
{
super();
this.instanceId = CommentList.instanceCount++;
CommentList.instanceMap[this.instanceId] = this;
CommentList.Data[this.instanceId] = {};
}
get idKey() {
get idKey()
{
return `gw-comment-list-${this.instanceId}`;
}
connectedCallback() {
//#region HTMLElement implementation
connectedCallback()
{
if (this.isInitialized) { return; }
this.gSpreadsheetId = this.getAttribute("gSpreadsheetId");
@ -248,8 +280,10 @@ window.GW = window.GW || {};
this.isInitialized = true;
}
//#endregion
async loadAndRender() {
async loadAndRender()
{
this.innerHTML = `
<div class="inline-banner">
<gw-icon iconkey="circle-info" title="info"></gw-icon>
@ -258,11 +292,12 @@ window.GW = window.GW || {};
`
const sheetReader = new GW.Gizmos.GoogleSheetsReader(this.gSpreadsheetId, this.gSheetId);
await sheetReader.loadData();
const sheetData = await sheetReader.loadData();
this.innerHTML = "";
const allComments = sheetReader.rowData;
if (this.isNewestFirst) {
if (this.isNewestFirst)
{
allComments.reverse();
}
@ -272,59 +307,72 @@ window.GW = window.GW || {};
const allCommentsIndex = {};
const topLevelCommentIdxs = [];
const childCommentIdxs = [];
for (let i = 0; i < allComments.length; i++) {
for (let i = 0; i < allComments.length; i++)
{
const comment = allComments[i];
allCommentsIndex[comment.ID] = i;
if (!comment.ResponseTo) {
if (!comment.ResponseTo)
{
topLevelCommentIdxs.push(i);
}
else {
else
{
childCommentIdxs.push(i);
}
}
childCommentIdxs.forEach(childIdx => {
childCommentIdxs.forEach(childIdx =>
{
const replyId = allComments[childIdx].ResponseTo;
const respondeeComment = allComments[allCommentsIndex[replyId]];
respondeeComment.ChildIdxs = respondeeComment.ChildIdxs || [];
respondeeComment.ChildIdxs.push(childIdx);
respondeeComment.childrenIdxs = respondeeComment.childrenIdxs || [];
respondeeComment.childrenIdxs.push(childIdx);
});
let commentsToBuild = [];
topLevelCommentIdxs.forEach(
topCommentIdx => commentsToBuild.push({
topCommentIdx => commentsToBuild.push(
{
parent: this.containerEl,
parentId: null,
comment: allComments[topCommentIdx]
})
}
)
);
while (commentsToBuild.length > 0) {
let { parent, comment } = commentsToBuild.shift();
if (!comment.Timestamp) {
while (commentsToBuild.length > 0)
{
let { parent, parentId, comment } = commentsToBuild.shift();
if (!comment.Timestamp)
{
continue;
}
CommentList.Data[this.instanceId][comment.ID] = comment;
parent.insertAdjacentHTML("beforeend", `
<gw-comment-card id="${this.idKey}-cmt-${comment.ID}"
listInstance=${this.instanceId}
commentId=${comment.ID}
gwCommentFormId=${this.gwCommentFormId || ""}
commentId="${comment.ID || ""}"
replyToId="${parentId || ""}"
numChildren="${(comment.childrenIdxs || []).length}"
commenterName="${comment["Display Name"] || ""}"
isoTimestamp="${comment.Timestamp.toISOString()}"
websiteURL="${comment.Website || ""}"
commentText="${comment.Comment || ""}"
gwCommentFormId="${this.gwCommentFormId || ""}"
></gw-comment-card>
`);
const commentEl = document.getElementById(`${this.idKey}-cmt-${comment.ID}`);
(comment.ChildIdxs || []).forEach(
(comment.childrenIdxs || []).forEach(
childIdx => commentsToBuild.push({
parent: commentEl.articleEl,
parentId: comment.ID,
comment: allComments[childIdx]
})
);
}
}
renderContent() {
renderContent()
{
//Markup
this.innerHTML = `
<div id="${this.idKey}-container" class="comments-container"">
@ -336,14 +384,17 @@ window.GW = window.GW || {};
}
//#region Handlers
registerHandlers() {
registerHandlers()
{
}
//#endregion
};
customElements.define("gw-comment-list", ns.CommentList);
ns.CommentCard = class CommentCard extends HTMLElement {
ns.CommentCard = class CommentCard extends HTMLElement
{
//#region staticProperties
static observedAttributes = [];
static instanceCount = 0;
static instanceMap = {};
//#endregion
@ -351,16 +402,15 @@ window.GW = window.GW || {};
//#region instance properties
instanceId;
isInitialized;
commentId;
gwCommentFormId;
replyToId;
numChildren;
commenterName;
isoTimestamp;
datetime;
websiteURL;
commentText;
gwCommentFormId;
//#region element properties
articleEl;
@ -368,32 +418,33 @@ window.GW = window.GW || {};
//#endregion
//#endregion
constructor() {
constructor()
{
super();
this.instanceId = CommentCard.instanceCount++;
CommentCard.instanceMap[this.instanceId] = this;
}
get idKey() {
get idKey()
{
return `gw-comment-card-${this.instanceId}`;
}
//#region HTMLElement implementation
connectedCallback() {
connectedCallback()
{
if (this.isInitialized) { return; }
this.commentId = this.getAttribute("commentId");
this.replyToId = this.getAttribute("replyToId");
this.numChildren = this.getAttribute("numChildren");
this.commenterName = this.getAttribute("commenterName");
this.isoTimestamp = this.getAttribute("isoTimestamp");
this.datetime = new Date(this.isoTimestamp);
this.websiteURL = this.getAttribute("websiteURL");
this.commentText = this.getAttribute("commentText");
this.gwCommentFormId = this.getAttribute("gwCommentFormId");
const commentData = ns.CommentList.Data[this.getAttribute("listInstance")][this.commentId];
this.replyToId = commentData.ResponseTo;
this.numChildren = (commentData.ChildIdxs || []).length;
this.commenterName = commentData["Display Name"];
this.datetime = commentData.Timestamp;
this.websiteURL = commentData.Website;
this.commentText = this.parseCommentText(commentData.Comment);
this.renderContent();
this.registerHandlers();
@ -401,10 +452,12 @@ window.GW = window.GW || {};
}
//#endregion
renderContent() {
renderContent()
{
let headerText = this.replyToId
? `Comment #${this.commentId} replying to #${this.replyToId}`
: `Top level comment #${this.commentId}`;
headerText += ` with ${this.numChildren} direct ${this.numChildren == 1 ? "reply" : "replies"}`;
const displayTimestamp = this.datetime.toLocaleString(
@ -429,7 +482,7 @@ window.GW = window.GW || {};
${commenterNameEl}
<div class="comment-header-right">
<time id="${this.idKey}-timestamp"
datetime="${this.datetime.toISOString()}"
datetime="${this.isoTimestamp}"
tabindex="-1"
>${displayTimestamp}</time>
<button id="${this.idKey}-show" class="show-comment">Show #${this.commentId}</button>
@ -452,16 +505,19 @@ window.GW = window.GW || {};
}
//#region Handlers
registerHandlers() {
registerHandlers()
{
this.replyBtn.onclick = this.onReply;
this.hideBtn.onclick = this.onHide;
this.showBtn.onclick = this.onShow;
}
onReply = () => {
onReply = () =>
{
const gwCommentForm = document.getElementById(this.gwCommentFormId);
const respToInpt = gwCommentForm.respToInpt;
if (!respToInpt) {
if (!respToInpt)
{
alert("Comment form not found");
return;
}
@ -470,59 +526,18 @@ window.GW = window.GW || {};
respToInpt.focus();
};
onHide = () => {
onHide = () =>
{
this.classList.add("collapsed");
this.showBtn.focus();
};
onShow = () => {
onShow = () =>
{
this.classList.remove("collapsed");
this.timestamp.focus();
};
//#endregion
parseCommentText(commentString) {
let commentText = "";
let linkObj = {};
for(let i = 0; i < commentString.length; i++){
let char = commentString.charAt(i);
switch (char) {
case '[':
linkObj = {tStart: i};
break;
case ']':
if(linkObj.tStart !== undefined && linkObj.tStart !== i-1) {
linkObj.tEnd = i;
}
else { linkObj = {}; }
break;
case '(':
if(linkObj.tEnd !== undefined && linkObj.tEnd === i-1) {
linkObj.lStart = i;
}
else { linkObj = {}; }
break;
case ')':
if(linkObj.lStart !== undefined && linkObj.lStart !== i-1) {
linkObj.lEnd = i;
}
else { linkObj = {}; }
break;
}
if(linkObj.lEnd !== undefined) {
const linkText = commentString.substring(linkObj.tStart + 1, linkObj.tEnd);
const linkURL = commentString.substring(linkObj.lStart + 1, linkObj.lEnd);
commentText = commentText.substring(0, commentText.length - (i - linkObj.tStart));
commentText += `<a href="${linkURL}" target="_blank">${linkText}</a>`;
linkObj = {};
}
else {
commentText += char;
}
}
return commentText;
}
};
customElements.define("gw-comment-card", ns.CommentCard);
}) (window.GW.Controls = window.GW.Controls || {});
});

View File

@ -12,7 +12,7 @@ eleventyComputed:
<p class="center-text">Guestbook Archive: <a href="https://web.archive.org/web/20240528231121/https%3A%2F%2Fleilukin.123guestbook.com%2F">123Guestbook</a></p>
<p>Feel free to say hi and connect with me! The comment field supports <a href="https://www.markdownguide.org/basic-syntax/#links">Markdown links</a> and and HTML.</p>
<p>Feel free to say hi and connect with me!</p>
<p>JavaScript is required for this guestbook to function. Special thanks to <a href="https://groundedwren.neocities.org/pages/controls/guestbookDemo">Vera Konigin</a> for this guestbook widget!</p>