๐Ÿ“ฆ jasonbanboa / jsonPosts

๐Ÿ“„ commit.md ยท 246 lines
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246commit m feat adding category divs on enter press

```javascript
const $app = document.querySelector("#app");
const $detailDialog = document.querySelector("#post-detail-dialog");
const $filterDialog = document.querySelector("#filter-dialog");
const $filterByUsernameInput = $filterDialog.querySelector(
  "#filter-by-username"
);
const $filterByCategoriesInput = $filterDialog.querySelector(
  "#filter-by-categories"
);
const $cancleButton = document.querySelector("#cancel");
const $filterButton = document.querySelector("#filter");
const $categoryOutput = document.querySelector('.category-output')

const fetchJSON = (path) => fetch(path).then((res) => res.json());
const POSTS = await fetchJSON("../../json/posts.json");
const CATEGORIES = await fetchJSON("../../json/categorys.json");
const MEMBERS = await fetchJSON("../../json/members.json");

// global states
const modalState = new Proxy(
  { open: false },
  {
    set(target, key, value) {
      enableScroll();
      if (key === "open" && value) {
        disableScroll();
      }
      target[key] = value;
      return true;
    },
  }
);

const scrollStates = {
  postStartIndex: 0,
  postEndIndex: 30,
  arr: POSTS,
  totalResultCount: POSTS.length,
  updateScrollState: function () {
    this.postStartIndex = this.postEndIndex;
    this.postEndIndex += 30;
  },
  resetIndex: function () {
    this.postStartIndex = 0;
    this.postEndIndex = 30;
  },
  updateResult: function (arr) {
    this.arr = arr;
    this.totalResultCount = arr.length;
  },
};
const keyPressStates = {};
const filterStates = {
  username: "",
  categories: [],
  reset: function () {
    this.categories = [];
    this.username = "";
  },
};

// util functions
const removePosts = () =>
  document.querySelectorAll(".post").forEach(($post) => $post.remove());
const getUser = (memberIndex) =>
  MEMBERS.find(({ index }) => memberIndex === index);
const getCategories = (categoryIndexArray) =>
  CATEGORIES.filter(({ index }) => categoryIndexArray.includes(index));
const makeCategoryInnerHTML = (categoriesArray) =>
  categoriesArray.reduce(
    (innerHTML, { name, color }) =>
      (innerHTML += `<span style="background-color: ${color}" class="category">${name}</span>`),
    ""
  );
const categoryNameTocategoryId = (categoryName) =>
  CATEGORIES.find(({ name }) => name === categoryName).index;
const isValidCategory = (category) =>
  !filterStates.categories.includes(categoryNameTocategoryId(category));
const filterByCategories = (arr, categories) =>
  arr.filter(({ categorys }) =>
    categories.every((categoryID) => categorys.includes(categoryID))
  );
const categoryIDToCategory = (id) => CATEGORIES.find(({ index }) => index === id);   
const filterByUsername = (arr, username) => {
  const userData = MEMBERS.find(({ name }) => name === username);
  if (!userData) return false;
  return arr.filter(({ memberIndex }) => memberIndex === userData.index);
};
function filterSearch(posts, { username, categories }) {
  const filteredByUsername = filterByUsername(posts, username);
  const fileredByCategories = filterByCategories(posts, categories);

  if (categories && !filteredByUsername) return fileredByCategories;
  if (!filteredByUsername) return false;
  if (filteredByUsername && !categories) return filteredByUsername;
  return filterByCategories(filteredByUsername, categories);
}

function preventScroll(e) {
  e.preventDefault();
  e.stopPropagation();
  return false;
}
function disableScroll() {
  document.body.addEventListener("wheel", preventScroll, { passive: false });
}
function enableScroll() {
  document.body.removeEventListener("wheel", preventScroll, { passive: false });
}

// main
POSTS.sort((a, b) => new Date(b.date) - new Date(a.date));
POSTS.slice(0, 30).forEach(renderPosts);

window.onscroll = () => {
  const fullPageHeight = document.body.clientHeight;
  if (window.scrollY + window.innerHeight >= fullPageHeight - 200) {
    const { postStartIndex, postEndIndex, totalResultCount, arr } =
      scrollStates;
    if (postStartIndex >= totalResultCount) return;
    console.log(scrollStates);
    scrollStates.updateScrollState();
    console.log(scrollStates);
    arr.slice(postStartIndex, postEndIndex).forEach(renderPosts);
  }
};

$detailDialog.addEventListener("click", (e) => {
  if (e.target === $detailDialog) {
    $detailDialog.close();
    modalState.open = false;
  }
});

window.addEventListener("keyup", (e) => delete keyPressStates[e.key]);

window.addEventListener("keydown", (e) => {
  if (modalState.open) return;
  keyPressStates[e.key] = true;
  if (keyPressStates.Shift && keyPressStates.Control) {
    modalState.open = true;
    $filterDialog.showModal();
  }
});

$filterDialog.addEventListener("click", (e) => {
  if (e.target === $filterDialog || e.target === $cancleButton) {
    $filterDialog.close();
    modalState.open = false;
  }
});

$filterByCategoriesInput.addEventListener("keydown", (e) => {
  const { categories } = filterStates;
  const { value } = $filterByCategoriesInput;
  if (!value) return;
  if (e.key === "Enter" && isValidCategory(value.toLowerCase())) {
    const categoryID = categoryNameTocategoryId(value.toLowerCase());
    filterStates.categories = [
      ...categories,
      categoryID,
    ];
    renderCategory(categoryIDToCategory(categoryID));
    $filterByCategoriesInput.value = "";
    console.log(filterStates);
  }
});

$filterButton.addEventListener("click", () => {
  const username = $filterByUsernameInput.value;
  filterStates.username = username;

  console.log(filterStates);
  const filteredPosts = filterSearch(POSTS, filterStates);
  window.scrollTo(0, 0);
  scrollStates.resetIndex();
  scrollStates.updateResult(filteredPosts);
  removePosts();
  filterStates.reset();
  modalState.open = false;
  $filterDialog.close();
  console.log(filteredPosts, scrollStates);
});

// TODO 
function renderCategory({ index, name, color }) {
  const $categorySpan = document.createElement('span');
  $categorySpan.className = 'category';
  $categorySpan.style.background = `${color}`;
  $categorySpan.innerText = name;

  const $removeCategorySpan = document.createElement('span');
  $removeCategorySpan.innerText = 'x';
  $removeCategorySpan.dataset.id = index;
  // make handler to delete element on click
  $removeCategorySpan.addEventListener('click', (e) => console.log(e.target.dataset.id));
  // FIX append to come first  
  $categorySpan.appendChild($removeCategorySpan);
  $categoryOutput.appendChild($categorySpan);
  
} 

function renderPosts({ title, contents, date, memberIndex, categorys }) {
  const { name } = getUser(Number(memberIndex));
  const $post = document.createElement("article");

  $post.className = "post";
  $post.innerHTML = `
    <div class="image"></div>
    <h3 class="title">${title}</h3>
    <p class="content">${contents}</p>
    <section class="post-details">
      <span class="created-by">${name}</span>
      <span class="timestamp">${date}</span>
    </section>
  `;

  $post.addEventListener("click", () => {
    modalState.open = true;
    showPostDetailModal(title, contents, date, name, categorys);
  });
  $app.appendChild($post);
}

function showPostDetailModal(title, contents, date, username, categorys) {
  const categoriesArray = getCategories(categorys);
  const categoryInnerHTML = makeCategoryInnerHTML(categoriesArray);
  $detailDialog.showModal();

  $detailDialog.innerHTML = `
    <div>
      <div class="image"></div>
      <h3 class="title">${title}</h3>
      <p class="content">${contents}</p>
      <section class="categories">${categoryInnerHTML}</section>
      <section class="post-details">
        <span class="created-by">${username}</span>
        <span class="timestamp">${date}</span>
      </section>
    </div>
  `;
}