aboutsummaryrefslogtreecommitdiff
path: root/http/public/scripts/feed-condense-content.js
blob: 5203517c95d6312ac4728e830d4862857762f689 (plain)
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
65
66
67
const expandedClass = "e-content--expanded";

export function toggleContentExpanded(id) {
  const content = document.querySelector(`.e-content[data-content-id="${id}"]`);
  const buttonBefore = document.querySelector(
    `button:has(+ .e-content[data-content-id="${id}"])`,
  );
  const buttonAfter = document.querySelector(
    `.e-content[data-content-id="${id}"] + button`,
  );

  if (!content) {
    throw new Error(`No content found with ID: ${id}`);
  }
  const classes = content.getAttribute("class").split(" ");
  const wasExpanded = classes.includes(expandedClass);
  if (wasExpanded) {
    const newClasses = classes.filter((c) => c != expandedClass);
    content.setAttribute("class", newClasses.join(" "));
  } else {
    content.setAttribute("class", [...classes, expandedClass].join(" "));
  }

  if (wasExpanded) {
    if (!buttonBefore) {
      console.warn("Tried to remove 'Read less' button but could not find it");
    } else {
      buttonBefore.remove();
    }
    if (!buttonAfter) {
      console.warn(
        "Tried to toggle 'Read less' button to say 'Read more' but could not find it",
      );
    } else {
      buttonAfter.textContent = "Read more";
    }
  } else {
    if (!buttonAfter) {
      console.warn(
        "Tried to toggle 'Read more' button to say 'Read less' but could not find it",
      );
    } else {
      buttonAfter.textContent = "Read more";
    }
    if (buttonBefore) {
      buttonBefore.remove();
    }
    const newButtonBefore = createExpandCondenseButton(id, "Read less");
    content.insertAdjacentElement("beforebegin", newButtonBefore);
  }
}

export function addExpandItemButtons() {
  for (const content of document.querySelectorAll(".e-content")) {
    const contentId = crypto.randomUUID();
    content.setAttribute("data-content-id", contentId);
    const button = createExpandCondenseButton(contentId, "Read more");
    content.insertAdjacentElement("afterend", button);
  }
}

function createExpandCondenseButton(contentId, initialText) {
  const button = document.createElement("button");
  button.textContent = initialText;
  button.addEventListener("click", () => toggleContentExpanded(contentId));
  return button;
}